menuform.py 87 KB

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