menuform.py 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761
  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 # LayerTree | None
  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.ETCICONDIR, '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. if len(self.parent.GetPyData(self.layer)[0]['cmd']) < 1:
  722. self.parent.Delete(self.layer)
  723. self.Destroy()
  724. else:
  725. self.Hide()
  726. else:
  727. self.Destroy()
  728. def OnHelp(self, event):
  729. """Show manual page (switch to the 'Manual' notebook page)"""
  730. if hasattr(self.notebookpanel, "manual_tab_id"):
  731. self.notebookpanel.notebook.SetSelection(self.notebookpanel.manual_tab_id)
  732. self.notebookpanel.OnPageChange(None)
  733. event.Skip()
  734. def OnAbout(self, event):
  735. """General 'about' information"""
  736. dlg = wx.MessageDialog(self, _("This is a sample program for\n"
  737. "GRASS command interface parsing\n"
  738. "and automatic GUI building.\n%s") %(__version__),
  739. _("About wxPython GRASS GUI"), wx.OK | wx.ICON_INFORMATION)
  740. dlg.ShowModal()
  741. dlg.Destroy()
  742. def OnAboutCommand(self, event):
  743. """About command"""
  744. dlg = wx.MessageDialog(self,
  745. self.task.name+": "+self.task.description,
  746. "About " + self.task.name,
  747. wx.OK | wx.ICON_INFORMATION)
  748. dlg.ShowModal()
  749. dlg.Destroy()
  750. def createCmd(self, ignoreErrors = False):
  751. """Create command string (python list)"""
  752. return self.notebookpanel.createCmd(ignoreErrors=ignoreErrors)
  753. class cmdPanel(wx.Panel):
  754. """
  755. A panel containing a notebook dividing in tabs the different guisections of the GRASS cmd.
  756. """
  757. def __init__( self, parent, task, standalone, mainFrame, *args, **kwargs ):
  758. wx.Panel.__init__( self, parent, *args, **kwargs )
  759. self.parent = mainFrame
  760. self.task = task
  761. fontsize = 10
  762. # Determine tab layout
  763. sections = []
  764. is_section = {}
  765. not_hidden = [ p for p in self.task.params + self.task.flags if not p.get( 'hidden','no' ) == 'yes' ]
  766. for task in not_hidden:
  767. if task.get( 'required','no' ) == 'yes':
  768. # All required go into Main, even if they had defined another guisection
  769. task['guisection'] = _( 'Required' )
  770. if task.get( 'guisection','' ) == '':
  771. # Undefined guisections end up into Options
  772. task['guisection'] = _( 'Optional' )
  773. if not is_section.has_key(task['guisection']):
  774. # We do it like this to keep the original order, except for Main which goes first
  775. is_section[task['guisection']] = 1
  776. sections.append( task['guisection'] )
  777. else:
  778. is_section[ task['guisection'] ] += 1
  779. del is_section
  780. # 'Required' tab goes first, 'Optional' as the last one
  781. for (newidx,content) in [ (0,_( 'Required' )), (len(sections)-1,_('Optional')) ]:
  782. if content in sections:
  783. idx = sections.index( content )
  784. sections[idx:idx+1] = []
  785. sections[newidx:newidx] = [content]
  786. panelsizer = wx.BoxSizer(orient=wx.VERTICAL)
  787. # Build notebook
  788. nbStyle = globalvar.FNPageStyle
  789. self.notebook = FN.FlatNotebook( self, id=wx.ID_ANY, style=nbStyle)
  790. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  791. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  792. tab = {}
  793. tabsizer = {}
  794. for section in sections:
  795. tab[section] = wx.ScrolledWindow( parent=self.notebook )
  796. tab[section].SetScrollRate(10,10)
  797. tabsizer[section] = wx.BoxSizer(orient=wx.VERTICAL)
  798. self.notebook.AddPage( tab[section], text=section )
  799. # are we running from command line?
  800. ### add 'command output' tab regardless standalone dialog
  801. if self.parent.get_dcmd is None:
  802. self.goutput = goutput.GMConsole(parent=self, margin=False,
  803. pageid=self.notebook.GetPageCount())
  804. self.outpage = self.notebook.AddPage(self.goutput, text=_("Command output") )
  805. else:
  806. self.goutput = None
  807. self.manual_tab = helpPanel(parent = self.notebook, grass_command = self.task.name)
  808. self.manual_tabsizer = wx.BoxSizer(wx.VERTICAL)
  809. self.notebook.AddPage(self.manual_tab, text=_("Manual"))
  810. self.manual_tab_id = self.notebook.GetPageCount() - 1
  811. self.notebook.SetSelection(0)
  812. panelsizer.Add(item=self.notebook, proportion=1, flag=wx.EXPAND )
  813. #
  814. # flags
  815. #
  816. text_style = wx.FONTWEIGHT_NORMAL
  817. visible_flags = [ f for f in self.task.flags if not f.get( 'hidden', 'no' ) == 'yes' ]
  818. for f in visible_flags:
  819. which_sizer = tabsizer[ f['guisection'] ]
  820. which_panel = tab[ f['guisection'] ]
  821. # if label is given: description -> tooltip
  822. if f.get('label','') != '':
  823. title = text_beautify( f['label'] )
  824. tooltip = text_beautify ( f['description'] )
  825. else:
  826. title = text_beautify( f['description'] )
  827. tooltip = None
  828. chk = wx.CheckBox(parent=which_panel, label = title, style = wx.NO_BORDER)
  829. if tooltip:
  830. chk.SetToolTipString(tooltip)
  831. if 'value' in f:
  832. chk.SetValue( f['value'] )
  833. # chk.SetFont(wx.Font(pointSize=fontsize, family=wx.FONTFAMILY_DEFAULT,
  834. # style=wx.NORMAL, weight=text_style))
  835. which_sizer.Add( item=chk, proportion=0,
  836. flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=5)
  837. f['wxId'] = chk.GetId()
  838. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  839. if f['name'] in ('verbose', 'quiet'):
  840. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  841. vq = UserSettings.Get(group='cmd', key='verbosity', subkey='selection')
  842. if f['name'] == vq:
  843. chk.SetValue(True)
  844. f['value'] = True
  845. elif f['name'] == 'overwrite':
  846. chk.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
  847. f['value'] = UserSettings.Get(group='cmd', key='overwrite', subkey='enabled')
  848. #
  849. # parameters
  850. #
  851. visible_params = [ p for p in self.task.params if not p.get( 'hidden', 'no' ) == 'yes' ]
  852. for p in visible_params:
  853. which_sizer = tabsizer[ p['guisection'] ]
  854. which_panel = tab[ p['guisection'] ]
  855. # if label is given -> label and description -> tooltip
  856. # otherwise description -> lavel
  857. if p.get('label','') != '':
  858. title = text_beautify( p['label'] )
  859. tooltip = text_beautify ( p['description'] )
  860. else:
  861. title = text_beautify( p['description'] )
  862. tooltip = None
  863. txt = None
  864. # text style (required -> bold)
  865. if p.get('required','no') == 'no':
  866. text_style = wx.FONTWEIGHT_NORMAL
  867. else:
  868. text_style = wx.FONTWEIGHT_BOLD
  869. # title expansion
  870. if p.get('multiple','no') == 'yes' and len( p.get('values','') ) == 0:
  871. title = _("[multiple]") + " " + title
  872. if p.get('value','') == '' :
  873. p['value'] = p.get('default','')
  874. if ( len(p.get('values', []) ) > 0):
  875. valuelist=map( str, p.get('values',[]) )
  876. if p.get('multiple', 'no') == 'yes' and \
  877. p.get('type', '') == 'string':
  878. txt = wx.StaticBox (parent=which_panel, id=0, label=" " + title + ": ")
  879. if len(valuelist) > 6:
  880. hSizer=wx.StaticBoxSizer ( box=txt, orient=wx.VERTICAL )
  881. else:
  882. hSizer=wx.StaticBoxSizer ( box=txt, orient=wx.HORIZONTAL )
  883. isEnabled = {}
  884. # copy default values
  885. if p['value'] == '':
  886. p['value'] = p.get('default', '')
  887. for defval in p.get('value', '').split(','):
  888. isEnabled[ defval ] = 'yes'
  889. # for multi checkboxes, this is an array of all wx IDs
  890. # for each individual checkbox
  891. p[ 'wxId' ] = []
  892. for val in valuelist:
  893. chkbox = wx.CheckBox( parent=which_panel, label = text_beautify(val) )
  894. p[ 'wxId' ].append( chkbox.GetId() )
  895. if isEnabled.has_key(val):
  896. chkbox.SetValue( True )
  897. hSizer.Add( item=chkbox, proportion=0,
  898. flag=wx.ADJUST_MINSIZE | wx.ALL, border=1 )
  899. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  900. which_sizer.Add( item=hSizer, proportion=0,
  901. flag=wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border=5 )
  902. else:
  903. if len(valuelist) == 1: # -> textctrl
  904. txt = wx.StaticText(parent=which_panel,
  905. label = "%s. %s %s" % (title, _('Valid range'),
  906. str(valuelist[0]) + ':'))
  907. which_sizer.Add(item=txt, proportion=0,
  908. flag=wx.ADJUST_MINSIZE | wx.TOP | wx.RIGHT | wx.LEFT, border=5)
  909. if p.get('type','') == 'integer' and \
  910. p.get('multiple','no') == 'no':
  911. # for multiple integers use textctrl instead of spinsctrl
  912. try:
  913. minValue, maxValue = map(int, valuelist[0].split('-'))
  914. except ValueError:
  915. minValue = -1e6
  916. maxValue = 1e6
  917. txt2 = wx.SpinCtrl(parent=which_panel, id=wx.ID_ANY, size=globalvar.DIALOG_SPIN_SIZE,
  918. min=minValue, max=maxValue)
  919. else:
  920. txt2 = wx.TextCtrl(parent=which_panel, value = p.get('default',''),
  921. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  922. if p.get('value','') != '':
  923. txt2.SetValue(p['value']) # parameter previously set
  924. which_sizer.Add(item=txt2, proportion=0,
  925. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  926. p['wxId'] = txt2.GetId()
  927. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  928. else:
  929. # list of values (combo)
  930. txt = wx.StaticText(parent=which_panel, label = title + ':' )
  931. which_sizer.Add(item=txt, proportion=0,
  932. flag=wx.ADJUST_MINSIZE | wx.TOP | wx.RIGHT | wx.LEFT, border=5)
  933. cb = wx.ComboBox(parent=which_panel, id=wx.ID_ANY, value=p.get('default',''),
  934. size=globalvar.DIALOG_COMBOBOX_SIZE,
  935. choices=valuelist, style=wx.CB_DROPDOWN)
  936. if p.get('value','') != '':
  937. cb.SetValue(p['value']) # parameter previously set
  938. which_sizer.Add( item=cb, proportion=0,
  939. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  940. p['wxId'] = cb.GetId()
  941. cb.Bind( wx.EVT_COMBOBOX, self.OnSetValue)
  942. # text entry
  943. if (p.get('type','string') in ('string','integer','float')
  944. and len(p.get('values',[])) == 0
  945. and p.get('gisprompt',False) == False
  946. and p.get('prompt','') != 'color'):
  947. txt = wx.StaticText(parent=which_panel, label = title + ':' )
  948. which_sizer.Add(item=txt, proportion=0,
  949. flag=wx.RIGHT | wx.LEFT | wx.TOP | wx.EXPAND, border=5)
  950. if p.get('multiple','yes') == 'yes' or \
  951. p.get('type', 'string') in ('string', 'float') or \
  952. len(p.get('key_desc', [])) > 1:
  953. txt3 = wx.TextCtrl(parent=which_panel, value = p.get('default',''),
  954. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  955. if p.get('value','') != '':
  956. txt3.SetValue(str(p['value'])) # parameter previously set
  957. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  958. else:
  959. minValue = -1e9
  960. maxValue = 1e9
  961. txt3 = wx.SpinCtrl(parent=which_panel, value=p.get('default',''),
  962. size=globalvar.DIALOG_SPIN_SIZE,
  963. min=minValue, max=maxValue)
  964. if p.get('value','') != '':
  965. txt3.SetValue(int(p['value'])) # parameter previously set
  966. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  967. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  968. which_sizer.Add(item=txt3, proportion=0, flag=wx.BOTTOM | wx.LEFT, border=5)
  969. p['wxId'] = txt3.GetId()
  970. if p.get('type','string') == 'string' and p.get('gisprompt',False) == True:
  971. txt = wx.StaticText(parent=which_panel, label = title + ':')
  972. which_sizer.Add(item=txt, proportion=0,
  973. flag=wx.ADJUST_MINSIZE | wx.RIGHT | wx.LEFT | wx.TOP, border=5)
  974. # element selection tree combobox (maps, icons, regions, etc.)
  975. if p.get('prompt','') not in ('color', 'dbcolumn', 'dbtable') and \
  976. p.get('element', '') != 'file':
  977. if p.get('multiple','no') == 'yes':
  978. multiple = True
  979. else:
  980. multiple = False
  981. if p.get('age','') == 'new':
  982. mapsets = [grassenv.GetGRASSVariable('MAPSET'),]
  983. else:
  984. mapsets = None
  985. selection = gselect.Select(parent=which_panel, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
  986. type=p.get('element',''), multiple=multiple, mapsets=mapsets)
  987. if p.get('value','') != '':
  988. selection.SetValue(p['value']) # parameter previously set
  989. which_sizer.Add(item=selection, proportion=0,
  990. flag=wx.ADJUST_MINSIZE| wx.BOTTOM | wx.LEFT | wx.RIGHT, border=5)
  991. # A select.Select is a combobox with two children: a textctl and a popupwindow;
  992. # we target the textctl here
  993. p['wxId'] = selection.GetChildren()[0].GetId()
  994. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  995. # dbcolumn entry
  996. elif p.get('prompt','') in ('dbcolumn', 'dbtable'):
  997. if p.get('age', 'old') == 'old':
  998. style = wx.CB_SIMPLE | wx.CB_READONLY
  999. else:
  1000. style = wx.CB_SIMPLE
  1001. columns = wx.ComboBox(parent=which_panel, id=wx.ID_ANY,
  1002. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1003. style=style,
  1004. choices=[])
  1005. p['wxId'] = columns.GetId()
  1006. p['wxGetValue'] = columns.GetStringSelection
  1007. if p.get('prompt', '') == 'dbcolumn':
  1008. columns.Bind(wx.EVT_ENTER_WINDOW, self.OnDbColumn)
  1009. else:
  1010. columns.Bind(wx.EVT_ENTER_WINDOW, self.OnDbTable)
  1011. columns.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1012. which_sizer.Add(item=columns, proportion=0,
  1013. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  1014. # color entry
  1015. elif p.get('prompt','') == 'color':
  1016. # Heuristic way of finding whether transparent is allowed
  1017. handle_transparency = 'none' in title
  1018. default_color = (200,200,200)
  1019. label_color = _("Select Color")
  1020. if p.get('default','') != '':
  1021. default_color, label_color = color_resolve( p['default'] )
  1022. if p.get('value','') != '': # parameter previously set
  1023. default_color, label_color = color_resolve( p['value'] )
  1024. if handle_transparency:
  1025. this_sizer = wx.BoxSizer(orient=wx.HORIZONTAL )
  1026. else:
  1027. this_sizer = which_sizer
  1028. btn_colour = csel.ColourSelect(parent=which_panel, id=wx.ID_ANY,
  1029. label=label_color, colour=default_color,
  1030. pos=wx.DefaultPosition, size=(150,-1) )
  1031. this_sizer.Add(item=btn_colour, proportion=0,
  1032. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  1033. # For color selectors, this is a two-member array, holding the IDs of
  1034. # the selector proper and either a "transparent" button or None
  1035. p['wxId'] = [btn_colour.GetId(),]
  1036. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange )
  1037. if handle_transparency:
  1038. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent") )
  1039. if p.get('value','') != '' and p.get('value',[''])[0] == "none":
  1040. none_check.SetValue(True)
  1041. else:
  1042. none_check.SetValue(False)
  1043. # none_check.SetFont( wx.Font( fontsize, wx.FONTFAMILY_DEFAULT, wx.NORMAL, text_style, 0, ''))
  1044. this_sizer.Add(item=none_check, proportion=0,
  1045. flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border=5)
  1046. which_sizer.Add( this_sizer )
  1047. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1048. p['wxId'].append( none_check.GetId() )
  1049. else:
  1050. p['wxId'].append(None)
  1051. # file selector
  1052. elif p.get('prompt','') != 'color' and p.get('element', '') == 'file':
  1053. fbb = filebrowse.FileBrowseButton(parent=which_panel, id=wx.ID_ANY,
  1054. size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
  1055. dialogTitle=_('Choose %s') % \
  1056. p.get('description',_('File')),
  1057. buttonText=_('Browse'),
  1058. startDirectory=os.getcwd(), fileMode=0,
  1059. changeCallback=self.OnSetValue)
  1060. if p.get('value','') != '':
  1061. fbb.SetValue(p['value']) # parameter previously set
  1062. which_sizer.Add(item=fbb, proportion=0,
  1063. flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.TOP | wx.RIGHT, border=-3)
  1064. # A file browse button is a combobox with two children:
  1065. # a textctl and a button;
  1066. # we have to target the button here
  1067. p['wxId'] = fbb.GetChildren()[1].GetId()
  1068. if txt is not None:
  1069. # txt.SetFont( wx.Font( fontsize, wx.FONTFAMILY_DEFAULT, wx.NORMAL, text_style, 0, ''))
  1070. # create tooltip if given
  1071. if len(p['values_desc']) > 0:
  1072. if tooltip:
  1073. tooltip += 2 * os.linesep
  1074. else:
  1075. tooltip = ''
  1076. if len(p['values']) == len(p['values_desc']):
  1077. for i in range(len(p['values'])):
  1078. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1079. tooltip.strip(os.linesep)
  1080. if tooltip:
  1081. txt.SetToolTipString(tooltip)
  1082. #
  1083. # determine panel size
  1084. #
  1085. maxsizes = (0,0)
  1086. for section in sections:
  1087. # tabsizer[section].SetSizeHints( tab[section] )
  1088. #tab[section].SetAutoLayout(True)
  1089. tab[section].SetSizer( tabsizer[section] )
  1090. tabsizer[section].Fit( tab[section] )
  1091. tab[section].Layout()
  1092. minsecsizes = tabsizer[section].GetSize()
  1093. maxsizes = map( lambda x: max( maxsizes[x], minsecsizes[x] ), (0,1) )
  1094. # TODO: be less arbitrary with these 600
  1095. self.panelMinHeight = 100
  1096. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1097. for section in sections:
  1098. tab[section].SetMinSize( (self.constrained_size[0], self.panelMinHeight) )
  1099. # tab[section].SetMinSize( constrained_size )
  1100. if self.manual_tab.Ok:
  1101. self.manual_tab.SetMinSize( (self.constrained_size[0], self.panelMinHeight) )
  1102. # manual_tab.SetMinSize( constrained_size )
  1103. self.SetSizer( panelsizer )
  1104. panelsizer.Fit(self.notebook)
  1105. self.hasMain = tab.has_key( _('Required') ) # publish, to enclosing Frame for instance
  1106. def OnVerbosity(self, event):
  1107. """Verbosity level changed"""
  1108. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'])
  1109. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'])
  1110. if event.IsChecked():
  1111. if event.GetId() == verbose.GetId():
  1112. if quiet.IsChecked():
  1113. quiet.SetValue(False)
  1114. self.task.get_flag('quiet')['value'] = False
  1115. else:
  1116. if verbose.IsChecked():
  1117. verbose.SetValue(False)
  1118. self.task.get_flag('verbose')['value'] = False
  1119. event.Skip()
  1120. def OnPageChange(self, event):
  1121. if not event:
  1122. sel = self.notebook.GetSelection()
  1123. else:
  1124. sel = event.GetSelection()
  1125. if hasattr(self, "manual_tab_id") and \
  1126. sel == self.manual_tab_id:
  1127. # calling LoadPage() is strangely time-consuming (only first call)
  1128. # FIXME: move to helpPage.__init__()
  1129. if not self.manual_tab.Ok:
  1130. wx.Yield()
  1131. self.manual_tab.LoadPage(self.manual_tab.fspath + self.task.name + ".html")
  1132. self.manual_tab.Ok = True
  1133. self.Layout()
  1134. def OnColorChange( self, event ):
  1135. myId = event.GetId()
  1136. for p in self.task.params:
  1137. if 'wxId' in p and type( p['wxId'] ) == type( [] ) and myId in p['wxId']:
  1138. has_button = p['wxId'][1] is not None
  1139. if has_button and wx.FindWindowById( p['wxId'][1] ).GetValue() == True:
  1140. p[ 'value' ] = 'none'
  1141. else:
  1142. colorchooser = wx.FindWindowById( p['wxId'][0] )
  1143. new_color = colorchooser.GetValue()[:]
  1144. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1145. # under wx2.8.1
  1146. new_label = rgb2str.get( new_color, ':'.join(map(str,new_color)) )
  1147. colorchooser.SetLabel( new_label )
  1148. colorchooser.SetColour( new_color )
  1149. colorchooser.Refresh()
  1150. p[ 'value' ] = colorchooser.GetLabel()
  1151. self.OnUpdateValues()
  1152. def OnUpdateValues(self):
  1153. """
  1154. If we were part of a richer interface, report back the current command being built.
  1155. This method should be set by the parent of this panel if needed. It's a hook, actually.
  1156. Beware of what is 'self' in the method def, though. It will be called with no arguments.
  1157. """
  1158. pass
  1159. def OnCheckBoxMulti(self, event):
  1160. """
  1161. Fill the values as a ','-separated string according to current status of the checkboxes.
  1162. """
  1163. me = event.GetId()
  1164. theParam = None
  1165. for p in self.task.params:
  1166. if 'wxId' in p and type( p['wxId'] ) == type( [] ) and me in p['wxId']:
  1167. theParam = p
  1168. myIndex = p['wxId'].index( me )
  1169. # Unpack current value list
  1170. currentValues = {}
  1171. for isThere in theParam.get('value', '').split(','):
  1172. currentValues[isThere] = 1
  1173. theValue = theParam['values'][myIndex]
  1174. if event.Checked():
  1175. currentValues[ theValue ] = 1
  1176. else:
  1177. del currentValues[ theValue ]
  1178. # Keep the original order, so that some defaults may be recovered
  1179. currentValueList = []
  1180. for v in theParam['values']:
  1181. if currentValues.has_key(v):
  1182. currentValueList.append( v )
  1183. # Pack it back
  1184. theParam['value'] = ','.join( currentValueList )
  1185. self.OnUpdateValues()
  1186. def OnSetValue(self, event):
  1187. """
  1188. Retrieve the widget value and set the task value field accordingly.
  1189. Use for widgets that have a proper GetValue() method, i.e. not for selectors.
  1190. """
  1191. myId = event.GetId()
  1192. me = wx.FindWindowById( myId )
  1193. for porf in self.task.params + self.task.flags:
  1194. if 'wxId' in porf and type( porf[ 'wxId' ] ) == type( 1 ) and porf['wxId'] == myId:
  1195. if porf.has_key('wxGetValue') and porf['wxGetValue']:
  1196. porf['value'] = porf['wxGetValue']()
  1197. else:
  1198. porf['value'] = me.GetValue()
  1199. self.OnUpdateValues()
  1200. event.Skip()
  1201. def OnDbColumn(self, event):
  1202. """Get list of table columns"""
  1203. choices = []
  1204. p = self.task.get_param('table', raiseError=False)
  1205. if p and p.get('prompt', '') == 'dbtable':
  1206. cmd = ['db.columns',
  1207. 'table=%s' % p.get('value')]
  1208. try:
  1209. choices = gcmd.Command(cmd).ReadStdOutput()
  1210. except gcmd.CmdError:
  1211. choices = []
  1212. if not p:
  1213. p = self.task.get_param('map', raiseError=False)
  1214. if not p:
  1215. p = self.task.get_param('input', raiseError=False)
  1216. if p:
  1217. mapName = utils.GetLayerNameFromCmd(self.task.getCmd(ignoreErrors=True))
  1218. if mapName != _('<required>'):
  1219. layer = 1
  1220. p = self.task.get_param('layer')
  1221. if p:
  1222. value = p.get('value', '1')
  1223. if value:
  1224. layer = int(value)
  1225. cmd = ['v.info',
  1226. 'map=%s' % mapName,
  1227. 'layer=%d' % layer,
  1228. '-c', '--q']
  1229. try:
  1230. for line in gcmd.Command(cmd).ReadStdOutput():
  1231. type, name = line.split('|')
  1232. choices.append(name.strip())
  1233. except gcmd.CmdError:
  1234. choices = []
  1235. win = self.FindWindowById(event.GetId())
  1236. win.SetItems(choices)
  1237. if len(choices) < 1:
  1238. win.SetValue('')
  1239. event.Skip()
  1240. def OnDbTable(self, event):
  1241. """Get list of tables"""
  1242. # TODO: add driver/database
  1243. cmd = ['db.tables',
  1244. '-p', '--q']
  1245. for p in self.task.params:
  1246. if p.get('name', '') == 'driver' and \
  1247. len(p.get('value', '')) > 0:
  1248. cmd.append('driver=%s' % p.get('value'))
  1249. elif p.get('name', '') == 'database' and \
  1250. len(p.get('value', '')) > 0:
  1251. cmd.append('database=%s' % p.get('value'))
  1252. try:
  1253. choices = gcmd.Command(cmd).ReadStdOutput()
  1254. except gcmd.CmdError:
  1255. choices = []
  1256. win = self.FindWindowById(event.GetId())
  1257. win.SetItems(choices)
  1258. if len(choices) < 1:
  1259. win.SetValue('')
  1260. event.Skip()
  1261. def createCmd( self, ignoreErrors = False ):
  1262. """
  1263. Produce a command line string (list) or feeding into GRASS.
  1264. If ignoreErrors==True then it will return whatever has been
  1265. built so far, even though it would not be a correct command
  1266. for GRASS.
  1267. """
  1268. try:
  1269. cmd = self.task.getCmd( ignoreErrors=ignoreErrors )
  1270. except ValueError, err:
  1271. dlg = wx.MessageDialog(parent=self,
  1272. message=str(err),
  1273. caption=_("Error in %s") % self.task.name,
  1274. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1275. dlg.ShowModal()
  1276. dlg.Destroy()
  1277. cmd = None
  1278. return cmd
  1279. def getInterfaceDescription( cmd ):
  1280. """
  1281. Returns the XML description for the GRASS cmd.
  1282. The DTD must be located in $GISBASE/etc/grass-interface.dtd,
  1283. otherwise the parser will not succeed.
  1284. Note: 'cmd' is given as string
  1285. """
  1286. cmdout = os.popen(cmd + r' --interface-description', "r").read()
  1287. if not len(cmdout) > 0 :
  1288. raise IOError, _("Unable to fetch interface description for command '%s'.") % cmd
  1289. p = re.compile( '(grass-interface.dtd)')
  1290. p.search( cmdout )
  1291. cmdout = p.sub(globalvar.ETCDIR + r'/grass-interface.dtd', cmdout)
  1292. return cmdout
  1293. class GrassGUIApp(wx.App):
  1294. """
  1295. Stand-alone GRASS command GUI
  1296. """
  1297. def __init__(self, grass_task):
  1298. self.grass_task = grass_task
  1299. wx.App.__init__(self, False)
  1300. def OnInit(self):
  1301. self.mf = mainFrame(parent=None, ID=wx.ID_ANY, task_description=self.grass_task)
  1302. self.mf.CentreOnScreen()
  1303. self.mf.Show(True)
  1304. self.SetTopWindow(self.mf)
  1305. # print >> sys.stderr, time.time() - start
  1306. return True
  1307. class GUI:
  1308. """
  1309. Parses GRASS commands when module is imported and used
  1310. from Layer Manager.
  1311. """
  1312. def __init__(self, parent=-1):
  1313. self.parent = parent
  1314. self.grass_task = None
  1315. def ParseCommand(self, cmd, gmpath=None, completed=None, parentframe=None, show=True, modal=False):
  1316. """
  1317. Parse command
  1318. Note: cmd is given as list
  1319. If command is given with options, return validated cmd list:
  1320. * add key name for first parameter if not given
  1321. * change mapname to mapname@mapset
  1322. """
  1323. start = time.time()
  1324. dcmd_params = {}
  1325. if completed == None:
  1326. get_dcmd = None
  1327. layer = None
  1328. dcmd_params = None
  1329. else:
  1330. get_dcmd = completed[0]
  1331. layer = completed[1]
  1332. if completed[2]:
  1333. dcmd_params.update(completed[2])
  1334. self.parent = parentframe
  1335. # parse the interface decription
  1336. self.grass_task = grassTask()
  1337. handler = processTask(self.grass_task)
  1338. xml.sax.parseString( getInterfaceDescription(cmd[0]), handler )
  1339. # if layer parameters previously set, re-insert them into dialog
  1340. if completed is not None:
  1341. if 'params' in dcmd_params:
  1342. self.grass_task.params = dcmd_params['params']
  1343. if 'flags' in dcmd_params:
  1344. self.grass_task.flags = dcmd_params['flags']
  1345. # update parameters if needed && validate command
  1346. if len(cmd) > 1:
  1347. i = 0
  1348. cmd_validated = [cmd[0]]
  1349. for option in cmd[1:]:
  1350. if option[0] == '-': # flag
  1351. self.grass_task.set_flag(option[1], True)
  1352. cmd_validated.append(option)
  1353. else: # parameter
  1354. try:
  1355. key, value = option.split('=', 1)
  1356. except:
  1357. if i == 0: # add key name of first parameter if not given
  1358. key = self.grass_task.firstParam
  1359. value = option
  1360. else:
  1361. raise ValueError, _("Unable to parse command %s") % ' '.join(cmd)
  1362. if self.grass_task.get_param(key)['element'] in ['cell', 'vector']:
  1363. # mapname -> mapname@mapset
  1364. if '@' not in value:
  1365. value = value + '@' + grassenv.GetGRASSVariable('MAPSET')
  1366. self.grass_task.set_param(key, value)
  1367. cmd_validated.append(key + '=' + value)
  1368. i = i + 1
  1369. # update original command list
  1370. cmd = cmd_validated
  1371. self.mf = mainFrame(parent=self.parent, ID=wx.ID_ANY,
  1372. task_description=self.grass_task,
  1373. get_dcmd=get_dcmd, layer=layer)
  1374. if get_dcmd is not None:
  1375. # update only propwin reference
  1376. get_dcmd(dcmd=None, layer=layer, params=None,
  1377. propwin=self.mf)
  1378. if show:
  1379. if self.parent:
  1380. self.mf.CentreOnParent()
  1381. self.mf.Show(show)
  1382. self.mf.MakeModal(modal)
  1383. else:
  1384. self.mf.OnApply(None)
  1385. # print >> sys.stderr, time.time() - start
  1386. return cmd
  1387. def GetCommandInputMapParamKey(self, cmd):
  1388. """Get parameter key for input raster/vector map
  1389. @param cmd module name
  1390. @return parameter key
  1391. @return None on failure
  1392. """
  1393. # parse the interface decription
  1394. if not self.grass_task:
  1395. self.grass_task = grassTask()
  1396. handler = processTask(self.grass_task)
  1397. xml.sax.parseString(getInterfaceDescription(cmd), handler)
  1398. for p in self.grass_task.params:
  1399. if p.get('name', '') in ('input', 'map'):
  1400. age = p.get('age', '')
  1401. prompt = p.get('prompt', '')
  1402. element = p.get('element', '')
  1403. if age == 'old' and \
  1404. element in ('cell', 'grid3', 'vector') and \
  1405. prompt in ('raster', '3d-raster', 'vector'):
  1406. return p.get('name', None)
  1407. return None
  1408. class StaticWrapText(wx.StaticText):
  1409. """
  1410. A Static Text field that wraps its text to fit its width, enlarging its height if necessary.
  1411. """
  1412. def __init__(self, parent, id=wx.ID_ANY, label=u'', *args, **kwds):
  1413. self.originalLabel = label
  1414. wx.StaticText.__init__(self, parent, id, u'', *args, **kwds)
  1415. self.SetLabel(label)
  1416. self.Bind(wx.EVT_SIZE, self.onResize)
  1417. def SetLabel(self, label):
  1418. self.originalLabel = label
  1419. self.wrappedSize = None
  1420. #self.onResize(None)
  1421. def onResize(self, event):
  1422. if not getattr(self, "resizing", False):
  1423. self.resizing = True
  1424. newSize = self.GetSize()
  1425. if self.wrappedSize != newSize:
  1426. wx.StaticText.SetLabel(self, self.originalLabel)
  1427. self.Wrap(newSize.width)
  1428. self.wrappedSize = self.GetMinSize()
  1429. self.SetSize(self.wrappedSize)
  1430. del self.resizing
  1431. if __name__ == "__main__":
  1432. if len(sys.argv) == 1:
  1433. print _("usage: %s <grass command>") % sys.argv[0]
  1434. sys.exit()
  1435. if sys.argv[1] != 'test':
  1436. q=wx.LogNull()
  1437. GrassGUIApp( grassTask( sys.argv[1] ) ).MainLoop()
  1438. else: #Test
  1439. # Test grassTask from within a GRASS session
  1440. if os.getenv("GISBASE") is not None:
  1441. task = grassTask( "d.vect" )
  1442. task.get_param('map')['value'] = "map_name"
  1443. task.get_flag('v')['value'] = True
  1444. task.get_param('layer')['value'] = 1
  1445. task.get_param('bcolor')['value'] = "red"
  1446. assert ' '.join( task.getCmd() ) == "d.vect -v map=map_name layer=1 bcolor=red"
  1447. # Test interface building with handmade grassTask,
  1448. # possibly outside of a GRASS session.
  1449. task = grassTask()
  1450. task.name = "TestTask"
  1451. task.description = "This is an artificial grassTask() object intended for testing purposes."
  1452. task.keywords = ["grass","test","task"]
  1453. task.params = [
  1454. {
  1455. "name" : "text",
  1456. "description" : "Descriptions go into tooltips if labels are present, like this one",
  1457. "label" : "Enter some text",
  1458. },{
  1459. "name" : "hidden_text",
  1460. "description" : "This text should not appear in the form",
  1461. "hidden" : "yes"
  1462. },{
  1463. "name" : "text_default",
  1464. "description" : "Enter text to override the default",
  1465. "default" : "default text"
  1466. },{
  1467. "name" : "text_prefilled",
  1468. "description" : "You should see a friendly welcome message here",
  1469. "value" : "hello, world"
  1470. },{
  1471. "name" : "plain_color",
  1472. "description" : "This is a plain color, and it is a compulsory parameter",
  1473. "required" : "yes",
  1474. "gisprompt" : True,
  1475. "prompt" : "color"
  1476. },{
  1477. "name" : "transparent_color",
  1478. "description" : "This color becomes transparent when set to none",
  1479. "guisection" : "tab",
  1480. "gisprompt" : True,
  1481. "prompt" : "color"
  1482. },{
  1483. "name" : "multi",
  1484. "description" : "A multiple selection",
  1485. 'default': u'red,green,blue',
  1486. 'gisprompt': False,
  1487. 'guisection': 'tab',
  1488. 'multiple': u'yes',
  1489. 'type': u'string',
  1490. 'value': '',
  1491. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other']
  1492. },{
  1493. "name" : "single",
  1494. "description" : "A single multiple-choice selection",
  1495. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  1496. "guisection" : "tab"
  1497. },{
  1498. "name" : "large_multi",
  1499. "description" : "A large multiple selection",
  1500. "gisprompt" : False,
  1501. "multiple" : "yes",
  1502. # values must be an array of strings
  1503. "values" : str2rgb.keys() + map( str, str2rgb.values() )
  1504. },{
  1505. "name" : "a_file",
  1506. "description" : "A file selector",
  1507. "gisprompt" : True,
  1508. "element" : "file"
  1509. }
  1510. ]
  1511. task.flags = [
  1512. {
  1513. "name" : "a",
  1514. "description" : "Some flag, will appear in Main since it is required",
  1515. "required" : "yes"
  1516. },{
  1517. "name" : "b",
  1518. "description" : "pre-filled flag, will appear in options since it is not required",
  1519. "value" : True
  1520. },{
  1521. "name" : "hidden_flag",
  1522. "description" : "hidden flag, should not be changeable",
  1523. "hidden" : "yes",
  1524. "value" : True
  1525. }
  1526. ]
  1527. q=wx.LogNull()
  1528. GrassGUIApp( task ).MainLoop()