menuform.py 85 KB

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