menuform.py 93 KB

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