menuform.py 86 KB

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