menuform.py 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487
  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. value = self._getValue(p)
  1235. if value:
  1236. selection.SetValue(value)
  1237. formatSelector = True
  1238. # A select.Select is a combobox with two children: a textctl and a popupwindow;
  1239. # we target the textctl here
  1240. textWin = selection.GetTextCtrl()
  1241. p['wxId'] = [ textWin.GetId(), ]
  1242. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1243. if p.get('prompt', '') == 'vector':
  1244. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1245. if formatSelector and p.get('age', 'old') == 'old':
  1246. # OGR supported (read-only)
  1247. self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  1248. self.hsizer.Add(item = selection,
  1249. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1250. border = 5)
  1251. # format (native / ogr)
  1252. rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  1253. label = " %s " % _("Format"),
  1254. style = wx.RA_SPECIFY_ROWS,
  1255. choices = [_("Native / Linked OGR"), _("Direct OGR")])
  1256. if p.get('value', '').lower().rfind('@ogr') > -1:
  1257. rbox.SetSelection(1)
  1258. rbox.SetName('VectorFormat')
  1259. rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  1260. self.hsizer.Add(item = rbox,
  1261. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1262. wx.RIGHT | wx.ALIGN_TOP,
  1263. border = 5)
  1264. ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  1265. default = 'dir',
  1266. exclude = ['file'])
  1267. self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  1268. self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  1269. ogrSelection.SetName('OgrSelect')
  1270. ogrSelection.Hide()
  1271. which_sizer.Add(item = self.hsizer, proportion = 0)
  1272. p['wxId'].append(rbox.GetId())
  1273. p['wxId'].append(ogrSelection.GetId())
  1274. for win in ogrSelection.GetDsnWin():
  1275. p['wxId'].append(win.GetId())
  1276. else:
  1277. which_sizer.Add(item = selection, proportion = 0,
  1278. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1279. border = 5)
  1280. elif p.get('prompt', '') == 'group':
  1281. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  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. else:
  1286. which_sizer.Add(item = selection, proportion = 0,
  1287. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1288. border = 5)
  1289. # subgroup
  1290. elif p.get('prompt', '') == 'subgroup':
  1291. selection = gselect.SubGroupSelect(parent = which_panel)
  1292. p['wxId'] = [ selection.GetId() ]
  1293. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1294. which_sizer.Add(item = selection, proportion = 0,
  1295. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1296. border = 5)
  1297. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1298. elif p.get('prompt', '') in ('dbdriver',
  1299. 'dbname',
  1300. 'dbtable',
  1301. 'dbcolumn',
  1302. 'layer',
  1303. 'layer_all',
  1304. 'location',
  1305. 'mapset',
  1306. 'dbase'):
  1307. if p.get('multiple', 'no') == 'yes':
  1308. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1309. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1310. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1311. else:
  1312. value = p.get('value', '')
  1313. if not value:
  1314. value = p.get('default', '')
  1315. if p.get('prompt', '') in ('layer',
  1316. 'layer_all'):
  1317. if p.get('prompt', '') == 'layer_all':
  1318. all = True
  1319. else:
  1320. all = False
  1321. win = wx.BoxSizer(wx.HORIZONTAL)
  1322. if p.get('age', 'old') == 'old':
  1323. win1 = gselect.LayerSelect(parent = which_panel,
  1324. all = all,
  1325. default = p['default'])
  1326. win1.Bind(wx.EVT_CHOICE, self.OnUpdateSelection)
  1327. win1.Bind(wx.EVT_CHOICE, self.OnSetValue)
  1328. else:
  1329. win1 = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY,
  1330. min = 1, max = 100, initial = int(p['default']))
  1331. win1.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1332. win2 = gselect.LayerNameSelect(parent = which_panel)
  1333. if p.get('value','') != '':
  1334. win2.SetItems([p['value']])
  1335. win2.SetSelection(0)
  1336. win2.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1337. p['wxId'] = [ win1.GetId(), win2.GetId() ]
  1338. win.Add(item = win1, proportion = 0)
  1339. win.Add(item = win2, proportion = 0,
  1340. flag = wx.LEFT | wx.ALIGN_CENTER_VERTICAL,
  1341. border = 5)
  1342. elif p.get('prompt', '') == 'dbdriver':
  1343. win = gselect.DriverSelect(parent = which_panel,
  1344. choices = p.get('values', []),
  1345. value = value)
  1346. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1347. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1348. elif p.get('prompt', '') == 'dbname':
  1349. win = gselect.DatabaseSelect(parent = which_panel,
  1350. value = value)
  1351. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1352. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1353. elif p.get('prompt', '') == 'dbtable':
  1354. if p.get('age', 'old') == 'old':
  1355. win = gselect.TableSelect(parent = which_panel)
  1356. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1357. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1358. else:
  1359. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1360. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1361. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1362. elif p.get('prompt', '') == 'dbcolumn':
  1363. win = gselect.ColumnSelect(parent = which_panel,
  1364. value = value,
  1365. param = p)
  1366. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1367. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1368. elif p.get('prompt', '') == 'location':
  1369. win = gselect.LocationSelect(parent = which_panel,
  1370. value = value)
  1371. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1372. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1373. elif p.get('prompt', '') == 'mapset':
  1374. win = gselect.MapsetSelect(parent = which_panel,
  1375. value = value)
  1376. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1377. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1378. elif p.get('prompt', '') == 'dbase':
  1379. win = gselect.DbaseSelect(parent = which_panel,
  1380. changeCallback = self.OnSetValue)
  1381. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1382. p['wxId'] = [ win.GetChildren()[1].GetId() ]
  1383. if not p.has_key('wxId'):
  1384. try:
  1385. p['wxId'] = [ win.GetId(), ]
  1386. except AttributeError:
  1387. pass
  1388. which_sizer.Add(item = win, proportion = 0,
  1389. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1390. # color entry
  1391. elif p.get('prompt', '') in ('color',
  1392. 'color_none'):
  1393. default_color = (200,200,200)
  1394. label_color = _("Select Color")
  1395. if p.get('default','') != '':
  1396. default_color, label_color = color_resolve(p['default'])
  1397. if p.get('value','') != '': # parameter previously set
  1398. default_color, label_color = color_resolve(p['value'])
  1399. if p.get('prompt', '') == 'color_none':
  1400. this_sizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1401. else:
  1402. this_sizer = which_sizer
  1403. btn_colour = csel.ColourSelect(parent = which_panel, id = wx.ID_ANY,
  1404. label = label_color, colour = default_color,
  1405. pos = wx.DefaultPosition, size = (150,-1))
  1406. this_sizer.Add(item = btn_colour, proportion = 0,
  1407. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1408. # For color selectors, this is a two-member array, holding the IDs of
  1409. # the selector proper and either a "transparent" button or None
  1410. p['wxId'] = [btn_colour.GetId(),]
  1411. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1412. if p.get('prompt', '') == 'color_none':
  1413. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent"))
  1414. if p.get('value','') != '' and p.get('value',[''])[0] == "none":
  1415. none_check.SetValue(True)
  1416. else:
  1417. none_check.SetValue(False)
  1418. this_sizer.Add(item = none_check, proportion = 0,
  1419. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border = 5)
  1420. which_sizer.Add(this_sizer)
  1421. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1422. p['wxId'].append(none_check.GetId())
  1423. else:
  1424. p['wxId'].append(None)
  1425. # file selector
  1426. elif p.get('prompt','') != 'color' and p.get('element', '') == 'file':
  1427. fbb = filebrowse.FileBrowseButton(parent = which_panel, id = wx.ID_ANY, fileMask = '*',
  1428. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1429. dialogTitle = _('Choose %s') % \
  1430. p.get('description',_('File')),
  1431. buttonText = _('Browse'),
  1432. startDirectory = os.getcwd(), fileMode = 0,
  1433. changeCallback = self.OnSetValue)
  1434. value = self._getValue(p)
  1435. if value:
  1436. fbb.SetValue(value) # parameter previously set
  1437. which_sizer.Add(item = fbb, proportion = 0,
  1438. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1439. # A file browse button is a combobox with two children:
  1440. # a textctl and a button;
  1441. # we have to target the button here
  1442. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1443. if p.get('age', 'new') == 'old' and \
  1444. UserSettings.Get(group = 'cmd', key = 'interactiveInput', subkey = 'enabled'):
  1445. # widget for interactive input
  1446. ifbb = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY,
  1447. style = wx.TE_MULTILINE,
  1448. size = (-1, 75))
  1449. if p.get('value', '') and os.path.isfile(p['value']):
  1450. f = open(p['value'])
  1451. ifbb.SetValue(''.join(f.readlines()))
  1452. f.close()
  1453. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1454. which_sizer.Add(item = wx.StaticText(parent = which_panel, id = wx.ID_ANY,
  1455. label = _('or enter values interactively')),
  1456. proportion = 0,
  1457. flag = wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM, border = 5)
  1458. which_sizer.Add(item = ifbb, proportion = 1,
  1459. flag = wx.EXPAND | wx.RIGHT | wx.LEFT, border = 5)
  1460. p['wxId'].append(ifbb.GetId())
  1461. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  1462. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1463. label = _("Parameterized in model"))
  1464. parChk.SetName('ModelParam')
  1465. parChk.SetValue(p.get('parameterized', False))
  1466. if p.has_key('wxId'):
  1467. p['wxId'].append(parChk.GetId())
  1468. else:
  1469. p['wxId'] = [ parChk.GetId() ]
  1470. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1471. which_sizer.Add(item = parChk, proportion = 0,
  1472. flag = wx.LEFT, border = 20)
  1473. if title_txt is not None:
  1474. # create tooltip if given
  1475. if len(p['values_desc']) > 0:
  1476. if tooltip:
  1477. tooltip += 2 * os.linesep
  1478. else:
  1479. tooltip = ''
  1480. if len(p['values']) == len(p['values_desc']):
  1481. for i in range(len(p['values'])):
  1482. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1483. tooltip.strip(os.linesep)
  1484. if tooltip:
  1485. title_txt.SetToolTipString(tooltip)
  1486. if p == first_param:
  1487. if p.has_key('wxId') and len(p['wxId']) > 0:
  1488. win = self.FindWindowById(p['wxId'][0])
  1489. win.SetFocus()
  1490. #
  1491. # set widget relations for OnUpdateSelection
  1492. #
  1493. pMap = None
  1494. pLayer = []
  1495. pDriver = None
  1496. pDatabase = None
  1497. pTable = None
  1498. pColumn = []
  1499. pGroup = None
  1500. pSubGroup = None
  1501. pDbase = None
  1502. pLocation = None
  1503. pMapset = None
  1504. for p in self.task.params:
  1505. if p.get('gisprompt', False) == False:
  1506. continue
  1507. guidep = p.get('guidependency', '')
  1508. if guidep:
  1509. # fixed options dependency defined
  1510. options = guidep.split(',')
  1511. for opt in options:
  1512. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1513. if id:
  1514. if not p.has_key('wxId-bind'):
  1515. p['wxId-bind'] = list()
  1516. p['wxId-bind'] += pOpt['wxId']
  1517. continue
  1518. prompt = p.get('element', '')
  1519. if prompt in ('cell', 'vector'):
  1520. name = p.get('name', '')
  1521. if name in ('map', 'input'):
  1522. pMap = p
  1523. elif prompt == 'layer':
  1524. pLayer.append(p)
  1525. elif prompt == 'dbcolumn':
  1526. pColumn.append(p)
  1527. elif prompt == 'dbdriver':
  1528. pDriver = p
  1529. elif prompt == 'dbname':
  1530. pDatabase = p
  1531. elif prompt == 'dbtable':
  1532. pTable = p
  1533. elif prompt == 'group':
  1534. pGroup = p
  1535. elif prompt == 'subgroup':
  1536. pSubGroup = p
  1537. elif prompt == 'dbase':
  1538. pDbase = p
  1539. elif prompt == 'location':
  1540. pLocation = p
  1541. elif prompt == 'mapset':
  1542. pMapset = p
  1543. # collect ids
  1544. pColumnIds = []
  1545. for p in pColumn:
  1546. pColumnIds += p['wxId']
  1547. pLayerIds = []
  1548. for p in pLayer:
  1549. pLayerIds += p['wxId']
  1550. # set wxId-bindings
  1551. if pMap:
  1552. pMap['wxId-bind'] = copy.copy(pColumnIds)
  1553. if pLayer:
  1554. pMap['wxId-bind'] += pLayerIds
  1555. if pLayer:
  1556. for p in pLayer:
  1557. p['wxId-bind'] = copy.copy(pColumnIds)
  1558. if pDriver and pTable:
  1559. pDriver['wxId-bind'] = pTable['wxId']
  1560. if pDatabase and pTable:
  1561. pDatabase['wxId-bind'] = pTable['wxId']
  1562. if pTable and pColumnIds:
  1563. pTable['wxId-bind'] = pColumnIds
  1564. if pGroup and pSubGroup:
  1565. pGroup['wxId-bind'] = pSubGroup['wxId']
  1566. if pDbase and pLocation:
  1567. pDbase['wxId-bind'] = pLocation['wxId']
  1568. if pLocation and pMapset:
  1569. pLocation['wxId-bind'] = pMapset['wxId']
  1570. if pLocation and pMapset and pMap:
  1571. pLocation['wxId-bind'] += pMap['wxId']
  1572. pMapset['wxId-bind'] = pMap['wxId']
  1573. #
  1574. # determine panel size
  1575. #
  1576. maxsizes = (0, 0)
  1577. for section in sections:
  1578. tab[section].SetSizer(tabsizer[section])
  1579. tabsizer[section].Fit(tab[section])
  1580. tab[section].Layout()
  1581. minsecsizes = tabsizer[section].GetSize()
  1582. maxsizes = map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1))
  1583. # TODO: be less arbitrary with these 600
  1584. self.panelMinHeight = 100
  1585. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1586. for section in sections:
  1587. tab[section].SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1588. if self.manual_tab.IsLoaded():
  1589. self.manual_tab.SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1590. self.SetSizer(panelsizer)
  1591. panelsizer.Fit(self.notebook)
  1592. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1593. def _getValue(self, p):
  1594. """!Get value or default value of given parameter
  1595. @param p parameter directory
  1596. """
  1597. if p.get('value', '') != '':
  1598. return p['value']
  1599. return p.get('default', '')
  1600. def OnFileText(self, event):
  1601. """File input interactively entered"""
  1602. text = event.GetString()
  1603. p = self.task.get_param(value = event.GetId(), element = 'wxId', raiseError = False)
  1604. if not p:
  1605. return # should not happen
  1606. win = self.FindWindowById(p['wxId'][0])
  1607. if text:
  1608. filename = win.GetValue()
  1609. if not filename:
  1610. # outFile = tempfile.NamedTemporaryFile(mode = 'w+b')
  1611. filename = grass.tempfile()
  1612. win.SetValue(filename)
  1613. f = open(filename, "w")
  1614. try:
  1615. f.write(text)
  1616. finally:
  1617. f.close()
  1618. else:
  1619. win.SetValue('')
  1620. def OnVectorFormat(self, event):
  1621. """!Change vector format (native / ogr)"""
  1622. sel = event.GetSelection()
  1623. idEvent = event.GetId()
  1624. p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
  1625. if not p:
  1626. return # should not happen
  1627. # detect windows
  1628. winNative = None
  1629. winOgr = None
  1630. for id in p['wxId']:
  1631. if id == idEvent:
  1632. continue
  1633. name = self.FindWindowById(id).GetName()
  1634. if name == 'Select':
  1635. winNative = self.FindWindowById(id + 1) # fix the mystery (also in nviz_tools.py)
  1636. elif name == 'OgrSelect':
  1637. winOgr = self.FindWindowById(id)
  1638. # enable / disable widgets & update values
  1639. rbox = self.FindWindowByName('VectorFormat')
  1640. self.hsizer.Remove(rbox)
  1641. if sel == 0: # -> native
  1642. winOgr.Hide()
  1643. self.hsizer.Remove(winOgr)
  1644. self.hsizer.Add(item = winNative,
  1645. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1646. border = 5)
  1647. winNative.Show()
  1648. p['value'] = winNative.GetValue()
  1649. elif sel == 1: # -> OGR
  1650. sizer = wx.BoxSizer(wx.VERTICAL)
  1651. winNative.Hide()
  1652. self.hsizer.Remove(winNative)
  1653. sizer.Add(item = winOgr)
  1654. winOgr.Show()
  1655. p['value'] = winOgr.GetDsn()
  1656. self.hsizer.Add(item = sizer,
  1657. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1658. border = 5)
  1659. self.hsizer.Add(item = rbox,
  1660. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1661. wx.RIGHT | wx.ALIGN_TOP,
  1662. border = 5)
  1663. self.hsizer.Layout()
  1664. self.Layout()
  1665. self.OnUpdateValues()
  1666. self.OnUpdateSelection(event)
  1667. def OnUpdateDialog(self, event):
  1668. for fn, kwargs in event.data.iteritems():
  1669. fn(**kwargs)
  1670. self.parent.updateValuesHook()
  1671. def OnVerbosity(self, event):
  1672. """!Verbosity level changed"""
  1673. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  1674. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  1675. if event.IsChecked():
  1676. if event.GetId() == verbose.GetId():
  1677. if quiet.IsChecked():
  1678. quiet.SetValue(False)
  1679. self.task.get_flag('quiet')['value'] = False
  1680. else:
  1681. if verbose.IsChecked():
  1682. verbose.SetValue(False)
  1683. self.task.get_flag('verbose')['value'] = False
  1684. event.Skip()
  1685. def OnPageChange(self, event):
  1686. if not event:
  1687. sel = self.notebook.GetSelection()
  1688. else:
  1689. sel = event.GetSelection()
  1690. if hasattr(self, "manual_tab_id") and \
  1691. sel == self.manual_tab_id:
  1692. # calling LoadPage() is strangely time-consuming (only first call)
  1693. # FIXME: move to helpPage.__init__()
  1694. if not self.manual_tab.IsLoaded():
  1695. wx.Yield()
  1696. self.manual_tab.LoadPage()
  1697. self.Layout()
  1698. def OnColorChange(self, event):
  1699. myId = event.GetId()
  1700. for p in self.task.params:
  1701. if 'wxId' in p and myId in p['wxId']:
  1702. has_button = p['wxId'][1] is not None
  1703. if has_button and wx.FindWindowById(p['wxId'][1]).GetValue() == True:
  1704. p[ 'value' ] = 'none'
  1705. else:
  1706. colorchooser = wx.FindWindowById(p['wxId'][0])
  1707. new_color = colorchooser.GetValue()[:]
  1708. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1709. # under wx2.8.1
  1710. new_label = rgb2str.get(new_color, ':'.join(map(str,new_color)))
  1711. colorchooser.SetLabel(new_label)
  1712. colorchooser.SetColour(new_color)
  1713. colorchooser.Refresh()
  1714. p[ 'value' ] = colorchooser.GetLabel()
  1715. self.OnUpdateValues()
  1716. def OnUpdateValues(self, event = None):
  1717. """!If we were part of a richer interface, report back the
  1718. current command being built.
  1719. This method should be set by the parent of this panel if
  1720. needed. It's a hook, actually. Beware of what is 'self' in
  1721. the method def, though. It will be called with no arguments.
  1722. """
  1723. pass
  1724. def OnCheckBoxMulti(self, event):
  1725. """!Fill the values as a ','-separated string according to
  1726. current status of the checkboxes.
  1727. """
  1728. me = event.GetId()
  1729. theParam = None
  1730. for p in self.task.params:
  1731. if 'wxId' in p and me in p['wxId']:
  1732. theParam = p
  1733. myIndex = p['wxId'].index(me)
  1734. # Unpack current value list
  1735. currentValues = {}
  1736. for isThere in theParam.get('value', '').split(','):
  1737. currentValues[isThere] = 1
  1738. theValue = theParam['values'][myIndex]
  1739. if event.Checked():
  1740. currentValues[ theValue ] = 1
  1741. else:
  1742. del currentValues[ theValue ]
  1743. # Keep the original order, so that some defaults may be recovered
  1744. currentValueList = []
  1745. for v in theParam['values']:
  1746. if currentValues.has_key(v):
  1747. currentValueList.append(v)
  1748. # Pack it back
  1749. theParam['value'] = ','.join(currentValueList)
  1750. self.OnUpdateValues()
  1751. def OnSetValue(self, event):
  1752. """!Retrieve the widget value and set the task value field
  1753. accordingly.
  1754. Use for widgets that have a proper GetValue() method, i.e. not
  1755. for selectors.
  1756. """
  1757. myId = event.GetId()
  1758. me = wx.FindWindowById(myId)
  1759. name = me.GetName()
  1760. found = False
  1761. for porf in self.task.params + self.task.flags:
  1762. if not porf.has_key('wxId'):
  1763. continue
  1764. if myId in porf['wxId']:
  1765. found = True
  1766. break
  1767. if not found:
  1768. return
  1769. if name in ('LayerSelect', 'DriverSelect', 'TableSelect',
  1770. 'LocationSelect', 'MapsetSelect', 'ProjSelect'):
  1771. porf['value'] = me.GetStringSelection()
  1772. elif name == 'GdalSelect':
  1773. porf['value'] = event.dsn
  1774. elif name == 'ModelParam':
  1775. porf['parameterized'] = me.IsChecked()
  1776. else:
  1777. porf['value'] = me.GetValue()
  1778. self.OnUpdateValues(event)
  1779. event.Skip()
  1780. def OnUpdateSelection(self, event):
  1781. """!Update dialog (layers, tables, columns, etc.)
  1782. """
  1783. if not hasattr(self.parent, "updateThread"):
  1784. if event:
  1785. event.Skip()
  1786. return
  1787. if event:
  1788. self.parent.updateThread.Update(UpdateDialog,
  1789. self,
  1790. event,
  1791. event.GetId(),
  1792. self.task)
  1793. else:
  1794. self.parent.updateThread.Update(UpdateDialog,
  1795. self,
  1796. None,
  1797. None,
  1798. self.task)
  1799. def createCmd(self, ignoreErrors = False):
  1800. """!Produce a command line string (list) or feeding into GRASS.
  1801. If ignoreErrors == True then it will return whatever has been
  1802. built so far, even though it would not be a correct command
  1803. for GRASS.
  1804. """
  1805. try:
  1806. cmd = self.task.getCmd(ignoreErrors = ignoreErrors)
  1807. except ValueError, err:
  1808. dlg = wx.MessageDialog(parent = self,
  1809. message = unicode(err),
  1810. caption = _("Error in %s") % self.task.name,
  1811. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1812. dlg.ShowModal()
  1813. dlg.Destroy()
  1814. cmd = None
  1815. return cmd
  1816. def OnSize(self, event):
  1817. width = event.GetSize()[0]
  1818. fontsize = self.GetFont().GetPointSize()
  1819. text_width = max(width / (fontsize - 3), 70)
  1820. for id in self.label_id:
  1821. win = self.FindWindowById(id)
  1822. label = win.GetLabel()
  1823. label_new = '\n'.join(textwrap.wrap(label, text_width))
  1824. win.SetLabel(label_new)
  1825. event.Skip()
  1826. def getInterfaceDescription(cmd):
  1827. """!Returns the XML description for the GRASS cmd.
  1828. The DTD must be located in $GISBASE/etc/grass-interface.dtd,
  1829. otherwise the parser will not succeed.
  1830. @param cmd command (name of GRASS module)
  1831. """
  1832. try:
  1833. cmdout, cmderr = grass.Popen([cmd, '--interface-description'], stdout = grass.PIPE,
  1834. stderr = grass.PIPE).communicate()
  1835. except OSError, e:
  1836. raise gcmd.GException, _("Unable to fetch interface description for command '%s'. "
  1837. "Details: %s") % (cmd, repr(e))
  1838. if cmderr and cmderr[:7] != 'WARNING':
  1839. raise gcmd.GException, _("Unable to fetch interface description for command '%s'. "
  1840. "Details: %s") % (cmd, cmderr)
  1841. return cmdout.replace('grass-interface.dtd', os.path.join(globalvar.ETCDIR, 'grass-interface.dtd'))
  1842. class GrassGUIApp(wx.App):
  1843. """!Stand-alone GRASS command GUI
  1844. """
  1845. def __init__(self, grass_task):
  1846. self.grass_task = grass_task
  1847. wx.App.__init__(self, False)
  1848. def OnInit(self):
  1849. msg = self.grass_task.get_error_msg()
  1850. if msg:
  1851. gcmd.GError(msg + '\n\nTry to set up GRASS_ADDON_PATH variable.')
  1852. return True
  1853. self.mf = mainFrame(parent = None, ID = wx.ID_ANY, task_description = self.grass_task)
  1854. self.mf.CentreOnScreen()
  1855. self.mf.Show(True)
  1856. self.SetTopWindow(self.mf)
  1857. return True
  1858. class GUI:
  1859. """
  1860. Parses GRASS commands when module is imported and used
  1861. from Layer Manager.
  1862. """
  1863. def __init__(self, parent = -1):
  1864. self.parent = parent
  1865. self.grass_task = None
  1866. self.cmd = list()
  1867. def GetCmd(self):
  1868. """Get validated command"""
  1869. return self.cmd
  1870. def ParseInterface(self, cmd, parser = processTask):
  1871. """!Parse interface
  1872. @param cmd command to be parsed (given as list)
  1873. """
  1874. # enc = locale.getdefaultlocale()[1]
  1875. # if enc and enc.lower() not in ("utf8", "utf-8"):
  1876. # tree = etree.fromstring(getInterfaceDescription(cmd[0]).decode(enc).encode("utf-8"))
  1877. # else:
  1878. tree = etree.fromstring(getInterfaceDescription(cmd[0]))
  1879. return processTask(tree).GetTask()
  1880. def ParseCommand(self, cmd, gmpath = None, completed = None, parentframe = None,
  1881. show = True, modal = False, centreOnParent = False, checkError = False):
  1882. """!Parse command
  1883. Note: cmd is given as list
  1884. If command is given with options, return validated cmd list:
  1885. - add key name for first parameter if not given
  1886. - change mapname to mapname@mapset
  1887. """
  1888. start = time.time()
  1889. dcmd_params = {}
  1890. if completed == None:
  1891. get_dcmd = None
  1892. layer = None
  1893. dcmd_params = None
  1894. else:
  1895. get_dcmd = completed[0]
  1896. layer = completed[1]
  1897. if completed[2]:
  1898. dcmd_params.update(completed[2])
  1899. self.parent = parentframe
  1900. # parse the interface decription
  1901. self.grass_task = self.ParseInterface(cmd)
  1902. # if layer parameters previously set, re-insert them into dialog
  1903. if completed is not None:
  1904. if 'params' in dcmd_params:
  1905. self.grass_task.params = dcmd_params['params']
  1906. if 'flags' in dcmd_params:
  1907. self.grass_task.flags = dcmd_params['flags']
  1908. err = list()
  1909. # update parameters if needed && validate command
  1910. if len(cmd) > 1:
  1911. i = 0
  1912. cmd_validated = [cmd[0]]
  1913. for option in cmd[1:]:
  1914. if option[0] == '-': # flag
  1915. if option[1] == '-':
  1916. self.grass_task.set_flag(option[2:], True)
  1917. else:
  1918. self.grass_task.set_flag(option[1], True)
  1919. cmd_validated.append(option)
  1920. else: # parameter
  1921. try:
  1922. key, value = option.split('=', 1)
  1923. except:
  1924. if i == 0: # add key name of first parameter if not given
  1925. key = self.grass_task.firstParam
  1926. value = option
  1927. else:
  1928. raise gcmd.GException, _("Unable to parse command '%s'") % ' '.join(cmd)
  1929. element = self.grass_task.get_param(key, raiseError = False)
  1930. if not element:
  1931. err.append(_("%(cmd)s: parameter '%(key)s' not available") % \
  1932. { 'cmd' : cmd[0],
  1933. 'key' : key })
  1934. continue
  1935. element = element['element']
  1936. if element in ['cell', 'vector']:
  1937. # mapname -> mapname@mapset
  1938. try:
  1939. name, mapset = value.split('@')
  1940. except ValueError:
  1941. mapset = grass.find_file(value, element)['mapset']
  1942. curr_mapset = grass.gisenv()['MAPSET']
  1943. if mapset and mapset != curr_mapset:
  1944. value = value + '@' + mapset
  1945. self.grass_task.set_param(key, value)
  1946. cmd_validated.append(key + '=' + value)
  1947. i += 1
  1948. # update original command list
  1949. cmd = cmd_validated
  1950. if show is not None:
  1951. self.mf = mainFrame(parent = self.parent, ID = wx.ID_ANY,
  1952. task_description = self.grass_task,
  1953. get_dcmd = get_dcmd, layer = layer)
  1954. else:
  1955. self.mf = None
  1956. if get_dcmd is not None:
  1957. # update only propwin reference
  1958. get_dcmd(dcmd = None, layer = layer, params = None,
  1959. propwin = self.mf)
  1960. if show is not None:
  1961. self.mf.notebookpanel.OnUpdateSelection(None)
  1962. if show is True:
  1963. if self.parent and centreOnParent:
  1964. self.mf.CentreOnParent()
  1965. else:
  1966. self.mf.CenterOnScreen()
  1967. self.mf.Show(show)
  1968. self.mf.MakeModal(modal)
  1969. else:
  1970. self.mf.OnApply(None)
  1971. self.cmd = cmd
  1972. if checkError:
  1973. return self.grass_task, err
  1974. else:
  1975. return self.grass_task
  1976. def GetCommandInputMapParamKey(self, cmd):
  1977. """!Get parameter key for input raster/vector map
  1978. @param cmd module name
  1979. @return parameter key
  1980. @return None on failure
  1981. """
  1982. # parse the interface decription
  1983. if not self.grass_task:
  1984. tree = etree.fromstring(getInterfaceDescription(cmd))
  1985. self.grass_task = processTask(tree).GetTask()
  1986. for p in self.grass_task.params:
  1987. if p.get('name', '') in ('input', 'map'):
  1988. age = p.get('age', '')
  1989. prompt = p.get('prompt', '')
  1990. element = p.get('element', '')
  1991. if age == 'old' and \
  1992. element in ('cell', 'grid3', 'vector') and \
  1993. prompt in ('raster', '3d-raster', 'vector'):
  1994. return p.get('name', None)
  1995. return None
  1996. class FloatValidator(wx.PyValidator):
  1997. """!Validator for floating-point input"""
  1998. def __init__(self):
  1999. wx.PyValidator.__init__(self)
  2000. self.Bind(wx.EVT_TEXT, self.OnText)
  2001. def Clone(self):
  2002. """!Clone validator"""
  2003. return FloatValidator()
  2004. def Validate(self):
  2005. """Validate input"""
  2006. textCtrl = self.GetWindow()
  2007. text = textCtrl.GetValue()
  2008. if text:
  2009. try:
  2010. float(text)
  2011. except ValueError:
  2012. textCtrl.SetBackgroundColour("grey")
  2013. textCtrl.SetFocus()
  2014. textCtrl.Refresh()
  2015. return False
  2016. sysColor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW)
  2017. textCtrl.SetBackgroundColour(sysColor)
  2018. textCtrl.Refresh()
  2019. return True
  2020. def OnText(self, event):
  2021. """!Do validation"""
  2022. self.Validate()
  2023. event.Skip()
  2024. def TransferToWindow(self):
  2025. return True # Prevent wxDialog from complaining.
  2026. def TransferFromWindow(self):
  2027. return True # Prevent wxDialog from complaining.
  2028. if __name__ == "__main__":
  2029. if len(sys.argv) == 1:
  2030. sys.exit(_("usage: %s <grass command>") % sys.argv[0])
  2031. if sys.argv[1] != 'test':
  2032. q = wx.LogNull()
  2033. cmd = shlex.split(sys.argv[1])
  2034. task = grassTask(cmd[0])
  2035. task.set_options(cmd[1:])
  2036. app = GrassGUIApp(task)
  2037. app.MainLoop()
  2038. else: #Test
  2039. # Test grassTask from within a GRASS session
  2040. if os.getenv("GISBASE") is not None:
  2041. task = grassTask("d.vect")
  2042. task.get_param('map')['value'] = "map_name"
  2043. task.get_flag('v')['value'] = True
  2044. task.get_param('layer')['value'] = 1
  2045. task.get_param('bcolor')['value'] = "red"
  2046. assert ' '.join(task.getCmd()) == "d.vect -v map = map_name layer = 1 bcolor = red"
  2047. # Test interface building with handmade grassTask,
  2048. # possibly outside of a GRASS session.
  2049. task = grassTask()
  2050. task.name = "TestTask"
  2051. task.description = "This is an artificial grassTask() object intended for testing purposes."
  2052. task.keywords = ["grass","test","task"]
  2053. task.params = [
  2054. {
  2055. "name" : "text",
  2056. "description" : "Descriptions go into tooltips if labels are present, like this one",
  2057. "label" : "Enter some text",
  2058. },{
  2059. "name" : "hidden_text",
  2060. "description" : "This text should not appear in the form",
  2061. "hidden" : "yes"
  2062. },{
  2063. "name" : "text_default",
  2064. "description" : "Enter text to override the default",
  2065. "default" : "default text"
  2066. },{
  2067. "name" : "text_prefilled",
  2068. "description" : "You should see a friendly welcome message here",
  2069. "value" : "hello, world"
  2070. },{
  2071. "name" : "plain_color",
  2072. "description" : "This is a plain color, and it is a compulsory parameter",
  2073. "required" : False,
  2074. "gisprompt" : True,
  2075. "prompt" : "color"
  2076. },{
  2077. "name" : "transparent_color",
  2078. "description" : "This color becomes transparent when set to none",
  2079. "guisection" : "tab",
  2080. "gisprompt" : True,
  2081. "prompt" : "color"
  2082. },{
  2083. "name" : "multi",
  2084. "description" : "A multiple selection",
  2085. 'default': u'red,green,blue',
  2086. 'gisprompt': False,
  2087. 'guisection': 'tab',
  2088. 'multiple': u'yes',
  2089. 'type': u'string',
  2090. 'value': '',
  2091. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other']
  2092. },{
  2093. "name" : "single",
  2094. "description" : "A single multiple-choice selection",
  2095. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  2096. "guisection" : "tab"
  2097. },{
  2098. "name" : "large_multi",
  2099. "description" : "A large multiple selection",
  2100. "gisprompt" : False,
  2101. "multiple" : "yes",
  2102. # values must be an array of strings
  2103. "values" : str2rgb.keys() + map(str, str2rgb.values())
  2104. },{
  2105. "name" : "a_file",
  2106. "description" : "A file selector",
  2107. "gisprompt" : True,
  2108. "element" : "file"
  2109. }
  2110. ]
  2111. task.flags = [
  2112. {
  2113. "name" : "a",
  2114. "description" : "Some flag, will appear in Main since it is required",
  2115. "required" : True
  2116. },{
  2117. "name" : "b",
  2118. "description" : "pre-filled flag, will appear in options since it is not required",
  2119. "value" : True
  2120. },{
  2121. "name" : "hidden_flag",
  2122. "description" : "hidden flag, should not be changeable",
  2123. "hidden" : "yes",
  2124. "value" : True
  2125. }
  2126. ]
  2127. q = wx.LogNull()
  2128. GrassGUIApp(task).MainLoop()