Skip to main content

yew_e2e/test_driver/
canvas.rs

1//! What a canvas drew, and what is drawn at a point.
2
3use anyhow::{Context, Result};
4
5use crate::{TestDriver, TestElement};
6
7/// A canvas's own reported size -- see [`TestDriver::canvas_size`].
8#[derive(Debug, Clone, Copy)]
9pub struct CanvasSize {
10    /// The backing buffer's width, in device pixels.
11    pub device_width: f64,
12    /// The backing buffer's height, in device pixels.
13    pub device_height: f64,
14    /// The element's own layout box width, in CSS pixels.
15    pub css_width: f64,
16    /// The element's own layout box height, in CSS pixels.
17    pub css_height: f64,
18    /// What the browser itself reports for `window.devicePixelRatio`.
19    pub device_pixel_ratio: f64,
20}
21
22impl TestDriver {
23    /// **A canvas's own drawn envelope**, read from its actual pixel buffer
24    /// rather than any DOM or SVG geometry: a `<canvas>` carries no
25    /// `points`/`viewBox` attribute a test could read instead. Samples up to `columns` evenly
26    /// spaced points across the canvas's backing-buffer width; each entry is
27    /// `(x, top, bottom)`, all fractions (0.0..=1.0) of the canvas's own box
28    /// -- `x` across its width, `top`/`bottom` the first and last drawn
29    /// (non-transparent) pixel row down its height. A sampled column with
30    /// nothing drawn reads `(x, -1.0, -1.0)`.
31    pub async fn canvas_columns(
32        &self,
33        canvas: &TestElement,
34        columns: usize,
35    ) -> Result<Vec<(f64, f64, f64)>> {
36        let script = "const canvas = arguments[0]; \
37             const columns = Math.max(1, arguments[1]); \
38             const w = canvas.width, h = canvas.height; \
39             if (w === 0 || h === 0) return []; \
40             const ctx = canvas.getContext('2d'); \
41             const data = ctx.getImageData(0, 0, w, h).data; \
42             const step = Math.max(1, Math.floor(w / columns)); \
43             const out = []; \
44             for (let x = 0; x < w; x += step) { \
45                 let top = -1, bottom = -1; \
46                 for (let y = 0; y < h; y++) { \
47                     if (data[(y * w + x) * 4 + 3] > 0) { \
48                         if (top === -1) top = y; \
49                         bottom = y; \
50                     } \
51                 } \
52                 out.push([x / w, top === -1 ? -1 : top / h, bottom === -1 ? -1 : bottom / h]); \
53             } \
54             return out;";
55
56        let value = self
57            .inner
58            .execute(
59                script,
60                vec![canvas.inner.to_json()?, serde_json::json!(columns)],
61            )
62            .await?;
63
64        let read = value.json();
65        let read = read.as_array().context("canvas column scan")?;
66        let mut out = Vec::with_capacity(read.len());
67
68        for row in read {
69            let row = row.as_array().context("a canvas column")?;
70            let field = |at: usize, name: &str| {
71                row.get(at)
72                    .and_then(serde_json::Value::as_f64)
73                    .with_context(|| format!("a canvas column's {name}"))
74            };
75            out.push((field(0, "x")?, field(1, "top")?, field(2, "bottom")?));
76        }
77
78        Ok(out)
79    }
80
81    /// A canvas's backing-buffer size in device pixels alongside its
82    /// own CSS box and the browser's reported device pixel ratio, so a caller
83    /// can check the three agree -- that the buffer is sized for the actual
84    /// visible box and pixel density, not a fixed or stale guess.
85    pub async fn canvas_size(&self, canvas: &TestElement) -> Result<CanvasSize> {
86        let script = "const c = arguments[0]; const r = c.getBoundingClientRect(); \
87             return [c.width, c.height, r.width, r.height, window.devicePixelRatio];";
88
89        let value = self
90            .inner
91            .execute(script, vec![canvas.inner.to_json()?])
92            .await?;
93        let read = value.json();
94        let read = read.as_array().context("canvas size read")?;
95        let field = |at: usize, name: &str| {
96            read.get(at)
97                .and_then(serde_json::Value::as_f64)
98                .with_context(|| format!("canvas size's {name}"))
99        };
100
101        Ok(CanvasSize {
102            device_width: field(0, "device_width")?,
103            device_height: field(1, "device_height")?,
104            css_width: field(2, "css_width")?,
105            css_height: field(3, "css_height")?,
106            device_pixel_ratio: field(4, "device_pixel_ratio")?,
107        })
108    }
109
110    /// Whether what is drawn at one point of the page belongs to `selector` and
111    /// nothing is standing over it. A frame says what is drawn somewhere but
112    /// not what drew it, so a test measuring a window's own content has to be
113    /// able to tell that content from whatever floats in front of it.
114    ///
115    /// Two questions, because one does not do. Hit testing says which element
116    /// is uppermost at the point, which settles the ordinary case. But a menu,
117    /// a drag ghost or a help bubble is drawn through a portal into the
118    /// document body, over the top of a window and often wider than it, and a
119    /// bubble takes no pointer events at all -- hit testing looks straight
120    /// through it and answers with the window underneath. So anything portaled
121    /// beside the application is asked separately whether it covers the point.
122    ///
123    /// The point is in the page's own pixels, not the frame's.
124    pub async fn drawn_inside(&self, selector: &str, x: f64, y: f64) -> Result<bool> {
125        tracing::trace!(selector, x, y, "Asking what is drawn at a point");
126
127        let script = "const [selector, x, y] = arguments; \
128             const host = document.querySelector(selector); \
129             const found = document.elementFromPoint(x, y); \
130             if (!host || !found || !host.contains(found)) return false; \
131             for (const over of document.body.children) { \
132                 if (over.contains(host) || host.contains(over)) continue; \
133                 const box = over.getBoundingClientRect(); \
134                 if (x >= box.left && x <= box.right && y >= box.top && y <= box.bottom) \
135                     return false; \
136             } \
137             return true;";
138
139        let value = self
140            .inner
141            .execute(
142                script,
143                vec![
144                    serde_json::json!(selector),
145                    serde_json::json!(x),
146                    serde_json::json!(y),
147                ],
148            )
149            .await?;
150
151        Ok(value.json().as_bool().unwrap_or_default())
152    }
153}