speedpulse 0.1.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
speedpulse/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """SpeedPulse: cross-platform internet speed monitor for the system tray."""
2
+
3
+ __version__ = "0.1.3"
4
+ APP_NAME = "SpeedPulse"
speedpulse/__main__.py ADDED
@@ -0,0 +1,10 @@
1
+ """``python -m speedpulse`` entry point.
2
+
3
+ Must use absolute imports: PyInstaller also executes this file as the
4
+ bundled launcher, where relative imports have no parent package.
5
+ """
6
+
7
+ from speedpulse.app import main
8
+
9
+ if __name__ == "__main__":
10
+ raise SystemExit(main())
speedpulse/app.py ADDED
@@ -0,0 +1,98 @@
1
+ """Composition root: parse args, wire core + UI, run the Qt event loop."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import logging
7
+ import signal
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ from PySide6 import QtCore, QtWidgets
12
+
13
+ from . import APP_NAME, __version__
14
+ from .core.autostart import get_autostart
15
+ from .core.config import config_path, load
16
+ from .core.sampler import Sampler
17
+ from .core.singleinstance import SingleInstanceLock
18
+ from .ui.tray import SpeedPulseTray
19
+
20
+ log = logging.getLogger(APP_NAME.lower())
21
+
22
+
23
+ def main(argv: list[str] | None = None) -> int:
24
+ parser = argparse.ArgumentParser(
25
+ prog="speedpulse",
26
+ description="Internet speed monitor for your system tray.",
27
+ )
28
+ parser.add_argument("--config", type=Path, default=None, help="path to config.toml")
29
+ parser.add_argument("-v", "--verbose", action="store_true", help="debug logging")
30
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
31
+ args = parser.parse_args(argv)
32
+
33
+ logging.basicConfig(
34
+ level=logging.DEBUG if args.verbose else logging.INFO,
35
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s",
36
+ )
37
+
38
+ lock = SingleInstanceLock()
39
+ if not lock.acquire():
40
+ log.info("%s is already running; exiting.", APP_NAME)
41
+ return 0
42
+
43
+ settings_path = args.config or config_path()
44
+ settings = load(settings_path)
45
+ log.info("Starting %s %s (config: %s)", APP_NAME, __version__, settings_path)
46
+
47
+ app = QtWidgets.QApplication(sys.argv)
48
+ app.setApplicationName(APP_NAME)
49
+ app.setApplicationVersion(__version__)
50
+ app.setApplicationDisplayName(APP_NAME)
51
+ # The tray icon *is* the app; closing the settings window must not quit.
52
+ app.setQuitOnLastWindowClosed(False)
53
+
54
+ sampler = Sampler(settings.sampler)
55
+ tray = SpeedPulseTray(
56
+ settings=settings,
57
+ settings_path=settings_path,
58
+ sampler=sampler,
59
+ autostart=get_autostart(),
60
+ )
61
+ tray.welcome()
62
+
63
+ _install_signal_handlers(app)
64
+
65
+ try:
66
+ code = app.exec()
67
+ finally:
68
+ tray.shutdown()
69
+ lock.release()
70
+ return code
71
+
72
+
73
+ def _install_signal_handlers(app: QtWidgets.QApplication) -> None:
74
+ """Route SIGINT/SIGTERM into Qt's quit path.
75
+
76
+ During ``app.exec()`` the interpreter only gets control back when a
77
+ Python callback runs, so a short no-op timer keeps signal handlers
78
+ alive; otherwise Ctrl+C would appear dead until the next event.
79
+ """
80
+
81
+ def _quit(*_args: object) -> None:
82
+ app.quit()
83
+
84
+ for sig in (signal.SIGINT, signal.SIGTERM):
85
+ try:
86
+ signal.signal(sig, _quit)
87
+ except (OSError, ValueError): # pragma: no cover - platform-dependent
88
+ log.debug("Could not install handler for %s", sig)
89
+ keepalive = QtCore.QTimer()
90
+ keepalive.timeout.connect(lambda: None)
91
+ keepalive.start(250)
92
+ # Keep a reference for the app's lifetime (QTimer with no parent would
93
+ # otherwise be garbage-collected, silently breaking Ctrl+C).
94
+ app._speedpulse_keepalive = keepalive # type: ignore[attr-defined]
95
+
96
+
97
+ if __name__ == "__main__":
98
+ sys.exit(main())
@@ -0,0 +1,5 @@
1
+ """Pure, headless-testable core: measurement, units, config, autostart.
2
+
3
+ Nothing in this package may import a GUI toolkit. The UI layer
4
+ (:mod:`speedpulse.ui`) adapts these primitives to the system tray.
5
+ """
@@ -0,0 +1,257 @@
1
+ """Launch-at-login support, app-managed (no installer hooks).
2
+
3
+ Per-OS mechanism:
4
+
5
+ * Linux: XDG autostart ``~/.config/autostart/speedpulse.desktop``
6
+ * Windows: ``HKCU\\...\\CurrentVersion\\Run`` registry value
7
+ * macOS: LaunchAgent plist in ``~/Library/LaunchAgents``
8
+
9
+ macOS notes (researched): SMAppService would be the modern API but it is
10
+ unreliable for ad-hoc-signed PyInstaller bundles (``kSMErrorInvalidSignature``),
11
+ so a runtime-written plist is the robust default until Developer-ID signing
12
+ exists. We refuse to register from an App-Translocation path and strip the
13
+ quarantine xattr from the plist (macOS 27's launchd refuses quarantined
14
+ plists). App Translocation gives a randomised path, so registering from it
15
+ would break at next login anyway.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import logging
21
+ import plistlib
22
+ import re
23
+ import subprocess
24
+ import sys
25
+ from abc import ABC, abstractmethod
26
+ from pathlib import Path
27
+
28
+ log = logging.getLogger(__name__)
29
+
30
+ APP_VALUE_NAME = "SpeedPulse"
31
+ MACOS_LABEL = "org.speedpulse.app"
32
+
33
+
34
+ class AutostartError(RuntimeError):
35
+ """Raised when launch-at-login cannot be configured."""
36
+
37
+
38
+ def app_command() -> list[str]:
39
+ """Command line that relaunches this app in the current install mode."""
40
+ if getattr(sys, "frozen", False):
41
+ return [sys.executable]
42
+ exe = Path(sys.executable)
43
+ if sys.platform == "win32":
44
+ pythonw = exe.with_name("pythonw.exe")
45
+ if pythonw.exists():
46
+ return [str(pythonw), "-m", "speedpulse"]
47
+ return [sys.executable, "-m", "speedpulse"]
48
+
49
+
50
+ def _quote_exec_part(part: str) -> str:
51
+ """Quote one argv element for a freedesktop Exec line.
52
+
53
+ Everything is quoted (the spec permits it unconditionally); inside
54
+ double quotes ``"`` and ``\\`` must be escaped, and a literal ``%``
55
+ must be doubled because Exec treats bare ``%`` as a field code.
56
+ """
57
+ escaped = part.replace("\\", "\\\\").replace('"', '\\"').replace("%", "%%")
58
+ return f'"{escaped}"'
59
+
60
+
61
+ def _quote_exec(command: list[str]) -> str:
62
+ return " ".join(_quote_exec_part(part) for part in command)
63
+
64
+
65
+ class AutostartBase(ABC):
66
+ def __init__(self, base_dir: Path | None = None) -> None:
67
+ self._base_dir = base_dir
68
+
69
+ @abstractmethod
70
+ def enable(self) -> None:
71
+ """Register launch-at-login; idempotent."""
72
+
73
+ @abstractmethod
74
+ def disable(self) -> None:
75
+ """Unregister launch-at-login; idempotent, no error if absent."""
76
+
77
+ @abstractmethod
78
+ def is_enabled(self) -> bool:
79
+ """Whether the OS currently has a *live* registration for this app.
80
+
81
+ Implementations must verify the registration still points at this
82
+ install, not merely that a file/key exists — otherwise a moved or
83
+ deleted app leaves a dead registration that the UI reports as on.
84
+ """
85
+
86
+
87
+ class LinuxAutostart(AutostartBase):
88
+ FILENAME = "speedpulse.desktop"
89
+
90
+ _EXEC_LINE_RE = re.compile(r"^Exec=(.*)$", re.MULTILINE)
91
+
92
+ _TEMPLATE = """[Desktop Entry]
93
+ Type=Application
94
+ Name=SpeedPulse
95
+ Comment=Internet speed monitor in your system tray
96
+ Exec={exec}
97
+ Terminal=false
98
+ Categories=Network;Monitor;
99
+ X-GNOME-Autostart-enabled=true
100
+ """
101
+
102
+ def _path(self) -> Path:
103
+ base = self._base_dir or Path.home() / ".config"
104
+ return base / "autostart" / self.FILENAME
105
+
106
+ def enable(self) -> None:
107
+ path = self._path()
108
+ path.parent.mkdir(parents=True, exist_ok=True)
109
+ path.write_text(self._TEMPLATE.format(exec=_quote_exec(app_command())), encoding="utf-8")
110
+ log.info("Autostart enabled via %s", path)
111
+
112
+ def disable(self) -> None:
113
+ self._path().unlink(missing_ok=True)
114
+
115
+ def is_enabled(self) -> bool:
116
+ path = self._path()
117
+ if not path.exists():
118
+ return False
119
+ try:
120
+ text = path.read_text(encoding="utf-8")
121
+ except OSError:
122
+ return False
123
+ # Compare the *parsed* Exec value against the escaped form of the
124
+ # current command: raw substring matching fails on Windows paths
125
+ # because enable() escapes backslashes (C:\app -> "C:\\app").
126
+ match = self._EXEC_LINE_RE.search(text)
127
+ if not match:
128
+ return False
129
+ return match.group(1).strip() == _quote_exec(app_command())
130
+
131
+
132
+ class WindowsAutostart(AutostartBase):
133
+ RUN_KEY = r"Software\Microsoft\Windows\CurrentVersion\Run"
134
+
135
+ def enable(self) -> None:
136
+ import winreg
137
+
138
+ value = subprocess.list2cmdline(app_command())
139
+ with winreg.CreateKey( # pyright: ignore[reportAttributeAccessIssue]
140
+ winreg.HKEY_CURRENT_USER, # pyright: ignore[reportAttributeAccessIssue]
141
+ self.RUN_KEY,
142
+ ) as key:
143
+ winreg.SetValueEx(key, APP_VALUE_NAME, 0, winreg.REG_SZ, value) # pyright: ignore[reportAttributeAccessIssue]
144
+ log.info("Autostart enabled via HKCU Run key")
145
+
146
+ def disable(self) -> None:
147
+ import winreg
148
+
149
+ try:
150
+ with winreg.OpenKey( # pyright: ignore[reportAttributeAccessIssue]
151
+ winreg.HKEY_CURRENT_USER, # pyright: ignore[reportAttributeAccessIssue]
152
+ self.RUN_KEY,
153
+ 0,
154
+ winreg.KEY_SET_VALUE, # pyright: ignore[reportAttributeAccessIssue]
155
+ ) as key:
156
+ winreg.DeleteValue(key, APP_VALUE_NAME) # pyright: ignore[reportAttributeAccessIssue]
157
+ except FileNotFoundError:
158
+ pass
159
+ except OSError as exc:
160
+ log.warning("Could not remove autostart value: %s", exc)
161
+
162
+ def is_enabled(self) -> bool:
163
+ import winreg
164
+
165
+ try:
166
+ with winreg.OpenKey( # pyright: ignore[reportAttributeAccessIssue]
167
+ winreg.HKEY_CURRENT_USER, # pyright: ignore[reportAttributeAccessIssue]
168
+ self.RUN_KEY,
169
+ 0,
170
+ winreg.KEY_QUERY_VALUE, # pyright: ignore[reportAttributeAccessIssue]
171
+ ) as key:
172
+ stored = winreg.QueryValueEx(key, APP_VALUE_NAME)[0] # pyright: ignore[reportAttributeAccessIssue]
173
+ except OSError:
174
+ return False
175
+ # Registration must match this install, not just exist.
176
+ return stored == subprocess.list2cmdline(app_command())
177
+
178
+
179
+ class MacOSAutostart(AutostartBase):
180
+ def _path(self) -> Path:
181
+ base = self._base_dir or Path.home() / "Library"
182
+ return base / "LaunchAgents" / f"{MACOS_LABEL}.plist"
183
+
184
+ def enable(self) -> None:
185
+ _reject_translocation()
186
+ path = self._path()
187
+ path.parent.mkdir(parents=True, exist_ok=True)
188
+ plist = {
189
+ "Label": MACOS_LABEL,
190
+ "ProgramArguments": app_command(),
191
+ "RunAtLoad": True,
192
+ "KeepAlive": False,
193
+ }
194
+ with path.open("wb") as fh:
195
+ plistlib.dump(plist, fh)
196
+ _strip_quarantine(path)
197
+ log.info("Autostart enabled via %s", path)
198
+
199
+ def disable(self) -> None:
200
+ self._path().unlink(missing_ok=True)
201
+
202
+ def is_enabled(self) -> bool:
203
+ path = self._path()
204
+ if not path.exists():
205
+ return False
206
+ try:
207
+ with path.open("rb") as fh:
208
+ data = plistlib.load(fh)
209
+ except (OSError, plistlib.InvalidFileException):
210
+ return False
211
+ if not isinstance(data, dict):
212
+ return False
213
+ arguments = data.get("ProgramArguments")
214
+ return isinstance(arguments, list) and bool(arguments) and arguments[0] == app_command()[0]
215
+
216
+
217
+ def _resolved_app_path() -> Path:
218
+ exe = Path(sys.executable).resolve()
219
+ if getattr(sys, "frozen", False):
220
+ # <Bundle>.app/Contents/MacOS/binary -> <Bundle>.app
221
+ for parent in exe.parents:
222
+ if parent.suffix == ".app":
223
+ return parent
224
+ return exe
225
+ return exe
226
+
227
+
228
+ def _reject_translocation() -> None:
229
+ resolved = str(_resolved_app_path())
230
+ if "AppTranslocation" in resolved:
231
+ raise AutostartError(
232
+ "The app is running from a translocated path. Move it to /Applications "
233
+ "first, then enable launch-at-login."
234
+ )
235
+
236
+
237
+ def _strip_quarantine(path: Path) -> None:
238
+ """Best-effort: macOS 27's launchd refuses quarantined plists.
239
+
240
+ Plists we write ourselves never get the xattr, but be defensive for
241
+ any path that might have picked it up (e.g. restored from archives).
242
+ """
243
+ if sys.platform != "darwin":
244
+ return
245
+ subprocess.run(
246
+ ["xattr", "-d", "com.apple.quarantine", str(path)],
247
+ capture_output=True,
248
+ check=False,
249
+ )
250
+
251
+
252
+ def get_autostart() -> AutostartBase:
253
+ if sys.platform == "win32":
254
+ return WindowsAutostart()
255
+ if sys.platform == "darwin":
256
+ return MacOSAutostart()
257
+ return LinuxAutostart()
@@ -0,0 +1,262 @@
1
+ """Settings: TOML on disk, dataclasses in memory.
2
+
3
+ Design rules:
4
+
5
+ * a missing, corrupt, or partial config file must never crash the app —
6
+ load falls back to defaults and logs a warning;
7
+ * unknown keys are ignored (forward compatibility);
8
+ * values are clamped into sane ranges;
9
+ * the writer emits a tiny, known-good subset of TOML (stdlib ``tomllib``
10
+ reads TOML but the stdlib cannot write it, and we avoid a dependency
11
+ for our flat schema).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import logging
18
+ import os
19
+ import sys
20
+ import tomllib
21
+ from dataclasses import asdict, dataclass, field
22
+ from pathlib import Path
23
+
24
+ log = logging.getLogger(__name__)
25
+
26
+ SCHEMA_VERSION = 1
27
+ MIN_INTERVAL_SECONDS = 0.25
28
+ MAX_INTERVAL_SECONDS = 10.0
29
+ THEMES = ("auto", "light", "dark")
30
+ TRAY_LAYOUTS = ("stacked", "wide")
31
+ MIN_TEXT_SCALE = 0.6
32
+ MAX_TEXT_SCALE = 2.0
33
+ MIN_WIDGET_FONT_PT = 8
34
+ MAX_WIDGET_FONT_PT = 96
35
+ MIN_WIDGET_W = 120
36
+ MAX_WIDGET_W = 1200
37
+ MIN_WIDGET_H = 50
38
+ MAX_WIDGET_H = 600
39
+
40
+
41
+ @dataclass
42
+ class UnitsConfig:
43
+ use_bits: bool = False
44
+ binary_units: bool = False
45
+
46
+
47
+ @dataclass
48
+ class DisplayConfig:
49
+ theme: str = "auto" # auto | light | dark
50
+ layout: str = "stacked" # stacked (two lines, square) | wide (side by side)
51
+ text_scale: float = 1.0 # tray text size multiplier
52
+ # Only used where the panel draws tray text (GNOME): show the rates as
53
+ # panel text next to the icon. Off -> icon-only, like every other desktop.
54
+ panel_text: bool = True
55
+
56
+
57
+ @dataclass
58
+ class WidgetConfig:
59
+ """Floating on-desktop rates display (for when the tray slot is too small)."""
60
+
61
+ enabled: bool = False # show at startup
62
+ font_pt: int = 28
63
+ x: int = 80
64
+ y: int = 80
65
+ width: int = 260
66
+ height: int = 90
67
+
68
+
69
+ @dataclass
70
+ class SamplerConfig:
71
+ interval_seconds: float = 1.0
72
+ max_gap_seconds: float = 10.0
73
+ include_vpn: bool = False
74
+ excluded_interfaces: list[str] = field(default_factory=list)
75
+
76
+
77
+ @dataclass
78
+ class Settings:
79
+ units: UnitsConfig = field(default_factory=UnitsConfig)
80
+ display: DisplayConfig = field(default_factory=DisplayConfig)
81
+ sampler: SamplerConfig = field(default_factory=SamplerConfig)
82
+ widget: WidgetConfig = field(default_factory=WidgetConfig)
83
+ autostart: bool = False
84
+
85
+
86
+ def config_dir() -> Path:
87
+ """Per-user configuration directory, respecting platform conventions."""
88
+ if sys.platform == "win32":
89
+ appdata = os.environ.get("APPDATA")
90
+ base = Path(appdata) if appdata else Path.home() / "AppData" / "Roaming"
91
+ return base / "SpeedPulse"
92
+ if sys.platform == "darwin":
93
+ return Path.home() / "Library" / "Application Support" / "SpeedPulse"
94
+ xdg = os.environ.get("XDG_CONFIG_HOME")
95
+ base = Path(xdg) if xdg else Path.home() / ".config"
96
+ return base / "speedpulse"
97
+
98
+
99
+ def config_path() -> Path:
100
+ return config_dir() / "config.toml"
101
+
102
+
103
+ def load(path: Path) -> Settings:
104
+ """Load settings, falling back to defaults for anything unusable."""
105
+ settings = Settings()
106
+ if not path.exists():
107
+ return settings
108
+ try:
109
+ with path.open("rb") as fh:
110
+ raw = tomllib.load(fh)
111
+ except (OSError, tomllib.TOMLDecodeError) as exc:
112
+ log.warning("Could not read config %s (%s); using defaults", path, exc)
113
+ return settings
114
+ _apply(settings.units, raw.get("units"), _UNITS_KEYS)
115
+ _apply(settings.display, raw.get("display"), _DISPLAY_KEYS)
116
+ _apply(settings.sampler, raw.get("sampler"), _SAMPLER_KEYS)
117
+ _apply(settings.widget, raw.get("widget"), _WIDGET_KEYS)
118
+ settings.autostart = _as_bool(raw.get("autostart"), settings.autostart)
119
+ return settings
120
+
121
+
122
+ _UNITS_KEYS = {"use_bits", "binary_units"}
123
+ _DISPLAY_KEYS = {"theme", "layout", "text_scale", "panel_text"}
124
+ _SAMPLER_KEYS = {"interval_seconds", "max_gap_seconds", "include_vpn", "excluded_interfaces"}
125
+ _WIDGET_KEYS = {"enabled", "font_pt", "x", "y", "width", "height"}
126
+
127
+
128
+ def _apply(target: object, section: object, known: set[str]) -> None:
129
+ if not isinstance(section, dict):
130
+ return
131
+ unknown = set(section) - known
132
+ if unknown:
133
+ log.debug("Ignoring unknown config keys: %s", ", ".join(sorted(unknown)))
134
+ for key in known & set(section):
135
+ value = section[key]
136
+ if key == "use_bits":
137
+ target.use_bits = _as_bool(value, target.use_bits) # type: ignore[attr-defined]
138
+ elif key == "binary_units":
139
+ target.binary_units = _as_bool(value, target.binary_units) # type: ignore[attr-defined]
140
+ elif key == "theme":
141
+ target.theme = _as_theme(value, target.theme) # type: ignore[attr-defined]
142
+ elif key == "layout":
143
+ target.layout = _as_layout(value, target.layout) # type: ignore[attr-defined]
144
+ elif key == "text_scale":
145
+ target.text_scale = _as_text_scale(value, target.text_scale) # type: ignore[attr-defined]
146
+ elif key == "panel_text":
147
+ target.panel_text = _as_bool(value, target.panel_text) # type: ignore[attr-defined]
148
+ elif key == "font_pt":
149
+ setattr(
150
+ target,
151
+ key,
152
+ _as_clamped_int(
153
+ value, getattr(target, key), MIN_WIDGET_FONT_PT, MAX_WIDGET_FONT_PT
154
+ ),
155
+ )
156
+ elif key == "x" or key == "y":
157
+ setattr(target, key, _as_int(value, getattr(target, key), -10000, 10000))
158
+ elif key == "width":
159
+ target.width = _as_clamped_int(value, target.width, MIN_WIDGET_W, MAX_WIDGET_W) # type: ignore[attr-defined]
160
+ elif key == "height":
161
+ target.height = _as_clamped_int(value, target.height, MIN_WIDGET_H, MAX_WIDGET_H) # type: ignore[attr-defined]
162
+ elif key == "interval_seconds":
163
+ target.interval_seconds = _as_interval(value, target.interval_seconds) # type: ignore[attr-defined]
164
+ elif key == "max_gap_seconds":
165
+ target.max_gap_seconds = _as_positive_float(value, target.max_gap_seconds) # type: ignore[attr-defined]
166
+ elif key == "include_vpn":
167
+ target.include_vpn = _as_bool(value, target.include_vpn) # type: ignore[attr-defined]
168
+ elif key == "excluded_interfaces":
169
+ target.excluded_interfaces = _as_str_list(value, target.excluded_interfaces) # type: ignore[attr-defined]
170
+ elif key == "enabled":
171
+ target.enabled = _as_bool(value, target.enabled) # type: ignore[attr-defined]
172
+
173
+
174
+ def _as_bool(value: object, default: bool) -> bool:
175
+ return value if isinstance(value, bool) else default
176
+
177
+
178
+ def _as_positive_float(value: object, default: float) -> float:
179
+ if isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0:
180
+ return float(value)
181
+ log.debug("Ignoring invalid float value: %r", value)
182
+ return default
183
+
184
+
185
+ def _as_interval(value: object, default: float) -> float:
186
+ candidate = _as_positive_float(value, default)
187
+ return min(max(candidate, MIN_INTERVAL_SECONDS), MAX_INTERVAL_SECONDS)
188
+
189
+
190
+ def _as_theme(value: object, default: str) -> str:
191
+ return value if value in THEMES else default
192
+
193
+
194
+ def _as_layout(value: object, default: str) -> str:
195
+ return value if value in TRAY_LAYOUTS else default
196
+
197
+
198
+ def _as_text_scale(value: object, default: float) -> float:
199
+ candidate = _as_positive_float(value, default)
200
+ return min(max(candidate, MIN_TEXT_SCALE), MAX_TEXT_SCALE)
201
+
202
+
203
+ def _as_int(value: object, default: int, low: int, high: int) -> int:
204
+ if isinstance(value, int) and not isinstance(value, bool):
205
+ return min(max(value, low), high)
206
+ log.debug("Ignoring invalid int value: %r", value)
207
+ return default
208
+
209
+
210
+ _as_clamped_int = _as_int
211
+
212
+
213
+ def _as_str_list(value: object, default: list[str]) -> list[str]:
214
+ if isinstance(value, list) and all(isinstance(item, str) for item in value):
215
+ return list(value)
216
+ log.debug("Ignoring invalid string list: %r", value)
217
+ return default
218
+
219
+
220
+ def save(path: Path, settings: Settings) -> None:
221
+ """Write settings as TOML atomically (interrupted saves never corrupt).
222
+
223
+ Writes to a sibling temp file, then ``os.replace`` — atomic on POSIX
224
+ and Windows, so a crash mid-write can never destroy the old config.
225
+ """
226
+ path.parent.mkdir(parents=True, exist_ok=True)
227
+ tmp = path.with_name(path.name + ".tmp")
228
+ tmp.write_text(_dump_toml(settings), encoding="utf-8")
229
+ os.replace(tmp, path)
230
+
231
+
232
+ def _dump_toml(settings: Settings) -> str:
233
+ data = asdict(settings)
234
+ # TOML: top-level keys must precede any [section] header, or they would
235
+ # silently become keys of the last section.
236
+ lines = [f"version = {SCHEMA_VERSION}"]
237
+ sections: list[tuple[str, dict]] = []
238
+ for section, values in data.items():
239
+ if isinstance(values, dict):
240
+ sections.append((section, values))
241
+ else:
242
+ lines.append(f"{section} = {_toml_value(values)}")
243
+ lines.append("")
244
+ for section, values in sections:
245
+ lines.append(f"[{section}]")
246
+ for key, value in values.items():
247
+ lines.append(f"{key} = {_toml_value(value)}")
248
+ lines.append("")
249
+ return "\n".join(lines).rstrip() + "\n"
250
+
251
+
252
+ def _toml_value(value: object) -> str:
253
+ if isinstance(value, bool):
254
+ return "true" if value else "false"
255
+ if isinstance(value, (int, float)):
256
+ return repr(value)
257
+ if isinstance(value, list):
258
+ return json.dumps(value, ensure_ascii=False) if value else "[]"
259
+ # ensure_ascii=False: JSON's surrogate-pair escapes (𝄞) are
260
+ # invalid in TOML, so emit non-ASCII characters literally instead (the
261
+ # file is written UTF-8). Standard escapes like \n and \" stay valid.
262
+ return json.dumps(str(value), ensure_ascii=False)