menuform.py 89 KB

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