forms.py 94 KB

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