menuform.py 85 KB

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