wxgui.py 60 KB

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