Truly independent web browser
LibWeb+WebContent: Reset pointer input between test-web tests
sideshowbarkerf9512dd5a5bf
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex a149d969705..5e3c091680e 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -2499,7 +2499,7 @@ void Internals::perform_per_test_cleanup()// Clear any input stateif (auto local_root = local_root_of(window())) {- local_root->event_handler().clear_per_test_input_state({});+ local_root->event_handler().clear_per_test_input_state();WebDriver::reset_input_state(*local_root->top_level_traversable());}if (auto* compositor_context = compositor_context_routing_input_for(window()))diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cppindex 1d43d6f6269..e61ffe90f21 100644--- a/Libraries/LibWeb/Page/EventHandler.cpp+++ b/Libraries/LibWeb/Page/EventHandler.cpp@@ -6067,15 +6067,17 @@ void EventHandler::release_held_scroll_key()m_scroll_key_gesture_hold = nullptr;}-void EventHandler::clear_per_test_input_state(Badge<Internals::Internals>)+void EventHandler::clear_per_test_input_state(){clear_mousedown_tracking();stop_updating_selection();release_held_scroll_key();stop_middle_button_scroll();- m_mouse_pointer.prevent_mouse_event = false;+ m_mouse_pointer = {};m_additional_pointers.clear();+ m_last_mousedown_target = nullptr;+ m_nested_navigable_under_pointer = nullptr;m_captured_chrome_widget = nullptr;m_effective_legacy_mouse_pointer_position = nullptr;m_effective_legacy_mouse_pointer_type = PointerType::Mouse;@@ -6084,14 +6086,25 @@ void EventHandler::clear_per_test_input_state(Badge<Internals::Internals>)m_mousemove_previous_screen_position.clear();m_visual_animation_sample_time_nanoseconds.clear();m_last_known_mouse_visual_viewport_position.clear();- m_hover_may_be_stale = false;- // The lanes carry the pointer over to the next document, which the host then hovers where it rests.+ m_last_known_mouse_screen_position = {};+ m_last_known_mouse_buttons = 0;+ m_last_known_mouse_modifiers = 0;if (auto document = m_navigable->active_document()) {if (auto* arena = document->layout_node_arena_if_created())Layout::RustFFI::document_host_forget_pointer_for_testing(arena->host());}+ m_hover_may_be_stale = false;m_wheel_event_target_latch.clear();m_navigable->page().clear_context_menu_request();}+void EventHandler::clear_hover_for_next_test()+{+ // A test's screenshot can still show its hover after the test is done, so only the reset before the next test+ // clears it. That reset isn't pointer motion, so it dispatches no boundary events.+ if (auto document = m_navigable->active_document())+ document->dispatch_boundary_events(nullptr, nullptr, {}, DOM::Document::BoundaryEventTypes::All);+ report_hovered_node_to_client(nullptr);+}+}diff --git a/Libraries/LibWeb/Page/EventHandler.h b/Libraries/LibWeb/Page/EventHandler.hindex 2f2c9ffd674..3e135220a5c 100644--- a/Libraries/LibWeb/Page/EventHandler.h+++ b/Libraries/LibWeb/Page/EventHandler.h@@ -174,7 +174,8 @@ public:// For a held key whose release will not reach the page, as when the window loses focus.void release_held_scroll_key();- void clear_per_test_input_state(Badge<Internals::Internals>);+ void clear_per_test_input_state();+ void clear_hover_for_next_test();private:bool should_ignore_device_input_event() const;diff --git a/Libraries/LibWeb/Rust/src/render_state/clock.rs b/Libraries/LibWeb/Rust/src/render_state/clock.rsindex 87362f78f97..c86cafe94a2 100644--- a/Libraries/LibWeb/Rust/src/render_state/clock.rs+++ b/Libraries/LibWeb/Rust/src/render_state/clock.rs@@ -1928,7 +1928,13 @@ pub extern "C" fn document_host_take_clock_lanes_in(host: &DocumentHost, update:/// move before one of its own. For a test, whose documents follow each other with the pointer where the last left it.#[unsafe(no_mangle)]pub extern "C" fn document_host_forget_pointer_for_testing(host: &DocumentHost) {- host.clock_ticks().pointer_state().forget();+ let ticks = Arc::clone(host.clock_ticks());+ // Wait for a tick already running before discarding its report and the pointer it could hover again.+ super::on_render_side(0, move || {+ ticks.pointer_state().forget();+ let _ = take_lane_report(&ticks);+ });+ host.clear_lane_hover_for_testing();}/// Takes in what the lanes of `host`'s document did, as a task between two rendering updates handles a press, anddiff --git a/Libraries/LibWeb/Rust/src/render_state/document_host.rs b/Libraries/LibWeb/Rust/src/render_state/document_host.rsindex 44bb0635029..fa2f134f9e4 100644--- a/Libraries/LibWeb/Rust/src/render_state/document_host.rs+++ b/Libraries/LibWeb/Rust/src/render_state/document_host.rs@@ -577,6 +577,12 @@ impl DocumentHost {moves}+ pub(super) fn clear_lane_hover_for_testing(&self) {+ self.hover_events_owed.set(None);+ self.lane_move.set(None);+ self.lane_transitions.borrow_mut().clear();+ }+/// The element the lanes' hover put the hover on at the pointer move with the input event id `input_event_id`, or/// nothing, where a tick of theirs took that move and hovered it, as the last rendering update took them in.pub(super) fn lane_hover_target_for(&self, input_event_id: u64) -> Option<Option<StyleNodeID>> {@@ -1750,6 +1756,43 @@ mod tests {host.changes.stop_holding_style();}+ #[test]+ fn test_reset_forgets_hover_already_owed_to_the_host() {+ use super::super::clock::{LaneMove, LaneReport, PendingPointer, document_host_forget_pointer_for_testing};++ let host = TestHost::new();+ let host = host.host();+ let [target] = style_nodes(host);+ let _ = host.ticks.pointer_moved(PendingPointer {+ position: Some(FloatPoint { x: 50.0, y: 50.0 }),+ buttons: 0,+ scrolled_since_frame: false,+ input_event_id: 1,+ });+ host.keep_what_lanes_did(+ Some(LaneReport {+ last_move: Some(LaneMove {+ input_event_id: 1,+ target: Some(Some(target)),+ handed: false,+ }),+ ..Default::default()+ }),+ 0,+ );+ assert!(host.hover_events_owed.get().is_some());+ assert!(host.lane_hover_target_for(1).is_some());++ document_host_forget_pointer_for_testing(host);++ assert!(host.take_hover_events_owed().is_none());+ assert!(host.lane_hover_target_for(1).is_none());+ assert!(host.ticks.newest_pointer().is_none());+ assert!(!host.ticks.pointer_waits());+ host.take_in_what_clock_lanes_did(0);+ assert!(host.take_hover_events_owed().is_none());+ }+#[test]fn the_plan_of_an_earlier_update_leaves_a_later_take_in_standing() {let host = TestHost::new();diff --git a/Services/WebContent/TestConnection.cpp b/Services/WebContent/TestConnection.cppindex 151f3644086..4ad3c0bc3ad 100644--- a/Services/WebContent/TestConnection.cpp+++ b/Services/WebContent/TestConnection.cpp@@ -6,6 +6,8 @@#include <LibWeb/Compositor/RenderClock.h>#include <LibWeb/HTML/LocalTraversableNavigable.h>+#include <LibWeb/Page/EventHandler.h>+#include <LibWeb/WebDriver/InputState.h>#include <WebContent/ConnectionFromClient.h>#include <WebContent/PageClient.h>#include <WebContent/TestConnection.h>@@ -35,6 +37,17 @@ void TestConnection::reset_state_for_testing(Web::PageId page_id)m_client.dispatch_pending_messages();if (auto page = m_client.page(page_id); page.has_value()) {+ // A timed-out test skips its cleanup, and document replacement preserves the stationary pointer.+ for (auto const& navigable : page->page().hosted_navigables()) {+ navigable->event_handler().clear_per_test_input_state();+ navigable->event_handler().clear_hover_for_next_test();+ // The compositor keeps wheel gestures and scroll momentum of its own, and a gesture the previous test left+ // unended would take in the next test's wheel steps.+ if (navigable->has_compositor_context())+ navigable->compositor_context().clear_per_test_input_state_for_testing();+ }+ Web::WebDriver::reset_input_state(*page->page().top_level_traversable());+// A test that times out may never restore automatic rendering in its finally block. Both controls outlive// the document, so restore them at the test boundary before acknowledging the reset.Web::Compositor::RenderClock::the().set_manual_for_testing(false);diff --git a/Tests/LibWeb/test-web/CMakeLists.txt b/Tests/LibWeb/test-web/CMakeLists.txtindex a0fbe2e3b6c..082a6cbe96a 100644--- a/Tests/LibWeb/test-web/CMakeLists.txt+++ b/Tests/LibWeb/test-web/CMakeLists.txt@@ -33,6 +33,8 @@ if (BUILD_TESTING)PYTHON_EXECUTABLE "${LADYBIRD_TEST_PYTHON}" ARGS $<TARGET_FILE:test-web>)ladybird_python_test(test-manual-rendering-reset.pyPYTHON_EXECUTABLE "${LADYBIRD_TEST_PYTHON}" ARGS $<TARGET_FILE:test-web> TIMEOUT 240)+ ladybird_python_test(test-pointer-input-reset.py+ PYTHON_EXECUTABLE "${LADYBIRD_TEST_PYTHON}" ARGS $<TARGET_FILE:test-web> TIMEOUT 240)add_test(NAME LibWebdiff --git a/Tests/LibWeb/test-web/test-pointer-input-reset.py b/Tests/LibWeb/test-web/test-pointer-input-reset.pynew file mode 100755index 00000000000..0aebdd19864--- /dev/null+++ b/Tests/LibWeb/test-web/test-pointer-input-reset.py@@ -0,0 +1,133 @@+#!/usr/bin/env python3+#+# Copyright (c) 2026-present, the Ladybird developers.+#+# SPDX-License-Identifier: BSD-2-Clause++import argparse+import os+import re+import shutil+import subprocess+import sys+import tempfile++from pathlib import Path++ENTRY_EVENTS = "pointerover,mouseover,pointerenter,mouseenter"+++def run_case(binary, source, root, name, timeout):+ root = root / name+ for directory in ("Accessibility", "Layout", "Text", "Ref", "Screenshot"):+ for kind in ("input", "expected"):+ (root / directory / kind).mkdir(parents=True)+ (root / "Crash").mkdir()+ (root / "TestConfig.ini").write_text("")+ for file in ("Fixtures/http-test-server.py", "test-web/results-index.html"):+ (root / file).parent.mkdir()+ shutil.copyfile(source / "Tests/LibWeb" / file, root / file)+ (root / "Text/input/wpt-import").mkdir()+ shutil.copyfile(source / "Tests/LibWeb/Text/input/include.js", root / "Text/input/include.js")+ shutil.copyfile(+ source / "Tests/LibWeb/Text/input/HTML/frame-in-flight/frame-in-flight.js",+ root / "Text/input/frame-in-flight.js",+ )+ target = "<style>html,body{margin:0}#target{width:100px;height:100px;background:green}</style><div id=target></div>"+ if timeout:+ # A test that times out never runs its cleanup, and here the hover lanes still owe the host a hover of their own,+ # with its own pointer position. Only the reset before the next test clears both.+ # The timeout is armed only once the pointer is in, so that a slow setup can't time out before it.+ poison = (+ "await whileLaneHovers(frameTime => {"+ " internals.injectHoverPointer(50, 50, frameTime + 16);"+ ' console.log("POINTER_RESET_INJECTED");'+ " internals.setTestTimeout(500);"+ "});"+ )+ else:+ poison = 'internals.mouseMove(50, 50); println("hovered"); done();'+ (root / "Text/input/poison.html").write_text(+ f'<!doctype html>{target}<script src="include.js"></script><script src="frame-in-flight.js"></script>'+ '<script>asyncTest(async done => {console.log("POINTER_RESET_POISON");'+ f"{poison}}});</script>"+ )+ with (root / "Text/expected/poison.txt").open("w", newline="\n") as file:+ file.write("" if timeout else "hovered\n")+ # Text tests precede reference tests. At -j1 these two files use the same view, without relying on directory order.+ (root / "Ref/input/consumer.html").write_text(+ f'<!doctype html><html class="reftest-wait"><link rel="match" href="../expected/green.html">{target}<script>'+ "const events = [];"+ 'for (const type of ["pointerover", "mouseover", "pointerenter", "mouseenter"])'+ " target.addEventListener(type, event => events.push(event.type));"+ "requestAnimationFrame(() => requestAnimationFrame(() => {"+ ' const hovered = document.querySelector(":hover") ? "yes" : "no";'+ " internals.mouseMove(50, 50);"+ ' console.log(`POINTER_RESET_CONSUMER hovered=${hovered} entry=${events.join(",")}`);'+ " internals.mouseLeave();"+ ' document.documentElement.classList.remove("reftest-wait");'+ "}));"+ "</script></html>"+ )+ (root / "Ref/expected/green.html").write_text(f"<!doctype html>{target}")+ results = root / "results"+ env = os.environ.copy()+ # The echo server imports its vendored tools even though these fixtures use only file URLs. Keep those tools+ # outside the private input tree so test discovery cannot collect their own HTML fixtures.+ wpt = source / "Tests/LibWeb/Text/input/wpt-import"+ env["PYTHONPATH"] = os.pathsep.join((str(wpt), str(wpt / "_wpttools")))+ process = subprocess.run(+ [+ str(binary),+ "--test-path",+ str(root),+ "-j1",+ "-v",+ "-v",+ "--per-test-timeout",+ "30",+ "--python-executable",+ sys.executable,+ "--results-dir",+ str(results),+ ],+ env=env,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ text=True,+ timeout=100,+ )+ print(f"{name}:\n{process.stdout}", flush=True)+ assert process.returncode == int(timeout), f"{name}: unexpected exit status {process.returncode}"+ status = dict(+ line.split(": ", 1) for line in (results / "harness-status.txt").read_text().splitlines() if ": " in line+ )+ assert status["completed"] == "2/2" and status["remaining"] == "0", status+ assert status["pass"] == str(2 - int(timeout)), status+ assert status["timeout"] == str(int(timeout)) and status["fail"] == "0" and status["crashed"] == "0", status+ processes = re.findall(r"WebContent\((\d+)\).*POINTER_RESET_(POISON|CONSUMER)", process.stdout)+ assert len(processes) == 2 and processes[0][1] == "POISON" and processes[1][1] == "CONSUMER", processes+ assert processes[0][0] == processes[1][0], f"{name}: WebContent was not reused: {processes}"+ if timeout:+ assert "POINTER_RESET_INJECTED" in process.stdout, f"{name}: the poison timed out before it hovered"+ consumer = re.search(r"POINTER_RESET_CONSUMER hovered=(\w+) entry=([\w,]*)", process.stdout)+ assert consumer, f"{name}: the consumer reported nothing"+ assert consumer.group(1) == "no", f"{name}: the consumer started with an element hovered"+ assert consumer.group(2) == ENTRY_EVENTS, f"{name}: the consumer's first move entered with {consumer.group(2)!r}"+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument("test_web", type=Path)+ args = parser.parse_args()+ source = Path(os.environ["LADYBIRD_SOURCE_DIR"]).resolve()+ with tempfile.TemporaryDirectory(prefix="test-web-pointer-reset-") as temporary:+ root = Path(temporary)+ run_case(args.test_web.resolve(), source, root, "normal-completion", False)+ # The pointer leaks through the lanes only some of the time, so give a leak several chances to show.+ for attempt in range(5):+ run_case(args.test_web.resolve(), source, root, f"timeout-{attempt}", True)+++if __name__ == "__main__":+ main()