menuform.py 87 KB

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