menuform.py 95 KB

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