forms.py 98 KB

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