menuform.py 76 KB

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