mapdisplay.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. """!
  2. @package gcp.mapdisplay
  3. @brief Display to manage ground control points with two toolbars, one
  4. for various display management functions, one for manipulating GCPs.
  5. Classes:
  6. - mapdisplay::MapFrame
  7. (C) 2006-2011 by the GRASS Development Team
  8. This program is free software under the GNU General Public License
  9. (>=v2). Read the file COPYING that comes with GRASS for details.
  10. @author Markus Metz
  11. """
  12. import os
  13. import math
  14. import platform
  15. from core import globalvar
  16. import wx
  17. import wx.aui
  18. from core.render import EVT_UPDATE_PRGBAR
  19. from mapdisp.toolbars import MapToolbar
  20. from gcp.toolbars import GCPDisplayToolbar, GCPManToolbar
  21. from mapdisp.gprint import PrintOptions
  22. from core.gcmd import GMessage
  23. from gui_core.dialogs import GetImageHandlers, ImageSizeDialog
  24. from gui_core.mapdisp import SingleMapFrame
  25. from core.settings import UserSettings
  26. from mapdisp.mapwindow import BufferedWindow
  27. import mapdisp.statusbar as sb
  28. # for standalone app
  29. cmdfilename = None
  30. class MapFrame(SingleMapFrame):
  31. """!Main frame for map display window. Drawing takes place in
  32. child double buffered drawing window.
  33. """
  34. def __init__(self, parent=None, title=_("GRASS GIS Manage Ground Control Points"),
  35. toolbars=["gcpdisp"], tree=None, notebook=None, lmgr=None,
  36. page=None, Map=None, auimgr=None, name = 'GCPMapWindow', **kwargs):
  37. """!Main map display window with toolbars, statusbar and
  38. DrawWindow
  39. @param toolbars array of activated toolbars, e.g. ['map', 'digit']
  40. @param tree reference to layer tree
  41. @param notebook control book ID in Layer Manager
  42. @param lmgr Layer Manager
  43. @param page notebook page with layer tree
  44. @param Map instance of render.Map
  45. @param auimgs AUI manager
  46. @param kwargs wx.Frame attribures
  47. """
  48. SingleMapFrame.__init__(self, parent = parent, title = title,
  49. Map = Map, auimgr = auimgr, name = name, **kwargs)
  50. self._layerManager = lmgr # Layer Manager object
  51. self.tree = tree # Layer Manager layer tree object
  52. self.page = page # Notebook page holding the layer tree
  53. self.layerbook = notebook # Layer Manager layer tree notebook
  54. #
  55. # Add toolbars
  56. #
  57. for toolb in toolbars:
  58. self.AddToolbar(toolb)
  59. self.activemap = self.toolbars['gcpdisp'].togglemap
  60. self.activemap.SetSelection(0)
  61. self.SrcMap = self.grwiz.SrcMap # instance of render.Map
  62. self.TgtMap = self.grwiz.TgtMap # instance of render.Map
  63. self._mgr.SetDockSizeConstraint(0.5, 0.5)
  64. #
  65. # Add statusbar
  66. #
  67. # items for choice
  68. self.statusbarItems = [sb.SbCoordinates,
  69. sb.SbRegionExtent,
  70. sb.SbCompRegionExtent,
  71. sb.SbShowRegion,
  72. sb.SbResolution,
  73. sb.SbDisplayGeometry,
  74. sb.SbMapScale,
  75. sb.SbProjection,
  76. sb.SbGoToGCP,
  77. sb.SbRMSError]
  78. # create statusbar and its manager
  79. statusbar = self.CreateStatusBar(number = 4, style = 0)
  80. statusbar.SetStatusWidths([-5, -2, -1, -1])
  81. self.statusbarManager = sb.SbManager(mapframe = self, statusbar = statusbar)
  82. # fill statusbar manager
  83. self.statusbarManager.AddStatusbarItemsByClass(self.statusbarItems, mapframe = self, statusbar = statusbar)
  84. self.statusbarManager.AddStatusbarItem(sb.SbMask(self, statusbar = statusbar, position = 2))
  85. self.statusbarManager.AddStatusbarItem(sb.SbRender(self, statusbar = statusbar, position = 3))
  86. self.statusbarManager.SetMode(8) # goto GCP
  87. self.statusbarManager.Update()
  88. #
  89. # Init map display (buffered DC & set default cursor)
  90. #
  91. self.grwiz.SwitchEnv('source')
  92. self.SrcMapWindow = BufferedWindow(self, id=wx.ID_ANY,
  93. Map=self.SrcMap, tree=self.tree, lmgr=self._layerManager)
  94. self.grwiz.SwitchEnv('target')
  95. self.TgtMapWindow = BufferedWindow(self, id=wx.ID_ANY,
  96. Map=self.TgtMap, tree=self.tree, lmgr=self._layerManager)
  97. self.MapWindow = self.SrcMapWindow
  98. self.Map = self.SrcMap
  99. self.SrcMapWindow.SetCursor(self.cursors["cross"])
  100. self.TgtMapWindow.SetCursor(self.cursors["cross"])
  101. #
  102. # initialize region values
  103. #
  104. self._initMap(Map = self.SrcMap)
  105. self._initMap(Map = self.TgtMap)
  106. #
  107. # Bind various events
  108. #
  109. self.Bind(EVT_UPDATE_PRGBAR, self.OnUpdateProgress)
  110. self.activemap.Bind(wx.EVT_CHOICE, self.OnUpdateActive)
  111. #
  112. # Update fancy gui style
  113. #
  114. # AuiManager wants a CentrePane, workaround to get two equally sized windows
  115. self.list = self.CreateGCPList()
  116. #self.SrcMapWindow.SetSize((300, 300))
  117. #self.TgtMapWindow.SetSize((300, 300))
  118. self.list.SetSize((100, 150))
  119. self._mgr.AddPane(self.list, wx.aui.AuiPaneInfo().
  120. Name("gcplist").Caption(_("GCP List")).LeftDockable(False).
  121. RightDockable(False).PinButton().FloatingSize((600,200)).
  122. CloseButton(False).DestroyOnClose(True).
  123. Top().Layer(1).MinSize((200,100)))
  124. self._mgr.AddPane(self.SrcMapWindow, wx.aui.AuiPaneInfo().
  125. Name("source").Caption(_("Source Display")).Dockable(False).
  126. CloseButton(False).DestroyOnClose(True).Floatable(False).
  127. Centre())
  128. self._mgr.AddPane(self.TgtMapWindow, wx.aui.AuiPaneInfo().
  129. Name("target").Caption(_("Target Display")).Dockable(False).
  130. CloseButton(False).DestroyOnClose(True).Floatable(False).
  131. Right().Layer(0))
  132. srcwidth, srcheight = self.SrcMapWindow.GetSize()
  133. tgtwidth, tgtheight = self.TgtMapWindow.GetSize()
  134. srcwidth = (srcwidth + tgtwidth) / 2
  135. self._mgr.GetPane("target").Hide()
  136. self._mgr.Update()
  137. self._mgr.GetPane("source").BestSize((srcwidth, srcheight))
  138. self._mgr.GetPane("target").BestSize((srcwidth, srcheight))
  139. if self.show_target:
  140. self._mgr.GetPane("target").Show()
  141. else:
  142. self.activemap.Enable(False)
  143. # needed by Mac OS, does not harm on Linux, breaks display on Windows
  144. if platform.system() != 'Windows':
  145. self._mgr.Update()
  146. #
  147. # Init print module and classes
  148. #
  149. self.printopt = PrintOptions(self, self.MapWindow)
  150. #
  151. # Initialization of digitization tool
  152. #
  153. self.digit = None
  154. # set active map
  155. self.MapWindow = self.SrcMapWindow
  156. self.Map = self.SrcMap
  157. # do not init zoom history here, that happens when zooming to map(s)
  158. #
  159. # Re-use dialogs
  160. #
  161. self.dialogs = {}
  162. self.dialogs['attributes'] = None
  163. self.dialogs['category'] = None
  164. self.dialogs['barscale'] = None
  165. self.dialogs['legend'] = None
  166. self.decorationDialog = None # decoration/overlays
  167. def AddToolbar(self, name):
  168. """!Add defined toolbar to the window
  169. Currently known toolbars are:
  170. - 'map' - basic map toolbar
  171. - 'vdigit' - vector digitizer
  172. - 'gcpdisp' - GCP Manager, Display
  173. - 'gcpman' - GCP Manager, points management
  174. - 'nviz' - 3D view mode
  175. """
  176. # default toolbar
  177. if name == "map":
  178. self.toolbars['map'] = MapToolbar(self, self.Map)
  179. self._mgr.AddPane(self.toolbars['map'],
  180. wx.aui.AuiPaneInfo().
  181. Name("maptoolbar").Caption(_("Map Toolbar")).
  182. ToolbarPane().Top().
  183. LeftDockable(False).RightDockable(False).
  184. BottomDockable(False).TopDockable(True).
  185. CloseButton(False).Layer(2).
  186. BestSize((self.toolbars['map'].GetSize())))
  187. # GCP display
  188. elif name == "gcpdisp":
  189. self.toolbars['gcpdisp'] = GCPDisplayToolbar(self)
  190. self._mgr.AddPane(self.toolbars['gcpdisp'],
  191. wx.aui.AuiPaneInfo().
  192. Name("gcpdisplaytoolbar").Caption(_("GCP Display toolbar")).
  193. ToolbarPane().Top().
  194. LeftDockable(False).RightDockable(False).
  195. BottomDockable(False).TopDockable(True).
  196. CloseButton(False).Layer(2))
  197. if self.show_target == False:
  198. self.toolbars['gcpdisp'].Enable('zoommenu', enable = False)
  199. self.toolbars['gcpman'] = GCPManToolbar(self)
  200. self._mgr.AddPane(self.toolbars['gcpman'],
  201. wx.aui.AuiPaneInfo().
  202. Name("gcpmanagertoolbar").Caption(_("GCP Manager toolbar")).
  203. ToolbarPane().Top().Row(1).
  204. LeftDockable(False).RightDockable(False).
  205. BottomDockable(False).TopDockable(True).
  206. CloseButton(False).Layer(2))
  207. self._mgr.Update()
  208. def OnUpdateProgress(self, event):
  209. """
  210. Update progress bar info
  211. """
  212. self.GetProgressBar().SetValue(event.value)
  213. event.Skip()
  214. def OnFocus(self, event):
  215. """
  216. Change choicebook page to match display.
  217. Or set display for georectifying
  218. """
  219. if self._layerManager and \
  220. self._layerManager.gcpmanagement:
  221. # in GCP Management, set focus to current MapWindow for mouse actions
  222. self.OnPointer(event)
  223. self.MapWindow.SetFocus()
  224. else:
  225. # change bookcontrol page to page associated with display
  226. # GCP Manager: use bookcontrol?
  227. if self.page:
  228. pgnum = self.layerbook.GetPageIndex(self.page)
  229. if pgnum > -1:
  230. self.layerbook.SetSelection(pgnum)
  231. event.Skip()
  232. def OnDraw(self, event):
  233. """!Re-display current map composition
  234. """
  235. self.MapWindow.UpdateMap(render = False)
  236. def OnRender(self, event):
  237. """!Re-render map composition (each map layer)
  238. """
  239. # delete tmp map layers (queries)
  240. qlayer = self.Map.GetListOfLayers(l_name=globalvar.QUERYLAYER)
  241. for layer in qlayer:
  242. self.Map.DeleteLayer(layer)
  243. self.SrcMapWindow.UpdateMap(render=True)
  244. if self.show_target:
  245. self.TgtMapWindow.UpdateMap(render=True)
  246. # update statusbar
  247. self.StatusbarUpdate()
  248. def OnPointer(self, event):
  249. """!Pointer button clicked
  250. """
  251. # change the cursor
  252. self.SrcMapWindow.SetCursor(self.cursors["cross"])
  253. self.SrcMapWindow.mouse['use'] = "pointer"
  254. self.SrcMapWindow.mouse['box'] = "point"
  255. self.TgtMapWindow.SetCursor(self.cursors["cross"])
  256. self.TgtMapWindow.mouse['use'] = "pointer"
  257. self.TgtMapWindow.mouse['box'] = "point"
  258. def OnZoomIn(self, event):
  259. """
  260. Zoom in the map.
  261. Set mouse cursor, zoombox attributes, and zoom direction
  262. """
  263. self.toolbars['gcpdisp'].OnTool(event)
  264. self.toolbars['gcpdisp'].action['desc'] = ''
  265. self.MapWindow.mouse['use'] = "zoom"
  266. self.MapWindow.mouse['box'] = "box"
  267. self.MapWindow.zoomtype = 1
  268. self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  269. # change the cursor
  270. self.MapWindow.SetCursor(self.cursors["cross"])
  271. if self.MapWindow == self.SrcMapWindow:
  272. win = self.TgtMapWindow
  273. elif self.MapWindow == self.TgtMapWindow:
  274. win = self.SrcMapWindow
  275. win.mouse['use'] = "zoom"
  276. win.mouse['box'] = "box"
  277. win.zoomtype = 1
  278. win.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  279. # change the cursor
  280. win.SetCursor(self.cursors["cross"])
  281. def OnZoomOut(self, event):
  282. """
  283. Zoom out the map.
  284. Set mouse cursor, zoombox attributes, and zoom direction
  285. """
  286. self.toolbars['gcpdisp'].OnTool(event)
  287. self.toolbars['gcpdisp'].action['desc'] = ''
  288. self.MapWindow.mouse['use'] = "zoom"
  289. self.MapWindow.mouse['box'] = "box"
  290. self.MapWindow.zoomtype = -1
  291. self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  292. # change the cursor
  293. self.MapWindow.SetCursor(self.cursors["cross"])
  294. if self.MapWindow == self.SrcMapWindow:
  295. win = self.TgtMapWindow
  296. elif self.MapWindow == self.TgtMapWindow:
  297. win = self.SrcMapWindow
  298. win.mouse['use'] = "zoom"
  299. win.mouse['box'] = "box"
  300. win.zoomtype = -1
  301. win.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  302. # change the cursor
  303. win.SetCursor(self.cursors["cross"])
  304. def OnPan(self, event):
  305. """
  306. Panning, set mouse to drag
  307. """
  308. self.toolbars['gcpdisp'].OnTool(event)
  309. self.toolbars['gcpdisp'].action['desc'] = ''
  310. self.MapWindow.mouse['use'] = "pan"
  311. self.MapWindow.mouse['box'] = "pan"
  312. self.MapWindow.zoomtype = 0
  313. # change the cursor
  314. self.MapWindow.SetCursor(self.cursors["hand"])
  315. if self.MapWindow == self.SrcMapWindow:
  316. win = self.TgtMapWindow
  317. elif self.MapWindow == self.TgtMapWindow:
  318. win = self.SrcMapWindow
  319. win.mouse['use'] = "pan"
  320. win.mouse['box'] = "pan"
  321. win.zoomtype = 0
  322. # change the cursor
  323. win.SetCursor(self.cursors["hand"])
  324. def OnErase(self, event):
  325. """
  326. Erase the canvas
  327. """
  328. self.MapWindow.EraseMap()
  329. if self.MapWindow == self.SrcMapWindow:
  330. win = self.TgtMapWindow
  331. elif self.MapWindow == self.TgtMapWindow:
  332. win = self.SrcMapWindow
  333. win.EraseMap()
  334. def OnZoomRegion(self, event):
  335. """
  336. Zoom to region
  337. """
  338. self.Map.getRegion()
  339. self.Map.getResolution()
  340. self.UpdateMap()
  341. # event.Skip()
  342. def OnAlignRegion(self, event):
  343. """
  344. Align region
  345. """
  346. if not self.Map.alignRegion:
  347. self.Map.alignRegion = True
  348. else:
  349. self.Map.alignRegion = False
  350. # event.Skip()
  351. def SaveToFile(self, event):
  352. """!Save map to image
  353. """
  354. img = self.MapWindow.img
  355. if not img:
  356. GMessage(parent = self,
  357. message = _("Nothing to render (empty map). Operation canceled."))
  358. return
  359. filetype, ltype = GetImageHandlers(img)
  360. # get size
  361. dlg = ImageSizeDialog(self)
  362. dlg.CentreOnParent()
  363. if dlg.ShowModal() != wx.ID_OK:
  364. dlg.Destroy()
  365. return
  366. width, height = dlg.GetValues()
  367. dlg.Destroy()
  368. # get filename
  369. dlg = wx.FileDialog(parent = self,
  370. message = _("Choose a file name to save the image "
  371. "(no need to add extension)"),
  372. wildcard = filetype,
  373. style=wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  374. if dlg.ShowModal() == wx.ID_OK:
  375. path = dlg.GetPath()
  376. if not path:
  377. dlg.Destroy()
  378. return
  379. base, ext = os.path.splitext(path)
  380. fileType = ltype[dlg.GetFilterIndex()]['type']
  381. extType = ltype[dlg.GetFilterIndex()]['ext']
  382. if ext != extType:
  383. path = base + '.' + extType
  384. self.MapWindow.SaveToFile(path, fileType,
  385. width, height)
  386. dlg.Destroy()
  387. def PrintMenu(self, event):
  388. """
  389. Print options and output menu for map display
  390. """
  391. point = wx.GetMousePosition()
  392. printmenu = wx.Menu()
  393. # Add items to the menu
  394. setup = wx.MenuItem(printmenu, wx.ID_ANY, _('Page setup'))
  395. printmenu.AppendItem(setup)
  396. self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
  397. preview = wx.MenuItem(printmenu, wx.ID_ANY, _('Print preview'))
  398. printmenu.AppendItem(preview)
  399. self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
  400. doprint = wx.MenuItem(printmenu, wx.ID_ANY, _('Print display'))
  401. printmenu.AppendItem(doprint)
  402. self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
  403. # Popup the menu. If an item is selected then its handler
  404. # will be called before PopupMenu returns.
  405. self.PopupMenu(printmenu)
  406. printmenu.Destroy()
  407. def FormatDist(self, dist):
  408. """!Format length numbers and units in a nice way,
  409. as a function of length. From code by Hamish Bowman
  410. Grass Development Team 2006"""
  411. mapunits = self.Map.projinfo['units']
  412. if mapunits == 'metres': mapunits = 'meters'
  413. outunits = mapunits
  414. dist = float(dist)
  415. divisor = 1.0
  416. # figure out which units to use
  417. if mapunits == 'meters':
  418. if dist > 2500.0:
  419. outunits = 'km'
  420. divisor = 1000.0
  421. else: outunits = 'm'
  422. elif mapunits == 'feet':
  423. # nano-bug: we match any "feet", but US Survey feet is really
  424. # 5279.9894 per statute mile, or 10.6' per 1000 miles. As >1000
  425. # miles the tick markers are rounded to the nearest 10th of a
  426. # mile (528'), the difference in foot flavours is ignored.
  427. if dist > 5280.0:
  428. outunits = 'miles'
  429. divisor = 5280.0
  430. else:
  431. outunits = 'ft'
  432. elif 'degree' in mapunits:
  433. if dist < 1:
  434. outunits = 'min'
  435. divisor = (1/60.0)
  436. else:
  437. outunits = 'deg'
  438. # format numbers in a nice way
  439. if (dist/divisor) >= 2500.0:
  440. outdist = round(dist/divisor)
  441. elif (dist/divisor) >= 1000.0:
  442. outdist = round(dist/divisor,1)
  443. elif (dist/divisor) > 0.0:
  444. outdist = round(dist/divisor,int(math.ceil(3-math.log10(dist/divisor))))
  445. else:
  446. outdist = float(dist/divisor)
  447. return (outdist, outunits)
  448. def OnZoomToRaster(self, event):
  449. """!
  450. Set display extents to match selected raster map (ignore NULLs)
  451. """
  452. self.MapWindow.ZoomToMap(ignoreNulls = True)
  453. def OnZoomToSaved(self, event):
  454. """!Set display geometry to match extents in
  455. saved region file
  456. """
  457. self.MapWindow.ZoomToSaved()
  458. def OnDisplayToWind(self, event):
  459. """!Set computational region (WIND file) to match display
  460. extents
  461. """
  462. self.MapWindow.DisplayToWind()
  463. def SaveDisplayRegion(self, event):
  464. """!Save display extents to named region file.
  465. """
  466. self.MapWindow.SaveDisplayRegion()
  467. def OnZoomMenu(self, event):
  468. """!Popup Zoom menu
  469. """
  470. point = wx.GetMousePosition()
  471. zoommenu = wx.Menu()
  472. # Add items to the menu
  473. zoomwind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to computational region (set with g.region)'))
  474. zoommenu.AppendItem(zoomwind)
  475. self.Bind(wx.EVT_MENU, self.OnZoomToWind, zoomwind)
  476. zoomdefault = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to default region'))
  477. zoommenu.AppendItem(zoomdefault)
  478. self.Bind(wx.EVT_MENU, self.OnZoomToDefault, zoomdefault)
  479. zoomsaved = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to saved region'))
  480. zoommenu.AppendItem(zoomsaved)
  481. self.Bind(wx.EVT_MENU, self.OnZoomToSaved, zoomsaved)
  482. savewind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Set computational region from display'))
  483. zoommenu.AppendItem(savewind)
  484. self.Bind(wx.EVT_MENU, self.OnDisplayToWind, savewind)
  485. savezoom = wx.MenuItem(zoommenu, wx.ID_ANY, _('Save display geometry to named region'))
  486. zoommenu.AppendItem(savezoom)
  487. self.Bind(wx.EVT_MENU, self.SaveDisplayRegion, savezoom)
  488. # Popup the menu. If an item is selected then its handler
  489. # will be called before PopupMenu returns.
  490. self.PopupMenu(zoommenu)
  491. zoommenu.Destroy()
  492. def IsStandalone(self):
  493. """!Check if Map display is standalone"""
  494. if self._layerManager:
  495. return False
  496. return True
  497. def GetLayerManager(self):
  498. """!Get reference to Layer Manager
  499. @return window reference
  500. @return None (if standalone)
  501. """
  502. return self._layerManager
  503. def GetSrcWindow(self):
  504. return self.SrcMapWindow
  505. def GetTgtWindow(self):
  506. return self.TgtMapWindow
  507. def GetShowTarget(self):
  508. return self.show_target
  509. def GetMapToolbar(self):
  510. """!Returns toolbar with zooming tools"""
  511. return self.toolbars['gcpdisp']