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.
gleplot/compiler.py ADDED
@@ -0,0 +1,863 @@
1
+ """GLE compiler wrapper for gleplot."""
2
+
3
+ import glob
4
+ import logging
5
+ import os
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import List, Literal, Optional, Union
13
+
14
+ from ._warn import warn_external
15
+
16
+ _logger = logging.getLogger(__name__)
17
+
18
+ #: Well-known install locations to probe, keyed by ``sys.platform`` prefix.
19
+ #: Entries may be literal paths *or* glob patterns (``*``/``**``): users
20
+ #: install GLE in a variety of locations and versioned directories, so :func:`autodetect_gle` expands every entry with
21
+ #: :func:`glob.glob` and keeps the existing matches. Ordinary ``pip`` / library
22
+ #: use is unaffected (the literal entries below match the common installs).
23
+ _WELL_KNOWN_PATHS = {
24
+ "win32": [
25
+ r"C:\Program Files\GLE\bin\gle.exe",
26
+ r"C:\Program Files (x86)\GLE\bin\gle.exe",
27
+ # Versioned / non-default install roots, e.g. "GLE-4.3.9".
28
+ r"C:\Program Files*\GLE*\bin\gle.exe",
29
+ r"C:\Program Files*\GLE*\gle.exe",
30
+ # Per-user installs (some installers / manual unzips land here).
31
+ os.path.join(
32
+ os.environ.get("LOCALAPPDATA", r"C:\Users\Default\AppData\Local"),
33
+ "Programs",
34
+ "GLE*",
35
+ "**",
36
+ "gle.exe",
37
+ ),
38
+ ],
39
+ "darwin": [
40
+ "/usr/local/bin/gle", # Homebrew (Intel)
41
+ "/opt/homebrew/bin/gle", # Homebrew (Apple Silicon)
42
+ "/opt/local/bin/gle", # MacPorts
43
+ "/usr/bin/gle",
44
+ "/Applications/GLE*/**/gle",
45
+ ],
46
+ "default": [
47
+ "/usr/local/bin/gle",
48
+ "/opt/homebrew/bin/gle",
49
+ "/usr/bin/gle",
50
+ "/snap/bin/gle", # snap
51
+ ],
52
+ }
53
+
54
+ #: Process-global explicit override for the GLE executable, set via
55
+ #: :func:`set_gle_path_override`. This is how an application built on gleplot
56
+ #: (a GUI with its own "choose GLE" setting, say) pins the binary its user
57
+ #: chose; it takes precedence over every other discovery source (see
58
+ #: :func:`find_gle`). ``None`` means "not set", the default, so nothing
59
+ #: changes for plain library use.
60
+ _gle_path_override: Optional[str] = None
61
+
62
+
63
+ def set_gle_path_override(path: Optional[str]) -> None:
64
+ """Pin (or clear) the GLE executable used by :func:`find_gle`.
65
+
66
+ gleplot itself never calls this. It is the hook for an application that
67
+ stores its own GLE path: call it once and everything resolving GLE via
68
+ :func:`find_gle` honors the same choice. An
69
+ empty string is normalized to ``None`` (i.e. "clear the override and fall
70
+ back to auto-detection").
71
+
72
+ Parameters
73
+ ----------
74
+ path : str or None
75
+ Absolute path to a GLE executable, or ``None`` / ``""`` to clear the
76
+ override and revert to auto-detection.
77
+ """
78
+ global _gle_path_override
79
+ _gle_path_override = path or None
80
+
81
+
82
+ #: Output formats (GLE ``-d`` device names, lowercased) that
83
+ #: :meth:`GLECompiler.compile` accepts.
84
+ SUPPORTED_COMPILE_FORMATS = frozenset({"pdf", "png", "eps", "jpg", "svg"})
85
+
86
+ #: Mapping from a file suffix (including the leading dot, lowercased) to the
87
+ #: GLE compile format that should be used to produce it. Kept alongside
88
+ #: :data:`SUPPORTED_COMPILE_FORMATS` so callers (e.g. ``Figure.savefig``) that
89
+ #: auto-detect a format from a filename can't drift out of sync with what the
90
+ #: compiler actually supports. ``.jpeg`` maps to ``jpg`` since GLE only
91
+ #: recognizes ``jpg`` as a device name.
92
+ #: The formats :meth:`GLECompiler.compile` accepts, as a type.
93
+ CompileFormat = Literal["pdf", "png", "eps", "jpg", "svg"]
94
+
95
+ SUFFIX_TO_COMPILE_FORMAT = {f".{fmt}": fmt for fmt in SUPPORTED_COMPILE_FORMATS}
96
+ SUFFIX_TO_COMPILE_FORMAT[".jpeg"] = "jpg"
97
+
98
+ #: Formats for which GLE's ``-r`` (raster resolution / DPI) flag is
99
+ #: meaningful. Passing ``-r`` for a vector format (pdf/eps/svg) is harmless --
100
+ #: GLE silently ignores it -- but including it unconditionally obscures which
101
+ #: formats it actually affects.
102
+ RASTER_COMPILE_FORMATS = frozenset({"png", "jpg"})
103
+
104
+
105
+ def build_compile_args(
106
+ output_format: str,
107
+ output_path: Union[str, Path],
108
+ input_path: Union[str, Path],
109
+ dpi: Optional[int] = None,
110
+ cairo: bool = False,
111
+ transparent: bool = False,
112
+ grayscale: bool = False,
113
+ ) -> List[str]:
114
+ """Build the GLE command-line arguments for one compile invocation.
115
+
116
+ This is the single place that decides ``-d``/``-cairo``/``-nocolor``/
117
+ ``-transparent``/``-r``/``-o`` argument shape for
118
+ :meth:`GLECompiler.compile`. It lowercases the device name (GLE's ``-d``
119
+ is case-insensitive; verified against a real ``gle`` binary) and
120
+ includes ``-r`` only for :data:`RASTER_COMPILE_FORMATS`.
121
+
122
+ Does **not** include the ``gle`` executable path itself -- callers using
123
+ :mod:`subprocess` prepend it to this list.
124
+
125
+ Parameters
126
+ ----------
127
+ output_format : str
128
+ One of :data:`SUPPORTED_COMPILE_FORMATS` (case-insensitive).
129
+ output_path : str or Path
130
+ Value passed to ``-o``. Can be relative (resolved against the
131
+ process's working directory) or absolute.
132
+ input_path : str or Path
133
+ The ``.gle`` script to compile. Same relative/absolute freedom as
134
+ ``output_path``.
135
+ dpi : int, optional
136
+ Raster resolution. Only emitted (as ``-r <dpi>``) when
137
+ ``output_format`` is in :data:`RASTER_COMPILE_FORMATS` *and* ``dpi``
138
+ is not ``None``.
139
+ cairo : bool, optional
140
+ When ``True``, appends ``-cairo`` to enable GLE's Cairo rendering
141
+ backend (SPEC §6.1/§10.6). Required for a script using
142
+ semi-transparency (an ``rgba(...)``/``rgba255(...)`` colour); GLE
143
+ fails outright on such a script without it, on every device this
144
+ function supports *except* ``svg`` (``-d svg`` always renders
145
+ through GLE's Cairo backend regardless of this flag -- but see the
146
+ Notes below for why passing it explicitly still matters there too).
147
+ Deciding *when* to enable Cairo is the caller's job:
148
+ :meth:`gleplot.figure.Figure.savefig` passes
149
+ ``figure.requires_cairo()`` automatically; other callers pass an
150
+ explicit override. An ``svg`` always gets the flag, whatever this
151
+ says (see the Notes).
152
+ transparent : bool, optional
153
+ When ``True`` and ``output_format`` is ``png``, appends
154
+ ``-transparent`` (an alpha channel instead of a white background).
155
+ GLE ignores the flag on every other device, so it is left out there:
156
+ PDF, EPS and SVG have no background, and a JPEG warns because it has
157
+ no alpha channel. A grayscale PNG keeps its alpha channel only with
158
+ ``cairo=True``, and warns without it.
159
+ grayscale : bool, optional
160
+ When ``True``, appends ``-nocolor``: GLE converts the colours it draws
161
+ to their grey level. Colormap images (heatmaps) are converted only in
162
+ PNG and JPEG output.
163
+
164
+ Notes
165
+ -----
166
+ Device composition under ``-cairo`` (verified against a real GLE 4.3.10
167
+ binary; see ``gleplot.cairo_support`` for the font-substitution half of
168
+ this):
169
+
170
+ * ``pdf``/``eps``/``png``/``jpg`` -- without ``-cairo``, a script using
171
+ semi-transparency fails (exit 1, "semi-transparency only supported
172
+ with command line option '-cairo'"); with it, they succeed. ``png``/
173
+ ``jpg`` route through an internal Cairo PDF pass first (visible in
174
+ GLE's own progress output as ``[foo.pdf][foo.png]``) but GLE cleans up
175
+ that intermediate itself -- no leftover ``.pdf`` was observed.
176
+ * ``svg`` -- GLE *always* selects its Cairo SVG backend for ``-d svg``,
177
+ with or without ``-cairo`` on the command line. But the flag still
178
+ changes behavior: GLE's own automatic PostScript-font fallback
179
+ (silently substituting a Cairo-safe font, with only an informational
180
+ note) is gated on the ``-cairo`` *flag* being present, not on the
181
+ Cairo backend being active. Compile ``-d svg`` *without* ``-cairo``
182
+ against the default (PostScript) font and GLE still exits 0 but drops
183
+ the affected text from the output (a hard, uncaught
184
+ ``PostScript fonts not supported with '-cairo'`` at the point each
185
+ character would have been drawn). So an SVG compile always passes
186
+ ``-cairo``, which lets GLE's own graceful fallback run instead.
187
+
188
+ Returns
189
+ -------
190
+ list of str
191
+ E.g. ``['-d', 'png', '-r', '150', '-o', 'out.png', 'in.gle']``.
192
+
193
+ Raises
194
+ ------
195
+ ValueError
196
+ If ``output_format`` is not in :data:`SUPPORTED_COMPILE_FORMATS`.
197
+ """
198
+ fmt = output_format.lower()
199
+ if fmt not in SUPPORTED_COMPILE_FORMATS:
200
+ raise ValueError(
201
+ f"Unsupported GLE compile format: {output_format!r} "
202
+ f"(supported: {sorted(SUPPORTED_COMPILE_FORMATS)})"
203
+ )
204
+
205
+ args = ["-d", fmt]
206
+ if cairo or fmt == "svg":
207
+ args.append("-cairo")
208
+ if grayscale:
209
+ args.append("-nocolor")
210
+ if transparent and fmt == "png":
211
+ args.append("-transparent")
212
+ if grayscale and not cairo:
213
+ # Verified with GLE 4.3.10: without -cairo, -nocolor writes a
214
+ # grey-only PNG and the alpha channel is lost.
215
+ warn_external(
216
+ "transparent=True has no effect on a grayscale PNG unless it "
217
+ "is compiled with cairo=True; pass cairo=True to keep the "
218
+ "transparent background."
219
+ )
220
+ elif transparent and fmt == "jpg":
221
+ warn_external(
222
+ "transparent=True has no effect on a JPEG, which has no alpha "
223
+ "channel; save as PNG for a transparent background."
224
+ )
225
+ if fmt in RASTER_COMPILE_FORMATS and dpi is not None:
226
+ args.extend(["-r", str(int(dpi))])
227
+ args.extend(["-o", str(output_path), str(input_path)])
228
+ return args
229
+
230
+
231
+ def remove_generated_intermediates(
232
+ directory: Union[str, Path], filenames: "list[str]"
233
+ ) -> "list[Path]":
234
+ """Delete engine-generated intermediates by exact name (GLEstudio §9.1/§10.8).
235
+
236
+ GLE's ``begin contour``/``fitz`` code paths write files into the
237
+ compiling script's directory as an undocumented side effect of running
238
+ the ``gle`` binary -- never something gleplot itself asked GLE to write.
239
+ ``begin contour`` always produces ``<stem>-cdata.dat``,
240
+ ``<stem>-clabels.dat`` and ``<stem>-cvalues.dat`` (GLE derives ``<stem>``
241
+ from its ``data "<stem>.z"`` line by stripping the extension --
242
+ ``GetMainName`` in GLE's own ``gcontour.cpp``); a scattered (points-based)
243
+ heatmap or contour additionally runs ``fitz``, which writes a gridded
244
+ ``<stem>.z`` from the raw points ``.dat`` gleplot wrote (``fit.cpp``).
245
+ None of these are gleplot's own output and none of them are meant to
246
+ survive past the compile that produced them -- left behind, they clutter
247
+ (and can go stale in) the export directory.
248
+
249
+ This function does no globbing and no prefix matching: ``filenames`` is
250
+ the closed, exact list of basenames a *specific* figure's contour/fitz
251
+ series can produce (built by
252
+ :meth:`~gleplot.figure.Figure._engine_intermediate_filenames`, itself
253
+ derived from sidecar names that figure's own writer reserved -- see
254
+ ``axes._reserve_sidecar``). A name is removed only if it is a literal,
255
+ case-sensitive match to something in ``filenames`` *and* it exists as a
256
+ plain file directly inside ``directory``; anything else -- a user's own
257
+ file, a same-looking name in a different figure's stem sequence, a
258
+ subdirectory -- is left alone. Path separators in a candidate name are
259
+ rejected outright (defence in depth: every real caller only ever puts
260
+ plain basenames in ``filenames``, but nothing here should ever escape
261
+ ``directory`` even if a caller lists something malformed).
262
+
263
+ Parameters
264
+ ----------
265
+ directory : str or Path
266
+ The directory the ``.gle`` script was compiled from (its intermediates
267
+ land here -- see the module note in ``Figure.savefig``).
268
+ filenames : list of str
269
+ Exact basenames to remove if present.
270
+
271
+ Returns
272
+ -------
273
+ list of Path
274
+ The files actually removed (a subset of ``filenames``; a name with no
275
+ matching file -- e.g. a dangling series that produced no output, or
276
+ a heatmap/contour without ``clabel`` so no ``-clabels.dat`` -- is
277
+ silently skipped, not an error).
278
+ """
279
+ directory = Path(directory)
280
+ removed: "list[Path]" = []
281
+ for name in dict.fromkeys(filenames): # de-dupe, preserve order
282
+ if not name or "/" in name or "\\" in name or name in (".", ".."):
283
+ continue
284
+ candidate = directory / name
285
+ try:
286
+ if candidate.is_file():
287
+ candidate.unlink()
288
+ removed.append(candidate)
289
+ except OSError:
290
+ # Best-effort cleanup: a permissions error or a race (file
291
+ # removed by something else between the is_file() check and the
292
+ # unlink()) should not turn a successful compile into a failure.
293
+ pass
294
+ return removed
295
+
296
+
297
+ def _remove_tex_cache(
298
+ cache_dir: Union[str, Path], stem: str, existing: "set[str]"
299
+ ) -> None:
300
+ """Delete what compiling ``<stem>.gle`` left in GLE's LaTeX cache.
301
+
302
+ GLE runs LaTeX for ``begin tex`` blocks and ``set texlabels 1`` labels
303
+ in a ``.gle/`` directory beside the script: a ``<stem>/`` folder that
304
+ belongs to that script alone, and ``texpreamble.*`` files that every
305
+ script in the directory with the same preamble shares. The ``<stem>/``
306
+ folder is removed. A ``texpreamble.*`` file is removed only if it is not
307
+ in ``existing`` (the names the cache held before the compile) and no
308
+ other script's folder is in the cache, since that script may be using
309
+ the preamble right now. The cache directory goes only if that leaves it
310
+ empty. Nothing else is touched.
311
+
312
+ Two first-time compiles started together in one directory can still
313
+ race: if one finishes before the other's LaTeX run has made its folder,
314
+ it removes the preamble that run is using, and that compile may fail.
315
+ """
316
+ cache_dir = Path(cache_dir)
317
+ if not stem or stem in (".", ".."):
318
+ return
319
+ shutil.rmtree(cache_dir / stem, ignore_errors=True)
320
+ try:
321
+ entries = list(cache_dir.iterdir())
322
+ if all(e.name.startswith("texpreamble.") for e in entries):
323
+ for entry in entries:
324
+ if entry.name not in existing:
325
+ entry.unlink()
326
+ cache_dir.rmdir()
327
+ except OSError:
328
+ # Best effort: a missing or non-empty cache, or a file another
329
+ # process holds, must not fail a compile that succeeded.
330
+ pass
331
+
332
+
333
+ def _iter_well_known_gle_paths() -> "list[str]":
334
+ """Return existing GLE executables among the well-known locations.
335
+
336
+ Each entry in :data:`_WELL_KNOWN_PATHS` for the current platform is treated
337
+ as a :func:`glob.glob` pattern (a literal path is simply a pattern with no
338
+ wildcards), so versioned / non-standard install directories are matched
339
+ too. Results are de-duplicated while preserving discovery order.
340
+ """
341
+ patterns = _WELL_KNOWN_PATHS.get(sys.platform, _WELL_KNOWN_PATHS["default"])
342
+ seen: set = set()
343
+ found: list = []
344
+ for pattern in patterns:
345
+ # recursive=True so a ``**`` segment spans nested directories.
346
+ for match in glob.glob(pattern, recursive=True):
347
+ if match not in seen and Path(match).exists():
348
+ seen.add(match)
349
+ found.append(match)
350
+ return found
351
+
352
+
353
+ def autodetect_gle() -> Optional[str]:
354
+ """
355
+ Auto-detect the GLE executable, ignoring any explicit override.
356
+
357
+ This is the discovery used both as the fallback inside :func:`find_gle`
358
+ (when no override is set) and directly by an application that wants to
359
+ propose a path regardless of what its user has currently pinned.
360
+
361
+ Discovery precedence (first match wins):
362
+
363
+ 1. ``GLE_PATH`` environment variable -- the supported way to pin a
364
+ specific GLE binary from the environment (e.g. to select among several
365
+ installed versions, or a non-standard install location). If ``GLE_PATH``
366
+ is set but does not point at an existing path, a :class:`UserWarning` is
367
+ emitted and discovery falls through rather than silently ignoring the
368
+ misconfiguration.
369
+ 2. ``shutil.which("gle")`` (searches ``PATH``, respecting ``PATHEXT`` on
370
+ Windows)
371
+ 3. Platform-specific well-known install locations (:data:`_WELL_KNOWN_PATHS`,
372
+ expanded as globs so versioned install dirs are matched).
373
+
374
+ Returns
375
+ -------
376
+ str, optional
377
+ Path to the GLE executable, or None if it could not be found.
378
+ """
379
+ env_path = os.environ.get("GLE_PATH")
380
+ if env_path:
381
+ if Path(env_path).exists():
382
+ return env_path
383
+ warn_external(
384
+ f"GLE_PATH is set to {env_path!r} but that path does not exist; "
385
+ "falling back to PATH / well-known install locations.",
386
+ )
387
+
388
+ which_path = shutil.which("gle")
389
+ if which_path:
390
+ return which_path
391
+
392
+ well_known = _iter_well_known_gle_paths()
393
+ if well_known:
394
+ return well_known[0]
395
+
396
+ return None
397
+
398
+
399
+ def find_gle() -> Optional[str]:
400
+ """
401
+ Locate the GLE executable, honoring an explicit override first.
402
+
403
+ Discovery precedence (first match wins):
404
+
405
+ 1. The explicit override set via :func:`set_gle_path_override` (how an
406
+ application pins its user's chosen binary). If the override is set but no longer
407
+ points at an existing path, a :class:`UserWarning` is emitted and
408
+ discovery falls through to auto-detection rather than failing outright.
409
+ 2. Everything :func:`autodetect_gle` checks (``GLE_PATH`` env, then
410
+ ``PATH``, then well-known install locations).
411
+
412
+ The override deliberately outranks ``GLE_PATH``: it represents an explicit,
413
+ in-app choice by the user, which should win over an ambient environment
414
+ variable. With no override set (the library / CLI default) this is exactly
415
+ :func:`autodetect_gle`.
416
+
417
+ Returns
418
+ -------
419
+ str, optional
420
+ Path to the GLE executable, or None if it could not be found.
421
+ """
422
+ if _gle_path_override:
423
+ if Path(_gle_path_override).exists():
424
+ return _gle_path_override
425
+ warn_external(
426
+ f"Configured GLE path {_gle_path_override!r} does not exist; "
427
+ "falling back to auto-detection.",
428
+ )
429
+
430
+ return autodetect_gle()
431
+
432
+
433
+ @dataclass
434
+ class GLEError:
435
+ """A single structured error parsed from GLE compiler output."""
436
+
437
+ file: Optional[str]
438
+ line: Optional[int]
439
+ column: Optional[int]
440
+ message: str
441
+ source_line: Optional[str] = None
442
+
443
+
444
+ class GLECompileError(RuntimeError):
445
+ """Raised when GLE compilation fails.
446
+
447
+ Parameters
448
+ ----------
449
+ message : str
450
+ Human-readable summary of the failure.
451
+ errors : list[GLEError]
452
+ Structured errors parsed from the compiler output.
453
+ raw_output : str
454
+ The raw combined output produced by the GLE process.
455
+ """
456
+
457
+ def __init__(
458
+ self, message: str, errors: Optional[list] = None, raw_output: str = ""
459
+ ):
460
+ super().__init__(message)
461
+ self.errors: list = errors if errors is not None else []
462
+ self.raw_output = raw_output
463
+
464
+
465
+ # Matches the location/source line, e.g.:
466
+ # >> bad.gle (3) |let d1 = sin(x frum 0 to 2*pi|
467
+ #: ANSI SGR color/style escape sequences (e.g. ``\x1b[91m``) emitted by
468
+ #: GLE builds compiled with CONSOLE_COLORS=ON (the Linux/macOS default).
469
+ _ANSI_ESCAPE_RE = re.compile(r"\x1b\[[0-9;]*m")
470
+
471
+ _LOCATION_RE = re.compile(
472
+ r"^>>\s*(?P<file>.+?)\s*\((?P<line>\d+)\)\s*\|(?P<source>.*)\|\s*$"
473
+ )
474
+
475
+ # Matches the caret line, e.g.:
476
+ # >> ^
477
+ # The caret's absolute column position (from the start of the line) is used,
478
+ # together with the position of the opening '|' on the location line, to
479
+ # compute the column within the quoted source text.
480
+ _CARET_RE = re.compile(r"^>>\s*\^\s*$")
481
+
482
+ # Matches the message line, e.g.:
483
+ # >> Error: expected closing ')'
484
+ _MESSAGE_RE = re.compile(r"^>>\s*(?:Error:\s*)?(?P<message>.+)$")
485
+
486
+ # Matches specifically the line that *starts* an error message, e.g.:
487
+ # >> Error: expected closing ')'
488
+ # Used to tell a fresh error block apart from a plain continuation line of a
489
+ # multi-line message (e.g. the "expecting one of: ..." list GLE appends after
490
+ # some errors), which repeats the ">> " prefix but never repeats "Error:".
491
+ _ERROR_START_RE = re.compile(r"^>>\s*Error:", re.IGNORECASE)
492
+
493
+ # GLE's message for an `include` it cannot find (text_load_include in
494
+ # drawit.cpp). Scripts gleplot writes include routines from GLE's gleinc
495
+ # library, which a GLE built from source without gle-library lacks.
496
+ _MISSING_INCLUDE_RE = re.compile(r"include file not found: '(.*)'")
497
+ _GLEINC_DOCS_URL = (
498
+ "https://benhuddart.github.io/gleplot/getting_started.html#gle-s-include-library"
499
+ )
500
+
501
+
502
+ def _collect_message_lines(lines: list, i: int, n: int) -> tuple:
503
+ """Collect the ``>> ...`` message line(s) for one error block.
504
+
505
+ Starting at index ``i`` (which may be sitting on a blank line rather than
506
+ directly on the message -- see below), gather consecutive ``>> ``-prefixed
507
+ lines into a list of message fragments.
508
+
509
+ Two real-GLE landmines drive the scanning rules here:
510
+
511
+ * For several of the commonest error classes (missing data files, unknown
512
+ colours, unclosed ``begin``/``end`` blocks, runtime markup errors), GLE
513
+ emits a *blank* line where the caret would otherwise go, then the
514
+ ``>> Error: ...`` line -- there is no caret line to swallow that blank.
515
+ Blank lines are therefore skipped while scanning for the message,
516
+ rather than treated as the end of the block.
517
+ * When a script has multiple independent errors, GLE only prints a full
518
+ ``>> file (line) |source|`` location block before the *first* one;
519
+ subsequent errors appear as bare ``>> Error: ...`` lines with no
520
+ location at all, separated from their predecessors by a blank line.
521
+ So a second (or third, ...) ``>> Error:`` line always marks the start
522
+ of a new error record, never a continuation of the current message --
523
+ only non-"Error:" ``>> `` lines (e.g. a wrapped list of valid values)
524
+ continue the current message.
525
+
526
+ Returns
527
+ -------
528
+ tuple[int, list[str]]
529
+ The index just past the consumed lines, and the collected message
530
+ fragments (empty if none were found).
531
+ """
532
+ message_parts = []
533
+ started = False
534
+ while i < n:
535
+ raw = lines[i]
536
+ if not raw.strip():
537
+ # Blank line: may be padding before the message (no caret was
538
+ # emitted) or trailing padding after it. Either way, keep
539
+ # scanning past it -- it never itself ends the block.
540
+ i += 1
541
+ continue
542
+ if not raw.startswith(">>"):
543
+ break
544
+ if _LOCATION_RE.match(raw):
545
+ # A new error's location block starts here; let the caller's
546
+ # outer loop handle it.
547
+ break
548
+ if _ERROR_START_RE.match(raw) and started:
549
+ # A second "Error:" line: this is a new, location-less error
550
+ # block, not a continuation of the one we're building.
551
+ break
552
+ msg_match = _MESSAGE_RE.match(raw)
553
+ if msg_match:
554
+ text = msg_match.group("message").strip()
555
+ if text:
556
+ message_parts.append(text)
557
+ started = True
558
+ i += 1
559
+ return i, message_parts
560
+
561
+
562
+ def parse_gle_errors(output: str) -> list:
563
+ """
564
+ Parse structured errors out of raw GLE compiler output.
565
+
566
+ GLE reports errors in blocks that look like::
567
+
568
+ >> bad.gle (3) |let d1 = sin(x frum 0 to 2*pi|
569
+ >> ^
570
+ >> Error: expected closing ')'
571
+
572
+ Multiple such blocks may appear in one run. The caret line is optional
573
+ (some errors only report file/line/message). If the output cannot be
574
+ parsed as one or more GLE error blocks, a single :class:`GLEError` is
575
+ returned with ``message`` set to the raw output.
576
+
577
+ Parameters
578
+ ----------
579
+ output : str
580
+ Combined stdout/stderr text produced by the GLE process.
581
+
582
+ Returns
583
+ -------
584
+ list of GLEError
585
+ Structured errors found in the output. Always non-empty for
586
+ non-empty input.
587
+ """
588
+ if not output or not output.strip():
589
+ return []
590
+
591
+ # Linux/macOS GLE builds (CONSOLE_COLORS=ON) wrap diagnostics in ANSI
592
+ # color escapes, which would defeat the location regex below and
593
+ # degrade every error to an unstructured raw-text fallback. Strip them
594
+ # up front; harmless on output that has none (Windows builds).
595
+ output = _ANSI_ESCAPE_RE.sub("", output)
596
+
597
+ lines = output.splitlines()
598
+ errors = []
599
+
600
+ i = 0
601
+ n = len(lines)
602
+ while i < n:
603
+ loc_match = _LOCATION_RE.match(lines[i])
604
+ if loc_match:
605
+ file = loc_match.group("file")
606
+ line_no = int(loc_match.group("line"))
607
+ source_line = loc_match.group("source")
608
+ # Position of the opening '|' delimiter on the location line,
609
+ # used below to translate the caret's absolute column into a
610
+ # column relative to the start of the quoted source text.
611
+ pipe_pos = lines[i].index("|")
612
+ column = None
613
+ i += 1
614
+
615
+ # Optional caret line.
616
+ if i < n:
617
+ caret_match = _CARET_RE.match(lines[i])
618
+ if caret_match:
619
+ caret_pos = lines[i].index("^")
620
+ column = max(caret_pos - pipe_pos - 1, 0)
621
+ i += 1
622
+
623
+ i, message_parts = _collect_message_lines(lines, i, n)
624
+ message = " ".join(message_parts) if message_parts else "GLE error"
625
+
626
+ errors.append(
627
+ GLEError(
628
+ file=file,
629
+ line=line_no,
630
+ column=column,
631
+ message=message,
632
+ source_line=source_line,
633
+ )
634
+ )
635
+ continue
636
+
637
+ if _ERROR_START_RE.match(lines[i]):
638
+ # A bare "Error:" line with no preceding location block: GLE
639
+ # only prints the full location for the first error in a run of
640
+ # several independent ones (e.g. N unrelated bad commands), so
641
+ # each subsequent "Error:" line found here starts its own
642
+ # GLEError rather than being silently dropped.
643
+ i, message_parts = _collect_message_lines(lines, i, n)
644
+ message = " ".join(message_parts) if message_parts else "GLE error"
645
+
646
+ errors.append(
647
+ GLEError(
648
+ file=None,
649
+ line=None,
650
+ column=None,
651
+ message=message,
652
+ source_line=None,
653
+ )
654
+ )
655
+ continue
656
+
657
+ i += 1
658
+
659
+ if not errors:
660
+ # Unparseable output: fall back to a single error carrying the raw text.
661
+ errors.append(
662
+ GLEError(
663
+ file=None,
664
+ line=None,
665
+ column=None,
666
+ message=output.strip(),
667
+ source_line=None,
668
+ )
669
+ )
670
+
671
+ return errors
672
+
673
+
674
+ class GLECompiler:
675
+ """Wrapper for GLE command-line compiler.
676
+
677
+ When ``gle_path`` is not given explicitly, the GLE executable is located
678
+ via :func:`find_gle`, which searches (in order) the ``GLE_PATH``
679
+ environment variable, ``PATH`` (via :func:`shutil.which`), and a set of
680
+ platform-specific well-known install locations. Set ``GLE_PATH`` to pin a
681
+ specific GLE binary, e.g. when multiple versions are installed.
682
+ """
683
+
684
+ def __init__(self, gle_path: Optional[str] = None):
685
+ """
686
+ Initialize GLE compiler.
687
+
688
+ Parameters
689
+ ----------
690
+ gle_path : str, optional
691
+ Path to GLE executable. If None, resolved via :func:`find_gle`
692
+ (``GLE_PATH`` env var, then ``PATH``, then well-known install
693
+ locations).
694
+ """
695
+ resolved = gle_path or find_gle()
696
+ if not resolved:
697
+ raise RuntimeError("GLE not found. Install GLE or provide gle_path.")
698
+ self.gle_path: str = resolved
699
+
700
+ def compile(
701
+ self,
702
+ input_file: str,
703
+ output_format: CompileFormat = "pdf",
704
+ dpi: int = 150,
705
+ verbose: bool = False,
706
+ timeout: int = 30,
707
+ cairo: bool = False,
708
+ transparent: bool = False,
709
+ grayscale: bool = False,
710
+ ) -> Path:
711
+ """
712
+ Compile GLE file to output format.
713
+
714
+ Parameters
715
+ ----------
716
+ input_file : str
717
+ Path to .gle input file
718
+ output_format : {'pdf', 'png', 'eps', 'jpg', 'svg'}
719
+ Output format
720
+ dpi : int
721
+ DPI for raster formats (png, jpg)
722
+ verbose : bool
723
+ Log GLE's output (stdout and stderr) to the ``gleplot.compiler``
724
+ logger at ``INFO`` level. Nothing reaches the console unless
725
+ logging is configured, e.g. ``logging.basicConfig(level="INFO")``.
726
+ On failure the output is in the raised :class:`GLECompileError`
727
+ whether or not this is set.
728
+ timeout : int
729
+ Maximum number of seconds to allow the GLE process to run.
730
+ cairo : bool
731
+ Whether to pass GLE's ``-cairo`` device flag (SPEC §6.1/§10.6).
732
+ Required for any script using semi-transparency (an
733
+ ``rgba(...)``/``rgba255(...)`` colour -- e.g. a ``fill_between``
734
+ with ``alpha < 1``); without it GLE fails outright on such a
735
+ script (``semi-transparency only supported with command line
736
+ option '-cairo'``). This method has no ``Figure`` to inspect, so
737
+ it never decides this for you -- ``cairo`` is an explicit,
738
+ caller-supplied override. :meth:`gleplot.figure.Figure.savefig`
739
+ is the caller that *does* have the figure and passes
740
+ ``figure.requires_cairo()`` here automatically; pass an explicit
741
+ ``True``/``False`` yourself when compiling a ``.gle`` file this
742
+ compiler didn't write (or to force the flag either way). An
743
+ ``svg`` always gets the flag (see :func:`build_compile_args`).
744
+ transparent : bool
745
+ Give a PNG an alpha channel instead of a white background (GLE's
746
+ ``-transparent``); see :func:`build_compile_args` for the other
747
+ formats and for a grayscale PNG.
748
+ grayscale : bool
749
+ Convert the colours GLE draws to their grey level (GLE's
750
+ ``-nocolor``); see :func:`build_compile_args` for colormap
751
+ images.
752
+
753
+ Returns
754
+ -------
755
+ Path
756
+ Path to output file
757
+
758
+ Raises
759
+ ------
760
+ FileNotFoundError
761
+ If the input file does not exist.
762
+ GLECompileError
763
+ If compilation fails (nonzero exit code, or the expected output
764
+ file was not produced). Carries structured ``errors`` and the
765
+ ``raw_output`` from the GLE process. When the failure is an
766
+ ``include`` file GLE cannot find, the message names the file and
767
+ points to installing GLE's include library.
768
+ """
769
+ input_path = Path(input_file).resolve()
770
+
771
+ if not input_path.exists():
772
+ raise FileNotFoundError(f"Input file not found: {input_file}")
773
+
774
+ # Determine output file
775
+ output_path = input_path.with_suffix(f".{output_format}")
776
+
777
+ # Build command (all options must come before filename). Pass as a
778
+ # list (no shell=True) so paths containing spaces are handled safely
779
+ # on all platforms, notably "Program Files" on Windows. Argument
780
+ # shape (device name case, when -r is included) comes from the one
781
+ # shared builder so callers assembling their own GLE command line
782
+ # cannot drift from it -- see build_compile_args().
783
+ cmd = [self.gle_path] + build_compile_args(
784
+ output_format,
785
+ output_path,
786
+ input_path,
787
+ dpi=dpi,
788
+ cairo=cairo,
789
+ transparent=transparent,
790
+ grayscale=grayscale,
791
+ )
792
+
793
+ try:
794
+ # GLE echoes script lines, which gleplot writes as UTF-8, so decode
795
+ # as UTF-8 whatever the locale (cp1252 on Windows); a byte that is
796
+ # not UTF-8 (a path in the ANSI code page) is replaced, not raised.
797
+ result = subprocess.run(
798
+ cmd,
799
+ capture_output=True,
800
+ encoding="utf-8",
801
+ errors="replace",
802
+ timeout=timeout,
803
+ )
804
+ except subprocess.TimeoutExpired:
805
+ raise GLECompileError(
806
+ f"GLE compilation timed out after {timeout}s",
807
+ errors=[],
808
+ raw_output="",
809
+ )
810
+
811
+ # GLE writes most diagnostic/error output to stderr, but some builds
812
+ # emit informational or error text on stdout too. Concatenate both
813
+ # streams so nothing is silently dropped; parse_gle_errors only
814
+ # matches its specific block pattern, so extra non-matching text is
815
+ # harmless.
816
+ raw_output = "\n".join(s for s in (result.stdout, result.stderr) if s)
817
+
818
+ if verbose and raw_output:
819
+ _logger.info("%s", raw_output)
820
+
821
+ if result.returncode != 0:
822
+ errors = parse_gle_errors(raw_output)
823
+ missing = _MISSING_INCLUDE_RE.search(_ANSI_ESCAPE_RE.sub("", raw_output))
824
+ if missing:
825
+ raise GLECompileError(
826
+ f"GLE could not find the include file '{missing.group(1)}'. "
827
+ "GLE looks for it next to the script, then in the gleinc "
828
+ "folder of its installation (GLE_TOP in `gle -info`), then "
829
+ "in GLE_USRLIB. If it is one of GLE's library routines, "
830
+ f"install GLE's include library: see {_GLEINC_DOCS_URL}\n"
831
+ f"GLE output: {raw_output.strip()}",
832
+ errors=errors,
833
+ raw_output=raw_output,
834
+ )
835
+ raise GLECompileError(
836
+ f"GLE compilation failed: {raw_output.strip()}",
837
+ errors=errors,
838
+ raw_output=raw_output,
839
+ )
840
+
841
+ if not output_path.exists():
842
+ errors = parse_gle_errors(raw_output)
843
+ raise GLECompileError(
844
+ f"Output file not created: {output_path}",
845
+ errors=errors,
846
+ raw_output=raw_output,
847
+ )
848
+
849
+ return output_path
850
+
851
+ def info(self) -> dict:
852
+ """Get GLE version and info."""
853
+ try:
854
+ result = subprocess.run(
855
+ [self.gle_path, "-info"],
856
+ capture_output=True,
857
+ encoding="utf-8",
858
+ errors="replace",
859
+ timeout=5,
860
+ )
861
+ return {"version": result.stdout.strip()}
862
+ except Exception as e:
863
+ return {"error": str(e)}