cydonia 0.1.16

Desktop workspace for the ACP agents you run, keeping what they produce as files on your disk
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! The keymap, put together in one place.
//!
//! Every chord the app answers to arrives here: bezel's own defaults for the
//! fields and the editor, this crate's context-scoped keys, and last the
//! commands a person may move — see [`Command`].
//!
//! Last is what makes them movable. gpui breaks a tie between two bindings on
//! the same chord by insertion order, so a command bound after bezel's
//! defaults wins the chord from them; and [`bind_all`] clears the keymap
//! before it runs, so a rebind is this list assembled again rather than a
//! patch laid over what was already there. `gpui::NoAction` would have been
//! the smaller move and is the wrong one: bound app-wide it takes the chord
//! from the editor too, which is the opposite of what freeing ⌘B is for.
//!
//! A rebind goes through [`rebind`] and not through [`bind_all`] alone,
//! because the menu bar holds its own copy of every equivalent — see
//! [`menubar::refresh`].

use crate::{
    model::settings::Shortcuts,
    view::{
        article::{self, TogglePlainText},
        board,
        component::{composer, ribbon, terminal},
        create, info, menubar,
        root::{
            self, CloseProject, NewArticle, NewBoard, NewSession, NewSessionNext, NewTable,
            NextEntry, OpenFiles, OpenProject, OpenReview, OpenSettings, PrevEntry, ToggleChanges,
            ToggleSidebar, ToggleTerminal,
        },
        table,
    },
};
use bezel::{
    gpui::{App, DummyKeyboardMapper, KeyBinding, KeybindingKeystroke, Keystroke, SharedString},
    ui::{combobox, focus, input, keys},
};

/// One command whose chord is the reader's to choose.
///
/// Named rather than reached as a field, so the settings section can list them
/// and one writer can put any of them in the file — the shape
/// [`crate::model::settings::Feature`] already uses.
///
/// What is *not* here is as decided as what is. The context-scoped keys —
/// `enter` in a card, `escape` in a dialog — cannot go on the menu bar at all
/// (see [`menubar`]) and are the surface's grammar rather than a preference.
/// ⌘Q, ⌘W, ⌘H and ⌘M are where macOS puts them for every app, and an app that
/// let you move them would be the only one you had to remember.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Command {
    OpenSettings,
    NewSession,
    NewSessionNext,
    NewBoard,
    NewArticle,
    NewTable,
    OpenProject,
    CloseProject,
    ToggleSidebar,
    ToggleTerminal,
    ToggleChanges,
    OpenFiles,
    OpenReview,
    NextEntry,
    PrevEntry,
    PlainText,
    FindCard,
}

/// Which menu a command is reached by, so the section is read in the order the
/// bar is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Menu {
    App,
    File,
    View,
}

impl Menu {
    pub const ALL: [Self; 3] = [Self::App, Self::File, Self::View];

    pub fn title(self) -> &'static str {
        match self {
            // The menu's own name, which a bundle takes from `CFBundleName`.
            Self::App => "cydonia",
            Self::File => "File",
            Self::View => "View",
        }
    }
}

impl Command {
    pub const ALL: [Self; 17] = [
        Self::OpenSettings,
        Self::NewSession,
        Self::NewSessionNext,
        Self::NewBoard,
        Self::NewArticle,
        Self::NewTable,
        Self::OpenProject,
        Self::CloseProject,
        Self::ToggleSidebar,
        Self::ToggleTerminal,
        Self::ToggleChanges,
        Self::OpenFiles,
        Self::OpenReview,
        Self::NextEntry,
        Self::PrevEntry,
        Self::PlainText,
        Self::FindCard,
    ];

    /// The key it is written under, inside `[shortcuts]`.
    pub fn key(self) -> &'static str {
        match self {
            Self::OpenSettings => "open_settings",
            Self::NewSession => "new_session",
            Self::NewSessionNext => "new_session_next",
            Self::NewBoard => "new_board",
            Self::NewArticle => "new_article",
            Self::NewTable => "new_table",
            Self::OpenProject => "open_project",
            Self::CloseProject => "close_project",
            Self::ToggleSidebar => "toggle_sidebar",
            Self::ToggleTerminal => "toggle_terminal",
            Self::ToggleChanges => "toggle_changes",
            Self::OpenFiles => "open_files",
            Self::OpenReview => "open_review",
            Self::NextEntry => "next_entry",
            Self::PrevEntry => "prev_entry",
            Self::PlainText => "plain_text",
            Self::FindCard => "find_card",
        }
    }

    /// What the menu bar calls it, so the two lists name one thing.
    pub fn title(self) -> &'static str {
        match self {
            Self::OpenSettings => "Settings…",
            Self::NewSession => "New Session",
            Self::NewSessionNext => "New Session on Next Agent",
            Self::NewBoard => "New Board",
            Self::NewArticle => "New Article",
            Self::NewTable => "New Table",
            Self::OpenProject => "Open Project…",
            Self::CloseProject => "Close Project",
            Self::ToggleSidebar => "Toggle Sidebar",
            Self::ToggleTerminal => "Toggle Terminal",
            Self::ToggleChanges => "Toggle Right Panel",
            Self::OpenFiles => "Open Files",
            Self::OpenReview => "Open Review",
            Self::NextEntry => "Next Entry",
            Self::PrevEntry => "Previous Entry",
            Self::PlainText => "Plain Text",
            Self::FindCard => "Find Card",
        }
    }

    pub fn menu(self) -> Menu {
        match self {
            Self::OpenSettings => Menu::App,
            Self::NewSession
            | Self::NewSessionNext
            | Self::NewBoard
            | Self::NewArticle
            | Self::NewTable
            | Self::OpenProject
            | Self::CloseProject => Menu::File,
            Self::ToggleTerminal
            | Self::ToggleChanges
            | Self::OpenFiles
            | Self::OpenReview
            | Self::ToggleSidebar
            | Self::NextEntry
            | Self::PrevEntry
            | Self::PlainText
            | Self::FindCard => Menu::View,
        }
    }

    /// The chord it ships with, where it ships with one. The six that do not
    /// are reachable from the menu and were never worth a default between
    /// them: ⌘N is the session, and three more `New` chords would spend the
    /// letters a person may want for their own.
    pub fn default(self) -> Option<&'static str> {
        Some(match self {
            // What macOS binds Preferences to in every other app.
            Self::OpenSettings => "secondary-,",
            Self::NewSession => "secondary-n",
            // ⌘N's other agent: the chord a second agent needs, since ⌘N
            // stays with whoever the project last talked to.
            Self::NewSessionNext => "alt-secondary-n",
            Self::NewBoard | Self::NewArticle | Self::NewTable | Self::CloseProject => return None,
            // Nothing: ⌃⇥ and ⇧⌃⇥ are what step between entries, and they are
            // bound where nothing can name them — see [`root::bindings`]. A
            // second default would go in the menu as a key equivalent, and an
            // equivalent is claimed by AppKit before the window is offered the
            // chord (user report: the pair drawn here did nothing at all).
            Self::NextEntry | Self::PrevEntry => return None,
            Self::OpenProject => "secondary-o",
            // What every app with a sidebar binds it to.
            Self::ToggleSidebar => "secondary-b",
            Self::ToggleTerminal => "secondary-j",
            Self::ToggleChanges => "secondary-l",
            Self::OpenFiles => "secondary-shift-f",
            Self::OpenReview => "secondary-shift-g",
            Self::PlainText => "secondary-e",
            Self::FindCard => "secondary-f",
        })
    }

    /// The binding this command answers to, or nothing where it answers to no
    /// chord at all.
    fn binding(self, chord: Option<&str>) -> Option<KeyBinding> {
        let chord = chord?;
        let context = GLOBAL;
        Some(match self {
            Self::OpenSettings => KeyBinding::new(chord, OpenSettings, context),
            Self::NewSession => KeyBinding::new(chord, NewSession, context),
            Self::NewSessionNext => KeyBinding::new(chord, NewSessionNext, context),
            Self::NewBoard => KeyBinding::new(chord, NewBoard, context),
            Self::NewArticle => KeyBinding::new(chord, NewArticle, context),
            Self::NewTable => KeyBinding::new(chord, NewTable, context),
            Self::OpenProject => KeyBinding::new(chord, OpenProject, context),
            Self::CloseProject => KeyBinding::new(chord, CloseProject, context),
            Self::ToggleSidebar => KeyBinding::new(chord, ToggleSidebar, context),
            Self::ToggleTerminal => KeyBinding::new(chord, ToggleTerminal, context),
            Self::ToggleChanges => KeyBinding::new(chord, ToggleChanges, context),
            Self::OpenFiles => KeyBinding::new(chord, OpenFiles, context),
            Self::OpenReview => KeyBinding::new(chord, OpenReview, context),
            Self::NextEntry => KeyBinding::new(chord, NextEntry, context),
            Self::PrevEntry => KeyBinding::new(chord, PrevEntry, context),
            Self::PlainText => KeyBinding::new(chord, TogglePlainText, context),
            // Everywhere but the files panel, which holds ⌘F for its own
            // filter — see [`bind_all`]. Scoped rather than left app-wide
            // because commands are bound last and would take the chord from
            // it.
            Self::FindCard => KeyBinding::new(
                chord,
                board::FindCard,
                Some(match NATIVE {
                    true => "!SessionPanel",
                    false => "!SessionPanel && !CydoniaTerminal",
                }),
            ),
        })
    }
}

const NATIVE: bool = cfg!(target_os = "macos");

/// The context an app-wide chord is bound in. Off macOS the secondary modifier
/// is `ctrl`, and a shell reads every `ctrl` letter, so there a focused
/// terminal keeps the keystroke.
pub(crate) const GLOBAL: Option<&str> = match NATIVE {
    true => None,
    false => Some("!CydoniaTerminal"),
};

/// `mac` on macOS, `other` everywhere else.
pub(crate) const fn platform(mac: &'static str, other: &'static str) -> &'static str {
    match NATIVE {
        true => mac,
        false => other,
    }
}

/// What `command` answers to right now: what the file says, or its default
/// where the file says nothing.
///
/// An empty string is how the file says *nothing at all* — the way to take a
/// default away, which absence cannot express because absence is the default.
/// A chord that does not parse is treated the same as one nobody wrote: the
/// line stays in the file where it can be seen and fixed, and the command
/// keeps working in the meantime.
pub fn chord(command: Command, shortcuts: &Shortcuts) -> Option<&str> {
    match shortcuts.get(command.key()) {
        Some("") => None,
        Some(chord) if parses(chord) => Some(chord),
        Some(_) | None => command.default(),
    }
}

/// Whether `chord` is one gpui can bind. Asked before it reaches
/// [`KeyBinding::new`], which panics on what it cannot parse — and this file
/// is written by hand.
pub fn parses(chord: &str) -> bool {
    let mut strokes = chord.split_whitespace().peekable();
    strokes.peek().is_some() && strokes.all(|stroke| Keystroke::parse(stroke).is_ok())
}

/// How a chord is written on screen: `cmd-shift-b` as ⇧⌘B.
pub fn glyphs(chord: &str) -> Option<SharedString> {
    let strokes = chord
        .split_whitespace()
        .map(|stroke| {
            Keystroke::parse(stroke).ok().map(|stroke| {
                KeybindingKeystroke::new_with_mapper(stroke, false, &DummyKeyboardMapper)
            })
        })
        .collect::<Option<Vec<_>>>()?;
    (!strokes.is_empty()).then(|| keys::format(&strokes))
}

/// How a command's chord is written on screen right now, for a control that
/// names it — a tooltip, a menu row.
///
/// Read off the same table [`bind_all`] is built from, so a label cannot drift
/// from the chord that fires: a control with its chord typed beside it goes on
/// saying ⌘B long after ⌘B was moved.
pub fn label(command: Command, shortcuts: &Shortcuts) -> Option<SharedString> {
    glyphs(chord(command, shortcuts)?)
}

/// The commands that already answer to `chord`, minus `mine`.
///
/// One chord on two commands is not an error the keymap reports — the later
/// binding simply wins and the earlier one goes quiet — so the section has to
/// ask before it writes.
pub fn claimed(wanted: &str, mine: Command, shortcuts: &Shortcuts) -> Vec<Command> {
    Command::ALL
        .into_iter()
        .filter(|&command| {
            command != mine && chord(command, shortcuts).is_some_and(|chord| same(chord, wanted))
        })
        .collect()
}

/// Whether two chords name the same keystrokes: `secondary-b` and `ctrl-b`
/// are one chord off macOS.
fn same(a: &str, b: &str) -> bool {
    let strokes = |chord: &str| {
        chord
            .split_whitespace()
            .map(|stroke| Keystroke::parse(stroke).ok())
            .collect::<Option<Vec<_>>>()
    };
    a == b || strokes(a).is_some_and(|a| strokes(b) == Some(a))
}

/// Optional word shortcuts, scoped to editable text.
fn emacs_bindings() -> Vec<KeyBinding> {
    vec![
        KeyBinding::new("alt-b", input::WordLeft, Some(input::KEY_CONTEXT)),
        KeyBinding::new("alt-f", input::WordRight, Some(input::KEY_CONTEXT)),
        KeyBinding::new(
            "alt-shift-b",
            input::SelectWordLeft,
            Some(input::KEY_CONTEXT),
        ),
        KeyBinding::new(
            "alt-shift-f",
            input::SelectWordRight,
            Some(input::KEY_CONTEXT),
        ),
        KeyBinding::new("alt-d", input::DeleteWordRight, Some(input::KEY_CONTEXT)),
        KeyBinding::new("alt-b", editor::keys::WordLeft, Some(editor::CONTEXT)),
        KeyBinding::new("alt-f", editor::keys::WordRight, Some(editor::CONTEXT)),
        KeyBinding::new(
            "alt-shift-b",
            editor::keys::SelectWordLeft,
            Some(editor::CONTEXT),
        ),
        KeyBinding::new(
            "alt-shift-f",
            editor::keys::SelectWordRight,
            Some(editor::CONTEXT),
        ),
        KeyBinding::new(
            "alt-d",
            editor::keys::DeleteWordRight,
            Some(editor::CONTEXT),
        ),
    ]
}

/// Put the whole keymap in, from bezel's defaults up to the commands.
///
/// Cleared first, so calling it twice leaves the same keymap as calling it
/// once — which is what makes a rebind possible without a restart.
pub fn bind_all(shortcuts: &Shortcuts, cx: &mut App) {
    cx.clear_key_bindings();
    // bezel's, which this crate has rather than takes: `init` on each of them
    // is this same list bound, and going through the data is what lets a
    // command below win a chord one of them holds.
    cx.bind_keys(input::bindings());
    cx.bind_keys(combobox::bindings());
    cx.bind_keys(focus::bindings());
    cx.bind_keys(editor::keys::bindings());
    if shortcuts.emacs {
        cx.bind_keys(emacs_bindings());
    }
    // The app's own, every one of them scoped to a surface.
    cx.bind_keys(article::bindings());
    cx.bind_keys(board::bindings());
    cx.bind_keys(composer::bindings());
    cx.bind_keys(create::bindings());
    cx.bind_keys(info::bindings());
    cx.bind_keys(ribbon::bindings());
    cx.bind_keys(table::bindings());
    cx.bind_keys(terminal::bindings());
    cx.bind_keys([
        KeyBinding::new(
            "secondary-f",
            super::component::files::ToggleFilter,
            Some(platform("SessionPanel", "SessionPanel && !CydoniaTerminal")),
        ),
        KeyBinding::new(
            "secondary-p",
            super::component::panel::OpenFile,
            Some(platform("SessionPanel", "SessionPanel && !CydoniaTerminal")),
        ),
        KeyBinding::new(
            platform("cmd-w", "ctrl-shift-w"),
            super::component::panel::CloseTab,
            Some("SessionPanel || BottomTerminalPanel"),
        ),
        KeyBinding::new(
            platform("cmd-t", "ctrl-shift-t"),
            super::component::panel::NewTerminal,
            Some("SessionPanel || BottomTerminalPanel"),
        ),
        // The chord that steps between entries everywhere else steps between
        // tabs here — see [`root::bindings`], whose binding this shadows while
        // a panel holds the focus. `cmd-tab` is the system's and never reaches
        // an app; the terminal makes no bytes of `ctrl-tab`, so a shell under
        // the pointer does not eat it either.
        KeyBinding::new(
            "ctrl-tab",
            super::component::panel::NextTab,
            Some("SessionPanel || BottomTerminalPanel"),
        ),
        KeyBinding::new(
            "ctrl-shift-tab",
            super::component::panel::PrevTab,
            Some("SessionPanel || BottomTerminalPanel"),
        ),
        KeyBinding::new(
            "secondary-s",
            super::component::file::Save,
            Some("FileEditor"),
        ),
        KeyBinding::new("secondary-c", input::Copy, Some("FileEditor")),
        KeyBinding::new("secondary-a", input::SelectAll, Some("FileEditor")),
        KeyBinding::new(
            "secondary-=",
            super::component::file::IncreaseTextSize,
            Some("FileEditor"),
        ),
        KeyBinding::new(
            "secondary-+",
            super::component::file::IncreaseTextSize,
            Some("FileEditor"),
        ),
        KeyBinding::new(
            "secondary-shift-=",
            super::component::file::IncreaseTextSize,
            Some("FileEditor"),
        ),
        KeyBinding::new(
            "secondary--",
            super::component::file::DecreaseTextSize,
            Some("FileEditor"),
        ),
        KeyBinding::new(
            "secondary-0",
            super::component::file::ResetTextSize,
            Some("FileEditor"),
        ),
    ]);
    cx.bind_keys(root::bindings());
    cx.bind_keys(menubar::bindings());
    // Last, and the only ones the reader can move.
    cx.bind_keys(
        Command::ALL
            .into_iter()
            .filter_map(|command| command.binding(chord(command, shortcuts)))
            .collect::<Vec<_>>(),
    );
}

/// Assemble the keymap again and hand the menu bar what it now says.
///
/// The second half is not decoration. AppKit holds the key equivalent it was
/// given and claims the chord before gpui is offered it, so a rebind that left
/// the menus alone would leave the old chord firing and the new one dead.
pub fn rebind(shortcuts: &Shortcuts, cx: &mut App) {
    bind_all(shortcuts, cx);
    menubar::refresh(cx);
}