menuform.py 92 KB

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