menuform.py 92 KB

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