wxgui.py 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640
  1. """!
  2. @package wxgui.py
  3. @brief Main Python app for GRASS wxPython GUI. Main menu, layer management
  4. toolbar, notebook control for display management and access to
  5. command console.
  6. Classes:
  7. - GMFrame
  8. - GMApp
  9. (C) 2006-2011 by the GRASS Development Team
  10. This program is free software under the GNU General Public
  11. License (>=v2). Read the file COPYING that comes with GRASS
  12. for details.
  13. @author Michael Barton (Arizona State University)
  14. @author Jachym Cepicky (Mendel University of Agriculture)
  15. @author Martin Landa <landa.martin gmail.com>
  16. @author Vaclav Petras <wenzeslaus gmail.com> (menu customization)
  17. """
  18. import sys
  19. import os
  20. import time
  21. import string
  22. import getopt
  23. import platform
  24. import signal
  25. import tempfile
  26. ### XML
  27. try:
  28. import xml.etree.ElementTree as etree
  29. except ImportError:
  30. import elementtree.ElementTree as etree # Python <= 2.4
  31. ### i18N
  32. import gettext
  33. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  34. from gui_modules import globalvar
  35. import wx
  36. import wx.aui
  37. import wx.combo
  38. import wx.html
  39. import wx.stc
  40. try:
  41. import wx.lib.agw.customtreectrl as CT
  42. import wx.lib.agw.flatnotebook as FN
  43. except ImportError:
  44. import wx.lib.customtreectrl as CT
  45. import wx.lib.flatnotebook as FN
  46. try:
  47. import wx.lib.agw.advancedsplash as SC
  48. except ImportError:
  49. SC = None
  50. sys.path.append(os.path.join(globalvar.ETCDIR, "python"))
  51. from grass.script import core as grass
  52. from gui_modules import utils
  53. from gui_modules import preferences
  54. from gui_modules import layertree
  55. from gui_modules import mapdisp
  56. from gui_modules import menudata
  57. from gui_modules import menuform
  58. from gui_modules import histogram
  59. from gui_modules import profile
  60. from gui_modules import mcalc_builder as mapcalculator
  61. from gui_modules import gcmd
  62. from gui_modules import dbm
  63. from gui_modules import workspace
  64. from gui_modules import goutput
  65. from gui_modules import gdialogs
  66. from gui_modules import colorrules
  67. from gui_modules import ogc_services
  68. from gui_modules import prompt
  69. from gui_modules import menu
  70. from gui_modules import gmodeler
  71. from gui_modules import vclean
  72. from gui_modules import nviz_tools
  73. from gui_modules.debug import Debug
  74. from gui_modules.ghelp import MenuTreeWindow, AboutWindow, InstallExtensionWindow
  75. from gui_modules.toolbars import LayerManagerToolbar, ToolsToolbar
  76. from gui_modules.gpyshell import PyShellWindow
  77. from icons.icon import Icons
  78. UserSettings = preferences.globalSettings
  79. class GMFrame(wx.Frame):
  80. """!Layer Manager frame with notebook widget for controlling GRASS
  81. GIS. Includes command console page for typing GRASS (and other)
  82. commands, tree widget page for managing map layers.
  83. """
  84. def __init__(self, parent, id = wx.ID_ANY, title = _("GRASS GIS Layer Manager"),
  85. workspace = None,
  86. size = globalvar.GM_WINDOW_SIZE, style = wx.DEFAULT_FRAME_STYLE, **kwargs):
  87. self.parent = parent
  88. self.baseTitle = title
  89. self.iconsize = (16, 16)
  90. wx.Frame.__init__(self, parent = parent, id = id, size = size,
  91. style = style, **kwargs)
  92. self.SetTitle(self.baseTitle)
  93. self.SetName("LayerManager")
  94. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  95. self._auimgr = wx.aui.AuiManager(self)
  96. # initialize variables
  97. self.disp_idx = 0 # index value for map displays and layer trees
  98. self.curr_page = None # currently selected page for layer tree notebook
  99. self.curr_pagenum = None # currently selected page number for layer tree notebook
  100. self.workspaceFile = workspace # workspace file
  101. self.workspaceChanged = False # track changes in workspace
  102. self.georectifying = None # reference to GCP class or None
  103. self.gcpmanagement = None # reference to GCP class or None
  104. # list of open dialogs
  105. self.dialogs = dict()
  106. self.dialogs['preferences'] = None
  107. self.dialogs['atm'] = list()
  108. # creating widgets
  109. self._createMenuBar()
  110. self.statusbar = self.CreateStatusBar(number=1)
  111. self.notebook = self._createNoteBook()
  112. self.toolbars = { 'main' : LayerManagerToolbar(parent = self),
  113. 'tools' : ToolsToolbar(parent = self) }
  114. # self.SetToolBar(self.toolbar)
  115. self._auimgr.AddPane(self.toolbars['main'],
  116. wx.aui.AuiPaneInfo().
  117. Name("toolbarMain").Caption(_("Main Toolbar")).
  118. ToolbarPane().Top().
  119. LeftDockable(False).RightDockable(False).
  120. BottomDockable(False).TopDockable(True).
  121. CloseButton(False).Layer(3).
  122. BestSize((self.toolbars['main'].GetSize())))
  123. self._auimgr.AddPane(self.toolbars['tools'],
  124. wx.aui.AuiPaneInfo().
  125. Name("toolbarTools").Caption(_("Tools Toolbar")).
  126. ToolbarPane().Top().
  127. LeftDockable(False).RightDockable(False).
  128. BottomDockable(False).TopDockable(True).
  129. CloseButton(False).Layer(2).
  130. BestSize((self.toolbars['tools'].GetSize())))
  131. # bindings
  132. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  133. self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
  134. # minimal frame size
  135. self.SetMinSize((500, 400))
  136. # AUI stuff
  137. self._auimgr.AddPane(self.notebook, wx.aui.AuiPaneInfo().
  138. Left().CentrePane().BestSize((-1,-1)).Dockable(False).
  139. CloseButton(False).DestroyOnClose(True).Row(1).Layer(0))
  140. self._auimgr.Update()
  141. wx.CallAfter(self.notebook.SetSelection, 0)
  142. # use default window layout ?
  143. if UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'enabled'):
  144. dim = UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'dim')
  145. try:
  146. x, y = map(int, dim.split(',')[0:2])
  147. w, h = map(int, dim.split(',')[2:4])
  148. self.SetPosition((x, y))
  149. self.SetSize((w, h))
  150. except:
  151. pass
  152. else:
  153. self.Centre()
  154. self.Layout()
  155. self.Show()
  156. # load workspace file if requested
  157. if self.workspaceFile:
  158. # load given workspace file
  159. if self.LoadWorkspaceFile(self.workspaceFile):
  160. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  161. else:
  162. self.workspaceFile = None
  163. else:
  164. # start default initial display
  165. self.NewDisplay(show = False)
  166. # show map display widnow
  167. # -> OnSize() -> UpdateMap()
  168. if self.curr_page and not self.curr_page.maptree.mapdisplay.IsShown():
  169. self.curr_page.maptree.mapdisplay.Show()
  170. # redirect stderr to log area
  171. self.goutput.Redirect()
  172. # fix goutput's pane size
  173. self.goutput.SetSashPosition(int(self.GetSize()[1] * .45))
  174. self.workspaceChanged = False
  175. # start with layer manager on top
  176. if self.curr_page:
  177. self.curr_page.maptree.mapdisplay.Raise()
  178. wx.CallAfter(self.Raise)
  179. def _createMenuBar(self):
  180. """!Creates menu bar"""
  181. self.menubar = menu.Menu(parent = self, data = menudata.ManagerData())
  182. self.SetMenuBar(self.menubar)
  183. self.menucmd = self.menubar.GetCmd()
  184. def _createNoteBook(self):
  185. """!Creates notebook widgets"""
  186. if globalvar.hasAgw:
  187. self.notebook = FN.FlatNotebook(parent = self, id = wx.ID_ANY, agwStyle = globalvar.FNPageDStyle)
  188. else:
  189. self.notebook = FN.FlatNotebook(parent = self, id = wx.ID_ANY, style = globalvar.FNPageDStyle)
  190. # create displays notebook widget and add it to main notebook page
  191. cbStyle = globalvar.FNPageStyle
  192. if globalvar.hasAgw:
  193. self.gm_cb = FN.FlatNotebook(self, id = wx.ID_ANY, agwStyle = cbStyle)
  194. else:
  195. self.gm_cb = FN.FlatNotebook(self, id = wx.ID_ANY, style = cbStyle)
  196. self.gm_cb.SetTabAreaColour(globalvar.FNPageColor)
  197. self.notebook.AddPage(self.gm_cb, text = _("Map layers"))
  198. # create 'command output' text area
  199. self.goutput = goutput.GMConsole(self, pageid = 1)
  200. self.notebook.AddPage(self.goutput, text = _("Command console"))
  201. # create 'search module' notebook page
  202. self.search = MenuTreeWindow(parent = self)
  203. self.notebook.AddPage(self.search, text = _("Search module"))
  204. # create 'python shell' notebook page
  205. self.pyshell = PyShellWindow(parent = self)
  206. self.notebook.AddPage(self.pyshell, text = _("Python shell"))
  207. # bindings
  208. self.gm_cb.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnCBPageChanged)
  209. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
  210. self.gm_cb.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CLOSING, self.OnCBPageClosed)
  211. return self.notebook
  212. def AddNviz(self):
  213. """!Add nviz notebook page"""
  214. self.nviz = nviz_tools.NvizToolWindow(parent = self,
  215. display = self.curr_page.maptree.GetMapDisplay())
  216. self.notebook.AddPage(self.nviz, text = _("3D view"))
  217. self.notebook.SetSelection(self.notebook.GetPageCount() - 1)
  218. def RemoveNviz(self):
  219. """!Remove nviz notebook page"""
  220. # print self.notebook.GetPage(1)
  221. self.notebook.RemovePage(3)
  222. del self.nviz
  223. self.notebook.SetSelection(0)
  224. def WorkspaceChanged(self):
  225. """!Update window title"""
  226. if not self.workspaceChanged:
  227. self.workspaceChanged = True
  228. if self.workspaceFile:
  229. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile) + '*')
  230. def OnSettingsChanged(self, event):
  231. """!Here can be functions which have to be called after EVT_SETTINGS_CHANGED.
  232. Now recreates menu only.
  233. """
  234. self._createMenuBar()
  235. def OnGCPManager(self, event):
  236. """!Launch georectifier module
  237. """
  238. from gui_modules import gcpmanager
  239. gcpmanager.GCPWizard(self)
  240. def OnGModeler(self, event):
  241. """!Launch Graphical Modeler"""
  242. win = gmodeler.ModelFrame(parent = self)
  243. win.CentreOnScreen()
  244. win.Show()
  245. def OnPsMap(self, event):
  246. """!Launch Hardcopy Map Output Utility
  247. """
  248. try:
  249. from gui_modules import psmap
  250. except:
  251. gcmd.GError(parent = self.parent,
  252. message = _("Hardcopy Map Output Utility is not available. You can install it by %s") % \
  253. 'g.extension -s svnurl=https://svn.osgeo.org/grass/grass-addons extension=wx.psmap')
  254. return
  255. win = psmap.PsMapFrame(parent = self)
  256. win.CentreOnScreen()
  257. win.Show()
  258. def OnDone(self, returncode):
  259. """Command execution finised"""
  260. if hasattr(self, "model"):
  261. self.model.DeleteIntermediateData(log = self.goutput)
  262. del self.model
  263. self.SetStatusText('')
  264. def OnRunModel(self, event):
  265. """!Run model"""
  266. filename = ''
  267. dlg = wx.FileDialog(parent = self, message=_("Choose model to run"),
  268. defaultDir = os.getcwd(),
  269. wildcard=_("GRASS Model File (*.gxm)|*.gxm"))
  270. if dlg.ShowModal() == wx.ID_OK:
  271. filename = dlg.GetPath()
  272. if not filename:
  273. return
  274. self.model = gmodeler.Model()
  275. self.model.LoadModel(filename)
  276. self.SetStatusText(_('Validating model...'), 0)
  277. result = self.model.Validate()
  278. if result:
  279. dlg = wx.MessageDialog(parent = self,
  280. message = _('Model is not valid. Do you want to '
  281. 'run the model anyway?\n\n%s') % '\n'.join(errList),
  282. caption=_("Run model?"),
  283. style = wx.YES_NO | wx.NO_DEFAULT |
  284. wx.ICON_QUESTION | wx.CENTRE)
  285. ret = dlg.ShowModal()
  286. if ret != wx.ID_YES:
  287. return
  288. self.SetStatusText(_('Running model...'), 0)
  289. self.model.Run(log = self.goutput,
  290. onDone = self.OnDone)
  291. def OnMapsets(self, event):
  292. """!Launch mapset access dialog
  293. """
  294. dlg = preferences.MapsetAccess(parent = self, id = wx.ID_ANY)
  295. dlg.CenterOnScreen()
  296. if dlg.ShowModal() == wx.ID_OK:
  297. ms = dlg.GetMapsets()
  298. gcmd.RunCommand('g.mapsets',
  299. parent = self,
  300. mapset = '%s' % ','.join(ms))
  301. def OnCBPageChanged(self, event):
  302. """!Page in notebook (display) changed"""
  303. old_pgnum = event.GetOldSelection()
  304. new_pgnum = event.GetSelection()
  305. self.curr_page = self.gm_cb.GetCurrentPage()
  306. self.curr_pagenum = self.gm_cb.GetSelection()
  307. try:
  308. self.curr_page.maptree.mapdisplay.SetFocus()
  309. self.curr_page.maptree.mapdisplay.Raise()
  310. except:
  311. pass
  312. event.Skip()
  313. def OnPageChanged(self, event):
  314. """!Page in notebook changed"""
  315. page = event.GetSelection()
  316. if page == self.goutput.pageid:
  317. # remove '(...)'
  318. self.notebook.SetPageText(page, _("Command console"))
  319. wx.CallAfter(self.goutput.cmd_prompt.SetFocus)
  320. self.SetStatusText('', 0)
  321. event.Skip()
  322. def OnCBPageClosed(self, event):
  323. """!Page of notebook closed
  324. Also close associated map display
  325. """
  326. if UserSettings.Get(group = 'manager', key = 'askOnQuit', subkey = 'enabled'):
  327. maptree = self.curr_page.maptree
  328. if self.workspaceFile:
  329. message = _("Do you want to save changes in the workspace?")
  330. else:
  331. message = _("Do you want to store current settings "
  332. "to workspace file?")
  333. # ask user to save current settings
  334. if maptree.GetCount() > 0:
  335. dlg = wx.MessageDialog(self,
  336. message = message,
  337. caption = _("Close Map Display %d") % (self.curr_pagenum + 1),
  338. style = wx.YES_NO | wx.YES_DEFAULT |
  339. wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
  340. ret = dlg.ShowModal()
  341. if ret == wx.ID_YES:
  342. if not self.workspaceFile:
  343. self.OnWorkspaceSaveAs()
  344. else:
  345. self.SaveToWorkspaceFile(self.workspaceFile)
  346. elif ret == wx.ID_CANCEL:
  347. event.Veto()
  348. dlg.Destroy()
  349. return
  350. dlg.Destroy()
  351. self.gm_cb.GetPage(event.GetSelection()).maptree.Map.Clean()
  352. self.gm_cb.GetPage(event.GetSelection()).maptree.Close(True)
  353. self.curr_page = None
  354. event.Skip()
  355. def GetLayerTree(self):
  356. """!Get current layer tree"""
  357. return self.curr_page.maptree
  358. def GetLogWindow(self):
  359. """!Get widget for command output"""
  360. return self.goutput
  361. def GetMenuCmd(self, event):
  362. """!Get GRASS command from menu item
  363. Return command as a list"""
  364. layer = None
  365. if event:
  366. cmd = self.menucmd[event.GetId()]
  367. try:
  368. cmdlist = cmd.split(' ')
  369. except: # already list?
  370. cmdlist = cmd
  371. # check list of dummy commands for GUI modules that do not have GRASS
  372. # bin modules or scripts.
  373. if cmd in ['vcolors', 'r.mapcalc', 'r3.mapcalc']:
  374. return cmdlist
  375. try:
  376. layer = self.curr_page.maptree.layer_selected
  377. name = self.curr_page.maptree.GetPyData(layer)[0]['maplayer'].name
  378. type = self.curr_page.maptree.GetPyData(layer)[0]['type']
  379. except:
  380. layer = None
  381. if layer and len(cmdlist) == 1: # only if no paramaters given
  382. if (type == 'raster' and cmdlist[0][0] == 'r' and cmdlist[0][1] != '3') or \
  383. (type == 'vector' and cmdlist[0][0] == 'v'):
  384. input = menuform.GUI().GetCommandInputMapParamKey(cmdlist[0])
  385. if input:
  386. cmdlist.append("%s=%s" % (input, name))
  387. return cmdlist
  388. def RunMenuCmd(self, event = None, cmd = []):
  389. """!Run command selected from menu"""
  390. if event:
  391. cmd = self.GetMenuCmd(event)
  392. self.goutput.RunCmd(cmd, switchPage = False)
  393. def OnMenuCmd(self, event = None, cmd = []):
  394. """!Parse command selected from menu"""
  395. if event:
  396. cmd = self.GetMenuCmd(event)
  397. menuform.GUI(parent = self).ParseCommand(cmd)
  398. def OnVDigit(self, event):
  399. """!Start vector digitizer
  400. """
  401. if not self.curr_page:
  402. self.MsgNoLayerSelected()
  403. return
  404. tree = self.GetLayerTree()
  405. layer = tree.layer_selected
  406. # no map layer selected
  407. if not layer:
  408. self.MsgNoLayerSelected()
  409. return
  410. # available only for vector map layers
  411. try:
  412. mapLayer = tree.GetPyData(layer)[0]['maplayer']
  413. except:
  414. mapLayer = None
  415. if not mapLayer or mapLayer.GetType() != 'vector':
  416. gcmd.GMessage(parent = self,
  417. message = _("Selected map layer is not vector."))
  418. return
  419. if mapLayer.GetMapset() != grass.gisenv()['MAPSET']:
  420. gcmd.GMessage(parent = self,
  421. message = _("Editing is allowed only for vector maps from the "
  422. "current mapset."))
  423. return
  424. if not tree.GetPyData(layer)[0]:
  425. return
  426. dcmd = tree.GetPyData(layer)[0]['cmd']
  427. if not dcmd:
  428. return
  429. tree.OnStartEditing(None)
  430. def OnRunScript(self, event):
  431. """!Run script"""
  432. # open dialog and choose script file
  433. dlg = wx.FileDialog(parent = self, message = _("Choose script file to run"),
  434. defaultDir = os.getcwd(),
  435. wildcard = _("Python script (*.py)|*.py|Bash script (*.sh)|*.sh"))
  436. filename = None
  437. if dlg.ShowModal() == wx.ID_OK:
  438. filename = dlg.GetPath()
  439. if not filename:
  440. return False
  441. if not os.path.exists(filename):
  442. gcmd.GError(parent = self,
  443. message = _("Script file '%s' doesn't exist. "
  444. "Operation cancelled.") % filename)
  445. return
  446. self.goutput.WriteCmdLog(_("Launching script '%s'...") % filename)
  447. self.goutput.RunCmd([filename], switchPage = True)
  448. def OnChangeLocation(self, event):
  449. """Change current location"""
  450. dlg = gdialogs.LocationDialog(parent = self)
  451. if dlg.ShowModal() == wx.ID_OK:
  452. location, mapset = dlg.GetValues()
  453. if location and mapset:
  454. ret = gcmd.RunCommand("g.gisenv",
  455. set = "LOCATION_NAME=%s" % location)
  456. ret += gcmd.RunCommand("g.gisenv",
  457. set = "MAPSET=%s" % mapset)
  458. if ret > 0:
  459. wx.MessageBox(parent = self,
  460. message = _("Unable to switch to location <%(loc)s> mapset <%(mapset)s>.") % \
  461. { 'loc' : location, 'mapset' : mapset },
  462. caption = _("Error"), style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  463. else:
  464. # close workspace
  465. self.OnWorkspaceClose()
  466. self.OnWorkspaceNew()
  467. wx.MessageBox(parent = self,
  468. message = _("Current location is <%(loc)s>.\n"
  469. "Current mapset is <%(mapset)s>.") % \
  470. { 'loc' : location, 'mapset' : mapset },
  471. caption = _("Info"), style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  472. def OnChangeMapset(self, event):
  473. """Change current mapset"""
  474. dlg = gdialogs.MapsetDialog(parent = self)
  475. if dlg.ShowModal() == wx.ID_OK:
  476. mapset = dlg.GetMapset()
  477. if mapset:
  478. if gcmd.RunCommand("g.gisenv",
  479. set = "MAPSET=%s" % mapset) != 0:
  480. wx.MessageBox(parent = self,
  481. message = _("Unable to switch to mapset <%s>.") % mapset,
  482. caption = _("Error"), style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  483. else:
  484. wx.MessageBox(parent = self,
  485. message = _("Current mapset is <%s>.") % mapset,
  486. caption = _("Info"), style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  487. def OnNewVector(self, event):
  488. """!Create new vector map layer"""
  489. name, add = gdialogs.CreateNewVector(self, log = self.goutput,
  490. cmd = (('v.edit',
  491. { 'tool' : 'create' },
  492. 'map')))
  493. if name and add:
  494. # add layer to map layer tree
  495. self.curr_page.maptree.AddLayer(ltype = 'vector',
  496. lname = name,
  497. lchecked = True,
  498. lopacity = 1.0,
  499. lcmd = ['d.vect', 'map=%s' % name])
  500. def OnAboutGRASS(self, event):
  501. """!Display 'About GRASS' dialog"""
  502. win = AboutWindow(self)
  503. win.CentreOnScreen()
  504. win.Show(True)
  505. def _popupMenu(self, data):
  506. """!Create popup menu
  507. """
  508. point = wx.GetMousePosition()
  509. menu = wx.Menu()
  510. for key, handler in data:
  511. if key is None:
  512. menu.AppendSeparator()
  513. continue
  514. item = wx.MenuItem(menu, wx.ID_ANY, Icons['layerManager'][key].GetLabel())
  515. item.SetBitmap(Icons['layerManager'][key].GetBitmap(self.iconsize))
  516. menu.AppendItem(item)
  517. self.Bind(wx.EVT_MENU, handler, item)
  518. # create menu
  519. self.PopupMenu(menu)
  520. menu.Destroy()
  521. def OnNewMenu(self, event):
  522. """!New display/workspace menu
  523. """
  524. self._popupMenu((('newdisplay', self.OnNewDisplay),
  525. ('workspaceNew', self.OnWorkspaceNew)))
  526. def OnLoadMenu(self, event):
  527. """!Load maps menu (new, load, import, link)
  528. """
  529. self._popupMenu((('workspaceLoad', self.OnWorkspaceLoad),
  530. (None, None),
  531. ('rastImport', self.OnImportGdalLayers),
  532. ('rastLink', self.OnLinkGdalLayers),
  533. (None, None),
  534. ('vectImport', self.OnImportOgrLayers),
  535. ('vectLink', self.OnLinkOgrLayers)))
  536. def OnWorkspaceNew(self, event = None):
  537. """!Create new workspace file
  538. Erase current workspace settings first
  539. """
  540. Debug.msg(4, "GMFrame.OnWorkspaceNew():")
  541. # start new map display if no display is available
  542. if not self.curr_page:
  543. self.NewDisplay()
  544. maptree = self.curr_page.maptree
  545. # ask user to save current settings
  546. if self.workspaceFile and self.workspaceChanged:
  547. self.OnWorkspaceSave()
  548. elif self.workspaceFile is None and maptree.GetCount() > 0:
  549. dlg = wx.MessageDialog(self, message = _("Current workspace is not empty. "
  550. "Do you want to store current settings "
  551. "to workspace file?"),
  552. caption = _("Create new workspace?"),
  553. style = wx.YES_NO | wx.YES_DEFAULT | \
  554. wx.CANCEL | wx.ICON_QUESTION)
  555. ret = dlg.ShowModal()
  556. if ret == wx.ID_YES:
  557. self.OnWorkspaceSaveAs()
  558. elif ret == wx.ID_CANCEL:
  559. dlg.Destroy()
  560. return
  561. dlg.Destroy()
  562. # delete all items
  563. maptree.DeleteAllItems()
  564. # add new root element
  565. maptree.root = maptree.AddRoot("Map Layers")
  566. self.curr_page.maptree.SetPyData(maptree.root, (None,None))
  567. # no workspace file loaded
  568. self.workspaceFile = None
  569. self.workspaceChanged = False
  570. self.SetTitle(self.baseTitle)
  571. def OnWorkspaceOpen(self, event = None):
  572. """!Open file with workspace definition"""
  573. dlg = wx.FileDialog(parent = self, message = _("Choose workspace file"),
  574. defaultDir = os.getcwd(), wildcard = _("GRASS Workspace File (*.gxw)|*.gxw"))
  575. filename = ''
  576. if dlg.ShowModal() == wx.ID_OK:
  577. filename = dlg.GetPath()
  578. if filename == '':
  579. return
  580. Debug.msg(4, "GMFrame.OnWorkspaceOpen(): filename=%s" % filename)
  581. # delete current layer tree content
  582. self.OnWorkspaceClose()
  583. self.LoadWorkspaceFile(filename)
  584. self.workspaceFile = filename
  585. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  586. def LoadWorkspaceFile(self, filename):
  587. """!Load layer tree definition stored in GRASS Workspace XML file (gxw)
  588. @todo Validate against DTD
  589. @return True on success
  590. @return False on error
  591. """
  592. # dtd
  593. dtdFilename = os.path.join(globalvar.ETCWXDIR, "xml", "grass-gxw.dtd")
  594. # parse workspace file
  595. try:
  596. gxwXml = workspace.ProcessWorkspaceFile(etree.parse(filename))
  597. except Exception, e:
  598. gcmd.GError(parent = self,
  599. message = _("Reading workspace file <%s> failed.\n"
  600. "Invalid file, unable to parse XML document.") % filename)
  601. return
  602. busy = wx.BusyInfo(message = _("Please wait, loading workspace..."),
  603. parent = self)
  604. wx.Yield()
  605. #
  606. # load layer manager window properties
  607. #
  608. if UserSettings.Get(group = 'workspace', key = 'posManager', subkey = 'enabled') is False:
  609. if gxwXml.layerManager['pos']:
  610. self.SetPosition(gxwXml.layerManager['pos'])
  611. if gxwXml.layerManager['size']:
  612. self.SetSize(gxwXml.layerManager['size'])
  613. #
  614. # start map displays first (list of layers can be empty)
  615. #
  616. displayId = 0
  617. mapdisplay = list()
  618. for display in gxwXml.displays:
  619. mapdisp = self.NewDisplay(show = False)
  620. mapdisplay.append(mapdisp)
  621. maptree = self.gm_cb.GetPage(displayId).maptree
  622. # set windows properties
  623. mapdisp.SetProperties(render = display['render'],
  624. mode = display['mode'],
  625. showCompExtent = display['showCompExtent'],
  626. constrainRes = display['constrainRes'],
  627. projection = display['projection']['enabled'])
  628. if display['projection']['enabled']:
  629. if display['projection']['epsg']:
  630. UserSettings.Set(group = 'display', key = 'projection', subkey = 'epsg',
  631. value = display['projection']['epsg'])
  632. if display['projection']['proj']:
  633. UserSettings.Set(group = 'display', key = 'projection', subkey = 'proj4',
  634. value = display['projection']['proj'])
  635. # set position and size of map display
  636. if UserSettings.Get(group = 'workspace', key = 'posDisplay', subkey = 'enabled') is False:
  637. if display['pos']:
  638. mapdisp.SetPosition(display['pos'])
  639. if display['size']:
  640. mapdisp.SetSize(display['size'])
  641. # set extent if defined
  642. if display['extent']:
  643. w, s, e, n = display['extent']
  644. region = maptree.Map.region = maptree.Map.GetRegion(w = w, s = s, e = e, n = n)
  645. mapdisp.GetWindow().ResetZoomHistory()
  646. mapdisp.GetWindow().ZoomHistory(region['n'],
  647. region['s'],
  648. region['e'],
  649. region['w'])
  650. mapdisp.Show()
  651. displayId += 1
  652. maptree = None
  653. selected = [] # list of selected layers
  654. #
  655. # load list of map layers
  656. #
  657. for layer in gxwXml.layers:
  658. display = layer['display']
  659. maptree = self.gm_cb.GetPage(display).maptree
  660. newItem = maptree.AddLayer(ltype = layer['type'],
  661. lname = layer['name'],
  662. lchecked = layer['checked'],
  663. lopacity = layer['opacity'],
  664. lcmd = layer['cmd'],
  665. lgroup = layer['group'],
  666. lnviz = layer['nviz'],
  667. lvdigit = layer['vdigit'])
  668. if layer.has_key('selected'):
  669. if layer['selected']:
  670. selected.append((maptree, newItem))
  671. else:
  672. maptree.SelectItem(newItem, select = False)
  673. for maptree, layer in selected:
  674. if not maptree.IsSelected(layer):
  675. maptree.SelectItem(layer, select = True)
  676. maptree.layer_selected = layer
  677. busy.Destroy()
  678. if maptree:
  679. # reverse list of map layers
  680. maptree.Map.ReverseListOfLayers()
  681. for mdisp in mapdisplay:
  682. mdisp.MapWindow2D.UpdateMap()
  683. return True
  684. def OnWorkspaceLoad(self, event = None):
  685. """!Load given map layers into layer tree"""
  686. dialog = gdialogs.LoadMapLayersDialog(parent = self, title = _("Load map layers into layer tree"))
  687. if dialog.ShowModal() == wx.ID_OK:
  688. # start new map display if no display is available
  689. if not self.curr_page:
  690. self.NewDisplay()
  691. maptree = self.curr_page.maptree
  692. busy = wx.BusyInfo(message = _("Please wait, loading workspace..."),
  693. parent = self)
  694. wx.Yield()
  695. for layerName in dialog.GetMapLayers():
  696. if dialog.GetLayerType() == 'raster':
  697. cmd = ['d.rast', 'map=%s' % layerName]
  698. elif dialog.GetLayerType() == 'vector':
  699. cmd = ['d.vect', 'map=%s' % layerName]
  700. newItem = maptree.AddLayer(ltype = dialog.GetLayerType(),
  701. lname = layerName,
  702. lchecked = False,
  703. lopacity = 1.0,
  704. lcmd = cmd,
  705. lgroup = None)
  706. busy.Destroy()
  707. def OnWorkspaceLoadGrcFile(self, event):
  708. """!Load map layers from GRC file (Tcl/Tk GUI) into map layer tree"""
  709. dlg = wx.FileDialog(parent = self, message = _("Choose GRC file to load"),
  710. defaultDir = os.getcwd(), wildcard = _("Old GRASS Workspace File (*.grc)|*.grc"))
  711. filename = ''
  712. if dlg.ShowModal() == wx.ID_OK:
  713. filename = dlg.GetPath()
  714. if filename == '':
  715. return
  716. Debug.msg(4, "GMFrame.OnWorkspaceLoadGrcFile(): filename=%s" % filename)
  717. # start new map display if no display is available
  718. if not self.curr_page:
  719. self.NewDisplay()
  720. busy = wx.BusyInfo(message = _("Please wait, loading workspace..."),
  721. parent = self)
  722. wx.Yield()
  723. maptree = None
  724. for layer in workspace.ProcessGrcFile(filename).read(self):
  725. maptree = self.gm_cb.GetPage(layer['display']).maptree
  726. newItem = maptree.AddLayer(ltype = layer['type'],
  727. lname = layer['name'],
  728. lchecked = layer['checked'],
  729. lopacity = layer['opacity'],
  730. lcmd = layer['cmd'],
  731. lgroup = layer['group'])
  732. busy.Destroy()
  733. if maptree:
  734. # reverse list of map layers
  735. maptree.Map.ReverseListOfLayers()
  736. def OnWorkspaceSaveAs(self, event = None):
  737. """!Save workspace definition to selected file"""
  738. dlg = wx.FileDialog(parent = self, message = _("Choose file to save current workspace"),
  739. defaultDir = os.getcwd(), wildcard = _("GRASS Workspace File (*.gxw)|*.gxw"), style = wx.FD_SAVE)
  740. filename = ''
  741. if dlg.ShowModal() == wx.ID_OK:
  742. filename = dlg.GetPath()
  743. if filename == '':
  744. return False
  745. # check for extension
  746. if filename[-4:] != ".gxw":
  747. filename += ".gxw"
  748. if os.path.exists(filename):
  749. dlg = wx.MessageDialog(self, message = _("Workspace file <%s> already exists. "
  750. "Do you want to overwrite this file?") % filename,
  751. caption = _("Save workspace"), style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  752. if dlg.ShowModal() != wx.ID_YES:
  753. dlg.Destroy()
  754. return False
  755. Debug.msg(4, "GMFrame.OnWorkspaceSaveAs(): filename=%s" % filename)
  756. self.SaveToWorkspaceFile(filename)
  757. self.workspaceFile = filename
  758. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  759. def OnWorkspaceSave(self, event = None):
  760. """!Save file with workspace definition"""
  761. if self.workspaceFile:
  762. dlg = wx.MessageDialog(self, message = _("Workspace file <%s> already exists. "
  763. "Do you want to overwrite this file?") % \
  764. self.workspaceFile,
  765. caption = _("Save workspace"), style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  766. if dlg.ShowModal() == wx.ID_NO:
  767. dlg.Destroy()
  768. else:
  769. Debug.msg(4, "GMFrame.OnWorkspaceSave(): filename=%s" % self.workspaceFile)
  770. self.SaveToWorkspaceFile(self.workspaceFile)
  771. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  772. self.workspaceChanged = False
  773. else:
  774. self.OnWorkspaceSaveAs()
  775. def SaveToWorkspaceFile(self, filename):
  776. """!Save layer tree layout to workspace file
  777. Return True on success, False on error
  778. """
  779. tmpfile = tempfile.TemporaryFile(mode = 'w+b')
  780. try:
  781. workspace.WriteWorkspaceFile(lmgr = self, file = tmpfile)
  782. except StandardError, e:
  783. gcmd.GError(parent = self,
  784. message = _("Writing current settings to workspace file "
  785. "failed."))
  786. return False
  787. try:
  788. mfile = open(filename, "w")
  789. tmpfile.seek(0)
  790. for line in tmpfile.readlines():
  791. mfile.write(line)
  792. except IOError:
  793. gcmd.GError(parent = self,
  794. message = _("Unable to open file <%s> for writing.") % filename)
  795. return False
  796. mfile.close()
  797. return True
  798. def OnWorkspaceClose(self, event = None):
  799. """!Close file with workspace definition
  800. If workspace has been modified ask user to save the changes.
  801. """
  802. Debug.msg(4, "GMFrame.OnWorkspaceClose(): file=%s" % self.workspaceFile)
  803. self.OnDisplayCloseAll()
  804. self.workspaceFile = None
  805. self.workspaceChanged = False
  806. self.SetTitle(self.baseTitle)
  807. self.disp_idx = 0
  808. self.curr_page = None
  809. def OnDisplayClose(self, event = None):
  810. """!Close current map display window
  811. """
  812. if self.curr_page and self.curr_page.maptree.mapdisplay:
  813. self.curr_page.maptree.mapdisplay.OnCloseWindow(event)
  814. def OnDisplayCloseAll(self, event = None):
  815. """!Close all open map display windows
  816. """
  817. displays = list()
  818. for page in range(0, self.gm_cb.GetPageCount()):
  819. displays.append(self.gm_cb.GetPage(page).maptree.mapdisplay)
  820. for display in displays:
  821. display.OnCloseWindow(event)
  822. def RulesCmd(self, event):
  823. """!Launches dialog for commands that need rules input and
  824. processes rules
  825. """
  826. cmd = self.GetMenuCmd(event)
  827. if cmd[0] == 'r.colors':
  828. ctable = colorrules.ColorTable(self, raster = True)
  829. else:
  830. ctable = colorrules.ColorTable(self, raster = False)
  831. ctable.CentreOnScreen()
  832. ctable.Show()
  833. def OnInstallExtension(self, event):
  834. """!Install extension from GRASS Addons SVN repository"""
  835. win = InstallExtensionWindow(self, size = (650, 550))
  836. win.CentreOnScreen()
  837. win.Show()
  838. def OnPreferences(self, event):
  839. """!General GUI preferences/settings
  840. """
  841. if not self.dialogs['preferences']:
  842. dlg = preferences.PreferencesDialog(parent = self)
  843. self.dialogs['preferences'] = dlg
  844. self.dialogs['preferences'].CenterOnScreen()
  845. dlg.Bind(preferences.EVT_SETTINGS_CHANGED, self.OnSettingsChanged)
  846. self.dialogs['preferences'].ShowModal()
  847. def OnHelp(self, event):
  848. """!Show help
  849. """
  850. self.goutput.RunCmd(['g.manual','-i'])
  851. def DispHistogram(self, event):
  852. """
  853. Init histogram display canvas and tools
  854. """
  855. self.histogram = histogram.HistFrame(self,
  856. id = wx.ID_ANY, pos = wx.DefaultPosition, size = (400,300),
  857. style = wx.DEFAULT_FRAME_STYLE)
  858. #show new display
  859. self.histogram.Show()
  860. self.histogram.Refresh()
  861. self.histogram.Update()
  862. def DispProfile(self, event):
  863. """
  864. Init profile canvas and tools
  865. """
  866. self.profile = profile.ProfileFrame(self,
  867. id = wx.ID_ANY, pos = wx.DefaultPosition, size = (400,300),
  868. style = wx.DEFAULT_FRAME_STYLE)
  869. self.profile.Show()
  870. self.profile.Refresh()
  871. self.profile.Update()
  872. def OnMapCalculator(self, event, cmd = ''):
  873. """!Init map calculator for interactive creation of mapcalc statements
  874. """
  875. if event:
  876. try:
  877. cmd = self.GetMenuCmd(event)
  878. except KeyError:
  879. cmd = ['r.mapcalc']
  880. win = mapcalculator.MapCalcFrame(parent = self,
  881. cmd = cmd[0])
  882. win.CentreOnScreen()
  883. win.Show()
  884. def OnVectorCleaning(self, event, cmd = ''):
  885. """!Init interactive vector cleaning
  886. """
  887. if event:
  888. cmd = self.GetMenuCmd(event)
  889. win = vclean.VectorCleaningFrame(parent = self, cmd = cmd[0])
  890. win.CentreOnScreen()
  891. win.Show()
  892. def OnImportDxfFile(self, event, cmd = None):
  893. """!Convert multiple DXF layers to GRASS vector map layers"""
  894. dlg = gdialogs.DxfImportDialog(parent = self)
  895. dlg.CentreOnScreen()
  896. dlg.Show()
  897. def OnImportGdalLayers(self, event, cmd = None):
  898. """!Convert multiple GDAL layers to GRASS raster map layers"""
  899. dlg = gdialogs.GdalImportDialog(parent = self)
  900. dlg.CentreOnScreen()
  901. dlg.Show()
  902. def OnLinkGdalLayers(self, event, cmd = None):
  903. """!Link multiple GDAL layers to GRASS raster map layers"""
  904. dlg = gdialogs.GdalImportDialog(parent = self, link = True)
  905. dlg.CentreOnScreen()
  906. dlg.Show()
  907. def OnImportOgrLayers(self, event, cmd = None):
  908. """!Convert multiple OGR layers to GRASS vector map layers"""
  909. dlg = gdialogs.GdalImportDialog(parent = self, ogr = True)
  910. dlg.CentreOnScreen()
  911. dlg.Show()
  912. def OnLinkOgrLayers(self, event, cmd = None):
  913. """!Links multiple OGR layers to GRASS vector map layers"""
  914. dlg = gdialogs.GdalImportDialog(parent = self, ogr = True, link = True)
  915. dlg.CentreOnScreen()
  916. dlg.Show()
  917. def OnImportWMS(self, event):
  918. """!Import data from OGC WMS server"""
  919. dlg = ogc_services.WMSDialog(parent = self, service = 'wms')
  920. dlg.CenterOnScreen()
  921. if dlg.ShowModal() == wx.ID_OK: # -> import layers
  922. layers = dlg.GetLayers()
  923. if len(layers.keys()) > 0:
  924. for layer in layers.keys():
  925. cmd = ['r.in.wms',
  926. 'mapserver=%s' % dlg.GetSettings()['server'],
  927. 'layers=%s' % layer,
  928. 'output=%s' % layer,
  929. 'format=png',
  930. '--overwrite']
  931. styles = ','.join(layers[layer])
  932. if styles:
  933. cmd.append('styles=%s' % styles)
  934. self.goutput.RunCmd(cmd, switchPage = True)
  935. self.curr_page.maptree.AddLayer(ltype = 'raster',
  936. lname = layer,
  937. lcmd = ['d.rast', 'map=%s' % layer],
  938. multiple = False)
  939. else:
  940. self.goutput.WriteWarning(_("Nothing to import. No WMS layer selected."))
  941. dlg.Destroy()
  942. def OnShowAttributeTable(self, event):
  943. """!Show attribute table of the given vector map layer
  944. """
  945. if not self.curr_page:
  946. self.MsgNoLayerSelected()
  947. return
  948. tree = self.GetLayerTree()
  949. layer = tree.layer_selected
  950. # no map layer selected
  951. if not layer:
  952. self.MsgNoLayerSelected()
  953. return
  954. # available only for vector map layers
  955. try:
  956. maptype = tree.GetPyData(layer)[0]['maplayer'].type
  957. except:
  958. maptype = None
  959. if not maptype or maptype != 'vector':
  960. gcmd.GMessage(parent = self,
  961. message = _("Selected map layer is not vector."))
  962. return
  963. if not tree.GetPyData(layer)[0]:
  964. return
  965. dcmd = tree.GetPyData(layer)[0]['cmd']
  966. if not dcmd:
  967. return
  968. busy = wx.BusyInfo(message = _("Please wait, loading attribute data..."),
  969. parent = self)
  970. wx.Yield()
  971. dbmanager = dbm.AttributeManager(parent = self, id = wx.ID_ANY,
  972. size = wx.Size(500, 300),
  973. item = layer, log = self.goutput)
  974. busy.Destroy()
  975. # register ATM dialog
  976. self.dialogs['atm'].append(dbmanager)
  977. # show ATM window
  978. dbmanager.Show()
  979. def OnNewDisplay(self, event = None):
  980. """!Create new layer tree and map display instance"""
  981. self.NewDisplay()
  982. def NewDisplay(self, show = True):
  983. """!Create new layer tree, which will
  984. create an associated map display frame
  985. @param show show map display window if True
  986. @return reference to mapdisplay intance
  987. """
  988. Debug.msg(1, "GMFrame.NewDisplay(): idx=%d" % self.disp_idx)
  989. # make a new page in the bookcontrol for the layer tree (on page 0 of the notebook)
  990. self.pg_panel = wx.Panel(self.gm_cb, id = wx.ID_ANY, style = wx.EXPAND)
  991. self.gm_cb.AddPage(self.pg_panel, text = "Display "+ str(self.disp_idx + 1), select = True)
  992. self.curr_page = self.gm_cb.GetCurrentPage()
  993. # create layer tree (tree control for managing GIS layers) and put on new notebook page
  994. self.curr_page.maptree = layertree.LayerTree(self.curr_page, id = wx.ID_ANY, pos = wx.DefaultPosition,
  995. size = wx.DefaultSize, style = wx.TR_HAS_BUTTONS |
  996. wx.TR_LINES_AT_ROOT| wx.TR_HIDE_ROOT |
  997. wx.TR_DEFAULT_STYLE| wx.NO_BORDER | wx.FULL_REPAINT_ON_RESIZE,
  998. idx = self.disp_idx, lmgr = self, notebook = self.gm_cb,
  999. auimgr = self._auimgr, showMapDisplay = show)
  1000. # layout for controls
  1001. cb_boxsizer = wx.BoxSizer(wx.VERTICAL)
  1002. cb_boxsizer.Add(self.curr_page.maptree, proportion = 1, flag = wx.EXPAND, border = 1)
  1003. self.curr_page.SetSizer(cb_boxsizer)
  1004. cb_boxsizer.Fit(self.curr_page.maptree)
  1005. self.curr_page.Layout()
  1006. self.curr_page.maptree.Layout()
  1007. # use default window layout
  1008. if UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'enabled'):
  1009. dim = UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'dim')
  1010. idx = 4 + self.disp_idx * 4
  1011. try:
  1012. x, y = map(int, dim.split(',')[idx:idx + 2])
  1013. w, h = map(int, dim.split(',')[idx + 2:idx + 4])
  1014. self.curr_page.maptree.mapdisplay.SetPosition((x, y))
  1015. self.curr_page.maptree.mapdisplay.SetSize((w, h))
  1016. except:
  1017. pass
  1018. self.disp_idx += 1
  1019. return self.curr_page.maptree.mapdisplay
  1020. def OnAddRaster(self, event):
  1021. """!Add raster map layer"""
  1022. # start new map display if no display is available
  1023. if not self.curr_page:
  1024. self.NewDisplay(show = True)
  1025. self.notebook.SetSelection(0)
  1026. self.curr_page.maptree.AddLayer('raster')
  1027. def OnAddRaster3D(self, event):
  1028. """!Add 3D raster map layer"""
  1029. # start new map display if no display is available
  1030. if not self.curr_page:
  1031. self.NewDisplay(show = True)
  1032. self.AddRaster3D(event)
  1033. def OnAddRasterMisc(self, event):
  1034. """!Create misc raster popup-menu"""
  1035. # start new map display if no display is available
  1036. if not self.curr_page:
  1037. self.NewDisplay(show = True)
  1038. self._popupMenu((('addRast3d', self.OnAddRaster3D),
  1039. (None, None),
  1040. ('addRgb', self.OnAddRasterRGB),
  1041. ('addHis', self.OnAddRasterHIS),
  1042. (None, None),
  1043. ('addShaded', self.OnAddRasterShaded),
  1044. (None, None),
  1045. ('addRArrow', self.OnAddRasterArrow),
  1046. ('addRNum', self.OnAddRasterNum)))
  1047. # show map display
  1048. self.curr_page.maptree.mapdisplay.Show()
  1049. def OnAddVector(self, event):
  1050. """!Add vector map to the current layer tree"""
  1051. # start new map display if no display is available
  1052. if not self.curr_page:
  1053. self.NewDisplay(show = True)
  1054. self.notebook.SetSelection(0)
  1055. self.curr_page.maptree.AddLayer('vector')
  1056. def OnAddVectorMisc(self, event):
  1057. """!Create misc vector popup-menu"""
  1058. # start new map display if no display is available
  1059. if not self.curr_page:
  1060. self.NewDisplay(show = True)
  1061. self._popupMenu((('addThematic', self.OnAddVectorTheme),
  1062. ('addChart', self.OnAddVectorChart)))
  1063. # show map display
  1064. self.curr_page.maptree.mapdisplay.Show()
  1065. def OnAddVectorTheme(self, event):
  1066. """!Add thematic vector map to the current layer tree"""
  1067. self.notebook.SetSelection(0)
  1068. self.curr_page.maptree.AddLayer('thememap')
  1069. def OnAddVectorChart(self, event):
  1070. """!Add chart vector map to the current layer tree"""
  1071. self.notebook.SetSelection(0)
  1072. self.curr_page.maptree.AddLayer('themechart')
  1073. def OnAddOverlay(self, event):
  1074. """!Create decoration overlay menu"""
  1075. # start new map display if no display is available
  1076. if not self.curr_page:
  1077. self.NewDisplay(show = True)
  1078. self._popupMenu((('addGrid', self.OnAddGrid),
  1079. ('addLabels', self.OnAddLabels),
  1080. ('addGeodesic', self.OnAddGeodesic),
  1081. ('addRhumb', self.OnAddRhumb),
  1082. (None, None),
  1083. ('addCmd', self.OnAddCommand)))
  1084. # show map display
  1085. self.curr_page.maptree.mapdisplay.Show()
  1086. def OnAddRaster3D(self, event):
  1087. """!Add 3D raster map to the current layer tree"""
  1088. self.notebook.SetSelection(0)
  1089. self.curr_page.maptree.AddLayer('3d-raster')
  1090. def OnAddRasterRGB(self, event):
  1091. """!Add RGB raster map to the current layer tree"""
  1092. self.notebook.SetSelection(0)
  1093. self.curr_page.maptree.AddLayer('rgb')
  1094. def OnAddRasterHIS(self, event):
  1095. """!Add HIS raster map to the current layer tree"""
  1096. self.notebook.SetSelection(0)
  1097. self.curr_page.maptree.AddLayer('his')
  1098. def OnAddRasterShaded(self, event):
  1099. """!Add shaded relief raster map to the current layer tree"""
  1100. self.notebook.SetSelection(0)
  1101. self.curr_page.maptree.AddLayer('shaded')
  1102. def OnAddRasterArrow(self, event):
  1103. """!Add flow arrows raster map to the current layer tree"""
  1104. self.notebook.SetSelection(0)
  1105. self.curr_page.maptree.AddLayer('rastarrow')
  1106. def OnAddRasterNum(self, event):
  1107. """!Add cell number raster map to the current layer tree"""
  1108. self.notebook.SetSelection(0)
  1109. self.curr_page.maptree.AddLayer('rastnum')
  1110. def OnAddCommand(self, event):
  1111. """!Add command line map layer to the current layer tree"""
  1112. # start new map display if no display is available
  1113. if not self.curr_page:
  1114. self.NewDisplay(show = True)
  1115. self.notebook.SetSelection(0)
  1116. self.curr_page.maptree.AddLayer('command')
  1117. # show map display
  1118. self.curr_page.maptree.mapdisplay.Show()
  1119. def OnAddGroup(self, event):
  1120. """!Add layer group"""
  1121. # start new map display if no display is available
  1122. if not self.curr_page:
  1123. self.NewDisplay(show = True)
  1124. self.notebook.SetSelection(0)
  1125. self.curr_page.maptree.AddLayer('group')
  1126. # show map display
  1127. self.curr_page.maptree.mapdisplay.Show()
  1128. def OnAddGrid(self, event):
  1129. """!Add grid map layer to the current layer tree"""
  1130. self.notebook.SetSelection(0)
  1131. self.curr_page.maptree.AddLayer('grid')
  1132. def OnAddGeodesic(self, event):
  1133. """!Add geodesic line map layer to the current layer tree"""
  1134. self.notebook.SetSelection(0)
  1135. self.curr_page.maptree.AddLayer('geodesic')
  1136. def OnAddRhumb(self, event):
  1137. """!Add rhumb map layer to the current layer tree"""
  1138. self.notebook.SetSelection(0)
  1139. self.curr_page.maptree.AddLayer('rhumb')
  1140. def OnAddLabels(self, event):
  1141. """!Add vector labels map layer to the current layer tree"""
  1142. # start new map display if no display is available
  1143. if not self.curr_page:
  1144. self.NewDisplay(show = True)
  1145. self.notebook.SetSelection(0)
  1146. self.curr_page.maptree.AddLayer('labels')
  1147. # show map display
  1148. self.curr_page.maptree.mapdisplay.Show()
  1149. def OnDeleteLayer(self, event):
  1150. """!Remove selected map layer from the current layer Tree
  1151. """
  1152. if not self.curr_page or not self.curr_page.maptree.layer_selected:
  1153. self.MsgNoLayerSelected()
  1154. return
  1155. if UserSettings.Get(group = 'manager', key = 'askOnRemoveLayer', subkey = 'enabled'):
  1156. layerName = ''
  1157. for item in self.curr_page.maptree.GetSelections():
  1158. name = str(self.curr_page.maptree.GetItemText(item))
  1159. idx = name.find('(opacity')
  1160. if idx > -1:
  1161. layerName += '<' + name[:idx].strip(' ') + '>,\n'
  1162. else:
  1163. layerName += '<' + name + '>,\n'
  1164. layerName = layerName.rstrip(',\n')
  1165. if len(layerName) > 2: # <>
  1166. message = _("Do you want to remove map layer(s)\n%s\n"
  1167. "from layer tree?") % layerName
  1168. else:
  1169. message = _("Do you want to remove selected map layer(s) "
  1170. "from layer tree?")
  1171. dlg = wx.MessageDialog (parent = self, message = message,
  1172. caption = _("Remove map layer"),
  1173. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  1174. if dlg.ShowModal() != wx.ID_YES:
  1175. dlg.Destroy()
  1176. return
  1177. dlg.Destroy()
  1178. for layer in self.curr_page.maptree.GetSelections():
  1179. if self.curr_page.maptree.GetPyData(layer)[0]['type'] == 'group':
  1180. self.curr_page.maptree.DeleteChildren(layer)
  1181. self.curr_page.maptree.Delete(layer)
  1182. def OnKeyDown(self, event):
  1183. """!Key pressed"""
  1184. kc = event.GetKeyCode()
  1185. if event.ControlDown():
  1186. if kc == wx.WXK_TAB:
  1187. # switch layer list / command output
  1188. if self.notebook.GetSelection() == 0:
  1189. self.notebook.SetSelection(1)
  1190. else:
  1191. self.notebook.SetSelection(0)
  1192. try:
  1193. ckc = chr(kc)
  1194. except ValueError:
  1195. event.Skip()
  1196. return
  1197. if event.CtrlDown():
  1198. if kc == 'R':
  1199. self.OnAddRaster(None)
  1200. elif kc == 'V':
  1201. self.OnAddVector(None)
  1202. event.Skip()
  1203. def OnCloseWindow(self, event):
  1204. """!Cleanup when wxGUI is quitted"""
  1205. if not self.curr_page:
  1206. self._auimgr.UnInit()
  1207. self.Destroy()
  1208. return
  1209. maptree = self.curr_page.maptree
  1210. if self.workspaceChanged and \
  1211. UserSettings.Get(group = 'manager', key = 'askOnQuit', subkey = 'enabled'):
  1212. if self.workspaceFile:
  1213. message = _("Do you want to save changes in the workspace?")
  1214. else:
  1215. message = _("Do you want to store current settings "
  1216. "to workspace file?")
  1217. # ask user to save current settings
  1218. if maptree.GetCount() > 0:
  1219. dlg = wx.MessageDialog(self,
  1220. message = message,
  1221. caption = _("Quit GRASS GUI"),
  1222. style = wx.YES_NO | wx.YES_DEFAULT |
  1223. wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
  1224. ret = dlg.ShowModal()
  1225. if ret == wx.ID_YES:
  1226. if not self.workspaceFile:
  1227. self.OnWorkspaceSaveAs()
  1228. else:
  1229. self.SaveToWorkspaceFile(self.workspaceFile)
  1230. elif ret == wx.ID_CANCEL:
  1231. event.Veto()
  1232. dlg.Destroy()
  1233. return
  1234. dlg.Destroy()
  1235. # don't ask any more...
  1236. UserSettings.Set(group = 'manager', key = 'askOnQuit', subkey = 'enabled',
  1237. value = False)
  1238. self.OnDisplayCloseAll()
  1239. self.gm_cb.DeleteAllPages()
  1240. self._auimgr.UnInit()
  1241. self.Destroy()
  1242. def MsgNoLayerSelected(self):
  1243. """!Show dialog message 'No layer selected'"""
  1244. wx.MessageBox(parent = self,
  1245. message = _("No map layer selected. Operation cancelled."),
  1246. caption = _("Message"),
  1247. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1248. class GMApp(wx.App):
  1249. def __init__(self, workspace = None):
  1250. """!Main GUI class.
  1251. @param workspace path to the workspace file
  1252. """
  1253. self.workspaceFile = workspace
  1254. # call parent class initializer
  1255. wx.App.__init__(self, False)
  1256. self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
  1257. def OnInit(self):
  1258. """!Initialize all available image handlers
  1259. @return True
  1260. """
  1261. wx.InitAllImageHandlers()
  1262. # create splash screen
  1263. introImagePath = os.path.join(globalvar.ETCIMGDIR, "silesia_splash.png")
  1264. introImage = wx.Image(introImagePath, wx.BITMAP_TYPE_PNG)
  1265. introBmp = introImage.ConvertToBitmap()
  1266. if SC:
  1267. splash = SC.AdvancedSplash(bitmap = introBmp,
  1268. timeout = 2000, parent = None, id = wx.ID_ANY)
  1269. splash.SetText(_('Starting GRASS GUI...'))
  1270. splash.SetTextColour(wx.Colour(45, 52, 27))
  1271. splash.SetTextFont(wx.Font(pointSize = 15, family = wx.DEFAULT, style = wx.NORMAL,
  1272. weight = wx.BOLD))
  1273. splash.SetTextPosition((150, 430))
  1274. else:
  1275. wx.SplashScreen (bitmap = introBmp, splashStyle = wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
  1276. milliseconds = 2000, parent = None, id = wx.ID_ANY)
  1277. wx.Yield()
  1278. w, h = wx.GetDisplaySize()
  1279. if globalvar.MAP_WINDOW_SIZE[0] + globalvar.GM_WINDOW_SIZE[0] > w:
  1280. gmX = w - globalvar.GM_WINDOW_SIZE[0]
  1281. dim = '%d,0,%d,%d,0,0,%d,%d' % \
  1282. (gmX,
  1283. globalvar.GM_WINDOW_SIZE[0],
  1284. globalvar.GM_WINDOW_SIZE[1],
  1285. globalvar.MAP_WINDOW_SIZE[0],
  1286. globalvar.MAP_WINDOW_SIZE[1])
  1287. UserSettings.Set(group = 'general', key = 'defWindowPos',
  1288. subkey = 'dim', value = dim)
  1289. # create and show main frame
  1290. mainframe = GMFrame(parent = None, id = wx.ID_ANY,
  1291. workspace = self.workspaceFile)
  1292. mainframe.Show()
  1293. self.SetTopWindow(mainframe)
  1294. return True
  1295. class Usage(Exception):
  1296. def __init__(self, msg):
  1297. self.msg = msg
  1298. def printHelp():
  1299. """!Print program help"""
  1300. print >> sys.stderr, "Usage:"
  1301. print >> sys.stderr, " python wxgui.py [options]"
  1302. print >> sys.stderr, "%sOptions:" % os.linesep
  1303. print >> sys.stderr, " -w\t--workspace file\tWorkspace file to load"
  1304. sys.exit(0)
  1305. def process_opt(opts, args):
  1306. """!Process command-line arguments"""
  1307. workspaceFile = None
  1308. for o, a in opts:
  1309. if o in ("-h", "--help"):
  1310. printHelp()
  1311. if o in ("-w", "--workspace"):
  1312. if a != '':
  1313. workspaceFile = str(a)
  1314. else:
  1315. workspaceFile = args.pop(0)
  1316. return (workspaceFile,)
  1317. def main(argv = None):
  1318. #
  1319. # process command-line arguments
  1320. #
  1321. if argv is None:
  1322. argv = sys.argv
  1323. try:
  1324. try:
  1325. opts, args = getopt.getopt(argv[1:], "hw:",
  1326. ["help", "workspace"])
  1327. except getopt.error, msg:
  1328. raise Usage(msg)
  1329. except Usage, err:
  1330. print >> sys.stderr, err.msg
  1331. print >> sys.stderr, "for help use --help"
  1332. printHelp()
  1333. workspaceFile = process_opt(opts, args)[0]
  1334. #
  1335. # run application
  1336. #
  1337. app = GMApp(workspaceFile)
  1338. # suppress wxPython logs
  1339. q = wx.LogNull()
  1340. app.MainLoop()
  1341. if __name__ == "__main__":
  1342. sys.exit(main())