native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
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
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
//! Canvas damage, repaint scheduling, and surface update efficiency helpers.
//!
//! # Architecture & Background
//!
//! Drawing surfaces (`WidgetKind::Canvas`) support retained display-list scenes
//! and raw RGBA raster surfaces (`CanvasSurface`). In high-frequency interactive
//! scenarios — such as pointer drag strokes in paint applications or continuous
//! CAD editing — pointer move events can arrive at 120 Hz to 1,000 Hz.
//!
//! If an application publishes a complete raster surface on every pointer move event,
//! memory bandwidth and allocation churn rapidly saturate the host system:
//! - For a 12 megapixel document (4000×3000 RGBA8 = 48 MB per buffer), copying
//!   the surface at 1,000 Hz consumes 48.0 GB/s memory bandwidth and takes ~1.8 ms
//!   per single-threaded `memcpy`, exceeding the 1.0 ms event interval and locking
//!   the event loop.
//! - Even at 120 Hz, copying 48 MB requires 5.76 GB/s bandwidth and consumes ~22%
//!   of the entire 8.33 ms frame budget solely in buffer cloning.
//!
//! This module provides:
//! 1. [`CanvasDamage`]: Describes full or localized rectangular damage regions.
//! 2. [`CanvasDamageAccumulator`]: Coalesces high-frequency damage updates to at most
//!    one surface refresh per event-loop tick.
//! 3. [`CanvasStrokeCoalescingPolicy`]: Defines threshold parameters for damage
//!    promotion and frame pacing.
//! 4. [`CanvasBufferCost`]: Quantifies buffer memory sizes, bandwidth, and latency
//!    budgets for document dimensions and input rates.

use crate::widgets::CanvasRect;

impl CanvasRect {
    /// Computes the minimal enclosing bounding box of `self` and `other`.
    ///
    /// If either rectangle has non-positive dimensions, the other rectangle
    /// is returned. If both have non-positive dimensions, a zero-sized rectangle
    /// at the minimum origin is returned.
    pub fn bounding_union(&self, other: &CanvasRect) -> CanvasRect {
        if self.is_empty() {
            return *other;
        }
        if other.is_empty() {
            return *self;
        }

        let min_x = self.x.min(other.x);
        let min_y = self.y.min(other.y);
        let max_x = (self.x + self.width).max(other.x + other.width);
        let max_y = (self.y + self.height).max(other.y + other.height);

        CanvasRect {
            x: min_x,
            y: min_y,
            width: max_x - min_x,
            height: max_y - min_y,
        }
    }

    /// Returns `true` if the rectangle has non-positive width or height.
    pub fn is_empty(&self) -> bool {
        self.width <= 0 || self.height <= 0
    }

    /// Computes the pixel area of the rectangle, returning `0` if empty.
    pub fn area(&self) -> u64 {
        if self.is_empty() {
            0
        } else {
            (self.width as u64) * (self.height as u64)
        }
    }

    /// Returns `true` if this rectangle fully encloses `other`.
    pub fn contains_rect(&self, other: &CanvasRect) -> bool {
        if other.is_empty() {
            return true;
        }
        if self.is_empty() {
            return false;
        }
        self.x <= other.x
            && self.y <= other.y
            && (self.x + self.width) >= (other.x + other.width)
            && (self.y + self.height) >= (other.y + other.height)
    }

    /// Returns `true` if this rectangle intersects `other`.
    pub fn intersects(&self, other: &CanvasRect) -> bool {
        if self.is_empty() || other.is_empty() {
            return false;
        }
        self.x < (other.x + other.width)
            && (self.x + self.width) > other.x
            && self.y < (other.y + other.height)
            && (self.y + self.height) > other.y
    }
}

/// Describes the damaged region of a Canvas for repaint scheduling and partial updates.
///
/// Implements the invalidation contract.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CanvasDamage {
    /// The entire canvas area requires redraw.
    Full,
    /// A localized rectangular region in logical coordinates requires redraw.
    Rect(CanvasRect),
}

impl CanvasDamage {
    /// Returns `true` if this damage represents a full canvas repaint.
    pub fn is_full(&self) -> bool {
        matches!(self, CanvasDamage::Full)
    }

    /// Returns `true` if this damage represents an empty rectangular region.
    pub fn is_empty(&self) -> bool {
        match self {
            CanvasDamage::Full => false,
            CanvasDamage::Rect(r) => r.is_empty(),
        }
    }

    /// Returns the localized damage rectangle if this is `CanvasDamage::Rect`.
    pub fn rect(&self) -> Option<CanvasRect> {
        match self {
            CanvasDamage::Full => None,
            CanvasDamage::Rect(r) => Some(*r),
        }
    }

    /// Computes the conservative union of two damage specifications.
    ///
    /// - `Full` union anything yields `Full`.
    /// - `Rect(r1)` union `Rect(r2)` yields the minimal enclosing bounding box.
    pub fn union(&self, other: &CanvasDamage) -> CanvasDamage {
        match (self, other) {
            (CanvasDamage::Full, _) | (_, CanvasDamage::Full) => CanvasDamage::Full,
            (CanvasDamage::Rect(r1), CanvasDamage::Rect(r2)) => {
                CanvasDamage::Rect(r1.bounding_union(r2))
            }
        }
    }

    /// Computes the union of this damage with a rectangle.
    pub fn union_rect(&self, rect: CanvasRect) -> CanvasDamage {
        self.union(&CanvasDamage::Rect(rect))
    }

    /// Returns the pixel area of the damage rectangle, or `None` if this is `CanvasDamage::Full`.
    pub fn area(&self) -> Option<u64> {
        match self {
            CanvasDamage::Full => None,
            CanvasDamage::Rect(r) => Some(r.area()),
        }
    }

    /// Evaluates whether this damage region should be promoted to `CanvasDamage::Full`.
    ///
    /// Damage-scheduling rule: if the bounding box of accumulated rectangular
    /// damage exceeds the promotion threshold ratio (default 60%) of the total canvas area,
    /// partial rasterization overhead exceeds full redraw efficiency.
    pub fn should_promote_to_full(
        &self,
        canvas_width: u32,
        canvas_height: u32,
        threshold_ratio: f64,
    ) -> bool {
        match self {
            CanvasDamage::Full => true,
            CanvasDamage::Rect(r) => {
                if canvas_width == 0 || canvas_height == 0 {
                    return true;
                }
                let total_area = (canvas_width as f64) * (canvas_height as f64);
                let damage_area = r.area() as f64;
                (damage_area / total_area) >= threshold_ratio
            }
        }
    }
}

/// Accumulates damage regions across multiple high-frequency input events
/// to emit a single coalesced update per event-loop tick.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CanvasDamageAccumulator {
    pending_damage: Option<CanvasDamage>,
    events_coalesced: u64,
    refreshes_emitted: u64,
}

impl CanvasDamageAccumulator {
    /// Creates a new empty accumulator.
    pub fn new() -> Self {
        Self::default()
    }

    /// Records an incoming damage region, merging it with any pending damage.
    pub fn record_damage(&mut self, damage: CanvasDamage) {
        self.events_coalesced = self.events_coalesced.saturating_add(1);
        self.pending_damage = match self.pending_damage {
            None => Some(damage),
            Some(prev) => Some(prev.union(&damage)),
        };
    }

    /// Records full canvas invalidation.
    pub fn record_full_damage(&mut self) {
        self.record_damage(CanvasDamage::Full);
    }

    /// Records localized rectangular damage.
    pub fn record_rect_damage(&mut self, rect: CanvasRect) {
        self.record_damage(CanvasDamage::Rect(rect));
    }

    /// Returns `true` if there is unconsumed damage pending for repaint.
    pub fn is_dirty(&self) -> bool {
        self.pending_damage.is_some()
    }

    /// Peeks at the currently pending damage without clearing it.
    pub fn pending_damage(&self) -> Option<CanvasDamage> {
        self.pending_damage
    }

    /// Checks the pending damage against the canvas dimensions and promotes to
    /// `CanvasDamage::Full` if it exceeds `threshold_ratio` of the viewport area.
    pub fn promote_if_exceeds(
        &mut self,
        canvas_width: u32,
        canvas_height: u32,
        threshold_ratio: f64,
    ) {
        if let Some(damage) = self.pending_damage {
            if damage.should_promote_to_full(canvas_width, canvas_height, threshold_ratio) {
                self.pending_damage = Some(CanvasDamage::Full);
            }
        }
    }

    /// Consumes and returns the pending damage, resetting the dirty flag
    /// and incrementing the refresh counter.
    pub fn take_damage(&mut self) -> Option<CanvasDamage> {
        let damage = self.pending_damage.take();
        if damage.is_some() {
            self.refreshes_emitted = self.refreshes_emitted.saturating_add(1);
        }
        damage
    }

    /// Returns the total number of individual input/damage events absorbed.
    pub fn events_coalesced(&self) -> u64 {
        self.events_coalesced
    }

    /// Returns the total number of coalesced refreshes emitted.
    pub fn refreshes_emitted(&self) -> u64 {
        self.refreshes_emitted
    }

    /// Resets all counters and clears pending damage.
    pub fn reset(&mut self) {
        self.pending_damage = None;
        self.events_coalesced = 0;
        self.refreshes_emitted = 0;
    }
}

/// Policy configuration for canvas refresh coalescing and damage promotion.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CanvasStrokeCoalescingPolicy {
    /// Ratio of canvas area (0.0..=1.0) above which rectangular damage promotes to `Full`.
    /// Defaults to 0.60 (60%).
    pub promotion_threshold: f64,
    /// Target maximum refresh rate in Hz for paced stroke/animation updates.
    /// Defaults to 60 Hz.
    pub target_refresh_rate_hz: u32,
}

impl Default for CanvasStrokeCoalescingPolicy {
    fn default() -> Self {
        Self {
            promotion_threshold: 0.60,
            target_refresh_rate_hz: 60,
        }
    }
}

impl CanvasStrokeCoalescingPolicy {
    /// Creates a new policy with explicit parameters.
    pub fn new(promotion_threshold: f64, target_refresh_rate_hz: u32) -> Self {
        Self {
            promotion_threshold: promotion_threshold.clamp(0.01, 1.0),
            target_refresh_rate_hz: target_refresh_rate_hz.max(1),
        }
    }

    /// Returns the frame budget duration corresponding to the target refresh rate.
    pub fn frame_interval(&self) -> std::time::Duration {
        std::time::Duration::from_nanos((1_000_000_000u64) / (self.target_refresh_rate_hz as u64))
    }
}

/// Analytical cost and bandwidth model for canvas raster buffer transfers.
pub struct CanvasBufferCost;

impl CanvasBufferCost {
    /// Computes the exact byte size of an RGBA8 buffer for the given dimensions (`width * height * 4`).
    pub const fn buffer_bytes(width: u32, height: u32) -> usize {
        (width as usize) * (height as usize) * 4
    }

    /// Computes memory bandwidth in bytes per second for copying full frames at `rate_hz`.
    pub fn bandwidth_bytes_per_sec(width: u32, height: u32, rate_hz: u32) -> u64 {
        (Self::buffer_bytes(width, height) as u64) * (rate_hz as u64)
    }

    /// Computes memory bandwidth in decimal megabytes (MB = 10^6 bytes) per second.
    pub fn bandwidth_mb_per_sec(width: u32, height: u32, rate_hz: u32) -> f64 {
        (Self::bandwidth_bytes_per_sec(width, height, rate_hz) as f64) / 1_000_000.0
    }

    /// Computes memory bandwidth in binary mebibytes (MiB = 2^20 bytes) per second.
    pub fn bandwidth_mib_per_sec(width: u32, height: u32, rate_hz: u32) -> f64 {
        (Self::bandwidth_bytes_per_sec(width, height, rate_hz) as f64) / (1024.0 * 1024.0)
    }

    /// Computes estimated copy duration in milliseconds given an effective single-threaded
    /// `memcpy` throughput in GiB/s.
    pub fn estimated_copy_duration_ms(width: u32, height: u32, throughput_gib_per_sec: f64) -> f64 {
        if throughput_gib_per_sec <= 0.0 {
            return f64::INFINITY;
        }
        let bytes = Self::buffer_bytes(width, height) as f64;
        let bytes_per_sec = throughput_gib_per_sec * 1024.0 * 1024.0 * 1024.0;
        (bytes / bytes_per_sec) * 1000.0
    }

    /// Computes byte size of a rectangular damage patch in an RGBA8 buffer.
    pub fn damage_buffer_bytes(rect: &CanvasRect) -> usize {
        (rect.area() as usize) * 4
    }

    /// Computes the ratio of damage rectangle area to total canvas area (fraction 0.0..=1.0).
    pub fn damage_area_ratio(canvas_width: u32, canvas_height: u32, rect: &CanvasRect) -> f64 {
        if canvas_width == 0 || canvas_height == 0 {
            return 1.0;
        }
        let total = (canvas_width as f64) * (canvas_height as f64);
        (rect.area() as f64 / total).clamp(0.0, 1.0)
    }

    /// Computes the factor by which partial damage reduces buffer copy volume compared
    /// to a full surface clone.
    pub fn copy_reduction_factor(canvas_width: u32, canvas_height: u32, rect: &CanvasRect) -> f64 {
        let ratio = Self::damage_area_ratio(canvas_width, canvas_height, rect);
        if ratio <= 0.0 {
            f64::INFINITY
        } else {
            1.0 / ratio
        }
    }
}

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

    #[test]
    fn test_canvas_rect_bounding_union() {
        let r1 = CanvasRect {
            x: 10,
            y: 10,
            width: 20,
            height: 20,
        };
        let r2 = CanvasRect {
            x: 20,
            y: 20,
            width: 30,
            height: 30,
        };
        let u = r1.bounding_union(&r2);
        assert_eq!(
            u,
            CanvasRect {
                x: 10,
                y: 10,
                width: 40,
                height: 40,
            }
        );
        assert_eq!(u.area(), 1600);

        // Empty rect union
        let empty = CanvasRect {
            x: 0,
            y: 0,
            width: 0,
            height: 0,
        };
        assert_eq!(r1.bounding_union(&empty), r1);
        assert_eq!(empty.bounding_union(&r2), r2);
    }

    #[test]
    fn test_canvas_rect_contains_and_intersects() {
        let outer = CanvasRect {
            x: 0,
            y: 0,
            width: 100,
            height: 100,
        };
        let inner = CanvasRect {
            x: 10,
            y: 10,
            width: 20,
            height: 20,
        };
        let disjoint = CanvasRect {
            x: 200,
            y: 200,
            width: 50,
            height: 50,
        };
        let overlapping = CanvasRect {
            x: 90,
            y: 90,
            width: 50,
            height: 50,
        };

        assert!(outer.contains_rect(&inner));
        assert!(!inner.contains_rect(&outer));
        assert!(!outer.contains_rect(&disjoint));

        assert!(outer.intersects(&overlapping));
        assert!(overlapping.intersects(&outer));
        assert!(!outer.intersects(&disjoint));
    }

    #[test]
    fn test_canvas_damage_union() {
        let d_full = CanvasDamage::Full;
        let d1 = CanvasDamage::Rect(CanvasRect {
            x: 10,
            y: 10,
            width: 20,
            height: 20,
        });
        let d2 = CanvasDamage::Rect(CanvasRect {
            x: 20,
            y: 20,
            width: 30,
            height: 30,
        });

        // Full subsumes everything
        assert_eq!(d_full.union(&d1), CanvasDamage::Full);
        assert_eq!(d1.union(&d_full), CanvasDamage::Full);
        assert_eq!(d_full.union(&d_full), CanvasDamage::Full);

        // Rect union merges bounding boxes
        let merged = d1.union(&d2);
        assert_eq!(
            merged,
            CanvasDamage::Rect(CanvasRect {
                x: 10,
                y: 10,
                width: 40,
                height: 40,
            })
        );
        assert_eq!(merged.area(), Some(1600));
        assert!(!merged.is_full());
        assert!(!merged.is_empty());
    }

    #[test]
    fn test_canvas_damage_promotion_threshold() {
        // Canvas is 1000 x 1000 = 1,000,000 pixels
        let small_rect = CanvasDamage::Rect(CanvasRect {
            x: 100,
            y: 100,
            width: 200,
            height: 200,
        }); // 40,000 px = 4%
        assert!(!small_rect.should_promote_to_full(1000, 1000, 0.60));

        let large_rect = CanvasDamage::Rect(CanvasRect {
            x: 0,
            y: 0,
            width: 800,
            height: 800,
        }); // 640,000 px = 64%
        assert!(large_rect.should_promote_to_full(1000, 1000, 0.60));

        assert!(CanvasDamage::Full.should_promote_to_full(1000, 1000, 0.60));
    }

    #[test]
    fn test_accumulator_lifecycle_and_coalescing() {
        let mut accum = CanvasDamageAccumulator::new();
        assert!(!accum.is_dirty());
        assert_eq!(accum.events_coalesced(), 0);
        assert_eq!(accum.refreshes_emitted(), 0);

        // Record 5 successive pointer drag moves with localized damage
        for i in 0..5 {
            accum.record_rect_damage(CanvasRect {
                x: i * 10,
                y: i * 10,
                width: 20,
                height: 20,
            });
        }

        assert!(accum.is_dirty());
        assert_eq!(accum.events_coalesced(), 5);
        assert_eq!(accum.refreshes_emitted(), 0);

        // Bounding box spans x=0..60, y=0..60 -> 60x60 = 3600 px
        let coalesced = accum.take_damage().expect("damage should be present");
        assert_eq!(
            coalesced,
            CanvasDamage::Rect(CanvasRect {
                x: 0,
                y: 0,
                width: 60,
                height: 60,
            })
        );
        assert_eq!(accum.refreshes_emitted(), 1);
        assert!(!accum.is_dirty());

        // Subsequent take returns None
        assert_eq!(accum.take_damage(), None);
    }

    #[test]
    fn test_accumulator_full_damage_subsumption_and_promotion() {
        let mut accum = CanvasDamageAccumulator::new();

        accum.record_rect_damage(CanvasRect {
            x: 10,
            y: 10,
            width: 20,
            height: 20,
        });
        accum.record_full_damage();
        accum.record_rect_damage(CanvasRect {
            x: 30,
            y: 30,
            width: 20,
            height: 20,
        });

        assert_eq!(accum.events_coalesced(), 3);
        assert_eq!(accum.take_damage(), Some(CanvasDamage::Full));

        // Test promote_if_exceeds (800x800 = 640,000 px = 64% of 1,000,000)
        accum.record_rect_damage(CanvasRect {
            x: 0,
            y: 0,
            width: 800,
            height: 800,
        });
        accum.promote_if_exceeds(1000, 1000, 0.60);
        assert_eq!(accum.take_damage(), Some(CanvasDamage::Full));
    }

    #[test]
    fn test_canvas_buffer_cost_measurement_12mp() {
        // 12 MP document: 4000 × 3000 RGBA8
        let bytes = CanvasBufferCost::buffer_bytes(4000, 3000);
        assert_eq!(bytes, 48_000_000); // exactly 48 MB

        // 60 Hz full copy
        let bw_60hz = CanvasBufferCost::bandwidth_bytes_per_sec(4000, 3000, 60);
        assert_eq!(bw_60hz, 2_880_000_000); // 2.88 GB/s
        assert!((CanvasBufferCost::bandwidth_mb_per_sec(4000, 3000, 60) - 2880.0).abs() < 1e-4);

        // 120 Hz full copy
        let bw_120hz = CanvasBufferCost::bandwidth_bytes_per_sec(4000, 3000, 120);
        assert_eq!(bw_120hz, 5_760_000_000); // 5.76 GB/s

        // 1,000 Hz gaming mouse move rate
        let bw_1000hz = CanvasBufferCost::bandwidth_bytes_per_sec(4000, 3000, 1000);
        assert_eq!(bw_1000hz, 48_000_000_000); // 48.0 GB/s!

        // Copy duration at 25 GiB/s effective throughput (~26.84 GB/s)
        let latency_ms = CanvasBufferCost::estimated_copy_duration_ms(4000, 3000, 25.0);
        assert!(latency_ms > 1.5 && latency_ms < 2.0); // ~1.79 ms

        // Localized 40x40 px stroke damage patch
        let stroke_damage = CanvasRect {
            x: 500,
            y: 500,
            width: 40,
            height: 40,
        };
        let stroke_bytes = CanvasBufferCost::damage_buffer_bytes(&stroke_damage);
        assert_eq!(stroke_bytes, 6_400); // 6.4 KB

        let factor = CanvasBufferCost::copy_reduction_factor(4000, 3000, &stroke_damage);
        assert_eq!(factor, 7500.0); // 7,500x copy volume reduction!
    }

    #[test]
    fn test_canvas_buffer_cost_resolutions_scaling() {
        // Standard resolutions
        assert_eq!(
            CanvasBufferCost::buffer_bytes(800, 600),
            1_920_000 // 1.92 MB
        );
        assert_eq!(
            CanvasBufferCost::buffer_bytes(1920, 1080),
            8_294_400 // 8.29 MB
        );
        assert_eq!(
            CanvasBufferCost::buffer_bytes(3840, 2160),
            33_177_600 // 33.18 MB (4K UHD)
        );
        assert_eq!(
            CanvasBufferCost::buffer_bytes(6000, 4000),
            96_000_000 // 96.0 MB (24 MP)
        );
    }
}