menuform.py 101 KB

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