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/// Which pane a group of options belongs beside.
49///
50/// Options live in the header of the pane they act on: the ones that decide
51/// the answer sit with the input, the ones that decide how it reads sit with
52/// the output. Keeping them apart from the panes made a tall block that
53/// squeezed everything else at small window sizes.
54#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
55pub enum OptionPane {
56    #[default]
57    Input,
58    Output,
59}
60
61/// Whether the tool transforms text or produces it from nothing.
62#[derive(Clone, Copy, PartialEq, Eq, Debug)]
63pub enum InputMode {
64    /// Runs continuously as the user types.
65    Text { placeholder: &'static str },
66    /// Two documents, for tools that compare rather than transform. The
67    /// frontend shows a pane per side; the labels name them.
68    TwoText {
69        left_label: &'static str,
70        right_label: &'static str,
71        placeholder: &'static str,
72    },
73    /// No input pane; runs when the user asks for it.
74    None,
75}
76
77/// What the user typed.
78///
79/// `right` is empty for every mode except [`InputMode::TwoText`], so a tool
80/// that only declared one input can read `left` and ignore the rest.
81#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
82pub struct Input<'a> {
83    pub left: &'a str,
84    pub right: &'a str,
85}
86
87impl<'a> Input<'a> {
88    pub fn pair(left: &'a str, right: &'a str) -> Self {
89        Input { left, right }
90    }
91}
92
93impl<'a> From<&'a str> for Input<'a> {
94    fn from(left: &'a str) -> Self {
95        Input { left, right: "" }
96    }
97}
98
99#[derive(Clone, Copy, Debug)]
100pub enum OptionSpec {
101    Toggle {
102        id: &'static str,
103        label: &'static str,
104        default: bool,
105    },
106    /// A one-of-N picker. Choices are `(value, label)` pairs.
107    Choice {
108        id: &'static str,
109        label: &'static str,
110        choices: &'static [(&'static str, &'static str)],
111        default: &'static str,
112    },
113    Number {
114        id: &'static str,
115        label: &'static str,
116        min: i64,
117        max: i64,
118        default: i64,
119    },
120    /// Marks where the options that follow belong. Carries no value of its
121    /// own; it exists so a tool with many knobs can say which of them decide
122    /// the answer and which decide how it is presented.
123    ///
124    /// Options declared before any group default to [`OptionPane::Input`].
125    Group {
126        label: &'static str,
127        pane: OptionPane,
128    },
129    /// A short free-text field, for values no picker can enumerate — a cron
130    /// field, a delimiter, a format string. Rendered inline with the other
131    /// options, so keep it genuinely short.
132    Text {
133        id: &'static str,
134        label: &'static str,
135        placeholder: &'static str,
136        default: &'static str,
137    },
138}
139
140impl OptionSpec {
141    pub fn id(&self) -> &'static str {
142        match self {
143            OptionSpec::Toggle { id, .. }
144            | OptionSpec::Choice { id, .. }
145            | OptionSpec::Number { id, .. }
146            | OptionSpec::Text { id, .. } => id,
147            // A heading holds no value, so it answers to no id.
148            OptionSpec::Group { .. } => "",
149        }
150    }
151
152    pub fn label(&self) -> &'static str {
153        match self {
154            OptionSpec::Toggle { label, .. }
155            | OptionSpec::Choice { label, .. }
156            | OptionSpec::Number { label, .. }
157            | OptionSpec::Text { label, .. }
158            | OptionSpec::Group { label, .. } => label,
159        }
160    }
161
162    /// Whether this spec carries a value the user can set.
163    pub fn is_value(&self) -> bool {
164        !matches!(self, OptionSpec::Group { .. })
165    }
166
167    fn default_value(&self) -> OptionValue {
168        match self {
169            OptionSpec::Toggle { default, .. } => OptionValue::Bool(*default),
170            OptionSpec::Choice { default, .. } => OptionValue::Choice((*default).to_string()),
171            OptionSpec::Number { default, .. } => OptionValue::Number(*default),
172            OptionSpec::Text { default, .. } => OptionValue::Text((*default).to_string()),
173            OptionSpec::Group { .. } => OptionValue::Bool(false),
174        }
175    }
176}
177
178#[derive(Clone, PartialEq, Debug)]
179pub enum OptionValue {
180    Bool(bool),
181    Choice(String),
182    Number(i64),
183    Text(String),
184}
185
186/// The current setting of every knob a tool declared.
187///
188/// Built from the specs, so every lookup has a default and the getters cannot
189/// fail — tool implementations never deal with missing options.
190#[derive(Clone, PartialEq, Debug, Default)]
191pub struct Options {
192    values: HashMap<&'static str, OptionValue>,
193}
194
195impl Options {
196    pub fn from_specs(specs: &[OptionSpec]) -> Self {
197        Options {
198            values: specs
199                .iter()
200                .filter(|s| s.is_value())
201                .map(|s| (s.id(), s.default_value()))
202                .collect(),
203        }
204    }
205
206    pub fn get(&self, id: &str) -> Option<&OptionValue> {
207        self.values.get(id)
208    }
209
210    pub fn set(&mut self, id: &'static str, value: OptionValue) {
211        self.values.insert(id, value);
212    }
213
214    pub fn bool(&self, id: &str) -> bool {
215        matches!(self.values.get(id), Some(OptionValue::Bool(true)))
216    }
217
218    pub fn choice(&self, id: &str) -> &str {
219        match self.values.get(id) {
220            Some(OptionValue::Choice(v)) => v,
221            _ => "",
222        }
223    }
224
225    pub fn number(&self, id: &str) -> i64 {
226        match self.values.get(id) {
227            Some(OptionValue::Number(v)) => *v,
228            _ => 0,
229        }
230    }
231
232    pub fn text(&self, id: &str) -> &str {
233        match self.values.get(id) {
234            Some(OptionValue::Text(v)) => v,
235            _ => "",
236        }
237    }
238}
239
240/// A human-readable failure. Tools surface these to the output pane, so the
241/// message is user-facing copy, not a debug dump.
242#[derive(Clone, PartialEq, Debug)]
243pub struct ToolError(pub String);
244
245impl ToolError {
246    pub fn new(msg: impl Into<String>) -> Self {
247        ToolError(msg.into())
248    }
249}
250
251impl fmt::Display for ToolError {
252    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253        f.write_str(&self.0)
254    }
255}
256
257impl std::error::Error for ToolError {}
258
259pub type ToolResult = Result<String, ToolError>;
260
261/// What a tool's text *is*, so a chain can refuse a link that cannot work.
262///
263/// Deliberately coarse. This exists to keep "send my list of names to the JSON
264/// formatter" out of a menu, not to type-check a pipeline; anything finer would
265/// tax every future tool for no gain.
266#[derive(Clone, Copy, PartialEq, Eq, Debug)]
267pub enum Format {
268    /// No claim made — the text could be anything. What a decoder produces,
269    /// and what a tool that takes arbitrary text accepts.
270    Any,
271    /// Human-readable text that is not structured data: a digest, a report,
272    /// a list of names. Nothing parses it, so it flows nowhere in particular.
273    Plain,
274    Json,
275    Yaml,
276    Xml,
277    Base64,
278}
279
280impl Format {
281    /// Whether text of this format can be fed to a tool accepting `accepted`.
282    ///
283    /// `Any` on either side waves the check through, and that is the point:
284    /// Base64-decode declares its output `Any` because it genuinely does not
285    /// know, which keeps the everyday chain — decode this, now pretty-print
286    /// it — in the menu. Only a format that is *known* and *wrong* is refused.
287    pub fn flows_into(self, accepted: &[Format]) -> bool {
288        self == Format::Any || accepted.contains(&Format::Any) || accepted.contains(&self)
289    }
290}
291
292pub trait Tool: Send + Sync {
293    fn meta(&self) -> ToolMeta;
294
295    fn input_mode(&self) -> InputMode {
296        InputMode::Text {
297            placeholder: "Paste your input here",
298        }
299    }
300
301    fn options(&self) -> &'static [OptionSpec] {
302        &[]
303    }
304
305    /// Formats this tool can be handed as input. The default accepts anything.
306    fn accepts(&self) -> &'static [Format] {
307        &[Format::Any]
308    }
309
310    /// What `run` will produce. Takes the options because for several tools
311    /// the answer depends on them — Base64 encodes to Base64 but decodes to
312    /// anything at all.
313    fn produces(&self, _opts: &Options) -> Format {
314        Format::Any
315    }
316
317    fn run(&self, input: Input<'_>, opts: &Options) -> ToolResult;
318}