menuform.py 100 KB

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