forms.py 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267
  1. """
  2. @package gui_core.forms
  3. @brief Construct simple wxPython GUI from a GRASS command interface
  4. description.
  5. Classes:
  6. - forms::UpdateThread
  7. - forms::UpdateQThread
  8. - forms::TaskFrame
  9. - forms::CmdPanel
  10. - forms::GUI
  11. - forms::GrassGUIApp
  12. This program is just a coarse approach to automatically build a GUI
  13. from a xml-based GRASS user interface description.
  14. You need to have Python 2.4, wxPython 2.8 and python-xml.
  15. The XML stream is read from executing the command given in the
  16. command line, thus you may call it for instance this way:
  17. python <this file.py> r.basins.fill
  18. Or you set an alias or wrap the call up in a nice shell script, GUI
  19. environment ... please contribute your idea.
  20. Updated to wxPython 2.8 syntax and contrib widgets. Methods added to
  21. make it callable by gui. Method added to automatically re-run with
  22. pythonw on a Mac.
  23. @todo
  24. - verify option value types
  25. Copyright(C) 2000-2012 by the GRASS Development Team
  26. This program is free software under the GPL(>=v2) Read the file
  27. COPYING coming with GRASS for details.
  28. @author Jan-Oliver Wagner <jan@intevation.de>
  29. @author Bernhard Reiter <bernhard@intevation.de>
  30. @author Michael Barton, Arizona State University
  31. @author Daniel Calvelo <dca.gis@gmail.com>
  32. @author Martin Landa <landa.martin@gmail.com>
  33. @author Luca Delucchi <lucadeluge@gmail.com>
  34. """
  35. import sys
  36. import string
  37. import textwrap
  38. import os
  39. import time
  40. import copy
  41. import locale
  42. from threading import Thread
  43. import Queue
  44. gisbase = os.getenv("GISBASE")
  45. if gisbase is None:
  46. print >>sys.stderr, "We don't seem to be properly installed, or we are being run outside GRASS. Expect glitches."
  47. gisbase = os.path.join(os.path.dirname(sys.argv[0]), os.path.pardir)
  48. wxbase = gisbase
  49. else:
  50. wxbase = os.path.join(gisbase, 'etc', 'gui', 'wxpython')
  51. sys.path.append(wxbase)
  52. from core import globalvar
  53. import wx
  54. try:
  55. import wx.lib.agw.flatnotebook as FN
  56. except ImportError:
  57. import wx.lib.flatnotebook as FN
  58. import wx.lib.colourselect as csel
  59. import wx.lib.filebrowsebutton as filebrowse
  60. from wx.lib.newevent import NewEvent
  61. try:
  62. import xml.etree.ElementTree as etree
  63. except ImportError:
  64. import elementtree.ElementTree as etree # Python <= 2.4
  65. from grass.script import core as grass
  66. from grass.script import task as gtask
  67. from gui_core.widgets import StaticWrapText, ScrolledPanel
  68. from gui_core.ghelp import HelpPanel
  69. from gui_core import gselect
  70. from core import gcmd
  71. from core import utils
  72. from core.settings import UserSettings
  73. from gui_core.widgets import FloatValidator, GNotebook
  74. wxUpdateDialog, EVT_DIALOG_UPDATE = NewEvent()
  75. # From lib/gis/col_str.c, except purple which is mentioned
  76. # there but not given RGB values
  77. str2rgb = {'aqua': (100, 128, 255),
  78. 'black': (0, 0, 0),
  79. 'blue': (0, 0, 255),
  80. 'brown': (180, 77, 25),
  81. 'cyan': (0, 255, 255),
  82. 'gray': (128, 128, 128),
  83. 'green': (0, 255, 0),
  84. 'grey': (128, 128, 128),
  85. 'indigo': (0, 128, 255),
  86. 'magenta': (255, 0, 255),
  87. 'orange': (255, 128, 0),
  88. 'purple': (128, 0, 128),
  89. 'red': (255, 0, 0),
  90. 'violet': (128, 0, 255),
  91. 'white': (255, 255, 255),
  92. 'yellow': (255, 255, 0)}
  93. rgb2str = {}
  94. for (s,r) in str2rgb.items():
  95. rgb2str[ r ] = s
  96. """!Hide some options in the GUI"""
  97. #_blackList = { 'enabled' : False,
  98. # 'items' : { 'r.buffer' : {'params' : ['input', 'output'],
  99. # 'flags' : ['z', 'overwrite']}}}
  100. _blackList = { 'enabled' : False,
  101. 'items' : {} }
  102. def color_resolve(color):
  103. if len(color) > 0 and color[0] in "0123456789":
  104. rgb = tuple(map(int, color.split(':')))
  105. label = color
  106. else:
  107. # Convert color names to RGB
  108. try:
  109. rgb = str2rgb[color]
  110. label = color
  111. except KeyError:
  112. rgb = (200, 200, 200)
  113. label = _('Select Color')
  114. return (rgb, label)
  115. def text_beautify(someString , width = 70):
  116. """!Make really long texts shorter, clean up whitespace and remove
  117. trailing punctuation.
  118. """
  119. if width > 0:
  120. return escape_ampersand(string.strip(
  121. os.linesep.join(textwrap.wrap(utils.normalize_whitespace(someString), width)),
  122. ".,;:"))
  123. else:
  124. return escape_ampersand(string.strip(utils.normalize_whitespace(someString), ".,;:"))
  125. def escape_ampersand(text):
  126. """!Escapes ampersands with additional ampersand for GUI"""
  127. return string.replace(text, "&", "&&")
  128. class UpdateThread(Thread):
  129. """!Update dialog widgets in the thread"""
  130. def __init__(self, parent, event, eventId, task):
  131. Thread.__init__(self)
  132. self.parent = parent
  133. self.event = event
  134. self.eventId = eventId
  135. self.task = task
  136. self.setDaemon(True)
  137. # list of functions which updates the dialog
  138. self.data = {}
  139. def run(self):
  140. # get widget id
  141. if not self.eventId:
  142. for p in self.task.params:
  143. if p.get('gisprompt', False) == False:
  144. continue
  145. prompt = p.get('element', '')
  146. if prompt == 'vector':
  147. name = p.get('name', '')
  148. if name in ('map', 'input'):
  149. self.eventId = p['wxId'][0]
  150. if self.eventId is None:
  151. return
  152. p = self.task.get_param(self.eventId, element = 'wxId', raiseError = False)
  153. if not p or 'wxId-bind' not in p:
  154. return
  155. # get widget prompt
  156. pType = p.get('prompt', '')
  157. if not pType:
  158. return
  159. # check for map/input parameter
  160. pMap = self.task.get_param('map', raiseError = False)
  161. if not pMap:
  162. pMap = self.task.get_param('input', raiseError = False)
  163. if pMap:
  164. map = pMap.get('value', '')
  165. else:
  166. map = None
  167. # avoid running db.describe several times
  168. cparams = dict()
  169. cparams[map] = { 'dbInfo' : None,
  170. 'layers' : None, }
  171. # update reference widgets
  172. for uid in p['wxId-bind']:
  173. win = self.parent.FindWindowById(uid)
  174. if not win:
  175. continue
  176. name = win.GetName()
  177. pBind = self.task.get_param(uid, element = 'wxId', raiseError = False)
  178. if pBind:
  179. pBind['value'] = ''
  180. map = layer = None
  181. driver = db = table = None
  182. if name in ('LayerSelect', 'ColumnSelect'):
  183. if p.get('element', '') == 'vector': # -> vector
  184. # get map name
  185. map = p.get('value', '')
  186. # get layer
  187. for bid in p['wxId-bind']:
  188. p = self.task.get_param(bid, element = 'wxId', raiseError = False)
  189. if not p:
  190. continue
  191. if p.get('element', '') == 'layer':
  192. layer = p.get('value', '')
  193. if layer != '':
  194. layer = p.get('value', '')
  195. else:
  196. layer = p.get('default', '')
  197. break
  198. elif p.get('element', '') == 'layer': # -> layer
  199. # get layer
  200. layer = p.get('value', '')
  201. if layer != '':
  202. layer = p.get('value', '')
  203. else:
  204. layer = p.get('default', '')
  205. # get map name
  206. pMapL = self.task.get_param(p['wxId'][0], element = 'wxId-bind', raiseError = False)
  207. if pMapL:
  208. map = pMapL.get('value', '')
  209. if name == 'TableSelect' or \
  210. (name == 'ColumnSelect' and not map):
  211. pDriver = self.task.get_param('dbdriver', element = 'prompt', raiseError = False)
  212. if pDriver:
  213. driver = pDriver.get('value', '')
  214. pDb = self.task.get_param('dbname', element = 'prompt', raiseError = False)
  215. if pDb:
  216. db = pDb.get('value', '')
  217. if name == 'ColumnSelect':
  218. pTable = self.task.get_param('dbtable', element = 'element', raiseError = False)
  219. if pTable:
  220. table = pTable.get('value', '')
  221. if name == 'LayerSelect':
  222. # determine format
  223. native = True
  224. for id in pMap['wxId']:
  225. winVec = self.parent.FindWindowById(id)
  226. if winVec.GetName() == 'VectorFormat' and \
  227. winVec.GetSelection() != 0:
  228. native = False
  229. break
  230. # TODO: update only if needed
  231. if native:
  232. if map:
  233. self.data[win.InsertLayers] = { 'vector' : map }
  234. else:
  235. self.data[win.InsertLayers] = { }
  236. else:
  237. if map:
  238. self.data[win.InsertLayers] = { 'dsn' : map.rstrip('@OGR') }
  239. else:
  240. self.data[win.InsertLayers] = { }
  241. elif name == 'TableSelect':
  242. self.data[win.InsertTables] = { 'driver' : driver,
  243. 'database' : db }
  244. elif name == 'ColumnSelect':
  245. if map:
  246. if map in cparams:
  247. if not cparams[map]['dbInfo']:
  248. cparams[map]['dbInfo'] = gselect.VectorDBInfo(map)
  249. self.data[win.InsertColumns] = { 'vector' : map, 'layer' : layer,
  250. 'dbInfo' : cparams[map]['dbInfo'] }
  251. else: # table
  252. if driver and db:
  253. self.data[win.InsertTableColumns] = { 'table' : pTable.get('value'),
  254. 'driver' : driver,
  255. 'database' : db }
  256. elif pTable:
  257. self.data[win.InsertTableColumns] = { 'table' : pTable.get('value') }
  258. elif name == 'SubGroupSelect':
  259. self.data[win.Insert] = { 'group' : p.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 | FN.FNB_NO_X_BUTTON )
  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] = 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. prompt = p.get('prompt', '')
  769. # text style (required -> bold)
  770. if not p.get('required', False):
  771. text_style = wx.FONTWEIGHT_NORMAL
  772. else:
  773. text_style = wx.FONTWEIGHT_BOLD
  774. # title sizer (description, name, type)
  775. if (len(p.get('values', [])) > 0) and \
  776. p.get('multiple', False) and \
  777. p.get('gisprompt', False) == False and \
  778. p.get('type', '') == 'string':
  779. title_txt = wx.StaticBox(parent = which_panel, id = wx.ID_ANY)
  780. else:
  781. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  782. title_txt = wx.StaticText(parent = which_panel)
  783. if p['key_desc']:
  784. ltype = ','.join(p['key_desc'])
  785. else:
  786. ltype = p['type']
  787. rtitle_txt = wx.StaticText(parent = which_panel,
  788. label = '(' + p['name'] + '=' + ltype + ')')
  789. title_sizer.Add(item = title_txt, proportion = 1,
  790. flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
  791. title_sizer.Add(item = rtitle_txt, proportion = 0,
  792. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  793. which_sizer.Add(item = title_sizer, proportion = 0,
  794. flag = wx.EXPAND)
  795. self.label_id.append(title_txt.GetId())
  796. # title expansion
  797. if p.get('multiple', False) and len(p.get('values','')) == 0:
  798. title = _("[multiple]") + " " + title
  799. if p.get('value','') == '' :
  800. p['value'] = p.get('default','')
  801. if (len(p.get('values', [])) > 0):
  802. valuelist = map(str, p.get('values',[]))
  803. valuelist_desc = map(unicode, p.get('values_desc',[]))
  804. if p.get('multiple', False) and \
  805. p.get('gisprompt',False) == False and \
  806. p.get('type', '') == 'string':
  807. title_txt.SetLabel(" %s: (%s, %s) " % (title, p['name'], p['type']))
  808. if valuelist_desc:
  809. hSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.VERTICAL)
  810. else:
  811. hSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.HORIZONTAL)
  812. isEnabled = {}
  813. # copy default values
  814. if p['value'] == '':
  815. p['value'] = p.get('default', '')
  816. for defval in p.get('value', '').split(','):
  817. isEnabled[ defval ] = 'yes'
  818. # for multi checkboxes, this is an array of all wx IDs
  819. # for each individual checkbox
  820. p[ 'wxId' ] = list()
  821. idx = 0
  822. for val in valuelist:
  823. try:
  824. label = valuelist_desc[idx]
  825. except IndexError:
  826. label = val
  827. chkbox = wx.CheckBox(parent = which_panel,
  828. label = text_beautify(label))
  829. p[ 'wxId' ].append(chkbox.GetId())
  830. if val in isEnabled:
  831. chkbox.SetValue(True)
  832. hSizer.Add(item = chkbox, proportion = 0,
  833. flag = wx.ADJUST_MINSIZE | wx.ALL, border = 1)
  834. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  835. idx += 1
  836. which_sizer.Add(item = hSizer, proportion = 0,
  837. flag = wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border = 5)
  838. elif p.get('gisprompt', False) == False:
  839. if len(valuelist) == 1: # -> textctrl
  840. title_txt.SetLabel("%s (%s %s):" % (title, _('valid range'),
  841. str(valuelist[0])))
  842. if p.get('type', '') == 'integer' and \
  843. not p.get('multiple', False):
  844. # for multiple integers use textctrl instead of spinsctrl
  845. try:
  846. minValue, maxValue = map(int, valuelist[0].split('-'))
  847. except ValueError:
  848. minValue = -1e6
  849. maxValue = 1e6
  850. txt2 = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY, size = globalvar.DIALOG_SPIN_SIZE,
  851. min = minValue, max = maxValue)
  852. txt2.SetName("SpinCtrl")
  853. style = wx.BOTTOM | wx.LEFT
  854. else:
  855. txt2 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  856. txt2.SetName("TextCtrl")
  857. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  858. value = self._getValue(p)
  859. # parameter previously set
  860. if value:
  861. if txt2.GetName() == "SpinCtrl":
  862. txt2.SetValue(int(value))
  863. else:
  864. txt2.SetValue(value)
  865. which_sizer.Add(item = txt2, proportion = 0,
  866. flag = style, border = 5)
  867. p['wxId'] = [ txt2.GetId(), ]
  868. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  869. else:
  870. title_txt.SetLabel(title + ':')
  871. value = self._getValue(p)
  872. if p['name'] == 'icon': # symbols
  873. bitmap = wx.Bitmap(os.path.join(globalvar.ETCSYMBOLDIR, value) + '.png')
  874. bb = wx.BitmapButton(parent = which_panel, id = wx.ID_ANY,
  875. bitmap = bitmap)
  876. iconLabel = wx.StaticText(parent = which_panel, id = wx.ID_ANY)
  877. iconLabel.SetLabel(value)
  878. p['value'] = value
  879. p['wxId'] = [bb.GetId(), iconLabel.GetId()]
  880. bb.Bind(wx.EVT_BUTTON, self.OnSetSymbol)
  881. this_sizer = wx.BoxSizer(wx.HORIZONTAL)
  882. this_sizer.Add(item = bb, proportion = 0,
  883. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  884. this_sizer.Add(item = iconLabel, proportion = 0,
  885. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border = 5)
  886. which_sizer.Add(item = this_sizer, proportion = 0,
  887. flag = wx.ADJUST_MINSIZE, border = 0)
  888. else:
  889. # list of values (combo)
  890. cb = wx.ComboBox(parent = which_panel, id = wx.ID_ANY, value = p.get('default',''),
  891. size = globalvar.DIALOG_COMBOBOX_SIZE,
  892. choices = valuelist, style = wx.CB_DROPDOWN)
  893. if value:
  894. cb.SetValue(value) # parameter previously set
  895. which_sizer.Add(item = cb, proportion = 0,
  896. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  897. p['wxId'] = [cb.GetId(),]
  898. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  899. cb.Bind(wx.EVT_TEXT, self.OnSetValue)
  900. # text entry
  901. if (p.get('type','string') in ('string','integer','float')
  902. and len(p.get('values',[])) == 0
  903. and p.get('gisprompt',False) == False
  904. and p.get('prompt','') != 'color'):
  905. title_txt.SetLabel(title + ':')
  906. if p.get('multiple', False) or \
  907. p.get('type', 'string') == 'string' or \
  908. len(p.get('key_desc', [])) > 1:
  909. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  910. value = self._getValue(p)
  911. if value:
  912. # parameter previously set
  913. txt3.SetValue(str(value))
  914. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  915. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  916. else:
  917. minValue = -1e9
  918. maxValue = 1e9
  919. if p.get('type', '') == 'integer':
  920. txt3 = wx.SpinCtrl(parent = which_panel, value = p.get('default',''),
  921. size = globalvar.DIALOG_SPIN_SIZE,
  922. min = minValue, max = maxValue)
  923. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  924. value = self._getValue(p)
  925. if value:
  926. txt3.SetValue(int(value)) # parameter previously set
  927. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  928. else:
  929. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  930. validator = FloatValidator())
  931. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  932. value = self._getValue(p)
  933. if value:
  934. txt3.SetValue(str(value)) # parameter previously set
  935. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  936. which_sizer.Add(item = txt3, proportion = 0,
  937. flag = style, border = 5)
  938. p['wxId'] = [ txt3.GetId(), ]
  939. #
  940. # element selection tree combobox (maps, icons, regions, etc.)
  941. #
  942. if p.get('gisprompt', False):
  943. title_txt.SetLabel(title + ':')
  944. # GIS element entry
  945. if p.get('prompt','') not in ('color',
  946. 'color_none',
  947. 'subgroup',
  948. 'dbdriver',
  949. 'dbname',
  950. 'dbtable',
  951. 'dbcolumn',
  952. 'layer',
  953. 'layer_all',
  954. 'location',
  955. 'mapset',
  956. 'dbase') and \
  957. p.get('element', '') not in ('file', 'dir'):
  958. multiple = p.get('multiple', False)
  959. if p.get('age', '') == 'new':
  960. mapsets = [grass.gisenv()['MAPSET'],]
  961. else:
  962. mapsets = None
  963. if self.task.name in ('r.proj', 'v.proj') \
  964. and p.get('name', '') == 'input':
  965. if self.task.name == 'r.proj':
  966. isRaster = True
  967. else:
  968. isRaster = False
  969. selection = gselect.ProjSelect(parent = which_panel,
  970. isRaster = isRaster)
  971. p['wxId'] = [ selection.GetId(), ]
  972. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  973. formatSelector = False
  974. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  975. else:
  976. selection = gselect.Select(parent = which_panel, id = wx.ID_ANY,
  977. size = globalvar.DIALOG_GSELECT_SIZE,
  978. type = p.get('element', ''),
  979. multiple = multiple, mapsets = mapsets,
  980. fullyQualified = p.get('age', 'old') == 'old')
  981. value = self._getValue(p)
  982. if value:
  983. selection.SetValue(value)
  984. formatSelector = True
  985. # A select.Select is a combobox with two children: a textctl and a popupwindow;
  986. # we target the textctl here
  987. textWin = selection.GetTextCtrl()
  988. p['wxId'] = [ textWin.GetId(), ]
  989. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  990. if prompt == 'vector':
  991. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  992. # if formatSelector and p.get('age', 'old') == 'old':
  993. # # OGR supported (read-only)
  994. # self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  995. # self.hsizer.Add(item = selection,
  996. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  997. # border = 5)
  998. # # format (native / ogr)
  999. # rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  1000. # label = " %s " % _("Format"),
  1001. # style = wx.RA_SPECIFY_ROWS,
  1002. # choices = [_("Native / Linked OGR"), _("Direct OGR")])
  1003. # if p.get('value', '').lower().rfind('@ogr') > -1:
  1004. # rbox.SetSelection(1)
  1005. # rbox.SetName('VectorFormat')
  1006. # rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  1007. # self.hsizer.Add(item = rbox,
  1008. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1009. # wx.RIGHT | wx.ALIGN_TOP,
  1010. # border = 5)
  1011. # ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  1012. # default = 'dir',
  1013. # exclude = ['file'])
  1014. # self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  1015. # self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  1016. # ogrSelection.SetName('OgrSelect')
  1017. # ogrSelection.Hide()
  1018. # which_sizer.Add(item = self.hsizer, proportion = 0)
  1019. # p['wxId'].append(rbox.GetId())
  1020. # p['wxId'].append(ogrSelection.GetId())
  1021. # for win in ogrSelection.GetDsnWin():
  1022. # p['wxId'].append(win.GetId())
  1023. # else:
  1024. which_sizer.Add(item = selection, proportion = 0,
  1025. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1026. border = 5)
  1027. elif prompt == 'group':
  1028. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1029. which_sizer.Add(item = selection, proportion = 0,
  1030. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1031. border = 5)
  1032. else:
  1033. which_sizer.Add(item = selection, proportion = 0,
  1034. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1035. border = 5)
  1036. # subgroup
  1037. elif prompt == 'subgroup':
  1038. selection = gselect.SubGroupSelect(parent = which_panel)
  1039. p['wxId'] = [ selection.GetId() ]
  1040. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1041. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1042. which_sizer.Add(item = selection, proportion = 0,
  1043. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1044. border = 5)
  1045. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1046. elif prompt in ('dbdriver',
  1047. 'dbname',
  1048. 'dbtable',
  1049. 'dbcolumn',
  1050. 'layer',
  1051. 'layer_all',
  1052. 'location',
  1053. 'mapset',
  1054. 'dbase'):
  1055. if p.get('multiple', 'no') == 'yes':
  1056. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1057. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1058. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1059. else:
  1060. value = self._getValue(p)
  1061. if prompt in ('layer', 'layer_all'):
  1062. if prompt == 'layer_all':
  1063. all = True
  1064. else:
  1065. all = False
  1066. if p.get('age', 'old') == 'old':
  1067. win = gselect.LayerSelect(parent = which_panel,
  1068. all = all,
  1069. default = p['default'])
  1070. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1071. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1072. win.SetValue(str(value)) # default or previously set value
  1073. else:
  1074. win = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY,
  1075. min = 1, max = 100, initial = int(p['default']))
  1076. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1077. win.SetValue(int(value)) # default or previously set value
  1078. p['wxId'] = [ win.GetId() ]
  1079. elif prompt == 'dbdriver':
  1080. win = gselect.DriverSelect(parent = which_panel,
  1081. choices = p.get('values', []),
  1082. value = value)
  1083. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1084. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1085. elif prompt == 'dbname':
  1086. win = gselect.DatabaseSelect(parent = which_panel,
  1087. value = value)
  1088. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1089. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1090. elif prompt == 'dbtable':
  1091. if p.get('age', 'old') == 'old':
  1092. win = gselect.TableSelect(parent = which_panel)
  1093. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1094. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1095. else:
  1096. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1097. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1098. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1099. elif prompt == 'dbcolumn':
  1100. win = gselect.ColumnSelect(parent = which_panel,
  1101. value = value,
  1102. param = p)
  1103. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1104. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1105. elif prompt == 'location':
  1106. win = gselect.LocationSelect(parent = which_panel,
  1107. value = value)
  1108. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1109. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1110. elif prompt == 'mapset':
  1111. if p.get('age', 'old') == 'old':
  1112. new = False
  1113. else:
  1114. new = True
  1115. win = gselect.MapsetSelect(parent = which_panel,
  1116. value = value, new = new)
  1117. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1118. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1119. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1120. elif prompt == 'dbase':
  1121. win = gselect.DbaseSelect(parent = which_panel,
  1122. changeCallback = self.OnSetValue)
  1123. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1124. p['wxId'] = [ win.GetChildren()[1].GetId() ]
  1125. if 'wxId' not in p:
  1126. try:
  1127. p['wxId'] = [ win.GetId(), ]
  1128. except AttributeError:
  1129. pass
  1130. flags = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1131. if prompt == 'dbname':
  1132. flags |= wx.EXPAND
  1133. which_sizer.Add(item = win, proportion = 0,
  1134. flag = flags, border = 5)
  1135. # color entry
  1136. elif prompt in ('color',
  1137. 'color_none'):
  1138. default_color = (200,200,200)
  1139. label_color = _("Select Color")
  1140. if p.get('default','') != '':
  1141. default_color, label_color = color_resolve(p['default'])
  1142. if p.get('value','') != '': # parameter previously set
  1143. default_color, label_color = color_resolve(p['value'])
  1144. if prompt == 'color_none':
  1145. this_sizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1146. else:
  1147. this_sizer = which_sizer
  1148. btn_colour = csel.ColourSelect(parent = which_panel, id = wx.ID_ANY,
  1149. label = label_color, colour = default_color,
  1150. pos = wx.DefaultPosition, size = (150,-1))
  1151. this_sizer.Add(item = btn_colour, proportion = 0,
  1152. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1153. # For color selectors, this is a two-member array, holding the IDs of
  1154. # the selector proper and either a "transparent" button or None
  1155. p['wxId'] = [btn_colour.GetId(),]
  1156. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1157. if prompt == 'color_none':
  1158. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent"))
  1159. if p.get('value','') != '' and p.get('value',[''])[0] == "none":
  1160. none_check.SetValue(True)
  1161. else:
  1162. none_check.SetValue(False)
  1163. this_sizer.Add(item = none_check, proportion = 0,
  1164. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border = 5)
  1165. which_sizer.Add(this_sizer)
  1166. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1167. p['wxId'].append(none_check.GetId())
  1168. else:
  1169. p['wxId'].append(None)
  1170. # file selector
  1171. elif p.get('prompt','') != 'color' and p.get('element', '') == 'file':
  1172. if p.get('age', 'new') == 'new':
  1173. fmode = wx.SAVE
  1174. else:
  1175. fmode = wx.OPEN
  1176. fbb = filebrowse.FileBrowseButton(parent = which_panel, id = wx.ID_ANY, fileMask = '*',
  1177. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1178. dialogTitle = _('Choose %s') % \
  1179. p.get('description',_('File')),
  1180. buttonText = _('Browse'),
  1181. startDirectory = os.getcwd(), fileMode = fmode,
  1182. changeCallback = self.OnSetValue)
  1183. value = self._getValue(p)
  1184. if value:
  1185. fbb.SetValue(value) # parameter previously set
  1186. which_sizer.Add(item = fbb, proportion = 0,
  1187. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1188. # A file browse button is a combobox with two children:
  1189. # a textctl and a button;
  1190. # we have to target the button here
  1191. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1192. if p.get('age', 'new') == 'old' and \
  1193. p.get('prompt', 'input') == 'input' and \
  1194. UserSettings.Get(group = 'cmd', key = 'interactiveInput', subkey = 'enabled'):
  1195. # widget for interactive input
  1196. ifbb = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY,
  1197. style = wx.TE_MULTILINE,
  1198. size = (-1, 75))
  1199. if p.get('value', '') and os.path.isfile(p['value']):
  1200. f = open(p['value'])
  1201. ifbb.SetValue(''.join(f.readlines()))
  1202. f.close()
  1203. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1204. btnLoad = wx.Button(parent = which_panel, id = wx.ID_ANY, label = _("&Load"))
  1205. btnLoad.Bind(wx.EVT_BUTTON, self.OnFileLoad)
  1206. btnSave = wx.Button(parent = which_panel, id = wx.ID_SAVEAS)
  1207. btnSave.Bind(wx.EVT_BUTTON, self.OnFileSave)
  1208. which_sizer.Add(item = wx.StaticText(parent = which_panel, id = wx.ID_ANY,
  1209. label = _('or enter values interactively')),
  1210. proportion = 0,
  1211. flag = wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM, border = 5)
  1212. which_sizer.Add(item = ifbb, proportion = 1,
  1213. flag = wx.EXPAND | wx.RIGHT | wx.LEFT, border = 5)
  1214. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1215. btnSizer.Add(item = btnLoad, proportion = 0,
  1216. flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 10)
  1217. btnSizer.Add(item = btnSave, proportion = 0,
  1218. flag = wx.ALIGN_RIGHT)
  1219. which_sizer.Add(item = btnSizer, proportion = 0,
  1220. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  1221. p['wxId'].append(ifbb.GetId())
  1222. p['wxId'].append(btnLoad.GetId())
  1223. p['wxId'].append(btnSave.GetId())
  1224. # directory selector
  1225. elif p.get('prompt','') != 'color' and p.get('element', '') == 'dir':
  1226. fbb = filebrowse.DirBrowseButton(parent = which_panel, id = wx.ID_ANY,
  1227. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1228. dialogTitle = _('Choose %s') % \
  1229. p.get('description', _('Directory')),
  1230. buttonText = _('Browse'),
  1231. startDirectory = os.getcwd(),
  1232. changeCallback = self.OnSetValue)
  1233. value = self._getValue(p)
  1234. if value:
  1235. fbb.SetValue(value) # parameter previously set
  1236. which_sizer.Add(item = fbb, proportion = 0,
  1237. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1238. # A file browse button is a combobox with two children:
  1239. # a textctl and a button;
  1240. # we have to target the button here
  1241. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1242. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  1243. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1244. label = _("Parameterized in model"))
  1245. parChk.SetName('ModelParam')
  1246. parChk.SetValue(p.get('parameterized', False))
  1247. if 'wxId' in p:
  1248. p['wxId'].append(parChk.GetId())
  1249. else:
  1250. p['wxId'] = [ parChk.GetId() ]
  1251. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1252. which_sizer.Add(item = parChk, proportion = 0,
  1253. flag = wx.LEFT, border = 20)
  1254. if title_txt is not None:
  1255. # create tooltip if given
  1256. if len(p['values_desc']) > 0:
  1257. if tooltip:
  1258. tooltip += 2 * os.linesep
  1259. else:
  1260. tooltip = ''
  1261. if len(p['values']) == len(p['values_desc']):
  1262. for i in range(len(p['values'])):
  1263. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1264. tooltip.strip(os.linesep)
  1265. if tooltip:
  1266. title_txt.SetToolTipString(tooltip)
  1267. if p == first_param:
  1268. if 'wxId' in p and len(p['wxId']) > 0:
  1269. win = self.FindWindowById(p['wxId'][0])
  1270. win.SetFocus()
  1271. #
  1272. # set widget relations for OnUpdateSelection
  1273. #
  1274. pMap = None
  1275. pLayer = []
  1276. pDriver = None
  1277. pDatabase = None
  1278. pTable = None
  1279. pColumn = []
  1280. pGroup = None
  1281. pSubGroup = None
  1282. pDbase = None
  1283. pLocation = None
  1284. pMapset = None
  1285. for p in self.task.params:
  1286. if p.get('gisprompt', False) == False:
  1287. continue
  1288. guidep = p.get('guidependency', '')
  1289. if guidep:
  1290. # fixed options dependency defined
  1291. options = guidep.split(',')
  1292. for opt in options:
  1293. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1294. if id:
  1295. if 'wxId-bind' not in p:
  1296. p['wxId-bind'] = list()
  1297. p['wxId-bind'] += pOpt['wxId']
  1298. continue
  1299. prompt = p.get('element', '')
  1300. if prompt in ('cell', 'vector'):
  1301. name = p.get('name', '')
  1302. if name in ('map', 'input'):
  1303. pMap = p
  1304. elif prompt == 'layer':
  1305. pLayer.append(p)
  1306. elif prompt == 'dbcolumn':
  1307. pColumn.append(p)
  1308. elif prompt == 'dbdriver':
  1309. pDriver = p
  1310. elif prompt == 'dbname':
  1311. pDatabase = p
  1312. elif prompt == 'dbtable':
  1313. pTable = p
  1314. elif prompt == 'group':
  1315. pGroup = p
  1316. elif prompt == 'subgroup':
  1317. pSubGroup = p
  1318. elif prompt == 'dbase':
  1319. pDbase = p
  1320. elif prompt == 'location':
  1321. pLocation = p
  1322. elif prompt == 'mapset':
  1323. pMapset = p
  1324. # collect ids
  1325. pColumnIds = []
  1326. for p in pColumn:
  1327. pColumnIds += p['wxId']
  1328. pLayerIds = []
  1329. for p in pLayer:
  1330. pLayerIds += p['wxId']
  1331. # set wxId-bindings
  1332. if pMap:
  1333. pMap['wxId-bind'] = copy.copy(pColumnIds)
  1334. if pLayer:
  1335. pMap['wxId-bind'] += pLayerIds
  1336. if pLayer:
  1337. for p in pLayer:
  1338. p['wxId-bind'] = copy.copy(pColumnIds)
  1339. if pDriver and pTable:
  1340. pDriver['wxId-bind'] = pTable['wxId']
  1341. if pDatabase and pTable:
  1342. pDatabase['wxId-bind'] = pTable['wxId']
  1343. if pTable and pColumnIds:
  1344. pTable['wxId-bind'] = pColumnIds
  1345. if pGroup and pSubGroup:
  1346. pGroup['wxId-bind'] = pSubGroup['wxId']
  1347. if pDbase and pLocation:
  1348. pDbase['wxId-bind'] = pLocation['wxId']
  1349. if pLocation and pMapset:
  1350. pLocation['wxId-bind'] = pMapset['wxId']
  1351. if pLocation and pMapset and pMap:
  1352. pLocation['wxId-bind'] += pMap['wxId']
  1353. pMapset['wxId-bind'] = pMap['wxId']
  1354. #
  1355. # determine panel size
  1356. #
  1357. maxsizes = (0, 0)
  1358. for section in sections:
  1359. tab[section].SetSizer(tabsizer[section])
  1360. tabsizer[section].Fit(tab[section])
  1361. tab[section].Layout()
  1362. minsecsizes = tabsizer[section].GetSize()
  1363. maxsizes = map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1))
  1364. # TODO: be less arbitrary with these 600
  1365. self.panelMinHeight = 100
  1366. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1367. for section in sections:
  1368. tab[section].SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1369. if self.manual_tab.IsLoaded():
  1370. self.manual_tab.SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1371. self.SetSizer(panelsizer)
  1372. panelsizer.Fit(self.notebook)
  1373. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1374. def _getValue(self, p):
  1375. """!Get value or default value of given parameter
  1376. @param p parameter directory
  1377. """
  1378. if p.get('value', '') != '':
  1379. return p['value']
  1380. return p.get('default', '')
  1381. def OnFileLoad(self, event):
  1382. """!Load file to interactive input"""
  1383. me = event.GetId()
  1384. win = dict()
  1385. for p in self.task.params:
  1386. if 'wxId' in p and me in p['wxId']:
  1387. win['file'] = self.FindWindowById(p['wxId'][0])
  1388. win['text'] = self.FindWindowById(p['wxId'][1])
  1389. break
  1390. if not win:
  1391. return
  1392. path = win['file'].GetValue()
  1393. if not path:
  1394. gcmd.GMessage(parent = self,
  1395. message = _("Nothing to load."))
  1396. return
  1397. data = ''
  1398. f = open(path, "r")
  1399. try:
  1400. data = f.read()
  1401. finally:
  1402. f.close()
  1403. win['text'].SetValue(data)
  1404. def OnFileSave(self, event):
  1405. """!Save interactive input to the file"""
  1406. wId = event.GetId()
  1407. win = {}
  1408. for p in self.task.params:
  1409. if wId in p.get('wxId', []):
  1410. win['file'] = self.FindWindowById(p['wxId'][0])
  1411. win['text'] = self.FindWindowById(p['wxId'][1])
  1412. break
  1413. if not win:
  1414. return
  1415. text = win['text'].GetValue()
  1416. if not text:
  1417. gcmd.GMessage(parent = self,
  1418. message = _("Nothing to save."))
  1419. return
  1420. dlg = wx.FileDialog(parent = self,
  1421. message = _("Save input as..."),
  1422. defaultDir = os.getcwd(),
  1423. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  1424. if dlg.ShowModal() == wx.ID_OK:
  1425. path = dlg.GetPath()
  1426. f = open(path, "w")
  1427. try:
  1428. f.write(text + os.linesep)
  1429. finally:
  1430. f.close()
  1431. win['file'].SetValue(path)
  1432. dlg.Destroy()
  1433. def OnFileText(self, event):
  1434. """File input interactively entered"""
  1435. text = event.GetString()
  1436. p = self.task.get_param(value = event.GetId(), element = 'wxId', raiseError = False)
  1437. if not p:
  1438. return # should not happen
  1439. win = self.FindWindowById(p['wxId'][0])
  1440. if text:
  1441. filename = win.GetValue()
  1442. if not filename:
  1443. # outFile = tempfile.NamedTemporaryFile(mode = 'w+b')
  1444. filename = grass.tempfile()
  1445. win.SetValue(filename)
  1446. f = open(filename, "w")
  1447. try:
  1448. f.write(text)
  1449. if text[-1] != os.linesep:
  1450. f.write(os.linesep)
  1451. finally:
  1452. f.close()
  1453. else:
  1454. win.SetValue('')
  1455. def OnVectorFormat(self, event):
  1456. """!Change vector format (native / ogr)"""
  1457. sel = event.GetSelection()
  1458. idEvent = event.GetId()
  1459. p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
  1460. if not p:
  1461. return # should not happen
  1462. # detect windows
  1463. winNative = None
  1464. winOgr = None
  1465. for id in p['wxId']:
  1466. if id == idEvent:
  1467. continue
  1468. name = self.FindWindowById(id).GetName()
  1469. if name == 'Select':
  1470. winNative = self.FindWindowById(id + 1) # fix the mystery (also in nviz_tools.py)
  1471. elif name == 'OgrSelect':
  1472. winOgr = self.FindWindowById(id)
  1473. # enable / disable widgets & update values
  1474. rbox = self.FindWindowByName('VectorFormat')
  1475. self.hsizer.Remove(rbox)
  1476. if sel == 0: # -> native
  1477. winOgr.Hide()
  1478. self.hsizer.Remove(winOgr)
  1479. self.hsizer.Add(item = winNative,
  1480. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1481. border = 5)
  1482. winNative.Show()
  1483. p['value'] = winNative.GetValue()
  1484. elif sel == 1: # -> OGR
  1485. sizer = wx.BoxSizer(wx.VERTICAL)
  1486. winNative.Hide()
  1487. self.hsizer.Remove(winNative)
  1488. sizer.Add(item = winOgr)
  1489. winOgr.Show()
  1490. p['value'] = winOgr.GetDsn()
  1491. self.hsizer.Add(item = sizer,
  1492. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1493. border = 5)
  1494. self.hsizer.Add(item = rbox,
  1495. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1496. wx.RIGHT | wx.ALIGN_TOP,
  1497. border = 5)
  1498. self.hsizer.Layout()
  1499. self.Layout()
  1500. self.OnUpdateValues()
  1501. self.OnUpdateSelection(event)
  1502. def OnUpdateDialog(self, event):
  1503. for fn, kwargs in event.data.iteritems():
  1504. fn(**kwargs)
  1505. self.parent.updateValuesHook()
  1506. def OnVerbosity(self, event):
  1507. """!Verbosity level changed"""
  1508. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  1509. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  1510. if event.IsChecked():
  1511. if event.GetId() == verbose.GetId():
  1512. if quiet.IsChecked():
  1513. quiet.SetValue(False)
  1514. self.task.get_flag('quiet')['value'] = False
  1515. else:
  1516. if verbose.IsChecked():
  1517. verbose.SetValue(False)
  1518. self.task.get_flag('verbose')['value'] = False
  1519. event.Skip()
  1520. def OnPageChange(self, event):
  1521. if not event:
  1522. sel = self.notebook.GetSelection()
  1523. else:
  1524. sel = event.GetSelection()
  1525. idx = self.notebook.GetPageIndexByName('manual')
  1526. if idx > -1 and sel == idx:
  1527. # calling LoadPage() is strangely time-consuming (only first call)
  1528. # FIXME: move to helpPage.__init__()
  1529. if not self.manual_tab.IsLoaded():
  1530. wx.Yield()
  1531. self.manual_tab.LoadPage()
  1532. self.Layout()
  1533. def OnColorChange(self, event):
  1534. myId = event.GetId()
  1535. for p in self.task.params:
  1536. if 'wxId' in p and myId in p['wxId']:
  1537. has_button = p['wxId'][1] is not None
  1538. if has_button and wx.FindWindowById(p['wxId'][1]).GetValue() == True:
  1539. p[ 'value' ] = 'none'
  1540. else:
  1541. colorchooser = wx.FindWindowById(p['wxId'][0])
  1542. new_color = colorchooser.GetValue()[:]
  1543. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1544. # under wx2.8.1
  1545. new_label = rgb2str.get(new_color, ':'.join(map(str,new_color)))
  1546. colorchooser.SetLabel(new_label)
  1547. colorchooser.SetColour(new_color)
  1548. colorchooser.Refresh()
  1549. p[ 'value' ] = colorchooser.GetLabel()
  1550. self.OnUpdateValues()
  1551. def OnUpdateValues(self, event = None):
  1552. """!If we were part of a richer interface, report back the
  1553. current command being built.
  1554. This method should be set by the parent of this panel if
  1555. needed. It's a hook, actually. Beware of what is 'self' in
  1556. the method def, though. It will be called with no arguments.
  1557. """
  1558. pass
  1559. def OnCheckBoxMulti(self, event):
  1560. """!Fill the values as a ','-separated string according to
  1561. current status of the checkboxes.
  1562. """
  1563. me = event.GetId()
  1564. theParam = None
  1565. for p in self.task.params:
  1566. if 'wxId' in p and me in p['wxId']:
  1567. theParam = p
  1568. myIndex = p['wxId'].index(me)
  1569. # Unpack current value list
  1570. currentValues = {}
  1571. for isThere in theParam.get('value', '').split(','):
  1572. currentValues[isThere] = 1
  1573. theValue = theParam['values'][myIndex]
  1574. if event.Checked():
  1575. currentValues[ theValue ] = 1
  1576. else:
  1577. del currentValues[ theValue ]
  1578. # Keep the original order, so that some defaults may be recovered
  1579. currentValueList = []
  1580. for v in theParam['values']:
  1581. if v in currentValues:
  1582. currentValueList.append(v)
  1583. # Pack it back
  1584. theParam['value'] = ','.join(currentValueList)
  1585. self.OnUpdateValues()
  1586. def OnSetValue(self, event):
  1587. """!Retrieve the widget value and set the task value field
  1588. accordingly.
  1589. Use for widgets that have a proper GetValue() method, i.e. not
  1590. for selectors.
  1591. """
  1592. myId = event.GetId()
  1593. me = wx.FindWindowById(myId)
  1594. name = me.GetName()
  1595. found = False
  1596. for porf in self.task.params + self.task.flags:
  1597. if 'wxId' not in porf:
  1598. continue
  1599. if myId in porf['wxId']:
  1600. found = True
  1601. break
  1602. if not found:
  1603. return
  1604. if name == 'GdalSelect':
  1605. porf['value'] = event.dsn
  1606. elif name == 'ModelParam':
  1607. porf['parameterized'] = me.IsChecked()
  1608. else:
  1609. porf['value'] = me.GetValue()
  1610. self.OnUpdateValues(event)
  1611. event.Skip()
  1612. def OnSetSymbol(self, event):
  1613. """!Shows dialog for symbol selection"""
  1614. myId = event.GetId()
  1615. for p in self.task.params:
  1616. if 'wxId' in p and myId in p['wxId']:
  1617. from gui_core.dialogs import SymbolDialog
  1618. dlg = SymbolDialog(self, symbolPath = globalvar.ETCSYMBOLDIR,
  1619. currentSymbol = p['value'])
  1620. if dlg.ShowModal() == wx.ID_OK:
  1621. img = dlg.GetSelectedSymbol(fullPath = True)
  1622. p['value'] = dlg.GetSelectedSymbol(fullPath = False)
  1623. bitmapButton = wx.FindWindowById(p['wxId'][0])
  1624. label = wx.FindWindowById(p['wxId'][1])
  1625. bitmapButton.SetBitmapLabel(wx.Bitmap(img + '.png'))
  1626. label.SetLabel(p['value'])
  1627. self.OnUpdateValues(event)
  1628. dlg.Destroy()
  1629. def OnUpdateSelection(self, event):
  1630. """!Update dialog (layers, tables, columns, etc.)
  1631. """
  1632. if not hasattr(self.parent, "updateThread"):
  1633. if event:
  1634. event.Skip()
  1635. return
  1636. if event:
  1637. self.parent.updateThread.Update(UpdateDialog,
  1638. self,
  1639. event,
  1640. event.GetId(),
  1641. self.task)
  1642. else:
  1643. self.parent.updateThread.Update(UpdateDialog,
  1644. self,
  1645. None,
  1646. None,
  1647. self.task)
  1648. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  1649. """!Produce a command line string (list) or feeding into GRASS.
  1650. @param ignoreErrors True then it will return whatever has been
  1651. built so far, even though it would not be a correct command
  1652. for GRASS
  1653. """
  1654. try:
  1655. cmd = self.task.get_cmd(ignoreErrors = ignoreErrors,
  1656. ignoreRequired = ignoreRequired)
  1657. except ValueError, err:
  1658. dlg = wx.MessageDialog(parent = self,
  1659. message = unicode(err),
  1660. caption = _("Error in %s") % self.task.name,
  1661. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1662. dlg.ShowModal()
  1663. dlg.Destroy()
  1664. cmd = None
  1665. return cmd
  1666. def OnSize(self, event):
  1667. width = event.GetSize()[0]
  1668. fontsize = self.GetFont().GetPointSize()
  1669. text_width = max(width / (fontsize - 3), 70)
  1670. for id in self.label_id:
  1671. win = self.FindWindowById(id)
  1672. label = win.GetLabel()
  1673. label_new = '\n'.join(textwrap.wrap(label, text_width))
  1674. win.SetLabel(label_new)
  1675. event.Skip()
  1676. class GUI:
  1677. def __init__(self, parent = None, show = True, modal = False,
  1678. centreOnParent = False, checkError = False):
  1679. """!Parses GRASS commands when module is imported and used from
  1680. Layer Manager.
  1681. """
  1682. self.parent = parent
  1683. self.show = show
  1684. self.modal = modal
  1685. self.centreOnParent = centreOnParent
  1686. self.checkError = checkError
  1687. self.grass_task = None
  1688. self.cmd = list()
  1689. global _blackList
  1690. if self.parent:
  1691. _blackList['enabled'] = True
  1692. else:
  1693. _blackList['enabled'] = False
  1694. def GetCmd(self):
  1695. """!Get validated command"""
  1696. return self.cmd
  1697. def ParseCommand(self, cmd, gmpath = None, completed = None):
  1698. """!Parse command
  1699. Note: cmd is given as list
  1700. If command is given with options, return validated cmd list:
  1701. - add key name for first parameter if not given
  1702. - change mapname to mapname@mapset
  1703. """
  1704. start = time.time()
  1705. dcmd_params = {}
  1706. if completed == None:
  1707. get_dcmd = None
  1708. layer = None
  1709. dcmd_params = None
  1710. else:
  1711. get_dcmd = completed[0]
  1712. layer = completed[1]
  1713. if completed[2]:
  1714. dcmd_params.update(completed[2])
  1715. # parse the interface decription
  1716. try:
  1717. global _blackList
  1718. self.grass_task = gtask.parse_interface(gcmd.GetRealCmd(cmd[0]),
  1719. blackList = _blackList)
  1720. except (grass.ScriptError, ValueError), e:
  1721. raise gcmd.GException(e)
  1722. # if layer parameters previously set, re-insert them into dialog
  1723. if completed is not None:
  1724. if 'params' in dcmd_params:
  1725. self.grass_task.params = dcmd_params['params']
  1726. if 'flags' in dcmd_params:
  1727. self.grass_task.flags = dcmd_params['flags']
  1728. err = list()
  1729. # update parameters if needed && validate command
  1730. if len(cmd) > 1:
  1731. i = 0
  1732. cmd_validated = [cmd[0]]
  1733. for option in cmd[1:]:
  1734. if option[0] == '-': # flag
  1735. if option[1] == '-':
  1736. self.grass_task.set_flag(option[2:], True)
  1737. else:
  1738. self.grass_task.set_flag(option[1], True)
  1739. cmd_validated.append(option)
  1740. else: # parameter
  1741. try:
  1742. key, value = option.split('=', 1)
  1743. except:
  1744. if self.grass_task.firstParam:
  1745. if i == 0: # add key name of first parameter if not given
  1746. key = self.grass_task.firstParam
  1747. value = option
  1748. else:
  1749. raise GException, _("Unable to parse command '%s'") % ' '.join(cmd)
  1750. else:
  1751. continue
  1752. element = self.grass_task.get_param(key, raiseError = False)
  1753. if not element:
  1754. err.append(_("%(cmd)s: parameter '%(key)s' not available") % \
  1755. { 'cmd' : cmd[0],
  1756. 'key' : key })
  1757. continue
  1758. element = element['element']
  1759. if element in ['cell', 'vector']:
  1760. # mapname -> mapname@mapset
  1761. try:
  1762. name, mapset = value.split('@')
  1763. except ValueError:
  1764. mapset = grass.find_file(value, element)['mapset']
  1765. curr_mapset = grass.gisenv()['MAPSET']
  1766. if mapset and mapset != curr_mapset:
  1767. value = value + '@' + mapset
  1768. self.grass_task.set_param(key, value)
  1769. cmd_validated.append(key + '=' + value)
  1770. i += 1
  1771. # update original command list
  1772. cmd = cmd_validated
  1773. if self.show is not None:
  1774. self.mf = TaskFrame(parent = self.parent,
  1775. task_description = self.grass_task,
  1776. get_dcmd = get_dcmd, layer = layer)
  1777. else:
  1778. self.mf = None
  1779. if get_dcmd is not None:
  1780. # update only propwin reference
  1781. get_dcmd(dcmd = None, layer = layer, params = None,
  1782. propwin = self.mf)
  1783. if self.show is not None:
  1784. self.mf.notebookpanel.OnUpdateSelection(None)
  1785. if self.show is True:
  1786. if self.parent and self.centreOnParent:
  1787. self.mf.CentreOnParent()
  1788. else:
  1789. self.mf.CenterOnScreen()
  1790. self.mf.Show(self.show)
  1791. self.mf.MakeModal(self.modal)
  1792. else:
  1793. self.mf.OnApply(None)
  1794. self.cmd = cmd
  1795. if self.checkError:
  1796. return self.grass_task, err
  1797. else:
  1798. return self.grass_task
  1799. def GetCommandInputMapParamKey(self, cmd):
  1800. """!Get parameter key for input raster/vector map
  1801. @param cmd module name
  1802. @return parameter key
  1803. @return None on failure
  1804. """
  1805. # parse the interface decription
  1806. if not self.grass_task:
  1807. enc = locale.getdefaultlocale()[1]
  1808. if enc and enc.lower() == "cp932":
  1809. p = re.compile('encoding="' + enc + '"', re.IGNORECASE)
  1810. tree = etree.fromstring(p.sub('encoding="utf-8"',
  1811. gtask.get_interface_description(cmd).decode(enc).encode('utf-8')))
  1812. else:
  1813. tree = etree.fromstring(gtask.get_interface_description(cmd))
  1814. self.grass_task = gtask.processTask(tree).get_task()
  1815. for p in self.grass_task.params:
  1816. if p.get('name', '') in ('input', 'map'):
  1817. age = p.get('age', '')
  1818. prompt = p.get('prompt', '')
  1819. element = p.get('element', '')
  1820. if age == 'old' and \
  1821. element in ('cell', 'grid3', 'vector') and \
  1822. prompt in ('raster', '3d-raster', 'vector'):
  1823. return p.get('name', None)
  1824. return None
  1825. class GrassGUIApp(wx.App):
  1826. """!Stand-alone GRASS command GUI
  1827. """
  1828. def __init__(self, grass_task):
  1829. self.grass_task = grass_task
  1830. wx.App.__init__(self, False)
  1831. def OnInit(self):
  1832. msg = self.grass_task.get_error_msg()
  1833. if msg:
  1834. gcmd.GError(msg + '\n\n' +
  1835. _('Try to set up GRASS_ADDON_PATH or GRASS_ADDON_BASE variable.'))
  1836. return True
  1837. self.mf = TaskFrame(parent = None, task_description = self.grass_task)
  1838. self.mf.CentreOnScreen()
  1839. self.mf.Show(True)
  1840. self.SetTopWindow(self.mf)
  1841. return True
  1842. if __name__ == "__main__":
  1843. import gettext
  1844. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1845. if len(sys.argv) == 1:
  1846. sys.exit(_("usage: %s <grass command>") % sys.argv[0])
  1847. if sys.argv[1] != 'test':
  1848. q = wx.LogNull()
  1849. cmd = utils.split(sys.argv[1])
  1850. task = gtask.grassTask(gcmd.GetRealCmd(cmd[0]))
  1851. task.set_options(cmd[1:])
  1852. app = GrassGUIApp(task)
  1853. app.MainLoop()
  1854. else: #Test
  1855. # Test grassTask from within a GRASS session
  1856. if os.getenv("GISBASE") is not None:
  1857. task = gtask.grassTask("d.vect")
  1858. task.get_param('map')['value'] = "map_name"
  1859. task.get_flag('v')['value'] = True
  1860. task.get_param('layer')['value'] = 1
  1861. task.get_param('bcolor')['value'] = "red"
  1862. assert ' '.join(task.get_cmd()) == "d.vect -v map = map_name layer = 1 bcolor = red"
  1863. # Test interface building with handmade grassTask,
  1864. # possibly outside of a GRASS session.
  1865. task = gtask.grassTask()
  1866. task.name = "TestTask"
  1867. task.description = "This is an artificial grassTask() object intended for testing purposes."
  1868. task.keywords = ["grass","test","task"]
  1869. task.params = [
  1870. {
  1871. "name" : "text",
  1872. "description" : "Descriptions go into tooltips if labels are present, like this one",
  1873. "label" : "Enter some text",
  1874. },{
  1875. "name" : "hidden_text",
  1876. "description" : "This text should not appear in the form",
  1877. "hidden" : True
  1878. },{
  1879. "name" : "text_default",
  1880. "description" : "Enter text to override the default",
  1881. "default" : "default text"
  1882. },{
  1883. "name" : "text_prefilled",
  1884. "description" : "You should see a friendly welcome message here",
  1885. "value" : "hello, world"
  1886. },{
  1887. "name" : "plain_color",
  1888. "description" : "This is a plain color, and it is a compulsory parameter",
  1889. "required" : False,
  1890. "gisprompt" : True,
  1891. "prompt" : "color"
  1892. },{
  1893. "name" : "transparent_color",
  1894. "description" : "This color becomes transparent when set to none",
  1895. "guisection" : "tab",
  1896. "gisprompt" : True,
  1897. "prompt" : "color"
  1898. },{
  1899. "name" : "multi",
  1900. "description" : "A multiple selection",
  1901. 'default': u'red,green,blue',
  1902. 'gisprompt': False,
  1903. 'guisection': 'tab',
  1904. 'multiple': u'yes',
  1905. 'type': u'string',
  1906. 'value': '',
  1907. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other']
  1908. },{
  1909. "name" : "single",
  1910. "description" : "A single multiple-choice selection",
  1911. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  1912. "guisection" : "tab"
  1913. },{
  1914. "name" : "large_multi",
  1915. "description" : "A large multiple selection",
  1916. "gisprompt" : False,
  1917. "multiple" : "yes",
  1918. # values must be an array of strings
  1919. "values" : str2rgb.keys() + map(str, str2rgb.values())
  1920. },{
  1921. "name" : "a_file",
  1922. "description" : "A file selector",
  1923. "gisprompt" : True,
  1924. "element" : "file"
  1925. }
  1926. ]
  1927. task.flags = [
  1928. {
  1929. "name" : "a",
  1930. "description" : "Some flag, will appear in Main since it is required",
  1931. "required" : True
  1932. },{
  1933. "name" : "b",
  1934. "description" : "pre-filled flag, will appear in options since it is not required",
  1935. "value" : True
  1936. },{
  1937. "name" : "hidden_flag",
  1938. "description" : "hidden flag, should not be changeable",
  1939. "hidden" : "yes",
  1940. "value" : True
  1941. }
  1942. ]
  1943. q = wx.LogNull()
  1944. GrassGUIApp(task).MainLoop()