wxgui.py 59 KB

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