menuform.py 65 KB

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