Skip to main content

native_gui_core/
canvas.rs

1//! Canvas damage, repaint scheduling, and surface update efficiency helpers.
2//!
3//! # Architecture & Background
4//!
5//! Drawing surfaces (`WidgetKind::Canvas`) support retained display-list scenes
6//! and raw RGBA raster surfaces (`CanvasSurface`). In high-frequency interactive
7//! scenarios — such as pointer drag strokes in paint applications or continuous
8//! CAD editing — pointer move events can arrive at 120 Hz to 1,000 Hz.
9//!
10//! If an application publishes a complete raster surface on every pointer move event,
11//! memory bandwidth and allocation churn rapidly saturate the host system:
12//! - For a 12 megapixel document (4000×3000 RGBA8 = 48 MB per buffer), copying
13//!   the surface at 1,000 Hz consumes 48.0 GB/s memory bandwidth and takes ~1.8 ms
14//!   per single-threaded `memcpy`, exceeding the 1.0 ms event interval and locking
15//!   the event loop.
16//! - Even at 120 Hz, copying 48 MB requires 5.76 GB/s bandwidth and consumes ~22%
17//!   of the entire 8.33 ms frame budget solely in buffer cloning.
18//!
19//! This module provides:
20//! 1. [`CanvasDamage`]: Describes full or localized rectangular damage regions.
21//! 2. [`CanvasDamageAccumulator`]: Coalesces high-frequency damage updates to at most
22//!    one surface refresh per event-loop tick.
23//! 3. [`CanvasStrokeCoalescingPolicy`]: Defines threshold parameters for damage
24//!    promotion and frame pacing.
25//! 4. [`CanvasBufferCost`]: Quantifies buffer memory sizes, bandwidth, and latency
26//!    budgets for document dimensions and input rates.
27
28use crate::widgets::CanvasRect;
29
30impl CanvasRect {
31    /// Computes the minimal enclosing bounding box of `self` and `other`.
32    ///
33    /// If either rectangle has non-positive dimensions, the other rectangle
34    /// is returned. If both have non-positive dimensions, a zero-sized rectangle
35    /// at the minimum origin is returned.
36    pub fn bounding_union(&self, other: &CanvasRect) -> CanvasRect {
37        if self.is_empty() {
38            return *other;
39        }
40        if other.is_empty() {
41            return *self;
42        }
43
44        let min_x = self.x.min(other.x);
45        let min_y = self.y.min(other.y);
46        let max_x = (self.x + self.width).max(other.x + other.width);
47        let max_y = (self.y + self.height).max(other.y + other.height);
48
49        CanvasRect {
50            x: min_x,
51            y: min_y,
52            width: max_x - min_x,
53            height: max_y - min_y,
54        }
55    }
56
57    /// Returns `true` if the rectangle has non-positive width or height.
58    pub fn is_empty(&self) -> bool {
59        self.width <= 0 || self.height <= 0
60    }
61
62    /// Computes the pixel area of the rectangle, returning `0` if empty.
63    pub fn area(&self) -> u64 {
64        if self.is_empty() {
65            0
66        } else {
67            (self.width as u64) * (self.height as u64)
68        }
69    }
70
71    /// Returns `true` if this rectangle fully encloses `other`.
72    pub fn contains_rect(&self, other: &CanvasRect) -> bool {
73        if other.is_empty() {
74            return true;
75        }
76        if self.is_empty() {
77            return false;
78        }
79        self.x <= other.x
80            && self.y <= other.y
81            && (self.x + self.width) >= (other.x + other.width)
82            && (self.y + self.height) >= (other.y + other.height)
83    }
84
85    /// Returns `true` if this rectangle intersects `other`.
86    pub fn intersects(&self, other: &CanvasRect) -> bool {
87        if self.is_empty() || other.is_empty() {
88            return false;
89        }
90        self.x < (other.x + other.width)
91            && (self.x + self.width) > other.x
92            && self.y < (other.y + other.height)
93            && (self.y + self.height) > other.y
94    }
95}
96
97/// Describes the damaged region of a Canvas for repaint scheduling and partial updates.
98///
99/// Implements the invalidation contract.
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101pub enum CanvasDamage {
102    /// The entire canvas area requires redraw.
103    Full,
104    /// A localized rectangular region in logical coordinates requires redraw.
105    Rect(CanvasRect),
106}
107
108impl CanvasDamage {
109    /// Returns `true` if this damage represents a full canvas repaint.
110    pub fn is_full(&self) -> bool {
111        matches!(self, CanvasDamage::Full)
112    }
113
114    /// Returns `true` if this damage represents an empty rectangular region.
115    pub fn is_empty(&self) -> bool {
116        match self {
117            CanvasDamage::Full => false,
118            CanvasDamage::Rect(r) => r.is_empty(),
119        }
120    }
121
122    /// Returns the localized damage rectangle if this is `CanvasDamage::Rect`.
123    pub fn rect(&self) -> Option<CanvasRect> {
124        match self {
125            CanvasDamage::Full => None,
126            CanvasDamage::Rect(r) => Some(*r),
127        }
128    }
129
130    /// Computes the conservative union of two damage specifications.
131    ///
132    /// - `Full` union anything yields `Full`.
133    /// - `Rect(r1)` union `Rect(r2)` yields the minimal enclosing bounding box.
134    pub fn union(&self, other: &CanvasDamage) -> CanvasDamage {
135        match (self, other) {
136            (CanvasDamage::Full, _) | (_, CanvasDamage::Full) => CanvasDamage::Full,
137            (CanvasDamage::Rect(r1), CanvasDamage::Rect(r2)) => {
138                CanvasDamage::Rect(r1.bounding_union(r2))
139            }
140        }
141    }
142
143    /// Computes the union of this damage with a rectangle.
144    pub fn union_rect(&self, rect: CanvasRect) -> CanvasDamage {
145        self.union(&CanvasDamage::Rect(rect))
146    }
147
148    /// Returns the pixel area of the damage rectangle, or `None` if this is `CanvasDamage::Full`.
149    pub fn area(&self) -> Option<u64> {
150        match self {
151            CanvasDamage::Full => None,
152            CanvasDamage::Rect(r) => Some(r.area()),
153        }
154    }
155
156    /// Evaluates whether this damage region should be promoted to `CanvasDamage::Full`.
157    ///
158    /// Damage-scheduling rule: if the bounding box of accumulated rectangular
159    /// damage exceeds the promotion threshold ratio (default 60%) of the total canvas area,
160    /// partial rasterization overhead exceeds full redraw efficiency.
161    pub fn should_promote_to_full(
162        &self,
163        canvas_width: u32,
164        canvas_height: u32,
165        threshold_ratio: f64,
166    ) -> bool {
167        match self {
168            CanvasDamage::Full => true,
169            CanvasDamage::Rect(r) => {
170                if canvas_width == 0 || canvas_height == 0 {
171                    return true;
172                }
173                let total_area = (canvas_width as f64) * (canvas_height as f64);
174                let damage_area = r.area() as f64;
175                (damage_area / total_area) >= threshold_ratio
176            }
177        }
178    }
179}
180
181/// Accumulates damage regions across multiple high-frequency input events
182/// to emit a single coalesced update per event-loop tick.
183#[derive(Clone, Debug, Default, PartialEq, Eq)]
184pub struct CanvasDamageAccumulator {
185    pending_damage: Option<CanvasDamage>,
186    events_coalesced: u64,
187    refreshes_emitted: u64,
188}
189
190impl CanvasDamageAccumulator {
191    /// Creates a new empty accumulator.
192    pub fn new() -> Self {
193        Self::default()
194    }
195
196    /// Records an incoming damage region, merging it with any pending damage.
197    pub fn record_damage(&mut self, damage: CanvasDamage) {
198        self.events_coalesced = self.events_coalesced.saturating_add(1);
199        self.pending_damage = match self.pending_damage {
200            None => Some(damage),
201            Some(prev) => Some(prev.union(&damage)),
202        };
203    }
204
205    /// Records full canvas invalidation.
206    pub fn record_full_damage(&mut self) {
207        self.record_damage(CanvasDamage::Full);
208    }
209
210    /// Records localized rectangular damage.
211    pub fn record_rect_damage(&mut self, rect: CanvasRect) {
212        self.record_damage(CanvasDamage::Rect(rect));
213    }
214
215    /// Returns `true` if there is unconsumed damage pending for repaint.
216    pub fn is_dirty(&self) -> bool {
217        self.pending_damage.is_some()
218    }
219
220    /// Peeks at the currently pending damage without clearing it.
221    pub fn pending_damage(&self) -> Option<CanvasDamage> {
222        self.pending_damage
223    }
224
225    /// Checks the pending damage against the canvas dimensions and promotes to
226    /// `CanvasDamage::Full` if it exceeds `threshold_ratio` of the viewport area.
227    pub fn promote_if_exceeds(
228        &mut self,
229        canvas_width: u32,
230        canvas_height: u32,
231        threshold_ratio: f64,
232    ) {
233        if let Some(damage) = self.pending_damage {
234            if damage.should_promote_to_full(canvas_width, canvas_height, threshold_ratio) {
235                self.pending_damage = Some(CanvasDamage::Full);
236            }
237        }
238    }
239
240    /// Consumes and returns the pending damage, resetting the dirty flag
241    /// and incrementing the refresh counter.
242    pub fn take_damage(&mut self) -> Option<CanvasDamage> {
243        let damage = self.pending_damage.take();
244        if damage.is_some() {
245            self.refreshes_emitted = self.refreshes_emitted.saturating_add(1);
246        }
247        damage
248    }
249
250    /// Returns the total number of individual input/damage events absorbed.
251    pub fn events_coalesced(&self) -> u64 {
252        self.events_coalesced
253    }
254
255    /// Returns the total number of coalesced refreshes emitted.
256    pub fn refreshes_emitted(&self) -> u64 {
257        self.refreshes_emitted
258    }
259
260    /// Resets all counters and clears pending damage.
261    pub fn reset(&mut self) {
262        self.pending_damage = None;
263        self.events_coalesced = 0;
264        self.refreshes_emitted = 0;
265    }
266}
267
268/// Policy configuration for canvas refresh coalescing and damage promotion.
269#[derive(Clone, Copy, Debug, PartialEq)]
270pub struct CanvasStrokeCoalescingPolicy {
271    /// Ratio of canvas area (0.0..=1.0) above which rectangular damage promotes to `Full`.
272    /// Defaults to 0.60 (60%).
273    pub promotion_threshold: f64,
274    /// Target maximum refresh rate in Hz for paced stroke/animation updates.
275    /// Defaults to 60 Hz.
276    pub target_refresh_rate_hz: u32,
277}
278
279impl Default for CanvasStrokeCoalescingPolicy {
280    fn default() -> Self {
281        Self {
282            promotion_threshold: 0.60,
283            target_refresh_rate_hz: 60,
284        }
285    }
286}
287
288impl CanvasStrokeCoalescingPolicy {
289    /// Creates a new policy with explicit parameters.
290    pub fn new(promotion_threshold: f64, target_refresh_rate_hz: u32) -> Self {
291        Self {
292            promotion_threshold: promotion_threshold.clamp(0.01, 1.0),
293            target_refresh_rate_hz: target_refresh_rate_hz.max(1),
294        }
295    }
296
297    /// Returns the frame budget duration corresponding to the target refresh rate.
298    pub fn frame_interval(&self) -> std::time::Duration {
299        std::time::Duration::from_nanos((1_000_000_000u64) / (self.target_refresh_rate_hz as u64))
300    }
301}
302
303/// Analytical cost and bandwidth model for canvas raster buffer transfers.
304pub struct CanvasBufferCost;
305
306impl CanvasBufferCost {
307    /// Computes the exact byte size of an RGBA8 buffer for the given dimensions (`width * height * 4`).
308    pub const fn buffer_bytes(width: u32, height: u32) -> usize {
309        (width as usize) * (height as usize) * 4
310    }
311
312    /// Computes memory bandwidth in bytes per second for copying full frames at `rate_hz`.
313    pub fn bandwidth_bytes_per_sec(width: u32, height: u32, rate_hz: u32) -> u64 {
314        (Self::buffer_bytes(width, height) as u64) * (rate_hz as u64)
315    }
316
317    /// Computes memory bandwidth in decimal megabytes (MB = 10^6 bytes) per second.
318    pub fn bandwidth_mb_per_sec(width: u32, height: u32, rate_hz: u32) -> f64 {
319        (Self::bandwidth_bytes_per_sec(width, height, rate_hz) as f64) / 1_000_000.0
320    }
321
322    /// Computes memory bandwidth in binary mebibytes (MiB = 2^20 bytes) per second.
323    pub fn bandwidth_mib_per_sec(width: u32, height: u32, rate_hz: u32) -> f64 {
324        (Self::bandwidth_bytes_per_sec(width, height, rate_hz) as f64) / (1024.0 * 1024.0)
325    }
326
327    /// Computes estimated copy duration in milliseconds given an effective single-threaded
328    /// `memcpy` throughput in GiB/s.
329    pub fn estimated_copy_duration_ms(width: u32, height: u32, throughput_gib_per_sec: f64) -> f64 {
330        if throughput_gib_per_sec <= 0.0 {
331            return f64::INFINITY;
332        }
333        let bytes = Self::buffer_bytes(width, height) as f64;
334        let bytes_per_sec = throughput_gib_per_sec * 1024.0 * 1024.0 * 1024.0;
335        (bytes / bytes_per_sec) * 1000.0
336    }
337
338    /// Computes byte size of a rectangular damage patch in an RGBA8 buffer.
339    pub fn damage_buffer_bytes(rect: &CanvasRect) -> usize {
340        (rect.area() as usize) * 4
341    }
342
343    /// Computes the ratio of damage rectangle area to total canvas area (fraction 0.0..=1.0).
344    pub fn damage_area_ratio(canvas_width: u32, canvas_height: u32, rect: &CanvasRect) -> f64 {
345        if canvas_width == 0 || canvas_height == 0 {
346            return 1.0;
347        }
348        let total = (canvas_width as f64) * (canvas_height as f64);
349        (rect.area() as f64 / total).clamp(0.0, 1.0)
350    }
351
352    /// Computes the factor by which partial damage reduces buffer copy volume compared
353    /// to a full surface clone.
354    pub fn copy_reduction_factor(canvas_width: u32, canvas_height: u32, rect: &CanvasRect) -> f64 {
355        let ratio = Self::damage_area_ratio(canvas_width, canvas_height, rect);
356        if ratio <= 0.0 {
357            f64::INFINITY
358        } else {
359            1.0 / ratio
360        }
361    }
362}
363
364#[cfg(test)]
365mod tests {
366    use super::*;
367
368    #[test]
369    fn test_canvas_rect_bounding_union() {
370        let r1 = CanvasRect {
371            x: 10,
372            y: 10,
373            width: 20,
374            height: 20,
375        };
376        let r2 = CanvasRect {
377            x: 20,
378            y: 20,
379            width: 30,
380            height: 30,
381        };
382        let u = r1.bounding_union(&r2);
383        assert_eq!(
384            u,
385            CanvasRect {
386                x: 10,
387                y: 10,
388                width: 40,
389                height: 40,
390            }
391        );
392        assert_eq!(u.area(), 1600);
393
394        // Empty rect union
395        let empty = CanvasRect {
396            x: 0,
397            y: 0,
398            width: 0,
399            height: 0,
400        };
401        assert_eq!(r1.bounding_union(&empty), r1);
402        assert_eq!(empty.bounding_union(&r2), r2);
403    }
404
405    #[test]
406    fn test_canvas_rect_contains_and_intersects() {
407        let outer = CanvasRect {
408            x: 0,
409            y: 0,
410            width: 100,
411            height: 100,
412        };
413        let inner = CanvasRect {
414            x: 10,
415            y: 10,
416            width: 20,
417            height: 20,
418        };
419        let disjoint = CanvasRect {
420            x: 200,
421            y: 200,
422            width: 50,
423            height: 50,
424        };
425        let overlapping = CanvasRect {
426            x: 90,
427            y: 90,
428            width: 50,
429            height: 50,
430        };
431
432        assert!(outer.contains_rect(&inner));
433        assert!(!inner.contains_rect(&outer));
434        assert!(!outer.contains_rect(&disjoint));
435
436        assert!(outer.intersects(&overlapping));
437        assert!(overlapping.intersects(&outer));
438        assert!(!outer.intersects(&disjoint));
439    }
440
441    #[test]
442    fn test_canvas_damage_union() {
443        let d_full = CanvasDamage::Full;
444        let d1 = CanvasDamage::Rect(CanvasRect {
445            x: 10,
446            y: 10,
447            width: 20,
448            height: 20,
449        });
450        let d2 = CanvasDamage::Rect(CanvasRect {
451            x: 20,
452            y: 20,
453            width: 30,
454            height: 30,
455        });
456
457        // Full subsumes everything
458        assert_eq!(d_full.union(&d1), CanvasDamage::Full);
459        assert_eq!(d1.union(&d_full), CanvasDamage::Full);
460        assert_eq!(d_full.union(&d_full), CanvasDamage::Full);
461
462        // Rect union merges bounding boxes
463        let merged = d1.union(&d2);
464        assert_eq!(
465            merged,
466            CanvasDamage::Rect(CanvasRect {
467                x: 10,
468                y: 10,
469                width: 40,
470                height: 40,
471            })
472        );
473        assert_eq!(merged.area(), Some(1600));
474        assert!(!merged.is_full());
475        assert!(!merged.is_empty());
476    }
477
478    #[test]
479    fn test_canvas_damage_promotion_threshold() {
480        // Canvas is 1000 x 1000 = 1,000,000 pixels
481        let small_rect = CanvasDamage::Rect(CanvasRect {
482            x: 100,
483            y: 100,
484            width: 200,
485            height: 200,
486        }); // 40,000 px = 4%
487        assert!(!small_rect.should_promote_to_full(1000, 1000, 0.60));
488
489        let large_rect = CanvasDamage::Rect(CanvasRect {
490            x: 0,
491            y: 0,
492            width: 800,
493            height: 800,
494        }); // 640,000 px = 64%
495        assert!(large_rect.should_promote_to_full(1000, 1000, 0.60));
496
497        assert!(CanvasDamage::Full.should_promote_to_full(1000, 1000, 0.60));
498    }
499
500    #[test]
501    fn test_accumulator_lifecycle_and_coalescing() {
502        let mut accum = CanvasDamageAccumulator::new();
503        assert!(!accum.is_dirty());
504        assert_eq!(accum.events_coalesced(), 0);
505        assert_eq!(accum.refreshes_emitted(), 0);
506
507        // Record 5 successive pointer drag moves with localized damage
508        for i in 0..5 {
509            accum.record_rect_damage(CanvasRect {
510                x: i * 10,
511                y: i * 10,
512                width: 20,
513                height: 20,
514            });
515        }
516
517        assert!(accum.is_dirty());
518        assert_eq!(accum.events_coalesced(), 5);
519        assert_eq!(accum.refreshes_emitted(), 0);
520
521        // Bounding box spans x=0..60, y=0..60 -> 60x60 = 3600 px
522        let coalesced = accum.take_damage().expect("damage should be present");
523        assert_eq!(
524            coalesced,
525            CanvasDamage::Rect(CanvasRect {
526                x: 0,
527                y: 0,
528                width: 60,
529                height: 60,
530            })
531        );
532        assert_eq!(accum.refreshes_emitted(), 1);
533        assert!(!accum.is_dirty());
534
535        // Subsequent take returns None
536        assert_eq!(accum.take_damage(), None);
537    }
538
539    #[test]
540    fn test_accumulator_full_damage_subsumption_and_promotion() {
541        let mut accum = CanvasDamageAccumulator::new();
542
543        accum.record_rect_damage(CanvasRect {
544            x: 10,
545            y: 10,
546            width: 20,
547            height: 20,
548        });
549        accum.record_full_damage();
550        accum.record_rect_damage(CanvasRect {
551            x: 30,
552            y: 30,
553            width: 20,
554            height: 20,
555        });
556
557        assert_eq!(accum.events_coalesced(), 3);
558        assert_eq!(accum.take_damage(), Some(CanvasDamage::Full));
559
560        // Test promote_if_exceeds (800x800 = 640,000 px = 64% of 1,000,000)
561        accum.record_rect_damage(CanvasRect {
562            x: 0,
563            y: 0,
564            width: 800,
565            height: 800,
566        });
567        accum.promote_if_exceeds(1000, 1000, 0.60);
568        assert_eq!(accum.take_damage(), Some(CanvasDamage::Full));
569    }
570
571    #[test]
572    fn test_canvas_buffer_cost_measurement_12mp() {
573        // 12 MP document: 4000 × 3000 RGBA8
574        let bytes = CanvasBufferCost::buffer_bytes(4000, 3000);
575        assert_eq!(bytes, 48_000_000); // exactly 48 MB
576
577        // 60 Hz full copy
578        let bw_60hz = CanvasBufferCost::bandwidth_bytes_per_sec(4000, 3000, 60);
579        assert_eq!(bw_60hz, 2_880_000_000); // 2.88 GB/s
580        assert!((CanvasBufferCost::bandwidth_mb_per_sec(4000, 3000, 60) - 2880.0).abs() < 1e-4);
581
582        // 120 Hz full copy
583        let bw_120hz = CanvasBufferCost::bandwidth_bytes_per_sec(4000, 3000, 120);
584        assert_eq!(bw_120hz, 5_760_000_000); // 5.76 GB/s
585
586        // 1,000 Hz gaming mouse move rate
587        let bw_1000hz = CanvasBufferCost::bandwidth_bytes_per_sec(4000, 3000, 1000);
588        assert_eq!(bw_1000hz, 48_000_000_000); // 48.0 GB/s!
589
590        // Copy duration at 25 GiB/s effective throughput (~26.84 GB/s)
591        let latency_ms = CanvasBufferCost::estimated_copy_duration_ms(4000, 3000, 25.0);
592        assert!(latency_ms > 1.5 && latency_ms < 2.0); // ~1.79 ms
593
594        // Localized 40x40 px stroke damage patch
595        let stroke_damage = CanvasRect {
596            x: 500,
597            y: 500,
598            width: 40,
599            height: 40,
600        };
601        let stroke_bytes = CanvasBufferCost::damage_buffer_bytes(&stroke_damage);
602        assert_eq!(stroke_bytes, 6_400); // 6.4 KB
603
604        let factor = CanvasBufferCost::copy_reduction_factor(4000, 3000, &stroke_damage);
605        assert_eq!(factor, 7500.0); // 7,500x copy volume reduction!
606    }
607
608    #[test]
609    fn test_canvas_buffer_cost_resolutions_scaling() {
610        // Standard resolutions
611        assert_eq!(
612            CanvasBufferCost::buffer_bytes(800, 600),
613            1_920_000 // 1.92 MB
614        );
615        assert_eq!(
616            CanvasBufferCost::buffer_bytes(1920, 1080),
617            8_294_400 // 8.29 MB
618        );
619        assert_eq!(
620            CanvasBufferCost::buffer_bytes(3840, 2160),
621            33_177_600 // 33.18 MB (4K UHD)
622        );
623        assert_eq!(
624            CanvasBufferCost::buffer_bytes(6000, 4000),
625            96_000_000 // 96.0 MB (24 MP)
626        );
627    }
628}