wxgui.py 60 KB

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