umbruch-matplotlib 0.2.0__tar.gz → 0.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: umbruch-matplotlib
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: Matplotlib backend that renders PDF, text and math through umbruch
5
5
  License-Expression: MIT
6
6
  Project-URL: Homepage, https://github.com/manuel-rhdt/umbruch-matplotlib
@@ -53,12 +53,13 @@ pixels in total (the raster backend's limit) is an error.
53
53
 
54
54
  ### In Jupyter
55
55
 
56
- There is no interactive canvas, so `plt.show()` cannot open a window: it hands the open figures to
57
- IPython, which prints them through this backend's own `print_png`, so a notebook shows the engine's
58
- raster of the figure rather than an Agg preview. Run `%matplotlib inline` once: IPython then
59
- registers its figure formatter, a figure as the last expression of a cell is displayed, and a cell
60
- that only draws (`plt.plot(...)`) flushes the figure at its end. Without any `%matplotlib` there is
61
- nothing that displays figures at all — that is IPython's rule, not the backend's.
56
+ There is no interactive canvas, so a figure is shown by rendering it: `plt.show()` hands the open
57
+ figures to the notebook's own `show()`, which prints them through this backend's `print_png` (and
58
+ closes them as the notebook is configured to), so a figure is never shown twice. A plotting command
59
+ on its own is enough — the canvas' `draw_idle` tells the notebook that something changed, which is
60
+ what makes it flush the figure at the end of the cell, as with any other backend. Run
61
+ `%matplotlib inline` once to get that: it is what registers the figure formatter. Without any
62
+ `%matplotlib` nothing displays figures at all — IPython's rule, not the backend's.
62
63
 
63
64
  To keep exploring with a fast backend and render only the final file with umbruch, leave the
64
65
  notebook's backend alone and save with `fig.savefig("fig.pdf", backend="module://umbruch_matplotlib")`;
@@ -28,12 +28,13 @@ pixels in total (the raster backend's limit) is an error.
28
28
 
29
29
  ### In Jupyter
30
30
 
31
- There is no interactive canvas, so `plt.show()` cannot open a window: it hands the open figures to
32
- IPython, which prints them through this backend's own `print_png`, so a notebook shows the engine's
33
- raster of the figure rather than an Agg preview. Run `%matplotlib inline` once: IPython then
34
- registers its figure formatter, a figure as the last expression of a cell is displayed, and a cell
35
- that only draws (`plt.plot(...)`) flushes the figure at its end. Without any `%matplotlib` there is
36
- nothing that displays figures at all — that is IPython's rule, not the backend's.
31
+ There is no interactive canvas, so a figure is shown by rendering it: `plt.show()` hands the open
32
+ figures to the notebook's own `show()`, which prints them through this backend's `print_png` (and
33
+ closes them as the notebook is configured to), so a figure is never shown twice. A plotting command
34
+ on its own is enough — the canvas' `draw_idle` tells the notebook that something changed, which is
35
+ what makes it flush the figure at the end of the cell, as with any other backend. Run
36
+ `%matplotlib inline` once to get that: it is what registers the figure formatter. Without any
37
+ `%matplotlib` nothing displays figures at all — IPython's rule, not the backend's.
37
38
 
38
39
  To keep exploring with a fast backend and render only the final file with umbruch, leave the
39
40
  notebook's backend alone and save with `fig.savefig("fig.pdf", backend="module://umbruch_matplotlib")`;
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "umbruch-matplotlib"
7
- version = "0.2.0"
7
+ version = "0.2.1"
8
8
  description = "Matplotlib backend that renders PDF, text and math through umbruch"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -1,6 +1,7 @@
1
1
  """Tests; those that need the real umbruch binary ($UMBRUCH, the package or PATH) are
2
2
  skipped without it. Run with ``pytest tests``."""
3
3
  import io
4
+ import logging
4
5
  import os
5
6
  import re
6
7
  import shutil
@@ -756,28 +757,61 @@ def test_rich_text_is_set_in_the_bold_and_italic_faces(real_bridge, tmp_path):
756
757
  assert "DejaVuSans-Oblique" in fonts, fonts
757
758
 
758
759
 
759
- def test_show_hands_the_figures_to_ipython(monkeypatch):
760
- """`plt.show()` cannot open a window here, so in a notebook it must hand the figure to
761
- IPython, whose own figure printer renders it through this canvas' print_png."""
760
+ def _fake_ipython(with_shell=True):
761
+ """A minimal IPython module: matplotlib asks `get_ipython()` and registers its display hooks
762
+ on the shell, so the fake one has to look like a shell."""
763
+ import types
764
+ module = types.ModuleType("IPython")
765
+ module.version_info = (8, 30, 0) # (matplotlib reads it while installing its hook)
766
+ events = types.SimpleNamespace(register=lambda *a, **k: None, unregister=lambda *a, **k: None)
767
+ shell = types.SimpleNamespace(events=events)
768
+ module.get_ipython = (lambda: shell) if with_shell else (lambda: None)
769
+ return module
770
+
771
+
772
+ def test_show_uses_the_notebooks_own_show(monkeypatch):
773
+ plt.close("all") # (a figure left open by another test would be shown too)
774
+ """In a notebook `plt.show()` must go through the inline backend's `show()`, which displays
775
+ every open figure (through this canvas' print_png) and closes them as configured — otherwise
776
+ the end-of-cell flush would show the same figure twice."""
777
+ import types
778
+ calls = []
779
+ fake_display = types.ModuleType("IPython.display")
780
+ fake_display.display = lambda figure, **kwargs: calls.append(("display", figure))
781
+ fake_ipython = _fake_ipython()
782
+ fake_inline = types.ModuleType("matplotlib_inline.backend_inline")
783
+ fake_inline.show = lambda **kwargs: calls.append(("inline.show", kwargs))
784
+ monkeypatch.setitem(sys.modules, "IPython", fake_ipython)
785
+ monkeypatch.setitem(sys.modules, "IPython.display", fake_display)
786
+ monkeypatch.setitem(sys.modules, "matplotlib_inline", types.ModuleType("matplotlib_inline"))
787
+ monkeypatch.setitem(sys.modules, "matplotlib_inline.backend_inline", fake_inline)
788
+ fig, ax = plt.subplots()
789
+ ax.plot([0, 1])
790
+ plt.show()
791
+ assert calls == [("inline.show", {"block": None})], calls
792
+
793
+
794
+ def test_show_displays_the_figures_without_the_inline_backend(monkeypatch):
795
+ plt.close("all") # (a figure left open by another test would be shown too)
762
796
  import types
763
797
  shown = []
764
798
  fake_display = types.ModuleType("IPython.display")
765
799
  fake_display.display = lambda figure, **kwargs: shown.append(figure)
766
- fake_ipython = types.ModuleType("IPython")
767
- fake_ipython.get_ipython = lambda: None # (matplotlib asks for the shell)
768
- monkeypatch.setitem(sys.modules, "IPython", fake_ipython)
800
+ monkeypatch.setitem(sys.modules, "IPython", _fake_ipython())
769
801
  monkeypatch.setitem(sys.modules, "IPython.display", fake_display)
802
+ monkeypatch.setitem(sys.modules, "matplotlib_inline", None) # (not importable)
803
+ monkeypatch.setitem(sys.modules, "matplotlib_inline.backend_inline", None)
770
804
  fig, ax = plt.subplots()
771
805
  ax.plot([0, 1])
772
806
  plt.show()
773
- assert [f for f in shown] == [fig], shown
807
+ assert shown == [fig], shown
774
808
 
775
809
 
776
810
  def test_show_without_ipython_is_left_to_matplotlib(monkeypatch):
811
+ plt.close("all") # (a figure left open by another test would be shown too)
777
812
  """Outside IPython there is nothing to display into, so the call goes to the non-interactive
778
813
  backend — which warns where a window could have existed and is silent when headless."""
779
814
  monkeypatch.setitem(sys.modules, "IPython", None) # (not importable)
780
- monkeypatch.setitem(sys.modules, "IPython.display", None)
781
815
  calls = []
782
816
  monkeypatch.setattr(hb.FigureManagerBase, "pyplot_show",
783
817
  classmethod(lambda cls, **kwargs: calls.append(kwargs)))
@@ -785,3 +819,25 @@ def test_show_without_ipython_is_left_to_matplotlib(monkeypatch):
785
819
  ax.plot([0, 1])
786
820
  plt.show()
787
821
  assert calls == [{"block": None}], calls
822
+
823
+
824
+ def test_draw_idle_tells_the_inline_backend_that_the_figure_changed(monkeypatch):
825
+ plt.close("all") # (a figure left open by another test would be shown too)
826
+ """A plotting command is enough in a notebook only because pyplot's own
827
+ draw_if_interactive calls draw_idle, which sets the inline backend's flag."""
828
+ import types
829
+ fake_inline = types.ModuleType("matplotlib_inline.backend_inline")
830
+ fake_inline.show = types.SimpleNamespace(_draw_called=False)
831
+ monkeypatch.setitem(sys.modules, "matplotlib_inline", types.ModuleType("matplotlib_inline"))
832
+ monkeypatch.setitem(sys.modules, "matplotlib_inline.backend_inline", fake_inline)
833
+ fig, ax = plt.subplots()
834
+ fig.canvas.draw_idle()
835
+ assert fake_inline.show._draw_called is True
836
+
837
+
838
+ def test_warnings_about_umbruch_itself_are_not_logged(caplog):
839
+ with caplog.at_level(logging.WARNING, logger="umbruch_matplotlib"):
840
+ hb._report(["stop_parsing for XML5 not implemented, full speed ahead!",
841
+ "The document has no `lang`: the PDF does not conform to PDF/UA.",
842
+ "something about the document"])
843
+ assert caplog.messages == ["umbruch: something about the document"], caplog.messages
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: umbruch-matplotlib
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: Matplotlib backend that renders PDF, text and math through umbruch
5
5
  License-Expression: MIT
6
6
  Project-URL: Homepage, https://github.com/manuel-rhdt/umbruch-matplotlib
@@ -53,12 +53,13 @@ pixels in total (the raster backend's limit) is an error.
53
53
 
54
54
  ### In Jupyter
55
55
 
56
- There is no interactive canvas, so `plt.show()` cannot open a window: it hands the open figures to
57
- IPython, which prints them through this backend's own `print_png`, so a notebook shows the engine's
58
- raster of the figure rather than an Agg preview. Run `%matplotlib inline` once: IPython then
59
- registers its figure formatter, a figure as the last expression of a cell is displayed, and a cell
60
- that only draws (`plt.plot(...)`) flushes the figure at its end. Without any `%matplotlib` there is
61
- nothing that displays figures at all — that is IPython's rule, not the backend's.
56
+ There is no interactive canvas, so a figure is shown by rendering it: `plt.show()` hands the open
57
+ figures to the notebook's own `show()`, which prints them through this backend's `print_png` (and
58
+ closes them as the notebook is configured to), so a figure is never shown twice. A plotting command
59
+ on its own is enough — the canvas' `draw_idle` tells the notebook that something changed, which is
60
+ what makes it flush the figure at the end of the cell, as with any other backend. Run
61
+ `%matplotlib inline` once to get that: it is what registers the figure formatter. Without any
62
+ `%matplotlib` nothing displays figures at all — IPython's rule, not the backend's.
62
63
 
63
64
  To keep exploring with a fast backend and render only the final file with umbruch, leave the
64
65
  notebook's backend alone and save with `fig.savefig("fig.pdf", backend="module://umbruch_matplotlib")`;
@@ -95,6 +95,17 @@ from matplotlib.transforms import Affine2D
95
95
 
96
96
  log = logging.getLogger(__name__)
97
97
 
98
+ #: What umbruch reports about the parse or the PDF and not about the figure: the XML tokenizer's
99
+ #: own note, and PDF/UA conformance (not a goal of a plot).
100
+ _QUIET_WARNINGS = ("stop_parsing for XML5", "PDF/UA")
101
+
102
+
103
+ def _report(warnings):
104
+ """Logs the warnings of a render, minus the ones that are about umbruch itself."""
105
+ for warning in warnings:
106
+ if not any(quiet in str(warning) for quiet in _QUIET_WARNINGS):
107
+ log.warning("umbruch: %s", warning)
108
+
98
109
  XHTML = "http://www.w3.org/1999/xhtml"
99
110
  RICH_MARK = ""
100
111
 
@@ -469,18 +480,14 @@ class UmbruchServer(UmbruchBridge):
469
480
 
470
481
  def render(self, svg, width, height):
471
482
  rendered = umbruch.HTML(svg, xml=True, server=self.server).render()
472
- for w in rendered.warnings:
473
- if "PDF/UA" not in str(w): # not a goal of a plot
474
- log.warning("umbruch: %s", w)
483
+ _report(rendered.warnings)
475
484
  return rendered.pdf
476
485
 
477
486
  def render_png(self, svg, width, height, dpi=96):
478
487
  if "png" not in self.capabilities:
479
488
  raise umbruch.Error("server", "this umbruch has no PNG output (the `png-output` feature)")
480
489
  rendered = umbruch.HTML(svg, xml=True, server=self.server).render_png(dpi=dpi)
481
- for w in rendered.warnings:
482
- if "PDF/UA" not in str(w):
483
- log.warning("umbruch: %s", w)
490
+ _report(rendered.warnings)
484
491
  return rendered.png
485
492
 
486
493
  def close(self):
@@ -1014,6 +1021,17 @@ class FigureCanvasUmbruch(FigureCanvasSVG):
1014
1021
  def get_default_filetype(self):
1015
1022
  return "pdf"
1016
1023
 
1024
+ def draw_idle(self):
1025
+ """Draws nothing — there is no live canvas — but tells a notebook's inline backend that the
1026
+ figure changed, which is what makes it show the figure at the end of a cell. Pyplot's own
1027
+ ``draw_if_interactive`` calls this, so a plotting command is enough; without it every cell
1028
+ would need an explicit ``plt.show()``."""
1029
+ try:
1030
+ import matplotlib_inline.backend_inline as inline
1031
+ except ImportError:
1032
+ return
1033
+ inline.show._draw_called = True
1034
+
1017
1035
  def _draw_to(self, fh, bridge, bbox_inches_restore, metadata, color_space=None):
1018
1036
  dpi = self.figure.dpi
1019
1037
  self.figure.dpi = 72
@@ -1091,15 +1109,24 @@ def show(*, block=None):
1091
1109
  leaves it to ``FigureManagerBase.pyplot_show``, which warns that the backend is
1092
1110
  non-interactive. IPython's own figure printer calls ``print_figure`` on whatever canvas a
1093
1111
  figure has, so displaying the figure object goes through umbruch already."""
1094
- from matplotlib._pylab_helpers import Gcf
1095
- figures = [manager.canvas.figure for manager in Gcf.get_all_fig_managers()]
1096
- if figures:
1112
+ try:
1113
+ from IPython import get_ipython
1114
+ except ImportError:
1115
+ get_ipython = None
1116
+ if get_ipython is not None and get_ipython() is not None:
1097
1117
  try:
1098
- from IPython.display import display
1118
+ # The notebook's own show(): displays every open figure (through this canvas'
1119
+ # print_png) and closes them the way it is configured to — so the end-of-cell flush
1120
+ # does not show the same figure a second time.
1121
+ import matplotlib_inline.backend_inline as inline
1099
1122
  except ImportError:
1100
- display = None
1101
- if display is not None:
1102
- for figure in figures:
1103
- display(figure)
1123
+ inline = None
1124
+ if inline is not None:
1125
+ inline.show(block=block)
1104
1126
  return
1127
+ from IPython.display import display
1128
+ from matplotlib._pylab_helpers import Gcf
1129
+ for manager in Gcf.get_all_fig_managers():
1130
+ display(manager.canvas.figure)
1131
+ return
1105
1132
  FigureManagerBase.pyplot_show(block=block)