menuform.py 80 KB

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