forms.py 100 KB

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