menuform.py 95 KB

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