wxgui.py 59 KB

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