menuform.py 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063
  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 menuform.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. elif pTable:
  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.rstrip('.py').rstrip('.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. # A select.Select is a combobox with two children: a textctl and a popupwindow;
  1071. # we target the textctl here
  1072. p['wxId'] = [selection.GetChildren()[0].GetId(), ]
  1073. selection.GetChildren()[0].Bind(wx.EVT_TEXT, self.OnSetValue)
  1074. if p.get('prompt', '') == 'vector':
  1075. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1076. if p.get('age', '') == 'old':
  1077. # OGR supported (read-only)
  1078. hsizer = wx.GridBagSizer(vgap=5, hgap=5)
  1079. hsizer.Add(item=selection,
  1080. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1081. border=5,
  1082. pos = (0, 0))
  1083. # format (native / ogr)
  1084. rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  1085. label = " %s " % _("Format"),
  1086. style = wx.RA_SPECIFY_ROWS,
  1087. size = (100, -1),
  1088. choices = [_("Native"), _("OGR")])
  1089. rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  1090. hsizer.Add(item=rbox,
  1091. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.ALIGN_TOP,
  1092. pos = (0, 1),
  1093. span = (3, 1),
  1094. border=5)
  1095. ogrSelection = filebrowse.DirBrowseButton(parent = which_panel, id = wx.ID_ANY,
  1096. size = globalvar.DIALOG_GSELECT_SIZE,
  1097. labelText = '',
  1098. dialogTitle = _('Choose OGR data source'),
  1099. buttonText = _('Browse'),
  1100. startDirectory = os.getcwd())
  1101. ogrSelection.SetName('OgrSelect')
  1102. ogrSelection.Enable(False)
  1103. ogrSelection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1104. hsizer.Add(item=wx.StaticText(parent = which_panel, id = wx.ID_ANY,
  1105. label = _("Name of OGR data source:")),
  1106. flag=wx.ALIGN_BOTTOM | wx.LEFT,
  1107. pos = (1, 0),
  1108. border=5)
  1109. hsizer.Add(item=ogrSelection,
  1110. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.ALIGN_TOP,
  1111. pos = (2, 0),
  1112. border=5)
  1113. which_sizer.Add(item = hsizer, proportion = 0)
  1114. p['wxId'].append(rbox.GetId())
  1115. p['wxId'].append(ogrSelection.GetId())
  1116. p['wxId'].append(ogrSelection.GetChildren()[1].GetId()) # fix
  1117. else:
  1118. which_sizer.Add(item=selection, proportion=0,
  1119. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1120. border=5)
  1121. else:
  1122. which_sizer.Add(item=selection, proportion=0,
  1123. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1124. border=5)
  1125. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1126. elif p.get('prompt', '') in ('dbdriver',
  1127. 'dbname',
  1128. 'dbtable',
  1129. 'dbcolumn',
  1130. 'layer',
  1131. 'layer_all'):
  1132. if p.get('multiple', 'no') == 'yes':
  1133. win = wx.TextCtrl(parent=which_panel, value = p.get('default',''),
  1134. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  1135. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1136. else:
  1137. if p.get('prompt', '') in ('layer',
  1138. 'layer_all'):
  1139. if p.get('prompt', '') == 'layer_all':
  1140. all = True
  1141. else:
  1142. all = False
  1143. if p.get('age', 'old_layer') == 'old_layer':
  1144. win = gselect.LayerSelect(parent=which_panel,
  1145. all=all,
  1146. default=p['default'])
  1147. p['wxGetValue'] = win.GetStringSelection
  1148. win.Bind(wx.EVT_CHOICE, self.OnUpdateSelection)
  1149. win.Bind(wx.EVT_CHOICE, self.OnSetValue)
  1150. else:
  1151. win = wx.SpinCtrl(parent=which_panel, id=wx.ID_ANY,
  1152. min=1, max=100, initial=int(p['default']))
  1153. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1154. elif p.get('prompt', '') == 'dbdriver':
  1155. win = gselect.DriverSelect(parent=which_panel,
  1156. choices=p['values'],
  1157. value=p['default'])
  1158. p['wxGetValue'] = win.GetStringSelection
  1159. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1160. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1161. elif p.get('prompt', '') == 'dbname':
  1162. win = gselect.DatabaseSelect(parent=which_panel,
  1163. value=p['default'])
  1164. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1165. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1166. elif p.get('prompt', '') == 'dbtable':
  1167. if p.get('age', 'old_dbtable') == 'old_dbtable':
  1168. win = gselect.TableSelect(parent=which_panel)
  1169. p['wxGetValue'] = win.GetStringSelection
  1170. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1171. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1172. else:
  1173. win = wx.TextCtrl(parent=which_panel, value = p.get('default',''),
  1174. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  1175. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1176. elif p.get('prompt', '') == 'dbcolumn':
  1177. win = gselect.ColumnSelect(parent=which_panel)
  1178. p['wxGetValue'] = win.GetStringSelection
  1179. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1180. p['wxId'] = win.GetId()
  1181. which_sizer.Add(item=win, proportion=0,
  1182. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  1183. # color entry
  1184. elif p.get('prompt', '') in ('color',
  1185. 'color_none'):
  1186. default_color = (200,200,200)
  1187. label_color = _("Select Color")
  1188. if p.get('default','') != '':
  1189. default_color, label_color = color_resolve( p['default'] )
  1190. if p.get('value','') != '': # parameter previously set
  1191. default_color, label_color = color_resolve( p['value'] )
  1192. if p.get('prompt', '') == 'color_none':
  1193. this_sizer = wx.BoxSizer(orient=wx.HORIZONTAL )
  1194. else:
  1195. this_sizer = which_sizer
  1196. btn_colour = csel.ColourSelect(parent=which_panel, id=wx.ID_ANY,
  1197. label=label_color, colour=default_color,
  1198. pos=wx.DefaultPosition, size=(150,-1) )
  1199. this_sizer.Add(item=btn_colour, proportion=0,
  1200. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  1201. # For color selectors, this is a two-member array, holding the IDs of
  1202. # the selector proper and either a "transparent" button or None
  1203. p['wxId'] = [btn_colour.GetId(),]
  1204. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange )
  1205. if p.get('prompt', '') == 'color_none':
  1206. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent") )
  1207. if p.get('value','') != '' and p.get('value',[''])[0] == "none":
  1208. none_check.SetValue(True)
  1209. else:
  1210. none_check.SetValue(False)
  1211. # none_check.SetFont( wx.Font( fontsize, wx.FONTFAMILY_DEFAULT, wx.NORMAL, text_style, 0, ''))
  1212. this_sizer.Add(item=none_check, proportion=0,
  1213. flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border=5)
  1214. which_sizer.Add( this_sizer )
  1215. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1216. p['wxId'].append( none_check.GetId() )
  1217. else:
  1218. p['wxId'].append(None)
  1219. # file selector
  1220. elif p.get('prompt','') != 'color' and p.get('element', '') == 'file':
  1221. fbb = filebrowse.FileBrowseButton(parent=which_panel, id=wx.ID_ANY,
  1222. size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
  1223. dialogTitle=_('Choose %s') % \
  1224. p.get('description',_('File')),
  1225. buttonText=_('Browse'),
  1226. startDirectory=os.getcwd(), fileMode=0,
  1227. changeCallback=self.OnSetValue)
  1228. if p.get('value','') != '':
  1229. fbb.SetValue(p['value']) # parameter previously set
  1230. which_sizer.Add(item=fbb, proportion=0,
  1231. flag=wx.EXPAND | wx.RIGHT, border=5)
  1232. # A file browse button is a combobox with two children:
  1233. # a textctl and a button;
  1234. # we have to target the button here
  1235. p['wxId'] = fbb.GetChildren()[1].GetId()
  1236. if title_txt is not None:
  1237. # create tooltip if given
  1238. if len(p['values_desc']) > 0:
  1239. if tooltip:
  1240. tooltip += 2 * os.linesep
  1241. else:
  1242. tooltip = ''
  1243. if len(p['values']) == len(p['values_desc']):
  1244. for i in range(len(p['values'])):
  1245. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1246. tooltip.strip(os.linesep)
  1247. if tooltip:
  1248. title_txt.SetToolTipString(tooltip)
  1249. if p == first_param:
  1250. if type(p['wxId']) == type(1):
  1251. self.FindWindowById(p['wxId']).SetFocus()
  1252. #
  1253. # set widget relations for OnUpdateSelection
  1254. #
  1255. pMap = None
  1256. pLayer = []
  1257. pDriver = None
  1258. pDatabase = None
  1259. pTable = None
  1260. pColumn = []
  1261. for p in self.task.params:
  1262. if p.get('gisprompt', False) == False:
  1263. continue
  1264. guidep = p.get('guidependency', '')
  1265. if guidep:
  1266. # fixed options dependency defined
  1267. options = guidep.split(',')
  1268. for opt in options:
  1269. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1270. if id:
  1271. if not p.has_key('wxId-bind'):
  1272. p['wxId-bind'] = list()
  1273. p['wxId-bind'].append(pOpt['wxId'])
  1274. continue
  1275. prompt = p.get('element', '')
  1276. if prompt == 'vector':
  1277. name = p.get('name', '')
  1278. if name in ('map', 'input'):
  1279. pMap = p
  1280. elif prompt == 'layer':
  1281. pLayer.append(p)
  1282. elif prompt == 'dbcolumn':
  1283. pColumn.append(p)
  1284. elif prompt == 'dbdriver':
  1285. pDriver = p
  1286. elif prompt == 'dbname':
  1287. pDatabase = p
  1288. elif prompt == 'dbtable':
  1289. pTable = p
  1290. # collect ids
  1291. pColumnIds = []
  1292. for p in pColumn:
  1293. pColumnIds.append(p['wxId'])
  1294. pLayerIds = []
  1295. for p in pLayer:
  1296. pLayerIds.append(p['wxId'])
  1297. # set wxId-bindings
  1298. if pMap:
  1299. pMap['wxId-bind'] = copy.copy(pColumnIds)
  1300. if pLayer:
  1301. pMap['wxId-bind'] += pLayerIds
  1302. if len(pLayer) == 1:
  1303. # TODO: fix modules with more 'layer' options
  1304. pLayer[0]['wxId-bind'] = copy.copy(pColumnIds)
  1305. if pDriver and pTable:
  1306. pDriver['wxId-bind'] = [pTable['wxId'], ]
  1307. if pDatabase and pTable:
  1308. pDatabase['wxId-bind'] = [pTable['wxId'], ]
  1309. if pTable and pColumnIds:
  1310. pTable['wxId-bind'] = pColumnIds
  1311. #
  1312. # determine panel size
  1313. #
  1314. maxsizes = (0,0)
  1315. for section in sections:
  1316. # tabsizer[section].SetSizeHints( tab[section] )
  1317. #tab[section].SetAutoLayout(True)
  1318. tab[section].SetSizer( tabsizer[section] )
  1319. tabsizer[section].Fit( tab[section] )
  1320. tab[section].Layout()
  1321. minsecsizes = tabsizer[section].GetSize()
  1322. maxsizes = map( lambda x: max( maxsizes[x], minsecsizes[x] ), (0,1) )
  1323. # TODO: be less arbitrary with these 600
  1324. self.panelMinHeight = 100
  1325. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1326. for section in sections:
  1327. tab[section].SetMinSize( (self.constrained_size[0], self.panelMinHeight) )
  1328. # tab[section].SetMinSize( constrained_size )
  1329. if self.manual_tab.Ok:
  1330. self.manual_tab.SetMinSize( (self.constrained_size[0], self.panelMinHeight) )
  1331. # manual_tab.SetMinSize( constrained_size )
  1332. self.SetSizer( panelsizer )
  1333. panelsizer.Fit(self.notebook)
  1334. self.hasMain = tab.has_key( _('Required') ) # publish, to enclosing Frame for instance
  1335. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1336. def OnVectorFormat(self, event):
  1337. """!Change vector format (native / ogr)"""
  1338. sel = event.GetSelection()
  1339. idEvent = event.GetId()
  1340. p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
  1341. if not p:
  1342. return # should not happen
  1343. winNative = None
  1344. winOGR = None
  1345. for id in p['wxId']:
  1346. if id == idEvent:
  1347. continue
  1348. name = self.FindWindowById(id).GetName()
  1349. if name == 'Select':
  1350. winNative = self.FindWindowById(id + 1) # fix the mystery (also in nviz_tools.py)
  1351. elif name == 'OgrSelect':
  1352. winOgr = self.FindWindowById(id)
  1353. # enable / disable widgets & update values
  1354. if sel == 0: # -> native
  1355. winOgr.Enable(False)
  1356. winNative.Enable(True)
  1357. p['value'] = winNative.GetValue()
  1358. elif sel == 1: # -> OGR
  1359. winNative.Enable(False)
  1360. winOgr.Enable(True)
  1361. p['value'] = winOgr.GetValue()
  1362. self.OnUpdateValues()
  1363. def OnUpdateDialog(self, event):
  1364. for fn, kwargs in event.data.iteritems():
  1365. fn(**kwargs)
  1366. def OnVerbosity(self, event):
  1367. """!Verbosity level changed"""
  1368. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'])
  1369. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'])
  1370. if event.IsChecked():
  1371. if event.GetId() == verbose.GetId():
  1372. if quiet.IsChecked():
  1373. quiet.SetValue(False)
  1374. self.task.get_flag('quiet')['value'] = False
  1375. else:
  1376. if verbose.IsChecked():
  1377. verbose.SetValue(False)
  1378. self.task.get_flag('verbose')['value'] = False
  1379. event.Skip()
  1380. def OnPageChange(self, event):
  1381. if not event:
  1382. sel = self.notebook.GetSelection()
  1383. else:
  1384. sel = event.GetSelection()
  1385. if hasattr(self, "manual_tab_id") and \
  1386. sel == self.manual_tab_id:
  1387. # calling LoadPage() is strangely time-consuming (only first call)
  1388. # FIXME: move to helpPage.__init__()
  1389. if not self.manual_tab.Ok:
  1390. wx.Yield()
  1391. self.manual_tab.LoadPage(self.manual_tab.fspath + self.task.name + ".html")
  1392. self.manual_tab.Ok = True
  1393. self.Layout()
  1394. def OnColorChange( self, event ):
  1395. myId = event.GetId()
  1396. for p in self.task.params:
  1397. if 'wxId' in p and type( p['wxId'] ) == type( [] ) and myId in p['wxId']:
  1398. has_button = p['wxId'][1] is not None
  1399. if has_button and wx.FindWindowById( p['wxId'][1] ).GetValue() == True:
  1400. p[ 'value' ] = 'none'
  1401. else:
  1402. colorchooser = wx.FindWindowById( p['wxId'][0] )
  1403. new_color = colorchooser.GetValue()[:]
  1404. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1405. # under wx2.8.1
  1406. new_label = rgb2str.get( new_color, ':'.join(map(str,new_color)) )
  1407. colorchooser.SetLabel( new_label )
  1408. colorchooser.SetColour( new_color )
  1409. colorchooser.Refresh()
  1410. p[ 'value' ] = colorchooser.GetLabel()
  1411. self.OnUpdateValues()
  1412. def OnUpdateValues(self):
  1413. """
  1414. If we were part of a richer interface, report back the current command being built.
  1415. This method should be set by the parent of this panel if needed. It's a hook, actually.
  1416. Beware of what is 'self' in the method def, though. It will be called with no arguments.
  1417. """
  1418. pass
  1419. def OnCheckBoxMulti(self, event):
  1420. """
  1421. Fill the values as a ','-separated string according to current status of the checkboxes.
  1422. """
  1423. me = event.GetId()
  1424. theParam = None
  1425. for p in self.task.params:
  1426. if 'wxId' in p and type( p['wxId'] ) == type( [] ) and me in p['wxId']:
  1427. theParam = p
  1428. myIndex = p['wxId'].index( me )
  1429. # Unpack current value list
  1430. currentValues = {}
  1431. for isThere in theParam.get('value', '').split(','):
  1432. currentValues[isThere] = 1
  1433. theValue = theParam['values'][myIndex]
  1434. if event.Checked():
  1435. currentValues[ theValue ] = 1
  1436. else:
  1437. del currentValues[ theValue ]
  1438. # Keep the original order, so that some defaults may be recovered
  1439. currentValueList = []
  1440. for v in theParam['values']:
  1441. if currentValues.has_key(v):
  1442. currentValueList.append( v )
  1443. # Pack it back
  1444. theParam['value'] = ','.join( currentValueList )
  1445. self.OnUpdateValues()
  1446. def OnSetValue(self, event):
  1447. """!
  1448. Retrieve the widget value and set the task value field
  1449. accordingly.
  1450. Use for widgets that have a proper GetValue() method, i.e. not
  1451. for selectors.
  1452. """
  1453. myId = event.GetId()
  1454. me = wx.FindWindowById( myId )
  1455. for porf in self.task.params + self.task.flags:
  1456. if 'wxId' in porf:
  1457. found = False
  1458. porf['wxId']
  1459. if type(porf['wxId']) == types.IntType:
  1460. if porf['wxId'] == myId:
  1461. found = True
  1462. else: # -> list
  1463. for id in porf['wxId']:
  1464. if id == myId:
  1465. found = True
  1466. break
  1467. if found:
  1468. if porf.has_key('wxGetValue') and porf['wxGetValue']:
  1469. porf['value'] = porf['wxGetValue']()
  1470. else:
  1471. porf['value'] = me.GetValue()
  1472. self.OnUpdateValues()
  1473. event.Skip()
  1474. def OnUpdateSelection(self, event):
  1475. """
  1476. Update dialog (layers, tables, columns, etc.)
  1477. """
  1478. if event:
  1479. self.parent.updateThread.Update(UpdateDialog,
  1480. self,
  1481. event,
  1482. event.GetId(),
  1483. self.task)
  1484. else:
  1485. self.parent.updateThread.Update(UpdateDialog,
  1486. self,
  1487. None,
  1488. None,
  1489. self.task)
  1490. def createCmd( self, ignoreErrors = False ):
  1491. """
  1492. Produce a command line string (list) or feeding into GRASS.
  1493. If ignoreErrors==True then it will return whatever has been
  1494. built so far, even though it would not be a correct command
  1495. for GRASS.
  1496. """
  1497. try:
  1498. cmd = self.task.getCmd( ignoreErrors=ignoreErrors )
  1499. except ValueError, err:
  1500. dlg = wx.MessageDialog(parent=self,
  1501. message=unicode(err),
  1502. caption=_("Error in %s") % self.task.name,
  1503. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1504. dlg.ShowModal()
  1505. dlg.Destroy()
  1506. cmd = None
  1507. return cmd
  1508. def OnSize(self, event):
  1509. width = event.GetSize()[0]
  1510. fontsize = self.GetFont().GetPointSize()
  1511. text_width = width / (fontsize - 3)
  1512. if text_width < 70:
  1513. text_width = 70
  1514. for id in self.label_id:
  1515. win = self.FindWindowById(id)
  1516. label = win.GetLabel()
  1517. label_new = '\n'.join(textwrap.wrap(label, text_width ))
  1518. win.SetLabel(label_new)
  1519. event.Skip()
  1520. def getInterfaceDescription( cmd ):
  1521. """
  1522. Returns the XML description for the GRASS cmd.
  1523. The DTD must be located in $GISBASE/etc/grass-interface.dtd,
  1524. otherwise the parser will not succeed.
  1525. Note: 'cmd' is given as string
  1526. """
  1527. cmdout = os.popen(cmd + r' --interface-description', "r").read()
  1528. if not len(cmdout) > 0 :
  1529. raise IOError, _("Unable to fetch interface description for command '%s'.") % cmd
  1530. p = re.compile( '(grass-interface.dtd)')
  1531. p.search( cmdout )
  1532. cmdout = p.sub(globalvar.ETCDIR + r'/grass-interface.dtd', cmdout)
  1533. return cmdout
  1534. class GrassGUIApp(wx.App):
  1535. """
  1536. Stand-alone GRASS command GUI
  1537. """
  1538. def __init__(self, grass_task):
  1539. self.grass_task = grass_task
  1540. wx.App.__init__(self, False)
  1541. def OnInit(self):
  1542. self.mf = mainFrame(parent=None, ID=wx.ID_ANY, task_description=self.grass_task)
  1543. self.mf.CentreOnScreen()
  1544. self.mf.Show(True)
  1545. self.SetTopWindow(self.mf)
  1546. return True
  1547. class GUI:
  1548. """
  1549. Parses GRASS commands when module is imported and used
  1550. from Layer Manager.
  1551. """
  1552. def __init__(self, parent=-1):
  1553. self.parent = parent
  1554. self.grass_task = None
  1555. def ParseInterface(self, cmd, parser = processTask):
  1556. """!Parse interface
  1557. @param cmd command to be parsed (given as list)
  1558. """
  1559. enc = locale.getdefaultlocale()[1]
  1560. if enc and enc.lower() not in ("utf8", "utf-8"):
  1561. tree = etree.fromstring(getInterfaceDescription(cmd[0]).decode(enc).encode("utf-8"))
  1562. else:
  1563. tree = etree.fromstring(getInterfaceDescription(cmd[0]))
  1564. return processTask(tree).GetTask()
  1565. def ParseCommand(self, cmd, gmpath=None, completed=None, parentframe=None,
  1566. show=True, modal=False):
  1567. """
  1568. Parse command
  1569. Note: cmd is given as list
  1570. If command is given with options, return validated cmd list:
  1571. * add key name for first parameter if not given
  1572. * change mapname to mapname@mapset
  1573. """
  1574. start = time.time()
  1575. dcmd_params = {}
  1576. if completed == None:
  1577. get_dcmd = None
  1578. layer = None
  1579. dcmd_params = None
  1580. else:
  1581. get_dcmd = completed[0]
  1582. layer = completed[1]
  1583. if completed[2]:
  1584. dcmd_params.update(completed[2])
  1585. self.parent = parentframe
  1586. # parse the interface decription
  1587. self.grass_task = self.ParseInterface(cmd)
  1588. # if layer parameters previously set, re-insert them into dialog
  1589. if completed is not None:
  1590. if 'params' in dcmd_params:
  1591. self.grass_task.params = dcmd_params['params']
  1592. if 'flags' in dcmd_params:
  1593. self.grass_task.flags = dcmd_params['flags']
  1594. # update parameters if needed && validate command
  1595. if len(cmd) > 1:
  1596. i = 0
  1597. cmd_validated = [cmd[0]]
  1598. for option in cmd[1:]:
  1599. if option[0] == '-': # flag
  1600. self.grass_task.set_flag(option[1], True)
  1601. cmd_validated.append(option)
  1602. else: # parameter
  1603. try:
  1604. key, value = option.split('=', 1)
  1605. except:
  1606. if i == 0: # add key name of first parameter if not given
  1607. key = self.grass_task.firstParam
  1608. value = option
  1609. else:
  1610. raise ValueError, _("Unable to parse command %s") % ' '.join(cmd)
  1611. if self.grass_task.get_param(key)['element'] in ['cell', 'vector']:
  1612. # mapname -> mapname@mapset
  1613. if '@' not in value:
  1614. value = value + '@' + grass.gisenv()['MAPSET']
  1615. self.grass_task.set_param(key, value)
  1616. cmd_validated.append(key + '=' + value)
  1617. i = i + 1
  1618. # update original command list
  1619. cmd = cmd_validated
  1620. self.mf = mainFrame(parent=self.parent, ID=wx.ID_ANY,
  1621. task_description=self.grass_task,
  1622. get_dcmd=get_dcmd, layer=layer)
  1623. if get_dcmd is not None:
  1624. # update only propwin reference
  1625. get_dcmd(dcmd=None, layer=layer, params=None,
  1626. propwin=self.mf)
  1627. self.mf.notebookpanel.OnUpdateSelection(None)
  1628. if show:
  1629. if self.parent:
  1630. self.mf.CentreOnParent()
  1631. self.mf.Show(show)
  1632. self.mf.MakeModal(modal)
  1633. else:
  1634. self.mf.OnApply(None)
  1635. return cmd
  1636. def GetCommandInputMapParamKey(self, cmd):
  1637. """!Get parameter key for input raster/vector map
  1638. @param cmd module name
  1639. @return parameter key
  1640. @return None on failure
  1641. """
  1642. # parse the interface decription
  1643. if not self.grass_task:
  1644. tree = etree.fromstring(getInterfaceDescription(cmd))
  1645. self.grass_task = processTask(tree).GetTask()
  1646. for p in self.grass_task.params:
  1647. if p.get('name', '') in ('input', 'map'):
  1648. age = p.get('age', '')
  1649. prompt = p.get('prompt', '')
  1650. element = p.get('element', '')
  1651. if age == 'old' and \
  1652. element in ('cell', 'grid3', 'vector') and \
  1653. prompt in ('raster', '3d-raster', 'vector'):
  1654. return p.get('name', None)
  1655. return None
  1656. class StaticWrapText(wx.StaticText):
  1657. """
  1658. A Static Text field that wraps its text to fit its width, enlarging its height if necessary.
  1659. """
  1660. def __init__(self, parent, id=wx.ID_ANY, label=u'', *args, **kwds):
  1661. self.originalLabel = label
  1662. wx.StaticText.__init__(self, parent, id, u'', *args, **kwds)
  1663. self.SetLabel(label)
  1664. self.Bind(wx.EVT_SIZE, self.onResize)
  1665. def SetLabel(self, label):
  1666. self.originalLabel = label
  1667. self.wrappedSize = None
  1668. #self.onResize(None)
  1669. def onResize(self, event):
  1670. if not getattr(self, "resizing", False):
  1671. self.resizing = True
  1672. newSize = self.GetSize()
  1673. if self.wrappedSize != newSize:
  1674. wx.StaticText.SetLabel(self, self.originalLabel)
  1675. self.Wrap(newSize.width)
  1676. self.wrappedSize = self.GetMinSize()
  1677. self.SetSize(self.wrappedSize)
  1678. del self.resizing
  1679. if __name__ == "__main__":
  1680. if len(sys.argv) == 1:
  1681. print _("usage: %s <grass command>") % sys.argv[0]
  1682. sys.exit()
  1683. if sys.argv[1] != 'test':
  1684. q=wx.LogNull()
  1685. GrassGUIApp(grassTask(sys.argv[1])).MainLoop()
  1686. else: #Test
  1687. # Test grassTask from within a GRASS session
  1688. if os.getenv("GISBASE") is not None:
  1689. task = grassTask( "d.vect" )
  1690. task.get_param('map')['value'] = "map_name"
  1691. task.get_flag('v')['value'] = True
  1692. task.get_param('layer')['value'] = 1
  1693. task.get_param('bcolor')['value'] = "red"
  1694. assert ' '.join( task.getCmd() ) == "d.vect -v map=map_name layer=1 bcolor=red"
  1695. # Test interface building with handmade grassTask,
  1696. # possibly outside of a GRASS session.
  1697. task = grassTask()
  1698. task.name = "TestTask"
  1699. task.description = "This is an artificial grassTask() object intended for testing purposes."
  1700. task.keywords = ["grass","test","task"]
  1701. task.params = [
  1702. {
  1703. "name" : "text",
  1704. "description" : "Descriptions go into tooltips if labels are present, like this one",
  1705. "label" : "Enter some text",
  1706. },{
  1707. "name" : "hidden_text",
  1708. "description" : "This text should not appear in the form",
  1709. "hidden" : "yes"
  1710. },{
  1711. "name" : "text_default",
  1712. "description" : "Enter text to override the default",
  1713. "default" : "default text"
  1714. },{
  1715. "name" : "text_prefilled",
  1716. "description" : "You should see a friendly welcome message here",
  1717. "value" : "hello, world"
  1718. },{
  1719. "name" : "plain_color",
  1720. "description" : "This is a plain color, and it is a compulsory parameter",
  1721. "required" : "yes",
  1722. "gisprompt" : True,
  1723. "prompt" : "color"
  1724. },{
  1725. "name" : "transparent_color",
  1726. "description" : "This color becomes transparent when set to none",
  1727. "guisection" : "tab",
  1728. "gisprompt" : True,
  1729. "prompt" : "color"
  1730. },{
  1731. "name" : "multi",
  1732. "description" : "A multiple selection",
  1733. 'default': u'red,green,blue',
  1734. 'gisprompt': False,
  1735. 'guisection': 'tab',
  1736. 'multiple': u'yes',
  1737. 'type': u'string',
  1738. 'value': '',
  1739. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other']
  1740. },{
  1741. "name" : "single",
  1742. "description" : "A single multiple-choice selection",
  1743. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  1744. "guisection" : "tab"
  1745. },{
  1746. "name" : "large_multi",
  1747. "description" : "A large multiple selection",
  1748. "gisprompt" : False,
  1749. "multiple" : "yes",
  1750. # values must be an array of strings
  1751. "values" : str2rgb.keys() + map( str, str2rgb.values() )
  1752. },{
  1753. "name" : "a_file",
  1754. "description" : "A file selector",
  1755. "gisprompt" : True,
  1756. "element" : "file"
  1757. }
  1758. ]
  1759. task.flags = [
  1760. {
  1761. "name" : "a",
  1762. "description" : "Some flag, will appear in Main since it is required",
  1763. "required" : "yes"
  1764. },{
  1765. "name" : "b",
  1766. "description" : "pre-filled flag, will appear in options since it is not required",
  1767. "value" : True
  1768. },{
  1769. "name" : "hidden_flag",
  1770. "description" : "hidden flag, should not be changeable",
  1771. "hidden" : "yes",
  1772. "value" : True
  1773. }
  1774. ]
  1775. q=wx.LogNull()
  1776. GrassGUIApp( task ).MainLoop()