menuform.py 88 KB

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