wxgui.py 61 KB

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