menuform.py 91 KB

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