wxgui.py 60 KB

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