menuform.py 77 KB

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