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/colors.py ADDED
@@ -0,0 +1,721 @@
1
+ """Color utilities for gleplot.
2
+
3
+ Colour fidelity contract
4
+ ------------------------
5
+ A colour that the user supplies as a **GLE colour name** (any case: ``red``,
6
+ ``DARKBLUE``, ``gray55``) is passed through as that name. Anything else --
7
+ a hex string, an RGB tuple, a grey-level string such as ``'0.3'``, a
8
+ matplotlib cycle code -- is converted to an
9
+ **exact** GLE colour expression ``rgb255(r,g,b)``.
10
+
11
+ This replaces the original "snap to the nearest of ~8 named colours by
12
+ dominant channel" behaviour, which silently destroyed the requested colour:
13
+ ``#8c8c8c`` and ``#999999`` (greys) both rendered MAGENTA, ``#bbbbbb``
14
+ rendered WHITE (invisible on a white page), and ``#9467bd`` (matplotlib's
15
+ tab purple) rendered MAGENTA -- so two distinct series could collide onto
16
+ one colour with no warning. GLE has supported ``rgb255(r,g,b)`` /
17
+ ``rgb(r,g,b)`` colour expressions since 4.2, everywhere a colour name is
18
+ accepted, so the snapping was never necessary.
19
+
20
+ An already-formed GLE colour expression (``rgb255(140,140,140)``,
21
+ ``rgb(0.55,0.4,0.74)``) is passed through unchanged apart from whitespace
22
+ normalisation. That matters for round-tripping: colours recovered from a
23
+ ``.gle`` file by :mod:`gleplot.parser` are fed back through this function
24
+ when the figure is rebuilt.
25
+ """
26
+
27
+ import re
28
+ from typing import Any, Dict, Optional, Sequence, Tuple, Union
29
+
30
+ import numpy as np
31
+
32
+ from ._warn import warn_external
33
+
34
+ # Matplotlib color codes to GLE color names
35
+ MATPLOTLIB_TO_GLE_COLORS = {
36
+ "b": "BLUE",
37
+ "g": "GREEN",
38
+ "r": "RED",
39
+ "c": "CYAN",
40
+ "m": "MAGENTA",
41
+ "y": "YELLOW",
42
+ "k": "BLACK",
43
+ "w": "WHITE",
44
+ # Named colors
45
+ "blue": "BLUE",
46
+ "green": "GREEN",
47
+ "red": "RED",
48
+ "cyan": "CYAN",
49
+ "magenta": "MAGENTA",
50
+ "yellow": "YELLOW",
51
+ "black": "BLACK",
52
+ "white": "WHITE",
53
+ "orange": "ORANGE",
54
+ "purple": "PURPLE",
55
+ "brown": "BROWN",
56
+ "pink": "PINK",
57
+ "gray": "GRAY",
58
+ "grey": "GRAY",
59
+ "lightblue": "LIGHTBLUE",
60
+ "lightgreen": "LIGHTGREEN",
61
+ "lightcyan": "LIGHTCYAN",
62
+ "lightgray": "LIGHTGRAY",
63
+ "lightgrey": "LIGHTGRAY",
64
+ "darkblue": "DARKBLUE",
65
+ "darkgreen": "DARKGREEN",
66
+ "darkred": "DARKRED",
67
+ "darkgray": "DARKGRAY",
68
+ "darkgrey": "DARKGRAY",
69
+ # The one CSS4 name GLE does not define.
70
+ "rebeccapurple": "rgb255(102,51,153)",
71
+ }
72
+
73
+ # Extended GLE color palette
74
+ GLE_COLORS = {
75
+ "BLUE",
76
+ "RED",
77
+ "GREEN",
78
+ "CYAN",
79
+ "MAGENTA",
80
+ "YELLOW",
81
+ "BLACK",
82
+ "WHITE",
83
+ "ORANGE",
84
+ "PURPLE",
85
+ "BROWN",
86
+ "PINK",
87
+ "GRAY",
88
+ "LIGHTBLUE",
89
+ "LIGHTGREEN",
90
+ "LIGHTCYAN",
91
+ "LIGHTGRAY",
92
+ "DARKBLUE",
93
+ "DARKGREEN",
94
+ "DARKRED",
95
+ "DARKGRAY",
96
+ }
97
+
98
+ #: matplotlib's default property cycle (``tab10``), keyed by both the cycle
99
+ #: reference (``C0``..``C9``) and the ``tab:`` colour name. These are NOT GLE
100
+ #: colour names, so they resolve to exact ``rgb255`` expressions -- ten
101
+ #: distinct colours. (They previously all collapsed to a handful of snapped
102
+ #: names, e.g. C4 ``#9467bd`` and C6 ``#e377c2`` both rendering MAGENTA.)
103
+ MATPLOTLIB_CYCLE_HEX = {
104
+ "c0": "#1f77b4",
105
+ "tab:blue": "#1f77b4",
106
+ "c1": "#ff7f0e",
107
+ "tab:orange": "#ff7f0e",
108
+ "c2": "#2ca02c",
109
+ "tab:green": "#2ca02c",
110
+ "c3": "#d62728",
111
+ "tab:red": "#d62728",
112
+ "c4": "#9467bd",
113
+ "tab:purple": "#9467bd",
114
+ "c5": "#8c564b",
115
+ "tab:brown": "#8c564b",
116
+ "c6": "#e377c2",
117
+ "tab:pink": "#e377c2",
118
+ "c7": "#7f7f7f",
119
+ "tab:gray": "#7f7f7f",
120
+ "tab:grey": "#7f7f7f",
121
+ "c8": "#bcbd22",
122
+ "tab:olive": "#bcbd22",
123
+ "c9": "#17becf",
124
+ "tab:cyan": "#17becf",
125
+ }
126
+
127
+ #: A GLE colour *expression* -- a function call such as ``rgb255(140,140,140)``,
128
+ #: ``rgb(0.1,0.2,0.8)`` or ``grey(0.5)``. Matched structurally (any identifier
129
+ #: applied to a parenthesised argument list) rather than against a fixed list
130
+ #: of function names, so a hand-written script's colour expression survives a
131
+ #: round trip untouched.
132
+ _COLOR_EXPR_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*\s*\([^()]*\)$")
133
+
134
+ #: Every colour name GLE recognises out of the box, uppercase: GLE's own
135
+ #: 151-name table plus the names gleplot's matplotlib mapping emits.
136
+ _GLE_COLOR_NAMES = None # type: Optional[frozenset]
137
+
138
+
139
+ def _gle_color_names() -> frozenset:
140
+ """Every colour name GLE recognises out of the box, uppercase."""
141
+ global _GLE_COLOR_NAMES
142
+ if _GLE_COLOR_NAMES is None:
143
+ _GLE_COLOR_NAMES = frozenset(COLORS) | frozenset(GLE_COLORS)
144
+ return _GLE_COLOR_NAMES
145
+
146
+
147
+ _ALPHA_NOT_APPLIED = (
148
+ "An RGBA colour's alpha (its fourth value) is not applied here. Pass an "
149
+ "RGB colour, and give the transparency with the alpha= keyword where the "
150
+ "function has one (fill_between, fill, axhspan, axvspan, hist)."
151
+ )
152
+
153
+ _ACCEPTED_COLOURS = (
154
+ "expected a GLE or matplotlib colour name ('red', 'k', 'C0', "
155
+ "'tab:blue'), a hex string ('#1f77b4'), a grey level string such as "
156
+ "'0.3', or a sequence of 3 or 4 numbers in [0, 1]."
157
+ )
158
+
159
+
160
+ def rgb_to_gle(color: Union[str, Sequence[float], np.ndarray]) -> str:
161
+ """
162
+ Convert a matplotlib color specification to a GLE color token.
163
+
164
+ A recognised GLE colour name is returned as that name (uppercased);
165
+ everything else is returned as an exact ``rgb255(r,g,b)`` expression, so
166
+ no requested colour is ever silently replaced by a different one.
167
+
168
+ Parameters
169
+ ----------
170
+ color : str, tuple, list or numpy.ndarray
171
+ Matplotlib color: a name, a single-letter code, a ``C0``..``C9``
172
+ cycle reference, a ``tab:`` name, a ``#RRGGBB``/``#RGB`` hex string,
173
+ a grey level as a number string in [0, 1] (``'0.3'``), an RGB
174
+ tuple/list/1-D array with components in [0, 1], or an already-formed
175
+ GLE colour expression.
176
+
177
+ Returns
178
+ -------
179
+ str
180
+ A GLE colour token: an uppercase GLE colour name, or ``rgb255(r,g,b)``.
181
+
182
+ Raises
183
+ ------
184
+ ValueError
185
+ For a string that is none of the forms above, a grey level outside
186
+ [0, 1], or a sequence of fewer than 3 numbers.
187
+ TypeError
188
+ For a value that is neither a string nor a sequence of numbers.
189
+
190
+ Examples
191
+ --------
192
+ >>> rgb_to_gle('blue')
193
+ 'BLUE'
194
+ >>> rgb_to_gle('b')
195
+ 'BLUE'
196
+ >>> rgb_to_gle((0.0, 0.0, 1.0))
197
+ 'rgb255(0,0,255)'
198
+ >>> rgb_to_gle('#8c8c8c')
199
+ 'rgb255(140,140,140)'
200
+ >>> rgb_to_gle('rgb255(140, 140, 140)')
201
+ 'rgb255(140,140,140)'
202
+ """
203
+ return _gle_color(color, "color")
204
+
205
+
206
+ def _gle_color(color: Any, arg: str) -> str:
207
+ """:func:`rgb_to_gle`, whose errors name ``arg``, the argument that held
208
+ ``color``, as a public function's caller wrote it."""
209
+ # Handle tuple (R, G, B) with values in [0, 1]; matplotlib also takes a
210
+ # 1-D array, or a single-row 2-D one such as ``cmap(x)[None]``.
211
+ if isinstance(color, np.ndarray) and color.ndim == 2 and color.shape[0] == 1:
212
+ color = color.reshape(-1)
213
+ if isinstance(color, (tuple, list)) or (
214
+ isinstance(color, np.ndarray)
215
+ and color.ndim == 1
216
+ and np.issubdtype(color.dtype, np.number)
217
+ ):
218
+ if len(color) == 4:
219
+ try:
220
+ opaque = float(color[3]) >= 1
221
+ except (TypeError, ValueError):
222
+ opaque = False
223
+ if not opaque:
224
+ warn_external(_ALPHA_NOT_APPLIED)
225
+ elif len(color) > 4:
226
+ warn_external(
227
+ f"Colour {color!r} has {len(color)} values; a colour sequence "
228
+ f"has 3 (RGB) or 4 (RGBA). Using the first three.",
229
+ )
230
+ if len(color) >= 3:
231
+ try:
232
+ return _rgb01_to_gle(color[0], color[1], color[2])
233
+ except (TypeError, ValueError):
234
+ pass
235
+
236
+ # Handle string colors
237
+ if isinstance(color, str):
238
+ text = color.strip()
239
+ color_lower = text.lower()
240
+ color_upper = text.upper()
241
+
242
+ # Already a GLE colour expression, e.g. round-tripped rgb255(...).
243
+ if _COLOR_EXPR_RE.match(text):
244
+ return re.sub(r"\s+", "", text)
245
+
246
+ # Check if it's already a GLE color name
247
+ if color_upper in _gle_color_names():
248
+ return color_upper
249
+
250
+ # British "grey" spellings of any named grey -- bare GREY, the
251
+ # numbered ramp GREY1/GREY5/GREY10..GREY90, DARKGREY, LIGHTGREY, etc.
252
+ # -- alias their "gray" equivalents. GLE itself defines these grey
253
+ # spellings as distinct colours (``defineOldGLEColors`` in
254
+ # color.cpp), matching the gray ramp's RGB values, and
255
+ # gle_color_rgb already treats GREY as an
256
+ # alias for GRAY when reading a ``.gle`` file; this mirrors that
257
+ # convention on the writing side so a name that round-trips one way
258
+ # round-trips the other too.
259
+ if "GREY" in color_upper:
260
+ gray_variant = color_upper.replace("GREY", "GRAY")
261
+ if gray_variant in _gle_color_names():
262
+ return gray_variant
263
+
264
+ # Check matplotlib color codes and named colors
265
+ if color_lower in MATPLOTLIB_TO_GLE_COLORS:
266
+ return MATPLOTLIB_TO_GLE_COLORS[color_lower]
267
+
268
+ # matplotlib default property cycle: 'C0'..'C9' / 'tab:blue' / ...
269
+ # 'C10' and beyond wrap round the ten, as in matplotlib.
270
+ cycle = re.fullmatch(r"c(\d+)", color_lower)
271
+ if cycle:
272
+ color_lower = f"c{int(cycle.group(1)) % 10}"
273
+ if color_lower in MATPLOTLIB_CYCLE_HEX:
274
+ return _hex_to_gle(MATPLOTLIB_CYCLE_HEX[color_lower], arg)
275
+
276
+ # Try hex color
277
+ if color_lower.startswith("#"):
278
+ return _hex_to_gle(color_lower, arg)
279
+
280
+ # matplotlib grey level: a string holding a number in [0, 1].
281
+ try:
282
+ level = float(text)
283
+ except ValueError:
284
+ pass
285
+ else:
286
+ if 0 <= level <= 1:
287
+ return _rgb01_to_gle(level, level, level)
288
+ raise ValueError(
289
+ f"Invalid grey level {color!r} for {arg}: a colour given as a "
290
+ f"number string must be within 0-1 (e.g. '0.3')."
291
+ )
292
+ # matplotlib colours with no GLE counterpart here.
293
+ if color_lower == "none" or color_lower.startswith("xkcd:"):
294
+ warn_external(
295
+ f"Colour {color!r} cannot be drawn here and is drawn in BLACK: "
296
+ + (
297
+ "GLE has no transparent colour for this element. Leave it "
298
+ "out to draw nothing."
299
+ if color_lower == "none"
300
+ else "gleplot has no table of xkcd colours. Pass the "
301
+ "colour's hex value instead."
302
+ )
303
+ )
304
+ return "BLACK"
305
+ raise ValueError(
306
+ f"Unrecognized colour {color!r} for {arg}: {_ACCEPTED_COLOURS}"
307
+ )
308
+ if isinstance(color, (tuple, list, np.ndarray)):
309
+ raise ValueError(
310
+ f"Unrecognized colour {color!r} for {arg}: {_ACCEPTED_COLOURS}"
311
+ )
312
+ raise TypeError(
313
+ f"Unrecognized colour {color!r} of type {type(color).__name__} for "
314
+ f"{arg}: {_ACCEPTED_COLOURS}"
315
+ )
316
+
317
+
318
+ def _stored_color(color: Any) -> Any:
319
+ """``color`` as a model field keeps it: an RGB(A) array or list becomes a
320
+ tuple of Python numbers, so the object compares with ``==`` and its
321
+ ``to_dict()`` survives JSON (which reads the tuple back as a list, and
322
+ this turns it back into a tuple). Anything else is returned unchanged."""
323
+ if isinstance(color, np.ndarray):
324
+ if color.ndim == 2 and color.shape[0] == 1:
325
+ color = color.reshape(-1)
326
+ color = color.tolist()
327
+ if isinstance(color, (list, tuple)):
328
+ return tuple(c.item() if isinstance(c, np.generic) else c for c in color)
329
+ return color
330
+
331
+
332
+ def _rgba_parts(color: Any) -> Tuple[Any, Any]:
333
+ """``(rgb, alpha)`` for an RGBA sequence or array, else ``(color, None)``.
334
+
335
+ For a caller that applies the alpha itself, so :func:`rgb_to_gle` does
336
+ not warn that it is dropped.
337
+ """
338
+ if isinstance(color, np.ndarray) and color.ndim == 2 and color.shape[0] == 1:
339
+ color = color.reshape(-1)
340
+ if isinstance(color, np.ndarray) and color.ndim == 1:
341
+ color = color.tolist()
342
+ if isinstance(color, (tuple, list)) and len(color) == 4:
343
+ return tuple(color[:3]), color[3]
344
+ return color, None
345
+
346
+
347
+ def _is_none_color(color: Any) -> bool:
348
+ """``True`` for matplotlib's ``'none'`` and for an RGBA colour whose alpha
349
+ is zero: both draw nothing."""
350
+ if isinstance(color, str):
351
+ return color.strip().lower() == "none"
352
+ _, alpha = _rgba_parts(color)
353
+ return bool(
354
+ isinstance(alpha, (int, float, np.integer, np.floating))
355
+ and not isinstance(alpha, bool)
356
+ and alpha <= 0
357
+ )
358
+
359
+
360
+ def rgb255_expr(r: int, g: int, b: int) -> str:
361
+ """Format an exact GLE colour expression from 0-255 components."""
362
+ return "rgb255({},{},{})".format(_clamp255(r), _clamp255(g), _clamp255(b))
363
+
364
+
365
+ def apply_alpha(color: str, alpha: Optional[float]) -> str:
366
+ """Compose a resolved GLE colour token with a transparency component.
367
+
368
+ ``color`` must already be a resolved GLE colour token, i.e. what
369
+ :func:`rgb_to_gle` returns (a colour name or an ``rgb255(...)``/``rgb(...)``
370
+ expression) -- this is what every caller (``FillSeries``/``Span``) stores.
371
+
372
+ When ``alpha`` is ``None`` or >= 1.0 (fully opaque), ``color`` is returned
373
+ completely unchanged -- this is what keeps every existing (opaque) figure's
374
+ generated ``.gle`` text byte-identical (gleplot's fixed-point contract):
375
+ the alpha path never touches a script that has nothing to be transparent.
376
+
377
+ Otherwise ``color`` is decomposed to its RGB components
378
+ (:func:`gle_color_to_rgb255`) and re-expressed as GLE's
379
+ ``rgba255(r,g,b,a)`` colour function (GLE >= 4.2), with ``a`` the 0-255
380
+ scaled alpha. Rendering a script containing ``rgba255`` requires GLE's
381
+ ``-cairo`` device flag (see ``gleplot.figure.Figure.requires_cairo`` and
382
+ ``gleplot.compiler.build_compile_args``); composing the colour here is
383
+ purely a *script-text* concern and is independent of that compile-time
384
+ flag decision, so this function never needs to know whether Cairo will
385
+ actually be used.
386
+
387
+ A token :func:`gle_color_to_rgb255` cannot decompose (notably: an
388
+ already-formed ``rgba255(...)``/``rgba(...)`` expression a user supplied
389
+ directly, or round-tripped from a parsed ``.gle`` file) is returned
390
+ unchanged -- it already carries its own alpha, so the separate ``alpha``
391
+ field is redundant for it, exactly like :func:`rgb_to_gle`'s "already a
392
+ GLE colour expression" pass-through.
393
+ """
394
+ if alpha is None:
395
+ return color
396
+ a = float(alpha)
397
+ if a >= 1.0:
398
+ return color
399
+ a = max(0.0, min(1.0, a))
400
+ rgb = gle_color_to_rgb255(color)
401
+ if rgb is None:
402
+ return color
403
+ r, g, b = rgb
404
+ return "rgba255({},{},{},{})".format(r, g, b, _clamp255(a * 255.0))
405
+
406
+
407
+ def gle_color_to_rgb255(color: str) -> Optional[Tuple[int, int, int]]:
408
+ """Best-effort inverse of :func:`rgb_to_gle`, for colour swatches.
409
+
410
+ Understands ``rgb255(r,g,b)``, ``rgb(r,g,b)`` (0-1 floats) and any GLE
411
+ colour name. Returns ``None`` when the token cannot be resolved.
412
+ """
413
+ if not isinstance(color, str):
414
+ return None
415
+ text = re.sub(r"\s+", "", color)
416
+ m = re.match(r"^(rgb255|rgb)\(([^()]*)\)$", text, re.IGNORECASE)
417
+ if m:
418
+ parts = [p for p in m.group(2).split(",") if p != ""]
419
+ if len(parts) < 3:
420
+ return None
421
+ try:
422
+ vals = [float(p) for p in parts[:3]]
423
+ except ValueError:
424
+ return None
425
+ if m.group(1).lower() == "rgb":
426
+ return tuple(_clamp255(round(v * 255.0)) for v in vals) # type: ignore[return-value]
427
+ return tuple(_clamp255(round(v)) for v in vals) # type: ignore[return-value]
428
+
429
+ return gle_color_rgb(text)
430
+
431
+
432
+ def _clamp255(value) -> int:
433
+ """Clamp a numeric component into the 0-255 integer range."""
434
+ try:
435
+ n = int(round(float(value)))
436
+ except (TypeError, ValueError):
437
+ return 0
438
+ return max(0, min(255, n))
439
+
440
+
441
+ def _rgb01_to_gle(r: float, g: float, b: float) -> str:
442
+ """Convert an RGB triple with components in [0, 1] to ``rgb255(...)``."""
443
+ return rgb255_expr(
444
+ _clamp255(float(r) * 255.0),
445
+ _clamp255(float(g) * 255.0),
446
+ _clamp255(float(b) * 255.0),
447
+ )
448
+
449
+
450
+ def _hex_to_gle(hex_color: str, arg: str) -> str:
451
+ """Convert a ``#RRGGBB`` or ``#RGB`` hex string to ``rgb255(...)``.
452
+
453
+ An alpha (``#RRGGBBAA`` or ``#RGBA``) below opaque warns that it is not
454
+ applied, as an RGBA sequence does.
455
+ """
456
+ digits = hex_color.lstrip("#").strip()
457
+
458
+ if len(digits) in (3, 4):
459
+ digits = "".join(ch * 2 for ch in digits)
460
+
461
+ if len(digits) in (6, 8):
462
+ try:
463
+ r, g, b = (int(digits[i : i + 2], 16) for i in (0, 2, 4))
464
+ alpha = int(digits[6:8] or "ff", 16)
465
+ except ValueError:
466
+ pass
467
+ else:
468
+ if alpha < 255:
469
+ warn_external(_ALPHA_NOT_APPLIED)
470
+ return rgb255_expr(r, g, b)
471
+ raise ValueError(
472
+ f"Unrecognized colour {hex_color!r} for {arg}: not a valid hex "
473
+ f"string (expected #RGB, #RGBA, #RRGGBB or #RRGGBBAA)."
474
+ )
475
+
476
+
477
+ def get_color_palette(name: str = "default") -> list:
478
+ """Get a preset color palette."""
479
+ palettes = {
480
+ "default": ["BLUE", "RED", "GREEN", "CYAN", "MAGENTA", "YELLOW"],
481
+ "dark": ["DARKBLUE", "DARKRED", "DARKGREEN", "DARKGRAY"],
482
+ "light": ["LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTGRAY"],
483
+ }
484
+ return palettes.get(name, palettes["default"])
485
+
486
+
487
+ #: GLE's fill patterns, from the ``op_def.cpp`` switch table of GLE 4.3.10.
488
+ #: Every one is diagonal hatching: ``SHADE`` runs like ``/``, ``RSHADE``
489
+ #: like ``\``, and ``GRID`` is both. The digit picks a line width and
490
+ #: spacing; ``2`` is the base pattern at half the spacing.
491
+ GLE_PATTERNS = frozenset(
492
+ f"{family}{suffix}"
493
+ for family in ("SHADE", "RSHADE", "GRID")
494
+ for suffix in ("", "1", "2", "3", "4", "5")
495
+ )
496
+
497
+ _HATCH_FAMILIES = {"/": "SHADE", "\\": "RSHADE", "x": "GRID", "X": "GRID"}
498
+
499
+
500
+ def hatch_to_gle(hatch: str) -> Optional[str]:
501
+ """The GLE pattern for a matplotlib hatch string, or ``None``.
502
+
503
+ A string of one repeated ``/``, ``\\`` or ``x`` (``X``) maps to
504
+ ``SHADE``, ``RSHADE`` or ``GRID``; two or more characters, matplotlib's
505
+ denser hatch, map to the ``2`` variant. GLE has no horizontal,
506
+ vertical, dotted or circular pattern, so anything else is ``None``.
507
+ """
508
+ family = _HATCH_FAMILIES.get(hatch[:1])
509
+ if family is None or any(_HATCH_FAMILIES.get(ch) != family for ch in hatch):
510
+ return None
511
+ return family if len(hatch) == 1 else family + "2"
512
+
513
+
514
+ # ---------------------------------------------------------------------------
515
+ # Colors
516
+ # ---------------------------------------------------------------------------
517
+ #
518
+ # Transcribed from GLE 4.3.10 ``src/gle/color.cpp`` lines ~131-299
519
+ # (``GLEColorList::defineGrays`` + ``GLEColorList::defineSVGColors``, called
520
+ # from ``defineDefaultColors``), with RGB values decoded from the
521
+ # ``0x01RRGGBB``-format hex literals in ``src/gle/color.h`` lines 66-218
522
+ # (the leading ``0x01`` byte is GLE's internal "color defined" flag, not part
523
+ # of the RGB value). Keys are the canonical uppercase GLE color names as
524
+ # ``defineColor`` registers them; GLE itself is case-insensitive.
525
+ COLORS: Dict[str, Tuple[int, int, int]] = {
526
+ "ALICEBLUE": (240, 248, 255),
527
+ "ANTIQUEWHITE": (250, 235, 215),
528
+ "AQUA": (0, 255, 255),
529
+ "AQUAMARINE": (127, 255, 212),
530
+ "AZURE": (240, 255, 255),
531
+ "BEIGE": (245, 245, 220),
532
+ "BISQUE": (255, 228, 196),
533
+ "BLACK": (0, 0, 0),
534
+ "BLANCHEDALMOND": (255, 235, 205),
535
+ "BLUE": (0, 0, 255),
536
+ "BLUEVIOLET": (138, 43, 226),
537
+ "BROWN": (165, 42, 42),
538
+ "BURLYWOOD": (222, 184, 135),
539
+ "CADETBLUE": (95, 158, 160),
540
+ "CHARTREUSE": (127, 255, 0),
541
+ "CHOCOLATE": (210, 105, 30),
542
+ "CORAL": (255, 127, 80),
543
+ "CORNFLOWERBLUE": (100, 149, 237),
544
+ "CORNSILK": (255, 248, 220),
545
+ "CRIMSON": (220, 20, 60),
546
+ "CYAN": (0, 255, 255),
547
+ "DARKBLUE": (0, 0, 139),
548
+ "DARKCYAN": (0, 139, 139),
549
+ "DARKGOLDENROD": (184, 134, 11),
550
+ "DARKGRAY": (169, 169, 169),
551
+ "DARKGREEN": (0, 100, 0),
552
+ "DARKKHAKI": (189, 183, 107),
553
+ "DARKMAGENTA": (139, 0, 139),
554
+ "DARKOLIVEGREEN": (85, 107, 47),
555
+ "DARKORANGE": (255, 140, 0),
556
+ "DARKORCHID": (153, 50, 204),
557
+ "DARKRED": (139, 0, 0),
558
+ "DARKSALMON": (233, 150, 122),
559
+ "DARKSEAGREEN": (143, 188, 143),
560
+ "DARKSLATEBLUE": (72, 61, 139),
561
+ "DARKSLATEGRAY": (47, 79, 79),
562
+ "DARKTURQUOISE": (0, 206, 209),
563
+ "DARKVIOLET": (148, 0, 211),
564
+ "DEEPPINK": (255, 20, 147),
565
+ "DEEPSKYBLUE": (0, 191, 255),
566
+ "DIMGRAY": (105, 105, 105),
567
+ "DODGERBLUE": (30, 144, 255),
568
+ "FIREBRICK": (178, 34, 34),
569
+ "FLORALWHITE": (255, 250, 240),
570
+ "FORESTGREEN": (34, 139, 34),
571
+ "FUCHSIA": (255, 0, 255),
572
+ "GAINSBORO": (220, 220, 220),
573
+ "GHOSTWHITE": (248, 248, 255),
574
+ "GOLD": (255, 215, 0),
575
+ "GOLDENROD": (218, 165, 32),
576
+ "GRAY": (128, 128, 128),
577
+ "GRAY1": (253, 253, 253),
578
+ "GRAY10": (200, 200, 200),
579
+ "GRAY20": (175, 175, 175),
580
+ "GRAY30": (150, 150, 150),
581
+ "GRAY40": (125, 125, 125),
582
+ "GRAY5": (240, 240, 240),
583
+ "GRAY50": (100, 100, 100),
584
+ "GRAY60": (75, 75, 75),
585
+ "GRAY70": (50, 50, 50),
586
+ "GRAY80": (25, 25, 25),
587
+ "GRAY90": (6, 6, 6),
588
+ "GREEN": (0, 128, 0),
589
+ "GREENYELLOW": (173, 255, 47),
590
+ "HONEYDEW": (240, 255, 240),
591
+ "HOTPINK": (255, 105, 180),
592
+ "INDIANRED": (205, 92, 92),
593
+ "INDIGO": (75, 0, 130),
594
+ "IVORY": (255, 255, 240),
595
+ "KHAKI": (240, 230, 140),
596
+ "LAVENDER": (230, 230, 250),
597
+ "LAVENDERBLUSH": (255, 240, 245),
598
+ "LAWNGREEN": (124, 252, 0),
599
+ "LEMONCHIFFON": (255, 250, 205),
600
+ "LIGHTBLUE": (173, 216, 230),
601
+ "LIGHTCORAL": (240, 128, 128),
602
+ "LIGHTCYAN": (224, 255, 255),
603
+ "LIGHTGOLDENRODYELLOW": (250, 250, 210),
604
+ "LIGHTGRAY": (211, 211, 211),
605
+ "LIGHTGREEN": (144, 238, 144),
606
+ "LIGHTPINK": (255, 182, 193),
607
+ "LIGHTSALMON": (255, 160, 122),
608
+ "LIGHTSEAGREEN": (32, 178, 170),
609
+ "LIGHTSKYBLUE": (135, 206, 250),
610
+ "LIGHTSLATEGRAY": (119, 136, 153),
611
+ "LIGHTSTEELBLUE": (176, 196, 222),
612
+ "LIGHTYELLOW": (255, 255, 224),
613
+ "LIME": (0, 255, 0),
614
+ "LIMEGREEN": (50, 205, 50),
615
+ "LINEN": (250, 240, 230),
616
+ "MAGENTA": (255, 0, 255),
617
+ "MAROON": (128, 0, 0),
618
+ "MEDIUMAQUAMARINE": (102, 205, 170),
619
+ "MEDIUMBLUE": (0, 0, 205),
620
+ "MEDIUMORCHID": (186, 85, 211),
621
+ "MEDIUMPURPLE": (147, 112, 219),
622
+ "MEDIUMSEAGREEN": (60, 179, 113),
623
+ "MEDIUMSLATEBLUE": (123, 104, 238),
624
+ "MEDIUMSPRINGGREEN": (0, 250, 154),
625
+ "MEDIUMTURQUOISE": (72, 209, 204),
626
+ "MEDIUMVIOLETRED": (199, 21, 133),
627
+ "MIDNIGHTBLUE": (25, 25, 112),
628
+ "MINTCREAM": (245, 255, 250),
629
+ "MISTYROSE": (255, 228, 225),
630
+ "MOCCASIN": (255, 228, 181),
631
+ "NAVAJOWHITE": (255, 222, 173),
632
+ "NAVY": (0, 0, 128),
633
+ "OLDLACE": (253, 245, 230),
634
+ "OLIVE": (128, 128, 0),
635
+ "OLIVEDRAB": (107, 142, 35),
636
+ "ORANGE": (255, 165, 0),
637
+ "ORANGERED": (255, 69, 0),
638
+ "ORCHID": (218, 112, 214),
639
+ "PALEGOLDENROD": (238, 232, 170),
640
+ "PALEGREEN": (152, 251, 152),
641
+ "PALETURQUOISE": (175, 238, 238),
642
+ "PALEVIOLETRED": (219, 112, 147),
643
+ "PAPAYAWHIP": (255, 239, 213),
644
+ "PEACHPUFF": (255, 218, 185),
645
+ "PERU": (205, 133, 63),
646
+ "PINK": (255, 192, 203),
647
+ "PLUM": (221, 160, 221),
648
+ "POWDERBLUE": (176, 224, 230),
649
+ "PURPLE": (128, 0, 128),
650
+ "RED": (255, 0, 0),
651
+ "ROSYBROWN": (188, 143, 143),
652
+ "ROYALBLUE": (65, 105, 225),
653
+ "SADDLEBROWN": (139, 69, 19),
654
+ "SALMON": (250, 128, 114),
655
+ "SANDYBROWN": (244, 164, 96),
656
+ "SEAGREEN": (46, 139, 87),
657
+ "SEASHELL": (255, 245, 238),
658
+ "SIENNA": (160, 82, 45),
659
+ "SILVER": (192, 192, 192),
660
+ "SKYBLUE": (135, 206, 235),
661
+ "SLATEBLUE": (106, 90, 205),
662
+ "SLATEGRAY": (112, 128, 144),
663
+ "SNOW": (255, 250, 250),
664
+ "SPRINGGREEN": (0, 255, 127),
665
+ "STEELBLUE": (70, 130, 180),
666
+ "TAN": (210, 180, 140),
667
+ "TEAL": (0, 128, 128),
668
+ "THISTLE": (216, 191, 216),
669
+ "TOMATO": (255, 99, 71),
670
+ "TURQUOISE": (64, 224, 208),
671
+ "VIOLET": (238, 130, 238),
672
+ "WHEAT": (245, 222, 179),
673
+ "WHITE": (255, 255, 255),
674
+ "WHITESMOKE": (245, 245, 245),
675
+ "YELLOW": (255, 255, 0),
676
+ "YELLOWGREEN": (154, 205, 50),
677
+ }
678
+
679
+
680
+ def gle_color_rgb(name: str) -> Optional[Tuple[int, int, int]]:
681
+ """Look up a GLE color name's RGB triple, case-insensitively.
682
+
683
+ British "GREY" spellings (GREY, DARKGREY, LIGHTSLATEGREY, ...) are
684
+ accepted as aliases for their "GRAY" forms: GLE's legacy color table
685
+ supports them, and hand-written .gle files use them, so the tolerant
686
+ parser must too. Returns ``None`` if ``name`` is not recognized.
687
+ """
688
+ key = str(name).strip().upper()
689
+ hit = COLORS.get(key)
690
+ if hit is None and "GREY" in key:
691
+ hit = COLORS.get(key.replace("GREY", "GRAY"))
692
+ return hit
693
+
694
+
695
+ def nearest_gle_color(r: int, g: int, b: int) -> str:
696
+ """Find the GLE color name nearest to an RGB triple.
697
+
698
+ Tries an exact match first; falls back to the color with the smallest
699
+ Euclidean distance in RGB space. Ties are broken by the first match in
700
+ :data:`COLORS`' iteration order (stable across calls since dicts
701
+ preserve insertion order).
702
+
703
+ Nothing in gleplot's own emission path snaps a color: an arbitrary color
704
+ is written out exactly as ``rgb255(r,g,b)`` (see
705
+ :func:`gleplot.colors.rgb_to_gle`). This helper exists for callers who
706
+ *want* a named approximation -- pass its result back in as the color.
707
+ """
708
+ target = (int(r), int(g), int(b))
709
+ for name, rgb in COLORS.items():
710
+ if rgb == target:
711
+ return name
712
+
713
+ # COLORS is never empty, so the first iteration always replaces this.
714
+ best_name = "BLACK"
715
+ best_dist = None
716
+ for name, (cr, cg, cb) in COLORS.items():
717
+ dist = (cr - target[0]) ** 2 + (cg - target[1]) ** 2 + (cb - target[2]) ** 2
718
+ if best_dist is None or dist < best_dist:
719
+ best_dist = dist
720
+ best_name = name
721
+ return best_name