menuform.py 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626
  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. btn_cancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
  554. btn_cancel.SetToolTipString(_("Cancel the command settings and ignore changes"))
  555. btnsizer.Add(item=btn_cancel, proportion=0, flag=wx.ALL | wx.ALIGN_CENTER, border=10)
  556. btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  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. btn_clipboard = wx.Button(parent=self.panel, id=wx.ID_COPY)
  580. 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=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. btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
  593. guisizer.Add(item=btnsizer, proportion=0, flag=wx.ALIGN_CENTER)
  594. if self.get_dcmd is None:
  595. # close dialog when command is terminated
  596. self.closebox = wx.CheckBox(parent=self.panel,
  597. label=_('Close dialog on finish'), style = wx.NO_BORDER)
  598. self.closebox.SetValue(UserSettings.Get(group='cmd', key='closeDlg', subkey='enabled'))
  599. guisizer.Add(item=self.closebox, proportion=0,
  600. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  601. border=5)
  602. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  603. #constrained_size = self.notebookpanel.GetSize()
  604. # 80 takes the tabbar into account
  605. #self.notebookpanel.SetSize( (constrained_size[0] + 25, constrained_size[1]) )
  606. #self.notebookpanel.Layout()
  607. #
  608. # put module description
  609. #
  610. if self.task.label != '':
  611. module_desc = self.task.label + os.linesep + self.task.description
  612. else:
  613. module_desc = self.task.description
  614. self.description = StaticWrapText (parent=self.panel,
  615. label=module_desc)
  616. topsizer.Add (item=self.description, proportion=1, border=5,
  617. flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  618. #
  619. # do layout
  620. #
  621. guisizer.SetSizeHints(self.panel)
  622. # called automatically by SetSizer()
  623. self.panel.SetAutoLayout(True)
  624. self.panel.SetSizer(guisizer)
  625. guisizer.Fit(self.panel)
  626. sizeFrame = self.GetBestSize()
  627. self.SetMinSize(sizeFrame)
  628. self.SetSize((sizeFrame[0], sizeFrame[1] +
  629. self.notebookpanel.constrained_size[1] -
  630. self.notebookpanel.panelMinHeight))
  631. self.Layout()
  632. def updateValuesHook(self):
  633. """Update status bar data"""
  634. self.SetStatusText(' '.join(self.notebookpanel.createCmd(ignoreErrors = True)) )
  635. def OnOK(self, event):
  636. """OK button pressed"""
  637. cmd = self.OnApply(event)
  638. if cmd is not None and self.get_dcmd is not None:
  639. self.OnCancel(event)
  640. def OnApply(self, event):
  641. """Apply the command"""
  642. cmd = self.createCmd()
  643. if cmd is not None and self.get_dcmd is not None:
  644. # return d.* command to layer tree for rendering
  645. self.get_dcmd(cmd, self.layer, {"params": self.task.params,
  646. "flags" :self.task.flags},
  647. self)
  648. # echo d.* command to output console
  649. # self.parent.writeDCommand(cmd)
  650. return cmd
  651. def OnRun(self, event):
  652. """Run the command"""
  653. if len(self.goutput.GetListOfCmdThreads()) > 0:
  654. return
  655. cmd = self.createCmd()
  656. if cmd == [] or cmd == None:
  657. return
  658. # change page if needed
  659. if self.notebookpanel.notebook.GetSelection() != self.notebookpanel.goutput.pageid:
  660. self.notebookpanel.notebook.SetSelection(self.notebookpanel.goutput.pageid)
  661. if cmd[0][0:2] != "d.":
  662. # Send any non-display command to parent window (probably wxgui.py)
  663. # put to parents
  664. try:
  665. self.goutput.RunCmd(cmd)
  666. except AttributeError,e:
  667. print >> sys.stderr, "%s: Propably not running in wxgui.py session?" % (e)
  668. print >> sys.stderr, "parent window is: %s" % (str(self.parent))
  669. # Send any other command to the shell.
  670. else:
  671. gcmd.Command(cmd)
  672. # update buttons status
  673. self.btn_run.Enable(False)
  674. self.btn_abort.Enable(True)
  675. def OnAbort(self, event):
  676. """Abort running command"""
  677. try:
  678. self.goutput.GetListOfCmdThreads()[0].abort()
  679. except IndexError:
  680. pass
  681. self.btn_run.Enable(True)
  682. self.btn_abort.Enable(False)
  683. def OnCopy(self, event):
  684. """Copy the command"""
  685. cmddata = wx.TextDataObject()
  686. # list -> string
  687. cmdstring = ' '.join(self.createCmd(ignoreErrors=True))
  688. cmddata.SetText(cmdstring)
  689. if wx.TheClipboard.Open():
  690. wx.TheClipboard.UsePrimarySelection(True)
  691. wx.TheClipboard.SetData(cmddata)
  692. wx.TheClipboard.Close()
  693. self.SetStatusText( _("'%s' copied to clipboard") % \
  694. (cmdstring))
  695. def OnCancel(self, event):
  696. """Cancel button pressed"""
  697. self.MakeModal(False)
  698. if self.get_dcmd:
  699. self.Hide()
  700. else:
  701. self.Destroy()
  702. def OnCloseWindow(self, event):
  703. """Close the main window"""
  704. self.MakeModal(False)
  705. self.Destroy()
  706. def OnAbout(self, event):
  707. """General 'about' information"""
  708. dlg = wx.MessageDialog(self, _("This is a sample program for\n"
  709. "GRASS command interface parsing\n"
  710. "and automatic GUI building.\n%s") %(__version__),
  711. _("About wxPython GRASS GUI"), wx.OK | wx.ICON_INFORMATION)
  712. dlg.ShowModal()
  713. dlg.Destroy()
  714. def OnAboutCommand(self, event):
  715. """About command"""
  716. dlg = wx.MessageDialog(self,
  717. self.task.name+": "+self.task.description,
  718. "About " + self.task.name,
  719. wx.OK | wx.ICON_INFORMATION)
  720. dlg.ShowModal()
  721. dlg.Destroy()
  722. def createCmd(self, ignoreErrors = False):
  723. """Create command string (python list)"""
  724. return self.notebookpanel.createCmd(ignoreErrors=ignoreErrors)
  725. class cmdPanel(wx.Panel):
  726. """
  727. A panel containing a notebook dividing in tabs the different guisections of the GRASS cmd.
  728. """
  729. def __init__( self, parent, task, standalone, mainFrame, *args, **kwargs ):
  730. wx.Panel.__init__( self, parent, *args, **kwargs )
  731. self.parent = mainFrame
  732. self.task = task
  733. fontsize = 10
  734. # Determine tab layout
  735. sections = []
  736. is_section = {}
  737. not_hidden = [ p for p in self.task.params + self.task.flags if not p.get( 'hidden','no' ) == 'yes' ]
  738. for task in not_hidden:
  739. if task.get( 'required','no' ) == 'yes':
  740. # All required go into Main, even if they had defined another guisection
  741. task['guisection'] = _( 'Required' )
  742. if task.get( 'guisection','' ) == '':
  743. # Undefined guisections end up into Options
  744. task['guisection'] = _( 'Optional' )
  745. if not is_section.has_key(task['guisection']):
  746. # We do it like this to keep the original order, except for Main which goes first
  747. is_section[task['guisection']] = 1
  748. sections.append( task['guisection'] )
  749. else:
  750. is_section[ task['guisection'] ] += 1
  751. del is_section
  752. # 'Required' tab goes first, 'Optional' as the last one
  753. for (newidx,content) in [ (0,_( 'Required' )), (len(sections)-1,_('Optional')) ]:
  754. if content in sections:
  755. idx = sections.index( content )
  756. sections[idx:idx+1] = []
  757. sections[newidx:newidx] = [content]
  758. panelsizer = wx.BoxSizer(orient=wx.VERTICAL)
  759. # Build notebook
  760. nbStyle = globalvar.FNPageStyle
  761. self.notebook = FN.FlatNotebook( self, id=wx.ID_ANY, style=nbStyle)
  762. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  763. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  764. tab = {}
  765. tabsizer = {}
  766. for section in sections:
  767. tab[section] = wx.ScrolledWindow( parent=self.notebook )
  768. tab[section].SetScrollRate(10,10)
  769. tabsizer[section] = wx.BoxSizer(orient=wx.VERTICAL)
  770. self.notebook.AddPage( tab[section], text=section )
  771. # are we running from command line?
  772. ### add 'command output' tab regardless standalone dialog
  773. if self.parent.get_dcmd is None:
  774. self.goutput = goutput.GMConsole(parent=self, margin=False,
  775. pageid=self.notebook.GetPageCount())
  776. self.outpage = self.notebook.AddPage(self.goutput, text=_("Command output") )
  777. else:
  778. self.goutput = None
  779. self.manual_tab = helpPanel(parent = self.notebook, grass_command = self.task.name)
  780. self.manual_tabsizer = wx.BoxSizer(wx.VERTICAL)
  781. self.notebook.AddPage(self.manual_tab, text=_("Manual"))
  782. self.manual_tab_id = self.notebook.GetPageCount() - 1
  783. self.notebook.SetSelection(0)
  784. panelsizer.Add(item=self.notebook, proportion=1, flag=wx.EXPAND )
  785. #
  786. # flags
  787. #
  788. text_style = wx.FONTWEIGHT_NORMAL
  789. visible_flags = [ f for f in self.task.flags if not f.get( 'hidden', 'no' ) == 'yes' ]
  790. for f in visible_flags:
  791. which_sizer = tabsizer[ f['guisection'] ]
  792. which_panel = tab[ f['guisection'] ]
  793. # if label is given -> label and description -> tooltip
  794. # otherwise description -> lavel
  795. if p.get('label','') != '':
  796. title = text_beautify( f['label'] )
  797. tooltip = text_beautify ( f['description'] )
  798. else:
  799. title = text_beautify( f['description'] )
  800. tooltip = None
  801. chk = wx.CheckBox(parent=which_panel, label = title, style = wx.NO_BORDER)
  802. if tooltip:
  803. chk.SetToolTipString(tooltip)
  804. if 'value' in f:
  805. chk.SetValue( f['value'] )
  806. # chk.SetFont(wx.Font(pointSize=fontsize, family=wx.FONTFAMILY_DEFAULT,
  807. # style=wx.NORMAL, weight=text_style))
  808. which_sizer.Add( item=chk, proportion=0,
  809. flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=5)
  810. f['wxId'] = chk.GetId()
  811. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  812. if f['name'] in ('verbose', 'quiet'):
  813. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  814. vq = UserSettings.Get(group='cmd', key='verbosity', subkey='selection')
  815. if f['name'] == vq:
  816. chk.SetValue(True)
  817. f['value'] = True
  818. elif f['name'] == 'overwrite':
  819. chk.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
  820. f['value'] = UserSettings.Get(group='cmd', key='overwrite', subkey='enabled')
  821. #
  822. # parameters
  823. #
  824. visible_params = [ p for p in self.task.params if not p.get( 'hidden', 'no' ) == 'yes' ]
  825. for p in visible_params:
  826. which_sizer = tabsizer[ p['guisection'] ]
  827. which_panel = tab[ p['guisection'] ]
  828. # if label is given -> label and description -> tooltip
  829. # otherwise description -> lavel
  830. if p.get('label','') != '':
  831. title = text_beautify( p['label'] )
  832. tooltip = text_beautify ( p['description'] )
  833. else:
  834. title = text_beautify( p['description'] )
  835. tooltip = None
  836. txt = None
  837. # text style (required -> bold)
  838. if p.get('required','no') == 'no':
  839. text_style = wx.FONTWEIGHT_NORMAL
  840. else:
  841. text_style = wx.FONTWEIGHT_BOLD
  842. # title expansion
  843. if p.get('multiple','no') == 'yes' and len( p.get('values','') ) == 0:
  844. title = _("[multiple]") + " " + title
  845. if p.get('value','') == '' :
  846. p['value'] = p.get('default','')
  847. if ( len(p.get('values', []) ) > 0):
  848. valuelist=map( str, p.get('values',[]) )
  849. if p.get('multiple', 'no') == 'yes' and \
  850. p.get('type', '') == 'string':
  851. txt = wx.StaticBox (parent=which_panel, id=0, label=" " + title + ": ")
  852. if len(valuelist) > 6:
  853. hSizer=wx.StaticBoxSizer ( box=txt, orient=wx.VERTICAL )
  854. else:
  855. hSizer=wx.StaticBoxSizer ( box=txt, orient=wx.HORIZONTAL )
  856. isEnabled = {}
  857. # copy default values
  858. if p['value'] == '':
  859. p['value'] = p.get('default', '')
  860. for defval in p.get('value', '').split(','):
  861. isEnabled[ defval ] = 'yes'
  862. # for multi checkboxes, this is an array of all wx IDs
  863. # for each individual checkbox
  864. p[ 'wxId' ] = []
  865. for val in valuelist:
  866. chkbox = wx.CheckBox( parent=which_panel, label = text_beautify(val) )
  867. p[ 'wxId' ].append( chkbox.GetId() )
  868. if isEnabled.has_key(val):
  869. chkbox.SetValue( True )
  870. hSizer.Add( item=chkbox, proportion=0,
  871. flag=wx.ADJUST_MINSIZE | wx.ALL, border=1 )
  872. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  873. which_sizer.Add( item=hSizer, proportion=0,
  874. flag=wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border=5 )
  875. else:
  876. if len(valuelist) == 1: # -> textctrl
  877. txt = wx.StaticText(parent=which_panel,
  878. label = "%s. %s %s" % (title, _('Valid range'),
  879. str(valuelist[0]) + ':'))
  880. which_sizer.Add(item=txt, proportion=0,
  881. flag=wx.ADJUST_MINSIZE | wx.TOP | wx.RIGHT | wx.LEFT, border=5)
  882. if p.get('type','') == 'integer' and \
  883. p.get('multiple','no') == 'no':
  884. # for multiple integers use textctrl instead of spinsctrl
  885. try:
  886. minValue, maxValue = map(int, valuelist[0].split('-'))
  887. except ValueError:
  888. minValue = -1e6
  889. maxValue = 1e6
  890. txt2 = wx.SpinCtrl(parent=which_panel, id=wx.ID_ANY, size=globalvar.DIALOG_SPIN_SIZE,
  891. min=minValue, max=maxValue)
  892. else:
  893. txt2 = wx.TextCtrl(parent=which_panel, value = p.get('default',''),
  894. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  895. if p.get('value','') != '':
  896. txt2.SetValue(p['value']) # parameter previously set
  897. which_sizer.Add(item=txt2, proportion=0,
  898. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  899. p['wxId'] = txt2.GetId()
  900. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  901. else:
  902. # list of values (combo)
  903. txt = wx.StaticText(parent=which_panel, label = title + ':' )
  904. which_sizer.Add(item=txt, proportion=0,
  905. flag=wx.ADJUST_MINSIZE | wx.TOP | wx.RIGHT | wx.LEFT, border=5)
  906. cb = wx.ComboBox(parent=which_panel, id=wx.ID_ANY, value=p.get('default',''),
  907. size=globalvar.DIALOG_COMBOBOX_SIZE,
  908. choices=valuelist, style=wx.CB_DROPDOWN)
  909. if p.get('value','') != '':
  910. cb.SetValue(p['value']) # parameter previously set
  911. which_sizer.Add( item=cb, proportion=0,
  912. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  913. p['wxId'] = cb.GetId()
  914. cb.Bind( wx.EVT_COMBOBOX, self.OnSetValue)
  915. # text entry
  916. if (p.get('type','string') in ('string','integer','float')
  917. and len(p.get('values',[])) == 0
  918. and p.get('gisprompt',False) == False
  919. and p.get('prompt','') != 'color'):
  920. txt = wx.StaticText(parent=which_panel, label = title + ':' )
  921. which_sizer.Add(item=txt, proportion=0,
  922. flag=wx.RIGHT | wx.LEFT | wx.TOP | wx.EXPAND, border=5)
  923. if p.get('multiple','yes') == 'yes' or \
  924. p.get('type', 'string') in ('string', 'float') or \
  925. len(p.get('key_desc', [])) > 1:
  926. txt3 = wx.TextCtrl(parent=which_panel, value = p.get('default',''),
  927. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  928. if p.get('value','') != '':
  929. txt3.SetValue(str(p['value'])) # parameter previously set
  930. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  931. else:
  932. minValue = -1e9
  933. maxValue = 1e9
  934. txt3 = wx.SpinCtrl(parent=which_panel, value=p.get('default',''),
  935. size=globalvar.DIALOG_SPIN_SIZE,
  936. min=minValue, max=maxValue)
  937. if p.get('value','') != '':
  938. txt3.SetValue(int(p['value'])) # parameter previously set
  939. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  940. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  941. which_sizer.Add(item=txt3, proportion=0, flag=wx.BOTTOM | wx.LEFT, border=5)
  942. p['wxId'] = txt3.GetId()
  943. if p.get('type','string') == 'string' and p.get('gisprompt',False) == True:
  944. txt = wx.StaticText(parent=which_panel, label = title + ':')
  945. which_sizer.Add(item=txt, proportion=0,
  946. flag=wx.ADJUST_MINSIZE | wx.RIGHT | wx.LEFT | wx.TOP, border=5)
  947. # element selection tree combobox (maps, icons, regions, etc.)
  948. if p.get('prompt','') != 'color' and p.get('element', '') != 'file':
  949. if p.get('multiple','no') == 'yes':
  950. multiple = True
  951. else:
  952. multiple = False
  953. if p.get('age','') == 'new':
  954. mapsets = [grassenv.GetGRASSVariable('MAPSET'),]
  955. else:
  956. mapsets = None
  957. selection = gselect.Select(parent=which_panel, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
  958. type=p.get('element',''), multiple=multiple, mapsets=mapsets)
  959. if p.get('value','') != '':
  960. selection.SetValue(p['value']) # parameter previously set
  961. which_sizer.Add(item=selection, proportion=0,
  962. flag=wx.ADJUST_MINSIZE| wx.BOTTOM | wx.LEFT | wx.RIGHT, border=5)
  963. # A select.Select is a combobox with two children: a textctl and a popupwindow;
  964. # we target the textctl here
  965. p['wxId'] = selection.GetChildren()[0].GetId()
  966. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  967. # color entry
  968. elif p.get('prompt','') == 'color':
  969. # Heuristic way of finding whether transparent is allowed
  970. handle_transparency = 'none' in title
  971. default_color = (200,200,200)
  972. label_color = _("Select Color")
  973. if p.get('default','') != '':
  974. default_color, label_color = color_resolve( p['default'] )
  975. if p.get('value','') != '': # parameter previously set
  976. default_color, label_color = color_resolve( p['value'] )
  977. if handle_transparency:
  978. this_sizer = wx.BoxSizer(orient=wx.HORIZONTAL )
  979. else:
  980. this_sizer = which_sizer
  981. btn_colour = csel.ColourSelect(parent=which_panel, id=wx.ID_ANY,
  982. label=label_color, colour=default_color,
  983. pos=wx.DefaultPosition, size=(150,-1) )
  984. this_sizer.Add(item=btn_colour, proportion=0,
  985. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  986. # For color selectors, this is a two-member array, holding the IDs of
  987. # the selector proper and either a "transparent" button or None
  988. p['wxId'] = [btn_colour.GetId(),]
  989. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange )
  990. if handle_transparency:
  991. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent") )
  992. if p.get('value','') != '' and p.get('value',[''])[0] == "none":
  993. none_check.SetValue(True)
  994. else:
  995. none_check.SetValue(False)
  996. # none_check.SetFont( wx.Font( fontsize, wx.FONTFAMILY_DEFAULT, wx.NORMAL, text_style, 0, ''))
  997. this_sizer.Add(item=none_check, proportion=0,
  998. flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border=5)
  999. which_sizer.Add( this_sizer )
  1000. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1001. p['wxId'].append( none_check.GetId() )
  1002. else:
  1003. p['wxId'].append(None)
  1004. # file selector
  1005. elif p.get('prompt','') != 'color' and p.get('element', '') == 'file':
  1006. fbb = filebrowse.FileBrowseButton(parent=which_panel, id=wx.ID_ANY,
  1007. size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
  1008. dialogTitle=_('Choose %s') % \
  1009. p.get('description',_('File')),
  1010. buttonText=_('Browse'),
  1011. startDirectory=os.getcwd(), fileMode=0,
  1012. changeCallback=self.OnSetValue)
  1013. if p.get('value','') != '':
  1014. fbb.SetValue(p['value']) # parameter previously set
  1015. which_sizer.Add(item=fbb, proportion=0,
  1016. flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.TOP | wx.RIGHT, border=-3)
  1017. # A file browse button is a combobox with two children:
  1018. # a textctl and a button;
  1019. # we have to target the button here
  1020. p['wxId'] = fbb.GetChildren()[1].GetId()
  1021. if txt is not None:
  1022. # txt.SetFont( wx.Font( fontsize, wx.FONTFAMILY_DEFAULT, wx.NORMAL, text_style, 0, ''))
  1023. # create tooltip if given
  1024. if len(p['values_desc']) > 0:
  1025. if tooltip:
  1026. tooltip += 2 * os.linesep
  1027. else:
  1028. tooltip = ''
  1029. if len(p['values']) == len(p['values_desc']):
  1030. for i in range(len(p['values'])):
  1031. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1032. tooltip.strip(os.linesep)
  1033. if tooltip:
  1034. txt.SetToolTipString(tooltip)
  1035. #
  1036. # determine panel size
  1037. #
  1038. maxsizes = (0,0)
  1039. for section in sections:
  1040. # tabsizer[section].SetSizeHints( tab[section] )
  1041. #tab[section].SetAutoLayout(True)
  1042. tab[section].SetSizer( tabsizer[section] )
  1043. tabsizer[section].Fit( tab[section] )
  1044. tab[section].Layout()
  1045. minsecsizes = tabsizer[section].GetSize()
  1046. maxsizes = map( lambda x: max( maxsizes[x], minsecsizes[x] ), (0,1) )
  1047. # TODO: be less arbitrary with these 600
  1048. self.panelMinHeight = 100
  1049. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1050. for section in sections:
  1051. tab[section].SetMinSize( (self.constrained_size[0], self.panelMinHeight) )
  1052. # tab[section].SetMinSize( constrained_size )
  1053. if self.manual_tab.Ok:
  1054. self.manual_tab.SetMinSize( (self.constrained_size[0], self.panelMinHeight) )
  1055. # manual_tab.SetMinSize( constrained_size )
  1056. self.SetSizer( panelsizer )
  1057. panelsizer.Fit(self.notebook)
  1058. self.hasMain = tab.has_key( _('Required') ) # publish, to enclosing Frame for instance
  1059. def OnVerbosity(self, event):
  1060. """Verbosity level changed"""
  1061. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'])
  1062. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'])
  1063. if event.IsChecked():
  1064. if event.GetId() == verbose.GetId():
  1065. if quiet.IsChecked():
  1066. quiet.SetValue(False)
  1067. self.task.get_flag('quiet')['value'] = False
  1068. else:
  1069. if verbose.IsChecked():
  1070. verbose.SetValue(False)
  1071. self.task.get_flag('verbose')['value'] = False
  1072. event.Skip()
  1073. def OnPageChange(self, event):
  1074. if hasattr(self, "manual_tab_id") and \
  1075. event.GetSelection() == self.manual_tab_id:
  1076. # calling LoadPage() is strangely time-consuming (only first call)
  1077. # FIXME: move to helpPage.__init__()
  1078. if not self.manual_tab.Ok:
  1079. self.manual_tab.LoadPage(self.manual_tab.fspath + self.task.name + ".html")
  1080. self.manual_tab.Ok = True
  1081. self.Layout()
  1082. def OnColorChange( self, event ):
  1083. myId = event.GetId()
  1084. for p in self.task.params:
  1085. if 'wxId' in p and type( p['wxId'] ) == type( [] ) and myId in p['wxId']:
  1086. has_button = p['wxId'][1] is not None
  1087. if has_button and wx.FindWindowById( p['wxId'][1] ).GetValue() == True:
  1088. p[ 'value' ] = 'none'
  1089. else:
  1090. colorchooser = wx.FindWindowById( p['wxId'][0] )
  1091. new_color = colorchooser.GetValue()[:]
  1092. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1093. # under wx2.8.1
  1094. new_label = rgb2str.get( new_color, ':'.join(map(str,new_color)) )
  1095. colorchooser.SetLabel( new_label )
  1096. colorchooser.SetColour( new_color )
  1097. colorchooser.Refresh()
  1098. p[ 'value' ] = colorchooser.GetLabel()
  1099. self.OnUpdateValues()
  1100. def OnUpdateValues(self):
  1101. """
  1102. If we were part of a richer interface, report back the current command being built.
  1103. This method should be set by the parent of this panel if needed. It's a hook, actually.
  1104. Beware of what is 'self' in the method def, though. It will be called with no arguments.
  1105. """
  1106. pass
  1107. def OnCheckBoxMulti(self, event):
  1108. """
  1109. Fill the values as a ','-separated string according to current status of the checkboxes.
  1110. """
  1111. me = event.GetId()
  1112. theParam = None
  1113. for p in self.task.params:
  1114. if 'wxId' in p and type( p['wxId'] ) == type( [] ) and me in p['wxId']:
  1115. theParam = p
  1116. myIndex = p['wxId'].index( me )
  1117. # Unpack current value list
  1118. currentValues = {}
  1119. for isThere in theParam.get('value', '').split(','):
  1120. currentValues[isThere] = 1
  1121. theValue = theParam['values'][myIndex]
  1122. if event.Checked():
  1123. currentValues[ theValue ] = 1
  1124. else:
  1125. del currentValues[ theValue ]
  1126. # Keep the original order, so that some defaults may be recovered
  1127. currentValueList = []
  1128. for v in theParam['values']:
  1129. if currentValues.has_key(v):
  1130. currentValueList.append( v )
  1131. # Pack it back
  1132. theParam['value'] = ','.join( currentValueList )
  1133. self.OnUpdateValues()
  1134. def OnSetValue(self, event):
  1135. """
  1136. Retrieve the widget value and set the task value field accordingly.
  1137. Use for widgets that have a proper GetValue() method, i.e. not for selectors.
  1138. """
  1139. myId = event.GetId()
  1140. me = wx.FindWindowById( myId )
  1141. for porf in self.task.params + self.task.flags:
  1142. if 'wxId' in porf and type( porf[ 'wxId' ] ) == type( 1 ) and porf['wxId'] == myId:
  1143. porf[ 'value' ] = me.GetValue()
  1144. self.OnUpdateValues()
  1145. def createCmd( self, ignoreErrors = False ):
  1146. """
  1147. Produce a command line string (list) or feeding into GRASS.
  1148. If ignoreErrors==True then it will return whatever has been
  1149. built so far, even though it would not be a correct command
  1150. for GRASS.
  1151. """
  1152. try:
  1153. cmd = self.task.getCmd( ignoreErrors=ignoreErrors )
  1154. except ValueError, err:
  1155. dlg = wx.MessageDialog(self, str(err), _("Error"), wx.OK | wx.ICON_ERROR)
  1156. dlg.ShowModal()
  1157. dlg.Destroy()
  1158. cmd = None
  1159. return cmd
  1160. def getInterfaceDescription( cmd ):
  1161. """
  1162. Returns the XML description for the GRASS cmd.
  1163. The DTD must be located in $GISBASE/etc/grass-interface.dtd,
  1164. otherwise the parser will not succeed.
  1165. Note: 'cmd' is given as string
  1166. """
  1167. cmdout = os.popen(cmd + r' --interface-description', "r").read()
  1168. if not len(cmdout) > 0 :
  1169. raise IOError, _("Unable to fetch interface description for command '%s'.") % cmd
  1170. p = re.compile( '(grass-interface.dtd)')
  1171. p.search( cmdout )
  1172. cmdout = p.sub(globalvar.ETCDIR + r'/grass-interface.dtd', cmdout)
  1173. return cmdout
  1174. class GrassGUIApp(wx.App):
  1175. """
  1176. Stand-alone GRASS command GUI
  1177. """
  1178. def __init__(self, grass_task):
  1179. self.grass_task = grass_task
  1180. wx.App.__init__(self, False)
  1181. def OnInit(self):
  1182. self.mf = mainFrame(parent=None, ID=wx.ID_ANY, task_description=self.grass_task)
  1183. self.mf.Show(True)
  1184. self.SetTopWindow(self.mf)
  1185. # print >> sys.stderr, time.time() - start
  1186. return True
  1187. class GUI:
  1188. """
  1189. Parses GRASS commands when module is imported and used
  1190. from Layer Manager.
  1191. """
  1192. def __init__(self, parent=-1):
  1193. self.parent = parent
  1194. self.grass_task = None
  1195. def ParseCommand(self, cmd, gmpath=None, completed=None, parentframe=-1, show=True, modal=False):
  1196. """
  1197. Parse command
  1198. Note: cmd is given as list
  1199. If command is given with options, return validated cmd list:
  1200. * add key name for first parameter if not given
  1201. * change mapname to mapname@mapset
  1202. """
  1203. start = time.time()
  1204. dcmd_params = {}
  1205. if completed == None:
  1206. get_dcmd = None
  1207. layer = None
  1208. dcmd_params = None
  1209. else:
  1210. get_dcmd = completed[0]
  1211. layer = completed[1]
  1212. if completed[2]:
  1213. dcmd_params.update(completed[2])
  1214. if parentframe != -1:
  1215. self.parent = parentframe
  1216. else:
  1217. self.parent = None
  1218. # parse the interface decription
  1219. self.grass_task = grassTask()
  1220. handler = processTask(self.grass_task)
  1221. xml.sax.parseString( getInterfaceDescription(cmd[0]), handler )
  1222. # if layer parameters previously set, re-insert them into dialog
  1223. if completed is not None:
  1224. if 'params' in dcmd_params:
  1225. self.grass_task.params = dcmd_params['params']
  1226. if 'flags' in dcmd_params:
  1227. self.grass_task.flags = dcmd_params['flags']
  1228. # update parameters if needed && validate command
  1229. if len(cmd) > 1:
  1230. i = 0
  1231. cmd_validated = [cmd[0]]
  1232. for option in cmd[1:]:
  1233. if option[0] == '-': # flag
  1234. self.grass_task.set_flag(option[1], True)
  1235. cmd_validated.append(option)
  1236. else: # parameter
  1237. try:
  1238. key, value = option.split('=', 1)
  1239. except:
  1240. if i == 0: # add key name of first parameter if not given
  1241. key = self.grass_task.firstParam
  1242. value = option
  1243. else:
  1244. raise ValueError, _("Unable to parse command %s") % ' '.join(cmd)
  1245. if self.grass_task.get_param(key)['element'] in ['cell', 'vector']:
  1246. # mapname -> mapname@mapset
  1247. if '@' not in value:
  1248. value = value + '@' + grassenv.GetGRASSVariable('MAPSET')
  1249. self.grass_task.set_param(key, value)
  1250. cmd_validated.append(key + '=' + value)
  1251. i = i + 1
  1252. # update original command list
  1253. cmd = cmd_validated
  1254. self.mf = mainFrame(parent=self.parent, ID=wx.ID_ANY,
  1255. task_description=self.grass_task,
  1256. get_dcmd=get_dcmd, layer=layer)
  1257. if get_dcmd is not None:
  1258. # update only propwin reference
  1259. get_dcmd(dcmd=None, layer=layer, params=None,
  1260. propwin=self.mf)
  1261. if show:
  1262. self.mf.Show(show)
  1263. self.mf.MakeModal(modal)
  1264. else:
  1265. self.mf.OnApply(None)
  1266. # print >> sys.stderr, time.time() - start
  1267. return cmd
  1268. def GetCommandInputMapParamKey(self, cmd):
  1269. """Get parameter key for input raster/vector map
  1270. @param cmd module name
  1271. @return parameter key
  1272. @return None on failure
  1273. """
  1274. # parse the interface decription
  1275. if not self.grass_task:
  1276. self.grass_task = grassTask()
  1277. handler = processTask(self.grass_task)
  1278. xml.sax.parseString(getInterfaceDescription(cmd), handler)
  1279. for p in self.grass_task.params:
  1280. if p.get('name', '') in ('input', 'map'):
  1281. age = p.get('age', '')
  1282. prompt = p.get('prompt', '')
  1283. element = p.get('element', '')
  1284. if age == 'old' and \
  1285. element in ('cell', 'grid3', 'vector') and \
  1286. prompt in ('raster', '3d-raster', 'vector'):
  1287. return p.get('name', None)
  1288. return None
  1289. class StaticWrapText(wx.StaticText):
  1290. """
  1291. A Static Text field that wraps its text to fit its width, enlarging its height if necessary.
  1292. """
  1293. def __init__(self, parent, id=wx.ID_ANY, label=u'', *args, **kwds):
  1294. self.originalLabel = label
  1295. wx.StaticText.__init__(self, parent, id, u'', *args, **kwds)
  1296. self.SetLabel(label)
  1297. self.Bind(wx.EVT_SIZE, self.onResize)
  1298. def SetLabel(self, label):
  1299. self.originalLabel = label
  1300. self.wrappedSize = None
  1301. #self.onResize(None)
  1302. def onResize(self, event):
  1303. if not getattr(self, "resizing", False):
  1304. self.resizing = True
  1305. newSize = self.GetSize()
  1306. if self.wrappedSize != newSize:
  1307. wx.StaticText.SetLabel(self, self.originalLabel)
  1308. self.Wrap(newSize.width)
  1309. self.wrappedSize = self.GetMinSize()
  1310. self.SetSize(self.wrappedSize)
  1311. del self.resizing
  1312. if __name__ == "__main__":
  1313. if len(sys.argv) == 1:
  1314. print _("usage: %s <grass command>") % sys.argv[0]
  1315. sys.exit()
  1316. if sys.argv[1] != 'test':
  1317. q=wx.LogNull()
  1318. GrassGUIApp( grassTask( sys.argv[1] ) ).MainLoop()
  1319. else: #Test
  1320. # Test grassTask from within a GRASS session
  1321. if os.getenv("GISBASE") is not None:
  1322. task = grassTask( "d.vect" )
  1323. task.get_param('map')['value'] = "map_name"
  1324. task.get_flag('v')['value'] = True
  1325. task.get_param('layer')['value'] = 1
  1326. task.get_param('bcolor')['value'] = "red"
  1327. assert ' '.join( task.getCmd() ) == "d.vect -v map=map_name layer=1 bcolor=red"
  1328. # Test interface building with handmade grassTask,
  1329. # possibly outside of a GRASS session.
  1330. task = grassTask()
  1331. task.name = "TestTask"
  1332. task.description = "This is an artificial grassTask() object intended for testing purposes."
  1333. task.keywords = ["grass","test","task"]
  1334. task.params = [
  1335. {
  1336. "name" : "text",
  1337. "description" : "Descriptions go into tooltips if labels are present, like this one",
  1338. "label" : "Enter some text",
  1339. },{
  1340. "name" : "hidden_text",
  1341. "description" : "This text should not appear in the form",
  1342. "hidden" : "yes"
  1343. },{
  1344. "name" : "text_default",
  1345. "description" : "Enter text to override the default",
  1346. "default" : "default text"
  1347. },{
  1348. "name" : "text_prefilled",
  1349. "description" : "You should see a friendly welcome message here",
  1350. "value" : "hello, world"
  1351. },{
  1352. "name" : "plain_color",
  1353. "description" : "This is a plain color, and it is a compulsory parameter",
  1354. "required" : "yes",
  1355. "gisprompt" : True,
  1356. "prompt" : "color"
  1357. },{
  1358. "name" : "transparent_color",
  1359. "description" : "This color becomes transparent when set to none",
  1360. "guisection" : "tab",
  1361. "gisprompt" : True,
  1362. "prompt" : "color"
  1363. },{
  1364. "name" : "multi",
  1365. "description" : "A multiple selection",
  1366. 'default': u'red,green,blue',
  1367. 'gisprompt': False,
  1368. 'guisection': 'tab',
  1369. 'multiple': u'yes',
  1370. 'type': u'string',
  1371. 'value': '',
  1372. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other']
  1373. },{
  1374. "name" : "single",
  1375. "description" : "A single multiple-choice selection",
  1376. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  1377. "guisection" : "tab"
  1378. },{
  1379. "name" : "large_multi",
  1380. "description" : "A large multiple selection",
  1381. "gisprompt" : False,
  1382. "multiple" : "yes",
  1383. # values must be an array of strings
  1384. "values" : str2rgb.keys() + map( str, str2rgb.values() )
  1385. },{
  1386. "name" : "a_file",
  1387. "description" : "A file selector",
  1388. "gisprompt" : True,
  1389. "element" : "file"
  1390. }
  1391. ]
  1392. task.flags = [
  1393. {
  1394. "name" : "a",
  1395. "description" : "Some flag, will appear in Main since it is required",
  1396. "required" : "yes"
  1397. },{
  1398. "name" : "b",
  1399. "description" : "pre-filled flag, will appear in options since it is not required",
  1400. "value" : True
  1401. },{
  1402. "name" : "hidden_flag",
  1403. "description" : "hidden flag, should not be changeable",
  1404. "hidden" : "yes",
  1405. "value" : True
  1406. }
  1407. ]
  1408. q=wx.LogNull()
  1409. GrassGUIApp( task ).MainLoop()