menuform.py 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914
  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. chk = wx.CheckBox(parent=which_panel, label = title, style = wx.NO_BORDER)
  835. self.label_id.append(chk.GetId())
  836. if tooltip:
  837. chk.SetToolTipString(tooltip)
  838. if 'value' in f:
  839. chk.SetValue( f['value'] )
  840. # chk.SetFont(wx.Font(pointSize=fontsize, family=wx.FONTFAMILY_DEFAULT,
  841. # style=wx.NORMAL, weight=text_style))
  842. which_sizer.Add( item=chk, proportion=0,
  843. flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=5)
  844. f['wxId'] = chk.GetId()
  845. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  846. if f['name'] in ('verbose', 'quiet'):
  847. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  848. vq = UserSettings.Get(group='cmd', key='verbosity', subkey='selection')
  849. if f['name'] == vq:
  850. chk.SetValue(True)
  851. f['value'] = True
  852. elif f['name'] == 'overwrite':
  853. chk.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
  854. f['value'] = UserSettings.Get(group='cmd', key='overwrite', subkey='enabled')
  855. #
  856. # parameters
  857. #
  858. visible_params = [ p for p in self.task.params if not p.get( 'hidden', 'no' ) == 'yes' ]
  859. try:
  860. first_param = visible_params[0]
  861. except IndexError:
  862. first_param = None
  863. for p in visible_params:
  864. which_sizer = tabsizer[ p['guisection'] ]
  865. which_panel = tab[ p['guisection'] ]
  866. # if label is given -> label and description -> tooltip
  867. # otherwise description -> lavel
  868. if p.get('label','') != '':
  869. title = text_beautify( p['label'] )
  870. tooltip = text_beautify ( p['description'], width = -1)
  871. else:
  872. title = text_beautify( p['description'] )
  873. tooltip = None
  874. txt = None
  875. # text style (required -> bold)
  876. if p.get('required','no') == 'no':
  877. text_style = wx.FONTWEIGHT_NORMAL
  878. else:
  879. text_style = wx.FONTWEIGHT_BOLD
  880. # title sizer (description, name, type)
  881. if (len(p.get('values', []) ) > 0) and \
  882. p.get('multiple', 'no') == 'yes' and \
  883. p.get('gisprompt',False) == False and \
  884. p.get('type', '') == 'string':
  885. title_txt = wx.StaticBox (parent=which_panel, id=wx.ID_ANY)
  886. else:
  887. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  888. title_txt = wx.StaticText(parent=which_panel)
  889. rtitle_txt = wx.StaticText(parent=which_panel,
  890. label = '(' + p['name'] + ', ' + p['type'] + ')')
  891. title_sizer.Add(item=title_txt, proportion=1,
  892. flag=wx.LEFT | wx.TOP | wx.EXPAND, border=5)
  893. title_sizer.Add(item=rtitle_txt, proportion=0,
  894. flag=wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border=5)
  895. which_sizer.Add(item=title_sizer, proportion=0,
  896. flag=wx.EXPAND)
  897. self.label_id.append(title_txt.GetId())
  898. # title expansion
  899. if p.get('multiple','no') == 'yes' and len( p.get('values','') ) == 0:
  900. title = _("[multiple]") + " " + title
  901. if p.get('value','') == '' :
  902. p['value'] = p.get('default','')
  903. if ( len(p.get('values', []) ) > 0):
  904. valuelist = map(str, p.get('values',[]))
  905. valuelist_desc = map(unicode, p.get('values_desc',[]))
  906. if p.get('multiple', 'no') == 'yes' and \
  907. p.get('gisprompt',False) == False and \
  908. p.get('type', '') == 'string':
  909. title_txt.SetLabel(" " + title + ": ")
  910. if len(valuelist) > 6:
  911. hSizer=wx.StaticBoxSizer ( box=title_txt, orient=wx.VERTICAL )
  912. else:
  913. hSizer=wx.StaticBoxSizer ( box=title_txt, orient=wx.HORIZONTAL )
  914. isEnabled = {}
  915. # copy default values
  916. if p['value'] == '':
  917. p['value'] = p.get('default', '')
  918. for defval in p.get('value', '').split(','):
  919. isEnabled[ defval ] = 'yes'
  920. # for multi checkboxes, this is an array of all wx IDs
  921. # for each individual checkbox
  922. p[ 'wxId' ] = []
  923. idx = 0
  924. for val in valuelist:
  925. try:
  926. label = valuelist_desc[idx]
  927. except IndexError:
  928. label = val
  929. chkbox = wx.CheckBox( parent=which_panel, label = text_beautify(label) )
  930. p[ 'wxId' ].append( chkbox.GetId() )
  931. if isEnabled.has_key(val):
  932. chkbox.SetValue( True )
  933. hSizer.Add( item=chkbox, proportion=0,
  934. flag=wx.ADJUST_MINSIZE | wx.ALL, border=1 )
  935. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  936. idx += 1
  937. which_sizer.Add( item=hSizer, proportion=0,
  938. flag=wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border=5 )
  939. elif p.get('gisprompt', False) == False:
  940. if len(valuelist) == 1: # -> textctrl
  941. title_txt.SetLabel("%s. %s %s" % (title, _('Valid range'),
  942. str(valuelist[0]) + ':'))
  943. if p.get('type','') == 'integer' and \
  944. p.get('multiple','no') == 'no':
  945. # for multiple integers use textctrl instead of spinsctrl
  946. try:
  947. minValue, maxValue = map(int, valuelist[0].split('-'))
  948. except ValueError:
  949. minValue = -1e6
  950. maxValue = 1e6
  951. txt2 = wx.SpinCtrl(parent=which_panel, id=wx.ID_ANY, size=globalvar.DIALOG_SPIN_SIZE,
  952. min=minValue, max=maxValue)
  953. txt2.SetName("SpinCtrl")
  954. style = wx.BOTTOM | wx.LEFT
  955. else:
  956. txt2 = wx.TextCtrl(parent=which_panel, value = p.get('default',''))
  957. txt2.SetName("TextCtrl")
  958. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  959. if p.get('value', '') != '':
  960. # parameter previously set
  961. if txt2.GetName() == "SpinCtrl":
  962. txt2.SetValue(int(p['value']))
  963. else:
  964. txt2.SetValue(p['value'])
  965. which_sizer.Add(item=txt2, proportion=0,
  966. flag=style, border=5)
  967. p['wxId'] = txt2.GetId()
  968. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  969. else:
  970. # list of values (combo)
  971. title_txt.SetLabel(title + ':')
  972. cb = wx.ComboBox(parent=which_panel, id=wx.ID_ANY, value=p.get('default',''),
  973. size=globalvar.DIALOG_COMBOBOX_SIZE,
  974. choices=valuelist, style=wx.CB_DROPDOWN | wx.CB_READONLY)
  975. if p.get('value','') != '':
  976. cb.SetValue(p['value']) # parameter previously set
  977. which_sizer.Add( item=cb, proportion=0,
  978. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  979. p['wxId'] = cb.GetId()
  980. cb.Bind( wx.EVT_COMBOBOX, self.OnSetValue)
  981. # text entry
  982. if (p.get('type','string') in ('string','integer','float')
  983. and len(p.get('values',[])) == 0
  984. and p.get('gisprompt',False) == False
  985. and p.get('prompt','') != 'color'):
  986. title_txt.SetLabel(title + ':' )
  987. if p.get('multiple','yes') == 'yes' or \
  988. p.get('type', 'string') in ('string', 'float') or \
  989. len(p.get('key_desc', [])) > 1:
  990. txt3 = wx.TextCtrl(parent=which_panel, value = p.get('default',''))
  991. if p.get('value','') != '':
  992. txt3.SetValue(str(p['value'])) # parameter previously set
  993. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  994. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  995. else:
  996. minValue = -1e9
  997. maxValue = 1e9
  998. txt3 = wx.SpinCtrl(parent=which_panel, value=p.get('default',''),
  999. size=globalvar.DIALOG_SPIN_SIZE,
  1000. min=minValue, max=maxValue)
  1001. if p.get('value','') != '':
  1002. txt3.SetValue(int(p['value'])) # parameter previously set
  1003. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1004. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  1005. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1006. which_sizer.Add(item=txt3, proportion=0,
  1007. flag=style, border=5)
  1008. p['wxId'] = txt3.GetId()
  1009. #
  1010. # element selection tree combobox (maps, icons, regions, etc.)
  1011. #
  1012. if p.get('gisprompt', False) == True:
  1013. title_txt.SetLabel(title + ':')
  1014. # GIS element entry
  1015. if p.get('prompt','') not in ('color',
  1016. 'color_none',
  1017. 'dbdriver',
  1018. 'dbname',
  1019. 'dbtable',
  1020. 'dbcolumn',
  1021. 'layer',
  1022. 'layer_all') and \
  1023. p.get('element', '') != 'file':
  1024. if p.get('multiple', 'no') == 'yes':
  1025. multiple = True
  1026. else:
  1027. multiple = False
  1028. if p.get('age', '') == 'new':
  1029. mapsets = [grass.gisenv()['MAPSET'],]
  1030. else:
  1031. mapsets = None
  1032. selection = gselect.Select(parent=which_panel, id=wx.ID_ANY,
  1033. size=globalvar.DIALOG_GSELECT_SIZE,
  1034. type=p.get('element', ''),
  1035. multiple=multiple, mapsets=mapsets)
  1036. if p.get('value','') != '':
  1037. selection.SetValue(p['value']) # parameter previously set
  1038. which_sizer.Add(item=selection, proportion=0,
  1039. flag=wx.ADJUST_MINSIZE| wx.BOTTOM | wx.LEFT | wx.RIGHT, border=5)
  1040. # A select.Select is a combobox with two children: a textctl and a popupwindow;
  1041. # we target the textctl here
  1042. p['wxId'] = selection.GetChildren()[0].GetId()
  1043. selection.GetChildren()[0].Bind(wx.EVT_TEXT, self.OnSetValue)
  1044. if p.get('prompt', '') == 'vector':
  1045. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1046. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1047. elif p.get('prompt', '') in ('dbdriver',
  1048. 'dbname',
  1049. 'dbtable',
  1050. 'dbcolumn',
  1051. 'layer',
  1052. 'layer_all'):
  1053. if p.get('multiple', 'no') == 'yes':
  1054. win = wx.TextCtrl(parent=which_panel, value = p.get('default',''),
  1055. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  1056. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1057. else:
  1058. if p.get('prompt', '') in ('layer',
  1059. 'layer_all'):
  1060. if p.get('prompt', '') == 'layer_all':
  1061. all = True
  1062. else:
  1063. all = False
  1064. if p.get('age', 'old_layer') == 'old_layer':
  1065. win = gselect.LayerSelect(parent=which_panel,
  1066. all=all,
  1067. default=p['default'])
  1068. p['wxGetValue'] = win.GetStringSelection
  1069. win.Bind(wx.EVT_CHOICE, self.OnUpdateSelection)
  1070. win.Bind(wx.EVT_CHOICE, self.OnSetValue)
  1071. else:
  1072. win = wx.SpinCtrl(parent=which_panel, id=wx.ID_ANY,
  1073. min=1, max=100, initial=int(p['default']))
  1074. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1075. elif p.get('prompt', '') == 'dbdriver':
  1076. win = gselect.DriverSelect(parent=which_panel,
  1077. choices=p['values'],
  1078. value=p['default'])
  1079. p['wxGetValue'] = win.GetStringSelection
  1080. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1081. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1082. elif p.get('prompt', '') == 'dbname':
  1083. win = gselect.DatabaseSelect(parent=which_panel,
  1084. value=p['default'])
  1085. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1086. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1087. elif p.get('prompt', '') == 'dbtable':
  1088. if p.get('age', 'old_dbtable') == 'old_dbtable':
  1089. win = gselect.TableSelect(parent=which_panel)
  1090. p['wxGetValue'] = win.GetStringSelection
  1091. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1092. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1093. else:
  1094. win = wx.TextCtrl(parent=which_panel, value = p.get('default',''),
  1095. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  1096. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1097. elif p.get('prompt', '') == 'dbcolumn':
  1098. win = gselect.ColumnSelect(parent=which_panel)
  1099. p['wxGetValue'] = win.GetStringSelection
  1100. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1101. p['wxId'] = win.GetId()
  1102. which_sizer.Add(item=win, proportion=0,
  1103. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  1104. # color entry
  1105. elif p.get('prompt', '') in ('color',
  1106. 'color_none'):
  1107. default_color = (200,200,200)
  1108. label_color = _("Select Color")
  1109. if p.get('default','') != '':
  1110. default_color, label_color = color_resolve( p['default'] )
  1111. if p.get('value','') != '': # parameter previously set
  1112. default_color, label_color = color_resolve( p['value'] )
  1113. if p.get('prompt', '') == 'color_none':
  1114. this_sizer = wx.BoxSizer(orient=wx.HORIZONTAL )
  1115. else:
  1116. this_sizer = which_sizer
  1117. btn_colour = csel.ColourSelect(parent=which_panel, id=wx.ID_ANY,
  1118. label=label_color, colour=default_color,
  1119. pos=wx.DefaultPosition, size=(150,-1) )
  1120. this_sizer.Add(item=btn_colour, proportion=0,
  1121. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  1122. # For color selectors, this is a two-member array, holding the IDs of
  1123. # the selector proper and either a "transparent" button or None
  1124. p['wxId'] = [btn_colour.GetId(),]
  1125. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange )
  1126. if p.get('prompt', '') == 'color_none':
  1127. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent") )
  1128. if p.get('value','') != '' and p.get('value',[''])[0] == "none":
  1129. none_check.SetValue(True)
  1130. else:
  1131. none_check.SetValue(False)
  1132. # none_check.SetFont( wx.Font( fontsize, wx.FONTFAMILY_DEFAULT, wx.NORMAL, text_style, 0, ''))
  1133. this_sizer.Add(item=none_check, proportion=0,
  1134. flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border=5)
  1135. which_sizer.Add( this_sizer )
  1136. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1137. p['wxId'].append( none_check.GetId() )
  1138. else:
  1139. p['wxId'].append(None)
  1140. # file selector
  1141. elif p.get('prompt','') != 'color' and p.get('element', '') == 'file':
  1142. fbb = filebrowse.FileBrowseButton(parent=which_panel, id=wx.ID_ANY,
  1143. size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
  1144. dialogTitle=_('Choose %s') % \
  1145. p.get('description',_('File')),
  1146. buttonText=_('Browse'),
  1147. startDirectory=os.getcwd(), fileMode=0,
  1148. changeCallback=self.OnSetValue)
  1149. if p.get('value','') != '':
  1150. fbb.SetValue(p['value']) # parameter previously set
  1151. which_sizer.Add(item=fbb, proportion=0,
  1152. flag=wx.EXPAND | wx.RIGHT, border=5)
  1153. # A file browse button is a combobox with two children:
  1154. # a textctl and a button;
  1155. # we have to target the button here
  1156. p['wxId'] = fbb.GetChildren()[1].GetId()
  1157. if title_txt is not None:
  1158. # create tooltip if given
  1159. if len(p['values_desc']) > 0:
  1160. if tooltip:
  1161. tooltip += 2 * os.linesep
  1162. else:
  1163. tooltip = ''
  1164. if len(p['values']) == len(p['values_desc']):
  1165. for i in range(len(p['values'])):
  1166. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1167. tooltip.strip(os.linesep)
  1168. if tooltip:
  1169. title_txt.SetToolTipString(tooltip)
  1170. if p == first_param:
  1171. if type(p['wxId']) == type(1):
  1172. self.FindWindowById(p['wxId']).SetFocus()
  1173. #
  1174. # set widget relations for OnUpdateSelection
  1175. #
  1176. pMap = None
  1177. pLayer = []
  1178. pDriver = None
  1179. pDatabase = None
  1180. pTable = None
  1181. pColumn = []
  1182. for p in self.task.params:
  1183. if p.get('gisprompt', False) == False:
  1184. continue
  1185. prompt = p.get('element', '')
  1186. if prompt == 'vector':
  1187. name = p.get('name', '')
  1188. if name in ('map', 'input'):
  1189. pMap = p
  1190. elif prompt == 'layer':
  1191. pLayer.append(p)
  1192. elif prompt == 'dbcolumn':
  1193. pColumn.append(p)
  1194. elif prompt == 'dbdriver':
  1195. pDriver = p
  1196. elif prompt == 'dbname':
  1197. pDatabase = p
  1198. elif prompt == 'dbtable':
  1199. pTable = p
  1200. pColumnIds = []
  1201. for p in pColumn:
  1202. pColumnIds.append(p['wxId'])
  1203. pLayerIds = []
  1204. for p in pLayer:
  1205. pLayerIds.append(p['wxId'])
  1206. if pMap:
  1207. pMap['wxId-bind'] = copy.copy(pColumnIds)
  1208. if pLayer:
  1209. pMap['wxId-bind'] += pLayerIds
  1210. for p in pLayer:
  1211. p['wxId-bind'] = copy.copy(pColumnIds)
  1212. if pDriver and pTable:
  1213. pDriver['wxId-bind'] = [pTable['wxId'], ]
  1214. if pDatabase and pTable:
  1215. pDatabase['wxId-bind'] = [pTable['wxId'], ]
  1216. if pTable and pColumnIds:
  1217. pTable['wxId-bind'] = pColumnIds
  1218. #
  1219. # determine panel size
  1220. #
  1221. maxsizes = (0,0)
  1222. for section in sections:
  1223. # tabsizer[section].SetSizeHints( tab[section] )
  1224. #tab[section].SetAutoLayout(True)
  1225. tab[section].SetSizer( tabsizer[section] )
  1226. tabsizer[section].Fit( tab[section] )
  1227. tab[section].Layout()
  1228. minsecsizes = tabsizer[section].GetSize()
  1229. maxsizes = map( lambda x: max( maxsizes[x], minsecsizes[x] ), (0,1) )
  1230. # TODO: be less arbitrary with these 600
  1231. self.panelMinHeight = 100
  1232. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1233. for section in sections:
  1234. tab[section].SetMinSize( (self.constrained_size[0], self.panelMinHeight) )
  1235. # tab[section].SetMinSize( constrained_size )
  1236. if self.manual_tab.Ok:
  1237. self.manual_tab.SetMinSize( (self.constrained_size[0], self.panelMinHeight) )
  1238. # manual_tab.SetMinSize( constrained_size )
  1239. self.SetSizer( panelsizer )
  1240. panelsizer.Fit(self.notebook)
  1241. self.hasMain = tab.has_key( _('Required') ) # publish, to enclosing Frame for instance
  1242. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1243. def OnUpdateDialog(self, event):
  1244. for fn, kwargs in event.data.iteritems():
  1245. fn(**kwargs)
  1246. def OnVerbosity(self, event):
  1247. """!Verbosity level changed"""
  1248. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'])
  1249. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'])
  1250. if event.IsChecked():
  1251. if event.GetId() == verbose.GetId():
  1252. if quiet.IsChecked():
  1253. quiet.SetValue(False)
  1254. self.task.get_flag('quiet')['value'] = False
  1255. else:
  1256. if verbose.IsChecked():
  1257. verbose.SetValue(False)
  1258. self.task.get_flag('verbose')['value'] = False
  1259. event.Skip()
  1260. def OnPageChange(self, event):
  1261. if not event:
  1262. sel = self.notebook.GetSelection()
  1263. else:
  1264. sel = event.GetSelection()
  1265. if hasattr(self, "manual_tab_id") and \
  1266. sel == self.manual_tab_id:
  1267. # calling LoadPage() is strangely time-consuming (only first call)
  1268. # FIXME: move to helpPage.__init__()
  1269. if not self.manual_tab.Ok:
  1270. wx.Yield()
  1271. self.manual_tab.LoadPage(self.manual_tab.fspath + self.task.name + ".html")
  1272. self.manual_tab.Ok = True
  1273. self.Layout()
  1274. def OnColorChange( self, event ):
  1275. myId = event.GetId()
  1276. for p in self.task.params:
  1277. if 'wxId' in p and type( p['wxId'] ) == type( [] ) and myId in p['wxId']:
  1278. has_button = p['wxId'][1] is not None
  1279. if has_button and wx.FindWindowById( p['wxId'][1] ).GetValue() == True:
  1280. p[ 'value' ] = 'none'
  1281. else:
  1282. colorchooser = wx.FindWindowById( p['wxId'][0] )
  1283. new_color = colorchooser.GetValue()[:]
  1284. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1285. # under wx2.8.1
  1286. new_label = rgb2str.get( new_color, ':'.join(map(str,new_color)) )
  1287. colorchooser.SetLabel( new_label )
  1288. colorchooser.SetColour( new_color )
  1289. colorchooser.Refresh()
  1290. p[ 'value' ] = colorchooser.GetLabel()
  1291. self.OnUpdateValues()
  1292. def OnUpdateValues(self):
  1293. """
  1294. If we were part of a richer interface, report back the current command being built.
  1295. This method should be set by the parent of this panel if needed. It's a hook, actually.
  1296. Beware of what is 'self' in the method def, though. It will be called with no arguments.
  1297. """
  1298. pass
  1299. def OnCheckBoxMulti(self, event):
  1300. """
  1301. Fill the values as a ','-separated string according to current status of the checkboxes.
  1302. """
  1303. me = event.GetId()
  1304. theParam = None
  1305. for p in self.task.params:
  1306. if 'wxId' in p and type( p['wxId'] ) == type( [] ) and me in p['wxId']:
  1307. theParam = p
  1308. myIndex = p['wxId'].index( me )
  1309. # Unpack current value list
  1310. currentValues = {}
  1311. for isThere in theParam.get('value', '').split(','):
  1312. currentValues[isThere] = 1
  1313. theValue = theParam['values'][myIndex]
  1314. if event.Checked():
  1315. currentValues[ theValue ] = 1
  1316. else:
  1317. del currentValues[ theValue ]
  1318. # Keep the original order, so that some defaults may be recovered
  1319. currentValueList = []
  1320. for v in theParam['values']:
  1321. if currentValues.has_key(v):
  1322. currentValueList.append( v )
  1323. # Pack it back
  1324. theParam['value'] = ','.join( currentValueList )
  1325. self.OnUpdateValues()
  1326. def OnSetValue(self, event):
  1327. """
  1328. Retrieve the widget value and set the task value field accordingly.
  1329. Use for widgets that have a proper GetValue() method, i.e. not for selectors.
  1330. """
  1331. myId = event.GetId()
  1332. me = wx.FindWindowById( myId )
  1333. for porf in self.task.params + self.task.flags:
  1334. if 'wxId' in porf and type( porf[ 'wxId' ] ) == type( 1 ) and porf['wxId'] == myId:
  1335. if porf.has_key('wxGetValue') and porf['wxGetValue']:
  1336. porf['value'] = porf['wxGetValue']()
  1337. else:
  1338. porf['value'] = me.GetValue()
  1339. self.OnUpdateValues()
  1340. event.Skip()
  1341. def OnUpdateSelection(self, event):
  1342. """
  1343. Update dialog (layers, tables, columns, etc.)
  1344. """
  1345. if event:
  1346. self.parent.updateThread.Update(UpdateDialog,
  1347. self,
  1348. event,
  1349. event.GetId(),
  1350. self.task)
  1351. else:
  1352. self.parent.updateThread.Update(UpdateDialog,
  1353. self,
  1354. None,
  1355. None,
  1356. self.task)
  1357. def createCmd( self, ignoreErrors = False ):
  1358. """
  1359. Produce a command line string (list) or feeding into GRASS.
  1360. If ignoreErrors==True then it will return whatever has been
  1361. built so far, even though it would not be a correct command
  1362. for GRASS.
  1363. """
  1364. try:
  1365. cmd = self.task.getCmd( ignoreErrors=ignoreErrors )
  1366. except ValueError, err:
  1367. dlg = wx.MessageDialog(parent=self,
  1368. message=unicode(err),
  1369. caption=_("Error in %s") % self.task.name,
  1370. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1371. dlg.ShowModal()
  1372. dlg.Destroy()
  1373. cmd = None
  1374. return cmd
  1375. def OnSize(self, event):
  1376. width = event.GetSize()[0]
  1377. fontsize = self.GetFont().GetPointSize()
  1378. text_width = width / (fontsize - 3)
  1379. if text_width < 70:
  1380. text_width = 70
  1381. for id in self.label_id:
  1382. win = self.FindWindowById(id)
  1383. label = win.GetLabel()
  1384. label_new = '\n'.join(textwrap.wrap(label, text_width ))
  1385. win.SetLabel(label_new)
  1386. event.Skip()
  1387. def getInterfaceDescription( cmd ):
  1388. """
  1389. Returns the XML description for the GRASS cmd.
  1390. The DTD must be located in $GISBASE/etc/grass-interface.dtd,
  1391. otherwise the parser will not succeed.
  1392. Note: 'cmd' is given as string
  1393. """
  1394. cmdout = os.popen(cmd + r' --interface-description', "r").read()
  1395. if not len(cmdout) > 0 :
  1396. raise IOError, _("Unable to fetch interface description for command '%s'.") % cmd
  1397. p = re.compile( '(grass-interface.dtd)')
  1398. p.search( cmdout )
  1399. cmdout = p.sub(globalvar.ETCDIR + r'/grass-interface.dtd', cmdout)
  1400. return cmdout
  1401. class GrassGUIApp(wx.App):
  1402. """
  1403. Stand-alone GRASS command GUI
  1404. """
  1405. def __init__(self, grass_task):
  1406. self.grass_task = grass_task
  1407. wx.App.__init__(self, False)
  1408. def OnInit(self):
  1409. self.mf = mainFrame(parent=None, ID=wx.ID_ANY, task_description=self.grass_task)
  1410. self.mf.CentreOnScreen()
  1411. self.mf.Show(True)
  1412. self.SetTopWindow(self.mf)
  1413. return True
  1414. class GUI:
  1415. """
  1416. Parses GRASS commands when module is imported and used
  1417. from Layer Manager.
  1418. """
  1419. def __init__(self, parent=-1):
  1420. self.parent = parent
  1421. self.grass_task = None
  1422. def ParseInterface(self, cmd, parser = processTask):
  1423. """!Parse interface
  1424. @param cmd command to be parsed (given as list)
  1425. """
  1426. enc = locale.getdefaultlocale()[1]
  1427. if enc and enc.lower() not in ("utf8", "utf-8"):
  1428. tree = etree.fromstring(getInterfaceDescription(cmd[0]).decode(enc).encode("utf-8"))
  1429. else:
  1430. tree = etree.fromstring(getInterfaceDescription(cmd[0]))
  1431. return processTask(tree).GetTask()
  1432. def ParseCommand(self, cmd, gmpath=None, completed=None, parentframe=None,
  1433. show=True, modal=False):
  1434. """
  1435. Parse command
  1436. Note: cmd is given as list
  1437. If command is given with options, return validated cmd list:
  1438. * add key name for first parameter if not given
  1439. * change mapname to mapname@mapset
  1440. """
  1441. start = time.time()
  1442. dcmd_params = {}
  1443. if completed == None:
  1444. get_dcmd = None
  1445. layer = None
  1446. dcmd_params = None
  1447. else:
  1448. get_dcmd = completed[0]
  1449. layer = completed[1]
  1450. if completed[2]:
  1451. dcmd_params.update(completed[2])
  1452. self.parent = parentframe
  1453. # parse the interface decription
  1454. self.grass_task = self.ParseInterface(cmd)
  1455. # if layer parameters previously set, re-insert them into dialog
  1456. if completed is not None:
  1457. if 'params' in dcmd_params:
  1458. self.grass_task.params = dcmd_params['params']
  1459. if 'flags' in dcmd_params:
  1460. self.grass_task.flags = dcmd_params['flags']
  1461. # update parameters if needed && validate command
  1462. if len(cmd) > 1:
  1463. i = 0
  1464. cmd_validated = [cmd[0]]
  1465. for option in cmd[1:]:
  1466. if option[0] == '-': # flag
  1467. self.grass_task.set_flag(option[1], True)
  1468. cmd_validated.append(option)
  1469. else: # parameter
  1470. try:
  1471. key, value = option.split('=', 1)
  1472. except:
  1473. if i == 0: # add key name of first parameter if not given
  1474. key = self.grass_task.firstParam
  1475. value = option
  1476. else:
  1477. raise ValueError, _("Unable to parse command %s") % ' '.join(cmd)
  1478. if self.grass_task.get_param(key)['element'] in ['cell', 'vector']:
  1479. # mapname -> mapname@mapset
  1480. if '@' not in value:
  1481. value = value + '@' + grass.gisenv()['MAPSET']
  1482. self.grass_task.set_param(key, value)
  1483. cmd_validated.append(key + '=' + value)
  1484. i = i + 1
  1485. # update original command list
  1486. cmd = cmd_validated
  1487. self.mf = mainFrame(parent=self.parent, ID=wx.ID_ANY,
  1488. task_description=self.grass_task,
  1489. get_dcmd=get_dcmd, layer=layer)
  1490. if get_dcmd is not None:
  1491. # update only propwin reference
  1492. get_dcmd(dcmd=None, layer=layer, params=None,
  1493. propwin=self.mf)
  1494. self.mf.notebookpanel.OnUpdateSelection(None)
  1495. if show:
  1496. if self.parent:
  1497. self.mf.CentreOnParent()
  1498. self.mf.Show(show)
  1499. self.mf.MakeModal(modal)
  1500. else:
  1501. self.mf.OnApply(None)
  1502. return cmd
  1503. def GetCommandInputMapParamKey(self, cmd):
  1504. """!Get parameter key for input raster/vector map
  1505. @param cmd module name
  1506. @return parameter key
  1507. @return None on failure
  1508. """
  1509. # parse the interface decription
  1510. if not self.grass_task:
  1511. tree = etree.fromstring(getInterfaceDescription(cmd))
  1512. self.grass_task = processTask(tree).GetTask()
  1513. for p in self.grass_task.params:
  1514. if p.get('name', '') in ('input', 'map'):
  1515. age = p.get('age', '')
  1516. prompt = p.get('prompt', '')
  1517. element = p.get('element', '')
  1518. if age == 'old' and \
  1519. element in ('cell', 'grid3', 'vector') and \
  1520. prompt in ('raster', '3d-raster', 'vector'):
  1521. return p.get('name', None)
  1522. return None
  1523. class StaticWrapText(wx.StaticText):
  1524. """
  1525. A Static Text field that wraps its text to fit its width, enlarging its height if necessary.
  1526. """
  1527. def __init__(self, parent, id=wx.ID_ANY, label=u'', *args, **kwds):
  1528. self.originalLabel = label
  1529. wx.StaticText.__init__(self, parent, id, u'', *args, **kwds)
  1530. self.SetLabel(label)
  1531. self.Bind(wx.EVT_SIZE, self.onResize)
  1532. def SetLabel(self, label):
  1533. self.originalLabel = label
  1534. self.wrappedSize = None
  1535. #self.onResize(None)
  1536. def onResize(self, event):
  1537. if not getattr(self, "resizing", False):
  1538. self.resizing = True
  1539. newSize = self.GetSize()
  1540. if self.wrappedSize != newSize:
  1541. wx.StaticText.SetLabel(self, self.originalLabel)
  1542. self.Wrap(newSize.width)
  1543. self.wrappedSize = self.GetMinSize()
  1544. self.SetSize(self.wrappedSize)
  1545. del self.resizing
  1546. if __name__ == "__main__":
  1547. if len(sys.argv) == 1:
  1548. print _("usage: %s <grass command>") % sys.argv[0]
  1549. sys.exit()
  1550. if sys.argv[1] != 'test':
  1551. q=wx.LogNull()
  1552. GrassGUIApp(grassTask(sys.argv[1])).MainLoop()
  1553. else: #Test
  1554. # Test grassTask from within a GRASS session
  1555. if os.getenv("GISBASE") is not None:
  1556. task = grassTask( "d.vect" )
  1557. task.get_param('map')['value'] = "map_name"
  1558. task.get_flag('v')['value'] = True
  1559. task.get_param('layer')['value'] = 1
  1560. task.get_param('bcolor')['value'] = "red"
  1561. assert ' '.join( task.getCmd() ) == "d.vect -v map=map_name layer=1 bcolor=red"
  1562. # Test interface building with handmade grassTask,
  1563. # possibly outside of a GRASS session.
  1564. task = grassTask()
  1565. task.name = "TestTask"
  1566. task.description = "This is an artificial grassTask() object intended for testing purposes."
  1567. task.keywords = ["grass","test","task"]
  1568. task.params = [
  1569. {
  1570. "name" : "text",
  1571. "description" : "Descriptions go into tooltips if labels are present, like this one",
  1572. "label" : "Enter some text",
  1573. },{
  1574. "name" : "hidden_text",
  1575. "description" : "This text should not appear in the form",
  1576. "hidden" : "yes"
  1577. },{
  1578. "name" : "text_default",
  1579. "description" : "Enter text to override the default",
  1580. "default" : "default text"
  1581. },{
  1582. "name" : "text_prefilled",
  1583. "description" : "You should see a friendly welcome message here",
  1584. "value" : "hello, world"
  1585. },{
  1586. "name" : "plain_color",
  1587. "description" : "This is a plain color, and it is a compulsory parameter",
  1588. "required" : "yes",
  1589. "gisprompt" : True,
  1590. "prompt" : "color"
  1591. },{
  1592. "name" : "transparent_color",
  1593. "description" : "This color becomes transparent when set to none",
  1594. "guisection" : "tab",
  1595. "gisprompt" : True,
  1596. "prompt" : "color"
  1597. },{
  1598. "name" : "multi",
  1599. "description" : "A multiple selection",
  1600. 'default': u'red,green,blue',
  1601. 'gisprompt': False,
  1602. 'guisection': 'tab',
  1603. 'multiple': u'yes',
  1604. 'type': u'string',
  1605. 'value': '',
  1606. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other']
  1607. },{
  1608. "name" : "single",
  1609. "description" : "A single multiple-choice selection",
  1610. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  1611. "guisection" : "tab"
  1612. },{
  1613. "name" : "large_multi",
  1614. "description" : "A large multiple selection",
  1615. "gisprompt" : False,
  1616. "multiple" : "yes",
  1617. # values must be an array of strings
  1618. "values" : str2rgb.keys() + map( str, str2rgb.values() )
  1619. },{
  1620. "name" : "a_file",
  1621. "description" : "A file selector",
  1622. "gisprompt" : True,
  1623. "element" : "file"
  1624. }
  1625. ]
  1626. task.flags = [
  1627. {
  1628. "name" : "a",
  1629. "description" : "Some flag, will appear in Main since it is required",
  1630. "required" : "yes"
  1631. },{
  1632. "name" : "b",
  1633. "description" : "pre-filled flag, will appear in options since it is not required",
  1634. "value" : True
  1635. },{
  1636. "name" : "hidden_flag",
  1637. "description" : "hidden flag, should not be changeable",
  1638. "hidden" : "yes",
  1639. "value" : True
  1640. }
  1641. ]
  1642. q=wx.LogNull()
  1643. GrassGUIApp( task ).MainLoop()