menuform.py 89 KB

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