menuform.py 99 KB

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