menuform.py 64 KB

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