forms.py 95 KB

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