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    /// Two documents, for tools that compare rather than transform. The
54    /// frontend shows a pane per side; the labels name them.
55    TwoText {
56        left_label: &'static str,
57        right_label: &'static str,
58        placeholder: &'static str,
59    },
60    /// No input pane; runs when the user asks for it.
61    None,
62}
63
64/// What the user typed.
65///
66/// `right` is empty for every mode except [`InputMode::TwoText`], so a tool
67/// that only declared one input can read `left` and ignore the rest.
68#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
69pub struct Input<'a> {
70    pub left: &'a str,
71    pub right: &'a str,
72}
73
74impl<'a> Input<'a> {
75    pub fn pair(left: &'a str, right: &'a str) -> Self {
76        Input { left, right }
77    }
78}
79
80impl<'a> From<&'a str> for Input<'a> {
81    fn from(left: &'a str) -> Self {
82        Input { left, right: "" }
83    }
84}
85
86#[derive(Clone, Copy, Debug)]
87pub enum OptionSpec {
88    Toggle {
89        id: &'static str,
90        label: &'static str,
91        default: bool,
92    },
93    /// A one-of-N picker. Choices are `(value, label)` pairs.
94    Choice {
95        id: &'static str,
96        label: &'static str,
97        choices: &'static [(&'static str, &'static str)],
98        default: &'static str,
99    },
100    Number {
101        id: &'static str,
102        label: &'static str,
103        min: i64,
104        max: i64,
105        default: i64,
106    },
107    /// A heading that starts a new row of options. Carries no value of its
108    /// own; it exists so a tool with many knobs can say which of them decide
109    /// the answer and which decide how it is presented.
110    Group { label: &'static str },
111    /// A short free-text field, for values no picker can enumerate — a cron
112    /// field, a delimiter, a format string. Rendered inline with the other
113    /// options, so keep it genuinely short.
114    Text {
115        id: &'static str,
116        label: &'static str,
117        placeholder: &'static str,
118        default: &'static str,
119    },
120}
121
122impl OptionSpec {
123    pub fn id(&self) -> &'static str {
124        match self {
125            OptionSpec::Toggle { id, .. }
126            | OptionSpec::Choice { id, .. }
127            | OptionSpec::Number { id, .. }
128            | OptionSpec::Text { id, .. } => id,
129            // A heading holds no value, so it answers to no id.
130            OptionSpec::Group { .. } => "",
131        }
132    }
133
134    pub fn label(&self) -> &'static str {
135        match self {
136            OptionSpec::Toggle { label, .. }
137            | OptionSpec::Choice { label, .. }
138            | OptionSpec::Number { label, .. }
139            | OptionSpec::Text { label, .. }
140            | OptionSpec::Group { label } => label,
141        }
142    }
143
144    /// Whether this spec carries a value the user can set.
145    pub fn is_value(&self) -> bool {
146        !matches!(self, OptionSpec::Group { .. })
147    }
148
149    fn default_value(&self) -> OptionValue {
150        match self {
151            OptionSpec::Toggle { default, .. } => OptionValue::Bool(*default),
152            OptionSpec::Choice { default, .. } => OptionValue::Choice((*default).to_string()),
153            OptionSpec::Number { default, .. } => OptionValue::Number(*default),
154            OptionSpec::Text { default, .. } => OptionValue::Text((*default).to_string()),
155            OptionSpec::Group { .. } => OptionValue::Bool(false),
156        }
157    }
158}
159
160#[derive(Clone, PartialEq, Debug)]
161pub enum OptionValue {
162    Bool(bool),
163    Choice(String),
164    Number(i64),
165    Text(String),
166}
167
168/// The current setting of every knob a tool declared.
169///
170/// Built from the specs, so every lookup has a default and the getters cannot
171/// fail — tool implementations never deal with missing options.
172#[derive(Clone, PartialEq, Debug, Default)]
173pub struct Options {
174    values: HashMap<&'static str, OptionValue>,
175}
176
177impl Options {
178    pub fn from_specs(specs: &[OptionSpec]) -> Self {
179        Options {
180            values: specs
181                .iter()
182                .filter(|s| s.is_value())
183                .map(|s| (s.id(), s.default_value()))
184                .collect(),
185        }
186    }
187
188    pub fn get(&self, id: &str) -> Option<&OptionValue> {
189        self.values.get(id)
190    }
191
192    pub fn set(&mut self, id: &'static str, value: OptionValue) {
193        self.values.insert(id, value);
194    }
195
196    pub fn bool(&self, id: &str) -> bool {
197        matches!(self.values.get(id), Some(OptionValue::Bool(true)))
198    }
199
200    pub fn choice(&self, id: &str) -> &str {
201        match self.values.get(id) {
202            Some(OptionValue::Choice(v)) => v,
203            _ => "",
204        }
205    }
206
207    pub fn number(&self, id: &str) -> i64 {
208        match self.values.get(id) {
209            Some(OptionValue::Number(v)) => *v,
210            _ => 0,
211        }
212    }
213
214    pub fn text(&self, id: &str) -> &str {
215        match self.values.get(id) {
216            Some(OptionValue::Text(v)) => v,
217            _ => "",
218        }
219    }
220}
221
222/// A human-readable failure. Tools surface these to the output pane, so the
223/// message is user-facing copy, not a debug dump.
224#[derive(Clone, PartialEq, Debug)]
225pub struct ToolError(pub String);
226
227impl ToolError {
228    pub fn new(msg: impl Into<String>) -> Self {
229        ToolError(msg.into())
230    }
231}
232
233impl fmt::Display for ToolError {
234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235        f.write_str(&self.0)
236    }
237}
238
239impl std::error::Error for ToolError {}
240
241pub type ToolResult = Result<String, ToolError>;
242
243pub trait Tool: Send + Sync {
244    fn meta(&self) -> ToolMeta;
245
246    fn input_mode(&self) -> InputMode {
247        InputMode::Text {
248            placeholder: "Paste your input here",
249        }
250    }
251
252    fn options(&self) -> &'static [OptionSpec] {
253        &[]
254    }
255
256    fn run(&self, input: Input<'_>, opts: &Options) -> ToolResult;
257}