menuform.py 77 KB

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