-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Expand file tree
/
Copy pathwindow.rs
More file actions
3991 lines (3500 loc) · 151 KB
/
window.rs
File metadata and controls
3991 lines (3500 loc) · 151 KB
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 std::borrow::ToOwned;
use std::cell::{Cell, RefCell, RefMut};
use std::cmp;
use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::default::Default;
use std::ffi::c_void;
use std::io::{Write, stderr, stdout};
use std::rc::{Rc, Weak};
use std::sync::Arc;
use std::time::{Duration, Instant};
use app_units::Au;
use base64::Engine;
use content_security_policy::Violation;
use content_security_policy::sandboxing_directive::SandboxingFlagSet;
use crossbeam_channel::{Sender, unbounded};
use cssparser::SourceLocation;
use devtools_traits::{ScriptToDevtoolsControlMsg, TimelineMarker, TimelineMarkerType};
use dom_struct::dom_struct;
use embedder_traits::user_contents::UserScript;
use embedder_traits::{
AlertResponse, ConfirmResponse, EmbedderMsg, JavaScriptEvaluationError, PromptResponse,
ScriptToEmbedderChan, SimpleDialogRequest, Theme, UntrustedNodeAddress, ViewportDetails,
WebDriverJSResult, WebDriverLoadStatus,
};
use euclid::default::Rect as UntypedRect;
use euclid::{Point2D, Rect, Scale, Size2D, Vector2D};
use fonts::{CspViolationHandler, FontContext, NetworkTimingHandler, WebFontDocumentContext};
use js::context::JSContext;
use js::glue::DumpJSStack;
use js::jsapi::{
GCReason, Heap, JS_GC, JSAutoRealm, JSContext as RawJSContext, JSObject, JSPROP_ENUMERATE,
};
use js::jsval::{NullValue, UndefinedValue};
use js::realm::CurrentRealm;
use js::rust::wrappers::JS_DefineProperty;
use js::rust::{
CustomAutoRooter, CustomAutoRooterGuard, HandleObject, HandleValue, MutableHandleObject,
MutableHandleValue,
};
use layout_api::{
AxesOverflow, BoxAreaType, CSSPixelRectIterator, ElementsFromPointFlags,
ElementsFromPointResult, FragmentType, Layout, LayoutImageDestination, PendingImage,
PendingImageState, PendingRasterizationImage, PhysicalSides, QueryMsg, ReflowGoal,
ReflowPhasesRun, ReflowRequest, ReflowRequestRestyle, ReflowStatistics, RestyleReason,
ScrollContainerQueryFlags, ScrollContainerResponse, TrustedNodeAddress,
combine_id_with_fragment_type,
};
use malloc_size_of::MallocSizeOf;
use media::WindowGLContext;
use net_traits::image_cache::{
ImageCache, ImageCacheResponseCallback, ImageCacheResponseMessage, ImageLoadListener,
ImageResponse, PendingImageId, PendingImageResponse, RasterizationCompleteResponse,
};
use net_traits::request::Referrer;
use net_traits::{ResourceFetchTiming, ResourceThreads};
use num_traits::ToPrimitive;
use paint_api::{CrossProcessPaintApi, PinchZoomInfos};
use profile_traits::generic_channel as ProfiledGenericChannel;
use profile_traits::mem::ProfilerChan as MemProfilerChan;
use profile_traits::time::ProfilerChan as TimeProfilerChan;
use rustc_hash::{FxBuildHasher, FxHashMap};
use script_bindings::codegen::GenericBindings::WindowBinding::ScrollToOptions;
use script_bindings::conversions::SafeToJSValConvertible;
use script_bindings::interfaces::WindowHelpers;
use script_bindings::root::Root;
use script_traits::{ConstellationInputEvent, ScriptThreadMessage};
use selectors::attr::CaseSensitivity;
use servo_arc::Arc as ServoArc;
use servo_base::cross_process_instant::CrossProcessInstant;
use servo_base::generic_channel::{self, GenericCallback, GenericSender};
use servo_base::id::{BrowsingContextId, PipelineId, WebViewId};
#[cfg(feature = "bluetooth")]
use servo_bluetooth_traits::BluetoothRequest;
use servo_canvas_traits::webgl::WebGLChan;
use servo_config::pref;
use servo_constellation_traits::{
LoadData, LoadOrigin, ScreenshotReadinessResponse, ScriptToConstellationChan,
ScriptToConstellationMessage, StructuredSerializedData, WindowSizeType,
};
use servo_geometry::DeviceIndependentIntRect;
use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
use storage_traits::StorageThreads;
use storage_traits::webstorage_thread::WebStorageType;
use style::error_reporting::{ContextualParseError, ParseErrorReporter};
use style::properties::PropertyId;
use style::properties::style_structs::Font;
use style::selector_parser::PseudoElement;
use style::str::HTML_SPACE_CHARACTERS;
use style::stylesheets::UrlExtraData;
use style_traits::CSSPixel;
use stylo_atoms::Atom;
use time::Duration as TimeDuration;
use webrender_api::ExternalScrollId;
use webrender_api::units::{DeviceIntSize, DevicePixel, LayoutPixel, LayoutPoint};
use super::bindings::codegen::Bindings::MessagePortBinding::StructuredSerializeOptions;
use super::bindings::trace::HashMapTracedValues;
use super::performanceresourcetiming::InitiatorType;
use super::types::SVGSVGElement;
use crate::dom::bindings::cell::{DomRefCell, Ref};
use crate::dom::bindings::codegen::Bindings::DocumentBinding::{
DocumentMethods, DocumentReadyState, NamedPropertyValue,
};
use crate::dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElementMethods;
use crate::dom::bindings::codegen::Bindings::HistoryBinding::History_Binding::HistoryMethods;
use crate::dom::bindings::codegen::Bindings::ImageBitmapBinding::{
ImageBitmapOptions, ImageBitmapSource,
};
use crate::dom::bindings::codegen::Bindings::MediaQueryListBinding::MediaQueryList_Binding::MediaQueryListMethods;
use crate::dom::bindings::codegen::Bindings::ReportingObserverBinding::Report;
use crate::dom::bindings::codegen::Bindings::RequestBinding::{RequestInfo, RequestInit};
use crate::dom::bindings::codegen::Bindings::VoidFunctionBinding::VoidFunction;
use crate::dom::bindings::codegen::Bindings::WindowBinding::{
self, DeferredRequestInit, FrameRequestCallback, ScrollBehavior, WindowMethods,
WindowPostMessageOptions,
};
use crate::dom::bindings::codegen::UnionTypes::{
RequestOrUSVString, TrustedScriptOrString, TrustedScriptOrStringOrFunction,
};
use crate::dom::bindings::error::{
Error, ErrorInfo, ErrorResult, Fallible, javascript_error_info_from_error_info,
};
use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
use crate::dom::bindings::num::Finite;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::{DomGlobal, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use crate::dom::bindings::str::{DOMString, USVString};
use crate::dom::bindings::structuredclone;
use crate::dom::bindings::trace::{CustomTraceable, JSTraceable, RootedTraceableBox};
use crate::dom::bindings::utils::GlobalStaticData;
use crate::dom::bindings::weakref::DOMTracker;
#[cfg(feature = "bluetooth")]
use crate::dom::bluetooth::BluetoothExtraPermissionData;
use crate::dom::cookiestore::CookieStore;
use crate::dom::crypto::Crypto;
use crate::dom::csp::GlobalCspReporting;
use crate::dom::css::cssstyledeclaration::{
CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner,
};
use crate::dom::customelementregistry::CustomElementRegistry;
use crate::dom::document::focus::{FocusInitiator, FocusOperation, FocusableArea};
use crate::dom::document::{
AnimationFrameCallback, Document, SameOriginDescendantNavigablesIterator,
};
use crate::dom::element::Element;
use crate::dom::event::{Event, EventBubbles, EventCancelable};
use crate::dom::eventtarget::EventTarget;
use crate::dom::fetchlaterresult::FetchLaterResult;
use crate::dom::globalscope::GlobalScope;
use crate::dom::history::History;
use crate::dom::html::htmlcollection::{CollectionFilter, HTMLCollection};
use crate::dom::html::htmliframeelement::HTMLIFrameElement;
use crate::dom::idbfactory::IDBFactory;
use crate::dom::inputevent::HitTestResult;
use crate::dom::location::Location;
use crate::dom::medialist::MediaList;
use crate::dom::mediaquerylist::{MediaQueryList, MediaQueryListMatchState};
use crate::dom::mediaquerylistevent::MediaQueryListEvent;
use crate::dom::messageevent::MessageEvent;
use crate::dom::navigator::Navigator;
use crate::dom::node::{Node, NodeDamage, NodeTraits, from_untrusted_node_address};
use crate::dom::performance::performance::Performance;
use crate::dom::promise::Promise;
use crate::dom::reporting::reportingendpoint::{ReportingEndpoint, SendReportsToEndpoints};
use crate::dom::reporting::reportingobserver::ReportingObserver;
use crate::dom::screen::Screen;
use crate::dom::scrolling_box::{ScrollingBox, ScrollingBoxSource};
use crate::dom::selection::Selection;
use crate::dom::shadowroot::ShadowRoot;
use crate::dom::storage::Storage;
#[cfg(feature = "bluetooth")]
use crate::dom::testrunner::TestRunner;
use crate::dom::trustedtypes::trustedtypepolicyfactory::TrustedTypePolicyFactory;
use crate::dom::types::{ImageBitmap, MouseEvent, UIEvent};
use crate::dom::useractivation::UserActivationTimestamp;
use crate::dom::visualviewport::{VisualViewport, VisualViewportChanges};
#[cfg(feature = "webgpu")]
use crate::dom::webgpu::identityhub::IdentityHub;
use crate::dom::windowproxy::{WindowProxy, WindowProxyHandler};
use crate::dom::worklet::Worklet;
use crate::dom::workletglobalscope::WorkletGlobalScopeType;
use crate::layout_image::fetch_image_for_layout;
use crate::messaging::{MainThreadScriptMsg, ScriptEventLoopReceiver, ScriptEventLoopSender};
use crate::microtask::{Microtask, UserMicrotask};
use crate::network_listener::{ResourceTimingListener, submit_timing};
use crate::realms::enter_realm;
use crate::script_runtime::{CanGc, JSContext as SafeJSContext, Runtime};
use crate::script_thread::ScriptThread;
use crate::script_window_proxies::ScriptWindowProxies;
use crate::task_source::SendableTaskSource;
use crate::timers::{IsInterval, TimerCallback};
use crate::unminify::unminified_path;
use crate::webdriver_handlers::{find_node_by_unique_id_in_document, jsval_to_webdriver};
use crate::{fetch, window_named_properties};
/// A callback to call when a response comes back from the `ImageCache`.
///
/// This is wrapped in a struct so that we can implement `MallocSizeOf`
/// for this type.
#[derive(MallocSizeOf)]
pub struct PendingImageCallback(
#[ignore_malloc_size_of = "dyn Fn is currently impossible to measure"]
#[expect(clippy::type_complexity)]
Box<dyn Fn(PendingImageResponse, &mut js::context::JSContext) + 'static>,
);
/// Current state of the window object
#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
enum WindowState {
Alive,
Zombie, // Pipeline is closed, but the window hasn't been GCed yet.
}
/// How long we should wait before performing the initial reflow after `<body>` is parsed,
/// assuming that `<body>` take this long to parse.
const INITIAL_REFLOW_DELAY: Duration = Duration::from_millis(200);
/// During loading and parsing, layouts are suppressed to avoid flashing incomplete page
/// contents.
///
/// Exceptions:
/// - Parsing the body takes so long, that layouts are no longer suppressed in order
/// to show the user that the page is loading.
/// - Script triggers a layout query or scroll event in which case, we want to layout
/// but not display the contents.
///
/// For more information see: <https://github.com/servo/servo/pull/6028>.
#[derive(Clone, Copy, MallocSizeOf)]
enum LayoutBlocker {
/// The first load event hasn't been fired and we have not started to parse the `<body>` yet.
WaitingForParse,
/// The body is being parsed the `<body>` starting at the `Instant` specified.
Parsing(Instant),
/// The body finished parsing and the `load` event has been fired or parsing took so
/// long, that we are going to do layout anyway. Note that subsequent changes to the body
/// can trigger parsing again, but the `Window` stays in this state.
FiredLoadEventOrParsingTimerExpired,
}
impl LayoutBlocker {
fn layout_blocked(&self) -> bool {
!matches!(self, Self::FiredLoadEventOrParsingTimerExpired)
}
}
/// An id used to cancel navigations; for now only used for planned form navigations.
/// Loosely based on <https://html.spec.whatwg.org/multipage/#ongoing-navigation>.
#[derive(Clone, Copy, Debug, Default, JSTraceable, MallocSizeOf, PartialEq)]
pub(crate) struct OngoingNavigation(u32);
type PendingImageRasterizationKey = (PendingImageId, DeviceIntSize);
/// Ancillary data of pending image request that was initiated by layout during a reflow.
/// This data is used to faciliate invalidating layout when the image data becomes available
/// at some point in the future.
#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
#[derive(JSTraceable, MallocSizeOf)]
struct PendingLayoutImageAncillaryData {
node: Dom<Node>,
#[no_trace]
destination: LayoutImageDestination,
}
#[dom_struct]
pub(crate) struct Window {
globalscope: GlobalScope,
/// A `Weak` reference to this [`ScriptThread`] used to give to child [`Window`]s so
/// they can more easily call methods on the [`ScriptThread`] without constantly having
/// to pass it everywhere.
#[ignore_malloc_size_of = "Weak does not need to be accounted"]
#[no_trace]
weak_script_thread: Weak<ScriptThread>,
/// The webview that contains this [`Window`].
///
/// This may not be the top-level [`Window`], in the case of frames.
#[no_trace]
webview_id: WebViewId,
script_chan: Sender<MainThreadScriptMsg>,
#[no_trace]
#[ignore_malloc_size_of = "TODO: Add MallocSizeOf support to layout"]
layout: RefCell<Box<dyn Layout>>,
navigator: MutNullableDom<Navigator>,
crypto: MutNullableDom<Crypto>,
#[ignore_malloc_size_of = "ImageCache"]
#[no_trace]
image_cache: Arc<dyn ImageCache>,
#[no_trace]
image_cache_sender: Sender<ImageCacheResponseMessage>,
window_proxy: MutNullableDom<WindowProxy>,
document: MutNullableDom<Document>,
location: MutNullableDom<Location>,
history: MutNullableDom<History>,
custom_element_registry: MutNullableDom<CustomElementRegistry>,
performance: MutNullableDom<Performance>,
#[no_trace]
navigation_start: Cell<CrossProcessInstant>,
screen: MutNullableDom<Screen>,
session_storage: MutNullableDom<Storage>,
local_storage: MutNullableDom<Storage>,
/// <https://cookiestore.spec.whatwg.org/#globals>
cookie_store: MutNullableDom<CookieStore>,
status: DomRefCell<DOMString>,
trusted_types: MutNullableDom<TrustedTypePolicyFactory>,
/// The start of something resembling
/// <https://html.spec.whatwg.org/multipage/#ongoing-navigation>
ongoing_navigation: Cell<OngoingNavigation>,
/// For sending timeline markers. Will be ignored if
/// no devtools server
#[no_trace]
devtools_markers: DomRefCell<HashSet<TimelineMarkerType>>,
#[no_trace]
devtools_marker_sender: DomRefCell<Option<GenericSender<Option<TimelineMarker>>>>,
/// Most recent unhandled resize event, if any.
#[no_trace]
unhandled_resize_event: DomRefCell<Option<(ViewportDetails, WindowSizeType)>>,
/// Platform theme.
#[no_trace]
theme: Cell<Theme>,
/// Parent id associated with this page, if any.
#[no_trace]
parent_info: Option<PipelineId>,
/// Global static data related to the DOM.
dom_static: GlobalStaticData,
/// The JavaScript runtime.
#[conditional_malloc_size_of]
js_runtime: DomRefCell<Option<Rc<Runtime>>>,
/// The [`ViewportDetails`] of this [`Window`]'s frame.
#[no_trace]
viewport_details: Cell<ViewportDetails>,
/// A handle for communicating messages to the bluetooth thread.
#[no_trace]
#[cfg(feature = "bluetooth")]
bluetooth_thread: GenericSender<BluetoothRequest>,
#[cfg(feature = "bluetooth")]
bluetooth_extra_permission_data: BluetoothExtraPermissionData,
/// See the documentation for [`LayoutBlocker`]. Essentially, this flag prevents
/// layouts from happening before the first load event, apart from a few exceptional
/// cases.
#[no_trace]
layout_blocker: Cell<LayoutBlocker>,
/// A channel for communicating results of async scripts back to the webdriver server
#[no_trace]
webdriver_script_chan: DomRefCell<Option<GenericSender<WebDriverJSResult>>>,
/// A channel to notify webdriver if there is a navigation
#[no_trace]
webdriver_load_status_sender: RefCell<Option<GenericSender<WebDriverLoadStatus>>>,
/// The current state of the window object
current_state: Cell<WindowState>,
error_reporter: CSSErrorReporter,
/// All the MediaQueryLists we need to update
media_query_lists: DOMTracker<MediaQueryList>,
#[cfg(feature = "bluetooth")]
test_runner: MutNullableDom<TestRunner>,
/// A handle for communicating messages to the WebGL thread, if available.
#[no_trace]
webgl_chan: Option<WebGLChan>,
#[ignore_malloc_size_of = "defined in webxr"]
#[no_trace]
#[cfg(feature = "webxr")]
webxr_registry: Option<webxr_api::Registry>,
/// When an element triggers an image load or starts watching an image load from the
/// `ImageCache` it adds an entry to this list. When those loads are triggered from
/// layout, they also add an etry to [`Self::pending_layout_images`].
#[no_trace]
pending_image_callbacks: DomRefCell<FxHashMap<PendingImageId, Vec<PendingImageCallback>>>,
/// All of the elements that have an outstanding image request that was
/// initiated by layout during a reflow. They are stored in the [`ScriptThread`]
/// to ensure that the element can be marked dirty when the image data becomes
/// available at some point in the future.
pending_layout_images: DomRefCell<
HashMapTracedValues<PendingImageId, Vec<PendingLayoutImageAncillaryData>, FxBuildHasher>,
>,
/// Vector images for which layout has intiated rasterization at a specific size
/// and whose results are not yet available. They are stored in the [`ScriptThread`]
/// so that the element can be marked dirty once the rasterization is completed.
pending_images_for_rasterization: DomRefCell<
HashMapTracedValues<PendingImageRasterizationKey, Vec<Dom<Node>>, FxBuildHasher>,
>,
/// Directory to store unminified css for this window if unminify-css
/// opt is enabled.
unminified_css_dir: DomRefCell<Option<String>>,
/// Directory with stored unminified scripts
local_script_source: Option<String>,
/// Worklets
test_worklet: MutNullableDom<Worklet>,
/// <https://drafts.css-houdini.org/css-paint-api-1/#paint-worklet>
paint_worklet: MutNullableDom<Worklet>,
/// Flag to identify whether mutation observers are present(true)/absent(false)
exists_mut_observer: Cell<bool>,
/// Cross-process access to `Paint`.
#[no_trace]
paint_api: CrossProcessPaintApi,
/// The [`UserScript`]s added via `UserContentManager`. These are potentially shared with other
/// `WebView`s in this `ScriptThread`.
#[no_trace]
#[conditional_malloc_size_of]
user_scripts: Rc<Vec<UserScript>>,
/// Window's GL context from application
#[ignore_malloc_size_of = "defined in script_thread"]
#[no_trace]
player_context: WindowGLContext,
throttled: Cell<bool>,
/// A shared marker for the validity of any cached layout values. A value of true
/// indicates that any such values remain valid; any new layout that invalidates
/// those values will cause the marker to be set to false.
#[conditional_malloc_size_of]
layout_marker: DomRefCell<Rc<Cell<bool>>>,
/// <https://dom.spec.whatwg.org/#window-current-event>
current_event: DomRefCell<Option<Dom<Event>>>,
/// <https://w3c.github.io/reporting/#windoworworkerglobalscope-registered-reporting-observer-list>
reporting_observer_list: DomRefCell<Vec<DomRoot<ReportingObserver>>>,
/// <https://w3c.github.io/reporting/#windoworworkerglobalscope-reports>
report_list: DomRefCell<Vec<Report>>,
/// <https://w3c.github.io/reporting/#windoworworkerglobalscope-endpoints>
#[no_trace]
endpoints_list: DomRefCell<Vec<ReportingEndpoint>>,
/// The window proxies the script thread knows.
#[conditional_malloc_size_of]
script_window_proxies: Rc<ScriptWindowProxies>,
/// Whether or not this [`Window`] has a pending screenshot readiness request.
has_pending_screenshot_readiness_request: Cell<bool>,
/// Visual viewport interface that is associated to this [`Window`].
/// <https://drafts.csswg.org/cssom-view/#dom-window-visualviewport>
visual_viewport: MutNullableDom<VisualViewport>,
/// [`VisualViewport`] dimension changed and we need to process it on the next tick.
has_changed_visual_viewport_dimension: Cell<bool>,
/// <https://html.spec.whatwg.org/multipage/#last-activation-timestamp>
#[no_trace]
last_activation_timestamp: Cell<UserActivationTimestamp>,
/// A flag to indicate whether the developer tools has requested
/// live updates from the window.
devtools_wants_updates: Cell<bool>,
}
impl Window {
pub(crate) fn script_thread(&self) -> Rc<ScriptThread> {
Weak::upgrade(&self.weak_script_thread)
.expect("Weak reference should always be upgradable when a ScriptThread is running")
}
pub(crate) fn webview_id(&self) -> WebViewId {
self.webview_id
}
pub(crate) fn as_global_scope(&self) -> &GlobalScope {
self.upcast::<GlobalScope>()
}
pub(crate) fn layout(&self) -> Ref<'_, Box<dyn Layout>> {
self.layout.borrow()
}
pub(crate) fn layout_mut(&self) -> RefMut<'_, Box<dyn Layout>> {
self.layout.borrow_mut()
}
pub(crate) fn get_exists_mut_observer(&self) -> bool {
self.exists_mut_observer.get()
}
pub(crate) fn set_exists_mut_observer(&self) {
self.exists_mut_observer.set(true);
}
#[expect(unsafe_code)]
pub(crate) fn clear_js_runtime_for_script_deallocation(&self) {
self.as_global_scope()
.remove_web_messaging_and_dedicated_workers_infra();
unsafe {
*self.js_runtime.borrow_for_script_deallocation() = None;
self.window_proxy.set(None);
self.current_state.set(WindowState::Zombie);
self.as_global_scope()
.task_manager()
.cancel_all_tasks_and_ignore_future_tasks();
}
}
/// A convenience method for
/// <https://html.spec.whatwg.org/multipage/#a-browsing-context-is-discarded>
pub(crate) fn discard_browsing_context(&self) {
let proxy = match self.window_proxy.get() {
Some(proxy) => proxy,
None => panic!("Discarding a BC from a window that has none"),
};
proxy.discard_browsing_context();
// Step 4 of https://html.spec.whatwg.org/multipage/#discard-a-document
// Other steps performed when the `PipelineExit` message
// is handled by the ScriptThread.
self.as_global_scope()
.task_manager()
.cancel_all_tasks_and_ignore_future_tasks();
}
/// Get a sender to the time profiler thread.
pub(crate) fn time_profiler_chan(&self) -> &TimeProfilerChan {
self.globalscope.time_profiler_chan()
}
pub(crate) fn origin(&self) -> &MutableOrigin {
self.globalscope.origin()
}
#[expect(unsafe_code)]
pub(crate) fn get_cx(&self) -> SafeJSContext {
unsafe { SafeJSContext::from_ptr(js::rust::Runtime::get().unwrap().as_ptr()) }
}
pub(crate) fn get_js_runtime(&self) -> Ref<'_, Option<Rc<Runtime>>> {
self.js_runtime.borrow()
}
pub(crate) fn main_thread_script_chan(&self) -> &Sender<MainThreadScriptMsg> {
&self.script_chan
}
pub(crate) fn parent_info(&self) -> Option<PipelineId> {
self.parent_info
}
pub(crate) fn new_script_pair(&self) -> (ScriptEventLoopSender, ScriptEventLoopReceiver) {
let (sender, receiver) = unbounded();
(
ScriptEventLoopSender::MainThread(sender),
ScriptEventLoopReceiver::MainThread(receiver),
)
}
pub(crate) fn event_loop_sender(&self) -> ScriptEventLoopSender {
ScriptEventLoopSender::MainThread(self.script_chan.clone())
}
pub(crate) fn image_cache(&self) -> Arc<dyn ImageCache> {
self.image_cache.clone()
}
/// This can panic if it is called after the browsing context has been discarded
pub(crate) fn window_proxy(&self) -> DomRoot<WindowProxy> {
self.window_proxy.get().unwrap()
}
pub(crate) fn append_reporting_observer(&self, reporting_observer: DomRoot<ReportingObserver>) {
self.reporting_observer_list
.borrow_mut()
.push(reporting_observer);
}
pub(crate) fn remove_reporting_observer(&self, reporting_observer: &ReportingObserver) {
let index = {
let list = self.reporting_observer_list.borrow();
list.iter()
.position(|observer| &**observer == reporting_observer)
};
if let Some(index) = index {
self.reporting_observer_list.borrow_mut().remove(index);
}
}
pub(crate) fn registered_reporting_observers(&self) -> Vec<DomRoot<ReportingObserver>> {
self.reporting_observer_list.borrow().clone()
}
pub(crate) fn append_report(&self, report: Report) {
self.report_list.borrow_mut().push(report);
let trusted_window = Trusted::new(self);
self.upcast::<GlobalScope>()
.task_manager()
.dom_manipulation_task_source()
.queue(task!(send_to_reporting_endpoints: move || {
let window = trusted_window.root();
let reports = std::mem::take(&mut *window.report_list.borrow_mut());
window.upcast::<GlobalScope>().send_reports_to_endpoints(
reports,
window.endpoints_list.borrow().clone(),
);
}));
}
pub(crate) fn buffered_reports(&self) -> Vec<Report> {
self.report_list.borrow().clone()
}
pub(crate) fn set_endpoints_list(&self, endpoints: Vec<ReportingEndpoint>) {
*self.endpoints_list.borrow_mut() = endpoints;
}
/// Returns the window proxy if it has not been discarded.
/// <https://html.spec.whatwg.org/multipage/#a-browsing-context-is-discarded>
pub(crate) fn undiscarded_window_proxy(&self) -> Option<DomRoot<WindowProxy>> {
self.window_proxy.get().and_then(|window_proxy| {
if window_proxy.is_browsing_context_discarded() {
None
} else {
Some(window_proxy)
}
})
}
/// Get the active [`Document`] of top-level browsing context, or return [`Window`]'s [`Document`]
/// if it's browing context is the top-level browsing context. Returning none if the [`WindowProxy`]
/// is discarded or the [`Document`] is in another `ScriptThread`.
/// <https://html.spec.whatwg.org/multipage/#top-level-browsing-context>
pub(crate) fn top_level_document_if_local(&self) -> Option<DomRoot<Document>> {
if self.is_top_level() {
return Some(self.Document());
}
let window_proxy = self.undiscarded_window_proxy()?;
self.script_window_proxies
.find_window_proxy(window_proxy.webview_id().into())?
.document()
}
#[cfg(feature = "bluetooth")]
pub(crate) fn bluetooth_thread(&self) -> GenericSender<BluetoothRequest> {
self.bluetooth_thread.clone()
}
#[cfg(feature = "bluetooth")]
pub(crate) fn bluetooth_extra_permission_data(&self) -> &BluetoothExtraPermissionData {
&self.bluetooth_extra_permission_data
}
pub(crate) fn css_error_reporter(&self) -> &CSSErrorReporter {
&self.error_reporter
}
pub(crate) fn webgl_chan(&self) -> Option<WebGLChan> {
self.webgl_chan.clone()
}
// TODO: rename the function to webgl_chan after the existing `webgl_chan` function is removed.
pub(crate) fn webgl_chan_value(&self) -> Option<WebGLChan> {
self.webgl_chan.clone()
}
#[cfg(feature = "webxr")]
pub(crate) fn webxr_registry(&self) -> Option<webxr_api::Registry> {
self.webxr_registry.clone()
}
fn new_paint_worklet(&self, can_gc: CanGc) -> DomRoot<Worklet> {
debug!("Creating new paint worklet.");
Worklet::new(self, WorkletGlobalScopeType::Paint, can_gc)
}
pub(crate) fn register_image_cache_listener(
&self,
id: PendingImageId,
callback: impl Fn(PendingImageResponse, &mut js::context::JSContext) + 'static,
) -> ImageCacheResponseCallback {
self.pending_image_callbacks
.borrow_mut()
.entry(id)
.or_default()
.push(PendingImageCallback(Box::new(callback)));
let image_cache_sender = self.image_cache_sender.clone();
Box::new(move |message| {
let _ = image_cache_sender.send(message);
})
}
fn pending_layout_image_notification(&self, response: PendingImageResponse) {
let mut images = self.pending_layout_images.borrow_mut();
let nodes = images.entry(response.id);
let nodes = match nodes {
Entry::Occupied(nodes) => nodes,
Entry::Vacant(_) => return,
};
if matches!(
response.response,
ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode
) {
for ancillary_data in nodes.get() {
match ancillary_data.destination {
LayoutImageDestination::BoxTreeConstruction => {
ancillary_data.node.dirty(NodeDamage::Other);
},
LayoutImageDestination::DisplayListBuilding => {
self.layout().set_needs_new_display_list();
},
}
}
}
match response.response {
ImageResponse::MetadataLoaded(_) => {},
ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
nodes.remove();
},
}
}
pub(crate) fn handle_image_rasterization_complete_notification(
&self,
response: RasterizationCompleteResponse,
) {
let mut images = self.pending_images_for_rasterization.borrow_mut();
let nodes = images.entry((response.image_id, response.requested_size));
let nodes = match nodes {
Entry::Occupied(nodes) => nodes,
Entry::Vacant(_) => return,
};
for node in nodes.get() {
node.dirty(NodeDamage::Other);
}
nodes.remove();
}
pub(crate) fn pending_image_notification(
&self,
response: PendingImageResponse,
cx: &mut js::context::JSContext,
) {
// We take the images here, in order to prevent maintaining a mutable borrow when
// image callbacks are called. These, in turn, can trigger garbage collection.
// Normally this shouldn't trigger more pending image notifications, but just in
// case we do not want to cause a double borrow here.
let mut images = std::mem::take(&mut *self.pending_image_callbacks.borrow_mut());
let Entry::Occupied(callbacks) = images.entry(response.id) else {
let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
return;
};
for callback in callbacks.get() {
callback.0(response.clone(), cx);
}
match response.response {
ImageResponse::MetadataLoaded(_) => {},
ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
callbacks.remove();
},
}
let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
}
pub(crate) fn paint_api(&self) -> &CrossProcessPaintApi {
&self.paint_api
}
pub(crate) fn userscripts(&self) -> &[UserScript] {
&self.user_scripts
}
pub(crate) fn get_player_context(&self) -> WindowGLContext {
self.player_context.clone()
}
// see note at https://dom.spec.whatwg.org/#concept-event-dispatch step 2
pub(crate) fn dispatch_event_with_target_override(&self, event: &Event, can_gc: CanGc) {
event.dispatch(self.upcast(), true, can_gc);
}
pub(crate) fn font_context(&self) -> &Arc<FontContext> {
self.as_global_scope()
.font_context()
.expect("A `Window` should always have a `FontContext`")
}
pub(crate) fn ongoing_navigation(&self) -> OngoingNavigation {
self.ongoing_navigation.get()
}
/// <https://html.spec.whatwg.org/multipage/#set-the-ongoing-navigation>
pub(crate) fn set_ongoing_navigation(&self) -> OngoingNavigation {
// Note: since this value, for now, is only used in a single `ScriptThread`,
// we just increment it (it is not a uuid), which implies not
// using a `newValue` variable.
let new_value = self.ongoing_navigation.get().0.wrapping_add(1);
// 1. If navigable's ongoing navigation is equal to newValue, then return.
// Note: cannot happen in the way it is currently used.
// TODO: 2. Inform the navigation API about aborting navigation given navigable.
// 3. Set navigable's ongoing navigation to newValue.
self.ongoing_navigation.set(OngoingNavigation(new_value));
// Note: Return the ongoing navigation for the caller to use.
OngoingNavigation(new_value)
}
/// <https://html.spec.whatwg.org/multipage/#nav-stop>
fn stop_loading(&self, cx: &mut js::context::JSContext) {
// 1. Let document be navigable's active document.
let doc = self.Document();
// 2. If document's unload counter is 0,
// and navigable's ongoing navigation is a navigation ID,
// then set the ongoing navigation for navigable to null.
//
// Note: since the concept of `navigable` is nascent in Servo,
// for now we do two things:
// - increment the `ongoing_navigation`(preventing planned form navigations).
// - Send a `AbortLoadUrl` message(in case the navigation
// already started at the constellation).
self.set_ongoing_navigation();
// 3. Abort a document and its descendants given document.
doc.abort(cx);
}
/// <https://html.spec.whatwg.org/multipage/#destroy-a-top-level-traversable>
fn destroy_top_level_traversable(&self, cx: &mut js::context::JSContext) {
// Step 1. Let browsingContext be traversable's active browsing context.
// TODO
// Step 2. For each historyEntry in traversable's session history entries:
// TODO
// Step 2.1. Let document be historyEntry's document.
let document = self.Document();
// Step 2.2. If document is not null, then destroy a document and its descendants given document.
document.destroy_document_and_its_descendants(cx);
// Step 3-6.
self.send_to_constellation(ScriptToConstellationMessage::DiscardTopLevelBrowsingContext);
}
/// <https://html.spec.whatwg.org/multipage/#definitely-close-a-top-level-traversable>
fn definitely_close(&self, cx: &mut js::context::JSContext) {
let document = self.Document();
// Step 1. Let toUnload be traversable's active document's inclusive descendant navigables.
//
// Implemented by passing `false` into the method below
// Step 2. If the result of checking if unloading is canceled for toUnload is not "continue", then return.
if !document.check_if_unloading_is_cancelled(false, CanGc::from_cx(cx)) {
return;
}
// Step 3. Append the following session history traversal steps to traversable:
// TODO
// Step 3.2. Unload a document and its descendants given traversable's active document, null, and afterAllUnloads.
document.unload(false, CanGc::from_cx(cx));
// Step 3.1. Let afterAllUnloads be an algorithm step which destroys traversable.
self.destroy_top_level_traversable(cx);
}
/// <https://html.spec.whatwg.org/multipage/#cannot-show-simple-dialogs>
fn cannot_show_simple_dialogs(&self) -> bool {
// Step 1: If the active sandboxing flag set of window's associated Document has
// the sandboxed modals flag set, then return true.
if self
.Document()
.has_active_sandboxing_flag(SandboxingFlagSet::SANDBOXED_MODALS_FLAG)
{
return true;
}
// Step 2: If window's relevant settings object's origin and window's relevant settings
// object's top-level origin are not same origin-domain, then return true.
//
// TODO: This check doesn't work currently because it seems that comparing two
// opaque domains doesn't work between GlobalScope::top_level_creation_url and
// Document::origin().
// Step 3: If window's relevant agent's event loop's termination nesting level is nonzero,
// then optionally return true.
// TODO: This is unsupported currently.
// Step 4: Optionally, return true. (For example, the user agent might give the
// user the option to ignore all modal dialogs, and would thus abort at this step
// whenever the method was invoked.)
// TODO: The embedder currently cannot block an alert before it is sent to the embedder. This
// requires changes to the API.
// Step 5: Return false.
false
}
pub(crate) fn perform_a_microtask_checkpoint(&self, cx: &mut js::context::JSContext) {
self.script_thread().perform_a_microtask_checkpoint(cx);
}
pub(crate) fn web_font_context(&self) -> WebFontDocumentContext {
let global = self.as_global_scope();
WebFontDocumentContext {
policy_container: global.policy_container(),
request_client: global.request_client(),
document_url: global.api_base_url(),
has_trustworthy_ancestor_origin: global.has_trustworthy_ancestor_origin(),
insecure_requests_policy: global.insecure_requests_policy(),
csp_handler: Box::new(FontCspHandler {
global: Trusted::new(global),
task_source: global
.task_manager()
.dom_manipulation_task_source()
.to_sendable(),
}),
network_timing_handler: Box::new(FontNetworkTimingHandler {
global: Trusted::new(global),
task_source: global
.task_manager()
.dom_manipulation_task_source()
.to_sendable(),
}),
}
}
#[expect(unsafe_code)]
pub(crate) fn gc(&self) {
unsafe {
JS_GC(*self.get_cx(), GCReason::API);
}
}
}
#[derive(Debug)]
struct FontCspHandler {
global: Trusted<GlobalScope>,
task_source: SendableTaskSource,
}
impl CspViolationHandler for FontCspHandler {
fn process_violations(&self, violations: Vec<Violation>) {
let global = self.global.clone();
self.task_source.queue(task!(csp_violation: move || {
global.root().report_csp_violations(violations, None, None);
}));
}
fn clone(&self) -> Box<dyn CspViolationHandler> {
Box::new(Self {
global: self.global.clone(),
task_source: self.task_source.clone(),
})
}
}
#[derive(Debug)]
struct FontNetworkTimingHandler {
global: Trusted<GlobalScope>,
task_source: SendableTaskSource,
}
impl NetworkTimingHandler for FontNetworkTimingHandler {
fn submit_timing(&self, url: ServoUrl, response: ResourceFetchTiming) {
let global = self.global.clone();
self.task_source.queue(task!(network_timing: move |cx| {
submit_timing(
cx,
&FontFetchListener {
url,
global
},
&Ok(()),
&response,
);
}));
}