menuform.py 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198
  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. This program is just a coarse approach to automatically build a GUI
  14. from a xml-based GRASS user interface description.
  15. You need to have Python 2.4, wxPython 2.8 and python-xml.
  16. The XML stream is read from executing the command given in the
  17. command line, thus you may call it for instance this way:
  18. python menuform.py r.basins.fill
  19. Or you set an alias or wrap the call up in a nice shell script, GUI
  20. environment ... please contribute your idea.
  21. Updated to wxPython 2.8 syntax and contrib widgets. Methods added to
  22. make it callable by gui. Method added to automatically re-run with
  23. pythonw on a Mac.
  24. @todo
  25. - verify option value types
  26. Copyright (C) 2000-2010 by the GRASS Development Team
  27. This program is free software under the GPL (>=v2) Read the file
  28. COPYING coming with GRASS for details.
  29. @author Jan-Oliver Wagner <jan@intevation.de>
  30. @author Bernhard Reiter <bernhard@intevation.de>
  31. @author Michael Barton, Arizona State University
  32. @author Daniel Calvelo <dca.gis@gmail.com>
  33. @author Martin Landa <landa.martin@gmail.com>
  34. """
  35. import sys
  36. import re
  37. import string
  38. import textwrap
  39. import os
  40. import time
  41. import types
  42. import copy
  43. import locale
  44. import types
  45. from threading import Thread
  46. import Queue
  47. import shlex
  48. ### i18N
  49. import gettext
  50. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True)
  51. import globalvar
  52. if not os.getenv("GRASS_WXBUNDLED"):
  53. globalvar.CheckForWx()
  54. import wx
  55. import wx.html
  56. import wx.lib.flatnotebook as FN
  57. import wx.lib.colourselect as csel
  58. import wx.lib.filebrowsebutton as filebrowse
  59. from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
  60. from wx.lib.newevent import NewEvent
  61. try:
  62. import wx.lib.agw.floatspin as FS
  63. except ImportError:
  64. FS = None
  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. # update reference widgets
  180. for uid in p['wxId-bind']:
  181. win = self.parent.FindWindowById(uid)
  182. name = win.GetName()
  183. map = layer = None
  184. driver = db = table = None
  185. if name in ('LayerSelect', 'LayerNameSelect',
  186. 'ColumnSelect'):
  187. if p.get('element', '') == 'vector': # -> vector
  188. # get map name
  189. map = p.get('value', '')
  190. # get layer
  191. for bid in p['wxId-bind']:
  192. p = self.task.get_param(bid, element = 'wxId', raiseError = False)
  193. if not p:
  194. continue
  195. if p.get('element', '') == 'layer':
  196. layer = p.get('value', '')
  197. if layer != '':
  198. layer = p.get('value', 1)
  199. else:
  200. layer = p.get('default', 1)
  201. break
  202. elif p.get('element', '') == 'layer': # -> layer
  203. # get layer
  204. layer = p.get('value', '')
  205. if layer != '':
  206. layer = p.get('value', 1)
  207. else:
  208. layer = p.get('default', 1)
  209. # get map name
  210. pMap = self.task.get_param(p['wxId'][0], element = 'wxId-bind', raiseError = False)
  211. if pMap:
  212. map = pMap.get('value', '')
  213. if name == 'TableSelect' or \
  214. (name == 'ColumnSelect' and not map):
  215. pDriver = self.task.get_param('dbdriver', element='prompt', raiseError=False)
  216. if pDriver:
  217. driver = pDriver.get('value', '')
  218. pDb = self.task.get_param('dbname', element='prompt', raiseError=False)
  219. if pDb:
  220. db = pDb.get('value', '')
  221. if name == 'ColumnSelect':
  222. pTable = self.task.get_param('dbtable', element='element', raiseError=False)
  223. if pTable:
  224. table = pTable.get('value', '')
  225. if name == 'LayerSelect':
  226. self.data[win.InsertLayers] = { 'vector' : map }
  227. elif name == 'LayerNameSelect':
  228. # determine format
  229. native = True
  230. for id in pMap['wxId']:
  231. winVec = self.parent.FindWindowById(id)
  232. if winVec.GetName() == 'VectorFormat' and \
  233. winVec.GetSelection() != 0:
  234. native = False
  235. break
  236. if not native:
  237. if map:
  238. self.data[win.InsertLayers] = { 'dsn' : map.rstrip('@OGR') }
  239. else:
  240. self.data[win.InsertLayers] = { }
  241. elif name == 'TableSelect':
  242. self.data[win.InsertTables] = { 'driver' : driver,
  243. 'database' : db }
  244. elif name == 'ColumnSelect':
  245. if map:
  246. self.data[win.InsertColumns] = { 'vector' : map, 'layer' : layer }
  247. else: # table
  248. if driver and db:
  249. self.data[win.InsertTableColumns] = { 'table' : pTable.get('value'),
  250. 'driver' : driver,
  251. 'database' : db }
  252. elif pTable:
  253. self.data[win.InsertTableColumns] = { 'table' : pTable.get('value') }
  254. elif name == 'SubGroupSelect':
  255. pGroup = self.task.get_param('group', element='element', raiseError=False)
  256. if pGroup:
  257. self.data[win.Insert] = { 'group' : pGroup.get('value', '')}
  258. def UpdateDialog(parent, event, eventId, task):
  259. return UpdateThread(parent, event, eventId, task)
  260. class UpdateQThread(Thread):
  261. """!Update dialog widgets in the thread"""
  262. requestId = 0
  263. def __init__(self, parent, requestQ, resultQ, **kwds):
  264. Thread.__init__(self, **kwds)
  265. self.parent = parent # cmdPanel
  266. self.setDaemon(True)
  267. self.requestQ = requestQ
  268. self.resultQ = resultQ
  269. self.start()
  270. def Update(self, callable, *args, **kwds):
  271. UpdateQThread.requestId += 1
  272. self.request = None
  273. self.requestQ.put((UpdateQThread.requestId, callable, args, kwds))
  274. return UpdateQThread.requestId
  275. def run(self):
  276. while True:
  277. requestId, callable, args, kwds = self.requestQ.get()
  278. requestTime = time.time()
  279. self.request = callable(*args, **kwds)
  280. self.resultQ.put((requestId, self.request.run()))
  281. event = wxUpdateDialog(data = self.request.data)
  282. wx.PostEvent(self.parent, event)
  283. class grassTask:
  284. """!This class holds the structures needed for both filling by the
  285. parser and use by the interface constructor.
  286. Use as either grassTask() for empty definition or
  287. grassTask('grass.command' ) for parsed filling.
  288. """
  289. def __init__(self, grassModule = None):
  290. self.path = grassModule
  291. self.name = _('unknown')
  292. self.params = list()
  293. self.description = ''
  294. self.label = ''
  295. self.flags = list()
  296. self.keywords = list()
  297. if grassModule is not None:
  298. processTask(tree = etree.fromstring(getInterfaceDescription(grassModule)),
  299. task = self)
  300. def get_name(self):
  301. """!Get task name"""
  302. return self.name
  303. def get_list_params(self, element = 'name'):
  304. """!Get list of parameters"""
  305. params = []
  306. for p in self.params:
  307. params.append(p['name'])
  308. return params
  309. def get_list_flags(self, element = 'name'):
  310. """!Get list of parameters"""
  311. flags = []
  312. for p in self.flags:
  313. flags.append(p['name'])
  314. return flags
  315. def get_param(self, value, element='name', raiseError=True):
  316. """!Find and return a param by name."""
  317. try:
  318. for p in self.params:
  319. val = p[element]
  320. if val is None:
  321. continue
  322. if type(val) in (types.ListType, types.TupleType):
  323. if value in val:
  324. return p
  325. elif type(val) == types.StringType:
  326. if p[element][:len(value)] == value:
  327. return p
  328. else:
  329. if p[element] == value:
  330. return p
  331. except KeyError:
  332. pass
  333. if raiseError:
  334. raise ValueError, _("Parameter element '%(element)s' not found: '%(value)s'") % \
  335. { 'element' : element, 'value' : value }
  336. else:
  337. return None
  338. def set_param(self, aParam, aValue, element = 'value'):
  339. """
  340. Set param value/values.
  341. """
  342. try:
  343. param = self.get_param(aParam)
  344. except ValueError:
  345. return
  346. param[element] = aValue
  347. def get_flag(self, aFlag):
  348. """
  349. Find and return a flag by name.
  350. """
  351. for f in self.flags:
  352. if f['name'] == aFlag:
  353. return f
  354. raise ValueError, _("Flag not found: %s") % aFlag
  355. def set_flag(self, aFlag, aValue, element = 'value'):
  356. """
  357. Enable / disable flag.
  358. """
  359. try:
  360. param = self.get_flag(aFlag)
  361. except ValueError:
  362. return
  363. param[element] = aValue
  364. def getCmdError(self):
  365. """!Get error string produced by getCmd(ignoreErrors = False)
  366. @return list of errors
  367. """
  368. errorList = list()
  369. for p in self.params:
  370. if p.get('value', '') == '' and p.get('required', 'no') != 'no':
  371. if p.get('default', '') == '':
  372. errorList.append(_("Parameter '%(name)s' (%(desc)s) is missing.") % \
  373. {'name' : p['name'], 'desc' : p['description']})
  374. return errorList
  375. def getCmd(self, ignoreErrors = False):
  376. """!Produce an array of command name and arguments for feeding
  377. into some execve-like command processor.
  378. If ignoreErrors==True then it will return whatever has been
  379. built so far, even though it would not be a correct command
  380. for GRASS.
  381. """
  382. cmd = [self.name]
  383. for flag in self.flags:
  384. if 'value' in flag and flag['value']:
  385. if len(flag['name']) > 1: # e.g. overwrite
  386. cmd += [ '--' + flag['name'] ]
  387. else:
  388. cmd += [ '-' + flag['name'] ]
  389. for p in self.params:
  390. if p.get('value','') == '' and p.get('required','no') != 'no':
  391. if p.get('default', '') != '':
  392. cmd += [ '%s=%s' % ( p['name'], p['default'] ) ]
  393. elif ignoreErrors is False:
  394. cmd += [ '%s=%s' % ( p['name'], _('<required>') ) ]
  395. elif p.get('value','') != '' and p['value'] != p.get('default','') :
  396. # Output only values that have been set, and different from defaults
  397. cmd += [ '%s=%s' % ( p['name'], p['value'] ) ]
  398. errList = self.getCmdError()
  399. if ignoreErrors is False and errList:
  400. raise ValueError, '\n'.join(errList)
  401. return cmd
  402. def set_options(self, opts):
  403. """!Set flags and parameters
  404. @param opts list of flags and parameters"""
  405. for opt in opts:
  406. if opt[0] == '-': # flag
  407. self.set_flag(opt.lstrip('-'), True)
  408. else: # parameter
  409. key, value = opt.split('=', 1)
  410. self.set_param(key, value)
  411. def get_options(self):
  412. """!Get options"""
  413. return { 'flags' : self.flags,
  414. 'params' : self.params }
  415. class processTask:
  416. """!A ElementTree handler for the --interface-description output,
  417. as defined in grass-interface.dtd. Extend or modify this and the
  418. DTD if the XML output of GRASS' parser is extended or modified.
  419. @param tree root tree node
  420. @param task grassTask instance or None
  421. @return grassTask instance
  422. """
  423. def __init__(self, tree, task = None):
  424. if task:
  425. self.task = task
  426. else:
  427. self.task = grassTask()
  428. self.root = tree
  429. self.__processModule()
  430. self.__processParams()
  431. self.__processFlags()
  432. def __processModule(self):
  433. """!Process module description"""
  434. self.task.name = self.root.get('name', default = 'unknown')
  435. # keywords
  436. for keyword in self.__getNodeText(self.root, 'keywords').split(','):
  437. self.task.keywords.append(keyword.strip())
  438. self.task.label = self.__getNodeText(self.root, 'label')
  439. self.task.description = self.__getNodeText(self.root, 'description')
  440. def __processParams(self):
  441. """!Process parameters description"""
  442. for p in self.root.findall('parameter'):
  443. # gisprompt
  444. node_gisprompt = p.find('gisprompt')
  445. gisprompt = False
  446. age = element = prompt = None
  447. if node_gisprompt is not None:
  448. gisprompt = True
  449. age = node_gisprompt.get('age', '')
  450. element = node_gisprompt.get('element', '')
  451. prompt = node_gisprompt.get('prompt', '')
  452. # value(s)
  453. values = []
  454. values_desc = []
  455. node_values = p.find('values')
  456. if node_values is not None:
  457. for pv in node_values.findall('value'):
  458. values.append(self.__getNodeText(pv, 'name'))
  459. desc = self.__getNodeText(pv, 'description')
  460. if desc:
  461. values_desc.append(desc)
  462. # keydesc
  463. key_desc = []
  464. node_key_desc = p.find('keydesc')
  465. if node_key_desc is not None:
  466. for ki in node_key_desc.findall('item'):
  467. key_desc.append(ki.text)
  468. self.task.params.append( {
  469. "name" : p.get('name'),
  470. "type" : p.get('type'),
  471. "required" : p.get('required'),
  472. "multiple" : p.get('multiple'),
  473. "label" : self.__getNodeText(p, 'label'),
  474. "description" : self.__getNodeText(p, 'description'),
  475. 'gisprompt' : gisprompt,
  476. 'age' : age,
  477. 'element' : element,
  478. 'prompt' : prompt,
  479. "guisection" : self.__getNodeText(p, 'guisection'),
  480. "guidependency" : self.__getNodeText(p, 'guidependency'),
  481. "default" : self.__getNodeText(p, 'default'),
  482. "values" : values,
  483. "values_desc" : values_desc,
  484. "value" : '',
  485. "key_desc" : key_desc } )
  486. def __processFlags(self):
  487. """!Process flags description"""
  488. for p in self.root.findall('flag'):
  489. self.task.flags.append( {
  490. "name" : p.get('name'),
  491. "label" : self.__getNodeText(p, 'label'),
  492. "description" : self.__getNodeText(p, 'description'),
  493. "guisection" : self.__getNodeText(p, 'guisection') } )
  494. def __getNodeText(self, node, tag, default = ''):
  495. """!Get node text"""
  496. p = node.find(tag)
  497. if p is not None:
  498. return utils.normalize_whitespace(p.text)
  499. return default
  500. def GetTask(self):
  501. """!Get grassTask instance"""
  502. return self.task
  503. class mainFrame(wx.Frame):
  504. """!This is the Frame containing the dialog for options input.
  505. The dialog is organized in a notebook according to the guisections
  506. defined by each GRASS command.
  507. If run with a parent, it may Apply, Ok or Cancel; the latter two
  508. close the dialog. The former two trigger a callback.
  509. If run standalone, it will allow execution of the command.
  510. The command is checked and sent to the clipboard when clicking
  511. 'Copy'.
  512. """
  513. def __init__(self, parent, ID, task_description,
  514. get_dcmd = None, layer = None):
  515. self.get_dcmd = get_dcmd
  516. self.layer = layer
  517. self.task = task_description
  518. self.parent = parent # LayerTree | Modeler | None | ...
  519. if parent and parent.GetName() == 'Modeler':
  520. self.modeler = self.parent
  521. else:
  522. self.modeler = None
  523. # module name + keywords
  524. if self.task.name.split('.')[-1] in ('py', 'sh'):
  525. title = str(self.task.name.rsplit('.',1)[0])
  526. else:
  527. title = self.task.name
  528. try:
  529. if self.task.keywords != ['']:
  530. title += " [" + ', '.join( self.task.keywords ) + "]"
  531. except ValueError:
  532. pass
  533. wx.Frame.__init__(self, parent=parent, id=ID, title=title,
  534. pos=wx.DefaultPosition, style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL,
  535. name = "MainFrame")
  536. self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
  537. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  538. # statusbar
  539. self.CreateStatusBar()
  540. # icon
  541. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_dialog.ico'), wx.BITMAP_TYPE_ICO))
  542. guisizer = wx.BoxSizer(wx.VERTICAL)
  543. # set apropriate output window
  544. if self.parent:
  545. self.standalone = False
  546. else:
  547. self.standalone = True
  548. # logo+description
  549. topsizer = wx.BoxSizer(wx.HORIZONTAL)
  550. # GRASS logo
  551. self.logo = wx.StaticBitmap(parent=self.panel,
  552. bitmap=wx.Bitmap(name=os.path.join(imagepath,
  553. 'grass_form.png'),
  554. type=wx.BITMAP_TYPE_PNG))
  555. topsizer.Add (item=self.logo, proportion=0, border=3,
  556. flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
  557. #
  558. # put module description
  559. #
  560. if self.task.label != '':
  561. module_desc = self.task.label + ' ' + self.task.description
  562. else:
  563. module_desc = self.task.description
  564. self.description = gdialogs.StaticWrapText(parent=self.panel,
  565. label=module_desc)
  566. topsizer.Add (item=self.description, proportion=1, border=5,
  567. flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  568. guisizer.Add (item=topsizer, proportion=0, flag=wx.EXPAND)
  569. self.panel.SetSizerAndFit(guisizer)
  570. self.Layout()
  571. # notebooks
  572. self.notebookpanel = cmdPanel(parent = self.panel, task = self.task,
  573. mainFrame = self)
  574. self.goutput = self.notebookpanel.goutput
  575. self.notebookpanel.OnUpdateValues = self.updateValuesHook
  576. guisizer.Add (item=self.notebookpanel, proportion=1, flag=wx.EXPAND)
  577. # status bar
  578. status_text = _("Enter parameters for '") + self.task.name + "'"
  579. try:
  580. self.task.getCmd()
  581. self.updateValuesHook()
  582. except ValueError:
  583. self.SetStatusText( status_text )
  584. # buttons
  585. btnsizer = wx.BoxSizer(orient=wx.HORIZONTAL)
  586. # cancel
  587. self.btn_cancel = wx.Button(parent=self.panel, id=wx.ID_CLOSE)
  588. self.btn_cancel.SetToolTipString(_("Close this window without executing the command (Ctrl+Q)"))
  589. btnsizer.Add(item=self.btn_cancel, proportion=0, flag=wx.ALL | wx.ALIGN_CENTER, border=10)
  590. self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  591. # help
  592. self.btn_help = wx.Button(parent=self.panel, id=wx.ID_HELP)
  593. self.btn_help.SetToolTipString(_("Show manual page of the command (Ctrl+H)"))
  594. self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
  595. if not hasattr(self.notebookpanel, "manual_tab_id"):
  596. self.btn_help.Hide()
  597. if self.get_dcmd is not None: # A callback has been set up
  598. btn_apply = wx.Button(parent=self.panel, id=wx.ID_APPLY)
  599. btn_ok = wx.Button(parent=self.panel, id=wx.ID_OK)
  600. btn_ok.SetDefault()
  601. btnsizer.Add(item=btn_apply, proportion=0,
  602. flag=wx.ALL | wx.ALIGN_CENTER,
  603. border=10)
  604. btnsizer.Add(item=btn_ok, proportion=0,
  605. flag=wx.ALL | wx.ALIGN_CENTER,
  606. border=10)
  607. btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
  608. btn_ok.Bind(wx.EVT_BUTTON, self.OnOK)
  609. else: # We're standalone
  610. # run
  611. self.btn_run = wx.Button(parent=self.panel, id=wx.ID_OK, label= _("&Run"))
  612. self.btn_run.SetToolTipString(_("Run the command (Ctrl+R)"))
  613. self.btn_run.SetDefault()
  614. # abort
  615. ### self.btn_abort = wx.Button(parent=self.panel, id=wx.ID_STOP)
  616. ### self.btn_abort.SetToolTipString(_("Abort the running command"))
  617. ### self.btn_abort.Enable(False)
  618. # copy
  619. self.btn_clipboard = wx.Button(parent=self.panel, id=wx.ID_COPY)
  620. self.btn_clipboard.SetToolTipString(_("Copy the current command string to the clipboard (Ctrl+C)"))
  621. ### btnsizer.Add(item=self.btn_abort, proportion=0,
  622. ### flag=wx.ALL | wx.ALIGN_CENTER,
  623. ### border=10)
  624. btnsizer.Add(item=self.btn_run, proportion=0,
  625. flag=wx.ALL | wx.ALIGN_CENTER,
  626. border=10)
  627. btnsizer.Add(item=self.btn_clipboard, proportion=0,
  628. flag=wx.ALL | wx.ALIGN_CENTER,
  629. border=10)
  630. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  631. ### self.btn_abort.Bind(wx.EVT_BUTTON, self.OnAbort)
  632. self.btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
  633. # add help button
  634. btnsizer.Add(item=self.btn_help, proportion=0, flag=wx.ALL | wx.ALIGN_CENTER, border=10)
  635. guisizer.Add(item=btnsizer, proportion=0, flag=wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT,
  636. border = 30)
  637. if self.parent and not self.modeler:
  638. addLayer = False
  639. for p in self.task.params:
  640. if p.get('age', 'old') == 'new' and \
  641. p.get('prompt', '') in ('raster', 'vector', '3d-raster'):
  642. addLayer = True
  643. if addLayer:
  644. # add newly created map into layer tree
  645. self.addbox = wx.CheckBox(parent=self.panel,
  646. label=_('Add created map(s) into layer tree'), style = wx.NO_BORDER)
  647. self.addbox.SetValue(UserSettings.Get(group='cmd', key='addNewLayer', subkey='enabled'))
  648. guisizer.Add(item=self.addbox, proportion=0,
  649. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  650. border=5)
  651. if self.get_dcmd is None:
  652. # close dialog when command is terminated
  653. self.closebox = wx.CheckBox(parent=self.panel,
  654. label=_('Close dialog on finish'), style = wx.NO_BORDER)
  655. self.closebox.SetValue(UserSettings.Get(group='cmd', key='closeDlg', subkey='enabled'))
  656. guisizer.Add(item=self.closebox, proportion=0,
  657. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  658. border=5)
  659. self.Bind(wx.EVT_CLOSE, self.OnCancel)
  660. self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
  661. #constrained_size = self.notebookpanel.GetSize()
  662. # 80 takes the tabbar into account
  663. #self.notebookpanel.SetSize( (constrained_size[0] + 25, constrained_size[1]) )
  664. #self.notebookpanel.Layout()
  665. #
  666. # do layout
  667. #
  668. guisizer.SetSizeHints(self.panel)
  669. # called automatically by SetSizer()
  670. self.panel.SetAutoLayout(True)
  671. self.panel.SetSizerAndFit(guisizer)
  672. sizeFrame = self.GetBestSize()
  673. self.SetMinSize(sizeFrame)
  674. self.SetSize((sizeFrame[0], sizeFrame[1] +
  675. self.notebookpanel.constrained_size[1] -
  676. self.notebookpanel.panelMinHeight))
  677. # thread to update dialog
  678. # create queues
  679. self.requestQ = Queue.Queue()
  680. self.resultQ = Queue.Queue()
  681. self.updateThread = UpdateQThread(self.notebookpanel, self.requestQ, self.resultQ)
  682. self.Layout()
  683. #keep initial window size limited for small screens
  684. width, height = self.GetSizeTuple()
  685. if width > 640: width = 640
  686. if height > 480: height = 480
  687. self.SetSize((width, height))
  688. # fix goutput's pane size
  689. if self.goutput:
  690. self.goutput.SetSashPosition(int(self.GetSize()[1] * .75))
  691. def updateValuesHook(self):
  692. """!Update status bar data"""
  693. self.SetStatusText(' '.join(self.notebookpanel.createCmd(ignoreErrors = True)) )
  694. def OnKeyUp(self, event):
  695. """!Key released (check hot-keys)"""
  696. try:
  697. kc = chr(event.GetKeyCode())
  698. except ValueError:
  699. event.Skip()
  700. return
  701. if not event.ControlDown():
  702. event.Skip()
  703. return
  704. if kc == 'Q':
  705. self.OnCancel(None)
  706. elif kc == 'S':
  707. self.OnAbort(None)
  708. elif kc == 'H':
  709. self.OnHelp(None)
  710. elif kc == 'R':
  711. self.OnRun(None)
  712. elif kc == 'C':
  713. self.OnCopy(None)
  714. event.Skip()
  715. def OnOK(self, event):
  716. """!OK button pressed"""
  717. cmd = self.OnApply(event)
  718. if cmd is not None and self.get_dcmd is not None:
  719. self.OnCancel(event)
  720. def OnApply(self, event):
  721. """!Apply the command"""
  722. if self.modeler:
  723. cmd = self.createCmd(ignoreErrors = True)
  724. else:
  725. cmd = self.createCmd()
  726. if cmd is not None and self.get_dcmd is not None:
  727. # return d.* command to layer tree for rendering
  728. self.get_dcmd(cmd, self.layer, {"params": self.task.params,
  729. "flags" : self.task.flags},
  730. self)
  731. # echo d.* command to output console
  732. # self.parent.writeDCommand(cmd)
  733. return cmd
  734. def OnRun(self, event):
  735. """!Run the command"""
  736. cmd = self.createCmd()
  737. if cmd == None or len(cmd) < 2:
  738. return
  739. if self.standalone or cmd[0][0:2] != "d.":
  740. # Send any non-display command to parent window (probably wxgui.py)
  741. # put to parents
  742. # switch to 'Command output'
  743. if self.notebookpanel.notebook.GetSelection() != self.notebookpanel.goutputId:
  744. self.notebookpanel.notebook.SetSelection(self.notebookpanel.goutputId)
  745. try:
  746. if self.task.path:
  747. cmd[0] = self.task.path # full path
  748. self.goutput.RunCmd(cmd)
  749. except AttributeError, e:
  750. print >> sys.stderr, "%s: Propably not running in wxgui.py session?" % (e)
  751. print >> sys.stderr, "parent window is: %s" % (str(self.parent))
  752. # Send any other command to the shell.
  753. else:
  754. gcmd.Command(cmd)
  755. # update buttons status
  756. for btn in (self.btn_run,
  757. self.btn_cancel,
  758. self.btn_clipboard,
  759. self.btn_help):
  760. btn.Enable(False)
  761. ### self.btn_abort.Enable(True)
  762. def OnAbort(self, event):
  763. """!Abort running command"""
  764. event = goutput.wxCmdAbort(aborted=True)
  765. wx.PostEvent(self.goutput, event)
  766. def OnCopy(self, event):
  767. """!Copy the command"""
  768. cmddata = wx.TextDataObject()
  769. # list -> string
  770. cmdstring = ' '.join(self.createCmd(ignoreErrors=True))
  771. cmddata.SetText(cmdstring)
  772. if wx.TheClipboard.Open():
  773. # wx.TheClipboard.UsePrimarySelection(True)
  774. wx.TheClipboard.SetData(cmddata)
  775. wx.TheClipboard.Close()
  776. self.SetStatusText( _("'%s' copied to clipboard") % \
  777. (cmdstring))
  778. def OnCancel(self, event):
  779. """!Cancel button pressed"""
  780. self.MakeModal(False)
  781. if self.get_dcmd and \
  782. self.parent and \
  783. self.parent.GetName() in ('LayerTree',
  784. 'MapWindow'):
  785. # display decorations and
  786. # pressing OK or cancel after setting layer properties
  787. if self.task.name in ['d.barscale','d.legend','d.histogram'] \
  788. or len(self.parent.GetPyData(self.layer)[0]['cmd']) >= 1:
  789. self.Hide()
  790. # canceled layer with nothing set
  791. elif len(self.parent.GetPyData(self.layer)[0]['cmd']) < 1:
  792. self.parent.Delete(self.layer)
  793. self.Destroy()
  794. else:
  795. # cancel for non-display commands
  796. self.Destroy()
  797. def OnHelp(self, event):
  798. """!Show manual page (switch to the 'Manual' notebook page)"""
  799. if hasattr(self.notebookpanel, "manual_tab_id"):
  800. self.notebookpanel.notebook.SetSelection(self.notebookpanel.manual_tab_id)
  801. self.notebookpanel.OnPageChange(None)
  802. if event:
  803. event.Skip()
  804. def createCmd(self, ignoreErrors = False):
  805. """!Create command string (python list)"""
  806. return self.notebookpanel.createCmd(ignoreErrors=ignoreErrors)
  807. class cmdPanel(wx.Panel):
  808. """!A panel containing a notebook dividing in tabs the different
  809. guisections of the GRASS cmd.
  810. """
  811. def __init__(self, parent, task, id = wx.ID_ANY, mainFrame = None, *args, **kwargs):
  812. if mainFrame:
  813. self.parent = mainFrame
  814. else:
  815. self.parent = parent
  816. self.task = task
  817. wx.Panel.__init__(self, parent, id = id, *args, **kwargs)
  818. # Determine tab layout
  819. sections = []
  820. is_section = {}
  821. not_hidden = [ p for p in self.task.params + self.task.flags if not p.get( 'hidden','no' ) == 'yes' ]
  822. self.label_id = [] # wrap titles on resize
  823. self.Bind(wx.EVT_SIZE, self.OnSize)
  824. for task in not_hidden:
  825. if task.get( 'required','no' ) == 'yes':
  826. # All required go into Main, even if they had defined another guisection
  827. task['guisection'] = _( 'Required' )
  828. if task.get( 'guisection','' ) == '':
  829. # Undefined guisections end up into Options
  830. task['guisection'] = _( 'Optional' )
  831. if not is_section.has_key(task['guisection']):
  832. # We do it like this to keep the original order, except for Main which goes first
  833. is_section[task['guisection']] = 1
  834. sections.append( task['guisection'] )
  835. else:
  836. is_section[ task['guisection'] ] += 1
  837. del is_section
  838. # 'Required' tab goes first, 'Optional' as the last one
  839. for (newidx,content) in [ (0,_( 'Required' )), (len(sections)-1,_('Optional')) ]:
  840. if content in sections:
  841. idx = sections.index( content )
  842. sections[idx:idx+1] = []
  843. sections[newidx:newidx] = [content]
  844. panelsizer = wx.BoxSizer(orient=wx.VERTICAL)
  845. # Build notebook
  846. nbStyle = globalvar.FNPageStyle
  847. self.notebook = FN.FlatNotebook( self, id=wx.ID_ANY, style=nbStyle)
  848. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  849. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  850. tab = {}
  851. tabsizer = {}
  852. for section in sections:
  853. tab[section] = wx.ScrolledWindow( parent=self.notebook )
  854. tab[section].SetScrollRate(10,10)
  855. tabsizer[section] = wx.BoxSizer(orient=wx.VERTICAL)
  856. self.notebook.AddPage( tab[section], text=section )
  857. # are we running from command line?
  858. ### add 'command output' tab regardless standalone dialog
  859. if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
  860. self.goutput = goutput.GMConsole(parent=self, margin=False,
  861. pageid=self.notebook.GetPageCount())
  862. self.goutputId = self.notebook.GetPageCount()
  863. self.outpage = self.notebook.AddPage(self.goutput, text=_("Command output") )
  864. else:
  865. self.goutput = None
  866. self.goutputId = -1
  867. self.manual_tab = HelpPanel(parent = self, grass_command = self.task.name)
  868. if not self.manual_tab.IsFile():
  869. self.manual_tab.Hide()
  870. else:
  871. self.notebook.AddPage(self.manual_tab, text=_("Manual"))
  872. self.manual_tab_id = self.notebook.GetPageCount() - 1
  873. self.notebook.SetSelection(0)
  874. panelsizer.Add(item=self.notebook, proportion=1, flag=wx.EXPAND )
  875. #
  876. # flags
  877. #
  878. text_style = wx.FONTWEIGHT_NORMAL
  879. visible_flags = [ f for f in self.task.flags if not f.get( 'hidden', 'no' ) == 'yes' ]
  880. for f in visible_flags:
  881. which_sizer = tabsizer[ f['guisection'] ]
  882. which_panel = tab[ f['guisection'] ]
  883. # if label is given: description -> tooltip
  884. if f.get('label','') != '':
  885. title = text_beautify( f['label'])
  886. tooltip = text_beautify ( f['description'], width=-1)
  887. else:
  888. title = text_beautify( f['description'] )
  889. tooltip = None
  890. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  891. rtitle_txt = wx.StaticText(parent=which_panel,
  892. label = '(' + f['name'] + ')')
  893. chk = wx.CheckBox(parent=which_panel, label = title, style = wx.NO_BORDER)
  894. self.label_id.append(chk.GetId())
  895. if tooltip:
  896. chk.SetToolTipString(tooltip)
  897. if 'value' in f:
  898. chk.SetValue( f['value'] )
  899. title_sizer.Add(item=chk, proportion=1,
  900. flag=wx.EXPAND)
  901. title_sizer.Add(item=rtitle_txt, proportion=0,
  902. flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
  903. which_sizer.Add(item=title_sizer, proportion=0,
  904. flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=5)
  905. f['wxId'] = [ chk.GetId(), ]
  906. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  907. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  908. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  909. label = _("Parametrized in model"))
  910. parChk.SetName('ModelParam')
  911. parChk.SetValue(f.get('parametrized', False))
  912. if f.has_key('wxId'):
  913. f['wxId'].append(parChk.GetId())
  914. else:
  915. f['wxId'] = [ parChk.GetId() ]
  916. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  917. which_sizer.Add(item = parChk, proportion = 0,
  918. flag = wx.LEFT, border = 20)
  919. if f['name'] in ('verbose', 'quiet'):
  920. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  921. vq = UserSettings.Get(group='cmd', key='verbosity', subkey='selection')
  922. if f['name'] == vq:
  923. chk.SetValue(True)
  924. f['value'] = True
  925. elif f['name'] == 'overwrite':
  926. chk.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
  927. f['value'] = UserSettings.Get(group='cmd', key='overwrite', subkey='enabled')
  928. #
  929. # parameters
  930. #
  931. visible_params = [ p for p in self.task.params if not p.get( 'hidden', 'no' ) == 'yes' ]
  932. try:
  933. first_param = visible_params[0]
  934. except IndexError:
  935. first_param = None
  936. for p in visible_params:
  937. which_sizer = tabsizer[ p['guisection'] ]
  938. which_panel = tab[ p['guisection'] ]
  939. # if label is given -> label and description -> tooltip
  940. # otherwise description -> lavel
  941. if p.get('label','') != '':
  942. title = text_beautify( p['label'] )
  943. tooltip = text_beautify ( p['description'], width = -1)
  944. else:
  945. title = text_beautify( p['description'] )
  946. tooltip = None
  947. txt = None
  948. # text style (required -> bold)
  949. if p.get('required','no') == 'no':
  950. text_style = wx.FONTWEIGHT_NORMAL
  951. else:
  952. text_style = wx.FONTWEIGHT_BOLD
  953. # title sizer (description, name, type)
  954. if (len(p.get('values', []) ) > 0) and \
  955. p.get('multiple', 'no') == 'yes' and \
  956. p.get('gisprompt',False) == False and \
  957. p.get('type', '') == 'string':
  958. title_txt = wx.StaticBox (parent=which_panel, id=wx.ID_ANY)
  959. else:
  960. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  961. title_txt = wx.StaticText(parent=which_panel)
  962. rtitle_txt = wx.StaticText(parent=which_panel,
  963. label = '(' + p['name'] + ', ' + p['type'] + ')')
  964. title_sizer.Add(item=title_txt, proportion=1,
  965. flag=wx.LEFT | wx.TOP | wx.EXPAND, border=5)
  966. title_sizer.Add(item=rtitle_txt, proportion=0,
  967. flag=wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border=5)
  968. which_sizer.Add(item=title_sizer, proportion=0,
  969. flag=wx.EXPAND)
  970. self.label_id.append(title_txt.GetId())
  971. # title expansion
  972. if p.get('multiple','no') == 'yes' and len( p.get('values','') ) == 0:
  973. title = _("[multiple]") + " " + title
  974. if p.get('value','') == '' :
  975. p['value'] = p.get('default','')
  976. if ( len(p.get('values', []) ) > 0):
  977. valuelist = map(str, p.get('values',[]))
  978. valuelist_desc = map(unicode, p.get('values_desc',[]))
  979. if p.get('multiple', 'no') == 'yes' and \
  980. p.get('gisprompt',False) == False and \
  981. p.get('type', '') == 'string':
  982. title_txt.SetLabel(" %s: (%s, %s) " % (title, p['name'], p['type']))
  983. if len(valuelist) > 6:
  984. hSizer=wx.StaticBoxSizer ( box=title_txt, orient=wx.VERTICAL )
  985. else:
  986. hSizer=wx.StaticBoxSizer ( box=title_txt, orient=wx.HORIZONTAL )
  987. isEnabled = {}
  988. # copy default values
  989. if p['value'] == '':
  990. p['value'] = p.get('default', '')
  991. for defval in p.get('value', '').split(','):
  992. isEnabled[ defval ] = 'yes'
  993. # for multi checkboxes, this is an array of all wx IDs
  994. # for each individual checkbox
  995. p[ 'wxId' ] = list()
  996. idx = 0
  997. for val in valuelist:
  998. try:
  999. label = valuelist_desc[idx]
  1000. except IndexError:
  1001. label = val
  1002. chkbox = wx.CheckBox( parent=which_panel,
  1003. label = text_beautify(label))
  1004. p[ 'wxId' ].append( chkbox.GetId() )
  1005. if isEnabled.has_key(val):
  1006. chkbox.SetValue( True )
  1007. hSizer.Add( item=chkbox, proportion=0,
  1008. flag=wx.ADJUST_MINSIZE | wx.ALL, border=1 )
  1009. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  1010. idx += 1
  1011. which_sizer.Add( item=hSizer, proportion=0,
  1012. flag=wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border=5 )
  1013. elif p.get('gisprompt', False) == False:
  1014. if len(valuelist) == 1: # -> textctrl
  1015. title_txt.SetLabel("%s. %s %s" % (title, _('Valid range'),
  1016. str(valuelist[0]) + ':'))
  1017. if p.get('type', '') == 'integer' and \
  1018. p.get('multiple','no') == 'no':
  1019. # for multiple integers use textctrl instead of spinsctrl
  1020. try:
  1021. minValue, maxValue = map(int, valuelist[0].split('-'))
  1022. except ValueError:
  1023. minValue = -1e6
  1024. maxValue = 1e6
  1025. txt2 = wx.SpinCtrl(parent=which_panel, id=wx.ID_ANY, size=globalvar.DIALOG_SPIN_SIZE,
  1026. min=minValue, max=maxValue)
  1027. txt2.SetName("SpinCtrl")
  1028. style = wx.BOTTOM | wx.LEFT
  1029. else:
  1030. txt2 = wx.TextCtrl(parent=which_panel, value = p.get('default',''))
  1031. txt2.SetName("TextCtrl")
  1032. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  1033. if p.get('value', '') != '':
  1034. # parameter previously set
  1035. if txt2.GetName() == "SpinCtrl":
  1036. txt2.SetValue(int(p['value']))
  1037. else:
  1038. txt2.SetValue(p['value'])
  1039. which_sizer.Add(item=txt2, proportion=0,
  1040. flag=style, border=5)
  1041. p['wxId'] = [ txt2.GetId(), ]
  1042. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  1043. else:
  1044. # list of values (combo)
  1045. title_txt.SetLabel(title + ':')
  1046. cb = wx.ComboBox(parent = which_panel, id = wx.ID_ANY, value = p.get('default',''),
  1047. size = globalvar.DIALOG_COMBOBOX_SIZE,
  1048. choices = valuelist, style = wx.CB_DROPDOWN)
  1049. if p.get('value', '') != '':
  1050. cb.SetValue(p['value']) # parameter previously set
  1051. which_sizer.Add(item = cb, proportion = 0,
  1052. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1053. p['wxId'] = [cb.GetId(),]
  1054. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1055. cb.Bind(wx.EVT_TEXT, self.OnSetValue)
  1056. # text entry
  1057. if (p.get('type','string') in ('string','integer','float')
  1058. and len(p.get('values',[])) == 0
  1059. and p.get('gisprompt',False) == False
  1060. and p.get('prompt','') != 'color'):
  1061. title_txt.SetLabel(title + ':' )
  1062. if p.get('multiple','yes') == 'yes' or \
  1063. p.get('type', 'string') == 'string' or \
  1064. len(p.get('key_desc', [])) > 1:
  1065. txt3 = wx.TextCtrl(parent=which_panel, value = p.get('default',''))
  1066. if p.get('value','') != '':
  1067. txt3.SetValue(str(p['value'])) # parameter previously set
  1068. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  1069. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  1070. else:
  1071. minValue = -1e9
  1072. maxValue = 1e9
  1073. if p.get('type', '') == 'integer':
  1074. txt3 = wx.SpinCtrl(parent=which_panel, value=p.get('default',''),
  1075. size=globalvar.DIALOG_SPIN_SIZE,
  1076. min=minValue, max=maxValue)
  1077. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1078. if p.get('value', '') != '':
  1079. txt3.SetValue(int(p['value'])) # parameter previously set
  1080. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1081. elif FS:
  1082. txt3 = FS.FloatSpin(parent = which_panel, id = wx.ID_ANY,
  1083. size = globalvar.DIALOG_SPIN_SIZE,
  1084. min_val = minValue, max_val = maxValue)
  1085. txt3.SetDigits(3)
  1086. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1087. if p.get('value', '') != '':
  1088. txt3.SetValue(float(p['value'])) # parameter previously set
  1089. txt3.Bind(FS.EVT_FLOATSPIN, self.OnSetValue)
  1090. else:
  1091. txt3 = wx.TextCtrl(parent=which_panel, value = p.get('default',''))
  1092. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  1093. if p.get('value', '') != '':
  1094. txt3.SetValue(str(p['value'])) # parameter previously set
  1095. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  1096. which_sizer.Add(item=txt3, proportion=0,
  1097. flag=style, border=5)
  1098. p['wxId'] = [ txt3.GetId(), ]
  1099. #
  1100. # element selection tree combobox (maps, icons, regions, etc.)
  1101. #
  1102. if p.get('gisprompt', False) == True:
  1103. title_txt.SetLabel(title + ':')
  1104. # GIS element entry
  1105. if p.get('prompt','') not in ('color',
  1106. 'color_none',
  1107. 'subgroup',
  1108. 'dbdriver',
  1109. 'dbname',
  1110. 'dbtable',
  1111. 'dbcolumn',
  1112. 'layer',
  1113. 'layer_all') and \
  1114. p.get('element', '') != 'file':
  1115. if p.get('multiple', 'no') == 'yes':
  1116. multiple = True
  1117. else:
  1118. multiple = False
  1119. if p.get('age', '') == 'new':
  1120. mapsets = [grass.gisenv()['MAPSET'],]
  1121. else:
  1122. mapsets = None
  1123. selection = gselect.Select(parent=which_panel, id=wx.ID_ANY,
  1124. size=globalvar.DIALOG_GSELECT_SIZE,
  1125. type=p.get('element', ''),
  1126. multiple=multiple, mapsets=mapsets)
  1127. if p.get('value','') != '':
  1128. selection.SetValue(p['value']) # parameter previously set
  1129. # A select.Select is a combobox with two children: a textctl and a popupwindow;
  1130. # we target the textctl here
  1131. p['wxId'] = [selection.GetChildren()[0].GetId(), ]
  1132. selection.GetChildren()[0].Bind(wx.EVT_TEXT, self.OnSetValue)
  1133. if p.get('prompt', '') == 'vector':
  1134. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1135. if p.get('age', '') == 'old':
  1136. # OGR supported (read-only)
  1137. self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  1138. self.hsizer.Add(item=selection,
  1139. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1140. border=5)
  1141. # format (native / ogr)
  1142. rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  1143. label = " %s " % _("Format"),
  1144. style = wx.RA_SPECIFY_ROWS,
  1145. choices = [_("Native / Linked OGR"), _("Direct OGR")])
  1146. if p.get('value', '').lower().rfind('@ogr') > -1:
  1147. rbox.SetSelection(1)
  1148. rbox.SetName('VectorFormat')
  1149. rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  1150. self.hsizer.Add(item=rbox,
  1151. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1152. wx.RIGHT | wx.ALIGN_TOP,
  1153. border=5)
  1154. ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  1155. default = 'dir',
  1156. exclude = ['file'])
  1157. self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  1158. self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  1159. ogrSelection.SetName('OgrSelect')
  1160. ogrSelection.Hide()
  1161. which_sizer.Add(item = self.hsizer, proportion = 0)
  1162. p['wxId'].append(rbox.GetId())
  1163. p['wxId'].append(ogrSelection.GetId())
  1164. for win in ogrSelection.GetDsnWin():
  1165. p['wxId'].append(win.GetId())
  1166. else:
  1167. which_sizer.Add(item=selection, proportion=0,
  1168. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1169. border=5)
  1170. elif p.get('prompt', '') == 'group':
  1171. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1172. which_sizer.Add(item=selection, proportion=0,
  1173. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1174. border=5)
  1175. else:
  1176. which_sizer.Add(item=selection, proportion=0,
  1177. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1178. border=5)
  1179. # subgroup
  1180. elif p.get('prompt', '') == 'subgroup':
  1181. selection = gselect.SubGroupSelect(parent = which_panel)
  1182. p['wxId'] = [ selection.GetId() ]
  1183. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1184. which_sizer.Add(item = selection, proportion = 0,
  1185. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1186. border = 5)
  1187. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1188. elif p.get('prompt', '') in ('dbdriver',
  1189. 'dbname',
  1190. 'dbtable',
  1191. 'dbcolumn',
  1192. 'layer',
  1193. 'layer_all'):
  1194. if p.get('multiple', 'no') == 'yes':
  1195. win = wx.TextCtrl(parent=which_panel, value = p.get('default',''),
  1196. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  1197. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1198. else:
  1199. if p.get('prompt', '') in ('layer',
  1200. 'layer_all'):
  1201. if p.get('prompt', '') == 'layer_all':
  1202. all = True
  1203. else:
  1204. all = False
  1205. win = wx.BoxSizer(wx.HORIZONTAL)
  1206. if p.get('age', 'old_layer') == 'old_layer':
  1207. win1 = gselect.LayerSelect(parent=which_panel,
  1208. all=all,
  1209. default=p['default'])
  1210. win1.Bind(wx.EVT_CHOICE, self.OnUpdateSelection)
  1211. win1.Bind(wx.EVT_CHOICE, self.OnSetValue)
  1212. else:
  1213. win1 = wx.SpinCtrl(parent=which_panel, id=wx.ID_ANY,
  1214. min=1, max=100, initial=int(p['default']))
  1215. win1.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1216. win2 = gselect.LayerNameSelect(parent = which_panel)
  1217. if p.get('value','') != '':
  1218. win2.SetItems([p['value']])
  1219. win2.SetSelection(0)
  1220. win2.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1221. p['wxId'] = [ win1.GetId(), win2.GetId() ]
  1222. win.Add(item = win1, proportion = 0)
  1223. win.Add(item = win2, proportion = 0,
  1224. flag = wx.LEFT | wx.ALIGN_CENTER_VERTICAL,
  1225. border = 5)
  1226. elif p.get('prompt', '') == 'dbdriver':
  1227. win = gselect.DriverSelect(parent=which_panel,
  1228. choices=p['values'],
  1229. value=p['default'])
  1230. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1231. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1232. elif p.get('prompt', '') == 'dbname':
  1233. win = gselect.DatabaseSelect(parent=which_panel,
  1234. value=p['default'])
  1235. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1236. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1237. elif p.get('prompt', '') == 'dbtable':
  1238. if p.get('age', 'old_dbtable') == 'old_dbtable':
  1239. win = gselect.TableSelect(parent=which_panel)
  1240. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1241. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1242. else:
  1243. win = wx.TextCtrl(parent=which_panel, value = p.get('default',''),
  1244. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  1245. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1246. elif p.get('prompt', '') == 'dbcolumn':
  1247. win = gselect.ColumnSelect(parent = which_panel,
  1248. value = p.get('default', ''),
  1249. param = p)
  1250. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1251. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1252. try:
  1253. p['wxId'] = [ win.GetId(), ]
  1254. except AttributeError:
  1255. pass
  1256. which_sizer.Add(item=win, proportion=0,
  1257. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  1258. # color entry
  1259. elif p.get('prompt', '') in ('color',
  1260. 'color_none'):
  1261. default_color = (200,200,200)
  1262. label_color = _("Select Color")
  1263. if p.get('default','') != '':
  1264. default_color, label_color = color_resolve( p['default'] )
  1265. if p.get('value','') != '': # parameter previously set
  1266. default_color, label_color = color_resolve( p['value'] )
  1267. if p.get('prompt', '') == 'color_none':
  1268. this_sizer = wx.BoxSizer(orient=wx.HORIZONTAL )
  1269. else:
  1270. this_sizer = which_sizer
  1271. btn_colour = csel.ColourSelect(parent=which_panel, id=wx.ID_ANY,
  1272. label=label_color, colour=default_color,
  1273. pos=wx.DefaultPosition, size=(150,-1) )
  1274. this_sizer.Add(item=btn_colour, proportion=0,
  1275. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border=5)
  1276. # For color selectors, this is a two-member array, holding the IDs of
  1277. # the selector proper and either a "transparent" button or None
  1278. p['wxId'] = [btn_colour.GetId(),]
  1279. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange )
  1280. if p.get('prompt', '') == 'color_none':
  1281. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent") )
  1282. if p.get('value','') != '' and p.get('value',[''])[0] == "none":
  1283. none_check.SetValue(True)
  1284. else:
  1285. none_check.SetValue(False)
  1286. this_sizer.Add(item=none_check, proportion=0,
  1287. flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border=5)
  1288. which_sizer.Add( this_sizer )
  1289. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1290. p['wxId'].append( none_check.GetId() )
  1291. else:
  1292. p['wxId'].append(None)
  1293. # file selector
  1294. elif p.get('prompt','') != 'color' and p.get('element', '') == 'file':
  1295. fbb = filebrowse.FileBrowseButton(parent=which_panel, id=wx.ID_ANY, fileMask = '*',
  1296. size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
  1297. dialogTitle=_('Choose %s') % \
  1298. p.get('description',_('File')),
  1299. buttonText=_('Browse'),
  1300. startDirectory=os.getcwd(), fileMode=0,
  1301. changeCallback=self.OnSetValue)
  1302. if p.get('value','') != '':
  1303. fbb.SetValue(p['value']) # parameter previously set
  1304. which_sizer.Add(item=fbb, proportion=0,
  1305. flag=wx.EXPAND | wx.RIGHT, border=5)
  1306. # A file browse button is a combobox with two children:
  1307. # a textctl and a button;
  1308. # we have to target the button here
  1309. p['wxId'] = [ fbb.GetChildren()[1].GetId(), ]
  1310. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  1311. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1312. label = _("Parametrized in model"))
  1313. parChk.SetName('ModelParam')
  1314. parChk.SetValue(p.get('parametrized', False))
  1315. if p.has_key('wxId'):
  1316. p['wxId'].append(parChk.GetId())
  1317. else:
  1318. p['wxId'] = [ parChk.GetId() ]
  1319. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1320. which_sizer.Add(item = parChk, proportion = 0,
  1321. flag = wx.LEFT, border = 20)
  1322. if title_txt is not None:
  1323. # create tooltip if given
  1324. if len(p['values_desc']) > 0:
  1325. if tooltip:
  1326. tooltip += 2 * os.linesep
  1327. else:
  1328. tooltip = ''
  1329. if len(p['values']) == len(p['values_desc']):
  1330. for i in range(len(p['values'])):
  1331. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1332. tooltip.strip(os.linesep)
  1333. if tooltip:
  1334. title_txt.SetToolTipString(tooltip)
  1335. if p == first_param:
  1336. if len(p['wxId']) > 0:
  1337. self.FindWindowById(p['wxId'][0]).SetFocus()
  1338. #
  1339. # set widget relations for OnUpdateSelection
  1340. #
  1341. pMap = None
  1342. pLayer = []
  1343. pDriver = None
  1344. pDatabase = None
  1345. pTable = None
  1346. pColumn = []
  1347. pGroup = None
  1348. pSubGroup = None
  1349. for p in self.task.params:
  1350. if p.get('gisprompt', False) == False:
  1351. continue
  1352. guidep = p.get('guidependency', '')
  1353. if guidep:
  1354. # fixed options dependency defined
  1355. options = guidep.split(',')
  1356. for opt in options:
  1357. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1358. if id:
  1359. if not p.has_key('wxId-bind'):
  1360. p['wxId-bind'] = list()
  1361. p['wxId-bind'] += pOpt['wxId']
  1362. continue
  1363. prompt = p.get('element', '')
  1364. if prompt == 'vector':
  1365. name = p.get('name', '')
  1366. if name in ('map', 'input'):
  1367. pMap = p
  1368. elif prompt == 'layer':
  1369. pLayer.append(p)
  1370. elif prompt == 'dbcolumn':
  1371. pColumn.append(p)
  1372. elif prompt == 'dbdriver':
  1373. pDriver = p
  1374. elif prompt == 'dbname':
  1375. pDatabase = p
  1376. elif prompt == 'dbtable':
  1377. pTable = p
  1378. elif prompt == 'group':
  1379. pGroup = p
  1380. elif prompt == 'subgroup':
  1381. pSubGroup = p
  1382. # collect ids
  1383. pColumnIds = []
  1384. for p in pColumn:
  1385. pColumnIds += p['wxId']
  1386. pLayerIds = []
  1387. for p in pLayer:
  1388. pLayerIds += p['wxId']
  1389. # set wxId-bindings
  1390. if pMap:
  1391. pMap['wxId-bind'] = copy.copy(pColumnIds)
  1392. if pLayer:
  1393. pMap['wxId-bind'] += pLayerIds
  1394. if len(pLayer) == 1:
  1395. # TODO: fix modules with more 'layer' options
  1396. pLayer[0]['wxId-bind'] = copy.copy(pColumnIds)
  1397. if pDriver and pTable:
  1398. pDriver['wxId-bind'] = pTable['wxId']
  1399. if pDatabase and pTable:
  1400. pDatabase['wxId-bind'] = pTable['wxId']
  1401. if pTable and pColumnIds:
  1402. pTable['wxId-bind'] = pColumnIds
  1403. if pGroup and pSubGroup:
  1404. pGroup['wxId-bind'] = pSubGroup['wxId']
  1405. #
  1406. # determine panel size
  1407. #
  1408. maxsizes = (0,0)
  1409. for section in sections:
  1410. # tabsizer[section].SetSizeHints( tab[section] )
  1411. #tab[section].SetAutoLayout(True)
  1412. tab[section].SetSizer( tabsizer[section] )
  1413. tabsizer[section].Fit( tab[section] )
  1414. tab[section].Layout()
  1415. minsecsizes = tabsizer[section].GetSize()
  1416. maxsizes = map( lambda x: max( maxsizes[x], minsecsizes[x] ), (0,1) )
  1417. # TODO: be less arbitrary with these 600
  1418. self.panelMinHeight = 100
  1419. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1420. for section in sections:
  1421. tab[section].SetMinSize( (self.constrained_size[0], self.panelMinHeight) )
  1422. # tab[section].SetMinSize( constrained_size )
  1423. if self.manual_tab.IsLoaded():
  1424. self.manual_tab.SetMinSize( (self.constrained_size[0], self.panelMinHeight) )
  1425. self.SetSizer( panelsizer )
  1426. panelsizer.Fit(self.notebook)
  1427. self.hasMain = tab.has_key( _('Required') ) # publish, to enclosing Frame for instance
  1428. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1429. def OnVectorFormat(self, event):
  1430. """!Change vector format (native / ogr)"""
  1431. sel = event.GetSelection()
  1432. idEvent = event.GetId()
  1433. p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
  1434. if not p:
  1435. return # should not happen
  1436. # detect windows
  1437. winNative = None
  1438. winOgr = None
  1439. for id in p['wxId']:
  1440. if id == idEvent:
  1441. continue
  1442. name = self.FindWindowById(id).GetName()
  1443. if name == 'Select':
  1444. winNative = self.FindWindowById(id + 1) # fix the mystery (also in nviz_tools.py)
  1445. elif name == 'OgrSelect':
  1446. winOgr = self.FindWindowById(id)
  1447. # enable / disable widgets & update values
  1448. rbox = self.FindWindowByName('VectorFormat')
  1449. self.hsizer.Remove(rbox)
  1450. if sel == 0: # -> native
  1451. winOgr.Hide()
  1452. self.hsizer.Remove(winOgr)
  1453. self.hsizer.Add(item=winNative,
  1454. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1455. border=5)
  1456. winNative.Show()
  1457. p['value'] = winNative.GetValue()
  1458. elif sel == 1: # -> OGR
  1459. sizer = wx.BoxSizer(wx.VERTICAL)
  1460. winNative.Hide()
  1461. self.hsizer.Remove(winNative)
  1462. sizer.Add(item=winOgr)
  1463. winOgr.Show()
  1464. p['value'] = winOgr.GetDsn()
  1465. self.hsizer.Add(item=sizer,
  1466. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1467. border=5)
  1468. self.hsizer.Add(item=rbox,
  1469. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1470. wx.RIGHT | wx.ALIGN_TOP,
  1471. border=5)
  1472. self.hsizer.Layout()
  1473. self.Layout()
  1474. self.OnUpdateValues()
  1475. self.OnUpdateSelection(event)
  1476. def OnUpdateDialog(self, event):
  1477. for fn, kwargs in event.data.iteritems():
  1478. fn(**kwargs)
  1479. self.parent.updateValuesHook()
  1480. def OnVerbosity(self, event):
  1481. """!Verbosity level changed"""
  1482. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  1483. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  1484. if event.IsChecked():
  1485. if event.GetId() == verbose.GetId():
  1486. if quiet.IsChecked():
  1487. quiet.SetValue(False)
  1488. self.task.get_flag('quiet')['value'] = False
  1489. else:
  1490. if verbose.IsChecked():
  1491. verbose.SetValue(False)
  1492. self.task.get_flag('verbose')['value'] = False
  1493. event.Skip()
  1494. def OnPageChange(self, event):
  1495. if not event:
  1496. sel = self.notebook.GetSelection()
  1497. else:
  1498. sel = event.GetSelection()
  1499. if hasattr(self, "manual_tab_id") and \
  1500. sel == self.manual_tab_id:
  1501. # calling LoadPage() is strangely time-consuming (only first call)
  1502. # FIXME: move to helpPage.__init__()
  1503. if not self.manual_tab.IsLoaded():
  1504. wx.Yield()
  1505. self.manual_tab.LoadPage()
  1506. self.Layout()
  1507. def OnColorChange( self, event ):
  1508. myId = event.GetId()
  1509. for p in self.task.params:
  1510. if 'wxId' in p and myId in p['wxId']:
  1511. has_button = p['wxId'][1] is not None
  1512. if has_button and wx.FindWindowById( p['wxId'][1] ).GetValue() == True:
  1513. p[ 'value' ] = 'none'
  1514. else:
  1515. colorchooser = wx.FindWindowById( p['wxId'][0] )
  1516. new_color = colorchooser.GetValue()[:]
  1517. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1518. # under wx2.8.1
  1519. new_label = rgb2str.get( new_color, ':'.join(map(str,new_color)) )
  1520. colorchooser.SetLabel( new_label )
  1521. colorchooser.SetColour( new_color )
  1522. colorchooser.Refresh()
  1523. p[ 'value' ] = colorchooser.GetLabel()
  1524. self.OnUpdateValues()
  1525. def OnUpdateValues(self):
  1526. """
  1527. If we were part of a richer interface, report back the current command being built.
  1528. This method should be set by the parent of this panel if needed. It's a hook, actually.
  1529. Beware of what is 'self' in 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['parametrized'] = me.IsChecked()
  1583. else:
  1584. porf['value'] = me.GetValue()
  1585. self.OnUpdateValues()
  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):
  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:
  1755. self.mf.CentreOnParent()
  1756. self.mf.Show(show)
  1757. self.mf.MakeModal(modal)
  1758. else:
  1759. self.mf.OnApply(None)
  1760. self.cmd = cmd
  1761. return self.grass_task
  1762. def GetCommandInputMapParamKey(self, cmd):
  1763. """!Get parameter key for input raster/vector map
  1764. @param cmd module name
  1765. @return parameter key
  1766. @return None on failure
  1767. """
  1768. # parse the interface decription
  1769. if not self.grass_task:
  1770. tree = etree.fromstring(getInterfaceDescription(cmd))
  1771. self.grass_task = processTask(tree).GetTask()
  1772. for p in self.grass_task.params:
  1773. if p.get('name', '') in ('input', 'map'):
  1774. age = p.get('age', '')
  1775. prompt = p.get('prompt', '')
  1776. element = p.get('element', '')
  1777. if age == 'old' and \
  1778. element in ('cell', 'grid3', 'vector') and \
  1779. prompt in ('raster', '3d-raster', 'vector'):
  1780. return p.get('name', None)
  1781. return None
  1782. if __name__ == "__main__":
  1783. if len(sys.argv) == 1:
  1784. sys.exit(_("usage: %s <grass command>") % sys.argv[0])
  1785. if sys.argv[1] != 'test':
  1786. q = wx.LogNull()
  1787. cmd = shlex.split(sys.argv[1])
  1788. task = grassTask(cmd[0])
  1789. task.set_options(cmd[1:])
  1790. app = GrassGUIApp(task)
  1791. app.MainLoop()
  1792. else: #Test
  1793. # Test grassTask from within a GRASS session
  1794. if os.getenv("GISBASE") is not None:
  1795. task = grassTask( "d.vect" )
  1796. task.get_param('map')['value'] = "map_name"
  1797. task.get_flag('v')['value'] = True
  1798. task.get_param('layer')['value'] = 1
  1799. task.get_param('bcolor')['value'] = "red"
  1800. assert ' '.join( task.getCmd() ) == "d.vect -v map=map_name layer=1 bcolor=red"
  1801. # Test interface building with handmade grassTask,
  1802. # possibly outside of a GRASS session.
  1803. task = grassTask()
  1804. task.name = "TestTask"
  1805. task.description = "This is an artificial grassTask() object intended for testing purposes."
  1806. task.keywords = ["grass","test","task"]
  1807. task.params = [
  1808. {
  1809. "name" : "text",
  1810. "description" : "Descriptions go into tooltips if labels are present, like this one",
  1811. "label" : "Enter some text",
  1812. },{
  1813. "name" : "hidden_text",
  1814. "description" : "This text should not appear in the form",
  1815. "hidden" : "yes"
  1816. },{
  1817. "name" : "text_default",
  1818. "description" : "Enter text to override the default",
  1819. "default" : "default text"
  1820. },{
  1821. "name" : "text_prefilled",
  1822. "description" : "You should see a friendly welcome message here",
  1823. "value" : "hello, world"
  1824. },{
  1825. "name" : "plain_color",
  1826. "description" : "This is a plain color, and it is a compulsory parameter",
  1827. "required" : "yes",
  1828. "gisprompt" : True,
  1829. "prompt" : "color"
  1830. },{
  1831. "name" : "transparent_color",
  1832. "description" : "This color becomes transparent when set to none",
  1833. "guisection" : "tab",
  1834. "gisprompt" : True,
  1835. "prompt" : "color"
  1836. },{
  1837. "name" : "multi",
  1838. "description" : "A multiple selection",
  1839. 'default': u'red,green,blue',
  1840. 'gisprompt': False,
  1841. 'guisection': 'tab',
  1842. 'multiple': u'yes',
  1843. 'type': u'string',
  1844. 'value': '',
  1845. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other']
  1846. },{
  1847. "name" : "single",
  1848. "description" : "A single multiple-choice selection",
  1849. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  1850. "guisection" : "tab"
  1851. },{
  1852. "name" : "large_multi",
  1853. "description" : "A large multiple selection",
  1854. "gisprompt" : False,
  1855. "multiple" : "yes",
  1856. # values must be an array of strings
  1857. "values" : str2rgb.keys() + map( str, str2rgb.values() )
  1858. },{
  1859. "name" : "a_file",
  1860. "description" : "A file selector",
  1861. "gisprompt" : True,
  1862. "element" : "file"
  1863. }
  1864. ]
  1865. task.flags = [
  1866. {
  1867. "name" : "a",
  1868. "description" : "Some flag, will appear in Main since it is required",
  1869. "required" : "yes"
  1870. },{
  1871. "name" : "b",
  1872. "description" : "pre-filled flag, will appear in options since it is not required",
  1873. "value" : True
  1874. },{
  1875. "name" : "hidden_flag",
  1876. "description" : "hidden flag, should not be changeable",
  1877. "hidden" : "yes",
  1878. "value" : True
  1879. }
  1880. ]
  1881. q=wx.LogNull()
  1882. GrassGUIApp( task ).MainLoop()