backend_nbagg.py 8.7 KB

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