diff --git a/CHANGELOG.md b/CHANGELOG.md index e55a90a..3527859 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,7 +32,15 @@ allowed to change behaviour, not just add to it. ### Added -- **MeshTerm can install a font its charts will actually draw in.** The classic Windows +- **MeshTerm offers to reopen itself in Windows Terminal.** The classic Windows console — + what you get from a double-click — can't show the emoji icons at all, whatever font it + is given: the only two Windows fonts with emoji in them are proportional, and a console + won't take one. A terminal is the only thing that fixes it, so MeshTerm now offers to + move there. One keypress, nothing installed, nothing changed — and you get the app as + it was drawn: icons, charts, path chips and all. + +- **MeshTerm can install a font its charts will actually draw in.** For anyone who stays + in the classic console. The classic Windows console does no font fallback at all, and none of the fonts it offers can draw braille — which every timeline and activity graph in MeshTerm is made of. Neither can Hack Nerd Font, JetBrains Mono, Fira Code, Source Code Pro, or even DejaVu Sans Mono; the usual @@ -43,7 +51,8 @@ allowed to change behaviour, not just add to it. and anyone with Windows Terminal) it just switches to it. If not, it offers to install it for you: no administrator rights, nothing downloaded, 723 KB. Saying no explains what saying no looks like and asks once more; a second no is remembered and never - raised again. Preferences → Display → Console font changes your mind either way. + raised again. Preferences → Display → Console setup changes your mind about either + offer. ## [0.2.4] — 2026-09-07 diff --git a/meshterm/cli.py b/meshterm/cli.py index 09aeb53..75e67d1 100644 --- a/meshterm/cli.py +++ b/meshterm/cli.py @@ -188,9 +188,11 @@ def main_callback( if ctx.invoked_subcommand is None: from .ui.menu import run_menu - # Before prompt_toolkit takes the screen, because this changes the console's own - # font and the full-screen frame should be drawn once, in whatever it ends up. - _offer_a_font_this_console_can_draw(console, prefs) + # Before prompt_toolkit takes the screen: this can change the console's own font, + # or hand the whole session to a better terminal, and the full-screen frame should + # be drawn once, in whatever it ends up in. + if _offer_a_console_that_can_draw_meshterm(console, prefs): + return # The interactive session is the one that holds the stores in memory and rewrites # them whole, so it is the one that claims the directory. One-shot subcommands are @@ -219,13 +221,75 @@ def main_callback( raise -def _offer_a_font_this_console_can_draw(console: Console, prefs: Preferences) -> None: - """On the classic Windows console, offer a font that can actually draw MeshTerm. +def _offer_a_console_that_can_draw_meshterm(console: Console, prefs: Preferences) -> bool: + """On the classic Windows console, offer the reader something better than it. - That console does no font fallback: whatever its font lacks is a box, and its default + Two offers, in the order of how much they buy. **Windows Terminal** first, because it + is the only one that gets the whole app: emoji icons included, which no font can put + on the classic console — the only Windows fonts carrying emoji are proportional, and + a console will not take one. Then, for a reader who stays, **a font** that can at + least draw the charts and the marks. + + Args: + console: The console to ask on. + prefs: The preference set, read for a previous refusal and written on a new one. + + Returns: + ``True`` when the session is being reopened elsewhere and this one should stop. + """ + from .ui.termfont import classic_console + + if not classic_console() or prefs.get("console_setup") == "off": + return False + if _offer_windows_terminal(console): + return True + _offer_a_font_this_console_can_draw(console, prefs) + return False + + +def _offer_windows_terminal(console: Console) -> bool: + """Offer to reopen the session in Windows Terminal, where the app looks like itself. + + Asked with yes as the default, which is not how the font offer is asked: this one + changes nothing on the machine — no install, no setting, one new window — and it is + the only answer that gets the reader the app as it was drawn. + + Args: + console: The console to ask on. + + Returns: + Whether Windows Terminal was started and this session should stand down. + """ + from .core import winterminal + + if winterminal.available() is None: + return False + + console.print() + console.print("[accent]•[/accent] This is the classic Windows console, and it can only") + console.print(" draw part of MeshTerm — no icons, and no charts.") + console.print() + console.print(" [accent]Windows Terminal[/accent] draws all of it, and you have it.") + console.print(" MeshTerm can reopen itself there now. Nothing is installed") + console.print(" and nothing is changed; it is just a better window.") + console.print() + if not _asks_yes(console, " Reopen in Windows Terminal? [Y/n] ", default=True): + return False + if winterminal.reopen(): + console.print("[ok]✓[/ok] Reopening in Windows Terminal.") + get_logger().info("reopened the session in Windows Terminal") + return True + console.print("[warn]⚠[/warn] Windows Terminal would not start. Staying here.") + get_logger().warning("could not start Windows Terminal") + return False + + +def _offer_a_font_this_console_can_draw(console: Console, prefs: Preferences) -> None: + """Offer a font that can at least draw the charts and marks, for a reader who stays. + + The console does no font fallback: whatever its font lacks is a box, and its default — Consolas, or Lucida Console under Windows PowerShell — lacks most of what MeshTerm is drawn with, including every one of the 44 braille cells the timelines are made of. - Nothing at the app's end fixes that, so this is the one thing left to offer. Two shapes, depending on what is already there: a machine with Windows Terminal (and every Windows 11 machine) already has Cascadia, so the offer is only to *use* it; a @@ -234,17 +298,15 @@ def _offer_a_font_this_console_can_draw(console: Console, prefs: Preferences) -> Declining is answered with a plain description of what declining looks like, and then asked once more — a reader who has never seen the app has no way to know what "some glyphs may not render" is going to mean. A second decline is remembered, in the - ``console_font`` preference, so the question is asked twice in total and never again. + ``console_setup`` preference, so the question is asked twice in total and never again. Args: console: The console to ask on. prefs: The preference set, read for a previous refusal and written on a new one. """ from .core import consolefont - from .ui.termfont import classic_console, face_draws_charts, installed_chart_font + from .ui.termfont import face_draws_charts, installed_chart_font - if not classic_console() or prefs.get("console_font") == "off": - return if face_draws_charts(consolefont.current_face()): return @@ -281,14 +343,14 @@ def _offer_a_font_this_console_can_draw(console: Console, prefs: Preferences) -> _use_a_better_console_font(console, installed) return - prefs.set("console_font", "off") + prefs.set("console_setup", "off") try: prefs.save() except (OSError, RuntimeError) as exc: # a read-only config dir is not fatal here - get_logger().warning("could not remember the console font choice: %s", exc) + get_logger().warning("could not remember the console setup choice: %s", exc) console.print() console.print("[muted] Leaving it as it is. Change your mind on the Preferences[/muted]") - console.print("[muted] page, under Display → Console font.[/muted]") + console.print("[muted] page, under Display → Console setup.[/muted]") console.print() @@ -316,26 +378,30 @@ def _use_a_better_console_font(console: Console, installed: str | None) -> None: get_logger().warning("console refused the font %s", face) -def _asks_yes(console: Console, prompt: str) -> bool: - """Ask a yes/no question on the console, defaulting to no. +def _asks_yes(console: Console, prompt: str, *, default: bool = False) -> bool: + """Ask a yes/no question on the console. Not a TUI dialog: this runs before prompt_toolkit owns the screen, alongside the other - plain-console reports here. An unanswerable prompt — no stdin, a closed pipe — reads as - "no", which is the answer that changes nothing. + plain-console reports here. An unanswerable prompt — no stdin, a closed pipe — takes + the default, and each caller's default is the answer that costs the reader least. Args: console: The console to ask on. prompt: The question, ending in its own spacing. + default: The answer an empty line means, and the one an unreadable stdin takes. Returns: Whether the reader said yes. """ console.print(prompt, end="") try: - return input().strip().lower() in {"y", "yes"} + answer = input().strip().lower() except (EOFError, KeyboardInterrupt, OSError): console.print() - return False + return default + if not answer: + return default + return answer in {"y", "yes"} def _report_log_location(console: Console, config_dir: Path) -> None: diff --git a/meshterm/core/preferences.py b/meshterm/core/preferences.py index 4415bae..7e28b1b 100644 --- a/meshterm/core/preferences.py +++ b/meshterm/core/preferences.py @@ -128,9 +128,9 @@ _WIDTH_CHOICES: dict[str, str] = {"auto": "auto", "yes": "yes", "no": "no"} #: What the log file keeps. The plain level names, which are what every other tool calls #: these — someone being talked through a problem is being told "set it to debug", not #: "set it to everything". -#: What MeshTerm may do about a console font that cannot draw it. Only ever consulted on -#: the classic Windows console, the one host with no font fallback of its own. -_CONSOLE_FONT_CHOICES: dict[str, str] = { +#: What MeshTerm may offer when it lands in a console that cannot draw it. Only ever +#: consulted on the classic Windows console, the one host with no font fallback of its own. +_CONSOLE_SETUP_CHOICES: dict[str, str] = { "ask": "Ask", "off": "Leave it alone", } @@ -303,16 +303,16 @@ PREFERENCES: tuple[PrefSpec, ...] = ( choices=_WIDTH_CHOICES, ), PrefSpec( - key="console_font", - label="Console font", - help="Offer a font this console can draw MeshTerm with (Windows console only)", + key="console_setup", + label="Console setup", + help="Offer a better terminal or font when this console can't draw MeshTerm", group="Display", value_type="enum", # "ask", not "always": changing the font of a window someone else opened is not # ours to do unasked. Declining twice writes "off" here, which is how the offer # stops being made rather than being made every launch. default="ask", - choices=_CONSOLE_FONT_CHOICES, + choices=_CONSOLE_SETUP_CHOICES, ), # --- Diagnostics --------------------------------------------------------------- PrefSpec( diff --git a/meshterm/core/winterminal.py b/meshterm/core/winterminal.py new file mode 100644 index 0000000..775da81 --- /dev/null +++ b/meshterm/core/winterminal.py @@ -0,0 +1,90 @@ +"""Reopening the session in Windows Terminal, which is where MeshTerm looks like itself. + +MeshTerm is drawn with emoji icons, braille charts and powerline path chips. Whether any +of that reaches the screen is decided by the *terminal*, not by MeshTerm and not really by +the font either: a modern terminal, asked for a character its font lacks, quietly borrows +the glyph from another font on the machine. That is why the app looks right in Windows +Terminal, in VS Code's terminal, and on macOS and Linux — and why it looks right there +even though the font the reader chose usually holds almost none of it. Measured on a +development machine, the everyday choices — Hack Nerd Font, JetBrains Mono, Fira Code, +Source Code Pro — carry no braille at all, and no monospace font anywhere carries emoji. + +The classic Windows console does not do that. It draws what its one font holds and boxes +for the rest, so on that host the emoji cannot be shown *at all* — the only two fonts on a +Windows machine with emoji glyphs, Segoe UI Emoji and Segoe UI Symbol, are proportional, +and a console will not take a proportional font. No font choice fixes it, which leaves +exactly one thing that does: a different terminal. + +So when MeshTerm finds itself in that console and Windows Terminal is installed — it is on +every Windows 11 machine, and a free install on 10 — it offers to reopen itself there. +One keypress, and the app looks the way it was drawn instead of the way conhost can +manage. Declining falls back to :mod:`meshterm.core.consolefont`, which makes the best of +the console the reader chose to stay in. +""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import sys + +#: Set in the reopened session, so a relaunch can never chain into another one. Windows +#: Terminal is not a classic console and so would not qualify anyway — this is the belt to +#: that braces, and it costs one environment variable. +REOPENED_ENV = "MESHTERM_REOPENED" + + +def available() -> str | None: + """The path to ``wt.exe``, or ``None`` when Windows Terminal is not installed. + + Found on ``PATH``, where Windows puts an execution alias for it under + ``%LOCALAPPDATA%/Microsoft/WindowsApps``. + """ + if sys.platform != "win32" or os.environ.get(REOPENED_ENV): + return None + return shutil.which("wt.exe") + + +def own_command() -> list[str]: + """The command that would start this same session again. + + A frozen build is its own executable and takes the arguments as they were given. A + development or ``pip`` install is reached through its interpreter, because the console + script's own path is not something ``wt`` can be relied on to resolve. + + Returns: + The program and its arguments, ready to hand to Windows Terminal. + """ + if getattr(sys, "frozen", False): + return [sys.executable, *sys.argv[1:]] + return [sys.executable, "-m", "meshterm", *sys.argv[1:]] + + +def reopen() -> bool: + """Start this session again in Windows Terminal, in the same directory. + + The new window is not a child in any meaningful sense — the caller exits immediately + afterwards and the two never talk — so nothing is waited on and no pipes are held. + + Returns: + Whether Windows Terminal was started. ``False`` leaves the caller exactly where it + was, which is why the offer is only ever a detour and never a dead end. + """ + terminal = available() + if terminal is None: + return False + environment = dict(os.environ, **{REOPENED_ENV: "1"}) + try: + # `--` ends wt's own option parsing, so MeshTerm's flags reach MeshTerm rather + # than being read as Windows Terminal's (verified: `--mock` and `--profile x` + # arrive intact). `-d` keeps the working directory, which relative paths given + # on the command line depend on. + subprocess.Popen( # noqa: S603 - the argv is ours, not the reader's + [terminal, "-d", os.getcwd(), "--", *own_command()], + env=environment, + close_fds=True, + ) + return True + except OSError: + return False diff --git a/tests/test_winterminal.py b/tests/test_winterminal.py new file mode 100644 index 0000000..ba9d14b --- /dev/null +++ b/tests/test_winterminal.py @@ -0,0 +1,75 @@ +"""Tests for reopening the session in Windows Terminal. + +Nothing here starts a terminal. What is pinned is the command that *would* be run — which +is the part that can be silently wrong, because a mistake in it produces a window that +opens, fails, and closes faster than anyone can read it. +""" + +from __future__ import annotations + +import sys + +import pytest + +from meshterm.core import winterminal + + +def test_it_is_only_ever_windows(monkeypatch: pytest.MonkeyPatch) -> None: + """Every other platform's terminal already draws the whole app; there is nothing to fix.""" + monkeypatch.setattr(sys, "platform", "linux") + assert winterminal.available() is None + assert winterminal.reopen() is False + + +def test_a_reopened_session_never_offers_to_reopen_again(monkeypatch: pytest.MonkeyPatch) -> None: + """The loop guard. Windows Terminal would not qualify anyway, and this is the backstop. + + A relaunch that could chain is not a cosmetic bug: each one spawns a window and exits, + so the reader would watch windows open forever. + """ + monkeypatch.setattr(sys, "platform", "win32") + monkeypatch.setenv(winterminal.REOPENED_ENV, "1") + assert winterminal.available() is None + assert winterminal.reopen() is False + + +def test_a_frozen_build_relaunches_itself(monkeypatch: pytest.MonkeyPatch) -> None: + """The installer's own executable takes the arguments exactly as they were given.""" + monkeypatch.setattr(sys, "frozen", True, raising=False) + monkeypatch.setattr(sys, "executable", r"C:\Downloads\meshterm.exe") + monkeypatch.setattr(sys, "argv", ["meshterm", "--mock", "--profile", "home"]) + assert winterminal.own_command() == [ + r"C:\Downloads\meshterm.exe", + "--mock", + "--profile", + "home", + ] + + +def test_a_source_install_relaunches_through_its_interpreter( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """``-m meshterm``, not the console script. + + The script's path is a wrapper whose location varies by install method (venv, pipx, + user site), while the interpreter running us is a fact we already hold. Using the + interpreter also guarantees the new window gets the same environment as this one. + """ + monkeypatch.delattr(sys, "frozen", raising=False) + monkeypatch.setattr(sys, "executable", r"C:\venv\Scripts\python.exe") + monkeypatch.setattr(sys, "argv", ["meshterm", "--mock"]) + assert winterminal.own_command() == [r"C:\venv\Scripts\python.exe", "-m", "meshterm", "--mock"] + + +def test_the_program_name_is_never_passed_on_as_an_argument( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """``argv[0]`` is how this process was named, not something to hand to the next one. + + Passing it through would reach MeshTerm as a stray positional argument and be rejected + by Typer — in a brand new window that then closes. + """ + monkeypatch.setattr(sys, "frozen", True, raising=False) + monkeypatch.setattr(sys, "executable", r"C:\meshterm.exe") + monkeypatch.setattr(sys, "argv", [r"C:\some\other\name.exe"]) + assert winterminal.own_command() == [r"C:\meshterm.exe"]