pixelplotlib 0.1.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.
pixelplotlib/rich.py ADDED
@@ -0,0 +1,139 @@
1
+ """Draw figures with `Rich <https://github.com/Textualize/rich>`_ in any colour terminal.
2
+
3
+ Each terminal cell shows two vertically stacked pixels using the upper half block
4
+ character ``▀`` (foreground = top pixel, background = bottom pixel), so this works
5
+ wherever Rich does, with no sixel support needed. Figures are re-rendered at the size
6
+ they are drawn at, so fonts and one-pixel lines stay sharp at any terminal width::
7
+
8
+ from rich import print
9
+ print(fig) # a Figure is a Rich renderable
10
+ print(Panel(Plot(fig, width=60))) # or wrap it to choose the size
11
+
12
+ Requires the ``rich`` extra: ``pip install "pixelplotlib[rich]"``.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from collections.abc import Iterator
18
+
19
+ import numpy as np
20
+ from rich.color import Color
21
+ from rich.console import Console, ConsoleOptions
22
+ from rich.measure import Measurement
23
+ from rich.segment import Segment
24
+ from rich.style import Style
25
+
26
+ from .figure import Figure
27
+
28
+ __all__ = ["Plot", "halfblock_lines"]
29
+
30
+ #: Narrowest width (in cells) a :class:`Plot` without an explicit width shrinks to.
31
+ MIN_WIDTH = 16
32
+
33
+ _UPPER_HALF = "\u2580"
34
+
35
+
36
+ class Plot:
37
+ """A Rich renderable that draws a :class:`~pixelplotlib.Figure` with half blocks.
38
+
39
+ Parameters
40
+ ----------
41
+ figure:
42
+ The figure to draw. It is rendered whenever the renderable is printed, so later
43
+ changes to the figure show up the next time it is drawn.
44
+ width, height:
45
+ Size in terminal cells (one cell is one pixel wide and two pixels tall). If only
46
+ one is given the other follows the figure's aspect ratio. By default the figure
47
+ is drawn at its native resolution, shrunk to fit the available width (and height,
48
+ when the container has a fixed height such as a :class:`rich.layout.Layout`).
49
+ expand:
50
+ Fill the available width (and height, if the container fixes it) instead.
51
+ """
52
+
53
+ def __init__(self, figure: Figure, width: int | None = None, height: int | None = None,
54
+ *, expand: bool = False):
55
+ if not isinstance(figure, Figure):
56
+ raise TypeError(f"expected a pixelplotlib Figure, got {type(figure).__name__}")
57
+ self.figure = figure
58
+ self.width = width
59
+ self.height = height
60
+ self.expand = expand
61
+
62
+ def pixel_size(self, max_width: int, max_height: int | None = None) -> tuple[int, int]:
63
+ """``(width, height)`` in pixels to render at, given the space available in cells."""
64
+ fw, fh = self.figure.size
65
+ max_width = max(max_width, 1)
66
+ w, h = self.width, self.height
67
+ if w is None and h is None:
68
+ w = max_width if self.expand else fw
69
+ h = max_height if self.expand else None
70
+ if w is None:
71
+ w = round(h * 2 * fw / fh)
72
+ w = max(min(w, max_width), 1)
73
+ px_h = max(h * 2 if h is not None else round(w * fh / fw), 1)
74
+ if self.height is None and max_height is not None and px_h > 2 * max_height:
75
+ px_h = 2 * max(max_height, 1)
76
+ if self.width is None and not self.expand:
77
+ w = max(min(w, round(px_h * fw / fh)), 1)
78
+ return w, px_h
79
+
80
+ def __rich_console__(self, console: Console, options: ConsoleOptions) -> Iterator[Segment]:
81
+ size = self.pixel_size(options.max_width, options.height)
82
+ pixels = self.figure.to_array(size=size)
83
+ for line in halfblock_lines(pixels):
84
+ yield from line
85
+ yield Segment.line()
86
+
87
+ def __rich_measure__(self, console: Console, options: ConsoleOptions) -> Measurement:
88
+ max_width = options.max_width
89
+ if self.width is not None:
90
+ width = min(self.width, max_width)
91
+ return Measurement(width, width)
92
+ if self.expand:
93
+ return Measurement(max_width, max_width)
94
+ natural = self.pixel_size(max_width)[0]
95
+ return Measurement(min(MIN_WIDTH, natural), natural)
96
+
97
+ def __repr__(self) -> str:
98
+ return f"<Plot {self.figure!r} width={self.width} height={self.height}>"
99
+
100
+
101
+ def halfblock_lines(pixels: np.ndarray) -> list[list[Segment]]:
102
+ """Convert an ``(H, W, 3)`` uint8 image into ``ceil(H / 2)`` lines of Rich segments.
103
+
104
+ Runs of identical cells share one segment. An odd last pixel row is drawn over the
105
+ terminal's default background.
106
+ """
107
+ pixels = np.asarray(pixels, dtype=np.uint8)
108
+ if pixels.ndim != 3 or pixels.shape[2] < 3:
109
+ raise ValueError(f"expected an (H, W, 3) image, got shape {pixels.shape}")
110
+ packed = (pixels[..., 0].astype(np.int64) << 16) | (pixels[..., 1].astype(np.int64) << 8)
111
+ packed |= pixels[..., 2]
112
+ if packed.shape[0] % 2:
113
+ packed = np.vstack([packed, np.full((1, packed.shape[1]), -1, dtype=np.int64)])
114
+ top, bottom = packed[0::2], packed[1::2]
115
+ styles: dict[tuple[int, int], tuple[str, Style]] = {}
116
+ lines = []
117
+ for t, b in zip(top, bottom):
118
+ starts = np.flatnonzero((np.diff(t, prepend=-2) != 0) | (np.diff(b, prepend=-2) != 0))
119
+ lengths = np.diff(np.append(starts, len(t)))
120
+ line = []
121
+ for key, n in zip(zip(t[starts].tolist(), b[starts].tolist()), lengths.tolist()):
122
+ if key not in styles:
123
+ styles[key] = _cell_style(*key)
124
+ char, style = styles[key]
125
+ line.append(Segment(char * n, style))
126
+ lines.append(line)
127
+ return lines
128
+
129
+
130
+ def _color(packed: int) -> Color:
131
+ return Color.from_rgb(packed >> 16, (packed >> 8) & 255, packed & 255)
132
+
133
+
134
+ def _cell_style(top: int, bottom: int) -> tuple[str, Style]:
135
+ if bottom < 0:
136
+ return _UPPER_HALF, Style(color=_color(top))
137
+ if top == bottom:
138
+ return " ", Style(bgcolor=_color(top))
139
+ return _UPPER_HALF, Style(color=_color(top), bgcolor=_color(bottom))
pixelplotlib/sixel.py ADDED
@@ -0,0 +1,147 @@
1
+ """Sixel encoding for showing figures directly in a terminal.
2
+
3
+ Sixel is a DEC bitmap format understood by terminals such as xterm (``-ti vt340``),
4
+ foot, WezTerm, mlterm, Konsole, iTerm2, Windows Terminal and tmux (3.4+). Each
5
+ "sixel" character encodes a column of six vertical pixels for one colour register.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import re
12
+ import sys
13
+ from functools import lru_cache
14
+ from typing import TextIO
15
+
16
+ import numpy as np
17
+
18
+ __all__ = ["encode", "terminal_supports_sixel", "write"]
19
+
20
+ #: Environment variable that forces sixel output on (``1``) or off (``0``).
21
+ ENV_VAR = "PIXELPLOTLIB_SIXEL"
22
+
23
+ _DA1_RESPONSE = re.compile(rb"\x1b\[\?([\d;]*)c")
24
+
25
+
26
+ def encode(image, max_colors: int = 256) -> str:
27
+ """Encode an ``(H, W, 3|4)`` uint8 array or :class:`PIL.Image.Image` as a sixel string.
28
+
29
+ Images with more than ``max_colors`` distinct colours are quantized first (pixel-art
30
+ figures rarely need to be). The alpha channel, if any, is ignored.
31
+ """
32
+ rgb = np.asarray(image)
33
+ if rgb.ndim != 3 or rgb.shape[2] not in (3, 4):
34
+ raise ValueError(f"expected an (H, W, 3) or (H, W, 4) image, got shape {rgb.shape}")
35
+ rgb = np.ascontiguousarray(rgb[..., :3], dtype=np.uint8)
36
+ h, w = rgb.shape[:2]
37
+ colors, index = _palette_index(rgb, max_colors)
38
+
39
+ # P2=1: pixels not set by any sixel keep the terminal background.
40
+ out = ["\x1bP0;1;0q", f'"1;1;{w};{h}']
41
+ for i, (r, g, b) in enumerate(colors.tolist()):
42
+ out.append(f"#{i};2;{round(r * 100 / 255)};{round(g * 100 / 255)};{round(b * 100 / 255)}")
43
+ for y0 in range(0, h, 6):
44
+ band = index[y0:y0 + 6]
45
+ weights = (1 << np.arange(band.shape[0]))[:, None]
46
+ layers = []
47
+ for c in np.unique(band).tolist():
48
+ bits = ((band == c) * weights).sum(axis=0)
49
+ bits = bits[:np.flatnonzero(bits)[-1] + 1]
50
+ layers.append(f"#{c}{_run_length(bits)}")
51
+ out.append("$".join(layers))
52
+ if y0 + 6 < h:
53
+ out.append("-")
54
+ out.append("\x1b\\")
55
+ return "".join(out)
56
+
57
+
58
+ def _palette_index(rgb: np.ndarray, max_colors: int) -> tuple[np.ndarray, np.ndarray]:
59
+ """Return ``(colors, index)``: an ``(N, 3)`` palette and per-pixel register numbers."""
60
+ packed = (rgb[..., 0].astype(np.uint32) << 16) | (rgb[..., 1].astype(np.uint32) << 8)
61
+ packed |= rgb[..., 2]
62
+ values, index = np.unique(packed, return_inverse=True)
63
+ if len(values) > max_colors:
64
+ from PIL import Image
65
+
66
+ quantized = Image.fromarray(rgb, "RGB").quantize(max_colors, dither=Image.Dither.NONE)
67
+ return _palette_index(np.asarray(quantized.convert("RGB")), max_colors)
68
+ colors = np.stack([(values >> 16) & 255, (values >> 8) & 255, values & 255], axis=1)
69
+ return colors.astype(np.uint8), index.reshape(rgb.shape[:2])
70
+
71
+
72
+ def _run_length(bits: np.ndarray) -> str:
73
+ """Sixel characters for one colour layer, with ``!<n><char>`` run-length compression."""
74
+ starts = np.flatnonzero(np.diff(bits, prepend=-1))
75
+ lengths = np.diff(np.append(starts, len(bits)))
76
+ parts = []
77
+ for value, n in zip(bits[starts].tolist(), lengths.tolist()):
78
+ ch = chr(63 + value)
79
+ parts.append(f"!{n}{ch}" if n > 3 else ch * n)
80
+ return "".join(parts)
81
+
82
+
83
+ def write(image, stream: TextIO | None = None) -> None:
84
+ """Write ``image`` as sixel graphics to ``stream`` (default ``sys.stdout``)."""
85
+ stream = stream if stream is not None else sys.stdout
86
+ stream.write(encode(image) + "\n")
87
+ stream.flush()
88
+
89
+
90
+ def terminal_supports_sixel(stream: TextIO | None = None) -> bool:
91
+ """Best-effort check whether ``stream`` (default ``sys.stdout``) can display sixels.
92
+
93
+ The ``PIXELPLOTLIB_SIXEL`` environment variable (``1``/``0``) overrides detection.
94
+ Otherwise ``stream`` must be a TTY whose terminal reports sixel support (attribute
95
+ ``4``) in its reply to a Primary Device Attributes query.
96
+ """
97
+ env = os.environ.get(ENV_VAR)
98
+ if env is not None:
99
+ return env.strip().lower() not in ("", "0", "false", "no", "off")
100
+ stream = stream if stream is not None else sys.stdout
101
+ try:
102
+ if not stream.isatty():
103
+ return False
104
+ except (AttributeError, ValueError):
105
+ return False
106
+ return _query_terminal()
107
+
108
+
109
+ def _parse_da1(response: bytes) -> bool:
110
+ """Whether a Primary Device Attributes reply (``ESC [ ? 62 ; 4 ; ... c``) lists sixel."""
111
+ match = _DA1_RESPONSE.search(response)
112
+ return bool(match) and "4" in match.group(1).decode().split(";")
113
+
114
+
115
+ @lru_cache(maxsize=1)
116
+ def _query_terminal(timeout: float = 0.2) -> bool:
117
+ try:
118
+ import select
119
+ import termios
120
+ import tty
121
+ except ImportError: # Windows: rely on PIXELPLOTLIB_SIXEL
122
+ return False
123
+ try:
124
+ fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
125
+ except OSError:
126
+ return False
127
+ response = b""
128
+ try:
129
+ old = termios.tcgetattr(fd)
130
+ try:
131
+ tty.setcbreak(fd)
132
+ os.write(fd, b"\x1b[c")
133
+ while not _DA1_RESPONSE.search(response):
134
+ ready, _, _ = select.select([fd], [], [], timeout)
135
+ if not ready:
136
+ break
137
+ chunk = os.read(fd, 256)
138
+ if not chunk:
139
+ break
140
+ response += chunk
141
+ finally:
142
+ termios.tcsetattr(fd, termios.TCSADRAIN, old)
143
+ except (OSError, termios.error):
144
+ return False
145
+ finally:
146
+ os.close(fd)
147
+ return _parse_da1(response)
pixelplotlib/styles.py ADDED
@@ -0,0 +1,347 @@
1
+ """Visual themes ("styles") that emulate retro hardware."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator, Sequence
6
+ from contextlib import contextmanager
7
+ from dataclasses import dataclass, field, replace
8
+ from typing import Any
9
+
10
+ import numpy as np
11
+
12
+ from . import palettes
13
+ from .colormaps import CmapLike, Ramp, build_ramp
14
+ from .colors import ColorLike, ColorSystem, shade
15
+ from .fonts import BitmapFont, get_font
16
+
17
+ Fill = ColorLike | tuple[ColorLike, ColorLike] | None
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Style:
22
+ """A complete description of a pixel-art look.
23
+
24
+ Colors may be anything accepted by :func:`pixelplotlib.colors.parse_color`.
25
+ Fields named ``*_fill`` accept either a color or a ``(top, bottom)`` tuple
26
+ for a dithered vertical gradient.
27
+ """
28
+
29
+ name: str
30
+ size: tuple[int, int] = (256, 224)
31
+ scale: int = 3
32
+ palette: Sequence[ColorLike] | None = None
33
+ bits: int | None = None
34
+
35
+ background: Fill = "#000000"
36
+ foreground: ColorLike = "#FFFFFF"
37
+ series: Sequence[ColorLike] = ("red", "blue", "green", "yellow")
38
+ linestyles: Sequence[str] = ("-",)
39
+ markers: Sequence[str] = ("o",)
40
+ fill_alphas: Sequence[float] = (1.0,)
41
+
42
+ panel: bool = False
43
+ panel_fill: Fill = None
44
+ panel_border: Sequence[ColorLike] = ()
45
+ panel_radius: int = 0
46
+ panel_shadow: ColorLike | None = None
47
+ plot_fill: Fill = None
48
+ legend_fill: Fill = None
49
+
50
+ frame_color: ColorLike | None = None
51
+ grid_color: ColorLike | None = None
52
+ grid_linestyle: str = ":"
53
+ text_shadow: ColorLike | None = None
54
+ title_color: ColorLike | None = None
55
+ uppercase: bool = False
56
+
57
+ font: str | BitmapFont = "5x7"
58
+ tick_font: str | BitmapFont = "5x7"
59
+
60
+ line_width: int = 1
61
+ line_shadow: ColorLike | None = None
62
+ line_halo: ColorLike | None = None
63
+ marker_outline: ColorLike | None = None
64
+ bar_shading: bool = False
65
+ bar_outline: str | None = "auto"
66
+
67
+ cmap: CmapLike = "viridis"
68
+ cmap_levels: int = 16
69
+ gradient_levels: int = 8
70
+ dither: bool = True
71
+
72
+ pad: int = 2
73
+ tick_length: int = 2
74
+ extra: dict[str, Any] = field(default_factory=dict)
75
+
76
+ # ------------------------------------------------------------------ helpers
77
+ def replace(self, **changes) -> Style:
78
+ """Return a copy of this style with some fields changed."""
79
+ return replace(self, **changes)
80
+
81
+ @property
82
+ def colors(self) -> ColorSystem:
83
+ cache = self.__dict__.get("_colors")
84
+ if cache is None:
85
+ cache = ColorSystem(self.palette, self.bits)
86
+ object.__setattr__(self, "_colors", cache)
87
+ return cache
88
+
89
+ def color(self, c: ColorLike | None, default: ColorLike | None = None):
90
+ """Resolve a user color to a displayable RGB tuple (``None`` stays ``None``)."""
91
+ if c is None:
92
+ if default is None:
93
+ return None
94
+ c = default
95
+ if isinstance(c, str):
96
+ s = c.strip()
97
+ if len(s) >= 2 and s[0] == "C" and s[1:].isdigit():
98
+ return self.series_color(int(s[1:]))
99
+ low = s.lower()
100
+ if low in ("fg", "foreground"):
101
+ return self.color(self.foreground)
102
+ if low in ("bg", "background"):
103
+ use_panel = self.panel and self.panel_fill is not None
104
+ bg = self.panel_fill if use_panel else self.background
105
+ return self.color(bg[0] if isinstance(bg, tuple) else bg)
106
+ if isinstance(c, (int, np.integer)) and self.palette is not None:
107
+ return self.colors.snap(self.palette[int(c) % len(self.palette)])
108
+ return self.colors.snap(c)
109
+
110
+ @property
111
+ def fg(self):
112
+ return self.color(self.foreground)
113
+
114
+ @property
115
+ def text_color(self):
116
+ return self.fg
117
+
118
+ def series_color(self, i: int):
119
+ return self.color(self.series[i % len(self.series)])
120
+
121
+ def shade(self, rgb, amount: float):
122
+ """Lighter/darker version of ``rgb`` that is still displayable."""
123
+ return self.colors.snap(shade(rgb, amount))
124
+
125
+ def ramp(self, cmap: CmapLike | None = None, levels: int | None = None) -> Ramp:
126
+ return build_ramp(cmap if cmap is not None else self.cmap, self.colors,
127
+ levels or self.cmap_levels)
128
+
129
+ def get_font(self):
130
+ return get_font(self.font)
131
+
132
+ def get_tick_font(self):
133
+ return get_font(self.tick_font)
134
+
135
+ def text(self, s) -> str:
136
+ s = "" if s is None else str(s)
137
+ return s.upper() if self.uppercase else s
138
+
139
+
140
+ NES_STYLE = Style(
141
+ name="8bit",
142
+ size=(256, 224),
143
+ scale=3,
144
+ palette=palettes.NES,
145
+ background="#000000",
146
+ foreground="#FCFCFC",
147
+ series=("#F83800", "#3CBCFC", "#B8F818", "#F8B800", "#F878F8", "#00E8D8", "#FCA044",
148
+ "#9878F8"),
149
+ markers=("o", "s", "^", "D", "x", "+", "heart", "star"),
150
+ panel=True,
151
+ panel_fill="#000000",
152
+ panel_border=("#FCFCFC",),
153
+ panel_radius=1,
154
+ frame_color="#FCFCFC",
155
+ grid_color="#7C7C7C",
156
+ title_color="#F8B800",
157
+ bar_outline="#000000",
158
+ cmap="viridis",
159
+ cmap_levels=9,
160
+ )
161
+
162
+ SNES_STYLE = Style(
163
+ name="16bit",
164
+ size=(320, 224),
165
+ scale=3,
166
+ bits=5,
167
+ background=("#183080", "#000010"),
168
+ foreground="#F8F8F8",
169
+ series=("#F85858", "#58C8F8", "#78F070", "#F8D030", "#F898F8", "#F8A040", "#B8F858",
170
+ "#C8A0F8"),
171
+ markers=("o", "D", "s", "^", "*", "v", "heart", "star"),
172
+ panel=True,
173
+ panel_fill=("#4868D8", "#101850"),
174
+ panel_border=("#000010", "#F8F8F8", "#A8A8C0"),
175
+ panel_radius=3,
176
+ panel_shadow="#000008",
177
+ legend_fill=("#384898", "#101840"),
178
+ frame_color="#E0E0F0",
179
+ grid_color="#7890E8",
180
+ text_shadow="#000020",
181
+ title_color="#F8E070",
182
+ line_shadow="#000028",
183
+ marker_outline="#000020",
184
+ bar_shading=True,
185
+ cmap="viridis",
186
+ cmap_levels=16,
187
+ gradient_levels=12,
188
+ )
189
+
190
+ GAMEBOY_STYLE = Style(
191
+ name="gameboy",
192
+ size=(160, 144),
193
+ scale=4,
194
+ palette=palettes.GAMEBOY,
195
+ background="#9BBC0F",
196
+ foreground="#0F380F",
197
+ series=("#0F380F", "#306230"),
198
+ linestyles=("-", "-", "--", "--", ":", ":"),
199
+ markers=("o", "s", "^", "x", "D", "+"),
200
+ fill_alphas=(1.0, 0.5, 0.75, 0.25),
201
+ line_halo="bg",
202
+ frame_color="#0F380F",
203
+ grid_color="#8BAC0F",
204
+ grid_linestyle=":",
205
+ bar_outline="#0F380F",
206
+ cmap="gameboy",
207
+ tick_font="3x5",
208
+ )
209
+
210
+ PICO8_STYLE = Style(
211
+ name="pico8",
212
+ size=(192, 160),
213
+ scale=4,
214
+ palette=palettes.PICO8,
215
+ background="#000000",
216
+ foreground="#FFF1E8",
217
+ series=("#FF004D", "#29ADFF", "#00E436", "#FFEC27", "#FF77A8", "#FFA300", "#83769C",
218
+ "#FFCCAA"),
219
+ markers=("o", "s", "^", "D", "x", "+"),
220
+ plot_fill="#1D2B53",
221
+ frame_color="#C2C3C7",
222
+ grid_color="#5F574F",
223
+ title_color="#FFEC27",
224
+ bar_outline="auto",
225
+ cmap="pico",
226
+ font="3x5",
227
+ tick_font="3x5",
228
+ )
229
+
230
+ C64_STYLE = Style(
231
+ name="c64",
232
+ size=(320, 200),
233
+ scale=3,
234
+ palette=palettes.C64,
235
+ background="#6C5EB5",
236
+ foreground="#6C5EB5",
237
+ series=("#FFFFFF", "#B8C76F", "#9AD284", "#9A6759", "#70A4B2", "#6F4F25", "#6F3D86",
238
+ "#959595"),
239
+ markers=("o", "s", "^", "D", "x", "+"),
240
+ panel=True,
241
+ panel_fill="#352879",
242
+ frame_color="#6C5EB5",
243
+ grid_color="#6C5EB5",
244
+ title_color="#FFFFFF",
245
+ uppercase=True,
246
+ bar_outline=None,
247
+ cmap="viridis",
248
+ cmap_levels=9,
249
+ )
250
+
251
+ CGA_STYLE = Style(
252
+ name="cga",
253
+ size=(320, 200),
254
+ scale=3,
255
+ palette=palettes.CGA,
256
+ background="#000000",
257
+ foreground="#FFFFFF",
258
+ series=("#55FFFF", "#FF55FF", "#FFFFFF"),
259
+ linestyles=("-", "-", "-", "--", "--", "--"),
260
+ markers=("o", "s", "^", "x", "D", "+"),
261
+ frame_color="#FFFFFF",
262
+ grid_color="#55FFFF",
263
+ title_color="#FF55FF",
264
+ bar_outline="#000000",
265
+ cmap="gray",
266
+ )
267
+
268
+ ONEBIT_STYLE = Style(
269
+ name="1bit",
270
+ size=(256, 192),
271
+ scale=3,
272
+ palette=palettes.ONE_BIT,
273
+ background="#FFFFFF",
274
+ foreground="#000000",
275
+ series=("#000000",),
276
+ linestyles=("-", "--", ":", "-."),
277
+ markers=("o", "s", "^", "x", "D", "+"),
278
+ fill_alphas=(0.5, 0.25, 0.75, 1.0),
279
+ line_halo="bg",
280
+ marker_outline="bg",
281
+ panel=True,
282
+ panel_fill="#FFFFFF",
283
+ panel_border=("#000000",),
284
+ panel_shadow="#000000",
285
+ frame_color="#000000",
286
+ grid_color="#000000",
287
+ bar_outline="#000000",
288
+ cmap="gray",
289
+ )
290
+
291
+ STYLES: dict[str, Style] = {
292
+ "8bit": NES_STYLE,
293
+ "nes": NES_STYLE,
294
+ "16bit": SNES_STYLE,
295
+ "snes": SNES_STYLE,
296
+ "gameboy": GAMEBOY_STYLE,
297
+ "gb": GAMEBOY_STYLE,
298
+ "pico8": PICO8_STYLE,
299
+ "c64": C64_STYLE,
300
+ "cga": CGA_STYLE,
301
+ "1bit": ONEBIT_STYLE,
302
+ "mac": ONEBIT_STYLE,
303
+ }
304
+
305
+ _current: list[Style] = [NES_STYLE]
306
+
307
+
308
+ def get_style(style: str | Style | None = None) -> Style:
309
+ """Return a :class:`Style` by name (or the current default when ``None``)."""
310
+ if style is None:
311
+ return _current[-1]
312
+ if isinstance(style, Style):
313
+ return style
314
+ try:
315
+ return STYLES[style.lower()]
316
+ except KeyError:
317
+ raise ValueError(f"unknown style {style!r}; choose from {available()}") from None
318
+
319
+
320
+ def available() -> list[str]:
321
+ """Names of the built-in styles (without aliases)."""
322
+ seen, names = set(), []
323
+ for name, st in STYLES.items():
324
+ if id(st) not in seen:
325
+ seen.add(id(st))
326
+ names.append(name)
327
+ return names
328
+
329
+
330
+ def use(style: str | Style) -> None:
331
+ """Set the default style for new figures."""
332
+ _current[-1] = get_style(style)
333
+
334
+
335
+ def register(style: Style, name: str | None = None) -> None:
336
+ """Register a custom style under ``name`` (defaults to ``style.name``)."""
337
+ STYLES[(name or style.name).lower()] = style
338
+
339
+
340
+ @contextmanager
341
+ def context(style: str | Style) -> Iterator[Style]:
342
+ """Temporarily use a different default style."""
343
+ _current.append(get_style(style))
344
+ try:
345
+ yield _current[-1]
346
+ finally:
347
+ _current.pop()