menuform.py 86 KB

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