mapwindow.py 8.6 KB

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