menuform.py 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243
  1. #! /usr/bin/python
  2. """
  3. @brief Construct simple wxPython 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. - FloatValidator
  14. This program is just a coarse approach to automatically build a GUI
  15. from a xml-based GRASS user interface description.
  16. You need to have Python 2.4, wxPython 2.8 and python-xml.
  17. The XML stream is read from executing the command given in the
  18. command line, thus you may call it for instance this way:
  19. python menuform.py r.basins.fill
  20. Or you set an alias or wrap the call up in a nice shell script, GUI
  21. environment ... please contribute your idea.
  22. Updated to wxPython 2.8 syntax and contrib widgets. Methods added to
  23. make it callable by gui. Method added to automatically re-run with
  24. pythonw on a Mac.
  25. @todo
  26. - verify option value types
  27. Copyright (C) 2000-2010 by the GRASS Development Team
  28. This program is free software under the GPL (>=v2) Read the file
  29. COPYING coming with GRASS for details.
  30. @author Jan-Oliver Wagner <jan@intevation.de>
  31. @author Bernhard Reiter <bernhard@intevation.de>
  32. @author Michael Barton, Arizona State University
  33. @author Daniel Calvelo <dca.gis@gmail.com>
  34. @author Martin Landa <landa.martin@gmail.com>
  35. """
  36. import sys
  37. import re
  38. import string
  39. import textwrap
  40. import os
  41. import time
  42. import types
  43. import copy
  44. import locale
  45. import types
  46. from threading import Thread
  47. import Queue
  48. import shlex
  49. ### i18N
  50. import gettext
  51. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True)
  52. import globalvar
  53. if not os.getenv("GRASS_WXBUNDLED"):
  54. globalvar.CheckForWx()
  55. import wx
  56. import wx.html
  57. import wx.lib.flatnotebook as FN
  58. import wx.lib.colourselect as csel
  59. import wx.lib.filebrowsebutton as filebrowse
  60. from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
  61. from wx.lib.newevent import NewEvent
  62. try:
  63. import xml.etree.ElementTree as etree
  64. except ImportError:
  65. import elementtree.ElementTree as etree # Python <= 2.4
  66. import gdialogs
  67. from ghelp import HelpPanel
  68. gisbase = os.getenv("GISBASE")
  69. if gisbase is None:
  70. print >>sys.stderr, "We don't seem to be properly installed, or we are being run outside GRASS. Expect glitches."
  71. gisbase = os.path.join(os.path.dirname( sys.argv[0] ), os.path.pardir)
  72. wxbase = gisbase
  73. else:
  74. wxbase = os.path.join(globalvar.ETCWXDIR)
  75. sys.path.append( wxbase)
  76. imagepath = os.path.join(wxbase, "images")
  77. sys.path.append(imagepath)
  78. from grass.script import core as grass
  79. import gselect
  80. import gcmd
  81. import goutput
  82. import utils
  83. from preferences import globalSettings as UserSettings
  84. try:
  85. import subprocess
  86. except:
  87. from compat import subprocess
  88. wxUpdateDialog, EVT_DIALOG_UPDATE = NewEvent()
  89. # From lib/gis/col_str.c, except purple which is mentioned
  90. # there but not given RGB values
  91. str2rgb = {'aqua': (100, 128, 255),
  92. 'black': (0, 0, 0),
  93. 'blue': (0, 0, 255),
  94. 'brown': (180, 77, 25),
  95. 'cyan': (0, 255, 255),
  96. 'gray': (128, 128, 128),
  97. 'green': (0, 255, 0),
  98. 'grey': (128, 128, 128),
  99. 'indigo': (0, 128, 255),
  100. 'magenta': (255, 0, 255),
  101. 'orange': (255, 128, 0),
  102. 'purple': (128, 0, 128),
  103. 'red': (255, 0, 0),
  104. 'violet': (128, 0, 255),
  105. 'white': (255, 255, 255),
  106. 'yellow': (255, 255, 0)}
  107. rgb2str = {}
  108. for (s,r) in str2rgb.items():
  109. rgb2str[ r ] = s
  110. def color_resolve(color):
  111. if len(color)>0 and color[0] in "0123456789":
  112. rgb = tuple(map(int, color.split( ':' )))
  113. label = color
  114. else:
  115. # Convert color names to RGB
  116. try:
  117. rgb = str2rgb[color]
  118. label = color
  119. except KeyError:
  120. rgb = (200, 200, 200)
  121. label = _('Select Color')
  122. return (rgb, label)
  123. def text_beautify( someString , width=70):
  124. """!Make really long texts shorter, clean up whitespace and remove
  125. trailing punctuation.
  126. """
  127. if width > 0:
  128. return escape_ampersand( string.strip(
  129. os.linesep.join( textwrap.wrap( utils.normalize_whitespace(someString), width ) ),
  130. ".,;:" ) )
  131. else:
  132. return escape_ampersand( string.strip(utils.normalize_whitespace(someString ), ".,;:" ))
  133. def escape_ampersand(text):
  134. """!Escapes ampersands with additional ampersand for GUI"""
  135. return string.replace(text, "&", "&&")
  136. class UpdateThread(Thread):
  137. """!Update dialog widgets in the thread"""
  138. def __init__(self, parent, event, eventId, task):
  139. Thread.__init__(self)
  140. self.parent = parent
  141. self.event = event
  142. self.eventId = eventId
  143. self.task = task
  144. self.setDaemon(True)
  145. # list of functions which updates the dialog
  146. self.data = {}
  147. def run(self):
  148. # get widget id
  149. if not self.eventId:
  150. for p in self.task.params:
  151. if p.get('gisprompt', False) == False:
  152. continue
  153. prompt = p.get('element', '')
  154. if prompt == 'vector':
  155. name = p.get('name', '')
  156. if name in ('map', 'input'):
  157. self.eventId = p['wxId'][0]
  158. if self.eventId is None:
  159. return
  160. p = self.task.get_param(self.eventId, element='wxId', raiseError=False)
  161. if not p or \
  162. not p.has_key('wxId-bind'):
  163. return
  164. # get widget prompt
  165. pType = p.get('prompt', '')
  166. if not pType:
  167. return
  168. # check for map/input parameter
  169. pMap = self.task.get_param('map', raiseError=False)
  170. if not pMap:
  171. pMap = self.task.get_param('input', raiseError=False)
  172. if pMap:
  173. map = pMap.get('value', '')
  174. else:
  175. map = None
  176. # avoid running db.describe several times
  177. cparams = dict()
  178. cparams[map] = { 'dbInfo' : None,
  179. 'layers' : None, }
  180. # update reference widgets
  181. for uid in p['wxId-bind']:
  182. win = self.parent.FindWindowById(uid)
  183. name = win.GetName()
  184. map = layer = None
  185. driver = db = table = None
  186. if name in ('LayerSelect', 'LayerNameSelect',
  187. 'ColumnSelect'):
  188. if p.get('element', '') == 'vector': # -> vector
  189. # get map name
  190. map = p.get('value', '')
  191. # get layer
  192. for bid in p['wxId-bind']:
  193. p = self.task.get_param(bid, element = 'wxId', raiseError = False)
  194. if not p:
  195. continue
  196. if p.get('element', '') == 'layer':
  197. layer = p.get('value', '')
  198. if layer != '':
  199. layer = p.get('value', 1)
  200. else:
  201. layer = p.get('default', 1)
  202. break
  203. elif p.get('element', '') == 'layer': # -> layer
  204. # get layer
  205. layer = p.get('value', '')
  206. if layer != '':
  207. layer = p.get('value', 1)
  208. else:
  209. layer = p.get('default', 1)
  210. # get map name
  211. pMap = self.task.get_param(p['wxId'][0], element = 'wxId-bind', raiseError = False)
  212. if pMap:
  213. map = pMap.get('value', '')
  214. if name == 'TableSelect' or \
  215. (name == 'ColumnSelect' and not map):
  216. pDriver = self.task.get_param('dbdriver', element='prompt', raiseError=False)
  217. if pDriver:
  218. driver = pDriver.get('value', '')
  219. pDb = self.task.get_param('dbname', element='prompt', raiseError=False)
  220. if pDb:
  221. db = pDb.get('value', '')
  222. if name == 'ColumnSelect':
  223. pTable = self.task.get_param('dbtable', element='element', raiseError=False)
  224. if pTable:
  225. table = pTable.get('value', '')
  226. if name == 'LayerSelect':
  227. if not cparams[map]['layers']:
  228. win.InsertLayers(vector = map)
  229. cparams[map]['layers'] = win.GetItems()
  230. elif name == 'LayerNameSelect':
  231. # determine format
  232. native = True
  233. for id in pMap['wxId']:
  234. winVec = self.parent.FindWindowById(id)
  235. if winVec.GetName() == 'VectorFormat' and \
  236. winVec.GetSelection() != 0:
  237. native = False
  238. break
  239. if not native:
  240. if map:
  241. self.data[win.InsertLayers] = { 'dsn' : map.rstrip('@OGR') }
  242. else:
  243. self.data[win.InsertLayers] = { }
  244. elif name == 'TableSelect':
  245. self.data[win.InsertTables] = { 'driver' : driver,
  246. 'database' : db }
  247. elif name == 'ColumnSelect':
  248. if map:
  249. if not cparams[map]['dbInfo']:
  250. cparams[map]['dbInfo'] = gselect.VectorDBInfo(map)
  251. self.data[win.InsertColumns] = { 'vector' : map, 'layer' : layer,
  252. 'dbInfo' : cparams[map]['dbInfo'] }
  253. else: # table
  254. if driver and db:
  255. self.data[win.InsertTableColumns] = { 'table' : pTable.get('value'),
  256. 'driver' : driver,
  257. 'database' : db }
  258. elif pTable:
  259. self.data[win.InsertTableColumns] = { 'table' : pTable.get('value') }
  260. elif name == 'SubGroupSelect':
  261. pGroup = self.task.get_param('group', element='element', raiseError=False)
  262. if pGroup:
  263. self.data[win.Insert] = { 'group' : pGroup.get('value', '')}
  264. def UpdateDialog(parent, event, eventId, task):
  265. return UpdateThread(parent, event, eventId, task)
  266. class UpdateQThread(Thread):
  267. """!Update dialog widgets in the thread"""
  268. requestId = 0
  269. def __init__(self, parent, requestQ, resultQ, **kwds):
  270. Thread.__init__(self, **kwds)
  271. self.parent = parent # cmdPanel
  272. self.setDaemon(True)
  273. self.requestQ = requestQ
  274. self.resultQ = resultQ
  275. self.start()
  276. def Update(self, callable, *args, **kwds):
  277. UpdateQThread.requestId += 1
  278. self.request = None
  279. self.requestQ.put((UpdateQThread.requestId, callable, args, kwds))
  280. return UpdateQThread.requestId
  281. def run(self):
  282. while True:
  283. requestId, callable, args, kwds = self.requestQ.get()
  284. requestTime = time.time()
  285. self.request = callable(*args, **kwds)
  286. self.resultQ.put((requestId, self.request.run()))
  287. event = wxUpdateDialog(data = self.request.data)
  288. wx.PostEvent(self.parent, event)
  289. class grassTask:
  290. """!This class holds the structures needed for both filling by the
  291. parser and use by the interface constructor.
  292. Use as either grassTask() for empty definition or
  293. grassTask('grass.command' ) for parsed filling.
  294. """
  295. def __init__(self, grassModule = None):
  296. self.path = grassModule
  297. self.name = _('unknown')
  298. self.params = list()
  299. self.description = ''
  300. self.label = ''
  301. self.flags = list()
  302. self.keywords = list()
  303. if grassModule is not None:
  304. processTask(tree = etree.fromstring(getInterfaceDescription(grassModule)),
  305. task = self)
  306. def get_name(self):
  307. """!Get task name"""
  308. return self.name
  309. def get_list_params(self, element = 'name'):
  310. """!Get list of parameters"""
  311. params = []
  312. for p in self.params:
  313. params.append(p['name'])
  314. return params
  315. def get_list_flags(self, element = 'name'):
  316. """!Get list of parameters"""
  317. flags = []
  318. for p in self.flags:
  319. flags.append(p['name'])
  320. return flags
  321. def get_param(self, value, element='name', raiseError=True):
  322. """!Find and return a param by name."""
  323. try:
  324. for p in self.params:
  325. val = p[element]
  326. if val is None:
  327. continue
  328. if type(val) in (types.ListType, types.TupleType):
  329. if value in val:
  330. return p
  331. elif type(val) == types.StringType:
  332. if p[element][:len(value)] == value:
  333. return p
  334. else:
  335. if p[element] == value:
  336. return p
  337. except KeyError:
  338. pass
  339. if raiseError:
  340. raise ValueError, _("Parameter element '%(element)s' not found: '%(value)s'") % \
  341. { 'element' : element, 'value' : value }
  342. else:
  343. return None
  344. def set_param(self, aParam, aValue, element = 'value'):
  345. """
  346. Set param value/values.
  347. """
  348. try:
  349. param = self.get_param(aParam)
  350. except ValueError:
  351. return
  352. param[element] = aValue
  353. def get_flag(self, aFlag):
  354. """
  355. Find and return a flag by name.
  356. """
  357. for f in self.flags:
  358. if f['name'] == aFlag:
  359. return f
  360. raise ValueError, _("Flag not found: %s") % aFlag
  361. def set_flag(self, aFlag, aValue, element = 'value'):
  362. """
  363. Enable / disable flag.
  364. """
  365. try:
  366. param = self.get_flag(aFlag)
  367. except ValueError:
  368. return
  369. param[element] = aValue
  370. def getCmdError(self):
  371. """!Get error string produced by getCmd(ignoreErrors = False)
  372. @return list of errors
  373. """
  374. errorList = list()
  375. for p in self.params:
  376. if p.get('value', '') == '' and p.get('required', 'no') != 'no':
  377. if p.get('default', '') == '':
  378. errorList.append(_("Parameter '%(name)s' (%(desc)s) is missing.") % \
  379. {'name' : p['name'], 'desc' : p['description']})
  380. return errorList
  381. def getCmd(self, ignoreErrors = False):
  382. """!Produce an array of command name and arguments for feeding
  383. into some execve-like command processor.
  384. If ignoreErrors==True then it will return whatever has been
  385. built so far, even though it would not be a correct command
  386. for GRASS.
  387. """
  388. cmd = [self.name]
  389. for flag in self.flags:
  390. if 'value' in flag and flag['value']:
  391. if len(flag['name']) > 1: # e.g. overwrite
  392. cmd += [ '--' + flag['name'] ]
  393. else:
  394. cmd += [ '-' + flag['name'] ]
  395. for p in self.params:
  396. if p.get('value','') == '' and p.get('required','no') != 'no':
  397. if p.get('default', '') != '':
  398. cmd += [ '%s=%s' % ( p['name'], p['default'] ) ]
  399. elif ignoreErrors is False:
  400. cmd += [ '%s=%s' % ( p['name'], _('<required>') ) ]
  401. elif p.get('value','') != '' and p['value'] != p.get('default','') :
  402. # Output only values that have been set, and different from defaults
  403. cmd += [ '%s=%s' % ( p['name'], p['value'] ) ]
  404. errList = self.getCmdError()
  405. if ignoreErrors is False and errList:
  406. raise ValueError, '\n'.join(errList)
  407. return cmd
  408. def set_options(self, opts):
  409. """!Set flags and parameters
  410. @param opts list of flags and parameters"""
  411. for opt in opts:
  412. if opt[0] == '-': # flag
  413. self.set_flag(opt.lstrip('-'), True)
  414. else: # parameter
  415. key, value = opt.split('=', 1)
  416. self.set_param(key, value)
  417. def get_options(self):
  418. """!Get options"""
  419. return { 'flags' : self.flags,
  420. 'params' : self.params }
  421. class processTask:
  422. """!A ElementTree handler for the --interface-description output,
  423. as defined in grass-interface.dtd. Extend or modify this and the
  424. DTD if the XML output of GRASS' parser is extended or modified.
  425. @param tree root tree node
  426. @param task grassTask instance or None
  427. @return grassTask instance
  428. """
  429. def __init__(self, tree, task = None):
  430. if task:
  431. self.task = task
  432. else:
  433. self.task = grassTask()
  434. self.root = tree
  435. self.__processModule()
  436. self.__processParams()
  437. self.__processFlags()
  438. def __processModule(self):
  439. """!Process module description"""
  440. self.task.name = self.root.get('name', default = 'unknown')
  441. # keywords
  442. for keyword in self.__getNodeText(self.root, 'keywords').split(','):
  443. self.task.keywords.append(keyword.strip())
  444. self.task.label = self.__getNodeText(self.root, 'label')
  445. self.task.description = self.__getNodeText(self.root, 'description')
  446. def __processParams(self):
  447. """!Process parameters description"""
  448. for p in self.root.findall('parameter'):
  449. # gisprompt
  450. node_gisprompt = p.find('gisprompt')
  451. gisprompt = False
  452. age = element = prompt = None
  453. if node_gisprompt is not None:
  454. gisprompt = True
  455. age = node_gisprompt.get('age', '')
  456. element = node_gisprompt.get('element', '')
  457. prompt = node_gisprompt.get('prompt', '')
  458. # value(s)
  459. values = []
  460. values_desc = []
  461. node_values = p.find('values')
  462. if node_values is not None:
  463. for pv in node_values.findall('value'):
  464. values.append(self.__getNodeText(pv, 'name'))
  465. desc = self.__getNodeText(pv, 'description')
  466. if desc:
  467. values_desc.append(desc)
  468. # keydesc
  469. key_desc = []
  470. node_key_desc = p.find('keydesc')
  471. if node_key_desc is not None:
  472. for ki in node_key_desc.findall('item'):
  473. key_desc.append(ki.text)
  474. self.task.params.append( {
  475. "name" : p.get('name'),
  476. "type" : p.get('type'),
  477. "required" : p.get('required'),
  478. "multiple" : p.get('multiple'),
  479. "label" : self.__getNodeText(p, 'label'),
  480. "description" : self.__getNodeText(p, 'description'),
  481. 'gisprompt' : gisprompt,
  482. 'age' : age,
  483. 'element' : element,
  484. 'prompt' : prompt,
  485. "guisection" : self.__getNodeText(p, 'guisection'),
  486. "guidependency" : self.__getNodeText(p, 'guidependency'),
  487. "default" : self.__getNodeText(p, 'default'),
  488. "values" : values,
  489. "values_desc" : values_desc,
  490. "value" : '',
  491. "key_desc" : key_desc } )
  492. def __processFlags(self):
  493. """!Process flags description"""
  494. for p in self.root.findall('flag'):
  495. self.task.flags.append( {
  496. "name" : p.get('name'),
  497. "label" : self.__getNodeText(p, 'label'),
  498. "description" : self.__getNodeText(p, 'description'),
  499. "guisection" : self.__getNodeText(p, 'guisection') } )
  500. def __getNodeText(self, node, tag, default = ''):
  501. """!Get node text"""
  502. p = node.find(tag)
  503. if p is not None:
  504. return utils.normalize_whitespace(p.text)
  505. return default
  506. def GetTask(self):
  507. """!Get grassTask instance"""
  508. return self.task
  509. class mainFrame(wx.Frame):
  510. """!This is the Frame containing the dialog for options input.
  511. The dialog is organized in a notebook according to the guisections
  512. defined by each GRASS command.
  513. If run with a parent, it may Apply, Ok or Cancel; the latter two
  514. close the dialog. The former two trigger a callback.
  515. If run standalone, it will allow execution of the command.
  516. The command is checked and sent to the clipboard when clicking
  517. 'Copy'.
  518. """
  519. def __init__(self, parent, ID, task_description,
  520. get_dcmd = None, layer = None):
  521. self.get_dcmd = get_dcmd
  522. self.layer = layer
  523. self.task = task_description
  524. self.parent = parent # LayerTree | Modeler | None | ...
  525. if parent and parent.GetName() == 'Modeler':
  526. self.modeler = self.parent
  527. else:
  528. self.modeler = None
  529. # module name + keywords
  530. if self.task.name.split('.')[-1] in ('py', 'sh'):
  531. title = str(self.task.name.rsplit('.',1)[0])
  532. else:
  533. title = self.task.name
  534. try:
  535. if self.task.keywords != ['']:
  536. title += " [" + ', '.join( self.task.keywords ) + "]"
  537. except ValueError:
  538. pass
  539. wx.Frame.__init__(self, parent=parent, id=ID, title=title,
  540. pos=wx.DefaultPosition, style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL,
  541. name = "MainFrame")
  542. self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
  543. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  544. # statusbar
  545. self.CreateStatusBar()
  546. # icon
  547. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_dialog.ico'), wx.BITMAP_TYPE_ICO))
  548. guisizer = wx.BoxSizer(wx.VERTICAL)
  549. # set apropriate output window
  550. if self.parent:
  551. self.standalone = False
  552. else:
  553. self.standalone = True
  554. # logo+description
  555. topsizer = wx.BoxSizer(wx.HORIZONTAL)
  556. # GRASS logo
  557. self.logo = wx.StaticBitmap(parent=self.panel,
  558. bitmap=wx.Bitmap(name=os.path.join(imagepath,
  559. 'grass_form.png'),
  560. type=wx.BITMAP_TYPE_PNG))
  561. topsizer.Add (item=self.logo, proportion=0, border=3,
  562. flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
  563. #
  564. # put module description
  565. #
  566. if self.task.label != '':
  567. module_desc = self.task.label + ' ' + self.task.description
  568. else:
  569. module_desc = self.task.description
  570. self.description = gdialogs.StaticWrapText(parent=self.panel,
  571. label=module_desc)
  572. topsizer.Add (item=self.description, proportion=1, border=5,
  573. flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  574. guisizer.Add (item=topsizer, proportion=0, flag=wx.EXPAND)
  575. self.panel.SetSizerAndFit(guisizer)
  576. self.Layout()
  577. # notebooks
  578. self.notebookpanel = cmdPanel(parent = self.panel, task = self.task,
  579. mainFrame = self)
  580. self.goutput = self.notebookpanel.goutput
  581. self.notebookpanel.OnUpdateValues = self.updateValuesHook
  582. guisizer.Add (item=self.notebookpanel, proportion=1, flag=wx.EXPAND)
  583. # status bar
  584. status_text = _("Enter parameters for '") + self.task.name + "'"
  585. try:
  586. self.task.getCmd()
  587. self.updateValuesHook()
  588. except ValueError:
  589. self.SetStatusText( status_text )
  590. # buttons
  591. btnsizer = wx.BoxSizer(orient=wx.HORIZONTAL)
  592. # cancel
  593. self.btn_cancel = wx.Button(parent=self.panel, id=wx.ID_CLOSE)
  594. self.btn_cancel.SetToolTipString(_("Close this window without executing the command (Ctrl+Q)"))
  595. btnsizer.Add(item=self.btn_cancel, proportion=0, flag=wx.ALL | wx.ALIGN_CENTER, border=10)
  596. self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  597. # help
  598. self.btn_help = wx.Button(parent=self.panel, id=wx.ID_HELP)
  599. self.btn_help.SetToolTipString(_("Show manual page of the command (Ctrl+H)"))
  600. self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
  601. if not hasattr(self.notebookpanel, "manual_tab_id"):
  602. self.btn_help.Hide()
  603. if self.get_dcmd is not None: # A callback has been set up
  604. btn_apply = wx.Button(parent=self.panel, id=wx.ID_APPLY)
  605. btn_ok = wx.Button(parent=self.panel, id=wx.ID_OK)
  606. btn_ok.SetDefault()
  607. btnsizer.Add(item=btn_apply, proportion=0,
  608. flag=wx.ALL | wx.ALIGN_CENTER,
  609. border=10)
  610. btnsizer.Add(item=btn_ok, proportion=0,
  611. flag=wx.ALL | wx.ALIGN_CENTER,
  612. border=10)
  613. btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
  614. btn_ok.Bind(wx.EVT_BUTTON, self.OnOK)
  615. else: # We're standalone
  616. # run
  617. self.btn_run = wx.Button(parent=self.panel, id=wx.ID_OK, label= _("&Run"))
  618. self.btn_run.SetToolTipString(_("Run the command (Ctrl+R)"))
  619. self.btn_run.SetDefault()
  620. # abort
  621. ### self.btn_abort = wx.Button(parent=self.panel, id=wx.ID_STOP)
  622. ### self.btn_abort.SetToolTipString(_("Abort the running command"))
  623. ### self.btn_abort.Enable(False)
  624. # copy
  625. self.btn_clipboard = wx.Button(parent=self.panel, id=wx.ID_COPY)
  626. self.btn_clipboard.SetToolTipString(_("Copy the current command string to the clipboard (Ctrl+C)"))
  627. ### btnsizer.Add(item=self.btn_abort, proportion=0,
  628. ### flag=wx.ALL | wx.ALIGN_CENTER,
  629. ### border=10)
  630. btnsizer.Add(item=self.btn_run, proportion=0,
  631. flag=wx.ALL | wx.ALIGN_CENTER,
  632. border=10)
  633. btnsizer.Add(item=self.btn_clipboard, proportion=0,
  634. flag=wx.ALL | wx.ALIGN_CENTER,
  635. border=10)
  636. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  637. ### self.btn_abort.Bind(wx.EVT_BUTTON, self.OnAbort)
  638. self.btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
  639. # add help button
  640. btnsizer.Add(item=self.btn_help, proportion=0, flag=wx.ALL | wx.ALIGN_CENTER, border=10)
  641. guisizer.Add(item=btnsizer, proportion=0, flag=wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT,
  642. border = 30)
  643. if self.parent and not self.modeler:
  644. addLayer = False
  645. for p in self.task.params:
  646. if p.get('age', 'old') == 'new' and \
  647. p.get('prompt', '') in ('raster', 'vector', '3d-raster'):
  648. addLayer = True
  649. if addLayer:
  650. # add newly created map into layer tree
  651. self.addbox = wx.CheckBox(parent=self.panel,
  652. label=_('Add created map(s) into layer tree'), style = wx.NO_BORDER)
  653. self.addbox.SetValue(UserSettings.Get(group='cmd', key='addNewLayer', subkey='enabled'))
  654. guisizer.Add(item=self.addbox, proportion=0,
  655. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  656. border=5)
  657. if self.get_dcmd is None:
  658. # close dialog when command is terminated
  659. self.closebox = wx.CheckBox(parent=self.panel,
  660. label=_('Close dialog on finish'), style = wx.NO_BORDER)
  661. self.closebox.SetValue(UserSettings.Get(group='cmd', key='closeDlg', subkey='enabled'))
  662. guisizer.Add(item=self.closebox, proportion=0,
  663. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  664. border=5)
  665. self.Bind(wx.EVT_CLOSE, self.OnCancel)
  666. self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
  667. #constrained_size = self.notebookpanel.GetSize()
  668. # 80 takes the tabbar into account
  669. #self.notebookpanel.SetSize( (constrained_size[0] + 25, constrained_size[1]) )
  670. #self.notebookpanel.Layout()
  671. #
  672. # do layout
  673. #
  674. guisizer.SetSizeHints(self.panel)
  675. # called automatically by SetSizer()
  676. self.panel.SetAutoLayout(True)
  677. self.panel.SetSizerAndFit(guisizer)
  678. sizeFrame = self.GetBestSize()
  679. self.SetMinSize(sizeFrame)
  680. self.SetSize((sizeFrame[0], sizeFrame[1] +
  681. self.notebookpanel.constrained_size[1] -
  682. self.notebookpanel.panelMinHeight))
  683. # thread to update dialog
  684. # create queues
  685. self.requestQ = Queue.Queue()
  686. self.resultQ = Queue.Queue()
  687. self.updateThread = UpdateQThread(self.notebookpanel, self.requestQ, self.resultQ)
  688. self.Layout()
  689. #keep initial window size limited for small screens
  690. width, height = self.GetSizeTuple()
  691. if width > 640: width = 640
  692. if height > 480: height = 480
  693. self.SetSize((width, height))
  694. # fix goutput's pane size
  695. if self.goutput:
  696. self.goutput.SetSashPosition(int(self.GetSize()[1] * .75))
  697. def updateValuesHook(self, event = None):
  698. """!Update status bar data"""
  699. self.SetStatusText(' '.join(self.notebookpanel.createCmd(ignoreErrors = True)))
  700. if event:
  701. event.Skip()
  702. def OnKeyUp(self, event):
  703. """!Key released (check hot-keys)"""
  704. try:
  705. kc = chr(event.GetKeyCode())
  706. except ValueError:
  707. event.Skip()
  708. return
  709. if not event.ControlDown():
  710. event.Skip()
  711. return
  712. if kc == 'Q':
  713. self.OnCancel(None)
  714. elif kc == 'S':
  715. self.OnAbort(None)
  716. elif kc == 'H':
  717. self.OnHelp(None)
  718. elif kc == 'R':
  719. self.OnRun(None)
  720. elif kc == 'C':
  721. self.OnCopy(None)
  722. event.Skip()
  723. def OnOK(self, event):
  724. """!OK button pressed"""
  725. cmd = self.OnApply(event)
  726. if cmd is not None and self.get_dcmd is not None:
  727. self.OnCancel(event)
  728. def OnApply(self, event):
  729. """!Apply the command"""
  730. if self.modeler:
  731. cmd = self.createCmd(ignoreErrors = True)
  732. else:
  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 self.standalone or 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. """!A panel containing a notebook dividing in tabs the different
  817. guisections of the GRASS cmd.
  818. """
  819. def __init__(self, parent, task, id = wx.ID_ANY, mainFrame = None, *args, **kwargs):
  820. if mainFrame:
  821. self.parent = mainFrame
  822. else:
  823. self.parent = parent
  824. self.task = task
  825. wx.Panel.__init__(self, parent, id = id, *args, **kwargs)
  826. # Determine tab layout
  827. sections = []
  828. is_section = {}
  829. not_hidden = [ p for p in self.task.params + self.task.flags if not p.get( 'hidden','no' ) == 'yes' ]
  830. self.label_id = [] # wrap titles on resize
  831. self.Bind(wx.EVT_SIZE, self.OnSize)
  832. for task in not_hidden:
  833. if task.get( 'required','no' ) == 'yes':
  834. # All required go into Main, even if they had defined another guisection
  835. task['guisection'] = _( 'Required' )
  836. if task.get( 'guisection','' ) == '':
  837. # Undefined guisections end up into Options
  838. task['guisection'] = _( 'Optional' )
  839. if not is_section.has_key(task['guisection']):
  840. # We do it like this to keep the original order, except for Main which goes first
  841. is_section[task['guisection']] = 1
  842. sections.append( task['guisection'] )
  843. else:
  844. is_section[ task['guisection'] ] += 1
  845. del is_section
  846. # 'Required' tab goes first, 'Optional' as the last one
  847. for (newidx,content) in [ (0,_( 'Required' )), (len(sections)-1,_('Optional')) ]:
  848. if content in sections:
  849. idx = sections.index( content )
  850. sections[idx:idx+1] = []
  851. sections[newidx:newidx] = [content]
  852. panelsizer = wx.BoxSizer(orient=wx.VERTICAL)
  853. # Build notebook
  854. nbStyle = globalvar.FNPageStyle
  855. self.notebook = FN.FlatNotebook( self, id=wx.ID_ANY, style=nbStyle)
  856. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  857. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  858. tab = {}
  859. tabsizer = {}
  860. for section in sections:
  861. tab[section] = wx.ScrolledWindow( parent=self.notebook )
  862. tab[section].SetScrollRate(10,10)
  863. tabsizer[section] = wx.BoxSizer(orient=wx.VERTICAL)
  864. self.notebook.AddPage( tab[section], text=section )
  865. # are we running from command line?
  866. ### add 'command output' tab regardless standalone dialog
  867. if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
  868. self.goutput = goutput.GMConsole(parent=self, margin=False,
  869. pageid=self.notebook.GetPageCount())
  870. self.goutputId = self.notebook.GetPageCount()
  871. self.outpage = self.notebook.AddPage(self.goutput, text=_("Command output") )
  872. else:
  873. self.goutput = None
  874. self.goutputId = -1
  875. self.manual_tab = HelpPanel(parent = self, grass_command = self.task.name)
  876. if not self.manual_tab.IsFile():
  877. self.manual_tab.Hide()
  878. else:
  879. self.notebook.AddPage(self.manual_tab, text=_("Manual"))
  880. self.manual_tab_id = self.notebook.GetPageCount() - 1
  881. self.notebook.SetSelection(0)
  882. panelsizer.Add(item=self.notebook, proportion=1, flag=wx.EXPAND )
  883. #
  884. # flags
  885. #
  886. text_style = wx.FONTWEIGHT_NORMAL
  887. visible_flags = [ f for f in self.task.flags if not f.get( 'hidden', 'no' ) == 'yes' ]
  888. for f in visible_flags:
  889. which_sizer = tabsizer[ f['guisection'] ]
  890. which_panel = tab[ f['guisection'] ]
  891. # if label is given: description -> tooltip
  892. if f.get('label','') != '':
  893. title = text_beautify( f['label'])
  894. tooltip = text_beautify ( f['description'], width=-1)
  895. else:
  896. title = text_beautify( f['description'] )
  897. tooltip = None
  898. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  899. rtitle_txt = wx.StaticText(parent=which_panel,
  900. label = '(' + f['name'] + ')')
  901. chk = wx.CheckBox(parent=which_panel, label = title, style = wx.NO_BORDER)
  902. self.label_id.append(chk.GetId())
  903. if tooltip:
  904. chk.SetToolTipString(tooltip)
  905. chk.SetValue(f.get('value', False))
  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 self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  915. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  916. label = _("Parameterized in model"))
  917. parChk.SetName('ModelParam')
  918. parChk.SetValue(f.get('parameterized', False))
  919. if f.has_key('wxId'):
  920. f['wxId'].append(parChk.GetId())
  921. else:
  922. f['wxId'] = [ parChk.GetId() ]
  923. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  924. which_sizer.Add(item = parChk, proportion = 0,
  925. flag = wx.LEFT, border = 20)
  926. if f['name'] in ('verbose', 'quiet'):
  927. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  928. vq = UserSettings.Get(group='cmd', key='verbosity', subkey='selection')
  929. if f['name'] == vq:
  930. chk.SetValue(True)
  931. f['value'] = True
  932. elif f['name'] == 'overwrite' and not f.has_key('value'):
  933. chk.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
  934. f['value'] = UserSettings.Get(group='cmd', key='overwrite', subkey='enabled')
  935. #
  936. # parameters
  937. #
  938. visible_params = [ p for p in self.task.params if not p.get( 'hidden', 'no' ) == 'yes' ]
  939. try:
  940. first_param = visible_params[0]
  941. except IndexError:
  942. first_param = None
  943. for p in visible_params:
  944. which_sizer = tabsizer[ p['guisection'] ]
  945. which_panel = tab[ p['guisection'] ]
  946. # if label is given -> label and description -> tooltip
  947. # otherwise description -> lavel
  948. if p.get('label','') != '':
  949. title = text_beautify( p['label'] )
  950. tooltip = text_beautify ( p['description'], width = -1)
  951. else:
  952. title = text_beautify( p['description'] )
  953. tooltip = None
  954. txt = None
  955. # text style (required -> bold)
  956. if p.get('required','no') == 'no':
  957. text_style = wx.FONTWEIGHT_NORMAL
  958. else:
  959. text_style = wx.FONTWEIGHT_BOLD
  960. # title sizer (description, name, type)
  961. if (len(p.get('values', []) ) > 0) and \
  962. p.get('multiple', 'no') == 'yes' and \
  963. p.get('gisprompt',False) == False and \
  964. p.get('type', '') == 'string':
  965. title_txt = wx.StaticBox (parent=which_panel, id=wx.ID_ANY)
  966. else:
  967. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  968. title_txt = wx.StaticText(parent=which_panel)
  969. rtitle_txt = wx.StaticText(parent=which_panel,
  970. label = '(' + p['name'] + ', ' + p['type'] + ')')
  971. title_sizer.Add(item=title_txt, proportion=1,
  972. flag=wx.LEFT | wx.TOP | wx.EXPAND, border=5)
  973. title_sizer.Add(item=rtitle_txt, proportion=0,
  974. flag=wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border=5)
  975. which_sizer.Add(item=title_sizer, proportion=0,
  976. flag=wx.EXPAND)
  977. self.label_id.append(title_txt.GetId())
  978. # title expansion
  979. if p.get('multiple','no') == 'yes' and len( p.get('values','') ) == 0:
  980. title = _("[multiple]") + " " + title
  981. if p.get('value','') == '' :
  982. p['value'] = p.get('default','')
  983. if ( len(p.get('values', []) ) > 0):
  984. valuelist = map(str, p.get('values',[]))
  985. valuelist_desc = map(unicode, p.get('values_desc',[]))
  986. if p.get('multiple', 'no') == 'yes' and \
  987. p.get('gisprompt',False) == False and \
  988. p.get('type', '') == 'string':
  989. title_txt.SetLabel(" %s: (%s, %s) " % (title, p['name'], p['type']))
  990. if len(valuelist) > 6:
  991. hSizer=wx.StaticBoxSizer ( box=title_txt, orient=wx.VERTICAL )
  992. else:
  993. hSizer=wx.StaticBoxSizer ( box=title_txt, orient=wx.HORIZONTAL )
  994. isEnabled = {}
  995. # copy default values
  996. if p['value'] == '':
  997. p['value'] = p.get('default', '')
  998. for defval in p.get('value', '').split(','):
  999. isEnabled[ defval ] = 'yes'
  1000. # for multi checkboxes, this is an array of all wx IDs
  1001. # for each individual checkbox
  1002. p[ 'wxId' ] = list()
  1003. idx = 0
  1004. for val in valuelist:
  1005. try:
  1006. label = valuelist_desc[idx]
  1007. except IndexError:
  1008. label = val
  1009. chkbox = wx.CheckBox( parent=which_panel,
  1010. label = text_beautify(label))
  1011. p[ 'wxId' ].append( chkbox.GetId() )
  1012. if isEnabled.has_key(val):
  1013. chkbox.SetValue( True )
  1014. hSizer.Add( item=chkbox, proportion=0,
  1015. flag=wx.ADJUST_MINSIZE | wx.ALL, border=1 )
  1016. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  1017. idx += 1
  1018. which_sizer.Add( item=hSizer, proportion=0,
  1019. flag=wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border=5 )
  1020. elif p.get('gisprompt', False) == False:
  1021. if len(valuelist) == 1: # -> textctrl
  1022. title_txt.SetLabel("%s. %s %s" % (title, _('Valid range'),
  1023. str(valuelist[0]) + ':'))
  1024. if p.get('type', '') == 'integer' and \
  1025. p.get('multiple','no') == 'no':
  1026. # for multiple integers use textctrl instead of spinsctrl
  1027. try:
  1028. minValue, maxValue = map(int, valuelist[0].split('-'))
  1029. except ValueError:
  1030. minValue = -1e6
  1031. maxValue = 1e6
  1032. txt2 = wx.SpinCtrl(parent=which_panel, id=wx.ID_ANY, size=globalvar.DIALOG_SPIN_SIZE,
  1033. min=minValue, max=maxValue)
  1034. txt2.SetName("SpinCtrl")
  1035. style = wx.BOTTOM | wx.LEFT
  1036. else:
  1037. txt2 = wx.TextCtrl(parent=which_panel, value = p.get('default',''))
  1038. txt2.SetName("TextCtrl")
  1039. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  1040. if p.get('value', '') != '':
  1041. # parameter previously set
  1042. if txt2.GetName() == "SpinCtrl":
  1043. txt2.SetValue(int(p['value']))
  1044. else:
  1045. txt2.SetValue(p['value'])
  1046. which_sizer.Add(item=txt2, proportion=0,
  1047. flag=style, border=5)
  1048. p['wxId'] = [ txt2.GetId(), ]
  1049. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  1050. else:
  1051. # list of values (combo)
  1052. title_txt.SetLabel(title + ':')
  1053. cb = wx.ComboBox(parent = which_panel, id = wx.ID_ANY, value = p.get('default',''),
  1054. size = globalvar.DIALOG_COMBOBOX_SIZE,
  1055. choices = valuelist, style = wx.CB_DROPDOWN)
  1056. if p.get('value', '') != '':
  1057. cb.SetValue(p['value']) # parameter previously set
  1058. which_sizer.Add(item = cb, proportion = 0,
  1059. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1060. p['wxId'] = [cb.GetId(),]
  1061. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1062. cb.Bind(wx.EVT_TEXT, self.OnSetValue)
  1063. # text entry
  1064. if (p.get('type','string') in ('string','integer','float')
  1065. and len(p.get('values',[])) == 0
  1066. and p.get('gisprompt',False) == False
  1067. and p.get('prompt','') != 'color'):
  1068. title_txt.SetLabel(title + ':' )
  1069. if p.get('multiple','yes') == 'yes' or \
  1070. p.get('type', 'string') == 'string' or \
  1071. len(p.get('key_desc', [])) > 1:
  1072. txt3 = wx.TextCtrl(parent=which_panel, value = p.get('default',''))
  1073. if p.get('value','') != '':
  1074. txt3.SetValue(str(p['value'])) # parameter previously set
  1075. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  1076. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  1077. else:
  1078. minValue = -1e9
  1079. maxValue = 1e9
  1080. if p.get('type', '') == 'integer':
  1081. txt3 = wx.SpinCtrl(parent=which_panel, value=p.get('default',''),
  1082. size=globalvar.DIALOG_SPIN_SIZE,
  1083. min=minValue, max=maxValue)
  1084. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1085. if p.get('value', '') != '':
  1086. txt3.SetValue(int(p['value'])) # parameter previously set
  1087. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1088. else:
  1089. txt3 = wx.TextCtrl(parent=which_panel, value = p.get('default',''),
  1090. validator = FloatValidator())
  1091. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  1092. if p.get('value', '') != '':
  1093. txt3.SetValue(str(p['value'])) # parameter previously set
  1094. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  1095. which_sizer.Add(item=txt3, proportion=0,
  1096. flag=style, border=5)
  1097. p['wxId'] = [ txt3.GetId(), ]
  1098. #
  1099. # element selection tree combobox (maps, icons, regions, etc.)
  1100. #
  1101. if p.get('gisprompt', False) == True:
  1102. title_txt.SetLabel(title + ':')
  1103. # GIS element entry
  1104. if p.get('prompt','') not in ('color',
  1105. 'color_none',
  1106. 'subgroup',
  1107. 'dbdriver',
  1108. 'dbname',
  1109. 'dbtable',
  1110. 'dbcolumn',
  1111. 'layer',
  1112. 'layer_all') and \
  1113. p.get('element', '') != 'file':
  1114. if p.get('multiple', 'no') == 'yes':
  1115. multiple = True
  1116. else:
  1117. multiple = False
  1118. if p.get('age', '') == 'new':
  1119. mapsets = [grass.gisenv()['MAPSET'],]
  1120. else:
  1121. mapsets = None
  1122. selection = gselect.Select(parent=which_panel, id=wx.ID_ANY,
  1123. size=globalvar.DIALOG_GSELECT_SIZE,
  1124. type=p.get('element', ''),
  1125. multiple=multiple, mapsets=mapsets)
  1126. if p.get('value','') != '':
  1127. selection.SetValue(p['value']) # parameter previously set
  1128. # A select.Select is a combobox with two children: a textctl and a popupwindow;
  1129. # we target the textctl here
  1130. p['wxId'] = [selection.GetChildren()[0].GetId(), ]
  1131. selection.GetChildren()[0].Bind(wx.EVT_TEXT, self.OnSetValue)
  1132. if p.get('prompt', '') == 'vector':
  1133. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1134. if p.get('age', '') == 'old':
  1135. # OGR supported (read-only)
  1136. self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  1137. self.hsizer.Add(item=selection,
  1138. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1139. border=5)
  1140. # format (native / ogr)
  1141. rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  1142. label = " %s " % _("Format"),
  1143. style = wx.RA_SPECIFY_ROWS,
  1144. choices = [_("Native / Linked OGR"), _("Direct OGR")])
  1145. if p.get('value', '').lower().rfind('@ogr') > -1:
  1146. rbox.SetSelection(1)
  1147. rbox.SetName('VectorFormat')
  1148. rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  1149. self.hsizer.Add(item=rbox,
  1150. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1151. wx.RIGHT | wx.ALIGN_TOP,
  1152. border=5)
  1153. ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  1154. default = 'dir',
  1155. exclude = ['file'])
  1156. self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  1157. self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  1158. ogrSelection.SetName('OgrSelect')
  1159. ogrSelection.Hide()
  1160. which_sizer.Add(item = self.hsizer, proportion = 0)
  1161. p['wxId'].append(rbox.GetId())
  1162. p['wxId'].append(ogrSelection.GetId())
  1163. for win in ogrSelection.GetDsnWin():
  1164. p['wxId'].append(win.GetId())
  1165. else:
  1166. which_sizer.Add(item=selection, proportion=0,
  1167. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1168. border=5)
  1169. elif p.get('prompt', '') == 'group':
  1170. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1171. which_sizer.Add(item=selection, proportion=0,
  1172. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1173. border=5)
  1174. else:
  1175. which_sizer.Add(item=selection, proportion=0,
  1176. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1177. border=5)
  1178. # subgroup
  1179. elif p.get('prompt', '') == 'subgroup':
  1180. selection = gselect.SubGroupSelect(parent = which_panel)
  1181. p['wxId'] = [ selection.GetId() ]
  1182. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1183. which_sizer.Add(item = selection, proportion = 0,
  1184. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1185. border = 5)
  1186. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1187. elif p.get('prompt', '') in ('dbdriver',
  1188. 'dbname',
  1189. 'dbtable',
  1190. 'dbcolumn',
  1191. 'layer',
  1192. 'layer_all'):
  1193. if p.get('multiple', 'no') == 'yes':
  1194. win = wx.TextCtrl(parent=which_panel, value = p.get('default',''),
  1195. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  1196. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1197. else:
  1198. if p.get('prompt', '') in ('layer',
  1199. 'layer_all'):
  1200. if p.get('prompt', '') == 'layer_all':
  1201. all = True
  1202. else:
  1203. all = False
  1204. win = wx.BoxSizer(wx.HORIZONTAL)
  1205. if p.get('age', 'old_layer') == 'old_layer':
  1206. win1 = gselect.LayerSelect(parent=which_panel,
  1207. all=all,
  1208. default=p['default'])
  1209. win1.Bind(wx.EVT_CHOICE, self.OnUpdateSelection)
  1210. win1.Bind(wx.EVT_CHOICE, self.OnSetValue)
  1211. else:
  1212. win1 = wx.SpinCtrl(parent=which_panel, id=wx.ID_ANY,
  1213. min=1, max=100, initial=int(p['default']))
  1214. win1.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1215. win2 = gselect.LayerNameSelect(parent = which_panel)
  1216. if p.get('value','') != '':
  1217. win2.SetItems([p['value']])
  1218. win2.SetSelection(0)
  1219. win2.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1220. p['wxId'] = [ win1.GetId(), win2.GetId() ]
  1221. win.Add(item = win1, proportion = 0)
  1222. win.Add(item = win2, proportion = 0,
  1223. flag = wx.LEFT | wx.ALIGN_CENTER_VERTICAL,
  1224. border = 5)
  1225. elif p.get('prompt', '') == 'dbdriver':
  1226. win = gselect.DriverSelect(parent=which_panel,
  1227. choices=p['values'],
  1228. value=p['default'])
  1229. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1230. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1231. elif p.get('prompt', '') == 'dbname':
  1232. win = gselect.DatabaseSelect(parent=which_panel,
  1233. value=p['default'])
  1234. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1235. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1236. elif p.get('prompt', '') == 'dbtable':
  1237. if p.get('age', 'old_dbtable') == 'old_dbtable':
  1238. win = gselect.TableSelect(parent=which_panel)
  1239. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1240. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1241. else:
  1242. win = wx.TextCtrl(parent=which_panel, value = p.get('default',''),
  1243. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  1244. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1245. elif p.get('prompt', '') == 'dbcolumn':
  1246. win = gselect.ColumnSelect(parent = which_panel,
  1247. value = p.get('default', ''),
  1248. param = p)
  1249. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1250. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1251. try:
  1252. p['wxId'] = [ win.GetId(), ]
  1253. except AttributeError:
  1254. pass
  1255. which_sizer.Add(item=win, proportion=0,
  1256. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  1257. # color entry
  1258. elif p.get('prompt', '') in ('color',
  1259. 'color_none'):
  1260. default_color = (200,200,200)
  1261. label_color = _("Select Color")
  1262. if p.get('default','') != '':
  1263. default_color, label_color = color_resolve( p['default'] )
  1264. if p.get('value','') != '': # parameter previously set
  1265. default_color, label_color = color_resolve( p['value'] )
  1266. if p.get('prompt', '') == 'color_none':
  1267. this_sizer = wx.BoxSizer(orient=wx.HORIZONTAL )
  1268. else:
  1269. this_sizer = which_sizer
  1270. btn_colour = csel.ColourSelect(parent=which_panel, id=wx.ID_ANY,
  1271. label=label_color, colour=default_color,
  1272. pos=wx.DefaultPosition, size=(150,-1) )
  1273. this_sizer.Add(item=btn_colour, proportion=0,
  1274. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  1275. # For color selectors, this is a two-member array, holding the IDs of
  1276. # the selector proper and either a "transparent" button or None
  1277. p['wxId'] = [btn_colour.GetId(),]
  1278. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange )
  1279. if p.get('prompt', '') == 'color_none':
  1280. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent") )
  1281. if p.get('value','') != '' and p.get('value',[''])[0] == "none":
  1282. none_check.SetValue(True)
  1283. else:
  1284. none_check.SetValue(False)
  1285. this_sizer.Add(item=none_check, proportion=0,
  1286. flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border=5)
  1287. which_sizer.Add( this_sizer )
  1288. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1289. p['wxId'].append( none_check.GetId() )
  1290. else:
  1291. p['wxId'].append(None)
  1292. # file selector
  1293. elif p.get('prompt','') != 'color' and p.get('element', '') == 'file':
  1294. fbb = filebrowse.FileBrowseButton(parent=which_panel, id=wx.ID_ANY, fileMask = '*',
  1295. size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
  1296. dialogTitle=_('Choose %s') % \
  1297. p.get('description',_('File')),
  1298. buttonText=_('Browse'),
  1299. startDirectory=os.getcwd(), fileMode=0,
  1300. changeCallback=self.OnSetValue)
  1301. if p.get('value','') != '':
  1302. fbb.SetValue(p['value']) # parameter previously set
  1303. which_sizer.Add(item=fbb, proportion=0,
  1304. flag=wx.EXPAND | wx.RIGHT, border=5)
  1305. # A file browse button is a combobox with two children:
  1306. # a textctl and a button;
  1307. # we have to target the button here
  1308. p['wxId'] = [ fbb.GetChildren()[1].GetId(), ]
  1309. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  1310. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1311. label = _("Parameterized in model"))
  1312. parChk.SetName('ModelParam')
  1313. parChk.SetValue(p.get('parameterized', False))
  1314. if p.has_key('wxId'):
  1315. p['wxId'].append(parChk.GetId())
  1316. else:
  1317. p['wxId'] = [ parChk.GetId() ]
  1318. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1319. which_sizer.Add(item = parChk, proportion = 0,
  1320. flag = wx.LEFT, border = 20)
  1321. if title_txt is not None:
  1322. # create tooltip if given
  1323. if len(p['values_desc']) > 0:
  1324. if tooltip:
  1325. tooltip += 2 * os.linesep
  1326. else:
  1327. tooltip = ''
  1328. if len(p['values']) == len(p['values_desc']):
  1329. for i in range(len(p['values'])):
  1330. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1331. tooltip.strip(os.linesep)
  1332. if tooltip:
  1333. title_txt.SetToolTipString(tooltip)
  1334. if p == first_param:
  1335. if len(p['wxId']) > 0:
  1336. self.FindWindowById(p['wxId'][0]).SetFocus()
  1337. #
  1338. # set widget relations for OnUpdateSelection
  1339. #
  1340. pMap = None
  1341. pLayer = []
  1342. pDriver = None
  1343. pDatabase = None
  1344. pTable = None
  1345. pColumn = []
  1346. pGroup = None
  1347. pSubGroup = None
  1348. for p in self.task.params:
  1349. if p.get('gisprompt', False) == False:
  1350. continue
  1351. guidep = p.get('guidependency', '')
  1352. if guidep:
  1353. # fixed options dependency defined
  1354. options = guidep.split(',')
  1355. for opt in options:
  1356. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1357. if id:
  1358. if not p.has_key('wxId-bind'):
  1359. p['wxId-bind'] = list()
  1360. p['wxId-bind'] += pOpt['wxId']
  1361. continue
  1362. prompt = p.get('element', '')
  1363. if prompt == 'vector':
  1364. name = p.get('name', '')
  1365. if name in ('map', 'input'):
  1366. pMap = p
  1367. elif prompt == 'layer':
  1368. pLayer.append(p)
  1369. elif prompt == 'dbcolumn':
  1370. pColumn.append(p)
  1371. elif prompt == 'dbdriver':
  1372. pDriver = p
  1373. elif prompt == 'dbname':
  1374. pDatabase = p
  1375. elif prompt == 'dbtable':
  1376. pTable = p
  1377. elif prompt == 'group':
  1378. pGroup = p
  1379. elif prompt == 'subgroup':
  1380. pSubGroup = p
  1381. # collect ids
  1382. pColumnIds = []
  1383. for p in pColumn:
  1384. pColumnIds += p['wxId']
  1385. pLayerIds = []
  1386. for p in pLayer:
  1387. pLayerIds += p['wxId']
  1388. # set wxId-bindings
  1389. if pMap:
  1390. pMap['wxId-bind'] = copy.copy(pColumnIds)
  1391. if pLayer:
  1392. pMap['wxId-bind'] += pLayerIds
  1393. if pLayer:
  1394. for p in pLayer:
  1395. p['wxId-bind'] = copy.copy(pColumnIds)
  1396. if pDriver and pTable:
  1397. pDriver['wxId-bind'] = pTable['wxId']
  1398. if pDatabase and pTable:
  1399. pDatabase['wxId-bind'] = pTable['wxId']
  1400. if pTable and pColumnIds:
  1401. pTable['wxId-bind'] = pColumnIds
  1402. if pGroup and pSubGroup:
  1403. pGroup['wxId-bind'] = pSubGroup['wxId']
  1404. #
  1405. # determine panel size
  1406. #
  1407. maxsizes = (0,0)
  1408. for section in sections:
  1409. # tabsizer[section].SetSizeHints( tab[section] )
  1410. #tab[section].SetAutoLayout(True)
  1411. tab[section].SetSizer( tabsizer[section] )
  1412. tabsizer[section].Fit( tab[section] )
  1413. tab[section].Layout()
  1414. minsecsizes = tabsizer[section].GetSize()
  1415. maxsizes = map( lambda x: max( maxsizes[x], minsecsizes[x] ), (0,1) )
  1416. # TODO: be less arbitrary with these 600
  1417. self.panelMinHeight = 100
  1418. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1419. for section in sections:
  1420. tab[section].SetMinSize( (self.constrained_size[0], self.panelMinHeight) )
  1421. # tab[section].SetMinSize( constrained_size )
  1422. if self.manual_tab.IsLoaded():
  1423. self.manual_tab.SetMinSize( (self.constrained_size[0], self.panelMinHeight) )
  1424. self.SetSizer( panelsizer )
  1425. panelsizer.Fit(self.notebook)
  1426. self.hasMain = tab.has_key( _('Required') ) # publish, to enclosing Frame for instance
  1427. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1428. def OnVectorFormat(self, event):
  1429. """!Change vector format (native / ogr)"""
  1430. sel = event.GetSelection()
  1431. idEvent = event.GetId()
  1432. p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
  1433. if not p:
  1434. return # should not happen
  1435. # detect windows
  1436. winNative = None
  1437. winOgr = None
  1438. for id in p['wxId']:
  1439. if id == idEvent:
  1440. continue
  1441. name = self.FindWindowById(id).GetName()
  1442. if name == 'Select':
  1443. winNative = self.FindWindowById(id + 1) # fix the mystery (also in nviz_tools.py)
  1444. elif name == 'OgrSelect':
  1445. winOgr = self.FindWindowById(id)
  1446. # enable / disable widgets & update values
  1447. rbox = self.FindWindowByName('VectorFormat')
  1448. self.hsizer.Remove(rbox)
  1449. if sel == 0: # -> native
  1450. winOgr.Hide()
  1451. self.hsizer.Remove(winOgr)
  1452. self.hsizer.Add(item=winNative,
  1453. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1454. border=5)
  1455. winNative.Show()
  1456. p['value'] = winNative.GetValue()
  1457. elif sel == 1: # -> OGR
  1458. sizer = wx.BoxSizer(wx.VERTICAL)
  1459. winNative.Hide()
  1460. self.hsizer.Remove(winNative)
  1461. sizer.Add(item=winOgr)
  1462. winOgr.Show()
  1463. p['value'] = winOgr.GetDsn()
  1464. self.hsizer.Add(item=sizer,
  1465. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1466. border=5)
  1467. self.hsizer.Add(item=rbox,
  1468. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1469. wx.RIGHT | wx.ALIGN_TOP,
  1470. border=5)
  1471. self.hsizer.Layout()
  1472. self.Layout()
  1473. self.OnUpdateValues()
  1474. self.OnUpdateSelection(event)
  1475. def OnUpdateDialog(self, event):
  1476. for fn, kwargs in event.data.iteritems():
  1477. fn(**kwargs)
  1478. self.parent.updateValuesHook()
  1479. def OnVerbosity(self, event):
  1480. """!Verbosity level changed"""
  1481. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  1482. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  1483. if event.IsChecked():
  1484. if event.GetId() == verbose.GetId():
  1485. if quiet.IsChecked():
  1486. quiet.SetValue(False)
  1487. self.task.get_flag('quiet')['value'] = False
  1488. else:
  1489. if verbose.IsChecked():
  1490. verbose.SetValue(False)
  1491. self.task.get_flag('verbose')['value'] = False
  1492. event.Skip()
  1493. def OnPageChange(self, event):
  1494. if not event:
  1495. sel = self.notebook.GetSelection()
  1496. else:
  1497. sel = event.GetSelection()
  1498. if hasattr(self, "manual_tab_id") and \
  1499. sel == self.manual_tab_id:
  1500. # calling LoadPage() is strangely time-consuming (only first call)
  1501. # FIXME: move to helpPage.__init__()
  1502. if not self.manual_tab.IsLoaded():
  1503. wx.Yield()
  1504. self.manual_tab.LoadPage()
  1505. self.Layout()
  1506. def OnColorChange( self, event ):
  1507. myId = event.GetId()
  1508. for p in self.task.params:
  1509. if 'wxId' in p and myId in p['wxId']:
  1510. has_button = p['wxId'][1] is not None
  1511. if has_button and wx.FindWindowById( p['wxId'][1] ).GetValue() == True:
  1512. p[ 'value' ] = 'none'
  1513. else:
  1514. colorchooser = wx.FindWindowById( p['wxId'][0] )
  1515. new_color = colorchooser.GetValue()[:]
  1516. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1517. # under wx2.8.1
  1518. new_label = rgb2str.get( new_color, ':'.join(map(str,new_color)) )
  1519. colorchooser.SetLabel( new_label )
  1520. colorchooser.SetColour( new_color )
  1521. colorchooser.Refresh()
  1522. p[ 'value' ] = colorchooser.GetLabel()
  1523. self.OnUpdateValues()
  1524. def OnUpdateValues(self, event = None):
  1525. """!If we were part of a richer interface, report back the
  1526. current command being built.
  1527. This method should be set by the parent of this panel if
  1528. needed. It's a hook, actually. Beware of what is 'self' in
  1529. the method def, though. It will be called with no arguments.
  1530. """
  1531. pass
  1532. def OnCheckBoxMulti(self, event):
  1533. """
  1534. Fill the values as a ','-separated string according to current status of the checkboxes.
  1535. """
  1536. me = event.GetId()
  1537. theParam = None
  1538. for p in self.task.params:
  1539. if 'wxId' in p and me in p['wxId']:
  1540. theParam = p
  1541. myIndex = p['wxId'].index( me )
  1542. # Unpack current value list
  1543. currentValues = {}
  1544. for isThere in theParam.get('value', '').split(','):
  1545. currentValues[isThere] = 1
  1546. theValue = theParam['values'][myIndex]
  1547. if event.Checked():
  1548. currentValues[ theValue ] = 1
  1549. else:
  1550. del currentValues[ theValue ]
  1551. # Keep the original order, so that some defaults may be recovered
  1552. currentValueList = []
  1553. for v in theParam['values']:
  1554. if currentValues.has_key(v):
  1555. currentValueList.append( v )
  1556. # Pack it back
  1557. theParam['value'] = ','.join( currentValueList )
  1558. self.OnUpdateValues()
  1559. def OnSetValue(self, event):
  1560. """!Retrieve the widget value and set the task value field
  1561. accordingly.
  1562. Use for widgets that have a proper GetValue() method, i.e. not
  1563. for selectors.
  1564. """
  1565. myId = event.GetId()
  1566. me = wx.FindWindowById(myId)
  1567. name = me.GetName()
  1568. for porf in self.task.params + self.task.flags:
  1569. if not porf.has_key('wxId'):
  1570. continue
  1571. found = False
  1572. for id in porf['wxId']:
  1573. if id == myId:
  1574. found = True
  1575. break
  1576. if found:
  1577. if name in ('LayerSelect', 'DriverSelect', 'TableSelect'):
  1578. porf['value'] = me.GetStringSelection()
  1579. elif name == 'GdalSelect':
  1580. porf['value'] = event.dsn
  1581. elif name == 'ModelParam':
  1582. porf['parameterized'] = me.IsChecked()
  1583. else:
  1584. porf['value'] = me.GetValue()
  1585. self.OnUpdateValues(event)
  1586. event.Skip()
  1587. def OnUpdateSelection(self, event):
  1588. """!Update dialog (layers, tables, columns, etc.)
  1589. """
  1590. if event:
  1591. self.parent.updateThread.Update(UpdateDialog,
  1592. self,
  1593. event,
  1594. event.GetId(),
  1595. self.task)
  1596. else:
  1597. self.parent.updateThread.Update(UpdateDialog,
  1598. self,
  1599. None,
  1600. None,
  1601. self.task)
  1602. def createCmd(self, ignoreErrors = False):
  1603. """!Produce a command line string (list) or feeding into GRASS.
  1604. If ignoreErrors==True then it will return whatever has been
  1605. built so far, even though it would not be a correct command
  1606. for GRASS.
  1607. """
  1608. try:
  1609. cmd = self.task.getCmd(ignoreErrors=ignoreErrors)
  1610. except ValueError, err:
  1611. dlg = wx.MessageDialog(parent=self,
  1612. message=unicode(err),
  1613. caption=_("Error in %s") % self.task.name,
  1614. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1615. dlg.ShowModal()
  1616. dlg.Destroy()
  1617. cmd = None
  1618. return cmd
  1619. def OnSize(self, event):
  1620. width = event.GetSize()[0]
  1621. fontsize = self.GetFont().GetPointSize()
  1622. text_width = width / (fontsize - 3)
  1623. if text_width < 70:
  1624. text_width = 70
  1625. for id in self.label_id:
  1626. win = self.FindWindowById(id)
  1627. label = win.GetLabel()
  1628. label_new = '\n'.join(textwrap.wrap(label, text_width ))
  1629. win.SetLabel(label_new)
  1630. event.Skip()
  1631. def getInterfaceDescription(cmd):
  1632. """!Returns the XML description for the GRASS cmd.
  1633. The DTD must be located in $GISBASE/etc/grass-interface.dtd,
  1634. otherwise the parser will not succeed.
  1635. @param cmd command (name of GRASS module)
  1636. """
  1637. cmdout = os.popen(cmd + r' --interface-description', "r").read()
  1638. if not len(cmdout) > 0:
  1639. raise IOError, _("Unable to fetch interface description for command '%s'.") % cmd
  1640. p = re.compile('(grass-interface.dtd)')
  1641. p.search(cmdout)
  1642. cmdout = p.sub(globalvar.ETCDIR + r'/grass-interface.dtd', cmdout)
  1643. return cmdout
  1644. class GrassGUIApp(wx.App):
  1645. """!Stand-alone GRASS command GUI
  1646. """
  1647. def __init__(self, grass_task):
  1648. self.grass_task = grass_task
  1649. wx.App.__init__(self, False)
  1650. def OnInit(self):
  1651. self.mf = mainFrame(parent = None, ID = wx.ID_ANY, task_description = self.grass_task)
  1652. self.mf.CentreOnScreen()
  1653. self.mf.Show(True)
  1654. self.SetTopWindow(self.mf)
  1655. return True
  1656. class GUI:
  1657. """
  1658. Parses GRASS commands when module is imported and used
  1659. from Layer Manager.
  1660. """
  1661. def __init__(self, parent=-1):
  1662. self.parent = parent
  1663. self.grass_task = None
  1664. self.cmd = list()
  1665. def GetCmd(self):
  1666. """Get validated command"""
  1667. return self.cmd
  1668. def ParseInterface(self, cmd, parser = processTask):
  1669. """!Parse interface
  1670. @param cmd command to be parsed (given as list)
  1671. """
  1672. # enc = locale.getdefaultlocale()[1]
  1673. # if enc and enc.lower() not in ("utf8", "utf-8"):
  1674. # tree = etree.fromstring(getInterfaceDescription(cmd[0]).decode(enc).encode("utf-8"))
  1675. # else:
  1676. tree = etree.fromstring(getInterfaceDescription(cmd[0]))
  1677. return processTask(tree).GetTask()
  1678. def ParseCommand(self, cmd, gmpath = None, completed = None, parentframe = None,
  1679. show = True, modal = False, centreOnParent = True):
  1680. """!Parse command
  1681. Note: cmd is given as list
  1682. If command is given with options, return validated cmd list:
  1683. - add key name for first parameter if not given
  1684. - change mapname to mapname@mapset
  1685. """
  1686. start = time.time()
  1687. dcmd_params = {}
  1688. if completed == None:
  1689. get_dcmd = None
  1690. layer = None
  1691. dcmd_params = None
  1692. else:
  1693. get_dcmd = completed[0]
  1694. layer = completed[1]
  1695. if completed[2]:
  1696. dcmd_params.update(completed[2])
  1697. self.parent = parentframe
  1698. # parse the interface decription
  1699. self.grass_task = self.ParseInterface(cmd)
  1700. # if layer parameters previously set, re-insert them into dialog
  1701. if completed is not None:
  1702. if 'params' in dcmd_params:
  1703. self.grass_task.params = dcmd_params['params']
  1704. if 'flags' in dcmd_params:
  1705. self.grass_task.flags = dcmd_params['flags']
  1706. # update parameters if needed && validate command
  1707. if len(cmd) > 1:
  1708. i = 0
  1709. cmd_validated = [cmd[0]]
  1710. for option in cmd[1:]:
  1711. if option[0] == '-': # flag
  1712. if option[1] == '-':
  1713. self.grass_task.set_flag(option[2:], True)
  1714. else:
  1715. self.grass_task.set_flag(option[1], True)
  1716. cmd_validated.append(option)
  1717. else: # parameter
  1718. try:
  1719. key, value = option.split('=', 1)
  1720. except:
  1721. if i == 0: # add key name of first parameter if not given
  1722. key = self.grass_task.firstParam
  1723. value = option
  1724. else:
  1725. raise ValueError, _("Unable to parse command %s") % ' '.join(cmd)
  1726. element = self.grass_task.get_param(key)['element']
  1727. if element in ['cell', 'vector']:
  1728. # mapname -> mapname@mapset
  1729. try:
  1730. name, mapset = value.split('@')
  1731. except ValueError:
  1732. mapset = grass.find_file(value, element)['mapset']
  1733. curr_mapset = grass.gisenv()['MAPSET']
  1734. if mapset and mapset != curr_mapset:
  1735. value = value + '@' + mapset
  1736. self.grass_task.set_param(key, value)
  1737. cmd_validated.append(key + '=' + value)
  1738. i = i + 1
  1739. # update original command list
  1740. cmd = cmd_validated
  1741. if show is not None:
  1742. self.mf = mainFrame(parent=self.parent, ID=wx.ID_ANY,
  1743. task_description=self.grass_task,
  1744. get_dcmd=get_dcmd, layer=layer)
  1745. else:
  1746. self.mf = None
  1747. if get_dcmd is not None:
  1748. # update only propwin reference
  1749. get_dcmd(dcmd=None, layer=layer, params=None,
  1750. propwin=self.mf)
  1751. if show is not None:
  1752. self.mf.notebookpanel.OnUpdateSelection(None)
  1753. if show is True:
  1754. if self.parent and centreOnParent:
  1755. self.mf.CentreOnParent()
  1756. else:
  1757. self.mf.CenterOnScreen()
  1758. self.mf.Show(show)
  1759. self.mf.MakeModal(modal)
  1760. else:
  1761. self.mf.OnApply(None)
  1762. self.cmd = cmd
  1763. return self.grass_task
  1764. def GetCommandInputMapParamKey(self, cmd):
  1765. """!Get parameter key for input raster/vector map
  1766. @param cmd module name
  1767. @return parameter key
  1768. @return None on failure
  1769. """
  1770. # parse the interface decription
  1771. if not self.grass_task:
  1772. tree = etree.fromstring(getInterfaceDescription(cmd))
  1773. self.grass_task = processTask(tree).GetTask()
  1774. for p in self.grass_task.params:
  1775. if p.get('name', '') in ('input', 'map'):
  1776. age = p.get('age', '')
  1777. prompt = p.get('prompt', '')
  1778. element = p.get('element', '')
  1779. if age == 'old' and \
  1780. element in ('cell', 'grid3', 'vector') and \
  1781. prompt in ('raster', '3d-raster', 'vector'):
  1782. return p.get('name', None)
  1783. return None
  1784. class FloatValidator(wx.PyValidator):
  1785. """!Validator for floating-point input"""
  1786. def __init__(self):
  1787. wx.PyValidator.__init__(self)
  1788. self.Bind(wx.EVT_TEXT, self.OnText)
  1789. def Clone(self):
  1790. """!Clone validator"""
  1791. return FloatValidator()
  1792. def Validate(self):
  1793. """Validate input"""
  1794. textCtrl = self.GetWindow()
  1795. text = textCtrl.GetValue()
  1796. if text:
  1797. try:
  1798. float(text)
  1799. except ValueError:
  1800. textCtrl.SetBackgroundColour("grey")
  1801. textCtrl.SetFocus()
  1802. textCtrl.Refresh()
  1803. return False
  1804. sysColor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW)
  1805. textCtrl.SetBackgroundColour(sysColor)
  1806. textCtrl.Refresh()
  1807. return True
  1808. def OnText(self, event):
  1809. """!Do validation"""
  1810. self.Validate()
  1811. event.Skip()
  1812. def TransferToWindow(self):
  1813. return True # Prevent wxDialog from complaining.
  1814. def TransferFromWindow(self):
  1815. return True # Prevent wxDialog from complaining.
  1816. if __name__ == "__main__":
  1817. if len(sys.argv) == 1:
  1818. sys.exit(_("usage: %s <grass command>") % sys.argv[0])
  1819. if sys.argv[1] != 'test':
  1820. q = wx.LogNull()
  1821. cmd = shlex.split(sys.argv[1])
  1822. task = grassTask(cmd[0])
  1823. task.set_options(cmd[1:])
  1824. app = GrassGUIApp(task)
  1825. app.MainLoop()
  1826. else: #Test
  1827. # Test grassTask from within a GRASS session
  1828. if os.getenv("GISBASE") is not None:
  1829. task = grassTask( "d.vect" )
  1830. task.get_param('map')['value'] = "map_name"
  1831. task.get_flag('v')['value'] = True
  1832. task.get_param('layer')['value'] = 1
  1833. task.get_param('bcolor')['value'] = "red"
  1834. assert ' '.join( task.getCmd() ) == "d.vect -v map=map_name layer=1 bcolor=red"
  1835. # Test interface building with handmade grassTask,
  1836. # possibly outside of a GRASS session.
  1837. task = grassTask()
  1838. task.name = "TestTask"
  1839. task.description = "This is an artificial grassTask() object intended for testing purposes."
  1840. task.keywords = ["grass","test","task"]
  1841. task.params = [
  1842. {
  1843. "name" : "text",
  1844. "description" : "Descriptions go into tooltips if labels are present, like this one",
  1845. "label" : "Enter some text",
  1846. },{
  1847. "name" : "hidden_text",
  1848. "description" : "This text should not appear in the form",
  1849. "hidden" : "yes"
  1850. },{
  1851. "name" : "text_default",
  1852. "description" : "Enter text to override the default",
  1853. "default" : "default text"
  1854. },{
  1855. "name" : "text_prefilled",
  1856. "description" : "You should see a friendly welcome message here",
  1857. "value" : "hello, world"
  1858. },{
  1859. "name" : "plain_color",
  1860. "description" : "This is a plain color, and it is a compulsory parameter",
  1861. "required" : "yes",
  1862. "gisprompt" : True,
  1863. "prompt" : "color"
  1864. },{
  1865. "name" : "transparent_color",
  1866. "description" : "This color becomes transparent when set to none",
  1867. "guisection" : "tab",
  1868. "gisprompt" : True,
  1869. "prompt" : "color"
  1870. },{
  1871. "name" : "multi",
  1872. "description" : "A multiple selection",
  1873. 'default': u'red,green,blue',
  1874. 'gisprompt': False,
  1875. 'guisection': 'tab',
  1876. 'multiple': u'yes',
  1877. 'type': u'string',
  1878. 'value': '',
  1879. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other']
  1880. },{
  1881. "name" : "single",
  1882. "description" : "A single multiple-choice selection",
  1883. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  1884. "guisection" : "tab"
  1885. },{
  1886. "name" : "large_multi",
  1887. "description" : "A large multiple selection",
  1888. "gisprompt" : False,
  1889. "multiple" : "yes",
  1890. # values must be an array of strings
  1891. "values" : str2rgb.keys() + map( str, str2rgb.values() )
  1892. },{
  1893. "name" : "a_file",
  1894. "description" : "A file selector",
  1895. "gisprompt" : True,
  1896. "element" : "file"
  1897. }
  1898. ]
  1899. task.flags = [
  1900. {
  1901. "name" : "a",
  1902. "description" : "Some flag, will appear in Main since it is required",
  1903. "required" : "yes"
  1904. },{
  1905. "name" : "b",
  1906. "description" : "pre-filled flag, will appear in options since it is not required",
  1907. "value" : True
  1908. },{
  1909. "name" : "hidden_flag",
  1910. "description" : "hidden flag, should not be changeable",
  1911. "hidden" : "yes",
  1912. "value" : True
  1913. }
  1914. ]
  1915. q=wx.LogNull()
  1916. GrassGUIApp( task ).MainLoop()