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