menuform.py 88 KB

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