menuform.py 102 KB

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