menuform.py 99 KB

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