menuform.py 76 KB

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