forms.py 93 KB

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