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