menuform.py 63 KB

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