menuform.py 86 KB

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