okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
8.3 KiB231 linesraw
1"""The look of the launch screens: the monitor's colours, rules and key hints, and the one list widget they share.
2
3Colours are the monitor's own (strata_cli/monitor.py: background #0e1113, panel #161a1d, text #eef1f3, muted #8e979f, accent
4#34d399, warning yellow); the launch mock-up adds a selection tint (#1f2a27), a warning amber and a soft red. Everything is plain
5text in a column of lines, as the monitor's text views are: a heading in the accent colour, a dim rule, the content, a dim
6explanation line and a dim line of key hints.
7"""
8
9from __future__ import annotations
10
11import os
12import sys
13from dataclasses import dataclass
14from typing import Any
15
16from rich.text import Text
17from textual.widgets import Static
18
19BG, PANEL, FG, MUTE = "#0e1113", "#161a1d", "#eef1f3", "#8e979f"
20ACCENT, WARN, BAD, SEL, RULE = "#34d399", "#f5c56b", "#f28b82", "#1f2a27", "#3a4146"
21
22
23@dataclass(frozen=True)
24class Palette:
25    """The colours of one theme. The launch screens are dark; the monitor's Connect view and its pop-ups follow the monitor's light theme."""
26
27    bg: str
28    panel: str
29    fg: str
30    mute: str
31    accent: str
32    warn: str
33    bad: str
34    sel: str
35    rule: str
36
37
38DARK = Palette(BG, PANEL, FG, MUTE, ACCENT, WARN, BAD, SEL, RULE)
39# Light: every text colour reads at 4.5:1 or better on the white panel (tests/terminal/test_tuiqa_monitor.py computes it).
40LIGHT = Palette("#f9fafb", "#ffffff", "#221e1f", "#5b5f66", "#0a6b4a", "#8a5a00", "#b01a2e", "#cfeadf", "#c9ced3")
41
42
43def unicode_ok() -> bool:
44    if os.environ.get("TERM") == "dumb":
45        return False
46    from strata_cli import consoleinfo
47    if consoleinfo.legacy_console():          # the classic Windows console's font has no arrows, check marks or block glyphs ...
48        if os.environ.get("STRATA_GLYPHS", "").strip().lower() in ("ascii", "legacy"):
49            return False
50        if consoleinfo.classic_style()["mode"] != "full":         # ... unless the window's font could be switched to Cascadia Mono
51            return False
52    enc = getattr(sys.stdout, "encoding", None) or "utf-8"
53    try:
54        "›─↑↓•█░".encode(enc)
55        return True
56    except (LookupError, UnicodeEncodeError):
57        return False
58
59
60class Glyphs:
61    def __init__(self, unicode: bool | None = None):
62        u = unicode_ok() if unicode is None else unicode
63        self.unicode = u
64        self.cursor = "›" if u else ">"      # (U+203A is in Consolas too, but one rule for the whole screen is simpler)
65        self.rule = "─" if u else "-"
66        self.updown = "↑↓" if u else "Up/Down"
67        self.dot = "·" if u else "-"
68        self.full = "█" if u else "#"
69        self.empty = "░" if u else "."
70        self.tick = "✓" if u else "ok"
71        self.mask = "•" if u else "*"
72        self.arrow = "→" if u else "->"
73
74
75CSS = f"""
76Screen {{ background: {BG}; color: {FG}; }}
77#shell {{ width: 100%; height: 100%; background: {PANEL}; padding: 0 1; }}
78#head {{ height: 1; }}
79#rule1, #rule2 {{ height: 1; color: {RULE}; }}
80#body {{ height: 1fr; overflow-y: auto; }}
81#explain {{ height: auto; max-height: 4; color: {MUTE}; }}
82#hints {{ height: auto; max-height: 3; color: {MUTE}; }}
83#message {{ height: auto; max-height: 3; color: {MUTE}; }}
84Menu {{ height: auto; max-height: 100%; }}
85.field {{ height: 3; border: solid {ACCENT}; display: none; }}
86.field.slim {{ height: 1; border: none; padding: 0 1; background: {SEL}; }}
87#cmdbox {{ height: 6; border-top: solid {RULE}; scrollbar-size-vertical: 1; }}
88.field.open {{ display: block; }}
89Input {{ background: {PANEL}; color: {FG}; }}
90"""
91
92
93@dataclass
94class Cell:
95    text: str
96    style: str = ""
97
98
99@dataclass
100class Item:
101    cells: list[Cell | str]
102    key: Any = None
103    enabled: bool = True
104    style: str = ""          # whole-row style when not selected
105
106
107def cell(c: Cell | str) -> Cell:
108    return c if isinstance(c, Cell) else Cell(str(c))
109
110
111class Menu(Static):
112    """A column list with a cursor: `items` is a list of `Item`, `columns` a list of (title, width) (width 0 = the rest)."""
113
114    DEFAULT_CSS = "Menu { height: auto; text-wrap: nowrap; text-overflow: clip; }"
115
116    def __init__(self, columns: list[tuple[str, int]] | None = None, *, glyphs: Glyphs | None = None, id: str | None = None,
117                 window: int = 0, palette: Palette | None = None) -> None:
118        super().__init__("", id=id, markup=False)
119        self.palette = palette or DARK
120        self.columns = columns or []
121        self.items: list[Item] = []
122        self.index = 0
123        self.top = 0
124        self.window = window            # 0 = show all rows
125        self.g = glyphs or Glyphs()
126        self.show_header = bool(self.columns and any(t for t, _ in self.columns))
127
128    def set_items(self, items: list[Item], index: int | None = None) -> None:
129        self.items = items
130        if index is not None:
131            self.index = index
132        self.index = max(0, min(self.index, len(items) - 1)) if items else 0
133        self._refresh()
134
135    @property
136    def current(self) -> Item | None:
137        return self.items[self.index] if self.items else None
138
139    def move(self, step: int) -> None:
140        if not self.items:
141            return
142        n = len(self.items)
143        i = self.index
144        for _ in range(n):
145            i = (i + step) % n
146            if self.items[i].enabled or not any(it.enabled for it in self.items):
147                break
148        self.index = i
149        self._refresh()
150
151    def select(self, key: Any) -> None:
152        for i, it in enumerate(self.items):
153            if it.key == key:
154                self.index = i
155        self._refresh()
156
157    def page(self, step: int) -> None:
158        self.index = max(0, min(len(self.items) - 1, self.index + step * max(1, (self.window or 8) - 1)))
159        self._refresh()
160
161    def _refresh(self) -> None:
162        win = self.window or len(self.items)
163        if self.index < self.top:
164            self.top = self.index
165        if self.index >= self.top + win:
166            self.top = self.index - win + 1
167        self.top = max(0, min(self.top, max(0, len(self.items) - win)))
168        self.update(self.build())
169
170    def build(self) -> Text:
171        out = Text(no_wrap=True, overflow="crop")
172        pad = "  "
173        widths = [w for _t, w in self.columns]
174        if self.show_header:
175            out.append(pad)
176            for (title, w) in self.columns:
177                out.append(title.ljust(w) if w else title, style="bold")
178            out.append("\n")
179        win = self.window or len(self.items)
180        rows = self.items[self.top:self.top + win]
181        for n, it in enumerate(rows):
182            selected = (self.top + n) == self.index
183            line = Text(no_wrap=True, overflow="crop")
184            line.append((self.g.cursor + " ") if selected else pad, style=f"bold {self.palette.accent}" if selected else "")
185            for k, c in enumerate(it.cells):
186                c = cell(c)
187                w = widths[k] if k < len(widths) else 0
188                txt = c.text.ljust(w) if w else c.text
189                style = c.style if not selected else (c.style if c.style and not selected else "")
190                if selected:
191                    style = f"bold {self.palette.accent}" if c.style in ("", None) else c.style
192                elif not c.style and it.style:
193                    style = it.style
194                if not it.enabled and not selected:
195                    style = self.palette.mute
196                line.append(txt, style=style)
197            if selected:
198                line.stylize(f"on {self.palette.sel}")
199                line.pad_right(max(0, (self.size.width or 100) - len(line.plain)))
200                line.stylize(f"on {self.palette.sel}")
201            out.append_text(line)
202            if n < len(rows) - 1:
203                out.append("\n")
204        if self.window and len(self.items) > win:
205            out.append(f"\n  {self.top + 1}-{min(len(self.items), self.top + win)} of {len(self.items)}", style=self.palette.mute)
206        return out
207
208    def on_resize(self, _event) -> None:
209        self._refresh()
210
211
212def heading(text: str) -> Text:
213    return Text(text, style=f"bold {ACCENT}")
214
215
216def muted(text: str) -> Text:
217    return Text(text, style=MUTE)
218
219
220def warn(text: str) -> Text:
221    return Text(text, style=WARN)
222
223
224def bad(text: str) -> Text:
225    return Text(text, style=BAD)
226
227
228def bar(fraction: float, width: int, g: Glyphs) -> str:
229    fraction = max(0.0, min(1.0, fraction))
230    full = int(round(fraction * width))
231    return g.full * full + g.empty * (width - full)