Skip to main content

paint/
webview_renderer.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::Cell;
6use std::collections::hash_map::Entry;
7use std::rc::Rc;
8
9use crossbeam_channel::Sender;
10use embedder_traits::{
11    AnimationState, InputEvent, InputEventAndId, InputEventId, InputEventResult,
12    PaintHitTestResult, Scroll, TouchEvent, TouchEventType, ViewportDetails, WebViewPoint,
13    WheelEvent,
14};
15use euclid::{Box2D, Rect, Scale, Size2D, Vector2D};
16use log::{debug, warn};
17use malloc_size_of::MallocSizeOf;
18use paint_api::display_list::ScrollType;
19use paint_api::viewport_description::{
20    DEFAULT_PAGE_ZOOM, MAX_PAGE_ZOOM, MIN_PAGE_ZOOM, ViewportDescription,
21};
22use paint_api::{PipelineExitSource, SendableFrameTree, WebViewTrait};
23use rustc_hash::FxHashMap;
24use servo_base::id::{PipelineId, WebViewId};
25use servo_constellation_traits::{
26    EmbedderToConstellationMessage, ScrollStateUpdate, WindowSizeType,
27};
28use servo_geometry::{DeviceIndependentPixel, FastLayoutTransform, au_rect_to_f32_rect};
29use style_traits::CSSPixel;
30use webrender::RenderApi;
31use webrender_api::units::{
32    Au, DevicePixel, DevicePoint, DeviceRect, DeviceVector2D, LayoutTransform, LayoutVector2D,
33    RectExt,
34};
35use webrender_api::{DocumentId, ExternalScrollId, PropertyBindingKey, ScrollLocation};
36
37use crate::paint::RepaintReason;
38use crate::painter::Painter;
39use crate::pinch_zoom::PinchZoom;
40use crate::pipeline_details::PipelineDetails;
41use crate::refresh_driver::BaseRefreshDriver;
42use crate::touch::{
43    PanPolicyInput, PendingTouchInputEvent, TouchHandler, TouchIdMoveTracking, TouchMoveAllowed,
44    TouchSequenceState,
45};
46
47#[derive(Clone, Copy)]
48pub(crate) struct ScrollEvent {
49    /// Scroll by this offset, or to Start or End
50    pub scroll: Scroll,
51    /// Scroll the scroll node that is found at this point.
52    pub point: DevicePoint,
53    /// The kind of input that originated this scroll. `Touch` respects `touch-action`
54    /// restrictions; `InputEvents` (mouse wheel, keyboard) does not.
55    pub scroll_type: ScrollType,
56}
57
58#[derive(Clone, Copy)]
59pub(crate) enum ScrollZoomEvent {
60    /// A pinch zoom event that magnifies the view by the given factor from the given
61    /// center point.
62    PinchZoom(f32, DevicePoint),
63    /// A scroll event that scrolls the scroll node at the given location by the
64    /// given amount.
65    Scroll(ScrollEvent),
66}
67
68#[derive(Clone, Debug)]
69pub(crate) struct ScrollResult {
70    pub hit_test_result: PaintHitTestResult,
71    /// The [`ExternalScrollId`] of the node that was actually scrolled.
72    ///
73    /// Note that this is an inclusive ancestor of `external_scroll_id` in
74    /// [`Self::hit_test_result`].
75    pub external_scroll_id: ExternalScrollId,
76    pub offset: LayoutVector2D,
77}
78
79#[derive(Debug, PartialEq)]
80pub(crate) enum PinchZoomResult {
81    DidPinchZoom,
82    DidNotPinchZoom,
83}
84
85/// A renderer for a libservo `WebView`. This is essentially the [`ServoRenderer`]'s interface to a
86/// libservo `WebView`, but the code here cannot depend on libservo in order to prevent circular
87/// dependencies, which is why we store a `dyn WebViewTrait` here instead of the `WebView` itself.
88pub(crate) struct WebViewRenderer {
89    /// The [`WebViewId`] of the `WebView` associated with this [`WebViewDetails`].
90    pub id: WebViewId,
91    /// The renderer's view of the embedding layer `WebView` as a trait implementation,
92    /// so that the renderer doesn't need to depend on the embedding layer. This avoids
93    /// a dependency cycle.
94    pub webview: Box<dyn WebViewTrait>,
95    /// The root [`PipelineId`] of the currently displayed page in this WebView.
96    pub root_pipeline_id: Option<PipelineId>,
97    /// The rectangle of the [`WebView`] in device pixels, which is the viewport.
98    pub rect: DeviceRect,
99    /// Tracks details about each active pipeline that `Paint` knows about.
100    pub pipelines: FxHashMap<PipelineId, PipelineDetails>,
101    /// Pending scroll/zoom events.
102    pending_scroll_zoom_events: Vec<ScrollZoomEvent>,
103    /// A map of pending wheel events. These are events that have been sent to script,
104    /// but are waiting for processing. When they are handled by script, they may trigger
105    /// scroll events depending on whether `preventDefault()` was called on the event.
106    pending_wheel_events: FxHashMap<InputEventId, WheelEvent>,
107    /// Touch input state machine
108    touch_handler: TouchHandler,
109    /// "Desktop-style" zoom that resizes the viewport to fit the window.
110    pub page_zoom: Scale<f32, CSSPixel, DeviceIndependentPixel>,
111    /// "Mobile-style" zoom that does not reflow the page. When there is no [`PinchZoom`] a
112    /// zoom factor of 1.0 is implied and the [`PinchZoom::transform`] will be the identity.
113    pinch_zoom: PinchZoom,
114    /// The HiDPI scale factor for the `WebView` associated with this renderer. This is controlled
115    /// by the embedding layer.
116    hidpi_scale_factor: Scale<f32, DeviceIndependentPixel, DevicePixel>,
117    /// Whether or not this [`WebViewRenderer`] is hidden.
118    hidden: bool,
119    /// Whether or not this [`WebViewRenderer`] isn't throttled and has a pipeline with
120    /// active animations or animation frame callbacks.
121    animating: bool,
122    /// A [`ViewportDescription`] for this [`WebViewRenderer`], which contains the limitations
123    /// and initial values for zoom derived from the `viewport` meta tag in web content.
124    viewport_description: ViewportDescription,
125    /// The dimensions of the screen on which this WebView is rendering.
126    screen_size: Size2D<f32, DevicePixel>,
127    /// The [`PropertyBindingKey`] that this [`WebViewRenderer`] uses for pinch zoom.
128    pinch_zoom_property_binding_key: PropertyBindingKey<LayoutTransform>,
129
130    //
131    // Data that is shared with the parent renderer.
132    //
133    /// The channel on which messages can be sent to the constellation.
134    embedder_to_constellation_sender: Sender<EmbedderToConstellationMessage>,
135    /// The [`BaseRefreshDriver`] which manages the painting of `WebView`s during animations.
136    refresh_driver: Rc<BaseRefreshDriver>,
137    /// The active webrender document.
138    webrender_document: DocumentId,
139}
140
141impl WebViewRenderer {
142    pub(crate) fn new(
143        renderer_webview: Box<dyn WebViewTrait>,
144        viewport_details: ViewportDetails,
145        embedder_to_constellation_sender: Sender<EmbedderToConstellationMessage>,
146        refresh_driver: Rc<BaseRefreshDriver>,
147        webrender_document: DocumentId,
148        pinch_zoom_property_binding_key: PropertyBindingKey<LayoutTransform>,
149    ) -> Self {
150        let hidpi_scale_factor = viewport_details.hidpi_scale_factor;
151        let size = viewport_details.size * viewport_details.hidpi_scale_factor;
152        let rect = DeviceRect::from_origin_and_size(DevicePoint::origin(), size);
153        let webview_id = renderer_webview.id();
154        Self {
155            id: webview_id,
156            webview: renderer_webview,
157            root_pipeline_id: None,
158            rect,
159            pipelines: Default::default(),
160            touch_handler: TouchHandler::new(webview_id),
161            pending_scroll_zoom_events: Default::default(),
162            pending_wheel_events: Default::default(),
163            page_zoom: DEFAULT_PAGE_ZOOM,
164            pinch_zoom: PinchZoom::new(rect),
165            hidpi_scale_factor: Scale::new(hidpi_scale_factor.0),
166            hidden: false,
167            animating: false,
168            viewport_description: Default::default(),
169            screen_size: viewport_details.device_size,
170            embedder_to_constellation_sender,
171            refresh_driver,
172            webrender_document,
173            pinch_zoom_property_binding_key,
174        }
175    }
176
177    fn hit_test(&self, webrender_api: &RenderApi, point: DevicePoint) -> Vec<PaintHitTestResult> {
178        Painter::hit_test_at_point_with_api_and_document(
179            webrender_api,
180            self.webrender_document,
181            point,
182        )
183    }
184
185    pub(crate) fn animation_callbacks_running(&self) -> bool {
186        self.pipelines
187            .values()
188            .any(PipelineDetails::animation_callbacks_running)
189    }
190
191    /// Whether this [`WebViewRenderer`] is animating. Note that hidden `WebView`s
192    /// are never considered to be animating.
193    pub(crate) fn animating(&self) -> bool {
194        self.animating && !self.hidden()
195    }
196
197    pub(crate) fn hidden(&self) -> bool {
198        self.hidden
199    }
200
201    /// Set whether this [`WebViewRenderer`] is in the hidden state or not. Return `true` if the
202    /// value changed or `false` otherwise.
203    pub(crate) fn set_hidden(&mut self, new_value: bool) -> bool {
204        let old_value = std::mem::replace(&mut self.hidden, new_value);
205        if new_value == old_value {
206            return false;
207        }
208
209        let _ = self.embedder_to_constellation_sender.send(
210            EmbedderToConstellationMessage::SetWebViewHidden(self.id, new_value),
211        );
212        self.update_animation_state();
213        true
214    }
215
216    /// Returns the [`PipelineDetails`] for the given [`PipelineId`], creating it if needed.
217    pub(crate) fn ensure_pipeline_details(
218        &mut self,
219        pipeline_id: PipelineId,
220    ) -> &mut PipelineDetails {
221        self.pipelines
222            .entry(pipeline_id)
223            .or_insert_with(PipelineDetails::new)
224    }
225
226    /// Record that `source` has reported `pipeline_id` as exited. Returns `true`
227    /// once every source has done so and the pipeline details have been discarded,
228    /// so that the caller can also drop the pipeline's scene state in WebRender.
229    pub(crate) fn pipeline_exited(
230        &mut self,
231        pipeline_id: PipelineId,
232        source: PipelineExitSource,
233    ) -> bool {
234        let pipeline = self.pipelines.entry(pipeline_id);
235        let Entry::Occupied(mut pipeline) = pipeline else {
236            return false;
237        };
238
239        pipeline.get_mut().exited.insert(source);
240
241        // Do not remove pipeline details until both the Constellation and Script have
242        // finished processing the pipeline shutdown. This prevents any followup messges
243        // from re-adding the pipeline details and creating a zombie.
244        if !pipeline.get().exited.is_all() {
245            return false;
246        }
247
248        // Flush the LCP candidates when exiting pipeline.
249        pipeline.get_mut().lcp_candidates.clear();
250
251        pipeline.remove_entry();
252        true
253    }
254
255    pub(crate) fn set_frame_tree(&mut self, frame_tree: &SendableFrameTree) {
256        let pipeline_id = frame_tree.pipeline.id;
257        let old_pipeline_id = self.root_pipeline_id.replace(pipeline_id);
258
259        if old_pipeline_id != self.root_pipeline_id {
260            debug!(
261                "Updating webview ({:?}) from pipeline {:?} to {:?}",
262                3, old_pipeline_id, self.root_pipeline_id
263            );
264        }
265
266        self.set_frame_tree_on_pipeline_details(frame_tree, None);
267    }
268
269    pub(crate) fn send_scroll_positions_to_layout_for_pipeline(
270        &self,
271        pipeline_id: PipelineId,
272        scrolled_node: ExternalScrollId,
273    ) {
274        let Some(details) = self.pipelines.get(&pipeline_id) else {
275            return;
276        };
277
278        let offsets = details.scroll_tree.scroll_offsets();
279
280        // This might be true if we have not received a display list from the layout
281        // associated with this pipeline yet. In that case, the layout is not ready to
282        // receive scroll offsets anyway, so just save time and prevent other issues by
283        // not sending them.
284        if offsets.is_empty() {
285            return;
286        }
287
288        let _ = self.embedder_to_constellation_sender.send(
289            EmbedderToConstellationMessage::SetScrollStates(
290                pipeline_id,
291                ScrollStateUpdate {
292                    scrolled_node,
293                    offsets,
294                },
295            ),
296        );
297    }
298
299    pub(crate) fn set_frame_tree_on_pipeline_details(
300        &mut self,
301        frame_tree: &SendableFrameTree,
302        parent_pipeline_id: Option<PipelineId>,
303    ) {
304        let pipeline_id = frame_tree.pipeline.id;
305        let pipeline_details = self.ensure_pipeline_details(pipeline_id);
306        pipeline_details.pipeline = Some(frame_tree.pipeline.clone());
307        pipeline_details.parent_pipeline_id = parent_pipeline_id;
308        pipeline_details.children = frame_tree
309            .children
310            .iter()
311            .map(|frame_tree| frame_tree.pipeline.id)
312            .collect();
313
314        for kid in &frame_tree.children {
315            self.set_frame_tree_on_pipeline_details(kid, Some(pipeline_id));
316        }
317    }
318
319    /// Sets or unsets the animations-running flag for the given pipeline. Returns
320    /// true if the pipeline has started animating.
321    pub(crate) fn change_pipeline_running_animations_state(
322        &mut self,
323        pipeline_id: PipelineId,
324        animation_state: AnimationState,
325    ) -> bool {
326        let pipeline_details = self.ensure_pipeline_details(pipeline_id);
327        let was_animating = pipeline_details.animating();
328        match animation_state {
329            AnimationState::AnimationsPresent => {
330                pipeline_details.animations_running = true;
331            },
332            AnimationState::AnimationCallbacksPresent => {
333                pipeline_details.animation_callbacks_running = true;
334            },
335            AnimationState::NoAnimationsPresent => {
336                pipeline_details.animations_running = false;
337            },
338            AnimationState::AnimationCallbacksAbsent => {
339                pipeline_details.animation_callbacks_running = false;
340            },
341        }
342        let started_animating = !was_animating && pipeline_details.animating();
343
344        self.update_animation_state();
345
346        // It's important that an animation tick is triggered even if the
347        // WebViewRenderer's overall animation state hasn't changed. It's possible that
348        // the WebView was animating, but not producing new display lists. In that case,
349        // no repaint will happen and thus no repaint will trigger the next animation tick.
350        started_animating
351    }
352
353    /// Sets or unsets the throttled flag for the given pipeline. Returns
354    /// true if the pipeline has started animating.
355    pub(crate) fn set_throttled(&mut self, pipeline_id: PipelineId, throttled: bool) -> bool {
356        let pipeline_details = self.ensure_pipeline_details(pipeline_id);
357        let was_animating = pipeline_details.animating();
358        pipeline_details.throttled = throttled;
359        let started_animating = !was_animating && pipeline_details.animating();
360
361        // Throttling a pipeline can cause it to be taken into the "not-animating" state.
362        self.update_animation_state();
363
364        // It's important that an animation tick is triggered even if the
365        // WebViewRenderer's overall animation state hasn't changed. It's possible that
366        // the WebView was animating, but not producing new display lists. In that case,
367        // no repaint will happen and thus no repaint will trigger the next animation tick.
368        started_animating
369    }
370
371    fn update_animation_state(&mut self) {
372        self.animating = self.pipelines.values().any(PipelineDetails::animating);
373        self.webview.set_animating(self.animating());
374    }
375
376    pub(crate) fn for_each_connected_pipeline(&self, callback: &mut impl FnMut(&PipelineDetails)) {
377        if let Some(root_pipeline_id) = self.root_pipeline_id {
378            self.for_each_connected_pipeline_internal(root_pipeline_id, callback);
379        }
380    }
381
382    fn for_each_connected_pipeline_internal(
383        &self,
384        pipeline_id: PipelineId,
385        callback: &mut impl FnMut(&PipelineDetails),
386    ) {
387        let Some(pipeline) = self.pipelines.get(&pipeline_id) else {
388            return;
389        };
390        callback(pipeline);
391        for child_pipeline_id in &pipeline.children {
392            self.for_each_connected_pipeline_internal(*child_pipeline_id, callback);
393        }
394    }
395
396    /// Update touch-based animations (currently just fling) during a `RefreshDriver`-based
397    /// frame tick. Returns `true` if we should continue observing frames (the fling is ongoing)
398    /// or `false` if we should stop observing frames (the fling has finished).
399    pub(crate) fn update_touch_handling_at_new_frame_start(&mut self) -> bool {
400        let Some(fling_action) = self.touch_handler.notify_new_frame_start() else {
401            return false;
402        };
403
404        self.on_scroll_window_event(
405            Scroll::Delta((-fling_action.delta).into()),
406            fling_action.cursor,
407            // Fling is a continuation of a touch pan, so it must respect
408            // `touch-action` like the originating touch gesture.
409            ScrollType::Touch,
410        );
411        true
412    }
413
414    fn dispatch_input_event_with_hit_testing(
415        &mut self,
416        render_api: &RenderApi,
417        event: InputEventAndId,
418    ) -> bool {
419        let event_point = event
420            .event
421            .point()
422            .map(|point| point.as_device_point(self.device_pixels_per_page_pixel()));
423        let is_touch_down = matches!(
424            &event.event,
425            InputEvent::Touch(TouchEvent {
426                event_type: TouchEventType::Down,
427                ..
428            })
429        );
430        let hit_test_result = match event_point {
431            Some(point) => {
432                let hit_test_result = match event.event {
433                    InputEvent::Touch(_) => self.touch_handler.get_hit_test_result_cache_value(),
434                    _ => None,
435                }
436                .or_else(|| self.hit_test(render_api, point).into_iter().nth(0));
437                if hit_test_result.is_none() {
438                    warn!("Empty hit test result for input event, ignoring.");
439                    return false;
440                }
441                hit_test_result
442            },
443            None => None,
444        };
445
446        // For touch-down, capture the hit node's `touch-action` and scrollable
447        // axes from the scroll tree so the pan axis-lock policy can be decided
448        // at pan-start.
449        if is_touch_down && let Some(hit) = &hit_test_result {
450            let policy_input = self
451                .pipelines
452                .get(&hit.pipeline_id)
453                .and_then(|pipeline_details| {
454                    pipeline_details
455                        .scroll_tree
456                        .touch_action_and_scrollable_axes_for(hit.external_scroll_id)
457                })
458                .map(
459                    |(touch_action, scrollable_x, scrollable_y)| PanPolicyInput {
460                        touch_action,
461                        scrollable_x,
462                        scrollable_y,
463                    },
464                );
465            if let Some(input) = policy_input {
466                self.touch_handler.set_pan_policy_input(input);
467            }
468        }
469
470        if let Err(error) = self.embedder_to_constellation_sender.send(
471            EmbedderToConstellationMessage::ForwardInputEvent(self.id, event, hit_test_result),
472        ) {
473            warn!("Sending event to constellation failed ({error:?}).");
474            false
475        } else {
476            true
477        }
478    }
479
480    pub(crate) fn notify_input_event(
481        &mut self,
482        render_api: &RenderApi,
483        repaint_reason: &Cell<RepaintReason>,
484        event_and_id: InputEventAndId,
485    ) -> bool {
486        if let InputEvent::Touch(touch_event) = event_and_id.event {
487            return self.on_touch_event(render_api, repaint_reason, touch_event, event_and_id.id);
488        }
489
490        if let InputEvent::Wheel(wheel_event) = event_and_id.event {
491            self.pending_wheel_events
492                .insert(event_and_id.id, wheel_event);
493        }
494
495        self.dispatch_input_event_with_hit_testing(render_api, event_and_id)
496    }
497
498    fn send_touch_event(
499        &mut self,
500        render_api: &RenderApi,
501        event: TouchEvent,
502        id: InputEventId,
503    ) -> bool {
504        let cancelable = event.is_cancelable();
505        let event_type = event.event_type;
506
507        let input_event_and_id = InputEventAndId {
508            event: InputEvent::Touch(event),
509            id,
510        };
511
512        let result = self.dispatch_input_event_with_hit_testing(render_api, input_event_and_id);
513
514        // We only post-process events that are actually cancelable. Uncancelable ones
515        // are processed immediately and can be ignored once they have been sent to the
516        // Constellation.
517        if cancelable && result {
518            self.touch_handler
519                .add_pending_touch_input_event(id, event.touch_id, event_type);
520        }
521
522        result
523    }
524
525    pub(crate) fn on_touch_event(
526        &mut self,
527        render_api: &RenderApi,
528        repaint_reason: &Cell<RepaintReason>,
529        event: TouchEvent,
530        id: InputEventId,
531    ) -> bool {
532        let result = match event.event_type {
533            TouchEventType::Down => self.on_touch_down(render_api, event, id),
534            TouchEventType::Move => self.on_touch_move(render_api, event, id),
535            TouchEventType::Up => self.on_touch_up(render_api, event, id),
536            TouchEventType::Cancel => self.on_touch_cancel(render_api, event, id),
537        };
538
539        self.touch_handler
540            .add_touch_move_refresh_observer_if_necessary(
541                self.refresh_driver.clone(),
542                repaint_reason,
543            );
544        result
545    }
546
547    fn on_touch_down(
548        &mut self,
549        render_api: &RenderApi,
550        event: TouchEvent,
551        id: InputEventId,
552    ) -> bool {
553        let point = event
554            .point
555            .as_device_point(self.device_pixels_per_page_pixel());
556        self.touch_handler.on_touch_down(event.touch_id, point);
557        self.send_touch_event(render_api, event, id)
558    }
559
560    fn on_touch_move(
561        &mut self,
562        render_api: &RenderApi,
563        mut event: TouchEvent,
564        id: InputEventId,
565    ) -> bool {
566        let point = event
567            .point
568            .as_device_point(self.device_pixels_per_page_pixel());
569        let action = self.touch_handler.on_touch_move(
570            event.touch_id,
571            point,
572            self.device_pixels_per_page_pixel_not_including_pinch_zoom()
573                .get(),
574        );
575        if let Some(action) = action {
576            // if first move processed and allowed, we directly process the move event,
577            // without waiting for the script handler.
578            if self
579                .touch_handler
580                .move_allowed(self.touch_handler.current_sequence_id)
581            {
582                // https://w3c.github.io/touch-events/#cancelability
583                event.disable_cancelable();
584                self.pending_scroll_zoom_events.push(action);
585            }
586        }
587        let mut reached_constellation = false;
588        // When the event is touchmove, if the script thread is processing the touch
589        // move event, we skip sending the event to the script thread.
590        // This prevents the script thread from stacking up for a large amount of time.
591        if !self.touch_handler.is_handling_touch_move_for_touch_id(
592            self.touch_handler.current_sequence_id,
593            event.touch_id,
594        ) {
595            reached_constellation = self.send_touch_event(render_api, event, id);
596            if reached_constellation && event.is_cancelable() {
597                self.touch_handler.set_handling_touch_move_for_touch_id(
598                    self.touch_handler.current_sequence_id,
599                    event.touch_id,
600                    TouchIdMoveTracking::Track,
601                );
602            }
603        }
604        reached_constellation
605    }
606
607    fn on_touch_up(
608        &mut self,
609        render_api: &RenderApi,
610        mut event: TouchEvent,
611        id: InputEventId,
612    ) -> bool {
613        let point = event
614            .point
615            .as_device_point(self.device_pixels_per_page_pixel());
616        // Tag taps so script can generate the compatibility mouse events.
617        if self.touch_handler.on_touch_up(event.touch_id, point) {
618            event.can_synthesize_mouse_events = true;
619        }
620        self.send_touch_event(render_api, event, id)
621    }
622
623    fn on_touch_cancel(
624        &mut self,
625        render_api: &RenderApi,
626        event: TouchEvent,
627        id: InputEventId,
628    ) -> bool {
629        let point = event
630            .point
631            .as_device_point(self.device_pixels_per_page_pixel());
632        self.touch_handler.on_touch_cancel(event.touch_id, point);
633        self.send_touch_event(render_api, event, id)
634    }
635
636    fn on_touch_event_processed(
637        &mut self,
638        pending_touch_input_event: PendingTouchInputEvent,
639        result: InputEventResult,
640    ) {
641        let PendingTouchInputEvent {
642            sequence_id,
643            event_type,
644            touch_id,
645        } = pending_touch_input_event;
646
647        // A touch is left to the compositor only if neither script nor a user agent widget
648        // process it.
649        if result.intersects(InputEventResult::DefaultPrevented | InputEventResult::Consumed) {
650            debug!(
651                "Touch event {:?} in sequence {:?} prevented or consumed",
652                event_type, sequence_id
653            );
654            match event_type {
655                TouchEventType::Down => {
656                    // prevents both click and move
657                    self.touch_handler.prevent_click(sequence_id);
658                    self.touch_handler.prevent_move(sequence_id);
659                    self.touch_handler
660                        .remove_pending_touch_move_actions(sequence_id);
661                },
662                TouchEventType::Move => {
663                    // script thread processed the touch move event, mark this false.
664                    if let Some(info) = self.touch_handler.get_touch_sequence_mut(sequence_id) {
665                        info.prevent_move = TouchMoveAllowed::Prevented;
666                        if let TouchSequenceState::PendingFling { .. } = info.state {
667                            info.state = TouchSequenceState::Finished;
668                        }
669                        self.touch_handler.set_handling_touch_move_for_touch_id(
670                            self.touch_handler.current_sequence_id,
671                            touch_id,
672                            TouchIdMoveTracking::Remove,
673                        );
674                        self.touch_handler
675                            .remove_pending_touch_move_actions(sequence_id);
676                    }
677                },
678                TouchEventType::Up => {
679                    // Note: We don't have to consider PendingFling here, since we handle that
680                    // in the DefaultAllowed case of the touch_move event.
681                    // Note: Removing can and should fail, if we still have an active Fling,
682                    let Some(info) = &mut self.touch_handler.get_touch_sequence_mut(sequence_id)
683                    else {
684                        // The sequence ID could already be removed, e.g. if Fling finished,
685                        // before the touch_up event was handled (since fling can start
686                        // immediately if move was previously allowed, and clicks are anyway not
687                        // happening from fling).
688                        return;
689                    };
690                    match info.state {
691                        TouchSequenceState::PendingClick => {
692                            info.state = TouchSequenceState::Finished;
693                            self.touch_handler.remove_touch_sequence(sequence_id);
694                        },
695                        TouchSequenceState::Flinging { .. } => {
696                            // We can't remove the touch sequence yet
697                        },
698                        TouchSequenceState::Finished => {
699                            self.touch_handler.remove_touch_sequence(sequence_id);
700                        },
701                        TouchSequenceState::Touching |
702                        TouchSequenceState::Panning { .. } |
703                        TouchSequenceState::Pinching |
704                        TouchSequenceState::MultiTouch |
705                        TouchSequenceState::PendingFling { .. } => {
706                            // It's possible to transition from Pinch to pan, Which means that
707                            // a touch_up event for a pinch might have arrived here, but we
708                            // already transitioned to pan or even PendingFling.
709                            // We don't need to do anything in these cases though.
710                        },
711                    }
712                },
713                TouchEventType::Cancel => {
714                    // We could still have pending event handlers, so we remove the pending
715                    // actions, and try to remove the touch sequence.
716                    self.touch_handler
717                        .remove_pending_touch_move_actions(sequence_id);
718                    self.touch_handler.try_remove_touch_sequence(sequence_id);
719                },
720            }
721        } else {
722            debug!(
723                "Touch event {:?} in sequence {:?} allowed",
724                event_type, sequence_id
725            );
726            match event_type {
727                TouchEventType::Down => {},
728                TouchEventType::Move => {
729                    self.pending_scroll_zoom_events.extend(
730                        self.touch_handler
731                            .take_pending_touch_move_actions(sequence_id),
732                    );
733                    self.touch_handler.set_handling_touch_move_for_touch_id(
734                        self.touch_handler.current_sequence_id,
735                        touch_id,
736                        TouchIdMoveTracking::Remove,
737                    );
738                    if let Some(info) = self.touch_handler.get_touch_sequence_mut(sequence_id) &&
739                        info.prevent_move == TouchMoveAllowed::Pending
740                    {
741                        info.prevent_move = TouchMoveAllowed::Allowed;
742                        if let TouchSequenceState::PendingFling { velocity, point } = info.state {
743                            info.state = TouchSequenceState::Flinging { velocity, point }
744                        }
745                    }
746                },
747                TouchEventType::Up => {
748                    let Some(info) = self.touch_handler.get_touch_sequence_mut(sequence_id) else {
749                        // The sequence was already removed because there is no default action.
750                        return;
751                    };
752                    match info.state {
753                        TouchSequenceState::PendingClick => {
754                            info.state = TouchSequenceState::Finished;
755                            self.touch_handler.remove_touch_sequence(sequence_id);
756                        },
757                        TouchSequenceState::Flinging { .. } => {
758                            // We can't remove the touch sequence yet
759                        },
760                        TouchSequenceState::Finished => {
761                            self.touch_handler.remove_touch_sequence(sequence_id);
762                        },
763                        TouchSequenceState::Panning { .. } |
764                        TouchSequenceState::Pinching |
765                        TouchSequenceState::PendingFling { .. } => {
766                            // It's possible to transition from Pinch to pan, Which means that
767                            // a touch_up event for a pinch might have arrived here, but we
768                            // already transitioned to pan or even PendingFling.
769                            // We don't need to do anything in these cases though.
770                        },
771                        TouchSequenceState::MultiTouch | TouchSequenceState::Touching => {
772                            // We transitioned to touching from multi-touch or pinching.
773                        },
774                    }
775                },
776                TouchEventType::Cancel => {
777                    self.touch_handler
778                        .remove_pending_touch_move_actions(sequence_id);
779                    self.touch_handler.try_remove_touch_sequence(sequence_id);
780                },
781            }
782        }
783    }
784
785    pub(crate) fn notify_scroll_event(&mut self, scroll: Scroll, point: WebViewPoint) {
786        let point = point.as_device_point(self.device_pixels_per_page_pixel());
787        self.on_scroll_window_event(scroll, point, ScrollType::InputEvents);
788    }
789
790    fn on_scroll_window_event(
791        &mut self,
792        scroll: Scroll,
793        cursor: DevicePoint,
794        scroll_type: ScrollType,
795    ) {
796        self.pending_scroll_zoom_events
797            .push(ScrollZoomEvent::Scroll(ScrollEvent {
798                scroll,
799                point: cursor,
800                scroll_type,
801            }));
802    }
803
804    /// Process pending scroll events for this [`WebViewRenderer`]. Returns a tuple containing:
805    ///
806    ///  - A boolean that is true if a zoom occurred.
807    ///  - An optional [`ScrollResult`] if a scroll occurred.
808    ///
809    /// It is up to the caller to ensure that these events update the rendering appropriately.
810    pub(crate) fn process_pending_scroll_and_pinch_zoom_events(
811        &mut self,
812        render_api: &RenderApi,
813    ) -> (PinchZoomResult, Option<ScrollResult>) {
814        if self.pending_scroll_zoom_events.is_empty() {
815            return (PinchZoomResult::DidNotPinchZoom, None);
816        }
817
818        // Batch up all scroll events and changes to pinch zoom into a single change, or
819        // else we'll do way too much painting.
820        let mut combined_scroll_event: Option<ScrollEvent> = None;
821        let mut new_pinch_zoom = self.pinch_zoom;
822        let device_pixels_per_page_pixel = self.device_pixels_per_page_pixel();
823
824        for scroll_event in self.pending_scroll_zoom_events.drain(..) {
825            match scroll_event {
826                ScrollZoomEvent::PinchZoom(magnification, center) => {
827                    let new_factor = self
828                        .viewport_description
829                        .clamp_zoom(self.pinch_zoom.zoom_factor().0 * magnification);
830                    new_pinch_zoom.set_zoom(new_factor, center);
831                },
832                ScrollZoomEvent::Scroll(scroll_event_info) => {
833                    let combined_event = match combined_scroll_event.as_mut() {
834                        None => {
835                            combined_scroll_event = Some(scroll_event_info);
836                            continue;
837                        },
838                        Some(combined_event) => combined_event,
839                    };
840
841                    match (combined_event.scroll, scroll_event_info.scroll) {
842                        (Scroll::Delta(old_delta), Scroll::Delta(new_delta)) => {
843                            let old_delta =
844                                old_delta.as_device_vector(device_pixels_per_page_pixel);
845                            let new_delta =
846                                new_delta.as_device_vector(device_pixels_per_page_pixel);
847                            combined_event.scroll = Scroll::Delta((old_delta + new_delta).into());
848                        },
849                        (Scroll::Start, _) | (Scroll::End, _) => {
850                            // Once we see Start or End, we shouldn't process any more events.
851                            break;
852                        },
853                        (_, Scroll::Start) | (_, Scroll::End) => {
854                            // If this is an event which is scrolling to the start or end of the page,
855                            // disregard other pending events and exit the loop.
856                            *combined_event = scroll_event_info;
857                            break;
858                        },
859                    }
860                },
861            }
862        }
863
864        // When zoomed in via pinch zoom, first try to move the center of the zoom and use the rest
865        // of the delta for scrolling. This allows moving the zoomed into viewport around in the
866        // unzoomed viewport before actually scrolling the underlying layers.
867        if let Some(combined_scroll_event) = combined_scroll_event.as_mut() {
868            new_pinch_zoom.pan(
869                &mut combined_scroll_event.scroll,
870                self.device_pixels_per_page_pixel(),
871            )
872        }
873
874        let scroll_result = combined_scroll_event.and_then(|combined_event| {
875            self.scroll_node_at_device_point(
876                render_api,
877                combined_event.point.to_f32(),
878                combined_event.scroll,
879                combined_event.scroll_type,
880            )
881        });
882        if let Some(ref scroll_result) = scroll_result {
883            self.send_scroll_positions_to_layout_for_pipeline(
884                scroll_result.hit_test_result.pipeline_id,
885                scroll_result.external_scroll_id,
886            );
887        } else {
888            self.touch_handler.stop_fling_if_needed();
889        }
890
891        // Additionally notify pinch zoom update to the script.
892        let pinch_zoom_result = self.set_pinch_zoom(new_pinch_zoom);
893        if pinch_zoom_result == PinchZoomResult::DidPinchZoom {
894            self.send_pinch_zoom_infos_to_script();
895            // Pinch zoom changes the viewport transform without touching the pipeline, so no reflow
896            // will occur. Notify the embedding layer so it can refresh the accessibility root node,
897            // whose transform scales by the pinch zoom.
898            self.webview.notify_viewport_updated();
899        }
900
901        (pinch_zoom_result, scroll_result)
902    }
903
904    /// Perform a hit test at the given [`DevicePoint`] and apply the [`Scroll`]
905    /// scrolling to the applicable scroll node under that point. If a scroll was
906    /// performed, returns the hit test result contains [`PipelineId`] of the node
907    /// scrolled, the id, and the final scroll delta.
908    fn scroll_node_at_device_point(
909        &mut self,
910        render_api: &RenderApi,
911        cursor: DevicePoint,
912        scroll: Scroll,
913        scroll_type: ScrollType,
914    ) -> Option<ScrollResult> {
915        let scroll_location = match scroll {
916            Scroll::Delta(delta) => {
917                let device_pixels_per_page = self.device_pixels_per_page_pixel();
918                let calculate_delta =
919                    delta.as_device_vector(device_pixels_per_page) / device_pixels_per_page;
920                ScrollLocation::Delta(calculate_delta.cast_unit())
921            },
922            Scroll::Start => ScrollLocation::Start,
923            Scroll::End => ScrollLocation::End,
924        };
925
926        let hit_test_results: Vec<_> = self
927            .touch_handler
928            .get_hit_test_result_cache_value()
929            .map(|result| vec![result])
930            .unwrap_or_else(|| self.hit_test(render_api, cursor));
931
932        // Iterate through all hit test results, processing only the first node of each pipeline.
933        // This is needed to propagate the scroll events from a pipeline representing an iframe to
934        // its ancestor pipelines.
935        let mut previous_pipeline_id = None;
936        for hit_test_result in hit_test_results {
937            let pipeline_details = self.pipelines.get_mut(&hit_test_result.pipeline_id)?;
938            if previous_pipeline_id.replace(hit_test_result.pipeline_id) !=
939                Some(hit_test_result.pipeline_id)
940            {
941                let scroll_result = pipeline_details.scroll_tree.scroll_node_or_ancestor(
942                    hit_test_result.external_scroll_id,
943                    scroll_location,
944                    scroll_type,
945                );
946                if let Some((external_scroll_id, offset)) = scroll_result {
947                    // We would like to cache the hit test for the node that that actually scrolls
948                    // while panning, which we don't know until right now (as some nodes
949                    // might be at the end of their scroll area). In particular, directionality of
950                    // scroll matters. That's why this is done here and not as soon as the touch
951                    // starts.
952                    self.touch_handler.set_hit_test_result_cache_value(
953                        hit_test_result.clone(),
954                        self.device_pixels_per_page_pixel(),
955                    );
956                    return Some(ScrollResult {
957                        hit_test_result,
958                        external_scroll_id,
959                        offset,
960                    });
961                }
962            }
963        }
964        None
965    }
966
967    /// Scroll the viewport (root pipeline, root scroll node) of this WebView, but first
968    /// attempting to pan the pinch zoom viewport. This is called when processing
969    /// key-based scrolling from script.
970    pub(crate) fn scroll_viewport_by_delta(
971        &mut self,
972        delta: LayoutVector2D,
973    ) -> (PinchZoomResult, Vec<ScrollResult>) {
974        let device_pixels_per_page_pixel = self.device_pixels_per_page_pixel();
975        let delta_in_device_pixels = delta.cast_unit() * device_pixels_per_page_pixel;
976        let remaining = self.pinch_zoom.pan_with_device_scroll(
977            Scroll::Delta(delta_in_device_pixels.into()),
978            device_pixels_per_page_pixel,
979        );
980
981        let pinch_zoom_result = match remaining == delta_in_device_pixels {
982            true => PinchZoomResult::DidNotPinchZoom,
983            false => PinchZoomResult::DidPinchZoom,
984        };
985        if remaining == Vector2D::zero() {
986            return (pinch_zoom_result, vec![]);
987        }
988
989        let Some(root_pipeline_id) = self.root_pipeline_id else {
990            return (pinch_zoom_result, vec![]);
991        };
992        let Some(root_pipeline) = self.pipelines.get_mut(&root_pipeline_id) else {
993            return (pinch_zoom_result, vec![]);
994        };
995
996        let remaining = remaining / device_pixels_per_page_pixel;
997        let Some((external_scroll_id, offset)) = root_pipeline.scroll_tree.scroll_node_or_ancestor(
998            ExternalScrollId(0, root_pipeline_id.into()),
999            ScrollLocation::Delta(remaining.cast_unit()),
1000            // These are initiated only by keyboard events currently.
1001            ScrollType::InputEvents,
1002        ) else {
1003            return (pinch_zoom_result, vec![]);
1004        };
1005
1006        let hit_test_result = PaintHitTestResult {
1007            pipeline_id: root_pipeline_id,
1008            // It's difficult to get a good value for this as it needs to be piped
1009            // all the way through script and back here.
1010            point_in_viewport: Default::default(),
1011            external_scroll_id,
1012        };
1013
1014        self.send_scroll_positions_to_layout_for_pipeline(root_pipeline_id, external_scroll_id);
1015
1016        if pinch_zoom_result == PinchZoomResult::DidPinchZoom {
1017            self.send_pinch_zoom_infos_to_script();
1018        }
1019
1020        let scroll_result = ScrollResult {
1021            hit_test_result,
1022            external_scroll_id,
1023            offset,
1024        };
1025        (pinch_zoom_result, vec![scroll_result])
1026    }
1027
1028    /// Send [`PinchZoom`] update to the script's root pipeline.
1029    fn send_pinch_zoom_infos_to_script(&self) {
1030        // Pinch-zoom is applicable only to the root pipeline.
1031        let Some(pipeline_id) = self.root_pipeline_id else {
1032            return;
1033        };
1034
1035        let pinch_zoom_infos = self.pinch_zoom.get_pinch_zoom_infos_for_script(
1036            self.device_pixels_per_page_pixel_not_including_pinch_zoom(),
1037        );
1038
1039        let _ = self.embedder_to_constellation_sender.send(
1040            EmbedderToConstellationMessage::UpdatePinchZoomInfos(pipeline_id, pinch_zoom_infos),
1041        );
1042    }
1043
1044    pub(crate) fn pinch_zoom(&self) -> PinchZoom {
1045        self.pinch_zoom
1046    }
1047
1048    fn set_pinch_zoom(&mut self, requested_pinch_zoom: PinchZoom) -> PinchZoomResult {
1049        if requested_pinch_zoom == self.pinch_zoom {
1050            return PinchZoomResult::DidNotPinchZoom;
1051        }
1052
1053        self.pinch_zoom = requested_pinch_zoom;
1054        PinchZoomResult::DidPinchZoom
1055    }
1056
1057    pub(crate) fn pinch_zoom_property_binding_key(&self) -> PropertyBindingKey<LayoutTransform> {
1058        self.pinch_zoom_property_binding_key
1059    }
1060
1061    /// Set the page zoom for this renderer, returning `true` if the value actually changed.
1062    pub(crate) fn set_page_zoom(
1063        &mut self,
1064        new_page_zoom: Scale<f32, CSSPixel, DeviceIndependentPixel>,
1065    ) -> bool {
1066        let new_page_zoom = new_page_zoom.clamp(MIN_PAGE_ZOOM, MAX_PAGE_ZOOM);
1067        let old_zoom = std::mem::replace(&mut self.page_zoom, new_page_zoom);
1068        if old_zoom == self.page_zoom {
1069            return false;
1070        }
1071        self.send_window_size_message();
1072        true
1073    }
1074
1075    /// The scale to use when displaying this [`WebViewRenderer`] in WebRender
1076    /// including both viewport scale (page zoom and hidpi scale) as well as any
1077    /// pinch zoom applied. This is based on the latest display list received,
1078    /// as page zoom changes are applied asynchronously and the rendered view
1079    /// should reflect the latest display list.
1080    pub(crate) fn device_pixels_per_page_pixel(&self) -> Scale<f32, CSSPixel, DevicePixel> {
1081        let viewport_scale = self
1082            .root_pipeline_id
1083            .and_then(|pipeline_id| self.pipelines.get(&pipeline_id))
1084            .and_then(|pipeline| pipeline.viewport_scale)
1085            .unwrap_or_else(|| self.page_zoom * self.hidpi_scale_factor);
1086        viewport_scale * self.pinch_zoom.zoom_factor()
1087    }
1088
1089    /// The current viewport scale (hidpi scale and page zoom and not pinch
1090    /// zoom) based on the current setting of the WebView. Note that this may
1091    /// not be the rendered viewport zoom as that is based on the latest display
1092    /// list and zoom changes are applied asynchronously.
1093    pub(crate) fn device_pixels_per_page_pixel_not_including_pinch_zoom(
1094        &self,
1095    ) -> Scale<f32, CSSPixel, DevicePixel> {
1096        self.page_zoom * self.hidpi_scale_factor
1097    }
1098
1099    /// Adjust the pinch zoom of the [`WebView`] by the given zoom delta.
1100    pub(crate) fn adjust_pinch_zoom(&mut self, magnification: f32, center: DevicePoint) {
1101        if magnification == 1.0 {
1102            return;
1103        }
1104
1105        self.pending_scroll_zoom_events
1106            .push(ScrollZoomEvent::PinchZoom(magnification, center));
1107    }
1108
1109    fn send_window_size_message(&self) {
1110        // The device pixel ratio used by the style system should include the scale from page pixels
1111        // to device pixels, but not including any pinch zoom.
1112        let device_pixel_ratio = self.device_pixels_per_page_pixel_not_including_pinch_zoom();
1113        // From <https://www.w3.org/TR/css-viewport-1/#actual-viewport>:
1114        // This is the viewport you get after processing the viewport <meta> tag.
1115        let layout_viewport = self.rect.size().to_f32() /
1116            (device_pixel_ratio * Scale::new(self.viewport_description.initial_scale.get()));
1117        let _ = self.embedder_to_constellation_sender.send(
1118            EmbedderToConstellationMessage::ChangeViewportDetails(
1119                self.id,
1120                ViewportDetails {
1121                    hidpi_scale_factor: device_pixel_ratio,
1122                    size: layout_viewport,
1123                    device_size: self.screen_size,
1124                },
1125                WindowSizeType::Resize,
1126            ),
1127        );
1128    }
1129
1130    /// Set the `hidpi_scale_factor` for this renderer, returning `true` if the value actually changed.
1131    pub(crate) fn set_hidpi_scale_factor(
1132        &mut self,
1133        new_scale: Scale<f32, DeviceIndependentPixel, DevicePixel>,
1134    ) -> bool {
1135        let old_scale_factor = std::mem::replace(&mut self.hidpi_scale_factor, new_scale);
1136        if self.hidpi_scale_factor == old_scale_factor {
1137            return false;
1138        }
1139
1140        self.send_window_size_message();
1141        true
1142    }
1143
1144    /// Set the `screen_size` for this renderer, returning `true` if the value actually changed.
1145    pub(crate) fn set_screen_size(&mut self, new_size: Size2D<f32, DevicePixel>) -> bool {
1146        if self.screen_size == new_size {
1147            return false;
1148        }
1149        self.screen_size = new_size;
1150
1151        self.send_window_size_message();
1152        true
1153    }
1154
1155    /// Set the `rect` for this renderer, returning `true` if the value actually changed.
1156    pub(crate) fn set_rect(&mut self, new_rect: DeviceRect) -> bool {
1157        let old_rect = std::mem::replace(&mut self.rect, new_rect);
1158        if old_rect.size() != self.rect.size() {
1159            self.send_window_size_message();
1160            self.pinch_zoom.resize_unscaled_viewport(new_rect);
1161            self.send_pinch_zoom_infos_to_script();
1162        }
1163        old_rect != self.rect
1164    }
1165
1166    pub fn set_viewport_description(&mut self, viewport_description: ViewportDescription) {
1167        self.viewport_description = viewport_description;
1168        self.send_window_size_message();
1169        self.adjust_pinch_zoom(
1170            self.viewport_description.initial_scale.get(),
1171            DevicePoint::origin(),
1172        );
1173    }
1174
1175    pub(crate) fn scroll_trees_memory_usage(
1176        &self,
1177        ops: &mut malloc_size_of::MallocSizeOfOps,
1178    ) -> usize {
1179        self.pipelines
1180            .values()
1181            .map(|pipeline| pipeline.scroll_tree.size_of(ops))
1182            .sum::<usize>()
1183    }
1184
1185    pub(crate) fn notify_input_event_handled(
1186        &mut self,
1187        repaint_reason: &Cell<RepaintReason>,
1188        id: InputEventId,
1189        result: InputEventResult,
1190    ) {
1191        if let Some(pending_touch_input_event) =
1192            self.touch_handler.take_pending_touch_input_event(id)
1193        {
1194            self.on_touch_event_processed(pending_touch_input_event, result);
1195            self.touch_handler
1196                .add_touch_move_refresh_observer_if_necessary(
1197                    self.refresh_driver.clone(),
1198                    repaint_reason,
1199                );
1200        }
1201
1202        if let Some(wheel_event) = self.pending_wheel_events.remove(&id) &&
1203            !result.contains(InputEventResult::DefaultPrevented)
1204        {
1205            // A scroll delta for a wheel event is the inverse of the wheel delta.
1206            let scroll_delta =
1207                DeviceVector2D::new(-wheel_event.delta.x as f32, -wheel_event.delta.y as f32);
1208            self.notify_scroll_event(Scroll::Delta(scroll_delta.into()), wheel_event.point);
1209        }
1210    }
1211
1212    /// Get the transform from page to device pixels of this [`WebViewRenderer`]
1213    /// incorporating the device pixel ratio, page zoom, and pinch zoom.
1214    pub(crate) fn root_transform(&self) -> LayoutTransform {
1215        let pinch_zoom_transform = self.pinch_zoom.transform().to_untyped();
1216        let device_pixels_per_page_pixel_not_including_pinch_zoom = self
1217            .device_pixels_per_page_pixel_not_including_pinch_zoom()
1218            .get();
1219
1220        LayoutTransform::scale(
1221            device_pixels_per_page_pixel_not_including_pinch_zoom,
1222            device_pixels_per_page_pixel_not_including_pinch_zoom,
1223            1.0,
1224        )
1225        .then(&LayoutTransform::from_untyped(
1226            &pinch_zoom_transform.to_3d(),
1227        ))
1228    }
1229
1230    /// If the pipeline is in the current frame tree, find its parent [`PipelineId`] and
1231    /// [`PipelineDetails`]. If it is not in the current frame tree return `None`.
1232    pub(crate) fn parent_pipeline(
1233        &self,
1234        pipeline_id: PipelineId,
1235    ) -> Option<(PipelineId, &PipelineDetails)> {
1236        let parent_id = self.pipelines.get(&pipeline_id)?.parent_pipeline_id?;
1237        let parent = self.pipelines.get(&parent_id)?;
1238        parent
1239            .children
1240            .contains(&pipeline_id)
1241            .then_some((parent_id, parent))
1242    }
1243
1244    /// Map a rectangle in pipeline viewport coordinates in the pipeline specified by the given
1245    /// [`PipelineId`] into device coordinates relative to the WebView origin.
1246    pub(crate) fn map_rect_to_device_pixel(
1247        &self,
1248        mut pipeline_id: PipelineId,
1249        rect: Rect<Au, CSSPixel>,
1250    ) -> DeviceRect {
1251        let mut transform = FastLayoutTransform::identity();
1252        while Some(pipeline_id) != self.root_pipeline_id {
1253            let Some((parent_pipeline_id, parent_details)) = self.parent_pipeline(pipeline_id)
1254            else {
1255                break;
1256            };
1257            let Some((iframe_spatial_node, iframe_rect)) =
1258                parent_details.iframes.get(&(pipeline_id.into()))
1259            else {
1260                break;
1261            };
1262
1263            let pipeline_transform = &parent_details
1264                .scroll_tree
1265                .cumulative_node_to_root_transform(*iframe_spatial_node);
1266            transform = transform
1267                .then_translate(iframe_rect.top_left().to_vector())
1268                .then(pipeline_transform);
1269
1270            pipeline_id = parent_pipeline_id;
1271        }
1272
1273        let transform = transform.to_transform().then(&self.root_transform());
1274        let rect = transform
1275            .outer_transformed_rect(&au_rect_to_f32_rect(rect.cast_unit()))
1276            .unwrap_or_default()
1277            .to_box2d()
1278            .cast_unit();
1279        let webview_max_point = DevicePoint::zero() + self.rect.size().to_vector();
1280        Box2D::new(
1281            rect.min.clamp(DevicePoint::zero(), webview_max_point),
1282            rect.max.clamp(DevicePoint::zero(), webview_max_point),
1283        )
1284    }
1285}
1286
1287#[derive(Clone, Copy, Debug, PartialEq)]
1288pub struct UnknownWebView(pub WebViewId);