menuform.py 75 KB

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