forms.py 116 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656
  1. """
  2. @package gui_core.forms
  3. @brief Construct simple wxPython GUI from a GRASS command interface
  4. description.
  5. Classes:
  6. - forms::UpdateThread
  7. - forms::UpdateQThread
  8. - forms::TaskFrame
  9. - forms::CmdPanel
  10. - forms::GUI
  11. - forms::GrassGUIApp
  12. This program is just a coarse approach to automatically build a GUI
  13. from a xml-based GRASS user interface description.
  14. You need to have Python 2.4, wxPython 2.8 and python-xml.
  15. The XML stream is read from executing the command given in the
  16. command line, thus you may call it for instance this way:
  17. python <this file.py> r.basins.fill
  18. Or you set an alias or wrap the call up in a nice shell script, GUI
  19. environment ... please contribute your idea.
  20. Updated to wxPython 2.8 syntax and contrib widgets. Methods added to
  21. make it callable by gui. Method added to automatically re-run with
  22. pythonw on a Mac.
  23. .. todo::
  24. verify option value types
  25. Copyright(C) 2000-2013 by the GRASS Development Team
  26. This program is free software under the GPL(>=v2) Read the file
  27. COPYING coming with GRASS for details.
  28. @author Jan-Oliver Wagner <jan@intevation.de>
  29. @author Bernhard Reiter <bernhard@intevation.de>
  30. @author Michael Barton, Arizona State University
  31. @author Daniel Calvelo <dca.gis@gmail.com>
  32. @author Martin Landa <landa.martin@gmail.com>
  33. @author Luca Delucchi <lucadeluge@gmail.com>
  34. @author Stepan Turek <stepan.turek seznam.cz> (CoordinatesSelect)
  35. """
  36. import sys
  37. import string
  38. import textwrap
  39. import os
  40. import copy
  41. import locale
  42. import Queue
  43. import re
  44. import codecs
  45. from threading import Thread
  46. if not os.getenv("GISBASE"):
  47. sys.write("We don't seem to be properly installed, or we are being run "
  48. "outside GRASS. Expect glitches.\n")
  49. gisbase = os.path.join(os.path.dirname(sys.argv[0]), os.path.pardir)
  50. import wx
  51. try:
  52. import wx.lib.agw.flatnotebook as FN
  53. except ImportError:
  54. import wx.lib.flatnotebook as FN
  55. import wx.lib.colourselect as csel
  56. import wx.lib.filebrowsebutton as filebrowse
  57. from wx.lib.newevent import NewEvent
  58. try:
  59. import xml.etree.ElementTree as etree
  60. except ImportError:
  61. import elementtree.ElementTree as etree # Python <= 2.4
  62. from grass.pydispatch.signal import Signal
  63. from grass.script import core as grass
  64. from grass.script import task as gtask
  65. from core import globalvar
  66. from gui_core.widgets import StaticWrapText, ScrolledPanel, ColorTablesComboBox, \
  67. BarscalesComboBox, NArrowsComboBox
  68. from gui_core.ghelp import HelpPanel
  69. from gui_core import gselect
  70. from core import gcmd
  71. from core import utils
  72. from core.utils import _
  73. from core.settings import UserSettings
  74. from gui_core.widgets import FloatValidator, GNotebook, FormNotebook, FormListbook
  75. from core.giface import Notification
  76. wxUpdateDialog, EVT_DIALOG_UPDATE = NewEvent()
  77. """Hide some options in the GUI"""
  78. #_blackList = { 'enabled' : False,
  79. # 'items' : { 'r.buffer' : {'params' : ['input', 'output'],
  80. # 'flags' : ['z', 'overwrite']}}}
  81. _blackList = { 'enabled' : False,
  82. 'items' : {} }
  83. def text_beautify(someString , width = 70):
  84. """Make really long texts shorter, clean up whitespace and remove
  85. trailing punctuation.
  86. """
  87. if width > 0:
  88. return escape_ampersand(string.strip(
  89. os.linesep.join(textwrap.wrap(utils.normalize_whitespace(someString), width)),
  90. ".,;:"))
  91. else:
  92. return escape_ampersand(string.strip(utils.normalize_whitespace(someString), ".,;:"))
  93. def escape_ampersand(text):
  94. """Escapes ampersands with additional ampersand for GUI"""
  95. return string.replace(text, "&", "&&")
  96. class UpdateThread(Thread):
  97. """Update dialog widgets in the thread"""
  98. def __init__(self, parent, event, eventId, task):
  99. Thread.__init__(self)
  100. self.parent = parent
  101. self.event = event
  102. self.eventId = eventId
  103. self.task = task
  104. self.setDaemon(True)
  105. # list of functions which updates the dialog
  106. self.data = {}
  107. def run(self):
  108. # get widget id
  109. if not self.eventId:
  110. for p in self.task.params:
  111. if p.get('gisprompt', False) == False:
  112. continue
  113. prompt = p.get('element', '')
  114. if prompt == 'vector':
  115. name = p.get('name', '')
  116. if name in ('map', 'input'):
  117. self.eventId = p['wxId'][0]
  118. if self.eventId is None:
  119. return
  120. p = self.task.get_param(self.eventId, element = 'wxId', raiseError = False)
  121. if not p or 'wxId-bind' not in p:
  122. return
  123. # is this check necessary?
  124. # get widget prompt
  125. # pType = p.get('prompt', '')
  126. # if not pType:
  127. # return
  128. # check for map/input parameter
  129. pMap = self.task.get_param('map', raiseError = False)
  130. if not pMap:
  131. pMap = self.task.get_param('input', raiseError = False)
  132. if pMap:
  133. map = pMap.get('value', '')
  134. else:
  135. map = None
  136. # avoid running db.describe several times
  137. cparams = dict()
  138. cparams[map] = { 'dbInfo' : None,
  139. 'layers' : None, }
  140. # update reference widgets
  141. for uid in p['wxId-bind']:
  142. win = self.parent.FindWindowById(uid)
  143. if not win:
  144. continue
  145. name = win.GetName()
  146. ### @todo: replace name by isinstance() and signals
  147. pBind = self.task.get_param(uid, element = 'wxId', raiseError = False)
  148. if pBind:
  149. pBind['value'] = ''
  150. # set appropriate types in t.* modules and g.list/remove element selections
  151. if name == 'Select':
  152. type_param = self.task.get_param('type', element='name', raiseError=False)
  153. if 'all' in type_param.get('value'):
  154. etype = type_param.get('values')
  155. if 'all' in etype:
  156. etype.remove('all')
  157. etype = ','.join(etype)
  158. else:
  159. etype = type_param.get('value')
  160. if globalvar.CheckWxVersion([3]):
  161. self.data[win.SetElementList] = {'type': etype}
  162. else:
  163. self.data[win.GetParent().SetElementList] = {'type': etype}
  164. # t.(un)register has one type for 'input', 'maps'
  165. maps_param = self.task.get_param('maps', element='name', raiseError=False)
  166. if self.task.get_name().startswith('t') and maps_param is not None:
  167. if maps_param['wxId'][0] != uid:
  168. element_dict = {'raster': 'strds', 'vector': 'stvds', 'raster_3d': 'str3ds'}
  169. self.data[win.GetParent().SetType] = {'etype': element_dict[type_param.get('value')]}
  170. map = layer = None
  171. driver = db = None
  172. if name in ('LayerSelect', 'ColumnSelect'):
  173. if p.get('element', '') == 'vector': # -> vector
  174. # get map name
  175. map = p.get('value', '')
  176. # get layer
  177. for bid in p['wxId-bind']:
  178. p = self.task.get_param(bid, element = 'wxId', raiseError = False)
  179. if not p:
  180. continue
  181. if p.get('element', '') in ['layer', 'layer_all']:
  182. layer = p.get('value', '')
  183. if layer != '':
  184. layer = p.get('value', '')
  185. else:
  186. layer = p.get('default', '')
  187. break
  188. elif p.get('element', '') in ['layer', 'layer_all']: # -> layer
  189. # get layer
  190. layer = p.get('value', '')
  191. if layer != '':
  192. layer = p.get('value', '')
  193. else:
  194. layer = p.get('default', '')
  195. # get map name
  196. pMapL = self.task.get_param(p['wxId'][0], element = 'wxId-bind', raiseError = False)
  197. if pMapL:
  198. map = pMapL.get('value', '')
  199. if name == 'TableSelect' or \
  200. (name == 'ColumnSelect' and not map):
  201. pDriver = self.task.get_param('dbdriver', element = 'prompt', raiseError = False)
  202. if pDriver:
  203. driver = pDriver.get('value', '')
  204. pDb = self.task.get_param('dbname', element = 'prompt', raiseError = False)
  205. if pDb:
  206. db = pDb.get('value', '')
  207. if name == 'ColumnSelect':
  208. pTable = self.task.get_param('dbtable', element = 'element', raiseError = False)
  209. if pTable:
  210. table = pTable.get('value', '')
  211. if name == 'LayerSelect':
  212. # determine format
  213. native = True
  214. for id in pMap['wxId']:
  215. winVec = self.parent.FindWindowById(id)
  216. if winVec.GetName() == 'VectorFormat' and \
  217. winVec.GetSelection() != 0:
  218. native = False
  219. break
  220. # TODO: update only if needed
  221. if native:
  222. if map:
  223. self.data[win.InsertLayers] = { 'vector' : map }
  224. else:
  225. self.data[win.InsertLayers] = { }
  226. else:
  227. if map:
  228. self.data[win.InsertLayers] = { 'dsn' : map.rstrip('@OGR') }
  229. else:
  230. self.data[win.InsertLayers] = { }
  231. elif name == 'TableSelect':
  232. self.data[win.InsertTables] = { 'driver' : driver,
  233. 'database' : db }
  234. elif name == 'ColumnSelect':
  235. if map:
  236. if map in cparams:
  237. if not cparams[map]['dbInfo']:
  238. cparams[map]['dbInfo'] = gselect.VectorDBInfo(map)
  239. self.data[win.GetParent().InsertColumns] = { 'vector' : map, 'layer' : layer,
  240. 'dbInfo' : cparams[map]['dbInfo'] }
  241. else: # table
  242. if driver and db:
  243. self.data[win.GetParent().InsertTableColumns] = { 'table' : pTable.get('value'),
  244. 'driver' : driver,
  245. 'database' : db }
  246. elif pTable:
  247. self.data[win.GetParent().InsertTableColumns] = { 'table' : pTable.get('value') }
  248. elif name == 'SubGroupSelect':
  249. self.data[win.Insert] = { 'group' : p.get('value', '')}
  250. elif name == 'SignatureSelect':
  251. if p.get('prompt', 'group') == 'group':
  252. group = p.get('value', '')
  253. pSubGroup = self.task.get_param('subgroup', element = 'prompt', raiseError = False)
  254. if pSubGroup:
  255. subgroup = pSubGroup.get('value', '')
  256. else:
  257. subgroup = None
  258. else:
  259. subgroup = p.get('value', '')
  260. pGroup = self.task.get_param('group', element = 'prompt', raiseError = False)
  261. if pGroup:
  262. group = pGroup.get('value', '')
  263. else:
  264. group = None
  265. self.data[win.Insert] = { 'group' : group,
  266. 'subgroup' : subgroup}
  267. elif name == 'LocationSelect':
  268. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  269. if pDbase:
  270. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', '')}
  271. elif name == 'MapsetSelect':
  272. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  273. pLocation = self.task.get_param('location', element = 'element', raiseError = False)
  274. if pDbase and pLocation:
  275. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', ''),
  276. 'location' : pLocation.get('value', '')}
  277. elif name == 'ProjSelect':
  278. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  279. pLocation = self.task.get_param('location', element = 'element', raiseError = False)
  280. pMapset = self.task.get_param('mapset', element = 'element', raiseError = False)
  281. if pDbase and pLocation and pMapset:
  282. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', ''),
  283. 'location' : pLocation.get('value', ''),
  284. 'mapset' : pMapset.get('value', '')}
  285. def UpdateDialog(parent, event, eventId, task):
  286. return UpdateThread(parent, event, eventId, task)
  287. class UpdateQThread(Thread):
  288. """Update dialog widgets in the thread"""
  289. requestId = 0
  290. def __init__(self, parent, requestQ, resultQ, **kwds):
  291. Thread.__init__(self, **kwds)
  292. self.parent = parent # cmdPanel
  293. self.setDaemon(True)
  294. self.requestQ = requestQ
  295. self.resultQ = resultQ
  296. self.start()
  297. def Update(self, callable, *args, **kwds):
  298. UpdateQThread.requestId += 1
  299. self.request = None
  300. self.requestQ.put((UpdateQThread.requestId, callable, args, kwds))
  301. return UpdateQThread.requestId
  302. def run(self):
  303. while True:
  304. requestId, callable, args, kwds = self.requestQ.get()
  305. self.request = callable(*args, **kwds)
  306. self.resultQ.put((requestId, self.request.run()))
  307. if self.request:
  308. event = wxUpdateDialog(data = self.request.data)
  309. wx.PostEvent(self.parent, event)
  310. class TaskFrame(wx.Frame):
  311. """This is the Frame containing the dialog for options input.
  312. The dialog is organized in a notebook according to the guisections
  313. defined by each GRASS command.
  314. If run with a parent, it may Apply, Ok or Cancel; the latter two
  315. close the dialog. The former two trigger a callback.
  316. If run standalone, it will allow execution of the command.
  317. The command is checked and sent to the clipboard when clicking
  318. 'Copy'.
  319. """
  320. def __init__(self, parent, giface, task_description, id = wx.ID_ANY,
  321. get_dcmd = None, layer = None,
  322. style = wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL, **kwargs):
  323. self.get_dcmd = get_dcmd
  324. self.layer = layer
  325. self.task = task_description
  326. self.parent = parent # LayerTree | Modeler | None | ...
  327. self._giface = giface
  328. self.dialogClosing = Signal('TaskFrame.dialogClosing')
  329. # module name + keywords
  330. title = self.task.get_name()
  331. try:
  332. if self.task.keywords != ['']:
  333. title += " [" + ', '.join(self.task.keywords) + "]"
  334. except ValueError:
  335. pass
  336. wx.Frame.__init__(self, parent = parent, id = id, title = title,
  337. name = "MainFrame", style = style, **kwargs)
  338. self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
  339. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  340. # statusbar
  341. self.CreateStatusBar()
  342. # icon
  343. self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_dialog.ico'), wx.BITMAP_TYPE_ICO))
  344. guisizer = wx.BoxSizer(wx.VERTICAL)
  345. # set apropriate output window
  346. if self.parent:
  347. self.standalone = False
  348. else:
  349. self.standalone = True
  350. # logo + description
  351. topsizer = wx.BoxSizer(wx.HORIZONTAL)
  352. # GRASS logo
  353. self.logo = wx.StaticBitmap(parent = self.panel,
  354. bitmap = wx.Bitmap(name = os.path.join(globalvar.IMGDIR,
  355. 'grass_form.png'),
  356. type = wx.BITMAP_TYPE_PNG))
  357. topsizer.Add(item = self.logo, proportion = 0, border = 3,
  358. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL)
  359. # add module description
  360. if self.task.label:
  361. module_desc = self.task.label + ' ' + self.task.description
  362. else:
  363. module_desc = self.task.description
  364. self.description = StaticWrapText(parent=self.panel,
  365. label=module_desc)
  366. topsizer.Add(item = self.description, proportion = 1, border = 5,
  367. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  368. guisizer.Add(item = topsizer, proportion = 0, flag = wx.EXPAND)
  369. self.panel.SetSizerAndFit(guisizer)
  370. self.Layout()
  371. # notebooks
  372. self.notebookpanel = CmdPanel(parent = self.panel, giface = self._giface, task = self.task,
  373. frame = self)
  374. self._gconsole = self.notebookpanel._gconsole
  375. if self._gconsole:
  376. self._gconsole.mapCreated.connect(self.OnMapCreated)
  377. self._gconsole.updateMap.connect(lambda: self._giface.updateMap.emit())
  378. self.goutput = self.notebookpanel.goutput
  379. if self.goutput:
  380. self.goutput.showNotification.connect(lambda message: self.SetStatusText(message))
  381. self.notebookpanel.OnUpdateValues = self.updateValuesHook
  382. guisizer.Add(item = self.notebookpanel, proportion = 1, flag = wx.EXPAND)
  383. # status bar
  384. status_text = _("Enter parameters for '") + self.task.name + "'"
  385. try:
  386. self.task.get_cmd()
  387. self.updateValuesHook()
  388. except ValueError:
  389. self.SetStatusText(status_text)
  390. # buttons
  391. btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  392. # cancel
  393. self.btn_cancel = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  394. self.btn_cancel.SetToolTipString(_("Close this window without executing the command (Ctrl+Q)"))
  395. btnsizer.Add(item = self.btn_cancel, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
  396. self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  397. # bind closing to ESC and CTRL+Q
  398. self.Bind(wx.EVT_MENU, self.OnCancel, id=wx.ID_CLOSE)
  399. accelTableList = [(wx.ACCEL_NORMAL, wx.WXK_ESCAPE, wx.ID_CLOSE)]
  400. accelTableList = [(wx.ACCEL_CTRL, ord('Q'), wx.ID_CLOSE)]
  401. # TODO: bind Ctrl-t for tile windows here (trac #2004)
  402. if self.get_dcmd is not None: # A callback has been set up
  403. btn_apply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
  404. btn_ok = wx.Button(parent = self.panel, id = wx.ID_OK)
  405. btn_ok.SetDefault()
  406. btnsizer.Add(item = btn_apply, proportion = 0,
  407. flag = wx.ALL | wx.ALIGN_CENTER,
  408. border = 10)
  409. btnsizer.Add(item = btn_ok, proportion = 0,
  410. flag = wx.ALL | wx.ALIGN_CENTER,
  411. border = 10)
  412. btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
  413. btn_ok.Bind(wx.EVT_BUTTON, self.OnOK)
  414. else: # We're standalone
  415. # run
  416. self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label = _("&Run"))
  417. self.btn_run.SetToolTipString(_("Run the command (Ctrl+R)"))
  418. self.btn_run.SetDefault()
  419. self.btn_run.SetForegroundColour(wx.Colour(35, 142, 35))
  420. # copy
  421. self.btn_clipboard = wx.Button(parent = self.panel, id = wx.ID_COPY)
  422. self.btn_clipboard.SetToolTipString(_("Copy the current command string to the clipboard"))
  423. btnsizer.Add(item = self.btn_run, proportion = 0,
  424. flag = wx.ALL | wx.ALIGN_CENTER,
  425. border = 10)
  426. btnsizer.Add(item = self.btn_clipboard, proportion = 0,
  427. flag = wx.ALL | wx.ALIGN_CENTER,
  428. border = 10)
  429. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  430. self.Bind(wx.EVT_MENU, self.OnRun, id=wx.ID_OK)
  431. accelTableList.append((wx.ACCEL_CTRL, ord('R'), wx.ID_OK))
  432. self.btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
  433. # help
  434. self.btn_help = wx.Button(parent = self.panel, id = wx.ID_HELP)
  435. self.btn_help.SetToolTipString(_("Show manual page of the command (Ctrl+H)"))
  436. self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
  437. self.Bind(wx.EVT_MENU, self.OnHelp, id=wx.ID_HELP)
  438. accelTableList.append((wx.ACCEL_CTRL, ord('H'), wx.ID_HELP))
  439. if self.notebookpanel.notebook.GetPageIndexByName('manual') < 0:
  440. self.btn_help.Hide()
  441. # add help button
  442. btnsizer.Add(item = self.btn_help, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
  443. guisizer.Add(item = btnsizer, proportion = 0, flag = wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT,
  444. border = 30)
  445. # abort key bindings
  446. abortId = wx.NewId()
  447. self.Bind(wx.EVT_MENU, self.OnAbort, id=abortId)
  448. accelTableList.append((wx.ACCEL_CTRL, ord('S'), abortId))
  449. # set accelerator table
  450. accelTable = wx.AcceleratorTable(accelTableList)
  451. self.SetAcceleratorTable(accelTable)
  452. if self._giface and self._giface.GetLayerTree():
  453. addLayer = False
  454. for p in self.task.params:
  455. if p.get('age', 'old') == 'new' and \
  456. p.get('prompt', '') in ('raster', 'vector', '3d-raster'):
  457. addLayer = True
  458. if addLayer:
  459. # add newly created map into layer tree
  460. self.addbox = wx.CheckBox(parent = self.panel,
  461. label = _('Add created map(s) into layer tree'), style = wx.NO_BORDER)
  462. self.addbox.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  463. guisizer.Add(item = self.addbox, proportion = 0,
  464. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  465. border = 5)
  466. hasNew = False
  467. for p in self.task.params:
  468. if p.get('age', 'old') == 'new':
  469. hasNew = True
  470. break
  471. if self.get_dcmd is None and hasNew:
  472. # close dialog when command is terminated
  473. self.closebox = wx.CheckBox(parent = self.panel,
  474. label = _('Close dialog on finish'), style = wx.NO_BORDER)
  475. self.closebox.SetValue(UserSettings.Get(group = 'cmd', key = 'closeDlg', subkey = 'enabled'))
  476. self.closebox.SetToolTipString(_("Close dialog when command is successfully finished. "
  477. "Change this settings in Preferences dialog ('Command' tab)."))
  478. guisizer.Add(item = self.closebox, proportion = 0,
  479. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  480. border = 5)
  481. # bindings
  482. self.Bind(wx.EVT_CLOSE, self.OnCancel)
  483. # do layout
  484. # called automatically by SetSizer()
  485. self.panel.SetAutoLayout(True)
  486. self.panel.SetSizerAndFit(guisizer)
  487. sizeFrame = self.GetBestSize()
  488. self.SetMinSize(sizeFrame)
  489. if hasattr(self, "closebox"):
  490. scale = 0.33
  491. else:
  492. scale = 0.50
  493. self.SetSize(wx.Size(sizeFrame[0], sizeFrame[1] + scale * max(self.notebookpanel.panelMinHeight,
  494. self.notebookpanel.constrained_size[1])))
  495. # thread to update dialog
  496. # create queues
  497. self.requestQ = Queue.Queue()
  498. self.resultQ = Queue.Queue()
  499. self.updateThread = UpdateQThread(self.notebookpanel, self.requestQ, self.resultQ)
  500. self.Layout()
  501. # keep initial window size limited for small screens
  502. width, height = self.GetSizeTuple()
  503. self.SetSize(wx.Size(min(width, 650),
  504. min(height, 500)))
  505. # fix goutput's pane size (required for Mac OSX)
  506. if self.goutput:
  507. self.goutput.SetSashPosition(int(self.GetSize()[1] * .75))
  508. def updateValuesHook(self, event = None):
  509. """Update status bar data"""
  510. self.SetStatusText(' '.join(self.notebookpanel.createCmd(ignoreErrors = True)))
  511. if event:
  512. event.Skip()
  513. def OnDone(self, event):
  514. """This function is launched from OnRun() when command is
  515. finished
  516. """
  517. if hasattr(self, "btn_cancel"):
  518. self.btn_cancel.Enable(True)
  519. if hasattr(self, "btn_clipboard"):
  520. self.btn_clipboard.Enable(True)
  521. if hasattr(self, "btn_help"):
  522. self.btn_help.Enable(True)
  523. if hasattr(self, "btn_run"):
  524. self.btn_run.Enable(True)
  525. if hasattr(self, "get_dcmd") and \
  526. self.get_dcmd is None and \
  527. hasattr(self, "closebox") and \
  528. self.closebox.IsChecked() and \
  529. (event.returncode == 0):
  530. # was closed also when aborted but better is leave it open
  531. wx.FutureCall(2000, self.Close)
  532. def OnMapCreated(self, name, ltype):
  533. """Map created or changed
  534. :param name: map name
  535. :param ltype: layer type (prompt value)
  536. """
  537. if hasattr(self, "addbox") and self.addbox.IsChecked():
  538. add = True
  539. else:
  540. add = False
  541. if self._giface:
  542. self._giface.mapCreated.emit(name=name, ltype=ltype, add=add)
  543. def OnOK(self, event):
  544. """OK button pressed"""
  545. cmd = self.OnApply(event)
  546. if cmd is not None and self.get_dcmd is not None:
  547. self.OnCancel(event)
  548. def OnApply(self, event):
  549. """Apply the command"""
  550. if self._giface and hasattr(self._giface, "_model"):
  551. cmd = self.createCmd(ignoreErrors = True, ignoreRequired = True)
  552. else:
  553. cmd = self.createCmd()
  554. if cmd is not None and self.get_dcmd is not None:
  555. # return d.* command to layer tree for rendering
  556. self.get_dcmd(cmd, self.layer, {"params": self.task.params,
  557. "flags" : self.task.flags},
  558. self)
  559. # echo d.* command to output console
  560. # self.parent.writeDCommand(cmd)
  561. return cmd
  562. def OnRun(self, event):
  563. """Run the command"""
  564. cmd = self.createCmd()
  565. if not cmd or len(cmd) < 1:
  566. return
  567. ret = 0
  568. if self.standalone or cmd[0][0:2] != "d.":
  569. # Send any non-display command to parent window (probably wxgui.py)
  570. # put to parents switch to 'Command output'
  571. self.notebookpanel.notebook.SetSelectionByName('output')
  572. try:
  573. if self.task.path:
  574. cmd[0] = self.task.path # full path
  575. ret = self._gconsole.RunCmd(cmd, onDone = self.OnDone)
  576. except AttributeError as e:
  577. print >> sys.stderr, "%s: Probably not running in wxgui.py session?" % (e)
  578. print >> sys.stderr, "parent window is: %s" % (str(self.parent))
  579. else:
  580. gcmd.Command(cmd)
  581. if ret != 0:
  582. self.notebookpanel.notebook.SetSelection(0)
  583. return
  584. # update buttons status
  585. for btn in (self.btn_run,
  586. self.btn_cancel,
  587. self.btn_clipboard,
  588. self.btn_help):
  589. btn.Enable(False)
  590. def OnAbort(self, event):
  591. """Abort running command"""
  592. from core.gconsole import wxCmdAbort
  593. event = wxCmdAbort(aborted = True)
  594. wx.PostEvent(self._gconsole, event)
  595. def OnCopy(self, event):
  596. """Copy the command"""
  597. cmddata = wx.TextDataObject()
  598. # list -> string
  599. cmdlist = self.createCmd(ignoreErrors = True)
  600. # TODO: better protect whitespace with quotes
  601. for i in range(1, len(cmdlist)):
  602. if ' ' in cmdlist[i]:
  603. optname, val = cmdlist[i].split("=", 1)
  604. cmdlist[i] = '%s="%s"' % (optname, val)
  605. cmdstring = ' '.join(cmdlist)
  606. cmddata.SetText(cmdstring)
  607. if wx.TheClipboard.Open():
  608. # wx.TheClipboard.UsePrimarySelection(True)
  609. wx.TheClipboard.SetData(cmddata)
  610. wx.TheClipboard.Close()
  611. self.SetStatusText(_("'%s' copied to clipboard") % \
  612. (cmdstring))
  613. def OnCancel(self, event):
  614. """Cancel button pressed"""
  615. self.MakeModal(False)
  616. self.dialogClosing.emit()
  617. if self.get_dcmd and \
  618. self.parent and \
  619. self.parent.GetName() in ('LayerTree',
  620. 'MapWindow'):
  621. # display decorations and
  622. # pressing OK or cancel after setting layer properties
  623. if self.task.name in ['d.barscale','d.legend', 'd.northarrow', 'd.histogram'] \
  624. or len(self.parent.GetLayerInfo(self.layer, key = 'cmd')) >= 1:
  625. self.Hide()
  626. # canceled layer with nothing set
  627. elif len(self.parent.GetLayerInfo(self.layer, key = 'cmd')) < 1:
  628. try:
  629. self.parent.Delete(self.layer)
  630. except ValueError:
  631. # happens when closing dialog of a new layer which was removed from tree
  632. pass
  633. self.Destroy()
  634. else:
  635. # cancel for non-display commands
  636. self.Destroy()
  637. def OnHelp(self, event):
  638. """Show manual page (switch to the 'Manual' notebook page)"""
  639. if self.notebookpanel.notebook.GetPageIndexByName('manual') > -1:
  640. self.notebookpanel.notebook.SetSelectionByName('manual')
  641. self.notebookpanel.OnPageChange(None)
  642. if event:
  643. event.Skip()
  644. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  645. """Create command string (python list)"""
  646. return self.notebookpanel.createCmd(ignoreErrors = ignoreErrors,
  647. ignoreRequired = ignoreRequired)
  648. class CmdPanel(wx.Panel):
  649. """A panel containing a notebook dividing in tabs the different
  650. guisections of the GRASS cmd.
  651. """
  652. def __init__(self, parent, giface, task, id = wx.ID_ANY, frame = None, *args, **kwargs):
  653. if frame:
  654. self.parent = frame
  655. else:
  656. self.parent = parent
  657. self.task = task
  658. self._giface = giface
  659. wx.Panel.__init__(self, parent, id = id, *args, **kwargs)
  660. self.mapCreated = Signal
  661. self.updateMap = Signal
  662. # Determine tab layout
  663. sections = []
  664. is_section = {}
  665. not_hidden = [ p for p in self.task.params + self.task.flags if not p.get('hidden', False) == True ]
  666. self.label_id = [] # wrap titles on resize
  667. self.Bind(wx.EVT_SIZE, self.OnSize)
  668. for task in not_hidden:
  669. if task.get('required', False) and not task.get('guisection', ''):
  670. # All required go into Main, even if they had defined another guisection
  671. task['guisection'] = _('Required')
  672. if task.get('guisection','') == '':
  673. # Undefined guisections end up into Options
  674. task['guisection'] = _('Optional')
  675. if task['guisection'] not in is_section:
  676. # We do it like this to keep the original order, except for Main which goes first
  677. is_section[task['guisection']] = 1
  678. sections.append(task['guisection'])
  679. else:
  680. is_section[ task['guisection'] ] += 1
  681. del is_section
  682. # 'Required' tab goes first, 'Optional' as the last one
  683. for (newidx,content) in [ (0,_('Required')), (len(sections)-1,_('Optional')) ]:
  684. if content in sections:
  685. idx = sections.index(content)
  686. sections[idx:idx+1] = []
  687. sections[newidx:newidx] = [content]
  688. panelsizer = wx.BoxSizer(orient = wx.VERTICAL)
  689. # build notebook
  690. style = UserSettings.Get(group = 'appearance', key = 'commandNotebook', subkey = 'selection')
  691. if style == 0: # basic top
  692. self.notebook = FormNotebook(self, style = wx.BK_TOP)
  693. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  694. elif style == 1: # basic left
  695. self.notebook = FormNotebook(self, style = wx.BK_LEFT)
  696. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  697. elif style == 2: # fancy green
  698. self.notebook = GNotebook(self, style = globalvar.FNPageStyle | FN.FNB_NO_X_BUTTON )
  699. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  700. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  701. elif style == 3:
  702. self.notebook = FormListbook(self, style = wx.BK_LEFT)
  703. self.notebook.Bind(wx.EVT_LISTBOOK_PAGE_CHANGED, self.OnPageChange)
  704. self.notebook.Refresh()
  705. tab = {}
  706. tabsizer = {}
  707. for section in sections:
  708. tab[section] = ScrolledPanel(parent = self.notebook)
  709. tab[section].SetScrollRate(10, 10)
  710. tabsizer[section] = wx.BoxSizer(orient = wx.VERTICAL)
  711. #
  712. # flags
  713. #
  714. visible_flags = [ f for f in self.task.flags if not f.get('hidden', False) == True ]
  715. for f in visible_flags:
  716. # we don't want another help (checkbox appeared in r58783)
  717. if f['name'] == 'help':
  718. continue
  719. which_sizer = tabsizer[ f['guisection'] ]
  720. which_panel = tab[ f['guisection'] ]
  721. # if label is given: description -> tooltip
  722. if f.get('label','') != '':
  723. title = text_beautify(f['label'])
  724. tooltip = text_beautify(f['description'], width = -1)
  725. else:
  726. title = text_beautify(f['description'])
  727. tooltip = None
  728. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  729. rtitle_txt = wx.StaticText(parent = which_panel,
  730. label = '(' + f['name'] + ')')
  731. chk = wx.CheckBox(parent = which_panel, label = title, style = wx.NO_BORDER)
  732. self.label_id.append(chk.GetId())
  733. if tooltip:
  734. chk.SetToolTipString(tooltip)
  735. chk.SetValue(f.get('value', False))
  736. title_sizer.Add(item = chk, proportion = 1,
  737. flag = wx.EXPAND)
  738. title_sizer.Add(item = rtitle_txt, proportion = 0,
  739. flag = wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
  740. which_sizer.Add(item = title_sizer, proportion = 0,
  741. flag = wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border = 5)
  742. f['wxId'] = [ chk.GetId(), ]
  743. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  744. if self.parent.GetName() == 'MainFrame' and (self._giface and hasattr(self._giface, "_model")):
  745. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  746. label = _("Parameterized in model"))
  747. parChk.SetName('ModelParam')
  748. parChk.SetValue(f.get('parameterized', False))
  749. if 'wxId' in f:
  750. f['wxId'].append(parChk.GetId())
  751. else:
  752. f['wxId'] = [ parChk.GetId() ]
  753. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  754. which_sizer.Add(item = parChk, proportion = 0,
  755. flag = wx.LEFT, border = 20)
  756. if f['name'] in ('verbose', 'quiet'):
  757. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  758. vq = UserSettings.Get(group = 'cmd', key = 'verbosity', subkey = 'selection')
  759. if f['name'] == vq:
  760. chk.SetValue(True)
  761. f['value'] = True
  762. if f['name'] == 'overwrite':
  763. f['value'] = UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled')
  764. chk.SetValue(f['value'])
  765. #
  766. # parameters
  767. #
  768. visible_params = [ p for p in self.task.params if not p.get('hidden', False) == True ]
  769. try:
  770. first_param = visible_params[0]
  771. except IndexError:
  772. first_param = None
  773. for p in visible_params:
  774. which_sizer = tabsizer[p['guisection']]
  775. which_panel = tab[p['guisection']]
  776. # if label is given -> label and description -> tooltip
  777. # otherwise description -> lavel
  778. if p.get('label','') != '':
  779. title = text_beautify(p['label'])
  780. tooltip = text_beautify(p['description'], width = -1)
  781. else:
  782. title = text_beautify(p['description'])
  783. tooltip = None
  784. prompt = p.get('prompt', '')
  785. # title sizer (description, name, type)
  786. if (len(p.get('values', [])) > 0) and \
  787. p.get('multiple', False) and \
  788. p.get('gisprompt', False) == False and \
  789. p.get('type', '') == 'string':
  790. title_txt = wx.StaticBox(parent = which_panel, id = wx.ID_ANY)
  791. else:
  792. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  793. title_txt = wx.StaticText(parent = which_panel)
  794. if p['key_desc']:
  795. ltype = ','.join(p['key_desc'])
  796. else:
  797. ltype = p['type']
  798. # red star for required options
  799. if p.get('required', False):
  800. required_txt = wx.StaticText(parent=which_panel, label="*")
  801. required_txt.SetForegroundColour(wx.RED)
  802. required_txt.SetToolTipString(_("This option is required"))
  803. else:
  804. required_txt = wx.StaticText(parent=which_panel, label="")
  805. rtitle_txt = wx.StaticText(parent = which_panel,
  806. label = '(' + p['name'] + '=' + ltype + ')')
  807. title_sizer.Add(item = title_txt, proportion = 0,
  808. flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
  809. title_sizer.Add(item = required_txt, proportion=1,
  810. flag = wx.EXPAND, border=0)
  811. title_sizer.Add(item = rtitle_txt, proportion = 0,
  812. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  813. which_sizer.Add(item = title_sizer, proportion = 0,
  814. flag = wx.EXPAND)
  815. self.label_id.append(title_txt.GetId())
  816. # title expansion
  817. if p.get('multiple', False) and len(p.get('values','')) == 0:
  818. title = _("[multiple]") + " " + title
  819. if p.get('value','') == '' :
  820. p['value'] = p.get('default','')
  821. if (len(p.get('values', [])) > 0):
  822. valuelist = map(str, p.get('values',[]))
  823. valuelist_desc = map(unicode, p.get('values_desc',[]))
  824. required_text = "*" if p.get('required', False) else ""
  825. if p.get('multiple', False) and \
  826. p.get('gisprompt',False) == False and \
  827. p.get('type', '') == 'string':
  828. title_txt.SetLabel(" %s:%s (%s=%s) " % (title, required_text, p['name'], p['type']))
  829. stSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.VERTICAL)
  830. if valuelist_desc:
  831. hSizer = wx.FlexGridSizer(cols = 1, vgap = 1)
  832. else:
  833. hSizer = wx.FlexGridSizer(cols = 6, vgap = 1, hgap = 1)
  834. isEnabled = {}
  835. # copy default values
  836. if p['value'] == '':
  837. p['value'] = p.get('default', '')
  838. for defval in p.get('value', '').split(','):
  839. isEnabled[ defval ] = 'yes'
  840. # for multi checkboxes, this is an array of all wx IDs
  841. # for each individual checkbox
  842. p[ 'wxId' ] = list()
  843. idx = 0
  844. for val in valuelist:
  845. try:
  846. label = valuelist_desc[idx]
  847. except IndexError:
  848. label = val
  849. chkbox = wx.CheckBox(parent = which_panel,
  850. label = text_beautify(label))
  851. p[ 'wxId' ].append(chkbox.GetId())
  852. if val in isEnabled:
  853. chkbox.SetValue(True)
  854. hSizer.Add(item = chkbox, proportion = 0)
  855. chkbox.Bind(wx.EVT_CHECKBOX, self.OnUpdateSelection)
  856. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  857. idx += 1
  858. stSizer.Add(item = hSizer, proportion = 0,
  859. flag = wx.ADJUST_MINSIZE | wx.ALL, border = 1)
  860. which_sizer.Add(item = stSizer, proportion = 0,
  861. flag = wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border = 5)
  862. elif p.get('gisprompt', False) is False:
  863. if len(valuelist) == 1: # -> textctrl
  864. title_txt.SetLabel("%s (%s %s):" % (title, _('valid range'),
  865. str(valuelist[0])))
  866. if p.get('type', '') == 'integer' and \
  867. not p.get('multiple', False):
  868. # for multiple integers use textctrl instead of spinsctrl
  869. try:
  870. minValue, maxValue = map(int, valuelist[0].rsplit('-', 1))
  871. except ValueError:
  872. minValue = -1e6
  873. maxValue = 1e6
  874. txt2 = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY, size = globalvar.DIALOG_SPIN_SIZE,
  875. min = minValue, max = maxValue)
  876. style = wx.BOTTOM | wx.LEFT
  877. else:
  878. txt2 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  879. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  880. value = self._getValue(p)
  881. # parameter previously set
  882. if value:
  883. if isinstance(txt2, wx.SpinCtrl):
  884. txt2.SetValue(int(value))
  885. else:
  886. txt2.SetValue(value)
  887. which_sizer.Add(item = txt2, proportion = 0,
  888. flag = style, border = 5)
  889. p['wxId'] = [ txt2.GetId(), ]
  890. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  891. else:
  892. title_txt.SetLabel(title + ':')
  893. value = self._getValue(p)
  894. if p['name'] == 'icon': # symbols
  895. bitmap = wx.Bitmap(os.path.join(globalvar.SYMBDIR, value) + '.png')
  896. bb = wx.BitmapButton(parent = which_panel, id = wx.ID_ANY,
  897. bitmap = bitmap)
  898. iconLabel = wx.StaticText(parent = which_panel, id = wx.ID_ANY)
  899. iconLabel.SetLabel(value)
  900. p['value'] = value
  901. p['wxId'] = [bb.GetId(), iconLabel.GetId()]
  902. bb.Bind(wx.EVT_BUTTON, self.OnSetSymbol)
  903. this_sizer = wx.BoxSizer(wx.HORIZONTAL)
  904. this_sizer.Add(item = bb, proportion = 0,
  905. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  906. this_sizer.Add(item = iconLabel, proportion = 0,
  907. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border = 5)
  908. which_sizer.Add(item = this_sizer, proportion = 0,
  909. flag = wx.ADJUST_MINSIZE, border = 0)
  910. else:
  911. # list of values (combo)
  912. cb = wx.ComboBox(parent=which_panel, id=wx.ID_ANY, value=p.get('default',''),
  913. size=globalvar.DIALOG_COMBOBOX_SIZE,
  914. choices=valuelist, style=wx.CB_DROPDOWN)
  915. if value:
  916. cb.SetValue(value) # parameter previously set
  917. which_sizer.Add(item = cb, proportion = 0,
  918. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  919. p['wxId'] = [cb.GetId(),]
  920. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  921. cb.Bind(wx.EVT_TEXT, self.OnSetValue)
  922. if p.get('guidependency', ''):
  923. cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  924. # text entry
  925. if (p.get('type','string') in ('string','integer','float')
  926. and len(p.get('values',[])) == 0
  927. and p.get('gisprompt',False) == False
  928. and p.get('prompt','') != 'color'):
  929. title_txt.SetLabel(title + ':')
  930. if p.get('multiple', False) or \
  931. p.get('type', 'string') == 'string' or \
  932. len(p.get('key_desc', [])) > 1:
  933. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  934. value = self._getValue(p)
  935. if value:
  936. # parameter previously set
  937. txt3.SetValue(str(value))
  938. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  939. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  940. elif p.get('type', '') == 'integer':
  941. minValue = -1e9
  942. maxValue = 1e9
  943. value = self._getValue(p)
  944. txt3 = wx.SpinCtrl(parent = which_panel, value = p.get('default', ''),
  945. size = globalvar.DIALOG_SPIN_SIZE,
  946. min = minValue, max = maxValue)
  947. if value:
  948. txt3.SetValue(int(value)) # parameter previously set
  949. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  950. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  951. else: # float
  952. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  953. validator = FloatValidator())
  954. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  955. value = self._getValue(p)
  956. if value:
  957. txt3.SetValue(str(value)) # parameter previously set
  958. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  959. which_sizer.Add(item = txt3, proportion = 0,
  960. flag = style, border = 5)
  961. p['wxId'] = [ txt3.GetId(), ]
  962. #
  963. # element selection tree combobox (maps, icons, regions, etc.)
  964. #
  965. if p.get('gisprompt', False):
  966. title_txt.SetLabel(title + ':')
  967. # GIS element entry
  968. if p.get('prompt','') not in ('color',
  969. 'cat',
  970. 'cats',
  971. 'subgroup',
  972. 'sigfile',
  973. 'separator',
  974. 'dbdriver',
  975. 'dbname',
  976. 'dbtable',
  977. 'dbcolumn',
  978. 'layer',
  979. 'location',
  980. 'mapset',
  981. 'dbase',
  982. 'coords',
  983. 'file',
  984. 'dir',
  985. 'colortable',
  986. 'barscale',
  987. 'northarrow'):
  988. multiple = p.get('multiple', False)
  989. if p.get('age', '') == 'new':
  990. mapsets = [grass.gisenv()['MAPSET'],]
  991. else:
  992. mapsets = None
  993. if self.task.name in ('r.proj', 'v.proj') \
  994. and p.get('name', '') == 'input':
  995. if self.task.name == 'r.proj':
  996. isRaster = True
  997. else:
  998. isRaster = False
  999. selection = gselect.ProjSelect(parent = which_panel,
  1000. isRaster = isRaster)
  1001. p['wxId'] = [ selection.GetId(), ]
  1002. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1003. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1004. else:
  1005. elem = p.get('element', None)
  1006. # hack for t.* modules
  1007. if elem in ('stds', 'map'):
  1008. orig_elem = elem
  1009. type_param = self.task.get_param('type', element = 'name', raiseError = False)
  1010. if type_param:
  1011. elem = type_param.get('default', None)
  1012. # for t.(un)register:
  1013. maps_param = self.task.get_param('maps', element = 'name', raiseError = False)
  1014. if maps_param and orig_elem == 'stds':
  1015. element_dict = {'raster': 'strds', 'vector': 'stvds', 'raster_3d': 'str3ds'}
  1016. elem = element_dict[type_param.get('default')]
  1017. if self._giface and hasattr(self._giface, "_model"):
  1018. extraItems = {_('Graphical Modeler') : self._giface.GetLayerList(p.get('prompt'))}
  1019. else:
  1020. extraItems = None
  1021. selection = gselect.Select(parent = which_panel, id = wx.ID_ANY,
  1022. size = globalvar.DIALOG_GSELECT_SIZE,
  1023. type = elem, multiple = multiple, nmaps = len(p.get('key_desc', [])),
  1024. mapsets = mapsets, fullyQualified = p.get('age', 'old') == 'old',
  1025. extraItems = extraItems)
  1026. value = self._getValue(p)
  1027. if value:
  1028. selection.SetValue(value)
  1029. formatSelector = True
  1030. # A gselect.Select is a combobox with two children: a textctl and a popupwindow;
  1031. # we target the textctl here
  1032. textWin = selection.GetTextCtrl()
  1033. if globalvar.CheckWxVersion([3]):
  1034. p['wxId'] = [selection.GetId(), ]
  1035. else:
  1036. p['wxId'] = [textWin.GetId(), ]
  1037. if prompt != 'vector':
  1038. self.FindWindowById(p['wxId'][0]).Bind(wx.EVT_TEXT, self.OnSetValue)
  1039. if prompt == 'vector':
  1040. win = self.FindWindowById(p['wxId'][0])
  1041. # handlers should be bound in this order
  1042. # OnUpdateSelection depends on calling OnSetValue first which is bad
  1043. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1044. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1045. # if formatSelector and p.get('age', 'old') == 'old':
  1046. # # OGR supported (read-only)
  1047. # self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  1048. # self.hsizer.Add(item = selection,
  1049. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1050. # border = 5)
  1051. # # format (native / ogr)
  1052. # rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  1053. # label = " %s " % _("Format"),
  1054. # style = wx.RA_SPECIFY_ROWS,
  1055. # choices = [_("Native / Linked OGR"), _("Direct OGR")])
  1056. # if p.get('value', '').lower().rfind('@ogr') > -1:
  1057. # rbox.SetSelection(1)
  1058. # rbox.SetName('VectorFormat')
  1059. # rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  1060. # self.hsizer.Add(item = rbox,
  1061. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1062. # wx.RIGHT | wx.ALIGN_TOP,
  1063. # border = 5)
  1064. # ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  1065. # default = 'dir',
  1066. # exclude = ['file'])
  1067. # self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  1068. # self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  1069. # ogrSelection.SetName('OgrSelect')
  1070. # ogrSelection.Hide()
  1071. # which_sizer.Add(item = self.hsizer, proportion = 0)
  1072. # p['wxId'].append(rbox.GetId())
  1073. # p['wxId'].append(ogrSelection.GetId())
  1074. # for win in ogrSelection.GetDsnWin():
  1075. # p['wxId'].append(win.GetId())
  1076. # else:
  1077. which_sizer.Add(item = selection, proportion = 0,
  1078. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1079. border = 5)
  1080. elif prompt == 'group':
  1081. win = self.FindWindowById(p['wxId'][0])
  1082. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1083. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1084. which_sizer.Add(item = selection, proportion = 0,
  1085. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1086. border = 5)
  1087. else:
  1088. if prompt in ('stds', 'strds', 'stvds', 'str3ds'):
  1089. showButton = True
  1090. try:
  1091. # if matplotlib is there
  1092. from timeline import frame
  1093. showButton = True
  1094. except ImportError:
  1095. showButton = False
  1096. else:
  1097. showButton = False
  1098. if showButton:
  1099. iconTheme = UserSettings.Get(group='appearance', key='iconTheme', subkey='type')
  1100. bitmap = wx.Bitmap(os.path.join(globalvar.ICONDIR, iconTheme, 'map-info.png'))
  1101. bb = wx.BitmapButton(parent=which_panel, bitmap=bitmap)
  1102. bb.Bind(wx.EVT_BUTTON, self.OnTimelineTool)
  1103. bb.SetToolTipString(_("Show graphical representation of temporal extent of dataset(s) ."))
  1104. p['wxId'].append(bb.GetId())
  1105. hSizer = wx.BoxSizer(wx.HORIZONTAL)
  1106. hSizer.Add(item=selection, proportion=0,
  1107. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1108. border=5)
  1109. hSizer.Add(item=bb, proportion=0,
  1110. flag=wx.EXPAND|wx.BOTTOM | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1111. border=5)
  1112. which_sizer.Add(hSizer)
  1113. else:
  1114. which_sizer.Add(item=selection, proportion=0,
  1115. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1116. border=5)
  1117. # subgroup
  1118. elif prompt == 'subgroup':
  1119. selection = gselect.SubGroupSelect(parent = which_panel)
  1120. p['wxId'] = [ selection.GetId() ]
  1121. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1122. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1123. which_sizer.Add(item = selection, proportion = 0,
  1124. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1125. border = 5)
  1126. # sigrature file
  1127. elif prompt == 'sigfile':
  1128. selection = gselect.SignatureSelect(parent = which_panel, element = p.get('element', 'sig'))
  1129. p['wxId'] = [ selection.GetId() ]
  1130. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1131. which_sizer.Add(item = selection, proportion = 0,
  1132. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1133. border = 5)
  1134. # separator
  1135. elif prompt == 'separator':
  1136. win = gselect.SeparatorSelect(parent = which_panel)
  1137. value = self._getValue(p)
  1138. win.SetValue(value)
  1139. p['wxId'] = [ win.GetId() ]
  1140. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1141. which_sizer.Add(item = win, proportion = 0,
  1142. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1143. border = 5)
  1144. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1145. elif prompt in ('dbdriver',
  1146. 'dbname',
  1147. 'dbtable',
  1148. 'dbcolumn',
  1149. 'layer',
  1150. 'location',
  1151. 'mapset',
  1152. 'dbase'):
  1153. if p.get('multiple', 'no') == 'yes':
  1154. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1155. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1156. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1157. else:
  1158. value = self._getValue(p)
  1159. if prompt == 'layer':
  1160. if p.get('element', 'layer') == 'layer_all':
  1161. all = True
  1162. else:
  1163. all = False
  1164. if p.get('age', 'old') == 'old':
  1165. win = gselect.LayerSelect(parent = which_panel,
  1166. all = all,
  1167. default = p['default'])
  1168. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1169. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1170. win.SetValue(str(value)) # default or previously set value
  1171. else:
  1172. win = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY,
  1173. min = 1, max = 100, initial = int(p['default']))
  1174. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1175. win.SetValue(int(value)) # default or previously set value
  1176. p['wxId'] = [ win.GetId() ]
  1177. elif prompt == 'dbdriver':
  1178. win = gselect.DriverSelect(parent = which_panel,
  1179. choices = p.get('values', []),
  1180. value = value)
  1181. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1182. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1183. elif prompt == 'dbname':
  1184. win = gselect.DatabaseSelect(parent = which_panel,
  1185. value = value)
  1186. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1187. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1188. elif prompt == 'dbtable':
  1189. if p.get('age', 'old') == 'old':
  1190. win = gselect.TableSelect(parent = which_panel)
  1191. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1192. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1193. else:
  1194. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1195. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1196. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1197. elif prompt == 'dbcolumn':
  1198. win = gselect.ColumnSelect(parent = which_panel,
  1199. value = value,
  1200. param = p,
  1201. multiple = p.get('multiple', False))
  1202. # A gselect.ColumnSelect is a combobox
  1203. # with two children: a textctl and a
  1204. # popupwindow; we target the textctl here
  1205. textWin = win.GetTextCtrl()
  1206. p['wxId'] = [ textWin.GetId(), ]
  1207. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1208. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1209. elif prompt == 'location':
  1210. win = gselect.LocationSelect(parent = which_panel,
  1211. value = value)
  1212. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1213. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1214. elif prompt == 'mapset':
  1215. if p.get('age', 'old') == 'old':
  1216. new = False
  1217. else:
  1218. new = True
  1219. win = gselect.MapsetSelect(parent = which_panel,
  1220. value = value, new = new,
  1221. multiple = p.get('multiple', False))
  1222. textWin = win.GetTextCtrl()
  1223. p['wxId'] = [ textWin.GetId(), win.GetId() ]
  1224. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1225. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1226. elif prompt == 'dbase':
  1227. win = gselect.DbaseSelect(parent = which_panel,
  1228. changeCallback = self.OnSetValue)
  1229. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1230. p['wxId'] = [ win.GetChildren()[1].GetId() ]
  1231. if 'wxId' not in p:
  1232. try:
  1233. p['wxId'] = [ win.GetId(), ]
  1234. except AttributeError:
  1235. pass
  1236. flags = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1237. if prompt == 'dbname':
  1238. flags |= wx.EXPAND
  1239. which_sizer.Add(item = win, proportion = 0,
  1240. flag = flags, border = 5)
  1241. # color entry
  1242. elif prompt == 'color':
  1243. default_color = (200,200,200)
  1244. label_color = _("Select Color")
  1245. if p.get('default','') != '':
  1246. default_color, label_color = utils.color_resolve(p['default'])
  1247. if p.get('value','') != '' and p.get('value','') != 'none': # parameter previously set
  1248. default_color, label_color = utils.color_resolve(p['value'])
  1249. if p.get('element', '') == 'color_none' or p.get('multiple', False):
  1250. this_sizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1251. else:
  1252. this_sizer = which_sizer
  1253. colorSize = 150
  1254. # For color selectors, this is a three-member array, holding the IDs of
  1255. # the color picker, the text control for multiple colors (or None),
  1256. # and either a "transparent" checkbox or None
  1257. p['wxId'] = [None] * 3
  1258. if p.get('multiple', False):
  1259. txt = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY)
  1260. this_sizer.Add(item = txt, proportion = 1,
  1261. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.TOP, border = 5)
  1262. txt.Bind(wx.EVT_TEXT, self.OnSetValue)
  1263. colorSize = 40
  1264. label_color = ''
  1265. p['wxId'][1] = txt.GetId()
  1266. which_sizer.Add(this_sizer, flag = wx.EXPAND | wx.RIGHT, border = 5)
  1267. btn_colour = csel.ColourSelect(parent = which_panel, id = wx.ID_ANY,
  1268. label = label_color, colour = default_color,
  1269. pos = wx.DefaultPosition, size = (colorSize, 32))
  1270. this_sizer.Add(item = btn_colour, proportion = 0,
  1271. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1272. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1273. p['wxId'][0] = btn_colour.GetId()
  1274. if p.get('element', '') == 'color_none':
  1275. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent"))
  1276. if p.get('value','') == "none":
  1277. none_check.SetValue(True)
  1278. else:
  1279. none_check.SetValue(False)
  1280. this_sizer.Add(item = none_check, proportion = 0,
  1281. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border = 5)
  1282. which_sizer.Add(this_sizer)
  1283. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1284. p['wxId'][2] = none_check.GetId()
  1285. # file selector
  1286. elif p.get('prompt','') != 'color' and p.get('prompt', '') == 'file':
  1287. if p.get('age', 'new') == 'new':
  1288. fmode = wx.FD_SAVE
  1289. else:
  1290. fmode = wx.FD_OPEN
  1291. # check wildcard
  1292. try:
  1293. fExt = os.path.splitext(p.get('key_desc', ['*.*'])[0])[1]
  1294. except:
  1295. fExt = None
  1296. if not fExt:
  1297. fMask = '*'
  1298. else:
  1299. fMask = '%s files (*%s)|*%s|Files (*)|*' % (fExt[1:].upper(), fExt, fExt)
  1300. fbb = filebrowse.FileBrowseButton(parent = which_panel, id = wx.ID_ANY, fileMask = fMask,
  1301. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1302. dialogTitle = _('Choose %s') % \
  1303. p.get('description', _('file')).lower(),
  1304. buttonText = _('Browse'),
  1305. startDirectory = os.getcwd(), fileMode = fmode,
  1306. changeCallback = self.OnSetValue)
  1307. value = self._getValue(p)
  1308. if value:
  1309. fbb.SetValue(value) # parameter previously set
  1310. which_sizer.Add(item = fbb, proportion = 0,
  1311. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1312. # A file browse button is a combobox with two children:
  1313. # a textctl and a button;
  1314. # we have to target the button here
  1315. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1316. if p.get('age', 'new') == 'old' and \
  1317. p.get('prompt', '') == 'file' and p.get('element', '') == 'file' and \
  1318. UserSettings.Get(group = 'cmd', key = 'interactiveInput', subkey = 'enabled'):
  1319. # widget for interactive input
  1320. ifbb = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY,
  1321. style = wx.TE_MULTILINE,
  1322. size = (-1, 75))
  1323. if p.get('value', '') and os.path.isfile(p['value']):
  1324. f = open(p['value'])
  1325. ifbb.SetValue(''.join(f.readlines()))
  1326. f.close()
  1327. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1328. btnLoad = wx.Button(parent = which_panel, id = wx.ID_ANY, label = _("&Load"))
  1329. btnLoad.SetToolTipString(_("Load and edit content of a file"))
  1330. btnLoad.Bind(wx.EVT_BUTTON, self.OnFileLoad)
  1331. btnSave = wx.Button(parent = which_panel, id = wx.ID_ANY, label = _("&Save as"))
  1332. btnSave.SetToolTipString(_("Save content to a file for further use"))
  1333. btnSave.Bind(wx.EVT_BUTTON, self.OnFileSave)
  1334. fileContentLabel = wx.StaticText(parent=which_panel,
  1335. id=wx.ID_ANY,
  1336. label=_('or enter values directly:'))
  1337. fileContentLabel.SetToolTipString(
  1338. _("Enter file content directly instead of specifying"
  1339. " a file."
  1340. " Temporary file will be automatically created."))
  1341. which_sizer.Add(item=fileContentLabel,
  1342. proportion = 0,
  1343. flag = wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM, border = 5)
  1344. which_sizer.Add(item = ifbb, proportion = 1,
  1345. flag = wx.EXPAND | wx.RIGHT | wx.LEFT, border = 5)
  1346. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1347. btnSizer.Add(item = btnLoad, proportion = 0,
  1348. flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 10)
  1349. btnSizer.Add(item = btnSave, proportion = 0,
  1350. flag = wx.ALIGN_RIGHT)
  1351. which_sizer.Add(item = btnSizer, proportion = 0,
  1352. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  1353. p['wxId'].append(ifbb.GetId())
  1354. p['wxId'].append(btnLoad.GetId())
  1355. p['wxId'].append(btnSave.GetId())
  1356. # directory selector
  1357. elif p.get('prompt','') != 'color' and p.get('prompt', '') == 'dir':
  1358. fbb = filebrowse.DirBrowseButton(parent = which_panel, id = wx.ID_ANY,
  1359. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1360. dialogTitle = _('Choose %s') % \
  1361. p.get('description', _('Directory')),
  1362. buttonText = _('Browse'),
  1363. startDirectory = os.getcwd(),
  1364. changeCallback = self.OnSetValue)
  1365. value = self._getValue(p)
  1366. if value:
  1367. fbb.SetValue(value) # parameter previously set
  1368. which_sizer.Add(item = fbb, proportion = 0,
  1369. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1370. # A file browse button is a combobox with two children:
  1371. # a textctl and a button;
  1372. # we have to target the button here
  1373. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1374. # interactive inserting of coordinates from map window
  1375. elif prompt == 'coords':
  1376. # interactive inserting if layer manager is accessible
  1377. if self._giface:
  1378. win = gselect.CoordinatesSelect(parent = which_panel,
  1379. giface = self._giface,
  1380. multiple = p.get('multiple', False),
  1381. param = p)
  1382. p['wxId'] = [win.GetTextWin().GetId()]
  1383. win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
  1384. # bind closing event because destructor is not working properly
  1385. if hasattr(self.parent, 'dialogClosing'):
  1386. self.parent.dialogClosing.connect(win.OnClose)
  1387. # normal text field
  1388. else:
  1389. win = wx.TextCtrl(parent = which_panel)
  1390. p['wxId'] = [win.GetId()]
  1391. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1392. which_sizer.Add(item = win,
  1393. proportion = 0,
  1394. flag = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  1395. border = 5)
  1396. elif prompt in ('cat', 'cats'):
  1397. # interactive selection of vector categories if layer manager is accessible
  1398. if self._giface:
  1399. win = gselect.VectorCategorySelect(parent = which_panel, giface = self._giface, task=self.task)
  1400. p['wxId'] = [win.GetTextWin().GetId()]
  1401. win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
  1402. # bind closing event because destructor is not working properly
  1403. if hasattr(self.parent, 'dialogClosing'):
  1404. self.parent.dialogClosing.connect(win.OnClose)
  1405. # normal text field
  1406. else:
  1407. win = wx.TextCtrl(parent = which_panel)
  1408. value = self._getValue(p)
  1409. win.SetValue(value)
  1410. p['wxId'] = [win.GetId()]
  1411. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1412. which_sizer.Add(item = win,
  1413. proportion = 0,
  1414. flag = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  1415. border = 5)
  1416. elif prompt in ('colortable', 'barscale', 'northarrow'):
  1417. if prompt == 'colortable':
  1418. cb = ColorTablesComboBox(parent=which_panel, value=p.get('default',''),
  1419. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1420. choices=valuelist)
  1421. elif prompt == 'barscale':
  1422. cb = BarscalesComboBox(parent=which_panel, value=p.get('default',''),
  1423. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1424. choices=valuelist)
  1425. elif prompt == 'northarrow':
  1426. cb = NArrowsComboBox(parent=which_panel, value=p.get('default',''),
  1427. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1428. choices=valuelist)
  1429. value = self._getValue(p)
  1430. if value:
  1431. cb.SetValue(value) # parameter previously set
  1432. which_sizer.Add(item = cb, proportion = 0,
  1433. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1434. p['wxId'] = [cb.GetId(), cb.GetTextCtrl().GetId()]
  1435. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1436. cb.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnSetValue)
  1437. if p.get('guidependency', ''):
  1438. cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1439. if self.parent.GetName() == 'MainFrame' and (self._giface and hasattr(self._giface, "_model")):
  1440. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1441. label = _("Parameterized in model"))
  1442. parChk.SetName('ModelParam')
  1443. parChk.SetValue(p.get('parameterized', False))
  1444. if 'wxId' in p:
  1445. p['wxId'].append(parChk.GetId())
  1446. else:
  1447. p['wxId'] = [ parChk.GetId() ]
  1448. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1449. which_sizer.Add(item = parChk, proportion = 0,
  1450. flag = wx.LEFT, border = 20)
  1451. if title_txt is not None:
  1452. # create tooltip if given
  1453. if len(p['values_desc']) > 0:
  1454. if tooltip:
  1455. tooltip += 2 * os.linesep
  1456. else:
  1457. tooltip = ''
  1458. if len(p['values']) == len(p['values_desc']):
  1459. for i in range(len(p['values'])):
  1460. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1461. tooltip.strip(os.linesep)
  1462. if tooltip:
  1463. title_txt.SetToolTipString(tooltip)
  1464. if p == first_param:
  1465. if 'wxId' in p and len(p['wxId']) > 0:
  1466. win = self.FindWindowById(p['wxId'][0])
  1467. win.SetFocus()
  1468. #
  1469. # set widget relations for OnUpdateSelection
  1470. #
  1471. pMap = None
  1472. pLayer = []
  1473. pDriver = None
  1474. pDatabase = None
  1475. pTable = None
  1476. pColumn = []
  1477. pGroup = None
  1478. pSubGroup = None
  1479. pSigFile = []
  1480. pDbase = None
  1481. pLocation = None
  1482. pMapset = None
  1483. for p in self.task.params:
  1484. guidep = p.get('guidependency', '')
  1485. if guidep:
  1486. # fixed options dependency defined
  1487. options = guidep.split(',')
  1488. for opt in options:
  1489. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1490. if pOpt and id:
  1491. if 'wxId-bind' not in p:
  1492. p['wxId-bind'] = list()
  1493. p['wxId-bind'] += pOpt['wxId']
  1494. continue
  1495. if p.get('gisprompt', False) == False:
  1496. continue
  1497. prompt = p.get('prompt', '')
  1498. if prompt in ('raster', 'vector'):
  1499. name = p.get('name', '')
  1500. if name in ('map', 'input'):
  1501. pMap = p
  1502. elif prompt == 'layer':
  1503. pLayer.append(p)
  1504. elif prompt == 'dbcolumn':
  1505. pColumn.append(p)
  1506. elif prompt == 'dbdriver':
  1507. pDriver = p
  1508. elif prompt == 'dbname':
  1509. pDatabase = p
  1510. elif prompt == 'dbtable':
  1511. pTable = p
  1512. elif prompt == 'group':
  1513. pGroup = p
  1514. elif prompt == 'subgroup':
  1515. pSubGroup = p
  1516. elif prompt == 'sigfile':
  1517. pSigFile.append(p)
  1518. elif prompt == 'dbase':
  1519. pDbase = p
  1520. elif prompt == 'location':
  1521. pLocation = p
  1522. elif prompt == 'mapset':
  1523. pMapset = p
  1524. # collect ids
  1525. pColumnIds = []
  1526. for p in pColumn:
  1527. pColumnIds += p['wxId']
  1528. pLayerIds = []
  1529. for p in pLayer:
  1530. pLayerIds += p['wxId']
  1531. pSigFileIds = []
  1532. for p in pSigFile:
  1533. pSigFileIds += p['wxId']
  1534. # set wxId-bindings
  1535. if pMap:
  1536. pMap['wxId-bind'] = []
  1537. if pLayer:
  1538. pMap['wxId-bind'] += pLayerIds
  1539. pMap['wxId-bind'] += copy.copy(pColumnIds)
  1540. if pLayer:
  1541. for p in pLayer:
  1542. p['wxId-bind'] = copy.copy(pColumnIds)
  1543. if pDriver and pTable:
  1544. pDriver['wxId-bind'] = pTable['wxId']
  1545. if pDatabase and pTable:
  1546. pDatabase['wxId-bind'] = pTable['wxId']
  1547. if pTable and pColumnIds:
  1548. pTable['wxId-bind'] = pColumnIds
  1549. if pGroup and pSubGroup:
  1550. if pSigFile:
  1551. pGroup['wxId-bind'] = pSigFileIds + pSubGroup['wxId']
  1552. pSubGroup['wxId-bind'] = pSigFileIds
  1553. else:
  1554. pGroup['wxId-bind'] = pSubGroup['wxId']
  1555. if pDbase and pLocation:
  1556. pDbase['wxId-bind'] = pLocation['wxId']
  1557. if pLocation and pMapset:
  1558. pLocation['wxId-bind'] = pMapset['wxId']
  1559. if pLocation and pMapset and pMap:
  1560. pLocation['wxId-bind'] += pMap['wxId']
  1561. pMapset['wxId-bind'] = pMap['wxId']
  1562. #
  1563. # determine panel size
  1564. #
  1565. maxsizes = (0, 0)
  1566. for section in sections:
  1567. tab[section].SetSizer(tabsizer[section])
  1568. tabsizer[section].Fit(tab[section])
  1569. tab[section].Layout()
  1570. minsecsizes = tabsizer[section].GetSize()
  1571. maxsizes = map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1))
  1572. # TODO: be less arbitrary with these 600
  1573. self.panelMinHeight = 100
  1574. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1575. for section in sections:
  1576. tab[section].SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1577. # add pages to notebook
  1578. imageList = wx.ImageList(16, 16)
  1579. self.notebook.AssignImageList(imageList)
  1580. for section in sections:
  1581. self.notebook.AddPage(page = tab[section], text = section, name = section)
  1582. index = self.AddBitmapToImageList(section, imageList)
  1583. if index >= 0:
  1584. self.notebook.SetPageImage(section, index)
  1585. # are we running from command line?
  1586. ### add 'command output' tab regardless standalone dialog
  1587. if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
  1588. from core.gconsole import GConsole, EVT_CMD_RUN, EVT_CMD_DONE
  1589. from gui_core.goutput import GConsoleWindow
  1590. self._gconsole = GConsole(guiparent = self.notebook, giface = self._giface)
  1591. self.goutput = GConsoleWindow(parent = self.notebook, gconsole = self._gconsole, margin = False)
  1592. self._gconsole.Bind(EVT_CMD_RUN,
  1593. lambda event:
  1594. self._switchPageHandler(event=event, notification=Notification.MAKE_VISIBLE))
  1595. self._gconsole.Bind(EVT_CMD_DONE,
  1596. lambda event:
  1597. self._switchPageHandler(event = event, notification=Notification.RAISE_WINDOW))
  1598. self.outpage = self.notebook.AddPage(page = self.goutput, text = _("Command output"), name = 'output')
  1599. else:
  1600. self.goutput = None
  1601. self._gconsole = None
  1602. self.manualTab = HelpPanel(parent = self.notebook, command = self.task.get_name())
  1603. if not self.manualTab.GetFile():
  1604. self.manualTab.Hide()
  1605. else:
  1606. self.notebook.AddPage(page = self.manualTab, text = _("Manual"), name = 'manual')
  1607. index = self.AddBitmapToImageList(section = 'manual', imageList = imageList)
  1608. if index >= 0:
  1609. self.notebook.SetPageImage('manual', index)
  1610. if self.manualTab.IsLoaded():
  1611. self.manualTab.SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1612. self.notebook.SetSelection(0)
  1613. panelsizer.Add(item = self.notebook, proportion = 1, flag = wx.EXPAND)
  1614. self.SetSizer(panelsizer)
  1615. panelsizer.Fit(self.notebook)
  1616. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1617. def _getValue(self, p):
  1618. """Get value or default value of given parameter
  1619. :param p: parameter directory
  1620. """
  1621. if p.get('value', '') != '':
  1622. return p['value']
  1623. return p.get('default', '')
  1624. def OnFileLoad(self, event):
  1625. """Load file to interactive input"""
  1626. me = event.GetId()
  1627. win = dict()
  1628. for p in self.task.params:
  1629. if 'wxId' in p and me in p['wxId']:
  1630. win['file'] = self.FindWindowById(p['wxId'][0])
  1631. win['text'] = self.FindWindowById(p['wxId'][1])
  1632. break
  1633. if not win:
  1634. return
  1635. path = win['file'].GetValue()
  1636. if not path:
  1637. gcmd.GMessage(parent = self,
  1638. message = _("Nothing to load."))
  1639. return
  1640. data = ''
  1641. try:
  1642. f = open(path, "r")
  1643. except IOError as e:
  1644. gcmd.GError(parent = self, showTraceback = False,
  1645. message = _("Unable to load file.\n\nReason: %s") % e)
  1646. return
  1647. try:
  1648. data = f.read()
  1649. finally:
  1650. f.close()
  1651. win['text'].SetValue(data)
  1652. def OnFileSave(self, event):
  1653. """Save interactive input to the file"""
  1654. wId = event.GetId()
  1655. win = {}
  1656. for p in self.task.params:
  1657. if wId in p.get('wxId', []):
  1658. win['file'] = self.FindWindowById(p['wxId'][0])
  1659. win['text'] = self.FindWindowById(p['wxId'][1])
  1660. break
  1661. if not win:
  1662. return
  1663. text = win['text'].GetValue()
  1664. if not text:
  1665. gcmd.GMessage(parent = self,
  1666. message = _("Nothing to save."))
  1667. return
  1668. dlg = wx.FileDialog(parent = self,
  1669. message = _("Save input as..."),
  1670. defaultDir = os.getcwd(),
  1671. style = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
  1672. if dlg.ShowModal() == wx.ID_OK:
  1673. path = dlg.GetPath()
  1674. enc = locale.getdefaultlocale()[1]
  1675. f = codecs.open(path, encoding = enc, mode = 'w', errors='replace')
  1676. try:
  1677. f.write(text + os.linesep)
  1678. finally:
  1679. f.close()
  1680. win['file'].SetValue(path)
  1681. dlg.Destroy()
  1682. def OnFileText(self, event):
  1683. """File input interactively entered"""
  1684. text = event.GetString()
  1685. p = self.task.get_param(value = event.GetId(), element = 'wxId', raiseError = False)
  1686. if not p:
  1687. return # should not happen
  1688. win = self.FindWindowById(p['wxId'][0])
  1689. if text:
  1690. filename = win.GetValue()
  1691. if not filename or filename == p['default']: # m.proj has - as default
  1692. filename = grass.tempfile()
  1693. win.SetValue(filename)
  1694. enc = locale.getdefaultlocale()[1]
  1695. f = codecs.open(filename, encoding = enc, mode = 'w', errors='replace')
  1696. try:
  1697. f.write(text)
  1698. if text[-1] != os.linesep:
  1699. f.write(os.linesep)
  1700. finally:
  1701. f.close()
  1702. else:
  1703. win.SetValue('')
  1704. def OnVectorFormat(self, event):
  1705. """Change vector format (native / ogr).
  1706. Currently unused.
  1707. """
  1708. sel = event.GetSelection()
  1709. idEvent = event.GetId()
  1710. p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
  1711. if not p:
  1712. return # should not happen
  1713. # detect windows
  1714. winNative = None
  1715. winOgr = None
  1716. for id in p['wxId']:
  1717. if id == idEvent:
  1718. continue
  1719. name = self.FindWindowById(id).GetName()
  1720. if name == 'Select':
  1721. winNative = self.FindWindowById(id + 1) # fix the mystery (also in nviz_tools.py)
  1722. elif name == 'OgrSelect':
  1723. winOgr = self.FindWindowById(id)
  1724. # enable / disable widgets & update values
  1725. rbox = self.FindWindowByName('VectorFormat')
  1726. self.hsizer.Remove(rbox)
  1727. if sel == 0: # -> native
  1728. winOgr.Hide()
  1729. self.hsizer.Remove(winOgr)
  1730. self.hsizer.Add(item = winNative,
  1731. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1732. border = 5)
  1733. winNative.Show()
  1734. p['value'] = winNative.GetValue()
  1735. elif sel == 1: # -> OGR
  1736. sizer = wx.BoxSizer(wx.VERTICAL)
  1737. winNative.Hide()
  1738. self.hsizer.Remove(winNative)
  1739. sizer.Add(item = winOgr)
  1740. winOgr.Show()
  1741. p['value'] = winOgr.GetDsn()
  1742. self.hsizer.Add(item = sizer,
  1743. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1744. border = 5)
  1745. self.hsizer.Add(item = rbox,
  1746. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1747. wx.RIGHT | wx.ALIGN_TOP,
  1748. border = 5)
  1749. self.hsizer.Layout()
  1750. self.Layout()
  1751. self.OnUpdateValues()
  1752. self.OnUpdateSelection(event)
  1753. def OnUpdateDialog(self, event):
  1754. for fn, kwargs in event.data.iteritems():
  1755. fn(**kwargs)
  1756. self.parent.updateValuesHook()
  1757. def OnVerbosity(self, event):
  1758. """Verbosity level changed"""
  1759. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  1760. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  1761. if event.IsChecked():
  1762. if event.GetId() == verbose.GetId():
  1763. if quiet.IsChecked():
  1764. quiet.SetValue(False)
  1765. self.task.get_flag('quiet')['value'] = False
  1766. else:
  1767. if verbose.IsChecked():
  1768. verbose.SetValue(False)
  1769. self.task.get_flag('verbose')['value'] = False
  1770. event.Skip()
  1771. def OnPageChange(self, event):
  1772. if not event:
  1773. sel = self.notebook.GetSelection()
  1774. else:
  1775. sel = event.GetSelection()
  1776. idx = self.notebook.GetPageIndexByName('manual')
  1777. if idx > -1 and sel == idx:
  1778. # calling LoadPage() is strangely time-consuming (only first call)
  1779. # FIXME: move to helpPage.__init__()
  1780. if not self.manualTab.IsLoaded():
  1781. wx.Yield()
  1782. self.manualTab.LoadPage()
  1783. self.Layout()
  1784. if event:
  1785. # skip is needed for wx.Notebook on Windows
  1786. event.Skip()
  1787. # this is needed for dialogs launched from layer manager
  1788. # event is somehow propagated?
  1789. event.StopPropagation()
  1790. def _switchPageHandler(self, event, notification):
  1791. self._switchPage(notification=notification)
  1792. event.Skip()
  1793. def _switchPage(self, notification):
  1794. """Manages @c 'output' notebook page according to event notification."""
  1795. if notification == Notification.HIGHLIGHT:
  1796. self.notebook.HighlightPageByName('output')
  1797. if notification == Notification.MAKE_VISIBLE:
  1798. self.notebook.SetSelectionByName('output')
  1799. if notification == Notification.RAISE_WINDOW:
  1800. self.notebook.SetSelectionByName('output')
  1801. self.SetFocus()
  1802. self.Raise()
  1803. def OnColorChange(self, event):
  1804. myId = event.GetId()
  1805. for p in self.task.params:
  1806. if 'wxId' in p and myId in p['wxId']:
  1807. multiple = p['wxId'][1] is not None # multiple colors
  1808. hasTansp = p['wxId'][2] is not None
  1809. if multiple:
  1810. # selected color is added at the end of textCtrl
  1811. colorchooser = wx.FindWindowById(p['wxId'][0])
  1812. new_color = colorchooser.GetValue()[:]
  1813. new_label = utils.rgb2str.get(new_color, ':'.join(map(str, new_color)))
  1814. textCtrl = wx.FindWindowById(p['wxId'][1])
  1815. val = textCtrl.GetValue()
  1816. sep = ','
  1817. if val and val[-1] != sep:
  1818. val += sep
  1819. val += new_label
  1820. textCtrl.SetValue(val)
  1821. p[ 'value' ] = val
  1822. elif hasTansp and wx.FindWindowById(p['wxId'][2]).GetValue():
  1823. p[ 'value' ] = 'none'
  1824. else:
  1825. colorchooser = wx.FindWindowById(p['wxId'][0])
  1826. new_color = colorchooser.GetValue()[:]
  1827. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1828. # under wx2.8.1
  1829. new_label = utils.rgb2str.get(new_color, ':'.join(map(str,new_color)))
  1830. colorchooser.SetLabel(new_label)
  1831. colorchooser.SetColour(new_color)
  1832. colorchooser.Refresh()
  1833. p[ 'value' ] = colorchooser.GetLabel()
  1834. self.OnUpdateValues()
  1835. def OnUpdateValues(self, event = None):
  1836. """If we were part of a richer interface, report back the
  1837. current command being built.
  1838. This method should be set by the parent of this panel if
  1839. needed. It's a hook, actually. Beware of what is 'self' in
  1840. the method def, though. It will be called with no arguments.
  1841. """
  1842. pass
  1843. def OnCheckBoxMulti(self, event):
  1844. """Fill the values as a ','-separated string according to
  1845. current status of the checkboxes.
  1846. """
  1847. me = event.GetId()
  1848. theParam = None
  1849. for p in self.task.params:
  1850. if 'wxId' in p and me in p['wxId']:
  1851. theParam = p
  1852. myIndex = p['wxId'].index(me)
  1853. # Unpack current value list
  1854. currentValues = {}
  1855. for isThere in theParam.get('value', '').split(','):
  1856. currentValues[isThere] = 1
  1857. theValue = theParam['values'][myIndex]
  1858. if event.Checked():
  1859. currentValues[ theValue ] = 1
  1860. else:
  1861. del currentValues[ theValue ]
  1862. # Keep the original order, so that some defaults may be recovered
  1863. currentValueList = []
  1864. for v in theParam['values']:
  1865. if v in currentValues:
  1866. currentValueList.append(v)
  1867. # Pack it back
  1868. theParam['value'] = ','.join(currentValueList)
  1869. self.OnUpdateValues()
  1870. event.Skip()
  1871. def OnSetValue(self, event):
  1872. """Retrieve the widget value and set the task value field
  1873. accordingly.
  1874. Use for widgets that have a proper GetValue() method, i.e. not
  1875. for selectors.
  1876. """
  1877. myId = event.GetId()
  1878. me = wx.FindWindowById(myId)
  1879. name = me.GetName()
  1880. found = False
  1881. for porf in self.task.params + self.task.flags:
  1882. if 'wxId' not in porf:
  1883. continue
  1884. if myId in porf['wxId']:
  1885. found = True
  1886. break
  1887. if not found:
  1888. return
  1889. if name == 'GdalSelect':
  1890. porf['value'] = event.dsn
  1891. elif name == 'ModelParam':
  1892. porf['parameterized'] = me.IsChecked()
  1893. else:
  1894. if isinstance(me, wx.SpinCtrl):
  1895. porf['value'] = str(me.GetValue())
  1896. else:
  1897. porf['value'] = me.GetValue()
  1898. self.OnUpdateValues(event)
  1899. event.Skip()
  1900. def OnSetSymbol(self, event):
  1901. """Shows dialog for symbol selection"""
  1902. myId = event.GetId()
  1903. for p in self.task.params:
  1904. if 'wxId' in p and myId in p['wxId']:
  1905. from gui_core.dialogs import SymbolDialog
  1906. dlg = SymbolDialog(self, symbolPath = globalvar.SYMBDIR,
  1907. currentSymbol = p['value'])
  1908. if dlg.ShowModal() == wx.ID_OK:
  1909. img = dlg.GetSelectedSymbolPath()
  1910. p['value'] = dlg.GetSelectedSymbolName()
  1911. bitmapButton = wx.FindWindowById(p['wxId'][0])
  1912. label = wx.FindWindowById(p['wxId'][1])
  1913. bitmapButton.SetBitmapLabel(wx.Bitmap(img + '.png'))
  1914. label.SetLabel(p['value'])
  1915. self.OnUpdateValues(event)
  1916. dlg.Destroy()
  1917. def OnTimelineTool(self, event):
  1918. """Show Timeline Tool with dataset(s) from gselect.
  1919. .. todo::
  1920. update from gselect automatically
  1921. """
  1922. myId = event.GetId()
  1923. for p in self.task.params:
  1924. if 'wxId' in p and myId in p['wxId']:
  1925. select = self.FindWindowById(p['wxId'][0])
  1926. if not select.GetValue():
  1927. gcmd.GMessage(parent=self, message=_("No dataset given."))
  1928. return
  1929. datasets = select.GetValue().split(',')
  1930. from timeline import frame
  1931. frame.run(parent=self, datasets=datasets)
  1932. def OnUpdateSelection(self, event):
  1933. """Update dialog (layers, tables, columns, etc.)
  1934. """
  1935. if not hasattr(self.parent, "updateThread"):
  1936. if event:
  1937. event.Skip()
  1938. return
  1939. if event:
  1940. self.parent.updateThread.Update(UpdateDialog,
  1941. self,
  1942. event,
  1943. event.GetId(),
  1944. self.task)
  1945. else:
  1946. self.parent.updateThread.Update(UpdateDialog,
  1947. self,
  1948. None,
  1949. None,
  1950. self.task)
  1951. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  1952. """Produce a command line string (list) or feeding into GRASS.
  1953. :param ignoreErrors: True then it will return whatever has been
  1954. built so far, even though it would not be
  1955. a correct command for GRASS
  1956. """
  1957. try:
  1958. cmd = self.task.get_cmd(ignoreErrors = ignoreErrors,
  1959. ignoreRequired = ignoreRequired)
  1960. except ValueError as err:
  1961. dlg = wx.MessageDialog(parent = self,
  1962. message = unicode(err),
  1963. caption = _("Error in %s") % self.task.name,
  1964. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1965. dlg.ShowModal()
  1966. dlg.Destroy()
  1967. cmd = None
  1968. return cmd
  1969. def OnSize(self, event):
  1970. width = event.GetSize()[0]
  1971. fontsize = self.GetFont().GetPointSize()
  1972. text_width = max(width / (fontsize - 3), 70)
  1973. for id in self.label_id:
  1974. win = self.FindWindowById(id)
  1975. label = win.GetLabel()
  1976. label_new = '\n'.join(textwrap.wrap(label, text_width))
  1977. win.SetLabel(label_new)
  1978. event.Skip()
  1979. def AddBitmapToImageList(self, section, imageList):
  1980. iconTheme = UserSettings.Get(group = 'appearance', key = 'iconTheme', subkey = 'type')
  1981. iconSectionDict = {'manual': os.path.join(globalvar.ICONDIR, iconTheme, 'help.png')}
  1982. if section in iconSectionDict.keys():
  1983. image = wx.Image(iconSectionDict[section]).Scale(16, 16, wx.IMAGE_QUALITY_HIGH)
  1984. idx = imageList.Add(wx.BitmapFromImage(image))
  1985. return idx
  1986. return -1
  1987. class GUI:
  1988. def __init__(self, parent = None, giface = None, show = True, modal = False,
  1989. centreOnParent = False, checkError = False):
  1990. """Parses GRASS commands when module is imported and used from
  1991. Layer Manager.
  1992. """
  1993. self.parent = parent
  1994. self.show = show
  1995. self.modal = modal
  1996. self._giface = giface
  1997. self.centreOnParent = centreOnParent
  1998. self.checkError = checkError
  1999. self.grass_task = None
  2000. self.cmd = list()
  2001. global _blackList
  2002. if self.parent:
  2003. _blackList['enabled'] = True
  2004. else:
  2005. _blackList['enabled'] = False
  2006. def GetCmd(self):
  2007. """Get validated command"""
  2008. return self.cmd
  2009. def ParseCommand(self, cmd, completed = None):
  2010. """Parse command
  2011. Note: cmd is given as list
  2012. If command is given with options, return validated cmd list:
  2013. - add key name for first parameter if not given
  2014. - change mapname to mapname@mapset
  2015. """
  2016. dcmd_params = {}
  2017. if completed == None:
  2018. get_dcmd = None
  2019. layer = None
  2020. dcmd_params = None
  2021. else:
  2022. get_dcmd = completed[0]
  2023. layer = completed[1]
  2024. if completed[2]:
  2025. dcmd_params.update(completed[2])
  2026. # parse the interface decription
  2027. try:
  2028. global _blackList
  2029. self.grass_task = gtask.parse_interface(cmd[0],
  2030. blackList = _blackList)
  2031. except (grass.ScriptError, ValueError) as e:
  2032. raise gcmd.GException(e.value)
  2033. # if layer parameters previously set, re-insert them into dialog
  2034. if completed is not None:
  2035. if 'params' in dcmd_params:
  2036. self.grass_task.params = dcmd_params['params']
  2037. if 'flags' in dcmd_params:
  2038. self.grass_task.flags = dcmd_params['flags']
  2039. err = list()
  2040. # update parameters if needed && validate command
  2041. if len(cmd) > 1:
  2042. i = 0
  2043. cmd_validated = [cmd[0]]
  2044. for option in cmd[1:]:
  2045. if option[0] == '-': # flag
  2046. if option[1] == '-':
  2047. self.grass_task.set_flag(option[2:], True)
  2048. else:
  2049. self.grass_task.set_flag(option[1], True)
  2050. cmd_validated.append(option)
  2051. else: # parameter
  2052. try:
  2053. key, value = option.split('=', 1)
  2054. except ValueError:
  2055. if self.grass_task.firstParam:
  2056. if i == 0: # add key name of first parameter if not given
  2057. key = self.grass_task.firstParam
  2058. value = option
  2059. else:
  2060. raise gcmd.GException, _("Unable to parse command '%s'") % ' '.join(cmd)
  2061. else:
  2062. continue
  2063. task = self.grass_task.get_param(key, raiseError = False)
  2064. if not task:
  2065. err.append(_("%(cmd)s: parameter '%(key)s' not available") % \
  2066. { 'cmd' : cmd[0],
  2067. 'key' : key })
  2068. continue
  2069. multiple = task['multiple']
  2070. element = task['element']
  2071. # to filter out g.copy, g.rename
  2072. key_desc = task['key_desc']
  2073. # do we need to find mapset for each of multiple maps?
  2074. if element in ['cell', 'vector'] and not multiple and len(key_desc) != 2:
  2075. # mapname -> mapname@mapset
  2076. try:
  2077. name, mapset = value.split('@')
  2078. except ValueError:
  2079. mapset = grass.find_file(value, element)['mapset']
  2080. curr_mapset = grass.gisenv()['MAPSET']
  2081. if mapset and mapset != curr_mapset:
  2082. value = value + '@' + mapset
  2083. self.grass_task.set_param(key, value)
  2084. cmd_validated.append(key + '=' + value)
  2085. i += 1
  2086. # update original command list
  2087. cmd = cmd_validated
  2088. if self.show is not None:
  2089. self.mf = TaskFrame(parent = self.parent, giface = self._giface,
  2090. task_description = self.grass_task,
  2091. get_dcmd = get_dcmd, layer = layer)
  2092. else:
  2093. self.mf = None
  2094. if get_dcmd is not None:
  2095. # update only propwin reference
  2096. get_dcmd(dcmd = None, layer = layer, params = None,
  2097. propwin = self.mf)
  2098. if self.show is not None:
  2099. self.mf.notebookpanel.OnUpdateSelection(None)
  2100. if self.show is True:
  2101. if self.parent and self.centreOnParent:
  2102. self.mf.CentreOnParent()
  2103. else:
  2104. self.mf.CenterOnScreen()
  2105. self.mf.Show(self.show)
  2106. self.mf.MakeModal(self.modal)
  2107. else:
  2108. self.mf.OnApply(None)
  2109. self.cmd = cmd
  2110. if self.checkError:
  2111. return self.grass_task, err
  2112. else:
  2113. return self.grass_task
  2114. def GetCommandInputMapParamKey(self, cmd):
  2115. """Get parameter key for input raster/vector map
  2116. :param cmd: module name
  2117. :return: parameter key
  2118. :return: None on failure
  2119. """
  2120. # parse the interface decription
  2121. if not self.grass_task:
  2122. tree = etree.fromstring(gtask.get_interface_description(cmd))
  2123. self.grass_task = gtask.processTask(tree).get_task()
  2124. for p in self.grass_task.params:
  2125. if p.get('name', '') in ('input', 'map'):
  2126. age = p.get('age', '')
  2127. prompt = p.get('prompt', '')
  2128. element = p.get('element', '')
  2129. if age == 'old' and \
  2130. element in ('cell', 'grid3', 'vector') and \
  2131. prompt in ('raster', '3d-raster', 'vector'):
  2132. return p.get('name', None)
  2133. return None
  2134. class GrassGUIApp(wx.App):
  2135. """Stand-alone GRASS command GUI
  2136. """
  2137. def __init__(self, grass_task):
  2138. self.grass_task = grass_task
  2139. wx.App.__init__(self, False)
  2140. def OnInit(self):
  2141. msg = self.grass_task.get_error_msg()
  2142. if msg:
  2143. gcmd.GError(msg + '\n\n' +
  2144. _('Try to set up GRASS_ADDON_PATH or GRASS_ADDON_BASE variable.'))
  2145. return True
  2146. self.mf = TaskFrame(parent = None, giface = None, task_description = self.grass_task)
  2147. self.mf.CentreOnScreen()
  2148. self.mf.Show(True)
  2149. self.SetTopWindow(self.mf)
  2150. return True
  2151. USAGE_MESSAGE = """Usage:
  2152. {name} <grass module>
  2153. {name} <full path to file>
  2154. python {name} <grass module>
  2155. Test:
  2156. python {name} test
  2157. python {name} g.region
  2158. python {name} "g.region -p"
  2159. python {name} temporal/t.list/t.list.py"""
  2160. if __name__ == "__main__":
  2161. if len(sys.argv) == 1:
  2162. sys.exit(_(USAGE_MESSAGE).format(name=sys.argv[0]))
  2163. if sys.argv[1] != 'test':
  2164. q = wx.LogNull()
  2165. from core.debug import Debug
  2166. Debug.msg(1, "forms.py called using command: %s" % sys.argv[1])
  2167. cmd = utils.split(sys.argv[1])
  2168. task = gtask.grassTask(cmd[0])
  2169. task.set_options(cmd[1:])
  2170. Debug.msg(1, "forms.py opening form for: %s" % task.get_cmd(ignoreErrors=True))
  2171. app = GrassGUIApp(task)
  2172. app.MainLoop()
  2173. else: #Test
  2174. # Test grassTask from within a GRASS session
  2175. if os.getenv("GISBASE") is not None:
  2176. task = gtask.grassTask("d.vect")
  2177. task.get_param('map')['value'] = "map_name"
  2178. task.get_flag('i')['value'] = True
  2179. task.get_param('layer')['value'] = 1
  2180. task.get_param('label_bcolor')['value'] = "red"
  2181. # the default parameter display is added automatically
  2182. assert ' '.join(task.get_cmd()) == "d.vect -i map=map_name layer=1 display=shape label_bcolor=red"
  2183. print "Creation of task successful"
  2184. # Test interface building with handmade grassTask,
  2185. # possibly outside of a GRASS session.
  2186. print "Now creating a module dialog (task frame)"
  2187. task = gtask.grassTask()
  2188. task.name = "TestTask"
  2189. task.description = "This is an artificial grassTask() object intended for testing purposes."
  2190. task.keywords = ["grass","test","task"]
  2191. task.params = [
  2192. {
  2193. "name" : "text",
  2194. "description" : "Descriptions go into tooltips if labels are present, like this one",
  2195. "label" : "Enter some text",
  2196. "key_desc": ["value"],
  2197. "values_desc": []
  2198. },{
  2199. "name" : "hidden_text",
  2200. "description" : "This text should not appear in the form",
  2201. "hidden" : True,
  2202. "key_desc": ["value"],
  2203. "values_desc": []
  2204. },{
  2205. "name" : "text_default",
  2206. "description" : "Enter text to override the default",
  2207. "default" : "default text",
  2208. "key_desc": ["value"],
  2209. "values_desc": []
  2210. },{
  2211. "name" : "text_prefilled",
  2212. "description" : "You should see a friendly welcome message here",
  2213. "value" : "hello, world",
  2214. "key_desc": ["value"],
  2215. "values_desc": []
  2216. },{
  2217. "name" : "plain_color",
  2218. "description" : "This is a plain color, and it is a compulsory parameter",
  2219. "required" : False,
  2220. "gisprompt" : True,
  2221. "prompt" : "color",
  2222. "key_desc": ["value"],
  2223. "values_desc": []
  2224. },{
  2225. "name" : "transparent_color",
  2226. "description" : "This color becomes transparent when set to none",
  2227. "guisection" : "tab",
  2228. "gisprompt" : True,
  2229. "prompt" : "color",
  2230. "key_desc": ["value"],
  2231. "values_desc": []
  2232. },{
  2233. "name" : "multi",
  2234. "description" : "A multiple selection",
  2235. 'default': u'red,green,blue',
  2236. 'gisprompt': False,
  2237. 'guisection': 'tab',
  2238. 'multiple': u'yes',
  2239. 'type': u'string',
  2240. 'value': '',
  2241. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  2242. "key_desc": ["value"],
  2243. "values_desc": []
  2244. },{
  2245. "name" : "single",
  2246. "description" : "A single multiple-choice selection",
  2247. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  2248. "guisection" : "tab",
  2249. "key_desc": ["value"],
  2250. "values_desc": []
  2251. },{
  2252. "name" : "large_multi",
  2253. "description" : "A large multiple selection",
  2254. "gisprompt" : False,
  2255. "multiple" : "yes",
  2256. # values must be an array of strings
  2257. "values" : utils.str2rgb.keys() + map(str, utils.str2rgb.values()),
  2258. "key_desc": ["value"],
  2259. "values_desc": []
  2260. },{
  2261. "name" : "a_file",
  2262. "description" : "A file selector",
  2263. "gisprompt" : True,
  2264. "element" : "file",
  2265. "key_desc": ["value"],
  2266. "values_desc": []
  2267. }
  2268. ]
  2269. task.flags = [
  2270. {
  2271. "name" : "a",
  2272. "description" : "Some flag, will appear in Main since it is required",
  2273. "required" : True,
  2274. "value" : False,
  2275. "suppress_required": False
  2276. },{
  2277. "name" : "b",
  2278. "description" : "pre-filled flag, will appear in options since it is not required",
  2279. "value" : True,
  2280. "suppress_required": False
  2281. },{
  2282. "name" : "hidden_flag",
  2283. "description" : "hidden flag, should not be changeable",
  2284. "hidden" : "yes",
  2285. "value" : True,
  2286. "suppress_required": False
  2287. }
  2288. ]
  2289. q = wx.LogNull()
  2290. GrassGUIApp(task).MainLoop()