crisol-core 1.3.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
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
//! The command registry: registration, bindings, and shortcut polling.
//!
//! ```
//! use crisol_core::commands::registry;
//! ```

use std::collections::{BTreeMap, VecDeque};

use super::key::Key;
use super::{BindingError, Command, CommandId, KeyChord, KeySequence, Modifiers, WhenContext};

/// One palette row without the widget: label, secondary text, and command id.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::commands::PaletteEntry;
/// ```
pub struct PaletteEntry {
    /// Primary text.
    pub label: String,
    /// Secondary text (category and shortcut).
    pub detail: String,
    /// The command to run.
    pub value: CommandId,
}

/// The result of feeding one key press to the registry.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::commands::KeyOutcome;
/// ```
pub struct KeyOutcome {
    /// Whether the key belonged to a binding (and should not reach a text field).
    pub consumed: bool,
    /// The command to run, when the sequence completed.
    pub command: Option<CommandId>,
}

/// A default binding that was skipped because another command already owns it.
#[derive(Clone, Debug, PartialEq, Eq)]
/// # Example
///
/// ```
/// use crisol_core::commands::BindingConflict;
/// ```
pub struct BindingConflict {
    /// The command whose default was ignored.
    pub command: CommandId,
    /// The command that kept the sequence.
    pub existing: CommandId,
    /// The sequence.
    pub sequence: KeySequence,
}

/// The command registry.
#[derive(Clone, Debug)]
/// # Example
///
/// ```
/// use crisol_core::commands::CommandRegistry;
/// ```
pub struct CommandRegistry {
    commands: BTreeMap<CommandId, Command>,
    overrides: BTreeMap<CommandId, Option<KeySequence>>,
    conflicts: Vec<BindingConflict>,
    recent: VecDeque<CommandId>,
    pending: Vec<KeyChord>,
    pending_at: f64,
    pending_timeout: f64,
}

impl Default for CommandRegistry {
    fn default() -> Self {
        Self {
            commands: BTreeMap::new(),
            overrides: BTreeMap::new(),
            conflicts: Vec::new(),
            recent: VecDeque::new(),
            pending: Vec::new(),
            pending_at: 0.0,
            pending_timeout: Self::DEFAULT_TIMEOUT,
        }
    }
}

impl CommandRegistry {
    /// The default sequence timeout, in seconds (the 0.1.3 value).
    pub const DEFAULT_TIMEOUT: f64 = 1.5;

    /// An empty registry.
    pub fn new() -> Self {
        Self {
            pending_timeout: Self::DEFAULT_TIMEOUT,
            ..Self::default()
        }
    }

    /// Register a command. A default shortcut that conflicts with an earlier command is
    /// skipped and recorded in [`Self::conflicts`].
    pub fn register(&mut self, command: Command) -> Option<Command> {
        let id = command.id.clone();
        if let Some(sequence) = command.default_shortcut.clone()
            && let Some(existing) = self.owner_of(&sequence, Some(&id))
        {
            self.conflicts.push(BindingConflict {
                command: id.clone(),
                existing,
                sequence,
            });
        }
        self.commands.insert(id, command)
    }

    /// Register several commands.
    pub fn register_all(&mut self, commands: impl IntoIterator<Item = Command>) {
        for command in commands {
            self.register(command);
        }
    }

    /// Remove a command and its binding.
    pub fn remove(&mut self, id: &CommandId) -> Option<Command> {
        self.overrides.remove(id);
        self.recent.retain(|recent| recent != id);
        self.commands.remove(id)
    }

    /// A command by id.
    pub fn get(&self, id: &CommandId) -> Option<&Command> {
        self.commands.get(id)
    }

    /// A command by id, mutably.
    pub fn get_mut(&mut self, id: &CommandId) -> Option<&mut Command> {
        self.commands.get_mut(id)
    }

    /// Every command, sorted by id.
    pub fn iter(&self) -> impl Iterator<Item = &Command> {
        self.commands.values()
    }

    /// The number of commands.
    pub fn len(&self) -> usize {
        self.commands.len()
    }

    /// Whether no command is registered.
    pub fn is_empty(&self) -> bool {
        self.commands.is_empty()
    }

    /// Set the enabled state.
    pub fn set_enabled(&mut self, id: &CommandId, enabled: bool) -> bool {
        match self.commands.get_mut(id) {
            Some(command) => {
                command.state.enabled = enabled;
                true
            }
            None => false,
        }
    }

    /// Set the checked state.
    pub fn set_checked(&mut self, id: &CommandId, checked: bool) -> bool {
        match self.commands.get_mut(id) {
            Some(command) => {
                command.state.checked = checked;
                true
            }
            None => false,
        }
    }

    /// The palette metadata for the commands that apply in `context`, recent first.
    ///
    /// The UI maps each entry to its own `PaletteItem`; the core does not know the
    /// widget (CORE-KEY-02).
    pub fn palette_entries(&self, context: &WhenContext) -> Vec<PaletteEntry> {
        let mut entries = Vec::with_capacity(self.commands.len());
        for id in self.recent() {
            if let Some(entry) = self.entry_for(context, id) {
                entries.push(entry);
            }
        }
        for command in self.commands.values() {
            if self.recent().any(|recent| recent == &command.id) {
                continue;
            }
            if let Some(entry) = self.entry_for(context, &command.id) {
                entries.push(entry);
            }
        }
        entries
    }

    fn entry_for(&self, context: &WhenContext, id: &CommandId) -> Option<PaletteEntry> {
        let command = self.commands.get(id)?;
        if !command.is_enabled() || !command.applies(context) {
            return None;
        }
        let shortcut = self.binding(id).map(ToString::to_string).unwrap_or_default();
        let detail = if shortcut.is_empty() {
            command.category.clone()
        } else {
            format!("{} · {shortcut}", command.category)
        };
        Some(PaletteEntry {
            label: command.title.clone(),
            detail,
            value: id.clone(),
        })
    }

    /// The categories in display order.
    pub fn categories(&self) -> Vec<&str> {
        let mut categories: Vec<&str> = self
            .commands
            .values()
            .map(|command| command.category.as_str())
            .collect();
        categories.sort_unstable();
        categories.dedup();
        categories
    }

    /// The default shortcut of a command.
    pub fn default_binding(&self, id: &CommandId) -> Option<&KeySequence> {
        self.commands
            .get(id)
            .and_then(|command| command.default_shortcut.as_ref())
    }

    /// The active shortcut of a command, including overrides.
    pub fn binding(&self, id: &CommandId) -> Option<&KeySequence> {
        match self.overrides.get(id) {
            Some(override_binding) => override_binding.as_ref(),
            None => self.default_binding(id),
        }
    }

    /// Bind a command to a sequence, replacing its default. Fails when another command
    /// owns the sequence.
    ///
    /// # Errors
    /// When the command is unknown or another command already owns the sequence.
    pub fn bind(&mut self, id: &CommandId, sequence: KeySequence) -> Result<(), BindingError> {
        if !self.commands.contains_key(id) {
            return Err(BindingError::UnknownCommand(id.clone()));
        }
        if sequence.is_empty() {
            return Err(BindingError::InvalidSequence(String::new()));
        }
        if let Some(existing) = self.owner_of(&sequence, Some(id)) {
            return Err(BindingError::Conflict { sequence, existing });
        }
        self.overrides.insert(id.clone(), Some(sequence));
        Ok(())
    }

    /// Remove the active binding of a command.
    pub fn unbind(&mut self, id: &CommandId) {
        self.overrides.insert(id.clone(), None);
    }

    /// Return a command to its default binding.
    pub fn reset_binding(&mut self, id: &CommandId) {
        self.overrides.remove(id);
    }

    /// Whether the command has a user override (including an explicit unbind).
    pub fn has_override(&self, id: &CommandId) -> bool {
        self.overrides.contains_key(id)
    }

    /// The command that owns a sequence, if any.
    pub fn owner_of(&self, sequence: &KeySequence, except: Option<&CommandId>) -> Option<CommandId> {
        self.commands
            .iter()
            .filter(|(id, _)| except.is_none_or(|except| *id != except))
            .find(|(id, _command)| self.binding(id).is_some_and(|binding| binding == sequence))
            .map(|(id, _)| id.clone())
    }

    /// Defaults that were ignored because another command owned the sequence.
    pub fn conflicts(&self) -> &[BindingConflict] {
        &self.conflicts
    }

    /// Every active binding, longest sequence first.
    pub fn bindings(&self) -> Vec<(KeySequence, CommandId)> {
        let mut bindings: Vec<(KeySequence, CommandId)> = self
            .commands
            .keys()
            .filter_map(|id| self.binding(id).map(|sequence| (sequence.clone(), id.clone())))
            .collect();
        bindings.sort_by(|left, right| right.0.len().cmp(&left.0.len()).then_with(|| left.1.cmp(&right.1)));
        bindings
    }

    /// Feed one key press and resolve it against the registry.
    ///
    /// A single chord returns its command immediately. A prefix such as `Ctrl+K` starts
    /// a pending sequence and returns `consumed = true` with no command; the next chord
    /// completes it within [`Self::pending_timeout`] seconds. Time is passed in by the
    /// caller (normally from a [`Clock`](crate::time::Clock)); the core never reads a
    /// clock itself (CORE-KEY-03, CORE-DET-02).
    pub fn handle_key(&mut self, key: Key, modifiers: Modifiers, now: f64, context: &WhenContext) -> KeyOutcome {
        if !self.pending.is_empty() && now - self.pending_at > self.pending_timeout {
            self.pending.clear();
        }
        let candidates: Vec<(KeySequence, CommandId)> = self
            .bindings()
            .into_iter()
            .filter(|(_, id)| {
                self.commands
                    .get(id)
                    .is_some_and(|command| command.is_enabled() && command.applies(context))
            })
            .collect();

        if self.pending.is_empty() {
            for (sequence, id) in &candidates {
                let Some(first) = sequence.chords().first() else {
                    continue;
                };
                if first.matches(modifiers, key) {
                    if sequence.len() == 1 {
                        self.note_used(id.clone());
                        return KeyOutcome {
                            consumed: true,
                            command: Some(id.clone()),
                        };
                    }
                    self.pending.push(*first);
                    self.pending_at = now;
                    return KeyOutcome {
                        consumed: true,
                        command: None,
                    };
                }
            }
            return KeyOutcome::default();
        }

        let pending = self.pending.clone();
        let mut consumed = false;
        for (sequence, id) in &candidates {
            if !sequence.starts_with(&pending) || sequence.len() <= pending.len() {
                continue;
            }
            let Some(chord) = sequence.chords().get(pending.len()).copied() else {
                continue;
            };
            if chord.matches(modifiers, key) {
                consumed = true;
                self.pending.push(chord);
                self.pending_at = now;
                if self.pending.len() == sequence.len() {
                    self.pending.clear();
                    self.note_used(id.clone());
                    return KeyOutcome {
                        consumed: true,
                        command: Some(id.clone()),
                    };
                }
                break;
            }
        }
        if !consumed {
            self.pending.clear();
        }
        KeyOutcome {
            consumed,
            command: None,
        }
    }

    /// Seconds a started sequence waits for its next chord.
    pub fn pending_timeout(&self) -> f64 {
        self.pending_timeout
    }

    /// Change the sequence timeout.
    pub fn set_pending_timeout(&mut self, seconds: f64) {
        self.pending_timeout = seconds.max(0.0);
    }

    /// Mark a command as recently used, for palette ranking.
    pub fn note_used(&mut self, id: CommandId) {
        self.recent.retain(|recent| recent != &id);
        self.recent.push_front(id);
        while self.recent.len() > 12 {
            self.recent.pop_back();
        }
    }

    /// Recently used commands, newest first.
    pub fn recent(&self) -> impl Iterator<Item = &CommandId> {
        self.recent.iter()
    }

    /// Clear the recent list.
    pub fn clear_recent(&mut self) {
        self.recent.clear();
    }

    /// The chord currently being waited for, if a sequence has started.
    pub fn pending(&self) -> &[KeyChord] {
        &self.pending
    }
}

impl FromIterator<Command> for CommandRegistry {
    fn from_iter<T: IntoIterator<Item = Command>>(iter: T) -> Self {
        let mut registry = Self::new();
        registry.register_all(iter);
        registry
    }
}

#[cfg(test)]
mod tests;