menuform.py 89 KB

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