mapwindow.py 8.6 KB

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