menuform.py 86 KB

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