menuform.py 79 KB

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