menuform.py 87 KB

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