menuform.py 76 KB

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