From eb94d22f2d15ed7580e54e7a7b63760b448eff69 Mon Sep 17 00:00:00 2001 From: Sylvain Corlay Date: Sat, 14 Jul 2018 15:55:41 -0500 Subject: [PATCH 01/12] Add text-html repr --- ipympl/backend_nbagg.py | 58 +++++++++++++++++++++++++++++++++-------- 1 file changed, 47 insertions(+), 11 deletions(-) diff --git a/ipympl/backend_nbagg.py b/ipympl/backend_nbagg.py index a9fa0777..47151167 100644 --- a/ipympl/backend_nbagg.py +++ b/ipympl/backend_nbagg.py @@ -4,7 +4,8 @@ import json import io -from IPython.display import display, HTML +from IPython.display import update_display, display, HTML +from IPython import version_info as ipython_version_info from ipywidgets import DOMWidget, widget_serialization from traitlets import ( @@ -83,16 +84,8 @@ def __init__(self, canvas, *args, **kwargs): def export(self): buf = io.BytesIO() self.canvas.figure.savefig(buf, format='png', dpi='figure') - # Figure width in pixels - pwidth = (self.canvas.figure.get_figwidth() * - self.canvas.figure.get_dpi()) - # Scale size to match widget on HiDPI monitors. - if hasattr(self.canvas, 'device_pixel_ratio'): # Matplotlib 3.5+ - width = pwidth / self.canvas.device_pixel_ratio - else: - width = pwidth / self.canvas._dpi_ratio - data = "" - data = data.format(b64encode(buf.getvalue()).decode('utf-8'), width) + data = "" + data = data.format(b64encode(buf.getvalue()).decode('utf-8')) display(HTML(data)) @default('toolitems') @@ -204,10 +197,53 @@ def send_json(self, content): def send_binary(self, data): self.send({'data': '{"type": "binary"}'}, buffers=[data]) + update_display(self, display_id='matplotlib_{0}'.format(self.figure.number)) def new_timer(self, *args, **kwargs): return TimerTornado(*args, **kwargs) + def _repr_mimebundle_(self, **kwargs): + if self._view_name is not None: + # now happens before the actual display call. + self._handle_displayed(**kwargs) + plaintext = repr(self) + if len(plaintext) > 110: + plaintext = plaintext[:110] + '…' + # The 'application/vnd.jupyter.widget-view+json' mimetype has not been registered yet. + # See the registration process and naming convention at + # http://tools.ietf.org/html/rfc6838 + # and the currently registered mimetypes at + # http://www.iana.org/assignments/media-types/media-types.xhtml. + + buf = io.BytesIO() + self.figure.savefig(buf, format='png', dpi='figure') + data = "" + data = data.format(b64encode(buf.getvalue()).decode('utf-8')) + + data = { + 'text/plain': plaintext, + 'text/html': data, + 'application/vnd.jupyter.widget-view+json': { + 'version_major': 2, + 'version_minor': 0, + 'model_id': self._model_id + } + } + return data + + def _ipython_display_(self, **kwargs): + """Called when `IPython.display.display` is called on a widget. + + Note: if we are in IPython 6.1 or later, we return NotImplemented so + that _repr_mimebundle_ is used directly. + """ + if ipython_version_info >= (6, 1): + raise NotImplementedError + + data = self._repr_mimebundle_(**kwargs) + if data: + display(data, raw=True, display_id='matplotlib_{0}'.format(self.number)) + if matplotlib.__version__ < '3.4': # backport the Python side changes to match the js changes def _handle_key(self, event): From 8fb40c7ddfd7a7f3745435d75ab2192d64be5735 Mon Sep 17 00:00:00 2001 From: martinRenou Date: Tue, 14 Sep 2021 17:34:14 +0200 Subject: [PATCH 02/12] Update display on first render --- ipympl/backend_nbagg.py | 66 ++++++++++++++++++++++------------------- js/src/mpl_widget.js | 8 ++++- 2 files changed, 42 insertions(+), 32 deletions(-) diff --git a/ipympl/backend_nbagg.py b/ipympl/backend_nbagg.py index 47151167..194991af 100644 --- a/ipympl/backend_nbagg.py +++ b/ipympl/backend_nbagg.py @@ -161,6 +161,8 @@ def __init__(self, figure, *args, **kwargs): self.on_msg(self._handle_message) + self._rendered = False + def _handle_message(self, object, content, buffers): # Every content has a "type". if content['type'] == 'closing': @@ -168,6 +170,11 @@ def _handle_message(self, object, content, buffers): elif content['type'] == 'initialized': _, _, w, h = self.figure.bbox.bounds self.manager.resize(w, h) + elif content['type'] == 'ack': + update_display( + self._repr_mimebundle_(), + raw=True, display_id='matplotlib_{0}'.format(self._model_id) + ) else: self.manager.handle_json(content) @@ -197,39 +204,32 @@ def send_json(self, content): def send_binary(self, data): self.send({'data': '{"type": "binary"}'}, buffers=[data]) - update_display(self, display_id='matplotlib_{0}'.format(self.figure.number)) def new_timer(self, *args, **kwargs): return TimerTornado(*args, **kwargs) def _repr_mimebundle_(self, **kwargs): - if self._view_name is not None: - # now happens before the actual display call. - self._handle_displayed(**kwargs) - plaintext = repr(self) - if len(plaintext) > 110: - plaintext = plaintext[:110] + '…' - # The 'application/vnd.jupyter.widget-view+json' mimetype has not been registered yet. - # See the registration process and naming convention at - # http://tools.ietf.org/html/rfc6838 - # and the currently registered mimetypes at - # http://www.iana.org/assignments/media-types/media-types.xhtml. - - buf = io.BytesIO() - self.figure.savefig(buf, format='png', dpi='figure') - data = "" - data = data.format(b64encode(buf.getvalue()).decode('utf-8')) - - data = { - 'text/plain': plaintext, - 'text/html': data, - 'application/vnd.jupyter.widget-view+json': { - 'version_major': 2, - 'version_minor': 0, - 'model_id': self._model_id - } + # now happens before the actual display call. + self._handle_displayed(**kwargs) + plaintext = repr(self) + if len(plaintext) > 110: + plaintext = plaintext[:110] + '…' + + buf = io.BytesIO() + self.figure.savefig(buf, format='png', dpi='figure') + data_url = b64encode(buf.getvalue()).decode('utf-8') + + data = { + 'text/plain': plaintext, + 'image/png': data_url, + 'application/vnd.jupyter.widget-view+json': { + 'version_major': 2, + 'version_minor': 0, + 'model_id': self._model_id } - return data + } + + return data def _ipython_display_(self, **kwargs): """Called when `IPython.display.display` is called on a widget. @@ -240,9 +240,10 @@ def _ipython_display_(self, **kwargs): if ipython_version_info >= (6, 1): raise NotImplementedError - data = self._repr_mimebundle_(**kwargs) - if data: - display(data, raw=True, display_id='matplotlib_{0}'.format(self.number)) + display( + self._repr_mimebundle_(**kwargs), + raw=True, display_id='matplotlib_{0}'.format(self._model_id) + ) if matplotlib.__version__ < '3.4': # backport the Python side changes to match the js changes @@ -317,7 +318,10 @@ def __init__(self, canvas, num): def show(self): if self.canvas._closed: self.canvas._closed = False - display(self.canvas) + display( + self.canvas, + display_id='matplotlib_{0}'.format(self.canvas._model_id) + ) else: self.canvas.draw_idle() diff --git a/js/src/mpl_widget.js b/js/src/mpl_widget.js index 4e1acca7..9bfe8643 100644 --- a/js/src/mpl_widget.js +++ b/js/src/mpl_widget.js @@ -53,6 +53,8 @@ export class MPLCanvasModel extends widgets.DOMWidgetModel { this.ratio = (window.devicePixelRatio || 1) / backingStore; this._init_image(); + this.acknowledged_rendered = false; + this.on('msg:custom', this.on_comm_message.bind(this)); this.on('change:resizable', () => { this._for_each_view(function (view) { @@ -186,7 +188,11 @@ export class MPLCanvasModel extends widgets.DOMWidgetModel { this.image.src = image_url; // Tell Jupyter that the notebook contents must change. - this.send_message('ack'); + if (!this.acknowledged_rendered) { + this.send_message('ack'); + + this.acknowledged_rendered = true; + } this.waiting = false; } From b5f42aa82215b80c066dc20c90807a49e7d42355 Mon Sep 17 00:00:00 2001 From: martinRenou Date: Tue, 14 Sep 2021 18:08:04 +0200 Subject: [PATCH 03/12] Fix issue for latest ipywidgets --- ipympl/backend_nbagg.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ipympl/backend_nbagg.py b/ipympl/backend_nbagg.py index 194991af..238301d6 100644 --- a/ipympl/backend_nbagg.py +++ b/ipympl/backend_nbagg.py @@ -210,7 +210,8 @@ def new_timer(self, *args, **kwargs): def _repr_mimebundle_(self, **kwargs): # now happens before the actual display call. - self._handle_displayed(**kwargs) + if hasattr(self, '_handle_displayed'): + self._handle_displayed(**kwargs) plaintext = repr(self) if len(plaintext) > 110: plaintext = plaintext[:110] + '…' From a373f5c7b9a6f406a731c329d4e3c69d02f7c6e8 Mon Sep 17 00:00:00 2001 From: martinRenou Date: Mon, 20 Sep 2021 17:03:44 +0200 Subject: [PATCH 04/12] Solution that works without update_display --- ipympl/backend_nbagg.py | 69 +++++++++++++++++++++++++++++------------ js/src/mpl_widget.js | 11 +------ 2 files changed, 50 insertions(+), 30 deletions(-) diff --git a/ipympl/backend_nbagg.py b/ipympl/backend_nbagg.py index 238301d6..0f2e6fe5 100644 --- a/ipympl/backend_nbagg.py +++ b/ipympl/backend_nbagg.py @@ -4,8 +4,9 @@ import json import io -from IPython.display import update_display, display, HTML -from IPython import version_info as ipython_version_info +import numpy as np + +from IPython.display import display, HTML from ipywidgets import DOMWidget, widget_serialization from traitlets import ( @@ -161,7 +162,10 @@ def __init__(self, figure, *args, **kwargs): self.on_msg(self._handle_message) - self._rendered = False + self._display_requested = False + self._displayed_once = False + + self._has_data = False def _handle_message(self, object, content, buffers): # Every content has a "type". @@ -170,11 +174,6 @@ def _handle_message(self, object, content, buffers): elif content['type'] == 'initialized': _, _, w, h = self.figure.bbox.bounds self.manager.resize(w, h) - elif content['type'] == 'ack': - update_display( - self._repr_mimebundle_(), - raw=True, display_id='matplotlib_{0}'.format(self._model_id) - ) else: self.manager.handle_json(content) @@ -203,11 +202,40 @@ def send_json(self, content): self.send({'data': json.dumps(content)}) def send_binary(self, data): + if not self._has_data: + renderer = self.get_renderer() + + buff = (np.frombuffer(renderer.buffer_rgba(), dtype=np.uint32) + .reshape((renderer.height, renderer.width))) + + # If any pixels have transparency, we need to force a full + # draw as we cannot overlay new on top of old. + pixels = buff.view(dtype=np.uint8).reshape(buff.shape + (4,)) + + if np.any(pixels[:, :, :2] != 255): + self._has_data = True + + if (self._has_data and self._display_requested + and not self._displayed_once): + display( + self._repr_mimebundle_(**self._display_requested_kwargs), + raw=True, display_id='matplotlib_{0}'.format(self._model_id) + ) + + self._display_requested = False + self._displayed_once = True + self.send({'data': '{"type": "binary"}'}, buffers=[data]) def new_timer(self, *args, **kwargs): return TimerTornado(*args, **kwargs) + def force_initialize(self): + self._handle_message(self, {'type': 'send_image_mode'}, []) + self._handle_message(self, {'type': 'refresh'}, []) + self._handle_message(self, {'type': 'initialized'}, []) + self._handle_message(self, {'type': 'draw'}, []) + def _repr_mimebundle_(self, **kwargs): # now happens before the actual display call. if hasattr(self, '_handle_displayed'): @@ -233,18 +261,16 @@ def _repr_mimebundle_(self, **kwargs): return data def _ipython_display_(self, **kwargs): - """Called when `IPython.display.display` is called on a widget. - - Note: if we are in IPython 6.1 or later, we return NotImplemented so - that _repr_mimebundle_ is used directly. - """ - if ipython_version_info >= (6, 1): - raise NotImplementedError - - display( - self._repr_mimebundle_(**kwargs), - raw=True, display_id='matplotlib_{0}'.format(self._model_id) - ) + """Called when `IPython.display.display` is called on a widget.""" + # We defer the first display if we don't have any plot data yet + if not self._displayed_once and not self._has_data: + self._display_requested = True + self._display_requested_kwargs = kwargs + else: + display( + self._repr_mimebundle_(**kwargs), + raw=True, display_id='matplotlib_{0}'.format(self._model_id) + ) if matplotlib.__version__ < '3.4': # backport the Python side changes to match the js changes @@ -341,6 +367,9 @@ def new_figure_manager_given_figure(num, figure): if 'nbagg.transparent' in rcParams and rcParams['nbagg.transparent']: figure.patch.set_alpha(0) manager = FigureManager(canvas, num) + + canvas.force_initialize() + if is_interactive(): manager.show() figure.canvas.draw_idle() diff --git a/js/src/mpl_widget.js b/js/src/mpl_widget.js index 9bfe8643..1d0719ba 100644 --- a/js/src/mpl_widget.js +++ b/js/src/mpl_widget.js @@ -53,8 +53,6 @@ export class MPLCanvasModel extends widgets.DOMWidgetModel { this.ratio = (window.devicePixelRatio || 1) / backingStore; this._init_image(); - this.acknowledged_rendered = false; - this.on('msg:custom', this.on_comm_message.bind(this)); this.on('change:resizable', () => { this._for_each_view(function (view) { @@ -82,7 +80,7 @@ export class MPLCanvasModel extends widgets.DOMWidgetModel { this.send_message('send_image_mode'); this.send_message('refresh'); - this.send_message('initialized'); + this.send_message('draw'); } send_draw_message() { @@ -187,13 +185,6 @@ export class MPLCanvasModel extends widgets.DOMWidgetModel { this.image.src = image_url; - // Tell Jupyter that the notebook contents must change. - if (!this.acknowledged_rendered) { - this.send_message('ack'); - - this.acknowledged_rendered = true; - } - this.waiting = false; } From fefe076c553e6b09516d7ae5f20c3c2541931155 Mon Sep 17 00:00:00 2001 From: martinRenou Date: Mon, 20 Sep 2021 17:18:45 +0200 Subject: [PATCH 05/12] Globally save the current dpi --- ipympl/backend_nbagg.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/ipympl/backend_nbagg.py b/ipympl/backend_nbagg.py index 0f2e6fe5..8e0f744f 100644 --- a/ipympl/backend_nbagg.py +++ b/ipympl/backend_nbagg.py @@ -154,7 +154,9 @@ class Canvas(DOMWidget, FigureCanvasWebAggCore): _png_is_old = Bool() _force_full = Bool() _current_image_mode = Unicode() - _dpi_ratio = Float(1.0) + + # Static as it should be the same for all canvases + current_dpi_ratio = 1.0 def __init__(self, figure, *args, **kwargs): DOMWidget.__init__(self, *args, **kwargs) @@ -174,6 +176,9 @@ def _handle_message(self, object, content, buffers): elif content['type'] == 'initialized': _, _, w, h = self.figure.bbox.bounds self.manager.resize(w, h) + elif content['type'] == 'set_dpi_ratio': + Canvas.current_dpi_ratio = content['dpi_ratio'] + self.manager.handle_json(content) else: self.manager.handle_json(content) @@ -231,6 +236,13 @@ def new_timer(self, *args, **kwargs): return TimerTornado(*args, **kwargs) def force_initialize(self): + self._handle_message( + self, + { + 'type': 'set_dpi_ratio', 'dpi_ratio': Canvas.current_dpi_ratio + }, + [] + ) self._handle_message(self, {'type': 'send_image_mode'}, []) self._handle_message(self, {'type': 'refresh'}, []) self._handle_message(self, {'type': 'initialized'}, []) From a589859d6857f1410ec959c0179ce0a39352f4cd Mon Sep 17 00:00:00 2001 From: martinRenou Date: Mon, 20 Sep 2021 17:50:23 +0200 Subject: [PATCH 06/12] Dummy display --- ipympl/backend_nbagg.py | 18 +++++++++++++----- js/src/mpl_widget.js | 2 -- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/ipympl/backend_nbagg.py b/ipympl/backend_nbagg.py index 8e0f744f..3f552ab4 100644 --- a/ipympl/backend_nbagg.py +++ b/ipympl/backend_nbagg.py @@ -6,11 +6,11 @@ import numpy as np -from IPython.display import display, HTML +from IPython.display import update_display, display, HTML from ipywidgets import DOMWidget, widget_serialization from traitlets import ( - Unicode, Bool, CInt, Float, List, Instance, CaselessStrEnum, Enum, + Unicode, Bool, CInt, List, Instance, CaselessStrEnum, Enum, default ) @@ -169,16 +169,21 @@ def __init__(self, figure, *args, **kwargs): self._has_data = False + self._display_id = 'matplotlib_{0}'.format(self._model_id) + def _handle_message(self, object, content, buffers): # Every content has a "type". if content['type'] == 'closing': self._closed = True + elif content['type'] == 'initialized': _, _, w, h = self.figure.bbox.bounds self.manager.resize(w, h) + elif content['type'] == 'set_dpi_ratio': Canvas.current_dpi_ratio = content['dpi_ratio'] self.manager.handle_json(content) + else: self.manager.handle_json(content) @@ -222,9 +227,9 @@ def send_binary(self, data): if (self._has_data and self._display_requested and not self._displayed_once): - display( + update_display( self._repr_mimebundle_(**self._display_requested_kwargs), - raw=True, display_id='matplotlib_{0}'.format(self._model_id) + raw=True, display_id=self._display_id ) self._display_requested = False @@ -278,10 +283,13 @@ def _ipython_display_(self, **kwargs): if not self._displayed_once and not self._has_data: self._display_requested = True self._display_requested_kwargs = kwargs + + # Display a dummy, so we can update it later: + display(None, display_id=self._display_id) else: display( self._repr_mimebundle_(**kwargs), - raw=True, display_id='matplotlib_{0}'.format(self._model_id) + raw=True, display_id=self._display_id ) if matplotlib.__version__ < '3.4': diff --git a/js/src/mpl_widget.js b/js/src/mpl_widget.js index 1d0719ba..429e2c54 100644 --- a/js/src/mpl_widget.js +++ b/js/src/mpl_widget.js @@ -79,8 +79,6 @@ export class MPLCanvasModel extends widgets.DOMWidgetModel { this.send_message('send_image_mode'); this.send_message('refresh'); - - this.send_message('draw'); } send_draw_message() { From af699c223286d91fa42028005c4e7de1552acfde Mon Sep 17 00:00:00 2001 From: martinRenou Date: Tue, 21 Sep 2021 09:58:27 +0200 Subject: [PATCH 07/12] Use post_execute hook for showing figures --- ipympl/backend_nbagg.py | 193 ++++++++++++++++++++++++---------------- 1 file changed, 114 insertions(+), 79 deletions(-) diff --git a/ipympl/backend_nbagg.py b/ipympl/backend_nbagg.py index 3f552ab4..f74fb719 100644 --- a/ipympl/backend_nbagg.py +++ b/ipympl/backend_nbagg.py @@ -4,9 +4,9 @@ import json import io -import numpy as np - -from IPython.display import update_display, display, HTML +from IPython.display import display, HTML +from IPython import get_ipython +from IPython import version_info as ipython_version_info from ipywidgets import DOMWidget, widget_serialization from traitlets import ( @@ -15,8 +15,7 @@ ) import matplotlib -from matplotlib import rcParams -from matplotlib import is_interactive +from matplotlib import rcParams, is_interactive from matplotlib.backends.backend_webagg_core import (FigureManagerWebAgg, FigureCanvasWebAggCore, NavigationToolbar2WebAgg, @@ -42,7 +41,6 @@ def connection_info(): use. """ - from matplotlib._pylab_helpers import Gcf result = [] for manager in Gcf.get_all_fig_managers(): fig = manager.canvas.figure @@ -164,12 +162,7 @@ def __init__(self, figure, *args, **kwargs): self.on_msg(self._handle_message) - self._display_requested = False - self._displayed_once = False - - self._has_data = False - - self._display_id = 'matplotlib_{0}'.format(self._model_id) + self.display_id = 'matplotlib_{0}'.format(self._model_id) def _handle_message(self, object, content, buffers): # Every content has a "type". @@ -212,46 +205,23 @@ def send_json(self, content): self.send({'data': json.dumps(content)}) def send_binary(self, data): - if not self._has_data: - renderer = self.get_renderer() - - buff = (np.frombuffer(renderer.buffer_rgba(), dtype=np.uint32) - .reshape((renderer.height, renderer.width))) - - # If any pixels have transparency, we need to force a full - # draw as we cannot overlay new on top of old. - pixels = buff.view(dtype=np.uint8).reshape(buff.shape + (4,)) - - if np.any(pixels[:, :, :2] != 255): - self._has_data = True - - if (self._has_data and self._display_requested - and not self._displayed_once): - update_display( - self._repr_mimebundle_(**self._display_requested_kwargs), - raw=True, display_id=self._display_id - ) - - self._display_requested = False - self._displayed_once = True - self.send({'data': '{"type": "binary"}'}, buffers=[data]) def new_timer(self, *args, **kwargs): return TimerTornado(*args, **kwargs) - def force_initialize(self): - self._handle_message( - self, - { - 'type': 'set_dpi_ratio', 'dpi_ratio': Canvas.current_dpi_ratio - }, - [] - ) - self._handle_message(self, {'type': 'send_image_mode'}, []) - self._handle_message(self, {'type': 'refresh'}, []) - self._handle_message(self, {'type': 'initialized'}, []) - self._handle_message(self, {'type': 'draw'}, []) + # def force_initialize(self): + # self._handle_message( + # self, + # { + # 'type': 'set_dpi_ratio', 'dpi_ratio': Canvas.current_dpi_ratio + # }, + # [] + # ) + # self._handle_message(self, {'type': 'send_image_mode'}, []) + # self._handle_message(self, {'type': 'refresh'}, []) + # self._handle_message(self, {'type': 'initialized'}, []) + # self._handle_message(self, {'type': 'draw'}, []) def _repr_mimebundle_(self, **kwargs): # now happens before the actual display call. @@ -278,19 +248,15 @@ def _repr_mimebundle_(self, **kwargs): return data def _ipython_display_(self, **kwargs): - """Called when `IPython.display.display` is called on a widget.""" - # We defer the first display if we don't have any plot data yet - if not self._displayed_once and not self._has_data: - self._display_requested = True - self._display_requested_kwargs = kwargs - - # Display a dummy, so we can update it later: - display(None, display_id=self._display_id) - else: - display( - self._repr_mimebundle_(**kwargs), - raw=True, display_id=self._display_id - ) + """Called when `IPython.display.display` is called on a widget. + Note: if we are in IPython 6.1 or later, we return NotImplemented so + that _repr_mimebundle_ is used directly. + """ + if ipython_version_info >= (6, 1): + raise NotImplementedError + + data = self._repr_mimebundle_(**kwargs) + display(data, raw=True, display_id=self.display_id) if matplotlib.__version__ < '3.4': # backport the Python side changes to match the js changes @@ -367,7 +333,7 @@ def show(self): self.canvas._closed = False display( self.canvas, - display_id='matplotlib_{0}'.format(self.canvas._model_id) + display_id=self.canvas.display_id ) else: self.canvas.draw_idle() @@ -381,6 +347,9 @@ class _Backend_ipympl(_Backend): FigureCanvas = Canvas FigureManager = FigureManager + _to_show = [] + _draw_called = False + @staticmethod def new_figure_manager_given_figure(num, figure): canvas = Canvas(figure) @@ -388,10 +357,11 @@ def new_figure_manager_given_figure(num, figure): figure.patch.set_alpha(0) manager = FigureManager(canvas, num) - canvas.force_initialize() + # TODO For early animations????? + # canvas.force_initialize() if is_interactive(): - manager.show() + _Backend_ipympl._to_show.append(figure) figure.canvas.draw_idle() def destroy(event): @@ -402,24 +372,89 @@ def destroy(event): return manager @staticmethod - def show(block=None): - # TODO: something to do when keyword block==False ? + def show(close=None, block=None): + # # TODO: something to do when keyword block==False ? + interactive = is_interactive() - managers = Gcf.get_all_fig_managers() - if not managers: - return + try: + for manager in Gcf.get_all_fig_managers(): + display( + manager.canvas, + display_id=manager.canvas.display_id + # metadata=_fetch_figure_metadata(manager.canvas.figure) + ) + + # plt.figure adds an event which makes the figure in focus the + # active one. Disable this behaviour, as it results in + # figures being put as the active figure after they have been + # shown, even in non-interactive mode. + if hasattr(manager, '_cidgcf'): + manager.canvas.mpl_disconnect(manager._cidgcf) + + if not interactive: + Gcf.figs.pop(manager.num, None) + finally: + _Backend_ipympl._to_show = [] + # only call close('all') if any to close + # close triggers gc.collect, which can be slow + if close and Gcf.get_all_fig_managers(): + matplotlib.pyplot.close('all') - interactive = is_interactive() + @staticmethod + def draw_if_interactive(): + # If matplotlib was manually set to non-interactive mode, this function + # should be a no-op (otherwise we'll generate duplicate plots, since a + # user who set ioff() manually expects to make separate draw/show + # calls). + if not is_interactive(): + return - for manager in managers: - manager.show() + manager = Gcf.get_active() + if manager is None: + return + fig = manager.canvas.figure - # plt.figure adds an event which makes the figure in focus the - # active one. Disable this behaviour, as it results in - # figures being put as the active figure after they have been - # shown, even in non-interactive mode. - if hasattr(manager, '_cidgcf'): - manager.canvas.mpl_disconnect(manager._cidgcf) + # ensure current figure will be drawn, and each subsequent call + # of draw_if_interactive() moves the active figure to ensure it is + # drawn last + try: + _Backend_ipympl._to_show.remove(fig) + except ValueError: + # ensure it only appears in the draw list once + pass + # Queue up the figure for drawing in next show() call + _Backend_ipympl._to_show.append(fig) + _Backend_ipympl._draw_called = True + + +def flush_figures(): + if rcParams['backend'] == 'module://ipympl.backend_nbagg': + if not _Backend_ipympl._draw_called: + return - if not interactive: - Gcf.figs.pop(manager.num, None) + try: + # exclude any figures that were closed: + active = set([ + fm.canvas.figure for fm in Gcf.get_all_fig_managers() + ]) + for fig in [ + fig for fig in _Backend_ipympl._to_show if fig in active]: + try: + # display(fig.canvas, metadata=_fetch_figure_metadata(fig)) + display(fig.canvas, display_id=fig.canvas.display_id) + except Exception as e: + # safely show traceback if in IPython, else raise + ip = get_ipython() + if ip is None: + raise e + else: + ip.showtraceback() + return + finally: + # clear flags for next round + _Backend_ipympl._to_show = [] + _Backend_ipympl._draw_called = False + + +ip = get_ipython() +ip.events.register('post_execute', flush_figures) From bce06fab3f7e5fa30efbd8a356807cbfb55eceba Mon Sep 17 00:00:00 2001 From: martinRenou Date: Tue, 21 Sep 2021 10:14:42 +0200 Subject: [PATCH 08/12] Iterate --- ipympl/backend_nbagg.py | 51 +++++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 27 deletions(-) diff --git a/ipympl/backend_nbagg.py b/ipympl/backend_nbagg.py index f74fb719..00cdd948 100644 --- a/ipympl/backend_nbagg.py +++ b/ipympl/backend_nbagg.py @@ -377,22 +377,25 @@ def show(close=None, block=None): interactive = is_interactive() try: - for manager in Gcf.get_all_fig_managers(): - display( - manager.canvas, - display_id=manager.canvas.display_id - # metadata=_fetch_figure_metadata(manager.canvas.figure) - ) - - # plt.figure adds an event which makes the figure in focus the - # active one. Disable this behaviour, as it results in - # figures being put as the active figure after they have been - # shown, even in non-interactive mode. - if hasattr(manager, '_cidgcf'): - manager.canvas.mpl_disconnect(manager._cidgcf) - - if not interactive: - Gcf.figs.pop(manager.num, None) + manager = Gcf.get_active() + if manager is None: + return + + display( + manager.canvas, + display_id=manager.canvas.display_id + # metadata=_fetch_figure_metadata(manager.canvas.figure) + ) + + # plt.figure adds an event which makes the figure in focus the + # active one. Disable this behaviour, as it results in + # figures being put as the active figure after they have been + # shown, even in non-interactive mode. + if hasattr(manager, '_cidgcf'): + manager.canvas.mpl_disconnect(manager._cidgcf) + + if not interactive: + Gcf.figs.pop(manager.num, None) finally: _Backend_ipympl._to_show = [] # only call close('all') if any to close @@ -437,19 +440,13 @@ def flush_figures(): active = set([ fm.canvas.figure for fm in Gcf.get_all_fig_managers() ]) + + print('flush active ', active, ', toshow ', _Backend_ipympl._to_show) + for fig in [ fig for fig in _Backend_ipympl._to_show if fig in active]: - try: - # display(fig.canvas, metadata=_fetch_figure_metadata(fig)) - display(fig.canvas, display_id=fig.canvas.display_id) - except Exception as e: - # safely show traceback if in IPython, else raise - ip = get_ipython() - if ip is None: - raise e - else: - ip.showtraceback() - return + # display(fig.canvas, metadata=_fetch_figure_metadata(fig)) + display(fig.canvas, display_id=fig.canvas.display_id) finally: # clear flags for next round _Backend_ipympl._to_show = [] From 113a15dbe8618cac8a21446d6d818044112c1ec2 Mon Sep 17 00:00:00 2001 From: martinRenou Date: Tue, 21 Sep 2021 10:44:38 +0200 Subject: [PATCH 09/12] Clean --- ipympl/backend_nbagg.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/ipympl/backend_nbagg.py b/ipympl/backend_nbagg.py index 00cdd948..7f75955b 100644 --- a/ipympl/backend_nbagg.py +++ b/ipympl/backend_nbagg.py @@ -441,8 +441,6 @@ def flush_figures(): fm.canvas.figure for fm in Gcf.get_all_fig_managers() ]) - print('flush active ', active, ', toshow ', _Backend_ipympl._to_show) - for fig in [ fig for fig in _Backend_ipympl._to_show if fig in active]: # display(fig.canvas, metadata=_fetch_figure_metadata(fig)) From 783419bca96b8321c5ac1460dca60d761cf5dd18 Mon Sep 17 00:00:00 2001 From: martinRenou Date: Tue, 21 Sep 2021 11:30:11 +0200 Subject: [PATCH 10/12] Cleaning --- ipympl/backend_nbagg.py | 49 +++++++++-------------------------------- 1 file changed, 11 insertions(+), 38 deletions(-) diff --git a/ipympl/backend_nbagg.py b/ipympl/backend_nbagg.py index 7f75955b..1c955cb2 100644 --- a/ipympl/backend_nbagg.py +++ b/ipympl/backend_nbagg.py @@ -162,8 +162,6 @@ def __init__(self, figure, *args, **kwargs): self.on_msg(self._handle_message) - self.display_id = 'matplotlib_{0}'.format(self._model_id) - def _handle_message(self, object, content, buffers): # Every content has a "type". if content['type'] == 'closing': @@ -210,19 +208,6 @@ def send_binary(self, data): def new_timer(self, *args, **kwargs): return TimerTornado(*args, **kwargs) - # def force_initialize(self): - # self._handle_message( - # self, - # { - # 'type': 'set_dpi_ratio', 'dpi_ratio': Canvas.current_dpi_ratio - # }, - # [] - # ) - # self._handle_message(self, {'type': 'send_image_mode'}, []) - # self._handle_message(self, {'type': 'refresh'}, []) - # self._handle_message(self, {'type': 'initialized'}, []) - # self._handle_message(self, {'type': 'draw'}, []) - def _repr_mimebundle_(self, **kwargs): # now happens before the actual display call. if hasattr(self, '_handle_displayed'): @@ -256,7 +241,7 @@ def _ipython_display_(self, **kwargs): raise NotImplementedError data = self._repr_mimebundle_(**kwargs) - display(data, raw=True, display_id=self.display_id) + display(data, raw=True) if matplotlib.__version__ < '3.4': # backport the Python side changes to match the js changes @@ -331,10 +316,7 @@ def __init__(self, canvas, num): def show(self): if self.canvas._closed: self.canvas._closed = False - display( - self.canvas, - display_id=self.canvas.display_id - ) + display(self.canvas) else: self.canvas.draw_idle() @@ -357,9 +339,6 @@ def new_figure_manager_given_figure(num, figure): figure.patch.set_alpha(0) manager = FigureManager(canvas, num) - # TODO For early animations????? - # canvas.force_initialize() - if is_interactive(): _Backend_ipympl._to_show.append(figure) figure.canvas.draw_idle() @@ -376,16 +355,13 @@ def show(close=None, block=None): # # TODO: something to do when keyword block==False ? interactive = is_interactive() - try: - manager = Gcf.get_active() - if manager is None: - return + manager = Gcf.get_active() + if manager is None: + return - display( - manager.canvas, - display_id=manager.canvas.display_id - # metadata=_fetch_figure_metadata(manager.canvas.figure) - ) + try: + display(manager.canvas) + # metadata=_fetch_figure_metadata(manager.canvas.figure) # plt.figure adds an event which makes the figure in focus the # active one. Disable this behaviour, as it results in @@ -397,11 +373,8 @@ def show(close=None, block=None): if not interactive: Gcf.figs.pop(manager.num, None) finally: - _Backend_ipympl._to_show = [] - # only call close('all') if any to close - # close triggers gc.collect, which can be slow - if close and Gcf.get_all_fig_managers(): - matplotlib.pyplot.close('all') + if manager.canvas.figure in _Backend_ipympl._to_show: + _Backend_ipympl._to_show.remove(manager.canvas.figure) @staticmethod def draw_if_interactive(): @@ -444,7 +417,7 @@ def flush_figures(): for fig in [ fig for fig in _Backend_ipympl._to_show if fig in active]: # display(fig.canvas, metadata=_fetch_figure_metadata(fig)) - display(fig.canvas, display_id=fig.canvas.display_id) + display(fig.canvas) finally: # clear flags for next round _Backend_ipympl._to_show = [] From bc39d8f4af13e1e155ab81bb02b4b53f67303b73 Mon Sep 17 00:00:00 2001 From: martinRenou Date: Tue, 21 Sep 2021 11:33:21 +0200 Subject: [PATCH 11/12] Update "docs" --- examples/ipympl.ipynb | 43 +++---------------------------------------- 1 file changed, 3 insertions(+), 40 deletions(-) diff --git a/examples/ipympl.ipynb b/examples/ipympl.ipynb index 9d80dcc8..35e8c84b 100644 --- a/examples/ipympl.ipynb +++ b/examples/ipympl.ipynb @@ -201,7 +201,7 @@ "source": [ "# Interactions with other widgets and layouting\n", "\n", - "When you want to embed the figure into a layout of other widgets you should call `plt.ioff()` before creating the figure otherwise code inside of `plt.figure()` will display the canvas automatically and outside of your layout. " + "When you want to embed the figure into a layout of other widgets you should call `plt.ioff()` before creating the figure otherwise `plt.figure()` will trigger a display of the canvas automatically and outside of your layout. " ] }, { @@ -225,7 +225,6 @@ "# this is default but if this notebook is executed out of order it may have been turned off\n", "plt.ion()\n", "\n", - "\n", "fig = plt.figure()\n", "ax = fig.gca()\n", "ax.imshow(Z)\n", @@ -268,35 +267,6 @@ ")" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Fixing the double display with `ipywidgets.Output`\n", - "\n", - "Using `plt.ioff` use matplotlib to avoid the double display of the plot. You can also use `ipywidgets.Output` to capture the plot display to prevent this" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "out = widgets.Output()\n", - "with out:\n", - " fig = plt.figure()\n", - "\n", - "ax = fig.gca()\n", - "ax.imshow(Z)\n", - "\n", - "widgets.AppLayout(\n", - " center=out,\n", - " footer=widgets.Button(icon='check'),\n", - " pane_heights=[0, 6, 1]\n", - ")" - ] - }, { "cell_type": "markdown", "metadata": {}, @@ -446,18 +416,11 @@ "display(widgets.VBox([slider, fig.canvas]))\n", "display(out)" ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] } ], "metadata": { "kernelspec": { - "display_name": "Python 3", + "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, @@ -471,7 +434,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.7.8" + "version": "3.9.7" }, "widgets": { "application/vnd.jupyter.widget-state+json": { From bbfe34dc27a8d98c9f4b990c3c47b8767ef144fa Mon Sep 17 00:00:00 2001 From: martinRenou Date: Tue, 21 Sep 2021 11:34:47 +0200 Subject: [PATCH 12/12] Review --- js/src/mpl_widget.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/js/src/mpl_widget.js b/js/src/mpl_widget.js index 429e2c54..d58f5427 100644 --- a/js/src/mpl_widget.js +++ b/js/src/mpl_widget.js @@ -79,6 +79,8 @@ export class MPLCanvasModel extends widgets.DOMWidgetModel { this.send_message('send_image_mode'); this.send_message('refresh'); + + this.send_message('initialized'); } send_draw_message() {