menuform.py 69 KB

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