frame.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504
  1. """!
  2. @package mapdisp.frame
  3. @brief Map display with toolbar for various display management
  4. functions, and additional toolbars (vector digitizer, 3d view).
  5. Can be used either from Layer Manager or as d.mon backend.
  6. Classes:
  7. - MapFrame
  8. - MapApp
  9. Usage:
  10. python mapdisp.py monitor-identifier /path/to/map/file /path/to/command/file /path/to/env/file
  11. (C) 2006-2011 by the GRASS Development Team
  12. This program is free software under the GNU General Public
  13. License (>=v2). Read the file COPYING that comes with GRASS
  14. for details.
  15. @author Michael Barton
  16. @author Jachym Cepicky
  17. @author Martin Landa <landa.martin gmail.com>
  18. @author Vaclav Petras <wenzeslaus gmail.com> (MapFrameBase)
  19. @author Anna Kratochvilova <kratochanna gmail.com> (MapFrameBase)
  20. """
  21. import os
  22. import sys
  23. import math
  24. import copy
  25. from core import globalvar
  26. import wx
  27. import wx.aui
  28. sys.path.append(os.path.join(globalvar.ETCWXDIR, "icons"))
  29. sys.path.append(os.path.join(globalvar.ETCDIR, "python"))
  30. from core import globalvar
  31. from core.render import EVT_UPDATE_PRGBAR, Map
  32. from vdigit.toolbars import VDigitToolbar
  33. from mapdisp.toolbars import MapToolbar
  34. from mapdisp.gprint import PrintOptions
  35. from core.gcmd import GError, GMessage, RunCommand
  36. from dbm.dialogs import DisplayAttributesDialog
  37. from core.utils import ListOfCatsToRange, GetLayerNameFromCmd
  38. from gui_core.dialogs import GetImageHandlers, ImageSizeDialog, DecorationDialog, TextLayerDialog
  39. from core.debug import Debug
  40. from icon import Icons
  41. from core.settings import UserSettings
  42. from gui_core.mapdisp import MapFrameBase
  43. from mapdisp.mapwindow import BufferedWindow
  44. from modules.histogram import HistogramFrame
  45. from wxplot.histogram import Histogram2Frame
  46. from wxplot.profile import ProfileFrame
  47. from wxplot.scatter import ScatterFrame
  48. from mapdisp import statusbar as sb
  49. from grass.script import core as grass
  50. # for standalone app
  51. monFile = { 'cmd' : None,
  52. 'map' : None,
  53. 'env' : None,
  54. }
  55. monName = None
  56. monSize = list(globalvar.MAP_WINDOW_SIZE)
  57. haveCtypes = False
  58. class MapFrame(MapFrameBase):
  59. """!Main frame for map display window. Drawing takes place in
  60. child double buffered drawing window.
  61. """
  62. def __init__(self, parent = None, title = _("GRASS GIS - Map display"),
  63. toolbars = ["map"], tree = None, notebook = None, lmgr = None,
  64. page = None, Map = None, auimgr = None, name = 'MapWindow', **kwargs):
  65. """!Main map display window with toolbars, statusbar and
  66. BufferedWindow (map canvas)
  67. @param toolbars array of activated toolbars, e.g. ['map', 'digit']
  68. @param tree reference to layer tree
  69. @param notebook control book ID in Layer Manager
  70. @param lmgr Layer Manager
  71. @param page notebook page with layer tree
  72. @param Map instance of render.Map
  73. @param auimgs AUI manager
  74. @param name frame name
  75. @param kwargs wx.Frame attributes
  76. """
  77. MapFrameBase.__init__(self, parent = parent, title = title, toolbars = toolbars,
  78. Map = Map, auimgr = auimgr, name = name, **kwargs)
  79. self._layerManager = lmgr # Layer Manager object
  80. self.tree = tree # Layer Manager layer tree object
  81. self.page = page # Notebook page holding the layer tree
  82. self.layerbook = notebook # Layer Manager layer tree notebook
  83. #
  84. # Add toolbars
  85. #
  86. for toolb in toolbars:
  87. self.AddToolbar(toolb)
  88. #
  89. # Add statusbar
  90. #
  91. # items for choice
  92. self.statusbarItems = [sb.SbCoordinates,
  93. sb.SbRegionExtent,
  94. sb.SbCompRegionExtent,
  95. sb.SbShowRegion,
  96. sb.SbAlignExtent,
  97. sb.SbResolution,
  98. sb.SbDisplayGeometry,
  99. sb.SbMapScale,
  100. sb.SbGoTo,
  101. sb.SbProjection]
  102. self.statusbarItemsHiddenInNviz = (sb.SbAlignExtent,
  103. sb.SbDisplayGeometry,
  104. sb.SbShowRegion,
  105. sb.SbResolution,
  106. sb.SbMapScale)
  107. # create statusbar and its manager
  108. statusbar = self.CreateStatusBar(number = 4, style = 0)
  109. statusbar.SetStatusWidths([-5, -2, -1, -1])
  110. self.statusbarManager = sb.SbManager(mapframe = self, statusbar = statusbar)
  111. # fill statusbar manager
  112. self.statusbarManager.AddStatusbarItemsByClass(self.statusbarItems, mapframe = self, statusbar = statusbar)
  113. self.statusbarManager.AddStatusbarItem(sb.SbMask(self, statusbar = statusbar, position = 2))
  114. self.statusbarManager.AddStatusbarItem(sb.SbRender(self, statusbar = statusbar, position = 3))
  115. self.statusbarManager.Update()
  116. #
  117. # Init map display (buffered DC & set default cursor)
  118. #
  119. self.MapWindow2D = BufferedWindow(self, id = wx.ID_ANY,
  120. Map = self.Map, tree = self.tree, lmgr = self._layerManager)
  121. # default is 2D display mode
  122. self.MapWindow = self.MapWindow2D
  123. self.MapWindow.SetCursor(self.cursors["default"])
  124. # used by vector digitizer
  125. self.MapWindowVDigit = None
  126. # used by Nviz (3D display mode)
  127. self.MapWindow3D = None
  128. #
  129. # initialize region values
  130. #
  131. self._initMap(map = self.Map)
  132. #
  133. # Bind various events
  134. #
  135. self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
  136. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  137. self.Bind(EVT_UPDATE_PRGBAR, self.OnUpdateProgress)
  138. #
  139. # Update fancy gui style
  140. #
  141. self._mgr.AddPane(self.MapWindow, wx.aui.AuiPaneInfo().CentrePane().
  142. Dockable(False).BestSize((-1,-1)).Name('2d').
  143. CloseButton(False).DestroyOnClose(True).
  144. Layer(0))
  145. self._mgr.Update()
  146. #
  147. # Init print module and classes
  148. #
  149. self.printopt = PrintOptions(self, self.MapWindow)
  150. #
  151. # Init zoom history
  152. #
  153. self.MapWindow.ZoomHistory(self.Map.region['n'],
  154. self.Map.region['s'],
  155. self.Map.region['e'],
  156. self.Map.region['w'])
  157. #
  158. # Re-use dialogs
  159. #
  160. self.dialogs = {}
  161. self.dialogs['attributes'] = None
  162. self.dialogs['category'] = None
  163. self.dialogs['barscale'] = None
  164. self.dialogs['legend'] = None
  165. self.decorationDialog = None # decoration/overlays
  166. def _addToolbarVDigit(self):
  167. """!Add vector digitizer toolbar
  168. """
  169. from vdigit import haveVDigit
  170. if not haveVDigit:
  171. from vdigit import errorMsg
  172. msg = _("Unable to start wxGUI vector digitizer.\nDo you want to start "
  173. "TCL/TK digitizer (v.digit) instead?\n\n"
  174. "Details: %s" % errorMsg)
  175. self.toolbars['map'].combo.SetValue(_("2D view"))
  176. dlg = wx.MessageDialog(parent = self,
  177. message = msg,
  178. caption=_("Vector digitizer failed"),
  179. style = wx.YES_NO | wx.CENTRE)
  180. if dlg.ShowModal() == wx.ID_YES:
  181. mapName = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetName()
  182. self._layerManager.goutput.RunCmd(['v.digit', 'map=%s' % mapName],
  183. switchPage = False)
  184. dlg.Destroy()
  185. self.toolbars['map'].combo.SetValue(_("2D view"))
  186. return
  187. if self._layerManager:
  188. log = self._layerManager.goutput
  189. else:
  190. log = None
  191. if not self.MapWindowVDigit:
  192. from mapdisp_vdigit import VDigitWindow
  193. self.MapWindowVDigit = VDigitWindow(self, id = wx.ID_ANY,
  194. Map = self.Map, tree = self.tree,
  195. lmgr = self._layerManager)
  196. self.MapWindowVDigit.Show()
  197. self._mgr.AddPane(self.MapWindowVDigit, wx.aui.AuiPaneInfo().CentrePane().
  198. Dockable(False).BestSize((-1,-1)).Name('vdigit').
  199. CloseButton(False).DestroyOnClose(True).
  200. Layer(0))
  201. self.MapWindow = self.MapWindowVDigit
  202. if self._mgr.GetPane('2d').IsShown():
  203. self._mgr.GetPane('2d').Hide()
  204. elif self._mgr.GetPane('3d').IsShown():
  205. self._mgr.GetPane('3d').Hide()
  206. self._mgr.GetPane('vdigit').Show()
  207. self.toolbars['vdigit'] = VDigitToolbar(parent = self, MapWindow = self.MapWindow,
  208. layerTree = self.tree,
  209. log = log)
  210. self.MapWindowVDigit.SetToolbar(self.toolbars['vdigit'])
  211. self._mgr.AddPane(self.toolbars['vdigit'],
  212. wx.aui.AuiPaneInfo().
  213. Name("vdigittoolbar").Caption(_("Vector Digitizer Toolbar")).
  214. ToolbarPane().Top().Row(1).
  215. LeftDockable(False).RightDockable(False).
  216. BottomDockable(False).TopDockable(True).
  217. CloseButton(False).Layer(2).
  218. BestSize((self.toolbars['vdigit'].GetBestSize())))
  219. # change mouse to draw digitized line
  220. self.MapWindow.mouse['box'] = "point"
  221. self.MapWindow.zoomtype = 0
  222. self.MapWindow.pen = wx.Pen(colour = 'red', width = 2, style = wx.SOLID)
  223. self.MapWindow.polypen = wx.Pen(colour = 'green', width = 2, style = wx.SOLID)
  224. def AddNviz(self):
  225. """!Add 3D view mode window
  226. """
  227. import nviz
  228. # check for GLCanvas and OpenGL
  229. if not nviz.haveNviz:
  230. self.toolbars['map'].combo.SetValue(_("2D view"))
  231. GError(parent = self,
  232. message = _("Unable to switch to 3D display mode.\nThe Nviz python extension "
  233. "was not found or loaded properly.\n"
  234. "Switching back to 2D display mode.\n\nDetails: %s" % nviz.errorMsg))
  235. return
  236. # disable 3D mode for other displays
  237. for page in range(0, self._layerManager.gm_cb.GetPageCount()):
  238. if self._layerManager.gm_cb.GetPage(page) != self._layerManager.curr_page:
  239. if '3D' in self._layerManager.gm_cb.GetPage(page).maptree.mapdisplay.toolbars['map'].combo.GetString(1):
  240. self._layerManager.gm_cb.GetPage(page).maptree.mapdisplay.toolbars['map'].combo.Delete(1)
  241. self.toolbars['map'].Enable2D(False)
  242. # add rotate tool to map toolbar
  243. self.toolbars['map'].InsertTool((('rotate', Icons['nviz']['rotate'],
  244. self.OnRotate, wx.ITEM_CHECK, 7),)) # 7 is position
  245. self.toolbars['map'].InsertTool((('flyThrough', Icons['nviz']['flyThrough'],
  246. self.OnFlyThrough, wx.ITEM_CHECK, 8),))
  247. self.toolbars['map'].ChangeToolsDesc(mode2d = False)
  248. # update status bar
  249. self.statusbarManager.HideStatusbarChoiceItemsByClass(self.statusbarItemsHiddenInNviz)
  250. self.statusbarManager.SetMode(0)
  251. # erase map window
  252. self.MapWindow.EraseMap()
  253. self._layerManager.goutput.WriteCmdLog(_("Starting 3D view mode..."),
  254. switchPage = False)
  255. self.SetStatusText(_("Please wait, loading data..."), 0)
  256. # create GL window
  257. if not self.MapWindow3D:
  258. self.MapWindow3D = nviz.GLWindow(self, id = wx.ID_ANY,
  259. Map = self.Map, tree = self.tree, lmgr = self._layerManager)
  260. self.MapWindow = self.MapWindow3D
  261. self.MapWindow.SetCursor(self.cursors["default"])
  262. # add Nviz notebookpage
  263. self._layerManager.AddNvizTools()
  264. # switch from MapWindow to MapWindowGL
  265. self._mgr.GetPane('2d').Hide()
  266. self._mgr.AddPane(self.MapWindow3D, wx.aui.AuiPaneInfo().CentrePane().
  267. Dockable(False).BestSize((-1,-1)).Name('3d').
  268. CloseButton(False).DestroyOnClose(True).
  269. Layer(0))
  270. self.MapWindow3D.OnPaint(None) # -> LoadData
  271. self.MapWindow3D.Show()
  272. self.MapWindow3D.ResetViewHistory()
  273. self.MapWindow3D.UpdateView(None)
  274. else:
  275. self.MapWindow = self.MapWindow3D
  276. os.environ['GRASS_REGION'] = self.Map.SetRegion(windres = True)
  277. self.MapWindow3D.GetDisplay().Init()
  278. del os.environ['GRASS_REGION']
  279. # switch from MapWindow to MapWindowGL
  280. self._mgr.GetPane('2d').Hide()
  281. self._mgr.GetPane('3d').Show()
  282. # add Nviz notebookpage
  283. self._layerManager.AddNvizTools()
  284. self.MapWindow3D.ResetViewHistory()
  285. for page in ('view', 'light', 'fringe', 'constant', 'cplane', 'animation'):
  286. self._layerManager.nviz.UpdatePage(page)
  287. self.MapWindow3D.overlays = self.MapWindow2D.overlays
  288. self.MapWindow3D.textdict = self.MapWindow2D.textdict
  289. # update overlays needs to be called after because getClientSize
  290. # is called during update and it must give reasonable values
  291. wx.CallAfter(self.MapWindow3D.UpdateOverlays)
  292. self.SetStatusText("", 0)
  293. self._mgr.Update()
  294. def RemoveNviz(self):
  295. """!Restore 2D view"""
  296. self.toolbars['map'].RemoveTool(self.toolbars['map'].rotate)
  297. self.toolbars['map'].RemoveTool(self.toolbars['map'].flyThrough)
  298. # update status bar
  299. self.statusbarManager.ShowStatusbarChoiceItemsByClass(self.statusbarItemsHiddenInNviz)
  300. self.statusbarManager.SetMode(UserSettings.Get(group = 'display',
  301. key = 'statusbarMode',
  302. subkey = 'selection'))
  303. self.SetStatusText(_("Please wait, unloading data..."), 0)
  304. self._layerManager.goutput.WriteCmdLog(_("Switching back to 2D view mode..."),
  305. switchPage = False)
  306. self.MapWindow3D.OnClose(event = None)
  307. # switch from MapWindowGL to MapWindow
  308. self._mgr.GetPane('2d').Show()
  309. self._mgr.GetPane('3d').Hide()
  310. self.MapWindow = self.MapWindow2D
  311. # remove nviz notebook page
  312. self._layerManager.RemoveNvizTools()
  313. self.MapWindow2D.overlays = self.MapWindow3D.overlays
  314. self.MapWindow2D.textdict = self.MapWindow3D.textdict
  315. self.MapWindow.UpdateMap()
  316. self._mgr.Update()
  317. def AddToolbar(self, name):
  318. """!Add defined toolbar to the window
  319. Currently known toolbars are:
  320. - 'map' - basic map toolbar
  321. - 'vdigit' - vector digitizer
  322. - 'gcpdisp' - GCP Manager Display
  323. """
  324. # default toolbar
  325. if name == "map":
  326. self.toolbars['map'] = MapToolbar(self, self.Map)
  327. self._mgr.AddPane(self.toolbars['map'],
  328. wx.aui.AuiPaneInfo().
  329. Name("maptoolbar").Caption(_("Map Toolbar")).
  330. ToolbarPane().Top().Name('mapToolbar').
  331. LeftDockable(False).RightDockable(False).
  332. BottomDockable(False).TopDockable(True).
  333. CloseButton(False).Layer(2).
  334. BestSize((self.toolbars['map'].GetBestSize())))
  335. # vector digitizer
  336. elif name == "vdigit":
  337. self._addToolbarVDigit()
  338. self._mgr.Update()
  339. def RemoveToolbar (self, name):
  340. """!Removes defined toolbar from the window
  341. @todo Only hide, activate by calling AddToolbar()
  342. """
  343. # cannot hide main toolbar
  344. if name == "map":
  345. return
  346. self._mgr.DetachPane(self.toolbars[name])
  347. self.toolbars[name].Destroy()
  348. self.toolbars.pop(name)
  349. if name == 'vdigit':
  350. self._mgr.GetPane('vdigit').Hide()
  351. self._mgr.GetPane('2d').Show()
  352. self.MapWindow = self.MapWindow2D
  353. self.toolbars['map'].combo.SetValue(_("2D view"))
  354. self.toolbars['map'].Enable2D(True)
  355. self._mgr.Update()
  356. def IsPaneShown(self, name):
  357. """!Check if pane (toolbar, mapWindow ...) of given name is currently shown"""
  358. if self._mgr.GetPane(name).IsOk():
  359. return self._mgr.GetPane(name).IsShown()
  360. return False
  361. def OnUpdateProgress(self, event):
  362. """!Update progress bar info
  363. """
  364. self.GetProgressBar().SetValue(event.value)
  365. event.Skip()
  366. def OnFocus(self, event):
  367. """!Change choicebook page to match display.
  368. """
  369. # change bookcontrol page to page associated with display
  370. if self.page:
  371. pgnum = self.layerbook.GetPageIndex(self.page)
  372. if pgnum > -1:
  373. self.layerbook.SetSelection(pgnum)
  374. self._layerManager.curr_page = self.layerbook.GetCurrentPage()
  375. event.Skip()
  376. def OnRender(self, event):
  377. """!Re-render map composition (each map layer)
  378. """
  379. # delete tmp map layers (queries)
  380. qlayer = self.Map.GetListOfLayers(l_name = globalvar.QUERYLAYER)
  381. for layer in qlayer:
  382. self.Map.DeleteLayer(layer)
  383. # delete tmp lines
  384. if self.MapWindow.mouse["use"] in ("measure",
  385. "profile"):
  386. self.MapWindow.polycoords = []
  387. self.MapWindow.ClearLines()
  388. # deselect features in vdigit
  389. if self.GetToolbar('vdigit'):
  390. self.MapWindow.digit.GetDisplay().SetSelected([])
  391. self.MapWindow.UpdateMap(render = True, renderVector = True)
  392. else:
  393. self.MapWindow.UpdateMap(render = True)
  394. # update statusbar
  395. self.StatusbarUpdate()
  396. def OnPointer(self, event):
  397. """!Pointer button clicked
  398. """
  399. if self.GetMapToolbar():
  400. if event:
  401. self.toolbars['map'].OnTool(event)
  402. self.toolbars['map'].action['desc'] = ''
  403. self.MapWindow.mouse['use'] = "pointer"
  404. self.MapWindow.mouse['box'] = "point"
  405. # change the cursor
  406. if self.GetToolbar('vdigit'):
  407. # digitization tool activated
  408. self.MapWindow.SetCursor(self.cursors["cross"])
  409. # reset mouse['box'] if needed
  410. if self.toolbars['vdigit'].GetAction() in ['addLine']:
  411. if self.toolbars['vdigit'].GetAction('type') in ['point', 'centroid']:
  412. self.MapWindow.mouse['box'] = 'point'
  413. else: # line, boundary
  414. self.MapWindow.mouse['box'] = 'line'
  415. elif self.toolbars['vdigit'].GetAction() in ['addVertex', 'removeVertex', 'splitLine',
  416. 'editLine', 'displayCats', 'queryMap',
  417. 'copyCats']:
  418. self.MapWindow.mouse['box'] = 'point'
  419. else: # moveLine, deleteLine
  420. self.MapWindow.mouse['box'] = 'box'
  421. else:
  422. self.MapWindow.SetCursor(self.cursors["default"])
  423. def OnRotate(self, event):
  424. """!Rotate 3D view
  425. """
  426. if self.GetMapToolbar():
  427. self.toolbars['map'].OnTool(event)
  428. self.toolbars['map'].action['desc'] = ''
  429. self.MapWindow.mouse['use'] = "rotate"
  430. # change the cursor
  431. self.MapWindow.SetCursor(self.cursors["hand"])
  432. def OnFlyThrough(self, event):
  433. """!Fly-through mode
  434. """
  435. if self.GetMapToolbar():
  436. self.toolbars['map'].OnTool(event)
  437. self.toolbars['map'].action['desc'] = ''
  438. self.MapWindow.mouse['use'] = "fly"
  439. # change the cursor
  440. self.MapWindow.SetCursor(self.cursors["hand"])
  441. self.MapWindow.SetFocus()
  442. def OnZoomRegion(self, event):
  443. """!Zoom to region
  444. """
  445. self.Map.getRegion()
  446. self.Map.getResolution()
  447. self.UpdateMap()
  448. # event.Skip()
  449. def OnAlignRegion(self, event):
  450. """!Align region
  451. """
  452. if not self.Map.alignRegion:
  453. self.Map.alignRegion = True
  454. else:
  455. self.Map.alignRegion = False
  456. # event.Skip()
  457. def SaveToFile(self, event):
  458. """!Save map to image
  459. """
  460. if self.IsPaneShown('3d'):
  461. filetype = "PPM file (*.ppm)|*.ppm|TIF file (*.tif)|*.tif"
  462. ltype = [{ 'ext' : 'ppm', 'type' : 'ppm' },
  463. { 'ext' : 'tif', 'type' : 'tif' }]
  464. else:
  465. img = self.MapWindow.img
  466. if not img:
  467. GMessage(parent = self,
  468. message = _("Nothing to render (empty map). Operation canceled."))
  469. return
  470. filetype, ltype = GetImageHandlers(img)
  471. # get size
  472. dlg = ImageSizeDialog(self)
  473. dlg.CentreOnParent()
  474. if dlg.ShowModal() != wx.ID_OK:
  475. dlg.Destroy()
  476. return
  477. width, height = dlg.GetValues()
  478. dlg.Destroy()
  479. # get filename
  480. dlg = wx.FileDialog(parent = self,
  481. message = _("Choose a file name to save the image "
  482. "(no need to add extension)"),
  483. wildcard = filetype,
  484. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  485. if dlg.ShowModal() == wx.ID_OK:
  486. path = dlg.GetPath()
  487. if not path:
  488. dlg.Destroy()
  489. return
  490. base, ext = os.path.splitext(path)
  491. fileType = ltype[dlg.GetFilterIndex()]['type']
  492. extType = ltype[dlg.GetFilterIndex()]['ext']
  493. if ext != extType:
  494. path = base + '.' + extType
  495. self.MapWindow.SaveToFile(path, fileType,
  496. width, height)
  497. dlg.Destroy()
  498. def PrintMenu(self, event):
  499. """
  500. Print options and output menu for map display
  501. """
  502. point = wx.GetMousePosition()
  503. printmenu = wx.Menu()
  504. # Add items to the menu
  505. setup = wx.MenuItem(printmenu, wx.ID_ANY, _('Page setup'))
  506. printmenu.AppendItem(setup)
  507. self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
  508. preview = wx.MenuItem(printmenu, wx.ID_ANY, _('Print preview'))
  509. printmenu.AppendItem(preview)
  510. self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
  511. doprint = wx.MenuItem(printmenu, wx.ID_ANY, _('Print display'))
  512. printmenu.AppendItem(doprint)
  513. self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
  514. # Popup the menu. If an item is selected then its handler
  515. # will be called before PopupMenu returns.
  516. self.PopupMenu(printmenu)
  517. printmenu.Destroy()
  518. def OnCloseWindow(self, event):
  519. """!Window closed.
  520. Also close associated layer tree page
  521. """
  522. pgnum = None
  523. self.Map.Clean()
  524. # close edited map and 3D tools properly
  525. if self.GetToolbar('vdigit'):
  526. maplayer = self.toolbars['vdigit'].GetLayer()
  527. if maplayer:
  528. self.toolbars['vdigit'].OnExit()
  529. if self.IsPaneShown('3d'):
  530. self.RemoveNviz()
  531. if not self._layerManager:
  532. self.Destroy()
  533. elif self.page:
  534. pgnum = self.layerbook.GetPageIndex(self.page)
  535. if pgnum > -1:
  536. self.layerbook.DeletePage(pgnum)
  537. def QueryMap(self, x, y):
  538. """!Query raster or vector map layers by r/v.what
  539. @param x,y coordinates
  540. """
  541. # set query snap distance for v.what at map unit equivalent of 10 pixels
  542. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / self.Map.width)
  543. east, north = self.MapWindow.Pixel2Cell((x, y))
  544. if not self.IsStandalone():
  545. num = 0
  546. for layer in self.tree.GetSelections():
  547. ltype = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  548. if ltype in ('raster', 'rgb', 'his',
  549. 'vector', 'thememap', 'themechart'):
  550. num += 1
  551. if num < 1:
  552. GMessage(parent = self,
  553. message = _('No raster or vector map layer selected for querying.'))
  554. return
  555. rast = list()
  556. vect = list()
  557. rcmd = ['r.what', '--v']
  558. vcmd = ['v.what', '--v']
  559. if self.IsStandalone():
  560. pass
  561. else:
  562. for layer in self.tree.GetSelections():
  563. ltype = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  564. dcmd = self.tree.GetPyData(layer)[0]['cmd']
  565. name, found = GetLayerNameFromCmd(dcmd)
  566. if not found:
  567. continue
  568. if ltype == 'raster':
  569. rast.append(name)
  570. elif ltype in ('rgb', 'his'):
  571. for iname in name.split('\n'):
  572. rast.append(iname)
  573. elif ltype in ('vector', 'thememap', 'themechart'):
  574. vect.append(name)
  575. # rasters are not queried this way in 3D, we don't want them now
  576. if self.IsPaneShown('3d'):
  577. rast = list()
  578. # use display region settings instead of computation region settings
  579. self.tmpreg = os.getenv("GRASS_REGION")
  580. os.environ["GRASS_REGION"] = self.Map.SetRegion(windres = False)
  581. # build query commands for any selected rasters and vectors
  582. if rast:
  583. rcmd.append('-f')
  584. rcmd.append('-n')
  585. rcmd.append('input=%s' % ','.join(rast))
  586. rcmd.append('east_north=%f,%f' % (float(east), float(north)))
  587. if vect:
  588. # check for vector maps open to be edited
  589. digitToolbar = self.toolbars['vdigit']
  590. if digitToolbar:
  591. lmap = digitToolbar.GetLayer().GetName()
  592. for name in vect:
  593. if lmap == name:
  594. self._layerManager.goutput.WriteWarning(_("Vector map <%s> "
  595. "opened for editing - skipped.") % map)
  596. vect.remove(name)
  597. if len(vect) < 1:
  598. self._layerManager.goutput.WriteCmdLog(_("Nothing to query."))
  599. return
  600. vcmd.append('-a')
  601. vcmd.append('map=%s' % ','.join(vect))
  602. vcmd.append('layer=%s' % ','.join(['-1'] * len(vect)))
  603. vcmd.append('east_north=%f,%f' % (float(east), float(north)))
  604. vcmd.append('distance=%f' % float(qdist))
  605. Debug.msg(1, "QueryMap(): raster=%s vector=%s" % (','.join(rast),
  606. ','.join(vect)))
  607. # parse query command(s)
  608. if not self.IsStandalone():
  609. if rast:
  610. self._layerManager.goutput.RunCmd(rcmd,
  611. compReg = False,
  612. onDone = self._QueryMapDone)
  613. if vect:
  614. self._layerManager.goutput.RunCmd(vcmd,
  615. onDone = self._QueryMapDone)
  616. else:
  617. if rast:
  618. RunCommand(rcmd)
  619. if vect:
  620. RunCommand(vcmd)
  621. def _QueryMapDone(self, cmd, returncode):
  622. """!Restore settings after querying (restore GRASS_REGION)
  623. @param returncode command return code
  624. """
  625. if hasattr(self, "tmpreg"):
  626. if self.tmpreg:
  627. os.environ["GRASS_REGION"] = self.tmpreg
  628. elif 'GRASS_REGION' in os.environ:
  629. del os.environ["GRASS_REGION"]
  630. elif 'GRASS_REGION' in os.environ:
  631. del os.environ["GRASS_REGION"]
  632. if hasattr(self, "tmpreg"):
  633. del self.tmpreg
  634. def QueryVector(self, x, y):
  635. """!Query vector map layer features
  636. Attribute data of selected vector object are displayed in GUI dialog.
  637. Data can be modified (On Submit)
  638. """
  639. if not self.tree.layer_selected or \
  640. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] != 'vector':
  641. GMessage(parent = self,
  642. message = _("No map layer selected for querying."))
  643. return
  644. posWindow = self.ClientToScreen((x + self.MapWindow.dialogOffset,
  645. y + self.MapWindow.dialogOffset))
  646. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) /
  647. self.Map.width)
  648. east, north = self.MapWindow.Pixel2Cell((x, y))
  649. mapName = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name
  650. if self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetMapset() != \
  651. grass.gisenv()['MAPSET']:
  652. mode = 'display'
  653. else:
  654. mode = 'update'
  655. if self.dialogs['attributes'] is None:
  656. dlg = DisplayAttributesDialog(parent = self.MapWindow,
  657. map = mapName,
  658. query = ((east, north), qdist),
  659. pos = posWindow,
  660. action = mode)
  661. self.dialogs['attributes'] = dlg
  662. else:
  663. # selection changed?
  664. if not self.dialogs['attributes'].mapDBInfo or \
  665. self.dialogs['attributes'].mapDBInfo.map != mapName:
  666. self.dialogs['attributes'].UpdateDialog(map = mapName, query = ((east, north), qdist),
  667. action = mode)
  668. else:
  669. self.dialogs['attributes'].UpdateDialog(query = ((east, north), qdist),
  670. action = mode)
  671. if not self.dialogs['attributes'].IsFound():
  672. self._layerManager.goutput.WriteLog(_('Nothing found.'))
  673. cats = self.dialogs['attributes'].GetCats()
  674. qlayer = None
  675. if not self.IsPaneShown('3d'):
  676. try:
  677. qlayer = self.Map.GetListOfLayers(l_name = globalvar.QUERYLAYER)[0]
  678. except IndexError:
  679. pass
  680. if self.dialogs['attributes'].mapDBInfo and cats:
  681. if not self.IsPaneShown('3d'):
  682. # highlight feature & re-draw map
  683. if qlayer:
  684. qlayer.SetCmd(self.AddTmpVectorMapLayer(mapName, cats,
  685. useId = False,
  686. addLayer = False))
  687. else:
  688. qlayer = self.AddTmpVectorMapLayer(mapName, cats, useId = False)
  689. # set opacity based on queried layer
  690. opacity = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetOpacity(float = True)
  691. qlayer.SetOpacity(opacity)
  692. self.MapWindow.UpdateMap(render = False, renderVector = False)
  693. if not self.dialogs['attributes'].IsShown():
  694. self.dialogs['attributes'].Show()
  695. else:
  696. if qlayer:
  697. self.Map.DeleteLayer(qlayer)
  698. self.MapWindow.UpdateMap(render = False, renderVector = False)
  699. if self.dialogs['attributes'].IsShown():
  700. self.dialogs['attributes'].Hide()
  701. def OnQuery(self, event):
  702. """!Query tools menu"""
  703. if self.GetMapToolbar():
  704. self.toolbars['map'].OnTool(event)
  705. action = self.toolbars['map'].GetAction()
  706. self.toolbars['map'].action['desc'] = 'queryMap'
  707. self.MapWindow.mouse['use'] = "query"
  708. if not self.IsStandalone():
  709. # switch to output console to show query results
  710. self._layerManager.notebook.SetSelectionByName('output')
  711. self.MapWindow.mouse['box'] = "point"
  712. self.MapWindow.zoomtype = 0
  713. # change the cursor
  714. self.MapWindow.SetCursor(self.cursors["cross"])
  715. def AddTmpVectorMapLayer(self, name, cats, useId = False, addLayer = True):
  716. """!Add temporal vector map layer to map composition
  717. @param name name of map layer
  718. @param useId use feature id instead of category
  719. """
  720. # color settings from ATM
  721. color = UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'color')
  722. colorStr = str(color[0]) + ":" + \
  723. str(color[1]) + ":" + \
  724. str(color[2])
  725. # icon used in vector display and its size
  726. icon = ''
  727. size = 0
  728. vparam = self.tree.GetPyData(self.tree.layer_selected)[0]['cmd']
  729. for p in vparam:
  730. if '=' in p:
  731. parg,pval = p.split('=')
  732. if parg == 'icon': icon = pval
  733. elif parg == 'size': size = int(pval)
  734. pattern = ["d.vect",
  735. "map=%s" % name,
  736. "color=%s" % colorStr,
  737. "fcolor=%s" % colorStr,
  738. "width=%d" % UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'width')]
  739. if icon != '':
  740. pattern.append('icon=%s' % icon)
  741. if size > 0:
  742. pattern.append('size=%i' % size)
  743. if useId:
  744. cmd = pattern
  745. cmd.append('-i')
  746. cmd.append('cats=%s' % str(cats))
  747. else:
  748. cmd = []
  749. for layer in cats.keys():
  750. cmd.append(copy.copy(pattern))
  751. lcats = cats[layer]
  752. cmd[-1].append("layer=%d" % layer)
  753. cmd[-1].append("cats=%s" % ListOfCatsToRange(lcats))
  754. if addLayer:
  755. if useId:
  756. return self.Map.AddLayer(type = 'vector', name = globalvar.QUERYLAYER, command = cmd,
  757. l_active = True, l_hidden = True, l_opacity = 1.0)
  758. else:
  759. return self.Map.AddLayer(type = 'command', name = globalvar.QUERYLAYER, command = cmd,
  760. l_active = True, l_hidden = True, l_opacity = 1.0)
  761. else:
  762. return cmd
  763. def OnAnalyze(self, event):
  764. """!Analysis tools menu
  765. """
  766. point = wx.GetMousePosition()
  767. toolsmenu = wx.Menu()
  768. icons = Icons['displayWindow']
  769. # Add items to the menu
  770. measure = wx.MenuItem(toolsmenu, wx.ID_ANY, icons["measure"].GetLabel())
  771. measure.SetBitmap(icons["measure"].GetBitmap(self.iconsize))
  772. toolsmenu.AppendItem(measure)
  773. self.Bind(wx.EVT_MENU, self.OnMeasure, measure)
  774. profile = wx.MenuItem(toolsmenu, wx.ID_ANY, icons["profile"].GetLabel())
  775. profile.SetBitmap(icons["profile"].GetBitmap(self.iconsize))
  776. toolsmenu.AppendItem(profile)
  777. self.Bind(wx.EVT_MENU, self.OnProfile, profile)
  778. scatterplot = wx.MenuItem(toolsmenu, wx.ID_ANY, _("Create bivariate scatterplot of raster maps"))
  779. scatterplot.SetBitmap(icons["profile"].GetBitmap(self.iconsize))
  780. toolsmenu.AppendItem(scatterplot)
  781. self.Bind(wx.EVT_MENU, self.OnScatterplot, scatterplot)
  782. histogram2 = wx.MenuItem(toolsmenu, wx.ID_ANY, icons["histogram"].GetLabel())
  783. histogram2.SetBitmap(icons["histogram"].GetBitmap(self.iconsize))
  784. toolsmenu.AppendItem(histogram2)
  785. self.Bind(wx.EVT_MENU, self.OnHistogramPyPlot, histogram2)
  786. histogram = wx.MenuItem(toolsmenu, wx.ID_ANY, _("Create histogram with d.histogram"))
  787. histogram.SetBitmap(icons["histogram"].GetBitmap(self.iconsize))
  788. toolsmenu.AppendItem(histogram)
  789. self.Bind(wx.EVT_MENU, self.OnHistogram, histogram)
  790. # Popup the menu. If an item is selected then its handler
  791. # will be called before PopupMenu returns.
  792. self.PopupMenu(toolsmenu)
  793. toolsmenu.Destroy()
  794. def OnMeasure(self, event):
  795. """!Init measurement routine that calculates map distance
  796. along transect drawn on map display
  797. """
  798. self.totaldist = 0.0 # total measured distance
  799. # switch Layer Manager to output console to show measure results
  800. self._layerManager.notebook.SetSelectionByName('output')
  801. # change mouse to draw line for measurement
  802. self.MapWindow.mouse['use'] = "measure"
  803. self.MapWindow.mouse['box'] = "line"
  804. self.MapWindow.zoomtype = 0
  805. self.MapWindow.pen = wx.Pen(colour = 'red', width = 2, style = wx.SHORT_DASH)
  806. self.MapWindow.polypen = wx.Pen(colour = 'green', width = 2, style = wx.SHORT_DASH)
  807. # change the cursor
  808. self.MapWindow.SetCursor(self.cursors["pencil"])
  809. # initiating output
  810. style = self._layerManager.goutput.cmdOutput.StyleWarning
  811. self._layerManager.goutput.WriteLog(_('Click and drag with left mouse button '
  812. 'to measure.%s'
  813. 'Double click with left button to clear.') % \
  814. (os.linesep), style)
  815. if self.Map.projinfo['proj'] != 'xy':
  816. units = self.Map.projinfo['units']
  817. self._layerManager.goutput.WriteCmdLog(_('Measuring distance') + ' ('
  818. + units + '):')
  819. else:
  820. self._layerManager.goutput.WriteCmdLog(_('Measuring distance:'))
  821. if self.Map.projinfo['proj'] == 'll':
  822. try:
  823. import grass.lib.gis as gislib
  824. global haveCtypes
  825. haveCtypes = True
  826. gislib.G_begin_distance_calculations()
  827. except ImportError, e:
  828. self._layerManager.goutput.WriteWarning(_('Geodesic distance is not yet '
  829. 'supported by this tool.\n'
  830. 'Reason: %s' % e))
  831. def MeasureDist(self, beginpt, endpt):
  832. """!Calculate map distance from screen distance
  833. and print to output window
  834. """
  835. self._layerManager.notebook.SetSelectionByName('output')
  836. dist, (north, east) = self.MapWindow.Distance(beginpt, endpt)
  837. dist = round(dist, 3)
  838. d, dunits = self.FormatDist(dist)
  839. self.totaldist += dist
  840. td, tdunits = self.FormatDist(self.totaldist)
  841. strdist = str(d)
  842. strtotdist = str(td)
  843. if self.Map.projinfo['proj'] == 'xy' or 'degree' not in self.Map.projinfo['unit']:
  844. angle = int(math.degrees(math.atan2(north,east)) + 0.5)
  845. angle = 180 - angle
  846. if angle < 0:
  847. angle = 360 + angle
  848. mstring = '%s = %s %s\n%s = %s %s\n%s = %d %s\n%s' \
  849. % (_('segment'), strdist, dunits,
  850. _('total distance'), strtotdist, tdunits,
  851. _('bearing'), angle, _('deg'),
  852. '-' * 60)
  853. else:
  854. mstring = '%s = %s %s\n%s = %s %s\n%s' \
  855. % (_('segment'), strdist, dunits,
  856. _('total distance'), strtotdist, tdunits,
  857. '-' * 60)
  858. self._layerManager.goutput.WriteLog(mstring)
  859. return dist
  860. def OnProfile(self, event):
  861. """!Init profile canvas and tools
  862. """
  863. raster = []
  864. if self.tree.layer_selected and \
  865. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  866. raster.append(self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  867. self.profile = ProfileFrame(self, size = wx.Size(700, 300),
  868. rasterList = raster)
  869. self.profile.Show()
  870. # Open raster select dialog to make sure that a raster (and the desired raster)
  871. # is selected to be profiled
  872. self.profile.OnSelectRaster(None)
  873. def FormatDist(self, dist):
  874. """!Format length numbers and units in a nice way,
  875. as a function of length. From code by Hamish Bowman
  876. Grass Development Team 2006"""
  877. mapunits = self.Map.projinfo['units']
  878. if mapunits == 'metres':
  879. mapunits = 'meters'
  880. outunits = mapunits
  881. dist = float(dist)
  882. divisor = 1.0
  883. # figure out which units to use
  884. if mapunits == 'meters':
  885. if dist > 2500.0:
  886. outunits = 'km'
  887. divisor = 1000.0
  888. else: outunits = 'm'
  889. elif mapunits == 'feet':
  890. # nano-bug: we match any "feet", but US Survey feet is really
  891. # 5279.9894 per statute mile, or 10.6' per 1000 miles. As >1000
  892. # miles the tick markers are rounded to the nearest 10th of a
  893. # mile (528'), the difference in foot flavours is ignored.
  894. if dist > 5280.0:
  895. outunits = 'miles'
  896. divisor = 5280.0
  897. else:
  898. outunits = 'ft'
  899. elif 'degree' in mapunits and \
  900. not haveCtypes:
  901. if dist < 1:
  902. outunits = 'min'
  903. divisor = (1/60.0)
  904. else:
  905. outunits = 'deg'
  906. else:
  907. outunits = 'meters'
  908. # format numbers in a nice way
  909. if (dist/divisor) >= 2500.0:
  910. outdist = round(dist/divisor)
  911. elif (dist/divisor) >= 1000.0:
  912. outdist = round(dist/divisor,1)
  913. elif (dist/divisor) > 0.0:
  914. outdist = round(dist/divisor,int(math.ceil(3-math.log10(dist/divisor))))
  915. else:
  916. outdist = float(dist/divisor)
  917. return (outdist, outunits)
  918. def OnHistogramPyPlot(self, event):
  919. """!Init PyPlot histogram display canvas and tools
  920. """
  921. raster = []
  922. for layer in self.tree.GetSelections():
  923. if self.tree.GetPyData(layer)[0]['maplayer'].GetType() != 'raster':
  924. continue
  925. raster.append(self.tree.GetPyData(layer)[0]['maplayer'].GetName())
  926. self.histogramPyPlot = Histogram2Frame(self, id = wx.ID_ANY,
  927. pos = wx.DefaultPosition, size = (700,300),
  928. style = wx.DEFAULT_FRAME_STYLE,
  929. rasterList = raster)
  930. self.histogramPyPlot.Show()
  931. # Open raster select dialog to make sure that a raster (and the desired raster)
  932. # is selected to be histogrammed
  933. self.histogramPyPlot.OnSelectRaster(None)
  934. def OnScatterplot(self, event):
  935. """!Init PyPlot scatterplot display canvas and tools
  936. """
  937. raster = []
  938. for layer in self.tree.GetSelections():
  939. if self.tree.GetPyData(layer)[0]['maplayer'].GetType() != 'raster':
  940. continue
  941. raster.append(self.tree.GetPyData(layer)[0]['maplayer'].GetName())
  942. self.scatterplot = ScatterFrame(self, id = wx.ID_ANY,
  943. pos = wx.DefaultPosition, size = (700,300),
  944. style = wx.DEFAULT_FRAME_STYLE,
  945. rasterList = raster)
  946. self.scatterplot.Show()
  947. # Open raster select dialog to make sure that at least 2 rasters (and the desired rasters)
  948. # are selected to be plotted
  949. self.scatterplot.OnSelectRaster(None)
  950. def OnHistogram(self, event):
  951. """!Init histogram display canvas and tools
  952. """
  953. self.histogram = HistogramFrame(parent = self, id = wx.ID_ANY, size = globalvar.HIST_WINDOW_SIZE,
  954. style = wx.DEFAULT_FRAME_STYLE)
  955. # show new display
  956. self.histogram.Show()
  957. self.histogram.Refresh()
  958. self.histogram.Update()
  959. def OnDecoration(self, event):
  960. """!Decorations overlay menu
  961. """
  962. point = wx.GetMousePosition()
  963. decmenu = wx.Menu()
  964. icons = Icons['displayWindow']
  965. # Add items to the menu
  966. AddScale = wx.MenuItem(decmenu, wx.ID_ANY, icons["addBarscale"].GetLabel())
  967. AddScale.SetBitmap(icons["addBarscale"].GetBitmap(self.iconsize))
  968. decmenu.AppendItem(AddScale)
  969. self.Bind(wx.EVT_MENU, self.OnAddBarscale, AddScale)
  970. # temporary
  971. if self.IsPaneShown('3d'):
  972. AddScale.Enable(False)
  973. AddArrow = wx.MenuItem(decmenu, wx.ID_ANY, _("Add north arrow"))
  974. AddArrow.SetBitmap(icons["addBarscale"].GetBitmap(self.iconsize))
  975. decmenu.AppendItem(AddArrow)
  976. self.Bind(wx.EVT_MENU, self.OnAddArrow, AddArrow)
  977. AddLegend = wx.MenuItem(decmenu, wx.ID_ANY, icons["addLegend"].GetLabel())
  978. AddLegend.SetBitmap(icons["addLegend"].GetBitmap(self.iconsize))
  979. decmenu.AppendItem(AddLegend)
  980. self.Bind(wx.EVT_MENU, self.OnAddLegend, AddLegend)
  981. AddText = wx.MenuItem(decmenu, wx.ID_ANY, icons["addText"].GetLabel())
  982. AddText.SetBitmap(icons["addText"].GetBitmap(self.iconsize))
  983. decmenu.AppendItem(AddText)
  984. self.Bind(wx.EVT_MENU, self.OnAddText, AddText)
  985. # Popup the menu. If an item is selected then its handler
  986. # will be called before PopupMenu returns.
  987. self.PopupMenu(decmenu)
  988. decmenu.Destroy()
  989. def OnAddBarscale(self, event):
  990. """!Handler for scale/arrow map decoration menu selection.
  991. """
  992. if self.dialogs['barscale']:
  993. return
  994. id = 0 # unique index for overlay layer
  995. # If location is latlon, only display north arrow (scale won't work)
  996. # proj = self.Map.projinfo['proj']
  997. # if proj == 'll':
  998. # barcmd = 'd.barscale -n'
  999. # else:
  1000. # barcmd = 'd.barscale'
  1001. # decoration overlay control dialog
  1002. self.dialogs['barscale'] = \
  1003. DecorationDialog(parent = self, title = _('Scale and North arrow'),
  1004. size = (350, 200),
  1005. style = wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1006. cmd = ['d.barscale', 'at=0,95'],
  1007. ovlId = id,
  1008. name = 'barscale',
  1009. checktxt = _("Show/hide scale and North arrow"),
  1010. ctrltxt = _("scale object"))
  1011. self.dialogs['barscale'].CentreOnParent()
  1012. ### dialog cannot be show as modal - in the result d.barscale is not selectable
  1013. ### self.dialogs['barscale'].ShowModal()
  1014. self.dialogs['barscale'].Show()
  1015. self.MapWindow.mouse['use'] = 'pointer'
  1016. def OnAddLegend(self, event):
  1017. """!Handler for legend map decoration menu selection.
  1018. """
  1019. if self.dialogs['legend']:
  1020. return
  1021. id = 1 # index for overlay layer in render
  1022. cmd = ['d.legend', 'at=5,50,2,5']
  1023. if self.tree and self.tree.layer_selected and \
  1024. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  1025. cmd.append('map=%s' % self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  1026. # Decoration overlay control dialog
  1027. self.dialogs['legend'] = \
  1028. DecorationDialog(parent = self, title = ('Legend'),
  1029. size = (350, 200),
  1030. style = wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1031. cmd = cmd,
  1032. ovlId = id,
  1033. name = 'legend',
  1034. checktxt = _("Show/hide legend"),
  1035. ctrltxt = _("legend object"))
  1036. self.dialogs['legend'].CentreOnParent()
  1037. ### dialog cannot be show as modal - in the result d.legend is not selectable
  1038. ### self.dialogs['legend'].ShowModal()
  1039. self.dialogs['legend'].Show()
  1040. self.MapWindow.mouse['use'] = 'pointer'
  1041. def OnAddText(self, event):
  1042. """!Handler for text decoration menu selection.
  1043. """
  1044. if self.MapWindow.dragid > -1:
  1045. id = self.MapWindow.dragid
  1046. self.MapWindow.dragid = -1
  1047. else:
  1048. # index for overlay layer in render
  1049. if len(self.MapWindow.textdict.keys()) > 0:
  1050. id = max(self.MapWindow.textdict.keys()) + 1
  1051. else:
  1052. id = 101
  1053. self.dialogs['text'] = TextLayerDialog(parent = self, ovlId = id,
  1054. title = _('Add text layer'),
  1055. size = (400, 200))
  1056. self.dialogs['text'].CenterOnParent()
  1057. # If OK button pressed in decoration control dialog
  1058. if self.dialogs['text'].ShowModal() == wx.ID_OK:
  1059. text = self.dialogs['text'].GetValues()['text']
  1060. active = self.dialogs['text'].GetValues()['active']
  1061. # delete object if it has no text or is not active
  1062. if text == '' or active == False:
  1063. try:
  1064. self.MapWindow2D.pdc.ClearId(id)
  1065. self.MapWindow2D.pdc.RemoveId(id)
  1066. del self.MapWindow.textdict[id]
  1067. if self.IsPaneShown('3d'):
  1068. self.MapWindow3D.UpdateOverlays()
  1069. self.MapWindow.UpdateMap()
  1070. else:
  1071. self.MapWindow2D.UpdateMap(render = False, renderVector = False)
  1072. except:
  1073. pass
  1074. return
  1075. self.MapWindow.textdict[id] = self.dialogs['text'].GetValues()
  1076. if self.IsPaneShown('3d'):
  1077. self.MapWindow3D.UpdateOverlays()
  1078. self.MapWindow3D.UpdateMap()
  1079. else:
  1080. self.MapWindow2D.pdc.ClearId(id)
  1081. self.MapWindow2D.pdc.SetId(id)
  1082. self.MapWindow2D.UpdateMap(render = False, renderVector = False)
  1083. self.MapWindow.mouse['use'] = 'pointer'
  1084. def OnAddArrow(self, event):
  1085. """!Handler for north arrow menu selection.
  1086. Opens Appearance page of nviz notebook.
  1087. """
  1088. self._layerManager.nviz.SetPage('decoration')
  1089. self.MapWindow3D.SetDrawArrow((70, 70))
  1090. def GetOptData(self, dcmd, type, params, propwin):
  1091. """!Callback method for decoration overlay command generated by
  1092. dialog created in menuform.py
  1093. """
  1094. # Reset comand and rendering options in render.Map. Always render decoration.
  1095. # Showing/hiding handled by PseudoDC
  1096. self.Map.ChangeOverlay(ovltype = type, type = 'overlay', name = '', command = dcmd,
  1097. l_active = True, l_render = False)
  1098. self.params[type] = params
  1099. self.propwin[type] = propwin
  1100. def OnZoomToMap(self, event):
  1101. """!Set display extents to match selected raster (including
  1102. NULLs) or vector map.
  1103. """
  1104. layers = None
  1105. if self.IsStandalone():
  1106. layers = self.MapWindow.GetMap().GetListOfLayers(l_active = False)
  1107. self.MapWindow.ZoomToMap(layers = layers)
  1108. def OnZoomToRaster(self, event):
  1109. """!Set display extents to match selected raster map (ignore NULLs)
  1110. """
  1111. self.MapWindow.ZoomToMap(ignoreNulls = True)
  1112. def OnZoomToSaved(self, event):
  1113. """!Set display geometry to match extents in
  1114. saved region file
  1115. """
  1116. self.MapWindow.ZoomToSaved()
  1117. def OnDisplayToWind(self, event):
  1118. """!Set computational region (WIND file) to match display
  1119. extents
  1120. """
  1121. self.MapWindow.DisplayToWind()
  1122. def SaveDisplayRegion(self, event):
  1123. """!Save display extents to named region file.
  1124. """
  1125. self.MapWindow.SaveDisplayRegion()
  1126. def OnZoomMenu(self, event):
  1127. """!Popup Zoom menu
  1128. """
  1129. point = wx.GetMousePosition()
  1130. zoommenu = wx.Menu()
  1131. # Add items to the menu
  1132. zoomwind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to computational region'))
  1133. zoommenu.AppendItem(zoomwind)
  1134. self.Bind(wx.EVT_MENU, self.OnZoomToWind, zoomwind)
  1135. zoomdefault = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to default region'))
  1136. zoommenu.AppendItem(zoomdefault)
  1137. self.Bind(wx.EVT_MENU, self.OnZoomToDefault, zoomdefault)
  1138. zoomsaved = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to saved region'))
  1139. zoommenu.AppendItem(zoomsaved)
  1140. self.Bind(wx.EVT_MENU, self.OnZoomToSaved, zoomsaved)
  1141. savewind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Set computational region from display extent'))
  1142. zoommenu.AppendItem(savewind)
  1143. self.Bind(wx.EVT_MENU, self.OnDisplayToWind, savewind)
  1144. savezoom = wx.MenuItem(zoommenu, wx.ID_ANY, _('Save display geometry to named region'))
  1145. zoommenu.AppendItem(savezoom)
  1146. self.Bind(wx.EVT_MENU, self.SaveDisplayRegion, savezoom)
  1147. # Popup the menu. If an item is selected then its handler
  1148. # will be called before PopupMenu returns.
  1149. self.PopupMenu(zoommenu)
  1150. zoommenu.Destroy()
  1151. def SetProperties(self, render = False, mode = 0, showCompExtent = False,
  1152. constrainRes = False, projection = False, alignExtent = True):
  1153. """!Set properies of map display window"""
  1154. self.SetProperty('render', render)
  1155. self.statusbarManager.SetMode(mode)
  1156. self.StatusbarUpdate()
  1157. self.SetProperty('region', showCompExtent)
  1158. self.SetProperty('alignExtent', alignExtent)
  1159. self.SetProperty('resolution', constrainRes)
  1160. self.SetProperty('projection', projection)
  1161. def IsStandalone(self):
  1162. """!Check if Map display is standalone"""
  1163. if self._layerManager:
  1164. return False
  1165. return True
  1166. def GetLayerManager(self):
  1167. """!Get reference to Layer Manager
  1168. @return window reference
  1169. @return None (if standalone)
  1170. """
  1171. return self._layerManager
  1172. def GetMapToolbar(self):
  1173. """!Returns toolbar with zooming tools"""
  1174. return self.toolbars['map']
  1175. class MapApp(wx.App):
  1176. def OnInit(self):
  1177. wx.InitAllImageHandlers()
  1178. if __name__ == "__main__":
  1179. self.cmdTimeStamp = os.path.getmtime(monFile['cmd'])
  1180. Map = Map(cmdfile = monFile['cmd'], mapfile = monFile['map'],
  1181. envfile = monFile['env'], monitor = monName)
  1182. else:
  1183. Map = None
  1184. self.mapFrm = MapFrame(parent = None, id = wx.ID_ANY, Map = Map,
  1185. size = monSize)
  1186. # self.SetTopWindow(Map)
  1187. self.mapFrm.Show()
  1188. if __name__ == "__main__":
  1189. self.timer = wx.PyTimer(self.watcher)
  1190. #check each 0.5s
  1191. global mtime
  1192. mtime = 500
  1193. self.timer.Start(mtime)
  1194. return True
  1195. def OnExit(self):
  1196. if __name__ == "__main__":
  1197. # stop the timer
  1198. # self.timer.Stop()
  1199. # terminate thread
  1200. for f in monFile.itervalues():
  1201. grass.try_remove(f)
  1202. def watcher(self):
  1203. """!Redraw, if new layer appears (check's timestamp of
  1204. cmdfile)
  1205. """
  1206. # todo: events
  1207. if os.path.getmtime(monFile['cmd']) > self.cmdTimeStamp:
  1208. self.timer.Stop()
  1209. self.cmdTimeStamp = os.path.getmtime(monFile['cmd'])
  1210. self.mapFrm.OnDraw(None)
  1211. self.mapFrm.GetMap().GetLayersFromCmdFile()
  1212. self.timer.Start(mtime)
  1213. if __name__ == "__main__":
  1214. # set command variable
  1215. if len(sys.argv) < 5:
  1216. print __doc__
  1217. sys.exit(1)
  1218. monName = sys.argv[1]
  1219. monFile = { 'map' : sys.argv[2],
  1220. 'cmd' : sys.argv[3],
  1221. 'env' : sys.argv[4],
  1222. }
  1223. if len(sys.argv) >= 6:
  1224. try:
  1225. monSize[0] = int(sys.argv[5])
  1226. except ValueError:
  1227. pass
  1228. if len(sys.argv) == 7:
  1229. try:
  1230. monSize[1] = int(sys.argv[6])
  1231. except ValueError:
  1232. pass
  1233. import gettext
  1234. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1235. grass.verbose(_("Starting map display <%s>...") % (monName))
  1236. RunCommand('g.gisenv',
  1237. set = 'MONITOR_%s_PID=%d' % (monName, os.getpid()))
  1238. gm_map = MapApp(0)
  1239. # set title
  1240. gm_map.mapFrm.SetTitle(_("GRASS GIS Map Display: " +
  1241. monName +
  1242. " - Location: " + grass.gisenv()["LOCATION_NAME"]))
  1243. gm_map.MainLoop()
  1244. grass.verbose(_("Stopping map display <%s>...") % (monName))
  1245. # clean up GRASS env variables
  1246. env = grass.gisenv()
  1247. env_name = 'MONITOR_%s' % monName
  1248. for key in env.keys():
  1249. if key.find(env_name) == 0:
  1250. RunCommand('g.gisenv',
  1251. set = '%s=' % key)
  1252. if key == 'MONITOR' and env[key] == monName:
  1253. RunCommand('g.gisenv',
  1254. set = '%s=' % key)
  1255. sys.exit(0)