menuform.py 100 KB

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