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}
108
109impl OptionSpec {
110    pub fn id(&self) -> &'static str {
111        match self {
112            OptionSpec::Toggle { id, .. }
113            | OptionSpec::Choice { id, .. }
114            | OptionSpec::Number { id, .. } => id,
115        }
116    }
117
118    pub fn label(&self) -> &'static str {
119        match self {
120            OptionSpec::Toggle { label, .. }
121            | OptionSpec::Choice { label, .. }
122            | OptionSpec::Number { label, .. } => label,
123        }
124    }
125
126    fn default_value(&self) -> OptionValue {
127        match self {
128            OptionSpec::Toggle { default, .. } => OptionValue::Bool(*default),
129            OptionSpec::Choice { default, .. } => OptionValue::Choice((*default).to_string()),
130            OptionSpec::Number { default, .. } => OptionValue::Number(*default),
131        }
132    }
133}
134
135#[derive(Clone, PartialEq, Debug)]
136pub enum OptionValue {
137    Bool(bool),
138    Choice(String),
139    Number(i64),
140}
141
142/// The current setting of every knob a tool declared.
143///
144/// Built from the specs, so every lookup has a default and the getters cannot
145/// fail — tool implementations never deal with missing options.
146#[derive(Clone, PartialEq, Debug, Default)]
147pub struct Options {
148    values: HashMap<&'static str, OptionValue>,
149}
150
151impl Options {
152    pub fn from_specs(specs: &[OptionSpec]) -> Self {
153        Options {
154            values: specs.iter().map(|s| (s.id(), s.default_value())).collect(),
155        }
156    }
157
158    pub fn get(&self, id: &str) -> Option<&OptionValue> {
159        self.values.get(id)
160    }
161
162    pub fn set(&mut self, id: &'static str, value: OptionValue) {
163        self.values.insert(id, value);
164    }
165
166    pub fn bool(&self, id: &str) -> bool {
167        matches!(self.values.get(id), Some(OptionValue::Bool(true)))
168    }
169
170    pub fn choice(&self, id: &str) -> &str {
171        match self.values.get(id) {
172            Some(OptionValue::Choice(v)) => v,
173            _ => "",
174        }
175    }
176
177    pub fn number(&self, id: &str) -> i64 {
178        match self.values.get(id) {
179            Some(OptionValue::Number(v)) => *v,
180            _ => 0,
181        }
182    }
183}
184
185/// A human-readable failure. Tools surface these to the output pane, so the
186/// message is user-facing copy, not a debug dump.
187#[derive(Clone, PartialEq, Debug)]
188pub struct ToolError(pub String);
189
190impl ToolError {
191    pub fn new(msg: impl Into<String>) -> Self {
192        ToolError(msg.into())
193    }
194}
195
196impl fmt::Display for ToolError {
197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198        f.write_str(&self.0)
199    }
200}
201
202impl std::error::Error for ToolError {}
203
204pub type ToolResult = Result<String, ToolError>;
205
206pub trait Tool: Send + Sync {
207    fn meta(&self) -> ToolMeta;
208
209    fn input_mode(&self) -> InputMode {
210        InputMode::Text {
211            placeholder: "Paste your input here",
212        }
213    }
214
215    fn options(&self) -> &'static [OptionSpec] {
216        &[]
217    }
218
219    fn run(&self, input: Input<'_>, opts: &Options) -> ToolResult;
220}