menuform.py 102 KB

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