menuform.py 101 KB

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