plushie-core 0.4.0

Extension SDK 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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//! Incoming wire messages from the host process.

use serde::{Deserialize, Deserializer};
use serde_json::Value;

use super::types::{PatchOp, TreeNode};

/// Messages sent from the host to the renderer over stdin.
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum IncomingMessage {
    /// Replace the entire UI tree with a new snapshot.
    Snapshot { tree: TreeNode },
    /// Apply incremental changes to the retained UI tree.
    Patch { ops: Vec<PatchOp> },
    /// Request a platform effect (file dialog, clipboard, notification).
    Effect {
        id: String,
        kind: String,
        payload: Value,
    },
    /// Perform a widget operation (focus, scroll, select, etc.).
    WidgetOp {
        op: String,
        #[serde(default)]
        payload: Value,
    },
    /// Subscribe to a runtime event source (keyboard, mouse, window, etc.).
    Subscribe {
        kind: String,
        tag: String,
        /// Maximum events per second for this subscription. Omit for
        /// unlimited (immediate delivery). Zero means "subscribe but
        /// never emit."
        #[serde(default)]
        max_rate: Option<u32>,
    },
    /// Unsubscribe from a runtime event source.
    Unsubscribe { kind: String },
    /// Perform a window operation (resize, move, close, etc.).
    WindowOp {
        op: String,
        window_id: String,
        #[serde(default)]
        settings: Value,
    },
    /// Apply or update renderer settings.
    Settings { settings: Value },
    /// Query the current tree or find a widget.
    Query {
        id: String,
        target: String,
        #[serde(default)]
        selector: Value,
    },
    /// Interact with a widget (click, type, etc.)
    Interact {
        id: String,
        action: String,
        #[serde(default)]
        selector: Value,
        #[serde(default)]
        payload: Value,
    },
    /// Capture a structural tree hash (hash of JSON tree).
    // Used by the binary crate's headless and test modes. Appears dead
    // from plushie-core's perspective because the usage is in plushie/.
    #[allow(dead_code)]
    TreeHash { id: String, name: String },
    /// Capture a pixel screenshot (GPU-rendered RGBA data).
    #[allow(dead_code)]
    Screenshot {
        id: String,
        name: String,
        #[serde(default)]
        width: Option<u32>,
        #[serde(default)]
        height: Option<u32>,
    },
    /// Reset the app state.
    Reset { id: String },
    /// Image operation (create, update, delete in-memory image handles).
    ///
    /// Binary fields (`data`, `pixels`) accept either raw bytes (from msgpack)
    /// or base64-encoded strings (from JSON). The custom deserializer handles both.
    ImageOp {
        op: String,
        handle: String,
        #[serde(default, deserialize_with = "deserialize_binary_field")]
        data: Option<Vec<u8>>,
        #[serde(default, deserialize_with = "deserialize_binary_field")]
        pixels: Option<Vec<u8>>,
        #[serde(default)]
        width: Option<u32>,
        #[serde(default)]
        height: Option<u32>,
    },
    /// A single extension command pushed to a native extension widget.
    /// Bypasses the normal tree update / diff / patch cycle.
    ExtensionCommand {
        node_id: String,
        op: String,
        #[serde(default)]
        payload: Value,
    },
    /// A batch of extension commands processed in one cycle.
    ExtensionCommands { commands: Vec<ExtensionCommandItem> },
    /// Advance the animation clock by one frame (headless/test mode).
    /// Emits an `animation_frame` event if `on_animation_frame` is subscribed.
    AdvanceFrame { timestamp: u64 },
}

/// A single item within an `ExtensionCommands` batch.
#[derive(Debug, Clone, Deserialize)]
pub struct ExtensionCommandItem {
    pub node_id: String,
    pub op: String,
    #[serde(default)]
    pub payload: Value,
}

// ---------------------------------------------------------------------------
// Binary field deserialization (handles both raw bytes and base64 strings)
// ---------------------------------------------------------------------------

/// Deserializes a binary field that may arrive as:
/// - Raw bytes (msgpack binary type, via rmpv path)
/// - Base64-encoded string (JSON path)
/// - null / absent (returns None)
///
/// When the codec's rmpv-based decode extracts binary fields and injects them
/// as `serde_json::Value::Array` of u8 values, serde picks them up as `Vec<u8>`.
/// When the field arrives as a base64 string (JSON mode), we decode it here.
fn deserialize_binary_field<'de, D>(deserializer: D) -> Result<Option<Vec<u8>>, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::Error;

    let val: Option<Value> = Option::deserialize(deserializer)?;
    match val {
        None => Ok(None),
        Some(Value::Null) => Ok(None),
        // Base64 string (JSON mode)
        Some(Value::String(s)) => {
            use base64::Engine as _;
            base64::engine::general_purpose::STANDARD
                .decode(&s)
                .map(Some)
                .map_err(|e| D::Error::custom(format!("base64 decode: {e}")))
        }
        // Array of u8 values (injected by rmpv binary extraction)
        Some(Value::Array(arr)) => {
            let bytes: Result<Vec<u8>, _> = arr
                .into_iter()
                .map(|v| {
                    v.as_u64()
                        .and_then(|n| u8::try_from(n).ok())
                        .ok_or_else(|| D::Error::custom("expected u8 in binary array"))
                })
                .collect();
            bytes.map(Some)
        }
        Some(other) => Err(D::Error::custom(format!(
            "expected string, array, or null for binary field, got {other}"
        ))),
    }
}

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

    // -----------------------------------------------------------------------
    // IncomingMessage deserialization
    // -----------------------------------------------------------------------

    #[test]
    fn deserialize_snapshot() {
        let json =
            r#"{"type":"snapshot","tree":{"id":"root","type":"column","props":{},"children":[]}}"#;
        let msg: IncomingMessage = serde_json::from_str(json).unwrap();
        match msg {
            IncomingMessage::Snapshot { tree } => {
                assert_eq!(tree.id, "root");
                assert_eq!(tree.type_name, "column");
            }
            _ => panic!("expected Snapshot"),
        }
    }

    #[test]
    fn deserialize_snapshot_nested_tree() {
        let msg: IncomingMessage = serde_json::from_value(json!({
            "type": "snapshot",
            "tree": {
                "id": "root",
                "type": "column",
                "props": { "spacing": 10 },
                "children": [{
                    "id": "c1",
                    "type": "text",
                    "props": { "content": "hello" },
                    "children": []
                }]
            }
        }))
        .unwrap();
        match msg {
            IncomingMessage::Snapshot { tree } => {
                assert_eq!(tree.children.len(), 1);
                assert_eq!(tree.children[0].id, "c1");
                assert_eq!(tree.children[0].type_name, "text");
                assert_eq!(tree.props["spacing"], 10);
            }
            _ => panic!("expected Snapshot"),
        }
    }

    #[test]
    fn deserialize_patch_replace_node() {
        let msg: IncomingMessage = serde_json::from_value(json!({
            "type": "patch",
            "ops": [{
                "op": "replace_node",
                "path": [0],
                "node": {
                    "id": "x",
                    "type": "text",
                    "props": {},
                    "children": []
                }
            }]
        }))
        .unwrap();
        match msg {
            IncomingMessage::Patch { ops } => {
                assert_eq!(ops.len(), 1);
                assert_eq!(ops[0].op, "replace_node");
                assert_eq!(ops[0].path, vec![0]);
                assert!(ops[0].rest.get("node").is_some());
            }
            _ => panic!("expected Patch"),
        }
    }

    #[test]
    fn deserialize_patch_multiple_ops() {
        let msg: IncomingMessage = serde_json::from_value(json!({
            "type": "patch",
            "ops": [
                { "op": "update_props", "path": [0], "props": { "color": "red" } },
                { "op": "remove_child", "path": [], "index": 2 }
            ]
        }))
        .unwrap();
        match msg {
            IncomingMessage::Patch { ops } => {
                assert_eq!(ops.len(), 2);
                assert_eq!(ops[0].op, "update_props");
                assert_eq!(ops[1].op, "remove_child");
            }
            _ => panic!("expected Patch"),
        }
    }

    #[test]
    fn deserialize_effect() {
        let json = r#"{"type":"effect","id":"e1","kind":"clipboard_read","payload":{}}"#;
        let msg: IncomingMessage = serde_json::from_str(json).unwrap();
        match msg {
            IncomingMessage::Effect { id, kind, payload } => {
                assert_eq!(id, "e1");
                assert_eq!(kind, "clipboard_read");
                assert!(payload.is_object());
            }
            _ => panic!("expected Effect"),
        }
    }

    #[test]
    fn deserialize_effect_with_payload() {
        let msg: IncomingMessage = serde_json::from_value(json!({
            "type": "effect",
            "id": "e2",
            "kind": "clipboard_write",
            "payload": { "text": "copied" }
        }))
        .unwrap();
        match msg {
            IncomingMessage::Effect { id, kind, payload } => {
                assert_eq!(id, "e2");
                assert_eq!(kind, "clipboard_write");
                assert_eq!(payload["text"], "copied");
            }
            _ => panic!("expected Effect"),
        }
    }

    #[test]
    fn deserialize_widget_op() {
        let json = r#"{"type":"widget_op","op":"focus","payload":{"target":"input1"}}"#;
        let msg: IncomingMessage = serde_json::from_str(json).unwrap();
        match msg {
            IncomingMessage::WidgetOp { op, payload } => {
                assert_eq!(op, "focus");
                assert_eq!(payload["target"], "input1");
            }
            _ => panic!("expected WidgetOp"),
        }
    }

    #[test]
    fn deserialize_widget_op_no_payload() {
        let json = r#"{"type":"widget_op","op":"blur"}"#;
        let msg: IncomingMessage = serde_json::from_str(json).unwrap();
        match msg {
            IncomingMessage::WidgetOp { op, payload } => {
                assert_eq!(op, "blur");
                assert!(payload.is_null());
            }
            _ => panic!("expected WidgetOp"),
        }
    }

    #[test]
    fn deserialize_subscribe() {
        let json = r#"{"type":"subscribe","kind":"on_key_press","tag":"keys"}"#;
        let msg: IncomingMessage = serde_json::from_str(json).unwrap();
        match msg {
            IncomingMessage::Subscribe {
                kind,
                tag,
                max_rate,
            } => {
                assert_eq!(kind, "on_key_press");
                assert_eq!(tag, "keys");
                assert_eq!(max_rate, None);
            }
            _ => panic!("expected Subscribe"),
        }
    }

    #[test]
    fn deserialize_subscribe_with_max_rate() {
        let json = r#"{"type":"subscribe","kind":"on_mouse_move","tag":"mouse","max_rate":30}"#;
        let msg: IncomingMessage = serde_json::from_str(json).unwrap();
        match msg {
            IncomingMessage::Subscribe {
                kind,
                tag,
                max_rate,
            } => {
                assert_eq!(kind, "on_mouse_move");
                assert_eq!(tag, "mouse");
                assert_eq!(max_rate, Some(30));
            }
            _ => panic!("expected Subscribe"),
        }
    }

    #[test]
    fn deserialize_unsubscribe() {
        let json = r#"{"type":"unsubscribe","kind":"on_key_press"}"#;
        let msg: IncomingMessage = serde_json::from_str(json).unwrap();
        match msg {
            IncomingMessage::Unsubscribe { kind } => {
                assert_eq!(kind, "on_key_press");
            }
            _ => panic!("expected Unsubscribe"),
        }
    }

    #[test]
    fn deserialize_settings() {
        let json = r#"{"type":"settings","settings":{"default_text_size":18}}"#;
        let msg: IncomingMessage = serde_json::from_str(json).unwrap();
        match msg {
            IncomingMessage::Settings { settings } => {
                assert_eq!(settings["default_text_size"], 18);
            }
            _ => panic!("expected Settings"),
        }
    }

    #[test]
    fn deserialize_window_op() {
        let msg: IncomingMessage = serde_json::from_value(json!({
            "type": "window_op",
            "op": "resize",
            "window_id": "main",
            "settings": { "width": 800, "height": 600 }
        }))
        .unwrap();
        match msg {
            IncomingMessage::WindowOp {
                op,
                window_id,
                settings,
            } => {
                assert_eq!(op, "resize");
                assert_eq!(window_id, "main");
                assert_eq!(settings["width"], 800);
                assert_eq!(settings["height"], 600);
            }
            _ => panic!("expected WindowOp"),
        }
    }

    #[test]
    fn deserialize_window_op_no_settings() {
        let json = r#"{"type":"window_op","op":"close","window_id":"popup"}"#;
        let msg: IncomingMessage = serde_json::from_str(json).unwrap();
        match msg {
            IncomingMessage::WindowOp {
                op,
                window_id,
                settings,
            } => {
                assert_eq!(op, "close");
                assert_eq!(window_id, "popup");
                assert!(settings.is_null());
            }
            _ => panic!("expected WindowOp"),
        }
    }

    #[test]
    fn deserialize_malformed_json_missing_field() {
        let json = r#"{"type":"snapshot"}"#;
        let result = serde_json::from_str::<IncomingMessage>(json);
        assert!(result.is_err());
    }

    #[test]
    fn deserialize_unknown_type_tag() {
        let json = r#"{"type":"bogus_message","data":42}"#;
        let result = serde_json::from_str::<IncomingMessage>(json);
        assert!(result.is_err());
    }

    #[test]
    fn deserialize_invalid_json_syntax() {
        let json = r#"{"type":"snapshot",,,}"#;
        let result = serde_json::from_str::<IncomingMessage>(json);
        assert!(result.is_err());
    }

    // -----------------------------------------------------------------------
    // ExtensionCommand deserialization
    // -----------------------------------------------------------------------

    #[test]
    fn extension_command_deserializes() {
        let msg: IncomingMessage = serde_json::from_value(json!({
            "type": "extension_command",
            "node_id": "term-1",
            "op": "write",
            "payload": { "data": "hello" }
        }))
        .unwrap();
        match msg {
            IncomingMessage::ExtensionCommand {
                node_id,
                op,
                payload,
            } => {
                assert_eq!(node_id, "term-1");
                assert_eq!(op, "write");
                assert_eq!(payload["data"], "hello");
            }
            _ => panic!("wrong variant"),
        }
    }

    #[test]
    fn extension_commands_deserializes() {
        let msg: IncomingMessage = serde_json::from_value(json!({
            "type": "extension_commands",
            "commands": [
                { "node_id": "term-1", "op": "write", "payload": { "data": "a" } },
                { "node_id": "log-1", "op": "append", "payload": { "line": "x" } }
            ]
        }))
        .unwrap();
        match msg {
            IncomingMessage::ExtensionCommands { commands } => {
                assert_eq!(commands.len(), 2);
                assert_eq!(commands[0].node_id, "term-1");
                assert_eq!(commands[1].op, "append");
            }
            _ => panic!("wrong variant"),
        }
    }

    #[test]
    fn extension_command_with_default_payload() {
        let json = r#"{"type":"extension_command","node_id":"ext-1","op":"reset"}"#;
        let msg: IncomingMessage = serde_json::from_str(json).unwrap();
        match msg {
            IncomingMessage::ExtensionCommand { payload, .. } => {
                assert!(payload.is_null());
            }
            _ => panic!("wrong variant"),
        }
    }

    // -----------------------------------------------------------------------
    // Scripting message deserialization
    // -----------------------------------------------------------------------

    #[test]
    fn deserialize_query() {
        let msg: IncomingMessage = serde_json::from_value(json!({
            "type": "query",
            "id": "q1",
            "target": "tree"
        }))
        .unwrap();
        assert!(matches!(msg, IncomingMessage::Query { .. }));
    }

    #[test]
    fn deserialize_query_with_selector() {
        let msg: IncomingMessage = serde_json::from_value(json!({
            "type": "query",
            "id": "q2",
            "target": "find",
            "selector": {"by": "id", "value": "btn1"}
        }))
        .unwrap();
        assert!(matches!(msg, IncomingMessage::Query { .. }));
    }

    #[test]
    fn deserialize_interact() {
        let msg: IncomingMessage = serde_json::from_value(json!({
            "type": "interact",
            "id": "i1",
            "action": "click",
            "selector": {"by": "id", "value": "btn1"},
            "payload": {}
        }))
        .unwrap();
        assert!(matches!(msg, IncomingMessage::Interact { .. }));
    }

    #[test]
    fn deserialize_tree_hash() {
        let msg: IncomingMessage = serde_json::from_value(json!({
            "type": "tree_hash",
            "id": "th1",
            "name": "check"
        }))
        .unwrap();
        assert!(matches!(msg, IncomingMessage::TreeHash { .. }));
    }

    #[test]
    fn deserialize_screenshot() {
        let msg: IncomingMessage = serde_json::from_value(json!({
            "type": "screenshot",
            "id": "ss1",
            "name": "test"
        }))
        .unwrap();
        assert!(matches!(msg, IncomingMessage::Screenshot { .. }));
    }

    #[test]
    fn deserialize_reset() {
        let msg: IncomingMessage = serde_json::from_value(json!({
            "type": "reset",
            "id": "r1"
        }))
        .unwrap();
        assert!(matches!(msg, IncomingMessage::Reset { .. }));
    }

    #[test]
    fn deserialize_advance_frame() {
        let msg: IncomingMessage = serde_json::from_value(json!({
            "type": "advance_frame",
            "timestamp": 16
        }))
        .unwrap();
        assert!(matches!(msg, IncomingMessage::AdvanceFrame { .. }));
    }
}