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