menuform.py 92 KB

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