menuform.py 102 KB

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