menuform.py 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591
  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. Bernhard Reiter <bernhard@intevation.de>
  29. Michael Barton, Arizona State University
  30. Daniel Calvelo <dca.gis@gmail.com>
  31. 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.flags = []
  158. if grassModule is not None:
  159. xml.sax.parseString( getInterfaceDescription( grassModule ) , processTask( self ) )
  160. def get_param( self, aParam ):
  161. """
  162. Find and return a param by name.
  163. """
  164. for p in self.params:
  165. lparam = len(aParam)
  166. if p['name'] == aParam or \
  167. p['name'][:lparam] == aParam:
  168. return p
  169. raise ValueError, _("Parameter not found: %s") % aParam
  170. def set_param(self, aParam, aValue):
  171. """
  172. Set param value/values.
  173. """
  174. param = self.get_param(aParam)
  175. param['value'] = aValue
  176. def get_flag( self, aFlag ):
  177. """
  178. Find and return a flag by name.
  179. """
  180. for f in self.flags:
  181. if f['name'] == aFlag:
  182. return f
  183. raise ValueError, _("Flag not found: %s") % aFlag
  184. def set_flag(self, aFlag, aValue):
  185. """
  186. Enable / disable flag.
  187. """
  188. param = self.get_flag(aFlag)
  189. param['value'] = aValue
  190. def getCmd(self, ignoreErrors = False):
  191. """
  192. Produce an array of command name and arguments for feeding
  193. into some execve-like command processor.
  194. If ignoreErrors==True then it will return whatever has been
  195. built so far, even though it would not be a correct command
  196. for GRASS.
  197. """
  198. cmd = [self.name]
  199. errors = 0
  200. errStr = ""
  201. for flag in self.flags:
  202. if 'value' in flag and flag['value']:
  203. if len(flag['name']) > 1: # e.g. overwrite
  204. cmd += [ '--' + flag['name'] ]
  205. else:
  206. cmd += [ '-' + flag['name'] ]
  207. for p in self.params:
  208. if p.get('value','') == '' and p.get('required','no') != 'no':
  209. if p.get('default', '') != '':
  210. cmd += [ '%s=%s' % ( p['name'], p['default'] ) ]
  211. else:
  212. cmd += [ '%s=%s' % ( p['name'], _('<required>') ) ]
  213. errStr += _("Parameter %(name)s (%(desc)s) is missing.\n") % \
  214. {'name' : p['name'], 'desc' : p['description']}
  215. errors += 1
  216. elif p.get('value','') != '' and p['value'] != p.get('default','') :
  217. # Output only values that have been set, and different from defaults
  218. cmd += [ '%s=%s' % ( p['name'], p['value'] ) ]
  219. if errors and not ignoreErrors:
  220. raise ValueError, errStr
  221. return cmd
  222. class processTask(HandlerBase):
  223. """
  224. A SAX handler for the --interface-description output, as
  225. defined in grass-interface.dtd. Extend or modify this and the
  226. DTD if the XML output of GRASS' parser is extended or modified.
  227. """
  228. def __init__(self, task_description):
  229. self.inLabelContent = False
  230. self.inDescriptionContent = False
  231. self.inDefaultContent = False
  232. self.inValueContent = False
  233. self.inParameter = False
  234. self.inFlag = False
  235. self.inGispromptContent = False
  236. self.inGuisection = False
  237. self.inKeywordsContent = False
  238. self.inFirstParameter = True
  239. self.task = task_description
  240. def startElement(self, name, attrs):
  241. if name == 'task':
  242. self.task.name = attrs.get('name', None)
  243. self.task.keywords = []
  244. if name == 'parameter':
  245. self.inParameter = True;
  246. self.param_label = ''
  247. self.param_description = ''
  248. self.param_default = ''
  249. self.param_values = []
  250. self.param_values_description = []
  251. self.param_gisprompt = False
  252. self.param_age = ''
  253. self.param_element = ''
  254. self.param_prompt = ''
  255. self.param_guisection = ''
  256. # Look for the parameter name, type, requiredness
  257. self.param_name = attrs.get('name', None)
  258. self.param_type = attrs.get('type', None)
  259. self.param_required = attrs.get('required', None)
  260. self.param_multiple = attrs.get('multiple', None)
  261. if name == 'flag':
  262. self.inFlag = True;
  263. self.flag_description = ''
  264. self.flag_default = ''
  265. self.flag_guisection = ''
  266. self.flag_values = []
  267. # Look for the flag name
  268. self.flag_name = attrs.get('name', None)
  269. if name == 'label':
  270. self.inLabelContent = True
  271. self.label = ''
  272. if name == 'description':
  273. self.inDescriptionContent = True
  274. self.description = ''
  275. if name == 'default':
  276. self.inDefaultContent = True
  277. self.param_default = ''
  278. if name == 'value':
  279. self.inValueContent = True
  280. self.value_tmp = ''
  281. if name == 'gisprompt':
  282. self.param_gisprompt = True
  283. self.param_age = attrs.get('age', None)
  284. self.param_element = attrs.get('element', None)
  285. self.param_prompt = attrs.get('prompt', None)
  286. if name == 'guisection':
  287. self.inGuisection = True
  288. self.guisection = ''
  289. if name == 'keywords':
  290. self.inKeywordsContent = True
  291. self.keyword = ''
  292. # works with python 2.0, but is not SAX compliant
  293. def characters(self, ch):
  294. self.my_characters(ch)
  295. def my_characters(self, ch):
  296. if self.inLabelContent:
  297. self.label = self.label + ch
  298. if self.inDescriptionContent:
  299. self.description = self.description + ch
  300. if self.inDefaultContent:
  301. self.param_default = self.param_default + ch
  302. if self.inValueContent and not self.inDescriptionContent:
  303. # Beware: value_tmp will get anything outside of a <description>
  304. # so in this snippet:
  305. # <values>
  306. # <value>
  307. # <name> a </name>
  308. # <description> a desc </description>
  309. # </value>
  310. # </values>
  311. # 'a desc' will not be recorded anwhere; this unburdens further
  312. # handling of value sets to distinguish between those that do define
  313. # descriptions and those that do not.
  314. #
  315. # TODO: a set of flags to treat this case of a description sub-element
  316. self.value_tmp = self.value_tmp + ch
  317. if self.inGuisection:
  318. self.guisection = self.guisection + ch
  319. if self.inKeywordsContent:
  320. self.keyword = self.keyword + ch
  321. def endElement(self, name):
  322. # If it's not a parameter element, ignore it
  323. if name == 'parameter':
  324. self.inParameter = False;
  325. # description -> label substitution is delegated to the client;
  326. # we deal in the parser only with getting interface-description
  327. # verbatim
  328. self.task.params.append({
  329. "name" : self.param_name,
  330. "type" : self.param_type,
  331. "required" : self.param_required,
  332. "multiple" : self.param_multiple,
  333. "label" : self.param_label,
  334. "description" : self.param_description,
  335. 'gisprompt' : self.param_gisprompt,
  336. 'age' : self.param_age,
  337. 'element' :self.param_element,
  338. 'prompt' : self.param_prompt,
  339. "guisection" : self.param_guisection,
  340. "default" : self.param_default,
  341. "values" : self.param_values,
  342. "values_desc" : self.param_values_description,
  343. "value" : ''})
  344. if self.inFirstParameter:
  345. self.task.firstParam = self.param_name # store name of first parameter
  346. self.inFirstParameter = False;
  347. if name == 'flag':
  348. self.inFlag = False;
  349. self.task.flags.append({
  350. "name" : self.flag_name,
  351. "description" : self.flag_description,
  352. "guisection" : self.flag_guisection } )
  353. if name == 'label':
  354. self.param_label = normalize_whitespace(self.label)
  355. if name == 'description':
  356. if self.inValueContent:
  357. self.param_values_description.append(normalize_whitespace(self.description))
  358. elif self.inParameter:
  359. self.param_description = normalize_whitespace(self.description)
  360. elif self.inFlag:
  361. self.flag_description = normalize_whitespace(self.description)
  362. else:
  363. self.task.description = normalize_whitespace(self.description)
  364. self.inDescriptionContent = False
  365. if name == 'default':
  366. self.param_default = normalize_whitespace(self.param_default)
  367. self.inDefaultContent = False
  368. if name == 'value':
  369. v = normalize_whitespace(self.value_tmp)
  370. self.param_values.append(normalize_whitespace(self.value_tmp))
  371. self.inValueContent = False
  372. if name == 'guisection':
  373. if self.inParameter:
  374. self.param_guisection = normalize_whitespace(self.guisection)
  375. elif self.inFlag:
  376. self.flag_guisection = normalize_whitespace(self.guisection)
  377. self.inGuisection = False
  378. if name == 'keywords':
  379. for keyword in self.keyword.split(','):
  380. self.task.keywords.append (normalize_whitespace(keyword))
  381. self.inKeywordsContent = False
  382. class helpPanel(wx.html.HtmlWindow):
  383. """
  384. This panel holds the text from GRASS docs.
  385. GISBASE must be set in the environment to find the html docs dir.
  386. The SYNOPSIS section is skipped, since this Panel is supposed to
  387. be integrated into the cmdPanel and options are obvious there.
  388. """
  389. def __init__(self, grass_command = "index", text = None,
  390. skip_description=False, *args, **kwargs):
  391. """ If grass_command is given, the corresponding HTML help file will
  392. be presented, with all links pointing to absolute paths of
  393. local files.
  394. If 'skip_description' is True, the HTML corresponding to
  395. SYNOPSIS will be skipped, thus only presenting the help file
  396. from the DESCRIPTION section onwards.
  397. If 'text' is given, it must be the HTML text to be presented in the Panel.
  398. """
  399. wx.html.HtmlWindow.__init__(self, *args, **kwargs)
  400. self.fspath = gisbase + "/docs/html/"
  401. self.SetStandardFonts ( size = 10 )
  402. self.SetBorders(10)
  403. wx.InitAllImageHandlers()
  404. if text is None:
  405. if skip_description:
  406. self.fillContentsFromFile ( self.fspath + grass_command + ".html",
  407. skip_description=skip_description )
  408. self.Ok = True
  409. else:
  410. ### FIXME: calling LoadPage() is strangely time-consuming (only first call)
  411. # self.LoadPage(self.fspath + grass_command + ".html")
  412. self.Ok = False
  413. else:
  414. self.SetPage( text )
  415. self.Ok = True
  416. def fillContentsFromFile( self, htmlFile, skip_description=True ):
  417. aLink = re.compile( r'(<a href="?)(.+\.html?["\s]*>)', re.IGNORECASE )
  418. imgLink = re.compile( r'(<img src="?)(.+\.[png|gif])', re.IGNORECASE )
  419. try:
  420. # contents = [ '<head><base href="%s"></head>' % self.fspath ]
  421. contents = []
  422. skip = False
  423. for l in file( htmlFile, "rb" ).readlines():
  424. if "DESCRIPTION" in l:
  425. skip = False
  426. if not skip:
  427. # do skip the options description if requested
  428. if "SYNOPSIS" in l:
  429. skip = skip_description
  430. else:
  431. # FIXME: find only first item
  432. findALink = aLink.search( l )
  433. if findALink is not None:
  434. contents.append( aLink.sub(findALink.group(1)+
  435. self.fspath+findALink.group(2),l) )
  436. findImgLink = imgLink.search( l )
  437. if findImgLink is not None:
  438. contents.append( imgLink.sub(findImgLink.group(1)+
  439. self.fspath+findImgLink.group(2),l) )
  440. if findALink is None and findImgLink is None:
  441. contents.append( l )
  442. self.SetPage( "".join( contents ) )
  443. self.Ok = True
  444. except: # The Manual file was not found
  445. self.Ok = False
  446. class mainFrame(wx.Frame):
  447. """
  448. This is the Frame containing the dialog for options input.
  449. The dialog is organized in a notebook according to the guisections
  450. defined by each GRASS command.
  451. If run with a parent, it may Apply, Ok or Cancel; the latter two close the dialog.
  452. The former two trigger a callback.
  453. If run standalone, it will allow execution of the command.
  454. The command is checked and sent to the clipboard when clicking 'Copy'.
  455. """
  456. def __init__(self, parent, ID, task_description, get_dcmd=None, layer=None):
  457. self.get_dcmd = get_dcmd
  458. self.layer = layer
  459. self.task = task_description
  460. self.parent = parent
  461. # module name + keywords
  462. title = self.task.name
  463. try:
  464. title += " [" + ', '.join( self.task.keywords ) + "]"
  465. except ValueError:
  466. pass
  467. wx.Frame.__init__(self, parent=parent, id=ID, title=title,
  468. pos=wx.DefaultPosition, style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)
  469. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  470. # statusbar
  471. self.CreateStatusBar()
  472. # icon
  473. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCDIR, 'grass_dialog.ico'), wx.BITMAP_TYPE_ICO))
  474. # menu
  475. # menu = wx.Menu()
  476. # menu.Append(wx.ID_ABOUT, _("&About GrassGUI"),
  477. # _("Information about GrassGUI") )
  478. # menu.Append(ID_ABOUT_COMMAND, _("&About %s") % self.task.name,
  479. # _("Short descripton of GRASS command %s") % self.task.name)
  480. # menu.AppendSeparator()
  481. # menu.Append(wx.ID_EXIT, _("E&xit"), _("Terminate the program") )
  482. # menuBar = wx.MenuBar()
  483. # menuBar.Append(menu, "&File");
  484. # self.SetMenuBar(menuBar)
  485. #wx.EVT_MENU(self, wx.ID_ABOUT, self.OnAbout)
  486. #wx.EVT_MENU(self, ID_ABOUT_COMMAND, self.OnAboutCommand)
  487. #wx.EVT_MENU(self, wx.ID_EXIT, self.OnCancel)
  488. guisizer = wx.BoxSizer(wx.VERTICAL)
  489. # set apropriate output window
  490. if self.parent:
  491. self.standalone = False
  492. else:
  493. self.standalone = True
  494. # try:
  495. # self.goutput = self.parent.GetLogWindow()
  496. # except:
  497. # self.goutput = None
  498. # logo+description
  499. topsizer = wx.BoxSizer(wx.HORIZONTAL)
  500. # GRASS logo
  501. self.logo = wx.StaticBitmap(parent=self.panel,
  502. bitmap=wx.Bitmap(name=os.path.join(imagepath,
  503. 'grass_form.png'),
  504. type=wx.BITMAP_TYPE_PNG))
  505. topsizer.Add (item=self.logo, proportion=0, border=3,
  506. flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
  507. guisizer.Add (item=topsizer, proportion=0, flag=wx.EXPAND)
  508. # notebooks
  509. self.notebookpanel = cmdPanel (parent=self.panel, task=self.task, standalone=self.standalone,
  510. mainFrame=self)
  511. ### add 'command output' tab also for dialog open from menu
  512. # if self.standalone:
  513. self.goutput = self.notebookpanel.goutput
  514. self.notebookpanel.OnUpdateValues = self.updateValuesHook
  515. guisizer.Add (item=self.notebookpanel, proportion=1, flag=wx.EXPAND)
  516. # status bar
  517. status_text = _("Enter parameters for ") + self.task.name
  518. if self.notebookpanel.hasMain:
  519. # We have to wait for the notebookpanel to be filled in order
  520. # to know if there actually is a Main tab
  521. status_text += _(" (those in bold typeface are required)")
  522. try:
  523. self.task.getCmd()
  524. self.updateValuesHook()
  525. except ValueError:
  526. self.SetStatusText( status_text )
  527. # buttons
  528. btnsizer = wx.BoxSizer(orient=wx.HORIZONTAL)
  529. # cancel
  530. btn_cancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
  531. btn_cancel.SetToolTipString(_("Cancel the command settings and ignore changes"))
  532. btnsizer.Add(item=btn_cancel, proportion=0, flag=wx.ALL | wx.ALIGN_CENTER, border=10)
  533. btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  534. if self.get_dcmd is not None: # A callback has been set up
  535. btn_apply = wx.Button(parent=self.panel, id=wx.ID_APPLY)
  536. btn_ok = wx.Button(parent=self.panel, id=wx.ID_OK)
  537. btn_ok.SetDefault()
  538. btnsizer.Add(item=btn_apply, proportion=0,
  539. flag=wx.ALL | wx.ALIGN_CENTER,
  540. border=10)
  541. btnsizer.Add(item=btn_ok, proportion=0,
  542. flag=wx.ALL | wx.ALIGN_CENTER,
  543. border=10)
  544. btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
  545. btn_ok.Bind(wx.EVT_BUTTON, self.OnOK)
  546. else: # We're standalone
  547. # run
  548. self.btn_run = wx.Button(parent=self.panel, id=wx.ID_OK, label= _("&Run"))
  549. self.btn_run.SetToolTipString(_("Run the command"))
  550. self.btn_run.SetDefault()
  551. # abort
  552. self.btn_abort = wx.Button(parent=self.panel, id=wx.ID_STOP)
  553. self.btn_abort.SetToolTipString(_("Abort the running command"))
  554. # copy
  555. btn_clipboard = wx.Button(parent=self.panel, id=wx.ID_COPY)
  556. btn_clipboard.SetToolTipString(_("Copy the current command string to the clipboard"))
  557. btnsizer.Add(item=self.btn_abort, proportion=0,
  558. flag=wx.ALL | wx.ALIGN_CENTER,
  559. border=10)
  560. btnsizer.Add(item=self.btn_run, proportion=0,
  561. flag=wx.ALL | wx.ALIGN_CENTER,
  562. border=10)
  563. btnsizer.Add(item=btn_clipboard, proportion=0,
  564. flag=wx.ALL | wx.ALIGN_CENTER,
  565. border=10)
  566. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  567. self.btn_abort.Bind(wx.EVT_BUTTON, self.OnAbort)
  568. btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
  569. guisizer.Add(item=btnsizer, proportion=0, flag=wx.ALIGN_CENTER)
  570. if self.get_dcmd is None:
  571. # close dialog when command is terminated
  572. self.closebox = wx.CheckBox(parent=self.panel,
  573. label=_('Close dialog on finish'), style = wx.NO_BORDER)
  574. self.closebox.SetValue(UserSettings.Get(group='cmd', key='closeDlg', subkey='enabled'))
  575. guisizer.Add(item=self.closebox, proportion=0,
  576. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  577. border=5)
  578. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  579. #constrained_size = self.notebookpanel.GetSize()
  580. # 80 takes the tabbar into account
  581. #self.notebookpanel.SetSize( (constrained_size[0] + 25, constrained_size[1]) )
  582. #self.notebookpanel.Layout()
  583. #
  584. # put module description
  585. #
  586. self.description = StaticWrapText (parent=self.panel, label=self.task.description)
  587. topsizer.Add (item=self.description, proportion=1, border=5,
  588. flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  589. #
  590. # do layout
  591. #
  592. guisizer.SetSizeHints(self.panel)
  593. # called automatically by SetSizer()
  594. self.panel.SetAutoLayout(True)
  595. self.panel.SetSizer(guisizer)
  596. guisizer.Fit(self.panel)
  597. sizeFrame = self.GetBestSize()
  598. self.SetMinSize(sizeFrame)
  599. self.SetSize((sizeFrame[0], sizeFrame[1] +
  600. self.notebookpanel.constrained_size[1] -
  601. self.notebookpanel.panelMinHeight))
  602. self.Layout()
  603. def updateValuesHook(self):
  604. """Update status bar data"""
  605. self.SetStatusText(' '.join(self.notebookpanel.createCmd(ignoreErrors = True)) )
  606. def OnOK(self, event):
  607. """OK button pressed"""
  608. cmd = self.OnApply(event)
  609. if cmd is not None and self.get_dcmd is not None:
  610. self.OnCancel(event)
  611. def OnApply(self, event):
  612. """Apply the command"""
  613. cmd = self.createCmd()
  614. if cmd is not None and self.get_dcmd is not None:
  615. # return d.* command to layer tree for rendering
  616. self.get_dcmd(cmd, self.layer, {"params": self.task.params,
  617. "flags" :self.task.flags},
  618. self)
  619. # echo d.* command to output console
  620. # self.parent.writeDCommand(cmd)
  621. return cmd
  622. def OnRun(self, event):
  623. """Run the command"""
  624. if len(self.goutput.GetListOfCmdThreads()) > 0:
  625. return
  626. cmd = self.createCmd()
  627. if cmd == [] or cmd == None:
  628. return
  629. # change page if needed
  630. if self.notebookpanel.notebook.GetSelection() != self.notebookpanel.goutput.pageid:
  631. self.notebookpanel.notebook.SetSelection(self.notebookpanel.goutput.pageid)
  632. if cmd[0][0:2] != "d.":
  633. # Send any non-display command to parent window (probably wxgui.py)
  634. # put to parents
  635. try:
  636. self.goutput.RunCmd(cmd)
  637. except AttributeError,e:
  638. print >> sys.stderr, "%s: Propably not running in wxgui.py session?" % (e)
  639. print >> sys.stderr, "parent window is: %s" % (str(self.parent))
  640. # Send any other command to the shell.
  641. else:
  642. gcmd.Command(cmd)
  643. # update buttons status
  644. self.btn_run.Enable(False)
  645. self.btn_abort.Enable(True)
  646. def OnAbort(self, event):
  647. """Abort running command"""
  648. try:
  649. self.goutput.GetListOfCmdThreads()[0].abort()
  650. except IndexError:
  651. pass
  652. self.btn_run.Enable(True)
  653. self.btn_abort.Enable(False)
  654. def OnCopy(self, event):
  655. """Copy the command"""
  656. cmddata = wx.TextDataObject()
  657. # list -> string
  658. cmdstring = ' '.join(self.createCmd(ignoreErrors=True))
  659. cmddata.SetText(cmdstring)
  660. if wx.TheClipboard.Open():
  661. wx.TheClipboard.UsePrimarySelection(True)
  662. wx.TheClipboard.SetData(cmddata)
  663. wx.TheClipboard.Close()
  664. self.SetStatusText( _("'%s' copied to clipboard") % \
  665. (cmdstring))
  666. def OnCancel(self, event):
  667. """Cancel button pressed"""
  668. self.MakeModal(False)
  669. if self.get_dcmd:
  670. self.Hide()
  671. else:
  672. self.Destroy()
  673. def OnCloseWindow(self, event):
  674. """Close the main window"""
  675. self.MakeModal(False)
  676. self.Destroy()
  677. def OnAbout(self, event):
  678. """General 'about' information"""
  679. dlg = wx.MessageDialog(self, _("This is a sample program for\n"
  680. "GRASS command interface parsing\n"
  681. "and automatic GUI building.\n%s") %(__version__),
  682. _("About wxPython GRASS GUI"), wx.OK | wx.ICON_INFORMATION)
  683. dlg.ShowModal()
  684. dlg.Destroy()
  685. def OnAboutCommand(self, event):
  686. """About command"""
  687. dlg = wx.MessageDialog(self,
  688. self.task.name+": "+self.task.description,
  689. "About " + self.task.name,
  690. wx.OK | wx.ICON_INFORMATION)
  691. dlg.ShowModal()
  692. dlg.Destroy()
  693. def createCmd(self, ignoreErrors = False):
  694. """Create command string (python list)"""
  695. return self.notebookpanel.createCmd(ignoreErrors=ignoreErrors)
  696. class cmdPanel(wx.Panel):
  697. """
  698. A panel containing a notebook dividing in tabs the different guisections of the GRASS cmd.
  699. """
  700. def __init__( self, parent, task, standalone, mainFrame, *args, **kwargs ):
  701. wx.Panel.__init__( self, parent, *args, **kwargs )
  702. self.parent = mainFrame
  703. self.task = task
  704. fontsize = 10
  705. # Determine tab layout
  706. sections = []
  707. is_section = {}
  708. not_hidden = [ p for p in self.task.params + self.task.flags if not p.get( 'hidden','no' ) == 'yes' ]
  709. for task in not_hidden:
  710. if task.get( 'required','no' ) == 'yes':
  711. # All required go into Main, even if they had defined another guisection
  712. task['guisection'] = _( 'Required' )
  713. if task.get( 'guisection','' ) == '':
  714. # Undefined guisections end up into Options
  715. task['guisection'] = _( 'Optional' )
  716. if not is_section.has_key(task['guisection']):
  717. # We do it like this to keep the original order, except for Main which goes first
  718. is_section[task['guisection']] = 1
  719. sections.append( task['guisection'] )
  720. else:
  721. is_section[ task['guisection'] ] += 1
  722. del is_section
  723. # 'Required' tab goes first, 'Optional' as the last one
  724. for (newidx,content) in [ (0,_( 'Required' )), (len(sections)-1,_('Optional')) ]:
  725. if content in sections:
  726. idx = sections.index( content )
  727. sections[idx:idx+1] = []
  728. sections[newidx:newidx] = [content]
  729. panelsizer = wx.BoxSizer(orient=wx.VERTICAL)
  730. # Build notebook
  731. nbStyle = globalvar.FNPageStyle
  732. self.notebook = FN.FlatNotebook( self, id=wx.ID_ANY, style=nbStyle)
  733. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  734. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  735. tab = {}
  736. tabsizer = {}
  737. for section in sections:
  738. tab[section] = wx.ScrolledWindow( parent=self.notebook )
  739. tab[section].SetScrollRate(10,10)
  740. tabsizer[section] = wx.BoxSizer(orient=wx.VERTICAL)
  741. self.notebook.AddPage( tab[section], text=section )
  742. # are we running from command line?
  743. ### add 'command output' tab regardless standalone dialog
  744. if self.parent.get_dcmd is None:
  745. self.goutput = goutput.GMConsole(parent=self, margin=False,
  746. pageid=self.notebook.GetPageCount())
  747. self.outpage = self.notebook.AddPage(self.goutput, text=_("Command output") )
  748. else:
  749. self.goutput = None
  750. self.manual_tab = helpPanel(parent = self.notebook, grass_command = self.task.name)
  751. self.manual_tabsizer = wx.BoxSizer(wx.VERTICAL)
  752. self.notebook.AddPage(self.manual_tab, text=_("Manual"))
  753. self.manual_tab_id = self.notebook.GetPageCount() - 1
  754. self.notebook.SetSelection(0)
  755. panelsizer.Add(item=self.notebook, proportion=1, flag=wx.EXPAND )
  756. #
  757. # flags
  758. #
  759. text_style = wx.FONTWEIGHT_NORMAL
  760. visible_flags = [ f for f in self.task.flags if not f.get( 'hidden', 'no' ) == 'yes' ]
  761. for f in visible_flags:
  762. which_sizer = tabsizer[ f['guisection'] ]
  763. which_panel = tab[ f['guisection'] ]
  764. # if label is given -> label and description -> tooltip
  765. # otherwise description -> lavel
  766. if p.get('label','') != '':
  767. title = text_beautify( f['label'] )
  768. tooltip = text_beautify ( f['description'] )
  769. else:
  770. title = text_beautify( f['description'] )
  771. tooltip = None
  772. chk = wx.CheckBox(parent=which_panel, label = title, style = wx.NO_BORDER)
  773. if tooltip:
  774. chk.SetToolTipString(tooltip)
  775. if 'value' in f:
  776. chk.SetValue( f['value'] )
  777. # chk.SetFont(wx.Font(pointSize=fontsize, family=wx.FONTFAMILY_DEFAULT,
  778. # style=wx.NORMAL, weight=text_style))
  779. which_sizer.Add( item=chk, proportion=0,
  780. flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=5)
  781. f['wxId'] = chk.GetId()
  782. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  783. if f['name'] in ('verbose', 'quiet'):
  784. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  785. vq = UserSettings.Get(group='cmd', key='verbosity', subkey='selection')
  786. if f['name'] == vq:
  787. chk.SetValue(True)
  788. f['value'] = True
  789. elif f['name'] == 'overwrite':
  790. chk.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
  791. f['value'] = True
  792. #
  793. # parameters
  794. #
  795. visible_params = [ p for p in self.task.params if not p.get( 'hidden', 'no' ) == 'yes' ]
  796. for p in visible_params:
  797. which_sizer = tabsizer[ p['guisection'] ]
  798. which_panel = tab[ p['guisection'] ]
  799. # if label is given -> label and description -> tooltip
  800. # otherwise description -> lavel
  801. if p.get('label','') != '':
  802. title = text_beautify( p['label'] )
  803. tooltip = text_beautify ( p['description'] )
  804. else:
  805. title = text_beautify( p['description'] )
  806. tooltip = None
  807. txt = None
  808. # text style (required -> bold)
  809. if p.get('required','no') == 'no':
  810. text_style = wx.FONTWEIGHT_NORMAL
  811. else:
  812. text_style = wx.FONTWEIGHT_BOLD
  813. # title expansion
  814. if p.get('multiple','no') == 'yes' and len( p.get('values','') ) == 0:
  815. title = _("[multiple]") + " " + title
  816. if p.get('value','') == '' :
  817. p['value'] = p.get('default','')
  818. if ( len(p.get('values', []) ) > 0):
  819. valuelist=map( str, p.get('values',[]) )
  820. if p.get('multiple', 'no') == 'yes' and \
  821. p.get('type', '') == 'string':
  822. txt = wx.StaticBox (parent=which_panel, id=0, label=" " + title + ": ")
  823. if len(valuelist) > 6:
  824. hSizer=wx.StaticBoxSizer ( box=txt, orient=wx.VERTICAL )
  825. else:
  826. hSizer=wx.StaticBoxSizer ( box=txt, orient=wx.HORIZONTAL )
  827. isEnabled = {}
  828. # copy default values
  829. if p['value'] == '':
  830. p['value'] = p.get('default', '')
  831. for defval in p.get('value', '').split(','):
  832. isEnabled[ defval ] = 'yes'
  833. # for multi checkboxes, this is an array of all wx IDs
  834. # for each individual checkbox
  835. p[ 'wxId' ] = []
  836. for val in valuelist:
  837. chkbox = wx.CheckBox( parent=which_panel, label = text_beautify(val) )
  838. p[ 'wxId' ].append( chkbox.GetId() )
  839. if isEnabled.has_key(val):
  840. chkbox.SetValue( True )
  841. hSizer.Add( item=chkbox, proportion=0,
  842. flag=wx.ADJUST_MINSIZE | wx.ALL, border=1 )
  843. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  844. which_sizer.Add( item=hSizer, proportion=0,
  845. flag=wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border=5 )
  846. else:
  847. if len(valuelist) == 1: # -> textctrl
  848. txt = wx.StaticText(parent=which_panel,
  849. label = "%s. %s %s" % (title, _('Valid range'),
  850. str(valuelist[0]) + ':'))
  851. which_sizer.Add(item=txt, proportion=0,
  852. flag=wx.ADJUST_MINSIZE | wx.TOP | wx.RIGHT | wx.LEFT, border=5)
  853. if p.get('type','') == 'integer' and \
  854. p.get('multiple','no') == 'no':
  855. # for multiple integers use textctrl instead of spinsctrl
  856. try:
  857. minValue, maxValue = map(int, valuelist[0].split('-'))
  858. except ValueError:
  859. minValue = -1e6
  860. maxValue = 1e6
  861. txt2 = wx.SpinCtrl(parent=which_panel, id=wx.ID_ANY, size=globalvar.DIALOG_SPIN_SIZE,
  862. min=minValue, max=maxValue)
  863. else:
  864. txt2 = wx.TextCtrl(parent=which_panel, value = p.get('default',''),
  865. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  866. if p.get('value','') != '':
  867. txt2.SetValue(p['value']) # parameter previously set
  868. which_sizer.Add(item=txt2, proportion=0,
  869. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  870. p['wxId'] = txt2.GetId()
  871. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  872. else:
  873. # list of values (combo)
  874. txt = wx.StaticText(parent=which_panel, label = title + ':' )
  875. which_sizer.Add(item=txt, proportion=0,
  876. flag=wx.ADJUST_MINSIZE | wx.TOP | wx.RIGHT | wx.LEFT, border=5)
  877. cb = wx.ComboBox(parent=which_panel, id=wx.ID_ANY, value=p.get('default',''),
  878. size=globalvar.DIALOG_COMBOBOX_SIZE,
  879. choices=valuelist, style=wx.CB_DROPDOWN)
  880. if p.get('value','') != '':
  881. cb.SetValue(p['value']) # parameter previously set
  882. which_sizer.Add( item=cb, proportion=0,
  883. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  884. p['wxId'] = cb.GetId()
  885. cb.Bind( wx.EVT_COMBOBOX, self.OnSetValue)
  886. # text entry
  887. if (p.get('type','string') in ('string','integer','float')
  888. and len(p.get('values',[])) == 0
  889. and p.get('gisprompt',False) == False
  890. and p.get('prompt','') != 'color'):
  891. txt = wx.StaticText(parent=which_panel, label = title + ':' )
  892. which_sizer.Add(item=txt, proportion=0,
  893. flag=wx.RIGHT | wx.LEFT | wx.TOP | wx.EXPAND, border=5)
  894. if p.get('multiple','yes') == 'yes' or \
  895. p.get('type','string') == 'string':
  896. txt3 = wx.TextCtrl(parent=which_panel, value = p.get('default',''),
  897. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  898. if p.get('value','') != '':
  899. txt3.SetValue(str(p['value'])) # parameter previously set
  900. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  901. else:
  902. minValue = -1e9
  903. maxValue = 1e9
  904. txt3 = wx.SpinCtrl(parent=which_panel, value=p.get('default',''),
  905. size=globalvar.DIALOG_SPIN_SIZE,
  906. min=minValue, max=maxValue)
  907. if p.get('value','') != '':
  908. txt3.SetValue(int(p['value'])) # parameter previously set
  909. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  910. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  911. which_sizer.Add(item=txt3, proportion=0, flag=wx.BOTTOM | wx.LEFT, border=5)
  912. p['wxId'] = txt3.GetId()
  913. if p.get('type','string') == 'string' and p.get('gisprompt',False) == True:
  914. txt = wx.StaticText(parent=which_panel, label = title + ':')
  915. which_sizer.Add(item=txt, proportion=0,
  916. flag=wx.ADJUST_MINSIZE | wx.RIGHT | wx.LEFT | wx.TOP, border=5)
  917. # element selection tree combobox (maps, icons, regions, etc.)
  918. if p.get('prompt','') != 'color' and p.get('element', '') != 'file':
  919. if p.get('multiple','no') == 'yes':
  920. multiple = True
  921. else:
  922. multiple = False
  923. if p.get('age','') == 'new':
  924. mapsets = [grassenv.GetGRASSVariable('MAPSET'),]
  925. else:
  926. mapsets = None
  927. selection = gselect.Select(parent=which_panel, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
  928. type=p.get('element',''), multiple=multiple, mapsets=mapsets)
  929. if p.get('value','') != '':
  930. selection.SetValue(p['value']) # parameter previously set
  931. which_sizer.Add(item=selection, proportion=0,
  932. flag=wx.ADJUST_MINSIZE| wx.BOTTOM | wx.LEFT | wx.RIGHT, border=5)
  933. # A select.Select is a combobox with two children: a textctl and a popupwindow;
  934. # we target the textctl here
  935. p['wxId'] = selection.GetChildren()[0].GetId()
  936. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  937. # color entry
  938. elif p.get('prompt','') == 'color':
  939. # Heuristic way of finding whether transparent is allowed
  940. handle_transparency = 'none' in title
  941. default_color = (200,200,200)
  942. label_color = _("Select Color")
  943. if p.get('default','') != '':
  944. default_color, label_color = color_resolve( p['default'] )
  945. if p.get('value','') != '': # parameter previously set
  946. default_color, label_color = color_resolve( p['value'] )
  947. if handle_transparency:
  948. this_sizer = wx.BoxSizer(orient=wx.HORIZONTAL )
  949. else:
  950. this_sizer = which_sizer
  951. btn_colour = csel.ColourSelect(parent=which_panel, id=wx.ID_ANY,
  952. label=label_color, colour=default_color,
  953. pos=wx.DefaultPosition, size=(150,-1) )
  954. this_sizer.Add(item=btn_colour, proportion=0,
  955. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  956. # For color selectors, this is a two-member array, holding the IDs of
  957. # the selector proper and either a "transparent" button or None
  958. p['wxId'] = [btn_colour.GetId(),]
  959. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange )
  960. if handle_transparency:
  961. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent") )
  962. if p.get('value','') != '' and p.get('value',[''])[0] == "none":
  963. none_check.SetValue(True)
  964. else:
  965. none_check.SetValue(False)
  966. # none_check.SetFont( wx.Font( fontsize, wx.FONTFAMILY_DEFAULT, wx.NORMAL, text_style, 0, ''))
  967. this_sizer.Add(item=none_check, proportion=0,
  968. flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border=5)
  969. which_sizer.Add( this_sizer )
  970. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  971. p['wxId'].append( none_check.GetId() )
  972. else:
  973. p['wxId'].append(None)
  974. # file selector
  975. elif p.get('prompt','') != 'color' and p.get('element', '') == 'file':
  976. fbb = filebrowse.FileBrowseButton(parent=which_panel, id=wx.ID_ANY,
  977. size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
  978. dialogTitle=_('Choose %s') % \
  979. p.get('description',_('File')),
  980. buttonText=_('Browse'),
  981. startDirectory=os.getcwd(), fileMode=0,
  982. changeCallback=self.OnSetValue)
  983. if p.get('value','') != '':
  984. fbb.SetValue(p['value']) # parameter previously set
  985. which_sizer.Add(item=fbb, proportion=0,
  986. flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.TOP | wx.RIGHT, border=-3)
  987. # A file browse button is a combobox with two children:
  988. # a textctl and a button;
  989. # we have to target the button here
  990. p['wxId'] = fbb.GetChildren()[1].GetId()
  991. if txt is not None:
  992. # txt.SetFont( wx.Font( fontsize, wx.FONTFAMILY_DEFAULT, wx.NORMAL, text_style, 0, ''))
  993. # create tooltip if given
  994. if len(p['values_desc']) > 0:
  995. if tooltip:
  996. tooltip += 2 * os.linesep
  997. else:
  998. tooltip = ''
  999. if len(p['values']) == len(p['values_desc']):
  1000. for i in range(len(p['values'])):
  1001. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1002. tooltip.strip(os.linesep)
  1003. if tooltip:
  1004. txt.SetToolTipString(tooltip)
  1005. #
  1006. # determine panel size
  1007. #
  1008. maxsizes = (0,0)
  1009. for section in sections:
  1010. # tabsizer[section].SetSizeHints( tab[section] )
  1011. #tab[section].SetAutoLayout(True)
  1012. tab[section].SetSizer( tabsizer[section] )
  1013. tabsizer[section].Fit( tab[section] )
  1014. tab[section].Layout()
  1015. minsecsizes = tabsizer[section].GetSize()
  1016. maxsizes = map( lambda x: max( maxsizes[x], minsecsizes[x] ), (0,1) )
  1017. # TODO: be less arbitrary with these 600
  1018. self.panelMinHeight = 100
  1019. self.constrained_size = (min(600, maxsizes[0]) + 25, min(600, maxsizes[1]) + 25)
  1020. for section in sections:
  1021. tab[section].SetMinSize( (self.constrained_size[0], self.panelMinHeight) )
  1022. # tab[section].SetMinSize( constrained_size )
  1023. if self.manual_tab.Ok:
  1024. self.manual_tab.SetMinSize( (self.constrained_size[0], self.panelMinHeight) )
  1025. # manual_tab.SetMinSize( constrained_size )
  1026. self.SetSizer( panelsizer )
  1027. panelsizer.Fit(self.notebook)
  1028. self.hasMain = tab.has_key( _('Required') ) # publish, to enclosing Frame for instance
  1029. def OnVerbosity(self, event):
  1030. """Verbosity level changed"""
  1031. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'])
  1032. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'])
  1033. if event.IsChecked():
  1034. if event.GetId() == verbose.GetId():
  1035. if quiet.IsChecked():
  1036. quiet.SetValue(False)
  1037. self.task.get_flag('quiet')['value'] = False
  1038. else:
  1039. if verbose.IsChecked():
  1040. verbose.SetValue(False)
  1041. self.task.get_flag('verbose')['value'] = False
  1042. event.Skip()
  1043. def OnPageChange(self, event):
  1044. if hasattr(self, "manual_tab_id") and \
  1045. event.GetSelection() == self.manual_tab_id:
  1046. # calling LoadPage() is strangely time-consuming (only first call)
  1047. # FIXME: move to helpPage.__init__()
  1048. if not self.manual_tab.Ok:
  1049. self.manual_tab.LoadPage(self.manual_tab.fspath + self.task.name + ".html")
  1050. self.manual_tab.Ok = True
  1051. self.Layout()
  1052. def OnColorChange( self, event ):
  1053. myId = event.GetId()
  1054. for p in self.task.params:
  1055. if 'wxId' in p and type( p['wxId'] ) == type( [] ) and myId in p['wxId']:
  1056. has_button = p['wxId'][1] is not None
  1057. if has_button and wx.FindWindowById( p['wxId'][1] ).GetValue() == True:
  1058. p[ 'value' ] = 'none'
  1059. else:
  1060. colorchooser = wx.FindWindowById( p['wxId'][0] )
  1061. new_color = colorchooser.GetValue()[:]
  1062. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1063. # under wx2.8.1
  1064. new_label = rgb2str.get( new_color, ':'.join(map(str,new_color)) )
  1065. colorchooser.SetLabel( new_label )
  1066. colorchooser.SetColour( new_color )
  1067. colorchooser.Refresh()
  1068. p[ 'value' ] = colorchooser.GetLabel()
  1069. self.OnUpdateValues()
  1070. def OnUpdateValues(self):
  1071. """
  1072. If we were part of a richer interface, report back the current command being built.
  1073. This method should be set by the parent of this panel if needed. It's a hook, actually.
  1074. Beware of what is 'self' in the method def, though. It will be called with no arguments.
  1075. """
  1076. pass
  1077. def OnCheckBoxMulti(self, event):
  1078. """
  1079. Fill the values as a ','-separated string according to current status of the checkboxes.
  1080. """
  1081. me = event.GetId()
  1082. theParam = None
  1083. for p in self.task.params:
  1084. if 'wxId' in p and type( p['wxId'] ) == type( [] ) and me in p['wxId']:
  1085. theParam = p
  1086. myIndex = p['wxId'].index( me )
  1087. # Unpack current value list
  1088. currentValues = {}
  1089. for isThere in theParam.get('value', '').split(','):
  1090. currentValues[isThere] = 1
  1091. theValue = theParam['values'][myIndex]
  1092. if event.Checked():
  1093. currentValues[ theValue ] = 1
  1094. else:
  1095. del currentValues[ theValue ]
  1096. # Keep the original order, so that some defaults may be recovered
  1097. currentValueList = []
  1098. for v in theParam['values']:
  1099. if currentValues.has_key(v):
  1100. currentValueList.append( v )
  1101. # Pack it back
  1102. theParam['value'] = ','.join( currentValueList )
  1103. self.OnUpdateValues()
  1104. def OnSetValue(self, event):
  1105. """
  1106. Retrieve the widget value and set the task value field accordingly.
  1107. Use for widgets that have a proper GetValue() method, i.e. not for selectors.
  1108. """
  1109. myId = event.GetId()
  1110. me = wx.FindWindowById( myId )
  1111. for porf in self.task.params + self.task.flags:
  1112. if 'wxId' in porf and type( porf[ 'wxId' ] ) == type( 1 ) and porf['wxId'] == myId:
  1113. porf[ 'value' ] = me.GetValue()
  1114. self.OnUpdateValues()
  1115. def createCmd( self, ignoreErrors = False ):
  1116. """
  1117. Produce a command line string (list) or feeding into GRASS.
  1118. If ignoreErrors==True then it will return whatever has been
  1119. built so far, even though it would not be a correct command
  1120. for GRASS.
  1121. """
  1122. try:
  1123. cmd = self.task.getCmd( ignoreErrors=ignoreErrors )
  1124. except ValueError, err:
  1125. dlg = wx.MessageDialog(self, str(err), _("Error"), wx.OK | wx.ICON_ERROR)
  1126. dlg.ShowModal()
  1127. dlg.Destroy()
  1128. cmd = None
  1129. return cmd
  1130. def getInterfaceDescription( cmd ):
  1131. """
  1132. Returns the XML description for the GRASS cmd.
  1133. The DTD must be located in $GISBASE/etc/grass-interface.dtd,
  1134. otherwise the parser will not succeed.
  1135. Note: 'cmd' is given as string
  1136. """
  1137. cmdout = os.popen(cmd + r' --interface-description', "r").read()
  1138. if not len(cmdout) > 0 :
  1139. raise IOError, _("Unable to fetch interface description for command '%s'.") % cmd
  1140. p = re.compile( '(grass-interface.dtd)')
  1141. p.search( cmdout )
  1142. cmdout = p.sub(globalvar.ETCDIR + r'/grass-interface.dtd', cmdout)
  1143. return cmdout
  1144. class GrassGUIApp(wx.App):
  1145. """
  1146. Stand-alone GRASS command GUI
  1147. """
  1148. def __init__(self, grass_task):
  1149. self.grass_task = grass_task
  1150. wx.App.__init__(self, False)
  1151. def OnInit(self):
  1152. self.mf = mainFrame(parent=None, ID=wx.ID_ANY, task_description=self.grass_task)
  1153. self.mf.Show(True)
  1154. self.SetTopWindow(self.mf)
  1155. # print >> sys.stderr, time.time() - start
  1156. return True
  1157. class GUI:
  1158. """
  1159. Parses GRASS commands when module is imported and used
  1160. from Layer Manager.
  1161. """
  1162. def __init__(self, parent=-1):
  1163. self.parent = parent
  1164. self.grass_task = None
  1165. def ParseCommand(self, cmd, gmpath=None, completed=None, parentframe=-1, show=True, modal=False):
  1166. """
  1167. Parse command
  1168. Note: cmd is given as list
  1169. If command is given with options, return validated cmd list:
  1170. * add key name for first parameter if not given
  1171. * change mapname to mapname@mapset
  1172. """
  1173. start = time.time()
  1174. dcmd_params = {}
  1175. if completed == None:
  1176. get_dcmd = None
  1177. layer = None
  1178. dcmd_params = None
  1179. else:
  1180. get_dcmd = completed[0]
  1181. layer = completed[1]
  1182. if completed[2]:
  1183. dcmd_params.update(completed[2])
  1184. if parentframe != -1:
  1185. self.parent = parentframe
  1186. else:
  1187. self.parent = None
  1188. # parse the interface decription
  1189. self.grass_task = grassTask()
  1190. handler = processTask(self.grass_task)
  1191. xml.sax.parseString( getInterfaceDescription(cmd[0]), handler )
  1192. # if layer parameters previously set, re-insert them into dialog
  1193. if completed is not None:
  1194. if 'params' in dcmd_params:
  1195. self.grass_task.params = dcmd_params['params']
  1196. if 'flags' in dcmd_params:
  1197. self.grass_task.flags = dcmd_params['flags']
  1198. # update parameters if needed && validate command
  1199. if len(cmd) > 1:
  1200. i = 0
  1201. cmd_validated = [cmd[0]]
  1202. for option in cmd[1:]:
  1203. if option[0] == '-': # flag
  1204. self.grass_task.set_flag(option[1], True)
  1205. cmd_validated.append(option)
  1206. else: # parameter
  1207. try:
  1208. key, value = option.split('=', 1)
  1209. except:
  1210. if i == 0: # add key name of first parameter if not given
  1211. key = self.grass_task.firstParam
  1212. value = option
  1213. else:
  1214. raise ValueError, _("Unable to parse command %s") % ' '.join(cmd)
  1215. if self.grass_task.get_param(key)['element'] in ['cell', 'vector']:
  1216. # mapname -> mapname@mapset
  1217. if '@' not in value:
  1218. value = value + '@' + grassenv.GetGRASSVariable('MAPSET')
  1219. self.grass_task.set_param(key, value)
  1220. cmd_validated.append(key + '=' + value)
  1221. i = i + 1
  1222. # update original command list
  1223. cmd = cmd_validated
  1224. self.mf = mainFrame(parent=self.parent, ID=wx.ID_ANY,
  1225. task_description=self.grass_task,
  1226. get_dcmd=get_dcmd, layer=layer)
  1227. if get_dcmd is not None:
  1228. # update only propwin reference
  1229. get_dcmd(dcmd=None, layer=layer, params=None,
  1230. propwin=self.mf)
  1231. if show:
  1232. self.mf.Show(show)
  1233. self.mf.MakeModal(modal)
  1234. else:
  1235. self.mf.OnApply(None)
  1236. # print >> sys.stderr, time.time() - start
  1237. return cmd
  1238. def GetCommandInputMapParamKey(self, cmd):
  1239. """Get parameter key for input raster/vector map
  1240. @param cmd module name
  1241. @return parameter key
  1242. @return None on failure
  1243. """
  1244. # parse the interface decription
  1245. if not self.grass_task:
  1246. self.grass_task = grassTask()
  1247. handler = processTask(self.grass_task)
  1248. xml.sax.parseString(getInterfaceDescription(cmd), handler)
  1249. for p in self.grass_task.params:
  1250. if p.get('name', '') in ('input', 'map'):
  1251. age = p.get('age', '')
  1252. prompt = p.get('prompt', '')
  1253. element = p.get('element', '')
  1254. if age == 'old' and \
  1255. element in ('cell', 'grid3', 'vector') and \
  1256. prompt in ('raster', '3d-raster', 'vector'):
  1257. return p.get('name', None)
  1258. return None
  1259. class StaticWrapText(wx.StaticText):
  1260. """
  1261. A Static Text field that wraps its text to fit its width, enlarging its height if necessary.
  1262. """
  1263. def __init__(self, parent, id=wx.ID_ANY, label=u'', *args, **kwds):
  1264. self.originalLabel = label
  1265. wx.StaticText.__init__(self, parent, id, u'', *args, **kwds)
  1266. self.SetLabel(label)
  1267. self.Bind(wx.EVT_SIZE, self.onResize)
  1268. def SetLabel(self, label):
  1269. self.originalLabel = label
  1270. self.wrappedSize = None
  1271. #self.onResize(None)
  1272. def onResize(self, event):
  1273. if not getattr(self, "resizing", False):
  1274. self.resizing = True
  1275. newSize = self.GetSize()
  1276. if self.wrappedSize != newSize:
  1277. wx.StaticText.SetLabel(self, self.originalLabel)
  1278. self.Wrap(newSize.width)
  1279. self.wrappedSize = self.GetMinSize()
  1280. self.SetSize(self.wrappedSize)
  1281. del self.resizing
  1282. if __name__ == "__main__":
  1283. if len(sys.argv) == 1:
  1284. print _("usage: %s <grass command>") % sys.argv[0]
  1285. sys.exit()
  1286. if sys.argv[1] != 'test':
  1287. q=wx.LogNull()
  1288. GrassGUIApp( grassTask( sys.argv[1] ) ).MainLoop()
  1289. else: #Test
  1290. # Test grassTask from within a GRASS session
  1291. if os.getenv("GISBASE") is not None:
  1292. task = grassTask( "d.vect" )
  1293. task.get_param('map')['value'] = "map_name"
  1294. task.get_flag('v')['value'] = True
  1295. task.get_param('layer')['value'] = 1
  1296. task.get_param('bcolor')['value'] = "red"
  1297. assert ' '.join( task.getCmd() ) == "d.vect -v map=map_name layer=1 bcolor=red"
  1298. # Test interface building with handmade grassTask,
  1299. # possibly outside of a GRASS session.
  1300. task = grassTask()
  1301. task.name = "TestTask"
  1302. task.description = "This is an artificial grassTask() object intended for testing purposes."
  1303. task.keywords = ["grass","test","task"]
  1304. task.params = [
  1305. {
  1306. "name" : "text",
  1307. "description" : "Descriptions go into tooltips if labels are present, like this one",
  1308. "label" : "Enter some text",
  1309. },{
  1310. "name" : "hidden_text",
  1311. "description" : "This text should not appear in the form",
  1312. "hidden" : "yes"
  1313. },{
  1314. "name" : "text_default",
  1315. "description" : "Enter text to override the default",
  1316. "default" : "default text"
  1317. },{
  1318. "name" : "text_prefilled",
  1319. "description" : "You should see a friendly welcome message here",
  1320. "value" : "hello, world"
  1321. },{
  1322. "name" : "plain_color",
  1323. "description" : "This is a plain color, and it is a compulsory parameter",
  1324. "required" : "yes",
  1325. "gisprompt" : True,
  1326. "prompt" : "color"
  1327. },{
  1328. "name" : "transparent_color",
  1329. "description" : "This color becomes transparent when set to none",
  1330. "guisection" : "tab",
  1331. "gisprompt" : True,
  1332. "prompt" : "color"
  1333. },{
  1334. "name" : "multi",
  1335. "description" : "A multiple selection",
  1336. 'default': u'red,green,blue',
  1337. 'gisprompt': False,
  1338. 'guisection': 'tab',
  1339. 'multiple': u'yes',
  1340. 'type': u'string',
  1341. 'value': '',
  1342. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other']
  1343. },{
  1344. "name" : "single",
  1345. "description" : "A single multiple-choice selection",
  1346. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  1347. "guisection" : "tab"
  1348. },{
  1349. "name" : "large_multi",
  1350. "description" : "A large multiple selection",
  1351. "gisprompt" : False,
  1352. "multiple" : "yes",
  1353. # values must be an array of strings
  1354. "values" : str2rgb.keys() + map( str, str2rgb.values() )
  1355. },{
  1356. "name" : "a_file",
  1357. "description" : "A file selector",
  1358. "gisprompt" : True,
  1359. "element" : "file"
  1360. }
  1361. ]
  1362. task.flags = [
  1363. {
  1364. "name" : "a",
  1365. "description" : "Some flag, will appear in Main since it is required",
  1366. "required" : "yes"
  1367. },{
  1368. "name" : "b",
  1369. "description" : "pre-filled flag, will appear in options since it is not required",
  1370. "value" : True
  1371. },{
  1372. "name" : "hidden_flag",
  1373. "description" : "hidden flag, should not be changeable",
  1374. "hidden" : "yes",
  1375. "value" : True
  1376. }
  1377. ]
  1378. q=wx.LogNull()
  1379. GrassGUIApp( task ).MainLoop()