menuform.py 95 KB

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