forms.py 96 KB

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