wxgui.py 60 KB

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