1mod error;
28pub use error::CommandError;
29
30use std::collections::VecDeque;
31use std::fmt;
32
33use serde::Serialize;
34use serde_json::Value as Json;
35
36use crate::ids::{CommandId, MenuId, OwnerId};
37use crate::keymap::BindOptions;
38use crate::registry::Registry;
39use crate::when::{When, WhenContext};
40
41#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, serde::Deserialize)]
44#[serde(tag = "kind", content = "id", rename_all = "lowercase")]
45pub enum Origin {
46 User,
48 Agent(String),
50 Script(String),
52 Device(String),
54 Remote(String),
56}
57
58impl fmt::Display for Origin {
59 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69 match self {
70 Origin::User => f.write_str("user"),
71 Origin::Agent(n) => write!(f, "agent:{n}"),
72 Origin::Script(n) => write!(f, "script:{n}"),
73 Origin::Device(n) => write!(f, "device:{n}"),
74 Origin::Remote(n) => write!(f, "remote:{n}"),
75 }
76 }
77}
78
79impl Origin {
80 pub fn writer(&self) -> OwnerId {
86 let (kind, name) = match self {
87 Origin::User => return OwnerId::FRAMEWORK,
88 Origin::Agent(n) => ("agent", n),
89 Origin::Script(n) => ("script", n),
90 Origin::Device(n) => ("device", n),
91 Origin::Remote(n) => ("remote", n),
92 };
93 let text = format!("{kind}:{name}");
94 OwnerId::new(text.clone()).unwrap_or_else(|_| {
95 let clean: String = text
96 .chars()
97 .take(128)
98 .map(|c| {
99 if c.is_ascii_alphanumeric() || "._:/-".contains(c) {
100 c
101 } else {
102 '_'
103 }
104 })
105 .collect();
106 OwnerId::new(clean).unwrap_or(OwnerId::from_static("unnamed"))
107 })
108 }
109}
110
111#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
113pub struct MenuPlacement {
114 pub menu: MenuId,
115 pub group: String,
116 pub order: i32,
117}
118
119#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
122pub struct KeySpec {
123 pub keys: String,
124 pub options: BindOptions,
125}
126
127#[derive(Clone, Debug, PartialEq, Serialize)]
130#[non_exhaustive]
131pub struct ArgMatch {
132 pub arg: String,
135 pub equals: Json,
137}
138
139impl ArgMatch {
140 pub fn matches(&self, args: &Json) -> bool {
142 let found = if self.arg.starts_with('/') {
143 args.pointer(&self.arg)
144 } else {
145 args.get(&self.arg)
146 };
147 found == Some(&self.equals)
148 }
149}
150
151#[derive(Clone, Debug, PartialEq, Serialize)]
153#[non_exhaustive]
154pub struct CommandSpec {
155 pub id: CommandId,
157 pub title: String,
158 pub category: String,
159 pub description: String,
161 pub when: String,
163 pub checked: String,
166 pub keys: Vec<KeySpec>,
168 pub menus: Vec<MenuPlacement>,
170 pub palette: bool,
172 pub agent: bool,
174 pub read_only: bool,
179 #[serde(skip_serializing_if = "std::ops::Not::not")]
185 pub destructive: bool,
186 #[serde(skip_serializing_if = "Vec::is_empty")]
192 pub destructive_if: Vec<ArgMatch>,
193 #[serde(skip_serializing_if = "std::ops::Not::not")]
198 pub private: bool,
199 pub args: Json,
207 #[serde(skip_serializing_if = "Option::is_none")]
211 pub icon: Option<String>,
212 #[serde(skip_serializing_if = "Option::is_none")]
215 pub icon_on: Option<String>,
216 #[serde(skip_serializing_if = "Option::is_none")]
219 pub menu_note: Option<String>,
220 #[serde(skip_serializing_if = "std::ops::Not::not")]
223 pub opens_link: bool,
224}
225
226impl CommandSpec {
227 pub fn new(id: CommandId, title: &str, category: &str) -> Self {
228 Self {
229 id,
230 title: title.into(),
231 category: category.into(),
232 description: String::new(),
233 when: String::new(),
234 checked: String::new(),
235 keys: Vec::new(),
236 menus: Vec::new(),
237 palette: true,
238 agent: true,
239 read_only: false,
240 destructive: false,
241 destructive_if: Vec::new(),
242 private: false,
243 args: Json::Null,
244 icon: None,
245 icon_on: None,
246 menu_note: None,
247 opens_link: false,
248 }
249 }
250
251 pub fn icon(mut self, name: &str) -> Self {
255 self.icon = Some(name.into());
256 self
257 }
258
259 pub fn icon_on(mut self, name: &str) -> Self {
261 self.icon_on = Some(name.into());
262 self
263 }
264
265 pub fn menu_note(mut self, note: &str) -> Self {
267 self.menu_note = Some(note.into());
268 self
269 }
270
271 pub fn opens_link(mut self, link: bool) -> Self {
274 self.opens_link = link;
275 self
276 }
277
278 pub fn icon_for(&self, checked: bool) -> Option<&str> {
281 if checked && let Some(on) = &self.icon_on {
282 return Some(on);
283 }
284 self.icon.as_deref()
285 }
286
287 pub fn when(mut self, when: &str) -> Self {
288 self.when = when.into();
289 self
290 }
291
292 pub fn checked(mut self, clause: &str) -> Self {
294 self.checked = clause.into();
295 self
296 }
297
298 pub fn description(mut self, text: &str) -> Self {
299 self.description = text.into();
300 self
301 }
302
303 pub fn key(self, keys: &str) -> Self {
306 self.key_with(keys, BindOptions::global())
307 }
308
309 pub fn key_with(mut self, keys: &str, options: BindOptions) -> Self {
312 self.keys.push(KeySpec {
313 keys: keys.into(),
314 options,
315 });
316 self
317 }
318
319 pub fn menu(mut self, menu: MenuId, group: &str, order: i32) -> Self {
321 self.menus.push(MenuPlacement {
322 menu,
323 group: group.into(),
324 order,
325 });
326 self
327 }
328
329 pub fn hidden(mut self) -> Self {
331 self.palette = false;
332 self
333 }
334
335 pub fn no_agent(mut self) -> Self {
337 self.agent = false;
338 self
339 }
340
341 pub fn read_only(mut self) -> Self {
345 self.read_only = true;
346 self
347 }
348
349 pub fn destructive(mut self) -> Self {
353 self.destructive = true;
354 self
355 }
356
357 pub fn destructive_if(mut self, arg: &str, value: Json) -> Self {
364 self.destructive_if.push(ArgMatch {
365 arg: arg.into(),
366 equals: value,
367 });
368 self
369 }
370
371 pub fn is_destructive(&self, args: &Json) -> bool {
375 self.destructive || self.destructive_if.iter().any(|m| m.matches(args))
376 }
377
378 pub fn private(mut self) -> Self {
384 self.private = true;
385 self
386 }
387
388 pub fn args(mut self, args: Json) -> Self {
391 self.args = args;
392 self
393 }
394
395 pub fn schema(self, schema: Json) -> Self {
403 self.args(schema)
404 }
405}
406
407pub type FnHandler = Box<dyn Fn(&Json, &Origin) -> Result<Json, String> + Send + Sync>;
409
410#[derive(Clone, Debug, PartialEq, Eq)]
412pub enum RegisterError {
413 BadWhen { id: CommandId, error: String },
415 Duplicate { id: CommandId, by: OwnerId },
417}
418
419impl fmt::Display for RegisterError {
420 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
421 match self {
422 RegisterError::BadWhen { id, error } => write!(f, "command `{id}`: {error}"),
423 RegisterError::Duplicate { id, by } => {
424 write!(f, "command `{id}` is already declared by `{by}`")
425 }
426 }
427 }
428}
429
430impl std::error::Error for RegisterError {}
431
432#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
434#[serde(tag = "refused", rename_all = "snake_case")]
435pub enum RunRefused {
436 Unknown { id: String },
437 NotHere { id: String, when: String },
438}
439
440impl fmt::Display for RunRefused {
441 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
442 match self {
443 RunRefused::Unknown { id } => write!(f, "no command `{id}`"),
444 RunRefused::NotHere { id, when } => write!(f, "`{id}` does not apply here ({when})"),
445 }
446 }
447}
448
449pub struct Entry<H> {
451 pub spec: CommandSpec,
452 when: When,
453 pub handler: H,
454}
455
456impl<H> fmt::Debug for Entry<H> {
457 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
458 f.debug_struct("Entry").field("spec", &self.spec).finish()
459 }
460}
461
462#[derive(Clone, Debug, PartialEq, Serialize)]
464pub struct Run {
465 pub id: CommandId,
466 pub args: Json,
467 pub origin: Origin,
468 pub result: Result<Json, String>,
469}
470
471pub const HISTORY: usize = 256;
473
474pub struct Commands<H = FnHandler> {
476 entries: Registry<CommandId, Entry<H>>,
477 history: VecDeque<Run>,
478}
479
480impl<H> Default for Commands<H> {
481 fn default() -> Self {
482 Self {
483 entries: Registry::new(),
484 history: VecDeque::new(),
485 }
486 }
487}
488
489impl<H> fmt::Debug for Commands<H> {
490 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
491 f.debug_struct("Commands")
492 .field("ids", &self.specs().map(|s| &s.id).collect::<Vec<_>>())
493 .field("history", &self.history.len())
494 .finish()
495 }
496}
497
498impl<H> Commands<H> {
499 pub fn new() -> Self {
500 Self::default()
501 }
502
503 pub fn register(
505 &mut self,
506 owner: &OwnerId,
507 spec: CommandSpec,
508 handler: H,
509 ) -> Result<(), RegisterError> {
510 let when = When::parse(&spec.when).map_err(|error| RegisterError::BadWhen {
511 id: spec.id.clone(),
512 error,
513 })?;
514 When::parse(&spec.checked).map_err(|error| RegisterError::BadWhen {
515 id: spec.id.clone(),
516 error: format!("checked: {error}"),
517 })?;
518 let id = spec.id.clone();
519 self.entries
520 .insert(
521 owner,
522 id,
523 Entry {
524 spec,
525 when,
526 handler,
527 },
528 )
529 .map_err(|t| RegisterError::Duplicate { id: t.id, by: t.by })
530 }
531
532 pub fn spec(&self, id: &CommandId) -> Option<&CommandSpec> {
533 self.entries.get(id).map(|e| &e.spec)
534 }
535
536 pub fn owner(&self, id: &CommandId) -> Option<&OwnerId> {
537 self.entries.owner(id)
538 }
539
540 pub fn specs(&self) -> impl Iterator<Item = &CommandSpec> {
542 self.entries.iter().map(|(_, s)| &s.item.spec)
543 }
544
545 pub fn applies(&self, id: &CommandId, cx: &WhenContext) -> bool {
547 self.entries.get(id).is_some_and(|e| e.when.eval(cx))
548 }
549
550 pub fn available(&self, cx: &WhenContext) -> Vec<&CommandSpec> {
552 self.entries
553 .iter()
554 .filter(|(_, s)| s.item.when.eval(cx))
555 .map(|(_, s)| &s.item.spec)
556 .collect()
557 }
558
559 pub fn search(&self, query: &str, cx: &WhenContext) -> Vec<&CommandSpec> {
564 let words: Vec<String> = query.split_whitespace().map(str::to_lowercase).collect();
565 let q = query.trim().to_lowercase();
566 let mut hits: Vec<(u8, &CommandSpec)> = self
567 .available(cx)
568 .into_iter()
569 .filter(|s| s.palette)
570 .filter_map(|s| {
571 let hay = format!("{} {} {}", s.category, s.title, s.id).to_lowercase();
572 if !words.iter().all(|w| hay.contains(w)) {
573 return None;
574 }
575 let title = s.title.to_lowercase();
576 let rank = if !q.is_empty() && title.starts_with(&q) {
577 0
578 } else if words.iter().all(|w| {
579 hay.split(|c: char| !c.is_alphanumeric())
580 .any(|t| t.starts_with(w.as_str()))
581 }) {
582 1
583 } else {
584 2
585 };
586 Some((rank, s))
587 })
588 .collect();
589 hits.sort_by(|a, b| (a.0, &a.1.title).cmp(&(b.0, &b.1.title)));
590 hits.into_iter().map(|(_, s)| s).collect()
591 }
592
593 pub fn prepare(&self, id: &CommandId, cx: &WhenContext) -> Result<&H, RunRefused> {
595 let entry = self
596 .entries
597 .get(id)
598 .ok_or_else(|| RunRefused::Unknown { id: id.to_string() })?;
599 if entry.when.eval(cx) {
600 Ok(&entry.handler)
601 } else {
602 Err(RunRefused::NotHere {
603 id: id.to_string(),
604 when: entry.spec.when.clone(),
605 })
606 }
607 }
608
609 pub fn record(&mut self, run: Run) {
611 if self.history.len() == HISTORY {
612 self.history.pop_front();
613 }
614 self.history.push_back(run);
615 }
616
617 pub fn history(&self) -> impl Iterator<Item = &Run> {
619 self.history.iter()
620 }
621
622 pub fn remove(&mut self, id: &CommandId) -> Option<OwnerId> {
624 self.entries.remove(id).map(|slot| slot.owner)
625 }
626
627 pub fn remove_owner(&mut self, owner: &OwnerId) -> Vec<CommandId> {
629 self.entries
630 .remove_owner(owner)
631 .into_iter()
632 .map(|(id, _)| id)
633 .collect()
634 }
635
636 pub fn len(&self) -> usize {
637 self.entries.len()
638 }
639
640 pub fn is_empty(&self) -> bool {
641 self.entries.is_empty()
642 }
643}
644
645impl Commands<FnHandler> {
646 pub fn register_fn(
648 &mut self,
649 owner: &OwnerId,
650 spec: CommandSpec,
651 handler: impl Fn(&Json, &Origin) -> Result<Json, String> + Send + Sync + 'static,
652 ) -> Result<(), RegisterError> {
653 self.register(owner, spec, Box::new(handler))
654 }
655
656 pub fn run(
659 &mut self,
660 id: &CommandId,
661 args: Json,
662 origin: Origin,
663 cx: &WhenContext,
664 ) -> Result<Json, String> {
665 let result = match self.prepare(id, cx) {
666 Ok(h) => h(&args, &origin),
667 Err(e @ RunRefused::Unknown { .. }) => return Err(e.to_string()),
668 Err(e) => Err(e.to_string()),
669 };
670 self.record(Run {
671 id: id.clone(),
672 args,
673 origin,
674 result: result.clone(),
675 });
676 result
677 }
678}
679
680#[cfg(test)]
681mod destructive_tests {
682 use super::*;
683 use serde_json::json;
684
685 #[test]
686 fn a_call_is_destructive_whole_or_by_its_arguments() {
687 let id = CommandId::from_static("library.export");
688 let plain = CommandSpec::new(id.clone(), "Export", "Library");
689 assert!(!plain.is_destructive(&json!({ "clash": "overwrite" })));
690
691 let whole = plain.clone().destructive();
692 assert!(whole.is_destructive(&Json::Null));
693 assert!(whole.destructive_if.is_empty());
694
695 let by_args = plain
696 .destructive_if("clash", json!("overwrite"))
697 .destructive_if("/options/purge", json!(true));
698 assert!(!by_args.destructive);
699 assert!(!by_args.is_destructive(&Json::Null));
700 assert!(!by_args.is_destructive(&json!({ "clash": "rename" })));
701 assert!(by_args.is_destructive(&json!({ "clash": "overwrite" })));
702 assert!(!by_args.is_destructive(&json!({ "options": { "purge": false } })));
703 assert!(by_args.is_destructive(&json!({ "options": { "purge": true } })));
704 let shown = serde_json::to_value(&by_args).unwrap();
705 assert_eq!(
706 shown["destructive_if"][0],
707 json!({ "arg": "clash", "equals": "overwrite" })
708 );
709 assert!(shown.get("destructive").is_none());
710 }
711}