menuform.py 77 KB

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