menuform.py 94 KB

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