1use std::fmt;
8
9use super::{KeySequence, When, WhenContext};
10
11#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
13pub struct CommandId(String);
19
20impl CommandId {
21 pub fn new(id: impl Into<String>) -> Self {
23 Self(id.into())
24 }
25
26 pub fn as_str(&self) -> &str {
28 &self.0
29 }
30
31 pub fn is_valid(&self) -> bool {
33 !self.0.is_empty() && !self.0.chars().any(char::is_whitespace)
34 }
35
36 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#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
88#[derive(Clone, Debug, PartialEq, Eq)]
89#[non_exhaustive]
90pub enum ArgKind {
96 Text,
98 Number,
100 Choice(Vec<String>),
102 Path,
104}
105
106impl ArgKind {
107 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#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
120#[derive(Clone, Debug, PartialEq, Eq)]
121#[non_exhaustive]
122pub struct ArgSchema {
128 pub name: String,
130 pub prompt: String,
132 pub kind: ArgKind,
134 pub required: bool,
136}
137
138impl ArgSchema {
139 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 pub fn optional(mut self) -> Self {
151 self.required = false;
152 self
153 }
154
155 pub fn kind(mut self, kind: ArgKind) -> Self {
157 self.kind = kind;
158 self
159 }
160}
161
162#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
164#[derive(Clone, Copy, Debug, PartialEq, Eq)]
165pub struct CommandState {
171 pub enabled: bool,
173 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#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
188#[derive(Clone, Debug)]
189#[non_exhaustive]
190pub struct Command {
196 pub id: CommandId,
198 pub title: String,
200 pub category: String,
202 pub icon: Option<String>,
204 pub description: Option<String>,
206 pub keywords: Vec<String>,
208 pub default_shortcut: Option<KeySequence>,
210 pub when: When,
212 pub state: CommandState,
214 pub args: Option<ArgSchema>,
216}
217
218impl Command {
219 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 pub fn category(mut self, category: impl Into<String>) -> Self {
237 self.category = category.into();
238 self
239 }
240
241 pub fn icon(mut self, icon: impl Into<String>) -> Self {
243 self.icon = Some(icon.into());
244 self
245 }
246
247 pub fn description(mut self, description: impl Into<String>) -> Self {
249 self.description = Some(description.into());
250 self
251 }
252
253 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 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 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 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 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 pub fn args(mut self, schema: ArgSchema) -> Self {
292 self.args = Some(schema);
293 self
294 }
295
296 pub fn is_enabled(&self) -> bool {
298 self.state.enabled
299 }
300
301 pub fn is_checked(&self) -> bool {
303 self.state.checked
304 }
305
306 pub fn applies(&self, context: &WhenContext) -> bool {
308 self.when.evaluate(context)
309 }
310}
311
312#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
314#[non_exhaustive]
315pub enum BindingError {
321 #[error("unknown command `{0}`")]
323 UnknownCommand(CommandId),
324 #[error("`{0}` is not a valid key sequence")]
326 InvalidSequence(String),
327 #[error("invalid when expression: {0}")]
329 InvalidWhen(String),
330 #[error("{sequence} is already bound to `{existing}`")]
332 Conflict {
333 sequence: KeySequence,
335 existing: CommandId,
337 },
338}