mapwindow.py 8.4 KB

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