menuform.py 89 KB

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