wxgui.py 58 KB

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