menuform.py 78 KB

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