Skip to main content

hammer/
lib.rs

1//! Hammer's plugin kit for Rust. See hammer-editor's docs/CLIENT-PLUGINS.md for the exports a plugin
2//! provides (`export`, `action`, `command`, `diagnose`) and the JSON each one is given, which always
3//! includes `locale`, the UI's language tag, for replying in the user's language. [export], [action],
4//! and [diagnose] have types for theirs.
5//!
6//! An export is a `#[unsafe(no_mangle)] pub extern "C" fn` returning `i32`, whose body is [run]:
7//!
8//! ```ignore
9//! #[unsafe(no_mangle)]
10//! pub extern "C" fn action() -> i32 {
11//!     hammer::run(|| {
12//!         let request: Request = hammer::input_json()?;
13//!         Reply::message(format!("Hello, {}", request.project)).to_json()
14//!     })
15//! }
16//! ```
17
18use serde::Serialize;
19use serde::de::DeserializeOwned;
20use std::sync::Once;
21
22pub mod action;
23pub mod base64;
24pub mod diagnose;
25pub mod export;
26pub mod http;
27pub mod images;
28pub mod ops;
29pub mod server;
30#[cfg(test)]
31mod ops_tests;
32mod word_classes;
33#[cfg(test)]
34mod text_tests;
35
36/// The host API version this kit targets; the manifest's `api` must match.
37pub const API_VERSION: u32 = 1;
38
39pub const CACHE_MAX_KEY: usize = 1024;
40pub const CACHE_MAX_VALUE: usize = 1024 * 1024;
41
42// Extism's kernel keeps the call's input, output, and any memory passed to or from Hammer. Offsets are
43// into the kernel's memory, not the module's.
44#[link(wasm_import_module = "extism:host/env")]
45unsafe extern "C" {
46    fn input_length() -> u64;
47    fn input_load_u8(index: u64) -> u8;
48    fn input_load_u64(index: u64) -> u64;
49    fn alloc(length: u64) -> u64;
50    fn free(offset: u64);
51    fn length(offset: u64) -> u64;
52    fn load_u8(offset: u64) -> u8;
53    fn load_u64(offset: u64) -> u64;
54    fn store_u8(offset: u64, value: u8);
55    fn store_u64(offset: u64, value: u64);
56    fn output_set(offset: u64, length: u64);
57    fn error_set(offset: u64);
58    fn log_debug(offset: u64);
59    fn log_info(offset: u64);
60    fn log_warn(offset: u64);
61    fn log_error(offset: u64);
62}
63
64#[link(wasm_import_module = "extism:host/user")]
65unsafe extern "C" {
66    fn hammer_dispatch(request: u64) -> u64;
67    fn hammer_cache_get(key: u64) -> u64;
68    fn hammer_cache_set(key: u64, value: u64);
69    fn hammer_progress(report: u64);
70    fn hammer_resource(name: u64) -> u64;
71}
72
73fn to_kernel(bytes: &[u8]) -> u64 {
74    unsafe {
75        let offset = alloc(bytes.len() as u64);
76        let mut chunks = bytes.chunks_exact(8);
77        let mut at = offset;
78        for chunk in &mut chunks {
79            store_u64(at, u64::from_le_bytes(chunk.try_into().unwrap()));
80            at += 8;
81        }
82        for &byte in chunks.remainder() {
83            store_u8(at, byte);
84            at += 1;
85        }
86        offset
87    }
88}
89
90fn from_kernel(offset: u64) -> Vec<u8> {
91    unsafe {
92        let size = length(offset) as usize;
93        let mut bytes = Vec::with_capacity(size);
94        let mut at = 0;
95        while at + 8 <= size {
96            bytes.extend_from_slice(&load_u64(offset + at as u64).to_le_bytes());
97            at += 8;
98        }
99        while at < size {
100            bytes.push(load_u8(offset + at as u64));
101            at += 1;
102        }
103        bytes
104    }
105}
106
107/// A failure to report to the user. `?` converts any error into one, and `.into()` a message.
108pub type Error = Box<dyn std::error::Error>;
109
110pub type Result<T> = std::result::Result<T, Error>;
111
112/// Runs an export's body: its output on success, its message on failure, and a panic's message too.
113pub fn run<O: AsRef<[u8]>>(body: impl FnOnce() -> Result<O>) -> i32 {
114    static PANIC_HOOK: Once = Once::new();
115    // A panic aborts the call with a trap; the message set here is what the user sees.
116    PANIC_HOOK.call_once(|| std::panic::set_hook(Box::new(|info| set_error(&info.to_string()))));
117    match body() {
118        Ok(output) => {
119            let output = output.as_ref();
120            unsafe { output_set(to_kernel(output), output.len() as u64) };
121            0
122        }
123        Err(error) => {
124            set_error(&error.to_string());
125            1
126        }
127    }
128}
129
130fn set_error(message: &str) {
131    unsafe { error_set(to_kernel(message.as_bytes())) };
132}
133
134pub fn input() -> Vec<u8> {
135    unsafe {
136        let size = input_length() as usize;
137        let mut bytes = Vec::with_capacity(size);
138        let mut at = 0;
139        while at + 8 <= size {
140            bytes.extend_from_slice(&input_load_u64(at as u64).to_le_bytes());
141            at += 8;
142        }
143        while at < size {
144            bytes.push(input_load_u8(at as u64));
145            at += 1;
146        }
147        bytes
148    }
149}
150
151pub fn input_json<T: DeserializeOwned>() -> Result<T> {
152    Ok(serde_json::from_slice(&input())?)
153}
154
155#[derive(serde::Deserialize)]
156struct Reply {
157    #[serde(default)]
158    output: serde_json::Value,
159    error: Option<ReplyError>,
160}
161
162#[derive(serde::Deserialize)]
163struct ReplyError {
164    kind: String,
165    #[serde(default)]
166    message: String,
167}
168
169/// Runs a Hammer operation the manifest has permission for, such as
170/// `call::<Tree>("scene.tree", &json!({"project": name}))`. A failure's message starts with its kind:
171/// NotFound, InvalidInput, PermissionDenied, or Failed.
172pub fn call<T: DeserializeOwned>(operation: &str, input: &impl Serialize) -> Result<T> {
173    #[derive(Serialize)]
174    struct Request<'a, I> {
175        operation: &'a str,
176        input: &'a I,
177    }
178    let request = to_kernel(&serde_json::to_vec(&Request { operation, input })?);
179    let reply = unsafe { hammer_dispatch(request) };
180    unsafe { free(request) };
181    let bytes = from_kernel(reply);
182    unsafe { free(reply) };
183    let reply: Reply = serde_json::from_slice(&bytes)?;
184    match reply.error {
185        Some(error) => Err(format!("{}: {}", error.kind, error.message).into()),
186        // An output of null is still a success.
187        None => Ok(serde_json::from_value(reply.output)?),
188    }
189}
190
191// The plugin's own cache, kept by Hammer between calls and runs. Hammer may drop any value at any
192// time, and clears them all when the plugin is installed again or uninstalled. A call still running on
193// the old version during an install may write after the clear, so put a version in keys whose values'
194// format may change.
195
196/// The value cached under `key`, or None when there is none.
197pub fn cache_get(key: &str) -> Option<Vec<u8>> {
198    if key.len() > CACHE_MAX_KEY {
199        return None;
200    }
201    let key = to_kernel(key.as_bytes());
202    let value = unsafe { hammer_cache_get(key) };
203    unsafe { free(key) };
204    if value == 0 {
205        return None;
206    }
207    let bytes = from_kernel(value);
208    unsafe { free(value) };
209    Some(bytes)
210}
211
212/// Caches `value` under `key`; an empty value removes it. False, storing nothing, when either is over
213/// its limit.
214pub fn cache_set(key: &str, value: &[u8]) -> bool {
215    if key.len() > CACHE_MAX_KEY || value.len() > CACHE_MAX_VALUE {
216        return false;
217    }
218    let key = to_kernel(key.as_bytes());
219    let value = if value.is_empty() { 0 } else { to_kernel(value) };
220    unsafe {
221        hammer_cache_set(key, value);
222        free(key);
223        if value != 0 {
224            free(value);
225        }
226    }
227    true
228}
229
230/// Reads a file from the package's `resources/` by its path there, such as `words/en.txt`: None when
231/// the package has none by that name, or it is empty. Hammer reads it from the package on every call,
232/// so keep one you use often.
233pub fn resource(name: &str) -> Option<Vec<u8>> {
234    let name = to_kernel(name.as_bytes());
235    let value = unsafe { hammer_resource(name) };
236    unsafe { free(name) };
237    if value == 0 {
238        return None;
239    }
240    let bytes = from_kernel(value);
241    unsafe { free(value) };
242    Some(bytes)
243}
244
245/// Reports how far an action has got: `fraction` from 0 to 1 when known, and a line saying what it is
246/// doing. Hammer shows it while the action runs. When the user has stopped the run, the call does not
247/// return: the action ends there.
248pub fn progress(fraction: Option<f64>, message: Option<&str>) {
249    #[derive(Serialize)]
250    struct Report<'a> {
251        #[serde(skip_serializing_if = "Option::is_none")]
252        fraction: Option<f64>,
253        #[serde(skip_serializing_if = "Option::is_none")]
254        message: Option<&'a str>,
255    }
256    let fraction = fraction.map(|it| it.clamp(0.0, 1.0));
257    let Ok(report) = serde_json::to_vec(&Report { fraction, message }) else { return };
258    let handle = to_kernel(&report);
259    unsafe {
260        hammer_progress(handle);
261        free(handle);
262    }
263}
264
265/// The UTF-8 byte offset of each character of `text`, plus one for its end, so a range counted in
266/// characters becomes the byte range Hammer expects.
267pub fn char_byte_offsets(text: &str) -> Vec<usize> {
268    text.char_indices().map(|(at, _)| at).chain(std::iter::once(text.len())).collect()
269}
270
271/// A word in a text: `text`, from byte `start` up to `end`, the offsets a [`diagnose::Diagnostic`] takes.
272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
273pub struct Word<'a> {
274    pub text: &'a str,
275    pub start: usize,
276    pub end: usize,
277}
278
279/// The words in `text`, in order. A word is a run of letters, with any combining marks on them, so
280/// accents, Indic vowel signs, and Arabic vowel marks stay in their word. An apostrophe (`'` or `’`), the
281/// Catalan middle dot, Hebrew's geresh and gershayim, ZWNJ, ZWJ, or a soft hyphen between two letters
282/// stays inside too, so "don't", "l'arbre", and "col·lecció" are one word each. Digits, hyphens, and
283/// everything else end a word.
284///
285/// Chinese and Japanese put no spaces between words, so each of their characters (Han, kana, and
286/// Bopomofo) is a word of its own. Thai, Lao, Khmer, and Burmese don't either, but there each run of
287/// letters is one word.
288///
289/// Letters come from a table of Unicode 17, the same one the Kotlin kit's `words` and the C kit's
290/// `hammer_words` use, so all three split text the same way.
291pub fn words(text: &str) -> impl Iterator<Item = Word<'_>> {
292    let class_at = move |at: usize| text[at..].chars().next().map_or(word_class::OTHER, word_class::of);
293    let after = move |at: usize| at + text[at..].chars().next().map_or(0, char::len_utf8);
294    let mut at = 0;
295    std::iter::from_fn(move || {
296        while at < text.len() {
297            let start = at;
298            let class = class_at(at);
299            at = after(at);
300            match class {
301                word_class::IDEOGRAPH => {
302                    while class_at(at) == word_class::MARK {
303                        at = after(at);
304                    }
305                }
306                word_class::LETTER => loop {
307                    let next = class_at(at);
308                    let inside = next == word_class::LETTER
309                        || next == word_class::MARK
310                        || (next == word_class::JOINER && class_at(after(at)) == word_class::LETTER);
311                    if !inside {
312                        break;
313                    }
314                    at = after(at);
315                },
316                _ => continue,
317            }
318            return Some(Word { text: &text[start..at], start, end: at });
319        }
320        None
321    })
322}
323
324mod word_class {
325    pub const OTHER: u8 = 0;
326    pub const LETTER: u8 = 1;
327    pub const MARK: u8 = 2;
328    pub const IDEOGRAPH: u8 = 3;
329    pub const JOINER: u8 = 4;
330
331    pub fn of(c: char) -> u8 {
332        match c {
333            'a'..='z' | 'A'..='Z' => LETTER,
334            '\'' => JOINER,
335            '\0'..='\x7F' => OTHER,
336            _ => {
337                let code = c as u32;
338                crate::word_classes::WORD_CLASSES
339                    .binary_search_by(|&(first, last, _)| {
340                        if last < code {
341                            std::cmp::Ordering::Less
342                        } else if first > code {
343                            std::cmp::Ordering::Greater
344                        } else {
345                            std::cmp::Ordering::Equal
346                        }
347                    })
348                    .map_or(OTHER, |i| crate::word_classes::WORD_CLASSES[i].2)
349            }
350        }
351    }
352}
353
354#[cfg(feature = "getrandom")]
355mod random {
356    #[link(wasm_import_module = "wasi_snapshot_preview1")]
357    unsafe extern "C" {
358        fn random_get(buf: *mut u8, len: usize) -> u16;
359    }
360
361    /// getrandom's backend, from the one WASI function Hammer offers for it. Needs
362    /// `--cfg getrandom_backend="custom"`, which this workspace's `.cargo/config.toml` sets.
363    #[unsafe(no_mangle)]
364    unsafe extern "Rust" fn __getrandom_v03_custom(dest: *mut u8, len: usize) -> Result<(), getrandom::Error> {
365        match unsafe { random_get(dest, len) } {
366            0 => Ok(()),
367            _ => Err(getrandom::Error::UNSUPPORTED),
368        }
369    }
370}
371
372pub mod log {
373    fn send(to: unsafe extern "C" fn(u64), message: &str) {
374        let handle = super::to_kernel(message.as_bytes());
375        unsafe {
376            to(handle);
377            super::free(handle);
378        }
379    }
380
381    pub fn debug(message: &str) {
382        send(super::log_debug, message)
383    }
384
385    pub fn info(message: &str) {
386        send(super::log_info, message)
387    }
388
389    pub fn warn(message: &str) {
390        send(super::log_warn, message)
391    }
392
393    pub fn error(message: &str) {
394        send(super::log_error, message)
395    }
396}