wxgui.py 60 KB

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