Skip to main content

rustafari_core/
spec.rs

1//! The UI-agnostic contract every tool implements.
2//!
3//! A tool declares *what* knobs it has; it never says how they are drawn. The
4//! frontend renders `OptionSpec`s generically, so adding a tool requires no UI
5//! code at all.
6
7use std::collections::HashMap;
8use std::fmt;
9
10#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
11pub enum Category {
12    Formatters,
13    Encoders,
14    Generators,
15    Text,
16}
17
18impl Category {
19    pub const ALL: &'static [Category] = &[
20        Category::Formatters,
21        Category::Encoders,
22        Category::Generators,
23        Category::Text,
24    ];
25
26    pub fn label(self) -> &'static str {
27        match self {
28            Category::Formatters => "Formatters",
29            Category::Encoders => "Encoders & Decoders",
30            Category::Generators => "Generators",
31            Category::Text => "Text",
32        }
33    }
34}
35
36/// Identity and search metadata for a tool.
37#[derive(Clone, Copy, Debug)]
38pub struct ToolMeta {
39    /// Stable id, used for persistence. Never change it once released.
40    pub id: &'static str,
41    pub name: &'static str,
42    pub category: Category,
43    pub description: &'static str,
44    /// Extra search terms that don't appear in the name.
45    pub keywords: &'static [&'static str],
46}
47
48/// Whether the tool transforms text or produces it from nothing.
49#[derive(Clone, Copy, PartialEq, Eq, Debug)]
50pub enum InputMode {
51    /// Runs continuously as the user types.
52    Text { placeholder: &'static str },
53    /// No input pane; runs when the user asks for it.
54    None,
55}
56
57#[derive(Clone, Copy, Debug)]
58pub enum OptionSpec {
59    Toggle {
60        id: &'static str,
61        label: &'static str,
62        default: bool,
63    },
64    /// A one-of-N picker. Choices are `(value, label)` pairs.
65    Choice {
66        id: &'static str,
67        label: &'static str,
68        choices: &'static [(&'static str, &'static str)],
69        default: &'static str,
70    },
71    Number {
72        id: &'static str,
73        label: &'static str,
74        min: i64,
75        max: i64,
76        default: i64,
77    },
78}
79
80impl OptionSpec {
81    pub fn id(&self) -> &'static str {
82        match self {
83            OptionSpec::Toggle { id, .. }
84            | OptionSpec::Choice { id, .. }
85            | OptionSpec::Number { id, .. } => id,
86        }
87    }
88
89    pub fn label(&self) -> &'static str {
90        match self {
91            OptionSpec::Toggle { label, .. }
92            | OptionSpec::Choice { label, .. }
93            | OptionSpec::Number { label, .. } => label,
94        }
95    }
96
97    fn default_value(&self) -> OptionValue {
98        match self {
99            OptionSpec::Toggle { default, .. } => OptionValue::Bool(*default),
100            OptionSpec::Choice { default, .. } => OptionValue::Choice((*default).to_string()),
101            OptionSpec::Number { default, .. } => OptionValue::Number(*default),
102        }
103    }
104}
105
106#[derive(Clone, PartialEq, Debug)]
107pub enum OptionValue {
108    Bool(bool),
109    Choice(String),
110    Number(i64),
111}
112
113/// The current setting of every knob a tool declared.
114///
115/// Built from the specs, so every lookup has a default and the getters cannot
116/// fail — tool implementations never deal with missing options.
117#[derive(Clone, PartialEq, Debug, Default)]
118pub struct Options {
119    values: HashMap<&'static str, OptionValue>,
120}
121
122impl Options {
123    pub fn from_specs(specs: &[OptionSpec]) -> Self {
124        Options {
125            values: specs.iter().map(|s| (s.id(), s.default_value())).collect(),
126        }
127    }
128
129    pub fn get(&self, id: &str) -> Option<&OptionValue> {
130        self.values.get(id)
131    }
132
133    pub fn set(&mut self, id: &'static str, value: OptionValue) {
134        self.values.insert(id, value);
135    }
136
137    pub fn bool(&self, id: &str) -> bool {
138        matches!(self.values.get(id), Some(OptionValue::Bool(true)))
139    }
140
141    pub fn choice(&self, id: &str) -> &str {
142        match self.values.get(id) {
143            Some(OptionValue::Choice(v)) => v,
144            _ => "",
145        }
146    }
147
148    pub fn number(&self, id: &str) -> i64 {
149        match self.values.get(id) {
150            Some(OptionValue::Number(v)) => *v,
151            _ => 0,
152        }
153    }
154}
155
156/// A human-readable failure. Tools surface these to the output pane, so the
157/// message is user-facing copy, not a debug dump.
158#[derive(Clone, PartialEq, Debug)]
159pub struct ToolError(pub String);
160
161impl ToolError {
162    pub fn new(msg: impl Into<String>) -> Self {
163        ToolError(msg.into())
164    }
165}
166
167impl fmt::Display for ToolError {
168    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169        f.write_str(&self.0)
170    }
171}
172
173impl std::error::Error for ToolError {}
174
175pub type ToolResult = Result<String, ToolError>;
176
177pub trait Tool: Send + Sync {
178    fn meta(&self) -> ToolMeta;
179
180    fn input_mode(&self) -> InputMode {
181        InputMode::Text {
182            placeholder: "Paste your input here",
183        }
184    }
185
186    fn options(&self) -> &'static [OptionSpec] {
187        &[]
188    }
189
190    fn run(&self, input: &str, opts: &Options) -> ToolResult;
191}