menuform.py 89 KB

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