/
document.rs
5186 lines (4614 loc) · 186 KB
/
document.rs
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* 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/. */
use crate::animation_timeline::AnimationTimeline;
use crate::animations::Animations;
use crate::document_loader::{DocumentLoader, LoadType};
use crate::dom::attr::Attr;
use crate::dom::beforeunloadevent::BeforeUnloadEvent;
use crate::dom::bindings::callback::ExceptionHandling;
use crate::dom::bindings::cell::{ref_filter_map, DomRefCell, Ref, RefMut};
use crate::dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEventBinding::BeforeUnloadEventMethods;
use crate::dom::bindings::codegen::Bindings::DocumentBinding::{
DocumentMethods, DocumentReadyState,
};
use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElementBinding::HTMLIFrameElementMethods;
use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use crate::dom::bindings::codegen::Bindings::NodeFilterBinding::NodeFilter;
use crate::dom::bindings::codegen::Bindings::PerformanceBinding::PerformanceMethods;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::ShadowRootMethods;
use crate::dom::bindings::codegen::Bindings::TouchBinding::TouchMethods;
use crate::dom::bindings::codegen::Bindings::WindowBinding::{
FrameRequestCallback, ScrollBehavior, WindowMethods,
};
use crate::dom::bindings::codegen::UnionTypes::{NodeOrString, StringOrElementCreationOptions};
use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
use crate::dom::bindings::num::Finite;
use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot, DomSlice, LayoutDom, MutNullableDom};
use crate::dom::bindings::str::{DOMString, USVString};
use crate::dom::bindings::xmlname::XMLName::InvalidXMLName;
use crate::dom::bindings::xmlname::{
namespace_from_domstring, validate_and_extract, xml_name_type,
};
use crate::dom::cdatasection::CDATASection;
use crate::dom::comment::Comment;
use crate::dom::compositionevent::CompositionEvent;
use crate::dom::cssstylesheet::CSSStyleSheet;
use crate::dom::customelementregistry::CustomElementDefinition;
use crate::dom::customevent::CustomEvent;
use crate::dom::documentfragment::DocumentFragment;
use crate::dom::documentorshadowroot::{DocumentOrShadowRoot, StyleSheetInDocument};
use crate::dom::documenttype::DocumentType;
use crate::dom::domimplementation::DOMImplementation;
use crate::dom::element::CustomElementCreationMode;
use crate::dom::element::{
Element, ElementCreator, ElementPerformFullscreenEnter, ElementPerformFullscreenExit,
};
use crate::dom::event::{Event, EventBubbles, EventCancelable, EventDefault, EventStatus};
use crate::dom::eventtarget::EventTarget;
use crate::dom::focusevent::FocusEvent;
use crate::dom::globalscope::GlobalScope;
use crate::dom::hashchangeevent::HashChangeEvent;
use crate::dom::htmlanchorelement::HTMLAnchorElement;
use crate::dom::htmlareaelement::HTMLAreaElement;
use crate::dom::htmlbaseelement::HTMLBaseElement;
use crate::dom::htmlbodyelement::HTMLBodyElement;
use crate::dom::htmlcollection::{CollectionFilter, HTMLCollection};
use crate::dom::htmlelement::HTMLElement;
use crate::dom::htmlembedelement::HTMLEmbedElement;
use crate::dom::htmlformelement::{FormControl, FormControlElementHelpers, HTMLFormElement};
use crate::dom::htmlheadelement::HTMLHeadElement;
use crate::dom::htmlhtmlelement::HTMLHtmlElement;
use crate::dom::htmliframeelement::HTMLIFrameElement;
use crate::dom::htmlimageelement::HTMLImageElement;
use crate::dom::htmlscriptelement::{HTMLScriptElement, ScriptResult};
use crate::dom::htmltitleelement::HTMLTitleElement;
use crate::dom::keyboardevent::KeyboardEvent;
use crate::dom::location::Location;
use crate::dom::messageevent::MessageEvent;
use crate::dom::mouseevent::MouseEvent;
use crate::dom::node::{self, document_from_node, window_from_node, CloneChildrenFlag};
use crate::dom::node::{Node, NodeDamage, NodeFlags, ShadowIncluding};
use crate::dom::nodeiterator::NodeIterator;
use crate::dom::nodelist::NodeList;
use crate::dom::pagetransitionevent::PageTransitionEvent;
use crate::dom::processinginstruction::ProcessingInstruction;
use crate::dom::promise::Promise;
use crate::dom::range::Range;
use crate::dom::selection::Selection;
use crate::dom::servoparser::ServoParser;
use crate::dom::shadowroot::ShadowRoot;
use crate::dom::storageevent::StorageEvent;
use crate::dom::stylesheetlist::{StyleSheetList, StyleSheetListOwner};
use crate::dom::text::Text;
use crate::dom::touch::Touch;
use crate::dom::touchevent::TouchEvent;
use crate::dom::touchlist::TouchList;
use crate::dom::treewalker::TreeWalker;
use crate::dom::uievent::UIEvent;
use crate::dom::virtualmethods::vtable_for;
use crate::dom::webglrenderingcontext::WebGLRenderingContext;
use crate::dom::wheelevent::WheelEvent;
use crate::dom::window::{ReflowReason, Window};
use crate::dom::windowproxy::WindowProxy;
use crate::fetch::FetchCanceller;
use crate::realms::{AlreadyInRealm, InRealm};
use crate::script_runtime::JSContext;
use crate::script_runtime::{CommonScriptMsg, ScriptThreadEventCategory};
use crate::script_thread::{MainThreadScriptMsg, ScriptThread};
use crate::stylesheet_set::StylesheetSetRef;
use crate::task::TaskBox;
use crate::task_source::{TaskSource, TaskSourceName};
use crate::timers::OneshotTimerCallback;
use canvas_traits::webgl::{self, SwapChainId, WebGLContextId, WebGLMsg};
use content_security_policy::{self as csp, CspList};
use cookie::Cookie;
use devtools_traits::ScriptToDevtoolsControlMsg;
use dom_struct::dom_struct;
use embedder_traits::EmbedderMsg;
use encoding_rs::{Encoding, UTF_8};
use euclid::default::Point2D;
use html5ever::{LocalName, Namespace, QualName};
use hyper_serde::Serde;
use ipc_channel::ipc::{self, IpcSender};
use js::jsapi::{JSObject, JSRuntime};
use keyboard_types::{Code, Key, KeyState};
use metrics::{
InteractiveFlag, InteractiveMetrics, InteractiveWindow, ProfilerMetadataFactory,
ProgressiveWebMetric,
};
use mime::{self, Mime};
use msg::constellation_msg::BrowsingContextId;
use net_traits::pub_domains::is_pub_domain;
use net_traits::request::RequestBuilder;
use net_traits::response::HttpsState;
use net_traits::CookieSource::NonHTTP;
use net_traits::CoreResourceMsg::{GetCookiesForUrl, SetCookiesForUrl};
use net_traits::{FetchResponseMsg, IpcSend, ReferrerPolicy};
use num_traits::ToPrimitive;
use percent_encoding::percent_decode;
use profile_traits::ipc as profile_ipc;
use profile_traits::time::{TimerMetadata, TimerMetadataFrameType, TimerMetadataReflowType};
use ref_slice::ref_slice;
use script_layout_interface::message::{Msg, PendingRestyle, ReflowGoal};
use script_layout_interface::TrustedNodeAddress;
use script_traits::{AnimationState, DocumentActivity, MouseButton, MouseEventType};
use script_traits::{
MsDuration, ScriptMsg, TouchEventType, TouchId, UntrustedNodeAddress, WheelDelta,
};
use servo_arc::Arc;
use servo_atoms::Atom;
use servo_config::pref;
use servo_media::{ClientContextId, ServoMedia};
use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
use std::borrow::Cow;
use std::cell::Cell;
use std::cmp::Ordering;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::{HashMap, HashSet, VecDeque};
use std::default::Default;
use std::mem;
use std::ptr::NonNull;
use std::rc::Rc;
use std::time::{Duration, Instant};
use style::attr::AttrValue;
use style::context::QuirksMode;
use style::invalidation::element::restyle_hints::RestyleHint;
use style::media_queries::{Device, MediaType};
use style::selector_parser::Snapshot;
use style::shared_lock::SharedRwLock as StyleSharedRwLock;
use style::str::{split_html_space_chars, str_join};
use style::stylesheet_set::DocumentStylesheetSet;
use style::stylesheets::{Origin, OriginSet, Stylesheet};
use url::Host;
use uuid::Uuid;
/// The number of times we are allowed to see spurious `requestAnimationFrame()` calls before
/// falling back to fake ones.
///
/// A spurious `requestAnimationFrame()` call is defined as one that does not change the DOM.
const SPURIOUS_ANIMATION_FRAME_THRESHOLD: u8 = 5;
/// The amount of time between fake `requestAnimationFrame()`s.
const FAKE_REQUEST_ANIMATION_FRAME_DELAY: u64 = 16;
pub enum TouchEventResult {
Processed(bool),
Forwarded,
}
pub enum FireMouseEventType {
Move,
Over,
Out,
}
impl FireMouseEventType {
pub fn as_str(&self) -> &str {
match self {
&FireMouseEventType::Move => "mousemove",
&FireMouseEventType::Over => "mouseover",
&FireMouseEventType::Out => "mouseout",
}
}
}
#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
pub enum IsHTMLDocument {
HTMLDocument,
NonHTMLDocument,
}
/// <https://dom.spec.whatwg.org/#document>
#[dom_struct]
pub struct Document {
node: Node,
document_or_shadow_root: DocumentOrShadowRoot,
window: Dom<Window>,
implementation: MutNullableDom<DOMImplementation>,
#[ignore_malloc_size_of = "type from external crate"]
content_type: Mime,
last_modified: Option<String>,
encoding: Cell<&'static Encoding>,
has_browsing_context: bool,
is_html_document: bool,
activity: Cell<DocumentActivity>,
url: DomRefCell<ServoUrl>,
#[ignore_malloc_size_of = "defined in selectors"]
quirks_mode: Cell<QuirksMode>,
/// Caches for the getElement methods
id_map: DomRefCell<HashMap<Atom, Vec<Dom<Element>>>>,
name_map: DomRefCell<HashMap<Atom, Vec<Dom<Element>>>>,
tag_map: DomRefCell<HashMap<LocalName, Dom<HTMLCollection>>>,
tagns_map: DomRefCell<HashMap<QualName, Dom<HTMLCollection>>>,
classes_map: DomRefCell<HashMap<Vec<Atom>, Dom<HTMLCollection>>>,
images: MutNullableDom<HTMLCollection>,
embeds: MutNullableDom<HTMLCollection>,
links: MutNullableDom<HTMLCollection>,
forms: MutNullableDom<HTMLCollection>,
scripts: MutNullableDom<HTMLCollection>,
anchors: MutNullableDom<HTMLCollection>,
applets: MutNullableDom<HTMLCollection>,
/// Lock use for style attributes and author-origin stylesheet objects in this document.
/// Can be acquired once for accessing many objects.
style_shared_lock: StyleSharedRwLock,
/// List of stylesheets associated with nodes in this document. |None| if the list needs to be refreshed.
stylesheets: DomRefCell<DocumentStylesheetSet<StyleSheetInDocument>>,
stylesheet_list: MutNullableDom<StyleSheetList>,
ready_state: Cell<DocumentReadyState>,
/// Whether the DOMContentLoaded event has already been dispatched.
domcontentloaded_dispatched: Cell<bool>,
/// The element that has most recently requested focus for itself.
possibly_focused: MutNullableDom<Element>,
/// The element that currently has the document focus context.
focused: MutNullableDom<Element>,
/// The script element that is currently executing.
current_script: MutNullableDom<HTMLScriptElement>,
/// <https://html.spec.whatwg.org/multipage/#pending-parsing-blocking-script>
pending_parsing_blocking_script: DomRefCell<Option<PendingScript>>,
/// Number of stylesheets that block executing the next parser-inserted script
script_blocking_stylesheets_count: Cell<u32>,
/// https://html.spec.whatwg.org/multipage/#list-of-scripts-that-will-execute-when-the-document-has-finished-parsing
deferred_scripts: PendingInOrderScriptVec,
/// <https://html.spec.whatwg.org/multipage/#list-of-scripts-that-will-execute-in-order-as-soon-as-possible>
asap_in_order_scripts_list: PendingInOrderScriptVec,
/// <https://html.spec.whatwg.org/multipage/#set-of-scripts-that-will-execute-as-soon-as-possible>
asap_scripts_set: DomRefCell<Vec<Dom<HTMLScriptElement>>>,
/// <https://html.spec.whatwg.org/multipage/#concept-n-noscript>
/// True if scripting is enabled for all scripts in this document
scripting_enabled: bool,
/// <https://html.spec.whatwg.org/multipage/#animation-frame-callback-identifier>
/// Current identifier of animation frame callback
animation_frame_ident: Cell<u32>,
/// <https://html.spec.whatwg.org/multipage/#list-of-animation-frame-callbacks>
/// List of animation frame callbacks
animation_frame_list: DomRefCell<Vec<(u32, Option<AnimationFrameCallback>)>>,
/// Whether we're in the process of running animation callbacks.
///
/// Tracking this is not necessary for correctness. Instead, it is an optimization to avoid
/// sending needless `ChangeRunningAnimationsState` messages to the compositor.
running_animation_callbacks: Cell<bool>,
/// Tracks all outstanding loads related to this document.
loader: DomRefCell<DocumentLoader>,
/// The current active HTML parser, to allow resuming after interruptions.
current_parser: MutNullableDom<ServoParser>,
/// When we should kick off a reflow. This happens during parsing.
reflow_timeout: Cell<Option<u64>>,
/// The cached first `base` element with an `href` attribute.
base_element: MutNullableDom<HTMLBaseElement>,
/// This field is set to the document itself for inert documents.
/// <https://html.spec.whatwg.org/multipage/#appropriate-template-contents-owner-document>
appropriate_template_contents_owner_document: MutNullableDom<Document>,
/// Information on elements needing restyle to ship over to the layout thread when the
/// time comes.
pending_restyles: DomRefCell<HashMap<Dom<Element>, PendingRestyle>>,
/// This flag will be true if layout suppressed a reflow attempt that was
/// needed in order for the page to be painted.
needs_paint: Cell<bool>,
/// <http://w3c.github.io/touch-events/#dfn-active-touch-point>
active_touch_points: DomRefCell<Vec<Dom<Touch>>>,
/// Navigation Timing properties:
/// <https://w3c.github.io/navigation-timing/#sec-PerformanceNavigationTiming>
dom_loading: Cell<u64>,
dom_interactive: Cell<u64>,
dom_content_loaded_event_start: Cell<u64>,
dom_content_loaded_event_end: Cell<u64>,
dom_complete: Cell<u64>,
top_level_dom_complete: Cell<u64>,
load_event_start: Cell<u64>,
load_event_end: Cell<u64>,
unload_event_start: Cell<u64>,
unload_event_end: Cell<u64>,
/// <https://html.spec.whatwg.org/multipage/#concept-document-https-state>
https_state: Cell<HttpsState>,
/// The document's origin.
origin: MutableOrigin,
/// https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-states
referrer_policy: Cell<Option<ReferrerPolicy>>,
/// <https://html.spec.whatwg.org/multipage/#dom-document-referrer>
referrer: Option<String>,
/// <https://html.spec.whatwg.org/multipage/#target-element>
target_element: MutNullableDom<Element>,
/// <https://w3c.github.io/uievents/#event-type-dblclick>
#[ignore_malloc_size_of = "Defined in std"]
last_click_info: DomRefCell<Option<(Instant, Point2D<f32>)>>,
/// <https://html.spec.whatwg.org/multipage/#ignore-destructive-writes-counter>
ignore_destructive_writes_counter: Cell<u32>,
/// <https://html.spec.whatwg.org/multipage/#ignore-opens-during-unload-counter>
ignore_opens_during_unload_counter: Cell<u32>,
/// The number of spurious `requestAnimationFrame()` requests we've received.
///
/// A rAF request is considered spurious if nothing was actually reflowed.
spurious_animation_frames: Cell<u8>,
/// Track the total number of elements in this DOM's tree.
/// This is sent to the layout thread every time a reflow is done;
/// layout uses this to determine if the gains from parallel layout will be worth the overhead.
///
/// See also: https://github.com/servo/servo/issues/10110
dom_count: Cell<u32>,
/// Entry node for fullscreen.
fullscreen_element: MutNullableDom<Element>,
/// Map from ID to set of form control elements that have that ID as
/// their 'form' content attribute. Used to reset form controls
/// whenever any element with the same ID as the form attribute
/// is inserted or removed from the document.
/// See https://html.spec.whatwg.org/multipage/#form-owner
form_id_listener_map: DomRefCell<HashMap<Atom, HashSet<Dom<Element>>>>,
interactive_time: DomRefCell<InteractiveMetrics>,
tti_window: DomRefCell<InteractiveWindow>,
/// RAII canceller for Fetch
canceller: FetchCanceller,
/// https://html.spec.whatwg.org/multipage/#throw-on-dynamic-markup-insertion-counter
throw_on_dynamic_markup_insertion_counter: Cell<u64>,
/// https://html.spec.whatwg.org/multipage/#page-showing
page_showing: Cell<bool>,
/// Whether the document is salvageable.
salvageable: Cell<bool>,
/// Whether the document was aborted with an active parser
active_parser_was_aborted: Cell<bool>,
/// Whether the unload event has already been fired.
fired_unload: Cell<bool>,
/// List of responsive images
responsive_images: DomRefCell<Vec<Dom<HTMLImageElement>>>,
/// Number of redirects for the document load
redirect_count: Cell<u16>,
/// Number of outstanding requests to prevent JS or layout from running.
script_and_layout_blockers: Cell<u32>,
/// List of tasks to execute as soon as last script/layout blocker is removed.
#[ignore_malloc_size_of = "Measuring trait objects is hard"]
delayed_tasks: DomRefCell<Vec<Box<dyn TaskBox>>>,
/// https://html.spec.whatwg.org/multipage/#completely-loaded
completely_loaded: Cell<bool>,
/// Set of shadow roots connected to the document tree.
shadow_roots: DomRefCell<HashSet<Dom<ShadowRoot>>>,
/// Whether any of the shadow roots need the stylesheets flushed.
shadow_roots_styles_changed: Cell<bool>,
/// List of registered media controls.
/// We need to keep this list to allow the media controls to
/// access the "privileged" document.servoGetMediaControls(id) API,
/// where `id` needs to match any of the registered ShadowRoots
/// hosting the media controls UI.
media_controls: DomRefCell<HashMap<String, Dom<ShadowRoot>>>,
/// List of all WebGL context IDs that need flushing.
dirty_webgl_contexts: DomRefCell<HashMap<WebGLContextId, Dom<WebGLRenderingContext>>>,
/// https://html.spec.whatwg.org/multipage/#concept-document-csp-list
#[ignore_malloc_size_of = "Defined in rust-content-security-policy"]
csp_list: DomRefCell<Option<CspList>>,
/// https://w3c.github.io/slection-api/#dfn-selection
selection: MutNullableDom<Selection>,
/// A timeline for animations which is used for synchronizing animations.
/// https://drafts.csswg.org/web-animations/#timeline
animation_timeline: DomRefCell<AnimationTimeline>,
/// Animations for this Document
animations: DomRefCell<Animations>,
/// The nearest inclusive ancestors to all the nodes that require a restyle.
dirty_root: MutNullableDom<Element>,
}
#[derive(JSTraceable, MallocSizeOf)]
struct ImagesFilter;
impl CollectionFilter for ImagesFilter {
fn filter(&self, elem: &Element, _root: &Node) -> bool {
elem.is::<HTMLImageElement>()
}
}
#[derive(JSTraceable, MallocSizeOf)]
struct EmbedsFilter;
impl CollectionFilter for EmbedsFilter {
fn filter(&self, elem: &Element, _root: &Node) -> bool {
elem.is::<HTMLEmbedElement>()
}
}
#[derive(JSTraceable, MallocSizeOf)]
struct LinksFilter;
impl CollectionFilter for LinksFilter {
fn filter(&self, elem: &Element, _root: &Node) -> bool {
(elem.is::<HTMLAnchorElement>() || elem.is::<HTMLAreaElement>()) &&
elem.has_attribute(&local_name!("href"))
}
}
#[derive(JSTraceable, MallocSizeOf)]
struct FormsFilter;
impl CollectionFilter for FormsFilter {
fn filter(&self, elem: &Element, _root: &Node) -> bool {
elem.is::<HTMLFormElement>()
}
}
#[derive(JSTraceable, MallocSizeOf)]
struct ScriptsFilter;
impl CollectionFilter for ScriptsFilter {
fn filter(&self, elem: &Element, _root: &Node) -> bool {
elem.is::<HTMLScriptElement>()
}
}
#[derive(JSTraceable, MallocSizeOf)]
struct AnchorsFilter;
impl CollectionFilter for AnchorsFilter {
fn filter(&self, elem: &Element, _root: &Node) -> bool {
elem.is::<HTMLAnchorElement>() && elem.has_attribute(&local_name!("href"))
}
}
enum ElementLookupResult {
None,
One(DomRoot<Element>),
Many,
}
#[allow(non_snake_case)]
impl Document {
pub fn note_node_with_dirty_descendants(&self, node: &Node) {
debug_assert!(*node.owner_doc() == *self);
if !node.is_connected() {
return;
}
let parent = match node.inclusive_ancestors(ShadowIncluding::Yes).nth(1) {
Some(parent) => parent,
None => {
// There is no parent so this is the Document node, so we
// behave as if we were called with the document element.
let document_element = match self.GetDocumentElement() {
Some(element) => element,
None => return,
};
if let Some(dirty_root) = self.dirty_root.get() {
// There was an existing dirty root so we mark its
// ancestors as dirty until the document element.
for ancestor in dirty_root
.upcast::<Node>()
.inclusive_ancestors(ShadowIncluding::Yes)
{
if ancestor.is::<Element>() {
ancestor.set_flag(NodeFlags::HAS_DIRTY_DESCENDANTS, true);
}
}
}
self.dirty_root.set(Some(&document_element));
return;
},
};
if parent.is::<Element>() {
if !parent.is_styled() {
return;
}
if parent.is_display_none() {
return;
}
}
let element_parent: DomRoot<Element>;
let element = match node.downcast::<Element>() {
Some(element) => element,
None => {
// Current node is not an element, it's probably a text node,
// we try to get its element parent.
match DomRoot::downcast::<Element>(parent) {
Some(parent) => {
element_parent = parent;
&element_parent
},
None => {
// Parent is not an element so it must be a document,
// and this is not an element either, so there is
// nothing to do.
return;
},
}
},
};
let dirty_root = match self.dirty_root.get() {
None => {
element
.upcast::<Node>()
.set_flag(NodeFlags::HAS_DIRTY_DESCENDANTS, true);
self.dirty_root.set(Some(element));
return;
},
Some(root) => root,
};
for ancestor in element
.upcast::<Node>()
.inclusive_ancestors(ShadowIncluding::Yes)
{
if ancestor.get_flag(NodeFlags::HAS_DIRTY_DESCENDANTS) {
return;
}
if ancestor.is::<Element>() {
ancestor.set_flag(NodeFlags::HAS_DIRTY_DESCENDANTS, true);
}
}
let new_dirty_root = element
.upcast::<Node>()
.common_ancestor(dirty_root.upcast(), ShadowIncluding::Yes);
let mut has_dirty_descendants = true;
for ancestor in dirty_root
.upcast::<Node>()
.inclusive_ancestors(ShadowIncluding::Yes)
{
ancestor.set_flag(NodeFlags::HAS_DIRTY_DESCENDANTS, has_dirty_descendants);
has_dirty_descendants &= *ancestor != *new_dirty_root;
}
self.dirty_root
.set(Some(new_dirty_root.downcast::<Element>().unwrap()));
}
pub fn take_dirty_root(&self) -> Option<DomRoot<Element>> {
self.dirty_root.take()
}
#[inline]
pub fn loader(&self) -> Ref<DocumentLoader> {
self.loader.borrow()
}
#[inline]
pub fn loader_mut(&self) -> RefMut<DocumentLoader> {
self.loader.borrow_mut()
}
#[inline]
pub fn has_browsing_context(&self) -> bool {
self.has_browsing_context
}
/// <https://html.spec.whatwg.org/multipage/#concept-document-bc>
#[inline]
pub fn browsing_context(&self) -> Option<DomRoot<WindowProxy>> {
if self.has_browsing_context {
self.window.undiscarded_window_proxy()
} else {
None
}
}
#[inline]
pub fn window(&self) -> &Window {
&*self.window
}
#[inline]
pub fn is_html_document(&self) -> bool {
self.is_html_document
}
pub fn set_https_state(&self, https_state: HttpsState) {
self.https_state.set(https_state);
}
pub fn is_fully_active(&self) -> bool {
self.activity.get() == DocumentActivity::FullyActive
}
pub fn is_active(&self) -> bool {
self.activity.get() != DocumentActivity::Inactive
}
pub fn set_activity(&self, activity: DocumentActivity) {
// This function should only be called on documents with a browsing context
assert!(self.has_browsing_context);
if activity == self.activity.get() {
return;
}
// Set the document's activity level, reflow if necessary, and suspend or resume timers.
self.activity.set(activity);
let media = ServoMedia::get().unwrap();
let pipeline_id = self.window().pipeline_id();
let client_context_id =
ClientContextId::build(pipeline_id.namespace_id.0, pipeline_id.index.0.get());
if activity != DocumentActivity::FullyActive {
self.window().suspend();
media.suspend(&client_context_id);
return;
}
self.title_changed();
self.dirty_all_nodes();
self.window()
.reflow(ReflowGoal::Full, ReflowReason::CachedPageNeededReflow);
self.window().resume();
media.resume(&client_context_id);
if self.ready_state.get() != DocumentReadyState::Complete {
return;
}
// html.spec.whatwg.org/multipage/#history-traversal
// Step 4.6
let document = Trusted::new(self);
self.window
.task_manager()
.dom_manipulation_task_source()
.queue(
task!(fire_pageshow_event: move || {
let document = document.root();
let window = document.window();
// Step 4.6.1
if document.page_showing.get() {
return;
}
// Step 4.6.2
document.page_showing.set(true);
// Step 4.6.4
let event = PageTransitionEvent::new(
window,
atom!("pageshow"),
false, // bubbles
false, // cancelable
true, // persisted
);
let event = event.upcast::<Event>();
event.set_trusted(true);
// FIXME(nox): Why are errors silenced here?
let _ = window.dispatch_event_with_target_override(
&event,
);
}),
self.window.upcast(),
)
.unwrap();
}
pub fn origin(&self) -> &MutableOrigin {
&self.origin
}
// https://dom.spec.whatwg.org/#concept-document-url
pub fn url(&self) -> ServoUrl {
self.url.borrow().clone()
}
pub fn set_url(&self, url: ServoUrl) {
*self.url.borrow_mut() = url;
}
// https://html.spec.whatwg.org/multipage/#fallback-base-url
pub fn fallback_base_url(&self) -> ServoUrl {
let document_url = self.url();
if let Some(browsing_context) = self.browsing_context() {
// Step 1: If document is an iframe srcdoc document, then return the
// document base URL of document's browsing context's container document.
let container_base_url = browsing_context
.parent()
.and_then(|parent| parent.document())
.map(|document| document.base_url());
if document_url.as_str() == "about:srcdoc" && container_base_url.is_some() {
return container_base_url.unwrap();
}
// Step 2: If document's URL is about:blank, and document's browsing
// context's creator base URL is non-null, then return that creator base URL.
if document_url.as_str() == "about:blank" && browsing_context.has_creator_base_url() {
return browsing_context.creator_base_url().unwrap();
}
}
// Step 3: Return document's URL.
document_url
}
// https://html.spec.whatwg.org/multipage/#document-base-url
pub fn base_url(&self) -> ServoUrl {
match self.base_element() {
// Step 1.
None => self.fallback_base_url(),
// Step 2.
Some(base) => base.frozen_base_url(),
}
}
pub fn needs_paint(&self) -> bool {
self.needs_paint.get()
}
pub fn needs_reflow(&self) -> Option<ReflowTriggerCondition> {
// FIXME: This should check the dirty bit on the document,
// not the document element. Needs some layout changes to make
// that workable.
if self.stylesheets.borrow().has_changed() {
return Some(ReflowTriggerCondition::StylesheetsChanged);
}
let root = self.GetDocumentElement()?;
if root.upcast::<Node>().has_dirty_descendants() {
return Some(ReflowTriggerCondition::DirtyDescendants);
}
if !self.pending_restyles.borrow().is_empty() {
return Some(ReflowTriggerCondition::PendingRestyles);
}
if self.needs_paint() {
return Some(ReflowTriggerCondition::PaintPostponed);
}
None
}
/// Returns the first `base` element in the DOM that has an `href` attribute.
pub fn base_element(&self) -> Option<DomRoot<HTMLBaseElement>> {
self.base_element.get()
}
/// Refresh the cached first base element in the DOM.
/// <https://github.com/w3c/web-platform-tests/issues/2122>
pub fn refresh_base_element(&self) {
let base = self
.upcast::<Node>()
.traverse_preorder(ShadowIncluding::No)
.filter_map(DomRoot::downcast::<HTMLBaseElement>)
.find(|element| {
element
.upcast::<Element>()
.has_attribute(&local_name!("href"))
});
self.base_element.set(base.as_deref());
}
pub fn dom_count(&self) -> u32 {
self.dom_count.get()
}
/// This is called by `bind_to_tree` when a node is added to the DOM.
/// The internal count is used by layout to determine whether to be sequential or parallel.
/// (it's sequential for small DOMs)
pub fn increment_dom_count(&self) {
self.dom_count.set(self.dom_count.get() + 1);
}
/// This is called by `unbind_from_tree` when a node is removed from the DOM.
pub fn decrement_dom_count(&self) {
self.dom_count.set(self.dom_count.get() - 1);
}
pub fn quirks_mode(&self) -> QuirksMode {
self.quirks_mode.get()
}
pub fn set_quirks_mode(&self, mode: QuirksMode) {
self.quirks_mode.set(mode);
if mode == QuirksMode::Quirks {
self.window
.layout_chan()
.send(Msg::SetQuirksMode(mode))
.unwrap();
}
}
pub fn encoding(&self) -> &'static Encoding {
self.encoding.get()
}
pub fn set_encoding(&self, encoding: &'static Encoding) {
self.encoding.set(encoding);
}
pub fn content_and_heritage_changed(&self, node: &Node) {
if node.is_connected() {
node.note_dirty_descendants();
}
// FIXME(emilio): This is very inefficient, ideally the flag above would
// be enough and incremental layout could figure out from there.
node.dirty(NodeDamage::OtherNodeDamage);
}
/// Reflows and disarms the timer if the reflow timer has expired.
pub fn reflow_if_reflow_timer_expired(&self) {
if let Some(reflow_timeout) = self.reflow_timeout.get() {
if time::precise_time_ns() < reflow_timeout {
return;
}
self.reflow_timeout.set(None);
self.window
.reflow(ReflowGoal::Full, ReflowReason::RefreshTick);
}
}
/// Schedules a reflow to be kicked off at the given `timeout` (in `time::precise_time_ns()`
/// units). This reflow happens even if the event loop is busy. This is used to display initial
/// page content during parsing.
pub fn set_reflow_timeout(&self, timeout: u64) {
if let Some(existing_timeout) = self.reflow_timeout.get() {
if existing_timeout < timeout {
return;
}
}
self.reflow_timeout.set(Some(timeout))
}
/// Remove any existing association between the provided id and any elements in this document.
pub fn unregister_element_id(&self, to_unregister: &Element, id: Atom) {
self.document_or_shadow_root
.unregister_named_element(&self.id_map, to_unregister, &id);
self.reset_form_owner_for_listeners(&id);
}
/// Associate an element present in this document with the provided id.
pub fn register_element_id(&self, element: &Element, id: Atom) {
let root = self.GetDocumentElement().expect(
"The element is in the document, so there must be a document \
element.",
);
self.document_or_shadow_root.register_named_element(
&self.id_map,
element,
&id,
DomRoot::from_ref(root.upcast::<Node>()),
);
self.reset_form_owner_for_listeners(&id);
}
/// Remove any existing association between the provided name and any elements in this document.
pub fn unregister_element_name(&self, to_unregister: &Element, name: Atom) {
self.document_or_shadow_root
.unregister_named_element(&self.name_map, to_unregister, &name);
}
/// Associate an element present in this document with the provided name.
pub fn register_element_name(&self, element: &Element, name: Atom) {
let root = self.GetDocumentElement().expect(
"The element is in the document, so there must be a document \
element.",
);
self.document_or_shadow_root.register_named_element(
&self.name_map,
element,
&name,
DomRoot::from_ref(root.upcast::<Node>()),
);
}
pub fn register_form_id_listener<T: ?Sized + FormControl>(&self, id: DOMString, listener: &T) {
let mut map = self.form_id_listener_map.borrow_mut();
let listener = listener.to_element();
let set = map.entry(Atom::from(id)).or_insert(HashSet::new());
set.insert(Dom::from_ref(listener));
}
pub fn unregister_form_id_listener<T: ?Sized + FormControl>(
&self,
id: DOMString,
listener: &T,
) {
let mut map = self.form_id_listener_map.borrow_mut();
if let Occupied(mut entry) = map.entry(Atom::from(id)) {
entry
.get_mut()
.remove(&Dom::from_ref(listener.to_element()));
if entry.get().is_empty() {
entry.remove();
}
}
}
/// Attempt to find a named element in this page's document.
/// <https://html.spec.whatwg.org/multipage/#the-indicated-part-of-the-document>
pub fn find_fragment_node(&self, fragid: &str) -> Option<DomRoot<Element>> {
// Step 1 is not handled here; the fragid is already obtained by the calling function
// Step 2: Simply use None to indicate the top of the document.
// Step 3 & 4
percent_decode(fragid.as_bytes())
.decode_utf8()
.ok()
// Step 5
.and_then(|decoded_fragid| self.get_element_by_id(&Atom::from(decoded_fragid)))
// Step 6
.or_else(|| self.get_anchor_by_name(fragid))
// Step 7 & 8
}
/// Scroll to the target element, and when we do not find a target
/// and the fragment is empty or "top", scroll to the top.
/// <https://html.spec.whatwg.org/multipage/#scroll-to-the-fragment-identifier>
pub fn check_and_scroll_fragment(&self, fragment: &str) {
let target = self.find_fragment_node(fragment);
// Step 1
self.set_target_element(target.as_deref());
let point = target
.as_ref()
.map(|element| {
// FIXME(#8275, pcwalton): This is pretty bogus when multiple layers are involved.
// Really what needs to happen is that this needs to go through layout to ask which
// layer the element belongs to, and have it send the scroll message to the
// compositor.
let rect = element.upcast::<Node>().bounding_content_box_or_zero();
// In order to align with element edges, we snap to unscaled pixel boundaries, since
// the paint thread currently does the same for drawing elements. This is important
// for pages that require pixel perfect scroll positioning for proper display
// (like Acid2). Since we don't have the device pixel ratio here, this might not be
// accurate, but should work as long as the ratio is a whole number. Once #8275 is
// fixed this should actually take into account the real device pixel ratio.
(
rect.origin.x.to_nearest_px() as f32,
rect.origin.y.to_nearest_px() as f32,
)
})
.or_else(|| {
if fragment.is_empty() || fragment.eq_ignore_ascii_case("top") {
// FIXME(stshine): this should be the origin of the stacking context space,
// which may differ under the influence of writing mode.
Some((0.0, 0.0))
} else {
None
}
});
if let Some((x, y)) = point {
// Step 3
let global_scope = self.window.upcast::<GlobalScope>();
self.window.update_viewport_for_scroll(x, y);
self.window.perform_a_scroll(
x,
y,
global_scope.pipeline_id().root_scroll_id(),
ScrollBehavior::Instant,
target.as_deref(),
);
}
}
fn get_anchor_by_name(&self, name: &str) -> Option<DomRoot<Element>> {
let name = Atom::from(name);
self.name_map.borrow().get(&name).and_then(|elements| {
elements
.iter()
.find(|e| e.is::<HTMLAnchorElement>())
.map(|e| DomRoot::from_ref(&**e))
})
}
// https://html.spec.whatwg.org/multipage/#current-document-readiness
pub fn set_ready_state(&self, state: DocumentReadyState) {
match state {
DocumentReadyState::Loading => {
update_with_current_time_ms(&self.dom_loading);
},
DocumentReadyState::Complete => {
update_with_current_time_ms(&self.dom_complete);
},
DocumentReadyState::Interactive => update_with_current_time_ms(&self.dom_interactive),
};
self.ready_state.set(state);
self.upcast::<EventTarget>()
.fire_event(atom!("readystatechange"));
}