fui-rs 0.2.16

Web-first retained Rust UI for WebAssembly and native desktop applications
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
use crate::assets;
use crate::drawing::DrawContext;
use crate::ffi;
use crate::frame_scheduler::on_loaded;
use crate::logger::error;
use crate::node::Node;
use crate::text::TextLayout;
use crate::typography::FontFace;
use std::cell::RefCell;
use std::rc::Rc;

const MAX_DIRTY_RECTS: usize = 16;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
/// Event payload emitted when retained bitmap text is ready to rasterize.
pub struct BitmapTextReadyEventArgs;

impl BitmapTextReadyEventArgs {
    /// The stateless readiness payload.
    pub const EMPTY: Self = Self;
}

struct BitmapState {
    width: u32,
    height: u32,
    texture_id: u32,
    pixel_bytes: Vec<u8>,
    offscreen_id: u32,
    canvas_used: bool,
    draw_context: Option<DrawContext>,
    disposed: bool,
    dirty_rects: Vec<(u32, u32, u32, u32)>,
}

#[derive(Clone)]
/// A shared premultiplied-RGBA buffer, texture, and optional offscreen surface.
///
/// Clones share one resource. The final clone releases the texture and
/// offscreen surface on browser and native hosts.
///
/// ```no_run
/// use fui::prelude::*;
///
/// let bitmap = Bitmap::new(32, 32);
/// {
///     let mut pixels = bitmap.pixels();
///     pixels[0..4].copy_from_slice(&[255, 96, 32, 255]);
/// }
/// bitmap.clear_dirty_rects().dirty_rect(0, 0, 1, 1).commit();
/// ```
pub struct Bitmap {
    inner: Rc<RefCell<BitmapState>>,
}

impl Bitmap {
    /// Allocates a non-empty bitmap and its host texture/offscreen resources.
    pub fn new(width: u32, height: u32) -> Self {
        assert!(
            width > 0 && height > 0,
            "Bitmap width and height must be greater than zero."
        );
        let byte_len = (width as usize)
            .checked_mul(height as usize)
            .and_then(|value| value.checked_mul(4))
            .expect("Bitmap byte length overflow.");
        let texture_id = assets::allocate_dynamic_texture_id();
        let offscreen_id = unsafe { ffi::fui_canvas_create_offscreen(width, height) };
        Self {
            inner: Rc::new(RefCell::new(BitmapState {
                width,
                height,
                texture_id,
                pixel_bytes: vec![0; byte_len],
                offscreen_id,
                canvas_used: false,
                draw_context: None,
                disposed: false,
                dirty_rects: Vec::new(),
            })),
        }
    }

    /// Returns the physical pixel width.
    pub fn width(&self) -> u32 {
        self.inner.borrow().width
    }

    /// Returns the physical pixel height.
    pub fn height(&self) -> u32 {
        self.inner.borrow().height
    }

    /// Returns the texture ID accepted by [`DrawContext::draw_image`](crate::drawing::DrawContext::draw_image).
    pub fn texture_id(&self) -> u32 {
        self.inner.borrow().texture_id
    }

    /// Mutably borrows premultiplied RGBA bytes.
    ///
    /// Drop the returned borrow before invoking any other bitmap method.
    pub fn pixels(&self) -> std::cell::RefMut<'_, Vec<u8>> {
        std::cell::RefMut::map(self.inner.borrow_mut(), |state| {
            assert!(!state.disposed, "Bitmap.pixels() called after dispose.");
            &mut state.pixel_bytes
        })
    }

    /// Returns the current pixel-buffer address for low-level host interop.
    pub fn pixel_ptr(&self) -> usize {
        let state = self.inner.borrow();
        if state.pixel_bytes.is_empty() {
            0
        } else {
            state.pixel_bytes.as_ptr() as usize
        }
    }

    /// Returns the persistent offscreen drawing context.
    ///
    /// Once used, each [`commit`](Self::commit) flushes and reads this surface
    /// over the pixel buffer before texture upload. Do not subsequently mix
    /// direct pixel ownership into the same bitmap.
    pub fn canvas(&self) -> DrawContext {
        let mut state = self.inner.borrow_mut();
        assert!(!state.disposed, "Bitmap.canvas() called after dispose.");
        state.canvas_used = true;
        if let Some(context) = &state.draw_context {
            return context.clone();
        }
        let ptr = unsafe { ffi::fui_canvas_get_offscreen_ptr(state.offscreen_id) };
        let context = DrawContext::new(ptr);
        state.draw_context = Some(context.clone());
        context
    }

    /// Rasterizes a built, laid-out retained node into the pixel buffer.
    ///
    /// Call this after layout, then call [`commit`](Self::commit). `scale`
    /// maps logical node coordinates to physical bitmap pixels.
    pub fn render<T: Node>(&self, node: &T, x: f32, y: f32, scale: f32) -> bool {
        let mut state = self.inner.borrow_mut();
        assert!(!state.disposed, "Bitmap.render() called after dispose.");
        let handle = node.handle().raw();
        if handle == 0 {
            return false;
        }
        unsafe {
            ffi::fui_render_node_to_rgba(
                handle,
                state.width,
                state.height,
                state.pixel_bytes.as_mut_ptr() as usize,
                state.pixel_bytes.len() as u32,
                scale,
                x,
                y,
            ) != 0
        }
    }

    /// Rasterizes a ready retained text layout into the pixel buffer.
    pub fn render_text_layout(&self, layout: &TextLayout, x: f32, y: f32, scale: f32) -> bool {
        if !layout.is_ready() {
            error(
                "TextLayout",
                "Bitmap.render_text_layout() called before the TextLayout was ready; register on_ready and render after the callback.",
            );
            return false;
        }
        let node = layout.draw_node();
        self.render(&node, x, y, scale)
    }

    /// Builds and prepares a retained text node for bitmap rasterization.
    pub fn prepare_text<T: Node>(node: &T) {
        node.build();
        crate::bindings::ui::prepare_node(node.handle().raw());
    }

    /// Invokes `callback` once required fonts and initial app load are ready.
    pub fn on_text_ready<T: Node + Clone + 'static>(
        &self,
        node: &T,
        callback: impl FnOnce(BitmapTextReadyEventArgs) + 'static,
    ) -> &Self {
        let node = node.clone();
        let required_font_ids = node.required_font_ids_for_preparation();
        let callback = Rc::new(RefCell::new(Some(callback)));
        FontFace::when_fonts_loaded(&required_font_ids, move |_| {
            let node = node.clone();
            let callback = callback.clone();
            on_loaded(move |_| {
                Self::prepare_text(&node);
                if let Some(callback) = callback.borrow_mut().take() {
                    callback(BitmapTextReadyEventArgs::EMPTY);
                }
            });
        });
        self
    }

    /// Adds a clipped dirty upload region for the next commit.
    ///
    /// Empty/outside regions are ignored and at most 16 regions are retained.
    pub fn dirty_rect(&self, x: u32, y: u32, w: u32, h: u32) -> &Self {
        let mut state = self.inner.borrow_mut();
        if w == 0 || h == 0 || x >= state.width || y >= state.height {
            return self;
        }
        let cw = (x + w).min(state.width) - x;
        let ch = (y + h).min(state.height) - y;
        if state.dirty_rects.len() < MAX_DIRTY_RECTS {
            state.dirty_rects.push((x, y, cw, ch));
        }
        self
    }

    /// Clears pending dirty regions so the next commit is a full upload unless
    /// new regions are added.
    pub fn clear_dirty_rects(&self) -> &Self {
        self.inner.borrow_mut().dirty_rects.clear();
        self
    }

    /// Reports whether the next commit contains partial upload regions.
    pub fn has_dirty_rects(&self) -> bool {
        !self.inner.borrow().dirty_rects.is_empty()
    }

    /// Flushes offscreen drawing if used, uploads full or dirty pixels, consumes
    /// dirty regions, marks the texture ready, and returns its texture ID.
    pub fn commit(&self) -> u32 {
        let mut state = self.inner.borrow_mut();
        assert!(!state.disposed, "Bitmap.commit() called after dispose.");
        if state.canvas_used {
            if let Some(context) = &state.draw_context {
                context.flush();
            }
            unsafe {
                ffi::fui_canvas_read_offscreen_pixels(
                    state.offscreen_id,
                    state.pixel_bytes.as_mut_ptr() as usize,
                    state.width,
                    state.height,
                )
            };
        }
        if state.dirty_rects.is_empty() {
            unsafe {
                ffi::fui_bitmap_commit(
                    state.texture_id,
                    state.pixel_bytes.as_ptr() as usize,
                    state.pixel_bytes.len() as u32,
                    state.width,
                    state.height,
                )
            };
        } else {
            let dirty_rects = std::mem::take(&mut state.dirty_rects);
            for (x, y, w, h) in dirty_rects {
                let mut rect_bytes = vec![0u8; (w as usize) * (h as usize) * 4];
                for row in 0..h as usize {
                    let src = (((y as usize + row) * state.width as usize) + x as usize) * 4;
                    let dst = row * w as usize * 4;
                    let len = w as usize * 4;
                    rect_bytes[dst..dst + len].copy_from_slice(&state.pixel_bytes[src..src + len]);
                }
                unsafe {
                    ffi::fui_bitmap_commit_dirty(
                        state.texture_id,
                        rect_bytes.as_ptr() as usize,
                        rect_bytes.len() as u32,
                        state.width,
                        state.height,
                        x,
                        y,
                        w,
                        h,
                    )
                };
            }
        }
        assets::mark_texture_asset_ready(state.texture_id, state.width as f32, state.height as f32);
        state.texture_id
    }

    /// Releases the texture and offscreen surface early.
    ///
    /// This operation is idempotent. Drawing and pixel operations after
    /// disposal are invalid.
    pub fn dispose(&self) {
        let mut state = self.inner.borrow_mut();
        if state.disposed {
            return;
        }
        state.disposed = true;
        unsafe { ffi::fui_canvas_destroy_offscreen(state.offscreen_id) };
        unsafe { ffi::fui_bitmap_release(state.texture_id) };
        state.pixel_bytes.clear();
        state.draw_context = None;
    }
}

impl Drop for Bitmap {
    fn drop(&mut self) {
        if Rc::strong_count(&self.inner) == 1 {
            self.dispose();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::Bitmap;
    use crate::drawing::Paint;
    use crate::ffi::{self, Call};
    use crate::frame_scheduler;
    use crate::node::{Node, TextNode};
    use std::cell::Cell;
    use std::rc::Rc;

    #[test]
    fn bitmap_canvas_commit_flushes_offscreen_and_marks_asset_ready() {
        ffi::test::reset();
        let bitmap = Bitmap::new(32, 24);
        let canvas = bitmap.canvas();
        canvas.draw_rect(0.0, 0.0, 10.0, 12.0, Paint::fill(0xFF00FFFF));
        bitmap.commit();

        let calls = ffi::test::take_calls();
        assert!(calls.iter().any(|call| matches!(
            call,
            Call::CanvasCreateOffscreen {
                width: 32,
                height: 24,
                ..
            }
        )));
        assert!(calls
            .iter()
            .any(|call| matches!(call, Call::CanvasDrawBatch { .. })));
        assert!(calls.iter().any(|call| matches!(
            call,
            Call::CanvasReadOffscreenPixels {
                width: 32,
                height: 24,
                ..
            }
        )));
        assert!(calls.iter().any(|call| matches!(
            call,
            Call::BitmapCommit {
                width: 32,
                height: 24,
                ..
            }
        )));
    }

    #[test]
    fn bitmap_dirty_commit_uses_subrect_upload() {
        ffi::test::reset();
        let bitmap = Bitmap::new(8, 6);
        bitmap.dirty_rect(2, 1, 3, 2).commit();

        let calls = ffi::test::take_calls();
        assert!(calls.iter().any(|call| matches!(
            call,
            Call::BitmapCommitDirty {
                full_width: 8,
                full_height: 6,
                sub_x: 2,
                sub_y: 1,
                sub_w: 3,
                sub_h: 2,
                ..
            }
        )));
    }

    #[test]
    fn bitmap_text_ready_builds_detached_text_before_preparing_it() {
        ffi::test::reset();
        frame_scheduler::reset_commit_state();
        let bitmap = Bitmap::new(64, 32);
        let text = TextNode::new("Detached bitmap text");
        let fired = Rc::new(Cell::new(false));
        bitmap.on_text_ready(&text, {
            let fired = fired.clone();
            move |_| fired.set(true)
        });

        frame_scheduler::fire_loaded_callbacks();

        assert!(fired.get());
        assert!(text.has_built_handle());
        let calls = ffi::test::take_calls();
        assert!(calls
            .iter()
            .any(|call| matches!(call, Call::PrepareNode { .. })));
    }

    #[test]
    fn bitmap_render_retains_host_written_pixels_for_the_next_upload() {
        ffi::test::reset();
        let bitmap = Bitmap::new(2, 2);
        let text = TextNode::new("Rich bitmap text");
        text.build();

        assert!(bitmap.render(&text, 0.0, 0.0, 1.0));
        bitmap.commit();

        let calls = ffi::test::take_calls();
        assert!(calls.iter().any(|call| matches!(
            call,
            Call::BitmapCommit { bytes, .. }
                if bytes.chunks_exact(4).any(|pixel| pixel == [0x3a, 0xc5, 0x6c, 0xff])
        )));
    }
}