wxgui.py 59 KB

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