menuform.py 89 KB

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