menuform.py 77 KB

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