Skip to main content

script/dom/document/
document_overlay_handler.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::default::Default;
6
7use embedder_traits::EmbedderMsg;
8use html5ever::{local_name, ns};
9use js::context::{JSContext, NoGC};
10use js::realm::CurrentRealm;
11use script_bindings::cell::DomRefCell;
12use servo_config::pref;
13use stylo_dom::ElementState;
14
15use crate::dom::RootedPromise;
16use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
17use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
18use crate::dom::bindings::error::Error;
19use crate::dom::bindings::inheritance::Castable;
20use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
21use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
22use crate::dom::document::document::Document;
23use crate::dom::element::element::Element;
24use crate::dom::event::event::{EventBubbles, EventCancelable, EventComposed};
25use crate::dom::event::eventtarget::EventTarget;
26use crate::dom::html::interactive::htmldialogelement::HTMLDialogElement;
27use crate::dom::node::NodeTraits;
28use crate::dom::promise::Promise;
29use crate::messaging::{CommonScriptMsg, MainThreadScriptMsg};
30use crate::runtime::script_runtime::ScriptThreadEventCategory;
31use crate::tasks::task::TaskOnce;
32use crate::tasks::task_source::TaskSourceName;
33
34/// The [`DocumentOverlayHandler`] is a structure responsible for overlays for
35/// the [`crate::Document`] and storing data related to overlays. It exists to
36/// decrease the size of the [`crate::Document`] structure.
37#[derive(JSTraceable, MallocSizeOf)]
38#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
39pub(crate) struct DocumentOverlayHandler {
40    /// The [`Document`] this [`DocumentOverlayHandler`] belongs to.
41    document: Dom<Document>,
42    /// Entry node for fullscreen.
43    fullscreen_element: MutNullableDom<Element>,
44    /// <https://drafts.csswg.org/css-position-4/#document-top-layer>
45    top_layer: DomRefCell<Vec<Dom<Element>>>,
46    /// <https://drafts.csswg.org/css-position-4/#document-pending-top-layer-removals>
47    pending_top_layer_removals: DomRefCell<Vec<Dom<Element>>>,
48    /// <https://html.spec.whatwg.org/multipage/#blocked-by-a-modal-dialog>
49    topmost_modal: MutNullableDom<Element>,
50    /// <https://html.spec.whatwg.org/multipage/#open-dialogs-list>
51    open_dialogs_list: DomRefCell<Vec<Dom<HTMLDialogElement>>>,
52    /// <https://html.spec.whatwg.org/multipage/#dialog-pointerdown-target>
53    dialog_pointerdown_target: MutNullableDom<HTMLDialogElement>,
54}
55
56impl DocumentOverlayHandler {
57    pub(crate) fn new(document: &Document) -> Self {
58        Self {
59            document: Dom::from_ref(document),
60            fullscreen_element: MutNullableDom::new(None),
61            top_layer: Default::default(),
62            pending_top_layer_removals: Default::default(),
63            topmost_modal: Default::default(),
64            open_dialogs_list: Default::default(),
65            dialog_pointerdown_target: Default::default(),
66        }
67    }
68
69    pub(crate) fn fullscreen_element(&self) -> Option<DomRoot<Element>> {
70        self.fullscreen_element.get()
71    }
72
73    pub(crate) fn set_fullscreen_element(&self, element: Option<&Element>) {
74        self.fullscreen_element.set(element);
75    }
76
77    /// <https://fullscreen.spec.whatwg.org/#fully-exit-fullscreen>
78    pub(crate) fn fully_exit_fullscreen(&self, cx: &mut JSContext) {
79        // Step 1. If document’s fullscreen element is null, terminate these
80        // steps.
81        if self.fullscreen_element().is_none() {
82            return;
83        };
84
85        // TODO Step 2. Unfullscreen elements whose fullscreen flag is set,
86        // within document’s top layer, except for document’s fullscreen element.
87
88        // Step 3. Exit fullscreen document.
89        let _ = self.exit_fullscreen(cx);
90    }
91
92    /// <https://fullscreen.spec.whatwg.org/#dom-element-requestfullscreen>
93    pub(crate) fn enter_fullscreen(
94        &self,
95        cx: &mut CurrentRealm,
96        pending: &Element,
97    ) -> RootedPromise {
98        // Step 1
99        // > Let pendingDoc be this’s node document.
100        let document = pending.owner_document();
101
102        // Step 2
103        // > Let promise be a new promise.
104        let promise = Promise::new_in_realm(cx);
105
106        // Step 3
107        // > If pendingDoc is not fully active, then reject promise with a TypeError exception and return promise.
108        if !document.is_fully_active() {
109            promise.reject_error(cx, Error::Type(c"Document is not fully active".to_owned()));
110            return promise;
111        }
112
113        // Step 4
114        // > Let error be false.
115        let mut error = false;
116
117        // Step 5
118        // > If any of the following conditions are false, then set error to true:
119        {
120            // > - This’s namespace is the HTML namespace or this is an SVG svg or MathML math element. [SVG] [MATHML]
121            match *pending.namespace() {
122                ns!(mathml) => {
123                    if *pending.local_name() != local_name!("math") {
124                        error = true;
125                    }
126                },
127                ns!(svg) => {
128                    if *pending.local_name() != local_name!("svg") {
129                        error = true;
130                    }
131                },
132                ns!(html) => (),
133                _ => error = true,
134            }
135
136            // > - This is not a dialog element.
137            if pending.is::<HTMLDialogElement>() {
138                error = true;
139            }
140
141            // > - The fullscreen element ready check for this returns true.
142            if !pending.fullscreen_element_ready_check() {
143                error = true;
144            }
145
146            // > - Fullscreen is supported.
147            // <https://fullscreen.spec.whatwg.org/#fullscreen-is-supported>
148            // > Fullscreen is supported if there is no previously-established user preference, security risk, or platform limitation.
149            // TODO: Add checks for whether fullscreen is supported as definition.
150
151            // > - This’s relevant global object has transient activation or the algorithm is triggered by a user generated orientation change.
152            // TODO: implement screen orientation API
153            if !pending.owner_window().has_transient_activation() {
154                error = true;
155            }
156        }
157
158        if pref!(dom_fullscreen_test) {
159            // For reftests we just take over the current window,
160            // and don't try to really enter fullscreen.
161            info!("Tests don't really enter fullscreen.");
162        } else {
163            // TODO fullscreen is supported
164            // TODO This algorithm is allowed to request fullscreen.
165            warn!("Fullscreen not supported yet");
166        }
167
168        // Step 6
169        // > If error is false, then consume user activation given pendingDoc’s relevant global object.
170        if !error {
171            pending
172                .owner_window_unrooted(cx.no_gc())
173                .consume_user_activation();
174        }
175
176        // Step 8.
177        // > If error is false, then resize pendingDoc’s node navigable’s top-level traversable’s active document’s viewport’s dimensions,
178        // > optionally taking into account options["navigationUI"]:
179        // TODO(#21600): Improve spec compliance of steps 7-13 paralelism.
180        // TODO(#42064): Implement fullscreen options, and ensure that this is spec compliant for all embedder.
181        if !error {
182            let event = EmbedderMsg::NotifyFullscreenStateChanged(document.webview_id(), true);
183            document.send_to_embedder(event);
184        }
185
186        // Step 7
187        // > Return promise, and run the remaining steps in parallel.
188        let pipeline_id = self.document.window().pipeline_id();
189
190        let trusted_pending = Trusted::new(pending);
191        let trusted_pending_doc = Trusted::new(&*document);
192        let trusted_promise = TrustedPromise::from(&promise);
193        let handler = ElementPerformFullscreenEnter::new(
194            trusted_pending,
195            trusted_pending_doc,
196            trusted_promise,
197            error,
198        );
199        let script_msg = CommonScriptMsg::Task(
200            ScriptThreadEventCategory::EnterFullscreen,
201            handler,
202            Some(pipeline_id),
203            TaskSourceName::DOMManipulation,
204        );
205        let msg = MainThreadScriptMsg::Common(script_msg);
206        self.document
207            .window()
208            .main_thread_script_chan()
209            .send(msg)
210            .unwrap();
211
212        promise
213    }
214
215    /// <https://fullscreen.spec.whatwg.org/#exit-fullscreen>
216    pub(crate) fn exit_fullscreen(&self, cx: &mut JSContext) -> RootedPromise {
217        let document = &*self.document;
218
219        // Step 1
220        // > Let promise be a new promise
221        let mut realm = CurrentRealm::assert(cx);
222        let promise = Promise::new_in_realm(&mut realm);
223
224        // Step 2
225        // > If doc is not fully active or doc’s fullscreen element is null, then reject promise with a TypeError exception and return promise.
226        if !document.is_fully_active() || self.fullscreen_element().is_none() {
227            promise.reject_error(
228                cx,
229                Error::Type(
230                    c"No fullscreen element to exit or document is not fully active".to_owned(),
231                ),
232            );
233            return promise;
234        }
235
236        // TODO(#42067): Implement step 3-7, handling fullscreen's propagation across navigables.
237
238        let element = self.fullscreen_element().unwrap();
239        // Step 10
240        // > If resize is true, resize doc’s viewport to its "normal" dimensions.
241        // TODO(#21600): Improve spec compliance of steps 8-15 paralelism.
242        let event = EmbedderMsg::NotifyFullscreenStateChanged(document.webview_id(), false);
243        document.send_to_embedder(event);
244
245        // Step 8
246        // > Return promise, and run the remaining steps in parallel.
247        let trusted_element = Trusted::new(&*element);
248        let trusted_promise = TrustedPromise::from(&promise);
249        let handler = ElementPerformFullscreenExit::new(trusted_element, trusted_promise);
250        let pipeline_id = Some(self.document.window().pipeline_id());
251        let script_msg = CommonScriptMsg::Task(
252            ScriptThreadEventCategory::ExitFullscreen,
253            handler,
254            pipeline_id,
255            TaskSourceName::DOMManipulation,
256        );
257        let msg = MainThreadScriptMsg::Common(script_msg);
258        self.document
259            .window()
260            .main_thread_script_chan()
261            .send(msg)
262            .unwrap();
263
264        promise
265    }
266
267    /// <https://html.spec.whatwg.org/multipage/#allowed-to-use>
268    pub(crate) fn get_allow_fullscreen(&self) -> bool {
269        match self.document.browsing_context() {
270            // Step 1
271            None => false,
272            Some(_) => {
273                // Step 2
274                if self.document.window().is_top_level() {
275                    true
276                } else {
277                    // Step 3
278                    self.document
279                        .window()
280                        .GetFrameElement()
281                        .is_some_and(|el| el.has_attribute(&local_name!("allowfullscreen")))
282                }
283            },
284        }
285    }
286
287    pub(crate) fn open_dialogs_list_contains(&self, dialog: &HTMLDialogElement) -> bool {
288        self.open_dialogs_list
289            .borrow()
290            .iter()
291            .any(|open_dialog| &**open_dialog == dialog)
292    }
293
294    pub(crate) fn add_to_open_dialogs_list(&self, dialog: &HTMLDialogElement, no_gc: &NoGC) {
295        self.open_dialogs_list
296            .safe_borrow_mut(no_gc)
297            .push(Dom::from_ref(dialog));
298    }
299
300    pub(crate) fn remove_from_open_dialogs_list(&self, dialog: &HTMLDialogElement, no_gc: &NoGC) {
301        self.open_dialogs_list
302            .safe_borrow_mut(no_gc)
303            .retain(|open| &**open != dialog);
304    }
305
306    pub(crate) fn topmost_open_dialog(&self) -> Option<DomRoot<HTMLDialogElement>> {
307        self.open_dialogs_list
308            .borrow()
309            .last()
310            .map(|dialog| dialog.as_rooted())
311    }
312
313    pub(crate) fn dialog_pointerdown_target(&self) -> Option<DomRoot<HTMLDialogElement>> {
314        self.dialog_pointerdown_target.get()
315    }
316
317    pub(crate) fn set_dialog_pointerdown_target(&self, dialog: Option<&HTMLDialogElement>) {
318        self.dialog_pointerdown_target.set(dialog);
319    }
320
321    pub(crate) fn top_layer_contains(&self, element: &Element) -> bool {
322        self.top_layer
323            .borrow()
324            .iter()
325            .any(|top_layer_element| &**top_layer_element == element)
326    }
327
328    fn pending_top_layer_removals_contains(&self, element: &Element) -> bool {
329        self.pending_top_layer_removals
330            .borrow()
331            .iter()
332            .any(|pending_element| &**pending_element == element)
333    }
334
335    /// <https://drafts.csswg.org/css-position-4/#in-the-top-layer>
336    pub(crate) fn is_in_the_top_layer(&self, element: &Element) -> bool {
337        // > An element el is in the top layer if el is contained in its node document’s top layer
338        // > but not contained in its node document’s pending top layer removals.
339        self.top_layer_contains(element) && !self.pending_top_layer_removals_contains(element)
340    }
341
342    /// <https://drafts.csswg.org/css-position-4/#add-an-element-to-the-top-layer>
343    pub(crate) fn add_an_element_to_the_top_layer(&self, element: &Element, no_gc: &NoGC) {
344        // Step 1. Let doc be el’s node document.
345
346        // Step 2. If el is already contained in doc's top layer:
347        if self.top_layer_contains(element) {
348            // Step 2.1. Assert: el is also in doc's pending top layer removals. (Otherwise, this is
349            // a spec error.)
350            assert!(self.pending_top_layer_removals_contains(element));
351
352            // Step 2.2. Remove el from both doc's top layer and pending top layer removals.
353            self.top_layer
354                .safe_borrow_mut(no_gc)
355                .retain(|top_layer_element| &**top_layer_element != element);
356            self.pending_top_layer_removals
357                .safe_borrow_mut(no_gc)
358                .retain(|pending_element| &**pending_element != element);
359        }
360
361        // Step 3. Append el to doc's top layer.
362        self.top_layer
363            .safe_borrow_mut(no_gc)
364            .push(Dom::from_ref(element));
365
366        // TODO: Step 4. At the UA !important cascade origin, add a rule targeting el
367        // containing an overlay: auto declaration.
368
369        self.update_topmost_modal(no_gc);
370    }
371
372    /// <https://drafts.csswg.org/css-position-4/#request-an-element-to-be-removed-from-the-top-layer>
373    pub(crate) fn request_an_element_to_be_removed_from_the_top_layer(
374        &self,
375        element: &Element,
376        no_gc: &NoGC,
377    ) {
378        // Step 1. Let doc be el's node document.
379
380        // Step 2. If el is not contained doc's top layer, or el is already contained in doc's
381        // pending top layer removals, return.
382        if !self.top_layer_contains(element) || self.pending_top_layer_removals_contains(element) {
383            return;
384        }
385
386        // TODO: Step 3. Remove the UA !important overlay: auto rule targeting el.
387
388        // Step 4. Append el to doc's pending top layer removals.
389        self.pending_top_layer_removals
390            .safe_borrow_mut(no_gc)
391            .push(Dom::from_ref(element));
392
393        self.update_topmost_modal(no_gc);
394    }
395
396    /// <https://drafts.csswg.org/css-position-4/#remove-an-element-from-the-top-layer-immediately>
397    pub(crate) fn remove_an_element_from_the_top_layer_immediately(
398        &self,
399        element: &Element,
400        no_gc: &NoGC,
401    ) {
402        // Step 1. Let doc be el's node document.
403
404        // Step 2. Remove el from doc's top layer and pending top layer removals.
405        self.top_layer
406            .safe_borrow_mut(no_gc)
407            .retain(|top_layer_element| &**top_layer_element != element);
408        self.pending_top_layer_removals
409            .safe_borrow_mut(no_gc)
410            .retain(|pending_element| &**pending_element != element);
411
412        // TODO: Step 3. Remove the UA !important overlay: auto rule targeting el, if it exists.
413
414        self.update_topmost_modal(no_gc);
415    }
416
417    /// <https://drafts.csswg.org/css-position-4/#process-top-layer-removals>
418    pub(crate) fn process_top_layer_removals(&self, cx: &mut JSContext) {
419        // Step 1. For each element el in doc’s pending top layer removals: if el's computed value
420        // of overlay is none, or el is not rendered, remove from the top layer immediately el.
421        // TODO: Check `overlay` once it is supported.
422        let pending_removals: Vec<_> = self
423            .pending_top_layer_removals
424            .borrow()
425            .iter()
426            .map(|element| DomRoot::from_ref(&**element))
427            .collect();
428        for element in pending_removals {
429            if !element.has_css_layout_box(cx) {
430                self.remove_an_element_from_the_top_layer_immediately(&element, cx)
431            }
432        }
433    }
434
435    /// <https://html.spec.whatwg.org/multipage/#blocked-by-a-modal-dialog>
436    pub fn update_topmost_modal(&self, no_gc: &NoGC) {
437        // > A Document document is blocked by a modal dialog subject if subject is the topmost
438        // > dialog element in document's top layer.
439        let new_topmost_modal = self
440            .top_layer
441            .borrow()
442            .iter()
443            .rev()
444            .find(|element| {
445                element.state().contains(ElementState::MODAL) &&
446                    !self.pending_top_layer_removals_contains(element)
447            })
448            .map(|element| DomRoot::from_ref(&**element));
449        let old_topmost_modal = self.topmost_modal.get();
450
451        if let Some(old_topmost_modal) = old_topmost_modal {
452            old_topmost_modal.set_state(no_gc, ElementState::TOPMOST_MODAL, false);
453        }
454        if let Some(new_topmost_modal) = &new_topmost_modal {
455            new_topmost_modal.set_state(no_gc, ElementState::TOPMOST_MODAL, true);
456        }
457
458        self.topmost_modal.set(new_topmost_modal.as_deref());
459
460        // > While document is so blocked, every node that is connected to document, with the
461        // > exception of the subject element and its flat tree descendants, must become inert.
462        if let Some(document_element) = self.document.GetDocumentElement() {
463            let is_inert = new_topmost_modal.is_some() ||
464                document_element.has_attribute(&local_name!("inert"));
465            document_element.set_state(no_gc, ElementState::INERT, is_inert);
466        }
467    }
468
469    /// <https://html.spec.whatwg.org/multipage/#blocked-by-a-modal-dialog>
470    pub(crate) fn is_blocked_by_a_modal_dialog(&self) -> bool {
471        self.topmost_modal.get().is_some()
472    }
473}
474
475struct ElementPerformFullscreenEnter {
476    element: Trusted<Element>,
477    document: Trusted<Document>,
478    promise: TrustedPromise,
479    error: bool,
480}
481
482impl ElementPerformFullscreenEnter {
483    fn new(
484        element: Trusted<Element>,
485        document: Trusted<Document>,
486        promise: TrustedPromise,
487        error: bool,
488    ) -> Box<ElementPerformFullscreenEnter> {
489        Box::new(ElementPerformFullscreenEnter {
490            element,
491            document,
492            promise,
493            error,
494        })
495    }
496}
497
498impl TaskOnce for ElementPerformFullscreenEnter {
499    /// Step 9-14 of <https://fullscreen.spec.whatwg.org/#dom-element-requestfullscreen>
500    fn run_once(self, cx: &mut js::context::JSContext) {
501        let element = self.element.root();
502        let promise = self.promise.root(cx);
503        let document = element.owner_document();
504
505        // Step 9
506        // > If any of the following conditions are false, then set error to true:
507        // > - This’s node document is pendingDoc.
508        // > - The fullscreen element ready check for this returns true.
509        // Step 10
510        // > If error is true:
511        // > - Append (fullscreenerror, this) to pendingDoc’s list of pending fullscreen events.
512        // > - Reject promise with a TypeError exception and terminate these steps.
513        if self.document.root() != document ||
514            !element.fullscreen_element_ready_check() ||
515            self.error
516        {
517            // TODO(#31866): we should queue this and fire them in update the rendering.
518            document
519                .upcast::<EventTarget>()
520                .fire_event(cx, atom!("fullscreenerror"));
521            promise.reject_error(cx, Error::Type(c"fullscreen is not connected".to_owned()));
522            return;
523        }
524
525        // TODO(#42067): Implement step 11-13
526        // The following operations is based on the old version of the specs.
527        element.set_fullscreen_state(cx.no_gc(), true);
528        document
529            .overlay_handler()
530            .set_fullscreen_element(Some(&element));
531        document.upcast::<EventTarget>().fire_event_with_params(
532            cx,
533            atom!("fullscreenchange"),
534            EventBubbles::Bubbles,
535            EventCancelable::NotCancelable,
536            EventComposed::Composed,
537        );
538
539        // Step 14.
540        // > Resolve promise with undefined.
541        promise.resolve_native(cx, &());
542    }
543}
544
545struct ElementPerformFullscreenExit {
546    element: Trusted<Element>,
547    promise: TrustedPromise,
548}
549
550impl ElementPerformFullscreenExit {
551    fn new(
552        element: Trusted<Element>,
553        promise: TrustedPromise,
554    ) -> Box<ElementPerformFullscreenExit> {
555        Box::new(ElementPerformFullscreenExit { element, promise })
556    }
557}
558
559impl TaskOnce for ElementPerformFullscreenExit {
560    /// Step 9-16 of <https://fullscreen.spec.whatwg.org/#exit-fullscreen>
561    fn run_once(self, cx: &mut js::context::JSContext) {
562        let element = self.element.root();
563        let document = element.owner_document();
564        // Step 9.
565        // > Run the fully unlock the screen orientation steps with doc.
566        // TODO: Need to implement ScreenOrientation API first
567
568        // TODO(#42067): Implement step 10-15
569        // The following operations is based on the old version of the specs.
570        element.set_fullscreen_state(cx.no_gc(), false);
571        document.overlay_handler().set_fullscreen_element(None);
572        document.upcast::<EventTarget>().fire_event_with_params(
573            cx,
574            atom!("fullscreenchange"),
575            EventBubbles::Bubbles,
576            EventCancelable::NotCancelable,
577            EventComposed::Composed,
578        );
579
580        // Step 16
581        // > Resolve promise with undefined.
582        self.promise.root(cx).resolve_native(cx, &());
583    }
584}