MeshTerm gets its own window on a Mac, and leaves yours alone
No Mac monospace face carries the Braille Patterns block, so Terminal -- which falls back generously rather than drawing a box -- borrows the charts and the map's terrain from a proportional face and lands them at the wrong width. Nothing announces itself as broken; it is just crooked, and a reader with nothing to compare against never finds out why. Fixing it means a font, and a font means a profile. The question that shapes this module is whose terminal it is. MeshTerm's palette is the 16-colour VT set, crude on purpose, and nobody should have to read their mail in it -- so nothing here touches the default profile or edits their preferences. It adds a profile named MeshTerm and opens our own window in it; theirs keeps its translucency, and quitting leaves nothing behind. That is also the only route that works at all. Terminal rewrites its preferences from memory when it quits, so a file written while it runs -- and MeshTerm always runs inside it -- is discarded later. Handing Terminal a .terminal file lets Terminal do the importing. The profile is generated from _VT_SLOTS rather than shipped, so the window cannot disagree with the screen it holds. The NSColor and NSFont archives are pinned to bytes read back off a profile that was installed on a real Mac and confirmed rendering, not to a reading of the format. relaunch.py is the half that was never Windows-specific -- own_command, child_environment and its _PYI trap, the wanted size -- moved out of winterminal so both terminals share one copy. Not yet wired into startup: the launch itself wants a Mac to confirm, and that machine is asleep. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
3edfaebadc
commit
2d31810801
4 files changed
+641
-74
No files matched your search
@@ -0,0 +1,350 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""Reopening the session in a Terminal window that looks like MeshTerm.
|
||||
|
||||
macOS Terminal is not the classic Windows console's problem over again. It falls back
|
||||
generously — ask it for a glyph its font lacks and it finds one somewhere — so nothing here
|
||||
is ever a box. The trouble is *what* it finds: no Mac monospace face carries the Braille
|
||||
Patterns block at all (SF Mono, Menlo, Monaco and Courier all measure zero), so the block
|
||||
the charts and the map's terrain are drawn from is borrowed from a **proportional** face
|
||||
and arrives at the wrong width. The screen is not empty, it is crooked, which is worse —
|
||||
nothing announces itself as broken and the reader has nothing to compare it against.
|
||||
|
||||
The fix is a font, and a font means a Terminal profile that names it. Which raises the
|
||||
question this module exists to answer carefully: **whose terminal is it?**
|
||||
|
||||
MeshTerm's palette is the 16-colour VT set (:data:`~meshterm.ui.theme._VT_SLOTS`) — a
|
||||
deliberately crude, deliberately CGA-ish thing that the app wears on purpose. Nobody should
|
||||
have to live in it to read their mail. So this module never touches the reader's default
|
||||
profile and never edits their preferences: it *adds* a profile named MeshTerm, and opens
|
||||
MeshTerm's own window in it. Their Terminal keeps whatever they chose, down to its
|
||||
translucency; ours is opaque and crude in a window of its own, and quitting leaves nothing
|
||||
behind.
|
||||
|
||||
That also sidesteps a trap worth recording, because it costs an evening to find. Terminal
|
||||
rewrites ``~/Library/Preferences/com.apple.Terminal.plist`` **from memory when it quits**,
|
||||
so anything written into that file while Terminal is running is silently discarded later —
|
||||
and MeshTerm is always running inside it. Nothing here writes that file. A ``.terminal``
|
||||
file is handed to Terminal and *Terminal* does the importing, which is the one path that
|
||||
works from inside a live session.
|
||||
|
||||
The profile is generated rather than shipped, from the same theme constant the app draws
|
||||
itself with, so the window can never disagree with the screen it is holding.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import plistlib
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from .relaunch import REOPENED_ENV, own_command, wanted_size
|
||||
|
||||
#: The name the profile is installed under, and the name the reader sees in Terminal's
|
||||
#: settings list. Stable: renaming it would strand the copy already on their machine.
|
||||
PROFILE_NAME = "MeshTerm"
|
||||
|
||||
#: The bundled face, by its PostScript name — which is what an ``NSFont`` archive holds,
|
||||
#: and not the family name Font Book shows. Installed by :func:`install_font` from the copy
|
||||
#: in the package; see :mod:`meshterm.core.consolefont` for the Windows half of the same
|
||||
#: idea.
|
||||
FONT_FACE = "CascadiaMonoPL-Regular"
|
||||
|
||||
#: Points. Terminal's own default is 11; 13 is a size the braille charts read cleanly at on
|
||||
#: a Retina panel without the map losing rows.
|
||||
FONT_SIZE = 13.0
|
||||
|
||||
#: Where a user-installed font goes on macOS. No administrator rights, no installer, and
|
||||
#: the reader can undo it by dragging the file out of Font Book.
|
||||
USER_FONT_DIR = Path("~/Library/Fonts").expanduser()
|
||||
|
||||
#: Terminal's key for each palette slot, in :data:`~meshterm.ui.theme._VT_SLOTS` order —
|
||||
#: the standard ANSI 16, dim bank then bright bank.
|
||||
_ANSI_KEYS: tuple[str, ...] = (
|
||||
"ANSIBlackColor",
|
||||
"ANSIRedColor",
|
||||
"ANSIGreenColor",
|
||||
"ANSIYellowColor",
|
||||
"ANSIBlueColor",
|
||||
"ANSIMagentaColor",
|
||||
"ANSICyanColor",
|
||||
"ANSIWhiteColor",
|
||||
"ANSIBrightBlackColor",
|
||||
"ANSIBrightRedColor",
|
||||
"ANSIBrightGreenColor",
|
||||
"ANSIBrightYellowColor",
|
||||
"ANSIBrightBlueColor",
|
||||
"ANSIBrightMagentaColor",
|
||||
"ANSIBrightCyanColor",
|
||||
"ANSIBrightWhiteColor",
|
||||
)
|
||||
|
||||
|
||||
def _archive(objects: list[object]) -> bytes:
|
||||
"""One ``NSKeyedArchiver`` document, as Terminal stores every colour and font.
|
||||
|
||||
Terminal keeps these as nested binary plists inside the profile — an archived
|
||||
``NSColor`` or ``NSFont`` rather than a number and a string, because the profile is
|
||||
written by AppKit rather than for us. The shape is small and fixed, so it is built
|
||||
here rather than reached for through a dependency.
|
||||
|
||||
Args:
|
||||
objects: The ``$objects`` array, with ``$null`` already at index 0.
|
||||
|
||||
Returns:
|
||||
The encoded archive. Binary, because :class:`plistlib.UID` has no XML spelling.
|
||||
"""
|
||||
return plistlib.dumps(
|
||||
{
|
||||
"$archiver": "NSKeyedArchiver",
|
||||
"$objects": objects,
|
||||
"$top": {"root": plistlib.UID(1)},
|
||||
"$version": 100000,
|
||||
},
|
||||
fmt=plistlib.FMT_BINARY,
|
||||
)
|
||||
|
||||
|
||||
def ns_color(rgb: str) -> bytes:
|
||||
"""An archived ``NSColor`` for a ``#rrggbb`` string.
|
||||
|
||||
Args:
|
||||
rgb: The colour, as the theme spells it.
|
||||
|
||||
Returns:
|
||||
The archive Terminal expects in a colour key.
|
||||
"""
|
||||
channels = (int(rgb[index : index + 2], 16) / 255 for index in (1, 3, 5))
|
||||
# Calibrated RGB, space-separated to six places and NUL-terminated: AppKit's own
|
||||
# spelling, matched exactly because Terminal parses it rather than tolerating it.
|
||||
packed = " ".join(f"{value:.6f}" for value in channels).encode("ascii") + b"\x00"
|
||||
return _archive(
|
||||
[
|
||||
"$null",
|
||||
{"$class": plistlib.UID(2), "NSColorSpace": 1, "NSRGB": packed},
|
||||
{"$classes": ["NSColor", "NSObject"], "$classname": "NSColor"},
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def ns_font(face: str = FONT_FACE, size: float = FONT_SIZE) -> bytes:
|
||||
"""An archived ``NSFont``.
|
||||
|
||||
Args:
|
||||
face: The PostScript name of the face.
|
||||
size: The size in points.
|
||||
|
||||
Returns:
|
||||
The archive Terminal expects in the ``Font`` key.
|
||||
"""
|
||||
return _archive(
|
||||
[
|
||||
"$null",
|
||||
{
|
||||
"$class": plistlib.UID(3),
|
||||
"NSName": plistlib.UID(2),
|
||||
"NSSize": float(size),
|
||||
"NSfFlags": 16,
|
||||
},
|
||||
face,
|
||||
{"$classes": ["NSFont", "NSObject"], "$classname": "NSFont"},
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def launch_command() -> str:
|
||||
"""The shell line that starts this session again, for the profile to run.
|
||||
|
||||
Terminal starts the command from a **fresh login shell**, which is why this is a
|
||||
string rather than an argv and why it carries what it needs explicitly. Nothing of the
|
||||
current process's environment survives the hop — good news for the ``_PYI*`` variables
|
||||
a frozen build must not pass on (see
|
||||
:func:`~meshterm.core.relaunch.child_environment`, which exists for the Windows side
|
||||
where they *do* survive), and bad news for a ``MESHTERM_HOME`` the reader set for this
|
||||
invocation alone, which the README itself suggests doing. So every ``MESHTERM_*``
|
||||
variable currently set is carried across, and the reopened-session marker with them.
|
||||
|
||||
``exec`` so the shell replaces itself: the window then holds MeshTerm and nothing else,
|
||||
and closing MeshTerm closes the window rather than dropping to a prompt.
|
||||
|
||||
Returns:
|
||||
A ``sh`` command line.
|
||||
"""
|
||||
carried = {name: value for name, value in os.environ.items() if name.startswith("MESHTERM_")}
|
||||
carried[REOPENED_ENV] = "1"
|
||||
assignments = " ".join(
|
||||
f"{name}={shlex.quote(value)}" for name, value in sorted(carried.items())
|
||||
)
|
||||
program = " ".join(shlex.quote(part) for part in own_command())
|
||||
return f"{assignments} exec {program}"
|
||||
|
||||
|
||||
def build_profile(command: str | None = None) -> dict[str, object]:
|
||||
"""The MeshTerm profile, as Terminal's preferences hold it.
|
||||
|
||||
Every colour comes from :data:`~meshterm.ui.theme._VT_SLOTS`, so the window and the
|
||||
app it is holding cannot disagree — change the theme and this follows on the next
|
||||
write. The window size is
|
||||
:func:`~meshterm.core.relaunch.wanted_size`'s, the same one Windows Terminal is asked
|
||||
for.
|
||||
|
||||
Args:
|
||||
command: A shell line for the window to run on open, or ``None`` for a profile
|
||||
that just sits in the list waiting to be chosen.
|
||||
|
||||
Returns:
|
||||
The profile dictionary, ready to write as a ``.terminal`` file.
|
||||
"""
|
||||
from ..ui.theme import _VT_SLOTS
|
||||
|
||||
cols, rows = wanted_size()
|
||||
profile: dict[str, object] = {
|
||||
"name": PROFILE_NAME,
|
||||
"type": "Window Settings",
|
||||
"ProfileCurrentVersion": 2.07,
|
||||
"Font": ns_font(),
|
||||
"FontAntialias": True,
|
||||
"FontWidthSpacing": 1.0,
|
||||
# Opaque on purpose. A braille raster over a translucent ground is unreadable, and
|
||||
# a translucent profile is a perfectly reasonable thing for the reader to have --
|
||||
# which is the whole argument for MeshTerm having a window of its own.
|
||||
"BackgroundColor": ns_color("#000000"),
|
||||
"TextColor": ns_color("#aaaaaa"),
|
||||
"TextBoldColor": ns_color("#ffffff"),
|
||||
"SelectionColor": ns_color("#555555"),
|
||||
"CursorColor": ns_color("#55ffff"),
|
||||
"CursorType": 0,
|
||||
"BlinkText": False,
|
||||
# Bold is bold, not a jump to the bright bank. The theme states brightness as a
|
||||
# colour (see the wordmark's own note); letting Terminal promote it as well would
|
||||
# land a bank too high.
|
||||
"UseBrightBold": False,
|
||||
"columnCount": cols,
|
||||
"rowCount": rows,
|
||||
"ScrollbackLines": 10000,
|
||||
"ShouldLimitScrollback": 0,
|
||||
"ShowActiveProcessInTitle": True,
|
||||
"ShowDimensionsInTitle": False,
|
||||
"ShowWindowSettingsNameInTitle": False,
|
||||
}
|
||||
for key, (_slot, _label, rgb) in zip(_ANSI_KEYS, _VT_SLOTS, strict=True):
|
||||
profile[key] = ns_color(rgb)
|
||||
if command is not None:
|
||||
profile["CommandString"] = command
|
||||
profile["RunCommandAsShell"] = False
|
||||
return profile
|
||||
|
||||
|
||||
def profile_path() -> Path:
|
||||
"""Where the generated ``.terminal`` file is kept.
|
||||
|
||||
In MeshTerm's own directory rather than the Desktop: it is ours, it is the one place
|
||||
that already survives an upgrade, and it moves with ``MESHTERM_HOME``.
|
||||
"""
|
||||
from .config import default_config_dir
|
||||
|
||||
return default_config_dir() / f"{PROFILE_NAME}.terminal"
|
||||
|
||||
|
||||
def write_profile(*, command: str | None = None) -> Path:
|
||||
"""Write the profile out, and return where it landed.
|
||||
|
||||
Args:
|
||||
command: A shell line for the window to run, or ``None`` for a bare profile.
|
||||
|
||||
Returns:
|
||||
The path written.
|
||||
"""
|
||||
path = profile_path()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(plistlib.dumps(build_profile(command), fmt=plistlib.FMT_XML))
|
||||
return path
|
||||
|
||||
|
||||
def font_installed() -> bool:
|
||||
"""Whether the bundled face is already in the reader's font directory."""
|
||||
from .consolefont import BUNDLED_FONT
|
||||
|
||||
return (USER_FONT_DIR / BUNDLED_FONT.name).is_file()
|
||||
|
||||
|
||||
def install_font() -> bool:
|
||||
"""Copy the bundled face into the reader's own font directory.
|
||||
|
||||
The one thing here that writes outside MeshTerm's own folder, which is why it is the
|
||||
one thing worth asking about: a single file, in the reader's own Library, no
|
||||
administrator rights, no installer, removable by dragging it out of Font Book. It
|
||||
changes nothing about how their Terminal looks — it only makes the face available for
|
||||
a profile to name.
|
||||
|
||||
Safe to repeat: an existing copy is left alone.
|
||||
|
||||
Returns:
|
||||
Whether the font is installed and usable, including when it already was.
|
||||
"""
|
||||
from .consolefont import BUNDLED_FONT
|
||||
|
||||
if sys.platform != "darwin" or not BUNDLED_FONT.is_file():
|
||||
return False
|
||||
target = USER_FONT_DIR / BUNDLED_FONT.name
|
||||
if target.is_file():
|
||||
return True
|
||||
try:
|
||||
USER_FONT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(BUNDLED_FONT, target)
|
||||
except OSError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def in_apple_terminal() -> bool:
|
||||
"""Whether this session is drawing into macOS Terminal.
|
||||
|
||||
iTerm2, Ghostty, kitty, WezTerm and VS Code all set ``TERM_PROGRAM`` to their own
|
||||
name, and several of them have both truecolor and a font the reader chose deliberately
|
||||
— none of them wants anything this module offers.
|
||||
"""
|
||||
return sys.platform == "darwin" and os.environ.get("TERM_PROGRAM") == "Apple_Terminal"
|
||||
|
||||
|
||||
def available() -> bool:
|
||||
"""Whether reopening in MeshTerm's own window is a thing worth doing here.
|
||||
|
||||
``False`` in a session that was itself reopened, which is what keeps a relaunch from
|
||||
chaining into another one: the profile's own command carries the marker, because
|
||||
Terminal starts it from a fresh shell that inherits nothing from us.
|
||||
"""
|
||||
return in_apple_terminal() and not os.environ.get(REOPENED_ENV)
|
||||
|
||||
|
||||
def reopen() -> bool:
|
||||
"""Open MeshTerm in a window using its own profile, and report whether it started.
|
||||
|
||||
``open`` hands the file to Terminal, and **Terminal** imports the profile and opens the
|
||||
window — the only route that works from inside a live session, since Terminal discards
|
||||
external edits to its preferences when it quits.
|
||||
|
||||
The new window is not a child in any meaningful sense: the caller exits immediately
|
||||
afterwards and the two never talk.
|
||||
|
||||
Returns:
|
||||
Whether ``open`` was launched. ``False`` leaves the caller exactly where it was,
|
||||
so a failure here is a detour and never a dead end.
|
||||
"""
|
||||
if not available():
|
||||
return False
|
||||
try:
|
||||
path = write_profile(command=launch_command())
|
||||
except OSError:
|
||||
return False
|
||||
try:
|
||||
subprocess.Popen( # noqa: S603 - the argv is ours, not the reader's
|
||||
["/usr/bin/open", str(path)],
|
||||
close_fds=True,
|
||||
)
|
||||
except OSError:
|
||||
return False
|
||||
return True
|
||||
@@ -0,0 +1,104 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""What every relaunch of MeshTerm needs, whichever terminal it is relaunching into.
|
||||
|
||||
MeshTerm reopens itself when the terminal it was started from cannot draw it, and there
|
||||
are two such terminals for two unrelated reasons. The classic Windows console has no font
|
||||
fallback at all, so an icon it lacks is a box and no font choice fixes it
|
||||
(:mod:`meshterm.core.winterminal`). macOS Terminal falls back generously — too generously:
|
||||
no Mac monospace face carries the Braille Patterns block, so the charts are borrowed from a
|
||||
*proportional* face and land at the wrong width (:mod:`meshterm.core.macterminal`). One
|
||||
host shows nothing, the other shows something crooked.
|
||||
|
||||
The destinations could hardly be less alike. The act is the same one: work out the command
|
||||
that would start this session again, hand it an environment a fresh launch can survive, and
|
||||
let the caller exit. So it is written once, here, and each platform module supplies only
|
||||
the part that is genuinely its own — which terminal, and how to ask it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
#: Set in the reopened session, so a relaunch can never chain into another one. Each
|
||||
#: platform's own gate would usually refuse a second pass anyway — Windows Terminal is not
|
||||
#: a classic console; a window opened from MeshTerm's profile is already in it — but this
|
||||
#: is the belt to those braces, and it costs one environment variable.
|
||||
REOPENED_ENV = "MESHTERM_REOPENED"
|
||||
|
||||
|
||||
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 the receiving terminal can be relied on to resolve.
|
||||
|
||||
Returns:
|
||||
The program and its arguments, ready to hand to a terminal.
|
||||
"""
|
||||
if getattr(sys, "frozen", False):
|
||||
return [sys.executable, *sys.argv[1:]]
|
||||
return [sys.executable, "-m", "meshterm", *sys.argv[1:]]
|
||||
|
||||
|
||||
def child_environment() -> dict[str, str]:
|
||||
"""The environment for a fresh launch of MeshTerm, minus this bundle's bookkeeping.
|
||||
|
||||
A PyInstaller one-file build runs in two stages: the executable unpacks itself into a
|
||||
temporary directory and then runs itself again as a child, the two halves coordinating
|
||||
through ``_PYI*`` environment variables. Those must not reach a *new* launch of the
|
||||
executable. The bootloader would find them, conclude it is the second stage of a launch
|
||||
it never made, check that its parent is the same program — find the terminal instead —
|
||||
and abort::
|
||||
|
||||
[PYI-33368:ERROR] Security validation failure: parent process has different
|
||||
executable!
|
||||
|
||||
Which is the whole session gone, in a brand new window holding a message nobody can act
|
||||
on, while the window that offered the move has already closed. Removing them makes the
|
||||
new process a first stage, which is what it actually is.
|
||||
|
||||
Returns:
|
||||
The environment to start the new process with.
|
||||
"""
|
||||
environment = dict(os.environ)
|
||||
environment[REOPENED_ENV] = "1"
|
||||
if not getattr(sys, "frozen", False):
|
||||
return environment
|
||||
|
||||
for key in [key for key in environment if key.startswith("_PYI")]:
|
||||
del environment[key]
|
||||
environment.pop("_MEIPASS2", None) # the name older bootloaders used
|
||||
# The bootloader points the loader at the unpacked bundle and parks the caller's own
|
||||
# value beside it. The new process unpacks its own copy, so it wants the original.
|
||||
for name in ("LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH", "DYLD_FRAMEWORK_PATH"):
|
||||
original = environment.pop(f"{name}_ORIG", None)
|
||||
if original is not None:
|
||||
environment[name] = original
|
||||
else:
|
||||
environment.pop(name, None)
|
||||
return environment
|
||||
|
||||
|
||||
def wanted_size() -> tuple[int, int]:
|
||||
"""The window to ask for, as ``(cols, rows)``.
|
||||
|
||||
Asked for, because a window MeshTerm opens should be one MeshTerm fits in. A session
|
||||
that lands in whatever size the reader's shell happens to launch at can arrive too
|
||||
small for the app, and the failure is quiet and cosmetic: the startup wordmark is 71
|
||||
columns, so at 70 it silently swaps to the narrow one drawn for the PicoCalc, and a
|
||||
short window truncates every description onto the pager.
|
||||
|
||||
The numbers come from the platform's own stated minimum plus a margin, so they follow
|
||||
it rather than repeating it. A terminal is free to clamp to what the display can show,
|
||||
so this is a request and not a demand — on a small screen the app degrades exactly as
|
||||
it would have anyway.
|
||||
|
||||
Returns:
|
||||
The columns and rows to ask the terminal for.
|
||||
"""
|
||||
from ..platforms import get_platform
|
||||
|
||||
platform = get_platform()
|
||||
return platform.readable_cols + 8, platform.readable_rows + 6
|
||||
@@ -30,10 +30,15 @@ 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"
|
||||
from .relaunch import REOPENED_ENV, child_environment, own_command, wanted_size
|
||||
|
||||
__all__ = [
|
||||
"REOPENED_ENV",
|
||||
"available",
|
||||
"child_environment",
|
||||
"own_command",
|
||||
"reopen",
|
||||
]
|
||||
|
||||
|
||||
def available() -> str | None:
|
||||
@@ -47,60 +52,6 @@ def available() -> str | 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 child_environment() -> dict[str, str]:
|
||||
"""The environment for a fresh launch of MeshTerm, minus this bundle's bookkeeping.
|
||||
|
||||
A PyInstaller one-file build runs in two stages: the executable unpacks itself into a
|
||||
temporary directory and then runs itself again as a child, the two halves coordinating
|
||||
through ``_PYI*`` environment variables. Those must not reach a *new* launch of the
|
||||
executable. The bootloader would find them, conclude it is the second stage of a launch
|
||||
it never made, check that its parent is the same program — find Windows Terminal
|
||||
instead — and abort::
|
||||
|
||||
[PYI-33368:ERROR] Security validation failure: parent process has different
|
||||
executable!
|
||||
|
||||
Which is the whole session gone, in a brand new window holding a message nobody can act
|
||||
on, while the window that offered the move has already closed. Removing them makes the
|
||||
new process a first stage, which is what it actually is.
|
||||
|
||||
Returns:
|
||||
The environment to start the new process with.
|
||||
"""
|
||||
environment = dict(os.environ)
|
||||
environment[REOPENED_ENV] = "1"
|
||||
if not getattr(sys, "frozen", False):
|
||||
return environment
|
||||
|
||||
for key in [key for key in environment if key.startswith("_PYI")]:
|
||||
del environment[key]
|
||||
environment.pop("_MEIPASS2", None) # the name older bootloaders used
|
||||
# The bootloader points the loader at the unpacked bundle and parks the caller's own
|
||||
# value beside it. The new process unpacks its own copy, so it wants the original.
|
||||
for name in ("LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH", "DYLD_FRAMEWORK_PATH"):
|
||||
original = environment.pop(f"{name}_ORIG", None)
|
||||
if original is not None:
|
||||
environment[name] = original
|
||||
else:
|
||||
environment.pop(name, None)
|
||||
return environment
|
||||
|
||||
|
||||
def reopen() -> bool:
|
||||
"""Start this session again in Windows Terminal, in the same directory.
|
||||
|
||||
@@ -148,20 +99,12 @@ def reopen() -> bool:
|
||||
def _wanted_size() -> str:
|
||||
"""The window to ask Windows Terminal for, as ``cols,rows``.
|
||||
|
||||
Asked for, because a window MeshTerm opens should be one MeshTerm fits in. Without
|
||||
``-w new`` the session lands as a *tab* in whatever window happens to be open and
|
||||
inherits its size; without ``--size`` a new window takes the reader's global launch
|
||||
size, which is a setting about their shell and not about this app. Either way the app
|
||||
can arrive in a window too small for it, and the failure is quiet and cosmetic: the
|
||||
startup wordmark is 71 columns, so at 70 it silently swaps to the narrow one drawn for
|
||||
the PicoCalc, and a short window truncates every description onto the pager.
|
||||
|
||||
The numbers come from the platform's own stated minimum plus a margin, so they follow
|
||||
it rather than repeating it. Windows Terminal clamps to what the display can show, so
|
||||
this is a request and not a demand — on a small screen the app degrades exactly as it
|
||||
would have anyway.
|
||||
Asked for, because without ``-w new`` the session lands as a *tab* in whatever window
|
||||
happens to be open and inherits its size, and without ``--size`` a new window takes the
|
||||
reader's global launch size, which is a setting about their shell and not about this
|
||||
app. The dimensions themselves are
|
||||
:func:`~meshterm.core.relaunch.wanted_size`'s, shared with every other terminal
|
||||
MeshTerm reopens itself in; only the spelling is Windows Terminal's.
|
||||
"""
|
||||
from ..platforms import get_platform
|
||||
|
||||
platform = get_platform()
|
||||
return f"{platform.readable_cols + 8},{platform.readable_rows + 6}"
|
||||
cols, rows = wanted_size()
|
||||
return f"{cols},{rows}"
|
||||
@@ -0,0 +1,170 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""The macOS Terminal profile: what it says, and what it refuses to touch.
|
||||
|
||||
The archive shapes here were not invented. They were read back off a profile installed on
|
||||
a real Mac and confirmed rendering — so the encoder is pinned to bytes that are known to
|
||||
work, rather than to a reading of Apple's format.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import plistlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from meshterm.core import macterminal
|
||||
from meshterm.core.relaunch import REOPENED_ENV
|
||||
from meshterm.ui.theme import _VT_SLOTS
|
||||
|
||||
|
||||
def test_color_archive_is_the_shape_appkit_writes() -> None:
|
||||
"""A colour decodes to a calibrated-RGB ``NSColor``, six places and NUL-terminated."""
|
||||
decoded = plistlib.loads(macterminal.ns_color("#aa0000"))
|
||||
|
||||
assert decoded["$archiver"] == "NSKeyedArchiver"
|
||||
assert decoded["$version"] == 100000
|
||||
colour = decoded["$objects"][1]
|
||||
assert colour["NSColorSpace"] == 1
|
||||
assert colour["NSRGB"] == b"0.666667 0.000000 0.000000\x00"
|
||||
assert decoded["$objects"][2]["$classname"] == "NSColor"
|
||||
|
||||
|
||||
def test_font_archive_names_the_bundled_face() -> None:
|
||||
"""The font archive carries the PostScript name, not the family name."""
|
||||
decoded = plistlib.loads(macterminal.ns_font())
|
||||
|
||||
assert macterminal.FONT_FACE in decoded["$objects"]
|
||||
assert decoded["$objects"][1]["NSSize"] == macterminal.FONT_SIZE
|
||||
assert decoded["$objects"][3]["$classname"] == "NSFont"
|
||||
|
||||
|
||||
def test_every_palette_slot_comes_from_the_theme() -> None:
|
||||
"""The window cannot disagree with the screen it is holding.
|
||||
|
||||
Sixteen keys, in the dim-then-bright order Terminal expects, each one the theme's own
|
||||
hex. A slot changed in :data:`~meshterm.ui.theme._VT_SLOTS` lands here on the next
|
||||
write, which is the reason the profile is generated rather than shipped.
|
||||
"""
|
||||
profile = macterminal.build_profile()
|
||||
|
||||
assert len(macterminal._ANSI_KEYS) == len(_VT_SLOTS) == 16
|
||||
for key, (_slot, _label, rgb) in zip(macterminal._ANSI_KEYS, _VT_SLOTS, strict=True):
|
||||
assert profile[key] == macterminal.ns_color(rgb), key
|
||||
|
||||
|
||||
def test_the_window_is_opaque_and_bold_is_not_brightness() -> None:
|
||||
"""The two settings the profile exists to guarantee, beside the font."""
|
||||
profile = macterminal.build_profile()
|
||||
|
||||
assert profile["BackgroundColor"] == macterminal.ns_color("#000000")
|
||||
assert "BackgroundBlur" not in profile
|
||||
assert profile["UseBrightBold"] is False
|
||||
|
||||
|
||||
def test_a_bare_profile_runs_nothing() -> None:
|
||||
"""Without a command it is an entry in the list, not a launcher."""
|
||||
profile = macterminal.build_profile()
|
||||
|
||||
assert "CommandString" not in profile
|
||||
assert "RunCommandAsShell" not in profile
|
||||
|
||||
|
||||
def test_the_profile_round_trips_as_a_terminal_file() -> None:
|
||||
"""What is written is what Terminal reads: a plist, with the nested archives intact."""
|
||||
written = plistlib.dumps(macterminal.build_profile("true"), fmt=plistlib.FMT_XML)
|
||||
reloaded = plistlib.loads(written)
|
||||
|
||||
assert reloaded["name"] == macterminal.PROFILE_NAME
|
||||
assert reloaded["type"] == "Window Settings"
|
||||
assert reloaded["CommandString"] == "true"
|
||||
assert plistlib.loads(reloaded["ANSIRedColor"])["$objects"][1]["NSColorSpace"] == 1
|
||||
|
||||
|
||||
def test_launch_command_carries_meshterm_variables_and_the_marker(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Terminal starts the command from a fresh shell, so what it needs travels with it."""
|
||||
monkeypatch.setenv("MESHTERM_HOME", "/Users/someone/meshterm test")
|
||||
monkeypatch.delenv(REOPENED_ENV, raising=False)
|
||||
monkeypatch.setattr(sys, "argv", ["meshterm", "--mock"])
|
||||
|
||||
command = macterminal.launch_command()
|
||||
|
||||
assert f"{REOPENED_ENV}=1" in command
|
||||
# Quoted, because the reader's path may contain a space and the shell would split it.
|
||||
assert "MESHTERM_HOME='/Users/someone/meshterm test'" in command
|
||||
assert command.split("exec ", 1)[1].endswith("--mock")
|
||||
assert " exec " in command
|
||||
|
||||
|
||||
def test_an_unrelated_variable_is_not_carried(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""The hop is not a chance to launder the whole environment into a new shell."""
|
||||
monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "nope")
|
||||
|
||||
assert "AWS_SECRET_ACCESS_KEY" not in macterminal.launch_command()
|
||||
|
||||
|
||||
def test_a_reopened_session_never_reopens_again(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""The guard that keeps a relaunch from chaining, since the profile's command sets it."""
|
||||
monkeypatch.setattr(sys, "platform", "darwin")
|
||||
monkeypatch.setenv("TERM_PROGRAM", "Apple_Terminal")
|
||||
monkeypatch.setenv(REOPENED_ENV, "1")
|
||||
|
||||
assert macterminal.available() is False
|
||||
assert macterminal.reopen() is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("program", ["iTerm.app", "ghostty", "vscode", "WezTerm"])
|
||||
def test_another_terminal_is_left_alone(program: str, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Nothing is offered to a terminal that already has truecolor and a chosen font."""
|
||||
monkeypatch.setattr(sys, "platform", "darwin")
|
||||
monkeypatch.delenv(REOPENED_ENV, raising=False)
|
||||
monkeypatch.setenv("TERM_PROGRAM", program)
|
||||
|
||||
assert macterminal.in_apple_terminal() is False
|
||||
assert macterminal.available() is False
|
||||
|
||||
|
||||
def test_nothing_happens_off_macos(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Every entry point is inert on the platforms this module is not about."""
|
||||
monkeypatch.setattr(sys, "platform", "win32")
|
||||
monkeypatch.setenv("TERM_PROGRAM", "Apple_Terminal")
|
||||
|
||||
assert macterminal.in_apple_terminal() is False
|
||||
assert macterminal.available() is False
|
||||
assert macterminal.reopen() is False
|
||||
assert macterminal.install_font() is False
|
||||
|
||||
|
||||
def test_the_profile_is_written_under_meshterm_home(
|
||||
tmp_path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""It lives in MeshTerm's own directory, and follows ``MESHTERM_HOME`` when set."""
|
||||
monkeypatch.setenv("MESHTERM_HOME", str(tmp_path / "home"))
|
||||
|
||||
path = macterminal.write_profile()
|
||||
|
||||
assert path == tmp_path / "home" / "MeshTerm.terminal"
|
||||
assert plistlib.loads(path.read_bytes())["name"] == "MeshTerm"
|
||||
|
||||
|
||||
def test_the_readers_preferences_are_never_named(tmp_path, monkeypatch) -> None:
|
||||
"""Terminal discards external edits to its prefs on quit, so nothing here writes them.
|
||||
|
||||
A guard against the obvious future shortcut rather than against today's code: the
|
||||
whole design rests on handing Terminal a file and letting it do the importing.
|
||||
"""
|
||||
source = (macterminal.__file__).replace(".pyc", ".py")
|
||||
with open(source, encoding="utf-8") as handle:
|
||||
body = handle.read().split('"""', 2)[2]
|
||||
|
||||
assert "com.apple.Terminal.plist" not in body
|
||||
assert "Library/Preferences" not in body
|
||||
assert "defaults" not in body.replace("default_config_dir", "")
|
||||
|
||||
|
||||
def test_the_font_goes_to_the_users_own_library() -> None:
|
||||
"""No administrator rights, and undoable from Font Book."""
|
||||
assert macterminal.USER_FONT_DIR == Path.home() / "Library" / "Fonts"
|
||||
Reference in new issue
Block a user