wxgui.py 59 KB

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