forms.py 93 KB

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