mtk-rs 0.1.0-beta.3

Muse Toolkit
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
//! Canvas widgets and painter abstractions for 2D software pixel buffers and custom WGPU pipelines.
//!
//! The canvas element allows developers to render arbitrary visual content inside the MTK
//! layout hierarchy. MTK supports two modes of canvas painting:
//!
//! 1. [`PixelPainter`]: Software-based direct pixel manipulation using a raw `[u32]` color buffer.
//! 2. [`WgpuPainter`]: Hardware-accelerated GPU rendering with full access to `wgpu` render/compute
//!    pipelines, shaders, uniform buffers, and offscreen render targets.
//!
//! Because canvases render into offscreen GPU textures, MTK seamlessly composites them with
//! native SDF rounded corners ([`corner_radius`](crate::style::Style::corner_radius)), opacity, borders,
//! scale, and scissor clipping without requiring extra boilerplate from the painter.

use std::cell::Cell;
use std::marker::PhantomData;

use crate::{
    Color, Context, Node,
    ui::{Event, View, event::EventResult},
};

/// A CPU-side pixel buffer representing the drawing area of a [`PixelPainter`].
///
/// ### Pixel Format: **RGBA8**
///
/// The image buffer uses standard **RGBA8** layout (8 bits per channel: Red, Green, Blue, Alpha).
/// Each pixel in the slice is laid out as 4 consecutive bytes `[R, G, B, A]`.
///
/// When accessing raw `u32` values:
/// * On native little-endian architectures, `0xAABBGGRR` maps directly to bytes `[R, G, B, A]`.
/// * You can use [`Color`] directly with [`set_pixel_with_color`](PixelBuffer::set_pixel_with_color),
///   [`get_pixel_by_color`](PixelBuffer::get_pixel_by_color), [`fill_with_color`](PixelBuffer::fill_with_color), etc.
/// * You can also construct raw RGBA `u32` values with [`PixelBuffer::rgba`](PixelBuffer::rgba) or [`PixelBuffer::rgb`](PixelBuffer::rgb).
pub struct PixelBuffer<'a> {
    /// Physical canvas width in pixels.
    pub width: u32,
    /// Physical canvas height in pixels.
    pub height: u32,
    /// Current display scale factor.
    pub scale_factor: f32,
    /// Mutable slice of 32-bit pixel values with length `width * height` in RGBA8 format.
    pub pixels: &'a mut [u32],
    pub(crate) frame_requested: &'a Cell<bool>,
}

impl<'a> PixelBuffer<'a> {
    /// Packs `(r, g, b, a)` components into a 32-bit integer matching the buffer's native RGBA8 layout.
    #[inline]
    pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> u32 {
        u32::from_ne_bytes([r, g, b, a])
    }

    /// Packs `(r, g, b)` components with full opacity (`a = 255`) into a 32-bit RGBA8 integer.
    #[inline]
    pub const fn rgb(r: u8, g: u8, b: u8) -> u32 {
        Self::rgba(r, g, b, 255)
    }

    /// Creates a new `PixelBuffer` wrapping a slice of pixels.
    #[inline]
    pub fn new(
        width: u32,
        height: u32,
        scale_factor: f32,
        pixels: &'a mut [u32],
        frame_requested: &'a Cell<bool>,
    ) -> Self {
        Self {
            width,
            height,
            scale_factor,
            pixels,
            frame_requested,
        }
    }

    /// Returns the logical width of the canvas in points.
    #[inline]
    pub fn logical_width(&self) -> f32 {
        self.width as f32 / self.scale_factor
    }

    /// Returns the logical height of the canvas in points.
    #[inline]
    pub fn logical_height(&self) -> f32 {
        self.height as f32 / self.scale_factor
    }

    /// Converts logical canvas coordinates `(x, y)` to physical buffer pixel coordinates `(px, py)`.
    #[inline]
    pub fn logical_to_physical(&self, x: f32, y: f32) -> (u32, u32) {
        (
            ((x * self.scale_factor).round() as u32).min(self.width.saturating_sub(1)),
            ((y * self.scale_factor).round() as u32).min(self.height.saturating_sub(1)),
        )
    }

    /// Fills a rectangular region defined in logical points, properly scaled by `scale_factor`.
    #[inline]
    pub fn fill_logical_rect_with_color(&mut self, x: f32, y: f32, w: f32, h: f32, color: Color) {
        let px = (x * self.scale_factor).round() as i32;
        let py = (y * self.scale_factor).round() as i32;
        let pw = ((w * self.scale_factor).round() as u32).max(1);
        let ph = ((h * self.scale_factor).round() as u32).max(1);
        self.fill_rect_with_color(px, py, pw, ph, color);
    }

    /// Schedules a redraw for the next frame. Call this if your pixel canvas contains continuous animations.
    #[inline]
    pub fn request_frame(&self) {
        self.frame_requested.set(true);
    }

    /// Sets the color of a single pixel at `(x, y)` using a raw 32-bit RGBA8 value. Out-of-bounds coordinates are ignored.
    #[inline]
    pub fn set_pixel(&mut self, x: u32, y: u32, color: u32) {
        if x < self.width && y < self.height {
            let index = (y * self.width + x) as usize;
            if index < self.pixels.len() {
                self.pixels[index] = color;
            }
        }
    }

    /// Sets the color of a single pixel at `(x, y)` using MTK's [`Color`]. Out-of-bounds coordinates are ignored.
    #[inline]
    pub fn set_pixel_with_color(&mut self, x: u32, y: u32, color: Color) {
        self.set_pixel(x, y, color.to_rgba_u32());
    }

    /// Alias for [`set_pixel_with_color`](PixelBuffer::set_pixel_with_color).
    #[inline]
    pub fn set_pixel_color(&mut self, x: u32, y: u32, color: Color) {
        self.set_pixel_with_color(x, y, color);
    }

    /// Gets the raw 32-bit RGBA8 color of a single pixel at `(x, y)`. Returns `None` if out of bounds.
    #[inline]
    pub fn get_pixel(&self, x: u32, y: u32) -> Option<u32> {
        if x < self.width && y < self.height {
            let index = (y * self.width + x) as usize;
            self.pixels.get(index).copied()
        } else {
            None
        }
    }

    /// Gets the decoded [`Color`] of a single pixel at `(x, y)`. Returns `None` if out of bounds.
    #[inline]
    pub fn get_pixel_by_color(&self, x: u32, y: u32) -> Option<Color> {
        self.get_pixel(x, y).map(Color::from_rgba_u32)
    }

    /// Alias for [`get_pixel_by_color`](PixelBuffer::get_pixel_by_color).
    #[inline]
    pub fn get_pixel_color(&self, x: u32, y: u32) -> Option<Color> {
        self.get_pixel_by_color(x, y)
    }

    /// Fills the entire buffer with a single solid raw RGBA8 value.
    #[inline]
    pub fn fill(&mut self, color: u32) {
        self.pixels.fill(color);
    }

    /// Fills the entire buffer with a single solid [`Color`].
    #[inline]
    pub fn fill_with_color(&mut self, color: Color) {
        self.fill(color.to_rgba_u32());
    }

    /// Alias for [`fill_with_color`](PixelBuffer::fill_with_color).
    #[inline]
    pub fn fill_color(&mut self, color: Color) {
        self.fill_with_color(color);
    }

    /// Clears the entire buffer to transparent black (`0x00000000` / `Color::transparent`).
    #[inline]
    pub fn clear(&mut self) {
        self.pixels.fill(0);
    }

    /// Fills a rectangular region with a raw RGBA8 `color`. Coordinates are clamped to the buffer bounds.
    pub fn fill_rect(&mut self, x: i32, y: i32, w: u32, h: u32, color: u32) {
        let x_start = x.max(0) as u32;
        let y_start = y.max(0) as u32;
        let x_end = ((x + w as i32).max(0) as u32).min(self.width);
        let y_end = ((y + h as i32).max(0) as u32).min(self.height);

        for row in y_start..y_end {
            let row_offset = (row * self.width) as usize;
            for col in x_start..x_end {
                let idx = row_offset + col as usize;
                if idx < self.pixels.len() {
                    self.pixels[idx] = color;
                }
            }
        }
    }

    /// Fills a rectangular region with MTK's [`Color`]. Coordinates are clamped to buffer bounds.
    #[inline]
    pub fn fill_rect_with_color(&mut self, x: i32, y: i32, w: u32, h: u32, color: Color) {
        self.fill_rect(x, y, w, h, color.to_rgba_u32());
    }

    /// Alias for [`fill_rect_with_color`](PixelBuffer::fill_rect_with_color).
    #[inline]
    pub fn fill_rect_color(&mut self, x: i32, y: i32, w: u32, h: u32, color: Color) {
        self.fill_rect_with_color(x, y, w, h, color);
    }

    /// Blits a rectangular slice of 32-bit RGBA8 pixel data onto the canvas at `(dst_x, dst_y)`.
    pub fn blit(&mut self, src: &[u32], src_w: u32, src_h: u32, dst_x: i32, dst_y: i32) {
        for row in 0..src_h {
            let target_y = dst_y + row as i32;
            if target_y < 0 || target_y >= self.height as i32 {
                continue;
            }
            for col in 0..src_w {
                let target_x = dst_x + col as i32;
                if target_x < 0 || target_x >= self.width as i32 {
                    continue;
                }
                let src_idx = (row * src_w + col) as usize;
                let dst_idx = (target_y as u32 * self.width + target_x as u32) as usize;
                if src_idx < src.len() && dst_idx < self.pixels.len() {
                    self.pixels[dst_idx] = src[src_idx];
                }
            }
        }
    }

    /// Blits a rectangular slice of [`Color`] onto the canvas at `(dst_x, dst_y)`.
    #[inline]
    pub fn blit_colors(&mut self, src: &[Color], src_w: u32, src_h: u32, dst_x: i32, dst_y: i32) {
        let src_u32 = bytemuck::cast_slice::<Color, u32>(src);
        self.blit(src_u32, src_w, src_h, dst_x, dst_y);
    }

    /// Blits raw RGBA byte slices onto the canvas at `(dst_x, dst_y)`.
    #[inline]
    pub fn blit_bytes(&mut self, src_bytes: &[u8], src_w: u32, src_h: u32, dst_x: i32, dst_y: i32) {
        let src_u32 = bytemuck::cast_slice::<u8, u32>(src_bytes);
        self.blit(src_u32, src_w, src_h, dst_x, dst_y);
    }

    /// Reinterprets the underlying pixel buffer as a slice of [`Color`].
    #[inline]
    pub fn as_colors(&self) -> &[Color] {
        bytemuck::cast_slice(self.pixels)
    }

    /// Reinterprets the underlying pixel buffer as a mutable slice of [`Color`].
    #[inline]
    pub fn as_colors_mut(&mut self) -> &mut [Color] {
        bytemuck::cast_slice_mut(self.pixels)
    }

    /// Reinterprets the underlying pixel buffer as raw RGBA bytes.
    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        bytemuck::cast_slice(self.pixels)
    }

    /// Reinterprets the underlying pixel buffer as mutable raw RGBA bytes.
    #[inline]
    pub fn as_bytes_mut(&mut self) -> &mut [u8] {
        bytemuck::cast_slice_mut(self.pixels)
    }
}

/// Trait implemented by software rasterizers and pixel painters.
pub trait PixelPainter: 'static {
    /// Renders pixel data into the provided CPU `buffer`.
    fn paint(&mut self, buffer: &mut PixelBuffer);
}

impl<F> PixelPainter for F
where
    F: FnMut(&mut PixelBuffer) + 'static,
{
    fn paint(&mut self, buffer: &mut PixelBuffer) {
        (self)(buffer);
    }
}

/// Execution context passed to [`WgpuPainter::paint`].
pub struct PaintContext<'a> {
    /// The WGPU Device handle.
    pub device: &'a wgpu::Device,
    /// The WGPU Queue handle for submitting writes and commands.
    pub queue: &'a wgpu::Queue,
    /// The active Command Encoder for recording render and compute passes.
    pub encoder: &'a mut wgpu::CommandEncoder,
    /// The offscreen TextureView target corresponding to this canvas element.
    pub target: &'a wgpu::TextureView,
    /// Physical canvas width in pixels.
    pub width: u32,
    /// Physical canvas height in pixels.
    pub height: u32,
    /// The texture format of `target` (typically `Rgba8UnormSrgb`).
    pub format: wgpu::TextureFormat,
    /// Elapsed delta time in seconds since the previous frame tick.
    pub dt: f32,
    /// Current display scale factor.
    pub scale_factor: f32,
    pub(crate) frame_requested: &'a Cell<bool>,
}

impl<'a> PaintContext<'a> {
    /// Schedules a redraw for the next frame. Call this if your canvas contains continuous animations or physics.
    #[inline]
    pub fn request_frame(&self) {
        self.frame_requested.set(true);
    }

    /// Returns the logical width of the canvas in points.
    #[inline]
    pub fn logical_width(&self) -> f32 {
        self.width as f32 / self.scale_factor
    }

    /// Returns the logical height of the canvas in points.
    #[inline]
    pub fn logical_height(&self) -> f32 {
        self.height as f32 / self.scale_factor
    }
}

/// Trait implemented by GPU painters with custom WGPU render pipelines, shaders, and passes.
pub trait WgpuPainter: 'static {
    /// Called once when the painter is initialized. Create pipelines, bind groups, and static buffers here.
    fn init(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat) {
        let _ = (device, queue, format);
    }

    /// Called whenever the canvas element layout size changes.
    fn resize(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, width: u32, height: u32) {
        let _ = (device, queue, width, height);
    }

    /// Called before `paint` to upload uniforms or staging buffers.
    fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
        let _ = (device, queue);
    }

    /// Records GPU draw commands targeting `ctx.target`.
    fn paint(&mut self, ctx: &mut PaintContext);
}

impl<F> WgpuPainter for F
where
    F: FnMut(&mut PaintContext) + 'static,
{
    fn paint(&mut self, ctx: &mut PaintContext) {
        (self)(ctx);
    }
}

/// Internal representation of canvas painter types stored in [`Context`].
pub enum CanvasPainterKind {
    /// Software CPU pixel painter.
    Pixel(Box<dyn PixelPainter>),
    /// Hardware WGPU GPU painter.
    Wgpu(Box<dyn WgpuPainter>),
}

/// Internal state stored per canvas node.
pub struct CanvasData {
    /// The attached painter instance.
    pub painter: CanvasPainterKind,
    /// Whether `init` has been called on the painter.
    pub initialized: bool,
    /// CPU buffer memory cached between frames for `PixelPainter`.
    pub cpu_buffer: Vec<u32>,
    /// Last known physical width in pixels.
    pub width: u32,
    /// Last known physical height in pixels.
    pub height: u32,
}

/// Interaction event information passed to canvas event handlers.
#[derive(Clone, Copy, Debug)]
pub struct CanvasEventDetails {
    /// Local horizontal logical position relative to top-left of canvas.
    pub local_x: f32,
    /// Local vertical logical position relative to top-left of canvas.
    pub local_y: f32,
    /// Physical horizontal pixel position matching PixelBuffer pixels (`local_x * scale_factor`).
    pub pixel_x: f32,
    /// Physical vertical pixel position matching PixelBuffer pixels (`local_y * scale_factor`).
    pub pixel_y: f32,
    /// Normalized horizontal position `0.0..=1.0`.
    pub uv_x: f32,
    /// Normalized vertical position `0.0..=1.0`.
    pub uv_y: f32,
    /// Current display scale factor for the canvas.
    pub scale_factor: f32,
}

/// A declarative UI element that renders custom 2D/3D graphics via an attached painter.
pub struct Canvas<State, Msg> {
    painter_fn: Box<dyn Fn() -> CanvasPainterKind>,
    on_event_fn: Option<Box<dyn Fn(&State, Event, CanvasEventDetails) -> Option<Msg>>>,
    source_loc: Option<crate::debugger::SourceLocation>,
    _marker: PhantomData<(State, Msg)>,
}

/// Creates a new software pixel canvas driven by a [`PixelPainter`] or closure `FnMut(&mut PixelBuffer)`.
///
/// # Examples
/// ```rust,ignore
/// pixel_canvas(|buf| {
///     buf.fill(0xFF181825);
///     buf.set_pixel(10, 10, 0xFFFFFFFF);
/// })
/// ```
#[track_caller]
pub fn pixel_canvas<P, State, Msg>(painter: P) -> Canvas<State, Msg>
where
    P: PixelPainter + Clone,
{
    Canvas {
        painter_fn: Box::new(move || CanvasPainterKind::Pixel(Box::new(painter.clone()))),
        on_event_fn: None,
        source_loc: Some(crate::debugger::SourceLocation::here("PixelCanvas")),
        _marker: PhantomData,
    }
}

/// Creates a new GPU canvas driven by a [`WgpuPainter`] or closure `FnMut(&mut PaintContext)`.
///
/// # Examples
/// ```rust,ignore
/// wgpu_canvas(|ctx| {
///     let _pass = ctx.encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
///         label: Some("Canvas Pass"),
///         color_attachments: &[Some(wgpu::RenderPassColorAttachment {
///             view: ctx.target,
///             resolve_target: None,
///             ops: wgpu::Operations {
///                 load: wgpu::LoadOp::Clear(wgpu::Color::BLUE),
///                 store: wgpu::StoreOp::Store,
///             },
///         })],
///         depth_stencil_attachment: None,
///         timestamp_writes: None,
///         occlusion_query_set: None,
///     });
/// })
/// ```
#[track_caller]
pub fn wgpu_canvas<P, State, Msg>(painter: P) -> Canvas<State, Msg>
where
    P: WgpuPainter + Clone,
{
    Canvas {
        painter_fn: Box::new(move || CanvasPainterKind::Wgpu(Box::new(painter.clone()))),
        on_event_fn: None,
        source_loc: Some(crate::debugger::SourceLocation::here("WgpuCanvas")),
        _marker: PhantomData,
    }
}

impl<State, Msg> Canvas<State, Msg> {
    /// Attaches an interactive event handler mapping canvas interactions into messages.
    pub fn on_event<F>(mut self, handler: F) -> Self
    where
        F: Fn(&State, Event, CanvasEventDetails) -> Option<Msg> + 'static,
    {
        self.on_event_fn = Some(Box::new(handler));
        self
    }
}

impl<State: 'static, Msg: 'static> View<State> for Canvas<State, Msg> {
    type Element = Node;
    type Message = Msg;

    fn build(&self, ctx: &mut Context) -> Self::Element {
        let node = ctx.create_node();
        if let Some(loc) = self.source_loc {
            ctx.set_node_source(node, loc);
        }
        let painter = (self.painter_fn)();
        ctx.canvases.borrow_mut().insert(
            node,
            CanvasData {
                painter,
                initialized: false,
                cpu_buffer: Vec::new(),
                width: 0,
                height: 0,
            },
        );
        node
    }

    fn rebuild(&self, _prev: &Self, ctx: &mut Context, element: &mut Self::Element) {
        let mut canvases = ctx.canvases.borrow_mut();
        if let Some(canvas_data) = canvases.get_mut(element) {
            match (&mut canvas_data.painter, (self.painter_fn)()) {
                (CanvasPainterKind::Pixel(_), new_p @ CanvasPainterKind::Pixel(_)) => {
                    canvas_data.painter = new_p;
                }
                (CanvasPainterKind::Wgpu(_), CanvasPainterKind::Wgpu(_)) => {
                    // Retain the initialized GPU pipeline, bind groups, and buffers for the active canvas
                }
                (_, new_p) => {
                    canvas_data.painter = new_p;
                    canvas_data.initialized = false;
                }
            }
        }
    }

    fn teardown(&self, ctx: &mut Context, element: &mut Self::Element) {
        ctx.canvases.borrow_mut().remove(element);
        element.remove(ctx);
        ctx.destroy_node(*element);
    }

    fn get_node(&self, element: &Self::Element) -> Node {
        *element
    }

    fn handle_event(
        &self,
        element: &mut Self::Element,
        state: &State,
        event: Event,
        ctx: &mut Context,
    ) -> (EventResult, Option<Self::Message>) {
        if let Some(on_event) = &self.on_event_fn {
            let (cursor_x, cursor_y, is_hit) = match &event {
                Event::CursorMoved {
                    x, y, hit_nodes, ..
                } => (*x, *y, hit_nodes.contains(element)),
                Event::MouseInput {
                    x, y, hit_nodes, ..
                } => (*x, *y, hit_nodes.contains(element)),
                Event::StylusInput {
                    x, y, hit_nodes, ..
                } => (*x, *y, hit_nodes.contains(element)),
                Event::MouseWheel { hit_nodes, .. } => (0.0, 0.0, hit_nodes.contains(element)),
                _ => (0.0, 0.0, false),
            };

            if is_hit {
                if let Some(computed) = element.get_computed(ctx) {
                    let local_x = (cursor_x - computed.x).max(0.0);
                    let local_y = (cursor_y - computed.y).max(0.0);
                    let scale_factor = ctx.scale_factor.max(0.1);
                    let pixel_x = (local_x * scale_factor).max(0.0);
                    let pixel_y = (local_y * scale_factor).max(0.0);
                    let uv_x = if computed.w > 0.0 {
                        (local_x / computed.w).clamp(0.0, 1.0)
                    } else {
                        0.0
                    };
                    let uv_y = if computed.h > 0.0 {
                        (local_y / computed.h).clamp(0.0, 1.0)
                    } else {
                        0.0
                    };

                    let details = CanvasEventDetails {
                        local_x,
                        local_y,
                        pixel_x,
                        pixel_y,
                        uv_x,
                        uv_y,
                        scale_factor,
                    };

                    if let Some(msg) = (on_event)(state, event, details) {
                        return (EventResult::Handled, Some(msg));
                    }
                }
            }
        }
        (EventResult::Ignored, None)
    }
}

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

    #[test]
    fn test_pixel_buffer_operations() {
        let mut data = vec![0u32; 100]; // 10x10
        let frame_requested = Cell::new(false);
        let mut buf = PixelBuffer::new(10, 10, 1.0, &mut data, &frame_requested);

        assert_eq!(buf.logical_width(), 10.0);
        assert_eq!(buf.logical_height(), 10.0);
        assert_eq!(buf.logical_to_physical(2.0, 3.0), (2, 3));

        buf.set_pixel(2, 3, 0xFF112233);
        assert_eq!(buf.get_pixel(2, 3), Some(0xFF112233));
        assert_eq!(buf.get_pixel(0, 0), Some(0));
        assert_eq!(buf.get_pixel(10, 10), None);

        buf.fill(0xFFAAAAAA);
        assert_eq!(buf.get_pixel(0, 0), Some(0xFFAAAAAA));
        assert_eq!(buf.get_pixel(9, 9), Some(0xFFAAAAAA));

        buf.clear();
        assert_eq!(buf.get_pixel(5, 5), Some(0));

        buf.fill_rect(2, 2, 4, 4, 0xFFEEFF00);
        assert_eq!(buf.get_pixel(2, 2), Some(0xFFEEFF00));
        assert_eq!(buf.get_pixel(5, 5), Some(0xFFEEFF00));
        assert_eq!(buf.get_pixel(6, 6), Some(0));

        let src = [0xFF010203, 0xFF040506, 0xFF070809, 0xFF0A0B0C];
        buf.blit(&src, 2, 2, 0, 0);
        assert_eq!(buf.get_pixel(0, 0), Some(0xFF010203));
        assert_eq!(buf.get_pixel(1, 0), Some(0xFF040506));
        assert_eq!(buf.get_pixel(0, 1), Some(0xFF070809));
        assert_eq!(buf.get_pixel(1, 1), Some(0xFF0A0B0C));
    }

    #[test]
    fn test_pixel_buffer_color_operations() {
        let mut data = vec![0u32; 100]; // 10x10
        let frame_requested = Cell::new(false);
        let mut buf = PixelBuffer::new(10, 10, 1.0, &mut data, &frame_requested);

        let red = Color::new(255, 0, 0, 255);
        let blue = Color::new(0, 0, 255, 255);
        let green = Color::new(0, 255, 0, 255);

        buf.fill_with_color(red);
        assert_eq!(buf.get_pixel_by_color(0, 0), Some(red));
        assert_eq!(buf.get_pixel_by_color(9, 9), Some(red));

        buf.set_pixel_with_color(4, 5, blue);
        assert_eq!(buf.get_pixel_by_color(4, 5), Some(blue));
        assert_eq!(buf.get_pixel_by_color(4, 6), Some(red));

        buf.fill_rect_with_color(1, 1, 3, 3, green);
        assert_eq!(buf.get_pixel_by_color(1, 1), Some(green));
        assert_eq!(buf.get_pixel_by_color(3, 3), Some(green));
        assert_eq!(buf.get_pixel_by_color(4, 4), Some(red));

        let color_src = [blue, green, red, blue];
        buf.blit_colors(&color_src, 2, 2, 0, 0);
        assert_eq!(buf.get_pixel_by_color(0, 0), Some(blue));
        assert_eq!(buf.get_pixel_by_color(1, 0), Some(green));
        assert_eq!(buf.get_pixel_by_color(0, 1), Some(red));
        assert_eq!(buf.get_pixel_by_color(1, 1), Some(blue));

        // Test as_colors slice view
        let colors = buf.as_colors();
        assert_eq!(colors.len(), 100);
        assert_eq!(colors[0], blue);
    }

    #[test]
    fn test_canvas_view_lifecycle() {
        let mut ctx = Context::new();
        let canvas_widget = pixel_canvas::<_, (), ()>(|buf: &mut PixelBuffer| {
            buf.fill_with_color(Color::green);
        });

        let element = canvas_widget.build(&mut ctx);
        assert!(ctx.canvases.borrow().contains_key(&element));

        canvas_widget.teardown(&mut ctx, &mut { element });
        assert!(!ctx.canvases.borrow().contains_key(&element));
    }
}