menuform.py 85 KB

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