menuform.py 78 KB

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