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. if self.notebookpanel.notebook.GetSelection() != self.notebookpanel.notebook.GetPageIndexByName('output'):
  852. self.notebookpanel.notebook.SetSelectionByName('output')
  853. try:
  854. if self.task.path:
  855. cmd[0] = self.task.path # full path
  856. self.goutput.RunCmd(cmd, onDone = self.OnDone)
  857. except AttributeError, e:
  858. print >> sys.stderr, "%s: Propably not running in wxgui.py session?" % (e)
  859. print >> sys.stderr, "parent window is: %s" % (str(self.parent))
  860. else:
  861. gcmd.Command(cmd)
  862. # update buttons status
  863. for btn in (self.btn_run,
  864. self.btn_cancel,
  865. self.btn_clipboard,
  866. self.btn_help):
  867. btn.Enable(False)
  868. def OnAbort(self, event):
  869. """!Abort running command"""
  870. event = goutput.wxCmdAbort(aborted = True)
  871. wx.PostEvent(self.goutput, event)
  872. def OnCopy(self, event):
  873. """!Copy the command"""
  874. cmddata = wx.TextDataObject()
  875. # list -> string
  876. cmdstring = ' '.join(self.createCmd(ignoreErrors = True))
  877. cmddata.SetText(cmdstring)
  878. if wx.TheClipboard.Open():
  879. # wx.TheClipboard.UsePrimarySelection(True)
  880. wx.TheClipboard.SetData(cmddata)
  881. wx.TheClipboard.Close()
  882. self.SetStatusText(_("'%s' copied to clipboard") % \
  883. (cmdstring))
  884. def OnCancel(self, event):
  885. """!Cancel button pressed"""
  886. self.MakeModal(False)
  887. if self.get_dcmd and \
  888. self.parent and \
  889. self.parent.GetName() in ('LayerTree',
  890. 'MapWindow'):
  891. # display decorations and
  892. # pressing OK or cancel after setting layer properties
  893. if self.task.name in ['d.barscale','d.legend','d.histogram'] \
  894. or len(self.parent.GetPyData(self.layer)[0]['cmd']) >= 1:
  895. self.Hide()
  896. # canceled layer with nothing set
  897. elif len(self.parent.GetPyData(self.layer)[0]['cmd']) < 1:
  898. self.parent.Delete(self.layer)
  899. self.Destroy()
  900. else:
  901. # cancel for non-display commands
  902. self.Destroy()
  903. def OnHelp(self, event):
  904. """!Show manual page (switch to the 'Manual' notebook page)"""
  905. if self.notebookpanel.notebook.GetPageIndexByName('manual') > -1:
  906. self.notebookpanel.notebook.SetSelectionByName('manual')
  907. self.notebookpanel.OnPageChange(None)
  908. if event:
  909. event.Skip()
  910. def createCmd(self, ignoreErrors = False):
  911. """!Create command string (python list)"""
  912. return self.notebookpanel.createCmd(ignoreErrors = ignoreErrors)
  913. class cmdPanel(wx.Panel):
  914. """!A panel containing a notebook dividing in tabs the different
  915. guisections of the GRASS cmd.
  916. """
  917. def __init__(self, parent, task, id = wx.ID_ANY, mainFrame = None, *args, **kwargs):
  918. if mainFrame:
  919. self.parent = mainFrame
  920. else:
  921. self.parent = parent
  922. self.task = task
  923. wx.Panel.__init__(self, parent, id = id, *args, **kwargs)
  924. # Determine tab layout
  925. sections = []
  926. is_section = {}
  927. not_hidden = [ p for p in self.task.params + self.task.flags if not p.get('hidden', False) == True ]
  928. self.label_id = [] # wrap titles on resize
  929. self.Bind(wx.EVT_SIZE, self.OnSize)
  930. for task in not_hidden:
  931. if task.get('required', False):
  932. # All required go into Main, even if they had defined another guisection
  933. task['guisection'] = _('Required')
  934. if task.get('guisection','') == '':
  935. # Undefined guisections end up into Options
  936. task['guisection'] = _('Optional')
  937. if task['guisection'] not in is_section:
  938. # We do it like this to keep the original order, except for Main which goes first
  939. is_section[task['guisection']] = 1
  940. sections.append(task['guisection'])
  941. else:
  942. is_section[ task['guisection'] ] += 1
  943. del is_section
  944. # 'Required' tab goes first, 'Optional' as the last one
  945. for (newidx,content) in [ (0,_('Required')), (len(sections)-1,_('Optional')) ]:
  946. if content in sections:
  947. idx = sections.index(content)
  948. sections[idx:idx+1] = []
  949. sections[newidx:newidx] = [content]
  950. panelsizer = wx.BoxSizer(orient = wx.VERTICAL)
  951. # Build notebook
  952. self.notebook = GNotebook(self, style = globalvar.FNPageStyle)
  953. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  954. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  955. tab = {}
  956. tabsizer = {}
  957. for section in sections:
  958. tab[section] = scrolled.ScrolledPanel(parent = self.notebook)
  959. tab[section].SetScrollRate(10, 10)
  960. tabsizer[section] = wx.BoxSizer(orient = wx.VERTICAL)
  961. self.notebook.AddPage(page = tab[section], text = section)
  962. # are we running from command line?
  963. ### add 'command output' tab regardless standalone dialog
  964. if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
  965. self.goutput = goutput.GMConsole(parent = self, margin = False)
  966. self.outpage = self.notebook.AddPage(page = self.goutput, text = _("Command output"), name = 'output')
  967. else:
  968. self.goutput = None
  969. self.manual_tab = HelpPanel(parent = self, grass_command = self.task.name)
  970. if not self.manual_tab.IsFile():
  971. self.manual_tab.Hide()
  972. else:
  973. self.notebook.AddPage(page = self.manual_tab, text = _("Manual"), name = 'manual')
  974. self.notebook.SetSelection(0)
  975. panelsizer.Add(item = self.notebook, proportion = 1, flag = wx.EXPAND)
  976. #
  977. # flags
  978. #
  979. text_style = wx.FONTWEIGHT_NORMAL
  980. visible_flags = [ f for f in self.task.flags if not f.get('hidden', False) == True ]
  981. for f in visible_flags:
  982. which_sizer = tabsizer[ f['guisection'] ]
  983. which_panel = tab[ f['guisection'] ]
  984. # if label is given: description -> tooltip
  985. if f.get('label','') != '':
  986. title = text_beautify(f['label'])
  987. tooltip = text_beautify(f['description'], width = -1)
  988. else:
  989. title = text_beautify(f['description'])
  990. tooltip = None
  991. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  992. rtitle_txt = wx.StaticText(parent = which_panel,
  993. label = '(' + f['name'] + ')')
  994. chk = wx.CheckBox(parent = which_panel, label = title, style = wx.NO_BORDER)
  995. self.label_id.append(chk.GetId())
  996. if tooltip:
  997. chk.SetToolTipString(tooltip)
  998. chk.SetValue(f.get('value', False))
  999. title_sizer.Add(item = chk, proportion = 1,
  1000. flag = wx.EXPAND)
  1001. title_sizer.Add(item = rtitle_txt, proportion = 0,
  1002. flag = wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
  1003. which_sizer.Add(item = title_sizer, proportion = 0,
  1004. flag = wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border = 5)
  1005. f['wxId'] = [ chk.GetId(), ]
  1006. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1007. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  1008. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1009. label = _("Parameterized in model"))
  1010. parChk.SetName('ModelParam')
  1011. parChk.SetValue(f.get('parameterized', False))
  1012. if 'wxId' in f:
  1013. f['wxId'].append(parChk.GetId())
  1014. else:
  1015. f['wxId'] = [ parChk.GetId() ]
  1016. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1017. which_sizer.Add(item = parChk, proportion = 0,
  1018. flag = wx.LEFT, border = 20)
  1019. if f['name'] in ('verbose', 'quiet'):
  1020. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  1021. vq = UserSettings.Get(group = 'cmd', key = 'verbosity', subkey = 'selection')
  1022. if f['name'] == vq:
  1023. chk.SetValue(True)
  1024. f['value'] = True
  1025. elif f['name'] == 'overwrite' and 'value' not in f:
  1026. chk.SetValue(UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'))
  1027. f['value'] = UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled')
  1028. #
  1029. # parameters
  1030. #
  1031. visible_params = [ p for p in self.task.params if not p.get('hidden', False) == True ]
  1032. try:
  1033. first_param = visible_params[0]
  1034. except IndexError:
  1035. first_param = None
  1036. for p in visible_params:
  1037. which_sizer = tabsizer[ p['guisection'] ]
  1038. which_panel = tab[ p['guisection'] ]
  1039. # if label is given -> label and description -> tooltip
  1040. # otherwise description -> lavel
  1041. if p.get('label','') != '':
  1042. title = text_beautify(p['label'])
  1043. tooltip = text_beautify(p['description'], width = -1)
  1044. else:
  1045. title = text_beautify(p['description'])
  1046. tooltip = None
  1047. txt = None
  1048. # text style (required -> bold)
  1049. if not p.get('required', False):
  1050. text_style = wx.FONTWEIGHT_NORMAL
  1051. else:
  1052. text_style = wx.FONTWEIGHT_BOLD
  1053. # title sizer (description, name, type)
  1054. if (len(p.get('values', [])) > 0) and \
  1055. p.get('multiple', False) and \
  1056. p.get('gisprompt',False) == False and \
  1057. p.get('type', '') == 'string':
  1058. title_txt = wx.StaticBox(parent = which_panel, id = wx.ID_ANY)
  1059. else:
  1060. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  1061. title_txt = wx.StaticText(parent = which_panel)
  1062. if p['key_desc']:
  1063. ltype = ','.join(p['key_desc'])
  1064. else:
  1065. ltype = p['type']
  1066. rtitle_txt = wx.StaticText(parent = which_panel,
  1067. label = '(' + p['name'] + '=' + ltype + ')')
  1068. title_sizer.Add(item = title_txt, proportion = 1,
  1069. flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
  1070. title_sizer.Add(item = rtitle_txt, proportion = 0,
  1071. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  1072. which_sizer.Add(item = title_sizer, proportion = 0,
  1073. flag = wx.EXPAND)
  1074. self.label_id.append(title_txt.GetId())
  1075. # title expansion
  1076. if p.get('multiple', False) and len(p.get('values','')) == 0:
  1077. title = _("[multiple]") + " " + title
  1078. if p.get('value','') == '' :
  1079. p['value'] = p.get('default','')
  1080. if (len(p.get('values', [])) > 0):
  1081. valuelist = map(str, p.get('values',[]))
  1082. valuelist_desc = map(unicode, p.get('values_desc',[]))
  1083. if p.get('multiple', False) and \
  1084. p.get('gisprompt',False) == False and \
  1085. p.get('type', '') == 'string':
  1086. title_txt.SetLabel(" %s: (%s, %s) " % (title, p['name'], p['type']))
  1087. if valuelist_desc:
  1088. hSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.VERTICAL)
  1089. else:
  1090. hSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.HORIZONTAL)
  1091. isEnabled = {}
  1092. # copy default values
  1093. if p['value'] == '':
  1094. p['value'] = p.get('default', '')
  1095. for defval in p.get('value', '').split(','):
  1096. isEnabled[ defval ] = 'yes'
  1097. # for multi checkboxes, this is an array of all wx IDs
  1098. # for each individual checkbox
  1099. p[ 'wxId' ] = list()
  1100. idx = 0
  1101. for val in valuelist:
  1102. try:
  1103. label = valuelist_desc[idx]
  1104. except IndexError:
  1105. label = val
  1106. chkbox = wx.CheckBox(parent = which_panel,
  1107. label = text_beautify(label))
  1108. p[ 'wxId' ].append(chkbox.GetId())
  1109. if val in isEnabled:
  1110. chkbox.SetValue(True)
  1111. hSizer.Add(item = chkbox, proportion = 0,
  1112. flag = wx.ADJUST_MINSIZE | wx.ALL, border = 1)
  1113. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  1114. idx += 1
  1115. which_sizer.Add(item = hSizer, proportion = 0,
  1116. flag = wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border = 5)
  1117. elif p.get('gisprompt', False) == False:
  1118. if len(valuelist) == 1: # -> textctrl
  1119. title_txt.SetLabel("%s (%s %s):" % (title, _('valid range'),
  1120. str(valuelist[0])))
  1121. if p.get('type', '') == 'integer' and \
  1122. not p.get('multiple', False):
  1123. # for multiple integers use textctrl instead of spinsctrl
  1124. try:
  1125. minValue, maxValue = map(int, valuelist[0].split('-'))
  1126. except ValueError:
  1127. minValue = -1e6
  1128. maxValue = 1e6
  1129. txt2 = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY, size = globalvar.DIALOG_SPIN_SIZE,
  1130. min = minValue, max = maxValue)
  1131. txt2.SetName("SpinCtrl")
  1132. style = wx.BOTTOM | wx.LEFT
  1133. else:
  1134. txt2 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  1135. txt2.SetName("TextCtrl")
  1136. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  1137. value = self._getValue(p)
  1138. # parameter previously set
  1139. if value:
  1140. if txt2.GetName() == "SpinCtrl":
  1141. txt2.SetValue(int(value))
  1142. else:
  1143. txt2.SetValue(value)
  1144. which_sizer.Add(item = txt2, proportion = 0,
  1145. flag = style, border = 5)
  1146. p['wxId'] = [ txt2.GetId(), ]
  1147. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  1148. else:
  1149. # list of values (combo)
  1150. title_txt.SetLabel(title + ':')
  1151. cb = wx.ComboBox(parent = which_panel, id = wx.ID_ANY, value = p.get('default',''),
  1152. size = globalvar.DIALOG_COMBOBOX_SIZE,
  1153. choices = valuelist, style = wx.CB_DROPDOWN)
  1154. value = self._getValue(p)
  1155. if value:
  1156. cb.SetValue(value) # parameter previously set
  1157. which_sizer.Add(item = cb, proportion = 0,
  1158. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1159. p['wxId'] = [cb.GetId(),]
  1160. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1161. cb.Bind(wx.EVT_TEXT, self.OnSetValue)
  1162. # text entry
  1163. if (p.get('type','string') in ('string','integer','float')
  1164. and len(p.get('values',[])) == 0
  1165. and p.get('gisprompt',False) == False
  1166. and p.get('prompt','') != 'color'):
  1167. title_txt.SetLabel(title + ':')
  1168. if p.get('multiple', False) or \
  1169. p.get('type', 'string') == 'string' or \
  1170. len(p.get('key_desc', [])) > 1:
  1171. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  1172. value = self._getValue(p)
  1173. if value:
  1174. # parameter previously set
  1175. txt3.SetValue(str(value))
  1176. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  1177. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  1178. else:
  1179. minValue = -1e9
  1180. maxValue = 1e9
  1181. if p.get('type', '') == 'integer':
  1182. txt3 = wx.SpinCtrl(parent = which_panel, value = p.get('default',''),
  1183. size = globalvar.DIALOG_SPIN_SIZE,
  1184. min = minValue, max = maxValue)
  1185. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1186. value = self._getValue(p)
  1187. if value:
  1188. txt3.SetValue(int(value)) # parameter previously set
  1189. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1190. else:
  1191. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1192. validator = FloatValidator())
  1193. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  1194. value = self._getValue(p)
  1195. if value:
  1196. txt3.SetValue(str(value)) # parameter previously set
  1197. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  1198. which_sizer.Add(item = txt3, proportion = 0,
  1199. flag = style, border = 5)
  1200. p['wxId'] = [ txt3.GetId(), ]
  1201. #
  1202. # element selection tree combobox (maps, icons, regions, etc.)
  1203. #
  1204. if p.get('gisprompt', False) == True:
  1205. title_txt.SetLabel(title + ':')
  1206. # GIS element entry
  1207. if p.get('prompt','') not in ('color',
  1208. 'color_none',
  1209. 'subgroup',
  1210. 'dbdriver',
  1211. 'dbname',
  1212. 'dbtable',
  1213. 'dbcolumn',
  1214. 'layer',
  1215. 'layer_all',
  1216. 'location',
  1217. 'mapset',
  1218. 'dbase') and \
  1219. p.get('element', '') != 'file':
  1220. multiple = p.get('multiple', False)
  1221. if p.get('age', '') == 'new':
  1222. mapsets = [grass.gisenv()['MAPSET'],]
  1223. else:
  1224. mapsets = None
  1225. if self.task.name in ('r.proj', 'v.proj') \
  1226. and p.get('name', '') == 'input':
  1227. if self.task.name == 'r.proj':
  1228. isRaster = True
  1229. else:
  1230. isRaster = False
  1231. selection = gselect.ProjSelect(parent = which_panel,
  1232. isRaster = isRaster)
  1233. p['wxId'] = [ selection.GetId(), ]
  1234. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1235. formatSelector = False
  1236. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1237. else:
  1238. selection = gselect.Select(parent = which_panel, id = wx.ID_ANY,
  1239. size = globalvar.DIALOG_GSELECT_SIZE,
  1240. type = p.get('element', ''),
  1241. multiple = multiple, mapsets = mapsets)
  1242. value = self._getValue(p)
  1243. if value:
  1244. selection.SetValue(value)
  1245. formatSelector = True
  1246. # A select.Select is a combobox with two children: a textctl and a popupwindow;
  1247. # we target the textctl here
  1248. textWin = selection.GetTextCtrl()
  1249. p['wxId'] = [ textWin.GetId(), ]
  1250. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1251. if p.get('prompt', '') == 'vector':
  1252. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1253. if formatSelector and p.get('age', 'old') == 'old':
  1254. # OGR supported (read-only)
  1255. self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  1256. self.hsizer.Add(item = selection,
  1257. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1258. border = 5)
  1259. # format (native / ogr)
  1260. rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  1261. label = " %s " % _("Format"),
  1262. style = wx.RA_SPECIFY_ROWS,
  1263. choices = [_("Native / Linked OGR"), _("Direct OGR")])
  1264. if p.get('value', '').lower().rfind('@ogr') > -1:
  1265. rbox.SetSelection(1)
  1266. rbox.SetName('VectorFormat')
  1267. rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  1268. self.hsizer.Add(item = rbox,
  1269. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1270. wx.RIGHT | wx.ALIGN_TOP,
  1271. border = 5)
  1272. ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  1273. default = 'dir',
  1274. exclude = ['file'])
  1275. self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  1276. self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  1277. ogrSelection.SetName('OgrSelect')
  1278. ogrSelection.Hide()
  1279. which_sizer.Add(item = self.hsizer, proportion = 0)
  1280. p['wxId'].append(rbox.GetId())
  1281. p['wxId'].append(ogrSelection.GetId())
  1282. for win in ogrSelection.GetDsnWin():
  1283. p['wxId'].append(win.GetId())
  1284. else:
  1285. which_sizer.Add(item = selection, proportion = 0,
  1286. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1287. border = 5)
  1288. elif p.get('prompt', '') == 'group':
  1289. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1290. which_sizer.Add(item = selection, proportion = 0,
  1291. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1292. border = 5)
  1293. else:
  1294. which_sizer.Add(item = selection, proportion = 0,
  1295. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1296. border = 5)
  1297. # subgroup
  1298. elif p.get('prompt', '') == 'subgroup':
  1299. selection = gselect.SubGroupSelect(parent = which_panel)
  1300. p['wxId'] = [ selection.GetId() ]
  1301. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1302. which_sizer.Add(item = selection, proportion = 0,
  1303. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1304. border = 5)
  1305. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1306. elif p.get('prompt', '') in ('dbdriver',
  1307. 'dbname',
  1308. 'dbtable',
  1309. 'dbcolumn',
  1310. 'layer',
  1311. 'layer_all',
  1312. 'location',
  1313. 'mapset',
  1314. 'dbase'):
  1315. if p.get('multiple', 'no') == 'yes':
  1316. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1317. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1318. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1319. else:
  1320. value = p.get('value', '')
  1321. if not value:
  1322. value = p.get('default', '')
  1323. if p.get('prompt', '') in ('layer',
  1324. 'layer_all'):
  1325. if p.get('prompt', '') == 'layer_all':
  1326. all = True
  1327. else:
  1328. all = False
  1329. win = wx.BoxSizer(wx.HORIZONTAL)
  1330. if p.get('age', 'old') == 'old':
  1331. win1 = gselect.LayerSelect(parent = which_panel,
  1332. all = all,
  1333. default = p['default'])
  1334. win1.Bind(wx.EVT_CHOICE, self.OnUpdateSelection)
  1335. win1.Bind(wx.EVT_CHOICE, self.OnSetValue)
  1336. else:
  1337. win1 = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY,
  1338. min = 1, max = 100, initial = int(p['default']))
  1339. win1.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1340. win2 = gselect.LayerNameSelect(parent = which_panel)
  1341. if p.get('value','') != '':
  1342. win2.SetItems([p['value']])
  1343. win2.SetSelection(0)
  1344. win2.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1345. p['wxId'] = [ win1.GetId(), win2.GetId() ]
  1346. win.Add(item = win1, proportion = 0)
  1347. win.Add(item = win2, proportion = 0,
  1348. flag = wx.LEFT | wx.ALIGN_CENTER_VERTICAL,
  1349. border = 5)
  1350. elif p.get('prompt', '') == 'dbdriver':
  1351. win = gselect.DriverSelect(parent = which_panel,
  1352. choices = p.get('values', []),
  1353. value = value)
  1354. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1355. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1356. elif p.get('prompt', '') == 'dbname':
  1357. win = gselect.DatabaseSelect(parent = which_panel,
  1358. value = value)
  1359. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1360. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1361. elif p.get('prompt', '') == 'dbtable':
  1362. if p.get('age', 'old') == 'old':
  1363. win = gselect.TableSelect(parent = which_panel)
  1364. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1365. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1366. else:
  1367. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1368. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1369. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1370. elif p.get('prompt', '') == 'dbcolumn':
  1371. win = gselect.ColumnSelect(parent = which_panel,
  1372. value = value,
  1373. param = p)
  1374. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1375. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1376. elif p.get('prompt', '') == 'location':
  1377. win = gselect.LocationSelect(parent = which_panel,
  1378. value = value)
  1379. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1380. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1381. elif p.get('prompt', '') == 'mapset':
  1382. win = gselect.MapsetSelect(parent = which_panel,
  1383. value = value)
  1384. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1385. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1386. elif p.get('prompt', '') == 'dbase':
  1387. win = gselect.DbaseSelect(parent = which_panel,
  1388. changeCallback = self.OnSetValue)
  1389. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1390. p['wxId'] = [ win.GetChildren()[1].GetId() ]
  1391. if 'wxId' not in p:
  1392. try:
  1393. p['wxId'] = [ win.GetId(), ]
  1394. except AttributeError:
  1395. pass
  1396. which_sizer.Add(item = win, proportion = 0,
  1397. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1398. # color entry
  1399. elif p.get('prompt', '') in ('color',
  1400. 'color_none'):
  1401. default_color = (200,200,200)
  1402. label_color = _("Select Color")
  1403. if p.get('default','') != '':
  1404. default_color, label_color = color_resolve(p['default'])
  1405. if p.get('value','') != '': # parameter previously set
  1406. default_color, label_color = color_resolve(p['value'])
  1407. if p.get('prompt', '') == 'color_none':
  1408. this_sizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1409. else:
  1410. this_sizer = which_sizer
  1411. btn_colour = csel.ColourSelect(parent = which_panel, id = wx.ID_ANY,
  1412. label = label_color, colour = default_color,
  1413. pos = wx.DefaultPosition, size = (150,-1))
  1414. this_sizer.Add(item = btn_colour, proportion = 0,
  1415. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1416. # For color selectors, this is a two-member array, holding the IDs of
  1417. # the selector proper and either a "transparent" button or None
  1418. p['wxId'] = [btn_colour.GetId(),]
  1419. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1420. if p.get('prompt', '') == 'color_none':
  1421. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent"))
  1422. if p.get('value','') != '' and p.get('value',[''])[0] == "none":
  1423. none_check.SetValue(True)
  1424. else:
  1425. none_check.SetValue(False)
  1426. this_sizer.Add(item = none_check, proportion = 0,
  1427. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border = 5)
  1428. which_sizer.Add(this_sizer)
  1429. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1430. p['wxId'].append(none_check.GetId())
  1431. else:
  1432. p['wxId'].append(None)
  1433. # file selector
  1434. elif p.get('prompt','') != 'color' and p.get('element', '') == 'file':
  1435. fbb = filebrowse.FileBrowseButton(parent = which_panel, id = wx.ID_ANY, fileMask = '*',
  1436. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1437. dialogTitle = _('Choose %s') % \
  1438. p.get('description',_('File')),
  1439. buttonText = _('Browse'),
  1440. startDirectory = os.getcwd(), fileMode = 0,
  1441. changeCallback = self.OnSetValue)
  1442. value = self._getValue(p)
  1443. if value:
  1444. fbb.SetValue(value) # parameter previously set
  1445. which_sizer.Add(item = fbb, proportion = 0,
  1446. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1447. # A file browse button is a combobox with two children:
  1448. # a textctl and a button;
  1449. # we have to target the button here
  1450. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1451. if p.get('age', 'new') == 'old' and \
  1452. UserSettings.Get(group = 'cmd', key = 'interactiveInput', subkey = 'enabled'):
  1453. # widget for interactive input
  1454. ifbb = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY,
  1455. style = wx.TE_MULTILINE,
  1456. size = (-1, 75))
  1457. if p.get('value', '') and os.path.isfile(p['value']):
  1458. f = open(p['value'])
  1459. ifbb.SetValue(''.join(f.readlines()))
  1460. f.close()
  1461. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1462. which_sizer.Add(item = wx.StaticText(parent = which_panel, id = wx.ID_ANY,
  1463. label = _('or enter values interactively')),
  1464. proportion = 0,
  1465. flag = wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM, border = 5)
  1466. which_sizer.Add(item = ifbb, proportion = 1,
  1467. flag = wx.EXPAND | wx.RIGHT | wx.LEFT, border = 5)
  1468. p['wxId'].append(ifbb.GetId())
  1469. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  1470. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1471. label = _("Parameterized in model"))
  1472. parChk.SetName('ModelParam')
  1473. parChk.SetValue(p.get('parameterized', False))
  1474. if 'wxId' in p:
  1475. p['wxId'].append(parChk.GetId())
  1476. else:
  1477. p['wxId'] = [ parChk.GetId() ]
  1478. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1479. which_sizer.Add(item = parChk, proportion = 0,
  1480. flag = wx.LEFT, border = 20)
  1481. if title_txt is not None:
  1482. # create tooltip if given
  1483. if len(p['values_desc']) > 0:
  1484. if tooltip:
  1485. tooltip += 2 * os.linesep
  1486. else:
  1487. tooltip = ''
  1488. if len(p['values']) == len(p['values_desc']):
  1489. for i in range(len(p['values'])):
  1490. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1491. tooltip.strip(os.linesep)
  1492. if tooltip:
  1493. title_txt.SetToolTipString(tooltip)
  1494. if p == first_param:
  1495. if 'wxId' in p and len(p['wxId']) > 0:
  1496. win = self.FindWindowById(p['wxId'][0])
  1497. win.SetFocus()
  1498. #
  1499. # set widget relations for OnUpdateSelection
  1500. #
  1501. pMap = None
  1502. pLayer = []
  1503. pDriver = None
  1504. pDatabase = None
  1505. pTable = None
  1506. pColumn = []
  1507. pGroup = None
  1508. pSubGroup = None
  1509. pDbase = None
  1510. pLocation = None
  1511. pMapset = None
  1512. for p in self.task.params:
  1513. if p.get('gisprompt', False) == False:
  1514. continue
  1515. guidep = p.get('guidependency', '')
  1516. if guidep:
  1517. # fixed options dependency defined
  1518. options = guidep.split(',')
  1519. for opt in options:
  1520. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1521. if id:
  1522. if 'wxId-bind' not in p:
  1523. p['wxId-bind'] = list()
  1524. p['wxId-bind'] += pOpt['wxId']
  1525. continue
  1526. prompt = p.get('element', '')
  1527. if prompt in ('cell', 'vector'):
  1528. name = p.get('name', '')
  1529. if name in ('map', 'input'):
  1530. pMap = p
  1531. elif prompt == 'layer':
  1532. pLayer.append(p)
  1533. elif prompt == 'dbcolumn':
  1534. pColumn.append(p)
  1535. elif prompt == 'dbdriver':
  1536. pDriver = p
  1537. elif prompt == 'dbname':
  1538. pDatabase = p
  1539. elif prompt == 'dbtable':
  1540. pTable = p
  1541. elif prompt == 'group':
  1542. pGroup = p
  1543. elif prompt == 'subgroup':
  1544. pSubGroup = p
  1545. elif prompt == 'dbase':
  1546. pDbase = p
  1547. elif prompt == 'location':
  1548. pLocation = p
  1549. elif prompt == 'mapset':
  1550. pMapset = p
  1551. # collect ids
  1552. pColumnIds = []
  1553. for p in pColumn:
  1554. pColumnIds += p['wxId']
  1555. pLayerIds = []
  1556. for p in pLayer:
  1557. pLayerIds += p['wxId']
  1558. # set wxId-bindings
  1559. if pMap:
  1560. pMap['wxId-bind'] = copy.copy(pColumnIds)
  1561. if pLayer:
  1562. pMap['wxId-bind'] += pLayerIds
  1563. if pLayer:
  1564. for p in pLayer:
  1565. p['wxId-bind'] = copy.copy(pColumnIds)
  1566. if pDriver and pTable:
  1567. pDriver['wxId-bind'] = pTable['wxId']
  1568. if pDatabase and pTable:
  1569. pDatabase['wxId-bind'] = pTable['wxId']
  1570. if pTable and pColumnIds:
  1571. pTable['wxId-bind'] = pColumnIds
  1572. if pGroup and pSubGroup:
  1573. pGroup['wxId-bind'] = pSubGroup['wxId']
  1574. if pDbase and pLocation:
  1575. pDbase['wxId-bind'] = pLocation['wxId']
  1576. if pLocation and pMapset:
  1577. pLocation['wxId-bind'] = pMapset['wxId']
  1578. if pLocation and pMapset and pMap:
  1579. pLocation['wxId-bind'] += pMap['wxId']
  1580. pMapset['wxId-bind'] = pMap['wxId']
  1581. #
  1582. # determine panel size
  1583. #
  1584. maxsizes = (0, 0)
  1585. for section in sections:
  1586. tab[section].SetSizer(tabsizer[section])
  1587. tabsizer[section].Fit(tab[section])
  1588. tab[section].Layout()
  1589. minsecsizes = tabsizer[section].GetSize()
  1590. maxsizes = map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1))
  1591. # TODO: be less arbitrary with these 600
  1592. self.panelMinHeight = 100
  1593. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1594. for section in sections:
  1595. tab[section].SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1596. if self.manual_tab.IsLoaded():
  1597. self.manual_tab.SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1598. self.SetSizer(panelsizer)
  1599. panelsizer.Fit(self.notebook)
  1600. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1601. def _getValue(self, p):
  1602. """!Get value or default value of given parameter
  1603. @param p parameter directory
  1604. """
  1605. if p.get('value', '') != '':
  1606. return p['value']
  1607. return p.get('default', '')
  1608. def OnFileText(self, event):
  1609. """File input interactively entered"""
  1610. text = event.GetString()
  1611. p = self.task.get_param(value = event.GetId(), element = 'wxId', raiseError = False)
  1612. if not p:
  1613. return # should not happen
  1614. win = self.FindWindowById(p['wxId'][0])
  1615. if text:
  1616. filename = win.GetValue()
  1617. if not filename:
  1618. # outFile = tempfile.NamedTemporaryFile(mode = 'w+b')
  1619. filename = grass.tempfile()
  1620. win.SetValue(filename)
  1621. f = open(filename, "w")
  1622. try:
  1623. f.write(text)
  1624. finally:
  1625. f.close()
  1626. else:
  1627. win.SetValue('')
  1628. def OnVectorFormat(self, event):
  1629. """!Change vector format (native / ogr)"""
  1630. sel = event.GetSelection()
  1631. idEvent = event.GetId()
  1632. p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
  1633. if not p:
  1634. return # should not happen
  1635. # detect windows
  1636. winNative = None
  1637. winOgr = None
  1638. for id in p['wxId']:
  1639. if id == idEvent:
  1640. continue
  1641. name = self.FindWindowById(id).GetName()
  1642. if name == 'Select':
  1643. winNative = self.FindWindowById(id + 1) # fix the mystery (also in nviz_tools.py)
  1644. elif name == 'OgrSelect':
  1645. winOgr = self.FindWindowById(id)
  1646. # enable / disable widgets & update values
  1647. rbox = self.FindWindowByName('VectorFormat')
  1648. self.hsizer.Remove(rbox)
  1649. if sel == 0: # -> native
  1650. winOgr.Hide()
  1651. self.hsizer.Remove(winOgr)
  1652. self.hsizer.Add(item = winNative,
  1653. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1654. border = 5)
  1655. winNative.Show()
  1656. p['value'] = winNative.GetValue()
  1657. elif sel == 1: # -> OGR
  1658. sizer = wx.BoxSizer(wx.VERTICAL)
  1659. winNative.Hide()
  1660. self.hsizer.Remove(winNative)
  1661. sizer.Add(item = winOgr)
  1662. winOgr.Show()
  1663. p['value'] = winOgr.GetDsn()
  1664. self.hsizer.Add(item = sizer,
  1665. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1666. border = 5)
  1667. self.hsizer.Add(item = rbox,
  1668. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1669. wx.RIGHT | wx.ALIGN_TOP,
  1670. border = 5)
  1671. self.hsizer.Layout()
  1672. self.Layout()
  1673. self.OnUpdateValues()
  1674. self.OnUpdateSelection(event)
  1675. def OnUpdateDialog(self, event):
  1676. for fn, kwargs in event.data.iteritems():
  1677. fn(**kwargs)
  1678. self.parent.updateValuesHook()
  1679. def OnVerbosity(self, event):
  1680. """!Verbosity level changed"""
  1681. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  1682. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  1683. if event.IsChecked():
  1684. if event.GetId() == verbose.GetId():
  1685. if quiet.IsChecked():
  1686. quiet.SetValue(False)
  1687. self.task.get_flag('quiet')['value'] = False
  1688. else:
  1689. if verbose.IsChecked():
  1690. verbose.SetValue(False)
  1691. self.task.get_flag('verbose')['value'] = False
  1692. event.Skip()
  1693. def OnPageChange(self, event):
  1694. if not event:
  1695. sel = self.notebook.GetSelection()
  1696. else:
  1697. sel = event.GetSelection()
  1698. idx = self.notebook.GetPageIndexByName('manual')
  1699. if idx > -1 and sel == idx:
  1700. # calling LoadPage() is strangely time-consuming (only first call)
  1701. # FIXME: move to helpPage.__init__()
  1702. if not self.manual_tab.IsLoaded():
  1703. wx.Yield()
  1704. self.manual_tab.LoadPage()
  1705. self.Layout()
  1706. def OnColorChange(self, event):
  1707. myId = event.GetId()
  1708. for p in self.task.params:
  1709. if 'wxId' in p and myId in p['wxId']:
  1710. has_button = p['wxId'][1] is not None
  1711. if has_button and wx.FindWindowById(p['wxId'][1]).GetValue() == True:
  1712. p[ 'value' ] = 'none'
  1713. else:
  1714. colorchooser = wx.FindWindowById(p['wxId'][0])
  1715. new_color = colorchooser.GetValue()[:]
  1716. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1717. # under wx2.8.1
  1718. new_label = rgb2str.get(new_color, ':'.join(map(str,new_color)))
  1719. colorchooser.SetLabel(new_label)
  1720. colorchooser.SetColour(new_color)
  1721. colorchooser.Refresh()
  1722. p[ 'value' ] = colorchooser.GetLabel()
  1723. self.OnUpdateValues()
  1724. def OnUpdateValues(self, event = None):
  1725. """!If we were part of a richer interface, report back the
  1726. current command being built.
  1727. This method should be set by the parent of this panel if
  1728. needed. It's a hook, actually. Beware of what is 'self' in
  1729. the method def, though. It will be called with no arguments.
  1730. """
  1731. pass
  1732. def OnCheckBoxMulti(self, event):
  1733. """!Fill the values as a ','-separated string according to
  1734. current status of the checkboxes.
  1735. """
  1736. me = event.GetId()
  1737. theParam = None
  1738. for p in self.task.params:
  1739. if 'wxId' in p and me in p['wxId']:
  1740. theParam = p
  1741. myIndex = p['wxId'].index(me)
  1742. # Unpack current value list
  1743. currentValues = {}
  1744. for isThere in theParam.get('value', '').split(','):
  1745. currentValues[isThere] = 1
  1746. theValue = theParam['values'][myIndex]
  1747. if event.Checked():
  1748. currentValues[ theValue ] = 1
  1749. else:
  1750. del currentValues[ theValue ]
  1751. # Keep the original order, so that some defaults may be recovered
  1752. currentValueList = []
  1753. for v in theParam['values']:
  1754. if v in currentValues:
  1755. currentValueList.append(v)
  1756. # Pack it back
  1757. theParam['value'] = ','.join(currentValueList)
  1758. self.OnUpdateValues()
  1759. def OnSetValue(self, event):
  1760. """!Retrieve the widget value and set the task value field
  1761. accordingly.
  1762. Use for widgets that have a proper GetValue() method, i.e. not
  1763. for selectors.
  1764. """
  1765. myId = event.GetId()
  1766. me = wx.FindWindowById(myId)
  1767. name = me.GetName()
  1768. found = False
  1769. for porf in self.task.params + self.task.flags:
  1770. if 'wxId' not in porf:
  1771. continue
  1772. if myId in porf['wxId']:
  1773. found = True
  1774. break
  1775. if not found:
  1776. return
  1777. if name in ('LayerSelect', 'DriverSelect', 'TableSelect',
  1778. 'LocationSelect', 'MapsetSelect', 'ProjSelect'):
  1779. porf['value'] = me.GetStringSelection()
  1780. elif name == 'GdalSelect':
  1781. porf['value'] = event.dsn
  1782. elif name == 'ModelParam':
  1783. porf['parameterized'] = me.IsChecked()
  1784. else:
  1785. porf['value'] = me.GetValue()
  1786. self.OnUpdateValues(event)
  1787. event.Skip()
  1788. def OnUpdateSelection(self, event):
  1789. """!Update dialog (layers, tables, columns, etc.)
  1790. """
  1791. if not hasattr(self.parent, "updateThread"):
  1792. if event:
  1793. event.Skip()
  1794. return
  1795. if event:
  1796. self.parent.updateThread.Update(UpdateDialog,
  1797. self,
  1798. event,
  1799. event.GetId(),
  1800. self.task)
  1801. else:
  1802. self.parent.updateThread.Update(UpdateDialog,
  1803. self,
  1804. None,
  1805. None,
  1806. self.task)
  1807. def createCmd(self, ignoreErrors = False):
  1808. """!Produce a command line string (list) or feeding into GRASS.
  1809. If ignoreErrors == True then it will return whatever has been
  1810. built so far, even though it would not be a correct command
  1811. for GRASS.
  1812. """
  1813. try:
  1814. cmd = self.task.getCmd(ignoreErrors = ignoreErrors)
  1815. except ValueError, err:
  1816. dlg = wx.MessageDialog(parent = self,
  1817. message = unicode(err),
  1818. caption = _("Error in %s") % self.task.name,
  1819. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1820. dlg.ShowModal()
  1821. dlg.Destroy()
  1822. cmd = None
  1823. return cmd
  1824. def OnSize(self, event):
  1825. width = event.GetSize()[0]
  1826. fontsize = self.GetFont().GetPointSize()
  1827. text_width = max(width / (fontsize - 3), 70)
  1828. for id in self.label_id:
  1829. win = self.FindWindowById(id)
  1830. label = win.GetLabel()
  1831. label_new = '\n'.join(textwrap.wrap(label, text_width))
  1832. win.SetLabel(label_new)
  1833. event.Skip()
  1834. def getInterfaceDescription(cmd):
  1835. """!Returns the XML description for the GRASS cmd.
  1836. The DTD must be located in $GISBASE/etc/grass-interface.dtd,
  1837. otherwise the parser will not succeed.
  1838. @param cmd command (name of GRASS module)
  1839. """
  1840. try:
  1841. cmdout, cmderr = grass.Popen([cmd, '--interface-description'], stdout = grass.PIPE,
  1842. stderr = grass.PIPE).communicate()
  1843. except OSError, e:
  1844. raise gcmd.GException, _("Unable to fetch interface description for command '%s'.") % cmd + \
  1845. _("Details:") + "%s" % e
  1846. if cmderr and cmderr[:7] != 'WARNING':
  1847. raise gcmd.GException, _("Unable to fetch interface description for command '%s'.") % cmd + \
  1848. _("Details:") + " %s" % cmderr
  1849. return cmdout.replace('grass-interface.dtd', os.path.join(globalvar.ETCDIR, 'grass-interface.dtd'))
  1850. class GrassGUIApp(wx.App):
  1851. """!Stand-alone GRASS command GUI
  1852. """
  1853. def __init__(self, grass_task):
  1854. self.grass_task = grass_task
  1855. wx.App.__init__(self, False)
  1856. def OnInit(self):
  1857. msg = self.grass_task.get_error_msg()
  1858. if msg:
  1859. gcmd.GError(msg + '\n\nTry to set up GRASS_ADDON_PATH variable.')
  1860. return True
  1861. self.mf = mainFrame(parent = None, ID = wx.ID_ANY, task_description = self.grass_task)
  1862. self.mf.CentreOnScreen()
  1863. self.mf.Show(True)
  1864. self.SetTopWindow(self.mf)
  1865. return True
  1866. class GUI:
  1867. def __init__(self, parent = None, show = True, modal = False,
  1868. centreOnParent = False, checkError = False):
  1869. """!Parses GRASS commands when module is imported and used from
  1870. Layer Manager.
  1871. """
  1872. self.parent = parent
  1873. self.show = show
  1874. self.modal = modal
  1875. self.centreOnParent = centreOnParent
  1876. self.checkError = checkError
  1877. self.grass_task = None
  1878. self.cmd = list()
  1879. global _ignoreBlackList
  1880. if self.parent:
  1881. _ignoreBlackList = False
  1882. else:
  1883. _ignoreBlackList = True
  1884. def GetCmd(self):
  1885. """!Get validated command"""
  1886. return self.cmd
  1887. def ParseInterface(self, cmd, parser = processTask):
  1888. """!Parse interface
  1889. @param cmd command to be parsed (given as list)
  1890. """
  1891. # enc = locale.getdefaultlocale()[1]
  1892. # if enc and enc.lower() not in ("utf8", "utf-8"):
  1893. # tree = etree.fromstring(getInterfaceDescription(cmd[0]).decode(enc).encode("utf-8"))
  1894. # else:
  1895. tree = etree.fromstring(getInterfaceDescription(cmd[0]))
  1896. return processTask(tree).GetTask()
  1897. def ParseCommand(self, cmd, gmpath = None, completed = None):
  1898. """!Parse command
  1899. Note: cmd is given as list
  1900. If command is given with options, return validated cmd list:
  1901. - add key name for first parameter if not given
  1902. - change mapname to mapname@mapset
  1903. """
  1904. start = time.time()
  1905. dcmd_params = {}
  1906. if completed == None:
  1907. get_dcmd = None
  1908. layer = None
  1909. dcmd_params = None
  1910. else:
  1911. get_dcmd = completed[0]
  1912. layer = completed[1]
  1913. if completed[2]:
  1914. dcmd_params.update(completed[2])
  1915. # parse the interface decription
  1916. self.grass_task = self.ParseInterface(cmd)
  1917. # if layer parameters previously set, re-insert them into dialog
  1918. if completed is not None:
  1919. if 'params' in dcmd_params:
  1920. self.grass_task.params = dcmd_params['params']
  1921. if 'flags' in dcmd_params:
  1922. self.grass_task.flags = dcmd_params['flags']
  1923. err = list()
  1924. # update parameters if needed && validate command
  1925. if len(cmd) > 1:
  1926. i = 0
  1927. cmd_validated = [cmd[0]]
  1928. for option in cmd[1:]:
  1929. if option[0] == '-': # flag
  1930. if option[1] == '-':
  1931. self.grass_task.set_flag(option[2:], True)
  1932. else:
  1933. self.grass_task.set_flag(option[1], True)
  1934. cmd_validated.append(option)
  1935. else: # parameter
  1936. try:
  1937. key, value = option.split('=', 1)
  1938. except:
  1939. if i == 0: # add key name of first parameter if not given
  1940. key = self.grass_task.firstParam
  1941. value = option
  1942. else:
  1943. raise gcmd.GException, _("Unable to parse command '%s'") % ' '.join(cmd)
  1944. element = self.grass_task.get_param(key, raiseError = False)
  1945. if not element:
  1946. err.append(_("%(cmd)s: parameter '%(key)s' not available") % \
  1947. { 'cmd' : cmd[0],
  1948. 'key' : key })
  1949. continue
  1950. element = element['element']
  1951. if element in ['cell', 'vector']:
  1952. # mapname -> mapname@mapset
  1953. try:
  1954. name, mapset = value.split('@')
  1955. except ValueError:
  1956. mapset = grass.find_file(value, element)['mapset']
  1957. curr_mapset = grass.gisenv()['MAPSET']
  1958. if mapset and mapset != curr_mapset:
  1959. value = value + '@' + mapset
  1960. self.grass_task.set_param(key, value)
  1961. cmd_validated.append(key + '=' + value)
  1962. i += 1
  1963. # update original command list
  1964. cmd = cmd_validated
  1965. if self.show is not None:
  1966. self.mf = mainFrame(parent = self.parent, ID = wx.ID_ANY,
  1967. task_description = self.grass_task,
  1968. get_dcmd = get_dcmd, layer = layer)
  1969. else:
  1970. self.mf = None
  1971. if get_dcmd is not None:
  1972. # update only propwin reference
  1973. get_dcmd(dcmd = None, layer = layer, params = None,
  1974. propwin = self.mf)
  1975. if self.show is not None:
  1976. self.mf.notebookpanel.OnUpdateSelection(None)
  1977. if self.show is True:
  1978. if self.parent and self.centreOnParent:
  1979. self.mf.CentreOnParent()
  1980. else:
  1981. self.mf.CenterOnScreen()
  1982. self.mf.Show(self.show)
  1983. self.mf.MakeModal(self.modal)
  1984. else:
  1985. self.mf.OnApply(None)
  1986. self.cmd = cmd
  1987. if self.checkError:
  1988. return self.grass_task, err
  1989. else:
  1990. return self.grass_task
  1991. def GetCommandInputMapParamKey(self, cmd):
  1992. """!Get parameter key for input raster/vector map
  1993. @param cmd module name
  1994. @return parameter key
  1995. @return None on failure
  1996. """
  1997. # parse the interface decription
  1998. if not self.grass_task:
  1999. tree = etree.fromstring(getInterfaceDescription(cmd))
  2000. self.grass_task = processTask(tree).GetTask()
  2001. for p in self.grass_task.params:
  2002. if p.get('name', '') in ('input', 'map'):
  2003. age = p.get('age', '')
  2004. prompt = p.get('prompt', '')
  2005. element = p.get('element', '')
  2006. if age == 'old' and \
  2007. element in ('cell', 'grid3', 'vector') and \
  2008. prompt in ('raster', '3d-raster', 'vector'):
  2009. return p.get('name', None)
  2010. return None
  2011. class FloatValidator(wx.PyValidator):
  2012. """!Validator for floating-point input"""
  2013. def __init__(self):
  2014. wx.PyValidator.__init__(self)
  2015. self.Bind(wx.EVT_TEXT, self.OnText)
  2016. def Clone(self):
  2017. """!Clone validator"""
  2018. return FloatValidator()
  2019. def Validate(self):
  2020. """Validate input"""
  2021. textCtrl = self.GetWindow()
  2022. text = textCtrl.GetValue()
  2023. if text:
  2024. try:
  2025. float(text)
  2026. except ValueError:
  2027. textCtrl.SetBackgroundColour("grey")
  2028. textCtrl.SetFocus()
  2029. textCtrl.Refresh()
  2030. return False
  2031. sysColor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW)
  2032. textCtrl.SetBackgroundColour(sysColor)
  2033. textCtrl.Refresh()
  2034. return True
  2035. def OnText(self, event):
  2036. """!Do validation"""
  2037. self.Validate()
  2038. event.Skip()
  2039. def TransferToWindow(self):
  2040. return True # Prevent wxDialog from complaining.
  2041. def TransferFromWindow(self):
  2042. return True # Prevent wxDialog from complaining.
  2043. class GNotebook(FN.FlatNotebook):
  2044. """!Generic notebook widget
  2045. """
  2046. def __init__(self, parent, style, **kwargs):
  2047. if globalvar.hasAgw:
  2048. FN.FlatNotebook.__init__(self, parent, id = wx.ID_ANY, agwStyle = style, **kwargs)
  2049. else:
  2050. FN.FlatNotebook.__init__(self, parent, id = wx.ID_ANY, style = style, **kwargs)
  2051. self.notebookPages = {}
  2052. def AddPage(self, **kwargs):
  2053. """!Add a page
  2054. """
  2055. if 'name' in kwargs:
  2056. self.notebookPages[kwargs['name']] = kwargs['page']
  2057. del kwargs['name']
  2058. super(GNotebook, self).AddPage(**kwargs)
  2059. def SetSelectionByName(self, page):
  2060. """!Set notebook
  2061. @param page names, eg. 'layers', 'console', 'search', 'pyshell', 'nviz'
  2062. """
  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()