Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/Conclave.App/Commands/AppCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace Conclave.App.Commands;

// One thing the user can invoke from the palette (or, later, a hotkey). `CanExecute`
// gates visibility/availability — e.g. "Cancel turn" only surfaces when a session has
// an in-flight CTS. Named `AppCommand` to avoid colliding with the BCL's
// System.Windows.Input.ICommand-style "Command" type some Avalonia code picks up.
public sealed record AppCommand(
string Id,
string Title,
string? Group,
Func<bool> CanExecute,
Action Execute);
23 changes: 23 additions & 0 deletions src/Conclave.App/Commands/CommandRegistry.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
namespace Conclave.App.Commands;

// Owns the catalog of static commands (palette.open, prefs.open, ...). Dynamic
// per-session commands ("Switch to <name>") are produced on demand by the palette
// VM and not registered here — they'd churn every time a session is added/removed.
public sealed class CommandRegistry
{
private readonly Dictionary<string, AppCommand> _byId = new();

public IReadOnlyCollection<AppCommand> All => _byId.Values;

public void Register(AppCommand cmd) => _byId[cmd.Id] = cmd;

public AppCommand? Get(string id) => _byId.GetValueOrDefault(id);

public bool TryExecute(string id)
{
if (!_byId.TryGetValue(id, out var cmd)) return false;
if (!cmd.CanExecute()) return false;
cmd.Execute();
return true;
}
}
50 changes: 50 additions & 0 deletions src/Conclave.App/Commands/FuzzyMatch.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
namespace Conclave.App.Commands;

// Subsequence-based fuzzy matcher for the command palette. All query chars must
// appear in order in the candidate. Score rewards consecutive matches and matches
// at word boundaries — the "ns" in "**N**ew **s**ession" beats "**n**ew sessio**n**s"
// even though both match.
//
// Returns (score, matchedIndices) so the UI can highlight the matched chars. Score
// of 0 means no match; higher is better.
public static class FuzzyMatch
{
public static (int Score, int[] Indices) Score(string query, string candidate)
{
if (string.IsNullOrEmpty(query)) return (1, Array.Empty<int>());
if (string.IsNullOrEmpty(candidate)) return (0, Array.Empty<int>());

var indices = new int[query.Length];
int score = 0;
int qi = 0;
int lastMatch = -2;

for (int ci = 0; ci < candidate.Length && qi < query.Length; ci++)
{
char qc = char.ToLowerInvariant(query[qi]);
char cc = char.ToLowerInvariant(candidate[ci]);
if (qc != cc) continue;

indices[qi] = ci;
// Bonus: consecutive match (no gap from previous match).
if (ci == lastMatch + 1) score += 5;
// Bonus: matched at start of string.
if (ci == 0) score += 8;
// Bonus: matched at a word boundary (after space/punctuation).
else if (IsBoundary(candidate[ci - 1])) score += 4;
// Base: every match contributes a small amount so longer matches outscore shorter
// (when ties happen on bonuses).
score += 1;
lastMatch = ci;
qi++;
}

if (qi < query.Length) return (0, Array.Empty<int>()); // unmatched chars left
// Penalty: shorter candidates of equal match are preferable. Subtract a tiny bit
// per unused char so "new session" beats "newest sessions" for "new s".
score -= candidate.Length / 8;
return (Math.Max(score, 1), indices);
}

private static bool IsBoundary(char c) => c is ' ' or '-' or '_' or '.' or '/' or ':';
}
95 changes: 95 additions & 0 deletions src/Conclave.App/Commands/KeyChord.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
using Avalonia.Input;

namespace Conclave.App.Commands;

// A single key + modifier combo, normalised so equality works regardless of how the
// chord was entered. `cmd` parses to Meta on macOS and Control elsewhere — this is
// the same convention VS Code uses, and it's what users expect when sharing keymaps
// across machines.
public readonly record struct KeyChord(Key Key, KeyModifiers Modifiers)
{
public static KeyChord FromEvent(KeyEventArgs e) => new(e.Key, NormaliseModifiers(e.KeyModifiers));

// Strip Shift when the underlying key already encodes case-sensitivity (letters/digits)?
// No — we want Shift to be significant for chords like "shift+G". Just clear stray
// modifier bits Avalonia might emit (none today, future-proofing only).
private static KeyModifiers NormaliseModifiers(KeyModifiers m) => m;

// "cmd+k", "ctrl+shift+p", "esc". Returns null on parse failure rather than
// throwing — bad keymaps shouldn't crash the app, they should just be ignored.
public static KeyChord? Parse(string spec)
{
if (string.IsNullOrWhiteSpace(spec)) return null;
var parts = spec.Split('+', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (parts.Length == 0) return null;
var mods = KeyModifiers.None;
Key? key = null;
foreach (var raw in parts)
{
switch (raw.ToLowerInvariant())
{
case "cmd":
case "meta":
case "win":
mods |= OperatingSystem.IsMacOS() ? KeyModifiers.Meta : KeyModifiers.Control;
break;
case "ctrl":
case "control":
mods |= KeyModifiers.Control;
break;
case "shift":
mods |= KeyModifiers.Shift;
break;
case "alt":
case "option":
mods |= KeyModifiers.Alt;
break;
default:
if (!TryParseKey(raw, out var parsed)) return null;
key = parsed;
break;
}
}
return key is null ? null : new KeyChord(key.Value, mods);
}

private static bool TryParseKey(string raw, out Key key)
{
// Single-char shortcuts: "k", "p". Avalonia's Key enum names letters as A..Z.
if (raw.Length == 1 && char.IsLetter(raw[0]))
return Enum.TryParse(raw.ToUpperInvariant(), out key);

// Common aliases users will type before the formal name.
switch (raw.ToLowerInvariant())
{
case "esc": key = Key.Escape; return true;
case "enter":
case "return": key = Key.Enter; return true;
case "space": key = Key.Space; return true;
}

return Enum.TryParse(raw, ignoreCase: true, out key);
}

public string Display
{
get
{
var parts = new List<string>(4);
if (Modifiers.HasFlag(KeyModifiers.Control)) parts.Add(OperatingSystem.IsMacOS() ? "⌃" : "Ctrl");
if (Modifiers.HasFlag(KeyModifiers.Alt)) parts.Add(OperatingSystem.IsMacOS() ? "⌥" : "Alt");
if (Modifiers.HasFlag(KeyModifiers.Shift)) parts.Add(OperatingSystem.IsMacOS() ? "⇧" : "Shift");
if (Modifiers.HasFlag(KeyModifiers.Meta)) parts.Add(OperatingSystem.IsMacOS() ? "⌘" : "Win");
parts.Add(KeyDisplay(Key));
return OperatingSystem.IsMacOS() ? string.Concat(parts) : string.Join("+", parts);
}
}

private static string KeyDisplay(Key k) => k switch
{
Key.Escape => "Esc",
Key.Enter => "↵",
Key.Space => "Space",
_ => k.ToString(),
};
}
69 changes: 69 additions & 0 deletions src/Conclave.App/Commands/KeyMap.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
using System.Text.Json;

namespace Conclave.App.Commands;

// Maps key chords to command ids. Defaults are baked in code; user overrides come from
// the settings table as JSON of the form `[ { "key": "cmd+k", "command": "palette.open" } ]`.
// Overrides are merged on top of defaults — a user can rebind without losing the rest.
public sealed class KeyMap
{
private readonly Dictionary<KeyChord, string> _bindings = new();

public IReadOnlyDictionary<KeyChord, string> Bindings => _bindings;

public void Bind(string chord, string commandId)
{
if (KeyChord.Parse(chord) is { } parsed) _bindings[parsed] = commandId;
}

public void Bind(KeyChord chord, string commandId) => _bindings[chord] = commandId;

public string? Lookup(KeyChord chord) => _bindings.GetValueOrDefault(chord);

// First chord bound to the given command id, for display purposes. Linear scan —
// we never have enough bindings for a reverse index to be worth the maintenance.
public KeyChord? FindForCommand(string commandId)
{
foreach (var (chord, id) in _bindings)
if (id == commandId) return chord;
return null;
}

// Defaults — kept minimal until we agree on the catalog. Cmd-K is the only one
// we're confident in shipping right now.
public static KeyMap Defaults()
{
var map = new KeyMap();
map.Bind("cmd+k", "palette.open");
return map;
}

// Manual JsonDocument walk rather than JsonSerializer.Deserialize so we don't pull
// in reflection-based deserialization — the project publishes with NativeAOT and the
// schema is trivial enough that hand-rolling is cleaner than wiring up a source-gen
// JsonSerializerContext.
public void ApplyOverridesJson(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return;
try
{
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.ValueKind != JsonValueKind.Array) return;
foreach (var entry in doc.RootElement.EnumerateArray())
{
if (entry.ValueKind != JsonValueKind.Object) continue;
if (!entry.TryGetProperty("key", out var keyEl) || keyEl.ValueKind != JsonValueKind.String) continue;
if (!entry.TryGetProperty("command", out var cmdEl) || cmdEl.ValueKind != JsonValueKind.String) continue;
var keyStr = keyEl.GetString();
var cmdStr = cmdEl.GetString();
if (string.IsNullOrWhiteSpace(keyStr) || string.IsNullOrWhiteSpace(cmdStr)) continue;
if (KeyChord.Parse(keyStr) is { } chord) _bindings[chord] = cmdStr;
}
}
catch (JsonException)
{
// Bad JSON — keep defaults. Users get told via a settings UI later; for now
// we just don't apply broken overrides.
}
}
}
47 changes: 47 additions & 0 deletions src/Conclave.App/Commands/KeyRouter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;

namespace Conclave.App.Commands;

// Window-level keyboard router. Listens on the tunnel phase so app-level chords with a
// modifier (Cmd-K, Ctrl-Shift-P) win even when a TextBox would otherwise consume the
// keystroke. Plain-key chords (no modifier) are handled on the bubble phase so typing
// in inputs still works normally.
public static class KeyRouter
{
public static void Attach(Window window, CommandRegistry registry, KeyMap map)
{
window.AddHandler(InputElement.KeyDownEvent, (s, e) => OnKey(e, registry, map, tunneling: true),
RoutingStrategies.Tunnel);
window.AddHandler(InputElement.KeyDownEvent, (s, e) => OnKey(e, registry, map, tunneling: false),
RoutingStrategies.Bubble);
}

private static void OnKey(KeyEventArgs e, CommandRegistry registry, KeyMap map, bool tunneling)
{
if (e.Handled) return;

var chord = KeyChord.FromEvent(e);
// Modifier keys arriving on their own (e.g. holding ⌘) come through as
// Key.LeftCommand / LWin / etc. Skip — they aren't a chord on their own.
if (IsModifierKey(e.Key)) return;

bool hasGlobalModifier = chord.Modifiers.HasFlag(KeyModifiers.Meta)
|| chord.Modifiers.HasFlag(KeyModifiers.Control);

// Tunnel phase only handles modifier-bearing chords — that's the whole point of
// grabbing them early. Plain-letter chords fall through to the bubble pass.
if (tunneling && !hasGlobalModifier) return;
if (!tunneling && hasGlobalModifier) return; // already considered on tunnel

if (map.Lookup(chord) is not { } commandId) return;
if (registry.TryExecute(commandId)) e.Handled = true;
}

private static bool IsModifierKey(Key k) => k
is Key.LeftCtrl or Key.RightCtrl
or Key.LeftShift or Key.RightShift
or Key.LeftAlt or Key.RightAlt
or Key.LWin or Key.RWin;
Comment on lines +42 to +46
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Key.LeftMeta / Key.RightMeta missing from IsModifierKey

Avalonia exposes Key.LeftMeta and Key.RightMeta for the macOS Command key (in addition to Key.LWin / Key.RWin). If either value is what Avalonia actually emits when the user holds Command alone on macOS, IsModifierKey returns false, KeyChord.FromEvent builds a chord whose Key is LeftMeta/RightMeta, map.Lookup finds nothing, and the event falls through harmlessly — but the guard's intent (skip bare-modifier keystrokes entirely) is violated. Adding both values keeps the intent sound across platform variations:

private static bool IsModifierKey(Key k) => k
    is Key.LeftCtrl or Key.RightCtrl
    or Key.LeftShift or Key.RightShift
    or Key.LeftAlt or Key.RightAlt
    or Key.LWin or Key.RWin
    or Key.LeftMeta or Key.RightMeta;

}
9 changes: 9 additions & 0 deletions src/Conclave.App/MainWindow.axaml.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Avalonia;
using Avalonia.Controls;
using Conclave.App.Claude;
using Conclave.App.Commands;
using Conclave.App.Design;
using Conclave.App.Platform;
using Conclave.App.Sessions;
Expand Down Expand Up @@ -41,6 +42,7 @@ public partial class MainWindow : Window
private NewFusionProjectModal? _newFusionModal;
private PreferencesModal? _preferencesModal;
private AboutModal? _aboutModal;
private CommandPaletteModal? _commandPaletteModal;

public MainWindow()
{
Expand Down Expand Up @@ -112,6 +114,11 @@ public MainWindow()

DataContext = _shell;

// Window-level keyboard router. Owns the tunnel-phase pass for modifier-bearing
// chords (Cmd-K and friends) so they win even over a focused TextBox; bare-key
// chords still bubble normally so typing into inputs is unaffected.
KeyRouter.Attach(this, _shell.Commands, _shell.KeyMap);

Activated += (_, _) => _isWindowActive = true;
Deactivated += (_, _) => _isWindowActive = false;

Expand Down Expand Up @@ -164,6 +171,8 @@ private void OnShellPropertyChanged(object? sender, System.ComponentModel.Proper
EnsureModal(ref _preferencesModal);
else if (e.PropertyName == nameof(ShellVm.IsAboutOpen) && _shell?.IsAboutOpen == true)
EnsureModal(ref _aboutModal);
else if (e.PropertyName == nameof(ShellVm.IsCommandPaletteOpen) && _shell?.IsCommandPaletteOpen == true)
EnsureModal(ref _commandPaletteModal);
}

private void EnsureModal<T>(ref T? slot) where T : Control, new()
Expand Down
1 change: 1 addition & 0 deletions src/Conclave.App/Sessions/SettingsKeys.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ public static class SettingsKeys
public const string NotificationsEnabled = "notifications.enabled";
public const string ClaudeVersion = "claude.version";
public const string AutoResumeStalledSessions = "stall_detection.auto_resume";
public const string KeybindingsJson = "keybindings.json";

public const int DefaultAutoCleanupDays = 7;

Expand Down
Loading
Loading