menuform.py 102 KB

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