menuform.py 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186
  1. #!/usr/bin/env python
  2. """
  3. @brief Construct simple wxPython GUI from a GRASS command interface
  4. description.
  5. Classes:
  6. - helpPanel
  7. - mainFrame
  8. - cmdPanel
  9. - GrassGUIApp
  10. - GUI
  11. - FloatValidator
  12. - GNotebook
  13. This program is just a coarse approach to automatically build a GUI
  14. from a xml-based GRASS user interface description.
  15. You need to have Python 2.4, wxPython 2.8 and python-xml.
  16. The XML stream is read from executing the command given in the
  17. command line, thus you may call it for instance this way:
  18. python <this file.py> r.basins.fill
  19. Or you set an alias or wrap the call up in a nice shell script, GUI
  20. environment ... please contribute your idea.
  21. Updated to wxPython 2.8 syntax and contrib widgets. Methods added to
  22. make it callable by gui. Method added to automatically re-run with
  23. pythonw on a Mac.
  24. @todo
  25. - verify option value types
  26. Copyright(C) 2000-2011 by the GRASS Development Team
  27. This program is free software under the GPL(>=v2) Read the file
  28. COPYING coming with GRASS for details.
  29. @author Jan-Oliver Wagner <jan@intevation.de>
  30. @author Bernhard Reiter <bernhard@intevation.de>
  31. @author Michael Barton, Arizona State University
  32. @author Daniel Calvelo <dca.gis@gmail.com>
  33. @author Martin Landa <landa.martin@gmail.com>
  34. """
  35. import sys
  36. import re
  37. import string
  38. import textwrap
  39. import os
  40. import time
  41. import types
  42. import copy
  43. import locale
  44. import types
  45. from threading import Thread
  46. import Queue
  47. import tempfile
  48. ### i18N
  49. import gettext
  50. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  51. import globalvar
  52. import wx
  53. import wx.html
  54. try:
  55. import wx.lib.agw.flatnotebook as FN
  56. except ImportError:
  57. import wx.lib.flatnotebook as FN
  58. import wx.lib.colourselect as csel
  59. import wx.lib.filebrowsebutton as filebrowse
  60. import wx.lib.scrolledpanel as scrolled
  61. from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
  62. from wx.lib.newevent import NewEvent
  63. try:
  64. import xml.etree.ElementTree as etree
  65. except ImportError:
  66. import elementtree.ElementTree as etree # Python <= 2.4
  67. import gdialogs
  68. from ghelp import HelpPanel
  69. gisbase = os.getenv("GISBASE")
  70. if gisbase is None:
  71. print >>sys.stderr, "We don't seem to be properly installed, or we are being run outside GRASS. Expect glitches."
  72. gisbase = os.path.join(os.path.dirname(sys.argv[0]), os.path.pardir)
  73. wxbase = gisbase
  74. else:
  75. wxbase = os.path.join(globalvar.ETCWXDIR)
  76. sys.path.append(wxbase)
  77. from grass.script import core as grass
  78. from grass.script import task as gtask
  79. import gselect
  80. import gcmd
  81. import goutput
  82. import utils
  83. from preferences import globalSettings as UserSettings
  84. try:
  85. import subprocess
  86. except:
  87. from compat import subprocess
  88. wxUpdateDialog, EVT_DIALOG_UPDATE = NewEvent()
  89. # From lib/gis/col_str.c, except purple which is mentioned
  90. # there but not given RGB values
  91. str2rgb = {'aqua': (100, 128, 255),
  92. 'black': (0, 0, 0),
  93. 'blue': (0, 0, 255),
  94. 'brown': (180, 77, 25),
  95. 'cyan': (0, 255, 255),
  96. 'gray': (128, 128, 128),
  97. 'green': (0, 255, 0),
  98. 'grey': (128, 128, 128),
  99. 'indigo': (0, 128, 255),
  100. 'magenta': (255, 0, 255),
  101. 'orange': (255, 128, 0),
  102. 'purple': (128, 0, 128),
  103. 'red': (255, 0, 0),
  104. 'violet': (128, 0, 255),
  105. 'white': (255, 255, 255),
  106. 'yellow': (255, 255, 0)}
  107. rgb2str = {}
  108. for (s,r) in str2rgb.items():
  109. rgb2str[ r ] = s
  110. """!Hide some options in the GUI"""
  111. #_blackList = { 'enabled' : False,
  112. # 'items' : { 'r.buffer' : {'params' : ['input', 'output'],
  113. # 'flags' : ['z', 'overwrite']}}}
  114. _blackList = { 'enabled' : False,
  115. 'items' : {} }
  116. def color_resolve(color):
  117. if len(color) > 0 and color[0] in "0123456789":
  118. rgb = tuple(map(int, color.split(':')))
  119. label = color
  120. else:
  121. # Convert color names to RGB
  122. try:
  123. rgb = str2rgb[color]
  124. label = color
  125. except KeyError:
  126. rgb = (200, 200, 200)
  127. label = _('Select Color')
  128. return (rgb, label)
  129. def text_beautify(someString , width = 70):
  130. """!Make really long texts shorter, clean up whitespace and remove
  131. trailing punctuation.
  132. """
  133. if width > 0:
  134. return escape_ampersand(string.strip(
  135. os.linesep.join(textwrap.wrap(utils.normalize_whitespace(someString), width)),
  136. ".,;:"))
  137. else:
  138. return escape_ampersand(string.strip(utils.normalize_whitespace(someString), ".,;:"))
  139. def escape_ampersand(text):
  140. """!Escapes ampersands with additional ampersand for GUI"""
  141. return string.replace(text, "&", "&&")
  142. class UpdateThread(Thread):
  143. """!Update dialog widgets in the thread"""
  144. def __init__(self, parent, event, eventId, task):
  145. Thread.__init__(self)
  146. self.parent = parent
  147. self.event = event
  148. self.eventId = eventId
  149. self.task = task
  150. self.setDaemon(True)
  151. # list of functions which updates the dialog
  152. self.data = {}
  153. def run(self):
  154. # get widget id
  155. if not self.eventId:
  156. for p in self.task.params:
  157. if p.get('gisprompt', False) == False:
  158. continue
  159. prompt = p.get('element', '')
  160. if prompt == 'vector':
  161. name = p.get('name', '')
  162. if name in ('map', 'input'):
  163. self.eventId = p['wxId'][0]
  164. if self.eventId is None:
  165. return
  166. p = self.task.get_param(self.eventId, element = 'wxId', raiseError = False)
  167. if not p or 'wxId-bind' not in p:
  168. return
  169. # get widget prompt
  170. pType = p.get('prompt', '')
  171. if not pType:
  172. return
  173. # check for map/input parameter
  174. pMap = self.task.get_param('map', raiseError = False)
  175. if not pMap:
  176. pMap = self.task.get_param('input', raiseError = False)
  177. if pMap:
  178. map = pMap.get('value', '')
  179. else:
  180. map = None
  181. # avoid running db.describe several times
  182. cparams = dict()
  183. cparams[map] = { 'dbInfo' : None,
  184. 'layers' : None, }
  185. # update reference widgets
  186. for uid in p['wxId-bind']:
  187. win = self.parent.FindWindowById(uid)
  188. name = win.GetName()
  189. map = layer = None
  190. driver = db = table = None
  191. if name in ('LayerSelect', 'ColumnSelect'):
  192. if p.get('element', '') == 'vector': # -> vector
  193. # get map name
  194. map = p.get('value', '')
  195. # get layer
  196. for bid in p['wxId-bind']:
  197. p = self.task.get_param(bid, element = 'wxId', raiseError = False)
  198. if not p:
  199. continue
  200. if p.get('element', '') == 'layer':
  201. layer = p.get('value', '')
  202. if layer != '':
  203. layer = p.get('value', '')
  204. else:
  205. layer = p.get('default', '')
  206. break
  207. elif p.get('element', '') == 'layer': # -> layer
  208. # get layer
  209. layer = p.get('value', '')
  210. if layer != '':
  211. layer = p.get('value', '')
  212. else:
  213. layer = p.get('default', '')
  214. # get map name
  215. pMap = self.task.get_param(p['wxId'][0], element = 'wxId-bind', raiseError = False)
  216. if pMap:
  217. map = pMap.get('value', '')
  218. if name == 'TableSelect' or \
  219. (name == 'ColumnSelect' and not map):
  220. pDriver = self.task.get_param('dbdriver', element = 'prompt', raiseError = False)
  221. if pDriver:
  222. driver = pDriver.get('value', '')
  223. pDb = self.task.get_param('dbname', element = 'prompt', raiseError = False)
  224. if pDb:
  225. db = pDb.get('value', '')
  226. if name == 'ColumnSelect':
  227. pTable = self.task.get_param('dbtable', element = 'element', raiseError = False)
  228. if pTable:
  229. table = pTable.get('value', '')
  230. if name == 'LayerSelect':
  231. # determine format
  232. native = True
  233. for id in pMap['wxId']:
  234. winVec = self.parent.FindWindowById(id)
  235. if winVec.GetName() == 'VectorFormat' and \
  236. winVec.GetSelection() != 0:
  237. native = False
  238. break
  239. # TODO: update only if needed
  240. if native:
  241. if map:
  242. self.data[win.InsertLayers] = { 'vector' : map }
  243. else:
  244. self.data[win.InsertLayers] = { }
  245. else:
  246. if map:
  247. self.data[win.InsertLayers] = { 'dsn' : map.rstrip('@OGR') }
  248. else:
  249. self.data[win.InsertLayers] = { }
  250. elif name == 'TableSelect':
  251. self.data[win.InsertTables] = { 'driver' : driver,
  252. 'database' : db }
  253. elif name == 'ColumnSelect':
  254. if map:
  255. if map in cparams:
  256. if not cparams[map]['dbInfo']:
  257. cparams[map]['dbInfo'] = gselect.VectorDBInfo(map)
  258. self.data[win.InsertColumns] = { 'vector' : map, 'layer' : layer,
  259. 'dbInfo' : cparams[map]['dbInfo'] }
  260. else: # table
  261. if driver and db:
  262. self.data[win.InsertTableColumns] = { 'table' : pTable.get('value'),
  263. 'driver' : driver,
  264. 'database' : db }
  265. elif pTable:
  266. self.data[win.InsertTableColumns] = { 'table' : pTable.get('value') }
  267. elif name == 'SubGroupSelect':
  268. pGroup = self.task.get_param('group', element = 'element', raiseError = False)
  269. if pGroup:
  270. self.data[win.Insert] = { 'group' : pGroup.get('value', '')}
  271. elif name == 'LocationSelect':
  272. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  273. if pDbase:
  274. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', '')}
  275. elif name == 'MapsetSelect':
  276. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  277. pLocation = self.task.get_param('location', element = 'element', raiseError = False)
  278. if pDbase and pLocation:
  279. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', ''),
  280. 'location' : pLocation.get('value', '')}
  281. elif name == 'ProjSelect':
  282. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  283. pLocation = self.task.get_param('location', element = 'element', raiseError = False)
  284. pMapset = self.task.get_param('mapset', element = 'element', raiseError = False)
  285. if pDbase and pLocation and pMapset:
  286. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', ''),
  287. 'location' : pLocation.get('value', ''),
  288. 'mapset' : pMapset.get('value', '')}
  289. def UpdateDialog(parent, event, eventId, task):
  290. return UpdateThread(parent, event, eventId, task)
  291. class UpdateQThread(Thread):
  292. """!Update dialog widgets in the thread"""
  293. requestId = 0
  294. def __init__(self, parent, requestQ, resultQ, **kwds):
  295. Thread.__init__(self, **kwds)
  296. self.parent = parent # cmdPanel
  297. self.setDaemon(True)
  298. self.requestQ = requestQ
  299. self.resultQ = resultQ
  300. self.start()
  301. def Update(self, callable, *args, **kwds):
  302. UpdateQThread.requestId += 1
  303. self.request = None
  304. self.requestQ.put((UpdateQThread.requestId, callable, args, kwds))
  305. return UpdateQThread.requestId
  306. def run(self):
  307. while True:
  308. requestId, callable, args, kwds = self.requestQ.get()
  309. requestTime = time.time()
  310. self.request = callable(*args, **kwds)
  311. self.resultQ.put((requestId, self.request.run()))
  312. if self.request:
  313. event = wxUpdateDialog(data = self.request.data)
  314. wx.PostEvent(self.parent, event)
  315. class mainFrame(wx.Frame):
  316. """!This is the Frame containing the dialog for options input.
  317. The dialog is organized in a notebook according to the guisections
  318. defined by each GRASS command.
  319. If run with a parent, it may Apply, Ok or Cancel; the latter two
  320. close the dialog. The former two trigger a callback.
  321. If run standalone, it will allow execution of the command.
  322. The command is checked and sent to the clipboard when clicking
  323. 'Copy'.
  324. """
  325. def __init__(self, parent, ID, task_description,
  326. get_dcmd = None, layer = None):
  327. self.get_dcmd = get_dcmd
  328. self.layer = layer
  329. self.task = task_description
  330. self.parent = parent # LayerTree | Modeler | None | ...
  331. if parent and parent.GetName() == 'Modeler':
  332. self.modeler = self.parent
  333. else:
  334. self.modeler = None
  335. # module name + keywords
  336. if self.task.name.split('.')[-1] in ('py', 'sh'):
  337. title = str(self.task.name.rsplit('.',1)[0])
  338. else:
  339. title = self.task.name
  340. try:
  341. if self.task.keywords != ['']:
  342. title += " [" + ', '.join(self.task.keywords) + "]"
  343. except ValueError:
  344. pass
  345. wx.Frame.__init__(self, parent = parent, id = ID, title = title,
  346. pos = wx.DefaultPosition, style = wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL,
  347. name = "MainFrame")
  348. self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
  349. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  350. # statusbar
  351. self.CreateStatusBar()
  352. # icon
  353. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_dialog.ico'), wx.BITMAP_TYPE_ICO))
  354. guisizer = wx.BoxSizer(wx.VERTICAL)
  355. # set apropriate output window
  356. if self.parent:
  357. self.standalone = False
  358. else:
  359. self.standalone = True
  360. # logo + description
  361. topsizer = wx.BoxSizer(wx.HORIZONTAL)
  362. # GRASS logo
  363. self.logo = wx.StaticBitmap(parent = self.panel,
  364. bitmap = wx.Bitmap(name = os.path.join(globalvar.ETCIMGDIR,
  365. 'grass_form.png'),
  366. type = wx.BITMAP_TYPE_PNG))
  367. topsizer.Add(item = self.logo, proportion = 0, border = 3,
  368. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL)
  369. # add module description
  370. if self.task.label:
  371. module_desc = self.task.label + ' ' + self.task.description
  372. else:
  373. module_desc = self.task.description
  374. self.description = gdialogs.StaticWrapText(parent = self.panel,
  375. label = module_desc)
  376. topsizer.Add(item = self.description, proportion = 1, border = 5,
  377. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  378. guisizer.Add(item = topsizer, proportion = 0, flag = wx.EXPAND)
  379. self.panel.SetSizerAndFit(guisizer)
  380. self.Layout()
  381. # notebooks
  382. self.notebookpanel = cmdPanel(parent = self.panel, task = self.task,
  383. mainFrame = self)
  384. self.goutput = self.notebookpanel.goutput
  385. self.notebookpanel.OnUpdateValues = self.updateValuesHook
  386. guisizer.Add(item = self.notebookpanel, proportion = 1, flag = wx.EXPAND)
  387. # status bar
  388. status_text = _("Enter parameters for '") + self.task.name + "'"
  389. try:
  390. self.task.getCmd()
  391. self.updateValuesHook()
  392. except ValueError:
  393. self.SetStatusText(status_text)
  394. # buttons
  395. btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  396. # cancel
  397. self.btn_cancel = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  398. self.btn_cancel.SetToolTipString(_("Close this window without executing the command (Ctrl+Q)"))
  399. btnsizer.Add(item = self.btn_cancel, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
  400. self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  401. if self.get_dcmd is not None: # A callback has been set up
  402. btn_apply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
  403. btn_ok = wx.Button(parent = self.panel, id = wx.ID_OK)
  404. btn_ok.SetDefault()
  405. btnsizer.Add(item = btn_apply, proportion = 0,
  406. flag = wx.ALL | wx.ALIGN_CENTER,
  407. border = 10)
  408. btnsizer.Add(item = btn_ok, proportion = 0,
  409. flag = wx.ALL | wx.ALIGN_CENTER,
  410. border = 10)
  411. btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
  412. btn_ok.Bind(wx.EVT_BUTTON, self.OnOK)
  413. else: # We're standalone
  414. # run
  415. self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label = _("&Run"))
  416. self.btn_run.SetToolTipString(_("Run the command (Ctrl+R)"))
  417. self.btn_run.SetDefault()
  418. # copy
  419. self.btn_clipboard = wx.Button(parent = self.panel, id = wx.ID_COPY, label = _("C&opy"))
  420. self.btn_clipboard.SetToolTipString(_("Copy the current command string to the clipboard (Ctrl+C)"))
  421. btnsizer.Add(item = self.btn_run, proportion = 0,
  422. flag = wx.ALL | wx.ALIGN_CENTER,
  423. border = 10)
  424. btnsizer.Add(item = self.btn_clipboard, proportion = 0,
  425. flag = wx.ALL | wx.ALIGN_CENTER,
  426. border = 10)
  427. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  428. self.btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
  429. # help
  430. self.btn_help = wx.Button(parent = self.panel, id = wx.ID_HELP)
  431. self.btn_help.SetToolTipString(_("Show manual page of the command (Ctrl+H)"))
  432. self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
  433. if self.notebookpanel.notebook.GetPageIndexByName('manual') < 0:
  434. self.btn_help.Hide()
  435. # add help button
  436. btnsizer.Add(item = self.btn_help, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
  437. guisizer.Add(item = btnsizer, proportion = 0, flag = wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT,
  438. border = 30)
  439. if self.parent and not self.modeler:
  440. addLayer = False
  441. for p in self.task.params:
  442. if p.get('age', 'old') == 'new' and \
  443. p.get('prompt', '') in ('raster', 'vector', '3d-raster'):
  444. addLayer = True
  445. if addLayer:
  446. # add newly created map into layer tree
  447. self.addbox = wx.CheckBox(parent = self.panel,
  448. label = _('Add created map(s) into layer tree'), style = wx.NO_BORDER)
  449. self.addbox.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  450. guisizer.Add(item = self.addbox, proportion = 0,
  451. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  452. border = 5)
  453. hasNew = False
  454. for p in self.task.params:
  455. if p.get('age', 'old') == 'new':
  456. hasNew = True
  457. break
  458. if self.get_dcmd is None and hasNew:
  459. # close dialog when command is terminated
  460. self.closebox = wx.CheckBox(parent = self.panel,
  461. label = _('Close dialog on finish'), style = wx.NO_BORDER)
  462. self.closebox.SetValue(UserSettings.Get(group = 'cmd', key = 'closeDlg', subkey = 'enabled'))
  463. self.closebox.SetToolTipString(_("Close dialog when command is successfully finished. "
  464. "Change this settings in Preferences dialog ('Command' tab)."))
  465. guisizer.Add(item = self.closebox, proportion = 0,
  466. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  467. border = 5)
  468. self.Bind(wx.EVT_CLOSE, self.OnCancel)
  469. self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
  470. # do layout
  471. # called automatically by SetSizer()
  472. self.panel.SetAutoLayout(True)
  473. self.panel.SetSizerAndFit(guisizer)
  474. sizeFrame = self.GetBestSize()
  475. self.SetMinSize(sizeFrame)
  476. if hasattr(self, "closebox"):
  477. scale = 0.33
  478. else:
  479. scale = 0.50
  480. self.SetSize(wx.Size(sizeFrame[0], sizeFrame[1] + scale * max(self.notebookpanel.panelMinHeight,
  481. self.notebookpanel.constrained_size[1])))
  482. # thread to update dialog
  483. # create queues
  484. self.requestQ = Queue.Queue()
  485. self.resultQ = Queue.Queue()
  486. self.updateThread = UpdateQThread(self.notebookpanel, self.requestQ, self.resultQ)
  487. self.Layout()
  488. # keep initial window size limited for small screens
  489. width, height = self.GetSizeTuple()
  490. self.SetSize(wx.Size(min(width, 650),
  491. min(height, 500)))
  492. # fix goutput's pane size
  493. if self.goutput:
  494. self.goutput.SetSashPosition(int(self.GetSize()[1] * .75))
  495. def updateValuesHook(self, event = None):
  496. """!Update status bar data"""
  497. self.SetStatusText(' '.join(self.notebookpanel.createCmd(ignoreErrors = True)))
  498. if event:
  499. event.Skip()
  500. def OnKeyUp(self, event):
  501. """!Key released (check hot-keys)"""
  502. try:
  503. kc = chr(event.GetKeyCode())
  504. except ValueError:
  505. event.Skip()
  506. return
  507. if not event.ControlDown():
  508. event.Skip()
  509. return
  510. if kc == 'Q':
  511. self.OnCancel(None)
  512. elif kc == 'S':
  513. self.OnAbort(None)
  514. elif kc == 'H':
  515. self.OnHelp(None)
  516. elif kc == 'R':
  517. self.OnRun(None)
  518. elif kc == 'C':
  519. self.OnCopy(None)
  520. event.Skip()
  521. def OnDone(self, cmd, returncode):
  522. """!This function is launched from OnRun() when command is
  523. finished
  524. @param returncode command's return code (0 for success)
  525. """
  526. if not self.parent or returncode != 0:
  527. return
  528. if self.parent.GetName() not in ('LayerTree', 'LayerManager'):
  529. return
  530. if self.parent.GetName() == 'LayerTree':
  531. display = self.parent.GetMapDisplay()
  532. else: # Layer Manager
  533. display = self.parent.GetLayerTree().GetMapDisplay()
  534. if not display or not display.IsAutoRendered():
  535. return
  536. mapLayers = map(lambda x: x.GetName(),
  537. display.GetRender().GetListOfLayers(l_type = 'raster') +
  538. display.GetRender().GetListOfLayers(l_type = 'vector'))
  539. task = GUI(show = None).ParseCommand(cmd)
  540. for p in task.get_options()['params']:
  541. if p.get('prompt', '') not in ('raster', 'vector'):
  542. continue
  543. mapName = p.get('value', '')
  544. if '@' not in mapName:
  545. mapName = mapName + '@' + grass.gisenv()['MAPSET']
  546. if mapName in mapLayers:
  547. display.GetWindow().UpdateMap(render = True)
  548. return
  549. def OnOK(self, event):
  550. """!OK button pressed"""
  551. cmd = self.OnApply(event)
  552. if cmd is not None and self.get_dcmd is not None:
  553. self.OnCancel(event)
  554. def OnApply(self, event):
  555. """!Apply the command"""
  556. if self.modeler:
  557. cmd = self.createCmd(ignoreErrors = True)
  558. else:
  559. cmd = self.createCmd()
  560. if cmd is not None and self.get_dcmd is not None:
  561. # return d.* command to layer tree for rendering
  562. self.get_dcmd(cmd, self.layer, {"params": self.task.params,
  563. "flags" : self.task.flags},
  564. self)
  565. # echo d.* command to output console
  566. # self.parent.writeDCommand(cmd)
  567. return cmd
  568. def OnRun(self, event):
  569. """!Run the command"""
  570. cmd = self.createCmd()
  571. if not cmd or len(cmd) < 1:
  572. return
  573. if self.standalone or cmd[0][0:2] != "d.":
  574. # Send any non-display command to parent window (probably wxgui.py)
  575. # put to parents switch to 'Command output'
  576. self.notebookpanel.notebook.SetSelectionByName('output')
  577. try:
  578. if self.task.path:
  579. cmd[0] = self.task.path # full path
  580. self.goutput.RunCmd(cmd, onDone = self.OnDone)
  581. except AttributeError, e:
  582. print >> sys.stderr, "%s: Probably not running in wxgui.py session?" % (e)
  583. print >> sys.stderr, "parent window is: %s" % (str(self.parent))
  584. else:
  585. gcmd.Command(cmd)
  586. # update buttons status
  587. for btn in (self.btn_run,
  588. self.btn_cancel,
  589. self.btn_clipboard,
  590. self.btn_help):
  591. btn.Enable(False)
  592. def OnAbort(self, event):
  593. """!Abort running command"""
  594. event = goutput.wxCmdAbort(aborted = True)
  595. wx.PostEvent(self.goutput, event)
  596. def OnCopy(self, event):
  597. """!Copy the command"""
  598. cmddata = wx.TextDataObject()
  599. # list -> string
  600. cmdstring = ' '.join(self.createCmd(ignoreErrors = True))
  601. cmddata.SetText(cmdstring)
  602. if wx.TheClipboard.Open():
  603. # wx.TheClipboard.UsePrimarySelection(True)
  604. wx.TheClipboard.SetData(cmddata)
  605. wx.TheClipboard.Close()
  606. self.SetStatusText(_("'%s' copied to clipboard") % \
  607. (cmdstring))
  608. def OnCancel(self, event):
  609. """!Cancel button pressed"""
  610. self.MakeModal(False)
  611. if self.get_dcmd and \
  612. self.parent and \
  613. self.parent.GetName() in ('LayerTree',
  614. 'MapWindow'):
  615. # display decorations and
  616. # pressing OK or cancel after setting layer properties
  617. if self.task.name in ['d.barscale','d.legend','d.histogram'] \
  618. or len(self.parent.GetPyData(self.layer)[0]['cmd']) >= 1:
  619. self.Hide()
  620. # canceled layer with nothing set
  621. elif len(self.parent.GetPyData(self.layer)[0]['cmd']) < 1:
  622. self.parent.Delete(self.layer)
  623. self.Destroy()
  624. else:
  625. # cancel for non-display commands
  626. self.Destroy()
  627. def OnHelp(self, event):
  628. """!Show manual page (switch to the 'Manual' notebook page)"""
  629. if self.notebookpanel.notebook.GetPageIndexByName('manual') > -1:
  630. self.notebookpanel.notebook.SetSelectionByName('manual')
  631. self.notebookpanel.OnPageChange(None)
  632. if event:
  633. event.Skip()
  634. def createCmd(self, ignoreErrors = False):
  635. """!Create command string (python list)"""
  636. return self.notebookpanel.createCmd(ignoreErrors = ignoreErrors)
  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', '') != 'file':
  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. win = gselect.MapsetSelect(parent = which_panel,
  1097. value = value)
  1098. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1099. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1100. elif p.get('prompt', '') == 'dbase':
  1101. win = gselect.DbaseSelect(parent = which_panel,
  1102. changeCallback = self.OnSetValue)
  1103. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1104. p['wxId'] = [ win.GetChildren()[1].GetId() ]
  1105. if 'wxId' not in p:
  1106. try:
  1107. p['wxId'] = [ win.GetId(), ]
  1108. except AttributeError:
  1109. pass
  1110. which_sizer.Add(item = win, proportion = 0,
  1111. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1112. # color entry
  1113. elif p.get('prompt', '') in ('color',
  1114. 'color_none'):
  1115. default_color = (200,200,200)
  1116. label_color = _("Select Color")
  1117. if p.get('default','') != '':
  1118. default_color, label_color = color_resolve(p['default'])
  1119. if p.get('value','') != '': # parameter previously set
  1120. default_color, label_color = color_resolve(p['value'])
  1121. if p.get('prompt', '') == 'color_none':
  1122. this_sizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1123. else:
  1124. this_sizer = which_sizer
  1125. btn_colour = csel.ColourSelect(parent = which_panel, id = wx.ID_ANY,
  1126. label = label_color, colour = default_color,
  1127. pos = wx.DefaultPosition, size = (150,-1))
  1128. this_sizer.Add(item = btn_colour, proportion = 0,
  1129. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1130. # For color selectors, this is a two-member array, holding the IDs of
  1131. # the selector proper and either a "transparent" button or None
  1132. p['wxId'] = [btn_colour.GetId(),]
  1133. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1134. if p.get('prompt', '') == 'color_none':
  1135. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent"))
  1136. if p.get('value','') != '' and p.get('value',[''])[0] == "none":
  1137. none_check.SetValue(True)
  1138. else:
  1139. none_check.SetValue(False)
  1140. this_sizer.Add(item = none_check, proportion = 0,
  1141. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border = 5)
  1142. which_sizer.Add(this_sizer)
  1143. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1144. p['wxId'].append(none_check.GetId())
  1145. else:
  1146. p['wxId'].append(None)
  1147. # file selector
  1148. elif p.get('prompt','') != 'color' and p.get('element', '') == 'file':
  1149. fbb = filebrowse.FileBrowseButton(parent = which_panel, id = wx.ID_ANY, fileMask = '*',
  1150. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1151. dialogTitle = _('Choose %s') % \
  1152. p.get('description',_('File')),
  1153. buttonText = _('Browse'),
  1154. startDirectory = os.getcwd(), fileMode = 0,
  1155. changeCallback = self.OnSetValue)
  1156. value = self._getValue(p)
  1157. if value:
  1158. fbb.SetValue(value) # parameter previously set
  1159. which_sizer.Add(item = fbb, proportion = 0,
  1160. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1161. # A file browse button is a combobox with two children:
  1162. # a textctl and a button;
  1163. # we have to target the button here
  1164. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1165. if p.get('age', 'new') == 'old' and \
  1166. UserSettings.Get(group = 'cmd', key = 'interactiveInput', subkey = 'enabled'):
  1167. # widget for interactive input
  1168. ifbb = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY,
  1169. style = wx.TE_MULTILINE,
  1170. size = (-1, 75))
  1171. if p.get('value', '') and os.path.isfile(p['value']):
  1172. f = open(p['value'])
  1173. ifbb.SetValue(''.join(f.readlines()))
  1174. f.close()
  1175. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1176. which_sizer.Add(item = wx.StaticText(parent = which_panel, id = wx.ID_ANY,
  1177. label = _('or enter values interactively')),
  1178. proportion = 0,
  1179. flag = wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM, border = 5)
  1180. which_sizer.Add(item = ifbb, proportion = 1,
  1181. flag = wx.EXPAND | wx.RIGHT | wx.LEFT, border = 5)
  1182. p['wxId'].append(ifbb.GetId())
  1183. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  1184. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1185. label = _("Parameterized in model"))
  1186. parChk.SetName('ModelParam')
  1187. parChk.SetValue(p.get('parameterized', False))
  1188. if 'wxId' in p:
  1189. p['wxId'].append(parChk.GetId())
  1190. else:
  1191. p['wxId'] = [ parChk.GetId() ]
  1192. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1193. which_sizer.Add(item = parChk, proportion = 0,
  1194. flag = wx.LEFT, border = 20)
  1195. if title_txt is not None:
  1196. # create tooltip if given
  1197. if len(p['values_desc']) > 0:
  1198. if tooltip:
  1199. tooltip += 2 * os.linesep
  1200. else:
  1201. tooltip = ''
  1202. if len(p['values']) == len(p['values_desc']):
  1203. for i in range(len(p['values'])):
  1204. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1205. tooltip.strip(os.linesep)
  1206. if tooltip:
  1207. title_txt.SetToolTipString(tooltip)
  1208. if p == first_param:
  1209. if 'wxId' in p and len(p['wxId']) > 0:
  1210. win = self.FindWindowById(p['wxId'][0])
  1211. win.SetFocus()
  1212. #
  1213. # set widget relations for OnUpdateSelection
  1214. #
  1215. pMap = None
  1216. pLayer = []
  1217. pDriver = None
  1218. pDatabase = None
  1219. pTable = None
  1220. pColumn = []
  1221. pGroup = None
  1222. pSubGroup = None
  1223. pDbase = None
  1224. pLocation = None
  1225. pMapset = None
  1226. for p in self.task.params:
  1227. if p.get('gisprompt', False) == False:
  1228. continue
  1229. guidep = p.get('guidependency', '')
  1230. if guidep:
  1231. # fixed options dependency defined
  1232. options = guidep.split(',')
  1233. for opt in options:
  1234. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1235. if id:
  1236. if 'wxId-bind' not in p:
  1237. p['wxId-bind'] = list()
  1238. p['wxId-bind'] += pOpt['wxId']
  1239. continue
  1240. prompt = p.get('element', '')
  1241. if prompt in ('cell', 'vector'):
  1242. name = p.get('name', '')
  1243. if name in ('map', 'input'):
  1244. pMap = p
  1245. elif prompt == 'layer':
  1246. pLayer.append(p)
  1247. elif prompt == 'dbcolumn':
  1248. pColumn.append(p)
  1249. elif prompt == 'dbdriver':
  1250. pDriver = p
  1251. elif prompt == 'dbname':
  1252. pDatabase = p
  1253. elif prompt == 'dbtable':
  1254. pTable = p
  1255. elif prompt == 'group':
  1256. pGroup = p
  1257. elif prompt == 'subgroup':
  1258. pSubGroup = p
  1259. elif prompt == 'dbase':
  1260. pDbase = p
  1261. elif prompt == 'location':
  1262. pLocation = p
  1263. elif prompt == 'mapset':
  1264. pMapset = p
  1265. # collect ids
  1266. pColumnIds = []
  1267. for p in pColumn:
  1268. pColumnIds += p['wxId']
  1269. pLayerIds = []
  1270. for p in pLayer:
  1271. pLayerIds += p['wxId']
  1272. # set wxId-bindings
  1273. if pMap:
  1274. pMap['wxId-bind'] = copy.copy(pColumnIds)
  1275. if pLayer:
  1276. pMap['wxId-bind'] += pLayerIds
  1277. if pLayer:
  1278. for p in pLayer:
  1279. p['wxId-bind'] = copy.copy(pColumnIds)
  1280. if pDriver and pTable:
  1281. pDriver['wxId-bind'] = pTable['wxId']
  1282. if pDatabase and pTable:
  1283. pDatabase['wxId-bind'] = pTable['wxId']
  1284. if pTable and pColumnIds:
  1285. pTable['wxId-bind'] = pColumnIds
  1286. if pGroup and pSubGroup:
  1287. pGroup['wxId-bind'] = pSubGroup['wxId']
  1288. if pDbase and pLocation:
  1289. pDbase['wxId-bind'] = pLocation['wxId']
  1290. if pLocation and pMapset:
  1291. pLocation['wxId-bind'] = pMapset['wxId']
  1292. if pLocation and pMapset and pMap:
  1293. pLocation['wxId-bind'] += pMap['wxId']
  1294. pMapset['wxId-bind'] = pMap['wxId']
  1295. #
  1296. # determine panel size
  1297. #
  1298. maxsizes = (0, 0)
  1299. for section in sections:
  1300. tab[section].SetSizer(tabsizer[section])
  1301. tabsizer[section].Fit(tab[section])
  1302. tab[section].Layout()
  1303. minsecsizes = tabsizer[section].GetSize()
  1304. maxsizes = map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1))
  1305. # TODO: be less arbitrary with these 600
  1306. self.panelMinHeight = 100
  1307. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1308. for section in sections:
  1309. tab[section].SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1310. if self.manual_tab.IsLoaded():
  1311. self.manual_tab.SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1312. self.SetSizer(panelsizer)
  1313. panelsizer.Fit(self.notebook)
  1314. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1315. def _getValue(self, p):
  1316. """!Get value or default value of given parameter
  1317. @param p parameter directory
  1318. """
  1319. if p.get('value', '') != '':
  1320. return p['value']
  1321. return p.get('default', '')
  1322. def OnFileText(self, event):
  1323. """File input interactively entered"""
  1324. text = event.GetString()
  1325. p = self.task.get_param(value = event.GetId(), element = 'wxId', raiseError = False)
  1326. if not p:
  1327. return # should not happen
  1328. win = self.FindWindowById(p['wxId'][0])
  1329. if text:
  1330. filename = win.GetValue()
  1331. if not filename:
  1332. # outFile = tempfile.NamedTemporaryFile(mode = 'w+b')
  1333. filename = grass.tempfile()
  1334. win.SetValue(filename)
  1335. f = open(filename, "w")
  1336. try:
  1337. f.write(text)
  1338. finally:
  1339. f.close()
  1340. else:
  1341. win.SetValue('')
  1342. def OnVectorFormat(self, event):
  1343. """!Change vector format (native / ogr)"""
  1344. sel = event.GetSelection()
  1345. idEvent = event.GetId()
  1346. p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
  1347. if not p:
  1348. return # should not happen
  1349. # detect windows
  1350. winNative = None
  1351. winOgr = None
  1352. for id in p['wxId']:
  1353. if id == idEvent:
  1354. continue
  1355. name = self.FindWindowById(id).GetName()
  1356. if name == 'Select':
  1357. winNative = self.FindWindowById(id + 1) # fix the mystery (also in nviz_tools.py)
  1358. elif name == 'OgrSelect':
  1359. winOgr = self.FindWindowById(id)
  1360. # enable / disable widgets & update values
  1361. rbox = self.FindWindowByName('VectorFormat')
  1362. self.hsizer.Remove(rbox)
  1363. if sel == 0: # -> native
  1364. winOgr.Hide()
  1365. self.hsizer.Remove(winOgr)
  1366. self.hsizer.Add(item = winNative,
  1367. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1368. border = 5)
  1369. winNative.Show()
  1370. p['value'] = winNative.GetValue()
  1371. elif sel == 1: # -> OGR
  1372. sizer = wx.BoxSizer(wx.VERTICAL)
  1373. winNative.Hide()
  1374. self.hsizer.Remove(winNative)
  1375. sizer.Add(item = winOgr)
  1376. winOgr.Show()
  1377. p['value'] = winOgr.GetDsn()
  1378. self.hsizer.Add(item = sizer,
  1379. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1380. border = 5)
  1381. self.hsizer.Add(item = rbox,
  1382. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1383. wx.RIGHT | wx.ALIGN_TOP,
  1384. border = 5)
  1385. self.hsizer.Layout()
  1386. self.Layout()
  1387. self.OnUpdateValues()
  1388. self.OnUpdateSelection(event)
  1389. def OnUpdateDialog(self, event):
  1390. for fn, kwargs in event.data.iteritems():
  1391. fn(**kwargs)
  1392. self.parent.updateValuesHook()
  1393. def OnVerbosity(self, event):
  1394. """!Verbosity level changed"""
  1395. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  1396. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  1397. if event.IsChecked():
  1398. if event.GetId() == verbose.GetId():
  1399. if quiet.IsChecked():
  1400. quiet.SetValue(False)
  1401. self.task.get_flag('quiet')['value'] = False
  1402. else:
  1403. if verbose.IsChecked():
  1404. verbose.SetValue(False)
  1405. self.task.get_flag('verbose')['value'] = False
  1406. event.Skip()
  1407. def OnPageChange(self, event):
  1408. if not event:
  1409. sel = self.notebook.GetSelection()
  1410. else:
  1411. sel = event.GetSelection()
  1412. idx = self.notebook.GetPageIndexByName('manual')
  1413. if idx > -1 and sel == idx:
  1414. # calling LoadPage() is strangely time-consuming (only first call)
  1415. # FIXME: move to helpPage.__init__()
  1416. if not self.manual_tab.IsLoaded():
  1417. wx.Yield()
  1418. self.manual_tab.LoadPage()
  1419. self.Layout()
  1420. def OnColorChange(self, event):
  1421. myId = event.GetId()
  1422. for p in self.task.params:
  1423. if 'wxId' in p and myId in p['wxId']:
  1424. has_button = p['wxId'][1] is not None
  1425. if has_button and wx.FindWindowById(p['wxId'][1]).GetValue() == True:
  1426. p[ 'value' ] = 'none'
  1427. else:
  1428. colorchooser = wx.FindWindowById(p['wxId'][0])
  1429. new_color = colorchooser.GetValue()[:]
  1430. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1431. # under wx2.8.1
  1432. new_label = rgb2str.get(new_color, ':'.join(map(str,new_color)))
  1433. colorchooser.SetLabel(new_label)
  1434. colorchooser.SetColour(new_color)
  1435. colorchooser.Refresh()
  1436. p[ 'value' ] = colorchooser.GetLabel()
  1437. self.OnUpdateValues()
  1438. def OnUpdateValues(self, event = None):
  1439. """!If we were part of a richer interface, report back the
  1440. current command being built.
  1441. This method should be set by the parent of this panel if
  1442. needed. It's a hook, actually. Beware of what is 'self' in
  1443. the method def, though. It will be called with no arguments.
  1444. """
  1445. pass
  1446. def OnCheckBoxMulti(self, event):
  1447. """!Fill the values as a ','-separated string according to
  1448. current status of the checkboxes.
  1449. """
  1450. me = event.GetId()
  1451. theParam = None
  1452. for p in self.task.params:
  1453. if 'wxId' in p and me in p['wxId']:
  1454. theParam = p
  1455. myIndex = p['wxId'].index(me)
  1456. # Unpack current value list
  1457. currentValues = {}
  1458. for isThere in theParam.get('value', '').split(','):
  1459. currentValues[isThere] = 1
  1460. theValue = theParam['values'][myIndex]
  1461. if event.Checked():
  1462. currentValues[ theValue ] = 1
  1463. else:
  1464. del currentValues[ theValue ]
  1465. # Keep the original order, so that some defaults may be recovered
  1466. currentValueList = []
  1467. for v in theParam['values']:
  1468. if v in currentValues:
  1469. currentValueList.append(v)
  1470. # Pack it back
  1471. theParam['value'] = ','.join(currentValueList)
  1472. self.OnUpdateValues()
  1473. def OnSetValue(self, event):
  1474. """!Retrieve the widget value and set the task value field
  1475. accordingly.
  1476. Use for widgets that have a proper GetValue() method, i.e. not
  1477. for selectors.
  1478. """
  1479. myId = event.GetId()
  1480. me = wx.FindWindowById(myId)
  1481. name = me.GetName()
  1482. found = False
  1483. for porf in self.task.params + self.task.flags:
  1484. if 'wxId' not in porf:
  1485. continue
  1486. if myId in porf['wxId']:
  1487. found = True
  1488. break
  1489. if not found:
  1490. return
  1491. if name in ('DriverSelect', 'TableSelect',
  1492. 'LocationSelect', 'MapsetSelect', 'ProjSelect'):
  1493. porf['value'] = me.GetStringSelection()
  1494. elif name == 'GdalSelect':
  1495. porf['value'] = event.dsn
  1496. elif name == 'ModelParam':
  1497. porf['parameterized'] = me.IsChecked()
  1498. elif name == 'LayerSelect':
  1499. porf['value'] = me.GetValue()
  1500. else:
  1501. porf['value'] = me.GetValue()
  1502. self.OnUpdateValues(event)
  1503. event.Skip()
  1504. def OnUpdateSelection(self, event):
  1505. """!Update dialog (layers, tables, columns, etc.)
  1506. """
  1507. if not hasattr(self.parent, "updateThread"):
  1508. if event:
  1509. event.Skip()
  1510. return
  1511. if event:
  1512. self.parent.updateThread.Update(UpdateDialog,
  1513. self,
  1514. event,
  1515. event.GetId(),
  1516. self.task)
  1517. else:
  1518. self.parent.updateThread.Update(UpdateDialog,
  1519. self,
  1520. None,
  1521. None,
  1522. self.task)
  1523. def createCmd(self, ignoreErrors = False):
  1524. """!Produce a command line string (list) or feeding into GRASS.
  1525. If ignoreErrors == True then it will return whatever has been
  1526. built so far, even though it would not be a correct command
  1527. for GRASS.
  1528. """
  1529. try:
  1530. cmd = self.task.getCmd(ignoreErrors = ignoreErrors)
  1531. except ValueError, err:
  1532. dlg = wx.MessageDialog(parent = self,
  1533. message = unicode(err),
  1534. caption = _("Error in %s") % self.task.name,
  1535. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1536. dlg.ShowModal()
  1537. dlg.Destroy()
  1538. cmd = None
  1539. return cmd
  1540. def OnSize(self, event):
  1541. width = event.GetSize()[0]
  1542. fontsize = self.GetFont().GetPointSize()
  1543. text_width = max(width / (fontsize - 3), 70)
  1544. for id in self.label_id:
  1545. win = self.FindWindowById(id)
  1546. label = win.GetLabel()
  1547. label_new = '\n'.join(textwrap.wrap(label, text_width))
  1548. win.SetLabel(label_new)
  1549. event.Skip()
  1550. class GrassGUIApp(wx.App):
  1551. """!Stand-alone GRASS command GUI
  1552. """
  1553. def __init__(self, grass_task):
  1554. self.grass_task = grass_task
  1555. wx.App.__init__(self, False)
  1556. def OnInit(self):
  1557. msg = self.grass_task.get_error_msg()
  1558. if msg:
  1559. gcmd.GError(msg + '\n\nTry to set up GRASS_ADDON_PATH variable.')
  1560. return True
  1561. self.mf = mainFrame(parent = None, ID = wx.ID_ANY, task_description = self.grass_task)
  1562. self.mf.CentreOnScreen()
  1563. self.mf.Show(True)
  1564. self.SetTopWindow(self.mf)
  1565. return True
  1566. class GUI:
  1567. def __init__(self, parent = None, show = True, modal = False,
  1568. centreOnParent = False, checkError = False):
  1569. """!Parses GRASS commands when module is imported and used from
  1570. Layer Manager.
  1571. """
  1572. self.parent = parent
  1573. self.show = show
  1574. self.modal = modal
  1575. self.centreOnParent = centreOnParent
  1576. self.checkError = checkError
  1577. self.grass_task = None
  1578. self.cmd = list()
  1579. global _blackList
  1580. if self.parent:
  1581. _blackList['enabled'] = True
  1582. else:
  1583. _blackList['enabled'] = False
  1584. def GetCmd(self):
  1585. """!Get validated command"""
  1586. return self.cmd
  1587. def ParseCommand(self, cmd, gmpath = None, completed = None):
  1588. """!Parse command
  1589. Note: cmd is given as list
  1590. If command is given with options, return validated cmd list:
  1591. - add key name for first parameter if not given
  1592. - change mapname to mapname@mapset
  1593. """
  1594. start = time.time()
  1595. dcmd_params = {}
  1596. if completed == None:
  1597. get_dcmd = None
  1598. layer = None
  1599. dcmd_params = None
  1600. else:
  1601. get_dcmd = completed[0]
  1602. layer = completed[1]
  1603. if completed[2]:
  1604. dcmd_params.update(completed[2])
  1605. # parse the interface decription
  1606. try:
  1607. global _blackList
  1608. self.grass_task = gtask.parse_interface(cmd[0],
  1609. blackList = _blackList)
  1610. except ValueError, e: #grass.ScriptError, e:
  1611. gcmd.GError(e.value)
  1612. return
  1613. # if layer parameters previously set, re-insert them into dialog
  1614. if completed is not None:
  1615. if 'params' in dcmd_params:
  1616. self.grass_task.params = dcmd_params['params']
  1617. if 'flags' in dcmd_params:
  1618. self.grass_task.flags = dcmd_params['flags']
  1619. err = list()
  1620. # update parameters if needed && validate command
  1621. if len(cmd) > 1:
  1622. i = 0
  1623. cmd_validated = [cmd[0]]
  1624. for option in cmd[1:]:
  1625. if option[0] == '-': # flag
  1626. if option[1] == '-':
  1627. self.grass_task.set_flag(option[2:], True)
  1628. else:
  1629. self.grass_task.set_flag(option[1], True)
  1630. cmd_validated.append(option)
  1631. else: # parameter
  1632. try:
  1633. key, value = option.split('=', 1)
  1634. except:
  1635. if i == 0: # add key name of first parameter if not given
  1636. key = self.grass_task.firstParam
  1637. value = option
  1638. else:
  1639. raise gcmd.GException, _("Unable to parse command '%s'") % ' '.join(cmd)
  1640. element = self.grass_task.get_param(key, raiseError = False)
  1641. if not element:
  1642. err.append(_("%(cmd)s: parameter '%(key)s' not available") % \
  1643. { 'cmd' : cmd[0],
  1644. 'key' : key })
  1645. continue
  1646. element = element['element']
  1647. if element in ['cell', 'vector']:
  1648. # mapname -> mapname@mapset
  1649. try:
  1650. name, mapset = value.split('@')
  1651. except ValueError:
  1652. mapset = grass.find_file(value, element)['mapset']
  1653. curr_mapset = grass.gisenv()['MAPSET']
  1654. if mapset and mapset != curr_mapset:
  1655. value = value + '@' + mapset
  1656. self.grass_task.set_param(key, value)
  1657. cmd_validated.append(key + '=' + value)
  1658. i += 1
  1659. # update original command list
  1660. cmd = cmd_validated
  1661. if self.show is not None:
  1662. self.mf = mainFrame(parent = self.parent, ID = wx.ID_ANY,
  1663. task_description = self.grass_task,
  1664. get_dcmd = get_dcmd, layer = layer)
  1665. else:
  1666. self.mf = None
  1667. if get_dcmd is not None:
  1668. # update only propwin reference
  1669. get_dcmd(dcmd = None, layer = layer, params = None,
  1670. propwin = self.mf)
  1671. if self.show is not None:
  1672. self.mf.notebookpanel.OnUpdateSelection(None)
  1673. if self.show is True:
  1674. if self.parent and self.centreOnParent:
  1675. self.mf.CentreOnParent()
  1676. else:
  1677. self.mf.CenterOnScreen()
  1678. self.mf.Show(self.show)
  1679. self.mf.MakeModal(self.modal)
  1680. else:
  1681. self.mf.OnApply(None)
  1682. self.cmd = cmd
  1683. if self.checkError:
  1684. return self.grass_task, err
  1685. else:
  1686. return self.grass_task
  1687. def GetCommandInputMapParamKey(self, cmd):
  1688. """!Get parameter key for input raster/vector map
  1689. @param cmd module name
  1690. @return parameter key
  1691. @return None on failure
  1692. """
  1693. # parse the interface decription
  1694. if not self.grass_task:
  1695. tree = etree.fromstring(gtask.get_interface_description(cmd))
  1696. self.grass_task = gtask.processTask(tree).get_task()
  1697. for p in self.grass_task.params:
  1698. if p.get('name', '') in ('input', 'map'):
  1699. age = p.get('age', '')
  1700. prompt = p.get('prompt', '')
  1701. element = p.get('element', '')
  1702. if age == 'old' and \
  1703. element in ('cell', 'grid3', 'vector') and \
  1704. prompt in ('raster', '3d-raster', 'vector'):
  1705. return p.get('name', None)
  1706. return None
  1707. class FloatValidator(wx.PyValidator):
  1708. """!Validator for floating-point input"""
  1709. def __init__(self):
  1710. wx.PyValidator.__init__(self)
  1711. self.Bind(wx.EVT_TEXT, self.OnText)
  1712. def Clone(self):
  1713. """!Clone validator"""
  1714. return FloatValidator()
  1715. def Validate(self):
  1716. """Validate input"""
  1717. textCtrl = self.GetWindow()
  1718. text = textCtrl.GetValue()
  1719. if text:
  1720. try:
  1721. float(text)
  1722. except ValueError:
  1723. textCtrl.SetBackgroundColour("grey")
  1724. textCtrl.SetFocus()
  1725. textCtrl.Refresh()
  1726. return False
  1727. sysColor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW)
  1728. textCtrl.SetBackgroundColour(sysColor)
  1729. textCtrl.Refresh()
  1730. return True
  1731. def OnText(self, event):
  1732. """!Do validation"""
  1733. self.Validate()
  1734. event.Skip()
  1735. def TransferToWindow(self):
  1736. return True # Prevent wxDialog from complaining.
  1737. def TransferFromWindow(self):
  1738. return True # Prevent wxDialog from complaining.
  1739. class GNotebook(FN.FlatNotebook):
  1740. """!Generic notebook widget
  1741. """
  1742. def __init__(self, parent, style, **kwargs):
  1743. if globalvar.hasAgw:
  1744. FN.FlatNotebook.__init__(self, parent, id = wx.ID_ANY, agwStyle = style, **kwargs)
  1745. else:
  1746. FN.FlatNotebook.__init__(self, parent, id = wx.ID_ANY, style = style, **kwargs)
  1747. self.notebookPages = {}
  1748. def AddPage(self, **kwargs):
  1749. """!Add a new page
  1750. """
  1751. if 'name' in kwargs:
  1752. self.notebookPages[kwargs['name']] = kwargs['page']
  1753. del kwargs['name']
  1754. super(GNotebook, self).AddPage(**kwargs)
  1755. def InsertPage(self, **kwargs):
  1756. """!Insert a new page
  1757. """
  1758. if 'name' in kwargs:
  1759. self.notebookPages[kwargs['name']] = kwargs['page']
  1760. del kwargs['name']
  1761. super(GNotebook, self).InsertPage(**kwargs)
  1762. def SetSelectionByName(self, page):
  1763. """!Set notebook
  1764. @param page names, eg. 'layers', 'output', 'search', 'pyshell', 'nviz'
  1765. """
  1766. if self.GetSelection() != self.GetPageIndexByName('output'):
  1767. self.SetSelection(self.GetPageIndexByName(page))
  1768. def GetPageIndexByName(self, page):
  1769. """!Get notebook page index
  1770. @param page name
  1771. """
  1772. if page not in self.notebookPages:
  1773. return -1
  1774. return self.GetPageIndex(self.notebookPages[page])
  1775. if __name__ == "__main__":
  1776. if len(sys.argv) == 1:
  1777. sys.exit(_("usage: %s <grass command>") % sys.argv[0])
  1778. if sys.argv[1] != 'test':
  1779. q = wx.LogNull()
  1780. cmd = utils.split(sys.argv[1])
  1781. task = gtask.grassTask(cmd[0], blackList = _blackList)
  1782. task.set_options(cmd[1:])
  1783. app = GrassGUIApp(task)
  1784. app.MainLoop()
  1785. else: #Test
  1786. # Test grassTask from within a GRASS session
  1787. if os.getenv("GISBASE") is not None:
  1788. task = gtask.grassTask("d.vect")
  1789. task.get_param('map')['value'] = "map_name"
  1790. task.get_flag('v')['value'] = True
  1791. task.get_param('layer')['value'] = 1
  1792. task.get_param('bcolor')['value'] = "red"
  1793. assert ' '.join(task.getCmd()) == "d.vect -v map = map_name layer = 1 bcolor = red"
  1794. # Test interface building with handmade grassTask,
  1795. # possibly outside of a GRASS session.
  1796. task = gtask.grassTask()
  1797. task.name = "TestTask"
  1798. task.description = "This is an artificial grassTask() object intended for testing purposes."
  1799. task.keywords = ["grass","test","task"]
  1800. task.params = [
  1801. {
  1802. "name" : "text",
  1803. "description" : "Descriptions go into tooltips if labels are present, like this one",
  1804. "label" : "Enter some text",
  1805. },{
  1806. "name" : "hidden_text",
  1807. "description" : "This text should not appear in the form",
  1808. "hidden" : True
  1809. },{
  1810. "name" : "text_default",
  1811. "description" : "Enter text to override the default",
  1812. "default" : "default text"
  1813. },{
  1814. "name" : "text_prefilled",
  1815. "description" : "You should see a friendly welcome message here",
  1816. "value" : "hello, world"
  1817. },{
  1818. "name" : "plain_color",
  1819. "description" : "This is a plain color, and it is a compulsory parameter",
  1820. "required" : False,
  1821. "gisprompt" : True,
  1822. "prompt" : "color"
  1823. },{
  1824. "name" : "transparent_color",
  1825. "description" : "This color becomes transparent when set to none",
  1826. "guisection" : "tab",
  1827. "gisprompt" : True,
  1828. "prompt" : "color"
  1829. },{
  1830. "name" : "multi",
  1831. "description" : "A multiple selection",
  1832. 'default': u'red,green,blue',
  1833. 'gisprompt': False,
  1834. 'guisection': 'tab',
  1835. 'multiple': u'yes',
  1836. 'type': u'string',
  1837. 'value': '',
  1838. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other']
  1839. },{
  1840. "name" : "single",
  1841. "description" : "A single multiple-choice selection",
  1842. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  1843. "guisection" : "tab"
  1844. },{
  1845. "name" : "large_multi",
  1846. "description" : "A large multiple selection",
  1847. "gisprompt" : False,
  1848. "multiple" : "yes",
  1849. # values must be an array of strings
  1850. "values" : str2rgb.keys() + map(str, str2rgb.values())
  1851. },{
  1852. "name" : "a_file",
  1853. "description" : "A file selector",
  1854. "gisprompt" : True,
  1855. "element" : "file"
  1856. }
  1857. ]
  1858. task.flags = [
  1859. {
  1860. "name" : "a",
  1861. "description" : "Some flag, will appear in Main since it is required",
  1862. "required" : True
  1863. },{
  1864. "name" : "b",
  1865. "description" : "pre-filled flag, will appear in options since it is not required",
  1866. "value" : True
  1867. },{
  1868. "name" : "hidden_flag",
  1869. "description" : "hidden flag, should not be changeable",
  1870. "hidden" : "yes",
  1871. "value" : True
  1872. }
  1873. ]
  1874. q = wx.LogNull()
  1875. GrassGUIApp(task).MainLoop()