backend_nbagg.py 8.4 KB

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