mapwindow.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. """
  2. @package animation.mapwindow
  3. @brief Animation window
  4. Classes:
  5. - mapwindow::BufferedWindow
  6. - mapwindow::AnimationWindow
  7. (C) 2013 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 Anna Petrasova <kratochanna gmail.com>
  11. """
  12. import wx
  13. from core.debug import Debug
  14. from gui_core.wrap import BitmapFromImage, EmptyBitmap, ImageFromBitmap, PseudoDC, Rect
  15. from .utils import ComputeScaledRect
  16. class BufferedWindow(wx.Window):
  17. """
  18. A Buffered window class (http://wiki.wxpython.org/DoubleBufferedDrawing).
  19. To use it, subclass it and define a Draw(DC) method that takes a DC
  20. to draw to. In that method, put the code needed to draw the picture
  21. you want. The window will automatically be double buffered, and the
  22. screen will be automatically updated when a Paint event is received.
  23. When the drawing needs to change, you app needs to call the
  24. UpdateDrawing() method. Since the drawing is stored in a bitmap, you
  25. can also save the drawing to file by calling the
  26. SaveToFile(self, file_name, file_type) method.
  27. """
  28. def __init__(self, *args, **kwargs):
  29. # make sure the NO_FULL_REPAINT_ON_RESIZE style flag is set.
  30. kwargs["style"] = (
  31. kwargs.setdefault("style", wx.NO_FULL_REPAINT_ON_RESIZE)
  32. | wx.NO_FULL_REPAINT_ON_RESIZE
  33. )
  34. wx.Window.__init__(self, *args, **kwargs)
  35. Debug.msg(2, "BufferedWindow.__init__()")
  36. self.Bind(wx.EVT_PAINT, self.OnPaint)
  37. self.Bind(wx.EVT_SIZE, self.OnSize)
  38. # OnSize called to make sure the buffer is initialized.
  39. # This might result in OnSize getting called twice on some
  40. # platforms at initialization, but little harm done.
  41. self.OnSize(None)
  42. def Draw(self, dc):
  43. # just here as a place holder.
  44. # This method should be over-ridden when subclassed
  45. pass
  46. def OnPaint(self, event):
  47. Debug.msg(5, "BufferedWindow.OnPaint()")
  48. # All that is needed here is to draw the buffer to screen
  49. dc = wx.BufferedPaintDC(self, self._Buffer)
  50. def OnSize(self, event):
  51. Debug.msg(5, "BufferedWindow.OnSize()")
  52. # The Buffer init is done here, to make sure the buffer is always
  53. # the same size as the Window
  54. # Size = self.GetClientSizeTuple()
  55. size = self.GetClientSize()
  56. # Make new offscreen bitmap: this bitmap will always have the
  57. # current drawing in it, so it can be used to save the image to
  58. # a file, or whatever.
  59. w = max(size[0], 20)
  60. h = max(size[1], 20)
  61. self._Buffer = EmptyBitmap(w, h)
  62. self.UpdateDrawing()
  63. # event.Skip()
  64. def SaveToFile(self, FileName, FileType=wx.BITMAP_TYPE_PNG):
  65. # This will save the contents of the buffer
  66. # to the specified file. See the wxWindows docs for
  67. # wx.Bitmap::SaveFile for the details
  68. self._Buffer.SaveFile(FileName, FileType)
  69. def UpdateDrawing(self):
  70. """
  71. This would get called if the drawing needed to change, for whatever reason.
  72. The idea here is that the drawing is based on some data generated
  73. elsewhere in the system. If that data changes, the drawing needs to
  74. be updated.
  75. This code re-draws the buffer, then calls Update, which forces a paint event.
  76. """
  77. dc = wx.MemoryDC()
  78. dc.SelectObject(self._Buffer)
  79. self.Draw(dc)
  80. del dc # need to get rid of the MemoryDC before Update() is called.
  81. self.Refresh()
  82. self.Update()
  83. class AnimationWindow(BufferedWindow):
  84. def __init__(
  85. self,
  86. parent,
  87. id=wx.ID_ANY,
  88. style=wx.DEFAULT_FRAME_STYLE | wx.FULL_REPAINT_ON_RESIZE | wx.BORDER_RAISED,
  89. ):
  90. Debug.msg(2, "AnimationWindow.__init__()")
  91. self.bitmap = EmptyBitmap(1, 1)
  92. self.parent = parent
  93. self._pdc = PseudoDC()
  94. self._overlay = None
  95. self._tmpMousePos = None
  96. self.x = self.y = 0
  97. self.bitmap_overlay = None
  98. BufferedWindow.__init__(self, parent=parent, id=id, style=style)
  99. self.SetBackgroundColour(wx.BLACK)
  100. self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
  101. self.Bind(wx.EVT_SIZE, self.OnSize)
  102. self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouseEvents)
  103. def Draw(self, dc):
  104. """Draws bitmap."""
  105. Debug.msg(5, "AnimationWindow.Draw()")
  106. dc.Clear() # make sure you clear the bitmap!
  107. if self.bitmap.GetWidth() > 1:
  108. dc.DrawBitmap(self.bitmap, x=self.x, y=self.y)
  109. def OnSize(self, event):
  110. Debug.msg(5, "AnimationWindow.OnSize()")
  111. BufferedWindow.OnSize(self, event)
  112. if event:
  113. event.Skip()
  114. def _rescaleIfNeeded(self, bitmap):
  115. """!If the bitmap has different size than the window, rescale it."""
  116. bW, bH = bitmap.GetSize()
  117. wW, wH = self.GetClientSize()
  118. if abs(bW - wW) > 5 or abs(bH - wH) > 5:
  119. params = ComputeScaledRect((bW, bH), (wW, wH))
  120. im = ImageFromBitmap(bitmap)
  121. im.Rescale(params["width"], params["height"])
  122. self.x = params["x"]
  123. self.y = params["y"]
  124. bitmap = BitmapFromImage(im)
  125. if self._overlay:
  126. im = ImageFromBitmap(self.bitmap_overlay)
  127. im.Rescale(
  128. im.GetWidth() * params["scale"], im.GetHeight() * params["scale"]
  129. )
  130. self._setOverlay(
  131. BitmapFromImage(im), xperc=self.perc[0], yperc=self.perc[1]
  132. )
  133. else:
  134. self.x = 0
  135. self.y = 0
  136. return bitmap
  137. def DrawBitmap(self, bitmap):
  138. """Draws bitmap.
  139. Does not draw the bitmap if it is the same one as last time.
  140. """
  141. bitmap = self._rescaleIfNeeded(bitmap)
  142. if self.bitmap == bitmap:
  143. return
  144. self.bitmap = bitmap
  145. self.UpdateDrawing()
  146. def DrawOverlay(self, x, y):
  147. self._pdc.BeginDrawing()
  148. self._pdc.SetId(1)
  149. self._pdc.DrawBitmap(bmp=self._overlay, x=x, y=y)
  150. self._pdc.SetIdBounds(
  151. 1, Rect(x, y, self._overlay.GetWidth(), self._overlay.GetHeight())
  152. )
  153. self._pdc.EndDrawing()
  154. def _setOverlay(self, bitmap, xperc, yperc):
  155. if self._overlay:
  156. self._pdc.RemoveAll()
  157. self._overlay = bitmap
  158. size = self.GetClientSize()
  159. x = xperc * size[0]
  160. y = yperc * size[1]
  161. self.DrawOverlay(x, y)
  162. def SetOverlay(self, bitmap, xperc, yperc):
  163. """Sets overlay bitmap (legend)
  164. :param bitmap: instance of wx.Bitmap
  165. :param xperc: x coordinate of bitmap top left corner in % of screen
  166. :param yperc: y coordinate of bitmap top left corner in % of screen
  167. """
  168. Debug.msg(3, "AnimationWindow.SetOverlay()")
  169. if bitmap:
  170. self._setOverlay(bitmap, xperc, yperc)
  171. self.bitmap_overlay = bitmap
  172. self.perc = (xperc, yperc)
  173. else:
  174. self._overlay = None
  175. self._pdc.RemoveAll()
  176. self.bitmap_overlay = None
  177. self.UpdateDrawing()
  178. def ClearOverlay(self):
  179. """Clear overlay (legend)"""
  180. Debug.msg(3, "AnimationWindow.ClearOverlay()")
  181. self._overlay = None
  182. self.bitmap_overlay = None
  183. self._pdc.RemoveAll()
  184. self.UpdateDrawing()
  185. def OnPaint(self, event):
  186. Debug.msg(5, "AnimationWindow.OnPaint()")
  187. # All that is needed here is to draw the buffer to screen
  188. dc = wx.BufferedPaintDC(self, self._Buffer)
  189. if self._overlay:
  190. self._pdc.DrawToDC(dc)
  191. def OnMouseEvents(self, event):
  192. """Handle mouse events."""
  193. # If it grows larger, split it.
  194. current = event.GetPosition()
  195. if event.LeftDown():
  196. self._dragid = None
  197. idlist = self._pdc.FindObjects(current[0], current[1], radius=10)
  198. if 1 in idlist:
  199. self._dragid = 1
  200. self._tmpMousePos = current
  201. elif event.LeftUp():
  202. self._dragid = None
  203. self._tmpMousePos = None
  204. elif event.Dragging():
  205. if self._dragid is None:
  206. return
  207. dx = current[0] - self._tmpMousePos[0]
  208. dy = current[1] - self._tmpMousePos[1]
  209. self._pdc.TranslateId(self._dragid, dx, dy)
  210. self.UpdateDrawing()
  211. self._tmpMousePos = current
  212. def GetOverlayPos(self):
  213. """Returns x, y position in pixels"""
  214. rect = self._pdc.GetIdBounds(1)
  215. return rect.GetX(), rect.GetY()