menuform.py 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780
  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. import sys
  37. import re
  38. import string
  39. import textwrap
  40. import os
  41. from os import system
  42. import time
  43. start = time.time()
  44. ### i18N
  45. import gettext
  46. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True)
  47. import globalvar
  48. globalvar.CheckForWx()
  49. import wx
  50. import wx.lib.flatnotebook as FN
  51. import wx.lib.colourselect as csel
  52. import wx.lib.filebrowsebutton as filebrowse
  53. from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
  54. import wx.html
  55. # Do the python 2.0 standard xml thing and map it on the old names
  56. import xml.sax
  57. import xml.sax.handler
  58. HandlerBase=xml.sax.handler.ContentHandler
  59. from xml.sax import make_parser
  60. import utils
  61. gisbase = os.getenv("GISBASE")
  62. if gisbase is None:
  63. print >>sys.stderr, "We don't seem to be properly installed, or we are being run outside GRASS. Expect glitches."
  64. gisbase = os.path.join(os.path.dirname( sys.argv[0] ), os.path.pardir)
  65. wxbase = gisbase
  66. else:
  67. wxbase = os.path.join(globalvar.ETCWXDIR)
  68. sys.path.append( wxbase)
  69. imagepath = os.path.join(wxbase, "images")
  70. sys.path.append(imagepath)
  71. import grassenv
  72. import gselect
  73. import gcmd
  74. import goutput
  75. import utils
  76. from preferences import globalSettings as UserSettings
  77. try:
  78. import subprocess
  79. except:
  80. from compat import subprocess
  81. utils.reexec_with_pythonw()
  82. # From lib/gis/col_str.c, except purple which is mentioned
  83. # there but not given RGB values
  84. str2rgb = {'aqua': (100, 128, 255),
  85. 'black': (0, 0, 0),
  86. 'blue': (0, 0, 255),
  87. 'brown': (180, 77, 25),
  88. 'cyan': (0, 255, 255),
  89. 'gray': (128, 128, 128),
  90. 'green': (0, 255, 0),
  91. 'grey': (128, 128, 128),
  92. 'indigo': (0, 128, 255),
  93. 'magenta': (255, 0, 255),
  94. 'orange': (255, 128, 0),
  95. 'purple': (128, 0, 128),
  96. 'red': (255, 0, 0),
  97. 'violet': (128, 0, 255),
  98. 'white': (255, 255, 255),
  99. 'yellow': (255, 255, 0)}
  100. rgb2str = {}
  101. for (s,r) in str2rgb.items():
  102. rgb2str[ r ] = s
  103. def color_resolve(color):
  104. if len(color)>0 and color[0] in "0123456789":
  105. rgb = tuple(map(int,color.split( ':' )))
  106. label = color
  107. else:
  108. # Convert color names to RGB
  109. try:
  110. rgb = str2rgb[ color ]
  111. label = color
  112. except KeyError:
  113. rgb = (200,200,200)
  114. label = _('Select Color')
  115. return (rgb, label)
  116. def normalize_whitespace(text):
  117. """Remove redundant whitespace from a string"""
  118. return string.join( string.split(text), ' ')
  119. def text_beautify( someString , width=70):
  120. """
  121. Make really long texts shorter, clean up whitespace and
  122. remove trailing punctuation.
  123. """
  124. if width > 0:
  125. return escape_ampersand( string.strip(
  126. os.linesep.join( textwrap.wrap( normalize_whitespace(someString), width ) ),
  127. ".,;:" ) )
  128. else:
  129. return escape_ampersand( string.strip(normalize_whitespace(someString ), ".,;:" ))
  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.replace('.py', '').replace('.sh', '')
  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. guisizer = wx.BoxSizer(wx.VERTICAL)
  505. # set apropriate output window
  506. if self.parent:
  507. self.standalone = False
  508. else:
  509. self.standalone = True
  510. # try:
  511. # self.goutput = self.parent.GetLogWindow()
  512. # except:
  513. # self.goutput = None
  514. # logo+description
  515. topsizer = wx.BoxSizer(wx.HORIZONTAL)
  516. # GRASS logo
  517. self.logo = wx.StaticBitmap(parent=self.panel,
  518. bitmap=wx.Bitmap(name=os.path.join(imagepath,
  519. 'grass_form.png'),
  520. type=wx.BITMAP_TYPE_PNG))
  521. topsizer.Add (item=self.logo, proportion=0, border=3,
  522. flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
  523. guisizer.Add (item=topsizer, proportion=0, flag=wx.EXPAND)
  524. # notebooks
  525. self.notebookpanel = cmdPanel (parent=self.panel, task=self.task, standalone=self.standalone,
  526. mainFrame=self)
  527. ### add 'command output' tab also for dialog open from menu
  528. # if self.standalone:
  529. self.goutput = self.notebookpanel.goutput
  530. self.notebookpanel.OnUpdateValues = self.updateValuesHook
  531. guisizer.Add (item=self.notebookpanel, proportion=1, flag=wx.EXPAND)
  532. # status bar
  533. status_text = _("Enter parameters for ") + self.task.name
  534. if self.notebookpanel.hasMain:
  535. # We have to wait for the notebookpanel to be filled in order
  536. # to know if there actually is a Main tab
  537. status_text += _(" (those in bold typeface are required)")
  538. try:
  539. self.task.getCmd()
  540. self.updateValuesHook()
  541. except ValueError:
  542. self.SetStatusText( status_text )
  543. # buttons
  544. btnsizer = wx.BoxSizer(orient=wx.HORIZONTAL)
  545. # cancel
  546. self.btn_cancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
  547. self.btn_cancel.SetToolTipString(_("Cancel the command settings and ignore changes"))
  548. btnsizer.Add(item=self.btn_cancel, proportion=0, flag=wx.ALL | wx.ALIGN_CENTER, border=10)
  549. self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  550. # help
  551. self.btn_help = wx.Button(parent=self.panel, id=wx.ID_HELP)
  552. self.btn_help.SetToolTipString(_("Show manual page of the command"))
  553. self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
  554. if self.get_dcmd is not None: # A callback has been set up
  555. btn_apply = wx.Button(parent=self.panel, id=wx.ID_APPLY)
  556. btn_ok = wx.Button(parent=self.panel, id=wx.ID_OK)
  557. btn_ok.SetDefault()
  558. btnsizer.Add(item=btn_apply, proportion=0,
  559. flag=wx.ALL | wx.ALIGN_CENTER,
  560. border=10)
  561. btnsizer.Add(item=btn_ok, proportion=0,
  562. flag=wx.ALL | wx.ALIGN_CENTER,
  563. border=10)
  564. btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
  565. btn_ok.Bind(wx.EVT_BUTTON, self.OnOK)
  566. else: # We're standalone
  567. # run
  568. self.btn_run = wx.Button(parent=self.panel, id=wx.ID_OK, label= _("&Run"))
  569. self.btn_run.SetToolTipString(_("Run the command"))
  570. self.btn_run.SetDefault()
  571. # abort
  572. self.btn_abort = wx.Button(parent=self.panel, id=wx.ID_STOP)
  573. self.btn_abort.SetToolTipString(_("Abort the running command"))
  574. self.btn_abort.Enable(False)
  575. # copy
  576. self.btn_clipboard = wx.Button(parent=self.panel, id=wx.ID_COPY)
  577. self.btn_clipboard.SetToolTipString(_("Copy the current command string to the clipboard"))
  578. btnsizer.Add(item=self.btn_abort, proportion=0,
  579. flag=wx.ALL | wx.ALIGN_CENTER,
  580. border=10)
  581. btnsizer.Add(item=self.btn_run, proportion=0,
  582. flag=wx.ALL | wx.ALIGN_CENTER,
  583. border=10)
  584. btnsizer.Add(item=self.btn_clipboard, proportion=0,
  585. flag=wx.ALL | wx.ALIGN_CENTER,
  586. border=10)
  587. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  588. self.btn_abort.Bind(wx.EVT_BUTTON, self.OnAbort)
  589. self.btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
  590. # add help button
  591. btnsizer.Add(item=self.btn_help, proportion=0, flag=wx.ALL | wx.ALIGN_CENTER, border=10)
  592. guisizer.Add(item=btnsizer, proportion=0, flag=wx.ALIGN_CENTER)
  593. if self.parent is not None:
  594. self.outputType = None
  595. for p in self.task.params:
  596. if p.get('name', '') == 'output':
  597. self.outputType = p.get('prompt', None)
  598. break
  599. if self.outputType in ('raster', 'vector', '3d-raster'):
  600. # add newly created map into layer tree
  601. self.addbox = wx.CheckBox(parent=self.panel,
  602. label=_('Add created map into layer tree'), style = wx.NO_BORDER)
  603. self.addbox.SetValue(UserSettings.Get(group='cmd', key='addNewLayer', subkey='enabled'))
  604. guisizer.Add(item=self.addbox, proportion=0,
  605. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  606. border=5)
  607. if self.get_dcmd is None:
  608. # close dialog when command is terminated
  609. self.closebox = wx.CheckBox(parent=self.panel,
  610. label=_('Close dialog on finish'), style = wx.NO_BORDER)
  611. self.closebox.SetValue(UserSettings.Get(group='cmd', key='closeDlg', subkey='enabled'))
  612. guisizer.Add(item=self.closebox, proportion=0,
  613. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  614. border=5)
  615. self.Bind(wx.EVT_CLOSE, self.OnCancel)
  616. #constrained_size = self.notebookpanel.GetSize()
  617. # 80 takes the tabbar into account
  618. #self.notebookpanel.SetSize( (constrained_size[0] + 25, constrained_size[1]) )
  619. #self.notebookpanel.Layout()
  620. #
  621. # put module description
  622. #
  623. if self.task.label != '':
  624. module_desc = self.task.label + os.linesep + self.task.description
  625. else:
  626. module_desc = self.task.description
  627. self.description = StaticWrapText (parent=self.panel,
  628. label=module_desc)
  629. topsizer.Add (item=self.description, proportion=1, border=5,
  630. flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  631. #
  632. # do layout
  633. #
  634. guisizer.SetSizeHints(self.panel)
  635. # called automatically by SetSizer()
  636. self.panel.SetAutoLayout(True)
  637. self.panel.SetSizer(guisizer)
  638. guisizer.Fit(self.panel)
  639. sizeFrame = self.GetBestSize()
  640. self.SetMinSize(sizeFrame)
  641. self.SetSize((sizeFrame[0], sizeFrame[1] +
  642. self.notebookpanel.constrained_size[1] -
  643. self.notebookpanel.panelMinHeight))
  644. self.Layout()
  645. def updateValuesHook(self):
  646. """Update status bar data"""
  647. self.SetStatusText(' '.join(self.notebookpanel.createCmd(ignoreErrors = True)) )
  648. def OnOK(self, event):
  649. """OK button pressed"""
  650. cmd = self.OnApply(event)
  651. if cmd is not None and self.get_dcmd is not None:
  652. self.OnCancel(event)
  653. def OnApply(self, event):
  654. """Apply the command"""
  655. cmd = self.createCmd()
  656. if cmd is not None and self.get_dcmd is not None:
  657. # return d.* command to layer tree for rendering
  658. self.get_dcmd(cmd, self.layer, {"params": self.task.params,
  659. "flags" :self.task.flags},
  660. self)
  661. # echo d.* command to output console
  662. # self.parent.writeDCommand(cmd)
  663. return cmd
  664. def OnRun(self, event):
  665. """Run the command"""
  666. cmd = self.createCmd()
  667. if cmd == [] or cmd == None:
  668. return
  669. if cmd[0][0:2] != "d.":
  670. # Send any non-display command to parent window (probably wxgui.py)
  671. # put to parents
  672. # switch to 'Command output'
  673. if self.notebookpanel.notebook.GetSelection() != self.notebookpanel.goutputId:
  674. self.notebookpanel.notebook.SetSelection(self.notebookpanel.goutputId)
  675. try:
  676. self.goutput.RunCmd(cmd)
  677. except AttributeError,e:
  678. print >> sys.stderr, "%s: Propably not running in wxgui.py session?" % (e)
  679. print >> sys.stderr, "parent window is: %s" % (str(self.parent))
  680. # Send any other command to the shell.
  681. else:
  682. gcmd.Command(cmd)
  683. # update buttons status
  684. for btn in (self.btn_run,
  685. self.btn_cancel,
  686. self.btn_clipboard,
  687. self.btn_help):
  688. btn.Enable(False)
  689. self.btn_abort.Enable(True)
  690. def OnAbort(self, event):
  691. """Abort running command"""
  692. event = goutput.wxCmdAbort(aborted=True)
  693. wx.PostEvent(self.goutput, event)
  694. def OnCopy(self, event):
  695. """Copy the command"""
  696. cmddata = wx.TextDataObject()
  697. # list -> string
  698. cmdstring = ' '.join(self.createCmd(ignoreErrors=True))
  699. cmddata.SetText(cmdstring)
  700. if wx.TheClipboard.Open():
  701. wx.TheClipboard.UsePrimarySelection(True)
  702. wx.TheClipboard.SetData(cmddata)
  703. wx.TheClipboard.Close()
  704. self.SetStatusText( _("'%s' copied to clipboard") % \
  705. (cmdstring))
  706. def OnCancel(self, event):
  707. """Cancel button pressed"""
  708. self.MakeModal(False)
  709. if self.get_dcmd:
  710. # display decorations and
  711. # pressing OK or cancel after setting layer properties
  712. if self.task.name in ['d.barscale','d.legend','d.histogram'] \
  713. or len(self.parent.GetPyData(self.layer)[0]['cmd']) >= 1:
  714. self.Hide()
  715. # canceled layer with nothing set
  716. elif len(self.parent.GetPyData(self.layer)[0]['cmd']) < 1:
  717. self.parent.Delete(self.layer)
  718. self.Destroy()
  719. else:
  720. # cancel for non-display commands
  721. self.Destroy()
  722. def OnHelp(self, event):
  723. """Show manual page (switch to the 'Manual' notebook page)"""
  724. if hasattr(self.notebookpanel, "manual_tab_id"):
  725. self.notebookpanel.notebook.SetSelection(self.notebookpanel.manual_tab_id)
  726. self.notebookpanel.OnPageChange(None)
  727. event.Skip()
  728. def createCmd(self, ignoreErrors = False):
  729. """Create command string (python list)"""
  730. return self.notebookpanel.createCmd(ignoreErrors=ignoreErrors)
  731. class cmdPanel(wx.Panel):
  732. """
  733. A panel containing a notebook dividing in tabs the different guisections of the GRASS cmd.
  734. """
  735. def __init__( self, parent, task, standalone, mainFrame, *args, **kwargs ):
  736. wx.Panel.__init__( self, parent, *args, **kwargs )
  737. self.parent = mainFrame
  738. self.task = task
  739. fontsize = 10
  740. # Determine tab layout
  741. sections = []
  742. is_section = {}
  743. not_hidden = [ p for p in self.task.params + self.task.flags if not p.get( 'hidden','no' ) == 'yes' ]
  744. self.label_id = [] # wrap titles on resize
  745. self.Bind(wx.EVT_SIZE, self.OnSize)
  746. for task in not_hidden:
  747. if task.get( 'required','no' ) == 'yes':
  748. # All required go into Main, even if they had defined another guisection
  749. task['guisection'] = _( 'Required' )
  750. if task.get( 'guisection','' ) == '':
  751. # Undefined guisections end up into Options
  752. task['guisection'] = _( 'Optional' )
  753. if not is_section.has_key(task['guisection']):
  754. # We do it like this to keep the original order, except for Main which goes first
  755. is_section[task['guisection']] = 1
  756. sections.append( task['guisection'] )
  757. else:
  758. is_section[ task['guisection'] ] += 1
  759. del is_section
  760. # 'Required' tab goes first, 'Optional' as the last one
  761. for (newidx,content) in [ (0,_( 'Required' )), (len(sections)-1,_('Optional')) ]:
  762. if content in sections:
  763. idx = sections.index( content )
  764. sections[idx:idx+1] = []
  765. sections[newidx:newidx] = [content]
  766. panelsizer = wx.BoxSizer(orient=wx.VERTICAL)
  767. # Build notebook
  768. nbStyle = globalvar.FNPageStyle
  769. self.notebook = FN.FlatNotebook( self, id=wx.ID_ANY, style=nbStyle)
  770. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  771. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  772. tab = {}
  773. tabsizer = {}
  774. for section in sections:
  775. tab[section] = wx.ScrolledWindow( parent=self.notebook )
  776. tab[section].SetScrollRate(10,10)
  777. tabsizer[section] = wx.BoxSizer(orient=wx.VERTICAL)
  778. self.notebook.AddPage( tab[section], text=section )
  779. # are we running from command line?
  780. ### add 'command output' tab regardless standalone dialog
  781. if self.parent.get_dcmd is None:
  782. self.goutput = goutput.GMConsole(parent=self, margin=False,
  783. pageid=self.notebook.GetPageCount())
  784. self.goutputId = self.notebook.GetPageCount()
  785. self.outpage = self.notebook.AddPage(self.goutput, text=_("Command output") )
  786. else:
  787. self.goutput = None
  788. self.goutputId = -1
  789. self.manual_tab = helpPanel(parent = self.notebook, grass_command = self.task.name)
  790. self.manual_tabsizer = wx.BoxSizer(wx.VERTICAL)
  791. self.notebook.AddPage(self.manual_tab, text=_("Manual"))
  792. self.manual_tab_id = self.notebook.GetPageCount() - 1
  793. self.notebook.SetSelection(0)
  794. panelsizer.Add(item=self.notebook, proportion=1, flag=wx.EXPAND )
  795. #
  796. # flags
  797. #
  798. text_style = wx.FONTWEIGHT_NORMAL
  799. visible_flags = [ f for f in self.task.flags if not f.get( 'hidden', 'no' ) == 'yes' ]
  800. for f in visible_flags:
  801. which_sizer = tabsizer[ f['guisection'] ]
  802. which_panel = tab[ f['guisection'] ]
  803. # if label is given: description -> tooltip
  804. if f.get('label','') != '':
  805. title = text_beautify( f['label'])
  806. tooltip = text_beautify ( f['description'], width=-1)
  807. else:
  808. title = text_beautify( f['description'] )
  809. tooltip = None
  810. chk = wx.CheckBox(parent=which_panel, label = title, style = wx.NO_BORDER)
  811. self.label_id.append(chk.GetId())
  812. if tooltip:
  813. chk.SetToolTipString(tooltip)
  814. if 'value' in f:
  815. chk.SetValue( f['value'] )
  816. # chk.SetFont(wx.Font(pointSize=fontsize, family=wx.FONTFAMILY_DEFAULT,
  817. # style=wx.NORMAL, weight=text_style))
  818. which_sizer.Add( item=chk, proportion=0,
  819. flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=5)
  820. f['wxId'] = chk.GetId()
  821. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  822. if f['name'] in ('verbose', 'quiet'):
  823. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  824. vq = UserSettings.Get(group='cmd', key='verbosity', subkey='selection')
  825. if f['name'] == vq:
  826. chk.SetValue(True)
  827. f['value'] = True
  828. elif f['name'] == 'overwrite':
  829. chk.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
  830. f['value'] = UserSettings.Get(group='cmd', key='overwrite', subkey='enabled')
  831. #
  832. # parameters
  833. #
  834. visible_params = [ p for p in self.task.params if not p.get( 'hidden', 'no' ) == 'yes' ]
  835. try:
  836. first_param = visible_params[0]
  837. except IndexError:
  838. first_param = None
  839. for p in visible_params:
  840. which_sizer = tabsizer[ p['guisection'] ]
  841. which_panel = tab[ p['guisection'] ]
  842. # if label is given -> label and description -> tooltip
  843. # otherwise description -> lavel
  844. if p.get('label','') != '':
  845. title = text_beautify( p['label'] )
  846. tooltip = text_beautify ( p['description'], width = -1)
  847. else:
  848. title = text_beautify( p['description'] )
  849. tooltip = None
  850. txt = None
  851. # text style (required -> bold)
  852. if p.get('required','no') == 'no':
  853. text_style = wx.FONTWEIGHT_NORMAL
  854. else:
  855. text_style = wx.FONTWEIGHT_BOLD
  856. # title expansion
  857. if p.get('multiple','no') == 'yes' and len( p.get('values','') ) == 0:
  858. title = _("[multiple]") + " " + title
  859. if p.get('value','') == '' :
  860. p['value'] = p.get('default','')
  861. if ( len(p.get('values', []) ) > 0):
  862. valuelist=map( str, p.get('values',[]) )
  863. if p.get('multiple', 'no') == 'yes' and \
  864. p.get('type', '') == 'string':
  865. txt = wx.StaticBox (parent=which_panel, id=0, label=" " + title + ": ")
  866. self.label_id.append(txt.GetId())
  867. if len(valuelist) > 6:
  868. hSizer=wx.StaticBoxSizer ( box=txt, orient=wx.VERTICAL )
  869. else:
  870. hSizer=wx.StaticBoxSizer ( box=txt, orient=wx.HORIZONTAL )
  871. isEnabled = {}
  872. # copy default values
  873. if p['value'] == '':
  874. p['value'] = p.get('default', '')
  875. for defval in p.get('value', '').split(','):
  876. isEnabled[ defval ] = 'yes'
  877. # for multi checkboxes, this is an array of all wx IDs
  878. # for each individual checkbox
  879. p[ 'wxId' ] = []
  880. for val in valuelist:
  881. chkbox = wx.CheckBox( parent=which_panel, label = text_beautify(val) )
  882. p[ 'wxId' ].append( chkbox.GetId() )
  883. if isEnabled.has_key(val):
  884. chkbox.SetValue( True )
  885. hSizer.Add( item=chkbox, proportion=0,
  886. flag=wx.ADJUST_MINSIZE | wx.ALL, border=1 )
  887. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  888. which_sizer.Add( item=hSizer, proportion=0,
  889. flag=wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border=5 )
  890. else:
  891. if len(valuelist) == 1: # -> textctrl
  892. txt = wx.StaticText(parent=which_panel,
  893. label = "%s. %s %s" % (title, _('Valid range'),
  894. str(valuelist[0]) + ':'))
  895. self.label_id.append(txt.GetId())
  896. which_sizer.Add(item=txt, proportion=0,
  897. flag=wx.ADJUST_MINSIZE | wx.TOP | wx.RIGHT | wx.LEFT, border=5)
  898. if p.get('type','') == 'integer' and \
  899. p.get('multiple','no') == 'no':
  900. # for multiple integers use textctrl instead of spinsctrl
  901. try:
  902. minValue, maxValue = map(int, valuelist[0].split('-'))
  903. except ValueError:
  904. minValue = -1e6
  905. maxValue = 1e6
  906. txt2 = wx.SpinCtrl(parent=which_panel, id=wx.ID_ANY, size=globalvar.DIALOG_SPIN_SIZE,
  907. min=minValue, max=maxValue)
  908. style = wx.BOTTOM | wx.LEFT
  909. else:
  910. txt2 = wx.TextCtrl(parent=which_panel, value = p.get('default',''))
  911. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  912. if p.get('value','') != '':
  913. txt2.SetValue(p['value']) # parameter previously set
  914. which_sizer.Add(item=txt2, proportion=0,
  915. flag=style, border=5)
  916. p['wxId'] = txt2.GetId()
  917. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  918. else:
  919. # list of values (combo)
  920. txt = wx.StaticText(parent=which_panel, label = title + ':' )
  921. self.label_id.append(txt.GetId())
  922. which_sizer.Add(item=txt, proportion=0,
  923. flag=wx.ADJUST_MINSIZE | wx.TOP | wx.RIGHT | wx.LEFT, border=5)
  924. cb = wx.ComboBox(parent=which_panel, id=wx.ID_ANY, value=p.get('default',''),
  925. size=globalvar.DIALOG_COMBOBOX_SIZE,
  926. choices=valuelist, style=wx.CB_DROPDOWN)
  927. if p.get('value','') != '':
  928. cb.SetValue(p['value']) # parameter previously set
  929. which_sizer.Add( item=cb, proportion=0,
  930. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  931. p['wxId'] = cb.GetId()
  932. cb.Bind( wx.EVT_COMBOBOX, self.OnSetValue)
  933. # text entry
  934. if (p.get('type','string') in ('string','integer','float')
  935. and len(p.get('values',[])) == 0
  936. and p.get('gisprompt',False) == False
  937. and p.get('prompt','') != 'color'):
  938. txt = wx.StaticText(parent=which_panel, label = title + ':' )
  939. self.label_id.append(txt.GetId())
  940. which_sizer.Add(item=txt, proportion=0,
  941. flag=wx.EXPAND | wx.RIGHT | wx.LEFT | wx.TOP, border=5)
  942. if p.get('multiple','yes') == 'yes' or \
  943. p.get('type', 'string') in ('string', 'float') or \
  944. len(p.get('key_desc', [])) > 1:
  945. txt3 = wx.TextCtrl(parent=which_panel, value = p.get('default',''))
  946. if p.get('value','') != '':
  947. txt3.SetValue(str(p['value'])) # parameter previously set
  948. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  949. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  950. else:
  951. minValue = -1e9
  952. maxValue = 1e9
  953. txt3 = wx.SpinCtrl(parent=which_panel, value=p.get('default',''),
  954. size=globalvar.DIALOG_SPIN_SIZE,
  955. min=minValue, max=maxValue)
  956. if p.get('value','') != '':
  957. txt3.SetValue(int(p['value'])) # parameter previously set
  958. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  959. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  960. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  961. which_sizer.Add(item=txt3, proportion=0,
  962. flag=style, border=5)
  963. p['wxId'] = txt3.GetId()
  964. if p.get('type','string') == 'string' and p.get('gisprompt',False) == True:
  965. txt = wx.StaticText(parent=which_panel, label = title + ':')
  966. self.label_id.append(txt.GetId())
  967. which_sizer.Add(item=txt, proportion=0,
  968. flag=wx.ADJUST_MINSIZE | wx.RIGHT | wx.LEFT | wx.TOP, border=5)
  969. # element selection tree combobox (maps, icons, regions, etc.)
  970. if p.get('prompt','') not in ('color', 'dbcolumn', 'dbtable') and \
  971. p.get('element', '') != 'file':
  972. if p.get('multiple','no') == 'yes':
  973. multiple = True
  974. else:
  975. multiple = False
  976. if p.get('age','') == 'new':
  977. mapsets = [grassenv.GetGRASSVariable('MAPSET'),]
  978. else:
  979. mapsets = None
  980. selection = gselect.Select(parent=which_panel, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
  981. type=p.get('element',''), multiple=multiple, mapsets=mapsets)
  982. if p.get('value','') != '':
  983. selection.SetValue(p['value']) # parameter previously set
  984. which_sizer.Add(item=selection, proportion=0,
  985. flag=wx.ADJUST_MINSIZE| wx.BOTTOM | wx.LEFT | wx.RIGHT, border=5)
  986. # A select.Select is a combobox with two children: a textctl and a popupwindow;
  987. # we target the textctl here
  988. p['wxId'] = selection.GetChildren()[0].GetId()
  989. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  990. # dbcolumn entry
  991. elif p.get('prompt','') in ('dbcolumn', 'dbtable'):
  992. if p.get('age', 'old') == 'old' and \
  993. p.get('multiple', 'no') == 'no':
  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 p.get('description', '')
  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.EXPAND | wx.RIGHT, border=5)
  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. if p == first_param:
  1079. if type(p['wxId']) == type(1):
  1080. self.FindWindowById(p['wxId']).SetFocus()
  1081. #
  1082. # determine panel size
  1083. #
  1084. maxsizes = (0,0)
  1085. for section in sections:
  1086. # tabsizer[section].SetSizeHints( tab[section] )
  1087. #tab[section].SetAutoLayout(True)
  1088. tab[section].SetSizer( tabsizer[section] )
  1089. tabsizer[section].Fit( tab[section] )
  1090. tab[section].Layout()
  1091. minsecsizes = tabsizer[section].GetSize()
  1092. maxsizes = map( lambda x: max( maxsizes[x], minsecsizes[x] ), (0,1) )
  1093. # TODO: be less arbitrary with these 600
  1094. self.panelMinHeight = 100
  1095. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1096. for section in sections:
  1097. tab[section].SetMinSize( (self.constrained_size[0], self.panelMinHeight) )
  1098. # tab[section].SetMinSize( constrained_size )
  1099. if self.manual_tab.Ok:
  1100. self.manual_tab.SetMinSize( (self.constrained_size[0], self.panelMinHeight) )
  1101. # manual_tab.SetMinSize( constrained_size )
  1102. self.SetSizer( panelsizer )
  1103. panelsizer.Fit(self.notebook)
  1104. self.hasMain = tab.has_key( _('Required') ) # publish, to enclosing Frame for instance
  1105. def OnVerbosity(self, event):
  1106. """Verbosity level changed"""
  1107. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'])
  1108. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'])
  1109. if event.IsChecked():
  1110. if event.GetId() == verbose.GetId():
  1111. if quiet.IsChecked():
  1112. quiet.SetValue(False)
  1113. self.task.get_flag('quiet')['value'] = False
  1114. else:
  1115. if verbose.IsChecked():
  1116. verbose.SetValue(False)
  1117. self.task.get_flag('verbose')['value'] = False
  1118. event.Skip()
  1119. def OnPageChange(self, event):
  1120. if not event:
  1121. sel = self.notebook.GetSelection()
  1122. else:
  1123. sel = event.GetSelection()
  1124. if hasattr(self, "manual_tab_id") and \
  1125. sel == self.manual_tab_id:
  1126. # calling LoadPage() is strangely time-consuming (only first call)
  1127. # FIXME: move to helpPage.__init__()
  1128. if not self.manual_tab.Ok:
  1129. wx.Yield()
  1130. self.manual_tab.LoadPage(self.manual_tab.fspath + self.task.name + ".html")
  1131. self.manual_tab.Ok = True
  1132. self.Layout()
  1133. def OnColorChange( self, event ):
  1134. myId = event.GetId()
  1135. for p in self.task.params:
  1136. if 'wxId' in p and type( p['wxId'] ) == type( [] ) and myId in p['wxId']:
  1137. has_button = p['wxId'][1] is not None
  1138. if has_button and wx.FindWindowById( p['wxId'][1] ).GetValue() == True:
  1139. p[ 'value' ] = 'none'
  1140. else:
  1141. colorchooser = wx.FindWindowById( p['wxId'][0] )
  1142. new_color = colorchooser.GetValue()[:]
  1143. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1144. # under wx2.8.1
  1145. new_label = rgb2str.get( new_color, ':'.join(map(str,new_color)) )
  1146. colorchooser.SetLabel( new_label )
  1147. colorchooser.SetColour( new_color )
  1148. colorchooser.Refresh()
  1149. p[ 'value' ] = colorchooser.GetLabel()
  1150. self.OnUpdateValues()
  1151. def OnUpdateValues(self):
  1152. """
  1153. If we were part of a richer interface, report back the current command being built.
  1154. This method should be set by the parent of this panel if needed. It's a hook, actually.
  1155. Beware of what is 'self' in the method def, though. It will be called with no arguments.
  1156. """
  1157. pass
  1158. def OnCheckBoxMulti(self, event):
  1159. """
  1160. Fill the values as a ','-separated string according to current status of the checkboxes.
  1161. """
  1162. me = event.GetId()
  1163. theParam = None
  1164. for p in self.task.params:
  1165. if 'wxId' in p and type( p['wxId'] ) == type( [] ) and me in p['wxId']:
  1166. theParam = p
  1167. myIndex = p['wxId'].index( me )
  1168. # Unpack current value list
  1169. currentValues = {}
  1170. for isThere in theParam.get('value', '').split(','):
  1171. currentValues[isThere] = 1
  1172. theValue = theParam['values'][myIndex]
  1173. if event.Checked():
  1174. currentValues[ theValue ] = 1
  1175. else:
  1176. del currentValues[ theValue ]
  1177. # Keep the original order, so that some defaults may be recovered
  1178. currentValueList = []
  1179. for v in theParam['values']:
  1180. if currentValues.has_key(v):
  1181. currentValueList.append( v )
  1182. # Pack it back
  1183. theParam['value'] = ','.join( currentValueList )
  1184. self.OnUpdateValues()
  1185. def OnSetValue(self, event):
  1186. """
  1187. Retrieve the widget value and set the task value field accordingly.
  1188. Use for widgets that have a proper GetValue() method, i.e. not for selectors.
  1189. """
  1190. myId = event.GetId()
  1191. me = wx.FindWindowById( myId )
  1192. for porf in self.task.params + self.task.flags:
  1193. if 'wxId' in porf and type( porf[ 'wxId' ] ) == type( 1 ) and porf['wxId'] == myId:
  1194. if porf.has_key('wxGetValue') and porf['wxGetValue']:
  1195. porf['value'] = porf['wxGetValue']()
  1196. else:
  1197. porf['value'] = me.GetValue()
  1198. self.OnUpdateValues()
  1199. event.Skip()
  1200. def OnDbColumn(self, event):
  1201. """Get list of table columns"""
  1202. choices = []
  1203. p = self.task.get_param('table', raiseError=False)
  1204. if p and p.get('prompt', '') == 'dbtable':
  1205. cmd = ['db.columns',
  1206. 'table=%s' % p.get('value')]
  1207. try:
  1208. choices = gcmd.Command(cmd).ReadStdOutput()
  1209. except gcmd.CmdError:
  1210. choices = []
  1211. if not p:
  1212. p = self.task.get_param('map', raiseError=False)
  1213. if not p:
  1214. p = self.task.get_param('input', raiseError=False)
  1215. if p:
  1216. mapName = utils.GetLayerNameFromCmd(self.task.getCmd(ignoreErrors=True))
  1217. if mapName != _('<required>'):
  1218. layer = 1
  1219. p = self.task.get_param('layer')
  1220. if p:
  1221. value = p.get('value', '1')
  1222. if value:
  1223. layer = int(value)
  1224. cmd = ['v.info',
  1225. 'map=%s' % mapName,
  1226. 'layer=%d' % layer,
  1227. '-c', '--q']
  1228. try:
  1229. for line in gcmd.Command(cmd).ReadStdOutput():
  1230. type, name = line.split('|')
  1231. choices.append(name.strip())
  1232. except gcmd.CmdError:
  1233. choices = []
  1234. win = self.FindWindowById(event.GetId())
  1235. win.SetItems(choices)
  1236. if len(choices) < 1:
  1237. win.SetValue('')
  1238. event.Skip()
  1239. def OnDbTable(self, event):
  1240. """Get list of tables"""
  1241. # TODO: add driver/database
  1242. cmd = ['db.tables',
  1243. '-p', '--q']
  1244. for p in self.task.params:
  1245. if p.get('name', '') == 'driver' and \
  1246. len(p.get('value', '')) > 0:
  1247. cmd.append('driver=%s' % p.get('value'))
  1248. elif p.get('name', '') == 'database' and \
  1249. len(p.get('value', '')) > 0:
  1250. cmd.append('database=%s' % p.get('value'))
  1251. try:
  1252. choices = gcmd.Command(cmd).ReadStdOutput()
  1253. except gcmd.CmdError:
  1254. choices = []
  1255. win = self.FindWindowById(event.GetId())
  1256. win.SetItems(choices)
  1257. if len(choices) < 1:
  1258. win.SetValue('')
  1259. event.Skip()
  1260. def createCmd( self, ignoreErrors = False ):
  1261. """
  1262. Produce a command line string (list) or feeding into GRASS.
  1263. If ignoreErrors==True then it will return whatever has been
  1264. built so far, even though it would not be a correct command
  1265. for GRASS.
  1266. """
  1267. try:
  1268. cmd = self.task.getCmd( ignoreErrors=ignoreErrors )
  1269. except ValueError, err:
  1270. dlg = wx.MessageDialog(parent=self,
  1271. message=str(err),
  1272. caption=_("Error in %s") % self.task.name,
  1273. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1274. dlg.ShowModal()
  1275. dlg.Destroy()
  1276. cmd = None
  1277. return cmd
  1278. def OnSize(self, event):
  1279. width = event.GetSize()[0]
  1280. fontsize = self.GetFont().GetPointSize()
  1281. text_width = width / (fontsize - 3)
  1282. if text_width < 70:
  1283. text_width = 70
  1284. for id in self.label_id:
  1285. win = self.FindWindowById(id)
  1286. label = win.GetLabel()
  1287. label_new = '\n'.join(textwrap.wrap(label, text_width ))
  1288. win.SetLabel(label_new)
  1289. event.Skip()
  1290. def getInterfaceDescription( cmd ):
  1291. """
  1292. Returns the XML description for the GRASS cmd.
  1293. The DTD must be located in $GISBASE/etc/grass-interface.dtd,
  1294. otherwise the parser will not succeed.
  1295. Note: 'cmd' is given as string
  1296. """
  1297. cmdout = os.popen(cmd + r' --interface-description', "r").read()
  1298. if not len(cmdout) > 0 :
  1299. raise IOError, _("Unable to fetch interface description for command '%s'.") % cmd
  1300. p = re.compile( '(grass-interface.dtd)')
  1301. p.search( cmdout )
  1302. cmdout = p.sub(globalvar.ETCDIR + r'/grass-interface.dtd', cmdout)
  1303. return cmdout
  1304. class GrassGUIApp(wx.App):
  1305. """
  1306. Stand-alone GRASS command GUI
  1307. """
  1308. def __init__(self, grass_task):
  1309. self.grass_task = grass_task
  1310. wx.App.__init__(self, False)
  1311. def OnInit(self):
  1312. self.mf = mainFrame(parent=None, ID=wx.ID_ANY, task_description=self.grass_task)
  1313. self.mf.CentreOnScreen()
  1314. self.mf.Show(True)
  1315. self.SetTopWindow(self.mf)
  1316. # print >> sys.stderr, time.time() - start
  1317. return True
  1318. class GUI:
  1319. """
  1320. Parses GRASS commands when module is imported and used
  1321. from Layer Manager.
  1322. """
  1323. def __init__(self, parent=-1):
  1324. self.parent = parent
  1325. self.grass_task = None
  1326. def ParseCommand(self, cmd, gmpath=None, completed=None, parentframe=None,
  1327. show=True, modal=False):
  1328. """
  1329. Parse command
  1330. Note: cmd is given as list
  1331. If command is given with options, return validated cmd list:
  1332. * add key name for first parameter if not given
  1333. * change mapname to mapname@mapset
  1334. """
  1335. start = time.time()
  1336. dcmd_params = {}
  1337. if completed == None:
  1338. get_dcmd = None
  1339. layer = None
  1340. dcmd_params = None
  1341. else:
  1342. get_dcmd = completed[0]
  1343. layer = completed[1]
  1344. if completed[2]:
  1345. dcmd_params.update(completed[2])
  1346. self.parent = parentframe
  1347. # parse the interface decription
  1348. self.grass_task = grassTask()
  1349. handler = processTask(self.grass_task)
  1350. xml.sax.parseString( getInterfaceDescription(cmd[0]), handler )
  1351. # if layer parameters previously set, re-insert them into dialog
  1352. if completed is not None:
  1353. if 'params' in dcmd_params:
  1354. self.grass_task.params = dcmd_params['params']
  1355. if 'flags' in dcmd_params:
  1356. self.grass_task.flags = dcmd_params['flags']
  1357. # update parameters if needed && validate command
  1358. if len(cmd) > 1:
  1359. i = 0
  1360. cmd_validated = [cmd[0]]
  1361. for option in cmd[1:]:
  1362. if option[0] == '-': # flag
  1363. self.grass_task.set_flag(option[1], True)
  1364. cmd_validated.append(option)
  1365. else: # parameter
  1366. try:
  1367. key, value = option.split('=', 1)
  1368. except:
  1369. if i == 0: # add key name of first parameter if not given
  1370. key = self.grass_task.firstParam
  1371. value = option
  1372. else:
  1373. raise ValueError, _("Unable to parse command %s") % ' '.join(cmd)
  1374. if self.grass_task.get_param(key)['element'] in ['cell', 'vector']:
  1375. # mapname -> mapname@mapset
  1376. if '@' not in value:
  1377. value = value + '@' + grassenv.GetGRASSVariable('MAPSET')
  1378. self.grass_task.set_param(key, value)
  1379. cmd_validated.append(key + '=' + value)
  1380. i = i + 1
  1381. # update original command list
  1382. cmd = cmd_validated
  1383. self.mf = mainFrame(parent=self.parent, ID=wx.ID_ANY,
  1384. task_description=self.grass_task,
  1385. get_dcmd=get_dcmd, layer=layer)
  1386. if get_dcmd is not None:
  1387. # update only propwin reference
  1388. get_dcmd(dcmd=None, layer=layer, params=None,
  1389. propwin=self.mf)
  1390. if show:
  1391. if self.parent:
  1392. self.mf.CentreOnParent()
  1393. self.mf.Show(show)
  1394. self.mf.MakeModal(modal)
  1395. else:
  1396. self.mf.OnApply(None)
  1397. # print >> sys.stderr, time.time() - start
  1398. return cmd
  1399. def GetCommandInputMapParamKey(self, cmd):
  1400. """Get parameter key for input raster/vector map
  1401. @param cmd module name
  1402. @return parameter key
  1403. @return None on failure
  1404. """
  1405. # parse the interface decription
  1406. if not self.grass_task:
  1407. self.grass_task = grassTask()
  1408. handler = processTask(self.grass_task)
  1409. xml.sax.parseString(getInterfaceDescription(cmd), handler)
  1410. for p in self.grass_task.params:
  1411. if p.get('name', '') in ('input', 'map'):
  1412. age = p.get('age', '')
  1413. prompt = p.get('prompt', '')
  1414. element = p.get('element', '')
  1415. if age == 'old' and \
  1416. element in ('cell', 'grid3', 'vector') and \
  1417. prompt in ('raster', '3d-raster', 'vector'):
  1418. return p.get('name', None)
  1419. return None
  1420. class StaticWrapText(wx.StaticText):
  1421. """
  1422. A Static Text field that wraps its text to fit its width, enlarging its height if necessary.
  1423. """
  1424. def __init__(self, parent, id=wx.ID_ANY, label=u'', *args, **kwds):
  1425. self.originalLabel = label
  1426. wx.StaticText.__init__(self, parent, id, u'', *args, **kwds)
  1427. self.SetLabel(label)
  1428. self.Bind(wx.EVT_SIZE, self.onResize)
  1429. def SetLabel(self, label):
  1430. self.originalLabel = label
  1431. self.wrappedSize = None
  1432. #self.onResize(None)
  1433. def onResize(self, event):
  1434. if not getattr(self, "resizing", False):
  1435. self.resizing = True
  1436. newSize = self.GetSize()
  1437. if self.wrappedSize != newSize:
  1438. wx.StaticText.SetLabel(self, self.originalLabel)
  1439. self.Wrap(newSize.width)
  1440. self.wrappedSize = self.GetMinSize()
  1441. self.SetSize(self.wrappedSize)
  1442. del self.resizing
  1443. if __name__ == "__main__":
  1444. if len(sys.argv) == 1:
  1445. print _("usage: %s <grass command>") % sys.argv[0]
  1446. sys.exit()
  1447. if sys.argv[1] != 'test':
  1448. q=wx.LogNull()
  1449. GrassGUIApp( grassTask( sys.argv[1] ) ).MainLoop()
  1450. else: #Test
  1451. # Test grassTask from within a GRASS session
  1452. if os.getenv("GISBASE") is not None:
  1453. task = grassTask( "d.vect" )
  1454. task.get_param('map')['value'] = "map_name"
  1455. task.get_flag('v')['value'] = True
  1456. task.get_param('layer')['value'] = 1
  1457. task.get_param('bcolor')['value'] = "red"
  1458. assert ' '.join( task.getCmd() ) == "d.vect -v map=map_name layer=1 bcolor=red"
  1459. # Test interface building with handmade grassTask,
  1460. # possibly outside of a GRASS session.
  1461. task = grassTask()
  1462. task.name = "TestTask"
  1463. task.description = "This is an artificial grassTask() object intended for testing purposes."
  1464. task.keywords = ["grass","test","task"]
  1465. task.params = [
  1466. {
  1467. "name" : "text",
  1468. "description" : "Descriptions go into tooltips if labels are present, like this one",
  1469. "label" : "Enter some text",
  1470. },{
  1471. "name" : "hidden_text",
  1472. "description" : "This text should not appear in the form",
  1473. "hidden" : "yes"
  1474. },{
  1475. "name" : "text_default",
  1476. "description" : "Enter text to override the default",
  1477. "default" : "default text"
  1478. },{
  1479. "name" : "text_prefilled",
  1480. "description" : "You should see a friendly welcome message here",
  1481. "value" : "hello, world"
  1482. },{
  1483. "name" : "plain_color",
  1484. "description" : "This is a plain color, and it is a compulsory parameter",
  1485. "required" : "yes",
  1486. "gisprompt" : True,
  1487. "prompt" : "color"
  1488. },{
  1489. "name" : "transparent_color",
  1490. "description" : "This color becomes transparent when set to none",
  1491. "guisection" : "tab",
  1492. "gisprompt" : True,
  1493. "prompt" : "color"
  1494. },{
  1495. "name" : "multi",
  1496. "description" : "A multiple selection",
  1497. 'default': u'red,green,blue',
  1498. 'gisprompt': False,
  1499. 'guisection': 'tab',
  1500. 'multiple': u'yes',
  1501. 'type': u'string',
  1502. 'value': '',
  1503. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other']
  1504. },{
  1505. "name" : "single",
  1506. "description" : "A single multiple-choice selection",
  1507. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  1508. "guisection" : "tab"
  1509. },{
  1510. "name" : "large_multi",
  1511. "description" : "A large multiple selection",
  1512. "gisprompt" : False,
  1513. "multiple" : "yes",
  1514. # values must be an array of strings
  1515. "values" : str2rgb.keys() + map( str, str2rgb.values() )
  1516. },{
  1517. "name" : "a_file",
  1518. "description" : "A file selector",
  1519. "gisprompt" : True,
  1520. "element" : "file"
  1521. }
  1522. ]
  1523. task.flags = [
  1524. {
  1525. "name" : "a",
  1526. "description" : "Some flag, will appear in Main since it is required",
  1527. "required" : "yes"
  1528. },{
  1529. "name" : "b",
  1530. "description" : "pre-filled flag, will appear in options since it is not required",
  1531. "value" : True
  1532. },{
  1533. "name" : "hidden_flag",
  1534. "description" : "hidden flag, should not be changeable",
  1535. "hidden" : "yes",
  1536. "value" : True
  1537. }
  1538. ]
  1539. q=wx.LogNull()
  1540. GrassGUIApp( task ).MainLoop()