wxgui.py 59 KB

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