From d6e3f30b67f5a34bda3e171f3ca371328c0cfabc Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Mon, 26 Oct 2026 10:48:16 +0000 Subject: [PATCH] Persist application defaults and improve Home and form recovery --- docs/wiki/Configuration.md | 36 +++++++ docs/wiki/Scripting-and-Menus.md | 8 +- docs/wiki/Terminal-Experience.md | 15 +++ scripts/cli_smoke.py | 46 ++++++++- scripts/terminal_smoke.py | 41 ++++++++ src/SidePulse.Cli/Animations.cs | 13 +-- src/SidePulse.Cli/Commands.cs | 16 +++- src/SidePulse.Cli/Hooks.cs | 9 +- src/SidePulse.Cli/HostManagement.cs | 12 ++- src/SidePulse.Cli/Interactive.cs | 115 ++++++++++++++++++----- src/SidePulse.Cli/Program.cs | 1 + src/SidePulse.Cli/Settings.cs | 49 ++++++++++ src/SidePulse.Cli/ShellSession.cs | 105 ++++++++++++++++----- src/SidePulse.Cli/TerminalMode.cs | 2 +- src/SidePulse.Core/Preferences.cs | 61 ++++++++++++ tests/SidePulse.Tests/PreferenceTests.cs | 65 +++++++++++++ 16 files changed, 525 insertions(+), 69 deletions(-) create mode 100644 src/SidePulse.Cli/Settings.cs create mode 100644 src/SidePulse.Core/Preferences.cs create mode 100644 tests/SidePulse.Tests/PreferenceTests.cs diff --git a/docs/wiki/Configuration.md b/docs/wiki/Configuration.md index a08b02e..10a247f 100644 --- a/docs/wiki/Configuration.md +++ b/docs/wiki/Configuration.md @@ -37,3 +37,39 @@ Use bounded, redacted logs and a clear export preview. Track state changes, outp attempts and failures without retaining conversation content. Distinguish idle, unknown, stale and unreachable. Retention duration and completion display timeout remain concept-review decisions. + +## Implemented application defaults + +`spn settings show` displays the effective saved defaults and the settings path. +Use **Settings → Preferences** in the interactive shell, or: + +```powershell +spn settings set --phone iphone --brightness 60 --shell powershell +spn settings set --profile personal --model dot +spn settings set --auto --no-profile +spn settings set --brightness 80 --dry-run +spn settings show --json +spn settings reset +``` + +Replace `iphone` with a saved alias; `default` follows the designated default phone. +Use `--device ` for a preferred USB/SD output. Explicit command +output flags override the saved output. Otherwise the saved output wins over USB +discovery. A missing or failing preferred output produces an error; it never +redirects delivery to another device. `--auto` restores USB/default-phone discovery. + +Defaults are Auto output, 100% brightness, built-in state programs and the platform +export shell (PowerShell on Windows, Bash elsewhere). State sends and the host +use the selected profile/model and brightness; animation preview/apply use the +saved brightness/model unless explicitly overridden. Global brightness scales a +profile's own brightness. `state` and `host run/start` accept `--brightness`, +`--profile`, `--no-profile` and `--model` overrides. A preferred profile requires +an explicit model, so phone delivery does not need USB model detection. Restart +the host after changing its defaults. + +The versioned `settings.json` lives next to the protected phone store, under +`SIDEPULSE_NET_HOME` when specified. It contains aliases/paths and ordinary +preferences, never push tokens or command history. Reading defaults and previewing +settings do not create files or open the credential vault. Invalid or newer-schema +settings are preserved with a recovery message. `settings reset` explicitly replaces +settings with defaults; phone links, profiles and integration configurations remain. diff --git a/docs/wiki/Scripting-and-Menus.md b/docs/wiki/Scripting-and-Menus.md index 6a5b855..251b101 100644 --- a/docs/wiki/Scripting-and-Menus.md +++ b/docs/wiki/Scripting-and-Menus.md @@ -5,15 +5,17 @@ In a terminal, `spn` opens a persistent session. Bare groups `animations`, Up/Down select, Enter continues, Escape goes back one section. Escape at Home stays in the session; choose Quit to leave. `/` opens a searchable action palette. Commands and recoverable failures return to their section. Ctrl+C cancels a -running command; when idle it exits. The detached host keeps running. +running command or a form; on Home it exits. The detached host keeps running. Fully specified commands always execute directly. The legacy `host --phone default` shorthand remains supported. -Send state retains its output choice and Preview mode until the session ends. +Send state saves its preferred output across launches and retains Preview mode until the session ends. Choose a state and press Enter to send; there is no repeated target or Run/Copy dialog. Change output lists mounted devices and saved phones; Auto selects one USB device, otherwise the default/sole saved phone. Preview never sends. -Saved application-wide UI preferences and first-run installation are still planned. +Settings → Preferences saves output, brightness, profile/model and export shell; +see [[Configuration]]. Home shows these defaults, host status and the last action. +Esc/Ctrl+C cancels forms while retaining text for retry; Ctrl+U clears text. Advanced guided actions display a single-line script command before running. Review offers Run, Copy command, Choose shell and Back. Simple arguments remain unquoted. diff --git a/docs/wiki/Terminal-Experience.md b/docs/wiki/Terminal-Experience.md index cb1f365..1a2155e 100644 --- a/docs/wiki/Terminal-Experience.md +++ b/docs/wiki/Terminal-Experience.md @@ -42,3 +42,18 @@ spn doctor These commands are proposals, not installation instructions. Reserve `--quiet`, `--json`, `--no-color` and `--non-interactive`. Redirected stdout must not start an interactive dashboard. Hook commands never prompt and keep stdout empty. + +## Implemented preferences and Home + +The persistent shell now keeps preferred output, brightness, animation profile/LED +model and export shell across launches. **Settings → Preferences** edits these +values; [[Configuration]] documents the equivalent scripting commands. Preview mode +remains a session choice. Home displays these defaults, a bounded host-status query +and the last action in the current session, inside the same menu panel. + +Esc returns from menus, including the searchable `/` action palette. Esc or Ctrl+C +cancels shell forms and retains text for retry; Ctrl+U clears the current input. +Ctrl+C during an executing command requests cancellation, and Ctrl+C on Home exits. +Only successful settings saves change the preferred output. Errors leave the shell +open. This does not complete the proposed live dashboard, persistent activity history, +all specialized editor controls or real Windows Terminal acceptance. diff --git a/scripts/cli_smoke.py b/scripts/cli_smoke.py index 276f4e4..34b85eb 100644 --- a/scripts/cli_smoke.py +++ b/scripts/cli_smoke.py @@ -26,6 +26,46 @@ def run(*args, input=None): assert not disconnected.stdout and not disconnected.stderr with tempfile.TemporaryDirectory(prefix='SidePulse test ü ') as directory: child_env['SIDEPULSE_NET_HOME'] = str(Path(directory) / 'config') + settings_path = Path(child_env['SIDEPULSE_NET_HOME']) / 'settings.json' + initial = json.loads(run('settings', '--json').stdout) + assert initial['preferences']['Brightness'] == 100 and not settings_path.exists() + run('settings', 'set', '--brightness', '42', '--shell', 'bash', '--dry-run') + assert not settings_path.exists(), 'Settings preview wrote configuration' + run('settings', 'set', '--brightness', '42', '--shell', 'bash') + persisted = json.loads(run('settings', 'show', '--json').stdout)['preferences'] + assert persisted['Brightness'] == 42 and persisted['Shell'] == 'bash' + dimmed = json.loads(run('state', 'working', '--dry-run', '--json').stdout) + assert dimmed['program'].startswith('brightness 107\n') + explicit = json.loads(run('state', 'working', '--brightness', '10', '--dry-run', '--json').stdout) + assert explicit['program'].startswith('brightness 26\n') + run('profiles', 'set', 'personal', '--state', 'working', '--pattern', 'solid-green', '--brightness', '80') + run('settings', 'set', '--profile', 'personal', '--model', 'dot') + profiled = json.loads(run('state', 'working', '--dry-run', '--json').stdout) + assert '#00ff66' in profiled['program'].lower() + built_in = json.loads(run('state', 'working', '--no-profile', '--dry-run', '--json').stdout) + assert '#00e5ff' in built_in['program'].lower() + run('settings', 'set', '--no-profile') + target_default = Path(directory) / 'preferred' + target_override = Path(directory) / 'override' + for target_dir in (target_default, target_override): + target_dir.mkdir() + (target_dir / 'LEDS.LED').write_text('off') + run('settings', 'set', '--device', str(target_default)) + run('state', 'done') + assert '#00ff66' in (target_default / 'LEDS.LED').read_text() + run('state', 'waiting', '--device', str(target_override)) + assert '#ff9900' in (target_override / 'LEDS.LED').read_text() + assert '#00ff66' in (target_default / 'LEDS.LED').read_text() + run('settings', 'set', '--device', str(Path(directory) / 'missing')) + failed = subprocess.run([exe, 'state', 'error'], capture_output=True, env=child_env, timeout=10) + assert failed.returncode != 0, 'Missing preferred output silently switched targets' + before = settings_path.read_bytes() + run('state', 'done', '--dry-run') + assert before == settings_path.read_bytes() + settings_path.write_text('{broken') + failed = subprocess.run([exe, 'settings', 'show'], capture_output=True, env=child_env, timeout=10) + assert failed.returncode != 0 and settings_path.read_text() == '{broken' + run('settings', 'reset') checks = json.loads(run('doctor', '--json').stdout) assert all(check['Status'] != 'error' for check in checks) if os.name == 'nt' or os.environ.get('SIDEPULSE_NATIVE_VAULT_TESTS') == '1': @@ -54,8 +94,9 @@ def run(*args, input=None): assert 'exit 0' in hooks['preToolUse'][0]['bash'] refused = subprocess.run([exe, 'hook-config', '--exe', exe, '--output', str(config)], capture_output=True) assert refused.returncode != 0 + run('settings', 'set', '--device', directory, '--brightness', '42') with open(Path(directory) / 'host.log', 'w') as log: - host = subprocess.Popen([exe, 'host', '--device', directory, '--plain'], stdout=log, stderr=log) + host = subprocess.Popen([exe, 'host', '--plain'], stdout=log, stderr=log, env=child_env) try: # Repeated idempotent input accommodates host startup without a timing-only assertion. for attempt in range(30): @@ -69,6 +110,7 @@ def run(*args, input=None): assert result.returncode == 0 assert not result.stdout and not result.stderr if '#00e5ff' in target.read_text(): + assert target.read_text().startswith('brightness 107\n') break time.sleep(0.1) else: @@ -87,7 +129,7 @@ def run(*args, input=None): host.terminate() host.wait(timeout=10) # A forcibly terminated host must be restartable without manual socket cleanup. - restarted = subprocess.Popen([exe, 'host', '--device', directory, '--plain'], stdout=log, stderr=log) + restarted = subprocess.Popen([exe, 'host', '--plain'], stdout=log, stderr=log, env=child_env) try: for attempt in range(30): assert restarted.poll() is None, 'Restarted host exited: ' + (Path(directory) / 'host.log').read_text() diff --git a/scripts/terminal_smoke.py b/scripts/terminal_smoke.py index 3074122..2894ee8 100644 --- a/scripts/terminal_smoke.py +++ b/scripts/terminal_smoke.py @@ -34,6 +34,9 @@ def until(self, text): needle = text.encode('utf-8') deadline = time.monotonic() + 10 while time.monotonic() < deadline: + if needle in self.output: + self.output = self.output[self.output.index(needle) + len(needle):] + return if select.select([self.master], [], [], 0.1)[0]: try: data = os.read(self.master, 65536) @@ -113,6 +116,44 @@ def finish(self): if menu.process.poll() is None: menu.process.kill() + settings = Terminal([]) + try: + settings.until('Last action:') + settings.until('Quit') + settings.send(b'\x1b[B' * 4 + b'\r') + settings.until('Preferences') + settings.send(b'\r') + settings.until('Show settings') + settings.send(b'\x1b[B' * 2 + b'\r') + settings.until('input retained') + settings.send(b'\x15' + b'42\x03') + settings.until('Show settings') + settings.send(b'\r') + settings.until('input retained') + settings.send(b'\r') + settings.until('Show settings') + settings.send(b'\x1b') + settings.until('Diagnostics') + settings.send(b'\x1b') + settings.until('Brightness: 42%') + settings.until('Quit') + settings.send(b'\x1b[B' * 2 + b'\r') + settings.finish() + finally: + if settings.process.poll() is None: + settings.process.kill() + import json + assert json.loads((root / 'config' / 'settings.json').read_text())['Brightness'] == 42 + restarted = Terminal([]) + try: + restarted.until('Brightness: 42%') + restarted.until('Quit') + restarted.send(b'\x03') + restarted.finish() + finally: + if restarted.process.poll() is None: + restarted.process.kill() + file = root / 'custom.LED' editor = Terminal(['animations', 'edit', '--file', str(file), '--model', 'dot']) try: diff --git a/src/SidePulse.Cli/Animations.cs b/src/SidePulse.Cli/Animations.cs index 0307072..2b1bf14 100644 --- a/src/SidePulse.Cli/Animations.cs +++ b/src/SidePulse.Cli/Animations.cs @@ -10,8 +10,8 @@ public class PatternSettings : CommandSettings { [CommandArgument(0, "[NAME]")] public string? Name { get; init; } [CommandOption("--file ")] public string? File { get; init; } - [CommandOption("--model ")] public DeviceModel Model { get; init; } = DeviceModel.Dot; - [CommandOption("--brightness ")] public int? Brightness { get; init; } + [CommandOption("--model ")] public DeviceModel Model { get; init; } = PreferenceStore.Default.Read().Model ?? DeviceModel.Dot; + [CommandOption("--brightness ")] public int? Brightness { get; init; } = PreferenceStore.Default.Read().Brightness is var value && value != 100 ? value : null; [CommandOption("--json")] public bool Json { get; init; } public override ValidationResult Validate() { @@ -154,11 +154,12 @@ public sealed class PatternApplyCommand : AsyncCommand { public override async Task ExecuteAsync(CommandContext context, PatternApplySettings settings, CancellationToken cancellationToken) { - var model = settings.Model ?? AnimationLibrary.DetectModel(settings.Device); + var preferences = PreferenceStore.Default.Read(); + var model = settings.Model ?? preferences.Model ?? AnimationLibrary.DetectModel(settings.Device ?? preferences.Device); var raw = settings.File is { } file ? new LedProgram(await System.IO.File.ReadAllTextAsync(file, cancellationToken)) : AnimationLibrary.Default.Get(settings.Name!, model); - var program = AnimationLibrary.WithBrightness(raw, settings.Brightness); + var program = AnimationLibrary.WithBrightness(raw, settings.Brightness ?? (preferences.Brightness == 100 ? null : preferences.Brightness)); Animation.Parse(program, model); - await Delivery.Send(settings, program, cancellationToken); Delivery.Receipt(settings, program); + await Delivery.Send(settings, program, cancellationToken, preferences); Delivery.Receipt(settings, program); return 0; } } @@ -214,7 +215,7 @@ public override int Execute(CommandContext context, ProfileSettings settings, Ca if (!AnimationLibrary.Default.List().Any(p => p.Name == settings.Pattern)) throw new ArgumentException("Pattern was not found. Import it first."); AnimationProfile profile; try { profile = AnimationLibrary.Default.LoadProfile(settings.Name); } - catch (FileNotFoundException) { profile = new([]); } + catch (IOException ex) when (ex is FileNotFoundException or DirectoryNotFoundException) { profile = new([]); } profile.States[settings.State.Value] = settings.Pattern; profile = profile with { Brightness = settings.Brightness ?? profile.Brightness }; var path = AnimationLibrary.Default.SaveProfile(settings.Name, profile, true); diff --git a/src/SidePulse.Cli/Commands.cs b/src/SidePulse.Cli/Commands.cs index 44e4cb6..bfb742b 100644 --- a/src/SidePulse.Cli/Commands.cs +++ b/src/SidePulse.Cli/Commands.cs @@ -65,10 +65,10 @@ public override ValidationResult Validate() => new[] { Device, TokenEnvironment, public static class Delivery { - public static async Task Send(TargetSettings settings, LedProgram program, CancellationToken cancellationToken) + public static async Task Send(TargetSettings settings, LedProgram program, CancellationToken cancellationToken, Preferences? preferences = null) { if (settings.DryRun) return; - var target = OutputTarget.Resolve(settings.Device, settings.Phone, settings.TokenEnvironment, + var target = (preferences ?? PreferenceStore.Default.Read()).ResolveOutput(settings.Device, settings.Phone, settings.TokenEnvironment, DeviceTransport.Discover, () => File.Exists(LinkStore.DefaultPath) ? PhoneStores.Open().List() : []); if (target.Transport == OutputTransport.Phone) { @@ -95,12 +95,17 @@ public static void Receipt(TargetSettings settings, LedProgram program) public sealed class StateSettings : TargetSettings { + [CommandOption("--brightness ")] public int? Brightness { get; init; } + [CommandOption("--profile ")] public string? Profile { get; init; } + [CommandOption("--no-profile")] public bool NoProfile { get; init; } + [CommandOption("--model ")] public DeviceModel? Model { get; init; } [CommandArgument(0, "")] public AgentState State { get; init; } public override ValidationResult Validate() { var target = base.Validate(); if (!target.Successful) return target; + if (Brightness is < 0 or > 100 || Model is { } model && !Enum.IsDefined(model)) return ValidationResult.Error("Choose brightness 0..100 and model dot or pro."); return Enum.IsDefined(State) ? ValidationResult.Success() : ValidationResult.Error("Unknown agent state."); } } @@ -108,8 +113,11 @@ public sealed class StateCommand : AsyncCommand { public override async Task ExecuteAsync(CommandContext context, StateSettings settings, CancellationToken cancellationToken) { - var program = LedProgram.ForState(settings.State); - await Delivery.Send(settings, program, cancellationToken); + if (settings.NoProfile && settings.Profile is not null) throw new ArgumentException("Choose --profile or --no-profile."); + var preferences = PreferenceStore.Default.Read(); + var profile = settings.NoProfile ? null : settings.Profile ?? preferences.Profile; + var program = AnimationLibrary.WithBrightness(AnimationLibrary.ResolveProfile(profile, settings.Model ?? preferences.Model, settings.Device ?? preferences.Device)[settings.State], settings.Brightness ?? (preferences.Brightness == 100 ? null : preferences.Brightness)); + await Delivery.Send(settings, program, cancellationToken, preferences); Delivery.Receipt(settings, program); return 0; } diff --git a/src/SidePulse.Cli/Hooks.cs b/src/SidePulse.Cli/Hooks.cs index 6fe7927..ba0e9b7 100644 --- a/src/SidePulse.Cli/Hooks.cs +++ b/src/SidePulse.Cli/Hooks.cs @@ -96,6 +96,8 @@ public override async Task ExecuteAsync(CommandContext context, HookSetting } public sealed class HostSettings : TargetSettings { + [CommandOption("--no-profile")] public bool NoProfile { get; init; } + [CommandOption("--brightness ")] public int? Brightness { get; init; } [CommandOption("--profile ")] public string? Profile { get; init; } [CommandOption("--model ")] @@ -117,7 +119,10 @@ public sealed class HostCommand : AsyncCommand { public override async Task ExecuteAsync(CommandContext context, HostSettings settings, CancellationToken cancellationToken) { - var patterns = AnimationLibrary.ResolveProfile(settings.Profile, settings.Model, settings.Device); + if (settings.NoProfile && settings.Profile is not null) throw new ArgumentException("Choose --profile or --no-profile."); + var preferences = PreferenceStore.Default.Read(); + var patterns = AnimationLibrary.ResolveProfile(settings.NoProfile ? null : settings.Profile ?? preferences.Profile, settings.Model ?? preferences.Model, settings.Device ?? preferences.Device) + .ToDictionary(item => item.Key, item => AnimationLibrary.WithBrightness(item.Value, settings.Brightness ?? (preferences.Brightness == 100 ? null : preferences.Brightness))); if (settings.Background) HostLogs.Detach(); using var shutdown = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); ConsoleCancelEventHandler cancel = (_, args) => { args.Cancel = true; shutdown.Cancel(); }; @@ -134,7 +139,7 @@ public override async Task ExecuteAsync(CommandContext context, HostSetting { await foreach (var program in outputs.Reader.ReadAllAsync(shutdown.Token)) { - try { await Delivery.Send(settings, program, shutdown.Token); } + try { await Delivery.Send(settings, program, shutdown.Token, preferences); } catch (Exception ex) when (ex is IOException or ArgumentException or OperationCanceledException) { Console.Error.WriteLine("Output unavailable; check the device, token environment variable or network."); diff --git a/src/SidePulse.Cli/HostManagement.cs b/src/SidePulse.Cli/HostManagement.cs index 03f649a..d65c1a9 100644 --- a/src/SidePulse.Cli/HostManagement.cs +++ b/src/SidePulse.Cli/HostManagement.cs @@ -12,10 +12,10 @@ namespace SidePulse.Cli; public sealed record HostSnapshot(bool Running, int? ProcessId, AgentState State, IReadOnlyList Sessions, int ProtocolVersion = 1); public static class HostControl { - public static async Task Request(string command, CancellationToken cancellationToken) + public static async Task Request(string command, CancellationToken cancellationToken, TimeSpan? timeout = null) { using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - deadline.CancelAfter(TimeSpan.FromSeconds(2)); + deadline.CancelAfter(timeout ?? TimeSpan.FromSeconds(2)); using var pipe = new NamedPipeClientStream(".", LocalPipe.Name, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); try { await pipe.ConnectAsync(deadline.Token); } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { return new(false, null, AgentState.Unknown, []); } @@ -67,6 +67,8 @@ public override async Task ExecuteAsync(CommandContext context, HostActionS public sealed class HostStartSettings : TargetSettings { [CommandOption("--profile ")] public string? Profile { get; init; } + [CommandOption("--no-profile")] public bool NoProfile { get; init; } + [CommandOption("--brightness ")] public int? Brightness { get; init; } [CommandOption("--model ")] public DeviceModel? Model { get; init; } [CommandOption("--exe ")] public string Executable { get; init; } = Installation.PreferredExecutable; @@ -82,7 +84,9 @@ public override async Task ExecuteAsync(CommandContext context, HostStartSe { var existing = await HostControl.Request("status", cancellationToken); if (existing.Running) { if (settings.Json) Output.Print(existing); else AnsiConsole.WriteLine("Host is already running. Stop it before changing its target."); return 0; } - _ = AnimationLibrary.ResolveProfile(settings.Profile, settings.Model, settings.Device); + var preferences = PreferenceStore.Default.Read(); + _ = AnimationLibrary.ResolveProfile(settings.NoProfile ? null : settings.Profile ?? preferences.Profile, settings.Model ?? preferences.Model, settings.Device ?? preferences.Device); + if (settings.Brightness is < 0 or > 100 || settings.NoProfile && settings.Profile is not null) throw new ArgumentException("Choose brightness 0..100 and either --profile or --no-profile."); var exe = HookConfiguration.Executable(settings.Executable); var directory = Path.Combine(Path.GetDirectoryName(LinkStore.DefaultPath)!, "host"); if (OperatingSystem.IsWindows()) Directory.CreateDirectory(directory); @@ -95,6 +99,8 @@ public override async Task ExecuteAsync(CommandContext context, HostStartSe if (settings.Device is { } device) { info.ArgumentList.Add("--device"); info.ArgumentList.Add(Path.GetFullPath(device)); } if (settings.Phone is { } phone) { info.ArgumentList.Add("--phone"); info.ArgumentList.Add(phone); } if (settings.TokenEnvironment is { } variable) { info.ArgumentList.Add("--token-env"); info.ArgumentList.Add(variable); } + if (settings.NoProfile) info.ArgumentList.Add("--no-profile"); + if (settings.Brightness is { } brightness) { info.ArgumentList.Add("--brightness"); info.ArgumentList.Add(brightness.ToString()); } if (settings.Profile is { } profile) { info.ArgumentList.Add("--profile"); info.ArgumentList.Add(profile); } if (settings.Model is { } model) { info.ArgumentList.Add("--model"); info.ArgumentList.Add(model.ToString()); } if (settings.DryRun) info.ArgumentList.Add("--dry-run"); diff --git a/src/SidePulse.Cli/Interactive.cs b/src/SidePulse.Cli/Interactive.cs index 9e053fe..fa90cbc 100644 --- a/src/SidePulse.Cli/Interactive.cs +++ b/src/SidePulse.Cli/Interactive.cs @@ -33,38 +33,101 @@ public static class Interactive group = null; } } - public static MenuItem? Choose(string title, IReadOnlyList items) + public static MenuItem? Choose(string title, IReadOnlyList items, string? context = null, bool search = false) { if (!TerminalMode.Interactive) throw new ArgumentException("This action requires an interactive terminal."); var selected = InSession ? Math.Clamp(Selections.GetValueOrDefault(title), 0, items.Count - 1) : 0; + var filter = ""; + var visible = items.ToArray(); MenuItem? result = null; IRenderable Draw() { - var rows = items.Select((item, i) => (IRenderable)new Text((i == selected ? "> " : " ") + item.Label, i == selected ? new Style(Color.Cyan1, decoration: Decoration.Bold) : Style.Plain)).ToList(); - rows.Add(new Text(InSession ? "\n↑/↓ select · Enter continue · Esc back · / actions" : "\n↑/↓ select · Enter continue · Esc back", new Style(Color.Grey))); - if (items[selected].Arguments is { } arguments) rows.Add(new Panel(new Text(TerminalMode.Command(arguments))).Header("Script command").Border(BoxBorder.Rounded)); + var rows = visible.Select((item, i) => (IRenderable)new Text((i == selected ? "> " : " ") + item.Label, i == selected ? new Style(Color.Cyan1, decoration: Decoration.Bold) : Style.Plain)).ToList(); + if (context is not null) rows.Insert(0, new Text(context + "\n")); + if (search) rows.Insert(0, new Text("Search: " + filter)); + if (visible.Length == 0) rows.Add(new Text("No matching actions.")); + rows.Add(new Text(search ? "\nType to search · Enter continue · Esc back" : InSession ? "\n↑/↓ select · Enter continue · Esc back · / actions" : "\n↑/↓ select · Enter continue · Esc back", new Style(Color.Grey))); + if (visible.Length > 0 && visible[selected].Arguments is { } arguments) + { + try { rows.Add(new Panel(new Text(TerminalMode.Command(arguments))).Header("Script command").Border(BoxBorder.Rounded)); } + catch (ArgumentException) { rows.Add(new Text("Command export unavailable. Choose another export shell in Settings.")); } + } return new Panel(new Rows(rows)).Header(Markup.Escape(title)).Border(BoxBorder.Rounded); } - AnsiConsole.Live(Draw()).AutoClear(true).Start(live => + var controlC = Console.TreatControlCAsInput; + try + { + Console.TreatControlCAsInput = true; + AnsiConsole.Live(Draw()).AutoClear(true).Start(live => + { + live.Refresh(); + while (true) + { + var input = Console.ReadKey(true); + var key = input.Key; + if (input.KeyChar == '\u0003') + { + if (title == "SidePulse.NET · Home") throw new SessionQuitRequested(); + break; + } + if (InSession && !search && input.KeyChar == '/') throw new ActionPaletteRequested(); + if (key == ConsoleKey.Escape) break; + if (key == ConsoleKey.Enter && visible.Length > 0) { result = visible[selected]; break; } + if (search && (key == ConsoleKey.Backspace || !char.IsControl(input.KeyChar))) + { + filter = key == ConsoleKey.Backspace ? filter[..Math.Max(0, filter.Length - 1)] : filter + input.KeyChar; + visible = items.Where(item => item.Label.Contains(filter, StringComparison.OrdinalIgnoreCase)).ToArray(); + selected = 0; + } + if (visible.Length > 0) + { + if (key == ConsoleKey.UpArrow) selected = (selected + visible.Length - 1) % visible.Length; + if (key == ConsoleKey.DownArrow) selected = (selected + 1) % visible.Length; + } + if (InSession && !search) Selections[title] = selected; + live.UpdateTarget(Draw()); live.Refresh(); + } + }); + } + finally { Console.TreatControlCAsInput = controlC; } + return result; + } + private static readonly Dictionary Drafts = new(); + public static string Ask(string prompt, string? value = null) + { + if (!InSession) return AnsiConsole.Prompt(value is null ? new TextPrompt(Markup.Escape(prompt)) : new TextPrompt(Markup.Escape(prompt)).DefaultValue(value)); + var text = Drafts.GetValueOrDefault(prompt, value ?? ""); + Console.WriteLine(prompt + " · Enter save · Esc/Ctrl+C back (input retained) · Ctrl+U clear"); + Console.Write(text); + var controlC = Console.TreatControlCAsInput; + try { - live.Refresh(); + Console.TreatControlCAsInput = true; while (true) { - var input = Console.ReadKey(true); - var key = input.Key; - if (InSession && input.KeyChar == '/') throw new ActionPaletteRequested(); - if (key == ConsoleKey.Escape) break; - if (key == ConsoleKey.Enter) { result = items[selected]; break; } - if (key == ConsoleKey.UpArrow) selected = (selected + items.Count - 1) % items.Count; - if (key == ConsoleKey.DownArrow) selected = (selected + 1) % items.Count; - if (InSession) Selections[title] = selected; - live.UpdateTarget(Draw()); live.Refresh(); + var key = Console.ReadKey(true); + if (key.Key == ConsoleKey.Escape || key.KeyChar == '\u0003') { Drafts[prompt] = text; Console.WriteLine(); throw new FormCancelled(); } + if (key.Key == ConsoleKey.Enter && !string.IsNullOrWhiteSpace(text)) { Drafts[prompt] = text; Console.WriteLine(); return text; } + if (key.KeyChar == '\u0015') { Console.Write(new string('\b', text.Length) + new string(' ', text.Length) + new string('\b', text.Length)); text = ""; continue; } + if (key.Key == ConsoleKey.Backspace && text.Length > 0) { text = text[..^1]; Console.Write("\b \b"); } + else if (!char.IsControl(key.KeyChar)) { text += key.KeyChar; Console.Write(key.KeyChar); } } - }); - return result; + } + finally { Console.TreatControlCAsInput = controlC; } + } + public static T Pick(string title, IEnumerable values) where T : notnull + { + var entries = values.ToArray(); + if (!InSession) return AnsiConsole.Prompt(new SelectionPrompt().Title(Markup.Escape(title)).AddChoices(entries)); + var selected = Choose(title, entries.Select(v => new MenuItem(v.ToString()!)).ToArray()) ?? throw new FormCancelled(); + return entries.First(v => v.ToString() == selected.Label); + } + public static bool Confirm(string title, bool defaultValue = false) + { + if (!InSession) return AnsiConsole.Confirm(title, defaultValue); + var selected = Choose(title, (defaultValue ? new[] { "Yes", "No" } : new[] { "No", "Yes" }).Select(v => new MenuItem(v)).ToArray()) ?? throw new FormCancelled(); + return selected.Label == "Yes"; } - public static string Ask(string prompt, string? value = null) => AnsiConsole.Prompt(value is null ? new TextPrompt(Markup.Escape(prompt)) : new TextPrompt(Markup.Escape(prompt)).DefaultValue(value)); - public static T Pick(string title, IEnumerable values) where T : notnull => AnsiConsole.Prompt(new SelectionPrompt().Title(Markup.Escape(title)).AddChoices(values)); public static string[]? Review(List arguments) { var shell = TerminalMode.Shell; @@ -74,7 +137,7 @@ IRenderable Draw() var action = Choose("Ready", [new("Run", arguments.ToArray()), new("Copy command"), new("Choose shell"), new("Back")]); if (action is null || action.Label == "Back") return null; if (action.Label == "Run") return arguments.ToArray(); - if (action.Label == "Choose shell") { shell = Pick("Command shell", new[] { "powershell", "bash", "cmd" }); continue; } + if (action.Label == "Choose shell") { shell = Pick("Command shell", new[] { "powershell", "bash", "cmd" }); PreferenceStore.Default.Save(PreferenceStore.Default.Read() with { Shell = shell }); continue; } try { Console.WriteLine(TerminalMode.Copy(TerminalMode.Command(arguments, shell)) ? "Command copied." : "Clipboard unavailable. Select and copy the displayed command."); } catch (ArgumentException ex) { Console.Error.WriteLine(ex.Message); shell = TerminalMode.Shell; } } @@ -97,8 +160,8 @@ internal static List Target() if (action is null) return null; if (action.Arguments is { } direct) return direct; var command = new List { "update", "install" }; - if (AnsiConsole.Confirm("Include prereleases?", false)) command.Add("--prerelease"); - if (AnsiConsole.Confirm("Preview the update only?", true)) command.Add("--dry-run"); + if (Confirm("Include prereleases?", false)) command.Add("--prerelease"); + if (Confirm("Preview the update only?", true)) command.Add("--dry-run"); return Review(command); } if (group == "about") @@ -122,7 +185,7 @@ internal static List Target() if (action.Label == "Preview .LED file") command.AddRange(["--file", Path.GetFullPath(Ask("Source .LED file"))]); else command.Add(Pick("Pattern", AnimationLibrary.Default.List().Where(p => p.Models.Contains(Enum.Parse(model, true))).Select(p => p.Name))); command.AddRange(["--model", model]); - command.AddRange(["--brightness", Ask("Brightness percent", "100")]); + command.AddRange(["--brightness", Ask("Brightness percent", PreferenceStore.Default.Read().Brightness.ToString())]); if (verb == "apply") command.AddRange(Target()); if (verb == "export") command.AddRange(["--output", Path.GetFullPath(Ask("Destination .LED file"))]); } @@ -142,8 +205,8 @@ internal static List Target() if (action.Arguments is { } direct) return direct; var command = new List { "agents", action.Label.ToLowerInvariant(), Pick("Agent", Enum.GetValues()).ToString() }; if (action.Label == "Install") command.AddRange(["--exe", Path.GetFullPath(Ask("Published SidePulse.NET executable", Environment.ProcessPath!))]); - if (AnsiConsole.Confirm("Use an explicit configuration file?", false)) command.AddRange(["--config", Path.GetFullPath(Ask("Configuration path"))]); - if (action.Label != "Status" && AnsiConsole.Confirm("Preview changes only?", true)) command.Add("--dry-run"); + if (Confirm("Use an explicit configuration file?", false)) command.AddRange(["--config", Path.GetFullPath(Ask("Configuration path"))]); + if (action.Label != "Status" && Confirm("Preview changes only?", true)) command.Add("--dry-run"); return Review(command); } if (group == "host") @@ -152,7 +215,7 @@ internal static List Target() if (action is null) return null; if (action.Arguments is { } direct) return direct; var command = new List { "host", "start" }; command.AddRange(Target()); - if (AnsiConsole.Confirm("Use a saved animation profile?", false)) command.AddRange(["--profile", Ask("Profile name"), "--model", Pick("LED layout", Enum.GetValues()).ToString()]); + if (Confirm("Use a saved animation profile?", false)) command.AddRange(["--profile", Ask("Profile name"), "--model", Pick("LED layout", Enum.GetValues()).ToString()]); return Review(command); } if (group == "link") diff --git a/src/SidePulse.Cli/Program.cs b/src/SidePulse.Cli/Program.cs index 8532afc..41a5622 100644 --- a/src/SidePulse.Cli/Program.cs +++ b/src/SidePulse.Cli/Program.cs @@ -26,6 +26,7 @@ static string[] Normalize(string[] command) config.ConfigureConsole(AnsiConsole.Console); config.SetApplicationName(ApplicationIdentity.Command); config.SetApplicationVersion(ProjectInfo.Version); + config.AddCommand("settings").WithDescription("Show, set or reset persistent non-secret defaults."); config.AddCommand("install").WithDescription("Install for this user; optionally configure user PATH."); config.AddCommand("uninstall").WithDescription("Remove the managed installation while retaining settings and phone links."); config.AddCommand("internal-uninstall").IsHidden(); diff --git a/src/SidePulse.Cli/Settings.cs b/src/SidePulse.Cli/Settings.cs new file mode 100644 index 0000000..8f7ee23 --- /dev/null +++ b/src/SidePulse.Cli/Settings.cs @@ -0,0 +1,49 @@ +using SidePulse.Core; +using Spectre.Console.Cli; + +namespace SidePulse.Cli; + +public sealed class PreferenceSettings : CommandSettings +{ + [CommandArgument(0, "[ACTION]")] public string Action { get; init; } = "show"; + [CommandOption("--device ")] public string? Device { get; init; } + [CommandOption("--phone ")] public string? Phone { get; init; } + [CommandOption("--auto")] public bool Auto { get; init; } + [CommandOption("--brightness ")] public int? Brightness { get; init; } + [CommandOption("--profile ")] public string? Profile { get; init; } + [CommandOption("--no-profile")] public bool NoProfile { get; init; } + [CommandOption("--model ")] public DeviceModel? Model { get; init; } + [CommandOption("--shell ")] public string? Shell { get; init; } + [CommandOption("--json")] public bool Json { get; init; } + [CommandOption("--dry-run")] public bool DryRun { get; init; } +} +public sealed class PreferencesCommand : Command +{ + public override int Execute(CommandContext context, PreferenceSettings settings, CancellationToken cancellationToken) + { + if (settings.Action is not ("show" or "set" or "reset")) throw new ArgumentException("Choose settings show, set or reset."); + var changes = settings.Device is not null || settings.Phone is not null || settings.Auto || settings.Brightness is not null || settings.Profile is not null || settings.NoProfile || settings.Model is not null || settings.Shell is not null; + if (changes && settings.Action != "set") throw new ArgumentException("Use settings set to change defaults."); + if (new[] { settings.Device is not null, settings.Phone is not null, settings.Auto }.Count(v => v) > 1) throw new ArgumentException("Choose --device, --phone or --auto."); + if (settings.NoProfile && settings.Profile is not null) throw new ArgumentException("Choose --profile or --no-profile."); + var store = PreferenceStore.Default; + var value = settings.Action == "reset" ? new Preferences() : store.Read(); + if (settings.Action == "set") + { + value = value with + { + Device = settings.Auto || settings.Phone is not null ? null : settings.Device is not null ? Path.GetFullPath(settings.Device) : value.Device, + Phone = settings.Auto || settings.Device is not null ? null : settings.Phone ?? value.Phone, + Brightness = settings.Brightness ?? value.Brightness, + Profile = settings.NoProfile ? null : settings.Profile ?? value.Profile, + Model = settings.Model ?? value.Model, Shell = settings.Shell ?? value.Shell + }; + value.Validate(); + if (value.Profile is not null) _ = AnimationLibrary.ResolveProfile(value.Profile, value.Model, value.Device); + } + if (settings.Action != "show" && !settings.DryRun) store.Save(value); + if (settings.Json) Output.Print(new { path = PreferenceStore.DefaultPath, dryRun = settings.DryRun, preferences = value }); + else Console.WriteLine($"{value.OutputDescription}\nBrightness: {value.Brightness}% · Profile: {value.Profile ?? "built-in"} · Model: {value.Model?.ToString() ?? "auto"}\nExport shell: {value.Shell ?? (OperatingSystem.IsWindows() ? "powershell" : "bash")}\nSettings: {PreferenceStore.DefaultPath}" + (settings.DryRun ? "\nPreview only; settings unchanged." : "")); + return 0; + } +} diff --git a/src/SidePulse.Cli/ShellSession.cs b/src/SidePulse.Cli/ShellSession.cs index c923e01..51f1588 100644 --- a/src/SidePulse.Cli/ShellSession.cs +++ b/src/SidePulse.Cli/ShellSession.cs @@ -4,6 +4,8 @@ namespace SidePulse.Cli; public sealed class ActionPaletteRequested : Exception; +public sealed class FormCancelled : Exception; +public sealed class SessionQuitRequested : Exception; /// Owns navigation; command execution happens only after menu rendering ends. public sealed class ShellSession(Func execute) @@ -11,7 +13,7 @@ public sealed class ShellSession(Func execute) private static readonly MenuItem[] Home = [new("Send state"), new("Animations"), new("Devices & phones"), new("Agents & host"), new("Settings"), new("Help & about"), new("Quit")]; private static readonly string[] Groups = ["about", "animations", "agents", "link", "host", "profiles", "update"]; - private readonly List target = []; + private readonly List target = new(PreferenceStore.Default.Read().OutputArguments); private readonly Stack parents = new(); private bool preview; private string? recent; @@ -29,8 +31,7 @@ public int Run(string[] args) { if (section is null) { - if (recent is not null) Console.WriteLine(recent); - var action = Interactive.Choose("SidePulse.NET · Home", Home); + var action = Interactive.Choose("SidePulse.NET · Home", Home, HomeContext()); if (action is null) continue; // Home Esc is navigation, never Quit. if (action.Label == "Quit") return 0; section = action.Label; @@ -52,18 +53,19 @@ public int Run(string[] args) } if (section == "Settings") { - var action = Interactive.Choose(section, [new("Diagnostics", ["doctor"]), new("Installation"), new("Updates"), new("Profiles"), new("Back")]); + var action = Interactive.Choose(section, [new("Preferences"), new("Diagnostics", ["doctor"]), new("Installation"), new("Updates"), new("Profiles"), new("Back")]); if (action is null || action.Label == "Back") { section = Back(); continue; } if (action.Arguments is { } command) RunCommand(command); else { parents.Push(section); section = action.Label.ToLowerInvariant(); } continue; } + if (section == "preferences") { EditPreferences(); section = Back(); continue; } if (section == "installation") { var action = Interactive.Choose("Installation", [new("Status", ["install", "--status"]), new("Install for this user"), new("Uninstall"), new("Back")]); if (action is null || action.Label == "Back") { section = Back(); continue; } if (action.Arguments is { } direct) { RunCommand(direct); continue; } var command = new List { action.Label == "Uninstall" ? "uninstall" : "install" }; - if (command[0] == "install" && AnsiConsole.Confirm("Add spn to your user PATH? The preview shows any shell-profile changes.", false)) command.Add("--add-to-path"); + if (command[0] == "install" && Interactive.Confirm("Add spn to your user PATH? The preview shows any shell-profile changes.", false)) command.Add("--add-to-path"); if (RunCommand([.. command, "--dry-run"]) != 0) continue; var apply = Interactive.Choose("Review installation changes", [new(command[0] == "install" ? "Install" : "Remove"), new("Back")]); if (apply is not null && apply.Label != "Back") @@ -79,12 +81,13 @@ public int Run(string[] args) var next = Interactive.Build(group); if (next is null) section = Back(); else RunCommand(next); } + catch (SessionQuitRequested) { return 0; } + catch (FormCancelled) { recent = "Cancelled · input retained."; } catch (ActionPaletteRequested) { - // Spectre's prompt owns the terminal only after the previous Live is disposed. + // The previous live renderer is disposed before opening the palette. var previous = section; - section = AnsiConsole.Prompt(new SelectionPrompt().Title("Actions").EnableSearch() - .AddChoices(Home.Select(item => item.Label).Prepend("Back"))); + section = Interactive.Choose("Actions", Home.Prepend(new MenuItem("Back")).ToArray(), search: true)?.Label ?? "Back"; if (section == "Quit") return 0; if (section == "Back") section = previous; else parents.Clear(); @@ -105,29 +108,87 @@ private void SendState() { while (true) { - var items = new[] { AgentState.Working, AgentState.Waiting, AgentState.Done, AgentState.Error, AgentState.Idle, AgentState.Unknown }.Select(state => new MenuItem(state.ToString(), ["state", state.ToString(), .. target, .. (preview ? new[] { "--dry-run" } : Array.Empty())])).ToList(); + var settings = PreferenceStore.Default.Read(); + string[] appearance = ["--brightness", settings.Brightness.ToString(), .. (settings.Profile is null ? new[] { "--no-profile" } : new[] { "--profile", settings.Profile, "--model", settings.Model!.Value.ToString() })]; + var items = new[] { AgentState.Working, AgentState.Waiting, AgentState.Done, AgentState.Error, AgentState.Idle, AgentState.Unknown }.Select(state => new MenuItem(state.ToString(), ["state", state.ToString(), .. target, .. appearance, .. (preview ? new[] { "--dry-run" } : Array.Empty())])).ToList(); items.AddRange([new(preview ? "Preview mode: on" : "Preview mode: off"), new("Change output"), new("Back")]); var selected = Interactive.Choose("Send state · " + (preview ? "Preview" : "Live") + " · " + (target.Count == 0 ? "Auto: USB, then default phone" : string.Join(' ', target)), items); if (selected is null || selected.Label == "Back") return; if (selected.Arguments is { } command) { RunCommand(command); continue; } if (selected.Label.StartsWith("Preview mode:", StringComparison.Ordinal)) { preview = !preview; continue; } - var output = Interactive.Choose("Output", [new("Auto: USB, then default phone"), new("USB / SD"), new("Saved phone"), new("Back")]); - if (output is null || output.Label == "Back") continue; - if (output.Label.StartsWith("Auto:", StringComparison.Ordinal)) { target.Clear(); continue; } - if (output.Label == "Saved phone") + ChangeOutput(); + } + } + private void ChangeOutput() + { + var output = Interactive.Choose("Output", [new("Auto: USB, then default phone"), new("USB / SD"), new("Saved phone"), new("Back")]); + if (output is null || output.Label == "Back") return; + if (output.Label.StartsWith("Auto:", StringComparison.Ordinal)) { SaveOutput([]); return; } + if (output.Label == "Saved phone") + { + var phones = File.Exists(LinkStore.DefaultPath) ? PhoneStores.Open().List() : []; + if (phones.Count == 0) { Console.WriteLine("No saved phones. Pair one under Devices & phones."); return; } + var phone = Interactive.Choose("Saved phones", phones.Select(item => new MenuItem(item.Name + " (" + item.Alias + ")", ["--phone", item.Alias])).ToArray()); + if (phone?.Arguments is { } choice) { SaveOutput(choice); } + } + else + { + var devices = DeviceTransport.Discover(); + if (devices.Count == 0) { Console.WriteLine("No mounted devices. Connect SidePulse or select a phone."); return; } + var device = Interactive.Choose("Mounted devices", devices.Select(item => new MenuItem(item.Label, ["--device", item.Path])).ToArray()); + if (device?.Arguments is { } choice) { SaveOutput(choice); } + } + } + + private void SaveOutput(string[] choice) + { + var current = PreferenceStore.Default.Read(); + PreferenceStore.Default.Save(current with { Device = choice.FirstOrDefault() == "--device" ? choice[1] : null, Phone = choice.FirstOrDefault() == "--phone" ? choice[1] : null }); + target.Clear(); target.AddRange(choice); + } + private string HomeContext() + { + var settings = PreferenceStore.Default.Read(); + string host; + try + { + var snapshot = HostControl.Request("status", CancellationToken.None, TimeSpan.FromMilliseconds(300)).GetAwaiter().GetResult(); + host = snapshot.Running ? $"running · {snapshot.State} · {snapshot.Sessions.Count} sessions" : "stopped"; + } + catch (Exception ex) when (ex is IOException or OperationCanceledException or UnauthorizedAccessException) { host = "not responding · see Agents & host"; } + return $"Output: {settings.OutputDescription}\nBrightness: {settings.Brightness}% · Profile: {settings.Profile ?? "built-in"} · Shell: {TerminalMode.Shell}\nHost: {host}\nLast action: {recent ?? "none this session"}"; + } + private void EditPreferences() + { + while (true) + { + var current = PreferenceStore.Default.Read(); + var action = Interactive.Choose("Preferences", [new("Show settings", ["settings", "show"]), new("Change output"), new("Brightness"), new("Animation profile"), new("Export shell"), new("Back")]); + if (action is null || action.Label == "Back") return; + if (action.Arguments is { } command) { RunCommand(command); continue; } + if (action.Label == "Change output") { ChangeOutput(); continue; } + if (action.Label == "Brightness") { - var phones = File.Exists(LinkStore.DefaultPath) ? PhoneStores.Open().List() : []; - if (phones.Count == 0) { Console.WriteLine("No saved phones. Pair one under Devices & phones."); continue; } - var phone = Interactive.Choose("Saved phones", phones.Select(item => new MenuItem(item.Name + " (" + item.Alias + ")", ["--phone", item.Alias])).ToArray()); - if (phone?.Arguments is { } choice) { target.Clear(); target.AddRange(choice); } + var text = Interactive.Ask("Brightness 0..100", current.Brightness.ToString()); + if (!int.TryParse(text, out var brightness) || brightness is < 0 or > 100) { Console.WriteLine("Enter a number from 0 to 100."); continue; } + current = current with { Brightness = brightness }; } - else + if (action.Label == "Export shell") current = current with { Shell = Interactive.Pick("Export shell", new[] { "powershell", "bash", "cmd" }) }; + if (action.Label == "Animation profile") { - var devices = DeviceTransport.Discover(); - if (devices.Count == 0) { Console.WriteLine("No mounted devices. Connect SidePulse or select a phone."); continue; } - var device = Interactive.Choose("Mounted devices", devices.Select(item => new MenuItem(item.Label, ["--device", item.Path])).ToArray()); - if (device?.Arguments is { } choice) { target.Clear(); target.AddRange(choice); } + var kind = Interactive.Choose("Animation profile", [new("Built-in states"), new("Saved profile"), new("Back")]); + if (kind is null || kind.Label == "Back") continue; + if (kind.Label == "Built-in states") current = current with { Profile = null }; + else + { + var name = Interactive.Ask("Profile name", current.Profile); + var model = Interactive.Pick("LED layout", Enum.GetValues()); + _ = AnimationLibrary.ResolveProfile(name, model, current.Device); + current = current with { Profile = name, Model = model }; + } } + PreferenceStore.Default.Save(current); + recent = "Settings saved."; } } diff --git a/src/SidePulse.Cli/TerminalMode.cs b/src/SidePulse.Cli/TerminalMode.cs index 3c86b6e..d619941 100644 --- a/src/SidePulse.Cli/TerminalMode.cs +++ b/src/SidePulse.Cli/TerminalMode.cs @@ -12,7 +12,7 @@ public static class TerminalMode public static bool Json { get; private set; } public static bool Interactive { get; private set; } public static bool ColorEnabled { get; private set; } - public static string Shell => OperatingSystem.IsWindows() ? "powershell" : "bash"; + public static string Shell => PreferenceStore.Default.Read().Shell ?? (OperatingSystem.IsWindows() ? "powershell" : "bash"); public static string[] Configure(string[] args) { // Global flags are deliberately accepted before or after subcommands. diff --git a/src/SidePulse.Core/Preferences.cs b/src/SidePulse.Core/Preferences.cs new file mode 100644 index 0000000..540b3df --- /dev/null +++ b/src/SidePulse.Core/Preferences.cs @@ -0,0 +1,61 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace SidePulse.Core; + +/// Non-secret defaults. Phone credentials remain in the protected link store. +public sealed record Preferences(int Version = 1, string? Device = null, string? Phone = null, + int Brightness = 100, string? Profile = null, DeviceModel? Model = null, string? Shell = null) +{ + [JsonIgnore] + public string OutputDescription => Device is not null ? "USB / SD: " + Device : Phone is not null ? "Phone: " + Phone : "Auto: USB, then default phone"; + [JsonIgnore] + public string[] OutputArguments => Device is not null ? ["--device", Device] : Phone is not null ? ["--phone", Phone] : []; + public void Validate() + { + if (Version != 1) throw new ArgumentException("Unsupported settings version."); + if (Device is not null && Phone is not null) throw new ArgumentException("Choose one preferred output."); + if (Device is not null && (!Path.IsPathFullyQualified(Device) || Device.IndexOfAny(['\r', '\n', '\0']) >= 0)) throw new ArgumentException("Use an absolute device path."); + if (Phone is not null && !Phone.Equals("default", StringComparison.OrdinalIgnoreCase)) PhoneTokens.Alias(Phone); + if (Brightness is < 0 or > 100) throw new ArgumentException("Brightness must be 0..100."); + if (Profile is not null) AnimationLibrary.Name(Profile); + if (Profile is not null && Model is null) throw new ArgumentException("A preferred profile requires an LED model."); + if (Model is { } model && !Enum.IsDefined(model)) throw new ArgumentException("Choose dot or pro."); + if (Shell is not null and not ("powershell" or "bash" or "cmd")) throw new ArgumentException("Choose powershell, bash or cmd."); + } + public OutputTarget ResolveOutput(string? device, string? phone, string? tokenEnvironment, + Func> devices, Func> phones) + { + var explicitOutput = device is not null || phone is not null || tokenEnvironment is not null; + return OutputTarget.Resolve(explicitOutput ? device : Device, explicitOutput ? phone : Phone, tokenEnvironment, devices, phones); + } +} + +public sealed class PreferenceStore(string path) +{ + public static string DefaultPath => Path.Combine(Path.GetDirectoryName(LinkStore.DefaultPath)!, "settings.json"); + public static PreferenceStore Default => new(DefaultPath); + public Preferences Read() + { + if (!File.Exists(path)) return new(); + try + { + if (new FileInfo(path).Length > 16384) throw new ArgumentException("Settings file is too large."); + var preferences = JsonSerializer.Deserialize(File.ReadAllBytes(path)) ?? throw new ArgumentException("Empty settings."); + preferences.Validate(); + return preferences; + } + catch (Exception ex) when (ex is JsonException or ArgumentException) + { + throw new IOException($"Cannot read settings at {path}. Keep the file for recovery or use settings reset. {ex.Message}", ex); + } + } + public void Save(Preferences preferences) + { + preferences.Validate(); + var directory = Path.GetDirectoryName(Path.GetFullPath(path))!; + if (OperatingSystem.IsWindows()) Directory.CreateDirectory(directory); + else Directory.CreateDirectory(directory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + UserInstallation.AtomicWrite(path, JsonSerializer.SerializeToUtf8Bytes(preferences, new JsonSerializerOptions { WriteIndented = true })); + } +} diff --git a/tests/SidePulse.Tests/PreferenceTests.cs b/tests/SidePulse.Tests/PreferenceTests.cs new file mode 100644 index 0000000..c99f520 --- /dev/null +++ b/tests/SidePulse.Tests/PreferenceTests.cs @@ -0,0 +1,65 @@ +using SidePulse.Core; +using Xunit; + +namespace SidePulse.Tests; + +public sealed class PreferenceTests +{ + [Fact] + public void SettingsSurviveRestartWithoutCredentialsAndUsePrivatePermissions() + { + var root = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + var path = Path.Combine(root, "settings.json"); + try + { + var store = new PreferenceStore(path); + Assert.Equal(new Preferences(), store.Read()); + Assert.False(Directory.Exists(root)); + var expected = new Preferences(Phone: "iphone", Brightness: 42, Profile: "personal", Model: DeviceModel.Pro, Shell: "powershell"); + store.Save(expected); + Assert.Equal(expected, new PreferenceStore(path).Read()); + Assert.DoesNotContain("OutputArguments", File.ReadAllText(path)); + if (!OperatingSystem.IsWindows()) Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(path)); + store.Save(new Preferences()); + Assert.Equal(new Preferences(), store.Read()); + } + finally { if (Directory.Exists(root)) Directory.Delete(root, true); } + } + [Fact] + public void InvalidAndFutureSettingsArePreservedUntilExplicitReset() + { + var root = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(root); + var path = Path.Combine(root, "settings.json"); + try + { + foreach (var text in new[] { "broken", "null", "{\"Version\":2}", "{\"Brightness\":101}", "{\"Profile\":\"personal\"}" }) + { + File.WriteAllText(path, text); + Assert.Throws(() => new PreferenceStore(path).Read()); + Assert.Equal(text, File.ReadAllText(path)); + Assert.Throws(() => new PreferenceStore(path).Save(new Preferences(Brightness: -1))); + Assert.Equal(text, File.ReadAllText(path)); + } + new PreferenceStore(path).Save(new Preferences()); + Assert.Equal(new Preferences(), new PreferenceStore(path).Read()); + } + finally { Directory.Delete(root, true); } + } + [Fact] + public void ExplicitTargetsOverridePreferencesAndSavedTargetsSkipDiscovery() + { + var settings = new Preferences(Phone: "iphone"); + IReadOnlyList NoDevices() => throw new Exception("Must not discover"); + IReadOnlyList NoPhones() => throw new Exception("Must not open credentials"); + Assert.Equal(new OutputTarget(OutputTransport.Phone, "iphone"), settings.ResolveOutput(null, null, null, NoDevices, NoPhones)); + Assert.Equal(new OutputTarget(OutputTransport.Device, "missing-device"), settings.ResolveOutput("missing-device", null, null, NoDevices, NoPhones)); + Assert.Equal(new OutputTarget(OutputTransport.TokenEnvironment, "TOKEN"), settings.ResolveOutput(null, null, "TOKEN", NoDevices, NoPhones)); + Assert.Throws(() => settings.ResolveOutput("device", "phone", null, NoDevices, NoPhones)); + } + [Theory] + [InlineData("token_abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz")] + [InlineData("../phone")] + [InlineData("")] + public void OnlyAliasesCanBeStoredAsPhonePreferences(string alias) => Assert.Throws(() => new Preferences(Phone: alias).Validate()); +}