plushie-renderer-wasm 0.7.1

WebAssembly bindings for Plushie
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! WASM entry point for the plushie renderer.
//!
//! Provides a `wasm-bindgen` API for running plushie in the browser.
//! Uses `iced::daemon` with a canvas-based backend and communicates
//! with the host via JavaScript callbacks.
//!
//! # Usage from JavaScript
//!
//! ```js
//! import init, { PlushieApp } from './plushie_renderer_wasm.js';
//!
//! await init();
//! const app = new PlushieApp(settingsJson, (event) => {
//!     console.log('event:', event);
//! });
//! app.send_message(snapshotJson);
//! ```
//!
//! # Usage from Rust (custom WASM builds with widgets)
//!
//! ```ignore
//! let mut builder = plushie_widget_sdk::app::PlushieAppBuilder::new();
//! builder.register(Box::new(MyWidget));
//! let app = PlushieApp::with_widgets(settings, on_event, builder)?;
//! app.send_message(snapshot_json)?;
//! ```
//!
//! # Limitations
//!
//! - Platform effects (file dialogs, clipboard, notifications) are
//!   stubbed as unsupported. Web API implementations can be added in
//!   a future iteration.
//! - The WASM entry point assumes standard single-threaded
//!   `wasm32-unknown-unknown`. Shared-memory wasm modules are rejected
//!   at runtime because the JavaScript callback output path is not
//!   thread-safe.

mod effects;
mod output;

use parking_lot::Mutex;

use wasm_bindgen::prelude::*;

use plushie_renderer_engine::Codec;
use plushie_widget_sdk::protocol::IncomingMessage;
use plushie_widget_sdk::runtime::{Message, StdinEvent};

use plushie_renderer_lib::App;
use plushie_renderer_lib::emitters::emit_hello;

use effects::WebEffectHandler;
use output::WebOutputWriter;

/// Global message receiver slot. Initialized by the [`PlushieApp`]
/// constructor, consumed once by the message subscription.
static MSG_RX: Mutex<Option<futures_channel::mpsc::UnboundedReceiver<String>>> = Mutex::new(None);

fn validate_protocol_version(settings: &serde_json::Value) -> Result<(), String> {
    let expected = plushie_widget_sdk::protocol::PROTOCOL_VERSION;
    match settings
        .get("protocol_version")
        .and_then(plushie_widget_sdk::protocol::json_protocol_version)
    {
        Some(version) if version == expected => Ok(()),
        Some(version) => Err(format!(
            "protocol version mismatch: expected {expected}, got {version}"
        )),
        None => Err(format!(
            "missing or invalid protocol_version in Settings (expected {expected})"
        )),
    }
}

/// Parse a settings JSON string and validate the protocol version.
///
/// Centralizes the two-step "parse then validate" sequence the
/// WASM constructor runs before wiring up its output sink. Pulled
/// into a free function so it can be unit-tested without spinning
/// up the iced daemon or touching the global sink: the constructor
/// proper still calls into this and routes its errors to JsValue.
///
/// # Errors
///
/// Returns a human-readable error string when the JSON does not
/// parse or when the protocol version is missing, malformed, or
/// mismatched. The same message is what the WASM caller sees as
/// a `JsValue` error.
fn parse_and_validate_settings(settings_json: &str) -> Result<serde_json::Value, String> {
    let settings: serde_json::Value =
        serde_json::from_str(settings_json).map_err(|e| format!("invalid settings JSON: {e}"))?;
    validate_protocol_version(&settings)?;
    Ok(settings)
}

/// WASM plushie renderer handle.
///
/// Created via the constructor, which initializes the renderer and
/// starts the iced daemon in the background. The host sends messages
/// (Snapshots, Patches, etc.) via [`send_message`](PlushieApp::send_message)
/// and receives events via the `on_event` callback.
///
/// This WASM entry point assumes the standard single-threaded
/// `wasm32-unknown-unknown` target. The renderer stores the JavaScript
/// `on_event` callback in its output sink, so construction fails when
/// the module uses shared memory. Real wasm thread support needs a
/// redesigned output path.
#[wasm_bindgen]
pub struct PlushieApp {
    sender: futures_channel::mpsc::UnboundedSender<String>,
}

#[wasm_bindgen]
impl PlushieApp {
    /// Create a new plushie renderer with no custom widgets.
    ///
    /// Parses settings, validates the protocol version, initializes the
    /// output writer, and starts the iced daemon in the background.
    /// Returns a handle for sending messages.
    ///
    /// `on_event` is a JavaScript callback that receives serialized
    /// event strings whenever the renderer emits an outgoing event.
    #[wasm_bindgen(constructor)]
    pub fn new(settings_json: &str, on_event: js_sys::Function) -> Result<PlushieApp, JsValue> {
        Self::with_widgets(
            settings_json,
            on_event,
            plushie_widget_sdk::app::PlushieAppBuilder::new(),
        )
    }

    /// Send a JSON-encoded protocol message to the renderer.
    ///
    /// The message is parsed as an [`IncomingMessage`] and processed
    /// by the iced daemon on the next event loop tick. This is the
    /// WASM equivalent of writing to stdin on native.
    ///
    /// This method is intended for the same non-shared-memory
    /// `wasm32-unknown-unknown` entry point as [`PlushieApp`].
    ///
    /// Accepts any valid protocol message: Snapshot, Patch, Settings,
    /// Subscribe, Unsubscribe, WidgetOp, WindowOp, Effect,
    /// WidgetCommand, etc.
    pub fn send_message(&self, json: &str) -> Result<(), JsValue> {
        self.sender
            .unbounded_send(json.to_string())
            .map_err(|e| JsValue::from_str(&format!("send failed: {e}")))
    }
}

impl PlushieApp {
    /// Create a renderer with pre-registered custom widgets.
    ///
    /// Rust callers building custom WASM modules use this to register
    /// widgets at compile time. Widgets are Rust code compiled
    /// into the WASM binary, they cannot be added at runtime from JS.
    ///
    /// ```ignore
    /// let mut builder = PlushieAppBuilder::new();
    /// builder.register(Box::new(MyWidget));
    /// let app = PlushieApp::with_widgets(settings, on_event, builder)?;
    /// ```
    pub fn with_widgets(
        settings_json: &str,
        on_event: js_sys::Function,
        builder: plushie_widget_sdk::app::PlushieAppBuilder,
    ) -> Result<PlushieApp, JsValue> {
        console_log::init_with_level(log::Level::Warn).ok();

        // Order matters: parse settings and validate the protocol
        // version before wiring up the event sink. Error paths here
        // return Err(JsValue) directly to the caller; they must not
        // route through a half-initialised sink.
        let settings =
            parse_and_validate_settings(settings_json).map_err(|e| JsValue::from_str(&e))?;

        // Settings validated. Safe to initialise the output sink now.
        let writer = WebOutputWriter::try_new(on_event)?;
        let codec = Codec::Json;
        let sink = plushie_renderer_lib::WriterSink::new(Box::new(writer), codec);
        plushie_renderer_lib::emitters::init_sink(Box::new(sink));
        plushie_renderer_lib::emitters::install_panic_hook();

        let iced_settings = plushie_renderer_lib::settings::parse_iced_settings(&settings);
        plushie_renderer_lib::settings::apply_validate_props(&settings);
        let font_bytes = plushie_renderer_lib::settings::parse_inline_fonts(&settings);

        // Load inline fonts directly into the global font system so they're
        // available before the first render. On WASM there are no system fonts,
        // so without this all text renders blank. Also set the sans-serif
        // family mapping, since the default Family::SansSerif won't resolve to
        // anything unless this mapping exists.
        if !font_bytes.is_empty() {
            let font_system = iced::advanced::graphics::text::font_system();
            let mut fs = font_system.write().expect("font_system lock");
            for bytes in &font_bytes {
                fs.load_font(std::borrow::Cow::Owned(bytes.clone()));
            }
            // Find the first non-icon font and set it as sans-serif fallback.
            let family_name = {
                let raw = fs.raw();
                let db = raw.db();
                db.faces()
                    .find(|f| !f.families.iter().any(|(n, _)| n == "Iced-Icons"))
                    .and_then(|f| f.families.first().map(|(n, _)| n.clone()))
            };
            if let Some(name) = family_name {
                log::info!("setting sans-serif family to: {}", name);
                fs.raw().db_mut().set_sans_serif_family(name);
            }
        }

        // Include custom type names in the hello message.
        let ext_keys: Vec<String> = builder
            .custom_type_names()
            .iter()
            .map(|s| s.to_string())
            .collect();
        let ext_key_refs: Vec<&str> = ext_keys.iter().map(|s| s.as_str()).collect();

        // The WASM build only enables the tiny-skia iced feature;
        // wgpu is not compiled in. Report what is actually shipped.
        emit_hello("web", "tiny-skia", &ext_key_refs, &["iced"], "wasm")
            .map_err(|e| JsValue::from_str(&format!("failed to emit hello: {e}")))?;

        // Create the message channel for JS -> renderer communication.
        let (sender, receiver) = futures_channel::mpsc::unbounded::<String>();
        *MSG_RX.lock() = Some(receiver);

        // Pack init data into a Mutex so the Fn closure can move it out once.
        type InitData = (
            serde_json::Value,
            plushie_widget_sdk::app::PlushieAppBuilder,
            Vec<Vec<u8>>,
        );
        let app_slot: Mutex<Option<InitData>> = Mutex::new(Some((settings, builder, font_bytes)));

        // Spawn the iced daemon in the background. On WASM, spawn_local
        // schedules the future on the browser's microtask queue, driven
        // by requestAnimationFrame.
        wasm_bindgen_futures::spawn_local(async move {
            let result = iced::daemon(
                move || {
                    let (settings, builder, fonts) = app_slot
                        .lock()
                        .take()
                        .expect("daemon init closure called more than once");

                    let builder =
                        builder.widget_set(&plushie_widget_sdk::runtime::iced_widget_set());
                    let registry = builder.build();
                    let effect_handler = Box::new(WebEffectHandler);
                    let sink = plushie_renderer_lib::emitters::sink_arc();
                    let mut app = App::new(registry, effect_handler, sink);

                    app.scale_factor = plushie_renderer_lib::validate_scale_factor(
                        settings
                            .get("scale_factor")
                            .and_then(|v| v.as_f64())
                            .map(plushie_widget_sdk::prop_helpers::f64_to_f32)
                            .unwrap_or(1.0),
                    );

                    let effects = app.core.apply(IncomingMessage::Settings { settings });
                    for effect in effects {
                        use plushie_renderer_engine::{CoreEffect, StateChange};
                        if let CoreEffect::StateChange(StateChange::WidgetConfig(config)) = effect {
                            let ctx = plushie_widget_sdk::registry::InitCtx {
                                config: &config,
                                theme: &app.theme,
                                default_text_size: app.core.default_text_size,
                                default_font: app.core.default_font,
                            };
                            app.registry.init_all(&ctx);
                        }
                    }

                    let font_tasks: Vec<iced::Task<Message>> = fonts
                        .into_iter()
                        .map(|bytes| {
                            iced::font::load(bytes).map(|result| {
                                if let Err(e) = result {
                                    log::error!("font load error: {e:?}");
                                }
                                Message::NoOp
                            })
                        })
                        .collect();

                    let task = if font_tasks.is_empty() {
                        iced::Task::none()
                    } else {
                        iced::Task::batch(font_tasks)
                    };

                    (app, task)
                },
                App::update,
                App::view_window,
            )
            .title(App::title_for_window)
            .subscription(|app: &App| {
                iced::Subscription::batch([
                    app.renderer_subscriptions(),
                    iced::Subscription::run(message_subscription).map(Message::Stdin),
                ])
            })
            .theme(App::theme_for_window)
            .scale_factor(App::scale_factor_for_window)
            .settings(iced_settings)
            .run();

            if let Err(e) = result {
                log::error!("iced daemon error: {e}");
            }
        });

        Ok(PlushieApp { sender })
    }
}

/// Subscription that reads JSON messages from the JS channel and feeds
/// them to the iced event loop as [`StdinEvent`]s. Mirrors the native
/// stdin subscription pattern.
fn message_subscription() -> impl iced::futures::Stream<Item = StdinEvent> {
    iced::stream::channel(32, async |mut sender| {
        use iced::futures::{SinkExt, StreamExt};

        let mut rx = MSG_RX
            .lock()
            .take()
            .expect("message_subscription: no receiver (called more than once?)");

        while let Some(json) = rx.next().await {
            let event = match serde_json::from_str::<IncomingMessage>(&json) {
                Ok(msg) => StdinEvent::Message(msg),
                Err(e) => StdinEvent::Warning(format!("parse error: {e}")),
            };
            if sender.send(event).await.is_err() {
                break;
            }
        }

        // Channel closed (PlushieApp dropped); signal the daemon.
        let _ = sender.send(StdinEvent::Closed).await;
    })
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::validate_protocol_version;

    #[test]
    fn validate_protocol_version_accepts_expected_value() {
        let settings = json!({
            "protocol_version": plushie_widget_sdk::protocol::PROTOCOL_VERSION,
        });

        assert!(validate_protocol_version(&settings).is_ok());
    }

    #[test]
    fn validate_protocol_version_rejects_missing_value() {
        let settings = json!({});

        let err = validate_protocol_version(&settings).unwrap_err();
        assert!(err.contains("missing or invalid protocol_version"));
    }

    #[test]
    fn validate_protocol_version_rejects_non_integer_value() {
        let settings = json!({
            "protocol_version": 1.5,
        });

        let err = validate_protocol_version(&settings).unwrap_err();
        assert!(err.contains("missing or invalid protocol_version"));
    }

    #[test]
    fn validate_protocol_version_rejects_mismatch() {
        let settings = json!({
            "protocol_version": plushie_widget_sdk::protocol::PROTOCOL_VERSION + 1,
        });

        let err = validate_protocol_version(&settings).unwrap_err();
        assert!(err.contains("protocol version mismatch"));
    }

    // -----------------------------------------------------------------------
    // parse_and_validate_settings: the WASM entry point's gating step.
    //
    // These tests pin the error shapes a WASM host caller receives
    // before anything is wired up, so a regression that changed the
    // error wording (and broke a host's user-facing log) shows up
    // immediately.
    // -----------------------------------------------------------------------

    use super::parse_and_validate_settings;

    #[test]
    fn parse_and_validate_settings_accepts_valid_json() {
        let v = plushie_widget_sdk::protocol::PROTOCOL_VERSION;
        let json = format!(r#"{{"protocol_version": {v}, "default_text_size": 14}}"#);
        let settings = parse_and_validate_settings(&json).expect("valid settings");
        assert_eq!(settings["default_text_size"], 14);
    }

    #[test]
    fn parse_and_validate_settings_rejects_invalid_json_syntax() {
        let err = parse_and_validate_settings("{not valid json}").unwrap_err();
        assert!(
            err.starts_with("invalid settings JSON"),
            "unexpected error: {err}",
        );
    }

    #[test]
    fn parse_and_validate_settings_rejects_truncated_json() {
        // Incomplete JSON: a frame cut mid-payload would land here.
        let err = parse_and_validate_settings("{\"protocol_version\":").unwrap_err();
        assert!(err.starts_with("invalid settings JSON"));
    }

    #[test]
    fn parse_and_validate_settings_rejects_non_object_root() {
        // Top-level array, string, or number is not a Settings object.
        // The protocol_version field can't be read from a non-object,
        // so validation surfaces a missing-version error.
        let err = parse_and_validate_settings("[1, 2, 3]").unwrap_err();
        assert!(
            err.contains("missing or invalid protocol_version"),
            "got: {err}",
        );
    }

    #[test]
    fn parse_and_validate_settings_rejects_missing_protocol_version() {
        let err = parse_and_validate_settings("{}").unwrap_err();
        assert!(err.contains("missing or invalid protocol_version"));
    }

    #[test]
    fn parse_and_validate_settings_rejects_protocol_version_mismatch() {
        let v = plushie_widget_sdk::protocol::PROTOCOL_VERSION + 1;
        let json = format!(r#"{{"protocol_version": {v}}}"#);
        let err = parse_and_validate_settings(&json).unwrap_err();
        assert!(err.contains("protocol version mismatch"));
    }
}