menuform.py 76 KB

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