wxgui.py 59 KB

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