menuform.py 76 KB

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