bao-servo-script 0.5.32

A component of the servo web-engine.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

//! Methods for layout of node

use atomic_refcell::AtomicRef;
use html5ever::ns;
use layout_api::{
    GenericLayoutData, HTMLCanvasData, HTMLMediaData, LayoutElementType, LayoutNodeType,
    SVGElementData,
};
use net_traits::image_cache::Image;
use pixels::ImageMetadata;
use script_bindings::codegen::InheritTypes::{
    ElementTypeId, HTMLElementTypeId, SVGElementTypeId, SVGGraphicsElementTypeId,
};
use servo_base::id::{BrowsingContextId, PipelineId};
use servo_base::text::{RangeAny, Utf16CodeUnits, Utf32CodeUnits};
use servo_url::ServoUrl;
use style::dom::OpaqueNode;
use style::selector_parser::PseudoElement;
use xml5ever::local_name;

use crate::dom::bindings::inheritance::{CharacterDataTypeId, NodeTypeId};
use crate::dom::bindings::root::{LayoutDom, ToLayout, ToLayoutOptional};
use crate::dom::document::Document;
use crate::dom::element::Element;
use crate::dom::html::form_controls::htmlinputelement::HTMLInputElement;
use crate::dom::html::htmlcanvaselement::HTMLCanvasElement;
use crate::dom::html::htmlelement::HTMLElement;
use crate::dom::html::htmliframeelement::HTMLIFrameElement;
use crate::dom::html::htmlimageelement::HTMLImageElement;
use crate::dom::html::htmlslotelement::HTMLSlotElement;
use crate::dom::html::htmltextareaelement::HTMLTextAreaElement;
use crate::dom::html::htmlvideoelement::HTMLVideoElement;
use crate::dom::shadowroot::shadowroot::ShadowRoot;
use crate::dom::svg::svgsvgelement::SVGSVGElement;
use crate::dom::text::Text;
use crate::dom::{Node, NodeFlags};

impl<'dom> LayoutDom<'dom, Node> {
    #[inline]
    #[expect(unsafe_code)]
    pub(crate) fn parent_node_ref(self) -> Option<LayoutDom<'dom, Node>> {
        unsafe { self.unsafe_get().parent_node().to_layout() }
    }

    #[inline]
    pub(crate) fn type_id_for_layout(self) -> NodeTypeId {
        self.unsafe_get().type_id()
    }

    #[inline]
    pub(crate) fn is_element_for_layout(&self) -> bool {
        (*self).is::<Element>()
    }

    pub(crate) fn is_text_node_for_layout(&self) -> bool {
        matches!(
            self.type_id_for_layout(),
            NodeTypeId::CharacterData(CharacterDataTypeId::Text(..))
        )
    }

    #[inline]
    pub(crate) fn composed_parent_node_ref(self) -> Option<LayoutDom<'dom, Node>> {
        let parent = self.parent_node_ref();
        if let Some(parent) = parent &&
            let Some(shadow_root) = parent.downcast::<ShadowRoot>()
        {
            return Some(shadow_root.get_host_for_layout().upcast());
        }
        parent
    }

    #[inline]
    pub(crate) fn traversal_parent(self) -> Option<LayoutDom<'dom, Element>> {
        if let Some(assigned_slot) = self.assigned_slot_for_layout() {
            return Some(assigned_slot.upcast());
        }
        let parent = self.parent_node_ref()?;
        if let Some(shadow) = parent.downcast::<ShadowRoot>() {
            return Some(shadow.get_host_for_layout());
        };
        parent.downcast()
    }

    #[inline]
    #[expect(unsafe_code)]
    pub(crate) fn first_child_ref(self) -> Option<LayoutDom<'dom, Node>> {
        unsafe { self.unsafe_get().first_child().to_layout() }
    }

    #[inline]
    #[expect(unsafe_code)]
    pub(crate) fn last_child_ref(self) -> Option<LayoutDom<'dom, Node>> {
        unsafe { self.unsafe_get().last_child().to_layout() }
    }

    #[inline]
    #[expect(unsafe_code)]
    pub(crate) fn prev_sibling_ref(self) -> Option<LayoutDom<'dom, Node>> {
        unsafe { self.unsafe_get().prev_sibling().to_layout() }
    }

    #[inline]
    #[expect(unsafe_code)]
    pub(crate) fn next_sibling_ref(self) -> Option<LayoutDom<'dom, Node>> {
        unsafe { self.unsafe_get().next_sibling().to_layout() }
    }

    #[inline]
    #[expect(unsafe_code)]
    pub(crate) fn owner_doc_for_layout(self) -> LayoutDom<'dom, Document> {
        unsafe { self.unsafe_get().get_owner_doc().to_layout().unwrap() }
    }

    #[inline]
    #[expect(unsafe_code)]
    pub(crate) fn containing_shadow_root_for_layout(self) -> Option<LayoutDom<'dom, ShadowRoot>> {
        unsafe {
            self.unsafe_get()
                .get_rare_data()
                .borrow_for_layout()
                .as_ref()?
                .containing_shadow_root
                .as_ref()
                .map(|sr| sr.to_layout())
        }
    }

    #[inline]
    #[expect(unsafe_code)]
    pub(crate) fn assigned_slot_for_layout(self) -> Option<LayoutDom<'dom, HTMLSlotElement>> {
        unsafe {
            self.unsafe_get()
                .get_rare_data()
                .borrow_for_layout()
                .as_ref()?
                .slottable_data
                .assigned_slot
                .as_ref()
                .map(|assigned_slot| assigned_slot.to_layout())
        }
    }

    // FIXME(nox): get_flag/set_flag (especially the latter) are not safe because
    // they mutate stuff while values of this type can be used from multiple
    // threads at once, this should be revisited.

    #[inline]
    #[expect(unsafe_code)]
    pub(crate) unsafe fn get_flag(self, flag: NodeFlags) -> bool {
        (self.unsafe_get()).flags().get().contains(flag)
    }

    #[inline]
    #[expect(unsafe_code)]
    pub(crate) unsafe fn set_flag(self, flag: NodeFlags, value: bool) {
        let this = self.unsafe_get();
        let mut flags = (this).flags().get();

        if value {
            flags.insert(flag);
        } else {
            flags.remove(flag);
        }

        (this).flags().set(flags);
    }

    #[inline]
    #[expect(unsafe_code)]
    pub(crate) fn layout_data(self) -> Option<&'dom GenericLayoutData> {
        unsafe {
            self.unsafe_get()
                .layout_data()
                .borrow_for_layout()
                .as_deref()
        }
    }

    /// Initialize the style data of this node.
    ///
    /// # Safety
    ///
    /// This method is unsafe because it modifies the given node during
    /// layout. Callers should ensure that no other layout thread is
    /// attempting to read or modify the opaque layout data of this node.
    #[inline]
    #[expect(unsafe_code)]
    pub(crate) unsafe fn initialize_layout_data(self, new_data: Box<GenericLayoutData>) {
        let data = unsafe { self.unsafe_get().layout_data().borrow_mut_for_layout() };
        debug_assert!(data.is_none());
        *data = Some(new_data);
    }

    /// Clear the style and opaque layout data of this node.
    ///
    /// # Safety
    ///
    /// This method is unsafe because it modifies the given node during
    /// layout. Callers should ensure that no other layout thread is
    /// attempting to read or modify the opaque layout data of this node.
    #[inline]
    #[expect(unsafe_code)]
    pub(crate) unsafe fn clear_layout_data(self) {
        unsafe {
            self.unsafe_get()
                .layout_data()
                .borrow_mut_for_layout()
                .take();
        }
    }

    /// Whether this element serve as a container of editable text for a text input
    /// that is implemented as an UA widget.
    pub(crate) fn is_single_line_text_inner_editor(&self) -> bool {
        matches!(
            self.implemented_pseudo_element(),
            Some(PseudoElement::ServoTextControlInnerEditor)
        )
    }

    /// Whether this element serve as a container of any text inside a text input
    /// that is implemented as an UA widget.
    pub(crate) fn is_text_container_of_single_line_input(&self) -> bool {
        let is_single_line_text_inner_placeholder = matches!(
            self.implemented_pseudo_element(),
            Some(PseudoElement::Placeholder)
        );
        // Currently `::placeholder` is only implemented for single line text input element.
        debug_assert!(
            !is_single_line_text_inner_placeholder ||
                self.containing_shadow_root_for_layout()
                    .map(|root| root.get_host_for_layout())
                    .map(|host| host.downcast::<HTMLInputElement>())
                    .is_some()
        );

        self.is_single_line_text_inner_editor() || is_single_line_text_inner_placeholder
    }

    pub(crate) fn text_content(self) -> AtomicRef<'dom, str> {
        self.downcast::<Text>()
            .expect("Called LayoutDom::text_content on non-Text node!")
            .upcast()
            .data_for_layout()
    }

    /// Whether this node is an editing host, in a layout-safe form for box tree
    /// construction. This is the layout thread mirror of `Node::is_editing_host` +
    /// `HTMLElement::is_editing_host`: an HTML element with its `contenteditable`
    /// attribute in the true or plaintext-only state is an editing host, unless an
    /// inclusive ancestor of its parent is part of an editable region (a nested
    /// `contenteditable` is a no-op; the outer host owns the region) or design mode
    /// makes the document itself the host.
    ///
    /// This reads only `contenteditable` attribute states and the document design
    /// mode flag via `*_for_layout` accessors; it cannot call the script predicate
    /// because that walks the tree through `GetParentNode()`, which creates
    /// `DomRoot`s on the layout thread. Unlike the script predicate this does not
    /// consider `EditContext`-associated elements.
    pub(crate) fn is_editing_host_for_layout(self) -> bool {
        let Some(element) = self.downcast::<HTMLElement>() else {
            return false;
        };
        if !matches!(
            content_editable_state_for_layout(element.upcast()),
            ContentEditableState::True | ContentEditableState::PlaintextOnly
        ) {
            return false;
        }

        // > node itself, if node is an editing host; or the nearest ancestor of
        // > node that is an editing host, if node is editable.
        //
        // The parent chain must not be part of an editable region: walking the
        // inclusive ancestors of the parent, the first `contenteditable` state
        // boundary decides (`Node::editing_host_of`). A `contenteditable="false"`
        // element is an editing boundary, so we are a host; an element in the true
        // or plaintext-only state owns the editable region, so we are not.
        let mut ancestor = self.parent_node_ref();
        while let Some(node) = ancestor {
            if node
                .downcast::<Document>()
                .is_some_and(|document| document.unsafe_get().design_mode_enabled())
            {
                // Design mode makes the document itself an editing host.
                return false;
            }
            if let Some(html_element) = node.downcast::<HTMLElement>() {
                match content_editable_state_for_layout(html_element.upcast()) {
                    ContentEditableState::False => return true,
                    ContentEditableState::True | ContentEditableState::PlaintextOnly => {
                        return false
                    },
                    ContentEditableState::Inherit => {},
                }
            }
            ancestor = node.parent_node_ref();
        }
        true
    }

    #[expect(unsafe_code)]
    pub(crate) fn selection_for_text_node(&self) -> Option<RangeAny<Utf32CodeUnits>> {
        if let Some(shadow_root) = self.containing_shadow_root_for_layout() {
            let host = shadow_root.get_host_for_layout();
            if let Some(input) = host.downcast::<HTMLInputElement>() {
                return input.selection_for_layout();
            }
            if let Some(textarea) = host.downcast::<HTMLTextAreaElement>() {
                return textarea.selection_for_layout();
            }
        }

        let unsafe_self = self.unsafe_get();
        if !unsafe_self.get_flag(NodeFlags::OVERLAPS_DOCUMENT_SELECTION) ||
            unsafe_self.get_flag(NodeFlags::SELECTION_INHIBITED)
        {
            return None;
        }

        let text_node = self.downcast::<Text>()?;
        let text = text_node.upcast().data_for_layout();
        let selection = self.owner_doc_for_layout().visible_selection_for_layout()?;
        let range = selection.range_for_layout();

        let range = range.as_ref()?;
        let is_start_node = unsafe { range.start.container.to_layout() } == *self;
        let is_end_node = unsafe { range.end.container.to_layout() } == *self;

        let start =
            is_start_node.then(|| Utf16CodeUnits(range.start.offset).to_utf32_code_units_in(&text));
        let end =
            is_end_node.then(|| Utf16CodeUnits(range.end.offset).to_utf32_code_units_in(&text));
        Some(RangeAny::new(start, end))
    }

    pub(crate) fn text_node_paints_caret(&self) -> bool {
        if let Some(shadow_root) = self.containing_shadow_root_for_layout() {
            let host = shadow_root.get_host_for_layout();
            if host.is::<HTMLInputElement>() || host.is::<HTMLTextAreaElement>() {
                // This is the cases where, if `selection_for_text_node` returns a selection
                // it is a `TextInput` selection
                return true;
            }
        }
        // This is the cases where, if `selection_for_text_node` returns a selection
        // it is a document selection.
        // For now, never paint a caret for document selection.
        // This will change as we improve `contenteditable` support.
        false
    }

    pub(crate) fn replaced_is_selected(&self) -> bool {
        let unsafe_self = self.unsafe_get();
        unsafe_self.get_flag(NodeFlags::OVERLAPS_DOCUMENT_SELECTION) &&
            !unsafe_self.get_flag(NodeFlags::SELECTION_INHIBITED)
    }

    pub(crate) fn image_url(self) -> Option<ServoUrl> {
        self.downcast::<HTMLImageElement>()
            .expect("not an image!")
            .image_url()
    }

    pub(crate) fn image_data(self) -> Option<(Option<Image>, Option<ImageMetadata>)> {
        self.downcast::<HTMLImageElement>().map(|e| e.image_data())
    }

    pub(crate) fn image_density(self) -> Option<f64> {
        self.downcast::<HTMLImageElement>()
            .expect("not an image!")
            .image_density()
    }

    pub(crate) fn showing_broken_image_icon(self) -> bool {
        self.downcast::<HTMLImageElement>()
            .map(|image_element| image_element.showing_broken_image_icon())
            .unwrap_or_default()
    }

    pub(crate) fn canvas_data(self) -> Option<HTMLCanvasData> {
        self.downcast::<HTMLCanvasElement>()
            .map(|canvas| canvas.data())
    }

    pub(crate) fn media_data(self) -> Option<HTMLMediaData> {
        self.downcast::<HTMLVideoElement>()
            .map(|media| media.data())
    }

    pub(crate) fn svg_data(self) -> Option<SVGElementData<'dom>> {
        self.downcast::<SVGSVGElement>().map(|svg| svg.data())
    }

    pub(crate) fn iframe_browsing_context_id(self) -> Option<BrowsingContextId> {
        self.downcast::<HTMLIFrameElement>()
            .and_then(|iframe_element| iframe_element.browsing_context_id())
    }

    pub(crate) fn iframe_pipeline_id(self) -> Option<PipelineId> {
        self.downcast::<HTMLIFrameElement>()
            .and_then(|iframe_element| iframe_element.pipeline_id())
    }

    #[expect(unsafe_code)]
    pub(crate) fn opaque(self) -> OpaqueNode {
        unsafe { OpaqueNode(self.get_jsobject() as usize) }
    }

    #[expect(unsafe_code)]
    pub(crate) fn implemented_pseudo_element(&self) -> Option<PseudoElement> {
        unsafe {
            self.unsafe_get()
                .get_rare_data()
                .borrow_for_layout()
                .as_ref()
                .and_then(|rare_data| rare_data.implemented_pseudo_element)
        }
    }

    pub(crate) fn is_in_ua_widget(&self) -> bool {
        self.unsafe_get().is_in_ua_widget()
    }

    pub(crate) fn is_root_of_user_agent_widget(&self) -> bool {
        self.downcast::<Element>().is_some_and(|element| {
            element
                .get_shadow_root_for_layout()
                .is_some_and(|shadow_root| shadow_root.is_user_agent_widget())
        })
    }

    pub(crate) fn children_count(&self) -> u32 {
        self.unsafe_get().children_count()
    }
}

/// The `contenteditable` attribute state of an element
/// (<https://html.spec.whatwg.org/multipage/#attr-contenteditable>).
#[derive(PartialEq)]
enum ContentEditableState {
    True,
    PlaintextOnly,
    False,
    Inherit,
}

/// The `contenteditable` attribute state of this element, in a layout-safe form:
/// an enumerated attribute matched ASCII case-insensitively, with missing or
/// invalid values in the inherit state.
fn content_editable_state_for_layout(element: LayoutDom<'_, Element>) -> ContentEditableState {
    let Some(value) = element.get_attr_val_for_layout(&ns!(), &local_name!("contenteditable"))
    else {
        return ContentEditableState::Inherit;
    };
    if value.is_empty() || value.eq_ignore_ascii_case("true") {
        ContentEditableState::True
    } else if value.eq_ignore_ascii_case("plaintext-only") {
        ContentEditableState::PlaintextOnly
    } else if value.eq_ignore_ascii_case("false") {
        ContentEditableState::False
    } else {
        ContentEditableState::Inherit
    }
}

pub(crate) struct NodeTypeIdWrapper(pub(crate) NodeTypeId);

impl From<NodeTypeIdWrapper> for LayoutNodeType {
    #[inline(always)]
    fn from(node_type: NodeTypeIdWrapper) -> LayoutNodeType {
        match node_type.0 {
            NodeTypeId::Element(e) => LayoutNodeType::Element(ElementTypeIdWrapper(e).into()),
            NodeTypeId::CharacterData(CharacterDataTypeId::Text(_)) => LayoutNodeType::Text,
            x => unreachable!("Layout should not traverse nodes of type {:?}", x),
        }
    }
}

struct ElementTypeIdWrapper(ElementTypeId);

impl From<ElementTypeIdWrapper> for LayoutElementType {
    #[inline(always)]
    fn from(element_type: ElementTypeIdWrapper) -> LayoutElementType {
        match element_type.0 {
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBodyElement) => {
                LayoutElementType::HTMLBodyElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement) => {
                LayoutElementType::HTMLButtonElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBRElement) => {
                LayoutElementType::HTMLBRElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLCanvasElement) => {
                LayoutElementType::HTMLCanvasElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLHtmlElement) => {
                LayoutElementType::HTMLHtmlElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLIFrameElement) => {
                LayoutElementType::HTMLIFrameElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLImageElement) => {
                LayoutElementType::HTMLImageElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLMediaElement(_)) => {
                LayoutElementType::HTMLMediaElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement) => {
                LayoutElementType::HTMLInputElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptGroupElement) => {
                LayoutElementType::HTMLOptGroupElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptionElement) => {
                LayoutElementType::HTMLOptionElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLObjectElement) => {
                LayoutElementType::HTMLObjectElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLParagraphElement) => {
                LayoutElementType::HTMLParagraphElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLPreElement) => {
                LayoutElementType::HTMLPreElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement) => {
                LayoutElementType::HTMLSelectElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableCellElement) => {
                LayoutElementType::HTMLTableCellElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableColElement) => {
                LayoutElementType::HTMLTableColElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableElement) => {
                LayoutElementType::HTMLTableElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableRowElement) => {
                LayoutElementType::HTMLTableRowElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableSectionElement) => {
                LayoutElementType::HTMLTableSectionElement
            },
            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement) => {
                LayoutElementType::HTMLTextAreaElement
            },
            ElementTypeId::SVGElement(SVGElementTypeId::SVGGraphicsElement(
                SVGGraphicsElementTypeId::SVGImageElement,
            )) => LayoutElementType::SVGImageElement,
            ElementTypeId::SVGElement(SVGElementTypeId::SVGGraphicsElement(
                SVGGraphicsElementTypeId::SVGSVGElement,
            )) => LayoutElementType::SVGSVGElement,
            _ => LayoutElementType::Element,
        }
    }
}