From 32cd63f6a4ccbd4b1c3e98740dfffe19a48862a1 Mon Sep 17 00:00:00 2001 From: ldm0 Date: Tue, 24 Nov 2026 08:23:23 +0800 Subject: [PATCH] fix(rebase): reconcile the native runtime with origin/main --- Cargo.lock | 24 +- moli-dom/src/forms/input_type.rs | 4 +- moli-dom/src/native/element/mod.rs | 5 +- .../src/native/host/frame_candidate_tests.rs | 8 +- moli-layout/src/lib.rs | 11 +- moli-parser/src/session.rs | 5 +- moli-renderer-v8/src/context_bootstrap.rs | 18 +- .../bridge_descriptor/descriptors.rs | 8 + .../css_runtime/typed_om/map.rs | 4 +- .../src/context_bootstrap/event_template.rs | 33 +- .../src/context_bootstrap/events.rs | 1 + .../media_queries/evaluation.rs | 1 + .../events/simple_event_target/listeners.rs | 26 +- .../src/context_bootstrap/viewport_edit.rs | 8 +- .../src/context_bootstrap/window_template.rs | 8 + .../src/document_runtime/events.rs | 202 +++ .../src/document_runtime/security_policy.rs | 660 ++++++---- moli-renderer-v8/src/host.rs | 7 +- moli-renderer-v8/src/host/events.rs | 1162 ++++++++++------- .../child_documents/live_parser.rs | 4 + .../context_host/child_documents/loads.rs | 5 +- .../context_host/child_events.rs | 376 +++--- .../child_frame_navigation/commands.rs | 64 +- .../context_host/child_frames.rs | 4 - .../context_host/event_callbacks.rs | 66 +- .../src/native_bridge/context_host/layout.rs | 17 +- .../src/native_bridge/context_host/mod.rs | 2 +- .../src/native_bridge/context_host/popups.rs | 78 +- .../context_host/security_policy.rs | 14 +- .../operation_receiver.rs | 82 +- .../context_host/window_security_tokens.rs | 2 +- moli-renderer-v8/src/native_bridge/element.rs | 67 +- .../element/event_handlers/generic.rs | 273 ++-- .../element/event_handlers/mod.rs | 70 +- .../src/native_bridge/element/events.rs | 14 +- .../element/events/constructors.rs | 11 +- .../element/geometry/hit_test.rs | 19 +- .../native_bridge/element/styles/methods.rs | 2 + .../native_bridge/element/trusted_types.rs | 6 +- moli-renderer-v8/src/native_bridge/mod.rs | 9 +- moli-renderer-v8/src/runtime/page_vm/mod.rs | 4 +- .../page_vm/tests/rendering_update/print.rs | 10 +- .../src/script_vm/child_frame_runtime.rs | 5 +- .../src/script_vm/input_dispatch.rs | 113 +- .../input_dispatch/mouse_boundary.rs | 3 +- moli-renderer-v8/src/script_vm/layout.rs | 2 +- .../src/script_vm/page_task_enqueue.rs | 8 +- .../src/script_vm/script_event_body.rs | 83 +- .../script_vm/subresource_fetch/streaming.rs | 3 +- .../tests/browser_api/event_handlers.rs | 560 ++++++-- .../event_dispatch_and_targets.rs | 24 +- .../browser_api/native_event_construction.rs | 30 +- ...legacy_resources_and_document_mutations.rs | 19 +- .../live_document/geometry_and_svg.rs | 10 - .../tests/dom_elements/viewport_input.rs | 2 +- .../tests/dom_xhr/dom/pointer_and_mouse.rs | 4 +- .../src/script_vm/tests/dom_xhr/xhr.rs | 1 - .../tests/extracted/realms_and_teardown.rs | 1 + moli-renderer-v8/src/script_vm/tests/mod.rs | 3 - .../src/script_vm/tests/post_parse.rs | 14 +- .../src/script_vm/tests/sqlite_web_storage.rs | 17 +- moli-renderer-v8/src/structured_clone.rs | 2 - .../src/style_engine/runtime_invalidation.rs | 5 +- .../src/stylesheet_runtime/connected.rs | 7 +- moli-renderer-v8/src/util.rs | 1 - .../global_scope/content_security_policy.rs | 8 +- .../worker/thread/tests/modules/module_map.rs | 11 +- 67 files changed, 2600 insertions(+), 1730 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5543b822855..e017c95aa9b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2501,7 +2501,7 @@ version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef975e30683b2d965054bb0a836f8973857c4ebf6acf274fe46617cd285060d8" dependencies = [ - "foldhash", + "foldhash 0.2.0", "libm", "portable-atomic", "siphasher", @@ -2922,8 +2922,8 @@ dependencies = [ "libc", "log", "rustversion", - "windows-link", - "windows-result", + "windows-link 0.1.3", + "windows-result 0.3.4", ] [[package]] @@ -4252,9 +4252,9 @@ dependencies = [ "jni-sys 0.4.1", "log", "simd_cesu8", - "thiserror", + "thiserror 2.0.18", "walkdir", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -4976,7 +4976,7 @@ dependencies = [ "half", "moli-image", "moli-web-mime", - "strum", + "strum 0.28.0", ] [[package]] @@ -5110,7 +5110,7 @@ dependencies = [ "moli-web-storage", "moli-wpt-compat", "parking_lot", - "percent-encoding 2.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "percent-encoding", "sanitize-filename", "serde", "serde_json", @@ -5484,7 +5484,7 @@ dependencies = [ "matroska-demuxer", "ogg", "shiguredo_libvpx", - "thiserror", + "thiserror 2.0.18", ] [[package]] @@ -8084,7 +8084,7 @@ dependencies = [ "rustc-hash 2.1.1", "rustls", "socket2", - "thiserror", + "thiserror 2.0.18", "tokio", "tracing", "web-time", @@ -8109,7 +8109,7 @@ dependencies = [ "rustls-pki-types", "rustls-platform-verifier", "slab", - "thiserror", + "thiserror 2.0.18", "tinyvec", "tracing", "web-time", @@ -11065,7 +11065,7 @@ dependencies = [ "bytes", "http", "sfv", - "thiserror", + "thiserror 2.0.18", "tokio", "url", ] @@ -11081,7 +11081,7 @@ dependencies = [ "quinn", "rustls", "rustls-native-certs", - "thiserror", + "thiserror 2.0.18", "tokio", "tracing", "url", diff --git a/moli-dom/src/forms/input_type.rs b/moli-dom/src/forms/input_type.rs index 2c3a4a7fe42..0b5209a8f84 100644 --- a/moli-dom/src/forms/input_type.rs +++ b/moli-dom/src/forms/input_type.rs @@ -291,10 +291,10 @@ pub fn email_value_type_mismatch(value: &str, multiple: bool) -> bool { if multiple { return value .split(',') - .map(|address| address.trim_matches(is_ascii_whitespace_char)) + .map(str::trim_ascii) .any(|address| address.is_empty() || !is_valid_email_address(address)); } - !is_valid_email_address(value.trim_matches(is_ascii_whitespace_char)) + !is_valid_email_address(value.trim_ascii()) } pub fn is_valid_email_address(value: &str) -> bool { diff --git a/moli-dom/src/native/element/mod.rs b/moli-dom/src/native/element/mod.rs index cf581109c2e..64eef14584e 100644 --- a/moli-dom/src/native/element/mod.rs +++ b/moli-dom/src/native/element/mod.rs @@ -72,7 +72,10 @@ fn initial_custom_element_state_for_identity( fn is_element_reference_attribute(name: &str) -> bool { matches!( name, - "aria-activedescendant" + "commandfor" + | "interestfor" + | "popovertarget" + | "aria-activedescendant" | "aria-controls" | "aria-describedby" | "aria-details" diff --git a/moli-dom/src/native/host/frame_candidate_tests.rs b/moli-dom/src/native/host/frame_candidate_tests.rs index 3abe5d213c4..a6a799e4273 100644 --- a/moli-dom/src/native/host/frame_candidate_tests.rs +++ b/moli-dom/src/native/host/frame_candidate_tests.rs @@ -65,7 +65,7 @@ fn reconnecting_shadow_trees_restores_compacted_frame_candidates() { host.child_browsing_context_host_candidate_handles() .is_empty() ); - assert!(frames(&host, outer).is_empty()); + assert_eq!(frames(&host, outer), vec![frame]); assert!(host.append_child(body, outer)); assert_eq!( @@ -76,7 +76,7 @@ fn reconnecting_shadow_trees_restores_compacted_frame_candidates() { assert!(host.remove_child(body, outer)); host.compact_child_browsing_context_host_candidates(); assert!(frames(&host, body).is_empty()); - assert!(frames(&host, shadow).is_empty()); + assert_eq!(frames(&host, shadow), vec![frame]); assert!(host.append_child(body, outer)); assert_eq!( @@ -115,7 +115,7 @@ fn cloned_imported_and_adopted_shadow_frames_keep_candidate_membership() { assert!(host.append_child(secondary, cloned)); host.compact_child_browsing_context_host_candidates(); assert_eq!(frames(&host, body), vec![imported_frame]); - assert!(frames(&host, secondary).is_empty()); + assert_eq!(frames(&host, secondary), vec![clone_frame]); assert_eq!(host.owner_document_handle(clone_frame), Some(secondary)); assert!(host.append_child(body, cloned)); @@ -153,5 +153,5 @@ fn frame_candidates_exclude_inert_template_contents_and_foreign_elements() { assert_eq!(frames(&host, body), vec![live_frame]); assert!(frames(&host, template).is_empty()); - assert!(frames(&host, contents).is_empty()); + assert_eq!(frames(&host, contents), vec![inert_frame]); } diff --git a/moli-layout/src/lib.rs b/moli-layout/src/lib.rs index 56ea1111504..b826e841afc 100644 --- a/moli-layout/src/lib.rs +++ b/moli-layout/src/lib.rs @@ -61,11 +61,12 @@ pub use layout_tree::{ LayoutFragmentKind, LayoutHit, LayoutIntersectionClip, LayoutIntersectionGeometry, LayoutNodeOutput, LayoutObjectGeometry, LayoutOutputBoxId, LayoutPaintedSurfaceHit, LayoutPassMetrics, LayoutPassResult, LayoutPoint, LayoutQuad, LayoutQuery, LayoutQueryAnswer, - LayoutQueryBatch, LayoutRect, LayoutResizeObserverBox, LayoutResizeObserverMetrics, LayoutResizeObserverSize, - LayoutResolvedGridTrackList, LayoutResolvedGridTracks, LayoutScrollContainerMetrics, - LayoutScrollExtent, LayoutScrollIntoViewGeometry, LayoutSize, LayoutTextGeometryRange, LayoutTransform2D, - LayoutTreeRetentionMetrics, LayoutUsedSize, LayoutViewport, MAX_RETAINED_LAYOUT_BOXES, - MAX_RETAINED_LAYOUT_FRAGMENTS, MAX_RETAINED_LAYOUT_TREE_BYTES, ScrollProjectionRefresh, + LayoutQueryBatch, LayoutRect, LayoutResizeObserverBox, LayoutResizeObserverMetrics, + LayoutResizeObserverSize, LayoutResolvedGridTrackList, LayoutResolvedGridTracks, + LayoutScrollContainerMetrics, LayoutScrollExtent, LayoutScrollIntoViewGeometry, LayoutSize, + LayoutTextGeometryRange, LayoutTransform2D, LayoutTreeRetentionMetrics, LayoutUsedSize, + LayoutViewport, MAX_RETAINED_LAYOUT_BOXES, MAX_RETAINED_LAYOUT_FRAGMENTS, + MAX_RETAINED_LAYOUT_TREE_BYTES, ScrollProjectionRefresh, }; pub use list::{ListCounter, list_marker_text}; pub use normalize::{NormalizedBoxNode, NormalizedBoxTree, NormalizedFormattingContext}; diff --git a/moli-parser/src/session.rs b/moli-parser/src/session.rs index e5824e6a380..602999dad5e 100644 --- a/moli-parser/src/session.rs +++ b/moli-parser/src/session.rs @@ -1,4 +1,7 @@ -use std::cell::{Cell, RefCell}; +use std::{ + cell::{Cell, RefCell}, + rc::Rc, +}; use html5ever::{ ParseOpts, diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs index c7a49bc7de6..64a0751f597 100644 --- a/moli-renderer-v8/src/context_bootstrap.rs +++ b/moli-renderer-v8/src/context_bootstrap.rs @@ -101,7 +101,6 @@ pub(crate) use indexed_db::{ mod location_history_storage; mod location_navigation; mod location_runtime; -pub(crate) use location_runtime::install_constructed_document_location_runtime_state; mod media_cues; pub(crate) use media_cues::new_media_error_value; mod media_file_template; @@ -272,10 +271,6 @@ pub(crate) use navigation_events::{ dispatch_beforeunload_for_runtime_owner, dispatch_pagehide_for_runtime_owner, dispatch_pageswap_for_runtime_owner, dispatch_unload_for_runtime_owner, }; -pub(crate) use navigation_events::{ - dispatch_cross_document_navigation_navigate_event_for_window_with_form_data, - dispatch_cross_document_navigation_navigate_event_for_window_with_type_and_form_data, -}; pub(crate) use navigation_history_pruning::{ NavigationHistoryPrunePlan, apply_navigation_history_prune_plan, finalize_navigation_history_prune, plan_navigation_history_prune, @@ -677,14 +672,11 @@ pub(crate) use self::websocket::{ WebSocketDispatchResult, WebSocketStreamAbortRegistration, dispatch_websocket_event, }; pub(crate) use self::window_events::{ - WINDOW_EVENT_HANDLER_PROPERTIES, - clear_simple_window_event_handler_values, dispatch_window_callback_exception, - dispatch_window_error_event, dispatch_window_error_event_with_details, - dispatch_window_promise_rejection_event, dispatch_window_report_error_message, - event_handler_property_is_exposed, install_secure_window_event_handler_accessors, - install_simple_window_event_handlers, - is_window_event_handler_property, set_window_body_onerror_handler_compiled, - set_window_onerror_handler_value, window_body_onerror_handler_is_compiled, + WINDOW_EVENT_HANDLER_PROPERTIES, clear_simple_window_event_handler_values, + dispatch_window_callback_exception, dispatch_window_error_event, + dispatch_window_error_event_with_details, dispatch_window_promise_rejection_event, + dispatch_window_report_error_message, install_secure_window_event_handler_accessors, + install_simple_window_event_handlers, is_window_event_handler_property, window_event_handler_properties, }; #[cfg(test)] diff --git a/moli-renderer-v8/src/context_bootstrap/bridge_descriptor/descriptors.rs b/moli-renderer-v8/src/context_bootstrap/bridge_descriptor/descriptors.rs index 188b32723f6..50cbad088e8 100644 --- a/moli-renderer-v8/src/context_bootstrap/bridge_descriptor/descriptors.rs +++ b/moli-renderer-v8/src/context_bootstrap/bridge_descriptor/descriptors.rs @@ -139,6 +139,10 @@ const NODE_BRIDGE_DESCRIPTORS: &[BridgeDescriptor] = &[ SpecializedTemplateInstaller::None, SVG_GEOMETRY_RUNTIME_INSTALL_GROUPS, ), + descriptor( + web_api_interfaces::SVGFilterElement::DESCRIPTOR, + ELEMENT_GROUPS, + ), descriptor( web_api_interfaces::SVGDefsElement::DESCRIPTOR, ELEMENT_GROUPS, @@ -414,6 +418,10 @@ const NODE_BRIDGE_DESCRIPTORS: &[BridgeDescriptor] = &[ web_api_interfaces::SVGUseElement::DESCRIPTOR, ELEMENT_GROUPS, ), + descriptor( + web_api_interfaces::SVGViewElement::DESCRIPTOR, + ELEMENT_GROUPS, + ), specialized_descriptor( web_api_interfaces::SVGRectElement::DESCRIPTOR, ELEMENT_GROUPS, diff --git a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/map.rs b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/map.rs index 435fb550412..bb39bc222e6 100644 --- a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/map.rs +++ b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/map.rs @@ -421,7 +421,9 @@ fn map_property_names<'s>( style: v8::Local<'s, v8::Object>, ) -> Option> { if !native_bridge::element::style_declaration_is_computed(scope, style) { - return Some(detached_css_style::css_declaration_property_names(scope, style)); + return Some(detached_css_style::css_declaration_property_names( + scope, style, + )); } // Computed CSSStyleDeclaration and Typed OM enumerate one public property list. let mut names = native_bridge::element::style_property_names_from_object(scope, style)?; diff --git a/moli-renderer-v8/src/context_bootstrap/event_template.rs b/moli-renderer-v8/src/context_bootstrap/event_template.rs index 57e7d5d0572..cfbe5e5d70e 100644 --- a/moli-renderer-v8/src/context_bootstrap/event_template.rs +++ b/moli-renderer-v8/src/context_bootstrap/event_template.rs @@ -4,22 +4,22 @@ use super::{ event_init_event_callback, mouse_event_init_callback, text_event_init_callback, }, events::{ - composition_event_init_callback, event_bubbles_getter_function, - event_cancel_bubble_getter_function, event_cancel_bubble_setter_function, - event_cancelable_getter_function, event_composed_getter_function, - event_composed_path_callback, event_current_target_getter_function, - event_default_prevented_getter_function, event_event_phase_getter_function, - event_get_modifier_state_callback, event_platform_attribute_getter, - event_prevent_default_callback, event_return_value_getter_function, - event_return_value_setter_function, event_src_element_getter_function, - event_stop_immediate_propagation_callback, event_stop_propagation_callback, - event_target_getter_function, event_time_stamp_getter_function, event_type_getter_function, - event_value_attribute_getter, focus_event_related_target_getter_function, - form_data_event_form_data_getter_function, input_event_get_target_ranges_callback, - interaction_event_source_getter, keyboard_event_init_callback, - mouse_event_related_target_getter_function, pointer_event_get_predicted_events_callback, - submit_event_submitter_getter_function, time_event_init_callback, ui_event_init_callback, - ui_event_pseudo_target_getter_function, ui_event_which_getter_function, + event_bubbles_getter_function, event_cancel_bubble_getter_function, + event_cancel_bubble_setter_function, event_cancelable_getter_function, + event_composed_getter_function, event_composed_path_callback, + event_current_target_getter_function, event_default_prevented_getter_function, + event_event_phase_getter_function, event_get_modifier_state_callback, + event_platform_attribute_getter, event_prevent_default_callback, + event_return_value_getter_function, event_return_value_setter_function, + event_src_element_getter_function, event_stop_immediate_propagation_callback, + event_stop_propagation_callback, event_target_getter_function, + event_time_stamp_getter_function, event_type_getter_function, event_value_attribute_getter, + focus_event_related_target_getter_function, form_data_event_form_data_getter_function, + input_event_get_target_ranges_callback, interaction_event_source_getter, + keyboard_event_init_callback, mouse_event_related_target_getter_function, + pointer_event_get_predicted_events_callback, submit_event_submitter_getter_function, + time_event_init_callback, ui_event_pseudo_target_getter_function, + ui_event_which_getter_function, }, selection_surface::document_get_selection_callback, specs::ConstructorSpec, @@ -28,6 +28,7 @@ use crate::util::v8str; use crate::web_api_interfaces; use crate::{native_bridge::document, window_host}; use moli_webapi::events::subclasses::EventTemplateDeclaration; +use moli_webapi::events::ui::{composition_event_init_callback, ui_event_init_callback}; use moli_webapi_declare::WebApiFunctionTemplate; #[derive(WebApiFunctionTemplate)] diff --git a/moli-renderer-v8/src/context_bootstrap/events.rs b/moli-renderer-v8/src/context_bootstrap/events.rs index 869247f79c7..05f7d22f65c 100644 --- a/moli-renderer-v8/src/context_bootstrap/events.rs +++ b/moli-renderer-v8/src/context_bootstrap/events.rs @@ -22,6 +22,7 @@ pub(crate) use moli_webapi::events::subclasses::submit::{ use moli_webapi::events::value; pub(crate) use subclasses::clear_input_event_target_ranges; pub(crate) use subclasses::initialize_native_security_policy_violation_event; +pub(in crate::context_bootstrap) use subclasses::input_event_get_target_ranges_callback; mod time; mod wrappers; diff --git a/moli-renderer-v8/src/context_bootstrap/media_queries/evaluation.rs b/moli-renderer-v8/src/context_bootstrap/media_queries/evaluation.rs index de305bb0fbe..0c80012895a 100644 --- a/moli-renderer-v8/src/context_bootstrap/media_queries/evaluation.rs +++ b/moli-renderer-v8/src/context_bootstrap/media_queries/evaluation.rs @@ -12,6 +12,7 @@ use crate::context_bootstrap::{ MEDIA_QUERY_LIST_REGISTRY_SLOT, }; use crate::context_bootstrap::{global_queue_array, push_object_to_global_registry}; +use crate::event_type::EventTypeKey; use crate::native_bridge::{ PageScriptHost, WindowDocumentTaskTarget, WindowExecutionContextBinding, }; diff --git a/moli-renderer-v8/src/context_bootstrap/media_queries/events/simple_event_target/listeners.rs b/moli-renderer-v8/src/context_bootstrap/media_queries/events/simple_event_target/listeners.rs index 5f16309d07c..a99844f5b21 100644 --- a/moli-renderer-v8/src/context_bootstrap/media_queries/events/simple_event_target/listeners.rs +++ b/moli-renderer-v8/src/context_bootstrap/media_queries/events/simple_event_target/listeners.rs @@ -148,7 +148,7 @@ impl<'s> SimpleObjectEventListenerSnapshot<'s> { &self, scope: &mut v8::PinScope<'s, '_>, registry: SimpleEventListenerRegistry<'s>, - event_type: &str, + event_type: &(impl EventTypeKey + ?Sized), ) -> Option { // Removing and re-adding the same callback creates a different entry. // The removed entry must stay inactive in an existing dispatch snapshot. @@ -156,6 +156,27 @@ impl<'s> SimpleObjectEventListenerSnapshot<'s> { return None; } let listener = if self.handler_slot.is_some() { + let target = get_private_value(scope, self.entry, HANDLER_TARGET_SLOT) + .and_then(|value| v8::Local::::try_from(value).ok())?; + if let Some(popup_id) = lightweight_popup_id_from_window(scope, target) + && let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) + { + let value = unsafe { &mut *host_ptr } + .lightweight_popup_event_handler_property_value( + scope, + popup_id, + self.handler_slot.as_deref()?, + )?; + // A failed lazy compilation returns null for this read even + // if its error handler has installed a replacement callback. + if !value.is_object() + || !simple_object_event_listener_entry_registered( + scope, registry, event_type, self.entry, + ) + { + return None; + } + } // An active handler keeps its registration position, but its value // and callback contexts can change before dispatch reaches it. simple_object_event_listener_snapshot_entry(scope, self.entry.into())? @@ -1095,6 +1116,9 @@ fn simple_object_event_handler_entry_object<'s>( relevant_identity: Option, ) -> v8::Local<'s, v8::Object> { let marker = format!("event-handler:{handler_slot_name}"); + let value = callback + .map(v8::Local::::from) + .unwrap_or_else(|| v8::null(scope).into()); let entry = SimpleObjectEventHandlerEntryDeclaration::new( v8_string(scope, &marker), v8_string(scope, handler_slot_name).expect("event handler slot"), diff --git a/moli-renderer-v8/src/context_bootstrap/viewport_edit.rs b/moli-renderer-v8/src/context_bootstrap/viewport_edit.rs index dadcbb8a006..f64d2412912 100644 --- a/moli-renderer-v8/src/context_bootstrap/viewport_edit.rs +++ b/moli-renderer-v8/src/context_bootstrap/viewport_edit.rs @@ -20,7 +20,7 @@ use crate::{ TextEditInputType, contenteditable_editing_host, dispatch_beforeinput, dispatch_public_event, is_text_control, is_text_control_user_editable, replace_contenteditable_selection_after_beforeinput, - replace_text_control_selection_after_beforeinput, + replace_text_control_selection_with_input_event, text_control_set_selection_range_internal, text_control_value, }, node_owner_document_relevant_context, @@ -401,7 +401,7 @@ impl ViewportEditing { revision, &range, &text, - TextEditInputType::InsertFromPaste, + TextEditInputType::InsertFromViewportPaste, ); if existing.is_some() { composition_event(scope, host_ptr, target, "compositionend", ""); @@ -499,9 +499,7 @@ fn replace_range( if live.map.is_some() { replace_contenteditable_selection_after_beforeinput(scope, host, target, text, input_type) } else { - replace_text_control_selection_after_beforeinput( - scope, host, target, text, input_type, None, - ) + replace_text_control_selection_with_input_event(scope, host, target, text, input_type, None) } } diff --git a/moli-renderer-v8/src/context_bootstrap/window_template.rs b/moli-renderer-v8/src/context_bootstrap/window_template.rs index ca1cd81268f..659cdae183e 100644 --- a/moli-renderer-v8/src/context_bootstrap/window_template.rs +++ b/moli-renderer-v8/src/context_bootstrap/window_template.rs @@ -30,6 +30,14 @@ use moli_webapi_declare::WebApiFunctionTemplate; const WINDOW_NAMED_PROPERTIES_READY_SLOT: &str = "__moliWindowNamedPropertiesReady"; const WINDOW_NAMED_PROPERTIES_REFLECT_SET_SLOT: &str = "__moliWindowNamedPropertiesReflectSet"; +pub(in crate::context_bootstrap) fn is_window_named_properties_object<'s>( + scope: &mut v8::PinScope<'s, '_>, + object: v8::Local<'s, v8::Object>, +) -> bool { + get_private_value(scope, object, WINDOW_NAMED_PROPERTIES_READY_SLOT) + .is_some_and(|value| value.is_true()) +} + #[derive(WebApiFunctionTemplate)] #[webapi(interface = web_api_interfaces::Window, enumerable, receiver = crate::context_bootstrap::is_window_receiver)] struct WindowEarlyTemplateMethodsDeclaration { diff --git a/moli-renderer-v8/src/document_runtime/events.rs b/moli-renderer-v8/src/document_runtime/events.rs index 50daf7ceed8..1257fb99541 100644 --- a/moli-renderer-v8/src/document_runtime/events.rs +++ b/moli-renderer-v8/src/document_runtime/events.rs @@ -439,6 +439,18 @@ impl DocumentRuntime { event_type: &(impl EventTypeKey + ?Sized), registration: crate::host::EventListenerRegistration, ) { + if !self + .events + .has_event_handler_property_entry(target, event_type) + { + let content_attribute_owner = + crate::host::event_handler_content_attribute(self, target, event_type); + self.events.ensure_event_handler_content_attribute( + target, + event_type, + content_attribute_owner, + ); + } self.events .insert_listener(target, event_type, registration); } @@ -775,3 +787,193 @@ fn source_target_for_reference_event( crate::native_bridge::node_runtime_and_handle_from_object(scope, object).ok()?; (runtime_ptr == host_ptr).then_some(EventTargetHandle::Node(handle)) } + +impl DocumentRuntime { + pub(crate) fn set_compiled_event_handler_property( + &mut self, + target: EventTargetHandle, + event_type: &(impl EventTypeKey + ?Sized), + callback_id: Option, + ) -> Option { + self.events + .set_compiled_event_handler_property(target, event_type, callback_id) + } + + pub(crate) fn sync_event_handler_content_attribute( + &mut self, + scope: &mut v8::PinScope<'_, '_>, + host_ptr: *mut PageScriptHost, + handle: DomHandle, + name: &str, + namespace: Option<&str>, + value: Option>, + ) -> Option { + if namespace.is_some() + || !crate::native_bridge::element::element_event_handler_content_attribute_applies( + self.dom_host(), + handle, + name, + ) + { + return None; + } + let event_type = name + .strip_prefix("on") + .filter(|event_type| !event_type.is_empty())?; + let event_type = + crate::native_bridge::element::canonical_event_handler_event_type(event_type); + let is_body_or_frameset = self.dom_host().node(handle).is_some_and(|node| { + node.is_html_element_named("body") || node.is_html_element_named("frameset") + }); + let reflects_window = is_body_or_frameset + && crate::native_bridge::element::body_or_frameset_reflects_window_event_type( + event_type, + ); + let owner = unsafe { &*host_ptr }.owner_dispatch_scope_for_node(handle); + if reflects_window && owner.is_none() { + return None; + } + let target = if reflects_window { + EventTargetHandle::Window + } else { + EventTargetHandle::Node(handle) + }; + let csp_allowed = value.as_ref().and_then(|source| { + let host = unsafe { &mut *host_ptr }; + if let Some(owner) = owner { + Some(host.allows_inline_event_handler_by_csp( + scope, + owner, + Some(handle), + source.as_str_lossy(), + )) + } else { + host.windowless_inline_event_handler_csp_admission( + scope, + handle, + source.as_str_lossy(), + ) + } + }); + if csp_allowed == Some(false) { + // A blocked change leaves an existing handler and its listener + // position intact. A fresh blocked attribute must also prevent the + // legacy prebuilt-DOM fallback from compiling its DOM value later. + if (!reflects_window || owner == Some(crate::native_bridge::OwnerDispatchScope::Top)) + && !self + .events + .has_event_handler_property_entry(target, event_type) + { + self.events + .set_event_handler_property(target, event_type, None); + } + return None; + } + // Admission is fixed at the attribute change, using the node + // Document's global. Uncommitted navigation projections retain the + // fallback until their actual settings are available. + let csp_admission = if csp_allowed == Some(true) { + crate::host::EventHandlerCspAdmission::Allowed + } else { + crate::host::EventHandlerCspAdmission::Pending + }; + let handler = value.map(|source| crate::host::UncompiledEventHandler { + source, + source_location: crate::host::UncompiledEventHandler::capture_source_location( + scope, + self.dom_host(), + handle, + name, + ), + csp_admission, + }); + if reflects_window { + match owner { + Some(crate::native_bridge::OwnerDispatchScope::Top) => {} + Some(crate::native_bridge::OwnerDispatchScope::Child(child_handle)) => { + return unsafe { &mut *host_ptr } + .set_child_window_event_handler_content_attribute( + child_handle, + event_type, + handler, + ); + } + Some(crate::native_bridge::OwnerDispatchScope::LightweightPopup(popup_id)) => { + unsafe { &mut *host_ptr } + .set_lightweight_popup_event_handler_content_attribute( + scope, popup_id, event_type, handler, + ); + return None; + } + None => return None, + }; + } + self.events + .set_event_handler_content_attribute(target, event_type, handler) + } + + pub(crate) fn initialize_cloned_event_handler_content_attributes( + &mut self, + scope: &mut v8::PinScope<'_, '_>, + host_ptr: *mut PageScriptHost, + root: DomHandle, + ) { + let mut stack = vec![root]; + while let Some(handle) = stack.pop() { + stack.extend(self.dom_host.child_handles(handle)); + stack.extend(self.dom_host.shadow_root_handle(handle)); + let Some(element) = self.dom_host.node(handle).and_then(Node::as_element) else { + continue; + }; + stack.extend(element.template_contents()); + let names = element + .attributes() + .iter() + .filter(|attribute| { + attribute.namespace().is_empty() + && crate::native_bridge::element::element_event_handler_content_attribute_applies( + &self.dom_host, + handle, + attribute.local_name(), + ) + }) + .map(|attribute| attribute.local_name().to_owned()) + .collect::>(); + for name in names { + let Some(source) = self + .dom_host + .dom() + .get_attribute_dom_string_value(handle, &name) + else { + continue; + }; + let location = crate::host::UncompiledEventHandler::capture_source_location( + scope, + &self.dom_host, + handle, + &name, + ); + self.set_attribute_source_location(handle, None, &name, Some(location)); + if let Some(previous) = self.sync_event_handler_content_attribute( + scope, + host_ptr, + handle, + &name, + None, + Some(std::sync::Arc::new(source)), + ) { + unsafe { &mut *host_ptr }.release_event_callback(previous); + } + } + } + } + + pub(crate) fn uncompiled_event_handler_content_attribute( + &self, + target: EventTargetHandle, + event_type: &(impl EventTypeKey + ?Sized), + ) -> Option { + self.events + .uncompiled_event_handler_content_attribute(target, event_type) + } +} diff --git a/moli-renderer-v8/src/document_runtime/security_policy.rs b/moli-renderer-v8/src/document_runtime/security_policy.rs index 0ec65cbf008..d1953d4a406 100644 --- a/moli-renderer-v8/src/document_runtime/security_policy.rs +++ b/moli-renderer-v8/src/document_runtime/security_policy.rs @@ -74,32 +74,33 @@ impl DocumentSubresourceCspKind { #[must_use = "report-only and enforced CSP results must be handled together"] #[derive(Default)] -pub(crate) struct DocumentContentSecurityPolicyCheck< - V = Option, -> { - report_only_violation: V, - enforced_violation: V, -} - -impl DocumentContentSecurityPolicyCheck { - pub(crate) fn into_violations(self) -> (V, V) { - (self.report_only_violation, self.enforced_violation) - } +pub(crate) struct DocumentContentSecurityPolicyCheck { + report_only_violations: Vec, + enforced_violations: Vec, } impl DocumentContentSecurityPolicyCheck { pub(crate) fn has_no_violations(&self) -> bool { - self.report_only_violation.is_none() && self.enforced_violation.is_none() + self.report_only_violations.is_empty() && self.enforced_violations.is_empty() + } + + pub(crate) fn into_violations( + self, + ) -> ( + Vec, + Vec, + ) { + (self.report_only_violations, self.enforced_violations) } #[cfg(test)] fn report_only_violation(&self) -> Option<&DocumentContentSecurityPolicyViolation> { - self.report_only_violation.as_ref() + self.report_only_violations.first() } #[cfg(test)] fn enforced_violation(&self) -> Option<&DocumentContentSecurityPolicyViolation> { - self.enforced_violation.as_ref() + self.enforced_violations.first() } } @@ -472,27 +473,25 @@ impl DocumentPolicyContainer { ) -> DocumentContentSecurityPolicyCheck { let DocumentNavigationEmbeddingContext::Nested(ancestor_origins) = embedding_context else { return DocumentContentSecurityPolicyCheck { - report_only_violation: None, - enforced_violation: None, + report_only_violations: Vec::new(), + enforced_violations: Vec::new(), }; }; DocumentContentSecurityPolicyCheck { - report_only_violation: - content_security_policy_frame_ancestors_violation_with_disposition_and_reporting_endpoints( - &self.response_content_security_report_only_policies, - protected_url, - ancestor_origins, - ContentSecurityPolicyDisposition::Report, - &self.content_security_reporting_endpoints, - ), - enforced_violation: - content_security_policy_frame_ancestors_violation_with_disposition_and_reporting_endpoints( - &self.response_content_security_policies, - protected_url, - ancestor_origins, - ContentSecurityPolicyDisposition::Enforce, - &self.content_security_reporting_endpoints, - ), + report_only_violations: document_frame_ancestors_policy_violations( + &self.response_content_security_report_only_policies, + protected_url, + ancestor_origins, + ContentSecurityPolicyDisposition::Report, + &self.content_security_reporting_endpoints, + ), + enforced_violations: document_frame_ancestors_policy_violations( + &self.response_content_security_policies, + protected_url, + ancestor_origins, + ContentSecurityPolicyDisposition::Enforce, + &self.content_security_reporting_endpoints, + ), } } @@ -1014,7 +1013,7 @@ impl DocumentRuntime { self.set_stylesheet_owner_csp_disposition( host_ptr, owner, - super::StylesheetOwnerCspDisposition::from_blocked(enforced_violation.is_some()), + super::StylesheetOwnerCspDisposition::from_blocked(!enforced_violation.is_empty()), ); for violation in [report_only_violation, enforced_violation] .into_iter() @@ -1184,12 +1183,6 @@ impl DocumentRuntime { self.policy_container.content_security_reporting_endpoints = endpoints; } - pub(crate) fn content_security_reporting_endpoints( - &self, - ) -> &ContentSecurityPolicyReportingEndpoints { - &self.policy_container.content_security_reporting_endpoints - } - #[cfg(test)] pub(crate) fn script_element_request_csp_violation( &self, @@ -1395,7 +1388,7 @@ impl DocumentRuntime { let document_uri = document_uri.clone(); move |url: &Url, nonce: Option<&str>, redirect_status| { let check = |policies: &[DocumentContentSecurityPolicy], disposition| { - document_style_element_url_policy_violation_from_document_policies( + document_style_element_url_policy_violations_from_document_policies( policies, &policy_url, url, @@ -1403,6 +1396,7 @@ impl DocumentRuntime { disposition, ContentSecurityPolicyStyleElementRequest { nonce }, ) + .into_iter() .map(|mut violation| { if let Some(uri) = &document_uri { violation.document_uri.clone_from(uri); @@ -1410,6 +1404,7 @@ impl DocumentRuntime { } violation }) + .collect::>() }; ( check(&report, ContentSecurityPolicyDisposition::Report), @@ -1450,7 +1445,7 @@ impl DocumentRuntime { parser_inserted: metadata.parser_inserted, }; let check = |policies: &[DocumentContentSecurityPolicy], disposition| { - document_module_url_policy_violation_from_document_policies( + document_module_url_policy_violations_from_document_policies( policies, &document_url, url, @@ -1591,7 +1586,7 @@ impl DocumentRuntime { &self, kind: ContentSecurityPolicyNonUrlKind, source: &str, - ) -> DocumentContentSecurityPolicyCheck> { + ) -> DocumentContentSecurityPolicyCheck { self.inline_source_csp_check_for_document( Some(self.document_handle()), self.document_url(), @@ -1645,11 +1640,11 @@ impl DocumentRuntime { policy_container: &DocumentPolicyContainer, source: &str, request: ContentSecurityPolicyStyleElementRequest<'_>, - ) -> DocumentContentSecurityPolicyCheck> { + ) -> DocumentContentSecurityPolicyCheck { if self.bypass_content_security_policy() { return DocumentContentSecurityPolicyCheck { - report_only_violation: Vec::new(), - enforced_violation: Vec::new(), + report_only_violations: Vec::new(), + enforced_violations: Vec::new(), }; } let enforced_policies = self.document_content_security_policies_for_optional_document( @@ -1678,8 +1673,8 @@ impl DocumentRuntime { ContentSecurityPolicyDisposition::Report, ); DocumentContentSecurityPolicyCheck { - report_only_violation, - enforced_violation, + report_only_violations: report_only_violation, + enforced_violations: enforced_violation, } } @@ -1694,14 +1689,15 @@ impl DocumentRuntime { &self.policy_container.response_content_security_policies, &self.policy_container.content_security_reporting_endpoints, ); - let enforced_violation = document_style_element_url_policy_violation_from_document_policies( - &enforced_policies, - document_url, - request_url, - ContentSecurityPolicyRedirectStatus::NoRedirect, - ContentSecurityPolicyDisposition::Enforce, - request, - ); + let enforced_violation = + document_style_element_url_policy_violations_from_document_policies( + &enforced_policies, + document_url, + request_url, + ContentSecurityPolicyRedirectStatus::NoRedirect, + ContentSecurityPolicyDisposition::Enforce, + request, + ); let report_only_policies = document_response_content_security_policies( &self .policy_container @@ -1709,7 +1705,7 @@ impl DocumentRuntime { &self.policy_container.content_security_reporting_endpoints, ); let report_only_violation = - document_style_element_url_policy_violation_from_document_policies( + document_style_element_url_policy_violations_from_document_policies( &report_only_policies, document_url, request_url, @@ -1718,8 +1714,8 @@ impl DocumentRuntime { request, ); DocumentContentSecurityPolicyCheck { - report_only_violation, - enforced_violation, + report_only_violations: report_only_violation, + enforced_violations: enforced_violation, } } @@ -1733,14 +1729,15 @@ impl DocumentRuntime { &self.policy_container.response_content_security_policies, &self.policy_container.content_security_reporting_endpoints, ); - let enforced_violation = document_style_element_url_policy_violation_from_document_policies( - &enforced_policies, - document_url, - request_url, - ContentSecurityPolicyRedirectStatus::NoRedirect, - ContentSecurityPolicyDisposition::Enforce, - request, - ); + let enforced_violation = + document_style_element_url_policy_violations_from_document_policies( + &enforced_policies, + document_url, + request_url, + ContentSecurityPolicyRedirectStatus::NoRedirect, + ContentSecurityPolicyDisposition::Enforce, + request, + ); let report_only_policies = document_response_content_security_policies( &self .policy_container @@ -1748,7 +1745,7 @@ impl DocumentRuntime { &self.policy_container.content_security_reporting_endpoints, ); let report_only_violation = - document_style_element_url_policy_violation_from_document_policies( + document_style_element_url_policy_violations_from_document_policies( &report_only_policies, document_url, request_url, @@ -1757,8 +1754,8 @@ impl DocumentRuntime { request, ); DocumentContentSecurityPolicyCheck { - report_only_violation, - enforced_violation, + report_only_violations: report_only_violation, + enforced_violations: enforced_violation, } } @@ -1772,7 +1769,7 @@ impl DocumentRuntime { response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints, source: &str, request: ContentSecurityPolicyScriptElementRequest<'_>, - ) -> DocumentContentSecurityPolicyCheck> { + ) -> DocumentContentSecurityPolicyCheck { let enforced_policies = self.document_content_security_policies_for_optional_document( document_handle, response_policies, @@ -1799,8 +1796,8 @@ impl DocumentRuntime { ContentSecurityPolicyDisposition::Report, ); DocumentContentSecurityPolicyCheck { - report_only_violation, - enforced_violation, + report_only_violations: report_only_violation, + enforced_violations: enforced_violation, } } @@ -1813,7 +1810,7 @@ impl DocumentRuntime { response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints, kind: ContentSecurityPolicyNonUrlKind, source: &str, - ) -> DocumentContentSecurityPolicyCheck> { + ) -> DocumentContentSecurityPolicyCheck { let enforced_policies = self.document_content_security_policies_for_optional_document( document_handle, response_policies, @@ -1838,8 +1835,8 @@ impl DocumentRuntime { ContentSecurityPolicyDisposition::Report, ); DocumentContentSecurityPolicyCheck { - report_only_violation, - enforced_violation, + report_only_violations: report_only_violation, + enforced_violations: enforced_violation, } } @@ -1858,7 +1855,7 @@ impl DocumentRuntime { response_policies, response_reporting_endpoints, ); - let enforced_violation = document_non_url_policy_violation_from_document_policies( + let enforced_violation = document_non_url_policy_violations_from_document_policies( enforced_policies, document_url, kind, @@ -1869,7 +1866,7 @@ impl DocumentRuntime { response_report_only_policies, response_reporting_endpoints, ); - let report_only_violation = document_non_url_policy_violation_from_document_policies( + let report_only_violation = document_non_url_policy_violations_from_document_policies( report_only_policies, document_url, kind, @@ -1877,8 +1874,8 @@ impl DocumentRuntime { ContentSecurityPolicyDisposition::Report, ); DocumentContentSecurityPolicyCheck { - report_only_violation, - enforced_violation, + report_only_violations: report_only_violation, + enforced_violations: enforced_violation, } } @@ -2478,8 +2475,7 @@ impl DocumentRuntime { None }; let violation = task.violation(); - let event_target = - EventTargetHandle::Node(task.target().unwrap_or_else(|| self.document_handle())); + let event_target = EventTargetHandle::Node(task.target().unwrap_or(dispatch_document)); let event_target_value = event_target_value(scope, host_ptr, event_target).map_err(anyhow::Error::msg)?; let context = window_context @@ -2693,25 +2689,6 @@ impl DocumentRuntime { } } -fn document_connect_policy_violation( - policies: &[ContentSecurityPolicy], - reporting_endpoints: &ContentSecurityPolicyReportingEndpoints, - document_url: &Url, - request_url: &Url, - redirect_status: ContentSecurityPolicyRedirectStatus, - disposition: ContentSecurityPolicyDisposition, -) -> Option { - document_url_policy_violation( - policies, - reporting_endpoints, - document_url, - request_url, - ContentSecurityPolicyResourceKind::DocumentConnect, - redirect_status, - disposition, - ) -} - fn document_frame_policy_violation( policies: &[ContentSecurityPolicy], reporting_endpoints: &ContentSecurityPolicyReportingEndpoints, @@ -2812,25 +2789,6 @@ fn document_response_content_security_policies( .collect() } -fn document_connect_policy_violation_from_document_policies( - policies: Vec, - document_url: &Url, - fallback_self_origin: Option<&Url>, - request_url: &Url, - redirect_status: ContentSecurityPolicyRedirectStatus, - disposition: ContentSecurityPolicyDisposition, -) -> Option { - document_url_policy_violation_from_document_policies( - policies, - document_url, - fallback_self_origin, - request_url, - ContentSecurityPolicyResourceKind::DocumentConnect, - redirect_status, - disposition, - ) -} - fn document_frame_policy_violation_from_document_policies( policies: Vec, document_url: &Url, @@ -2849,42 +2807,6 @@ fn document_frame_policy_violation_from_document_policies( ) } -fn document_module_url_policy_violation_from_document_policies( - policies: &[DocumentContentSecurityPolicy], - document_url: &Url, - request_url: &Url, - original_url: &Url, - kind: crate::module_runtime::ModuleKind, - redirect_status: ContentSecurityPolicyRedirectStatus, - request: ContentSecurityPolicyScriptElementRequest<'_>, - disposition: ContentSecurityPolicyDisposition, -) -> Option { - let resource_kind = crate::content_security_policy::module_csp_resource_kind( - kind, - ContentSecurityPolicyResourceKind::DocumentScriptElement, - ); - use crate::content_security_policy::ContentSecurityPolicyUrlRequest; - let request = match resource_kind { - ContentSecurityPolicyResourceKind::DocumentScriptElement => { - ContentSecurityPolicyUrlRequest::Script(request) - } - ContentSecurityPolicyResourceKind::DocumentStyleElement => { - ContentSecurityPolicyUrlRequest::Style(ContentSecurityPolicyStyleElementRequest { - nonce: request.nonce, - }) - } - _ => ContentSecurityPolicyUrlRequest::Standard, - }; - policies.iter().find_map(|policy| { - let mut violation = crate::content_security_policy::content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_reporting_endpoints_and_request( - std::slice::from_ref(&policy.policy), document_url, None, request_url, original_url, - resource_kind, redirect_status, disposition, &policy.reporting_endpoints, request, - )?; - apply_document_policy_reporting_flags(&mut violation, policy); - Some(violation) - }) -} - fn document_url_policy_violation_from_document_policies( policies: Vec, document_url: &Url, @@ -2920,44 +2842,16 @@ fn document_script_element_url_policy_violation_from_document_policies( disposition: ContentSecurityPolicyDisposition, request: ContentSecurityPolicyScriptElementRequest<'_>, ) -> Option { - policies.into_iter().find_map(|policy| { - let single_policy = [policy.policy.clone()]; - let mut violation = document_script_element_url_policy_violation( - &single_policy, - &policy.reporting_endpoints, - document_url, - request_url, - redirect_status, - disposition, - request, - )?; - apply_document_policy_reporting_flags(&mut violation, &policy); - Some(violation) - }) -} - -fn document_style_element_url_policy_violation_from_document_policies( - policies: &[DocumentContentSecurityPolicy], - document_url: &Url, - request_url: &Url, - redirect_status: ContentSecurityPolicyRedirectStatus, - disposition: ContentSecurityPolicyDisposition, - request: ContentSecurityPolicyStyleElementRequest<'_>, -) -> Option { - policies.iter().find_map(|policy| { - let single_policy = [policy.policy.clone()]; - let mut violation = document_style_element_url_policy_violation( - &single_policy, - &policy.reporting_endpoints, - document_url, - request_url, - redirect_status, - disposition, - request, - )?; - apply_document_policy_reporting_flags(&mut violation, policy); - Some(violation) - }) + document_script_element_url_policy_violations_from_document_policies( + policies, + document_url, + request_url, + redirect_status, + disposition, + request, + ) + .into_iter() + .next() } fn document_non_url_policy_violation_from_document_policies( @@ -2981,69 +2875,6 @@ fn document_non_url_policy_violation_from_document_policies( }) } -fn document_inline_source_policy_violations_from_document_policies( - policies: Vec, - document_url: &Url, - kind: ContentSecurityPolicyNonUrlKind, - source: &str, - disposition: ContentSecurityPolicyDisposition, -) -> Vec { - policies.into_iter().filter_map(|policy| { - let mut violation = content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints( - &policy.policy, - document_url, - kind, - source, - disposition, - &policy.reporting_endpoints, - )?; - apply_document_policy_reporting_flags(&mut violation, &policy); - Some(violation) - }).collect() -} - -fn document_inline_script_element_policy_violations_from_document_policies( - policies: Vec, - document_url: &Url, - source: &str, - request: ContentSecurityPolicyScriptElementRequest<'_>, - disposition: ContentSecurityPolicyDisposition, -) -> Vec { - policies.into_iter().filter_map(|policy| { - let mut violation = content_security_policy_inline_script_element_violation_with_disposition_and_reporting_endpoints( - &policy.policy, - document_url, - source, - request, - disposition, - &policy.reporting_endpoints, - )?; - apply_document_policy_reporting_flags(&mut violation, &policy); - Some(violation) - }).collect() -} - -fn document_inline_style_element_policy_violations_from_document_policies( - policies: Vec, - document_url: &Url, - source: &str, - request: ContentSecurityPolicyStyleElementRequest<'_>, - disposition: ContentSecurityPolicyDisposition, -) -> Vec { - policies.into_iter().filter_map(|policy| { - let mut violation = content_security_policy_inline_style_element_violation_with_disposition_and_reporting_endpoints( - &policy.policy, - document_url, - source, - request, - disposition, - &policy.reporting_endpoints, - )?; - apply_document_policy_reporting_flags(&mut violation, &policy); - Some(violation) - }).collect() -} - #[cfg(test)] fn document_trusted_types_sink_policy_violation_from_document_policies( policies: Vec, @@ -3181,11 +3012,320 @@ pub(crate) fn response_content_security_report_only_policies_from_headers( content_security_policy_report_only_headers(headers) } +fn document_module_url_policy_violations_from_document_policies( + policies: impl AsRef<[DocumentContentSecurityPolicy]>, + document_url: &Url, + request_url: &Url, + original_url: &Url, + kind: crate::module_runtime::ModuleKind, + redirect_status: ContentSecurityPolicyRedirectStatus, + request: ContentSecurityPolicyScriptElementRequest<'_>, + disposition: ContentSecurityPolicyDisposition, +) -> Vec { + let resource_kind = crate::content_security_policy::module_csp_resource_kind( + kind, + ContentSecurityPolicyResourceKind::DocumentScriptElement, + ); + use crate::content_security_policy::ContentSecurityPolicyUrlRequest; + let request = match resource_kind { + ContentSecurityPolicyResourceKind::DocumentScriptElement => { + ContentSecurityPolicyUrlRequest::Script(request) + } + ContentSecurityPolicyResourceKind::DocumentStyleElement => { + ContentSecurityPolicyUrlRequest::Style(ContentSecurityPolicyStyleElementRequest { + nonce: request.nonce, + }) + } + _ => ContentSecurityPolicyUrlRequest::Standard, + }; + policies.as_ref().iter().filter_map(|policy| { + let mut violation = crate::content_security_policy::content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_reporting_endpoints_and_request( + std::slice::from_ref(&policy.policy), document_url, None, request_url, original_url, + resource_kind, redirect_status, disposition, &policy.reporting_endpoints, request, + )?; + apply_document_policy_reporting_flags(&mut violation, policy); + Some(violation) + }).collect() +} + +fn document_url_policy_violations_from_document_policies( + policies: impl AsRef<[DocumentContentSecurityPolicy]>, + document_url: &Url, + fallback_self_origin: Option<&Url>, + request_url: &Url, + kind: ContentSecurityPolicyResourceKind, + redirect_status: ContentSecurityPolicyRedirectStatus, + disposition: ContentSecurityPolicyDisposition, +) -> Vec { + policies.as_ref().iter().filter_map(|policy| { + let mut violation = crate::content_security_policy::content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_reporting_endpoints_and_request( + std::slice::from_ref(&policy.policy), + document_url, + fallback_self_origin, + request_url, + request_url, + kind, + redirect_status, + disposition, + &policy.reporting_endpoints, + crate::content_security_policy::ContentSecurityPolicyUrlRequest::Standard, + )?; + apply_document_policy_reporting_flags(&mut violation, policy); + Some(violation) + }).collect() +} + +fn document_script_element_url_policy_violations_from_document_policies( + policies: impl AsRef<[DocumentContentSecurityPolicy]>, + document_url: &Url, + request_url: &Url, + redirect_status: ContentSecurityPolicyRedirectStatus, + disposition: ContentSecurityPolicyDisposition, + request: ContentSecurityPolicyScriptElementRequest<'_>, +) -> Vec { + policies + .as_ref() + .iter() + .filter_map(|policy| { + let single_policy = [policy.policy.clone()]; + let mut violation = document_script_element_url_policy_violation( + &single_policy, + &policy.reporting_endpoints, + document_url, + request_url, + redirect_status, + disposition, + request, + )?; + apply_document_policy_reporting_flags(&mut violation, policy); + Some(violation) + }) + .collect() +} + +fn document_style_element_url_policy_violations_from_document_policies( + policies: impl AsRef<[DocumentContentSecurityPolicy]>, + document_url: &Url, + request_url: &Url, + redirect_status: ContentSecurityPolicyRedirectStatus, + disposition: ContentSecurityPolicyDisposition, + request: ContentSecurityPolicyStyleElementRequest<'_>, +) -> Vec { + policies + .as_ref() + .iter() + .filter_map(|policy| { + let single_policy = [policy.policy.clone()]; + let mut violation = document_style_element_url_policy_violation( + &single_policy, + &policy.reporting_endpoints, + document_url, + request_url, + redirect_status, + disposition, + request, + )?; + apply_document_policy_reporting_flags(&mut violation, policy); + Some(violation) + }) + .collect() +} + +fn document_non_url_policy_violations_from_document_policies( + policies: impl AsRef<[DocumentContentSecurityPolicy]>, + document_url: &Url, + kind: ContentSecurityPolicyNonUrlKind, + source: Option<&str>, + disposition: ContentSecurityPolicyDisposition, +) -> Vec { + policies + .as_ref() + .iter() + .filter_map(|policy| { + let mut violation = content_security_policy_non_url_violation_with_source( + &policy.policy, + document_url, + kind, + source, + disposition, + &policy.reporting_endpoints, + )?; + apply_document_policy_reporting_flags(&mut violation, policy); + Some(violation) + }) + .collect() +} + +fn document_inline_source_policy_violations_from_document_policies( + policies: impl AsRef<[DocumentContentSecurityPolicy]>, + document_url: &Url, + kind: ContentSecurityPolicyNonUrlKind, + source: &str, + disposition: ContentSecurityPolicyDisposition, +) -> Vec { + policies.as_ref().iter().filter_map(|policy| { + let mut violation = content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints( + &policy.policy, + document_url, + kind, + source, + disposition, + &policy.reporting_endpoints, + )?; + apply_document_policy_reporting_flags(&mut violation, policy); + Some(violation) + }).collect() +} + +fn document_inline_script_element_policy_violations_from_document_policies( + policies: impl AsRef<[DocumentContentSecurityPolicy]>, + document_url: &Url, + source: &str, + request: ContentSecurityPolicyScriptElementRequest<'_>, + disposition: ContentSecurityPolicyDisposition, +) -> Vec { + policies.as_ref().iter().filter_map(|policy| { + let mut violation = content_security_policy_inline_script_element_violation_with_disposition_and_reporting_endpoints( + &policy.policy, + document_url, + source, + request, + disposition, + &policy.reporting_endpoints, + )?; + apply_document_policy_reporting_flags(&mut violation, policy); + Some(violation) + }).collect() +} + +fn document_inline_style_element_policy_violations_from_document_policies( + policies: impl AsRef<[DocumentContentSecurityPolicy]>, + document_url: &Url, + source: &str, + request: ContentSecurityPolicyStyleElementRequest<'_>, + disposition: ContentSecurityPolicyDisposition, +) -> Vec { + policies.as_ref().iter().filter_map(|policy| { + let mut violation = content_security_policy_inline_style_element_violation_with_disposition_and_reporting_endpoints( + &policy.policy, + document_url, + source, + request, + disposition, + &policy.reporting_endpoints, + )?; + apply_document_policy_reporting_flags(&mut violation, policy); + Some(violation) + }).collect() +} + +fn document_url_policy_violations( + policies: &[ContentSecurityPolicy], + reporting_endpoints: &ContentSecurityPolicyReportingEndpoints, + document_url: &Url, + request_url: &Url, + kind: ContentSecurityPolicyResourceKind, + redirect_status: ContentSecurityPolicyRedirectStatus, + disposition: ContentSecurityPolicyDisposition, +) -> Vec { + policies + .iter() + .filter_map(|policy| { + document_url_policy_violation( + std::slice::from_ref(policy), + reporting_endpoints, + document_url, + request_url, + kind, + redirect_status, + disposition, + ) + }) + .collect() +} + +fn document_frame_ancestors_policy_violations( + policies: &[ContentSecurityPolicy], + protected_url: &Url, + ancestor_origins: &[Option], + disposition: ContentSecurityPolicyDisposition, + reporting_endpoints: &ContentSecurityPolicyReportingEndpoints, +) -> Vec { + policies.iter().filter_map(|policy| { + content_security_policy_frame_ancestors_violation_with_disposition_and_reporting_endpoints( + std::slice::from_ref(policy), protected_url, ancestor_origins, + disposition, reporting_endpoints, + ) + }).collect() +} + #[cfg(test)] mod tests { use super::*; use crate::parser::HtmlParser; + #[test] + fn captured_module_and_stylesheet_csp_keep_all_policy_deliveries() { + let mut runtime = runtime_for_html( + r#" + + + "#, + ); + let policies = vec!["default-src 'none'; report-uri /report".to_owned(); 2]; + runtime.set_response_content_security_policies(&policies); + runtime.set_response_content_security_report_only_policies(&policies); + let url = Url::parse("https://example.test/resource").unwrap(); + let module = runtime.module_fetch_csp_context( + &url, + crate::module_runtime::ModuleKind::JavaScript, + &crate::module_runtime::ModuleFetchMetadata::default(), + ); + assert!(module.check_initial_request(&url).is_err()); + assert!(module.check_initial_request(&url).is_err()); + let module_violations = module.take_violations(); + assert!(module.take_violations().is_empty()); + let stylesheet = runtime.stylesheet_fetch_csp_context_for_document( + Some(runtime.document_handle()), + runtime.document_url(), + &runtime.policy_container, + None, + ); + let request = stylesheet.for_request(None); + assert!(request(&url, 0).is_err()); + assert!(request(&url, 0).is_err()); + let style_violations = stylesheet.take_violations(); + assert!(stylesheet.take_violations().is_empty()); + for violations in [module_violations, style_violations] { + assert_eq!(violations.len(), 6); + assert_eq!( + violations + .iter() + .filter(|v| v.disposition == ContentSecurityPolicyDisposition::Report) + .count(), + 2 + ); + assert_eq!( + violations + .iter() + .filter(|v| v.disposition == ContentSecurityPolicyDisposition::Enforce) + .count(), + 4 + ); + assert_eq!( + violations + .iter() + .filter(|v| !v.report_uri_endpoints.is_empty()) + .count(), + 4 + ); + assert!(violations.iter().all(|v| v.original_policy == policies[0])); + } + let another_request = stylesheet.for_request(None); + assert!(another_request(&url, 0).is_err()); + assert_eq!(stylesheet.take_violations().len(), 6); + } + fn runtime_for_html(html: &str) -> DocumentRuntime { let document_url = Url::parse("https://example.test/page").expect("document url"); let document = HtmlParser::SCRIPTING_ENABLED.parse(document_url, html.to_owned()); @@ -3626,8 +3766,6 @@ mod tests { "trusted-types 'none'; report-uri /report", ] .map(str::to_owned); - let enforced = enforced.map(moli_csp::ContentSecurityPolicy::from); - let report_only = report_only.map(moli_csp::ContentSecurityPolicy::from); let reports = runtime.trusted_type_policy_name_csp_violations_for_document( Some(runtime.document_handle()), runtime.document_url(), @@ -4775,12 +4913,14 @@ mod tests { DocumentNavigationEmbeddingContext::Nested(&ancestors), ) .into_violations(); + assert_eq!(report_only.len(), 1); + assert_eq!(enforced.len(), 1); assert_eq!( - report_only.unwrap().disposition, + report_only[0].disposition, ContentSecurityPolicyDisposition::Report ); assert_eq!( - enforced.unwrap().disposition, + enforced[0].disposition, ContentSecurityPolicyDisposition::Enforce ); } diff --git a/moli-renderer-v8/src/host.rs b/moli-renderer-v8/src/host.rs index a5c2a7bda5c..6d60c5b2c34 100644 --- a/moli-renderer-v8/src/host.rs +++ b/moli-renderer-v8/src/host.rs @@ -34,9 +34,10 @@ pub(crate) use self::events::EventListenerRegistration; pub(super) use self::events::{ DispatchStatus, HostEventTargetRegistry, PublicEventDispatchResult, create_host_event, dispatch_host_event, dispatch_public_event, dispatch_public_event_with_original_target, - event_dispatch_status, event_target_value, host_event_defaults, - invoke_prepared_before_unload_event_handler, invoke_prepared_event_callback, - report_event_callback_exception, report_event_listener_exception, + event_dispatch_status, event_handler_content_attribute, event_target_value, + host_event_defaults, invoke_prepared_before_unload_event_handler, + invoke_prepared_event_callback, report_event_callback_exception, + report_event_listener_exception, }; pub(crate) use self::events::{ EventHandlerCspAdmission, EventHandlerPropertyState, ListenerFilter, UncompiledEventHandler, diff --git a/moli-renderer-v8/src/host/events.rs b/moli-renderer-v8/src/host/events.rs index 8b5b626a45b..30b66e1ce26 100644 --- a/moli-renderer-v8/src/host/events.rs +++ b/moli-renderer-v8/src/host/events.rs @@ -8,6 +8,7 @@ use crate::{ event_target_dispatch::finish_dispatch, mark_event_trusted, set_event_composed_path, set_event_source_value, }, + document_runtime::DocumentRuntime, dom_parser::DOM_PARSER_FOREIGN_NODE_SLOT, util::{get_private_object, get_private_value, serialize_v8_iter_array}, v8_execution_watchdog::V8ExecutionWatchdog, @@ -87,20 +88,205 @@ impl EventListenerRegistration { } } -#[derive(Clone, Copy)] -enum EventHandlerPropertyEntry { - Callback { - callback_id: crate::native_bridge::EventCallbackId, - registration_id: u64, - }, +#[derive(Clone)] +pub(crate) struct UncompiledEventHandler { + // The handler keeps the source from its last attribute change. Its target + // already owns the handler state; adopting the source element must not + // make a Window read that element's new attribute or node Document. + pub(crate) source: std::sync::Arc, + pub(crate) source_location: std::sync::Arc, + pub(crate) csp_admission: EventHandlerCspAdmission, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum EventHandlerCspAdmission { + // Prebuilt DOM snapshots and unmodeled document owners have not run CSP + // admission. Keep their existing compilation-time check until that happens. + Pending, + Allowed, +} + +impl UncompiledEventHandler { + pub(crate) fn from_attribute( + dom_host: &crate::dom::native::DomHost, + owner: DomHandle, + event_type: &(impl EventTypeKey + ?Sized), + ) -> Option { + let name = crate::native_bridge::element::event_handler_content_attribute_name( + event_type.as_str()?, + )?; + let source = dom_host + .dom() + .get_attribute_dom_string_value(owner, &name)?; + Some(Self { + source: std::sync::Arc::new(source), + source_location: Self::attribute_source_location(dom_host, owner, &name) + .unwrap_or_else(|| Self::document_source_location(dom_host, owner)), + csp_admission: EventHandlerCspAdmission::Pending, + }) + } + + fn attribute_source_location( + dom_host: &crate::dom::native::DomHost, + owner: DomHandle, + name: &str, + ) -> Option> { + dom_host + .node(owner) + .and_then(crate::dom::native::Node::as_element) + .and_then(|element| element.attribute_source_location("", name)) + .cloned() + } + + fn document_source_location( + dom_host: &crate::dom::native::DomHost, + owner: DomHandle, + ) -> std::sync::Arc { + let resource_name = dom_host + .owner_document_handle(owner) + .and_then(|document| dom_host.document_url_for_handle(document)) + .map_or("", url::Url::as_str); + std::sync::Arc::new(crate::dom::native::SourceLocation::new(resource_name, 1, 1)) + } + + pub(crate) fn capture_source_location( + scope: &mut v8::PinScope<'_, '_>, + dom_host: &crate::dom::native::DomHost, + owner: DomHandle, + name: &str, + ) -> std::sync::Arc { + if let Some(location) = Self::attribute_source_location(dom_host, owner, name) { + return location; + } + // Borrowing a DOM binding can enter another realm before these steps. + // Capture the triggering script in its incumbent realm so V8 does not + // filter its frames against the binding realm's security token. + let context = scope + .get_incumbent_context() + .unwrap_or_else(|| scope.get_current_context()); + let scope = &mut v8::ContextScope::new(scope, context); + let frame = v8::StackTrace::current_stack_trace(scope, 1) + .filter(|stack| stack.get_frame_count() != 0) + .and_then(|stack| stack.get_frame(scope, 0)); + if let Some(frame) = frame + && let Some(resource_name) = frame.get_script_name_or_source_url(scope) + { + let resource_name = resource_name.to_rust_string_lossy(scope); + if !resource_name.is_empty() { + return std::sync::Arc::new(crate::dom::native::SourceLocation::new( + resource_name, + u64::try_from(frame.get_line_number()).unwrap_or(0), + u64::try_from(frame.get_column()).unwrap_or(0), + )); + } + } + Self::document_source_location(dom_host, owner) + } +} + +#[derive(Clone)] +pub(crate) enum EventHandlerPropertyState { + Uncompiled(UncompiledEventHandler), + Callback(crate::native_bridge::EventCallbackId), Null, } +impl EventHandlerPropertyState { + pub(crate) fn callback_id(&self) -> Option { + match self { + Self::Callback(callback_id) => Some(*callback_id), + Self::Uncompiled(_) | Self::Null => None, + } + } +} + +#[derive(Clone)] +struct EventHandlerPropertyEntry { + listener_id: Option, + state: EventHandlerPropertyState, +} + +fn event_handler_callback_id( + entry: EventHandlerPropertyEntry, +) -> Option { + entry.state.callback_id() +} + enum EventHandlerPropertyValue { Callback(crate::native_bridge::EventCallbackId), Null, } +struct EventListenerSnapshot { + id: u64, + callback_id: crate::native_bridge::EventCallbackId, + function_name: String, + script_id: i32, + script_url: Option, + line_number: Option, + column_number: Option, + capture: bool, + once: bool, + passive: bool, +} + +enum EventDispatchEntry { + Listener(EventListenerSnapshot), + Handler { id: u64 }, +} + +impl EventDispatchEntry { + fn id(&self) -> u64 { + match self { + Self::Listener(listener) => listener.id, + Self::Handler { id } => *id, + } + } +} + +pub(crate) fn event_handler_content_attribute( + runtime: &DocumentRuntime, + target: EventTargetHandle, + event_type: &(impl EventTypeKey + ?Sized), +) -> Option { + let event_type = event_type.as_str()?; + let attribute_name = + crate::native_bridge::element::event_handler_content_attribute_name(event_type)?; + let handle = match target { + EventTargetHandle::Node(handle) => { + if crate::native_bridge::element::body_or_frameset_reflects_window_event_type( + event_type, + ) && runtime.dom_host().node(handle).is_some_and(|node| { + node.is_html_element_named("body") || node.is_html_element_named("frameset") + }) { + return None; + } + handle + } + EventTargetHandle::Window + if crate::native_bridge::element::body_or_frameset_reflects_window_event_type( + event_type, + ) => + { + let document_handle = runtime.document_handle(); + let dom = runtime.dom_host().dom(); + dom.node(document_handle) + .and_then(crate::dom::native::Node::as_document) + .and_then(|document| document.body_or_frameset_handle(dom, document_handle))? + } + EventTargetHandle::ChildWindow(_) | EventTargetHandle::PopupWindow(_) => return None, + EventTargetHandle::Window => return None, + }; + if !crate::native_bridge::element::element_event_handler_content_attribute_applies( + runtime.dom_host(), + handle, + &attribute_name, + ) { + return None; + } + UncompiledEventHandler::from_attribute(runtime.dom_host(), handle, event_type) +} + pub(crate) struct HostEventTargetRegistry { listeners: HashMap>>, handler_properties: @@ -474,253 +660,54 @@ fn invoke_event_handler_property<'s>( host_ptr: *mut PageScriptHost, target: EventTargetHandle, invocation_target_in_shadow_tree: bool, - target_object: v8::Local<'s, v8::Object>, - event_type: &(impl EventTypeKey + ?Sized), - event: v8::Local<'s, v8::Object>, -) { - let Some(native_event_type) = event_type.as_str() else { - return; - }; - let Some(handler_name) = - crate::native_bridge::element::event_handler_content_attribute_name(native_event_type) - else { - return; - }; - let (callback_id, temporary) = match registry.event_handler_property_value(target, event_type) { - Some(EventHandlerPropertyValue::Callback(callback_id)) => (callback_id, false), - Some(EventHandlerPropertyValue::Null) => { - return; - } - None => { - if !crate::context_bootstrap::event_handler_property_is_exposed( - scope, - target_object, - &handler_name, - ) { - return; - } - let wrapper_handler = matches!(target, EventTargetHandle::Node(_)) - .then(|| { - crate::native_bridge::element::node_event_handler_value_from_wrapper( - scope, - target_object, - &handler_name, - ) - }) - .flatten(); - let native_inline = if wrapper_handler.is_some() { - None - } else { - match target { - EventTargetHandle::Window if matches!(native_event_type, "load" | "pageshow") => Some( - crate::native_bridge::element::compile_window_body_event_attribute( - scope, host_ptr, native_event_type, - ), - ), - EventTargetHandle::Node(handle) - if crate::native_bridge::element::is_global_event_handler_attribute( - &handler_name, - ) && unsafe { &*host_ptr } - .dom_host() - .node(handle) - .and_then(|node| node.as_element()) - .is_some_and(|element| { - element.namespace() == "http://www.w3.org/1999/xhtml" - }) => - { - Some( - crate::native_bridge::element::compile_node_content_attribute_for_dispatch( - scope, host_ptr, handle, native_event_type, - ), - ) - } - _ => None, - } - }; - let (handler, persistent) = if let Some(value) = wrapper_handler { - let Ok(handler) = v8::Local::::try_from(value) else { - return; - }; - // A foreign wrapper can still be updated in its producer realm. - // Do not cache a second registration in its new document. - (handler, false) - } else if let Some(handler) = native_inline { - let Some(handler) = handler else { - return; - }; - (handler, true) - } else { - let Some(key) = v8_string(scope, &handler_name) else { - return; - }; - let handler = target_object - .get(scope, key.into()) - .and_then(|value| v8::Local::::try_from(value).ok()); - match handler { - Some(handler) => (handler, false), - None if target == EventTargetHandle::Window && event_type.is_type("messageerror") => { - let Some(handler) = crate::native_bridge::element::compile_window_body_onmessageerror_attribute( - scope, host_ptr, - ) else { return; }; - (handler, true) - } - None => return, - } - }; - // Native inline compilation already installed its exact callback - // and realm. Reuse that identity rather than registering a second - // temporary callback for the same function. - if persistent - && let Some(EventHandlerPropertyValue::Callback(callback_id)) = - registry.event_handler_property_value(target, event_type) - { - (callback_id, false) - } else { - let callback = v8::Local::::from(handler); - let relevant_context = callback - .get_creation_context(scope) - .unwrap_or_else(|| scope.get_current_context()); - let incumbent_context = scope - .get_incumbent_context() - .unwrap_or_else(|| scope.get_current_context()); - let callback_id = unsafe { &mut *host_ptr }.register_event_callback( - scope, - callback, - relevant_context, - incumbent_context, - ); - if persistent { - if let Some(previous) = - registry.set_event_handler_property(target, event_type, Some(callback_id)) - { - unsafe { &mut *host_ptr }.release_event_callback(previous); - } - (callback_id, false) - } else { - (callback_id, true) - } - } - } - }; - let Some(prepared) = unsafe { &*host_ptr }.prepare_event_callback(scope, callback_id) else { - if temporary { - unsafe { &mut *host_ptr }.release_event_callback(callback_id); - } - return; - }; - - let timing_started = moli_trace::cdp_nav_timing_enabled().then(Instant::now); - if target == EventTargetHandle::Window - && event_type.is_type("error") - && let Some(arguments) = error_event_handler_arguments(scope, event) - { - let returned = invoke_prepared_event_callback( - scope, - host_ptr, - invocation_target_in_shadow_tree, - event_type, - &handler_name, - prepared, - target, - event, - &arguments, - ); - if temporary { - unsafe { &mut *host_ptr }.release_event_callback(callback_id); - } - if let Some(returned) = returned { - let returned = v8::Local::new(scope, returned); - apply_event_handler_return_value( - scope, - event, - returned, - EventHandlerType::OnErrorEventHandler, - ); - } - if let Some(timing_started) = timing_started { - tracing::info!( - target: "moli_cdp_nav_timing", - stage = "event_handler_property_invoked", - event_type = %event_type, - handler_name, - ?target, - elapsed_ms = timing_started.elapsed().as_millis(), - ); - } - return; - } - - let returned = if target == EventTargetHandle::Window && event_type.is_type("beforeunload") { - invoke_prepared_before_unload_event_handler( - scope, - host_ptr, - target, - invocation_target_in_shadow_tree, - event_type, - &handler_name, - prepared, - event, - ); - None - } else { - invoke_prepared_event_callback( - scope, - host_ptr, - invocation_target_in_shadow_tree, - event_type, - &handler_name, - prepared, - target, - event, - &[event.into()], - ) - }; - if temporary { - unsafe { &mut *host_ptr }.release_event_callback(callback_id); - } - if let Some(returned) = returned { - let returned = v8::Local::new(scope, returned); - apply_event_handler_return_value(scope, event, returned, EventHandlerType::EventHandler); - } - if let Some(timing_started) = timing_started { - tracing::info!( - target: "moli_cdp_nav_timing", - stage = "event_handler_property_invoked", - event_type = %event_type, - handler_name, - ?target, - elapsed_ms = timing_started.elapsed().as_millis(), - ); - } -} - -fn invoke_event_target_handler_property<'s>( - registry: &mut HostEventTargetRegistry, - scope: &mut v8::PinScope<'s, '_>, - host_ptr: *mut PageScriptHost, - target: EventTargetHandle, - invocation_target_in_shadow_tree: bool, - target_object: v8::Local<'s, v8::Object>, + _target_object: v8::Local<'s, v8::Object>, event_type: &(impl EventTypeKey + ?Sized), event: v8::Local<'s, v8::Object>, ) { if V8ExecutionWatchdog::callback_dispatch_has_timed_out(scope) { return; } - if matches!(target, EventTargetHandle::ChildWindow(_)) { - // Child Window event-handler properties share the native listener - // registry and are invoked in registration order by the listener phase. - return; - } - invoke_event_handler_property( + let callback_id = + match registry.event_handler_property_value(target, event_type) { + Some(EventHandlerPropertyValue::Callback(callback_id)) => callback_id, + Some(EventHandlerPropertyValue::Null) => return, + None => { + let Some(event_type_str) = event_type.as_str() else { + return; + }; + let compiled = match target { + EventTargetHandle::Window => { + crate::native_bridge::element::resolve_window_event_handler_content_attribute( + scope, host_ptr, event_type_str, + ).and_then(|value| v8::Local::::try_from(value).ok()) + } + EventTargetHandle::Node(handle) => { + crate::native_bridge::element::compile_node_content_attribute_for_dispatch( + scope, host_ptr, handle, event_type_str, + ) + } + EventTargetHandle::ChildWindow(_) | EventTargetHandle::PopupWindow(_) => None, + }; + if compiled.is_none() { + return; + } + let Some(EventHandlerPropertyValue::Callback(callback_id)) = + registry.event_handler_property_value(target, event_type) + else { + return; + }; + callback_id + } + }; + invoke_registered_event_handler( registry, scope, host_ptr, target, invocation_target_in_shadow_tree, - target_object, event_type, event, + callback_id, ); } @@ -964,10 +951,11 @@ impl HostEventTargetRegistry { for (target, handlers) in &mut self.handler_properties { if targets_to_clear.contains(target) { for handler in handlers.values_mut() { - if let EventHandlerPropertyEntry::Callback { callback_id, .. } = *handler { - retired.insert(callback_id); + if let EventHandlerPropertyState::Callback(callback_id) = &handler.state { + retired.insert(*callback_id); } - *handler = EventHandlerPropertyEntry::Null; + handler.listener_id = None; + handler.state = EventHandlerPropertyState::Null; } } } @@ -1006,81 +994,46 @@ impl HostEventTargetRegistry { event_type: &(impl EventTypeKey + ?Sized), callback_id: Option, ) -> Option { - let existing_registration_id = self + let existing_listener_id = self .handler_properties .get(&target) .and_then(|handlers| handlers.get(event_type)) - .and_then(|entry| match entry { - EventHandlerPropertyEntry::Callback { - registration_id, .. - } => Some(*registration_id), - EventHandlerPropertyEntry::Null => None, - }); - let entry = match callback_id { - Some(callback_id) => { - let registration_id = - existing_registration_id.unwrap_or_else(|| self.allocate_listener_id()); - self.ensure_event_type_registration_id(target, event_type, registration_id); - EventHandlerPropertyEntry::Callback { - callback_id, - registration_id, - } - } - None => EventHandlerPropertyEntry::Null, - }; - let previous = self - .handler_properties - .entry(target) - .or_default() - .insert(event_type.to_event_type(), entry); - let previous_callback = match previous { - Some(EventHandlerPropertyEntry::Callback { callback_id, .. }) => Some(callback_id), - Some(EventHandlerPropertyEntry::Null) | None => None, - }; - if callback_id.is_none() { + .and_then(|entry| entry.listener_id); + let listener_id = callback_id + .map(|_| existing_listener_id.unwrap_or_else(|| self.allocate_listener_id())); + if let Some(listener_id) = listener_id { + self.ensure_event_type_registration_id(target, event_type, listener_id); + } + let state = callback_id + .map(EventHandlerPropertyState::Callback) + .unwrap_or(EventHandlerPropertyState::Null); + let previous = self.handler_properties.entry(target).or_default().insert( + event_type.to_event_type(), + EventHandlerPropertyEntry { listener_id, state }, + ); + let previous_callback = previous.and_then(event_handler_callback_id); + if listener_id.is_none() { self.remove_event_type_registration_id_if_unused(target, event_type); } previous_callback } - pub(crate) fn clear_event_handler_property( - &mut self, - target: EventTargetHandle, - event_type: &(impl EventTypeKey + ?Sized), - ) -> Option { - let removed = self - .handler_properties - .get_mut(&target) - .and_then(|handlers| handlers.shift_remove(event_type)); - let remove_target = self - .handler_properties - .get(&target) - .is_some_and(indexmap::IndexMap::is_empty); - if remove_target { - self.handler_properties.remove(&target); - } - let callback_id = match removed { - Some(EventHandlerPropertyEntry::Callback { callback_id, .. }) => Some(callback_id), - Some(EventHandlerPropertyEntry::Null) | None => None, - }; - self.remove_event_type_registration_id_if_unused(target, event_type); - callback_id - } - fn event_handler_property_value( &self, target: EventTargetHandle, event_type: &(impl EventTypeKey + ?Sized), ) -> Option { - match self + match &self .handler_properties .get(&target) .and_then(|target_handlers| target_handlers.get(event_type))? + .state { - EventHandlerPropertyEntry::Callback { callback_id, .. } => { + EventHandlerPropertyState::Uncompiled(_) => None, + EventHandlerPropertyState::Callback(callback_id) => { Some(EventHandlerPropertyValue::Callback(*callback_id)) } - EventHandlerPropertyEntry::Null => Some(EventHandlerPropertyValue::Null), + EventHandlerPropertyState::Null => Some(EventHandlerPropertyValue::Null), } } @@ -1089,13 +1042,15 @@ impl HostEventTargetRegistry { target: EventTargetHandle, event_type: &(impl EventTypeKey + ?Sized), ) -> Option> { - match self + match &self .handler_properties .get(&target) .and_then(|target_handlers| target_handlers.get(event_type))? + .state { - EventHandlerPropertyEntry::Callback { callback_id, .. } => Some(Some(*callback_id)), - EventHandlerPropertyEntry::Null => Some(None), + EventHandlerPropertyState::Uncompiled(_) => None, + EventHandlerPropertyState::Callback(callback_id) => Some(Some(*callback_id)), + EventHandlerPropertyState::Null => Some(None), } } @@ -1143,11 +1098,10 @@ impl HostEventTargetRegistry { } if let Some(target_handlers) = self.handler_properties.get(&target) { for (event_type, entry) in target_handlers { - let EventHandlerPropertyEntry::Callback { - callback_id, - registration_id, - } = *entry - else { + let EventHandlerPropertyState::Callback(callback_id) = entry.state else { + continue; + }; + let Some(registration_id) = entry.listener_id else { continue; }; snapshots.push(( @@ -1259,13 +1213,14 @@ impl HostEventTargetRegistry { for target_handlers in self.handler_properties.values_mut() { for entry in target_handlers.values_mut() { if matches!( - entry, - EventHandlerPropertyEntry::Callback { callback_id, .. } - if retired.contains(callback_id) + entry.state, + EventHandlerPropertyState::Callback(callback_id) + if retired.contains(&callback_id) ) { // Absence enables the legacy wrapper fallback, which can // rediscover a callback from its retired realm. - *entry = EventHandlerPropertyEntry::Null; + entry.listener_id = None; + entry.state = EventHandlerPropertyState::Null; } } } @@ -1277,10 +1232,15 @@ impl HostEventTargetRegistry { target: EventTargetHandle, event_type: &(impl EventTypeKey + ?Sized), ) -> bool { - self.listeners + self.handler_properties .get(&target) - .and_then(|target_listeners| target_listeners.get(event_type)) - .is_some_and(|entries| entries.iter().any(|entry| !entry.removed)) + .and_then(|handlers| handlers.get(event_type)) + .is_some_and(|entry| entry.listener_id.is_some()) + || self + .listeners + .get(&target) + .and_then(|target_listeners| target_listeners.get(event_type)) + .is_some_and(|entries| entries.iter().any(|entry| !entry.removed)) } pub(crate) fn has_listener_in_dispatch_path( @@ -1346,7 +1306,7 @@ impl HostEventTargetRegistry { .handler_properties .get(&target) .and_then(|handlers| handlers.get(event_type)) - .is_some_and(|entry| matches!(entry, EventHandlerPropertyEntry::Callback { .. })) + .is_some_and(|entry| entry.listener_id.is_some()) } fn remove_event_type_registration_id_if_unused( @@ -1379,9 +1339,7 @@ impl HostEventTargetRegistry { || handler_properties .get(target) .and_then(|handlers| handlers.get(event_type)) - .is_some_and(|entry| { - matches!(entry, EventHandlerPropertyEntry::Callback { .. }) - }) + .is_some_and(|entry| entry.listener_id.is_some()) }); !event_types.is_empty() }); @@ -1398,48 +1356,53 @@ impl HostEventTargetRegistry { filter: ListenerFilter, at_target: bool, ) -> std::result::Result { - let snapshot: Vec<( - u64, - crate::native_bridge::EventCallbackId, - String, - i32, - Option, - Option, - Option, - bool, - bool, - bool, - )> = { - let Some(target_map) = self.listeners.get(&target) else { - return Ok(DispatchStatus::Continue); - }; - let Some(entries) = target_map.get(event_type) else { - return Ok(DispatchStatus::Continue); - }; - entries - .iter() - .filter(|entry| !entry.removed) - .filter(|entry| match filter { - ListenerFilter::Capturing => entry.capture, - ListenerFilter::Bubbling => !entry.capture, - ListenerFilter::All => true, + if !self.has_event_handler_property_entry(target, event_type) { + let content_attribute_owner = + event_handler_content_attribute(unsafe { &*host_ptr }, target, event_type); + self.ensure_event_handler_content_attribute( + target, + event_type, + content_attribute_owner, + ); + } + + let mut snapshot = self + .listeners + .get(&target) + .and_then(|target_map| target_map.get(event_type)) + .into_iter() + .flatten() + .filter(|entry| !entry.removed) + .filter(|entry| match filter { + ListenerFilter::Capturing => entry.capture, + ListenerFilter::Bubbling => !entry.capture, + ListenerFilter::All => true, + }) + .map(|entry| { + EventDispatchEntry::Listener(EventListenerSnapshot { + id: entry.id, + callback_id: entry.callback_id, + function_name: entry.function_name.clone(), + script_id: entry.script_id, + script_url: entry.script_url.clone(), + line_number: entry.line_number, + column_number: entry.column_number, + capture: entry.capture, + once: entry.once, + passive: entry.passive, }) - .map(|entry| { - ( - entry.id, - entry.callback_id, - entry.function_name.clone(), - entry.script_id, - entry.script_url.clone(), - entry.line_number, - entry.column_number, - entry.capture, - entry.once, - entry.passive, - ) - }) - .collect() - }; + }) + .collect::>(); + if !matches!(filter, ListenerFilter::Capturing) + && let Some(id) = self + .handler_properties + .get(&target) + .and_then(|handlers| handlers.get(event_type)) + .and_then(|entry| entry.listener_id) + { + snapshot.push(EventDispatchEntry::Handler { id }); + } + snapshot.sort_by_key(EventDispatchEntry::id); if snapshot.is_empty() { return Ok(DispatchStatus::Continue); @@ -1457,117 +1420,137 @@ impl HostEventTargetRegistry { listener_count = snapshot.len(), ); } - for ( - listener_index, - ( - listener_id, - callback_id, - function_name, - script_id, - script_url, - line_number, - column_number, - capture_flag, - is_once, - is_passive, - ), - ) in snapshot.into_iter().enumerate() - { + for (listener_index, entry) in snapshot.into_iter().enumerate() { if V8ExecutionWatchdog::callback_dispatch_has_timed_out(scope) { return Ok(DispatchStatus::StopImmediate); } - let still_registered = self - .listeners - .get(&target) - .and_then(|listeners| listeners.get(event_type)) - .is_some_and(|entries| { - entries.iter().any(|entry| { - !entry.removed - && entry.capture == capture_flag - && entry.callback_id == callback_id - }) - }); - - if !still_registered { - continue; - } - - let Some(prepared) = unsafe { &*host_ptr }.prepare_event_callback(scope, callback_id) - else { - self.remove_listener_by_id(target, event_type, callback_id, capture_flag); - unsafe { - (&mut *host_ptr).unregister_abort_target_listener(callback_id); - (&mut *host_ptr).release_event_callback(callback_id); + match entry { + EventDispatchEntry::Handler { id } => { + let still_registered = self + .handler_properties + .get(&target) + .and_then(|handlers| handlers.get(event_type)) + .is_some_and(|entry| entry.listener_id == Some(id)); + if !still_registered { + continue; + } + set_event_internal_flag(scope, event, EVENT_PASSIVE_SLOT, false); + let target_object = event_target_object(scope, host_ptr, target)?; + invoke_event_handler_property( + self, + scope, + host_ptr, + target, + invocation_target_in_shadow_tree, + target_object, + event_type, + event, + ); } - tracing::debug!( - listener_id, - ?target, - event_type, - "skipped event listener owned by a retired execution context" - ); - continue; - }; + EventDispatchEntry::Listener(listener) => { + let still_registered = self + .listeners + .get(&target) + .and_then(|listeners| listeners.get(event_type)) + .is_some_and(|entries| { + entries + .iter() + .any(|entry| !entry.removed && entry.id == listener.id) + }); + if !still_registered { + continue; + } - if is_once { - self.remove_listener_by_id(target, event_type, callback_id, capture_flag); - unsafe { - (&mut *host_ptr).unregister_abort_target_listener(callback_id); - (&mut *host_ptr).release_event_callback(callback_id); + let callback_id = listener.callback_id; + let Some(prepared) = + unsafe { &*host_ptr }.prepare_event_callback(scope, callback_id) + else { + self.remove_listener_by_id( + target, + event_type, + callback_id, + listener.capture, + ); + unsafe { + (&mut *host_ptr).unregister_abort_target_listener(callback_id); + (&mut *host_ptr).release_event_callback(callback_id); + } + tracing::debug!( + listener_id = listener.id, + ?target, + event_type = %event_type, + "skipped event listener owned by a retired execution context" + ); + continue; + }; + + if listener.once { + self.remove_listener_by_id( + target, + event_type, + callback_id, + listener.capture, + ); + unsafe { + (&mut *host_ptr).unregister_abort_target_listener(callback_id); + (&mut *host_ptr).release_event_callback(callback_id); + } + } + + let listener_name = format!("{event_type} listener"); + set_event_internal_flag(scope, event, EVENT_PASSIVE_SLOT, listener.passive); + let listener_started = timing_enabled.then(Instant::now); + let layout_trace_before = timing_enabled + .then(|| unsafe { &*host_ptr }.layout_metric_trace_snapshot()); + let _ = invoke_prepared_event_callback( + scope, + host_ptr, + invocation_target_in_shadow_tree, + event_type, + &listener_name, + prepared, + target, + event, + &[event.into()], + ); + if let Some(listener_started) = listener_started { + let layout_trace = layout_trace_before + .map(|before| { + unsafe { &*host_ptr } + .layout_metric_trace_snapshot() + .saturating_delta(before) + }) + .unwrap_or_default(); + tracing::info!( + target: "moli_cdp_nav_timing", + stage = "event_listener_invoked", + listener_id = listener.id, + event_type = %event_type, + ?target, + ?filter, + at_target, + listener_index, + function_name = listener.function_name.as_str(), + script_id = listener.script_id, + script_url = listener.script_url.as_deref().unwrap_or(""), + line_number = listener.line_number.map(u64::from), + column_number = listener.column_number.map(u64::from), + capture_flag = listener.capture, + is_once = listener.once, + is_passive = listener.passive, + layout_client_rect_count = layout_trace.client_rect_count, + layout_client_rect_ms = layout_trace.client_rect_ms(), + layout_offset_parent_count = layout_trace.offset_parent_count, + layout_offset_parent_ms = layout_trace.offset_parent_ms(), + layout_offset_position_count = layout_trace.offset_position_count, + layout_offset_position_ms = layout_trace.offset_position_ms(), + elapsed_ms = listener_started.elapsed().as_millis(), + ); + } + set_event_internal_flag(scope, event, EVENT_PASSIVE_SLOT, false); } } - let listener_name = format!("{event_type} listener"); - set_event_internal_flag(scope, event, EVENT_PASSIVE_SLOT, is_passive); - let listener_started = timing_enabled.then(Instant::now); - let layout_trace_before = - timing_enabled.then(|| unsafe { &*host_ptr }.layout_metric_trace_snapshot()); - let _ = invoke_prepared_event_callback( - scope, - host_ptr, - invocation_target_in_shadow_tree, - event_type, - &listener_name, - prepared, - target, - event, - &[event.into()], - ); - if let Some(listener_started) = listener_started { - let layout_trace = layout_trace_before - .map(|before| { - unsafe { &*host_ptr } - .layout_metric_trace_snapshot() - .saturating_delta(before) - }) - .unwrap_or_default(); - tracing::info!( - target: "moli_cdp_nav_timing", - stage = "event_listener_invoked", - listener_id, - event_type, - ?target, - ?filter, - at_target, - listener_index, - function_name = function_name.as_str(), - script_id, - script_url = script_url.as_deref().unwrap_or(""), - line_number = line_number.map(u64::from), - column_number = column_number.map(u64::from), - capture_flag, - is_once, - is_passive, - layout_client_rect_count = layout_trace.client_rect_count, - layout_client_rect_ms = layout_trace.client_rect_ms(), - layout_offset_parent_count = layout_trace.offset_parent_count, - layout_offset_parent_ms = layout_trace.offset_parent_ms(), - layout_offset_position_count = layout_trace.offset_position_count, - layout_offset_position_ms = layout_trace.offset_position_ms(), - elapsed_ms = listener_started.elapsed().as_millis(), - ); - } - set_event_internal_flag(scope, event, EVENT_PASSIVE_SLOT, false); - if event_internal_bool_flag(scope, event, EVENT_STOP_IMMEDIATE_SLOT) { return Ok(DispatchStatus::StopImmediate); } @@ -1654,6 +1637,9 @@ fn dispatch_public_event_with_original_target_impl<'s, 'i>( match dispatch_target { EventTargetHandle::Node(handle) => host.dom_host().owner_document_handle(handle), EventTargetHandle::Window => Some(host.document_handle()), + EventTargetHandle::PopupWindow(window) => { + host.lightweight_popup_document_handle(window.document_owner.popup_id()) + } EventTargetHandle::ChildWindow(window) => { host.child_browsing_context_document_handle(window.child_handle()) } @@ -1804,17 +1790,6 @@ fn dispatch_public_event_with_original_target_impl<'s, 'i>( )?; set_event_phase(scope, event, 2); - invoke_event_target_handler_property( - registry, - scope, - host_ptr, - dispatch_target, - invocation_targets_in_shadow_tree.contains(&dispatch_target), - target_object, - &event_type, - event, - ); - let stop_immediate = event_internal_bool_flag(scope, event, EVENT_STOP_IMMEDIATE_SLOT); let stop_prop = event_internal_bool_flag(scope, event, EVENT_STOP_PROPAGATION_SLOT); if !stop_immediate && dispatch_target == EventTargetHandle::Window { @@ -2003,16 +1978,6 @@ fn dispatch_public_event_with_original_target_impl<'s, 'i>( event_phase_for_current_target(host_ptr, original_target, *ancestor, 3), ); - invoke_event_target_handler_property( - registry, - scope, - host_ptr, - *ancestor, - invocation_targets_in_shadow_tree.contains(ancestor), - ancestor_obj, - &event_type, - event, - ); if event_internal_bool_flag(scope, event, EVENT_STOP_IMMEDIATE_SLOT) { break; } @@ -2124,7 +2089,6 @@ pub(crate) fn dispatch_host_event( host_ptr, dispatch_target, invocation_target_in_shadow_tree, - target_object, event_type, event, ); @@ -2142,21 +2106,9 @@ fn run_host_event_dispatch<'s>( host_ptr: *mut PageScriptHost, dispatch_target: EventTargetHandle, invocation_target_in_shadow_tree: bool, - target_object: v8::Local<'s, v8::Object>, event_type: &(impl EventTypeKey + ?Sized), event: v8::Local<'s, v8::Object>, ) -> std::result::Result<(), String> { - invoke_event_handler_property( - registry, - scope, - host_ptr, - dispatch_target, - invocation_target_in_shadow_tree, - target_object, - event_type, - event, - ); - if dispatch_target == EventTargetHandle::Window { registry.call_listeners_filtered( scope, @@ -2749,7 +2701,9 @@ fn retarget_event_target( }; let against = match current_target { EventTargetHandle::Node(handle) => Some(handle), - _ => None, + EventTargetHandle::Window + | EventTargetHandle::ChildWindow(_) + | EventTargetHandle::PopupWindow(_) => None, }; let runtime = unsafe { &*host_ptr }; EventTargetHandle::Node(runtime.dom_host().retarget(candidate, against)) @@ -2824,3 +2778,217 @@ fn event_bool_property( .get(scope, key.into()) .is_some_and(|value| value.boolean_value(scope)) } + +impl HostEventTargetRegistry { + pub(crate) fn set_compiled_event_handler_property( + &mut self, + target: EventTargetHandle, + event_type: &(impl EventTypeKey + ?Sized), + callback_id: Option, + ) -> Option { + let listener_id = self + .handler_properties + .get(&target) + .and_then(|handlers| handlers.get(event_type)) + .and_then(|entry| entry.listener_id) + .unwrap_or_else(|| self.allocate_listener_id()); + self.ensure_event_type_registration_id(target, event_type, listener_id); + let state = callback_id + .map(EventHandlerPropertyState::Callback) + .unwrap_or(EventHandlerPropertyState::Null); + let previous = self.handler_properties.entry(target).or_default().insert( + event_type.to_event_type(), + EventHandlerPropertyEntry { + listener_id: Some(listener_id), + state, + }, + ); + previous.and_then(event_handler_callback_id) + } + + pub(crate) fn set_event_handler_content_attribute( + &mut self, + target: EventTargetHandle, + event_type: &(impl EventTypeKey + ?Sized), + handler: Option, + ) -> Option { + let Some(handler) = handler else { + let removed = self + .handler_properties + .get_mut(&target) + .and_then(|handlers| handlers.shift_remove(event_type)); + let remove_target = self + .handler_properties + .get(&target) + .is_some_and(indexmap::IndexMap::is_empty); + if remove_target { + self.handler_properties.remove(&target); + } + let callback_id = removed.and_then(event_handler_callback_id); + self.remove_event_type_registration_id_if_unused(target, event_type); + return callback_id; + }; + let listener_id = self + .handler_properties + .get(&target) + .and_then(|handlers| handlers.get(event_type)) + .and_then(|entry| entry.listener_id) + .unwrap_or_else(|| self.allocate_listener_id()); + self.ensure_event_type_registration_id(target, event_type, listener_id); + let previous = self.handler_properties.entry(target).or_default().insert( + event_type.to_event_type(), + EventHandlerPropertyEntry { + listener_id: Some(listener_id), + state: EventHandlerPropertyState::Uncompiled(handler), + }, + ); + previous.and_then(event_handler_callback_id) + } + + pub(crate) fn has_event_handler_property_entry( + &self, + target: EventTargetHandle, + event_type: &(impl EventTypeKey + ?Sized), + ) -> bool { + self.handler_properties + .get(&target) + .is_some_and(|handlers| handlers.contains_key(event_type)) + } + + pub(crate) fn ensure_event_handler_content_attribute( + &mut self, + target: EventTargetHandle, + event_type: &(impl EventTypeKey + ?Sized), + handler: Option, + ) { + if let Some(handler) = handler + && self + .handler_properties + .get(&target) + .and_then(|handlers| handlers.get(event_type)) + .is_none() + { + let _ = self.set_event_handler_content_attribute(target, event_type, Some(handler)); + } + } + + pub(crate) fn uncompiled_event_handler_content_attribute( + &self, + target: EventTargetHandle, + event_type: &(impl EventTypeKey + ?Sized), + ) -> Option { + match &self + .handler_properties + .get(&target) + .and_then(|target_handlers| target_handlers.get(event_type))? + .state + { + EventHandlerPropertyState::Uncompiled(handler) => Some(handler.clone()), + EventHandlerPropertyState::Callback(_) | EventHandlerPropertyState::Null => None, + } + } +} + +fn invoke_registered_event_handler<'s>( + _registry: &mut HostEventTargetRegistry, + scope: &mut v8::PinScope<'s, '_>, + host_ptr: *mut PageScriptHost, + target: EventTargetHandle, + invocation_target_in_shadow_tree: bool, + event_type: &(impl EventTypeKey + ?Sized), + event: v8::Local<'s, v8::Object>, + callback_id: crate::native_bridge::EventCallbackId, +) { + let handler_name = format!("on{event_type}"); + let Some(prepared) = unsafe { &*host_ptr }.prepare_event_callback(scope, callback_id) else { + return; + }; + + let timing_started = moli_trace::cdp_nav_timing_enabled().then(Instant::now); + if target == EventTargetHandle::Window + && event_type.is_type("error") + && let Some(arguments) = error_event_handler_arguments(scope, event) + { + let returned = invoke_prepared_event_callback( + scope, + host_ptr, + invocation_target_in_shadow_tree, + event_type, + &handler_name, + prepared, + target, + event, + &arguments, + ); + if let Some(returned) = returned { + let returned = v8::Local::new(scope, returned); + apply_event_handler_return_value( + scope, + event, + returned, + EventHandlerType::OnErrorEventHandler, + ); + } + if let Some(timing_started) = timing_started { + tracing::info!( + target: "moli_cdp_nav_timing", + stage = "event_handler_property_invoked", + event_type = %event_type, + handler_name, + ?target, + elapsed_ms = timing_started.elapsed().as_millis(), + ); + } + return; + } + + if event_type.is_type("beforeunload") { + invoke_prepared_before_unload_event_handler( + scope, + host_ptr, + target, + invocation_target_in_shadow_tree, + event_type, + &handler_name, + prepared, + event, + ); + if let Some(timing_started) = timing_started { + tracing::info!( + target: "moli_cdp_nav_timing", + stage = "event_handler_property_invoked", + event_type = %event_type, + handler_name, + ?target, + elapsed_ms = timing_started.elapsed().as_millis(), + ); + } + return; + } + + let returned = invoke_prepared_event_callback( + scope, + host_ptr, + invocation_target_in_shadow_tree, + event_type, + &handler_name, + prepared, + target, + event, + &[event.into()], + ); + if let Some(returned) = returned { + let returned = v8::Local::new(scope, returned); + apply_event_handler_return_value(scope, event, returned, EventHandlerType::EventHandler); + } + if let Some(timing_started) = timing_started { + tracing::info!( + target: "moli_cdp_nav_timing", + stage = "event_handler_property_invoked", + event_type = %event_type, + handler_name, + ?target, + elapsed_ms = timing_started.elapsed().as_millis(), + ); + } +} diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs index abfcc15d8d8..307d49b1c3a 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs @@ -215,6 +215,7 @@ impl PageScriptHost { // resources discovered by the outer step before parking it too. let discovery_signals = parser.take_discovery_signals(); self.queue_live_child_parser_discovery_signals( + scope, child_handle, document_handle, discovery_signals, @@ -581,6 +582,7 @@ impl PageScriptHost { parser.finish(&mut owner) }; self.queue_live_child_parser_discovery_signals( + scope, child_handle, document_handle, finish_signals.discovery_signals, @@ -624,6 +626,7 @@ impl PageScriptHost { fn queue_live_child_parser_discovery_signals( &mut self, + scope: &mut v8::PinScope<'_, '_>, child_handle: DomHandle, document_handle: DomHandle, discovery_signals: crate::live_document_parser::LiveDocumentParserDiscoverySignals, @@ -898,6 +901,7 @@ impl PageScriptHost { return false; } self.queue_live_child_parser_discovery_signals( + scope, child_handle, document_handle, insertion.take_discovery_signals(), diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/loads.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/loads.rs index cfc0125758c..166e6fa5076 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/loads.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/loads.rs @@ -637,10 +637,7 @@ impl PageScriptHost { true, ) } - Ok( - outcome @ (ChildDocumentLoadOutcome::Redirect(_) - | ChildDocumentLoadOutcome::Download(_)), - ) => (Ok(outcome), false), + Ok(outcome @ ChildDocumentLoadOutcome::Redirect(_)) => (Ok(outcome), false), Err(error) => (Err(error), true), } } else { diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_events.rs b/moli-renderer-v8/src/native_bridge/context_host/child_events.rs index 6d4008a3b86..332601bfd31 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_events.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_events.rs @@ -8,20 +8,20 @@ use crate::{ }, document_runtime::DomHandle, document_runtime::EventTargetHandle, - exception_reporting::invoke_event_handler, frame_owner_model::{FrameDocumentTaskOwner, LocalWindowId}, host::{ - ChildWindowEventTarget, DispatchStatus, create_host_event, event_dispatch_status, - invoke_prepared_before_unload_event_handler, invoke_prepared_event_callback, + ChildWindowEventTarget, DispatchStatus, EventHandlerPropertyState, UncompiledEventHandler, + create_host_event, event_dispatch_status, invoke_prepared_before_unload_event_handler, + invoke_prepared_event_callback, }, native_bridge::{ ACTIVE_CHILD_WINDOW_HANDLE_SLOT, EventCallbackId, PreparedEventCallback, - element::EventAttributeHandlerScope, element::compile_event_attribute_handler_for_owner, + element::compile_body_window_event_attribute, }, - util::{get_private_value, set_private_value, v8_string, v8str}, + util::{get_private_value, set_private_value}, v8_execution_watchdog::V8ExecutionWatchdog, }; -use std::{collections::HashSet, convert::TryFrom}; +use std::collections::HashSet; #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum ChildWindowEventRegistrationKind { @@ -34,7 +34,7 @@ struct ChildWindowEventRegistrationId(u64); pub(super) struct ChildWindowEventListenerEntry { registration_id: ChildWindowEventRegistrationId, - callback_id: EventCallbackId, + callback_state: EventHandlerPropertyState, registration_kind: ChildWindowEventRegistrationKind, local_window_id: Option, capture: bool, @@ -42,7 +42,7 @@ pub(super) struct ChildWindowEventListenerEntry { } struct ChildWindowEventListenerSnapshot { - callback_id: EventCallbackId, + callback_state: EventHandlerPropertyState, registration_kind: ChildWindowEventRegistrationKind, local_window_id: Option, once: bool, @@ -149,7 +149,7 @@ impl PageScriptHost { entry.registration_kind == ChildWindowEventRegistrationKind::EventListener && entry.capture == capture }) - .map(|entry| entry.callback_id) + .filter_map(|entry| entry.callback_state.callback_id()) .collect() } @@ -199,7 +199,7 @@ impl PageScriptHost { .or_default() .push(ChildWindowEventListenerEntry { registration_id, - callback_id, + callback_state: EventHandlerPropertyState::Callback(callback_id), registration_kind: ChildWindowEventRegistrationKind::EventListener, local_window_id: Some(target.owner().local_window_id), capture, @@ -212,7 +212,7 @@ impl PageScriptHost { scope: &mut v8::PinScope<'s, '_>, handle: DomHandle, handler_name: &str, - handler: Option>, + handler: Option>, callback_relevant_context: v8::Local<'s, v8::Context>, ) { let Some(event_type) = child_window_event_type_from_handler_name(handler_name) else { @@ -226,20 +226,51 @@ impl PageScriptHost { } return; }; - let owner = self.frame_owner_current_child_snapshot(handle); - let local_window_id = owner.as_ref().map(|owner| owner.local_window_id); let incumbent_context = scope .get_incumbent_context() .unwrap_or_else(|| scope.get_current_context()); - let callback = v8::Local::::from(handler); - let callback_id = self.register_event_callback( + let callback_id = self.register_event_handler_callback( scope, - callback, + handler, callback_relevant_context, incumbent_context, ); self.capture_event_callback_initiator(scope, callback_id); - let previous_callback_id = self + if let Some(previous) = self.set_child_window_event_handler_state( + handle, + event_type, + EventHandlerPropertyState::Callback(callback_id), + ) { + self.release_event_callback(previous); + } + } + + pub(crate) fn set_child_window_event_handler_content_attribute( + &mut self, + handle: DomHandle, + event_type: &(impl EventTypeKey + ?Sized), + handler: Option, + ) -> Option { + match handler { + Some(handler) => self.set_child_window_event_handler_state( + handle, + event_type, + EventHandlerPropertyState::Uncompiled(handler), + ), + None => self.remove_child_window_event_handler_property(handle, event_type), + } + } + + fn set_child_window_event_handler_state( + &mut self, + handle: DomHandle, + event_type: &(impl EventTypeKey + ?Sized), + state: EventHandlerPropertyState, + ) -> Option { + let local_window_id = self + .frame_owner_current_child_snapshot(handle) + .map(|owner| owner.local_window_id); + if let Some(entry) = self .child_window_event_listeners .get_mut(&handle) .and_then(|target_map| target_map.get_mut(event_type)) @@ -249,15 +280,11 @@ impl PageScriptHost { == ChildWindowEventRegistrationKind::EventHandlerProperty }) }) - .map(|entry| { - let previous_callback_id = entry.callback_id; - entry.callback_id = callback_id; - entry.local_window_id = local_window_id; - previous_callback_id - }); - if let Some(previous_callback_id) = previous_callback_id { - self.release_event_callback(previous_callback_id); - return; + { + let previous = entry.callback_state.callback_id(); + entry.callback_state = state; + entry.local_window_id = local_window_id; + return previous; } let registration_id = self.allocate_child_window_event_registration_id(); self.child_window_event_listeners @@ -267,32 +294,99 @@ impl PageScriptHost { .or_default() .push(ChildWindowEventListenerEntry { registration_id, - callback_id, + callback_state: state, registration_kind: ChildWindowEventRegistrationKind::EventHandlerProperty, local_window_id, capture: false, once: false, }); + None } pub(crate) fn child_window_event_handler_property_value<'s>( - &self, + &mut self, scope: &mut v8::PinScope<'s, '_>, handle: DomHandle, handler_name: &str, ) -> Option> { let event_type = child_window_event_type_from_handler_name(handler_name)?; - self.child_window_event_listeners + let entry = self + .child_window_event_listeners .get(&handle) .and_then(|target_map| target_map.get(event_type)) .and_then(|entries| { - entries.iter().find_map(|entry| { - (entry.registration_kind - == ChildWindowEventRegistrationKind::EventHandlerProperty) - .then(|| self.event_callback_value(scope, entry.callback_id)) - .flatten() + entries.iter().find(|entry| { + entry.registration_kind + == ChildWindowEventRegistrationKind::EventHandlerProperty }) - }) + })?; + let state = entry.callback_state.clone(); + let registration_id = entry.registration_id; + let target = self.current_child_window_event_target(handle)?; + if entry.local_window_id != Some(target.owner().local_window_id) { + return None; + } + match state { + EventHandlerPropertyState::Callback(callback_id) => { + self.event_callback_value(scope, callback_id) + } + EventHandlerPropertyState::Null => Some(v8::null(scope).into()), + EventHandlerPropertyState::Uncompiled(uncompiled) => { + let context = self + .ensure_prebootstrapped_child_default_context(scope, handle) + .ok()?; + let scope = &mut v8::ContextScope::new(scope, context); + // Compilation can report a syntax error and re-enter this getter. + // Keep the listener's position while exposing null during that report. + self.child_window_event_listeners + .get_mut(&handle)? + .get_mut(event_type)? + .iter_mut() + .find(|entry| entry.registration_id == registration_id)? + .callback_state = EventHandlerPropertyState::Null; + let host_ptr = self as *mut PageScriptHost; + let handler = compile_body_window_event_attribute( + scope, + host_ptr, + crate::native_bridge::OwnerDispatchScope::Child(handle), + &uncompiled, + event_type, + ); + if !self.child_window_event_target_is_current(target) { + return Some(v8::null(scope).into()); + } + // An error listener can replace, remove or reactivate this handler. + // Do not overwrite the replacement after returning from the report. + let unchanged = self + .child_window_event_listeners + .get(&handle) + .and_then(|map| map.get(event_type)) + .is_some_and(|entries| { + entries.iter().any(|entry| { + entry.registration_id == registration_id + && matches!(entry.callback_state, EventHandlerPropertyState::Null) + }) + }); + if unchanged && let Some(handler) = handler { + let callback_id = self.register_event_handler_callback( + scope, + handler.into(), + context, + context, + ); + let _ = self.set_child_window_event_handler_state( + handle, + event_type, + EventHandlerPropertyState::Callback(callback_id), + ); + } + Some( + handler + .map(Into::into) + .unwrap_or_else(|| v8::null(scope).into()), + ) + } + } } fn remove_child_window_event_handler_property( @@ -307,7 +401,7 @@ impl PageScriptHost { .find(|entry| { entry.registration_kind == ChildWindowEventRegistrationKind::EventHandlerProperty }) - .map(|entry| entry.callback_id); + .and_then(|entry| entry.callback_state.callback_id()); entries.retain(|entry| { entry.registration_kind != ChildWindowEventRegistrationKind::EventHandlerProperty }); @@ -477,14 +571,6 @@ impl PageScriptHost { event_type, slot, ) else { - if let Some(callback_id) = self.remove_child_window_event_registration_by_id( - target.child_handle(), - event_type, - slot.registration_id, - ) { - self.unregister_abort_target_listener(callback_id); - self.release_event_callback(callback_id); - } continue; }; if ready.once @@ -603,32 +689,79 @@ impl PageScriptHost { .unwrap_or_default() } - fn prepare_child_window_event_listener_invocation( + fn child_window_event_listener_snapshot( &self, + handle: DomHandle, + event_type: &(impl EventTypeKey + ?Sized), + slot: ChildWindowEventDispatchSlot, + ) -> Option { + let entry = self + .child_window_event_listeners + .get(&handle)? + .get(event_type)? + .iter() + .find(|entry| entry.registration_id == slot.registration_id)?; + Some(ChildWindowEventListenerSnapshot { + callback_state: entry.callback_state.clone(), + registration_kind: entry.registration_kind, + local_window_id: entry.local_window_id, + once: entry.once, + }) + } + + fn retire_child_window_event_registration( + &mut self, + handle: DomHandle, + event_type: &(impl EventTypeKey + ?Sized), + slot: ChildWindowEventDispatchSlot, + ) { + if let Some(callback_id) = self.remove_child_window_event_registration_by_id( + handle, + event_type, + slot.registration_id, + ) { + self.unregister_abort_target_listener(callback_id); + self.release_event_callback(callback_id); + } + } + + fn prepare_child_window_event_listener_invocation( + &mut self, scope: &mut v8::PinScope<'_, '_>, handle: DomHandle, event_type: &(impl EventTypeKey + ?Sized), slot: ChildWindowEventDispatchSlot, ) -> Option { - let entry = self - .child_window_event_listeners - .get(&handle) - .and_then(|target_map| target_map.get(event_type))? - .iter() - .find(|entry| entry.registration_id == slot.registration_id)?; - let snapshot = ChildWindowEventListenerSnapshot { - callback_id: entry.callback_id, - registration_kind: entry.registration_kind, - local_window_id: entry.local_window_id, - once: entry.once, + let mut snapshot = self.child_window_event_listener_snapshot(handle, event_type, slot)?; + let Some(target) = self.current_child_window_event_target(handle) else { + self.retire_child_window_event_registration(handle, event_type, slot); + return None; }; - let target = self.current_child_window_event_target(handle)?; if snapshot.local_window_id != Some(target.owner().local_window_id) { + self.retire_child_window_event_registration(handle, event_type, slot); return None; } - let callback = self.prepare_event_callback(scope, snapshot.callback_id)?; + if matches!( + snapshot.callback_state, + EventHandlerPropertyState::Uncompiled(_) + ) { + let value = self.child_window_event_handler_property_value( + scope, + handle, + &format!("on{event_type}"), + )?; + if value.is_null_or_undefined() { + return None; + } + snapshot = self.child_window_event_listener_snapshot(handle, event_type, slot)?; + } + let callback_id = snapshot.callback_state.callback_id()?; + let Some(callback) = self.prepare_event_callback(scope, callback_id) else { + self.retire_child_window_event_registration(handle, event_type, slot); + return None; + }; Some(ReadyChildWindowEventListenerInvocation { - registration_id: entry.registration_id, + registration_id: slot.registration_id, registration_kind: snapshot.registration_kind, once: snapshot.once, target, @@ -692,14 +825,14 @@ impl PageScriptHost { let position = entries .iter() .position(|entry| entry.registration_id == registration_id)?; - let callback_id = entries.remove(position).callback_id; + let callback_id = entries.remove(position).callback_state.callback_id(); if entries.is_empty() { target_map.shift_remove(event_type); } if target_map.is_empty() { self.child_window_event_listeners.remove(&handle); } - Some(callback_id) + callback_id } pub(crate) fn remove_child_window_event_listener_by_id( @@ -716,7 +849,7 @@ impl PageScriptHost { .and_then(|entries| { entries.iter().find_map(|entry| { (entry.registration_kind == ChildWindowEventRegistrationKind::EventListener - && entry.callback_id == callback_id + && entry.callback_state.callback_id() == Some(callback_id) && entry.capture == capture) .then_some(entry.registration_id) }) @@ -737,7 +870,7 @@ impl PageScriptHost { for callback_id in target_map .into_values() .flatten() - .map(|entry| entry.callback_id) + .filter_map(|entry| entry.callback_state.callback_id()) { self.unregister_abort_target_listener(callback_id); self.release_event_callback(callback_id); @@ -750,7 +883,12 @@ impl PageScriptHost { ) { for target_map in self.child_window_event_listeners.values_mut() { target_map.retain(|_, entries| { - entries.retain(|entry| !retired.contains(&entry.callback_id)); + entries.retain(|entry| { + entry + .callback_state + .callback_id() + .is_none_or(|id| !retired.contains(&id)) + }); !entries.is_empty() }); } @@ -772,7 +910,8 @@ impl PageScriptHost { .and_then(|target_map| target_map.get(event_type)) .into_iter() .flatten() - .filter_map(|entry| self.event_callback_identities_for_test(entry.callback_id)) + .filter_map(|entry| entry.callback_state.callback_id()) + .filter_map(|id| self.event_callback_identities_for_test(id)) .collect() } } @@ -816,50 +955,6 @@ fn apply_child_window_event_handler_return<'s>( apply_event_handler_return_value(scope, event, returned, handler_type); } -fn install_child_body_load_attribute_handler_if_needed<'s>( - scope: &mut v8::PinScope<'s, '_>, - host: &mut PageScriptHost, - handle: DomHandle, -) { - let Some(source) = host - .child_browsing_context_document_handle(handle) - .and_then(|document| { - host.dom_host() - .elements_by_tag_name(document, "body", false) - .into_iter() - .next() - }) - .and_then(|body| host.dom_host().get_attribute(body, "onload")) - .filter(|source| !source.trim().is_empty()) - else { - return; - }; - let Ok(context) = host.ensure_prebootstrapped_child_default_context(scope, handle) else { - return; - }; - let scope = &mut v8::ContextScope::new(scope, context); - let Some(window) = host.child_window_proxy_records.live_window(scope, handle) else { - return; - }; - if let Some(current) = window.get(scope, v8str(scope, "onload").into()) - && !current.is_null_or_undefined() - { - return; - } - let host_ptr: *mut PageScriptHost = host; - let Some(handler) = compile_event_attribute_handler_for_owner( - scope, - host_ptr, - OwnerDispatchScope::Child(handle), - source.as_ref(), - EventAttributeHandlerScope::ChildWindow, - ) else { - let _ = window.set(scope, v8str(scope, "onload").into(), v8::null(scope).into()); - return; - }; - let _ = window.set(scope, v8str(scope, "onload").into(), handler.into()); -} - fn enter_child_window_event_dispatch<'s>( scope: &mut v8::PinScope<'s, '_>, handle: DomHandle, @@ -884,66 +979,3 @@ fn restore_child_window_event_dispatch<'s>( let global = scope.get_current_context().global(scope); set_private_value(scope, global, ACTIVE_CHILD_WINDOW_HANDLE_SLOT, previous); } - -fn dispatch_child_body_storage_attribute<'s>( - scope: &mut v8::PinScope<'s, '_>, - window: v8::Local<'s, v8::Object>, - event: v8::Local<'s, v8::Object>, -) { - let Some(document) = window - .get(scope, v8str(scope, "document").into()) - .and_then(|value| v8::Local::::try_from(value).ok()) - else { - return; - }; - let Some(body) = document - .get(scope, v8str(scope, "body").into()) - .and_then(|value| v8::Local::::try_from(value).ok()) - else { - return; - }; - let Some(get_attribute) = body - .get(scope, v8str(scope, "getAttribute").into()) - .and_then(|value| v8::Local::::try_from(value).ok()) - else { - return; - }; - let Some(source_value) = - get_attribute.call(scope, body.into(), &[v8str(scope, "onstorage").into()]) - else { - return; - }; - if source_value.is_null_or_undefined() { - return; - } - let Some(source) = source_value.to_string(scope) else { - return; - }; - let source = source.to_rust_string_lossy(scope); - if source.trim().is_empty() { - return; - } - let wrapped = format!("(function(window){{with(window){{{source}}}}})"); - let Some(script_source) = v8_string(scope, &wrapped) else { - return; - }; - let Some(handler) = v8::Script::compile(scope, script_source, None) - .and_then(|script| crate::script_execution::execute_compiled_script(scope, script)) - .and_then(|value| v8::Local::::try_from(value).ok()) - else { - return; - }; - let event_key = v8str(scope, "event"); - let previous_event = window - .get(scope, event_key.into()) - .unwrap_or_else(|| v8::undefined(scope).into()); - let _ = window.set(scope, event_key.into(), event.into()); - let _ = invoke_event_handler( - scope, - "child body onstorage", - handler, - body.into(), - &[window.into()], - ); - let _ = window.set(scope, event_key.into(), previous_event); -} diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commands.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commands.rs index bf217d18739..612ca0970bd 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commands.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commands.rs @@ -4,6 +4,7 @@ use super::super::{ child_frames::PendingChildFrameNavigation, }; use crate::document_runtime::DomHandle; +use moli_page_types::{NavigationHistoryMutation, cross_document_navigation_seed}; use url::Url; impl PageScriptHost { @@ -317,69 +318,6 @@ impl PageScriptHost { } } - pub(crate) fn queue_deferred_child_browsing_context_navigation_to_url( - &mut self, - scope: &mut v8::PinScope<'_, '_>, - handle: DomHandle, - resolved_url: &str, - ) -> bool { - let download_policy = self.capture_child_navigation_download_policy(scope, handle); - if !self.child_browsing_contexts.contains_key(&handle) { - return false; - } - let Some(url) = Url::parse(resolved_url).ok() else { - return false; - }; - if let Some(entry) = self.child_browsing_contexts.get_mut(&handle) { - entry.apply_deferred_navigation_to_entry_seed(&url); - } - if self - .set_child_browsing_context_pending_navigation( - handle, - ChildBrowsingContextBootstrap::Url(url), - None, - false, - ) - .is_none() - { - return false; - } - let queued = self.queue_child_browsing_context_navigation_commit(handle); - self.remember_child_navigation_download_policy(handle, download_policy, queued) - } - - pub(crate) fn queue_deferred_child_browsing_context_navigation_request( - &mut self, - scope: &mut v8::PinScope<'_, '_>, - handle: DomHandle, - request: ChildBrowsingContextNavigationRequest, - ) -> bool { - let download_policy = self.capture_child_navigation_download_policy(scope, handle); - if !self.child_browsing_contexts.contains_key(&handle) { - return false; - } - self.reject_replaced_service_worker_child_client_navigation( - handle, - "The navigation was canceled.".to_owned(), - ); - if let Some(entry) = self.child_browsing_contexts.get_mut(&handle) { - entry.apply_deferred_navigation_to_entry_seed(&request.url); - } - if self - .set_child_browsing_context_pending_navigation( - handle, - ChildBrowsingContextBootstrap::Request(request), - None, - false, - ) - .is_none() - { - return false; - } - let queued = self.queue_child_browsing_context_navigation_commit(handle); - self.remember_child_navigation_download_policy(handle, download_policy, queued) - } - pub(crate) fn child_browsing_context_has_pending_cross_document_traversal( &self, handle: DomHandle, diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs index a92407967cb..05284718060 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs @@ -957,10 +957,6 @@ impl ChildBrowsingContextEntry { } } - pub(super) fn apply_deferred_navigation_to_entry_seed(&mut self, url: &Url) { - self.apply_navigation_to_entry_seed(url); - } - pub(super) fn clear_navigation_activation(&mut self) { self.navigation_entry_seed.activation = None; } diff --git a/moli-renderer-v8/src/native_bridge/context_host/event_callbacks.rs b/moli-renderer-v8/src/native_bridge/context_host/event_callbacks.rs index d32b6bfc538..f16a7be37c5 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/event_callbacks.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/event_callbacks.rs @@ -4,11 +4,18 @@ use crate::event_type::EventTypeKey; use moli_webidl_callback::{PreparedWebIdlCallbackInterface, WebIdlCallbackInterface}; use std::collections::{HashMap, HashSet}; +#[derive(Clone, Copy, PartialEq, Eq)] +enum EventCallbackKind { + Listener, + Handler, +} + #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub(crate) struct EventCallbackId(u64); struct EventCallbackRecord { callback: WebIdlCallbackInterface, + kind: EventCallbackKind, resource_initiator: Option, relevant_identity: Option, registration_identity: Option, @@ -18,6 +25,7 @@ struct EventCallbackRecord { pub(crate) struct PreparedEventCallback { callback: PreparedWebIdlCallbackInterface, + kind: EventCallbackKind, resource_initiator: Option, relevant_identity: Option, relevant_host: *mut PageScriptHost, @@ -295,12 +303,12 @@ impl PageScriptHost { scope: &mut v8::PinScope<'s, '_>, target: crate::document_runtime::EventTargetHandle, event_type: &(impl EventTypeKey + ?Sized), - handler: Option>, + handler: Option>, ) { let resource_initiator = handler.map(|_| crate::resource_initiator::CallbackInitiator::capture(scope)); let relevant_context = handler - .and_then(|handler| v8::Local::::from(handler).get_creation_context(scope)) + .and_then(|handler| handler.get_creation_context(scope)) .unwrap_or_else(|| scope.get_current_context()); let incumbent_context = scope .get_incumbent_context() @@ -324,15 +332,19 @@ impl PageScriptHost { handler: Option>, target_context: v8::Local<'s, v8::Context>, ) { - self.set_registered_event_handler_property_with_contexts( - scope, - target, - event_type, - handler, - target_context, - target_context, - None, - ); + let callback_id = handler.map(|handler| { + self.register_event_handler_callback( + scope, + handler.into(), + target_context, + target_context, + ) + }); + if let Some(previous) = + self.set_compiled_event_handler_property(target, event_type, callback_id) + { + self.release_event_callback(previous); + } } fn set_registered_event_handler_property_with_contexts<'s>( @@ -340,13 +352,18 @@ impl PageScriptHost { scope: &mut v8::PinScope<'s, '_>, target: crate::document_runtime::EventTargetHandle, event_type: &(impl EventTypeKey + ?Sized), - handler: Option>, + handler: Option>, relevant_context: v8::Local<'s, v8::Context>, incumbent_context: v8::Local<'s, v8::Context>, resource_initiator: Option, ) { let callback_id = handler.map(|handler| { - self.register_event_callback(scope, handler.into(), relevant_context, incumbent_context) + self.register_event_handler_callback( + scope, + handler, + relevant_context, + incumbent_context, + ) }); if let Some(id) = callback_id && let Some(record) = self.event_callbacks.records.get_mut(&id) @@ -392,6 +409,27 @@ impl PageScriptHost { &mut self, scope: &mut v8::PinScope<'_, '_>, callback: WebIdlCallbackInterface, + ) -> EventCallbackId { + self.register_event_callback_with_kind(scope, callback, EventCallbackKind::Listener) + } + + pub(crate) fn register_event_handler_callback<'s>( + &mut self, + scope: &mut v8::PinScope<'s, '_>, + callback: v8::Local<'s, v8::Object>, + relevant_context: v8::Local<'s, v8::Context>, + incumbent_context: v8::Local<'s, v8::Context>, + ) -> EventCallbackId { + let callback = + WebIdlCallbackInterface::new(scope, callback, relevant_context, incumbent_context); + self.register_event_callback_with_kind(scope, callback, EventCallbackKind::Handler) + } + + fn register_event_callback_with_kind( + &mut self, + scope: &mut v8::PinScope<'_, '_>, + callback: WebIdlCallbackInterface, + kind: EventCallbackKind, ) -> EventCallbackId { let relevant_context = callback.relevant_context(scope); // A stored non-callable handler has no invocation realm. Its value @@ -414,6 +452,7 @@ impl PageScriptHost { id, EventCallbackRecord { callback, + kind, resource_initiator: None, relevant_identity, registration_identity, @@ -527,6 +566,7 @@ impl PageScriptHost { } Some(PreparedEventCallback { callback: record.callback.prepare(scope), + kind: record.kind, resource_initiator: record.resource_initiator.clone(), relevant_identity: record.relevant_identity, relevant_host, diff --git a/moli-renderer-v8/src/native_bridge/context_host/layout.rs b/moli-renderer-v8/src/native_bridge/context_host/layout.rs index 09533ee0250..535dc3d71f8 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/layout.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/layout.rs @@ -296,6 +296,7 @@ impl PageScriptHost { .frame_viewport(frame) } + #[cfg(debug_assertions)] pub(crate) fn style_viewport_generation(&self) -> u64 { self.style_viewport_generation.get() } @@ -609,13 +610,15 @@ impl PageScriptHost { frames.geometry, ); } else { - self.document_layout_state.borrow_mut().publish_latest_layout( - document, - tree, - metrics, - #[cfg(feature = "devtools")] - frames.geometry, - ); + self.document_layout_state + .borrow_mut() + .publish_latest_layout( + document, + tree, + metrics, + #[cfg(feature = "devtools")] + frames.geometry, + ); } for (target, size) in sampled_viewports { self.sample_realtime_frame_viewport(target, size); diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rs index c1f7d1bb576..f2d9a6e9c22 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs @@ -239,7 +239,7 @@ use child_documents::{ChildDocumentParserStore, PendingChildDocumentNavigation}; use child_events::ChildWindowEventListenerEntry; use child_frame_runtime::ChildWindowProxyRecords; pub(crate) use child_frame_runtime::{ - caller_can_access_window, cross_origin_lightweight_popup_id, is_cross_origin_location_proxy, + cross_origin_lightweight_popup_id, is_cross_origin_location_proxy, is_cross_origin_top_window_proxy, is_cross_origin_window_proxy, throw_cross_origin_location_security_error, throw_cross_origin_type_error, }; diff --git a/moli-renderer-v8/src/native_bridge/context_host/popups.rs b/moli-renderer-v8/src/native_bridge/context_host/popups.rs index 28fe0e173b3..a985932828f 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/popups.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/popups.rs @@ -14,11 +14,10 @@ use crate::{ construct_original_event, construct_original_page_transition_event, deep_clone_shared_web_storage_store, dispatch_simple_event_target_event_with_original_target, - finish_cross_document_navigation_for_window, - history_entry_seed_for_location_kind, initialize_simple_event_target, - install_navigation_bootstrap_entry_for_holder, install_simple_window_event_handlers, - install_storage_aliases_for_window, navigation_unload_event_active, - new_shared_web_storage_store, scoped_indexed_db_factory, + finish_cross_document_navigation_for_window, history_entry_seed_for_location_kind, + initialize_simple_event_target, install_navigation_bootstrap_entry_for_holder, + install_simple_window_event_handlers, install_storage_aliases_for_window, + navigation_unload_event_active, new_shared_web_storage_store, scoped_indexed_db_factory, sync_window_location_history_navigation_runtime_surface, sync_window_location_runtime_state, web_storage_area_key_for_storage_key, }, @@ -234,7 +233,7 @@ impl PendingLightweightPopupHistory { let mut seed = match self.entry_seed() { Some(seed) => seed.clone(), None => { - let Some(seed) = history_entry_seed_for_cross_document_location( + let Some(seed) = history_entry_seed_for_location_kind( scope, window, final_url, @@ -259,6 +258,12 @@ impl PendingLightweightPopupHistory { } } +#[derive(Clone, Copy)] +enum LightweightPopupParserStep { + Script(DomHandle), + WindowEventHandlers(DomHandle), +} + struct LightweightPopupClassicScriptContinuation { task: LightweightPopupNavigationTaskToken, document_handle: DomHandle, @@ -2144,10 +2149,9 @@ impl PageScriptHost { return false; } let document_owner = navigation_task.document_owner(); - let history = - history_entry_seed_for_location_kind(scope, window, &target_url, kind) - .map(PendingLightweightPopupHistory::Navigation) - .unwrap_or(PendingLightweightPopupHistory::Initial); + let history = history_entry_seed_for_location_kind(scope, window, &target_url, kind) + .map(PendingLightweightPopupHistory::Navigation) + .unwrap_or(PendingLightweightPopupHistory::Initial); if moli_url::is_about_blank(&target_url) { let inherited_origin = self.window_access_origin_for_dispatch_scope(creator_scope); let page_swap = history.page_swap_navigation( @@ -4270,16 +4274,31 @@ impl PageScriptHost { PopupDocumentLoadBodyActivity::NoPageCodeOrEventDispatch, ); }; - if !scripting_enabled { - return LightweightPopupClassicScriptAdvance::Completed( - PopupDocumentLoadBodyActivity::NoPageCodeOrEventDispatch, - ); - } let Some(document) = self.lightweight_popup_document_record(task.popup_id()) else { return LightweightPopupClassicScriptAdvance::Completed( PopupDocumentLoadBodyActivity::NoPageCodeOrEventDispatch, ); }; + // Register body/frameset handlers when execution reaches the element, + // after head scripts and before scripts within its subtree. Keeping + // these steps in the continuation also preserves listener order across + // a parser-blocking external script load. + let mut parser_steps = Vec::new(); + let mut stack = vec![document_handle]; + while let Some(handle) = stack.pop() { + let Some(node) = self.dom_host().node(handle) else { + continue; + }; + if node.is_script_element() && scripting_enabled { + parser_steps.push(LightweightPopupParserStep::Script(handle)); + } else if node.is_html_element_named("body") || node.is_html_element_named("frameset") { + parser_steps.push(LightweightPopupParserStep::WindowEventHandlers(handle)); + } + stack.extend(self.dom_host().child_handles_reversed(handle)); + if let Some(shadow_root) = self.dom_host().shadow_root_handle(handle) { + stack.push(shadow_root); + } + } let continuation = LightweightPopupClassicScriptContinuation { task, document_handle, @@ -4308,11 +4327,22 @@ impl PageScriptHost { ) -> LightweightPopupClassicScriptAdvance { let task = continuation.task; let popup_id = task.popup_id(); - while let Some(&script) = continuation.scripts.get(continuation.next_script_index) { - continuation.next_script_index += 1; + while let Some(&step) = continuation.parser_steps.get(continuation.next_step_index) { + continuation.next_step_index += 1; if !self.lightweight_popup_committed_navigation_task_is_current(task) { return LightweightPopupClassicScriptAdvance::Completed(body_activity); } + let script = match step { + LightweightPopupParserStep::Script(script) => script, + LightweightPopupParserStep::WindowEventHandlers(handle) => { + crate::native_bridge::element::initialize_parser_inserted_event_handlers( + scope, + self as *mut PageScriptHost, + handle, + ); + continue; + } + }; if continuation.stream_script.is_none() && self .dom_host() @@ -6433,20 +6463,6 @@ fn set_lightweight_popup_persisted_script_global<'s>( set_object_slot(scope, window, name, value); } -fn clear_lightweight_popup_window_document_event_state<'s>( - scope: &mut v8::PinScope<'s, '_>, - window: v8::Local<'s, v8::Object>, -) { - let registry = new_null_prototype_object(scope); - set_private_value( - scope, - window, - SIMPLE_EVENT_TARGET_LISTENERS_SLOT, - registry.into(), - ); - clear_simple_window_event_handler_values(scope, window); -} - fn lightweight_popup_effective_navigation_kind( current_document_is_initial_empty: bool, kind: crate::context_bootstrap::LocationNavigationKind, diff --git a/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs b/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs index ea497b3f072..65da046f994 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs @@ -1277,8 +1277,7 @@ impl PageScriptHost { owner: OwnerDispatchScope, kind: ContentSecurityPolicyNonUrlKind, source: &str, - ) -> Option>> - { + ) -> Option { let snapshot = self.owner_document_policy_snapshot(owner)?; // SAFETY: PageScriptHost is owned by the ScriptVm that owns this DocumentRuntime. Some( @@ -1303,8 +1302,7 @@ impl PageScriptHost { owner: OwnerDispatchScope, source: &str, request: ContentSecurityPolicyScriptElementRequest<'_>, - ) -> Option>> - { + ) -> Option { let snapshot = self.owner_document_policy_snapshot(owner)?; // SAFETY: PageScriptHost is owned by the ScriptVm that owns this DocumentRuntime. Some( @@ -1479,7 +1477,7 @@ impl PageScriptHost { request_url, ContentSecurityPolicyRedirectStatus::NoRedirect, ) - .map(|check| check.into_violations().1.is_none()) + .map(|check| check.into_violations().1.is_empty()) .unwrap_or(true) } @@ -1641,7 +1639,7 @@ impl PageScriptHost { include_call_location: bool, ) -> bool { let (mut report_only_violation, mut enforced_violation) = check.into_violations(); - if report_only_violation.is_none() && enforced_violation.is_none() { + if report_only_violation.is_empty() && enforced_violation.is_empty() { return true; } if include_call_location @@ -1657,7 +1655,7 @@ impl PageScriptHost { violation.column_number = column_number; } } - let allowed = enforced_violation.is_none(); + let allowed = enforced_violation.is_empty(); for violation in report_only_violation.iter().chain(&enforced_violation) { self.queue_content_security_policy_violation_task(scope, owner, None, violation); } @@ -1675,6 +1673,8 @@ impl PageScriptHost { )? .into_violations() .1 + .into_iter() + .next() } pub(crate) fn allows_trusted_type_policy_name_by_csp<'s>( diff --git a/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/operation_receiver.rs b/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/operation_receiver.rs index f2230969d07..998b892651b 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/operation_receiver.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/operation_receiver.rs @@ -6,28 +6,6 @@ use crate::{ util::get_private_value, }; -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub(crate) enum WindowOperationReceiverCaptureError { - IllegalInvocation, - CrossOrigin, -} - -impl WindowOperationReceiverCaptureError { - /// Ordinary operation functions report receiver errors in their own realm. - /// Cross-origin WindowProxy/Location access surfaces have a separate error path. - pub(crate) fn throw(self, scope: &mut v8::PinScope<'_, '_>) { - match self { - Self::IllegalInvocation => crate::util::throw_type_error(scope, "Illegal invocation"), - Self::CrossOrigin => crate::native_bridge::throw_dom_exception( - scope, - "SecurityError", - 18, - "Blocked access to a cross-origin Window.", - ), - } - } -} - /// Window receiver frozen at the start of a WebIDL operation. /// /// Blink separates three phases in generated Window bindings: @@ -51,27 +29,12 @@ impl WindowOperationReceiver { receiver: v8::Local<'s, v8::Object>, host: &PageScriptHost, ) -> Self { - Self::capture(scope, receiver, host, false).unwrap_or(Self { + let empty = Self { binding_at_capture: None, - }) - } - - pub(crate) fn capture_and_authorize<'s>( - scope: &mut v8::PinScope<'s, '_>, - receiver: v8::Local<'s, v8::Object>, - host: &PageScriptHost, - ) -> Result { - Self::capture(scope, receiver, host, true) - } - - fn capture<'s>( - scope: &mut v8::PinScope<'s, '_>, - receiver: v8::Local<'s, v8::Object>, - host: &PageScriptHost, - check_access: bool, - ) -> Result { - let receiver = moli_webapi_declare::web_api_object_target(scope, receiver) - .ok_or(WindowOperationReceiverCaptureError::IllegalInvocation)?; + }; + let Some(receiver) = moli_webapi_declare::web_api_object_target(scope, receiver) else { + return empty; + }; let current_context = scope.get_current_context(); if receiver.strict_equals(current_context.global(scope).into()) && is_window_receiver(scope, receiver) @@ -82,15 +45,9 @@ impl WindowOperationReceiver { // The context registry owns this exact native global, including // its retirement. Avoid private-slot reads on a detached proxy and // never resolve its old child marker to a replacement Window. - return Ok(Self { - binding_at_capture: None, - }); + return empty; } let marked_scope = marked_window_dispatch_scope(scope, receiver); - if marked_scope.is_none() && !is_window_receiver(scope, receiver) { - return Err(WindowOperationReceiverCaptureError::IllegalInvocation); - } - let relevant_context = receiver.get_creation_context(scope); let relevant_identity = relevant_context.and_then(|context| { host.window_execution_context_identity_for_v8_context(scope, context) @@ -111,29 +68,16 @@ impl WindowOperationReceiver { // the brand check so required-argument conversion can happen first, // then fail the native operation as a rejected current-realm Promise. let Some(target_scope) = target_scope else { - return Ok(Self { - binding_at_capture: None, - }); + return empty; }; let Some(target_owner) = host.current_window_execution_context_owner(target_scope) else { - return Ok(Self { - binding_at_capture: None, - }); + return empty; }; - let Some(accessing_identity) = - host.current_runtime_window_execution_context_identity(scope) - else { - return Ok(Self { - binding_at_capture: None, - }); - }; - if check_access - && !host.window_execution_context_can_access_dispatch_scope( - accessing_identity, - target_scope, - ) + if host + .current_runtime_window_execution_context_identity(scope) + .is_none() { - return Err(WindowOperationReceiverCaptureError::CrossOrigin); + return empty; } let binding_at_capture = match target_scope { @@ -160,7 +104,7 @@ impl WindowOperationReceiver { } }; - Ok(Self { binding_at_capture }) + Self { binding_at_capture } } /// Returns only the exact receiver realm captured before argument diff --git a/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs b/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs index 088c9b9be73..9d62fdd5698 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs @@ -311,7 +311,7 @@ impl PageScriptHost { }; let opaque_origin = inherited.or_else(|| { Some(crate::structured_clone::RuntimeMessageOpaqueOrigin::window( - self.child_default_context_bootstrap + self.window_default_context_bootstrap .as_ref()? .resource_owner_id, owner, diff --git a/moli-renderer-v8/src/native_bridge/element.rs b/moli-renderer-v8/src/native_bridge/element.rs index d1fc1a65a7c..4a0679cb21c 100644 --- a/moli-renderer-v8/src/native_bridge/element.rs +++ b/moli-renderer-v8/src/native_bridge/element.rs @@ -302,21 +302,19 @@ pub(crate) use details_dialog::{ queue_details_toggle_event_for_attribute_change, queue_parser_details_toggle_event, queue_parser_details_toggle_events_in_subtree, }; -pub(crate) use event_handlers::compile_window_body_onmessageerror_attribute; use event_handlers::install_global_event_handler_template_bindings as install_global_event_handler_templates_for_owner; use event_handlers::install_node_event_handler_template_bindings; pub(crate) use event_handlers::{ - EventAttributeHandlerScope, GlobalEventHandlerOwner, ParserAddedEventHandlers, compile_event_attribute_handler_for_owner, - compile_node_content_attribute_for_dispatch, compile_window_body_event_attribute, - event_handler_content_attribute_name, event_handler_content_attribute_names, initialize_parser_inserted_body_window_event_handlers, initialize_parser_inserted_event_handlers, - invalidate_event_handler_content_attribute, is_body_window_event_handler_attribute, - is_global_event_handler_attribute, node_event_handler_getter_function, - node_event_handler_setter_function, node_event_handler_value_from_wrapper, + GlobalEventHandlerOwner, ParserAddedEventHandlers, body_or_frameset_reflects_window_event_type, + canonical_event_handler_event_type, compile_body_window_event_attribute, + compile_node_content_attribute_for_dispatch, compile_window_event_attribute_handler, + element_event_handler_content_attribute_applies, event_handler_content_attribute_name, + event_handler_content_attribute_names, initialize_parser_inserted_event_handlers, + legacy_lenient_this_event_handler, node_event_handler_getter_function, + node_event_handler_setter_function, resolve_window_event_handler_content_attribute, }; use event_handlers::{ - body_onerror_getter_function, body_onerror_setter_function, body_onload_getter_function, - body_onload_setter_function, body_onmessageerror_getter_function, - body_onmessageerror_setter_function, + HtmlBodyWindowEventHandlersDeclaration, HtmlFrameSetWindowEventHandlersDeclaration, }; #[cfg(any(test, feature = "devtools"))] pub(crate) use events::construct_keyboard_event; @@ -333,8 +331,7 @@ pub(crate) use events::{TouchEventPoint, construct_touch_event_with_points}; pub(crate) use events::{ construct_activation_pointer_event, construct_drop_input_event, construct_mouse_event_for_target, construct_mouse_event_with_detail_for_target, - construct_mouse_event_with_related_target_for_target, - construct_wheel_event_for_target, + construct_mouse_event_with_related_target_for_target, construct_wheel_event_for_target, }; pub(crate) use events::{construct_clipboard_event, construct_focus_event}; #[cfg(any(test, feature = "devtools"))] @@ -343,6 +340,8 @@ pub(crate) use events::{construct_drag_event_with_related_target, construct_poin pub(crate) use focus::focus_live_element_for_inspector; pub(crate) use focus::is_disabled_form_control; use focus::is_focusable; +#[cfg(feature = "devtools")] +pub(crate) use focus::perform_mouse_focus_default_action; pub(crate) use focus::{ apply_document_focus_fixup, contenteditable_editing_host, dispatch_system_focus_change, focus_element, focus_element_preserving_selection, focus_window_document, @@ -353,8 +352,6 @@ pub(crate) use focus::{ }; pub(super) use focus::{node_blur_callback, node_focus_callback}; #[cfg(feature = "devtools")] -pub(crate) use focus::perform_mouse_focus_default_action; -#[cfg(feature = "devtools")] pub(crate) use forms::cache_input_files_from_selected_files; #[cfg(feature = "devtools")] pub(crate) use forms::perform_implicit_submission_from_control; @@ -468,11 +465,7 @@ pub(crate) use forms::{ text_control_value, text_control_value_dom_string, }; pub(crate) use forms::{form_control_is_effectively_disabled, input_files_for_object}; -#[cfg(feature = "molio")] pub(crate) use forms::{ - is_text_control_user_editable, replace_text_control_selection_after_beforeinput, -}; -pub(in crate::native_bridge) use forms::{ is_text_control_user_editable, replace_text_control_selection_with_input_event, }; #[cfg(feature = "devtools")] @@ -489,7 +482,6 @@ pub(super) use html_streaming::{ }; use rendered_state::{node_check_visibility_callback, node_current_css_zoom_getter_function}; -use form_controls::SvgAElementRelListPrototypeDeclaration; pub use geometry::ClientRect; #[cfg(feature = "devtools")] pub(crate) use geometry::observable_input_hit_test; @@ -1755,12 +1747,12 @@ pub(crate) fn install_element_template_bindings<'s>( "HTMLOListElement" => install!(HtmlOListElementPrototypeDeclaration), "HTMLUListElement" => install!(HtmlUListElementPrototypeDeclaration), "HTMLBodyElement" => install!( - HtmlBodyOrFrameSetEventHandlersPrototypeDeclaration, + HtmlBodyWindowEventHandlersDeclaration, HtmlBodyElementLegacyPrototypeDeclaration, ), "HTMLFrameSetElement" => { install!( - HtmlBodyOrFrameSetEventHandlersPrototypeDeclaration, + HtmlFrameSetWindowEventHandlersDeclaration, HtmlFrameSetElementLegacyPrototypeDeclaration, ); } @@ -2345,6 +2337,39 @@ fn aria_element_reference_attribute_setter_callback<'s>( rv.set_undefined(); } +pub(in crate::native_bridge::element) fn reflected_element_attribute_handle( + runtime: &PageScriptHost, + owner: DomHandle, + attribute: &str, +) -> Option { + let candidate = match runtime + .dom_host() + .explicit_element_references(owner, attribute) + { + Some(references) => references.into_iter().next()?, + None => { + let id = runtime.dom_host().get_attribute(owner, attribute)?; + aria_element_by_id_including_disconnected(runtime, owner, &id)? + } + }; + if !aria_element_reference_is_in_valid_scope(runtime, owner, candidate) { + return None; + } + runtime + .dom_host() + .resolve_reference_target_chain(candidate) + .map(|_| candidate) +} + +pub(in crate::native_bridge::element) fn resolved_reflected_element_attribute_handle( + runtime: &PageScriptHost, + owner: DomHandle, + attribute: &str, +) -> Option { + reflected_element_attribute_handle(runtime, owner, attribute) + .and_then(|candidate| runtime.dom_host().resolve_reference_target_chain(candidate)) +} + #[cfg(feature = "devtools")] pub(crate) use geometry::read_client_rects; diff --git a/moli-renderer-v8/src/native_bridge/element/event_handlers/generic.rs b/moli-renderer-v8/src/native_bridge/element/event_handlers/generic.rs index 7272c80f077..a5b6502d31a 100644 --- a/moli-renderer-v8/src/native_bridge/element/event_handlers/generic.rs +++ b/moli-renderer-v8/src/native_bridge/element/event_handlers/generic.rs @@ -1,22 +1,17 @@ use crate::{ - context_bootstrap::is_window_event_handler_property, + context_bootstrap::WINDOW_EVENT_HANDLER_PROPERTIES, document_runtime::EventTargetHandle, native_bridge::OwnerDispatchScope, - util::{ - context_host_ptr_from_global_bridge, get_private_value, node_wrapper_from_handle, - set_private_value, throw_type_error, v8_string, v8str, - }, + util::{node_wrapper_from_handle, throw_type_error, v8_string, v8str}, }; use super::super::super::node::{ node_is_document, node_is_element, reference::NativeNodeReference, }; use super::super::forms::form_associated_form_owner; -use super::super::{element_attribute, queue_text_track_load_if_needed}; +use super::super::queue_text_track_load_if_needed; use super::shared::compile_event_attribute_handler; -const EVENT_HANDLER_SLOT_PREFIX: &str = "__moliEventHandler_"; - pub(crate) const GENERIC_EVENT_HANDLER_PROPERTIES: &[&str] = &[ "onclick", "onauxclick", @@ -147,19 +142,16 @@ const ELEMENT_SPECIFIC_EVENT_HANDLER_PROPERTIES: &[&str] = &[ pub(in crate::native_bridge::element) fn is_element_event_handler_content_attribute_name( name: &str, ) -> bool { - GENERIC_EVENT_HANDLER_PROPERTIES.contains(&name) - || is_window_event_handler_property(name) - || ELEMENT_FULLSCREEN_EVENT_HANDLER_PROPERTIES.contains(&name) - || ELEMENT_SPECIFIC_EVENT_HANDLER_PROPERTIES.contains(&name) + event_handler_content_attribute_names().any(|candidate| candidate == name) } pub(crate) fn event_handler_content_attribute_names() -> impl Iterator { GENERIC_EVENT_HANDLER_PROPERTIES .iter() + .chain(WINDOW_EVENT_HANDLER_PROPERTIES) .chain(ELEMENT_FULLSCREEN_EVENT_HANDLER_PROPERTIES) .chain(ELEMENT_SPECIFIC_EVENT_HANDLER_PROPERTIES) .copied() - .chain(crate::context_bootstrap::window_event_handler_properties()) .chain(["onmessageerror"]) } @@ -198,7 +190,9 @@ pub(crate) fn element_event_handler_content_attribute_applies( || ELEMENT_FULLSCREEN_EVENT_HANDLER_PROPERTIES.contains(&name) || interface_specific || ((node.is_html_element_named("body") || node.is_html_element_named("frameset")) - && super::is_body_window_event_handler_attribute(name)) + && name + .strip_prefix("on") + .is_some_and(super::body_or_frameset_reflects_window_event_type)) } #[derive(Clone, Copy)] @@ -317,7 +311,7 @@ fn set_event_handler_property_for_target<'s>( let Some(event_type) = event_handler_event_type(&handler_name) else { return; }; - let handler = v8::Local::::try_from(value).ok(); + let handler = v8::Local::::try_from(value).ok(); unsafe { &mut *runtime_ptr } .set_registered_event_handler_property(scope, target, event_type, handler); } @@ -439,34 +433,44 @@ pub(crate) fn node_event_handler_getter_function<'s>( handle_invalid_event_handler_receiver(scope, &mut rv, &handler_name); return; } - let target = unsafe { &*runtime_ptr }.event_handler_attribute_target(handle, &handler_name); if let Some(event_type) = event_handler_event_type(&handler_name) - && let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) - && let Some(current) = - unsafe { &*host_ptr }.registered_event_handler_property_value(scope, target, event_type) + && let Some(current) = unsafe { &*runtime_ptr }.registered_event_handler_property_value( + scope, + EventTargetHandle::Node(handle), + event_type, + ) { rv.set(current); return; } - if target != EventTargetHandle::Window - && let Some(current) = node_event_handler_value_from_wrapper(scope, object, &handler_name) + if !handler_name.starts_with("on") + || !element_event_handler_content_attribute_applies( + unsafe { &*runtime_ptr }.dom_host(), + handle, + &handler_name, + ) { - rv.set(current); - return; - } - if !handler_name.starts_with("on") { rv.set_null(); return; } - let Some(source) = element_attribute(unsafe { &*runtime_ptr }, handle, &handler_name) else { + let handler = event_handler_event_type(&handler_name) + .and_then(|event_type| { + unsafe { &*runtime_ptr }.uncompiled_event_handler_content_attribute( + EventTargetHandle::Node(handle), + event_type, + ) + }) + .or_else(|| { + crate::host::UncompiledEventHandler::from_attribute( + unsafe { &*runtime_ptr }.dom_host(), + handle, + event_handler_event_type(&handler_name)?, + ) + }); + let Some(handler) = handler else { rv.set(v8::null(scope).into()); return; }; - if source.is_empty() { - rv.set(v8::null(scope).into()); - return; - } - let Some((target_context, owner)) = node_event_handler_target_context(scope, runtime_ptr, handle) else { @@ -485,7 +489,7 @@ pub(crate) fn node_event_handler_getter_function<'s>( handle, object, &handler_name, - &source, + &handler, ) .map(|handler| v8::Global::new(target_scope, handler)); owner.restore(target_scope, previous); @@ -520,42 +524,6 @@ fn node_event_handler_target_context<'s>( .map(|context| (context, owner)) } -pub(crate) fn compile_node_content_attribute_for_dispatch<'s>( - scope: &mut v8::PinScope<'s, '_>, - host_ptr: *mut crate::native_bridge::PageScriptHost, - handle: crate::document_runtime::DomHandle, - event_type: &str, -) -> Option> { - let name = event_handler_content_attribute_name(event_type)?; - if !GENERIC_EVENT_HANDLER_PROPERTIES.contains(&name.as_str()) { - return None; - } - let source_node = unsafe { &*host_ptr } - .event_handler_content_attribute_node(EventTargetHandle::Node(handle), event_type)?; - let source = element_attribute(unsafe { &*host_ptr }, source_node, &name)?; - let (context, owner) = node_event_handler_target_context(scope, host_ptr, source_node)?; - let handler = { - let target_scope = &mut v8::ContextScope::new(scope, context); - let previous = owner.enter(target_scope); - let handler = node_wrapper_from_handle(target_scope, source_node) - .and_then(|object| { - compile_node_event_attribute_handler( - target_scope, - host_ptr, - owner, - source_node, - object, - &name, - &source, - ) - }) - .map(|handler| v8::Global::new(target_scope, handler)); - owner.restore(target_scope, previous); - handler - }?; - Some(v8::Local::new(scope, &handler)) -} - fn compile_node_event_attribute_handler<'s>( scope: &mut v8::PinScope<'s, '_>, runtime_ptr: *mut crate::native_bridge::PageScriptHost, @@ -563,8 +531,21 @@ fn compile_node_event_attribute_handler<'s>( handle: crate::document_runtime::DomHandle, object: v8::Local<'s, v8::Object>, handler_name: &str, - source: &str, + handler: &crate::host::UncompiledEventHandler, ) -> Option> { + let target = EventTargetHandle::Node(handle); + let event_type = event_handler_event_type(handler_name)?; + let target_context = scope.get_current_context(); + // A parse error reports to author code. Re-entrant getters must see null + // without removing the listener's position, and any changes made while + // reporting the error must survive this compilation attempt. + unsafe { &mut *runtime_ptr }.set_registered_content_attribute_event_handler_property( + scope, + target, + event_type, + None, + target_context, + ); let event_argument = v8_string(scope, "event")?; let mut context_extensions = Vec::with_capacity(4); let window = match owner { @@ -591,23 +572,11 @@ fn compile_node_event_attribute_handler<'s>( } context_extensions.push(object); - let target = unsafe { &*runtime_ptr }.event_handler_attribute_target(handle, handler_name); - let target_context = scope.get_current_context(); - let event_type = event_handler_event_type(handler_name)?; - // A syntax error can invoke script which reads or changes the handler. - // Set its in-progress value before compilation so a nested getter sees null. - unsafe { &mut *runtime_ptr }.set_registered_content_attribute_event_handler_property( - scope, - target, - event_type, - None, - target_context, - ); let handler = compile_event_attribute_handler( scope, runtime_ptr, handle, - source, + handler, &[event_argument], &context_extensions, )?; @@ -649,27 +618,14 @@ pub(crate) fn node_event_handler_setter_function<'s>( handle_invalid_event_handler_receiver(scope, &mut rv, &handler_name); return; } - let target = unsafe { &*runtime_ptr }.event_handler_attribute_target(handle, &handler_name); - if target != EventTargetHandle::Window { - let stored = if value.is_function() { - value - } else { - v8::null(scope).into() - }; - let backing = moli_webapi_declare::web_api_object_target(scope, object).unwrap_or(object); - set_private_value( - scope, - backing, - &event_handler_slot_name(&handler_name), - stored, - ); - } if let Some(event_type) = event_handler_event_type(&handler_name) { - let handler = v8::Local::::try_from(value).ok(); - if let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) { - unsafe { &mut *host_ptr } - .set_registered_event_handler_property(scope, target, event_type, handler); - } + let handler = v8::Local::::try_from(value).ok(); + unsafe { &mut *runtime_ptr }.set_registered_event_handler_property( + scope, + EventTargetHandle::Node(handle), + event_type, + handler, + ); } if matches!(handler_name.as_str(), "onload" | "onerror") && unsafe { &*runtime_ptr } @@ -690,38 +646,13 @@ fn event_handler_name_from_data<'s>( .map(|name| name.to_rust_string_lossy(scope)) } -fn event_handler_slot_name(name: &str) -> String { - format!("{EVENT_HANDLER_SLOT_PREFIX}{name}") -} - -/// An adopted node keeps its original wrapper and callback realm. Read its -/// native handler slot without evaluating an author-defined property getter. -pub(crate) fn node_event_handler_value_from_wrapper<'s>( - scope: &mut v8::PinScope<'s, '_>, - object: v8::Local<'s, v8::Object>, - name: &str, -) -> Option> { - let backing = moli_webapi_declare::web_api_object_target(scope, object).unwrap_or(object); - get_private_value(scope, backing, &event_handler_slot_name(name)) - .filter(|value| !value.is_undefined()) -} - -pub(crate) fn is_global_event_handler_attribute(name: &str) -> bool { - GENERIC_EVENT_HANDLER_PROPERTIES.contains(&name) -} - fn event_handler_event_type(name: &str) -> Option<&str> { name.strip_prefix("on") .filter(|event_type| !event_type.is_empty()) - .map(|event_type| match event_type { - "begin" => "beginEvent", - "end" => "endEvent", - "repeat" => "repeatEvent", - event_type => event_type, - }) + .map(canonical_event_handler_event_type) } -fn legacy_lenient_this_event_handler(name: &str) -> bool { +pub(crate) fn legacy_lenient_this_event_handler(name: &str) -> bool { matches!(name, "onmouseenter" | "onmouseleave" | "onreadystatechange") } @@ -737,47 +668,69 @@ fn handle_invalid_event_handler_receiver<'s>( } } -pub(super) fn invalidate_event_attribute_handler( - scope: &mut v8::PinScope<'_, '_>, - runtime: &mut super::super::super::PageScriptHost, - handle: crate::document_runtime::DomHandle, - name: &str, -) { - let normalized_name = name.to_ascii_lowercase(); - let Some(event_type) = event_handler_event_type(&normalized_name) else { - return; - }; - let target = runtime.event_handler_attribute_target(handle, &normalized_name); - if let Some(callback) = runtime.clear_event_handler_property(target, event_type) { - runtime.release_event_callback(callback); +pub(crate) fn canonical_event_handler_event_type(event_type: &str) -> &str { + match event_type { + "begin" => "beginEvent", + "end" => "endEvent", + "repeat" => "repeatEvent", + "webkitanimationend" => "webkitAnimationEnd", + "webkitanimationiteration" => "webkitAnimationIteration", + "webkitanimationstart" => "webkitAnimationStart", + "webkittransitionend" => "webkitTransitionEnd", + event_type => event_type, } - if target == EventTargetHandle::Window { - return; - } - crate::util::with_cached_node_wrapper_realm(scope, runtime, handle, |scope, wrapper| { - let object = crate::util::get_private_object( - scope, - wrapper, - crate::dom_parser::DOM_PARSER_FOREIGN_NODE_SLOT, - ) - .unwrap_or(wrapper); - let backing = moli_webapi_declare::web_api_object_target(scope, object).unwrap_or(object); - set_private_value( - scope, - backing, - &event_handler_slot_name(&normalized_name), - v8::undefined(scope).into(), - ); - }); } pub(crate) fn event_handler_content_attribute_name(event_type: &str) -> Option { let event_type = match event_type { + // The SVG handlers observe the *Event types, not events named after + // their attributes. Do not invoke onbegin for dispatchEvent("begin"). "begin" | "end" | "repeat" => return None, "beginEvent" => "begin", "endEvent" => "end", "repeatEvent" => "repeat", + "webkitAnimationEnd" => "webkitanimationend", + "webkitAnimationIteration" => "webkitanimationiteration", + "webkitAnimationStart" => "webkitanimationstart", + "webkitTransitionEnd" => "webkittransitionend", event_type => event_type, }; Some(format!("on{event_type}")) } + +pub(crate) fn compile_node_content_attribute_for_dispatch<'s>( + scope: &mut v8::PinScope<'s, '_>, + host_ptr: *mut crate::native_bridge::PageScriptHost, + handle: crate::document_runtime::DomHandle, + event_type: &str, +) -> Option> { + let name = event_handler_content_attribute_name(event_type)?; + if !element_event_handler_content_attribute_applies( + unsafe { &*host_ptr }.dom_host(), + handle, + &name, + ) { + return None; + } + let handler = unsafe { &*host_ptr } + .uncompiled_event_handler_content_attribute(EventTargetHandle::Node(handle), event_type)?; + let (context, dispatch_scope) = node_event_handler_target_context(scope, host_ptr, handle)?; + let handler = { + let scope = &mut v8::ContextScope::new(scope, context); + let object = node_wrapper_from_handle(scope, handle)?; + let previous = dispatch_scope.enter(scope); + let compiled = compile_node_event_attribute_handler( + scope, + host_ptr, + dispatch_scope, + handle, + object, + &name, + &handler, + ) + .map(|handler| v8::Global::new(scope, handler)); + dispatch_scope.restore(scope, previous); + compiled + }?; + Some(v8::Local::new(scope, &handler)) +} diff --git a/moli-renderer-v8/src/native_bridge/element/event_handlers/mod.rs b/moli-renderer-v8/src/native_bridge/element/event_handlers/mod.rs index 96ea754ee63..a828c1f0a78 100644 --- a/moli-renderer-v8/src/native_bridge/element/event_handlers/mod.rs +++ b/moli-renderer-v8/src/native_bridge/element/event_handlers/mod.rs @@ -1,58 +1,27 @@ -mod body_onload; mod body_window; mod generic; mod parser; mod shared; -pub(crate) use body_onload::compile_window_body_event_attribute; -pub(crate) use body_onload::initialize_parser_inserted_body_window_event_handlers; -pub(super) use body_onload::{ - body_onerror_getter_function, body_onerror_setter_function, body_onload_getter_function, - body_onload_setter_function, -}; -pub(crate) use body_window::compile_window_body_onmessageerror_attribute; pub(super) use body_window::{ - body_onmessageerror_getter_function, body_onmessageerror_setter_function, + HtmlBodyWindowEventHandlersDeclaration, HtmlFrameSetWindowEventHandlersDeclaration, +}; +pub(crate) use body_window::{ + body_or_frameset_reflects_window_event_type, compile_body_window_event_attribute, + compile_window_event_attribute_handler, resolve_window_event_handler_content_attribute, }; pub(super) use generic::ELEMENT_FULLSCREEN_EVENT_HANDLER_PROPERTIES; -pub(super) use generic::install_node_event_handler_template_bindings; pub(super) use generic::is_element_event_handler_content_attribute_name; pub(crate) use generic::{ - GlobalEventHandlerOwner, compile_node_content_attribute_for_dispatch, - element_event_handler_content_attribute_applies, event_handler_content_attribute_name, event_handler_content_attribute_names, install_global_event_handler_template_bindings, - is_global_event_handler_attribute, node_event_handler_getter_function, - node_event_handler_setter_function, node_event_handler_value_from_wrapper, + GlobalEventHandlerOwner, canonical_event_handler_event_type, + compile_node_content_attribute_for_dispatch, element_event_handler_content_attribute_applies, + event_handler_content_attribute_name, event_handler_content_attribute_names, + install_global_event_handler_template_bindings, install_node_event_handler_template_bindings, + legacy_lenient_this_event_handler, node_event_handler_getter_function, + node_event_handler_setter_function, shadow_root_event_handler_getter_function, + shadow_root_event_handler_setter_function, }; pub(crate) use parser::{ParserAddedEventHandlers, initialize_parser_inserted_event_handlers}; -pub(crate) use shared::{EventAttributeHandlerScope, compile_event_attribute_handler_for_owner}; - -pub(crate) fn is_body_window_event_handler_attribute(name: &str) -> bool { - matches!( - name, - "onafterprint" - | "onbeforeprint" - | "onbeforeunload" - | "onblur" - | "onerror" - | "onfocus" - | "onhashchange" - | "onlanguagechange" - | "onload" - | "onmessage" - | "onmessageerror" - | "onoffline" - | "ononline" - | "onpagehide" - | "onpageshow" - | "onpopstate" - | "onrejectionhandled" - | "onresize" - | "onscroll" - | "onstorage" - | "onunhandledrejection" - | "onunload" - ) -} fn is_body_or_frameset_element( runtime: &super::super::PageScriptHost, @@ -63,13 +32,12 @@ fn is_body_or_frameset_element( }) } -pub(crate) fn invalidate_event_handler_content_attribute( - scope: &mut v8::PinScope<'_, '_>, - runtime_ptr: *mut super::super::PageScriptHost, +pub(super) fn body_or_frameset_window_owner( + runtime: &super::super::PageScriptHost, handle: crate::document_runtime::DomHandle, - name: &str, -) { - let runtime = unsafe { &mut *runtime_ptr }; - generic::invalidate_event_attribute_handler(scope, runtime, handle, name); - body_onload::invalidate_body_window_event_attribute_handler(scope, runtime, handle, name); +) -> Option { + if !is_body_or_frameset_element(runtime, handle) { + return None; + } + runtime.owner_dispatch_scope_for_node(handle) } diff --git a/moli-renderer-v8/src/native_bridge/element/events.rs b/moli-renderer-v8/src/native_bridge/element/events.rs index 7ed3e8f3aa9..c5be7e260fc 100644 --- a/moli-renderer-v8/src/native_bridge/element/events.rs +++ b/moli-renderer-v8/src/native_bridge/element/events.rs @@ -13,17 +13,21 @@ pub(crate) use self::constructors::{ }; #[cfg(any(feature = "devtools", test))] pub(crate) use self::constructors::{TouchEventPoint, construct_touch_event_with_points}; -#[cfg(any(test, feature = "devtools"))] -pub(crate) use self::constructors::{construct_drag_event_with_related_target, construct_pointer_event}; #[cfg(feature = "devtools")] pub(crate) use self::constructors::{ construct_activation_pointer_event, construct_drop_input_event, construct_mouse_event_for_target, construct_mouse_event_with_detail_for_target, - construct_mouse_event_with_related_target_for_target, - construct_text_input_event_for_target, construct_wheel_event_for_target, + construct_mouse_event_with_related_target_for_target, construct_text_input_event_for_target, + construct_wheel_event_for_target, +}; +#[cfg(any(test, feature = "devtools"))] +pub(crate) use self::constructors::{ + construct_drag_event_with_related_target, construct_pointer_event, }; #[cfg(test)] -pub(crate) use self::constructors::{construct_mouse_event_with_detail_and_modifiers, construct_wheel_event}; +pub(crate) use self::constructors::{ + construct_mouse_event_with_detail_and_modifiers, construct_wheel_event, +}; pub(crate) use self::dispatch::{ NodePublicEventDispatchOutcome, dispatch_beforeinput, dispatch_public_event, }; diff --git a/moli-renderer-v8/src/native_bridge/element/events/constructors.rs b/moli-renderer-v8/src/native_bridge/element/events/constructors.rs index 23cd5f94efd..4b4f0954c0f 100644 --- a/moli-renderer-v8/src/native_bridge/element/events/constructors.rs +++ b/moli-renderer-v8/src/native_bridge/element/events/constructors.rs @@ -1,3 +1,5 @@ +pub(crate) use moli_webapi::events::subclasses::construct_native_clipboard_event as construct_clipboard_event; +pub(super) use moli_webapi::events::subclasses::construct_native_input_event as construct_editing_input_event; #[cfg(any(test, feature = "devtools"))] use moli_webapi::events::subclasses::construct_native_keyboard_event; pub(crate) use moli_webapi::events::subclasses::{ @@ -6,8 +8,6 @@ pub(crate) use moli_webapi::events::subclasses::{ construct_native_interest_event as construct_interest_event, construct_native_toggle_event as construct_toggle_event, }; -pub(crate) use moli_webapi::events::subclasses::construct_native_clipboard_event as construct_clipboard_event; -pub(super) use moli_webapi::events::subclasses::construct_native_input_event as construct_editing_input_event; use moli_webapi::events::subclasses::{ construct_native_focus_event, construct_native_submit_event, }; @@ -17,10 +17,9 @@ mod devtools; pub(crate) use devtools::{construct_drag_event_with_related_target, construct_pointer_event}; #[cfg(feature = "devtools")] pub(crate) use devtools::{ - construct_drop_input_event, - construct_mouse_event_for_target, construct_mouse_event_with_detail_for_target, - construct_mouse_event_with_related_target_for_target, - construct_wheel_event_for_target, + construct_drop_input_event, construct_mouse_event_for_target, + construct_mouse_event_with_detail_for_target, + construct_mouse_event_with_related_target_for_target, construct_wheel_event_for_target, }; #[cfg(test)] pub(crate) use devtools::{construct_mouse_event_with_detail_and_modifiers, construct_wheel_event}; diff --git a/moli-renderer-v8/src/native_bridge/element/geometry/hit_test.rs b/moli-renderer-v8/src/native_bridge/element/geometry/hit_test.rs index 76758a62dba..c12fb904b84 100644 --- a/moli-renderer-v8/src/native_bridge/element/geometry/hit_test.rs +++ b/moli-renderer-v8/src/native_bridge/element/geometry/hit_test.rs @@ -54,7 +54,14 @@ pub(crate) fn observable_input_hit_test( document: DomHandle, point: LayoutPoint, ) -> Result, LayoutError> { - Ok(input_surface_hit_test(runtime, document, point, InputHitTestPolicy::INTERACTIVE, InputHitTestMode::Dom)?.target) + Ok(input_surface_hit_test( + runtime, + document, + point, + InputHitTestPolicy::INTERACTIVE, + InputHitTestMode::Dom, + )? + .target) } /// Hit tests within an already routed frame. The mouse press can keep that @@ -128,7 +135,10 @@ pub(crate) fn input_surface_hit_test( }, ); let is_document = target.is_some_and(|target| { - runtime.dom_host().node(target).is_some_and(|node| node.is_document()) + runtime + .dom_host() + .node(target) + .is_some_and(|node| node.is_document()) }); return Ok(InputSurfaceHit { target: target.filter(|_| !is_document), @@ -159,7 +169,10 @@ pub(crate) fn observable_deep_hit_test( point: LayoutPoint, policy: InputHitTestPolicy, ) -> Result, LayoutError> { - Ok(input_surface_hit_test(runtime, document, point, policy, InputHitTestMode::Dom)?.document_or_element()) + Ok( + input_surface_hit_test(runtime, document, point, policy, InputHitTestMode::Dom)? + .document_or_element(), + ) } fn input_surface_hit_test_in_tree( diff --git a/moli-renderer-v8/src/native_bridge/element/styles/methods.rs b/moli-renderer-v8/src/native_bridge/element/styles/methods.rs index dc475944490..82a82e8598e 100644 --- a/moli-renderer-v8/src/native_bridge/element/styles/methods.rs +++ b/moli-renderer-v8/src/native_bridge/element/styles/methods.rs @@ -1,5 +1,7 @@ use style::properties::{LonghandId, PropertyId}; +use super::style_object_computation_context; + use crate::{ css_style::{ CssStyleDeclarationItemArgs, CssStyleDeclarationPropertyArgs, diff --git a/moli-renderer-v8/src/native_bridge/element/trusted_types.rs b/moli-renderer-v8/src/native_bridge/element/trusted_types.rs index b8a028b83a5..2fa81289cf7 100644 --- a/moli-renderer-v8/src/native_bridge/element/trusted_types.rs +++ b/moli-renderer-v8/src/native_bridge/element/trusted_types.rs @@ -7,6 +7,7 @@ pub(in crate::native_bridge) enum TrustedAttributeSetter { SetAttributeNs, SetAttributeNode, AttrValue, + SvgAnimatedStringBaseVal, } impl TrustedAttributeSetter { @@ -16,6 +17,7 @@ impl TrustedAttributeSetter { Self::SetAttributeNs => "setAttributeNS", Self::SetAttributeNode => "setAttributeNode", Self::AttrValue => "value", + Self::SvgAnimatedStringBaseVal => "baseVal", } } @@ -27,6 +29,9 @@ impl TrustedAttributeSetter { crate::webidl::Context::argument("Element setAttributeNode", 1) } Self::AttrValue => crate::webidl::Context::member("Attr", "value"), + Self::SvgAnimatedStringBaseVal => { + crate::webidl::Context::member("SVGAnimatedString", "baseVal") + } } } } @@ -466,4 +471,3 @@ pub(crate) fn prepare_trusted_script_text( .set_script_text_internal_slot(handle, &source); Some(source) } - diff --git a/moli-renderer-v8/src/native_bridge/mod.rs b/moli-renderer-v8/src/native_bridge/mod.rs index ebd8fef665f..ff5a45c0ece 100644 --- a/moli-renderer-v8/src/native_bridge/mod.rs +++ b/moli-renderer-v8/src/native_bridge/mod.rs @@ -8,9 +8,11 @@ mod collections; mod context_host; mod current_input; pub(crate) use context_host::{ - ChildDocumentFetch, DecodedImageContent, DocumentDomainState, InputImageRequestId, LayoutPublicationRequest, NavigationImageDocumentCompletion, NavigationImageDocumentLoad, PageScriptHost, PageScriptHostTaskCapabilities, - PendingScrollObservableEffects, PostParseAutofocusAdmission, SelectionBoundarySnapshot, ServiceWorkerWindowOwner, - SharedResourceTimingBufferRegistry, WindowAccessOrigin, WindowOriginKey, caller_can_access_window, + ChildDocumentFetch, DecodedImageContent, DocumentDomainState, InputImageRequestId, + LayoutPublicationRequest, NavigationImageDocumentCompletion, NavigationImageDocumentLoad, + PageScriptHost, PageScriptHostTaskCapabilities, PendingScrollObservableEffects, + PostParseAutofocusAdmission, SelectionBoundarySnapshot, ServiceWorkerWindowOwner, + SharedResourceTimingBufferRegistry, WindowAccessOrigin, WindowOriginKey, }; #[cfg(feature = "devtools")] pub(crate) use context_host::{ @@ -98,7 +100,6 @@ pub(crate) use element::{ compute_mock_intersection_client_rect, compute_mock_intersection_scrollport_client_rect, }; pub(super) use helpers::*; -pub(crate) use node::NativeNodeReference; pub(crate) use node::branded_node_handle; pub(crate) use node::{ current_or_live_delegate_node_arg_handle, node_or_foreign_arg_handle_allow_detached, diff --git a/moli-renderer-v8/src/runtime/page_vm/mod.rs b/moli-renderer-v8/src/runtime/page_vm/mod.rs index 98d6fda4a36..0064ec23e94 100644 --- a/moli-renderer-v8/src/runtime/page_vm/mod.rs +++ b/moli-renderer-v8/src/runtime/page_vm/mod.rs @@ -4826,7 +4826,7 @@ impl PageVm { }, ) .into_violations(); - if enforced_violation.is_some() { + if !enforced_violation.is_empty() { return ScannedStylesheetAdmission::DeferredToParser( ScannedStylesheetDeferral::ContentSecurityPolicy, ); @@ -4886,7 +4886,7 @@ impl PageVm { crate::document_runtime::DocumentSubresourceCspKind::Image, ) .into_violations(); - if enforced_violation.is_some() { + if !enforced_violation.is_empty() { return ScannedImageAdmission::DeferredToParser( ScannedImageDeferral::ContentSecurityPolicy, ); diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/print.rs b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/print.rs index 7c9f16d175d..5c8deaf5a7e 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/print.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/print.rs @@ -108,14 +108,13 @@ async fn native_pdf_embeds_a_loaded_font_under_its_print_declaration() { "../../../../../../moli-layout/tests/fixtures/moli-ahem.woff2" )); for policy in [LayoutPolicy::OnDemand, LayoutPolicy::Realtime] { - let mut page = test_page_vm_with_loader_and_document_url( + let (mut page, _, _) = page_vm_with_bound_task_sources_and_owner_wake( &loader, - Vec::new(), Url::parse("https://cached-print-sources.test/")?, ); page.layout_configuration.policy = policy; page.vm_mut().set_layout_policy(policy); - let loaded = page.vm_mut().eval(&format!(r#" + page.vm_mut().eval(&format!(r#" document.head.innerHTML = '