backend_nbagg.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. """Interactive figures in the IPython notebook."""
  2. # Note: There is a notebook in
  3. # lib/matplotlib/backends/web_backend/nbagg_uat.ipynb to help verify
  4. # that changes made maintain expected behaviour.
  5. from base64 import b64encode
  6. import io
  7. import json
  8. import pathlib
  9. import uuid
  10. from ipykernel.comm import Comm
  11. from IPython.display import display, Javascript, HTML
  12. from matplotlib import is_interactive
  13. from matplotlib._pylab_helpers import Gcf
  14. from matplotlib.backend_bases import _Backend, CloseEvent, NavigationToolbar2
  15. from .backend_webagg_core import (
  16. FigureCanvasWebAggCore, FigureManagerWebAgg, NavigationToolbar2WebAgg)
  17. from .backend_webagg_core import ( # noqa: F401 # pylint: disable=W0611
  18. TimerTornado, TimerAsyncio)
  19. def connection_info():
  20. """
  21. Return a string showing the figure and connection status for the backend.
  22. This is intended as a diagnostic tool, and not for general use.
  23. """
  24. result = [
  25. '{fig} - {socket}'.format(
  26. fig=(manager.canvas.figure.get_label()
  27. or f"Figure {manager.num}"),
  28. socket=manager.web_sockets)
  29. for manager in Gcf.get_all_fig_managers()
  30. ]
  31. if not is_interactive():
  32. result.append(f'Figures pending show: {len(Gcf.figs)}')
  33. return '\n'.join(result)
  34. _FONT_AWESOME_CLASSES = { # font-awesome 4 names
  35. 'home': 'fa fa-home',
  36. 'back': 'fa fa-arrow-left',
  37. 'forward': 'fa fa-arrow-right',
  38. 'zoom_to_rect': 'fa fa-square-o',
  39. 'move': 'fa fa-arrows',
  40. 'download': 'fa fa-floppy-o',
  41. None: None
  42. }
  43. class NavigationIPy(NavigationToolbar2WebAgg):
  44. # Use the standard toolbar items + download button
  45. toolitems = [(text, tooltip_text,
  46. _FONT_AWESOME_CLASSES[image_file], name_of_method)
  47. for text, tooltip_text, image_file, name_of_method
  48. in (NavigationToolbar2.toolitems +
  49. (('Download', 'Download plot', 'download', 'download'),))
  50. if image_file in _FONT_AWESOME_CLASSES]
  51. class FigureManagerNbAgg(FigureManagerWebAgg):
  52. _toolbar2_class = ToolbarCls = NavigationIPy
  53. def __init__(self, canvas, num):
  54. self._shown = False
  55. super().__init__(canvas, num)
  56. @classmethod
  57. def create_with_canvas(cls, canvas_class, figure, num):
  58. canvas = canvas_class(figure)
  59. manager = cls(canvas, num)
  60. if is_interactive():
  61. manager.show()
  62. canvas.draw_idle()
  63. def destroy(event):
  64. canvas.mpl_disconnect(cid)
  65. Gcf.destroy(manager)
  66. cid = canvas.mpl_connect('close_event', destroy)
  67. return manager
  68. def display_js(self):
  69. # XXX How to do this just once? It has to deal with multiple
  70. # browser instances using the same kernel (require.js - but the
  71. # file isn't static?).
  72. display(Javascript(FigureManagerNbAgg.get_javascript()))
  73. def show(self):
  74. if not self._shown:
  75. self.display_js()
  76. self._create_comm()
  77. else:
  78. self.canvas.draw_idle()
  79. self._shown = True
  80. # plt.figure adds an event which makes the figure in focus the active
  81. # one. Disable this behaviour, as it results in figures being put as
  82. # the active figure after they have been shown, even in non-interactive
  83. # mode.
  84. if hasattr(self, '_cidgcf'):
  85. self.canvas.mpl_disconnect(self._cidgcf)
  86. if not is_interactive():
  87. from matplotlib._pylab_helpers import Gcf
  88. Gcf.figs.pop(self.num, None)
  89. def reshow(self):
  90. """
  91. A special method to re-show the figure in the notebook.
  92. """
  93. self._shown = False
  94. self.show()
  95. @property
  96. def connected(self):
  97. return bool(self.web_sockets)
  98. @classmethod
  99. def get_javascript(cls, stream=None):
  100. if stream is None:
  101. output = io.StringIO()
  102. else:
  103. output = stream
  104. super().get_javascript(stream=output)
  105. output.write((pathlib.Path(__file__).parent
  106. / "web_backend/js/nbagg_mpl.js")
  107. .read_text(encoding="utf-8"))
  108. if stream is None:
  109. return output.getvalue()
  110. def _create_comm(self):
  111. comm = CommSocket(self)
  112. self.add_web_socket(comm)
  113. return comm
  114. def destroy(self):
  115. self._send_event('close')
  116. # need to copy comms as callbacks will modify this list
  117. for comm in list(self.web_sockets):
  118. comm.on_close()
  119. self.clearup_closed()
  120. def clearup_closed(self):
  121. """Clear up any closed Comms."""
  122. self.web_sockets = {socket for socket in self.web_sockets
  123. if socket.is_open()}
  124. if len(self.web_sockets) == 0:
  125. CloseEvent("close_event", self.canvas)._process()
  126. def remove_comm(self, comm_id):
  127. self.web_sockets = {socket for socket in self.web_sockets
  128. if socket.comm.comm_id != comm_id}
  129. class FigureCanvasNbAgg(FigureCanvasWebAggCore):
  130. manager_class = FigureManagerNbAgg
  131. class CommSocket:
  132. """
  133. Manages the Comm connection between IPython and the browser (client).
  134. Comms are 2 way, with the CommSocket being able to publish a message
  135. via the send_json method, and handle a message with on_message. On the
  136. JS side figure.send_message and figure.ws.onmessage do the sending and
  137. receiving respectively.
  138. """
  139. def __init__(self, manager):
  140. self.supports_binary = None
  141. self.manager = manager
  142. self.uuid = str(uuid.uuid4())
  143. # Publish an output area with a unique ID. The javascript can then
  144. # hook into this area.
  145. display(HTML("<div id=%r></div>" % self.uuid))
  146. try:
  147. self.comm = Comm('matplotlib', data={'id': self.uuid})
  148. except AttributeError as err:
  149. raise RuntimeError('Unable to create an IPython notebook Comm '
  150. 'instance. Are you in the IPython '
  151. 'notebook?') from err
  152. self.comm.on_msg(self.on_message)
  153. manager = self.manager
  154. self._ext_close = False
  155. def _on_close(close_message):
  156. self._ext_close = True
  157. manager.remove_comm(close_message['content']['comm_id'])
  158. manager.clearup_closed()
  159. self.comm.on_close(_on_close)
  160. def is_open(self):
  161. return not (self._ext_close or self.comm._closed)
  162. def on_close(self):
  163. # When the socket is closed, deregister the websocket with
  164. # the FigureManager.
  165. if self.is_open():
  166. try:
  167. self.comm.close()
  168. except KeyError:
  169. # apparently already cleaned it up?
  170. pass
  171. def send_json(self, content):
  172. self.comm.send({'data': json.dumps(content)})
  173. def send_binary(self, blob):
  174. if self.supports_binary:
  175. self.comm.send({'blob': 'image/png'}, buffers=[blob])
  176. else:
  177. # The comm is ASCII, so we send the image in base64 encoded data
  178. # URL form.
  179. data = b64encode(blob).decode('ascii')
  180. data_uri = f"data:image/png;base64,{data}"
  181. self.comm.send({'data': data_uri})
  182. def on_message(self, message):
  183. # The 'supports_binary' message is relevant to the
  184. # websocket itself. The other messages get passed along
  185. # to matplotlib as-is.
  186. # Every message has a "type" and a "figure_id".
  187. message = json.loads(message['content']['data'])
  188. if message['type'] == 'closing':
  189. self.on_close()
  190. self.manager.clearup_closed()
  191. elif message['type'] == 'supports_binary':
  192. self.supports_binary = message['value']
  193. else:
  194. self.manager.handle_json(message)
  195. @_Backend.export
  196. class _BackendNbAgg(_Backend):
  197. FigureCanvas = FigureCanvasNbAgg
  198. FigureManager = FigureManagerNbAgg