menuform.py 86 KB

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