spongebob-cli 0.3.2__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.
Files changed (54) hide show
  1. spongebob/__init__.py +1 -0
  2. spongebob/__main__.py +375 -0
  3. spongebob/analyzer/__init__.py +9 -0
  4. spongebob/analyzer/__main__.py +39 -0
  5. spongebob/analyzer/analyzer.py +234 -0
  6. spongebob/bus/__init__.py +6 -0
  7. spongebob/bus/bus.py +38 -0
  8. spongebob/diagnose/__init__.py +29 -0
  9. spongebob/diagnose/__main__.py +111 -0
  10. spongebob/diagnose/adapter.py +82 -0
  11. spongebob/diagnose/models.py +79 -0
  12. spongebob/diagnose/probes.py +129 -0
  13. spongebob/engine/__init__.py +26 -0
  14. spongebob/engine/__main__.py +25 -0
  15. spongebob/engine/models.py +161 -0
  16. spongebob/engine/simulator.py +196 -0
  17. spongebob/export/__init__.py +25 -0
  18. spongebob/export/exporter.py +354 -0
  19. spongebob/meter/__init__.py +7 -0
  20. spongebob/meter/__main__.py +50 -0
  21. spongebob/meter/meter.py +140 -0
  22. spongebob/narrator/__init__.py +25 -0
  23. spongebob/narrator/narrator.py +352 -0
  24. spongebob/plugins/__init__.py +28 -0
  25. spongebob/plugins/loader.py +308 -0
  26. spongebob/plugins/models.py +47 -0
  27. spongebob/scenarios/__init__.py +25 -0
  28. spongebob/scenarios/builtin/__init__.py +1 -0
  29. spongebob/scenarios/builtin/control-line.toml +33 -0
  30. spongebob/scenarios/builtin/crowded-wifi.toml +33 -0
  31. spongebob/scenarios/builtin/flaky-last-mile.toml +33 -0
  32. spongebob/scenarios/builtin/long-haul-orbit.toml +33 -0
  33. spongebob/scenarios/builtin/overloaded-uplink.toml +35 -0
  34. spongebob/scenarios/builtin/tunnel-burst.toml +38 -0
  35. spongebob/scenarios/loader.py +205 -0
  36. spongebob/scenarios/models.py +55 -0
  37. spongebob/scenarios/runner.py +24 -0
  38. spongebob/ui/__init__.py +23 -0
  39. spongebob/ui/__main__.py +11 -0
  40. spongebob/ui/app.py +88 -0
  41. spongebob/ui/canvas.py +147 -0
  42. spongebob/ui/diagnose_screen.py +525 -0
  43. spongebob/ui/export_modal.py +158 -0
  44. spongebob/ui/menu_screen.py +159 -0
  45. spongebob/ui/replay.py +209 -0
  46. spongebob/ui/settings_screen.py +101 -0
  47. spongebob/ui/simulate_screen.py +566 -0
  48. spongebob/ui/theme.py +364 -0
  49. spongebob/ui/visualize_screen.py +411 -0
  50. spongebob_cli-0.3.2.dist-info/METADATA +78 -0
  51. spongebob_cli-0.3.2.dist-info/RECORD +54 -0
  52. spongebob_cli-0.3.2.dist-info/WHEEL +5 -0
  53. spongebob_cli-0.3.2.dist-info/entry_points.txt +2 -0
  54. spongebob_cli-0.3.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,205 @@
1
+ from __future__ import annotations
2
+
3
+ import importlib.resources
4
+ import tomllib
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from spongebob.engine.models import Flow, Hop
9
+
10
+ from .models import MAX_HOPS, MAX_PACKETS, MAX_SCENARIO_BYTES, Scenario
11
+
12
+ _TOP_LEVEL_KEYS = frozenset({"scenario", "flow", "hop"})
13
+ _SCENARIO_REQUIRED = frozenset({"name", "description"})
14
+ _FLOW_REQUIRED = frozenset({"packets", "interval_ms", "size_bytes"})
15
+ _FLOW_ALLOWED = _FLOW_REQUIRED | frozenset({"seed"})
16
+ _HOP_REQUIRED = frozenset({"name", "delay_ms", "jitter_ms", "loss_pct"})
17
+ _HOP_OPTIONAL = frozenset(
18
+ {
19
+ "jitter_model",
20
+ "bandwidth_kbps",
21
+ "queue_limit_packets",
22
+ "loss_model",
23
+ "p_good_to_bad",
24
+ "p_bad_to_good",
25
+ "loss_good",
26
+ "loss_bad",
27
+ }
28
+ )
29
+ _HOP_ALLOWED = _HOP_REQUIRED | _HOP_OPTIONAL
30
+
31
+
32
+ def _check_keys(
33
+ table: dict[str, Any],
34
+ section: str,
35
+ required: frozenset[str],
36
+ allowed: frozenset[str],
37
+ ) -> None:
38
+ for key in table:
39
+ if key not in allowed:
40
+ raise ValueError(f"Unknown key {key!r} in [{section}]")
41
+ for req in sorted(required):
42
+ if req not in table:
43
+ raise ValueError(f"Missing required key {req!r} in [{section}]")
44
+
45
+
46
+ def _parse_scenario_dict(data: dict[str, Any]) -> Scenario:
47
+ for key in data:
48
+ if key not in _TOP_LEVEL_KEYS:
49
+ raise ValueError(f"Unknown top-level key {key!r}")
50
+
51
+ for req_section in ("scenario", "flow", "hop"):
52
+ if req_section not in data:
53
+ raise ValueError(f"Missing required section {req_section!r}")
54
+
55
+ scen_tbl = data["scenario"]
56
+ if not isinstance(scen_tbl, dict):
57
+ raise ValueError("[scenario] must be a table")
58
+ _check_keys(scen_tbl, "scenario", _SCENARIO_REQUIRED, _SCENARIO_REQUIRED)
59
+
60
+ flow_tbl = data["flow"]
61
+ if not isinstance(flow_tbl, dict):
62
+ raise ValueError("[flow] must be a table")
63
+ _check_keys(flow_tbl, "flow", _FLOW_REQUIRED, _FLOW_ALLOWED)
64
+
65
+ packets = flow_tbl["packets"]
66
+ if not isinstance(packets, bool) and isinstance(packets, int) and packets > MAX_PACKETS:
67
+ raise ValueError(f"packets must be <= {MAX_PACKETS}, got {packets}")
68
+ flow = Flow(
69
+ packet_count=packets,
70
+ interval_ms=flow_tbl["interval_ms"],
71
+ size_bytes=flow_tbl["size_bytes"],
72
+ )
73
+ seed = flow_tbl.get("seed")
74
+
75
+ hop_list = data["hop"]
76
+ if not isinstance(hop_list, list) or not hop_list:
77
+ raise ValueError("[[hop]] must be a non-empty array of tables")
78
+ if len(hop_list) > MAX_HOPS:
79
+ raise ValueError(f"scenario hops must be <= {MAX_HOPS}, got {len(hop_list)}")
80
+
81
+ hops: list[Hop] = []
82
+ for idx, hop_tbl in enumerate(hop_list):
83
+ if not isinstance(hop_tbl, dict):
84
+ raise ValueError(f"[[hop]] entry {idx} must be a table")
85
+ _check_keys(hop_tbl, f"hop[{idx}]", _HOP_REQUIRED, _HOP_ALLOWED)
86
+ hops.append(Hop(**hop_tbl))
87
+
88
+ return Scenario(
89
+ name=scen_tbl["name"],
90
+ description=scen_tbl["description"],
91
+ flow=flow,
92
+ hops=tuple(hops),
93
+ seed=seed,
94
+ )
95
+
96
+
97
+ def loads_scenario(text: str) -> Scenario:
98
+ """Parse and validate a scenario from a TOML string."""
99
+ raw_bytes = text.encode("utf-8")
100
+ if len(raw_bytes) > MAX_SCENARIO_BYTES:
101
+ raise ValueError(
102
+ f"Scenario size {len(raw_bytes)} bytes exceeds limit of {MAX_SCENARIO_BYTES} bytes"
103
+ )
104
+ try:
105
+ data = tomllib.loads(text)
106
+ except tomllib.TOMLDecodeError as exc:
107
+ raise ValueError(f"Invalid TOML: {exc}") from exc
108
+ return _parse_scenario_dict(data)
109
+
110
+
111
+ def load_scenario(path: str | Path) -> Scenario:
112
+ """Load and validate a scenario from a user-specified TOML file."""
113
+ file_path = Path(path)
114
+ if not file_path.is_file():
115
+ raise FileNotFoundError(f"Scenario file not found: {file_path}")
116
+ size = file_path.stat().st_size
117
+ if size > MAX_SCENARIO_BYTES:
118
+ raise ValueError(
119
+ f"Scenario file {file_path} ({size} bytes) exceeds limit of {MAX_SCENARIO_BYTES} bytes"
120
+ )
121
+ raw = file_path.read_bytes()
122
+ if len(raw) > MAX_SCENARIO_BYTES:
123
+ raise ValueError(
124
+ f"Scenario file {file_path} ({len(raw)} bytes) exceeds limit of {MAX_SCENARIO_BYTES} bytes"
125
+ )
126
+ return loads_scenario(raw.decode("utf-8"))
127
+
128
+
129
+ def _toml_str(value: str) -> str:
130
+ escaped = (
131
+ value.replace("\\", "\\\\")
132
+ .replace('"', '\\"')
133
+ .replace("\n", "\\n")
134
+ .replace("\r", "\\r")
135
+ .replace("\t", "\\t")
136
+ )
137
+ return f'"{escaped}"'
138
+
139
+
140
+ def dump_scenario(scenario: Scenario) -> str:
141
+ """Serialize a Scenario to deterministic TOML."""
142
+ lines: list[str] = [
143
+ "[scenario]",
144
+ f"name = {_toml_str(scenario.name)}",
145
+ f"description = {_toml_str(scenario.description)}",
146
+ "",
147
+ "[flow]",
148
+ f"packets = {scenario.flow.packet_count}",
149
+ f"interval_ms = {scenario.flow.interval_ms}",
150
+ f"size_bytes = {scenario.flow.size_bytes}",
151
+ ]
152
+ if scenario.seed is not None:
153
+ lines.append(f"seed = {scenario.seed}")
154
+
155
+ for hop in scenario.hops:
156
+ lines.extend(
157
+ [
158
+ "",
159
+ "[[hop]]",
160
+ f"name = {_toml_str(hop.name)}",
161
+ f"delay_ms = {hop.delay_ms}",
162
+ f"jitter_ms = {hop.jitter_ms}",
163
+ f"loss_pct = {hop.loss_pct}",
164
+ f"jitter_model = {_toml_str(hop.jitter_model)}",
165
+ ]
166
+ )
167
+ if hop.bandwidth_kbps is not None:
168
+ lines.append(f"bandwidth_kbps = {hop.bandwidth_kbps}")
169
+ if hop.queue_limit_packets is not None:
170
+ lines.append(f"queue_limit_packets = {hop.queue_limit_packets}")
171
+ lines.extend(
172
+ [
173
+ f"loss_model = {_toml_str(hop.loss_model)}",
174
+ f"p_good_to_bad = {hop.p_good_to_bad}",
175
+ f"p_bad_to_good = {hop.p_bad_to_good}",
176
+ f"loss_good = {hop.loss_good}",
177
+ f"loss_bad = {hop.loss_bad}",
178
+ ]
179
+ )
180
+
181
+ lines.append("")
182
+ return "\n".join(lines)
183
+
184
+
185
+ def list_builtin_scenarios() -> list[str]:
186
+ """Return sorted names of built-in scenarios (without .toml extension)."""
187
+ root = importlib.resources.files("spongebob.scenarios.builtin")
188
+ names = [
189
+ entry.name[:-5]
190
+ for entry in root.iterdir()
191
+ if entry.name.endswith(".toml")
192
+ ]
193
+ return sorted(names)
194
+
195
+
196
+ def load_builtin_scenario(name: str) -> Scenario:
197
+ """Load a built-in scenario by name using importlib.resources."""
198
+ root = importlib.resources.files("spongebob.scenarios.builtin")
199
+ target = root.joinpath(f"{name}.toml")
200
+ if not target.is_file():
201
+ available = ", ".join(list_builtin_scenarios())
202
+ raise FileNotFoundError(
203
+ f"Unknown built-in scenario {name!r}. Available: {available}"
204
+ )
205
+ return loads_scenario(target.read_text(encoding="utf-8"))
@@ -0,0 +1,55 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+
5
+ from spongebob.analyzer import Finding
6
+ from spongebob.engine.models import Event, Flow, Hop
7
+ from spongebob.meter import Metrics
8
+ from spongebob.narrator import Line
9
+
10
+ MAX_SCENARIO_BYTES = 65_536
11
+ MAX_HOPS = 12
12
+ MAX_PACKETS = 100_000
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Scenario:
17
+ """Validated network impairment scenario definition."""
18
+
19
+ name: str
20
+ description: str
21
+ flow: Flow
22
+ hops: tuple[Hop, ...]
23
+ seed: int | None = None
24
+
25
+ def __post_init__(self) -> None:
26
+ if not isinstance(self.name, str) or not self.name.strip():
27
+ raise ValueError("scenario name must be a non-empty string")
28
+ if not isinstance(self.description, str) or not self.description.strip():
29
+ raise ValueError("scenario description must be a non-empty string")
30
+ if not isinstance(self.flow, Flow):
31
+ raise TypeError(f"flow must be a Flow, got {type(self.flow).__name__}")
32
+ if self.flow.packet_count > MAX_PACKETS:
33
+ raise ValueError(
34
+ f"packets must be <= {MAX_PACKETS}, got {self.flow.packet_count}"
35
+ )
36
+ if not self.hops:
37
+ raise ValueError("scenario must define at least one hop")
38
+ if len(self.hops) > MAX_HOPS:
39
+ raise ValueError(f"scenario hops must be <= {MAX_HOPS}, got {len(self.hops)}")
40
+ for hop in self.hops:
41
+ if not isinstance(hop, Hop):
42
+ raise TypeError(f"hops must be Hop instances, got {type(hop).__name__}")
43
+ if self.seed is not None and (isinstance(self.seed, bool) or not isinstance(self.seed, int)):
44
+ raise TypeError(f"seed must be an integer or None, got {type(self.seed).__name__}")
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class ScenarioRunResult:
49
+ """Full pipeline output from executing a Scenario."""
50
+
51
+ scenario: Scenario
52
+ events: list[Event]
53
+ metrics: Metrics
54
+ findings: list[Finding]
55
+ narrator_lines: list[Line]
@@ -0,0 +1,24 @@
1
+ from __future__ import annotations
2
+
3
+ from spongebob.analyzer import analyze
4
+ from spongebob.engine import simulate
5
+ from spongebob.meter import measure
6
+ from spongebob.narrator import narrate
7
+
8
+ from .models import Scenario, ScenarioRunResult
9
+
10
+
11
+ def run_scenario(scenario: Scenario, seed: int | None = None) -> ScenarioRunResult:
12
+ """Execute a Scenario through engine, meter, analyzer, and narrator."""
13
+ effective_seed = scenario.seed if seed is None else seed
14
+ events = simulate(flow=scenario.flow, path=scenario.hops, seed=effective_seed)
15
+ metrics = measure(events, packet_size_bytes=scenario.flow.size_bytes)
16
+ findings = analyze(events, scenario.hops)
17
+ narrator_lines = narrate(findings, metrics, events, seed=effective_seed)
18
+ return ScenarioRunResult(
19
+ scenario=scenario,
20
+ events=events,
21
+ metrics=metrics,
22
+ findings=findings,
23
+ narrator_lines=narrator_lines,
24
+ )
@@ -0,0 +1,23 @@
1
+ from .app import SimulatorApp
2
+ from .canvas import BrailleCanvas, detect_truecolor, rgb_to_ansi256
3
+ from .replay import (
4
+ DropEffect,
5
+ ParticleState,
6
+ PulseTarget,
7
+ ReplayState,
8
+ compute_replay_state,
9
+ select_pulse_target,
10
+ )
11
+
12
+ __all__ = [
13
+ "BrailleCanvas",
14
+ "DropEffect",
15
+ "ParticleState",
16
+ "PulseTarget",
17
+ "ReplayState",
18
+ "SimulatorApp",
19
+ "compute_replay_state",
20
+ "detect_truecolor",
21
+ "rgb_to_ansi256",
22
+ "select_pulse_target",
23
+ ]
@@ -0,0 +1,11 @@
1
+ from __future__ import annotations
2
+
3
+ from spongebob.ui.app import SimulatorApp
4
+
5
+
6
+ def main() -> None:
7
+ SimulatorApp().run()
8
+
9
+
10
+ if __name__ == "__main__":
11
+ main()
spongebob/ui/app.py ADDED
@@ -0,0 +1,88 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ from textual.app import App
6
+
7
+ from spongebob.analyzer import Finding, LatencyKind, analyze
8
+ from spongebob.engine import Flow, Hop, default_path, simulate
9
+ from spongebob.engine.models import Event
10
+ from spongebob.meter import Metrics, measure
11
+ from spongebob.narrator import Narrator
12
+ from spongebob.plugins import PluginRegistry, load_plugins_from_dir
13
+ from spongebob.ui import theme
14
+ from spongebob.ui.diagnose_screen import DiagnoseScreen
15
+ from spongebob.ui.menu_screen import MenuScreen
16
+ from spongebob.ui.settings_screen import SettingsScreen
17
+ from spongebob.ui.simulate_screen import SimulateScreen
18
+ from spongebob.ui.visualize_screen import VisualizeScreen
19
+
20
+
21
+ class SimulatorApp(App[None]):
22
+ """Terminal UI application for Spongebob (Network Impairment Simulator)."""
23
+
24
+ TITLE = "Spongebob"
25
+ SUB_TITLE = "Network Impairment Simulator (v0.3.2)"
26
+ CSS = theme.BASE_THEME_CSS
27
+
28
+ def __init__(self, plugins_dir: str | Path | None = None) -> None:
29
+ super().__init__()
30
+ self.narrator_enabled: bool = True
31
+ self.plugin_registry: PluginRegistry = PluginRegistry()
32
+ self.narrator = Narrator()
33
+ self.last_run: tuple[list[Hop], list[Event], Metrics, list[Finding]] | None = None
34
+ self.last_run_latency_kind: LatencyKind = "one_way"
35
+ if plugins_dir is not None:
36
+ self.load_plugins_folder(plugins_dir)
37
+
38
+ def load_plugins_folder(self, plugins_dir: str | Path) -> PluginRegistry:
39
+ reg = load_plugins_from_dir(plugins_dir)
40
+ self.plugin_registry = reg
41
+ self.narrator = Narrator(
42
+ extra_finding_pools=reg.finding_jokes or None,
43
+ extra_drop_pools=reg.drop_jokes or None,
44
+ )
45
+ return reg
46
+
47
+ def on_mount(self) -> None:
48
+ self.push_screen(MenuScreen())
49
+
50
+ def toggle_narrator(self) -> bool:
51
+ self.narrator_enabled = not self.narrator_enabled
52
+ return self.narrator_enabled
53
+
54
+ def open_simulate(self) -> None:
55
+ self.push_screen(SimulateScreen())
56
+
57
+ def open_diagnose(self) -> None:
58
+ self.push_screen(DiagnoseScreen())
59
+
60
+ def open_settings(self) -> None:
61
+ self.push_screen(SettingsScreen())
62
+
63
+ def open_visualize(self) -> None:
64
+ if self.last_run is None:
65
+ path = default_path(delay_ms=15.0, jitter_ms=5.0, loss_pct=2.0)
66
+ flow = Flow(packet_count=40, interval_ms=15.0, size_bytes=64)
67
+ events = simulate(flow, path=path, seed=42)
68
+ metrics = measure(events, packet_size_bytes=flow.size_bytes)
69
+ findings = analyze(events, path)
70
+ self.last_run = (path, events, metrics, findings)
71
+ self.last_run_latency_kind = "one_way"
72
+ path, events, metrics, findings = self.last_run
73
+ mode = "diagnose" if self.last_run_latency_kind == "rtt" else "simulate"
74
+ narrator_lines = (
75
+ self.narrator.narrate(findings, metrics, events, mode=mode)
76
+ if self.narrator_enabled
77
+ else []
78
+ )
79
+ self.push_screen(
80
+ VisualizeScreen(
81
+ path=path,
82
+ events=events,
83
+ findings=findings,
84
+ narrator_lines=narrator_lines,
85
+ narrator_enabled=self.narrator_enabled,
86
+ latency_kind=self.last_run_latency_kind,
87
+ )
88
+ )
spongebob/ui/canvas.py ADDED
@@ -0,0 +1,147 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from typing import Iterable
5
+
6
+ RGB = tuple[int, int, int]
7
+
8
+ # Braille dot bitmasks for (dx in {0, 1}, dy in {0, 1, 2, 3})
9
+ _BRAILLE_MAP: tuple[tuple[int, int, int, int], tuple[int, int, int, int]] = (
10
+ (0x01, 0x02, 0x04, 0x40),
11
+ (0x08, 0x10, 0x20, 0x80),
12
+ )
13
+
14
+
15
+ def detect_truecolor() -> bool:
16
+ """Return True if the environment advertises 24-bit truecolor support."""
17
+ colorterm = os.environ.get("COLORTERM", "").lower()
18
+ return colorterm in ("truecolor", "24bit")
19
+
20
+
21
+ def rgb_to_ansi256(r: int, g: int, b: int) -> int:
22
+ """Convert an 8-bit RGB triple to the nearest xterm 256-color index."""
23
+ r = max(0, min(255, int(r)))
24
+ g = max(0, min(255, int(g)))
25
+ b = max(0, min(255, int(b)))
26
+ if r == g == b:
27
+ if r < 8:
28
+ return 16
29
+ if r > 248:
30
+ return 231
31
+ return round(((r - 8) / 247) * 24) + 232
32
+ ri = round(r / 255 * 5)
33
+ gi = round(g / 255 * 5)
34
+ bi = round(b / 255 * 5)
35
+ return 16 + 36 * ri + 6 * gi + bi
36
+
37
+
38
+ class BrailleCanvas:
39
+ """Pure 2x4-subpixel Braille canvas with per-cell 24-bit RGB color and fade."""
40
+
41
+ def __init__(self, cols: int, rows: int) -> None:
42
+ if cols < 1 or rows < 1:
43
+ raise ValueError(f"cols and rows must be >= 1, got ({cols}, {rows})")
44
+ self.cols = cols
45
+ self.rows = rows
46
+ self.pixel_width = cols * 2
47
+ self.pixel_height = rows * 4
48
+ self._masks: list[list[int]] = [[0] * cols for _ in range(rows)]
49
+ self._colors: list[list[RGB | None]] = [[None] * cols for _ in range(rows)]
50
+
51
+ def clear(self) -> None:
52
+ """Clear all sub-pixels and colors."""
53
+ for r in range(self.rows):
54
+ for c in range(self.cols):
55
+ self._masks[r][c] = 0
56
+ self._colors[r][c] = None
57
+
58
+ def set_pixel(self, x: int, y: int, color: RGB = (255, 255, 255)) -> None:
59
+ """Set a sub-pixel at (x, y) with the given RGB color (bounds-safe)."""
60
+ if x < 0 or y < 0 or x >= self.pixel_width or y >= self.pixel_height:
61
+ return
62
+ col = x >> 1
63
+ row = y >> 2
64
+ dx = x & 1
65
+ dy = y & 3
66
+ self._masks[row][col] |= _BRAILLE_MAP[dx][dy]
67
+ self._colors[row][col] = color
68
+
69
+ def clear_pixel(self, x: int, y: int) -> None:
70
+ """Clear a sub-pixel at (x, y) (bounds-safe)."""
71
+ if x < 0 or y < 0 or x >= self.pixel_width or y >= self.pixel_height:
72
+ return
73
+ col = x >> 1
74
+ row = y >> 2
75
+ dx = x & 1
76
+ dy = y & 3
77
+ self._masks[row][col] &= ~_BRAILLE_MAP[dx][dy]
78
+ if self._masks[row][col] == 0:
79
+ self._colors[row][col] = None
80
+
81
+ def get_char(self, col: int, row: int) -> str:
82
+ """Return the Unicode Braille character at cell (col, row)."""
83
+ if col < 0 or row < 0 or col >= self.cols or row >= self.rows:
84
+ return chr(0x2800)
85
+ return chr(0x2800 + self._masks[row][col])
86
+
87
+ def get_color(self, col: int, row: int) -> RGB | None:
88
+ """Return the RGB color at cell (col, row), or None if empty."""
89
+ if col < 0 or row < 0 or col >= self.cols or row >= self.rows:
90
+ return None
91
+ return self._colors[row][col]
92
+
93
+ def fade(self, factor: float = 0.72, cutoff: int = 10) -> None:
94
+ """Monotonically dim all cell colors by factor; clear cells below cutoff."""
95
+ if factor <= 0.0:
96
+ self.clear()
97
+ return
98
+ clamped_factor = min(1.0, factor)
99
+ for r in range(self.rows):
100
+ for c in range(self.cols):
101
+ color = self._colors[r][c]
102
+ if color is None:
103
+ continue
104
+ nr = int(color[0] * clamped_factor)
105
+ ng = int(color[1] * clamped_factor)
106
+ nb = int(color[2] * clamped_factor)
107
+ if max(nr, ng, nb) < cutoff:
108
+ self._masks[r][c] = 0
109
+ self._colors[r][c] = None
110
+ else:
111
+ self._colors[r][c] = (nr, ng, nb)
112
+
113
+ def draw_line(self, x0: int, y0: int, x1: int, y1: int, color: RGB) -> None:
114
+ """Draw a sub-pixel line using Bresenham's algorithm."""
115
+ dx = abs(x1 - x0)
116
+ dy = -abs(y1 - y0)
117
+ sx = 1 if x0 < x1 else -1
118
+ sy = 1 if y0 < y1 else -1
119
+ err = dx + dy
120
+ x, y = x0, y0
121
+ while True:
122
+ self.set_pixel(x, y, color)
123
+ if x == x1 and y == y1:
124
+ break
125
+ e2 = 2 * err
126
+ if e2 >= dy:
127
+ err += dy
128
+ x += sx
129
+ if e2 <= dx:
130
+ err += dx
131
+ y += sy
132
+
133
+ def draw_circle(self, cx: int, cy: int, radius: int, color: RGB) -> None:
134
+ """Draw a filled sub-pixel disc."""
135
+ r2 = radius * radius
136
+ for dy in range(-radius, radius + 1):
137
+ for dx in range(-radius, radius + 1):
138
+ if dx * dx + dy * dy <= r2:
139
+ self.set_pixel(cx + dx, cy + dy, color)
140
+
141
+ def iter_rows(self) -> Iterable[list[tuple[str, RGB | None]]]:
142
+ """Yield each row as a list of (braille_char, rgb_or_none) tuples."""
143
+ for r in range(self.rows):
144
+ yield [
145
+ (chr(0x2800 + self._masks[r][c]), self._colors[r][c])
146
+ for c in range(self.cols)
147
+ ]