umbruch-matplotlib 0.1.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.1.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
@@ -51,6 +51,20 @@ Agg. The page background is the figure's facecolor, so a transparent figure come
51
51
  channel. One page per file — a figure is one page — and a `dpi` that needs more than 16.7 million
52
52
  pixels in total (the raster backend's limit) is an error.
53
53
 
54
+ ### In Jupyter
55
+
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.
63
+
64
+ To keep exploring with a fast backend and render only the final file with umbruch, leave the
65
+ notebook's backend alone and save with `fig.savefig("fig.pdf", backend="module://umbruch_matplotlib")`;
66
+ matplotlib hands the figure its Agg canvas back afterwards.
67
+
54
68
  The backend builds on parts of Matplotlib's SVG renderer that are not public API. It is tested with Matplotlib 3.9, 3.10 and 3.11 (CI runs the oldest and the newest), and on import it checks that the parts it needs are there, naming what is missing otherwise.
55
69
 
56
70
  Unsupported features raise instead of falling back to Matplotlib's own text rendering:
@@ -26,6 +26,20 @@ Agg. The page background is the figure's facecolor, so a transparent figure come
26
26
  channel. One page per file — a figure is one page — and a `dpi` that needs more than 16.7 million
27
27
  pixels in total (the raster backend's limit) is an error.
28
28
 
29
+ ### In Jupyter
30
+
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.
38
+
39
+ To keep exploring with a fast backend and render only the final file with umbruch, leave the
40
+ notebook's backend alone and save with `fig.savefig("fig.pdf", backend="module://umbruch_matplotlib")`;
41
+ matplotlib hands the figure its Agg canvas back afterwards.
42
+
29
43
  The backend builds on parts of Matplotlib's SVG renderer that are not public API. It is tested with Matplotlib 3.9, 3.10 and 3.11 (CI runs the oldest and the newest), and on import it checks that the parts it needs are there, naming what is missing otherwise.
30
44
 
31
45
  Unsupported features raise instead of falling back to Matplotlib's own text rendering:
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "umbruch-matplotlib"
7
- version = "0.1.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
@@ -754,3 +755,89 @@ def test_rich_text_is_set_in_the_bold_and_italic_faces(real_bridge, tmp_path):
754
755
  fonts = subprocess.run(["pdffonts", str(path)], capture_output=True, text=True).stdout
755
756
  assert "DejaVuSans-Bold" in fonts, fonts
756
757
  assert "DejaVuSans-Oblique" in fonts, fonts
758
+
759
+
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)
796
+ import types
797
+ shown = []
798
+ fake_display = types.ModuleType("IPython.display")
799
+ fake_display.display = lambda figure, **kwargs: shown.append(figure)
800
+ monkeypatch.setitem(sys.modules, "IPython", _fake_ipython())
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)
804
+ fig, ax = plt.subplots()
805
+ ax.plot([0, 1])
806
+ plt.show()
807
+ assert shown == [fig], shown
808
+
809
+
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)
812
+ """Outside IPython there is nothing to display into, so the call goes to the non-interactive
813
+ backend — which warns where a window could have existed and is silent when headless."""
814
+ monkeypatch.setitem(sys.modules, "IPython", None) # (not importable)
815
+ calls = []
816
+ monkeypatch.setattr(hb.FigureManagerBase, "pyplot_show",
817
+ classmethod(lambda cls, **kwargs: calls.append(kwargs)))
818
+ fig, ax = plt.subplots()
819
+ ax.plot([0, 1])
820
+ plt.show()
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.1.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
@@ -51,6 +51,20 @@ Agg. The page background is the figure's facecolor, so a transparent figure come
51
51
  channel. One page per file — a figure is one page — and a `dpi` that needs more than 16.7 million
52
52
  pixels in total (the raster backend's limit) is an error.
53
53
 
54
+ ### In Jupyter
55
+
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.
63
+
64
+ To keep exploring with a fast backend and render only the final file with umbruch, leave the
65
+ notebook's backend alone and save with `fig.savefig("fig.pdf", backend="module://umbruch_matplotlib")`;
66
+ matplotlib hands the figure its Agg canvas back afterwards.
67
+
54
68
  The backend builds on parts of Matplotlib's SVG renderer that are not public API. It is tested with Matplotlib 3.9, 3.10 and 3.11 (CI runs the oldest and the newest), and on import it checks that the parts it needs are there, naming what is missing otherwise.
55
69
 
56
70
  Unsupported features raise instead of falling back to Matplotlib's own text rendering:
@@ -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
@@ -1083,3 +1101,32 @@ class FigureCanvasUmbruch(FigureCanvasSVG):
1083
1101
 
1084
1102
 
1085
1103
  FigureCanvas = FigureCanvasUmbruch
1104
+
1105
+
1106
+ def show(*, block=None):
1107
+ """Shows the open figures where a frontend can take them — in IPython and Jupyter as the PNG
1108
+ that umbruch renders of them, since this backend has no interactive canvas — and otherwise
1109
+ leaves it to ``FigureManagerBase.pyplot_show``, which warns that the backend is
1110
+ non-interactive. IPython's own figure printer calls ``print_figure`` on whatever canvas a
1111
+ figure has, so displaying the figure object goes through umbruch already."""
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:
1117
+ try:
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
1122
+ except ImportError:
1123
+ inline = None
1124
+ if inline is not None:
1125
+ inline.show(block=block)
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
1132
+ FigureManagerBase.pyplot_show(block=block)