wxgui.py 60 KB

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