menuform.py 81 KB

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