menuform.py 74 KB

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