okami.mom/strata

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

Niko1221monitor: the classic Windows console switches to Cascadia Mono when installed, else a solid-block look with palette colours; several cards and CPUs in the Overview (totals, a Cards strip, sockets); whole card names in view 51d0397652

main
8.1 KiB184 linesraw
1"""What kind of terminal this is, for the few places that must change what they draw.
2
3The classic Windows console window (conhost: the default window of Windows PowerShell and cmd on Windows 10) uses Consolas or Lucida Console,
4which have no glyphs for the eighth-block sparkline characters or the check mark: they show as empty boxes (Consolas has the full, half and
5shade blocks, the box-drawing set and the rounded corners; Lucida Console has no rounded corners and no filled circle).
6Windows Terminal, VS Code's terminal, ConEmu and every Linux/macOS terminal with a modern font have them. `STRATA_GLYPHS=ascii|unicode`
7overrides the guess (`solid` draws the classic console's solid look without touching the window's font).
8
9In the classic console only, `classic_style()` does the best it can with no admin rights and no registry change:
10* Cascadia Mono installed: this window's font is switched to it (the console font API) and the full Unicode look is drawn;
11* otherwise the "solid" look: solid block bars with a thin track, ▄ / █ sparklines, square boxes, the 16 palette colours conhost really has,
12  and `•` instead of `●` when the font is not Consolas (Lucida has no `●`).
13Windows Terminal, Linux and macOS never get either: `legacy_console()` is False there.
14"""
15
16from __future__ import annotations
17
18import os
19import sys
20
21TIP = "For the full look, use Windows Terminal (built into Windows 11)"
22
23
24def legacy_console() -> bool:
25    """True for the classic Windows console (no Windows Terminal, no VS Code, no ConEmu, no ssh session into it)."""
26    forced = os.environ.get("STRATA_GLYPHS", "").strip().lower()
27    if forced in ("ascii", "legacy", "solid"):
28        return True
29    if forced == "unicode":
30        return False
31    if os.name != "nt" and sys.platform != "win32":
32        return False
33    env = os.environ
34    return not (env.get("WT_SESSION") or env.get("TERM_PROGRAM") or env.get("ConEmuANSI") or env.get("ANSICON")
35                or env.get("TERM", "").startswith(("xterm", "screen", "tmux", "vt")))
36
37
38def console_columns() -> int | None:
39    """The visible width of the Windows console window in columns (not its buffer), or None when it cannot be read."""
40    if os.name != "nt":
41        return None
42    try:
43        import ctypes
44        from ctypes import wintypes
45
46        class COORD(ctypes.Structure):
47            _fields_ = [("X", ctypes.c_short), ("Y", ctypes.c_short)]
48
49        class RECT(ctypes.Structure):
50            _fields_ = [("Left", ctypes.c_short), ("Top", ctypes.c_short), ("Right", ctypes.c_short), ("Bottom", ctypes.c_short)]
51
52        class INFO(ctypes.Structure):
53            _fields_ = [("size", COORD), ("cursor", COORD), ("attr", wintypes.WORD), ("window", RECT), ("maxsize", COORD)]
54
55        handle = ctypes.windll.kernel32.GetStdHandle(-11)
56        info = INFO()
57        if not ctypes.windll.kernel32.GetConsoleScreenBufferInfo(handle, ctypes.byref(info)):
58            return None
59        return int(info.window.Right - info.window.Left + 1)
60    except Exception:                                        # noqa: BLE001
61        return None
62
63
64# ------------------------------------------------------------------------------------------------ the font of the classic console
65
66def _font_struct():
67    import ctypes
68
69    class COORD(ctypes.Structure):
70        _fields_ = [("X", ctypes.c_short), ("Y", ctypes.c_short)]
71
72    class CONSOLE_FONT_INFOEX(ctypes.Structure):
73        _fields_ = [("cbSize", ctypes.c_ulong), ("nFont", ctypes.c_ulong), ("dwFontSize", COORD), ("FontFamily", ctypes.c_uint),
74                    ("FontWeight", ctypes.c_uint), ("FaceName", ctypes.c_wchar * 32)]
75    return CONSOLE_FONT_INFOEX
76
77
78def console_font() -> str | None:
79    """The face name of this console window's font (Windows only), or None."""
80    if os.name != "nt":
81        return None
82    try:
83        import ctypes
84        S = _font_struct()
85        info = S()
86        info.cbSize = ctypes.sizeof(S)
87        handle = ctypes.windll.kernel32.GetStdHandle(-11)
88        if not ctypes.windll.kernel32.GetCurrentConsoleFontEx(handle, False, ctypes.byref(info)):
89            return None
90        return info.FaceName or None
91    except Exception:                                        # noqa: BLE001
92        return None
93
94
95def cascadia_installed() -> bool:
96    """Is Cascadia Mono installed (it comes with Windows Terminal and Visual Studio, and can be installed alone)?"""
97    if os.name != "nt":
98        return False
99    try:
100        import winreg
101        for root in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER):
102            try:
103                with winreg.OpenKey(root, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts") as key:
104                    i = 0
105                    while True:
106                        name = winreg.EnumValue(key, i)[0]
107                        if name.lower().startswith("cascadia mono"):
108                            return True
109                        i += 1
110            except OSError:
111                continue
112    except Exception:                                        # noqa: BLE001
113        return False
114    fonts = os.path.join(os.environ.get("WINDIR", "C:\\Windows"), "Fonts")
115    return any(os.path.isfile(os.path.join(fonts, n)) for n in ("CascadiaMono.ttf", "CascadiaMonoPL.ttf"))
116
117
118def switch_font(face: str = "Cascadia Mono") -> bool:
119    """Set THIS console window's font through the console font API (no admin, nothing saved, gone when the window closes); True if it took."""
120    if os.name != "nt":
121        return False
122    try:
123        import ctypes
124        S = _font_struct()
125        info = S()
126        info.cbSize = ctypes.sizeof(S)
127        handle = ctypes.windll.kernel32.GetStdHandle(-11)
128        if not ctypes.windll.kernel32.GetCurrentConsoleFontEx(handle, False, ctypes.byref(info)):
129            return False
130        height = info.dwFontSize.Y or 16
131        info.FaceName = face
132        info.dwFontSize.X = 0
133        info.dwFontSize.Y = height
134        info.FontFamily = 54                                 # TMPF_TRUETYPE | fixed pitch | modern
135        info.FontWeight = 400
136        if not ctypes.windll.kernel32.SetCurrentConsoleFontEx(handle, False, ctypes.byref(info)):
137            return False
138        return console_font() == face
139    except Exception:                                        # noqa: BLE001
140        return False
141
142
143def decide_style(*, legacy: bool, cascadia_ok: bool, font: str | None) -> dict:
144    """The look for this console (pure: the tests give it the facts).
145
146    {"mode": "none"}                                      not the classic console: nothing here changes
147    {"mode": "full", "font": "Cascadia Mono", ...}        the font was switched to Cascadia Mono: the full Unicode look
148    {"mode": "solid", "font": face, "bullet": "●"|"•"}    solid blocks and palette colours; the bullet depends on the font
149    `tip` is the one line every classic console shows."""
150    if not legacy:
151        return {"mode": "none", "bullet": "●", "tip": None, "font": font}
152    if cascadia_ok:
153        return {"mode": "full", "bullet": "●", "tip": TIP, "font": "Cascadia Mono"}
154    bullet = "●" if (font or "").lower().startswith("consolas") else "•"       # Lucida Console (and unknown fonts) have no ●
155    return {"mode": "solid", "bullet": bullet, "tip": TIP, "font": font}
156
157
158_cached: dict | None = None
159
160
161def classic_style() -> dict:
162    """decide_style for this process, switching the font to Cascadia Mono once when that is possible. Cheap after the first call."""
163    global _cached
164    if _cached is not None:
165        return _cached
166    legacy = legacy_console()
167    forced = os.environ.get("STRATA_GLYPHS", "").strip().lower() in ("ascii", "legacy", "solid")
168    switched = False
169    font = console_font() if (legacy and forced) else None
170    if legacy and not forced and os.name == "nt":
171        font = console_font()
172        if font and font.lower().startswith("cascadia mono"):
173            switched = True
174        elif cascadia_installed():
175            switched = switch_font("Cascadia Mono")
176            font = console_font() if switched else font
177    _cached = decide_style(legacy=legacy, cascadia_ok=switched, font=font)
178    return _cached
179
180
181def forget_style() -> None:
182    """For the tests: decide again."""
183    global _cached
184    _cached = None