menuform.py 74 KB

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