Truly independent web browser
LibWeb: Show a drag selection in the clock lanes
Andreas Kling72298944af9e
diff --git a/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp b/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cppindex 960eb8a7403..fc2174ed4ee 100644--- a/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp+++ b/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp@@ -19,12 +19,14 @@#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/Element.h>#include <LibWeb/HTML/EventLoop/ClockPlan.h>+#include <LibWeb/HTML/LocalNavigable.h>#include <LibWeb/HTML/Navigable.h>#include <LibWeb/HTML/Window.h>#include <LibWeb/Layout/LayoutRustFFI.h>#include <LibWeb/Layout/Node.h>#include <LibWeb/Layout/RenderDocument.h>#include <LibWeb/Namespace.h>+#include <LibWeb/Page/EventHandler.h>#include <LibWeb/Page/Page.h>#include <LibWeb/Painting/BoxViews.h>@@ -310,6 +312,10 @@ bool seal_clock_plan(DOM::Document& document, bool may_plan, u64 update_serial)}}scroll_offsets = document.scroll_state_snapshot().device_offsets();+ Optional<Web::EventHandler::SelectionDragForLanes> selection_drag;+ if (auto navigable = document.navigable())+ selection_drag = navigable->event_handler().selection_drag_for_lanes(read);+ auto scrollport = selection_drag.has_value() ? selection_drag->scrollport.value_or(CSSPixelRect {}) : CSSPixelRect {};hover = Layout::RustFFI::FfiHoverPlanInputs {.device_pixels_per_css_pixel = document.page().client().device_pixels_per_css_pixel(),.scroll_offsets = scroll_offsets.data(),@@ -320,6 +326,15 @@ bool seal_clock_plan(DOM::Document& document, bool may_plan, u64 update_serial).effect_timing_identities = effect_timing_identities.data(),.effect_timings = effect_timings.data(),.effect_timing_count = effect_timings.size(),+ .selection_drag_anchor = selection_drag.has_value() ? selection_drag->anchor.value() : 0,+ .selection_drag_anchor_offset = selection_drag.has_value() ? selection_drag->anchor_offset : 0,+ .selection_drag_anchor_child = selection_drag.has_value() ? selection_drag->anchor_child.value() : 0,+ .selection_drag_scrollport = {+ .x = scrollport.x().to_float(),+ .y = scrollport.y().to_float(),+ .width = scrollport.width().to_float(),+ .height = scrollport.height().to_float(),+ },};}if (animates || hover.has_value()) {diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex 5f1c97fdcdd..b9f73ef718d 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -62,6 +62,7 @@#include <LibWeb/DOM/HTMLCollection.h>#include <LibWeb/DOM/NodeList.h>#include <LibWeb/DOM/ShadowRoot.h>+#include <LibWeb/DOM/Text.h>#include <LibWeb/DOMURL/DOMURL.h>#include <LibWeb/Dump.h>#include <LibWeb/Editing/SpellingMarkers.h>@@ -2425,12 +2426,12 @@ void Internals::inject_clock_tick_scrolling_element(double frame_time_ms, DOM::Einject_clock_tick_at_scroll_offset(window().associated_document(), frame_time_ms, &scroll_offset);}-void Internals::inject_hover_pointer(double x, double y, Optional<double> frame_time_ms, Optional<u64> input_event_id)+void Internals::inject_hover_pointer(double x, double y, Optional<double> frame_time_ms, Optional<u64> input_event_id, u32 buttons){auto& document = window().associated_document();auto device_pixels_per_css_pixel = page().client().device_pixels_per_css_pixel();auto frame_time = frame_time_ms.has_value() ? document.relevant_settings_object().time_origin() + *frame_time_ms : HighResolutionTime::unsafe_shared_current_time();- Layout::RustFFI::document_host_inject_pointer(document.layout_node_arena().host(), static_cast<float>(x * device_pixels_per_css_pixel), static_cast<float>(y * device_pixels_per_css_pixel), static_cast<i64>(frame_time * 1'000'000.0), input_event_id.value_or(0));+ Layout::RustFFI::document_host_inject_pointer(document.layout_node_arena().host(), static_cast<float>(x * device_pixels_per_css_pixel), static_cast<float>(y * device_pixels_per_css_pixel), buttons, static_cast<i64>(frame_time * 1'000'000.0), input_event_id.value_or(0));}void Internals::note_animated_content_moved_under_pointer(double frame_time_ms)@@ -2492,6 +2493,59 @@ bool Internals::clock_lane_is_coming(DOM::Document& document)return Layout::RustFFI::document_host_clock_lane_is_coming(document.layout_node_arena().host());}+struct SelectionForTesting {+ GC::Ref<DOM::Document> document;+ Utf16StringBuilder text {};+};++static void push_selection_for_testing(void* context, u32 style_node, u8 state, size_t start_offset, size_t end_offset, u32 background_color, u32 text_color)+{+ auto& selection = *static_cast<SelectionForTesting*>(context);+ auto node = selection.document->style_computer().node_for_style_node(CSS::StyleNodeID { style_node });+ if (!node)+ return;+ if (!selection.text.is_empty())+ selection.text.append_ascii(" | "sv);+ auto const* text = as_if<DOM::Text>(*node);+ auto append_selection_colors = [&] {+ if (background_color != 0 || text_color != 0)+ selection.text.appendff(" ({} on {})", Color::from_bgra(text_color).serialize_a_srgb_value(), Color::from_bgra(background_color).serialize_a_srgb_value());+ };+ if (!text) {+ selection.text.appendff("<{}>", node->node_name());+ append_selection_colors();+ return;+ }+ auto data = text->data().utf16_view();+ auto selection_state = static_cast<Painting::SelectionState>(state);+ auto start = first_is_one_of(selection_state, Painting::SelectionState::Start, Painting::SelectionState::StartAndEnd) ? min(start_offset, data.length_in_code_units()) : 0;+ auto end = first_is_one_of(selection_state, Painting::SelectionState::End, Painting::SelectionState::StartAndEnd) ? min(end_offset, data.length_in_code_units()) : data.length_in_code_units();+ selection.text.append(data.substring_view(start, max(start, end) - start));+ append_selection_colors();+}++enum class SelectionShownBy : u8 {+ Lane,+ Host,+};++static Utf16String selection_for_testing(DOM::Document& document, SelectionShownBy shown_by)+{+ SelectionForTesting selection { document };+ Layout::RustFFI::document_host_selection_for_testing(document.layout_node_arena().host(), shown_by == SelectionShownBy::Lane, &selection, push_selection_for_testing);+ return selection.text.to_string();+}++Utf16String Internals::presented_selection()+{+ return selection_for_testing(window().associated_document(), SelectionShownBy::Lane);+}++Utf16String Internals::painted_selection()+{+ return selection_for_testing(window().associated_document(), SelectionShownBy::Host);+}+GC::Ptr<Geometry::DOMRect> Internals::presented_border_box(DOM::Element& element){CSSPixelRect rect;diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.hindex 2a35c16b47d..0907512269e 100644--- a/Libraries/LibWeb/Internals/Internals.h+++ b/Libraries/LibWeb/Internals/Internals.h@@ -292,13 +292,15 @@ public:Utf16String last_frame_presented_by(DOM::Document&);void inject_clock_tick(double frame_time_ms, Optional<double> viewport_scroll_y);void inject_clock_tick_scrolling_element(double frame_time_ms, DOM::Element& scroller, double x, double y);- void inject_hover_pointer(double x, double y, Optional<double> frame_time_ms, Optional<u64> input_event_id);+ void inject_hover_pointer(double x, double y, Optional<double> frame_time_ms, Optional<u64> input_event_id, u32 buttons);void note_animated_content_moved_under_pointer(double frame_time_ms);void inject_pointer_rests_on_moving_content(double frame_time_ms);u64 queue_mouse_move(double x, double y, u32 buttons);void move_hover_pointer(double x, double y, Optional<u64> input_event_id);Utf16String clock_lane_state(DOM::Document&);bool clock_lane_is_coming(DOM::Document&);+ Utf16String presented_selection();+ Utf16String painted_selection();GC::Ptr<Geometry::DOMRect> presented_border_box(DOM::Element&);Optional<u32> presented_compositor_animation_count(DOM::Element&);Optional<double> presented_opacity(DOM::Element&);diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idlindex cb42ba936e4..a47102271ba 100644--- a/Libraries/LibWeb/Internals/Internals.idl+++ b/Libraries/LibWeb/Internals/Internals.idl@@ -311,7 +311,7 @@ interface Internals {// Hands the clock lanes of the current document a pointer move to the given point in CSS pixels as the compositor// would, beside the mouse event with the given input event id, if any, and waits until the tick that hovers what is// under it has run, at the given frame time, or now.- undefined injectHoverPointer(double x, double y, optional double frameTimeMs, optional unsigned long long inputEventId);+ undefined injectHoverPointer(double x, double y, optional double frameTimeMs, optional unsigned long long inputEventId, optional unsigned long buttons = 0);// Reports to the current document's navigable, as the compositor would, that a frame of a transform animation it// runs moved content under the pointer at rest, or away from it, as of the given frame time.undefined noteAnimatedContentMovedUnderPointer(double frameTimeMs);@@ -332,6 +332,12 @@ interface Internals {// The color, as a CSS color string, that the box of the element, or of its "::before", "::after" or "::marker"// pseudo-element, showed in the last frame a tick of a clock lane presented where the tick restyled it, or null.DOMString? presentedColor(Element element, optional DOMString pseudoElement);+ // The text and elements the selection highlights in the fork of the document's clock lane, joined by " | ", each+ // with the colors its ::selection styles give it, if any.+ DOMString presentedSelection();+ // The text and elements the selection highlights in what the host paints, joined by " | ", each with the colors its+ // ::selection styles give it, if any.+ DOMString paintedSelection();// The border box of the element in the last frame a clock tick presented.DOMRect? presentedBorderBox(Element element);// How many compositor animations drove the box of the element in the last frame a clock tick presented, or nulldiff --git a/Libraries/LibWeb/Page/AutoScrollHandler.cpp b/Libraries/LibWeb/Page/AutoScrollHandler.cppindex b5c7c7ea730..184385ea2d2 100644--- a/Libraries/LibWeb/Page/AutoScrollHandler.cpp+++ b/Libraries/LibWeb/Page/AutoScrollHandler.cpp@@ -89,6 +89,14 @@ void AutoScrollHandler::visit_edges(JS::Cell::Visitor& visitor) constvisitor.visit(m_container_element);}+Optional<CSSPixelRect> AutoScrollHandler::scrollport_in_viewport(Layout::BegunRead const& read) const+{+ auto* layout_node = auto_scroll_layout_node(read, m_container_element);+ if (!layout_node)+ return {};+ return scrollport_rect_in_viewport(*layout_node);+}+CSSPixelPoint AutoScrollHandler::process(CSSPixelPoint mouse_position){m_mouse_position = mouse_position;diff --git a/Libraries/LibWeb/Page/AutoScrollHandler.h b/Libraries/LibWeb/Page/AutoScrollHandler.hindex f16e50ccb54..e647e4d25a1 100644--- a/Libraries/LibWeb/Page/AutoScrollHandler.h+++ b/Libraries/LibWeb/Page/AutoScrollHandler.h@@ -28,6 +28,9 @@ public:bool is_active() const { return m_active; }+ // The scrollport that keeps the pointer of the selection the handler scrolls for, in the coordinates of the viewport.+ Optional<CSSPixelRect> scrollport_in_viewport(Layout::BegunRead const&) const;+static GC::Ptr<DOM::Element> find_scrollable_ancestor(Layout::Node const&);static Layout::Node* auto_scroll_layout_node(Layout::BegunRead const& read, DOM::Element&);diff --git a/Libraries/LibWeb/Page/DragAndDropEventHandler.cpp b/Libraries/LibWeb/Page/DragAndDropEventHandler.cppindex bf5c079dbbb..da890375042 100644--- a/Libraries/LibWeb/Page/DragAndDropEventHandler.cpp+++ b/Libraries/LibWeb/Page/DragAndDropEventHandler.cpp@@ -34,6 +34,19 @@ void DragAndDropEventHandler::visit_edges(JS::Cell::Visitor& visitor) const}// https://html.spec.whatwg.org/multipage/dnd.html#drag-and-drop-processing-model+GC::Ptr<HTML::HTMLElement> DragAndDropEventHandler::first_draggable_inclusive_ancestor(DOM::Node& node)+{+ GC::Ptr<HTML::HTMLElement> draggable_element;+ node.for_each_inclusive_ancestor_of_type<HTML::HTMLElement>([&](HTML::HTMLElement& element) {+ if (!element.draggable())+ return IterationDecision::Continue;++ draggable_element = element;+ return IterationDecision::Break;+ });+ return draggable_element;+}+EventResult DragAndDropEventHandler::handle_drag_start(JS::Object const& relevant_global_object,GC::Ptr<DOM::Node> drag_target,@@ -59,13 +72,7 @@ EventResult DragAndDropEventHandler::handle_drag_start(// starting at the node that the user tried to drag, that has the IDL attribute draggable set to true. If there is// no such element, then nothing is being dragged; return, the drag-and-drop operation is never started.if (drag_target) {- drag_target->for_each_inclusive_ancestor_of_type<HTML::HTMLElement>([&](HTML::HTMLElement& node) {- if (!node.draggable())- return IterationDecision::Continue;-- dragged_node = node;- return IterationDecision::Break;- });+ dragged_node = first_draggable_inclusive_ancestor(*drag_target);if (!dragged_node)return EventResult::Cancelled;diff --git a/Libraries/LibWeb/Page/DragAndDropEventHandler.h b/Libraries/LibWeb/Page/DragAndDropEventHandler.hindex d796653d935..a834ad92ed7 100644--- a/Libraries/LibWeb/Page/DragAndDropEventHandler.h+++ b/Libraries/LibWeb/Page/DragAndDropEventHandler.h@@ -25,6 +25,8 @@ public:bool has_ongoing_drag_and_drop_operation() const { return !m_drag_data_store.is_null(); }+ static GC::Ptr<HTML::HTMLElement> first_draggable_inclusive_ancestor(DOM::Node&);+EventResult handle_drag_start(JS::Object const& relevant_global_object, GC::Ptr<DOM::Node> drag_target, CSSPixelPoint screen_position, CSSPixelPoint page_offset, CSSPixelPoint client_offset, CSSPixelPoint offset, unsigned button, unsigned buttons, unsigned modifiers, Vector<HTML::SelectedFile> files);EventResult handle_drag_move(JS::Object const& relevant_global_object, GC::Ref<DOM::Node>, CSSPixelPoint screen_position, CSSPixelPoint page_offset, CSSPixelPoint client_offset, CSSPixelPoint offset, unsigned button, unsigned buttons, unsigned modifiers);EventResult handle_drag_leave(JS::Object const& relevant_global_object, CSSPixelPoint screen_position, CSSPixelPoint page_offset, CSSPixelPoint client_offset, CSSPixelPoint offset, unsigned button, unsigned buttons, unsigned modifiers);diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cppindex dfccad16907..12faabfefbb 100644--- a/Libraries/LibWeb/Page/EventHandler.cpp+++ b/Libraries/LibWeb/Page/EventHandler.cpp@@ -4455,6 +4455,43 @@ GC::Ptr<DOM::Range> EventHandler::context_menu_url_token_range(DOM::Text& hit_noreturn DOM::Range::create(hit_node, token_start, hit_node, token_end);}+static CSS::StyleNodeID style_node_of_text_or_element(DOM::Node const& node)+{+ if (auto const* text = as_if<DOM::Text>(node))+ return text->style_node_id();+ if (auto const* element = as_if<DOM::Element>(node))+ return element->style_node_id();+ return {};+}++Optional<EventHandler::SelectionDragForLanes> EventHandler::selection_drag_for_lanes(Layout::BegunRead const& read) const+{+ if (m_selection_mode != SelectionMode::Character || m_mouse_selection_target)+ return {};+ // NB: A press on something draggable drags it once the pointer leaves the drag threshold, which ends the selection.+ if (auto mousedown_target = m_mousedown_target.ptr(); m_mousedown_target_is_drag_candidate && mousedown_target+ && DragAndDropEventHandler::first_draggable_inclusive_ancestor(*mousedown_target))+ return {};+ auto document = m_navigable->active_document();+ if (!document)+ return {};+ auto selection = document->get_selection();+ if (!selection)+ return {};+ auto anchor = selection->anchor_node();+ if (!anchor || !anchor->is_connected())+ return {};+ auto anchor_style_node = style_node_of_text_or_element(*anchor);+ if (!anchor_style_node)+ return {};+ SelectionDragForLanes drag { .anchor = anchor_style_node, .anchor_offset = selection->anchor_offset(), .anchor_child = {}, .scrollport = {} };+ for (auto* child = anchor->child_at_index(selection->anchor_offset()); child && !drag.anchor_child; child = child->next_sibling())+ drag.anchor_child = style_node_of_text_or_element(*child);+ if (m_auto_scroll_handler)+ drag.scrollport = m_auto_scroll_handler->scrollport_in_viewport(read);+ return drag;+}+void EventHandler::update_mouse_selection(Layout::BegunRead const& read, CSSPixelPoint visual_viewport_position){if (m_selection_mode == SelectionMode::None)diff --git a/Libraries/LibWeb/Page/EventHandler.h b/Libraries/LibWeb/Page/EventHandler.hindex 7fc5a43891c..aca23ad1e3d 100644--- a/Libraries/LibWeb/Page/EventHandler.h+++ b/Libraries/LibWeb/Page/EventHandler.h@@ -146,6 +146,18 @@ public:Paragraph,};bool is_handling_mouse_selection() const { return m_selection_mode != SelectionMode::None; }++ // What a clock lane reads of a drag selecting the page's text by characters, which it shows beside a task.+ struct SelectionDragForLanes {+ CSS::StyleNodeID anchor;+ // Where the anchor is a text node, the offset in its text.+ size_t anchor_offset { 0 };+ // Where the anchor is an element, the first child after the boundary point that the lane knows of.+ CSS::StyleNodeID anchor_child;+ Optional<CSSPixelRect> scrollport;+ };+ Optional<SelectionDragForLanes> selection_drag_for_lanes(Layout::BegunRead const&) const;+void reset_mouse_input_tracking(Badge<Page>);void reset_hover_for_document_replacement(Badge<HTML::LocalNavigable>);diff --git a/Libraries/LibWeb/Rust/src/css/style/drag_selection.rs b/Libraries/LibWeb/Rust/src/css/style/drag_selection.rsnew file mode 100644index 00000000000..bd98fda1d1d--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/drag_selection.rs@@ -0,0 +1,227 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What a clock lane's drag selection reads of the DOM: the places of nodes in tree order, and what their `user-select`+//! allows, from the nodes the style engine mirrors, which is all the Render thread has of the document. Comments and+//! processing instructions have no place among them, and never have a box to highlight.+//!+//! A style update keeps the `::selection` styles of the elements the host's selection covers alone, so a row a drag+//! reaches first has none. A lane styles those in its fork, as the host does once it covers them.++use super::StyleEngine;+use super::tree::StyleNodeID;+use crate::css::computed_value_views::ComputedValuesView;+use crate::layout::node_data::DomPaintFact;+use crate::painting::hit_test::caret::NodeScopes;+use crate::painting::host::FfiNodeIdentity;+use smallvec::SmallVec;+use std::collections::HashSet;++/// The used value of `user-select`, as `DOM::Node::user_select_used_value` decides it.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum UsedUserSelect {+ Text,+ None,+ All,+ Contain,+}++impl StyleEngine {+ /// The parent of `node`, as `DOM::Node::parent` answers it: a shadow root has none.+ pub(crate) fn drag_parent(&self, node: StyleNodeID) -> Option<StyleNodeID> {+ match node.text_index() {+ Some(_) => self.retained.text_parent(node),+ None => self.retained.dom_parent(node),+ }+ }++ /// `node` and its ancestors, up to the root of its tree.+ fn drag_ancestry(&self, node: StyleNodeID) -> impl Iterator<Item = StyleNodeID> + '_ {+ std::iter::successors(Some(node), |&node| self.drag_parent(node))+ }++ /// The root of the tree `node` is in.+ pub(crate) fn drag_root(&self, node: StyleNodeID) -> StyleNodeID {+ self.drag_ancestry(node).last().unwrap_or(node)+ }++ /// Whether `ancestor` is `node` or an ancestor of it.+ pub(crate) fn drag_is_inclusive_ancestor(&self, ancestor: StyleNodeID, node: StyleNodeID) -> bool {+ self.drag_ancestry(node).any(|node| node == ancestor)+ }++ /// Whether `a` comes before `b` in the tree order of the tree they share.+ pub(crate) fn drag_precedes(&self, a: StyleNodeID, b: StyleNodeID) -> bool {+ let chain = |node| self.drag_ancestry(node).collect::<SmallVec<[StyleNodeID; 32]>>();+ let (a_chain, b_chain) = (chain(a), chain(b));+ // Walk both from the root end to where they part. An ancestor comes before what it holds.+ let shared = a_chain+ .iter()+ .rev()+ .zip(b_chain.iter().rev())+ .take_while(|(a, b)| a == b)+ .count();+ if shared == 0 || shared == b_chain.len() {+ return false;+ }+ if shared == a_chain.len() {+ return true;+ }+ let (left, right) = (a_chain[a_chain.len() - shared - 1], b_chain[b_chain.len() - shared - 1]);+ std::iter::successors(self.retained.next_sibling_in_dom_order(left), |&sibling| {+ self.retained.next_sibling_in_dom_order(sibling)+ })+ .any(|sibling| sibling == right)+ }++ /// The first child of `node`, in the tree it is in: a shadow tree is another tree.+ fn drag_first_child(&self, node: StyleNodeID) -> Option<StyleNodeID> {+ self.retained.dom_children(node).next()+ }++ /// Whether `node` has children.+ pub(crate) fn drag_has_children(&self, node: StyleNodeID) -> bool {+ self.drag_first_child(node).is_some()+ }++ /// The node right after `node`, which then is the last node of nothing it holds.+ pub(crate) fn drag_next_sibling(&self, node: StyleNodeID) -> Option<StyleNodeID> {+ self.retained.next_sibling_in_dom_order(node)+ }++ /// The node after `node` and all it holds, in tree order, within `stay_within`.+ pub(crate) fn drag_next_after_subtree(&self, node: StyleNodeID, stay_within: StyleNodeID) -> Option<StyleNodeID> {+ self.drag_ancestry(node)+ .take_while(|&node| node != stay_within)+ .find_map(|node| self.retained.next_sibling_in_dom_order(node))+ }++ /// The node after `node` in tree order, within `stay_within`, as `TreeNode::next_in_pre_order` answers it.+ pub(crate) fn drag_next_in_pre_order_within(+ &self,+ node: StyleNodeID,+ stay_within: StyleNodeID,+ ) -> Option<StyleNodeID> {+ self.drag_first_child(node)+ .or_else(|| self.drag_next_after_subtree(node, stay_within))+ }++ /// Whether `node` is inert.+ pub(crate) fn drag_is_inert(&self, node: StyleNodeID) -> bool {+ self.tree().dom_paint_facts(node) & DomPaintFact::Inert as u8 != 0+ }++ /// The element whose `user-select` decides for `node`: `node` itself, or the one a text node takes its style from.+ pub(crate) fn drag_style_element(&self, node: StyleNodeID) -> Option<StyleNodeID> {+ match node.text_index() {+ Some(_) => self.retained.inheritance_parent(node),+ None => Some(node),+ }+ }++ /// Whether `node` is an element with `display: contents`, which generates no box.+ pub(crate) fn drag_has_no_box_of_its_own(&self, node: StyleNodeID) -> bool {+ node.element_index().is_some()+ && self+ .computed_group_sets+ .assigned_style_record(node)+ .and_then(|record| self.computed_group_sets.style_record_view(record.raw()))+ .is_some_and(|view| ComputedValuesView::of(view.payloads).display().is_contents())+ }++ /// The used value of `user-select` on `element`, as `DOM::Node::user_select_used_value` decides it. An editing host+ /// or a mutable form control contains the selection, whatever its style says.+ ///+ /// NB: The mirror tells an editing host from the elements in it by nothing, and a form control not at all, so every+ /// editable element answers `Contain`, and a text control that is not editable answers as its style says. A+ /// drag that reaches either stays in a text control's user agent shadow tree, or is the host's by the answer.+ pub(crate) fn drag_used_user_select(&self, element: StyleNodeID) -> UsedUserSelect {+ use crate::css::css_enums::user_select;+ let mut node = element;+ loop {+ if self.tree().dom_paint_facts(node) & DomPaintFact::EditableOrEditingHost as u8 != 0 {+ return match node == element {+ true => UsedUserSelect::Contain,+ false => UsedUserSelect::Text,+ };+ }+ let view = self+ .computed_group_sets+ .assigned_style_record(node)+ .and_then(|record| self.computed_group_sets.style_record_view(record.raw()));+ let Some(view) = view else {+ return UsedUserSelect::None;+ };+ let computed = ComputedValuesView::of(view.payloads).misc_interaction().user_select;+ match computed {+ user_select::NONE => return UsedUserSelect::None,+ user_select::ALL => return UsedUserSelect::All,+ user_select::CONTAIN if node == element => return UsedUserSelect::Contain,+ user_select::AUTO => {}+ _ => return UsedUserSelect::Text,+ }+ match self.retained.inheritance_parent(node) {+ Some(parent) if parent.element_index().is_some() && !self.retained.is_relation_only(parent) => {+ node = parent;+ }+ _ => return UsedUserSelect::Text,+ }+ }+ }+}++/// Which elements a drag's highlight still owes their `::selection` styles.+pub(crate) struct SelectionStyles {+ /// Whether a rule of the document styles `::selection`, without which the rows show the default colors as they are.+ document_styles_selection: bool,+ /// The elements whose rows hold their `::selection` styles.+ styled: HashSet<StyleNodeID>,+}++impl SelectionStyles {+ /// What the frame of the document `engine` holds owes.+ pub(crate) fn of(engine: &StyleEngine) -> Self {+ Self {+ document_styles_selection: engine+ .retained+ .live_style+ .as_deref()+ .is_none_or(|live| live.styles_selection()),+ styled: HashSet::new(),+ }+ }++ /// Whether the rows of `element` have yet to get its `::selection` styles.+ pub(crate) fn owes(&self, element: StyleNodeID) -> bool {+ self.document_styles_selection && !self.styled.contains(&element)+ }++ /// Notes that the rows of `element` hold its `::selection` styles.+ pub(crate) fn note_styled(&mut self, element: StyleNodeID) {+ self.styled.insert(element);+ }+}++/// What `HitTestList`'s caret queries read of the DOM on the Render thread: the mirror, where the host asks the DOM.+pub(crate) struct MirrorNodeScopes<'a>(pub(crate) &'a StyleEngine);++impl NodeScopes for MirrorNodeScopes<'_> {+ fn contains(&self, ancestor: FfiNodeIdentity, node: FfiNodeIdentity) -> bool {+ let identity = |identity: FfiNodeIdentity| StyleNodeID::from_raw(identity.style_node);+ match (ancestor.is_document, node.is_document) {+ (_, true) => ancestor.is_document,+ // A shadow tree's nodes are not the document's descendants.+ (true, false) => identity(node).is_none_or(|node| {+ let root = self.0.drag_root(node);+ self.0.retained.host_of(root).is_none()+ }),+ (false, false) => match (identity(ancestor), identity(node)) {+ (Some(ancestor), Some(node)) => self.0.drag_is_inclusive_ancestor(ancestor, node),+ _ => false,+ },+ }+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/mod.rs b/Libraries/LibWeb/Rust/src/css/style/mod.rsindex 39913c4181c..6b0a277954a 100644--- a/Libraries/LibWeb/Rust/src/css/style/mod.rs+++ b/Libraries/LibWeb/Rust/src/css/style/mod.rs@@ -56,6 +56,7 @@ pub(crate) use container_queries::ContainerUnitBases;mod custom_property_cascade;mod custom_property_environments;mod dom_reads;+pub(crate) mod drag_selection;pub(crate) mod effect_descriptions;mod element_declarations;mod element_host_facts;diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/demand.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/demand.rsindex 7383a9043b6..19959de2bfd 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/demand.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/demand.rs@@ -642,6 +642,42 @@ impl StyleEngine {}}+ /// The record of the `::selection` of `element`, or zero where no rule styles it, for the fork of a clock lane, whose+ /// drag reaches an element the host shows no selection in. Answers none where what it takes to style it is the+ /// host's to resolve, as a font is.+ pub(crate) fn demand_selection_record(&mut self, element: StyleNodeID) -> Option<u64> {+ let mut live = self.retained.live_style.take()?;+ let record = self.selection_record_with(&mut live, element);+ self.retained.live_style = Some(live);+ record+ }++ fn selection_record_with(&mut self, live: &mut Live, element: StyleNodeID) -> Option<u64> {+ let kind = super::super::publication::pseudo_kind::SELECTION;+ let DemandedElement::Styled(element_record) = live.demand_element(&self.retained, element, false) else {+ return None;+ };+ let record = match live.demand_pseudo_element(&self.retained, element, kind, PseudoElementRead::Styled, None) {+ DemandedPseudoElement::Styled(record) => record,+ DemandedPseudoElement::Unstyled => return Some(0),+ DemandedPseudoElement::Waiting(..) | DemandedPseudoElement::Declined => return None,+ };+ let mut minted = HashMap::default();+ let element_environment = self.demanded_environment(live, element, &element_record, &mut minted);+ let environment = self.retained.pseudo_element_environment(+ element,+ &record,+ &element_record,+ element_environment,+ &mut minted,+ );+ let record = self.retained.record_in_environment(&record, environment);+ let style_record = self.retained.install_record(&record, &mut HashMap::default());+ self.retained+ .hold_demand_record(computed::ComputedStyleTarget::new(element, kind), style_record);+ Some(style_record.raw())+ }+/// Style the pseudo-element of `kind` of `node` as [`Live::demand_pseudo_element`] does,/// resolving the fonts and random base values it asks for first.fn demand_pseudo_element(diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rsindex a4e3f6ad15e..58a76184ba3 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs@@ -957,6 +957,12 @@ impl Live {&self.index}+ /// Whether a rule of the document's sheets styles `::selection`.+ pub(in super::super) fn styles_selection(&self) -> bool {+ self.index+ .styles_pseudo_element(super::super::publication::pseudo_kind::SELECTION)+ }+#[cfg(test)]pub(super) fn records(&self) -> &RetainedRecords {&self.recordsdiff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/rules.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/rules.rsindex 1df958e7953..22de1bedb7e 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/rules.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/rules.rs@@ -2137,6 +2137,14 @@ impl RuleIndex {RuleID(view.rule().0)}+ /// Whether a live entry of the document's sheets styles the pseudo-element of `kind`.+ pub(super) fn styles_pseudo_element(&self, kind: u8) -> bool {+ self.entries.own_numbers().any(|id| {+ let view = self.entries.view(id);+ view.pseudo_kind() == kind && view.live()+ })+ }+/// Whether an entry that does not revalidate tests for the id `id`.pub(super) fn tests_id(&self, id: StyleAtomID) -> bool {self.tested_ids.contains(&id)diff --git a/Libraries/LibWeb/Rust/src/painting/host/hit_test.rs b/Libraries/LibWeb/Rust/src/painting/host/hit_test.rsindex 31f4f2230d8..0dcea107dec 100644--- a/Libraries/LibWeb/Rust/src/painting/host/hit_test.rs+++ b/Libraries/LibWeb/Rust/src/painting/host/hit_test.rs@@ -27,8 +27,7 @@ pub struct FfiHitTestQueryCallbacks {impl FfiHitTestQueryCallbacks {/// Callbacks for a point query on the render owner, which reaches nothing of the host: the scroll offsets and- /// chrome metrics are copies the host sealed, and no caret query, the only one that asks the host about the DOM,- /// runs there.+ /// chrome metrics are copies the host sealed, and a caret query there asks the style engine's mirror about the DOM.pub(crate) fn sealed(device_pixels_per_css_pixel: f64,scroll_offsets: &[libgfx_rust::FloatPoint],diff --git a/Libraries/LibWeb/Rust/src/painting/selection.rs b/Libraries/LibWeb/Rust/src/painting/selection.rsindex 3a7dc6ac65b..56b3aa808b9 100644--- a/Libraries/LibWeb/Rust/src/painting/selection.rs+++ b/Libraries/LibWeb/Rust/src/painting/selection.rs@@ -421,6 +421,20 @@ pub(crate) fn sync_highlight_pseudo_styles(}}+/// Gives the rows that paint text under `element` `selection_record`, the record of its `::selection` a clock lane+/// styled, zero for none. The other highlight pseudo-elements stay as the host published them.+pub(crate) fn sync_selection_style(arena: &mut LayoutNodeArena, element: StyleNodeID, selection_record: u64) {+ let style_records = arena.with_style_store(|engine| {+ HighlightPseudoElement::ALL.map(|highlight| match highlight {+ HighlightPseudoElement::Selection => selection_record,+ _ => engine+ .pseudo_published_style_record(element, highlight.pseudo_kind())+ .unwrap_or(0),+ })+ });+ sync_highlight_pseudo_styles(arena, element, style_records);+}+/// Gives a row the tree build made what the published highlight pseudo-element records of/// `element` say highlighted text paints with: `element`'s own row, or a text row whose parent/// element has no box.diff --git a/Libraries/LibWeb/Rust/src/render_state/clock.rs b/Libraries/LibWeb/Rust/src/render_state/clock.rsindex 8c1f214cb7d..200397b6294 100644--- a/Libraries/LibWeb/Rust/src/render_state/clock.rs+++ b/Libraries/LibWeb/Rust/src/render_state/clock.rs@@ -64,6 +64,7 @@ use std::sync::{Arc, Mutex};mod effects;pub(crate) mod hover;mod lane;+mod selection;pub(crate) use hover::PendingPointer;pub(crate) use lane::LaneDelivery;pub(super) use lane::{LaneSlot, note_host_write, retire_slot, seal_plan, take_lane_report, take_lanes_in};@@ -354,6 +355,12 @@ pub(crate) struct Lane {/// Whether a move of the hover had boxes show the styles the host installed in them again in place of samples, which/// the tick shows again.samples_restored: bool,+ /// The list a drag selection finds its caret positions in, for the frame whose items it holds.+ selection_hit_test_list: Option<crate::painting::hit_test::HitTestList>,+ /// What a drag selection owes the rows of the fork of `::selection` styles, once a tick asked.+ selection_styles: Option<crate::css::style::drag_selection::SelectionStyles>,+ /// Where the highlight the fork holds ends, if a tick moved it.+ selection_focus_shown: Option<selection::Boundary>,}/// What the ticks of a lane write: the render state of the render owner while it still shows the lane's frame, which@@ -1301,6 +1308,9 @@ impl Lane {hovered: hover::LaneHover::default(),unshown_move: None,samples_restored: false,+ selection_hit_test_list: None,+ selection_styles: None,+ selection_focus_shown: None,}}@@ -1320,6 +1330,7 @@ impl Lane {fn rejoin_the_state(&mut self) {if self.samples_nothing() && self.state.rejoin_the_state() {self.hovered.installs.clear();+ self.selection_focus_shown = None;}}@@ -1341,6 +1352,11 @@ impl Lane {self.shown_scroll_progress = plan.scroll_progress(&self.scroll_positions);self.settling_frames = 0;self.shown_at = f64::NEG_INFINITY;+ self.selection_focus_shown = None;+ self.selection_styles = None;+ if plan.hover.as_ref().is_none_or(|hover| hover.selection_drag().is_none()) {+ self.selection_hit_test_list = None;+ }self.replan_host_effects(&plan.elements);self.plan = plan;}@@ -1439,7 +1455,19 @@ impl Lane {sampled |= self.sample_started_transitions(state, sampled_at.0).unwrap_or(true);moved |= sampled;}- if let Some(pointer) = hovers {+ let drags = hovers.filter(|pointer| pointer.holds_the_primary_button() && self.selection_drag().is_some());+ if let Some(pointer) = drags {+ moved |= self.extend_selection(state, pointer, frame_time_nanoseconds);+ // The host hovers what is under the pointer as it handles the move, as for any move with a button held.+ ticked.hover_move = Some(LaneMove {+ input_event_id: pointer.input_event_id,+ target: None,+ handed: false,+ });+ } else if let Some(pointer) = hovers {+ if !pointer.holds_the_primary_button() {+ self.end_selection_drag();+ }let hovered = self.hover(state, pointer, sampled_at.0, frame_time_nanoseconds);ticked.hover_move = Some(LaneMove {input_event_id: pointer.input_event_id,@@ -2081,6 +2109,29 @@ pub extern "C" fn document_host_presented_compositor_animation_count(true}+/// Calls `push` with `context` for every node the selection highlights, in the state the host paints, or where+/// `presented`, in the fork the lane of `host`'s document shows, if it has one: the node's style node, its selection+/// state, where the selection starts and ends, and the background and text colors of its `::selection` styles. For a+/// test.+#[unsafe(no_mangle)]+pub extern "C" fn document_host_selection_for_testing(+ host: &DocumentHost,+ presented: bool,+ context: *mut std::ffi::c_void,+ push: extern "C" fn(*mut std::ffi::c_void, u32, u8, usize, usize, u32, u32),+) {+ let document = host.clock_ticks().document;+ let rows = super::on_render_side(0, move || {+ presented+ .then(|| lane::selection_shown_for_testing(document))+ .flatten()+ .unwrap_or_else(|| super::owner::with_state(document, None, |state| selection::rows_for_testing(state)))+ });+ for (node, state, start, end, background, text) in rows {+ push(context, node, state, start, end, background, text);+ }+}+/// Writes the opacity the effect nodes of the box of `element` gave it in the last frame a tick of a lane of `host`'s/// document presented to `opacity`, and answers whether the frame showed the box's border box. For a test.#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Rust/src/render_state/clock/hover.rs b/Libraries/LibWeb/Rust/src/render_state/clock/hover.rsindex ffb65b56400..49b8fc31ec2 100644--- a/Libraries/LibWeb/Rust/src/render_state/clock/hover.rs+++ b/Libraries/LibWeb/Rust/src/render_state/clock/hover.rs@@ -24,6 +24,8 @@ use crate::layout::tree_mutation::{HostCalls, OwedHostWork};use crate::painting::ffi::FfiChromeMetrics;use crate::painting::hit_test::{HitTestItemKind, HitTestList};use crate::painting::host::FfiHitTestQueryCallbacks;+use crate::painting::record::PublishedHitTestItems;+use crate::painting::visual_context::VisualContextTree;use crate::stage_thread::Riding;use libgfx_rust::FloatPoint;use std::sync::Arc;@@ -44,6 +46,15 @@ pub struct FfiHoverPlanInputs {pub effect_timing_identities: *const u64,pub effect_timings: *const std::ffi::c_void,pub effect_timing_count: usize,+ /// Where a drag selecting text the lane may follow is anchored, if one runs: the style node of a text node or an+ /// element, or 0, and the offset in that text, or the style node of the child of that element right after the anchor,+ /// or 0 after its last child.+ pub selection_drag_anchor: u32,+ pub selection_drag_anchor_offset: usize,+ pub selection_drag_anchor_child: u32,+ /// The scrollport the host's autoscroll keeps the pointer of that drag in, in CSS pixels of the viewport. Empty where+ /// none does.+ pub selection_drag_scrollport: crate::layout::svg_formatting_context::FfiFloatRect,}unsafe extern "C" {@@ -140,6 +151,8 @@ pub(crate) struct HoverPlan {/// The timings the host runs effects on without sampling them, which the descriptions of their elements' effects/// hold from before: the step a hover decides over the transitions they run reads them.effect_timings: Vec<(StyleNodeID, u64, FfiEffectTiming)>,+ /// The drag selecting text the ticks show, until the button goes up.+ selection_drag: Option<super::selection::SelectionDrag>,}impl HoverPlan {@@ -187,6 +200,12 @@ impl HoverPlan {// SAFETY: Guaranteed by the caller.page_cursor: unsafe { PageCursor::retained(inputs.page_cursor) },effect_timings,+ selection_drag: super::selection::SelectionDrag::new(+ inputs.selection_drag_anchor,+ inputs.selection_drag_anchor_offset,+ inputs.selection_drag_anchor_child,+ inputs.selection_drag_scrollport,+ ),}}@@ -194,6 +213,10 @@ impl HoverPlan {let Some((root, _)) = self.style.as_ref() else {return;};+ // A drag writes the highlight in the lane's fork.+ if self.selection_drag.is_some() {+ return;+ }if !state.engine_ref().takes_hover_transactions()|| state.engine_ref().has_animation_overlay_records()|| state.engine_mut().hover_needs_style_state(*root)@@ -241,6 +264,22 @@ impl HoverPlan {self.read_only_frame.is_none()}+ pub(super) fn selection_drag(&self) -> Option<super::selection::SelectionDrag> {+ self.selection_drag+ }++ pub(super) fn end_selection_drag(&mut self) {+ self.selection_drag = None;+ }++ pub(super) fn device_pixels_per_css_pixel(&self) -> f64 {+ self.device_pixels_per_css_pixel+ }++ pub(super) fn chrome_metrics(&self) -> FfiChromeMetrics {+ self.chrome_metrics+ }+/// Has the hover's style updates take `inputs`, the document computation inputs the host sealed for its last/// transaction under `root`.pub(crate) fn with_style_inputs(self, style: Option<(StyleNodeID, Arc<SealedStyleInputs>)>) -> Self {@@ -263,6 +302,9 @@ fn hand_pointer_to_context(context: u64, position: Option<FloatPoint>, pointer:);}+/// The bit of `UIEvents::MouseButton::Primary` in the buttons of a move.+const PRIMARY_MOUSE_BUTTON: u32 = 1;+/// Where the render clock heard the pointer went.#[derive(Clone, Copy, Debug)]pub(crate) struct PendingPointer {@@ -276,6 +318,13 @@ pub(crate) struct PendingPointer {pub(crate) input_event_id: u64,}+impl PendingPointer {+ /// Whether the move has the primary mouse button held, the one that drags a selection.+ pub(super) fn holds_the_primary_button(&self) -> bool {+ self.buttons & PRIMARY_MOUSE_BUTTON != 0+ }+}+/// What the lanes want once they heard where the pointer went, as the render clock reads it.#[repr(u8)]pub(crate) enum PointerAnswer {@@ -342,6 +391,11 @@ impl PointerState {self.pending.is_some()}+ /// Whether the move that waits for a tick has the primary mouse button held.+ pub(super) fn holds_the_primary_button(&self) -> bool {+ self.pending.is_some_and(|pending| pending.holds_the_primary_button())+ }+/// Forgets where the pointer went, short of the mouse events the host handled.pub(super) fn forget(&mut self) {self.pending = None;@@ -349,10 +403,15 @@ impl PointerState {}/// Notes that the host handled the mouse event with the input event id `input_event_id`, and forgets the move that- /// waits for a tick, where it is older.+ /// waits for a tick, where it is older, or the very move of a drag, which an idle host paints itself.pub(super) fn note_handled(&mut self, input_event_id: u64) {self.handled = self.handled.max(input_event_id);- if self.pending.is_some_and(|pending| self.is_older_than_handled(pending)) {+ if self.pending.is_some_and(|pending| {+ self.is_older_than_handled(pending)+ || (pending.holds_the_primary_button()+ && pending.input_event_id != 0+ && pending.input_event_id == self.handled)+ }) {self.pending = None;}}@@ -1144,9 +1203,7 @@ impl Lane {}let frame = plan.read_only_frame.as_ref()?;let tree = frame.visual_context.tree.as_ref()?;- let recorder = self.recording.0.take(WaitsForTickRecording(()));- let published = recorder.recorder.published_hit_test_items.clone();- self.recording = TickRecording(Riding::landed(recorder));+ let published = self.published_hit_test_items();let published = published?;if published.structural_epoch != tree.structural_epoch {return None;@@ -1262,36 +1319,49 @@ impl Lane {}}- /// Hit tests `position`, in device pixels, in the frame the lane presented last.- fn hit_test(- &mut self,- state: &mut RenderState,- plan: &HoverPlan,- position: FloatPoint,- frame_time_nanoseconds: i64,- ) -> Result<HoverTarget, HoverDeclined> {- // The hit-test list is the one of the frame the lane presented last, which comes back with its recording.+ /// The hit-test items of the frame the lane presented last, which come back with its recording.+ fn published_hit_test_items(&mut self) -> Option<Arc<PublishedHitTestItems>> {let recorder = self.recording.0.take(WaitsForTickRecording(()));let published = recorder.recorder.published_hit_test_items.clone();self.recording = TickRecording(Riding::landed(recorder));- let published = published.ok_or(HoverDeclined::Unplaced("no hit-test list"))?;- let arena = state.arena.arena();- let tree = arena- .paint_state()- .visual_context- .tree- .clone()- .ok_or(HoverDeclined::Unplaced("no visual context tree"))?;+ published+ }++ /// The hit-test items of the frame the lane presented last, with the tree of visual contexts of `state` they name as+ /// the screen shows them at `frame_time_nanoseconds`, or why a hit test cannot read them.+ pub(super) fn presented_hit_test_items(+ &mut self,+ state: &RenderState,+ frame_time_nanoseconds: i64,+ ) -> Result<(Arc<VisualContextTree>, Arc<PublishedHitTestItems>), &'static str> {+ let published = self.published_hit_test_items().ok_or("no hit-test list")?;+ let visual_context = &state.arena.arena().paint_state().visual_context;+ let tree = visual_context.tree.clone().ok_or("no visual context tree")?;// The items name the visual contexts of the tree they were recorded against, which a hit test of the host's may// have built anew since without presenting it.if published.structural_epoch != tree.structural_epoch {- return Err(HoverDeclined::Unplaced("visual contexts the frame does not show"));+ return Err("visual contexts the frame does not show");}// The screen shows the compositor's animations sampled at the frame's time, where the hit test finds them.let tree = match tree.has_visual_animations() {true => Arc::new(tree.with_visual_animation_samples(frame_time_nanoseconds)),false => tree,};+ Ok((tree, published))+ }++ /// Hit tests `position`, in device pixels, in the frame the lane presented last.+ fn hit_test(+ &mut self,+ state: &mut RenderState,+ plan: &HoverPlan,+ position: FloatPoint,+ frame_time_nanoseconds: i64,+ ) -> Result<HoverTarget, HoverDeclined> {+ let (tree, published) = self+ .presented_hit_test_items(state, frame_time_nanoseconds)+ .map_err(HoverDeclined::Unplaced)?;+ let arena = state.arena.arena();let mut list = HitTestList {items: std::sync::Arc::clone(&published.items),..HitTestList::default()@@ -1378,7 +1448,7 @@ impl Lane {/// The device scroll offsets of the visual context tree's nodes as the screen shows them: those of the frame the/// host laid out, where the compositor scrolled the scroll containers to at the latest tick, as the hit test reads/// them.- fn scroll_offsets_on_screen(+ pub(super) fn scroll_offsets_on_screen(&self,arena: &impl crate::painting::paint_read::PaintRead,visual_context: &crate::painting::visual_context::VisualContextState,@@ -1558,14 +1628,15 @@ pub extern "C" fn document_host_move_pointer(});}-/// Hands the clock lanes of `host`'s document a pointer move to `x`, `y` in device pixels, beside the mouse event with-/// the input event id `input_event_id`, or none for 0, ticks them at `frame_time_nanoseconds`, and waits until the-/// Render thread has run the tick and the Paint thread the recording of the frame it presents. For a test.+/// Hands the clock lanes of `host`'s document a pointer move to `x`, `y` in device pixels, with `buttons` held, beside the+/// mouse event with the input event id `input_event_id`, or none for 0, ticks them at `frame_time_nanoseconds`, and waits+/// until the Render thread has run the tick and the Paint thread the recording of the frame it presents. For a test.#[unsafe(no_mangle)]pub extern "C" fn document_host_inject_pointer(host: &crate::render_state::DocumentHost,x: f32,y: f32,+ buttons: u32,frame_time_nanoseconds: i64,input_event_id: u64,) {@@ -1573,7 +1644,7 @@ pub extern "C" fn document_host_inject_pointer(host.clock_ticks().inject_pointer(PendingPointer {position: Some(FloatPoint { x, y }),- buttons: 0,+ buttons,scrolled_since_frame: false,input_event_id,},diff --git a/Libraries/LibWeb/Rust/src/render_state/clock/lane.rs b/Libraries/LibWeb/Rust/src/render_state/clock/lane.rsindex f231162f861..5ea544c5f7f 100644--- a/Libraries/LibWeb/Rust/src/render_state/clock/lane.rs+++ b/Libraries/LibWeb/Rust/src/render_state/clock/lane.rs@@ -197,6 +197,19 @@ fn with_slot<R>(document: DocumentId, job: impl FnOnce(&mut LaneSlot) -> R) -> O.flatten()}+/// The nodes the selection in the fork of the lane that follows the presented frame of `document` highlights. For a test.+pub(in crate::render_state) fn selection_shown_for_testing(+ document: DocumentId,+) -> Option<Vec<super::selection::SelectionRowForTesting>> {+ with_slot(document, |slot| {+ match slot.lanes.current_ref().map(|lane| &lane.state) {+ Some(super::LaneState::Forked { fork, .. }) => Some(super::selection::rows_for_testing(fork)),+ _ => None,+ }+ })+ .flatten()+}+/// On the render owner: notes that it sampled a frame of the document `ticks` belong to, whose lane starts once the/// frame is presented, and answers what hands the lane its pieces then.pub(in crate::render_state) fn note_sampled(ticks: &Arc<ClockTicks>) -> LaneDelivery {@@ -504,7 +517,18 @@ impl LaneSlot {return;}let samples_animations = !self.ticks.animations_held.load(Ordering::Relaxed);- let pointer = self.ticks.pointer_state().take();+ // NB: Beside an idle event loop the host gets to the move of a drag at once, and paints it itself. The move waits+ // until then, as a task that begins first keeps the host from it.+ let host_paints_the_drag = !samples_animations+ && self+ .lanes+ .current_ref()+ .is_some_and(|lane| lane.selection_drag().is_some())+ && self.ticks.pointer_state().holds_the_primary_button();+ let pointer = match host_paints_the_drag {+ true => None,+ false => self.ticks.pointer_state().take(),+ };if let Lanes::Newest(lane) = &mut self.lanes&& !lane.needs_render_state(){diff --git a/Libraries/LibWeb/Rust/src/render_state/clock/selection.rs b/Libraries/LibWeb/Rust/src/render_state/clock/selection.rsnew file mode 100644index 00000000000..c9339a7bc49--- /dev/null+++ b/Libraries/LibWeb/Rust/src/render_state/clock/selection.rs@@ -0,0 +1,588 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! A clock lane's drag selection: while the host runs a task, the highlight of a drag that selects text follows the+//! pointer in the frames the lane presents, so a busy page keeps up with the mouse.+//!+//! The press stays the host's, which alone knows whether the page lets the drag start, and a rendering update after it+//! seals where the selection is anchored with the plan. A mouse move has no default action, so nothing the page does+//! keeps the drag from going on, and a tick can show where it goes before the host gets to the move.+//!+//! The lane paints and decides nothing else. What a tick shows goes with the lane's fork, the selection stays the+//! host's, and the host makes its own selection as it handles the same moves, in the frame that takes over from the+//! lane's. What a tick shows includes the `::selection` styles of the elements it reaches, which it styles in the fork.+//! A move the host would treat in a way only it can, such as one that `user-select: all` widens, is left to it,+//! and the highlight waits where it was. A word or paragraph selection, and a selection in a text control or an editing+//! host, are the host's altogether.++use super::{Lane, RenderState, hover};+use crate::css::css_pixels::{CssPixelPoint, CssPixels};+use crate::css::style::StyleEngine;+use crate::css::style::drag_selection::{MirrorNodeScopes, SelectionStyles, UsedUserSelect};+use crate::css::style::tree::StyleNodeID;+use crate::layout::LayoutNodeArena;+use crate::layout::node_data::{NodeFlag, NodeKind, NodeSlotId};+use crate::layout::svg_formatting_context::FfiFloatRect;+use crate::painting::hit_test::HitTestList;+use crate::painting::hit_test::caret::CaretPositionMode;+use crate::painting::hit_test::resolve::row_dom_style_node;+use crate::painting::host::{FfiCaretBoundaryKind, FfiHitTestQueryCallbacks, FfiNodeIdentity, FfiResolvedCaret};+use crate::painting::paint_read::GeometryRead;+use crate::painting::paintable_data::{+ FfiSelectionEntry, SELECTION_STATE_END, SELECTION_STATE_FULL, SELECTION_STATE_NONE, SELECTION_STATE_START,+ SELECTION_STATE_START_AND_END,+};+use crate::painting::selection::sync_selection_style;+use std::collections::{HashMap, HashSet};+use std::sync::Arc;++/// Where a drag selection the host started is anchored, sealed with the plan.+#[derive(Clone, Copy, Debug)]+pub(crate) struct SelectionDrag {+ anchor: Boundary,+ /// The scrollport the host's autoscroll keeps the pointer in as it selects, in CSS pixels of the viewport.+ scrollport: Option<FfiFloatRect>,+}++impl SelectionDrag {+ /// The drag anchored in the node `anchor` names, if it names one: `anchor_offset` code units into it where it is a+ /// text node, or right before its child `anchor_child` otherwise, or after its last child for 0. A `scrollport`+ /// without an area stands for none.+ pub(crate) fn new(anchor: u32, anchor_offset: usize, anchor_child: u32, scrollport: FfiFloatRect) -> Option<Self> {+ let node = StyleNodeID::from_raw(anchor)?;+ let anchor = match node.text_index() {+ Some(_) => Boundary::InText {+ node,+ offset: anchor_offset,+ },+ None => Boundary::InElement {+ container: node,+ child: StyleNodeID::from_raw(anchor_child),+ },+ };+ Some(Self {+ anchor,+ scrollport: (scrollport.width > 0.0 && scrollport.height > 0.0).then_some(scrollport),+ })+ }++ /// `point`, in CSS pixels of the viewport, as the host's `AutoScrollHandler::process` keeps it in the scrollport.+ fn constrained(self, x: f32, y: f32) -> (f32, f32) {+ let Some(scrollport) = self.scrollport else {+ return (x, y);+ };+ (+ x.clamp(scrollport.x, scrollport.x + scrollport.width - 1.0),+ y.clamp(scrollport.y, scrollport.y + scrollport.height - 1.0),+ )+ }+}++/// A boundary point in the DOM, among the nodes the style engine mirrors. Comments and processing instructions have no+/// place there, and no box to highlight.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(super) enum Boundary {+ InText {+ node: StyleNodeID,+ offset: usize,+ },+ /// Right before `child`, or after the last of the children of `container` for none.+ InElement {+ container: StyleNodeID,+ child: Option<StyleNodeID>,+ },+}++impl Boundary {+ /// The boundary point right before `node`.+ fn before(engine: &StyleEngine, node: StyleNodeID) -> Option<Self> {+ Some(Self::InElement {+ container: engine.drag_parent(node)?,+ child: Some(node),+ })+ }++ /// The boundary point right after `node`.+ fn after(engine: &StyleEngine, node: StyleNodeID) -> Option<Self> {+ Some(Self::InElement {+ container: engine.drag_parent(node)?,+ child: engine.drag_next_sibling(node),+ })+ }++ /// The node of the boundary point.+ fn container(self) -> StyleNodeID {+ match self {+ Self::InText { node, .. } => node,+ Self::InElement { container, .. } => container,+ }+ }++ /// Whether this boundary point comes before `other`, in the tree they share, as+ /// `position_of_boundary_point_relative_to_other_boundary_point` decides it.+ fn precedes(self, engine: &StyleEngine, other: Self) -> bool {+ let (container, other_container) = (self.container(), other.container());+ // The child of `ancestor` that holds `node`.+ let holder_of = |node, ancestor| {+ std::iter::successors(Some(node), |&node| engine.drag_parent(node))+ .find(|&node| engine.drag_parent(node) == Some(ancestor))+ };+ let child_of = |boundary| match boundary {+ Self::InText { .. } => None,+ Self::InElement { child, .. } => child,+ };+ match (self, other) {+ _ if container == other_container => match (self, other) {+ (+ Self::InText { offset, .. },+ Self::InText {+ offset: other_offset, ..+ },+ ) => offset < other_offset,+ (Self::InElement { child: Some(child), .. }, Self::InElement { child: other_child, .. }) => {+ other_child.is_none_or(|other_child| engine.drag_precedes(child, other_child))+ }+ _ => false,+ },+ _ if engine.drag_is_inclusive_ancestor(container, other_container) => {+ let (Some(child), Some(holder)) = (child_of(self), holder_of(other_container, container)) else {+ return false;+ };+ child == holder || engine.drag_precedes(child, holder)+ }+ _ if engine.drag_is_inclusive_ancestor(other_container, container) => {+ let (Some(other_child), Some(holder)) = (child_of(other), holder_of(container, other_container)) else {+ return child_of(other).is_none();+ };+ engine.drag_precedes(holder, other_child)+ }+ _ => engine.drag_precedes(container, other_container),+ }+ }+}++/// A node a selection highlights: its style node, its selection state, where the selection starts and ends, and the+/// background and text colors its `::selection` styles give it, as ARGB, zero for none. For a test.+pub(in crate::render_state) type SelectionRowForTesting = (u32, u8, usize, usize, u32, u32);++/// The background and text colors the `::selection` styles of `row` give it, as ARGB, zero for none.+fn selection_colors_for_testing(arena: &LayoutNodeArena, row: NodeSlotId) -> (u32, u32) {+ let styles = &arena.paint_state().selection_pseudo_styles;+ let element_row = std::iter::successors(arena.node_parent_if_live(row), |&row| arena.node_parent_if_live(row))+ .find(|&row| arena.node_flags_if_live(row) & NodeFlag::Anonymous as u32 == 0);+ styles+ .get(&row)+ .or_else(|| element_row.and_then(|row| styles.get(&row)))+ .map_or((0, 0), |answer| {+ let text = answer.facts.text_color;+ (+ answer.facts.background_color.0,+ if text.has_value { text.value.0 } else { 0 },+ )+ })+}++/// The nodes the selection of `state` highlights, in the order of their style nodes. For a test.+pub(super) fn rows_for_testing(state: &RenderState) -> Vec<SelectionRowForTesting> {+ let arena = state.arena.arena();+ let Some(selection) = arena.paint_state().selection.clone() else {+ return Vec::new();+ };+ let texts = selection+ .text_states+ .iter()+ .map(|(&row, &state)| (row, row_dom_style_node(arena, row), state));+ let boxes = selection+ .boxes_with_selection_state+ .iter()+ .filter(|&&row| arena.paintable_row_is_populated(row))+ .map(|&row| {+ (+ row,+ row_dom_style_node(arena, row),+ arena.paintable_data(row).selection_state,+ )+ });+ let mut rows: Vec<_> = texts+ .chain(boxes)+ .filter(|&(_, node, state)| node != 0 && state != SELECTION_STATE_NONE)+ .map(|(row, node, state)| {+ let (background, text) = selection_colors_for_testing(arena, row);+ (+ node,+ state,+ selection.start_offset,+ selection.end_offset,+ background,+ text,+ )+ })+ .collect();+ rows.sort_unstable();+ rows.dedup();+ rows+}++/// Why a tick left a move of a drag to the host.+struct LeftToHost(&'static str);++/// The boundary point of the caret position `caret` as the focus of a drag anchored at `anchor`, with the node the caret+/// stands at, as `choose_caret_boundary_for_selection_focus` decides it: an atomic box has a caret position on both of+/// its sides, of which the focus takes the one away from the anchor.+fn focus_at(+ engine: &StyleEngine,+ caret: &FfiResolvedCaret,+ anchor: Boundary,+) -> Result<(Boundary, StyleNodeID), LeftToHost> {+ const OUTSIDE_OF_A_TREE: LeftToHost = LeftToHost("a boundary outside of a tree");+ if caret.node.is_document {+ return Err(LeftToHost("a boundary in the document"));+ }+ let node = StyleNodeID::from_raw(caret.node.style_node).ok_or(LeftToHost("a boundary in no node"))?;+ let focus = match caret.boundary {+ FfiCaretBoundaryKind::Offset if node.text_index().is_some() => Boundary::InText {+ node,+ offset: caret.offset,+ },+ // NB: The offset counts the comments the mirror does not hold.+ FfiCaretBoundaryKind::Offset => return Err(LeftToHost("a boundary among the children of an element")),+ FfiCaretBoundaryKind::IndexOfNodeInParent => Boundary::before(engine, node).ok_or(OUTSIDE_OF_A_TREE)?,+ FfiCaretBoundaryKind::BeforeNode | FfiCaretBoundaryKind::AfterNode => {+ let before = Boundary::before(engine, node).ok_or(OUTSIDE_OF_A_TREE)?;+ let after = Boundary::after(engine, node).ok_or(OUTSIDE_OF_A_TREE)?;+ if engine.drag_root(node) != engine.drag_root(anchor.container()) {+ match caret.boundary {+ FfiCaretBoundaryKind::BeforeNode => before,+ _ => after,+ }+ } else if anchor.precedes(engine, before) {+ after+ } else if after.precedes(engine, anchor) {+ before+ } else {+ match caret.boundary {+ FfiCaretBoundaryKind::BeforeNode => before,+ _ => after,+ }+ }+ }+ };+ Ok((focus, node))+}++/// The boundary point the host's `set_user_selection` leaves the focus `focus` at `node` of a drag anchored at `anchor`+/// on: a focus at a node whose `user-select` is `none` moves out of the outermost element of that value, to the side of it+/// that faces the anchor. What `all` and a `contain` element do to a selection stays with the host.+fn focus_after_user_select(+ engine: &StyleEngine,+ focus: Boundary,+ node: StyleNodeID,+ anchor: Boundary,+) -> Result<Boundary, LeftToHost> {+ let (container, anchor_container) = (focus.container(), anchor.container());+ if engine.drag_root(container) != engine.drag_root(anchor_container) {+ return Err(LeftToHost("a focus in another tree"));+ }+ let common = std::iter::successors(Some(anchor_container), |&node| engine.drag_parent(node))+ .find(|&node| engine.drag_is_inclusive_ancestor(node, container));+ for start in [anchor_container, container] {+ let contained = std::iter::successors(Some(start), |&node| engine.drag_parent(node))+ .take_while(|&node| Some(node) != common)+ .filter(|node| node.element_index().is_some())+ .any(|element| engine.drag_used_user_select(element) == UsedUserSelect::Contain);+ if contained {+ return Err(LeftToHost("a user-select: contain between the anchor and the focus"));+ }+ }+ // NB: The host asks the node of the boundary point, which for an atomic box is its parent, and the box where that+ // node has no box of its own.+ let decides = match engine.drag_has_no_box_of_its_own(container) {+ true => node,+ false => container,+ };+ let used = engine+ .drag_style_element(decides)+ .map_or(UsedUserSelect::None, |element| engine.drag_used_user_select(element));+ match used {+ UsedUserSelect::All => Err(LeftToHost("a focus user-select: all widens")),+ UsedUserSelect::None if container == anchor_container => {+ Err(LeftToHost("a focus user-select: none keeps at the anchor"))+ }+ UsedUserSelect::None => {+ let is_none = |node: &StyleNodeID| {+ node.element_index().is_some() && engine.drag_used_user_select(*node) == UsedUserSelect::None+ };+ let outermost = std::iter::successors(engine.drag_parent(container), |&node| engine.drag_parent(node))+ .take_while(is_none)+ .last()+ .unwrap_or(container);+ match engine.drag_precedes(outermost, anchor_container) {+ true => Boundary::after(engine, outermost),+ false => Boundary::before(engine, outermost),+ }+ .ok_or(LeftToHost("a focus user-select: none moves out of the tree"))+ }+ UsedUserSelect::Text | UsedUserSelect::Contain => Ok(focus),+ }+}++/// The highlight of a range, as `DocumentPaintState::recompute_selection_states` makes it.+struct Highlight<'a> {+ engine: &'a StyleEngine,+ arena: &'a LayoutNodeArena,+ selection_styles: &'a SelectionStyles,+ used_user_select: HashMap<StyleNodeID, UsedUserSelect>,+ entries: Vec<FfiSelectionEntry>,+ /// The elements of the entries whose rows have yet to get their `::selection` styles.+ unstyled: HashSet<StyleNodeID>,+}++impl Highlight<'_> {+ /// Whether `node` is left out of the selection, as `user-select: none` and inertness do.+ fn excludes(&mut self, node: StyleNodeID) -> bool {+ if self.engine.drag_is_inert(node) {+ return true;+ }+ if self.arena.bound_row(node).is_invalid() {+ return false;+ }+ let Some(element) = self.engine.drag_style_element(node) else {+ return true;+ };+ let engine = self.engine;+ *self+ .used_user_select+ .entry(element)+ .or_insert_with(|| engine.drag_used_user_select(element))+ == UsedUserSelect::None+ }++ fn mark(&mut self, node: StyleNodeID, state: u8) {+ if self.excludes(node) {+ return;+ }+ let layout_node = self.arena.bound_row(node);+ if !layout_node.is_invalid() {+ self.entries.push(FfiSelectionEntry {+ is_text_node_entry: node.text_index().is_some(),+ layout_node,+ state,+ });+ if let Some(element) = self.engine.drag_style_element(node)+ && self.selection_styles.owes(element)+ {+ self.unstyled.insert(element);+ }+ }+ }++ /// Marks the nodes of the range from `start` to `end`, as `for_each_node_in_highlight_range` does.+ fn mark_range(&mut self, start: Boundary, end: Boundary) {+ let engine = self.engine;+ if start == end {+ return;+ }+ let (start_container, end_container) = (start.container(), end.container());+ if start_container == end_container && start_container.text_index().is_some() {+ self.mark(start_container, SELECTION_STATE_START_AND_END);+ return;+ }+ let start_at = match start {+ Boundary::InText { node, .. } => {+ self.mark(node, SELECTION_STATE_START);+ engine.drag_next_in_pre_order_within(node, end_container)+ }+ Boundary::InElement { container, child } => {+ self.mark(container, SELECTION_STATE_FULL);+ child.or_else(|| engine.drag_next_after_subtree(container, end_container))+ }+ };+ let stop_at = match end {+ Boundary::InText { .. } => None,+ Boundary::InElement { child, .. } => child,+ };+ let mut next = start_at;+ while let Some(node) = next {+ if Some(node) == stop_at || (node == end_container && !engine.drag_has_children(node)) {+ break;+ }+ self.mark(node, SELECTION_STATE_FULL);+ next = engine.drag_next_in_pre_order_within(node, end_container);+ }+ if let Boundary::InText { node, .. } = end {+ self.mark(node, SELECTION_STATE_END);+ }+ }+}++impl Lane {+ /// The drag selection the lane follows, if any.+ pub(super) fn selection_drag(&self) -> Option<SelectionDrag> {+ self.plan.hover.as_ref()?.selection_drag()+ }++ /// Has the highlight the ticks show follow nothing more: the button went up, and a press after it is the host's.+ pub(super) fn end_selection_drag(&mut self) {+ if let Some(plan) = &mut self.plan.hover {+ plan.end_selection_drag();+ }+ self.selection_hit_test_list = None;+ self.selection_styles = None;+ }++ /// Has the highlight of the drag follow `pointer`, in the frame as the screen shows it at `frame_time_nanoseconds`,+ /// and answers whether that moved anything to present.+ pub(super) fn extend_selection(+ &mut self,+ state: &mut RenderState,+ pointer: hover::PendingPointer,+ frame_time_nanoseconds: i64,+ ) -> bool {+ let Some(drag) = self.selection_drag() else {+ return false;+ };+ let started = std::time::Instant::now();+ let moved = self.show_selection_at(state, drag, pointer, frame_time_nanoseconds);+ if hover::logs_hover() {+ let outcome = match &moved {+ Ok(true) => "extended",+ Ok(false) => "unmoved",+ Err(LeftToHost(reason)) => reason,+ };+ eprintln!(+ "{} hover lane: drag to {:?}: {outcome} in {} us",+ hover::log_time(),+ pointer.position,+ started.elapsed().as_micros()+ );+ }+ moved.unwrap_or(false)+ }++ fn show_selection_at(+ &mut self,+ state: &mut RenderState,+ drag: SelectionDrag,+ pointer: hover::PendingPointer,+ frame_time_nanoseconds: i64,+ ) -> Result<bool, LeftToHost> {+ let plan = self.plan.hover.take().ok_or(LeftToHost("no plan"))?;+ let shown = self.show_selection_with(state, &plan, drag, pointer, frame_time_nanoseconds);+ self.plan.hover = Some(plan);+ shown+ }++ fn show_selection_with(+ &mut self,+ state: &mut RenderState,+ plan: &hover::HoverPlan,+ drag: SelectionDrag,+ pointer: hover::PendingPointer,+ frame_time_nanoseconds: i64,+ ) -> Result<bool, LeftToHost> {+ let position = pointer.position.ok_or(LeftToHost("the pointer left the document"))?;+ // A scroll of the compositor's since the frame moved what is under the pointer, which only a tick that said where+ // it scrolled to tells, and the scrollport the plan sealed along with it.+ if pointer.scrolled_since_frame && (self.scroll_offsets.is_empty() || drag.scrollport.is_some()) {+ return Err(LeftToHost("scrolled since the frame"));+ }+ let (tree, published) = self+ .presented_hit_test_items(state, frame_time_nanoseconds)+ .map_err(LeftToHost)?;+ let arena = state.arena.arena();+ let engine = state.engine_ref();+ // NB: The caret lines take a walk over every item, which a drag need not repeat over the same frame.+ let list = self+ .selection_hit_test_list+ .take()+ .filter(|list| Arc::ptr_eq(&list.items, &published.items))+ .unwrap_or_else(|| {+ let mut list = HitTestList {+ items: Arc::clone(&published.items),+ ..HitTestList::default()+ };+ list.build_spatial_indexes_if_needed();+ list.build_caret_lines_if_needed(arena);+ list+ });+ let scroll_offsets = self.scroll_offsets_on_screen(arena, &arena.paint_state().visual_context, plan);+ let list = self.selection_hit_test_list.insert(list);+ let callbacks = FfiHitTestQueryCallbacks::sealed(+ plan.device_pixels_per_css_pixel(),+ &scroll_offsets,+ plan.chrome_metrics(),+ );+ let pixel_ratio = plan.device_pixels_per_css_pixel() as f32;+ let css_point =+ |x, y| CssPixelPoint::new(CssPixels::nearest_value_for_f32(x), CssPixels::nearest_value_for_f32(y));+ let (x, y) = (position.x / pixel_ratio, position.y / pixel_ratio);+ // The host hands a move over the content of another navigable to it, and the selection here stays as it is.+ let over_a_frame = list+ .find_topmost_item(arena, &tree, &callbacks, css_point(x, y))+ .and_then(|topmost| arena.node_kind_if_live(list.items[topmost.index].paintable))+ == Some(NodeKind::NavigableContainerViewport);+ if over_a_frame {+ return Err(LeftToHost("the content of another navigable"));+ }+ let (x, y) = drag.constrained(x, y);+ let caret = list+ .caret_position_from_point(+ &MirrorNodeScopes(engine),+ arena,+ &tree,+ &callbacks,+ css_point(x, y),+ CaretPositionMode::Selection,+ FfiNodeIdentity::default(),+ )+ .filter(|caret| caret.caret.has_position)+ .ok_or(LeftToHost("no caret position"))?;+ let (focus, focus_node) = focus_at(engine, &caret.caret, drag.anchor)?;+ let focus = focus_after_user_select(engine, focus, focus_node, drag.anchor)?;+ if self.selection_focus_shown == Some(focus) {+ return Ok(false);+ }+ let (start, end) = match focus.precedes(engine, drag.anchor) {+ true => (focus, drag.anchor),+ false => (drag.anchor, focus),+ };+ let selection_styles = self.selection_styles.get_or_insert_with(|| SelectionStyles::of(engine));+ let mut highlight = Highlight {+ engine,+ arena,+ selection_styles,+ used_user_select: HashMap::new(),+ entries: Vec::new(),+ unstyled: HashSet::new(),+ };+ highlight.mark_range(start, end);+ let Highlight { entries, unstyled, .. } = highlight;+ let engine = state.engine_mut();+ let records = unstyled+ .into_iter()+ .map(|element| Some((element, engine.demand_selection_record(element)?)))+ .collect::<Option<Vec<_>>>()+ .ok_or(LeftToHost("a ::selection style the host resolves"))?;+ let offset_in = |boundary| match boundary {+ Boundary::InText { offset, .. } => offset,+ Boundary::InElement { .. } => 0,+ };+ let arena = state.arena.arena_mut();+ for (element, record) in records {+ sync_selection_style(arena, element, record);+ selection_styles.note_styled(element);+ }+ let selection = crate::painting::selection::apply(+ &mut arena.paintable_rows_mut(),+ &entries,+ offset_in(start),+ offset_in(end),+ );+ arena.paint_state_mut().selection = Some(Arc::new(selection));+ self.selection_focus_shown = Some(focus);+ Ok(true)+ }+}diff --git a/Services/Compositor/ContextState.cpp b/Services/Compositor/ContextState.cppindex 95b764a37dd..a4c033cbd12 100644--- a/Services/Compositor/ContextState.cpp+++ b/Services/Compositor/ContextState.cpp@@ -102,8 +102,9 @@ void ContextState::dispatch_mouse_event_to_web_content(Web::MouseEvent const& ev// The render clock hears where the pointer went too, without waiting for WebContent's main thread, so that hover// can follow the pointer while that thread runs a task. The lanes hit test it in the frames on screen, which a- // scroll since, here or in a nested context, has moved.- if (event.type == Web::MouseEvent::Type::MouseMove)+ // scroll since, here or in a nested context, has moved. A button going up ends the drag a lane follows, whether or+ // not a move comes after it.+ if (event.type == Web::MouseEvent::Type::MouseMove || event.type == Web::MouseEvent::Type::MouseUp)m_web_content_client.pointer_moved(m_context_id, event.position, to_underlying(event.buttons), scrolled_since_last_frame() || nested_context_scrolled_since_last_frame, event.id);else if (event.type == Web::MouseEvent::Type::MouseLeave)m_web_content_client.pointer_left(m_context_id, event.id);diff --git a/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-beside-a-busy-task.txt b/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-beside-a-busy-task.txtnew file mode 100644index 00000000000..b1ccfc8b6bd--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-beside-a-busy-task.txt@@ -0,0 +1,2 @@+script saw nothing during the task: true+the host paints what the lane showed: truediff --git a/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-beside-a-task.txt b/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-beside-a-task.txtnew file mode 100644index 00000000000..3f3207bec70--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-beside-a-task.txt@@ -0,0 +1,8 @@+selection before the tick: ""+selection after the tick: ""+the lane shows something: true+the host paints nothing new: true+selection changes from the lane: 0+selection after the host handled the move: "irst line of plain text\nsecond line of "+the host paints what the lane showed: true+a drag ends when the button goes up: truediff --git a/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-matches-the-host.txt b/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-matches-the-host.txtnew file mode 100644index 00000000000..7e6bf7a5678--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-matches-the-host.txt@@ -0,0 +1,125 @@+same: "st"+same: " line of plain te"+same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | line of plain text | some | bold | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the very"+same: "<P> | <B> | <I> | line of plain text | some | bold | and | ita"+same: "e very"+same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | f plain text | some | bold | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the very"+same: "<P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | d | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the very"+same: "<IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | s | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the very"+same: "<B> | e | bold | and"+same: "<B> | <I> | <U> | e | bold | and | italic | underlin"+same: "<B> | <I> | <U> | <P> | e | bold | and | italic | underlined | text | text | ar"+same: "around | co"+same: "<P> | <SPAN> | <P> | mments | words | in a block | before | aft"+same: "<P> | <B> | <I> | <U> | <P> | text | some | bold | and | italic | underlined | text | text | around | co"+same: "<P> | k | before"+same: "<SPAN> | <P> | ords | in a block | before"+same: "<P> | k | before"+same: "<SPAN> | ords | in a bloc"+same: "efore | afte"+same: "<P> | efore | after | kept | kept ag"+same: "ept "+same: "ept | kept ag"+same: "<P> | <SPAN> | <P> | <SPAN> | <P> | ept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside content"+same: "<P> | kept agai"+same: "<P> | kept agai"+same: "ept | kept agai"+same: "ept "+same: "<P> | <SPAN> | <P> | <SPAN> | <P> | ept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside content"+same: "ept "+same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | line of plain text | some | bold | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept "+same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | line of plain text | some | bold | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept ag"+same: "<P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the"+same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | f plain text | some | bold | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the"+same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | line of plain text | some | bold | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer "+same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | line of plain text | some | bold | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer aga"+same: "<P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | outer again | words | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the"+same: "<P> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the"+same: "<A> | rds | around | boxes "+same: "<A> | <IMG> | rds | around | boxes | en"+left to the host: "<SPAN> | round | all of this"+same: "<SPAN> | round | all of this | the elem"+same: "<SPAN> | <P> | <SPAN> | <P> | round | all of this | the element | outside | kept in here | again outside | outer | inside content"+same: "<SPAN> | all of this"+same: "<SPAN> | all of this | the eleme"+same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | f plain text | some | bold | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept again | around "+left to the host: "utside "+same: "<SPAN> | utside | kept in here | again outsi"+same: "n her"+left to the host: "n here"+left to the host: "<SPAN> | kept i"+same: "ter | inside content"+same: "ter | inside contents | outer a"+same: "<IMG> | ords "+same: "<IMG> | ords "+same: "<IMG> | ords | more wor"+same: "<P> | <IMG> | more wor"+same: "<P> | <IMG> | more wor"+same: "<IMG> | ords | more wor"+same: ""+same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | st line of plain text | some | bold | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light"+same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | st line of plain text | some | bold | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left c"+same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | st line of plain text | some | bold | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell"+same: "<TD> | cell | right cell"+same: "<TD> | <P> | cell | right cell | שלום "+same: "<TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the very"+same: ""+same: "<TD> | <P> | | right cell | שלום עול"+same: "ted text"+same: "ted text | text around t"+same: "<P> | ted text | text around the float | text moved by"+same: "moved by a tran"+same: "<DIV> | moved by a transform | placed out of "+same: "<DIV> | <P> | moved by a transform | placed out of the flow | text afte"+same: " out of the flow"+same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | f plain text | some | bold | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed"+same: "<P> | <P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | out of the flow | text after generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the very"+same: "text afte"+same: "r generated con"+same: "<P> | r generated content | one line | anoth"+same: "n"+same: "<P> | <SPAN> | other line | words | in a block"+same: "ock"+same: "<SPAN> | ords | in a bl"+same: "ock | more wor"+same: ""+same: "<P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the very"+same: "<P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the"+same: "<P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | r generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the"+same: ""+same: ""+same: ""+same: ""+same: ""+same: ""+same: "<P> | around | boxes "+same: "<A> | rds "+same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | f plain text | some | bold | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words "+same: "<P> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the very"+same: "<A> | rds "+same: "<A> | rds | around "+same: "<A> | <IMG> | rds | around | boxes | e"+same: "<P> | <A> | ock | more words | words | around "+same: "with a selection (rgb(255, 0, 0) on rgb(255, 255, 0))"+same: "<P> | <A> | with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | "+same: "<A> | fore | the lin"+same: "<A> | <A> | fore | the link text | after | a link to dr"+same: "<A> | <A> | fore | the link text | after | a link to dr"+same: ""+same: ""+same: ""+same: ""+same: ""+same: ""+same: ""+same: "<BODY> | <svg> | <text> | <P> | text of a vector | the very"+same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | first line of plain text | some | bold | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the"+same: " very last line"+same: "<P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the"+same: "<P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the"+same: "olled line "+same: "<P> | olled line two | scrolled l"+same: "<P> | e one | scr"+same: "<P> | olled line two | scrolled "+same: "<I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | old | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the very last line"+same: "<I> | <U> | <P> | <P> | <SPAN> | old | and | italic | underlined | text | text | around | comments | words | in a block"diff --git a/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-shows-selection-styles.txt b/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-shows-selection-styles.txtnew file mode 100644index 00000000000..ba5583f9bcd--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-shows-selection-styles.txt@@ -0,0 +1,9 @@+no rule: same: "xt no rule "+a rule: same: "xt a rule s (rgb(255, 0, 0) on rgb(255, 255, 0))"+into a rule: same: "<P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | xt no rule styles | text a rule s (rgb(255, 0, 0) on rgb(255, 255, 0))"+past a rule: same: "<P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <DIV> (rgb(255, 255, 255) on rgb(0, 128, 0)) | <SPAN> (rgb(255, 255, 255) on rgb(0, 128, 0)) | xt no rule styles | text a rule styles (rgb(255, 0, 0) on rgb(255, 255, 0)) | te (rgb(255, 255, 255) on rgb(0, 128, 0))"+an inherited style: same: "xt that inh (rgb(255, 255, 255) on rgb(0, 128, 0))"+a shadow tree's rule: same: "xt in a sha (rgb(255, 255, 255) on rgb(128, 0, 128))"+a rule that came later: same: "xt the rule (rgb(0, 0, 255) on rgb(255, 192, 203))"+a rule that went away: same: "xt the rule"+a rule of a long sheet: same: "xt the rule (rgb(0, 0, 255) on rgb(255, 192, 203))"diff --git a/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-stays-with-the-host.txt b/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-stays-with-the-host.txtnew file mode 100644index 00000000000..548a0fbb2ff--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-stays-with-the-host.txt@@ -0,0 +1,7 @@+characters of the page: followed+words of the page: left to the host+paragraphs of the page: left to the host+an input element: left to the host+a textarea: left to the host+an editing host: left to the host+a cancelled selectstart: left to the hostdiff --git a/Tests/LibWeb/Text/input/HTML/frame-in-flight/clock-lane-drag-selection-beside-a-busy-task.html b/Tests/LibWeb/Text/input/HTML/frame-in-flight/clock-lane-drag-selection-beside-a-busy-task.htmlnew file mode 100644index 00000000000..e138ae50ef3--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/frame-in-flight/clock-lane-drag-selection-beside-a-busy-task.html@@ -0,0 +1,33 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<script src="frame-in-flight.js"></script>+<style>+ body { margin: 0; font: 20px SerenitySans, sans-serif; line-height: 30px; }+ p { margin: 0; height: 30px; width: max-content; white-space: nowrap; }+</style>+<p id="line">a line of plain text to drag over</p>+<script>+ // A drag goes through the UI process and the compositor to the clock lane while a task keeps the event loop from it.+ // The task ends once the lane showed the move, which the host then handles to the same highlight.+ asyncTest(async done => {+ const rect = line.getBoundingClientRect();+ const y = Math.round(rect.top + rect.height / 2);+ const [from, to] = [Math.round(rect.left + 10), Math.round(rect.left + 150)];+ await internals.mouseEventThroughUIProcess("mousemove", from, y);+ await internals.mouseEventThroughUIProcess("mousedown", from, y, { buttons: 1 });+ await twoFramesLanded();++ const moved = internals.mouseEventThroughUIProcess("mousemove", to, y, { buttons: 1 });+ let shown;+ do shown = internals.presentedSelection();+ while (shown === "");+ const selectionDuringTheTask = getSelection().toString();+ await moved;+ await twoFramesLanded();++ println(`script saw nothing during the task: ${selectionDuringTheTask === ""}`);+ println(`the host paints what the lane showed: ${internals.paintedSelection() === shown}`);+ await internals.mouseEventThroughUIProcess("mouseup", to, y);+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/HTML/frame-in-flight/clock-lane-drag-selection-beside-a-task.html b/Tests/LibWeb/Text/input/HTML/frame-in-flight/clock-lane-drag-selection-beside-a-task.htmlnew file mode 100644index 00000000000..f5b2ff3530c--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/frame-in-flight/clock-lane-drag-selection-beside-a-task.html@@ -0,0 +1,61 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<script src="frame-in-flight.js"></script>+<style>+ body { margin: 0; font: 20px SerenitySans, sans-serif; line-height: 30px; }+ p { margin: 0; height: 30px; white-space: nowrap; }+</style>+<p id="first">first line of plain text</p>+<p id="second">second line of plain text</p>+<script>+ // A lane paints a drag selection beside a task, and script keeps seeing only the selection of the host: the task+ // reads the same selection before and after the lane showed the move, and no selectionchange comes from the lane.+ asyncTest(async done => {+ let selectionChanges = 0;+ document.addEventListener("selectionchange", () => ++selectionChanges);+ const rect = first.getBoundingClientRect();+ internals.mouseDown(rect.left + 5, rect.top + 15);+ await twoFramesLanded();+ const changesBefore = selectionChanges;++ const seen = await whileLaneHovers(frameTime => {+ const before = getSelection().toString();+ internals.injectHoverPointer(rect.left + 150, rect.top + 45, frameTime + 16, 0, 1);+ return {+ before,+ after: getSelection().toString(),+ shown: internals.presentedSelection(),+ painted: internals.paintedSelection(),+ };+ });+ println(`selection before the tick: ${JSON.stringify(seen.before)}`);+ println(`selection after the tick: ${JSON.stringify(seen.after)}`);+ println(`the lane shows something: ${seen.shown.length > 0}`);+ println(`the host paints nothing new: ${seen.painted === ""}`);+ await twoFramesLanded();+ println(`selection changes from the lane: ${selectionChanges - changesBefore}`);++ // The host handles the same move in its own time, and takes over from the lane.+ internals.mouseMove(rect.left + 150, rect.top + 45, 0, 1);+ await twoFramesLanded();+ println(`selection after the host handled the move: ${JSON.stringify(getSelection().toString())}`);+ println(`the host paints what the lane showed: ${internals.paintedSelection() === seen.shown}`);+ internals.mouseUp(rect.left + 150, rect.top + 45);+ await twoFramesLanded();++ // The lane hears the button go up before the host does, and a later press is the host's to start.+ internals.mouseDown(rect.left + 5, rect.top + 15);+ await twoFramesLanded();+ const shownBesideARelease = await whileLaneHovers(frameTime => {+ internals.injectHoverPointer(rect.left + 100, rect.top + 15, frameTime + 16, 0, 1);+ const shown = internals.presentedSelection();+ internals.injectHoverPointer(rect.left + 100, rect.top + 15, frameTime + 32, 0, 0);+ internals.injectHoverPointer(rect.left + 150, rect.top + 45, frameTime + 48, 0, 1);+ return shown === internals.presentedSelection();+ });+ internals.mouseUp(rect.left + 5, rect.top + 15);+ await twoFramesLanded();+ println(`a drag ends when the button goes up: ${shownBesideARelease}`);+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/HTML/frame-in-flight/clock-lane-drag-selection-matches-the-host.html b/Tests/LibWeb/Text/input/HTML/frame-in-flight/clock-lane-drag-selection-matches-the-host.htmlnew file mode 100644index 00000000000..aadd85cfb02--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/frame-in-flight/clock-lane-drag-selection-matches-the-host.html@@ -0,0 +1,182 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<script src="frame-in-flight.js"></script>+<style>+ body { margin: 0; font: 14px SerenitySans, sans-serif; line-height: 20px; }+ p { margin: 0; height: 20px; width: max-content; white-space: nowrap; }+ img { display: inline-block; width: 40px; height: 14px; background: blue; }+ table { border-collapse: collapse; }+ td { padding: 0; width: 200px; height: 20px; }+ #scroller { width: 300px; height: 40px; overflow: auto; }+ #floated { float: left; width: 120px; height: 20px; }+ #transformed { transform: translateX(40px); }+ #positioned { position: absolute; left: 400px; top: 0; width: 200px; height: 20px; }+ #commented-block { position: absolute; left: 400px; top: 20px; }+ #generated::before { content: "generated "; }+ #broken { height: 40px; }+ #inline-block { display: inline-block; width: 100px; height: 20px; }+ #empty { display: inline-block; width: 60px; height: 14px; }+ #styled::selection { color: red; background: yellow; }+ iframe { display: block; width: 200px; height: 20px; border: 0; }+ button { display: block; height: 20px; padding: 0; font: inherit; }+ svg { display: block; width: 300px; height: 20px; }+</style>+<p id="first">first line of plain text</p>+<p id="inline">some <b>bold</b> and <i>italic <u>underlined</u></i> text</p>+<p id="commented"><!-- a comment -->text <!-- another comment -->around<!-- and one more --> comments</p>+<p id="commented-block">words <span id="before-a-comment" style="display: inline-block">in a block</span><!-- a comment --></p>+<p id="hidden">before <span style="display: none">not rendered</span> after</p>+<p id="unselectable-child">kept <span id="none" style="user-select: none">left <b id="none-inside">out</b></span> kept again</p>+<p id="all-child">around <span id="all" style="user-select: all">all of this</span> the element</p>+<p id="contain-child">outside <span id="contain" style="user-select: contain">kept in here</span> again outside</p>+<p id="contents">outer <span style="display: contents">inside contents <img id="unselectable-in-contents" style="user-select: none" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="></span> outer again</p>+<p id="image">words <img id="picture" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="> more words</p>+<p id="host"></p>+<p id="slotted-host">light text</p>+<table><tr><td id="left">left cell</td><td id="right">right cell</td></tr></table>+<p id="right-to-left" dir="rtl">שלום עולם</p>+<div id="scroller"><p id="scrolled-one">scrolled line one</p><p id="scrolled-two">scrolled line two</p><p id="scrolled-three">scrolled line three</p><p id="scrolled-four">scrolled line four</p></div>+<p id="floated-around"><span id="floated">floated text</span> text around the float</p>+<p id="transformed">text moved by a transform</p>+<div id="positioned">placed out of the flow</div>+<p id="generated">text after generated content</p>+<p id="broken">one line<br>another line</p>+<p id="inline-block-around">words <span id="inline-block">in a block</span> more words</p>+<p id="anchors">words <a id="empty" href="#" draggable="false"></a> around <img id="unselectable-picture" style="user-select: none" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="> boxes <span style="user-select: none"><img id="selectable-picture" style="user-select: text" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="></span> end</p>+<p id="inert" inert>inert text in here</p>+<p id="styled">text with a selection style</p>+<p id="linked">before <a id="link" href="#" draggable="false">the link text</a> after <a id="draggable-link" href="#">a link to drag</a></p>+<iframe id="frame" srcdoc="<p style='margin: 0'>text in a frame</p>"></iframe>+<button id="button">text of a button</button>+<svg id="vector"><text id="vector-text" x="0" y="15">text of a vector</text></svg>+<p id="last">the very last line</p>+<script>+ document.getElementById("host").attachShadow({ mode: "open" }).innerHTML = "shadow text";+ document.getElementById("slotted-host").attachShadow({ mode: "open" }).innerHTML = "before <slot></slot> after";+ document.getElementById("scroller").scrollTop = 10;++ const place = (id, across = 0.5) => {+ const rect = document.getElementById(id).getBoundingClientRect();+ return [Math.round(rect.left + rect.width * across), Math.round(rect.top + rect.height / 2)];+ };++ // Where each drag starts, and the places it goes to, in order.+ const drags = [+ { from: place("first", 0.2), to: [place("first", 0.1), place("first", 0.9), place("last", 0.5), place("inline", 0.5)] },+ { from: place("last", 0.5), to: [place("last", 0.1), place("first", 0.5), place("commented", 0.5), place("image", 0.2)] },+ { from: place("inline", 0.1), to: [place("inline", 0.4), place("inline", 0.8), place("commented", 0.3)] },+ { from: place("commented", 0.7), to: [place("commented", 0.2), place("hidden", 0.8), place("first", 0.8)] },+ { from: place("hidden", 0.5), to: [place("before-a-comment", 0.95), place("commented-block", 0.05)] },+ { from: place("before-a-comment", 0.95), to: [place("hidden", 0.5), place("commented-block", 0.05)] },+ { from: place("hidden", 0.1), to: [place("hidden", 0.9), place("unselectable-child", 0.9)] },+ { from: place("unselectable-child", 0.05), to: [place("none", 0.5), place("unselectable-child", 0.9), place("contents", 0.5)] },+ { from: place("unselectable-child", 0.95), to: [place("none", 0.5), place("none-inside", 0.5), place("unselectable-child", 0.05)] },+ { from: place("unselectable-child", 0.05), to: [place("none-inside", 0.5), place("contents", 0.5), place("none", 0.5)] },+ { from: place("first", 0.2), to: [place("none-inside", 0.5), place("unselectable-child", 0.9)] },+ { from: place("last", 0.2), to: [place("none", 0.5), place("first", 0.5)] },+ { from: place("first", 0.2), to: [place("unselectable-in-contents", 0.5), place("contents", 0.95)] },+ { from: place("last", 0.2), to: [place("unselectable-in-contents", 0.5), place("selectable-picture", 0.5)] },+ { from: place("anchors", 0.05), to: [place("selectable-picture", 0.5), place("anchors", 0.98)] },+ { from: place("all-child", 0.05), to: [place("all", 0.5), place("all-child", 0.9), place("contents", 0.5)] },+ { from: place("all", 0.5), to: [place("all", 0.9), place("all-child", 0.95), place("first", 0.5)] },+ { from: place("contain-child", 0.05), to: [place("contain", 0.5), place("contain-child", 0.95)] },+ { from: place("contain", 0.5), to: [place("contain", 0.9), place("contain-child", 0.95), place("first", 0.5)] },+ { from: place("contents", 0.05), to: [place("contents", 0.5), place("contents", 0.9)] },+ { from: place("image", 0.05), to: [place("picture", 0.1), place("picture", 0.9), place("image", 0.9)] },+ { from: place("image", 0.9), to: [place("picture", 0.9), place("picture", 0.1), place("image", 0.05)] },+ { from: place("first", 0.1), to: [place("host", 0.05), place("slotted-host", 0.5), place("left", 0.2), place("right", 0.5)] },+ { from: place("left", 0.1), to: [place("right", 0.5), place("right-to-left", 0.5), place("last", 0.5)] },+ { from: place("right-to-left", 0.9), to: [place("right-to-left", 0.95), place("left", 0.5)] },+ { from: place("floated", 0.2), to: [place("floated", 0.8), place("floated-around", 0.8), place("transformed", 0.5)] },+ { from: place("transformed", 0.2), to: [place("transformed", 0.8), place("positioned", 0.5), place("generated", 0.5)] },+ { from: place("positioned", 0.2), to: [place("positioned", 0.8), place("first", 0.5), place("last", 0.5)] },+ { from: place("generated", 0.5), to: [place("generated", 0.1), place("generated", 0.9), place("broken", 0.5)] },+ { from: place("broken", 0.2), to: [[10, document.getElementById("broken").getBoundingClientRect().top + 30], place("inline-block-around", 0.5)] },+ { from: place("inline-block", 0.5), to: [place("inline-block", 0.9), place("inline-block-around", 0.05), place("inline-block-around", 0.95)] },+ { from: place("inert", 0.5), to: [place("inert", 0.9), place("last", 0.5)] },+ { from: place("last", 0.2), to: [place("inert", 0.5), place("generated", 0.5)] },+ { from: place("picture", 0.5), to: [place("image", 0.9), place("image", 0.05), place("first", 0.5), place("last", 0.5)] },+ { from: place("picture", 0.1), to: [place("picture", 0.9), place("picture", 0.1)] },+ { from: place("empty", 0.5), to: [place("anchors", 0.9), place("anchors", 0.05), place("first", 0.5), place("last", 0.5)] },+ { from: place("anchors", 0.05), to: [place("empty", 0.5), place("unselectable-picture", 0.5), place("anchors", 0.95)] },+ { from: place("inline-block", 0.5), to: [place("unselectable-picture", 0.5)] },+ { from: place("styled", 0.2), to: [place("styled", 0.8), place("linked", 0.5)] },+ { from: place("linked", 0.05), to: [place("link", 0.5), place("linked", 0.95), place("frame", 0.5)] },+ { from: place("draggable-link", 0.1), to: [place("draggable-link", 0.9), place("first", 0.5)] },+ { from: place("last", 0.2), to: [place("frame", 0.5), place("button", 0.5), place("vector-text", 0.5), place("styled", 0.5)] },+ { from: place("vector-text", 0.2), to: [place("vector-text", 0.8), place("last", 0.5)] },+ { from: place("last", 0.2), to: [[10, -40], [10, 5000], [-100, 45], [5000, 45]] },+ ];++ // Drags past the edge of what scrolls, which the host keeps in its scrollport as it starts to scroll.+ const dragsThatScroll = [+ { from: place("scrolled-two", 0.2), to: place("scrolled-two", 0.8) },+ { from: place("scrolled-two", 0.2), to: place("scrolled-three", 0.5) },+ { from: place("scrolled-two", 0.2), to: place("first", 0.5) },+ { from: place("scrolled-two", 0.2), to: place("last", 0.5) },+ ];+ const dragsThatScrollThePage = [+ { from: place("inline", 0.2), to: [10, 5000] },+ { from: place("inline", 0.2), to: [5000, 45] },+ ];++ // The highlight a lane shows while the task runs is the one the host paints once it handled the same move, or the+ // one it showed before, for a move only the host can follow.+ asyncTest(async done => {+ await srcdocLoaded(document.getElementById("frame"));+ // NB: Printing moves what the drags point at.+ const results = [];+ for (const drag of drags) {+ const [x, y] = drag.from;+ getSelection().removeAllRanges();+ internals.mouseDown(x, y);+ await twoFramesLanded();+ let previous = internals.paintedSelection();+ for (const [toX, toY] of drag.to) {+ const shown = await whileLaneHovers(frameTime => {+ internals.injectHoverPointer(toX, toY, frameTime + 16, 0, 1);+ return internals.presentedSelection();+ });+ internals.mouseMove(toX, toY, 0, 1);+ await twoFramesLanded();+ const painted = internals.paintedSelection();+ if (shown === painted)+ results.push(`same: ${JSON.stringify(painted)}`);+ else if (shown === previous)+ results.push(`left to the host: ${JSON.stringify(painted)}`);+ else+ results.push(`DIFFERENT, shown ${JSON.stringify(shown)}: ${JSON.stringify(painted)}`);+ previous = painted;+ }+ internals.mouseUp(...drag.to.at(-1));+ await twoFramesLanded();+ }+ // NB: The button goes up before a scroll moves anything, in the task of the host's last move.+ const dragPastTheEdge = async ({ from, to }) => {+ getSelection().removeAllRanges();+ internals.mouseDown(...from);+ await twoFramesLanded();+ const shown = await whileLaneHovers(frameTime => {+ internals.injectHoverPointer(...to, frameTime + 16, 0, 1);+ return internals.presentedSelection();+ });+ internals.mouseMove(...to, 0, 1);+ internals.mouseUp(...to);+ await twoFramesLanded();+ const painted = internals.paintedSelection();+ results.push(`${shown === painted ? "same" : `DIFFERENT, shown ${JSON.stringify(shown)}`}: ${JSON.stringify(painted)}`);+ };+ for (const drag of dragsThatScroll) {+ await dragPastTheEdge(drag);+ document.getElementById("scroller").scrollTop = 10;+ }+ document.body.style.height = "2000px";+ await twoFramesLanded();+ for (const drag of dragsThatScrollThePage) {+ await dragPastTheEdge(drag);+ window.scrollTo(0, 0);+ }+ results.forEach(result => println(result));+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/HTML/frame-in-flight/clock-lane-drag-selection-shows-selection-styles.html b/Tests/LibWeb/Text/input/HTML/frame-in-flight/clock-lane-drag-selection-shows-selection-styles.htmlnew file mode 100644index 00000000000..67c7f2fbfca--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/frame-in-flight/clock-lane-drag-selection-shows-selection-styles.html@@ -0,0 +1,66 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<script src="frame-in-flight.js"></script>+<style>+ body { margin: 0; font: 20px SerenitySans, sans-serif; line-height: 30px; }+ p, div { margin: 0; height: 30px; white-space: nowrap; }+ #styled::selection { color: red; background: yellow; }+ #around::selection { color: white; background: green; }+</style>+<p id="plain">text no rule styles</p>+<p id="styled">text a rule styles</p>+<div id="around"><span id="inheriting">text that inherits a style</span></div>+<div id="host"></div>+<p id="last">text the rules leave alone</p>+<script>+ // What a lane shows of a drag beside a task is what the host paints once it handled the same move, the colors of the+ // `::selection` styles of the elements the drag reaches included.+ asyncTest(async done => {+ host.attachShadow({ mode: "open" }).innerHTML =+ "<style>::selection { color: white; background: purple; }</style><p>text in a shadow tree</p>";++ const place = (id, fraction) => {+ const rect = document.getElementById(id).getBoundingClientRect();+ return [rect.left + 5 + fraction * 140, rect.top + 15];+ };+ const compare = async (name, from, to) => {+ getSelection().removeAllRanges();+ await twoFramesLanded();+ internals.mouseDown(...from);+ await twoFramesLanded();+ const shown = await whileLaneHovers(frameTime => {+ internals.injectHoverPointer(...to, frameTime + 16, 0, 1);+ return internals.presentedSelection();+ });+ await twoFramesLanded();+ internals.mouseMove(...to, 0, 1);+ await twoFramesLanded();+ const painted = internals.paintedSelection();+ internals.mouseUp(...to);+ await twoFramesLanded();+ println(`${name}: ${shown === painted ? "same" : `DIFFERENT, shown ${JSON.stringify(shown)}`}: ${JSON.stringify(painted)}`);+ };++ await compare("no rule", place("plain", 0.1), place("plain", 0.9));+ await compare("a rule", place("styled", 0.1), place("styled", 0.9));+ await compare("into a rule", place("plain", 0.1), place("styled", 0.9));+ await compare("past a rule", place("plain", 0.1), place("around", 0.1));+ await compare("an inherited style", place("inheriting", 0.1), place("inheriting", 0.9));+ await compare("a shadow tree's rule", place("host", 0.1), place("host", 0.9));++ const sheet = document.head.appendChild(document.createElement("style"));+ sheet.textContent = "#last::selection { color: blue; background: pink; }";+ await twoFramesLanded();+ await compare("a rule that came later", place("last", 0.1), place("last", 0.9));+ sheet.textContent = "";+ await twoFramesLanded();+ await compare("a rule that went away", place("last", 0.1), place("last", 0.9));++ // A sheet this long is kept apart from the entries of the document.+ const unused = Array.from({ length: 64 }, (_, index) => `.unused-${index} { color: red; }`).join(" ");+ sheet.textContent = `${unused} #last::selection { color: blue; background: pink; }`;+ await twoFramesLanded();+ await compare("a rule of a long sheet", place("last", 0.1), place("last", 0.9));+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/HTML/frame-in-flight/clock-lane-drag-selection-stays-with-the-host.html b/Tests/LibWeb/Text/input/HTML/frame-in-flight/clock-lane-drag-selection-stays-with-the-host.htmlnew file mode 100644index 00000000000..7980b7b0ed4--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/frame-in-flight/clock-lane-drag-selection-stays-with-the-host.html@@ -0,0 +1,46 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<script src="frame-in-flight.js"></script>+<style>+ body { margin: 0; font: 20px SerenitySans, sans-serif; line-height: 30px; }+ p, div { margin: 0; height: 30px; white-space: nowrap; }+ input { display: block; width: 300px; height: 30px; padding: 0; border: 0; font: inherit; }+ textarea { display: block; width: 300px; height: 30px; padding: 0; border: 0; font: inherit; }+</style>+<p id="plain">plain text of the page, in one line</p>+<input id="input" value="text in an input element">+<textarea id="area">text in a textarea</textarea>+<div id="editable" contenteditable>text in an editing host</div>+<p id="cancelled">text whose selectstart is cancelled</p>+<script>+ cancelled.addEventListener("selectstart", event => event.preventDefault());++ // What a lane shows of a drag, beside a task, which starts at `id` with `clickCount` clicks.+ const shownOfDrag = async (id, clickCount) => {+ const rect = document.getElementById(id).getBoundingClientRect();+ const [x, y] = [rect.left + 10, rect.top + 15];+ getSelection().removeAllRanges();+ internals.mouseDown(x, y, clickCount);+ await twoFramesLanded();+ const before = internals.paintedSelection();+ const shown = await whileLaneHovers(frameTime => {+ internals.injectHoverPointer(x + 150, y, frameTime + 16, 0, 1);+ return internals.presentedSelection();+ });+ internals.mouseUp(x + 150, y);+ await twoFramesLanded();+ return shown === before ? "left to the host" : "followed";+ };++ // A lane follows a drag by characters over the text of the page, and leaves the rest to the host.+ asyncTest(async done => {+ println(`characters of the page: ${await shownOfDrag("plain", 1)}`);+ println(`words of the page: ${await shownOfDrag("plain", 2)}`);+ println(`paragraphs of the page: ${await shownOfDrag("plain", 3)}`);+ println(`an input element: ${await shownOfDrag("input", 1)}`);+ println(`a textarea: ${await shownOfDrag("area", 1)}`);+ println(`an editing host: ${await shownOfDrag("editable", 1)}`);+ println(`a cancelled selectstart: ${await shownOfDrag("cancelled", 1)}`);+ done();+ });+</script>