Skip to main content

crisol_core/commands/
command.rs

1//! Command metadata, ids, arguments, and binding errors.
2//!
3//! ```
4//! use crisol_core::commands::command;
5//! ```
6
7use std::fmt;
8
9use super::{KeySequence, When, WhenContext};
10
11/// A stable, namespaced command identifier such as `file.save`.
12#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
13/// # Example
14///
15/// ```
16/// use crisol_core::commands::CommandId;
17/// ```
18pub struct CommandId(String);
19
20impl CommandId {
21    /// An identifier from a string. Prefer a namespaced `category.action` name.
22    pub fn new(id: impl Into<String>) -> Self {
23        Self(id.into())
24    }
25
26    /// The identifier text.
27    pub fn as_str(&self) -> &str {
28        &self.0
29    }
30
31    /// Whether the identifier is non-empty and has no whitespace.
32    pub fn is_valid(&self) -> bool {
33        !self.0.is_empty() && !self.0.chars().any(char::is_whitespace)
34    }
35
36    /// Whether the identifier is in `category.action` form.
37    pub fn is_namespaced(&self) -> bool {
38        self.0.contains('.') && self.is_valid()
39    }
40}
41
42impl fmt::Display for CommandId {
43    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
44        formatter.write_str(&self.0)
45    }
46}
47
48impl From<&str> for CommandId {
49    fn from(id: &str) -> Self {
50        Self(id.to_owned())
51    }
52}
53
54impl From<String> for CommandId {
55    fn from(id: String) -> Self {
56        Self(id)
57    }
58}
59
60impl AsRef<str> for CommandId {
61    fn as_ref(&self) -> &str {
62        &self.0
63    }
64}
65
66impl std::borrow::Borrow<str> for CommandId {
67    fn borrow(&self) -> &str {
68        &self.0
69    }
70}
71
72#[cfg(feature = "serde")]
73impl serde::Serialize for CommandId {
74    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
75        serializer.serialize_str(&self.0)
76    }
77}
78
79#[cfg(feature = "serde")]
80impl<'de> serde::Deserialize<'de> for CommandId {
81    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
82        <String as serde::Deserialize>::deserialize(deserializer).map(Self)
83    }
84}
85
86/// The kind of argument a command asks for after it is chosen.
87#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
88#[derive(Clone, Debug, PartialEq, Eq)]
89#[non_exhaustive]
90/// # Example
91///
92/// ```
93/// use crisol_core::commands::ArgKind;
94/// ```
95pub enum ArgKind {
96    /// Free text.
97    Text,
98    /// A number.
99    Number,
100    /// One of a fixed set of values.
101    Choice(Vec<String>),
102    /// A path, with an optional directory/file filter.
103    Path,
104}
105
106impl ArgKind {
107    /// A short name for the palette prompt.
108    pub fn label(&self) -> &'static str {
109        match self {
110            Self::Text => "text",
111            Self::Number => "number",
112            Self::Choice(_) => "choice",
113            Self::Path => "path",
114        }
115    }
116}
117
118/// The optional argument a command asks for.
119#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
120#[derive(Clone, Debug, PartialEq, Eq)]
121#[non_exhaustive]
122/// # Example
123///
124/// ```
125/// use crisol_core::commands::ArgSchema;
126/// ```
127pub struct ArgSchema {
128    /// The argument name, used in the prompt and the command journal.
129    pub name: String,
130    /// The prompt shown to the user.
131    pub prompt: String,
132    /// What the palette should collect.
133    pub kind: ArgKind,
134    /// Whether the command can run without it.
135    pub required: bool,
136}
137
138impl ArgSchema {
139    /// A required text argument.
140    pub fn text(name: impl Into<String>, prompt: impl Into<String>) -> Self {
141        Self {
142            name: name.into(),
143            prompt: prompt.into(),
144            kind: ArgKind::Text,
145            required: true,
146        }
147    }
148
149    /// Make the argument optional.
150    pub fn optional(mut self) -> Self {
151        self.required = false;
152        self
153    }
154
155    /// Change the kind.
156    pub fn kind(mut self, kind: ArgKind) -> Self {
157        self.kind = kind;
158        self
159    }
160}
161
162/// Enabled and checked state, updated by the application before drawing a frame.
163#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
164#[derive(Clone, Copy, Debug, PartialEq, Eq)]
165/// # Example
166///
167/// ```
168/// use crisol_core::commands::CommandState;
169/// ```
170pub struct CommandState {
171    /// Whether the command can run now.
172    pub enabled: bool,
173    /// Whether the command is a checked toggle.
174    pub checked: bool,
175}
176
177impl Default for CommandState {
178    fn default() -> Self {
179        Self {
180            enabled: true,
181            checked: false,
182        }
183    }
184}
185
186/// Metadata for one action.
187#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
188#[derive(Clone, Debug)]
189#[non_exhaustive]
190/// # Example
191///
192/// ```
193/// use crisol_core::commands::Command;
194/// ```
195pub struct Command {
196    /// Stable namespaced identifier.
197    pub id: CommandId,
198    /// Visible title.
199    pub title: String,
200    /// Group shown in menus and the palette.
201    pub category: String,
202    /// Optional icon name.
203    pub icon: Option<String>,
204    /// Optional secondary text.
205    pub description: Option<String>,
206    /// Search terms beyond the title.
207    pub keywords: Vec<String>,
208    /// The default shortcut.
209    pub default_shortcut: Option<KeySequence>,
210    /// The context in which the command is available.
211    pub when: When,
212    /// Enabled and checked state.
213    pub state: CommandState,
214    /// Optional argument schema.
215    pub args: Option<ArgSchema>,
216}
217
218impl Command {
219    /// A command with the default category (`General`).
220    pub fn new(id: impl Into<CommandId>, title: impl Into<String>) -> Self {
221        Self {
222            id: id.into(),
223            title: title.into(),
224            category: "General".to_owned(),
225            icon: None,
226            description: None,
227            keywords: Vec::new(),
228            default_shortcut: None,
229            when: When::always(),
230            state: CommandState::default(),
231            args: None,
232        }
233    }
234
235    /// Set the menu category.
236    pub fn category(mut self, category: impl Into<String>) -> Self {
237        self.category = category.into();
238        self
239    }
240
241    /// Set the icon name.
242    pub fn icon(mut self, icon: impl Into<String>) -> Self {
243        self.icon = Some(icon.into());
244        self
245    }
246
247    /// Set the secondary text.
248    pub fn description(mut self, description: impl Into<String>) -> Self {
249        self.description = Some(description.into());
250        self
251    }
252
253    /// Add search terms.
254    pub fn keywords(mut self, keywords: impl IntoIterator<Item = impl Into<String>>) -> Self {
255        self.keywords.extend(keywords.into_iter().map(Into::into));
256        self
257    }
258
259    /// Set the default shortcut. An invalid string is ignored; use
260    /// [`Self::try_shortcut`] when the caller must see the error.
261    pub fn shortcut(mut self, shortcut: impl AsRef<str>) -> Self {
262        if let Some(sequence) = KeySequence::parse(shortcut.as_ref()) {
263            self.default_shortcut = Some(sequence);
264        }
265        self
266    }
267
268    /// Set the default shortcut and report an invalid string.
269    pub fn try_shortcut(mut self, shortcut: impl AsRef<str>) -> Result<Self, BindingError> {
270        let text = shortcut.as_ref();
271        let sequence = KeySequence::parse(text).ok_or_else(|| BindingError::InvalidSequence(text.to_owned()))?;
272        self.default_shortcut = Some(sequence);
273        Ok(self)
274    }
275
276    /// Set the availability context.
277    pub fn when(mut self, when: impl AsRef<str>) -> Self {
278        if let Ok(when) = When::parse(when.as_ref()) {
279            self.when = when;
280        }
281        self
282    }
283
284    /// Set the availability context and report a parse error.
285    pub fn try_when(mut self, when: impl AsRef<str>) -> Result<Self, BindingError> {
286        self.when = When::parse(when.as_ref()).map_err(|error| BindingError::InvalidWhen(error.to_string()))?;
287        Ok(self)
288    }
289
290    /// Attach an argument schema.
291    pub fn args(mut self, schema: ArgSchema) -> Self {
292        self.args = Some(schema);
293        self
294    }
295
296    /// Whether the command is currently enabled.
297    pub fn is_enabled(&self) -> bool {
298        self.state.enabled
299    }
300
301    /// Whether the command is currently checked.
302    pub fn is_checked(&self) -> bool {
303        self.state.checked
304    }
305
306    /// Whether the command applies in `context`.
307    pub fn applies(&self, context: &WhenContext) -> bool {
308        self.when.evaluate(context)
309    }
310}
311
312/// Why a binding could not be applied.
313#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
314#[non_exhaustive]
315/// # Example
316///
317/// ```
318/// use crisol_core::commands::BindingError;
319/// ```
320pub enum BindingError {
321    /// The command does not exist.
322    #[error("unknown command `{0}`")]
323    UnknownCommand(CommandId),
324    /// The shortcut text is not a valid chord or sequence.
325    #[error("`{0}` is not a valid key sequence")]
326    InvalidSequence(String),
327    /// The `when` expression is invalid.
328    #[error("invalid when expression: {0}")]
329    InvalidWhen(String),
330    /// Another command already owns the sequence.
331    #[error("{sequence} is already bound to `{existing}`")]
332    Conflict {
333        /// The sequence that is already bound.
334        sequence: KeySequence,
335        /// The command that owns it.
336        existing: CommandId,
337    },
338}