menuform.py 91 KB

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