wxgui.py 58 KB

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