menuform.py 88 KB

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