wxgui.py 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642
  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. import signal
  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 OnRunScript(self, event):
  377. """!Run script"""
  378. # open dialog and choose script file
  379. dlg = wx.FileDialog(parent = self, message = _("Choose script file"),
  380. defaultDir = os.getcwd(), wildcard = _("Bash script (*.sh)|*.sh|Python script (*.py)|*.py"))
  381. filename = None
  382. if dlg.ShowModal() == wx.ID_OK:
  383. filename = dlg.GetPath()
  384. if not filename:
  385. return False
  386. if not os.path.exists(filename):
  387. wx.MessageBox(parent = self,
  388. message = _("Script file '%s' doesn't exist. Operation cancelled.") % filename,
  389. caption = _("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  390. return
  391. self.goutput.WriteCmdLog(_("Launching script '%s'...") % filename)
  392. self.goutput.RunCmd(filename, switchPage = True)
  393. def OnChangeLocation(self, event):
  394. """Change current location"""
  395. dlg = gdialogs.LocationDialog(parent = self)
  396. if dlg.ShowModal() == wx.ID_OK:
  397. location, mapset = dlg.GetValues()
  398. if location and mapset:
  399. ret = gcmd.RunCommand("g.gisenv",
  400. set = "LOCATION_NAME=%s" % location)
  401. ret += gcmd.RunCommand("g.gisenv",
  402. set = "MAPSET=%s" % mapset)
  403. if ret > 0:
  404. wx.MessageBox(parent = self,
  405. message = _("Unable to switch to location <%(loc)s> mapset <%(mapset)s>.") % \
  406. { 'loc' : location, 'mapset' : mapset },
  407. caption = _("Error"), style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  408. else:
  409. # close workspace
  410. self.OnWorkspaceClose()
  411. self.OnWorkspaceNew()
  412. wx.MessageBox(parent = self,
  413. message = _("Current location is <%(loc)s>.\n"
  414. "Current mapset is <%(mapset)s>.") % \
  415. { 'loc' : location, 'mapset' : mapset },
  416. caption = _("Info"), style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  417. def OnChangeMapset(self, event):
  418. """Change current mapset"""
  419. dlg = gdialogs.MapsetDialog(parent = self)
  420. if dlg.ShowModal() == wx.ID_OK:
  421. mapset = dlg.GetMapset()
  422. if mapset:
  423. if gcmd.RunCommand("g.gisenv",
  424. set = "MAPSET=%s" % mapset) != 0:
  425. wx.MessageBox(parent = self,
  426. message = _("Unable to switch to mapset <%s>.") % mapset,
  427. caption = _("Error"), style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  428. else:
  429. wx.MessageBox(parent = self,
  430. message = _("Current mapset is <%s>.") % mapset,
  431. caption = _("Info"), style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  432. def OnNewVector(self, event):
  433. """!Create new vector map layer"""
  434. name, add = gdialogs.CreateNewVector(self, log = self.goutput,
  435. cmd = (('v.edit',
  436. { 'tool' : 'create' },
  437. 'map')))
  438. if name and add:
  439. # add layer to map layer tree
  440. self.curr_page.maptree.AddLayer(ltype='vector',
  441. lname=name,
  442. lchecked=True,
  443. lopacity=1.0,
  444. lcmd=['d.vect', 'map=%s' % name])
  445. def OnMenuTree(self, event):
  446. """!Show dialog with menu tree"""
  447. dlg = MenuTreeWindow(self)
  448. dlg.CentreOnScreen()
  449. dlg.Show()
  450. def OnAboutGRASS(self, event):
  451. """!Display 'About GRASS' dialog"""
  452. win = AboutWindow(self)
  453. win.Centre()
  454. win.Show(True)
  455. def OnWorkspace(self, event):
  456. """!Workspace menu (new, load)"""
  457. point = wx.GetMousePosition()
  458. menu = wx.Menu()
  459. # Add items to the menu
  460. new = wx.MenuItem(menu, wx.ID_ANY, Icons["workspaceNew"].GetLabel())
  461. new.SetBitmap(Icons["workspaceNew"].GetBitmap(self.iconsize))
  462. menu.AppendItem(new)
  463. self.Bind(wx.EVT_MENU, self.OnWorkspaceNew, new)
  464. load = wx.MenuItem(menu, wx.ID_ANY, Icons["workspaceLoad"].GetLabel())
  465. load.SetBitmap(Icons["workspaceLoad"].GetBitmap(self.iconsize))
  466. menu.AppendItem(load)
  467. self.Bind(wx.EVT_MENU, self.OnWorkspaceLoad, load)
  468. # create menu
  469. self.PopupMenu(menu)
  470. menu.Destroy()
  471. def OnWorkspaceNew(self, event=None):
  472. """!Create new workspace file
  473. Erase current workspace settings first"""
  474. Debug.msg(4, "GMFrame.OnWorkspaceNew():")
  475. # start new map display if no display is available
  476. if not self.curr_page:
  477. self.NewDisplay()
  478. maptree = self.curr_page.maptree
  479. # ask user to save current settings
  480. if maptree.GetCount() > 0:
  481. dlg = wx.MessageDialog(self, message=_("Current workspace is not empty. "
  482. "Do you want to store current settings "
  483. "to workspace file?"),
  484. caption=_("Create new workspace?"),
  485. style=wx.YES_NO | wx.YES_DEFAULT | \
  486. wx.CANCEL | wx.ICON_QUESTION)
  487. ret = dlg.ShowModal()
  488. if ret == wx.ID_YES:
  489. self.OnWorkspaceSaveAs()
  490. elif ret == wx.ID_CANCEL:
  491. dlg.Destroy()
  492. return
  493. dlg.Destroy()
  494. # delete all items
  495. maptree.DeleteAllItems()
  496. # add new root element
  497. maptree.root = maptree.AddRoot("Map Layers")
  498. self.curr_page.maptree.SetPyData(maptree.root, (None,None))
  499. # no workspace file loaded
  500. self.workspaceFile = None
  501. self.SetTitle(self.baseTitle)
  502. def OnWorkspaceOpen(self, event=None):
  503. """!Open file with workspace definition"""
  504. dlg = wx.FileDialog(parent=self, message=_("Choose workspace file"),
  505. defaultDir=os.getcwd(), wildcard=_("GRASS Workspace File (*.gxw)|*.gxw"))
  506. filename = ''
  507. if dlg.ShowModal() == wx.ID_OK:
  508. filename = dlg.GetPath()
  509. if filename == '':
  510. return
  511. Debug.msg(4, "GMFrame.OnWorkspaceOpen(): filename=%s" % filename)
  512. # delete current layer tree content
  513. self.OnWorkspaceClose()
  514. self.LoadWorkspaceFile(filename)
  515. self.workspaceFile = filename
  516. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  517. def LoadWorkspaceFile(self, filename):
  518. """!Load layer tree definition stored in GRASS Workspace XML file (gxw)
  519. @todo Validate against DTD
  520. @return True on success
  521. @return False on error
  522. """
  523. # dtd
  524. dtdFilename = os.path.join(globalvar.ETCWXDIR, "xml", "grass-gxw.dtd")
  525. # parse workspace file
  526. try:
  527. gxwXml = workspace.ProcessWorkspaceFile(etree.parse(filename))
  528. except Exception, err:
  529. raise gcmd.GStdError(_("Reading workspace file <%(file)s> failed.\n"
  530. "Invalid file, unable to parse XML document."
  531. "\n\n%(err)s") % { 'file' : filename, 'err': err},
  532. parent = self)
  533. busy = wx.BusyInfo(message=_("Please wait, loading workspace..."),
  534. parent=self)
  535. wx.Yield()
  536. #
  537. # load layer manager window properties
  538. #
  539. if UserSettings.Get(group='workspace', key='posManager', subkey='enabled') is False:
  540. if gxwXml.layerManager['pos']:
  541. self.SetPosition(gxwXml.layerManager['pos'])
  542. if gxwXml.layerManager['size']:
  543. self.SetSize(gxwXml.layerManager['size'])
  544. #
  545. # start map displays first (list of layers can be empty)
  546. #
  547. displayId = 0
  548. mapdisplay = []
  549. for display in gxwXml.displays:
  550. mapdisplay.append(self.NewDisplay(show=False))
  551. maptree = self.gm_cb.GetPage(displayId).maptree
  552. # set windows properties
  553. mapdisplay[-1].SetProperties(render=display['render'],
  554. mode=display['mode'],
  555. showCompExtent=display['showCompExtent'],
  556. constrainRes=display['constrainRes'],
  557. projection=display['projection']['enabled'])
  558. if display['projection']['enabled']:
  559. if display['projection']['epsg']:
  560. UserSettings.Set(group = 'display', key = 'projection', subkey = 'epsg',
  561. value = display['projection']['epsg'])
  562. if display['projection']['proj']:
  563. UserSettings.Set(group = 'display', key = 'projection', subkey = 'proj4',
  564. value = display['projection']['proj'])
  565. # set position and size of map display
  566. if UserSettings.Get(group='workspace', key='posDisplay', subkey='enabled') is False:
  567. if display['pos']:
  568. mapdisplay[-1].SetPosition(display['pos'])
  569. if display['size']:
  570. mapdisplay[-1].SetSize(display['size'])
  571. # set extent if defined
  572. if display['extent']:
  573. w, s, e, n = display['extent']
  574. maptree.Map.region = maptree.Map.GetRegion(w=w, s=s, e=e, n=n)
  575. mapdisplay[-1].Show()
  576. displayId += 1
  577. maptree = None
  578. selected = [] # list of selected layers
  579. #
  580. # load list of map layers
  581. #
  582. for layer in gxwXml.layers:
  583. display = layer['display']
  584. maptree = self.gm_cb.GetPage(display).maptree
  585. newItem = maptree.AddLayer(ltype=layer['type'],
  586. lname=layer['name'],
  587. lchecked=layer['checked'],
  588. lopacity=layer['opacity'],
  589. lcmd=layer['cmd'],
  590. lgroup=layer['group'],
  591. lnviz=layer['nviz'],
  592. lvdigit=layer['vdigit'])
  593. if layer.has_key('selected'):
  594. if layer['selected']:
  595. selected.append((maptree, newItem))
  596. else:
  597. maptree.SelectItem(newItem, select=False)
  598. for maptree, layer in selected:
  599. if not maptree.IsSelected(layer):
  600. maptree.SelectItem(layer, select=True)
  601. maptree.layer_selected = layer
  602. busy.Destroy()
  603. if maptree:
  604. # reverse list of map layers
  605. maptree.Map.ReverseListOfLayers()
  606. for mdisp in mapdisplay:
  607. mdisp.MapWindow2D.UpdateMap()
  608. return True
  609. def OnWorkspaceLoad(self, event=None):
  610. """!Load given map layers into layer tree"""
  611. dialog = gdialogs.LoadMapLayersDialog(parent=self, title=_("Load map layers into layer tree"))
  612. if dialog.ShowModal() == wx.ID_OK:
  613. # start new map display if no display is available
  614. if not self.curr_page:
  615. self.NewDisplay()
  616. maptree = self.curr_page.maptree
  617. busy = wx.BusyInfo(message=_("Please wait, loading workspace..."),
  618. parent=self)
  619. wx.Yield()
  620. for layerName in dialog.GetMapLayers():
  621. if dialog.GetLayerType() == 'raster':
  622. cmd = ['d.rast', 'map=%s' % layerName]
  623. elif dialog.GetLayerType() == 'vector':
  624. cmd = ['d.vect', 'map=%s' % layerName]
  625. newItem = maptree.AddLayer(ltype=dialog.GetLayerType(),
  626. lname=layerName,
  627. lchecked=True,
  628. lopacity=1.0,
  629. lcmd=cmd,
  630. lgroup=None)
  631. busy.Destroy()
  632. def OnWorkspaceLoadGrcFile(self, event):
  633. """!Load map layers from GRC file (Tcl/Tk GUI) into map layer tree"""
  634. dlg = wx.FileDialog(parent=self, message=_("Choose GRC file to load"),
  635. defaultDir=os.getcwd(), wildcard=_("Old GRASS Workspace File (*.grc)|*.grc"))
  636. filename = ''
  637. if dlg.ShowModal() == wx.ID_OK:
  638. filename = dlg.GetPath()
  639. if filename == '':
  640. return
  641. Debug.msg(4, "GMFrame.OnWorkspaceLoadGrcFile(): filename=%s" % filename)
  642. # start new map display if no display is available
  643. if not self.curr_page:
  644. self.NewDisplay()
  645. busy = wx.BusyInfo(message=_("Please wait, loading workspace..."),
  646. parent=self)
  647. wx.Yield()
  648. maptree = None
  649. for layer in workspace.ProcessGrcFile(filename).read(self):
  650. maptree = self.gm_cb.GetPage(layer['display']).maptree
  651. newItem = maptree.AddLayer(ltype=layer['type'],
  652. lname=layer['name'],
  653. lchecked=layer['checked'],
  654. lopacity=layer['opacity'],
  655. lcmd=layer['cmd'],
  656. lgroup=layer['group'])
  657. busy.Destroy()
  658. if maptree:
  659. # reverse list of map layers
  660. maptree.Map.ReverseListOfLayers()
  661. def OnWorkspaceSaveAs(self, event=None):
  662. """!Save workspace definition to selected file"""
  663. dlg = wx.FileDialog(parent=self, message=_("Choose file to save current workspace"),
  664. defaultDir=os.getcwd(), wildcard=_("GRASS Workspace File (*.gxw)|*.gxw"), style=wx.FD_SAVE)
  665. filename = ''
  666. if dlg.ShowModal() == wx.ID_OK:
  667. filename = dlg.GetPath()
  668. if filename == '':
  669. return False
  670. # check for extension
  671. if filename[-4:] != ".gxw":
  672. filename += ".gxw"
  673. if os.path.exists(filename):
  674. dlg = wx.MessageDialog(self, message=_("Workspace file <%s> already exists. "
  675. "Do you want to overwrite this file?") % filename,
  676. caption=_("Save workspace"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  677. if dlg.ShowModal() != wx.ID_YES:
  678. dlg.Destroy()
  679. return False
  680. Debug.msg(4, "GMFrame.OnWorkspaceSaveAs(): filename=%s" % filename)
  681. self.SaveToWorkspaceFile(filename)
  682. self.workspaceFile = filename
  683. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  684. def OnWorkspaceSave(self, event=None):
  685. """!Save file with workspace definition"""
  686. if self.workspaceFile:
  687. dlg = wx.MessageDialog(self, message=_("Workspace file <%s> already exists. "
  688. "Do you want to overwrite this file?") % \
  689. self.workspaceFile,
  690. caption=_("Save workspace"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  691. if dlg.ShowModal() == wx.ID_NO:
  692. dlg.Destroy()
  693. else:
  694. Debug.msg(4, "GMFrame.OnWorkspaceSave(): filename=%s" % self.workspaceFile)
  695. self.SaveToWorkspaceFile(self.workspaceFile)
  696. else:
  697. self.OnWorkspaceSaveAs()
  698. def SaveToWorkspaceFile(self, filename):
  699. """!Save layer tree layout to workspace file
  700. Return True on success, False on error
  701. """
  702. try:
  703. file = open(filename, "w")
  704. except IOError:
  705. wx.MessageBox(parent=self,
  706. message=_("Unable to open workspace file <%s> for writing.") % filename,
  707. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  708. return False
  709. try:
  710. workspace.WriteWorkspaceFile(lmgr=self, file=file)
  711. except StandardError, e:
  712. file.close()
  713. wx.MessageBox(parent=self,
  714. message=_("Writing current settings to workspace file failed (%s)." % e),
  715. caption=_("Error"),
  716. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  717. return False
  718. file.close()
  719. return True
  720. def OnWorkspaceClose(self, event=None):
  721. """!Close file with workspace definition
  722. If workspace has been modified ask user to save the changes.
  723. """
  724. Debug.msg(4, "GMFrame.OnWorkspaceClose(): file=%s" % self.workspaceFile)
  725. self.workspaceFile = None
  726. self.SetTitle(self.baseTitle)
  727. displays = []
  728. for page in range(0, self.gm_cb.GetPageCount()):
  729. displays.append(self.gm_cb.GetPage(page).maptree.mapdisplay)
  730. for display in displays:
  731. display.OnCloseWindow(event)
  732. self.disp_idx = 0
  733. self.curr_page = None
  734. def RulesCmd(self, event, cmd = ''):
  735. """
  736. Launches dialog for commands that need rules
  737. input and processes rules
  738. """
  739. if event:
  740. cmd = self.GetMenuCmd(event)
  741. if cmd[0] == 'r.colors' or cmd[0] == 'vcolors':
  742. ctable = colorrules.ColorTable(self, cmd=cmd[0])
  743. ctable.Show()
  744. else:
  745. dlg = rules.RulesText(self, cmd=cmd)
  746. dlg.CenterOnScreen()
  747. if dlg.ShowModal() == wx.ID_OK:
  748. gtemp = utils.GetTempfile()
  749. output = open(gtemp, "w")
  750. try:
  751. output.write(dlg.rules)
  752. finally:
  753. output.close()
  754. cmdlist = [cmd[0],
  755. 'input=%s' % dlg.inmap,
  756. 'output=%s' % dlg.outmap,
  757. 'rules=%s' % gtemp]
  758. if dlg.overwrite == True:
  759. cmdlist.append('--o')
  760. dlg.Destroy()
  761. self.goutput.RunCmd(cmdlist)
  762. def OnPreferences(self, event):
  763. """!General GUI preferences/settings"""
  764. if not self.dialogs['preferences']:
  765. dlg = preferences.PreferencesDialog(parent=self)
  766. self.dialogs['preferences'] = dlg
  767. self.dialogs['preferences'].CenterOnScreen()
  768. self.dialogs['preferences'].ShowModal()
  769. def DispHistogram(self, event):
  770. """
  771. Init histogram display canvas and tools
  772. """
  773. self.histogram = histogram.HistFrame(self,
  774. id=wx.ID_ANY, pos=wx.DefaultPosition, size=(400,300),
  775. style=wx.DEFAULT_FRAME_STYLE)
  776. #show new display
  777. self.histogram.Show()
  778. self.histogram.Refresh()
  779. self.histogram.Update()
  780. def DispProfile(self, event):
  781. """
  782. Init profile canvas and tools
  783. """
  784. self.profile = profile.ProfileFrame(self,
  785. id=wx.ID_ANY, pos=wx.DefaultPosition, size=(400,300),
  786. style=wx.DEFAULT_FRAME_STYLE)
  787. self.profile.Show()
  788. self.profile.Refresh()
  789. self.profile.Update()
  790. def DispMapCalculator(self, event):
  791. """
  792. Init map calculator for interactive creation of mapcalc statements
  793. """
  794. self.mapcalculator = mapcalculator.MapCalcFrame(self, wx.ID_ANY, title='',
  795. dimension=2)
  796. def Disp3DMapCalculator(self, event):
  797. """
  798. Init map calculator for interactive creation of mapcalc statements
  799. """
  800. self.mapcalculator = mapcalculator.MapCalcFrame(self, wx.ID_ANY, title='',
  801. dimension=3)
  802. def AddToolbarButton(self, toolbar, label, icon, help, handler):
  803. """!Adds button to the given toolbar"""
  804. if not label:
  805. toolbar.AddSeparator()
  806. return
  807. tool = toolbar.AddLabelTool(id=wx.ID_ANY, label=label, bitmap=icon, shortHelp=help)
  808. self.Bind(wx.EVT_TOOL, handler, tool)
  809. def ToolbarData(self):
  810. return (
  811. ('newdisplay', Icons["newdisplay"].GetBitmap(),
  812. Icons["newdisplay"].GetLabel(), self.OnNewDisplay),
  813. ('', '', '', ''),
  814. ('workspaceLoad', Icons["workspaceLoad"].GetBitmap(),
  815. Icons["workspaceLoad"].GetLabel(), self.OnWorkspace),
  816. ('workspaceOpen', Icons["workspaceOpen"].GetBitmap(),
  817. Icons["workspaceOpen"].GetLabel(), self.OnWorkspaceOpen),
  818. ('workspaceSave', Icons["workspaceSave"].GetBitmap(),
  819. Icons["workspaceSave"].GetLabel(), self.OnWorkspaceSave),
  820. ('', '', '', ''),
  821. ('addrast', Icons["addrast"].GetBitmap(),
  822. Icons["addrast"].GetLabel(), self.OnAddRaster),
  823. ('addshaded', Icons["addshaded"].GetBitmap(),
  824. _("Add various raster-based map layers"), self.OnAddRasterMisc),
  825. ('addvect', Icons["addvect"].GetBitmap(),
  826. Icons["addvect"].GetLabel(), self.OnAddVector),
  827. ('addthematic', Icons["addthematic"].GetBitmap(),
  828. _("Add various vector-based map layer"), self.OnAddVectorMisc),
  829. ('addcmd', Icons["addcmd"].GetBitmap(),
  830. Icons["addcmd"].GetLabel(), self.OnAddCommand),
  831. ('addgrp', Icons["addgrp"].GetBitmap(),
  832. Icons["addgrp"].GetLabel(), self.OnAddGroup),
  833. ('addovl', Icons["addovl"].GetBitmap(),
  834. Icons["addovl"].GetLabel(), self.OnAddOverlay),
  835. ('delcmd', Icons["delcmd"].GetBitmap(),
  836. Icons["delcmd"].GetLabel(), self.OnDeleteLayer),
  837. ('', '', '', ''),
  838. ('attrtable', Icons["attrtable"].GetBitmap(),
  839. Icons["attrtable"].GetLabel(), self.OnShowAttributeTable)
  840. )
  841. def OnImportDxfFile(self, event):
  842. """!Convert multiple DXF layers to GRASS vector map layers"""
  843. dlg = gdialogs.MultiImportDialog(parent=self, type='dxf',
  844. title=_("Import DXF layers"))
  845. dlg.ShowModal()
  846. def OnImportGdalLayers(self, event):
  847. """!Convert multiple GDAL layers to GRASS raster map layers"""
  848. dlg = gdialogs.MultiImportDialog(parent=self, type='gdal',
  849. title=_("Import GDAL layers"))
  850. dlg.ShowModal()
  851. def OnLinkGdalLayers(self, event):
  852. """!Link multiple GDAL layers to GRASS raster map layers"""
  853. dlg = gdialogs.MultiImportDialog(parent=self, type='gdal',
  854. title=_("Link GDAL layers"),
  855. link = True)
  856. dlg.ShowModal()
  857. def OnImportOgrLayers(self, event):
  858. """!Convert multiple OGR layers to GRASS vector map layers"""
  859. dlg = gdialogs.MultiImportDialog(parent=self, type='ogr',
  860. title=_("Import OGR layers"))
  861. dlg.ShowModal()
  862. def OnLinkOgrLayers(self, event):
  863. """!Links multiple OGR layers to GRASS vector map layers"""
  864. dlg = gdialogs.MultiImportDialog(parent=self, type='ogr',
  865. title=_("Link OGR layers"),
  866. link = True)
  867. dlg.ShowModal()
  868. def OnImportWMS(self, event):
  869. """!Import data from OGC WMS server"""
  870. dlg = ogc_services.WMSDialog(parent = self, service = 'wms')
  871. dlg.CenterOnScreen()
  872. if dlg.ShowModal() == wx.ID_OK: # -> import layers
  873. layers = dlg.GetLayers()
  874. if len(layers.keys()) > 0:
  875. for layer in layers.keys():
  876. cmd = ['r.in.wms',
  877. 'mapserver=%s' % dlg.GetSettings()['server'],
  878. 'layers=%s' % layer,
  879. 'output=%s' % layer]
  880. styles = ','.join(layers[layer])
  881. if styles:
  882. cmd.append('styles=%s' % styles)
  883. self.goutput.RunCmd(cmd, switchPage = True)
  884. else:
  885. self.goutput.WriteWarning(_("Nothing to import. No WMS layer selected."))
  886. dlg.Destroy()
  887. def OnShowAttributeTable(self, event):
  888. """
  889. Show attribute table of the given vector map layer
  890. """
  891. if not self.curr_page:
  892. self.MsgNoLayerSelected()
  893. return
  894. layer = self.curr_page.maptree.layer_selected
  895. # no map layer selected
  896. if not layer:
  897. self.MsgNoLayerSelected()
  898. return
  899. # available only for vector map layers
  900. try:
  901. maptype = self.curr_page.maptree.GetPyData(layer)[0]['maplayer'].type
  902. except:
  903. maptype = None
  904. if not maptype or maptype != 'vector':
  905. wx.MessageBox(parent=self,
  906. message=_("Attribute management is available only "
  907. "for vector maps."),
  908. caption=_("Message"),
  909. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  910. return
  911. if not self.curr_page.maptree.GetPyData(layer)[0]:
  912. return
  913. dcmd = self.curr_page.maptree.GetPyData(layer)[0]['cmd']
  914. if not dcmd:
  915. return
  916. busy = wx.BusyInfo(message=_("Please wait, loading attribute data..."),
  917. parent=self)
  918. wx.Yield()
  919. dbmanager = dbm.AttributeManager(parent=self, id=wx.ID_ANY,
  920. size=wx.Size(500, 300),
  921. item=layer, log=self.goutput)
  922. busy.Destroy()
  923. # register ATM dialog
  924. self.dialogs['atm'].append(dbmanager)
  925. # show ATM window
  926. dbmanager.Show()
  927. def OnNewDisplay(self, event=None):
  928. """!Create new layer tree and map display instance"""
  929. self.NewDisplay()
  930. def NewDisplay(self, show=True):
  931. """!Create new layer tree, which will
  932. create an associated map display frame
  933. @param show show map display window if True
  934. @return reference to mapdisplay intance
  935. """
  936. Debug.msg(1, "GMFrame.NewDisplay(): idx=%d" % self.disp_idx)
  937. # make a new page in the bookcontrol for the layer tree (on page 0 of the notebook)
  938. self.pg_panel = wx.Panel(self.gm_cb, id=wx.ID_ANY, style= wx.EXPAND)
  939. self.gm_cb.AddPage(self.pg_panel, text="Display "+ str(self.disp_idx + 1), select = True)
  940. self.curr_page = self.gm_cb.GetCurrentPage()
  941. # create layer tree (tree control for managing GIS layers) and put on new notebook page
  942. self.curr_page.maptree = wxgui_utils.LayerTree(self.curr_page, id=wx.ID_ANY, pos=wx.DefaultPosition,
  943. size=wx.DefaultSize, style=wx.TR_HAS_BUTTONS
  944. |wx.TR_LINES_AT_ROOT|wx.TR_HIDE_ROOT
  945. |wx.TR_DEFAULT_STYLE|wx.NO_BORDER|wx.FULL_REPAINT_ON_RESIZE,
  946. idx=self.disp_idx, lmgr=self, notebook=self.gm_cb,
  947. auimgr=self._auimgr, showMapDisplay=show)
  948. # layout for controls
  949. cb_boxsizer = wx.BoxSizer(wx.VERTICAL)
  950. cb_boxsizer.Add(self.curr_page.maptree, proportion=1, flag=wx.EXPAND, border=1)
  951. self.curr_page.SetSizer(cb_boxsizer)
  952. cb_boxsizer.Fit(self.curr_page.maptree)
  953. self.curr_page.Layout()
  954. self.curr_page.maptree.Layout()
  955. # use default window layout
  956. if UserSettings.Get(group='general', key='defWindowPos', subkey='enabled') is True:
  957. dim = UserSettings.Get(group='general', key='defWindowPos', subkey='dim')
  958. idx = 4 + self.disp_idx * 4
  959. try:
  960. x, y = map(int, dim.split(',')[idx:idx + 2])
  961. w, h = map(int, dim.split(',')[idx + 2:idx + 4])
  962. self.curr_page.maptree.mapdisplay.SetPosition((x, y))
  963. self.curr_page.maptree.mapdisplay.SetSize((w, h))
  964. except:
  965. pass
  966. self.disp_idx += 1
  967. return self.curr_page.maptree.mapdisplay
  968. # toolBar button handlers
  969. def OnAddRaster(self, event):
  970. """!Add raster map layer"""
  971. # start new map display if no display is available
  972. if not self.curr_page:
  973. self.NewDisplay(show=False)
  974. self.AddRaster(event)
  975. def OnAddRasterMisc(self, event):
  976. """!Add raster menu"""
  977. # start new map display if no display is available
  978. if not self.curr_page:
  979. self.NewDisplay(show=False)
  980. point = wx.GetMousePosition()
  981. rastmenu = wx.Menu()
  982. # add items to the menu
  983. if self.curr_page.maptree.mapdisplay.toolbars['nviz']:
  984. addrast3d = wx.MenuItem(rastmenu, -1, Icons ["addrast3d"].GetLabel())
  985. addrast3d.SetBitmap(Icons["addrast3d"].GetBitmap (self.iconsize))
  986. rastmenu.AppendItem(addrast3d)
  987. self.Bind(wx.EVT_MENU, self.AddRaster3d, addrast3d)
  988. addshaded = wx.MenuItem(rastmenu, -1, Icons ["addshaded"].GetLabel())
  989. addshaded.SetBitmap(Icons["addshaded"].GetBitmap (self.iconsize))
  990. rastmenu.AppendItem(addshaded)
  991. self.Bind(wx.EVT_MENU, self.AddShaded, addshaded)
  992. addrgb = wx.MenuItem(rastmenu, -1, Icons["addrgb"].GetLabel())
  993. addrgb.SetBitmap(Icons["addrgb"].GetBitmap(self.iconsize))
  994. rastmenu.AppendItem(addrgb)
  995. self.Bind(wx.EVT_MENU, self.AddRGB, addrgb)
  996. addhis = wx.MenuItem(rastmenu, -1, Icons ["addhis"].GetLabel())
  997. addhis.SetBitmap(Icons["addhis"].GetBitmap (self.iconsize))
  998. rastmenu.AppendItem(addhis)
  999. self.Bind(wx.EVT_MENU, self.AddHIS, addhis)
  1000. addrastarrow = wx.MenuItem(rastmenu, -1, Icons ["addrarrow"].GetLabel())
  1001. addrastarrow.SetBitmap(Icons["addrarrow"].GetBitmap (self.iconsize))
  1002. rastmenu.AppendItem(addrastarrow)
  1003. self.Bind(wx.EVT_MENU, self.AddRastarrow, addrastarrow)
  1004. addrastnums = wx.MenuItem(rastmenu, -1, Icons ["addrnum"].GetLabel())
  1005. addrastnums.SetBitmap(Icons["addrnum"].GetBitmap (self.iconsize))
  1006. rastmenu.AppendItem(addrastnums)
  1007. self.Bind(wx.EVT_MENU, self.AddRastnum, addrastnums)
  1008. # Popup the menu. If an item is selected then its handler
  1009. # will be called before PopupMenu returns.
  1010. self.PopupMenu(rastmenu)
  1011. rastmenu.Destroy()
  1012. # show map display
  1013. self.curr_page.maptree.mapdisplay.Show()
  1014. def OnAddVector(self, event):
  1015. """!Add vector map layer"""
  1016. # start new map display if no display is available
  1017. if not self.curr_page:
  1018. self.NewDisplay(show=False)
  1019. self.AddVector(event)
  1020. def OnAddVectorMisc(self, event):
  1021. """!Add vector menu"""
  1022. # start new map display if no display is available
  1023. if not self.curr_page:
  1024. self.NewDisplay(show=False)
  1025. point = wx.GetMousePosition()
  1026. vectmenu = wx.Menu()
  1027. addtheme = wx.MenuItem(vectmenu, -1, Icons["addthematic"].GetLabel())
  1028. addtheme.SetBitmap(Icons["addthematic"].GetBitmap(self.iconsize))
  1029. vectmenu.AppendItem(addtheme)
  1030. self.Bind(wx.EVT_MENU, self.AddThemeMap, addtheme)
  1031. addchart = wx.MenuItem(vectmenu, -1, Icons["addchart"].GetLabel())
  1032. addchart.SetBitmap(Icons["addchart"].GetBitmap(self.iconsize))
  1033. vectmenu.AppendItem(addchart)
  1034. self.Bind(wx.EVT_MENU, self.AddThemeChart, addchart)
  1035. # Popup the menu. If an item is selected then its handler
  1036. # will be called before PopupMenu returns.
  1037. self.PopupMenu(vectmenu)
  1038. vectmenu.Destroy()
  1039. # show map display
  1040. self.curr_page.maptree.mapdisplay.Show()
  1041. def OnAddOverlay(self, event):
  1042. """!Add overlay menu"""
  1043. # start new map display if no display is available
  1044. if not self.curr_page:
  1045. self.NewDisplay(show=False)
  1046. point = wx.GetMousePosition()
  1047. ovlmenu = wx.Menu()
  1048. addgrid = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addgrid"].GetLabel())
  1049. addgrid.SetBitmap(Icons["addgrid"].GetBitmap(self.iconsize))
  1050. ovlmenu.AppendItem(addgrid)
  1051. self.Bind(wx.EVT_MENU, self.AddGrid, addgrid)
  1052. addlabels = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addlabels"].GetLabel())
  1053. addlabels.SetBitmap(Icons["addlabels"].GetBitmap(self.iconsize))
  1054. ovlmenu.AppendItem(addlabels)
  1055. self.Bind(wx.EVT_MENU, self.OnAddLabels, addlabels)
  1056. addgeodesic = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addgeodesic"].GetLabel())
  1057. addgeodesic.SetBitmap(Icons["addgeodesic"].GetBitmap(self.iconsize))
  1058. ovlmenu.AppendItem(addgeodesic)
  1059. self.Bind(wx.EVT_MENU, self.AddGeodesic, addgeodesic)
  1060. addrhumb = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addrhumb"].GetLabel())
  1061. addrhumb.SetBitmap(Icons["addrhumb"].GetBitmap(self.iconsize))
  1062. ovlmenu.AppendItem(addrhumb)
  1063. self.Bind(wx.EVT_MENU, self.AddRhumb, addrhumb)
  1064. # Popup the menu. If an item is selected then its handler
  1065. # will be called before PopupMenu returns.
  1066. self.PopupMenu(ovlmenu)
  1067. ovlmenu.Destroy()
  1068. # show map display
  1069. self.curr_page.maptree.mapdisplay.Show()
  1070. def AddRaster(self, event):
  1071. self.notebook.SetSelection(0)
  1072. self.curr_page.maptree.AddLayer('raster')
  1073. def AddRaster3d(self, event):
  1074. self.notebook.SetSelection(0)
  1075. self.curr_page.maptree.AddLayer('3d-raster')
  1076. def AddRGB(self, event):
  1077. """!Add RGB layer"""
  1078. self.notebook.SetSelection(0)
  1079. self.curr_page.maptree.AddLayer('rgb')
  1080. def AddHIS(self, event):
  1081. """!Add HIS layer"""
  1082. self.notebook.SetSelection(0)
  1083. self.curr_page.maptree.AddLayer('his')
  1084. def AddShaded(self, event):
  1085. """!Add shaded relief map layer"""
  1086. self.notebook.SetSelection(0)
  1087. self.curr_page.maptree.AddLayer('shaded')
  1088. def AddRastarrow(self, event):
  1089. """!Add raster flow arrows map"""
  1090. self.notebook.SetSelection(0)
  1091. self.curr_page.maptree.AddLayer('rastarrow')
  1092. def AddRastnum(self, event):
  1093. """!Add raster map with cell numbers"""
  1094. self.notebook.SetSelection(0)
  1095. self.curr_page.maptree.AddLayer('rastnum')
  1096. def AddVector(self, event):
  1097. """!Add vector layer"""
  1098. self.notebook.SetSelection(0)
  1099. self.curr_page.maptree.AddLayer('vector')
  1100. def AddThemeMap(self, event):
  1101. """!Add thematic map layer"""
  1102. self.notebook.SetSelection(0)
  1103. self.curr_page.maptree.AddLayer('thememap')
  1104. def AddThemeChart(self, event):
  1105. """!Add thematic chart layer"""
  1106. self.notebook.SetSelection(0)
  1107. self.curr_page.maptree.AddLayer('themechart')
  1108. def OnAddCommand(self, event):
  1109. """!Add command line layer"""
  1110. # start new map display if no display is available
  1111. if not self.curr_page:
  1112. self.NewDisplay(show=False)
  1113. self.notebook.SetSelection(0)
  1114. self.curr_page.maptree.AddLayer('command')
  1115. # show map display
  1116. self.curr_page.maptree.mapdisplay.Show()
  1117. def OnAddGroup(self, event):
  1118. """!Add layer group"""
  1119. # start new map display if no display is available
  1120. if not self.curr_page:
  1121. self.NewDisplay(show=False)
  1122. self.notebook.SetSelection(0)
  1123. self.curr_page.maptree.AddLayer('group')
  1124. # show map display
  1125. self.curr_page.maptree.mapdisplay.Show()
  1126. def AddGrid(self, event):
  1127. """!Add layer grid"""
  1128. self.notebook.SetSelection(0)
  1129. self.curr_page.maptree.AddLayer('grid')
  1130. def AddGeodesic(self, event):
  1131. """!Add layer geodesic"""
  1132. self.notebook.SetSelection(0)
  1133. self.curr_page.maptree.AddLayer('geodesic')
  1134. def AddRhumb(self, event):
  1135. """!Add layer rhumb"""
  1136. self.notebook.SetSelection(0)
  1137. self.curr_page.maptree.AddLayer('rhumb')
  1138. def OnAddLabels(self, event):
  1139. """!Add layer vector labels"""
  1140. # start new map display if no display is available
  1141. if not self.curr_page:
  1142. self.NewDisplay(show=False)
  1143. self.notebook.SetSelection(0)
  1144. self.curr_page.maptree.AddLayer('labels')
  1145. # show map display
  1146. self.curr_page.maptree.mapdisplay.Show()
  1147. def OnDeleteLayer(self, event):
  1148. """
  1149. Delete selected map display layer in GIS Manager tree widget
  1150. """
  1151. if not self.curr_page or not self.curr_page.maptree.layer_selected:
  1152. self.MsgNoLayerSelected()
  1153. return
  1154. if UserSettings.Get(group='manager', key='askOnRemoveLayer', subkey='enabled'):
  1155. layerName = ''
  1156. for item in self.curr_page.maptree.GetSelections():
  1157. name = str(self.curr_page.maptree.GetItemText(item))
  1158. idx = name.find('(opacity')
  1159. if idx > -1:
  1160. layerName += '<' + name[:idx].strip(' ') + '>,\n'
  1161. else:
  1162. layerName += '<' + name + '>,\n'
  1163. layerName = layerName.rstrip(',\n')
  1164. if len(layerName) > 2: # <>
  1165. message = _("Do you want to remove map layer(s)\n%s\n"
  1166. "from layer tree?") % layerName
  1167. else:
  1168. message = _("Do you want to remove selected map layer(s) "
  1169. "from layer tree?")
  1170. dlg = wx.MessageDialog (parent=self, message=message,
  1171. caption=_("Remove map layer"),
  1172. style=wx.YES_NO | wx.YES_DEFAULT | wx.CANCEL | wx.ICON_QUESTION)
  1173. if dlg.ShowModal() in [wx.ID_NO, wx.ID_CANCEL]:
  1174. dlg.Destroy()
  1175. return
  1176. dlg.Destroy()
  1177. for layer in self.curr_page.maptree.GetSelections():
  1178. if self.curr_page.maptree.GetPyData(layer)[0]['type'] == 'group':
  1179. self.curr_page.maptree.DeleteChildren(layer)
  1180. self.curr_page.maptree.Delete(layer)
  1181. def OnKey(self, event):
  1182. """!Check hotkey"""
  1183. try:
  1184. kc = chr(event.GetKeyCode())
  1185. except ValueError:
  1186. event.Skip()
  1187. return
  1188. if event.AltDown():
  1189. if kc == 'R':
  1190. self.OnAddRaster(None)
  1191. elif kc == 'V':
  1192. self.OnAddVector(None)
  1193. event.Skip()
  1194. def OnQuit(self, event):
  1195. """!Quit GRASS"""
  1196. # quit wxGUI session
  1197. self.OnCloseWindow(event)
  1198. # quit GRASS shell
  1199. try:
  1200. pid = os.environ['GRASS_SHELL_PID']
  1201. except KeyError:
  1202. return
  1203. os.kill(int(pid), signal.SIGQUIT)
  1204. def OnCloseWindow(self, event):
  1205. """!Cleanup when wxGUI is quit"""
  1206. if not self.curr_page:
  1207. self._auimgr.UnInit()
  1208. self.Destroy()
  1209. return
  1210. maptree = self.curr_page.maptree
  1211. if UserSettings.Get(group='manager', key='askOnQuit', subkey='enabled'):
  1212. if self.workspaceFile:
  1213. message = _("Do you want to save changes in the workspace?")
  1214. else:
  1215. message = _("Do you want to store current settings "
  1216. "to workspace file?")
  1217. # ask user to save current settings
  1218. if maptree.GetCount() > 0:
  1219. dlg = wx.MessageDialog(self,
  1220. message=message,
  1221. caption=_("Quit GRASS GUI"),
  1222. style=wx.YES_NO | wx.YES_DEFAULT |
  1223. wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
  1224. ret = dlg.ShowModal()
  1225. if ret == wx.ID_YES:
  1226. if not self.workspaceFile:
  1227. self.OnWorkspaceSaveAs()
  1228. else:
  1229. self.SaveToWorkspaceFile(self.workspaceFile)
  1230. elif ret == wx.ID_CANCEL:
  1231. event.Veto()
  1232. dlg.Destroy()
  1233. return
  1234. dlg.Destroy()
  1235. # don't ask any more...
  1236. UserSettings.Set(group = 'manager', key = 'askOnQuit', subkey = 'enabled',
  1237. value = False)
  1238. for page in range(self.gm_cb.GetPageCount()):
  1239. self.gm_cb.GetPage(0).maptree.mapdisplay.OnCloseWindow(event)
  1240. self.gm_cb.DeleteAllPages()
  1241. self._auimgr.UnInit()
  1242. self.Destroy()
  1243. def MsgNoLayerSelected(self):
  1244. """!Show dialog message 'No layer selected'"""
  1245. wx.MessageBox(parent=self,
  1246. message=_("No map layer selected. Operation cancelled."),
  1247. caption=_("Message"),
  1248. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1249. class GMApp(wx.App):
  1250. def __init__(self, workspace = None):
  1251. """!Main GUI class.
  1252. @param workspace path to the workspace file
  1253. """
  1254. self.workspaceFile = workspace
  1255. # call parent class initializer
  1256. wx.App.__init__(self, False)
  1257. def OnInit(self):
  1258. """!Initialize all available image handlers
  1259. @return True
  1260. """
  1261. wx.InitAllImageHandlers()
  1262. # create splash screen
  1263. introImagePath = os.path.join(globalvar.ETCWXDIR, "images", "intro.png")
  1264. introImage = wx.Image(introImagePath, wx.BITMAP_TYPE_PNG)
  1265. introBmp = introImage.ConvertToBitmap()
  1266. wx.SplashScreen (bitmap=introBmp, splashStyle=wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
  1267. milliseconds=1500, parent=None, id=wx.ID_ANY)
  1268. wx.Yield()
  1269. # create and show main frame
  1270. mainframe = GMFrame(parent=None, id=wx.ID_ANY,
  1271. workspace = self.workspaceFile)
  1272. mainframe.Show()
  1273. self.SetTopWindow(mainframe)
  1274. return True
  1275. class Usage(Exception):
  1276. def __init__(self, msg):
  1277. self.msg = msg
  1278. def printHelp():
  1279. """!Print program help"""
  1280. print >> sys.stderr, "Usage:"
  1281. print >> sys.stderr, " python wxgui.py [options]"
  1282. print >> sys.stderr, "%sOptions:" % os.linesep
  1283. print >> sys.stderr, " -w\t--workspace file\tWorkspace file to load"
  1284. sys.exit(0)
  1285. def process_opt(opts, args):
  1286. """!Process command-line arguments"""
  1287. workspaceFile = None
  1288. for o, a in opts:
  1289. if o in ("-h", "--help"):
  1290. printHelp()
  1291. if o in ("-w", "--workspace"):
  1292. if a != '':
  1293. workspaceFile = str(a)
  1294. else:
  1295. workspaceFile = args.pop(0)
  1296. return (workspaceFile,)
  1297. def main(argv=None):
  1298. #
  1299. # process command-line arguments
  1300. #
  1301. if argv is None:
  1302. argv = sys.argv
  1303. try:
  1304. try:
  1305. opts, args = getopt.getopt(argv[1:], "hw:",
  1306. ["help", "workspace"])
  1307. except getopt.error, msg:
  1308. raise Usage(msg)
  1309. except Usage, err:
  1310. print >> sys.stderr, err.msg
  1311. print >> sys.stderr, "for help use --help"
  1312. printHelp()
  1313. workspaceFile = process_opt(opts, args)[0]
  1314. #
  1315. # run application
  1316. #
  1317. app = GMApp(workspaceFile)
  1318. # suppress wxPython logs
  1319. q = wx.LogNull()
  1320. app.MainLoop()
  1321. if __name__ == "__main__":
  1322. sys.exit(main())