menuform.py 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654
  1. #! /usr/bin/python
  2. """Construct simple wx.Python GUI from a GRASS command interface description.
  3. Classes:
  4. * testSAXContentHandler
  5. * grassTask
  6. * processTask
  7. * helpPanel
  8. * mainFrame
  9. * cmdPanel
  10. * GrassGUIApp
  11. * GUI
  12. Copyright (C) 2000-2007 by the GRASS Development Team
  13. This program is free software under the GPL (>=v2)
  14. Read the file COPYING coming with GRASS for details.
  15. This program is just a coarse approach to
  16. automatically build a GUI from a xml-based
  17. GRASS user interface description.
  18. You need to have Python 2.4, wxPython 2.8 and python-xml.
  19. The XML stream is read from executing the command given in the
  20. command line, thus you may call it for instance this way:
  21. python <this file.py> r.basins.fill
  22. Or you set an alias or wrap the call up in a nice
  23. shell script, GUI environment ... please contribute your idea.
  24. Updated to wxPython 2.8 syntax and contrib widgets.
  25. Methods added to make it callable by gui.
  26. Method added to automatically re-run with pythonw on a Mac.
  27. @author Jan-Oliver Wagner <jan@intevation.de>
  28. @author Bernhard Reiter <bernhard@intevation.de>
  29. @author Michael Barton, Arizona State University
  30. @author Daniel Calvelo <dca.gis@gmail.com>
  31. @author Martin Landa <landa.martin@gmail.com>
  32. @todo
  33. - verify option value types
  34. - use DOM instead of SAX
  35. """
  36. __version__ ="$Revision$"
  37. import sys
  38. import re
  39. import string
  40. import textwrap
  41. import os
  42. from os import system
  43. import time
  44. start = time.time()
  45. ### i18N
  46. import gettext
  47. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True)
  48. import globalvar
  49. globalvar.CheckForWx()
  50. import wx
  51. import wx.lib.flatnotebook as FN
  52. import wx.lib.colourselect as csel
  53. import wx.lib.filebrowsebutton as filebrowse
  54. from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
  55. import wx.html
  56. # Do the python 2.0 standard xml thing and map it on the old names
  57. import xml.sax
  58. import xml.sax.handler
  59. HandlerBase=xml.sax.handler.ContentHandler
  60. from xml.sax import make_parser
  61. import utils
  62. gisbase = os.getenv("GISBASE")
  63. if gisbase is None:
  64. print >>sys.stderr, "We don't seem to be properly installed, or we are being run outside GRASS. Expect glitches."
  65. gisbase = os.path.join(os.path.dirname( sys.argv[0] ), os.path.pardir)
  66. wxbase = gisbase
  67. else:
  68. wxbase = os.path.join(globalvar.ETCWXDIR)
  69. sys.path.append( wxbase)
  70. imagepath = os.path.join(wxbase, "images")
  71. sys.path.append(imagepath)
  72. import grassenv
  73. import gselect
  74. import gcmd
  75. import goutput
  76. import utils
  77. from preferences import globalSettings as UserSettings
  78. try:
  79. import subprocess
  80. except:
  81. from compat import subprocess
  82. utils.reexec_with_pythonw()
  83. # From lib/gis/col_str.c, except purple which is mentioned
  84. # there but not given RGB values
  85. str2rgb = {'aqua': (100, 128, 255),
  86. 'black': (0, 0, 0),
  87. 'blue': (0, 0, 255),
  88. 'brown': (180, 77, 25),
  89. 'cyan': (0, 255, 255),
  90. 'gray': (128, 128, 128),
  91. 'green': (0, 255, 0),
  92. 'grey': (128, 128, 128),
  93. 'indigo': (0, 128, 255),
  94. 'magenta': (255, 0, 255),
  95. 'orange': (255, 128, 0),
  96. 'purple': (128, 0, 128),
  97. 'red': (255, 0, 0),
  98. 'violet': (128, 0, 255),
  99. 'white': (255, 255, 255),
  100. 'yellow': (255, 255, 0)}
  101. rgb2str = {}
  102. for (s,r) in str2rgb.items():
  103. rgb2str[ r ] = s
  104. def color_resolve(color):
  105. if len(color)>0 and color[0] in "0123456789":
  106. rgb = tuple(map(int,color.split( ':' )))
  107. label = color
  108. else:
  109. # Convert color names to RGB
  110. try:
  111. rgb = str2rgb[ color ]
  112. label = color
  113. except KeyError:
  114. rgb = (200,200,200)
  115. label = _('Select Color')
  116. return (rgb, label)
  117. def normalize_whitespace(text):
  118. """Remove redundant whitespace from a string"""
  119. return string.join( string.split(text), ' ')
  120. def text_beautify( someString ):
  121. """
  122. Make really long texts shorter, clean up whitespace and
  123. remove trailing punctuation.
  124. """
  125. # TODO: remove magic number (calculate a correct value from
  126. # pixelSize of text and the magic number for maximum size)
  127. return escape_ampersand( string.strip(
  128. os.linesep.join( textwrap.wrap( normalize_whitespace(someString), 70 ) ),
  129. ".,;:" ) )
  130. def escape_ampersand(text):
  131. """Escapes ampersands with additional ampersand for GUI"""
  132. return string.replace(text, "&", "&&")
  133. class testSAXContentHandler(HandlerBase):
  134. # SAX compliant
  135. def characters(self, ch, start, length):
  136. pass
  137. def test_for_broken_SAX():
  138. ch=testSAXContentHandler()
  139. try:
  140. xml.sax.parseString("""<?xml version="1.0"?>
  141. <child1 name="paul">Text goes here</child1>
  142. """,ch)
  143. except TypeError:
  144. return 1
  145. return 0
  146. class grassTask:
  147. """
  148. This class holds the structures needed for both filling by the parser and
  149. use by the interface constructor.
  150. Use as either grassTask() for empty definition or grassTask( 'grass.command' )
  151. for parsed filling.
  152. """
  153. def __init__(self, grassModule = None):
  154. self.name = _('unknown')
  155. self.params = []
  156. self.description = ''
  157. self.label = ''
  158. self.flags = []
  159. self.keywords = []
  160. if grassModule is not None:
  161. xml.sax.parseString( getInterfaceDescription( grassModule ) , processTask( self ) )
  162. def get_param( self, aParam ):
  163. """
  164. Find and return a param by name.
  165. """
  166. for p in self.params:
  167. lparam = len(aParam)
  168. if p['name'] == aParam or \
  169. p['name'][:lparam] == aParam:
  170. return p
  171. raise ValueError, _("Parameter not found: %s") % aParam
  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
  490. # module name + keywords
  491. title = self.task.name
  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.ETCDIR, 'grass_dialog.ico'), wx.BITMAP_TYPE_ICO))
  503. # menu
  504. # menu = wx.Menu()
  505. # menu.Append(wx.ID_ABOUT, _("&About GrassGUI"),
  506. # _("Information about GrassGUI") )
  507. # menu.Append(ID_ABOUT_COMMAND, _("&About %s") % self.task.name,
  508. # _("Short descripton of GRASS command %s") % self.task.name)
  509. # menu.AppendSeparator()
  510. # menu.Append(wx.ID_EXIT, _("E&xit"), _("Terminate the program") )
  511. # menuBar = wx.MenuBar()
  512. # menuBar.Append(menu, "&File");
  513. # self.SetMenuBar(menuBar)
  514. #wx.EVT_MENU(self, wx.ID_ABOUT, self.OnAbout)
  515. #wx.EVT_MENU(self, ID_ABOUT_COMMAND, self.OnAboutCommand)
  516. #wx.EVT_MENU(self, wx.ID_EXIT, self.OnCancel)
  517. guisizer = wx.BoxSizer(wx.VERTICAL)
  518. # set apropriate output window
  519. if self.parent:
  520. self.standalone = False
  521. else:
  522. self.standalone = True
  523. # try:
  524. # self.goutput = self.parent.GetLogWindow()
  525. # except:
  526. # self.goutput = None
  527. # logo+description
  528. topsizer = wx.BoxSizer(wx.HORIZONTAL)
  529. # GRASS logo
  530. self.logo = wx.StaticBitmap(parent=self.panel,
  531. bitmap=wx.Bitmap(name=os.path.join(imagepath,
  532. 'grass_form.png'),
  533. type=wx.BITMAP_TYPE_PNG))
  534. topsizer.Add (item=self.logo, proportion=0, border=3,
  535. flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
  536. guisizer.Add (item=topsizer, proportion=0, flag=wx.EXPAND)
  537. # notebooks
  538. self.notebookpanel = cmdPanel (parent=self.panel, task=self.task, standalone=self.standalone,
  539. mainFrame=self)
  540. ### add 'command output' tab also for dialog open from menu
  541. # if self.standalone:
  542. self.goutput = self.notebookpanel.goutput
  543. self.notebookpanel.OnUpdateValues = self.updateValuesHook
  544. guisizer.Add (item=self.notebookpanel, proportion=1, flag=wx.EXPAND)
  545. # status bar
  546. status_text = _("Enter parameters for ") + self.task.name
  547. if self.notebookpanel.hasMain:
  548. # We have to wait for the notebookpanel to be filled in order
  549. # to know if there actually is a Main tab
  550. status_text += _(" (those in bold typeface are required)")
  551. try:
  552. self.task.getCmd()
  553. self.updateValuesHook()
  554. except ValueError:
  555. self.SetStatusText( status_text )
  556. # buttons
  557. btnsizer = wx.BoxSizer(orient=wx.HORIZONTAL)
  558. # cancel
  559. self.btn_cancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
  560. self.btn_cancel.SetToolTipString(_("Cancel the command settings and ignore changes"))
  561. btnsizer.Add(item=self.btn_cancel, proportion=0, flag=wx.ALL | wx.ALIGN_CENTER, border=10)
  562. self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  563. # help
  564. self.btn_help = wx.Button(parent=self.panel, id=wx.ID_HELP)
  565. self.btn_help.SetToolTipString(_("Show manual page of the command"))
  566. self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
  567. if self.get_dcmd is not None: # A callback has been set up
  568. btn_apply = wx.Button(parent=self.panel, id=wx.ID_APPLY)
  569. btn_ok = wx.Button(parent=self.panel, id=wx.ID_OK)
  570. btn_ok.SetDefault()
  571. btnsizer.Add(item=btn_apply, proportion=0,
  572. flag=wx.ALL | wx.ALIGN_CENTER,
  573. border=10)
  574. btnsizer.Add(item=btn_ok, proportion=0,
  575. flag=wx.ALL | wx.ALIGN_CENTER,
  576. border=10)
  577. btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
  578. btn_ok.Bind(wx.EVT_BUTTON, self.OnOK)
  579. else: # We're standalone
  580. # run
  581. self.btn_run = wx.Button(parent=self.panel, id=wx.ID_OK, label= _("&Run"))
  582. self.btn_run.SetToolTipString(_("Run the command"))
  583. self.btn_run.SetDefault()
  584. # abort
  585. self.btn_abort = wx.Button(parent=self.panel, id=wx.ID_STOP)
  586. self.btn_abort.SetToolTipString(_("Abort the running command"))
  587. self.btn_abort.Enable(False)
  588. # copy
  589. self.btn_clipboard = wx.Button(parent=self.panel, id=wx.ID_COPY)
  590. self.btn_clipboard.SetToolTipString(_("Copy the current command string to the clipboard"))
  591. btnsizer.Add(item=self.btn_abort, proportion=0,
  592. flag=wx.ALL | wx.ALIGN_CENTER,
  593. border=10)
  594. btnsizer.Add(item=self.btn_run, proportion=0,
  595. flag=wx.ALL | wx.ALIGN_CENTER,
  596. border=10)
  597. btnsizer.Add(item=self.btn_clipboard, proportion=0,
  598. flag=wx.ALL | wx.ALIGN_CENTER,
  599. border=10)
  600. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  601. self.btn_abort.Bind(wx.EVT_BUTTON, self.OnAbort)
  602. self.btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
  603. # add help button
  604. btnsizer.Add(item=self.btn_help, proportion=0, flag=wx.ALL | wx.ALIGN_CENTER, border=10)
  605. guisizer.Add(item=btnsizer, proportion=0, flag=wx.ALIGN_CENTER)
  606. if self.parent is not None:
  607. self.outputType = None
  608. for p in self.task.params:
  609. if p.get('name', '') == 'output':
  610. self.outputType = p.get('prompt', None)
  611. break
  612. if self.outputType:
  613. # add newly created map into layer tree
  614. self.addbox = wx.CheckBox(parent=self.panel,
  615. label=_('Add created map into layer tree'), style = wx.NO_BORDER)
  616. self.addbox.SetValue(UserSettings.Get(group='cmd', key='addNewLayer', subkey='enabled'))
  617. guisizer.Add(item=self.addbox, proportion=0,
  618. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  619. border=5)
  620. if self.get_dcmd is None:
  621. # close dialog when command is terminated
  622. self.closebox = wx.CheckBox(parent=self.panel,
  623. label=_('Close dialog on finish'), style = wx.NO_BORDER)
  624. self.closebox.SetValue(UserSettings.Get(group='cmd', key='closeDlg', subkey='enabled'))
  625. guisizer.Add(item=self.closebox, proportion=0,
  626. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  627. border=5)
  628. self.Bind(wx.EVT_CLOSE, self.OnCancel)
  629. #constrained_size = self.notebookpanel.GetSize()
  630. # 80 takes the tabbar into account
  631. #self.notebookpanel.SetSize( (constrained_size[0] + 25, constrained_size[1]) )
  632. #self.notebookpanel.Layout()
  633. #
  634. # put module description
  635. #
  636. if self.task.label != '':
  637. module_desc = self.task.label + os.linesep + self.task.description
  638. else:
  639. module_desc = self.task.description
  640. self.description = StaticWrapText (parent=self.panel,
  641. label=module_desc)
  642. topsizer.Add (item=self.description, proportion=1, border=5,
  643. flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  644. #
  645. # do layout
  646. #
  647. guisizer.SetSizeHints(self.panel)
  648. # called automatically by SetSizer()
  649. self.panel.SetAutoLayout(True)
  650. self.panel.SetSizer(guisizer)
  651. guisizer.Fit(self.panel)
  652. sizeFrame = self.GetBestSize()
  653. self.SetMinSize(sizeFrame)
  654. self.SetSize((sizeFrame[0], sizeFrame[1] +
  655. self.notebookpanel.constrained_size[1] -
  656. self.notebookpanel.panelMinHeight))
  657. self.Layout()
  658. def updateValuesHook(self):
  659. """Update status bar data"""
  660. self.SetStatusText(' '.join(self.notebookpanel.createCmd(ignoreErrors = True)) )
  661. def OnOK(self, event):
  662. """OK button pressed"""
  663. cmd = self.OnApply(event)
  664. if cmd is not None and self.get_dcmd is not None:
  665. self.OnCancel(event)
  666. def OnApply(self, event):
  667. """Apply the command"""
  668. cmd = self.createCmd()
  669. if cmd is not None and self.get_dcmd is not None:
  670. # return d.* command to layer tree for rendering
  671. self.get_dcmd(cmd, self.layer, {"params": self.task.params,
  672. "flags" :self.task.flags},
  673. self)
  674. # echo d.* command to output console
  675. # self.parent.writeDCommand(cmd)
  676. return cmd
  677. def OnRun(self, event):
  678. """Run the command"""
  679. cmd = self.createCmd()
  680. if cmd == [] or cmd == None:
  681. return
  682. if cmd[0][0:2] != "d.":
  683. # Send any non-display command to parent window (probably wxgui.py)
  684. # put to parents
  685. try:
  686. self.goutput.RunCmd(cmd)
  687. except AttributeError,e:
  688. print >> sys.stderr, "%s: Propably not running in wxgui.py session?" % (e)
  689. print >> sys.stderr, "parent window is: %s" % (str(self.parent))
  690. # Send any other command to the shell.
  691. else:
  692. gcmd.Command(cmd)
  693. # update buttons status
  694. for btn in (self.btn_run,
  695. self.btn_cancel,
  696. self.btn_clipboard,
  697. self.btn_help):
  698. btn.Enable(False)
  699. self.btn_abort.Enable(True)
  700. def OnAbort(self, event):
  701. """Abort running command"""
  702. event = goutput.wxCmdAbort(aborted=True)
  703. wx.PostEvent(self.goutput, event)
  704. def OnCopy(self, event):
  705. """Copy the command"""
  706. cmddata = wx.TextDataObject()
  707. # list -> string
  708. cmdstring = ' '.join(self.createCmd(ignoreErrors=True))
  709. cmddata.SetText(cmdstring)
  710. if wx.TheClipboard.Open():
  711. wx.TheClipboard.UsePrimarySelection(True)
  712. wx.TheClipboard.SetData(cmddata)
  713. wx.TheClipboard.Close()
  714. self.SetStatusText( _("'%s' copied to clipboard") % \
  715. (cmdstring))
  716. def OnCancel(self, event):
  717. """Cancel button pressed"""
  718. self.MakeModal(False)
  719. if self.get_dcmd:
  720. self.Hide()
  721. else:
  722. self.Destroy()
  723. def OnHelp(self, event):
  724. """Show manual page (switch to the 'Manual' notebook page)"""
  725. if hasattr(self.notebookpanel, "manual_tab_id"):
  726. self.notebookpanel.notebook.SetSelection(self.notebookpanel.manual_tab_id)
  727. self.notebookpanel.OnPageChange(None)
  728. event.Skip()
  729. def OnAbout(self, event):
  730. """General 'about' information"""
  731. dlg = wx.MessageDialog(self, _("This is a sample program for\n"
  732. "GRASS command interface parsing\n"
  733. "and automatic GUI building.\n%s") %(__version__),
  734. _("About wxPython GRASS GUI"), wx.OK | wx.ICON_INFORMATION)
  735. dlg.ShowModal()
  736. dlg.Destroy()
  737. def OnAboutCommand(self, event):
  738. """About command"""
  739. dlg = wx.MessageDialog(self,
  740. self.task.name+": "+self.task.description,
  741. "About " + self.task.name,
  742. wx.OK | wx.ICON_INFORMATION)
  743. dlg.ShowModal()
  744. dlg.Destroy()
  745. def createCmd(self, ignoreErrors = False):
  746. """Create command string (python list)"""
  747. return self.notebookpanel.createCmd(ignoreErrors=ignoreErrors)
  748. class cmdPanel(wx.Panel):
  749. """
  750. A panel containing a notebook dividing in tabs the different guisections of the GRASS cmd.
  751. """
  752. def __init__( self, parent, task, standalone, mainFrame, *args, **kwargs ):
  753. wx.Panel.__init__( self, parent, *args, **kwargs )
  754. self.parent = mainFrame
  755. self.task = task
  756. fontsize = 10
  757. # Determine tab layout
  758. sections = []
  759. is_section = {}
  760. not_hidden = [ p for p in self.task.params + self.task.flags if not p.get( 'hidden','no' ) == 'yes' ]
  761. for task in not_hidden:
  762. if task.get( 'required','no' ) == 'yes':
  763. # All required go into Main, even if they had defined another guisection
  764. task['guisection'] = _( 'Required' )
  765. if task.get( 'guisection','' ) == '':
  766. # Undefined guisections end up into Options
  767. task['guisection'] = _( 'Optional' )
  768. if not is_section.has_key(task['guisection']):
  769. # We do it like this to keep the original order, except for Main which goes first
  770. is_section[task['guisection']] = 1
  771. sections.append( task['guisection'] )
  772. else:
  773. is_section[ task['guisection'] ] += 1
  774. del is_section
  775. # 'Required' tab goes first, 'Optional' as the last one
  776. for (newidx,content) in [ (0,_( 'Required' )), (len(sections)-1,_('Optional')) ]:
  777. if content in sections:
  778. idx = sections.index( content )
  779. sections[idx:idx+1] = []
  780. sections[newidx:newidx] = [content]
  781. panelsizer = wx.BoxSizer(orient=wx.VERTICAL)
  782. # Build notebook
  783. nbStyle = globalvar.FNPageStyle
  784. self.notebook = FN.FlatNotebook( self, id=wx.ID_ANY, style=nbStyle)
  785. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  786. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  787. tab = {}
  788. tabsizer = {}
  789. for section in sections:
  790. tab[section] = wx.ScrolledWindow( parent=self.notebook )
  791. tab[section].SetScrollRate(10,10)
  792. tabsizer[section] = wx.BoxSizer(orient=wx.VERTICAL)
  793. self.notebook.AddPage( tab[section], text=section )
  794. # are we running from command line?
  795. ### add 'command output' tab regardless standalone dialog
  796. if self.parent.get_dcmd is None:
  797. self.goutput = goutput.GMConsole(parent=self, margin=False,
  798. pageid=self.notebook.GetPageCount())
  799. self.outpage = self.notebook.AddPage(self.goutput, text=_("Command output") )
  800. else:
  801. self.goutput = None
  802. self.manual_tab = helpPanel(parent = self.notebook, grass_command = self.task.name)
  803. self.manual_tabsizer = wx.BoxSizer(wx.VERTICAL)
  804. self.notebook.AddPage(self.manual_tab, text=_("Manual"))
  805. self.manual_tab_id = self.notebook.GetPageCount() - 1
  806. self.notebook.SetSelection(0)
  807. panelsizer.Add(item=self.notebook, proportion=1, flag=wx.EXPAND )
  808. #
  809. # flags
  810. #
  811. text_style = wx.FONTWEIGHT_NORMAL
  812. visible_flags = [ f for f in self.task.flags if not f.get( 'hidden', 'no' ) == 'yes' ]
  813. for f in visible_flags:
  814. which_sizer = tabsizer[ f['guisection'] ]
  815. which_panel = tab[ f['guisection'] ]
  816. # if label is given: description -> tooltip
  817. if f.get('label','') != '':
  818. title = text_beautify( f['label'] )
  819. tooltip = text_beautify ( f['description'] )
  820. else:
  821. title = text_beautify( f['description'] )
  822. tooltip = None
  823. chk = wx.CheckBox(parent=which_panel, label = title, style = wx.NO_BORDER)
  824. if tooltip:
  825. chk.SetToolTipString(tooltip)
  826. if 'value' in f:
  827. chk.SetValue( f['value'] )
  828. # chk.SetFont(wx.Font(pointSize=fontsize, family=wx.FONTFAMILY_DEFAULT,
  829. # style=wx.NORMAL, weight=text_style))
  830. which_sizer.Add( item=chk, proportion=0,
  831. flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=5)
  832. f['wxId'] = chk.GetId()
  833. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  834. if f['name'] in ('verbose', 'quiet'):
  835. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  836. vq = UserSettings.Get(group='cmd', key='verbosity', subkey='selection')
  837. if f['name'] == vq:
  838. chk.SetValue(True)
  839. f['value'] = True
  840. elif f['name'] == 'overwrite':
  841. chk.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
  842. f['value'] = UserSettings.Get(group='cmd', key='overwrite', subkey='enabled')
  843. #
  844. # parameters
  845. #
  846. visible_params = [ p for p in self.task.params if not p.get( 'hidden', 'no' ) == 'yes' ]
  847. for p in visible_params:
  848. which_sizer = tabsizer[ p['guisection'] ]
  849. which_panel = tab[ p['guisection'] ]
  850. # if label is given -> label and description -> tooltip
  851. # otherwise description -> lavel
  852. if p.get('label','') != '':
  853. title = text_beautify( p['label'] )
  854. tooltip = text_beautify ( p['description'] )
  855. else:
  856. title = text_beautify( p['description'] )
  857. tooltip = None
  858. txt = None
  859. # text style (required -> bold)
  860. if p.get('required','no') == 'no':
  861. text_style = wx.FONTWEIGHT_NORMAL
  862. else:
  863. text_style = wx.FONTWEIGHT_BOLD
  864. # title expansion
  865. if p.get('multiple','no') == 'yes' and len( p.get('values','') ) == 0:
  866. title = _("[multiple]") + " " + title
  867. if p.get('value','') == '' :
  868. p['value'] = p.get('default','')
  869. if ( len(p.get('values', []) ) > 0):
  870. valuelist=map( str, p.get('values',[]) )
  871. if p.get('multiple', 'no') == 'yes' and \
  872. p.get('type', '') == 'string':
  873. txt = wx.StaticBox (parent=which_panel, id=0, label=" " + title + ": ")
  874. if len(valuelist) > 6:
  875. hSizer=wx.StaticBoxSizer ( box=txt, orient=wx.VERTICAL )
  876. else:
  877. hSizer=wx.StaticBoxSizer ( box=txt, orient=wx.HORIZONTAL )
  878. isEnabled = {}
  879. # copy default values
  880. if p['value'] == '':
  881. p['value'] = p.get('default', '')
  882. for defval in p.get('value', '').split(','):
  883. isEnabled[ defval ] = 'yes'
  884. # for multi checkboxes, this is an array of all wx IDs
  885. # for each individual checkbox
  886. p[ 'wxId' ] = []
  887. for val in valuelist:
  888. chkbox = wx.CheckBox( parent=which_panel, label = text_beautify(val) )
  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. which_sizer.Add( item=hSizer, proportion=0,
  896. flag=wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border=5 )
  897. else:
  898. if len(valuelist) == 1: # -> textctrl
  899. txt = wx.StaticText(parent=which_panel,
  900. label = "%s. %s %s" % (title, _('Valid range'),
  901. str(valuelist[0]) + ':'))
  902. which_sizer.Add(item=txt, proportion=0,
  903. flag=wx.ADJUST_MINSIZE | wx.TOP | wx.RIGHT | wx.LEFT, border=5)
  904. if p.get('type','') == 'integer' and \
  905. p.get('multiple','no') == 'no':
  906. # for multiple integers use textctrl instead of spinsctrl
  907. try:
  908. minValue, maxValue = map(int, valuelist[0].split('-'))
  909. except ValueError:
  910. minValue = -1e6
  911. maxValue = 1e6
  912. txt2 = wx.SpinCtrl(parent=which_panel, id=wx.ID_ANY, size=globalvar.DIALOG_SPIN_SIZE,
  913. min=minValue, max=maxValue)
  914. else:
  915. txt2 = wx.TextCtrl(parent=which_panel, value = p.get('default',''),
  916. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  917. if p.get('value','') != '':
  918. txt2.SetValue(p['value']) # parameter previously set
  919. which_sizer.Add(item=txt2, proportion=0,
  920. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  921. p['wxId'] = txt2.GetId()
  922. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  923. else:
  924. # list of values (combo)
  925. txt = wx.StaticText(parent=which_panel, label = title + ':' )
  926. which_sizer.Add(item=txt, proportion=0,
  927. flag=wx.ADJUST_MINSIZE | wx.TOP | wx.RIGHT | wx.LEFT, border=5)
  928. cb = wx.ComboBox(parent=which_panel, id=wx.ID_ANY, value=p.get('default',''),
  929. size=globalvar.DIALOG_COMBOBOX_SIZE,
  930. choices=valuelist, style=wx.CB_DROPDOWN)
  931. if p.get('value','') != '':
  932. cb.SetValue(p['value']) # parameter previously set
  933. which_sizer.Add( item=cb, proportion=0,
  934. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  935. p['wxId'] = cb.GetId()
  936. cb.Bind( wx.EVT_COMBOBOX, self.OnSetValue)
  937. # text entry
  938. if (p.get('type','string') in ('string','integer','float')
  939. and len(p.get('values',[])) == 0
  940. and p.get('gisprompt',False) == False
  941. and p.get('prompt','') != 'color'):
  942. txt = wx.StaticText(parent=which_panel, label = title + ':' )
  943. which_sizer.Add(item=txt, proportion=0,
  944. flag=wx.RIGHT | wx.LEFT | wx.TOP | wx.EXPAND, border=5)
  945. if p.get('multiple','yes') == 'yes' or \
  946. p.get('type', 'string') in ('string', 'float') or \
  947. len(p.get('key_desc', [])) > 1:
  948. txt3 = wx.TextCtrl(parent=which_panel, value = p.get('default',''),
  949. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  950. if p.get('value','') != '':
  951. txt3.SetValue(str(p['value'])) # parameter previously set
  952. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  953. else:
  954. minValue = -1e9
  955. maxValue = 1e9
  956. txt3 = wx.SpinCtrl(parent=which_panel, value=p.get('default',''),
  957. size=globalvar.DIALOG_SPIN_SIZE,
  958. min=minValue, max=maxValue)
  959. if p.get('value','') != '':
  960. txt3.SetValue(int(p['value'])) # parameter previously set
  961. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  962. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  963. which_sizer.Add(item=txt3, proportion=0, flag=wx.BOTTOM | wx.LEFT, border=5)
  964. p['wxId'] = txt3.GetId()
  965. if p.get('type','string') == 'string' and p.get('gisprompt',False) == True:
  966. txt = wx.StaticText(parent=which_panel, label = title + ':')
  967. which_sizer.Add(item=txt, proportion=0,
  968. flag=wx.ADJUST_MINSIZE | wx.RIGHT | wx.LEFT | wx.TOP, border=5)
  969. # element selection tree combobox (maps, icons, regions, etc.)
  970. if p.get('prompt','') != 'color' and p.get('element', '') != 'file':
  971. if p.get('multiple','no') == 'yes':
  972. multiple = True
  973. else:
  974. multiple = False
  975. if p.get('age','') == 'new':
  976. mapsets = [grassenv.GetGRASSVariable('MAPSET'),]
  977. else:
  978. mapsets = None
  979. selection = gselect.Select(parent=which_panel, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
  980. type=p.get('element',''), multiple=multiple, mapsets=mapsets)
  981. if p.get('value','') != '':
  982. selection.SetValue(p['value']) # parameter previously set
  983. which_sizer.Add(item=selection, proportion=0,
  984. flag=wx.ADJUST_MINSIZE| wx.BOTTOM | wx.LEFT | wx.RIGHT, border=5)
  985. # A select.Select is a combobox with two children: a textctl and a popupwindow;
  986. # we target the textctl here
  987. p['wxId'] = selection.GetChildren()[0].GetId()
  988. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  989. # color entry
  990. elif p.get('prompt','') == 'color':
  991. # Heuristic way of finding whether transparent is allowed
  992. handle_transparency = 'none' in title
  993. default_color = (200,200,200)
  994. label_color = _("Select Color")
  995. if p.get('default','') != '':
  996. default_color, label_color = color_resolve( p['default'] )
  997. if p.get('value','') != '': # parameter previously set
  998. default_color, label_color = color_resolve( p['value'] )
  999. if handle_transparency:
  1000. this_sizer = wx.BoxSizer(orient=wx.HORIZONTAL )
  1001. else:
  1002. this_sizer = which_sizer
  1003. btn_colour = csel.ColourSelect(parent=which_panel, id=wx.ID_ANY,
  1004. label=label_color, colour=default_color,
  1005. pos=wx.DefaultPosition, size=(150,-1) )
  1006. this_sizer.Add(item=btn_colour, proportion=0,
  1007. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  1008. # For color selectors, this is a two-member array, holding the IDs of
  1009. # the selector proper and either a "transparent" button or None
  1010. p['wxId'] = [btn_colour.GetId(),]
  1011. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange )
  1012. if handle_transparency:
  1013. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent") )
  1014. if p.get('value','') != '' and p.get('value',[''])[0] == "none":
  1015. none_check.SetValue(True)
  1016. else:
  1017. none_check.SetValue(False)
  1018. # none_check.SetFont( wx.Font( fontsize, wx.FONTFAMILY_DEFAULT, wx.NORMAL, text_style, 0, ''))
  1019. this_sizer.Add(item=none_check, proportion=0,
  1020. flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border=5)
  1021. which_sizer.Add( this_sizer )
  1022. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1023. p['wxId'].append( none_check.GetId() )
  1024. else:
  1025. p['wxId'].append(None)
  1026. # file selector
  1027. elif p.get('prompt','') != 'color' and p.get('element', '') == 'file':
  1028. fbb = filebrowse.FileBrowseButton(parent=which_panel, id=wx.ID_ANY,
  1029. size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
  1030. dialogTitle=_('Choose %s') % \
  1031. p.get('description',_('File')),
  1032. buttonText=_('Browse'),
  1033. startDirectory=os.getcwd(), fileMode=0,
  1034. changeCallback=self.OnSetValue)
  1035. if p.get('value','') != '':
  1036. fbb.SetValue(p['value']) # parameter previously set
  1037. which_sizer.Add(item=fbb, proportion=0,
  1038. flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.TOP | wx.RIGHT, border=-3)
  1039. # A file browse button is a combobox with two children:
  1040. # a textctl and a button;
  1041. # we have to target the button here
  1042. p['wxId'] = fbb.GetChildren()[1].GetId()
  1043. if txt is not None:
  1044. # txt.SetFont( wx.Font( fontsize, wx.FONTFAMILY_DEFAULT, wx.NORMAL, text_style, 0, ''))
  1045. # create tooltip if given
  1046. if len(p['values_desc']) > 0:
  1047. if tooltip:
  1048. tooltip += 2 * os.linesep
  1049. else:
  1050. tooltip = ''
  1051. if len(p['values']) == len(p['values_desc']):
  1052. for i in range(len(p['values'])):
  1053. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1054. tooltip.strip(os.linesep)
  1055. if tooltip:
  1056. txt.SetToolTipString(tooltip)
  1057. #
  1058. # determine panel size
  1059. #
  1060. maxsizes = (0,0)
  1061. for section in sections:
  1062. # tabsizer[section].SetSizeHints( tab[section] )
  1063. #tab[section].SetAutoLayout(True)
  1064. tab[section].SetSizer( tabsizer[section] )
  1065. tabsizer[section].Fit( tab[section] )
  1066. tab[section].Layout()
  1067. minsecsizes = tabsizer[section].GetSize()
  1068. maxsizes = map( lambda x: max( maxsizes[x], minsecsizes[x] ), (0,1) )
  1069. # TODO: be less arbitrary with these 600
  1070. self.panelMinHeight = 100
  1071. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1072. for section in sections:
  1073. tab[section].SetMinSize( (self.constrained_size[0], self.panelMinHeight) )
  1074. # tab[section].SetMinSize( constrained_size )
  1075. if self.manual_tab.Ok:
  1076. self.manual_tab.SetMinSize( (self.constrained_size[0], self.panelMinHeight) )
  1077. # manual_tab.SetMinSize( constrained_size )
  1078. self.SetSizer( panelsizer )
  1079. panelsizer.Fit(self.notebook)
  1080. self.hasMain = tab.has_key( _('Required') ) # publish, to enclosing Frame for instance
  1081. def OnVerbosity(self, event):
  1082. """Verbosity level changed"""
  1083. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'])
  1084. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'])
  1085. if event.IsChecked():
  1086. if event.GetId() == verbose.GetId():
  1087. if quiet.IsChecked():
  1088. quiet.SetValue(False)
  1089. self.task.get_flag('quiet')['value'] = False
  1090. else:
  1091. if verbose.IsChecked():
  1092. verbose.SetValue(False)
  1093. self.task.get_flag('verbose')['value'] = False
  1094. event.Skip()
  1095. def OnPageChange(self, event):
  1096. if not event:
  1097. sel = self.notebook.GetSelection()
  1098. else:
  1099. sel = event.GetSelection()
  1100. if hasattr(self, "manual_tab_id") and \
  1101. sel == self.manual_tab_id:
  1102. # calling LoadPage() is strangely time-consuming (only first call)
  1103. # FIXME: move to helpPage.__init__()
  1104. if not self.manual_tab.Ok:
  1105. wx.Yield()
  1106. self.manual_tab.LoadPage(self.manual_tab.fspath + self.task.name + ".html")
  1107. self.manual_tab.Ok = True
  1108. self.Layout()
  1109. def OnColorChange( self, event ):
  1110. myId = event.GetId()
  1111. for p in self.task.params:
  1112. if 'wxId' in p and type( p['wxId'] ) == type( [] ) and myId in p['wxId']:
  1113. has_button = p['wxId'][1] is not None
  1114. if has_button and wx.FindWindowById( p['wxId'][1] ).GetValue() == True:
  1115. p[ 'value' ] = 'none'
  1116. else:
  1117. colorchooser = wx.FindWindowById( p['wxId'][0] )
  1118. new_color = colorchooser.GetValue()[:]
  1119. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1120. # under wx2.8.1
  1121. new_label = rgb2str.get( new_color, ':'.join(map(str,new_color)) )
  1122. colorchooser.SetLabel( new_label )
  1123. colorchooser.SetColour( new_color )
  1124. colorchooser.Refresh()
  1125. p[ 'value' ] = colorchooser.GetLabel()
  1126. self.OnUpdateValues()
  1127. def OnUpdateValues(self):
  1128. """
  1129. If we were part of a richer interface, report back the current command being built.
  1130. This method should be set by the parent of this panel if needed. It's a hook, actually.
  1131. Beware of what is 'self' in the method def, though. It will be called with no arguments.
  1132. """
  1133. pass
  1134. def OnCheckBoxMulti(self, event):
  1135. """
  1136. Fill the values as a ','-separated string according to current status of the checkboxes.
  1137. """
  1138. me = event.GetId()
  1139. theParam = None
  1140. for p in self.task.params:
  1141. if 'wxId' in p and type( p['wxId'] ) == type( [] ) and me in p['wxId']:
  1142. theParam = p
  1143. myIndex = p['wxId'].index( me )
  1144. # Unpack current value list
  1145. currentValues = {}
  1146. for isThere in theParam.get('value', '').split(','):
  1147. currentValues[isThere] = 1
  1148. theValue = theParam['values'][myIndex]
  1149. if event.Checked():
  1150. currentValues[ theValue ] = 1
  1151. else:
  1152. del currentValues[ theValue ]
  1153. # Keep the original order, so that some defaults may be recovered
  1154. currentValueList = []
  1155. for v in theParam['values']:
  1156. if currentValues.has_key(v):
  1157. currentValueList.append( v )
  1158. # Pack it back
  1159. theParam['value'] = ','.join( currentValueList )
  1160. self.OnUpdateValues()
  1161. def OnSetValue(self, event):
  1162. """
  1163. Retrieve the widget value and set the task value field accordingly.
  1164. Use for widgets that have a proper GetValue() method, i.e. not for selectors.
  1165. """
  1166. myId = event.GetId()
  1167. me = wx.FindWindowById( myId )
  1168. for porf in self.task.params + self.task.flags:
  1169. if 'wxId' in porf and type( porf[ 'wxId' ] ) == type( 1 ) and porf['wxId'] == myId:
  1170. porf[ 'value' ] = me.GetValue()
  1171. self.OnUpdateValues()
  1172. def createCmd( self, ignoreErrors = False ):
  1173. """
  1174. Produce a command line string (list) or feeding into GRASS.
  1175. If ignoreErrors==True then it will return whatever has been
  1176. built so far, even though it would not be a correct command
  1177. for GRASS.
  1178. """
  1179. try:
  1180. cmd = self.task.getCmd( ignoreErrors=ignoreErrors )
  1181. except ValueError, err:
  1182. dlg = wx.MessageDialog(self, str(err), _("Error"), wx.OK | wx.ICON_ERROR)
  1183. dlg.ShowModal()
  1184. dlg.Destroy()
  1185. cmd = None
  1186. return cmd
  1187. def getInterfaceDescription( cmd ):
  1188. """
  1189. Returns the XML description for the GRASS cmd.
  1190. The DTD must be located in $GISBASE/etc/grass-interface.dtd,
  1191. otherwise the parser will not succeed.
  1192. Note: 'cmd' is given as string
  1193. """
  1194. cmdout = os.popen(cmd + r' --interface-description', "r").read()
  1195. if not len(cmdout) > 0 :
  1196. raise IOError, _("Unable to fetch interface description for command '%s'.") % cmd
  1197. p = re.compile( '(grass-interface.dtd)')
  1198. p.search( cmdout )
  1199. cmdout = p.sub(globalvar.ETCDIR + r'/grass-interface.dtd', cmdout)
  1200. return cmdout
  1201. class GrassGUIApp(wx.App):
  1202. """
  1203. Stand-alone GRASS command GUI
  1204. """
  1205. def __init__(self, grass_task):
  1206. self.grass_task = grass_task
  1207. wx.App.__init__(self, False)
  1208. def OnInit(self):
  1209. self.mf = mainFrame(parent=None, ID=wx.ID_ANY, task_description=self.grass_task)
  1210. self.mf.Show(True)
  1211. self.SetTopWindow(self.mf)
  1212. # print >> sys.stderr, time.time() - start
  1213. return True
  1214. class GUI:
  1215. """
  1216. Parses GRASS commands when module is imported and used
  1217. from Layer Manager.
  1218. """
  1219. def __init__(self, parent=-1):
  1220. self.parent = parent
  1221. self.grass_task = None
  1222. def ParseCommand(self, cmd, gmpath=None, completed=None, parentframe=-1, show=True, modal=False):
  1223. """
  1224. Parse command
  1225. Note: cmd is given as list
  1226. If command is given with options, return validated cmd list:
  1227. * add key name for first parameter if not given
  1228. * change mapname to mapname@mapset
  1229. """
  1230. start = time.time()
  1231. dcmd_params = {}
  1232. if completed == None:
  1233. get_dcmd = None
  1234. layer = None
  1235. dcmd_params = None
  1236. else:
  1237. get_dcmd = completed[0]
  1238. layer = completed[1]
  1239. if completed[2]:
  1240. dcmd_params.update(completed[2])
  1241. if parentframe != -1:
  1242. self.parent = parentframe
  1243. else:
  1244. self.parent = None
  1245. # parse the interface decription
  1246. self.grass_task = grassTask()
  1247. handler = processTask(self.grass_task)
  1248. xml.sax.parseString( getInterfaceDescription(cmd[0]), handler )
  1249. # if layer parameters previously set, re-insert them into dialog
  1250. if completed is not None:
  1251. if 'params' in dcmd_params:
  1252. self.grass_task.params = dcmd_params['params']
  1253. if 'flags' in dcmd_params:
  1254. self.grass_task.flags = dcmd_params['flags']
  1255. # update parameters if needed && validate command
  1256. if len(cmd) > 1:
  1257. i = 0
  1258. cmd_validated = [cmd[0]]
  1259. for option in cmd[1:]:
  1260. if option[0] == '-': # flag
  1261. self.grass_task.set_flag(option[1], True)
  1262. cmd_validated.append(option)
  1263. else: # parameter
  1264. try:
  1265. key, value = option.split('=', 1)
  1266. except:
  1267. if i == 0: # add key name of first parameter if not given
  1268. key = self.grass_task.firstParam
  1269. value = option
  1270. else:
  1271. raise ValueError, _("Unable to parse command %s") % ' '.join(cmd)
  1272. if self.grass_task.get_param(key)['element'] in ['cell', 'vector']:
  1273. # mapname -> mapname@mapset
  1274. if '@' not in value:
  1275. value = value + '@' + grassenv.GetGRASSVariable('MAPSET')
  1276. self.grass_task.set_param(key, value)
  1277. cmd_validated.append(key + '=' + value)
  1278. i = i + 1
  1279. # update original command list
  1280. cmd = cmd_validated
  1281. self.mf = mainFrame(parent=self.parent, ID=wx.ID_ANY,
  1282. task_description=self.grass_task,
  1283. get_dcmd=get_dcmd, layer=layer)
  1284. if get_dcmd is not None:
  1285. # update only propwin reference
  1286. get_dcmd(dcmd=None, layer=layer, params=None,
  1287. propwin=self.mf)
  1288. if show:
  1289. self.mf.Show(show)
  1290. self.mf.MakeModal(modal)
  1291. else:
  1292. self.mf.OnApply(None)
  1293. # print >> sys.stderr, time.time() - start
  1294. return cmd
  1295. def GetCommandInputMapParamKey(self, cmd):
  1296. """Get parameter key for input raster/vector map
  1297. @param cmd module name
  1298. @return parameter key
  1299. @return None on failure
  1300. """
  1301. # parse the interface decription
  1302. if not self.grass_task:
  1303. self.grass_task = grassTask()
  1304. handler = processTask(self.grass_task)
  1305. xml.sax.parseString(getInterfaceDescription(cmd), handler)
  1306. for p in self.grass_task.params:
  1307. if p.get('name', '') in ('input', 'map'):
  1308. age = p.get('age', '')
  1309. prompt = p.get('prompt', '')
  1310. element = p.get('element', '')
  1311. if age == 'old' and \
  1312. element in ('cell', 'grid3', 'vector') and \
  1313. prompt in ('raster', '3d-raster', 'vector'):
  1314. return p.get('name', None)
  1315. return None
  1316. class StaticWrapText(wx.StaticText):
  1317. """
  1318. A Static Text field that wraps its text to fit its width, enlarging its height if necessary.
  1319. """
  1320. def __init__(self, parent, id=wx.ID_ANY, label=u'', *args, **kwds):
  1321. self.originalLabel = label
  1322. wx.StaticText.__init__(self, parent, id, u'', *args, **kwds)
  1323. self.SetLabel(label)
  1324. self.Bind(wx.EVT_SIZE, self.onResize)
  1325. def SetLabel(self, label):
  1326. self.originalLabel = label
  1327. self.wrappedSize = None
  1328. #self.onResize(None)
  1329. def onResize(self, event):
  1330. if not getattr(self, "resizing", False):
  1331. self.resizing = True
  1332. newSize = self.GetSize()
  1333. if self.wrappedSize != newSize:
  1334. wx.StaticText.SetLabel(self, self.originalLabel)
  1335. self.Wrap(newSize.width)
  1336. self.wrappedSize = self.GetMinSize()
  1337. self.SetSize(self.wrappedSize)
  1338. del self.resizing
  1339. if __name__ == "__main__":
  1340. if len(sys.argv) == 1:
  1341. print _("usage: %s <grass command>") % sys.argv[0]
  1342. sys.exit()
  1343. if sys.argv[1] != 'test':
  1344. q=wx.LogNull()
  1345. GrassGUIApp( grassTask( sys.argv[1] ) ).MainLoop()
  1346. else: #Test
  1347. # Test grassTask from within a GRASS session
  1348. if os.getenv("GISBASE") is not None:
  1349. task = grassTask( "d.vect" )
  1350. task.get_param('map')['value'] = "map_name"
  1351. task.get_flag('v')['value'] = True
  1352. task.get_param('layer')['value'] = 1
  1353. task.get_param('bcolor')['value'] = "red"
  1354. assert ' '.join( task.getCmd() ) == "d.vect -v map=map_name layer=1 bcolor=red"
  1355. # Test interface building with handmade grassTask,
  1356. # possibly outside of a GRASS session.
  1357. task = grassTask()
  1358. task.name = "TestTask"
  1359. task.description = "This is an artificial grassTask() object intended for testing purposes."
  1360. task.keywords = ["grass","test","task"]
  1361. task.params = [
  1362. {
  1363. "name" : "text",
  1364. "description" : "Descriptions go into tooltips if labels are present, like this one",
  1365. "label" : "Enter some text",
  1366. },{
  1367. "name" : "hidden_text",
  1368. "description" : "This text should not appear in the form",
  1369. "hidden" : "yes"
  1370. },{
  1371. "name" : "text_default",
  1372. "description" : "Enter text to override the default",
  1373. "default" : "default text"
  1374. },{
  1375. "name" : "text_prefilled",
  1376. "description" : "You should see a friendly welcome message here",
  1377. "value" : "hello, world"
  1378. },{
  1379. "name" : "plain_color",
  1380. "description" : "This is a plain color, and it is a compulsory parameter",
  1381. "required" : "yes",
  1382. "gisprompt" : True,
  1383. "prompt" : "color"
  1384. },{
  1385. "name" : "transparent_color",
  1386. "description" : "This color becomes transparent when set to none",
  1387. "guisection" : "tab",
  1388. "gisprompt" : True,
  1389. "prompt" : "color"
  1390. },{
  1391. "name" : "multi",
  1392. "description" : "A multiple selection",
  1393. 'default': u'red,green,blue',
  1394. 'gisprompt': False,
  1395. 'guisection': 'tab',
  1396. 'multiple': u'yes',
  1397. 'type': u'string',
  1398. 'value': '',
  1399. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other']
  1400. },{
  1401. "name" : "single",
  1402. "description" : "A single multiple-choice selection",
  1403. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  1404. "guisection" : "tab"
  1405. },{
  1406. "name" : "large_multi",
  1407. "description" : "A large multiple selection",
  1408. "gisprompt" : False,
  1409. "multiple" : "yes",
  1410. # values must be an array of strings
  1411. "values" : str2rgb.keys() + map( str, str2rgb.values() )
  1412. },{
  1413. "name" : "a_file",
  1414. "description" : "A file selector",
  1415. "gisprompt" : True,
  1416. "element" : "file"
  1417. }
  1418. ]
  1419. task.flags = [
  1420. {
  1421. "name" : "a",
  1422. "description" : "Some flag, will appear in Main since it is required",
  1423. "required" : "yes"
  1424. },{
  1425. "name" : "b",
  1426. "description" : "pre-filled flag, will appear in options since it is not required",
  1427. "value" : True
  1428. },{
  1429. "name" : "hidden_flag",
  1430. "description" : "hidden flag, should not be changeable",
  1431. "hidden" : "yes",
  1432. "value" : True
  1433. }
  1434. ]
  1435. q=wx.LogNull()
  1436. GrassGUIApp( task ).MainLoop()