menuform.py 102 KB

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