wxgui.py 59 KB

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