gleplot 6.0.0__py3-none-any.whl

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.
@@ -0,0 +1,232 @@
1
+ """Cairo-device support shared by the compile pipeline (Track G6).
2
+
3
+ GLE's ``-cairo`` device flag is required for two things gleplot cares about:
4
+
5
+ 1. **Semi-transparency.** Any ``rgba(...)``/``rgba255(...)`` colour --
6
+ notably the one :func:`gleplot.colors.apply_alpha` composes for a
7
+ ``fill_between``/``axvspan``/``axhspan`` whose ``alpha`` is below 1 --
8
+ makes GLE fail outright (``semi-transparency only supported with command
9
+ line option '-cairo'``, exit code 1) on every device except ``-d svg``
10
+ (which is *always* rendered through GLE's Cairo backend regardless of the
11
+ flag; see below).
12
+ 2. **PostScript-font rejection.** GLE's Cairo backend cannot draw PostScript
13
+ fonts. *With* ``-cairo`` on the command line, GLE substitutes gleplot's
14
+ long-standing SVG-preview fallback font (:data:`CAIRO_SAFE_FONT`) itself
15
+ and only prints an informational note (verified against GLE 4.3.10 --
16
+ exit code 0, output complete); *without* the flag -- which is exactly
17
+ what happens when ``-d svg`` forces the Cairo backend on but gleplot has
18
+ not asked for it explicitly -- the same substitution logic never runs and
19
+ GLE instead raises a hard, non-fatal-but-content-dropping error
20
+ (``PostScript fonts not supported with '-cairo'``) that silently omits
21
+ the affected text from the output. This is why gleplot must decide,
22
+ itself, whenever a Cairo-backed render is about to happen, whether the
23
+ configured font needs the same substitution -- and say so out loud
24
+ (SPEC's "no silent drops": a font swap must never happen without a
25
+ reported warning).
26
+
27
+ :func:`figure_requires_cairo` and :func:`is_cairo_safe_font` are pure,
28
+ Qt-free functions shared by :meth:`gleplot.figure.Figure.savefig` and other
29
+ compile callers so Cairo policy is not re-derived in multiple places.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import re
35
+ from typing import Any, Optional
36
+
37
+ #: The Cairo/TeX-safe font GLE itself substitutes for a rejected PostScript
38
+ #: font when ``-cairo`` is on the command line (empirically verified: GLE
39
+ #: 4.3.10 prints ``PostScript fonts not supported with '-cairo'; using
40
+ #: 'texcmr' instead`` and completes successfully). Named here so Cairo
41
+ #: substitution warnings can cite the same font GLE picks.
42
+ CAIRO_SAFE_FONT = "texcmr"
43
+
44
+ #: Font names GLE's Cairo backend draws natively -- the ``texcm*`` LaTeX
45
+ #: Computer Modern family (plus its ``texmi``/``texsy``/``texex`` aliases,
46
+ #: which point at the same ``.fve`` vector files -- see
47
+ #: ``font/font.dat`` in a GLE install) and ``glemark`` (GLE's own marker
48
+ #: glyph font, not a text face). Verified empirically against GLE 4.3.10:
49
+ #: compiling one ``set font <name>`` per entry here with ``-cairo`` and a
50
+ #: semi-transparent fill produces *no* ``PostScript fonts not supported``
51
+ #: note, while every other font in GLE's table (the ``rm``/``ss``/``tt``
52
+ #: aliases, the explicit ``ps*`` PostScript families, and the bitmap
53
+ #: ``arial8``/``cour8``/``times8`` Cyrillic faces) does.
54
+ #:
55
+ #: Not included: GLE's legacy ``pl*`` "Plotter" vector fonts, which also
56
+ #: tested Cairo-safe but are obscure enough (and distinct enough from
57
+ #: anything gleplot's own :class:`~gleplot.config.GLEStyleConfig` would set)
58
+ #: that treating them as unsafe -- one spurious substitution warning, never
59
+ #: a silent misrender -- is the safer default than growing this table to
60
+ #: chase every legacy name.
61
+ _CAIRO_SAFE_FONTS = frozenset(
62
+ {
63
+ "texcmr",
64
+ "texcmb",
65
+ "texcmti",
66
+ "texcmss",
67
+ "texcmssb",
68
+ "texcmssi",
69
+ "texcmtt",
70
+ "texcmitt",
71
+ "texcmsy",
72
+ "texcmex",
73
+ "texcmmi",
74
+ "texmi",
75
+ "texsy",
76
+ "texex",
77
+ "glemark",
78
+ }
79
+ )
80
+
81
+
82
+ def is_cairo_safe_font(font: Optional[str]) -> bool:
83
+ """Whether ``font`` is drawn natively by GLE's Cairo backend.
84
+
85
+ An empty/``None`` font -- gleplot's own "use GLE's built-in default"
86
+ sentinel (see ``GLEStyleConfig.font``) -- resolves to GLE's default font
87
+ (``rm``, PostScript Times), which is **not** Cairo-safe, so this
88
+ correctly returns ``False`` for it: a figure that never set a font still
89
+ needs the substitution-and-warning treatment the moment Cairo is active.
90
+ """
91
+ name = (font or "").strip().lower()
92
+ return name in _CAIRO_SAFE_FONTS
93
+
94
+
95
+ def cairo_font_warning(font: Optional[str]) -> Optional[str]:
96
+ """A warning message if ``font`` will be silently swapped under Cairo.
97
+
98
+ Returns ``None`` when ``font`` is already Cairo-safe (nothing to report).
99
+ Callers are expected to only call this once they've established Cairo is
100
+ actually active for the render at hand (see :func:`figure_requires_cairo`)
101
+ -- this function does not re-check that, so it always answers purely in
102
+ terms of the font.
103
+ """
104
+ if is_cairo_safe_font(font):
105
+ return None
106
+ shown = font if font else "(GLE default)"
107
+ return (
108
+ f"Font {shown!r} is not supported by GLE's Cairo backend "
109
+ f"(PostScript fonts are rejected); GLE will substitute "
110
+ f"{CAIRO_SAFE_FONT!r} when compiling with -cairo."
111
+ )
112
+
113
+
114
+ #: The TeX Computer Modern text fonts in OT1 encoding (verified against GLE
115
+ #: 4.3.10): ``<``, ``>``, ``\_``, ``|``, ``\{`` and ``\}`` draw as other
116
+ #: glyphs in them. ``texcmtt`` and ``texcmitt`` keep the ASCII layout.
117
+ _OT1_FONTS = frozenset(
118
+ {"texcmr", "texcmb", "texcmti", "texcmss", "texcmssb", "texcmssi"}
119
+ )
120
+
121
+ #: What draws each misdrawn character in an OT1 font: the math italic for
122
+ #: ``<``/``>``, the typewriter face for the rest.
123
+ _OT1_ESCAPES = {
124
+ "<": r"{\setfont{texmi}<}",
125
+ ">": r"{\setfont{texmi}>}",
126
+ r"\_": r"{\setfont{texcmtt}\_}",
127
+ "|": r"{\setfont{texcmtt}|}",
128
+ r"\{": r"{\setfont{texcmtt}\{}",
129
+ r"\}": r"{\setfont{texcmtt}\}}",
130
+ }
131
+
132
+ #: Non-ASCII characters no ``texcm*`` font draws (GLE writes their code
133
+ #: instead), with GLE's macro for each.
134
+ _TEXCM_MACROS = {"≥": r"\geq{}", "≤": r"\leq{}"}
135
+
136
+ #: The quoted strings of a GLE script: where gleplot writes all its text.
137
+ _QUOTED_RE = re.compile(r"\"[^\"]*\"|'[^']*'")
138
+
139
+ #: An escape from :data:`_OT1_ESCAPES` already written in the text.
140
+ _ESCAPED_RE = re.compile(r"\{\\setfont\{(?:texmi|texcmtt)\}(?:[<>|]|\\[_{}])\}")
141
+
142
+
143
+ def drawn_font(font: Optional[str], cairo: bool) -> str:
144
+ """The font GLE draws page text in: ``font``, or its Cairo substitute."""
145
+ if cairo and not is_cairo_safe_font(font):
146
+ return CAIRO_SAFE_FONT
147
+ return (font or "").strip().lower()
148
+
149
+
150
+ def text_glyph_warning(font: str, script: str) -> Optional[str]:
151
+ """A warning when text in ``script`` has characters ``font`` misdraws.
152
+
153
+ ``font`` is the font the text is drawn in (:func:`drawn_font`). Every
154
+ string quoted in ``script`` is checked; None when nothing is misdrawn.
155
+ """
156
+ if not font.startswith("texcm"):
157
+ return None
158
+ fixes = dict(_TEXCM_MACROS)
159
+ if font in _OT1_FONTS:
160
+ fixes.update(_OT1_ESCAPES)
161
+ text = _ESCAPED_RE.sub("", "".join(_QUOTED_RE.findall(script)))
162
+ found = [char for char in fixes if char in text]
163
+ if not found:
164
+ return None
165
+ # The text holds gleplot's escapes; the user typed the bare character.
166
+ hints = ", ".join(f"{char.lstrip(chr(92))} as {fixes[char]}" for char in found)
167
+ return (
168
+ f"Font {font!r} draws some characters in this figure's text as other "
169
+ f"glyphs. Write {hints} in the text instead, or choose another font "
170
+ "with GLEStyleConfig(font=...)."
171
+ )
172
+
173
+
174
+ #: Matches a GLE colour expression that already carries its own alpha --
175
+ #: ``rgba(...)`` or ``rgba255(...)`` -- wherever it can appear as a string in
176
+ #: the object model: a resolved colour token on a fill/span/line/marker/text
177
+ #: (see :func:`rgb_to_gle`'s "already a GLE colour expression" pass-through),
178
+ #: *or* embedded inside a raw ``passthrough`` line the parser could not fully
179
+ #: model (e.g. a hand-written ``fill dA,dB color rgba255(...)`` the
180
+ #: recognizer fell back on) -- so ``search`` rather than a start-anchored
181
+ #: ``match``, with a negative lookbehind so it does not fire on a longer
182
+ #: identifier that merely ends in ``rgba``.
183
+ _RGBA_COLOR_RE = re.compile(r"(?<![A-Za-z0-9_])rgba(255)?\s*\(", re.IGNORECASE)
184
+
185
+
186
+ def _value_requires_cairo(obj: Any) -> bool:
187
+ """Recursive worker for :func:`figure_requires_cairo`.
188
+
189
+ Walks a JSON-safe structure (as produced by ``Figure.to_dict()``) looking
190
+ for either of Cairo's two triggers (module docstring): a numeric
191
+ ``"alpha"`` field below 1.0 (today only ``FillSeries``/``Span`` declare
192
+ one, but this is a generic walk rather than a hardcoded field list, so a
193
+ future series kind that grows an ``alpha`` field is covered automatically
194
+ -- no second place to remember to update), or any string value that is
195
+ already a ``rgba(...)``/``rgba255(...)`` colour expression, wherever it
196
+ appears (fill/line/marker/text colour, ...).
197
+ """
198
+ if isinstance(obj, dict):
199
+ for key, value in obj.items():
200
+ if key == "alpha":
201
+ try:
202
+ if value is not None and float(value) < 1.0:
203
+ return True
204
+ except (TypeError, ValueError):
205
+ pass
206
+ if _value_requires_cairo(value):
207
+ return True
208
+ return False
209
+ if isinstance(obj, (list, tuple)):
210
+ return any(_value_requires_cairo(item) for item in obj)
211
+ if isinstance(obj, str):
212
+ return bool(_RGBA_COLOR_RE.search(obj))
213
+ return False
214
+
215
+
216
+ def figure_requires_cairo(snapshot: dict) -> bool:
217
+ """Whether a ``Figure.to_dict()`` snapshot needs GLE's ``-cairo`` device.
218
+
219
+ True when the figure uses transparency anywhere it can appear: a
220
+ ``fill_between``/``axvspan``/``axhspan`` with ``alpha < 1`` (the common
221
+ case), or any colour field already expressed as a raw
222
+ ``rgba(...)``/``rgba255(...)`` GLE expression (a user can pass one
223
+ directly to any colour parameter -- :func:`gleplot.colors.rgb_to_gle`
224
+ passes an already-formed colour expression through verbatim -- and a
225
+ ``.gle`` file recovered by the parser round-trips one the same way).
226
+
227
+ Operates on the plain-dict snapshot rather than a live ``Figure`` so
228
+ callers that already hold one can reuse it instead of re-serializing;
229
+ see :meth:`gleplot.figure.Figure.requires_cairo` for the convenience
230
+ wrapper that calls ``self.to_dict()`` for you.
231
+ """
232
+ return _value_requires_cairo(snapshot)