menuform.py 84 KB

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