menuform.py 102 KB

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