menuform.py 101 KB

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