Files
MeshTerm/meshterm/tools/preferences.py
T
Jean-Pierre MartineauandClaude Opus 5 cef7a764af How MeshTerm behaves gets a page of its own
Three kinds of "setting" were tangled into two files and one of them had no
screen at all. The radio's settings live on the radio and are edited on Device
config. Machine setup -- where the database is, which companion to talk to --
stays in config.toml, a text editor's job. Everything in between was app
behaviour: six keys sitting in config.toml with nothing to open them, and a
dozen more that were only module constants a reader could never reach.

Those are preferences now, and they have a page. core/preferences.py is a
PrefSpec registry in the shape of the device-config one -- group, type, bounds,
help, and a default -- and the page is built from the same parts as the device
editor, deliberately: one grouped lane-aligned list, current -> new staged in
warn, Apply/Back appearing only once something is staged, the shared discard
confirm on the way out. Two editors that stage values should not be two screens
to learn. What it adds is a Defaults section holding one row that stages every
changed preference back to its built-in value; it is drawn only while a reset
would do something, and it stages rather than writes, so it is as reviewable and
as Esc-discardable as any other change and the file is still only ever written
by the one action at the bottom. Its rows scroll sideways where the device
editor's don't: the explanation is the widest thing on the row and the only part
that runs past the edge, so <-> slide it under a pinned setting and value.

The file is preferences.yaml and holds only the values you disagree with the
code about -- grouped and commented, each entry above its help and its default.
That is what lets a later change to a default reach an install that never asked
to be exempt; delete a line and the code takes over again. A hand edit gone
wrong costs that line, never the session.

Every preference is wired to something that reads it. ctx.preferences is the
explicit path; preferences.current() is for the render layer, which has no
context to reach through, the same reason get_platform() exists.

The About pages come along into a This app section, the third scope after this
node and other nodes, with Preferences leading it -- the one row there that
changes MeshTerm rather than describing it. A section of one would have broken
the menu's own no-bucket-of-one rule, and the app's scope is the honest home for
both halves anyway.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-05 15:36:40 -04:00

160 lines
6.1 KiB
Python

"""The ``preferences`` tool: how MeshTerm itself behaves.
Interactively it opens the Preferences page (see :mod:`meshterm.ui.preferences`), which
stages changes and hands them back here to write. On the CLI it exposes the same
preferences as ``show`` / ``get`` / ``set`` / ``reset``, so a value can be changed from a
shell — or from a script setting a machine up — without launching the full-screen session.
Everything funnels through :meth:`PreferencesTool.run`, which applies a list of operations
and saves the file once at the end: one write per invocation, whether it came from the page
staging eleven changes or from a single ``preferences set``.
This is deliberately the *app's* tool, not the radio's. It reads nothing from the
companion, transmits nothing, and works with no device attached at all — which is why it
leads the **This app** section (the third scope, after this node and other nodes) rather
than sitting beside Device config.
"""
from __future__ import annotations
from typing import Any, Optional
import typer
from ..context import AppContext
from ..core.preferences import PreferenceError, format_value, get_spec
from .base import Tool, ToolResult, register
@register
class PreferencesTool(Tool):
"""View and change MeshTerm's own preferences, saved to ``preferences.yaml``."""
name = "preferences"
title = "Preferences"
icon = "⚙"
help = "How MeshTerm behaves — startup, sending, history, …"
category = "This app"
order = 5 # leads the section: the one row there that changes MeshTerm, not describes it
async def prompt_params(self, ctx: AppContext) -> Optional[dict[str, Any]]:
"""Open the Preferences page and collect the changes it staged.
Args:
ctx: Shared application context.
Returns:
``{"ops": [("set", key, value), …]}`` to write, or ``None`` if the reader left
with nothing staged.
"""
from ..ui.preferences import edit_preferences
staged = await edit_preferences(ctx)
if not staged:
return None
return {"ops": [("set", key, value) for key, value in staged.items()]}
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
"""Apply a list of preference operations, saving the file once if anything changed.
Operations are ``("show",)``, ``("get", key)``, ``("set", key, value)``, and
``("reset",)``. They run in order, so a scripted ``set`` after a ``reset`` lands on
top of the defaults rather than under them.
Args:
ctx: Shared application context.
params: ``ops`` — the operations to perform.
Returns:
A :class:`ToolResult` counting the preferences changed.
Raises:
PreferenceError: If a key is unknown or a value fails its spec — reported
cleanly by the CLI rather than as a traceback.
"""
from ..ui.preferences import preferences_table
prefs = ctx.preferences
ops: list[tuple] = list(params.get("ops") or [])
changes = 0
for op in ops:
action = op[0]
if action == "show":
ctx.ui.show(preferences_table(prefs, ctx.console.width))
elif action == "get":
spec = get_spec(op[1])
where = "changed" if prefs.is_overridden(spec.key) else "default"
ctx.ui.show(
f"[accent]{spec.key}[/accent] = "
f"[brand]{format_value(spec, prefs.get(spec.key))}[/brand] ({where})"
)
elif action == "set":
before = prefs.get(op[1])
after = prefs.set(op[1], op[2])
if after != before:
changes += 1
elif action == "reset":
changes += prefs.reset()
if changes:
prefs.save()
plural = "" if changes == 1 else "s"
message = (
f"[ok]✓[/ok] saved [brand]{changes}[/brand] preference{plural} to "
f"[accent]{prefs.path}[/accent]"
if changes
else None
)
return ToolResult(summary={"changes": changes}, message=message)
# -- CLI --------------------------------------------------------------------
def register_cli(self, app: typer.Typer) -> None:
"""Register the ``preferences`` subcommand group.
Args:
app: The Typer application.
"""
from ..cli import run_tool_command
prefs_app = typer.Typer(
help=self.help, no_args_is_help=False, rich_markup_mode="rich"
)
@prefs_app.callback(invoke_without_command=True)
def _root(ctx: typer.Context) -> None:
"""Show every preference when no subcommand is given."""
if ctx.invoked_subcommand is None:
run_tool_command(self, {"ops": [("show",)]})
@prefs_app.command("show", help="Show every preference, its value, and its default")
def _show_cmd() -> None:
run_tool_command(self, {"ops": [("show",)]})
@prefs_app.command("get", help="Print one preference's value")
def _get_cmd(key: str = typer.Argument(..., help="Preference key")) -> None:
run_tool_command(self, {"ops": [("get", key)]})
@prefs_app.command("set", help="Set one preference to a value")
def _set_cmd(
key: str = typer.Argument(..., help="Preference key"),
value: str = typer.Argument(..., help="New value"),
) -> None:
run_tool_command(self, {"ops": [("set", key, value)]})
@prefs_app.command("reset", help="Return every preference to its built-in default")
def _reset_cmd(
yes: bool = typer.Option(False, "--yes", help="Skip the confirmation"),
) -> None:
if not yes:
raise typer.BadParameter(
"resetting drops every preference you have changed; pass --yes to confirm"
)
run_tool_command(self, {"ops": [("reset",)]})
app.add_typer(prefs_app, name=self.name)
__all__ = ["PreferencesTool", "PreferenceError"]