menuform.py 86 KB

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