plushie-renderer-lib 0.6.0

Shared renderer engine 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
//! Widget operations: focus, scroll, cursor, pane grid, font loading,
//! tree hash queries, image management. Dispatched from [`CoreEffect::WidgetOp`]
//! via the `op` string and JSON `payload`.

use iced::widget::pane_grid;
use iced::{Task, window};

use plushie_ext::message::Message;
use plushie_ext::protocol::OutgoingEvent;

use crate::App;
use crate::emitters::emit_event;

use std::sync::atomic::{AtomicU32, Ordering};

use crate::constants::MAX_FONT_BYTES;

/// Maximum number of runtime font loads per process lifetime. Each
/// `load_font` call permanently leaks font bytes into iced's global
/// font system (no unload API). This cap prevents unbounded memory
/// growth from a misbehaving host.
const MAX_LOADED_FONTS: u32 = 256;

/// Process-wide counter of runtime font loads (windowed mode).
static LOADED_FONT_COUNT: AtomicU32 = AtomicU32::new(0);

// ---------------------------------------------------------------------------
// Widget operations (impl App)
// ---------------------------------------------------------------------------

impl App {
    /// Dispatch a widget operation by name. Called when Core produces a
    /// `WidgetOp` effect. Returns an iced `Task` for operations that
    /// need async completion (focus, scroll, font load).
    pub fn handle_widget_op(&mut self, op: &str, payload: &serde_json::Value) -> Task<Message> {
        let get_target = || {
            payload
                .get("target")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string()
        };

        match op {
            "focus" => {
                iced::widget::operation::focus::<Message>(iced::widget::Id::from(get_target()))
            }
            "focus_element" => {
                // Focus a specific interactive element within a canvas.
                // Focuses the canvas widget (so it receives keyboard events),
                // then emits a CanvasElementFocused event so the SDK knows
                // which element should be considered focused.
                //
                // Note: this sets iced-level focus on the canvas but does
                // NOT set the canvas's internal focused_id. The internal
                // state will be set when on_focus_gained fires (if the
                // canvas had a previously focused element) or on the first
                // keyboard interaction. Full programmatic element focus
                // requires a custom iced operation (future enhancement).
                let target = get_target();
                let element_id = payload
                    .get("element_id")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let focus_task = iced::widget::operation::focus::<Message>(iced::widget::Id::from(
                    target.clone(),
                ));
                if !element_id.is_empty() {
                    // Store the pending focus in caches so the canvas
                    // Program can set focused_id on the next update().
                    self.core
                        .caches
                        .set_canvas_pending_focus(target, element_id);
                }
                focus_task
            }
            "focus_next" => iced::widget::operation::focus_next(),
            "focus_previous" => iced::widget::operation::focus_previous(),
            "scroll_to" => {
                let target = get_target();
                let offset_x = payload
                    .get("offset_x")
                    .and_then(|v| v.as_f64())
                    .map(|v| v as f32);
                let offset_y = payload
                    .get("offset_y")
                    .and_then(|v| v.as_f64())
                    .map(|v| v as f32);
                iced::widget::operation::scroll_to(
                    iced::widget::Id::from(target),
                    iced::widget::operation::AbsoluteOffset {
                        x: offset_x.unwrap_or(0.0),
                        y: offset_y.unwrap_or(0.0),
                    },
                )
            }
            "scroll_by" => {
                let target = get_target();
                let offset_x = payload
                    .get("offset_x")
                    .and_then(|v| v.as_f64())
                    .unwrap_or(0.0) as f32;
                let offset_y = payload
                    .get("offset_y")
                    .and_then(|v| v.as_f64())
                    .unwrap_or(0.0) as f32;
                iced::widget::operation::scroll_by(
                    iced::widget::Id::from(target),
                    iced::widget::operation::AbsoluteOffset {
                        x: offset_x,
                        y: offset_y,
                    },
                )
            }
            "snap_to" => {
                let target = get_target();
                let x = payload.get("x").and_then(|v| v.as_f64()).map(|v| v as f32);
                let y = payload.get("y").and_then(|v| v.as_f64()).map(|v| v as f32);
                iced::widget::operation::snap_to(
                    iced::widget::Id::from(target),
                    iced::widget::operation::RelativeOffset { x, y },
                )
            }
            "snap_to_end" => {
                let target = get_target();
                iced::widget::operation::snap_to_end(iced::widget::Id::from(target))
            }
            "select_all" => {
                iced::widget::operation::select_all(iced::widget::Id::from(get_target()))
            }
            "select_range" => {
                let target = get_target();
                let start = payload.get("start").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
                let end = payload.get("end").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
                iced::widget::operation::select_range(iced::widget::Id::from(target), start, end)
            }
            "move_cursor_to_front" => {
                iced::widget::operation::move_cursor_to_front(iced::widget::Id::from(get_target()))
            }
            "move_cursor_to_end" => {
                iced::widget::operation::move_cursor_to_end(iced::widget::Id::from(get_target()))
            }
            "move_cursor_to" => {
                let target = get_target();
                let position = payload
                    .get("position")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0) as usize;
                iced::widget::operation::move_cursor_to(iced::widget::Id::from(target), position)
            }
            "close_window" => {
                // Look up the plushie window_id from the payload and close the
                // correct iced window. Falls back to oldest window only if no
                // window_id is provided (backwards compat).
                let win_id = payload
                    .get("window_id")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default();
                if !win_id.is_empty() {
                    if let Some(iced_id) = self.windows.remove_by_window(win_id) {
                        window::close(iced_id)
                    } else {
                        log::warn!("close_window: unknown window_id: {win_id}");
                        Task::none()
                    }
                } else {
                    window::oldest().and_then(window::close)
                }
            }
            "announce" => {
                let text = payload
                    .get("text")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string();
                iced::announce(text)
            }
            "exit" => iced::exit(),
            // -- PaneGrid operations --
            // The host sends: target (grid id), pane, axis, new_pane_id, a, b
            "pane_split" => {
                let target = get_target();
                let pane_id = payload
                    .get("pane")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string();
                let new_pane_id = payload
                    .get("new_pane_id")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string();
                let axis = match payload
                    .get("axis")
                    .and_then(|v| v.as_str())
                    .unwrap_or("vertical")
                {
                    "horizontal" => pane_grid::Axis::Horizontal,
                    _ => pane_grid::Axis::Vertical,
                };

                if let Some(state) = self.core.caches.pane_grid_state_mut(&target)
                    && let Some(pane) = find_pane_by_id(state, &pane_id)
                {
                    let _ = state.split(axis, pane, new_pane_id);
                }
                Task::none()
            }
            "pane_close" => {
                let target = get_target();
                let pane_id = payload
                    .get("pane")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string();

                if let Some(state) = self.core.caches.pane_grid_state_mut(&target)
                    && let Some(pane) = find_pane_by_id(state, &pane_id)
                {
                    let _ = state.close(pane);
                }
                Task::none()
            }
            "pane_swap" => {
                let target = get_target();
                let a_id = payload
                    .get("a")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string();
                let b_id = payload
                    .get("b")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string();

                if let Some(state) = self.core.caches.pane_grid_state_mut(&target)
                    && let (Some(a), Some(b)) =
                        (find_pane_by_id(state, &a_id), find_pane_by_id(state, &b_id))
                {
                    state.swap(a, b);
                }
                Task::none()
            }
            "pane_maximize" => {
                let target = get_target();
                let pane_id = payload
                    .get("pane")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string();

                if let Some(state) = self.core.caches.pane_grid_state_mut(&target)
                    && let Some(pane) = find_pane_by_id(state, &pane_id)
                {
                    state.maximize(pane);
                }
                Task::none()
            }
            "pane_restore" => {
                let target = get_target();

                if let Some(state) = self.core.caches.pane_grid_state_mut(&target) {
                    state.restore();
                }
                Task::none()
            }
            "find_focused" => {
                let tag = payload
                    .get("tag")
                    .and_then(|v| v.as_str())
                    .unwrap_or("find_focused")
                    .to_string();
                iced::widget::operation::find_focused().map(move |maybe_id| {
                    let focused = maybe_id.map(|id| id.to_string());
                    if let Err(e) = crate::emitters::emit_query_response(
                        "find_focused",
                        &tag,
                        serde_json::json!({"focused": focused}),
                    ) {
                        log::error!("write error: {e}");
                    }
                    Message::NoOp
                })
            }
            // Load a font from base64-encoded data at runtime. Supports
            // TrueType (.ttf), OpenType (.otf), and TrueType Collections
            // (.ttc). Variable fonts are supported. Format detection is
            // handled by fontdb (via cosmic-text) -- no explicit format
            // field is needed.
            "load_font" => {
                let data = payload
                    .get("data")
                    .and_then(crate::settings::decode_font_data)
                    .unwrap_or_default();
                if data.is_empty() {
                    log::warn!("load_font: no font data provided");
                    Task::none()
                } else if data.len() > MAX_FONT_BYTES {
                    log::warn!(
                        "load_font: font data ({} bytes) exceeds {} byte limit, rejecting",
                        data.len(),
                        MAX_FONT_BYTES
                    );
                    Task::none()
                } else if LOADED_FONT_COUNT.load(Ordering::Relaxed) >= MAX_LOADED_FONTS {
                    log::warn!(
                        "load_font: already loaded {MAX_LOADED_FONTS} fonts, \
                         rejecting to prevent unbounded memory growth"
                    );
                    Task::none()
                } else {
                    LOADED_FONT_COUNT.fetch_add(1, Ordering::Relaxed);
                    iced::font::load(data).map(|result| {
                        match result {
                            Ok(()) => log::info!("font loaded successfully"),
                            Err(e) => log::error!("font load failed: {e:?}"),
                        }
                        Message::NoOp
                    })
                }
            }
            "tree_hash" => {
                let tag = payload
                    .get("tag")
                    .and_then(|v| v.as_str())
                    .unwrap_or("tree_hash")
                    .to_string();
                let hash = self.core.tree_hash();
                if let Err(e) = crate::emitters::emit_query_response(
                    "tree_hash",
                    &tag,
                    serde_json::json!({"hash": hash}),
                ) {
                    log::error!("write error: {e}");
                    return iced::exit();
                }
                Task::none()
            }
            "list_images" => {
                let tag = payload
                    .get("tag")
                    .and_then(|v| v.as_str())
                    .unwrap_or("list_images")
                    .to_string();
                let handles: Vec<String> = self.image_registry.handle_names();
                if let Err(e) = crate::emitters::emit_query_response(
                    "list_images",
                    &tag,
                    serde_json::json!({"handles": handles}),
                ) {
                    log::error!("write error: {e}");
                    return iced::exit();
                }
                Task::none()
            }
            "clear_images" => {
                self.image_registry.clear();
                Task::none()
            }
            other => {
                log::warn!("unknown widget_op: {other}");
                Task::none()
            }
        }
    }

    // -----------------------------------------------------------------------
    // Image operations
    // -----------------------------------------------------------------------

    /// Apply an image operation (create, update, remove) to the
    /// in-memory image registry. Emits an error event on failure.
    pub fn handle_image_op(
        &mut self,
        op: &str,
        handle: &str,
        data: Option<Vec<u8>>,
        pixels: Option<Vec<u8>>,
        width: Option<u32>,
        height: Option<u32>,
    ) {
        if let Err(error) = self
            .image_registry
            .apply_op(op, handle, data, pixels, width, height)
        {
            // Best-effort error notification. If stdout is broken the
            // next synchronous write in update() will exit cleanly.
            if let Err(e) = emit_event(OutgoingEvent::generic(
                "image_error".to_string(),
                handle.to_string(),
                Some(serde_json::json!({ "error": error })),
            )) {
                log::error!("write error: {e}");
            }
        }
    }
}

// ---------------------------------------------------------------------------
// PaneGrid helpers
// ---------------------------------------------------------------------------

/// Find a pane_grid::Pane by its ID string.
pub fn find_pane_by_id(state: &pane_grid::State<String>, pane_id: &str) -> Option<pane_grid::Pane> {
    state
        .panes
        .iter()
        .find(|(_, id)| id.as_str() == pane_id)
        .map(|(pane, _)| *pane)
}