Truly independent web browser
LibWeb+Qt: Honor native macOS text-editing bindings
sideshowbarker309574e22253
diff --git a/Libraries/LibGfx/Rust/src/text_layout.rs b/Libraries/LibGfx/Rust/src/text_layout.rsindex 377fb95dd54..02756cb45b5 100644--- a/Libraries/LibGfx/Rust/src/text_layout.rs+++ b/Libraries/LibGfx/Rust/src/text_layout.rs@@ -41,7 +41,9 @@ pub struct DrawGlyph {pub length_in_code_units: usize,pub glyph_width: f32,pub glyph_id: u32,+ pub cluster_start: u32,pub should_paint: bool,+ pub is_rtl: bool,}unsafe extern "C" {diff --git a/Libraries/LibGfx/TextLayout.cpp b/Libraries/LibGfx/TextLayout.cppindex b1c1e84c926..c1a552e1444 100644--- a/Libraries/LibGfx/TextLayout.cpp+++ b/Libraries/LibGfx/TextLayout.cpp@@ -567,7 +567,9 @@ static ShapedGlyphs build_origin_relative_shape(Utf16View const& string, Font co.length_in_code_units = glyph_length_in_code_units(i),.glyph_width = should_paint ? positions[i].x_advance / text_shaping_resolution + extra_advance : 0,.glyph_id = glyph_info[i].codepoint,+ .cluster_start = glyph_info[i].cluster,.should_paint = should_paint,+ .is_rtl = is_right_to_left,});if (!should_paint)@@ -739,3 +741,5 @@ extern "C" void ladybird_gfx_glyph_run_glyph_intercepts(for (auto value : intercepts)push(sink, value);}+static_assert(offsetof(Gfx::FFI::DrawGlyph, cluster_start) == offsetof(Gfx::DrawGlyph, cluster_start));+static_assert(offsetof(Gfx::FFI::DrawGlyph, is_rtl) == offsetof(Gfx::DrawGlyph, is_rtl));diff --git a/Libraries/LibGfx/TextLayout.h b/Libraries/LibGfx/TextLayout.hindex d3329b0e58c..8e481c36ce2 100644--- a/Libraries/LibGfx/TextLayout.h+++ b/Libraries/LibGfx/TextLayout.h@@ -25,7 +25,9 @@ struct DrawGlyph {size_t length_in_code_units { 0 };float glyph_width { 0.0 };u32 glyph_id { 0 };+ u32 cluster_start { 0 };bool should_paint { true };+ bool is_rtl { false };};struct TrailingWhitespace {diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex d2319e0928d..ed283da3e43 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -10151,10 +10151,10 @@ Optional<CSSPixelRect> Document::current_caret_rect()};if (is<DOM::Text>(dom_node)) {- Layout::RustFFI::FfiOptionalCssPixelRect result;- Layout::RustFFI::layout_script_text_caret_rect_in_dom_range(- layout_node->document_host(), Layout::Node::slot_id(layout_node), position->offset(), &result);- if (result.has_value)+ Layout::RustFFI::FfiCaretRectResult result;+ Layout::RustFFI::layout_script_text_caret_rect_for_position(+ layout_node->document_host(), Layout::Node::slot_id(layout_node), position->offset(), position->affinity() == TextAffinity::Downstream, &result);+ if (result.found)return to_viewport_rect(result.rect);}diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.hindex 05b75b0991d..de9a483a2bc 100644--- a/Libraries/LibWeb/DOM/Document.h+++ b/Libraries/LibWeb/DOM/Document.h@@ -1045,7 +1045,7 @@ public:Yes,};WebIDL::ExceptionOr<bool> exec_command(Utf16FlyString const& command, bool show_ui, Utf16View value);- WebIDL::ExceptionOr<bool> exec_command_internal(Utf16FlyString const& command, bool show_ui, Utf16View value, DispatchInputEvent, Optional<Utf16FlyString> const& user_input_type = {});+ WebIDL::ExceptionOr<bool> exec_command_internal(Utf16FlyString const& command, bool show_ui, Utf16View value, DispatchInputEvent, Optional<Utf16FlyString> const& user_input_type = {}, GC::Ptr<StaticRange> deletion_range = nullptr);WebIDL::ExceptionOr<bool> query_command_enabled(Utf16FlyString const& command);WebIDL::ExceptionOr<bool> query_command_indeterm(Utf16FlyString const& command);WebIDL::ExceptionOr<bool> query_command_state(Utf16FlyString const& command);diff --git a/Libraries/LibWeb/DOM/EditingHostManager.cpp b/Libraries/LibWeb/DOM/EditingHostManager.cppindex 5ded0492c22..92e99eb443f 100644--- a/Libraries/LibWeb/DOM/EditingHostManager.cpp+++ b/Libraries/LibWeb/DOM/EditingHostManager.cpp@@ -9,9 +9,11 @@#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/EditingHostManager.h>#include <LibWeb/DOM/Range.h>+#include <LibWeb/DOM/StaticRange.h>#include <LibWeb/DOM/Text.h>#include <LibWeb/Editing/ClipboardSanitizer.h>#include <LibWeb/Editing/CommandNames.h>+#include <LibWeb/Editing/VisiblePosition.h>#include <LibWeb/HTML/HTMLElement.h>#include <LibWeb/Selection/Selection.h>#include <LibWeb/Selection/SelectionModifier.h>@@ -142,6 +144,24 @@ void EditingHostManager::move_cursor_to_end(CollapseSelection collapse)Selection::SelectionModifier(*selection).modify(collapse == CollapseSelection::Yes ? Selection::SelectionAlteration::Move : Selection::SelectionAlteration::Extend, Selection::SelectionDirection::Forward, Selection::SelectionGranularity::LineBoundary);}+void EditingHostManager::move_cursor_to_start_of_paragraph(CollapseSelection collapse)+{+ if (auto selection = get_selection_for_navigation(collapse))+ Selection::SelectionModifier(*selection).modify(collapse == CollapseSelection::Yes ? Selection::SelectionAlteration::Move : Selection::SelectionAlteration::Extend, Selection::SelectionDirection::Backward, Selection::SelectionGranularity::ParagraphBoundary);+}++void EditingHostManager::move_cursor_to_end_of_paragraph(CollapseSelection collapse)+{+ if (auto selection = get_selection_for_navigation(collapse))+ Selection::SelectionModifier(*selection).modify(collapse == CollapseSelection::Yes ? Selection::SelectionAlteration::Move : Selection::SelectionAlteration::Extend, Selection::SelectionDirection::Forward, Selection::SelectionGranularity::ParagraphBoundary);+}++void EditingHostManager::move_cursor_to_physical_line_boundary(bool left, CollapseSelection collapse)+{+ if (auto selection = get_selection_for_navigation(collapse))+ Selection::SelectionModifier(*selection).modify(collapse == CollapseSelection::Yes ? Selection::SelectionAlteration::Move : Selection::SelectionAlteration::Extend, left ? Selection::SelectionDirection::Backward : Selection::SelectionDirection::Forward, Selection::SelectionGranularity::PhysicalLineBoundary);+}+void EditingHostManager::move_cursor_to_start_of_document(CollapseSelection collapse){auto selection = get_selection_for_navigation(collapse);@@ -218,6 +238,43 @@ void EditingHostManager::decrement_cursor_position_to_previous_line(CollapseSeleselection->move_offset_to_previous_line(collapse == CollapseSelection::Yes);}+GC::Ptr<StaticRange> EditingHostManager::deletion_target_range(Utf16FlyString const& input_type)+{+ auto selection = m_document->get_selection();+ auto range = selection ? selection->range() : nullptr;+ auto host = m_active_contenteditable_element;+ if (!host || !host->is_connected() || !range+ || range->start_container()->editing_host() != host+ || range->end_container()->editing_host() != host)+ return nullptr;+ if (!range->collapsed())+ return host->heap().allocate<StaticRange>(range->start_container(), range->start_offset(), range->end_container(), range->end_offset());++ using namespace Web::Selection;+ auto backward = first_is_one_of(input_type, UIEvents::InputTypes::deleteContentBackward, UIEvents::InputTypes::deleteWordBackward);+ auto direction = backward ? SelectionDirection::Backward : SelectionDirection::Forward;+ auto granularity = SelectionGranularity::Character;+ if (first_is_one_of(input_type, UIEvents::InputTypes::deleteWordBackward, UIEvents::InputTypes::deleteWordForward))+ granularity = SelectionGranularity::Word;+ else if (input_type == UIEvents::InputTypes::deleteHardLineForward)+ granularity = SelectionGranularity::ParagraphBoundary;+ auto origin = Editing::VisiblePosition::create(*m_document, range->start());+ auto destination = origin.move(SelectionAlteration::Extend, direction, granularity);+ if (input_type == UIEvents::InputTypes::deleteHardLineForward+ && (!destination.has_value() || position_of_boundary_point_relative_to_other_boundary_point(destination->deep_equivalent(), origin.deep_equivalent()) == RelativeBoundaryPointPosition::Equal))+ destination = origin.move(SelectionAlteration::Extend, direction, SelectionGranularity::Character);+ if (!destination.has_value() || position_of_boundary_point_relative_to_other_boundary_point(destination->deep_equivalent(), origin.deep_equivalent()) == RelativeBoundaryPointPosition::Equal)+ return nullptr;+ auto boundary = destination->boundary();+ if (boundary.node->editing_host() != host)+ return nullptr;+ auto start = backward ? boundary : range->start();+ auto end = backward ? range->start() : boundary;+ if (position_of_boundary_point_relative_to_other_boundary_point(start, end) != RelativeBoundaryPointPosition::Before)+ return nullptr;+ return host->heap().allocate<StaticRange>(start.node, start.offset, end.node, end.offset);+}+void EditingHostManager::handle_delete(Utf16FlyString const& input_type, [[maybe_unused]] DispatchInputEvent dispatch_input_event){// https://w3c.github.io/editing/docs/execCommand/#additional-requirements@@ -230,8 +287,16 @@ void EditingHostManager::handle_delete(Utf16FlyString const& input_type, [[maybe//// NB: A cut deletes the selection like Backspace does, and passes its input type along so the input event fires// with inputType "deleteByCut" and the cut forms its own undo unit.- auto command = input_type == UIEvents::InputTypes::deleteContentForward ? Editing::CommandNames::forwardDelete : Editing::CommandNames::delete_;- auto editing_result = m_document->exec_command_internal(command, false, {}, Document::DispatchInputEvent::Yes, input_type);+ auto granular = first_is_one_of(input_type, UIEvents::InputTypes::deleteWordBackward, UIEvents::InputTypes::deleteWordForward, UIEvents::InputTypes::deleteHardLineForward);+ GC::Root<StaticRange> range;+ if (granular) {+ range = deletion_target_range(input_type);+ if (!range)+ return;+ }+ auto forward = first_is_one_of(input_type, UIEvents::InputTypes::deleteContentForward, UIEvents::InputTypes::deleteWordForward, UIEvents::InputTypes::deleteHardLineForward);+ auto command = forward ? Editing::CommandNames::forwardDelete : Editing::CommandNames::delete_;+ auto editing_result = m_document->exec_command_internal(command, false, {}, Document::DispatchInputEvent::Yes, input_type, range.ptr());if (editing_result.is_exception())dbgln("handle_delete(): editing resulted in exception: {}", editing_result.exception());}diff --git a/Libraries/LibWeb/DOM/EditingHostManager.h b/Libraries/LibWeb/DOM/EditingHostManager.hindex 4846deb1896..b45bab96fc3 100644--- a/Libraries/LibWeb/DOM/EditingHostManager.h+++ b/Libraries/LibWeb/DOM/EditingHostManager.h@@ -24,6 +24,7 @@ public:virtual void handle_insert(Utf16FlyString const& input_type, Utf16View) override;virtual void handle_insert_from_clipboard(Utf16FlyString const& input_type, Utf16View plain_text, Optional<Utf16View> html) override;+ virtual GC::Ptr<DOM::StaticRange> deletion_target_range(Utf16FlyString const& input_type) override;virtual void handle_delete(Utf16FlyString const& input_type, DispatchInputEvent = DispatchInputEvent::Yes) override;virtual EventResult handle_return_key(Utf16FlyString const& ui_input_type) override;virtual GC::Ptr<DOM::Node> mouse_selection_scope() override { return m_active_contenteditable_element; }@@ -32,6 +33,9 @@ public:virtual void set_selection_focus(GC::Ref<DOM::Node>, size_t offset, TextAffinity = TextAffinity::Downstream) override;virtual void move_cursor_to_start(CollapseSelection) override;virtual void move_cursor_to_end(CollapseSelection) override;+ virtual void move_cursor_to_start_of_paragraph(CollapseSelection) override;+ virtual void move_cursor_to_end_of_paragraph(CollapseSelection) override;+ virtual void move_cursor_to_physical_line_boundary(bool left, CollapseSelection) override;virtual void move_cursor_to_start_of_document(CollapseSelection) override;virtual void move_cursor_to_end_of_document(CollapseSelection) override;virtual void move_cursor_to_previous_page(CollapseSelection) override;diff --git a/Libraries/LibWeb/DOM/InputEventsTarget.h b/Libraries/LibWeb/DOM/InputEventsTarget.hindex 17afe2cfa97..7f8fc1dbe83 100644--- a/Libraries/LibWeb/DOM/InputEventsTarget.h+++ b/Libraries/LibWeb/DOM/InputEventsTarget.h@@ -30,6 +30,7 @@ public:No,Yes,};+ virtual GC::Ptr<DOM::StaticRange> deletion_target_range(Utf16FlyString const& input_type) = 0;virtual void handle_delete(Utf16FlyString const& input_type, DispatchInputEvent = DispatchInputEvent::Yes) = 0;// The node that mouse-driven selection through this target is constrained to (e.g. the text node inside a text@@ -45,6 +46,11 @@ public:};virtual void move_cursor_to_start(CollapseSelection) = 0;virtual void move_cursor_to_end(CollapseSelection) = 0;+ virtual void move_cursor_to_start_of_current_line(CollapseSelection collapse) { move_cursor_to_start(collapse); }+ virtual void move_cursor_to_end_of_current_line(CollapseSelection collapse) { move_cursor_to_end(collapse); }+ virtual void move_cursor_to_start_of_paragraph(CollapseSelection) = 0;+ virtual void move_cursor_to_end_of_paragraph(CollapseSelection) = 0;+ virtual void move_cursor_to_physical_line_boundary(bool left, CollapseSelection) = 0;virtual void move_cursor_to_start_of_document(CollapseSelection collapse) { move_cursor_to_start(collapse); }virtual void move_cursor_to_end_of_document(CollapseSelection collapse) { move_cursor_to_end(collapse); }virtual void move_cursor_to_previous_page(CollapseSelection collapse) { move_cursor_to_start_of_document(collapse); }diff --git a/Libraries/LibWeb/DOM/Position.h b/Libraries/LibWeb/DOM/Position.hindex 7ca7be9420a..534ea17ff38 100644--- a/Libraries/LibWeb/DOM/Position.h+++ b/Libraries/LibWeb/DOM/Position.h@@ -21,9 +21,9 @@ class Position final : public JS::Cell {GC_DECLARE_ALLOCATOR(Position);public:- [[nodiscard]] static GC::Ref<Position> create(GC::Ref<Node> node, unsigned offset)+ [[nodiscard]] static GC::Ref<Position> create(GC::Ref<Node> node, unsigned offset, TextAffinity affinity = TextAffinity::Downstream){- return GC::Heap::the().allocate<Position>(node, offset, TextAffinity::Downstream);+ return GC::Heap::the().allocate<Position>(node, offset, affinity);}GC::Ref<Node> node() { return m_node; }diff --git a/Libraries/LibWeb/Editing/ExecCommand.cpp b/Libraries/LibWeb/Editing/ExecCommand.cppindex 6b5bb259bb9..6a6e72c1ce4 100644--- a/Libraries/LibWeb/Editing/ExecCommand.cpp+++ b/Libraries/LibWeb/Editing/ExecCommand.cpp@@ -10,6 +10,7 @@#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/Event.h>#include <LibWeb/DOM/Range.h>+#include <LibWeb/DOM/StaticRange.h>#include <LibWeb/DOM/Text.h>#include <LibWeb/Editing/CommandNames.h>#include <LibWeb/Editing/Commands.h>@@ -40,7 +41,7 @@ WebIDL::ExceptionOr<bool> Document::exec_command(Utf16FlyString const& command,return exec_command_internal(command, show_ui, value, DispatchInputEvent::Yes);}-WebIDL::ExceptionOr<bool> Document::exec_command_internal(Utf16FlyString const& command, [[maybe_unused]] bool show_ui, Utf16View value, DispatchInputEvent dispatch_input_event, Optional<Utf16FlyString> const& user_input_type)+WebIDL::ExceptionOr<bool> Document::exec_command_internal(Utf16FlyString const& command, [[maybe_unused]] bool show_ui, Utf16View value, DispatchInputEvent dispatch_input_event, Optional<Utf16FlyString> const& user_input_type, GC::Ptr<StaticRange> deletion_range){// AD-HOC: This is not directly mentioned in the spec, but all major browsers limit editing API calls to HTML documentsif (!is_html_document())@@ -180,7 +181,7 @@ WebIDL::ExceptionOr<bool> Document::exec_command_internal(Utf16FlyString const&auto category = Editing::UndoStep::Category::Other;// INTEROP: Cut and paste are standalone undo units in Chromium: they never coalesce with typing or deletion// runs, so they categorize as Other even though they run the delete and insertText commands.- if (!is_cut_or_paste) {+ if (!is_cut_or_paste && !deletion_range) {if (command_definition.command.is_one_of(Editing::CommandNames::insertText, Editing::CommandNames::insertLineBreak, Editing::CommandNames::insertParagraph))category = Editing::UndoStep::Category::Insertion;else if (command_definition.command == Editing::CommandNames::delete_)@@ -195,6 +196,11 @@ WebIDL::ExceptionOr<bool> Document::exec_command_internal(Utf16FlyString const&history->end_recording();};+ if (deletion_range) {+ MUST(m_selection->set_base_and_extent(deletion_range->start_container(), deletion_range->start_offset(),+ deletion_range->end_container(), deletion_range->end_offset()));+ }+// 5. Take the action for command, passing value to the instructions as an argument.auto command_result = [&] {TemporaryChange running_action { m_running_editing_command_action, true };diff --git a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cppindex 4ed07ca550c..cfff4a249b1 100644--- a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp+++ b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp@@ -428,7 +428,7 @@ void EventLoop::process_input_events() const[&](Web::KeyEvent const& key_event) {switch (key_event.type) {case Web::KeyEvent::Type::KeyDown:- return page.handle_keydown(key_event.key, key_event.modifiers, key_event.code_point, key_event.repeat, key_event.should_insert_text, key_event.async_scroll_performed_default_action);+ return page.handle_keydown(key_event.key, key_event.modifiers, key_event.code_point, key_event.repeat, key_event.should_insert_text, key_event.async_scroll_performed_default_action, key_event.editing_commands, key_event.native_editing_binding_resolved);case Web::KeyEvent::Type::KeyUp:return page.handle_keyup(key_event.key, key_event.modifiers, key_event.code_point, key_event.repeat);}diff --git a/Libraries/LibWeb/HTML/FormAssociatedElement.cpp b/Libraries/LibWeb/HTML/FormAssociatedElement.cppindex 5b9fd16f8b6..5a83aeb560d 100644--- a/Libraries/LibWeb/HTML/FormAssociatedElement.cpp+++ b/Libraries/LibWeb/HTML/FormAssociatedElement.cpp@@ -19,6 +19,7 @@#include <LibWeb/DOM/Event.h>#include <LibWeb/DOM/Position.h>#include <LibWeb/DOM/SelectionchangeEventDispatching.h>+#include <LibWeb/DOM/StaticRange.h>#include <LibWeb/DOM/SubtreeInsertionScope.h>#include <LibWeb/Editing/EditCommand.h>#include <LibWeb/Editing/EditingHistory.h>@@ -38,9 +39,12 @@#include <LibWeb/HTML/Parser/HTMLParser.h>#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/ValidityState.h>+#include <LibWeb/HTML/Window.h>#include <LibWeb/Infra/SerializedURL.h>#include <LibWeb/Layout/TextNode.h>#include <LibWeb/Page/EventHandler.h>+#include <LibWeb/Painting/BoxViews.h>+#include <LibWeb/Painting/HitTestDisplayList.h>#include <LibWeb/UIEvents/InputTypes.h>#include <LibWeb/VisualLines.h>#include <LibWebCommon/Infra/Strings.h>@@ -1315,24 +1319,62 @@ void FormAssociatedTextControlElement::handle_insert(Utf16FlyString const& inputscroll_cursor_into_view();}+GC::Ptr<DOM::StaticRange> FormAssociatedTextControlElement::deletion_target_range(Utf16FlyString const& input_type)+{+ auto text = form_associated_element_to_text_node();+ if (!text || !static_cast<FormAssociatedElement&>(text_control_to_html_element()).is_mutable())+ return nullptr;+ auto start = min(selection_start(), text->length());+ auto end = min(selection_end(), text->length());+ if (start == end) {+ if (input_type == UIEvents::InputTypes::deleteContentBackward) {+ start = text->grapheme_segmenter().previous_boundary(start).value_or(start);+ } else if (input_type == UIEvents::InputTypes::deleteContentForward) {+ end = text->grapheme_segmenter().next_boundary(end).value_or(end);+ } else if (input_type == UIEvents::InputTypes::deleteWordBackward) {+ while (true) {+ auto boundary = text->word_segmenter().previous_boundary(start);+ if (!boundary.has_value())+ break;+ auto word = text->data().substring_view(*boundary, start - *boundary);+ start = *boundary;+ if (!Unicode::Segmenter::should_continue_beyond_word(word))+ break;+ }+ } else if (input_type == UIEvents::InputTypes::deleteWordForward) {+ while (true) {+ auto boundary = text->word_segmenter().next_boundary(end);+ if (!boundary.has_value())+ break;+ auto word = text->data().substring_view(end, *boundary - end);+ end = *boundary;+ if (!Unicode::Segmenter::should_continue_beyond_word(word))+ break;+ }+ } else if (input_type == UIEvents::InputTypes::deleteHardLineForward) {+ auto value = text->data().utf16_view();+ while (end < text->length() && value.code_unit_at(end) != '\n')+ ++end;+ if (start == end && end < text->length())+ ++end;+ }+ }+ if (start == end)+ return nullptr;+ return text->heap().allocate<DOM::StaticRange>(*text, start, *text, end);+}+void FormAssociatedTextControlElement::handle_delete(Utf16FlyString const& input_type, [[maybe_unused]] DispatchInputEvent dispatch_input_event){auto text_node = form_associated_element_to_text_node();if (!text_node || !static_cast<FormAssociatedElement&>(text_control_to_html_element()).is_mutable())return;- auto selection_start = this->selection_start();- auto selection_end = this->selection_end();-- if (selection_start == selection_end) {- if (input_type == UIEvents::InputTypes::deleteContentBackward) {- if (auto offset = text_node->grapheme_segmenter().previous_boundary(m_selection_end); offset.has_value())- selection_start = *offset;- } else {- if (auto offset = text_node->grapheme_segmenter().next_boundary(m_selection_end); offset.has_value())- selection_end = *offset;- }- }+ auto range = deletion_target_range(input_type);+ if (!range)+ return;+ auto selection_start = range->start_offset();+ auto selection_end = range->end_offset();// Record the edit on the document's editing history so the user can undo it. Backward and// forward deletion runs coalesce separately, and cuts never coalesce, like in the editing@@ -1389,6 +1431,10 @@ void FormAssociatedTextControlElement::move_selection_end_to(size_t offset, Textm_selection_start = offset;m_selection_end = offset;m_selection_end_affinity = affinity;+ if (collapse == CollapseSelection::Yes || m_selection_start == m_selection_end)+ m_selection_direction = SelectionDirection::None;+ else+ m_selection_direction = m_selection_end < m_selection_start ? SelectionDirection::Backward : SelectionDirection::Forward;// NB: Caret movement ends typing coalescence in the editing history.if (auto history = text_control_to_html_element().document().editing_history_if_exists())@@ -1521,6 +1567,77 @@ void FormAssociatedTextControlElement::move_cursor_to_end_of_current_line(Collapselection_was_changed(SelectionSource::UI);}+void FormAssociatedTextControlElement::move_cursor_to_start_of_paragraph(CollapseSelection collapse)+{+ auto text = form_associated_element_to_text_node();+ if (!text)+ return;+ auto value = text->data().utf16_view();+ auto offset = min(static_cast<size_t>(m_selection_end), value.length_in_code_units());+ while (offset > 0 && value.code_unit_at(offset - 1) != '\n')+ --offset;+ move_selection_end_to(offset, TextAffinity::Downstream, collapse);+ selection_was_changed(SelectionSource::UI);+}++void FormAssociatedTextControlElement::move_cursor_to_end_of_paragraph(CollapseSelection collapse)+{+ auto text = form_associated_element_to_text_node();+ if (!text)+ return;+ auto value = text->data().utf16_view();+ auto offset = min(static_cast<size_t>(m_selection_end), value.length_in_code_units());+ while (offset < value.length_in_code_units() && value.code_unit_at(offset) != '\n')+ ++offset;+ move_selection_end_to(offset, TextAffinity::Downstream, collapse);+ selection_was_changed(SelectionSource::UI);+}++void FormAssociatedTextControlElement::move_cursor_by_page(bool forward, CollapseSelection collapse)+{+ auto text = form_associated_element_to_text_node();+ auto& element = text_control_to_html_element();+ if (!text)+ return;+ Layout::ForcedReadScope read { element.document() };+ element.document().update_layout_if_needed_for_node(element, DOM::UpdateLayoutReason::CursorLineNavigation);+ auto* layout = element.layout_node(read);+ auto window = element.document().window();+ if (!layout || !window)+ return;+ auto page_height = min(Painting::absolute_padding_box_rect(*layout).height().to_int(), window->inner_height());+ if (page_height <= 0)+ return;+ auto distance = static_cast<i32>(page_height * 0.875);+#ifdef AK_OS_MACOS+ distance = max(distance, page_height - 40);+#endif+ auto position = compute_cursor_position_by_page(*text, m_selection_end, m_selection_end_affinity, forward, max(distance, 1));+ if (!position.has_value())+ return;+ move_selection_end_to(position->offset, position->affinity, collapse);+ selection_was_changed(SelectionSource::UI);+}++void FormAssociatedTextControlElement::move_cursor_to_physical_line_boundary(bool left, CollapseSelection collapse)+{+ auto text = form_associated_element_to_text_node();+ if (!text)+ return;+ auto& document = text_control_to_html_element().document();+ Layout::ForcedReadScope read { document };+ document.update_layout_if_needed_for_node(*text, DOM::UpdateLayoutReason::CursorLineNavigation);+ auto position = document.caret_position_at_line_edge(read, *text, m_selection_end, m_selection_end_affinity,+ left ? Painting::CaretLineEdge::Left : Painting::CaretLineEdge::Right);+ if (!position.has_value())+ return;+ auto boundary = position->boundary_point();+ if (!boundary.has_value() || boundary->node != text)+ return;+ move_selection_end_to(boundary->offset, position->affinity, collapse);+ selection_was_changed(SelectionSource::UI);+}+void FormAssociatedTextControlElement::increment_cursor_position_offset(CollapseSelection collapse){auto const text_node = form_associated_element_to_text_node();@@ -1626,7 +1743,7 @@ GC::Ptr<DOM::Position> FormAssociatedTextControlElement::cursor_position() constreturn nullptr;if (m_selection_start != m_selection_end)return nullptr;- return DOM::Position::create(const_cast<DOM::Text&>(*node), m_selection_start);+ return DOM::Position::create(const_cast<DOM::Text&>(*node), m_selection_start, m_selection_end_affinity);}GC::Ref<JS::Cell> FormAssociatedTextControlElement::as_cell()diff --git a/Libraries/LibWeb/HTML/FormAssociatedElement.h b/Libraries/LibWeb/HTML/FormAssociatedElement.hindex 982ad6cd53d..69d38a1152b 100644--- a/Libraries/LibWeb/HTML/FormAssociatedElement.h+++ b/Libraries/LibWeb/HTML/FormAssociatedElement.h@@ -287,6 +287,7 @@ public:virtual GC::Ptr<DOM::Element> text_control_scroll_container() = 0;virtual void handle_insert(Utf16FlyString const& input_type, Utf16View) override;+ virtual GC::Ptr<DOM::StaticRange> deletion_target_range(Utf16FlyString const& input_type) override;virtual void handle_delete(Utf16FlyString const& input_type, DispatchInputEvent = DispatchInputEvent::Yes) override;virtual GC::Ptr<DOM::Node> mouse_selection_scope() override;virtual void select_all() override;@@ -294,8 +295,13 @@ public:virtual void set_selection_focus(GC::Ref<DOM::Node>, size_t offset, TextAffinity = TextAffinity::Downstream) override;virtual void move_cursor_to_start(CollapseSelection) override;virtual void move_cursor_to_end(CollapseSelection) override;- void move_cursor_to_start_of_current_line(CollapseSelection);- void move_cursor_to_end_of_current_line(CollapseSelection);+ virtual void move_cursor_to_start_of_current_line(CollapseSelection) override;+ virtual void move_cursor_to_end_of_current_line(CollapseSelection) override;+ virtual void move_cursor_to_start_of_paragraph(CollapseSelection) override;+ virtual void move_cursor_to_end_of_paragraph(CollapseSelection) override;+ virtual void move_cursor_to_physical_line_boundary(bool left, CollapseSelection) override;+ virtual void move_cursor_to_previous_page(CollapseSelection collapse) override { move_cursor_by_page(false, collapse); }+ virtual void move_cursor_to_next_page(CollapseSelection collapse) override { move_cursor_by_page(true, collapse); }virtual void increment_cursor_position_offset(CollapseSelection) override;virtual void decrement_cursor_position_offset(CollapseSelection) override;virtual void increment_cursor_position_to_next_word(CollapseSelection) override;@@ -316,6 +322,7 @@ private:void collapse_selection_to_offset(size_t, TextAffinity = TextAffinity::Downstream);void move_selection_end_to(size_t offset, TextAffinity, CollapseSelection);+ void move_cursor_by_page(bool forward, CollapseSelection);void scroll_cursor_into_view();void selection_was_changed(SelectionSource);diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex a0db902cfd4..55c2e785f66 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -553,6 +553,45 @@ static constexpr Optional<WebDriverKeyData> webdriver_key_to_key_code(u32 code_preturn {};}+WebIDL::ExceptionOr<void> Internals::send_text_editing_command(HTML::HTMLElement& target, Utf16String const& command_name, bool extend_selection)+{+ using Type = Web::TextEditingCommand::Type;+ struct NamedCommand {+ Utf16View name;+ Type type;+ };+ static constexpr NamedCommand commands[] = {+ { u"MoveBackward"sv, Type::MoveBackward },+ { u"MoveForward"sv, Type::MoveForward },+ { u"MoveWordBackward"sv, Type::MoveWordBackward },+ { u"MoveWordForward"sv, Type::MoveWordForward },+ { u"MoveUp"sv, Type::MoveUp },+ { u"MoveDown"sv, Type::MoveDown },+ { u"MoveToBeginningOfParagraph"sv, Type::MoveToBeginningOfParagraph },+ { u"MoveToEndOfParagraph"sv, Type::MoveToEndOfParagraph },+ { u"MoveToBeginningOfLine"sv, Type::MoveToBeginningOfLine },+ { u"MoveToEndOfLine"sv, Type::MoveToEndOfLine },+ { u"MoveToLeftEndOfLine"sv, Type::MoveToLeftEndOfLine },+ { u"MoveToRightEndOfLine"sv, Type::MoveToRightEndOfLine },+ { u"PageUp"sv, Type::PageUp },+ { u"PageDown"sv, Type::PageDown },+ { u"DeleteBackward"sv, Type::DeleteBackward },+ { u"DeleteForward"sv, Type::DeleteForward },+ { u"DeleteWordBackward"sv, Type::DeleteWordBackward },+ { u"DeleteWordForward"sv, Type::DeleteWordForward },+ { u"DeleteToEndOfParagraph"sv, Type::DeleteToEndOfParagraph },+ };+ for (auto const& command : commands) {+ if (command_name.utf16_view() != command.name)+ continue;+ target.focus();+ Array<TextEditingCommand, 1> editing_commands { TextEditingCommand { command.type, extend_selection } };+ page().handle_keydown(UIEvents::KeyCode::Key_A, UIEvents::Mod_Ctrl, 'a', false, false, false, editing_commands, true);+ return {};+ }+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Unknown text editing command"_utf16 };+}+void Internals::send_text(HTML::HTMLElement& target, Utf16String const& text, WebIDL::UnsignedShort modifiers){auto& page = this->page();diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.hindex d572cb85466..356f147ecfc 100644--- a/Libraries/LibWeb/Internals/Internals.h+++ b/Libraries/LibWeb/Internals/Internals.h@@ -95,6 +95,7 @@ public:void click_through_ui_process(double x, double y);void wheel_through_ui_process(double x, double y, double delta_x, double delta_y, bool precise, Bindings::ScrollGesturePhase, GC::Ref<WebIDL::Promise>);void send_key(HTML::HTMLElement&, Utf16String const&, WebIDL::UnsignedShort modifiers, WebIDL::UnsignedLong repeat_count);+ WebIDL::ExceptionOr<void> send_text_editing_command(HTML::HTMLElement&, Utf16String const& command_name, bool extend_selection);void paste(HTML::HTMLElement& target, Utf16String const& text);void paste_from_clipboard();void commit_text();diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idlindex f0320d4ac81..dbe2a48096d 100644--- a/Libraries/LibWeb/Internals/Internals.idl+++ b/Libraries/LibWeb/Internals/Internals.idl@@ -72,6 +72,7 @@ interface Internals {// Resolves once the UI process reports that the event has been handled.[CreatesPromise] Promise<undefined> wheelThroughUIProcess(double x, double y, double deltaX, double deltaY, optional boolean precise = false, optional ScrollGesturePhase scrollGesturePhase = "none");undefined sendKey(HTMLElement target, DOMString keyName, optional unsigned short modifiers = 0, optional unsigned long repeatCount = 1);+ undefined sendTextEditingCommand(HTMLElement target, DOMString commandName, optional boolean extendSelection = false);undefined paste(HTMLElement target, DOMString text);undefined pasteFromClipboard();undefined commitText();diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cppindex e139a807d65..8e155831052 100644--- a/Libraries/LibWeb/Page/EventHandler.cpp+++ b/Libraries/LibWeb/Page/EventHandler.cpp@@ -1624,7 +1624,118 @@ EventHandler::KeyboardScrollSnapshot EventHandler::keyboard_scroll_snapshot() coreturn snapshot;}-EventResult EventHandler::handle_keydown(UIEvents::KeyCode key, u32 modifiers, u32 code_point, bool repeat, bool should_insert_text, bool async_scroll_performed_default_action)+EventResult EventHandler::handle_text_editing_command(TextEditingCommand const& command)+{+ auto document = m_navigable->active_document();+ if (!document || !document->is_fully_active())+ return EventResult::Dropped;+ auto* target = document->active_input_events_target();+ if (!target)+ return EventResult::Accepted;+ auto scope = target->mouse_selection_scope();+ if (!scope || !scope->is_connected())+ return EventResult::Handled;+ auto collapse = command.extend_selection ? InputEventsTarget::CollapseSelection::No : InputEventsTarget::CollapseSelection::Yes;+ using Type = TextEditingCommand::Type;+ switch (command.type) {+ case Type::MoveBackward:+ target->decrement_cursor_position_offset(collapse);+ break;+ case Type::MoveForward:+ target->increment_cursor_position_offset(collapse);+ break;+ case Type::MoveWordBackward:+ target->decrement_cursor_position_to_previous_word(collapse);+ break;+ case Type::MoveWordForward:+ target->increment_cursor_position_to_next_word(collapse);+ break;+ case Type::MoveUp:+ target->decrement_cursor_position_to_previous_line(collapse);+ break;+ case Type::MoveDown:+ target->increment_cursor_position_to_next_line(collapse);+ break;+ case Type::MoveToBeginningOfParagraph:+ target->move_cursor_to_start_of_paragraph(collapse);+ break;+ case Type::MoveToEndOfParagraph:+ target->move_cursor_to_end_of_paragraph(collapse);+ break;+ case Type::MoveToBeginningOfLine:+ target->move_cursor_to_start_of_current_line(collapse);+ break;+ case Type::MoveToEndOfLine:+ target->move_cursor_to_end_of_current_line(collapse);+ break;+ case Type::MoveToLeftEndOfLine:+ target->move_cursor_to_physical_line_boundary(true, collapse);+ break;+ case Type::MoveToRightEndOfLine:+ target->move_cursor_to_physical_line_boundary(false, collapse);+ break;+ case Type::PageUp:+ target->move_cursor_to_previous_page(collapse);+ break;+ case Type::PageDown:+ target->move_cursor_to_next_page(collapse);+ break;+ case Type::DeleteBackward:+ case Type::DeleteForward:+ case Type::DeleteWordBackward:+ case Type::DeleteWordForward:+ case Type::DeleteToEndOfParagraph: {+ auto input_type = UIEvents::InputTypes::deleteContentBackward;+ switch (command.type) {+ case Type::DeleteForward:+ input_type = UIEvents::InputTypes::deleteContentForward;+ break;+ case Type::DeleteWordBackward:+ input_type = UIEvents::InputTypes::deleteWordBackward;+ break;+ case Type::DeleteWordForward:+ input_type = UIEvents::InputTypes::deleteWordForward;+ break;+ case Type::DeleteToEndOfParagraph:+ input_type = UIEvents::InputTypes::deleteHardLineForward;+ break;+ default:+ break;+ }+ GC::Root<DOM::Document> rooted_document { document };+ GC::Root<JS::Cell> rooted_target { target->as_cell() };+ GC::Root<DOM::Node> scope { target->mouse_selection_scope() };+ GC::Root<DOM::StaticRange> range { target->deletion_target_range(input_type) };+ if (!range)+ return EventResult::Handled;+ bool selected = false;+ if (auto* control = document->focused_area() ? as_if<HTML::FormAssociatedTextControlElement>(*document->focused_area()) : nullptr)+ selected = control->selection_start() != control->selection_end();+ else if (auto selection = document->get_selection())+ selected = !selection->is_collapsed();+ if (selected)+ input_type = first_is_one_of(command.type, Type::DeleteBackward, Type::DeleteWordBackward)+ ? UIEvents::InputTypes::deleteContentBackward+ : UIEvents::InputTypes::deleteContentForward;+ auto result = input_event(UIEvents::EventNames::beforeinput, input_type, m_navigable, 0u, range.ptr());+ if (result != EventResult::Accepted)+ return result;+ if (m_navigable->active_document() != document || !document->is_fully_active()+ || document->active_input_events_target() != target || !scope || !scope->is_connected()+ || target->mouse_selection_scope().ptr() != scope.ptr())+ return EventResult::Handled;+ if (!target->deletion_target_range(input_type))+ return EventResult::Handled;+ target->handle_delete(input_type);+ break;+ }+ default:+ return EventResult::Dropped;+ }+ return EventResult::Handled;+}++EventResult EventHandler::handle_keydown(UIEvents::KeyCode key, u32 modifiers, u32 code_point, bool repeat, bool should_insert_text, bool async_scroll_performed_default_action, ReadonlySpan<TextEditingCommand> editing_commands, bool native_editing_binding_resolved){if (!m_navigable->active_document())return EventResult::Dropped;@@ -1647,6 +1758,9 @@ EventResult EventHandler::handle_keydown(UIEvents::KeyCode key, u32 modifiers, ureturn EventResult::Handled;};+ GC::Root<DOM::Document> native_command_document;+ if (native_editing_binding_resolved)+ native_command_document = m_navigable->active_document();auto dispatch_result = fire_keyboard_event(UIEvents::EventNames::keydown, m_navigable, key, modifiers, code_point, repeat);if (dispatch_result != EventResult::Accepted)return dispatch_result;@@ -1664,6 +1778,20 @@ EventResult EventHandler::handle_keydown(UIEvents::KeyCode key, u32 modifiers, ureturn dispatch_result;}+ if (native_editing_binding_resolved) {+ for (auto const& command : editing_commands) {+ if (m_navigable->active_document().ptr() != native_command_document.ptr() || !native_command_document->is_fully_active())+ return EventResult::Dropped;+ auto navigable = m_navigable->page().hosted_focused_navigable();+ if (!navigable)+ return EventResult::Dropped;+ auto result = navigable->event_handler().handle_text_editing_command(command);+ if (result != EventResult::Handled && result != EventResult::Accepted)+ return result;+ }+ return EventResult::Handled;+ }+// The compositor already performed this key's default action. Do not scroll twice, or insert text if focus has// since moved into an editor. DOM keydown/keypress dispatch above is still required.if (async_scroll_performed_default_action)@@ -2603,7 +2731,7 @@ EventResult EventHandler::fire_text_input_event(HTML::LocalNavigable& navigable,return EventResult::Accepted;}-EventResult EventHandler::input_event(Utf16FlyString const& event_name, Utf16FlyString const& input_type, HTML::LocalNavigable& navigable, Variant<u32, Utf16String> code_point_or_string)+EventResult EventHandler::input_event(Utf16FlyString const& event_name, Utf16FlyString const& input_type, HTML::LocalNavigable& navigable, Variant<u32, Utf16String> code_point_or_string, GC::Ptr<DOM::StaticRange> deletion_range){auto document = navigable.active_document();if (!document)@@ -2611,6 +2739,13 @@ EventResult EventHandler::input_event(Utf16FlyString const& event_name, Utf16Flyif (!document->is_fully_active())return EventResult::Dropped;+ GC::Root<DOM::StaticRange> rooted_range { deletion_range };+ auto target_ranges = target_ranges_for_input_event(*document, input_type);+ if (deletion_range) {+ target_ranges.clear();+ if (!document->focused_area() || !as_if<HTML::FormAssociatedTextControlElement>(*document->focused_area()))+ target_ranges.append(*deletion_range);+ }UIEvents::InputEventInit input_event_init;code_point_or_string.visit(@@ -2636,11 +2771,11 @@ EventResult EventHandler::input_event(Utf16FlyString const& event_name, Utf16Fly}}- auto event = UIEvents::InputEvent::create_from_platform_event(event_name, input_event_init, target_ranges_for_input_event(*document, input_type), HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*document)));+ auto event = UIEvents::InputEvent::create_from_platform_event(event_name, input_event_init, move(target_ranges), HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*document)));return focused_area->dispatch_event(event) ? EventResult::Accepted : EventResult::Cancelled;}- auto event = UIEvents::InputEvent::create_from_platform_event(event_name, input_event_init, target_ranges_for_input_event(*document, input_type), HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*document)));+ auto event = UIEvents::InputEvent::create_from_platform_event(event_name, input_event_init, move(target_ranges), HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*document)));if (auto* body = document->body())return body->dispatch_event(event) ? EventResult::Accepted : EventResult::Cancelled;diff --git a/Libraries/LibWeb/Page/EventHandler.h b/Libraries/LibWeb/Page/EventHandler.hindex 32a6f4fdce1..59ca2c0bdbc 100644--- a/Libraries/LibWeb/Page/EventHandler.h+++ b/Libraries/LibWeb/Page/EventHandler.h@@ -82,7 +82,8 @@ public:void update_cursor_after_rendering_update();GC::Ptr<DOM::Node> target_node_for_mouse_position(CSSPixelPoint);- EventResult handle_keydown(UIEvents::KeyCode, unsigned modifiers, u32 code_point, bool repeat, bool should_insert_text, bool async_scroll_performed_default_action = false);+ EventResult handle_keydown(UIEvents::KeyCode, unsigned modifiers, u32 code_point, bool repeat, bool should_insert_text, bool async_scroll_performed_default_action = false, ReadonlySpan<TextEditingCommand> editing_commands = {}, bool native_editing_binding_resolved = false);+ EventResult handle_text_editing_command(TextEditingCommand const&);struct KeyboardScrollSnapshot {Compositing::KeyboardScrollState state;Vector<GC::Weak<DOM::EventTarget>> event_path;@@ -128,7 +129,7 @@ private:EventResult fire_keyboard_event(Utf16FlyString const& event_name, HTML::LocalNavigable&, UIEvents::KeyCode, unsigned modifiers, u32 code_point, bool repeat);[[nodiscard]] EventResult fire_text_input_event(HTML::LocalNavigable&, Utf16String const& data);- [[nodiscard]] EventResult input_event(Utf16FlyString const& event_name, Utf16FlyString const& input_type, HTML::LocalNavigable&, Variant<u32, Utf16String> code_point_or_string);+ [[nodiscard]] EventResult input_event(Utf16FlyString const& event_name, Utf16FlyString const& input_type, HTML::LocalNavigable&, Variant<u32, Utf16String> code_point_or_string, GC::Ptr<DOM::StaticRange> deletion_range = nullptr);[[nodiscard]] EventResult perform_copy_action();[[nodiscard]] EventResult perform_cut_action();diff --git a/Libraries/LibWeb/Page/Page.cpp b/Libraries/LibWeb/Page/Page.cppindex 42503cb8e5f..333fbadbd71 100644--- a/Libraries/LibWeb/Page/Page.cpp+++ b/Libraries/LibWeb/Page/Page.cpp@@ -528,7 +528,7 @@ EventResult Page::handle_pinch_event(DevicePixelPoint position, unsigned modifiereturn handle_pinch_event(local_traversable(), position, modifiers, scale);}-EventResult Page::handle_keydown(UIEvents::KeyCode key, unsigned modifiers, u32 code_point, bool repeat, bool should_insert_text, bool async_scroll_performed_default_action)+EventResult Page::handle_keydown(UIEvents::KeyCode key, unsigned modifiers, u32 code_point, bool repeat, bool should_insert_text, bool async_scroll_performed_default_action, ReadonlySpan<TextEditingCommand> editing_commands, bool native_editing_binding_resolved){// The compositor forwards these updates ahead of keyboard events. Both DOM listeners and a main-thread// fallback default action must observe the offsets that have already been presented.@@ -536,7 +536,7 @@ EventResult Page::handle_keydown(UIEvents::KeyCode key, unsigned modifiers, u32if (!navigable)return EventResult::Dropped;navigable->local_root()->adopt_pending_async_scroll_offsets(Compositing::AsyncScrollUpdateFreshness::Pushed);- return navigable->event_handler().handle_keydown(key, modifiers, code_point, repeat, should_insert_text, async_scroll_performed_default_action);+ return navigable->event_handler().handle_keydown(key, modifiers, code_point, repeat, should_insert_text, async_scroll_performed_default_action, editing_commands, native_editing_binding_resolved);}EventResult Page::handle_keyup(UIEvents::KeyCode key, unsigned modifiers, u32 code_point, bool repeat)diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.hindex 7d99588528e..9aa2a313be1 100644--- a/Libraries/LibWeb/Page/Page.h+++ b/Libraries/LibWeb/Page/Page.h@@ -90,6 +90,7 @@#include <LibWebCommon/Page/PendingDialog.h>#include <LibWebCommon/Page/QueuedInputEvent.h>#include <LibWebCommon/Page/SpellingError.h>+#include <LibWebCommon/Page/TextEditingCommand.h>#include <LibWebCommon/Page/ViewportIsFullscreen.h>#include <LibWebCommon/PixelUnits.h>#include <LibWebCommon/StorageAPI/StorageEndpoint.h>@@ -207,7 +208,7 @@ public:EventResult handle_drag_and_drop_event(DragEvent::Type, DevicePixelPoint, DevicePixelPoint screen_position, unsigned button, unsigned buttons, unsigned modifiers, Vector<HTML::SelectedFile> files);EventResult handle_pinch_event(DevicePixelPoint point, unsigned modifiers, double scale);- EventResult handle_keydown(UIEvents::KeyCode, unsigned modifiers, u32 code_point, bool repeat, bool should_insert_text, bool async_scroll_performed_default_action = false);+ EventResult handle_keydown(UIEvents::KeyCode, unsigned modifiers, u32 code_point, bool repeat, bool should_insert_text, bool async_scroll_performed_default_action = false, ReadonlySpan<TextEditingCommand> editing_commands = {}, bool native_editing_binding_resolved = false);EventResult handle_keyup(UIEvents::KeyCode, unsigned modifiers, u32 code_point, bool repeat);void handle_gamepad_connected(Gamepad::GamepadDescription const&);diff --git a/Libraries/LibWeb/Painting/HitTestDisplayList.cpp b/Libraries/LibWeb/Painting/HitTestDisplayList.cppindex 01cd710393f..f2f23a6f5f7 100644--- a/Libraries/LibWeb/Painting/HitTestDisplayList.cpp+++ b/Libraries/LibWeb/Painting/HitTestDisplayList.cpp@@ -311,9 +311,12 @@ Optional<CaretPosition> HitTestDisplayList::caret_position_at_line_edge(Layout::if (!is_current())return {};CaretPositionQueryContext context { node, offset };- auto type = edge == CaretLineEdge::Start ? CaretPositionType::Before : CaretPositionType::After;+ auto type = first_is_one_of(edge, CaretLineEdge::Start, CaretLineEdge::Left) ? CaretPositionType::Before : CaretPositionType::After;+ auto physical = first_is_one_of(edge, CaretLineEdge::Left, CaretLineEdge::Right);+ QueryContext query_context { nullptr, m_arena->document() };+ auto scope = physical ? const_cast<DOM::Node&>(node).editing_host() : nullptr;Layout::RustFFI::FfiCaretAt caret_at;- Layout::RustFFI::layout_hit_test_caret_at_line_edge(m_arena->host(), &read, context.query, offset, affinity == TextAffinity::Downstream, to_underlying(type), &caret_at);+ Layout::RustFFI::layout_hit_test_caret_at_line_edge(m_arena->host(), &read, query_context.callbacks(), context.query, offset, affinity == TextAffinity::Downstream, to_underlying(type), physical, ffi_identity_of(scope.ptr()), &caret_at);return caret_position_from(caret_at);}diff --git a/Libraries/LibWeb/Painting/HitTestDisplayList.h b/Libraries/LibWeb/Painting/HitTestDisplayList.hindex a88c7d3bb52..b080f38be2b 100644--- a/Libraries/LibWeb/Painting/HitTestDisplayList.h+++ b/Libraries/LibWeb/Painting/HitTestDisplayList.h@@ -31,6 +31,8 @@ enum class CaretPositionMode : u8 {enum class CaretLineEdge : u8 {Start,End,+ Left,+ Right,};enum class CaretLineDirection : u8 {diff --git a/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rsindex e6693e59207..de95182dfbb 100644--- a/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs@@ -118,7 +118,9 @@ fn apply_text_overflow_to_line(line: &mut line_box::LineBoxData) {length_in_code_units: 1,glyph_width: ellipsis_inline_size,glyph_id: font.glyph_id_for_code_point(ELLIPSIS_CODE_POINT),+ cluster_start: 0,should_paint: true,+ is_rtl: false,});line.fragments[index].inline_length = CssPixels::nearest_value_for_f32(last_kept_end + ellipsis_inline_size);line.fragments[index].has_text_overflow_ellipsis = true;diff --git a/Libraries/LibWeb/Rust/src/layout/line_box.rs b/Libraries/LibWeb/Rust/src/layout/line_box.rsindex 01ce53c6d53..04a7457a93b 100644--- a/Libraries/LibWeb/Rust/src/layout/line_box.rs+++ b/Libraries/LibWeb/Rust/src/layout/line_box.rs@@ -127,7 +127,7 @@ impl LineBoxData {if can_merge {let last = self.fragments.last_mut().unwrap();last.length_in_code_units += length;- last.append_glyph_run(glyphs.unwrap(), content_inline_size);+ last.append_glyph_run(glyphs.unwrap(), content_inline_size, start - last.start);if trailing_whitespace.length_in_code_units == length {last.trailing_whitespace.length_in_code_units += trailing_whitespace.length_in_code_units;last.trailing_whitespace.inline_size += trailing_whitespace.inline_size;diff --git a/Libraries/LibWeb/Rust/src/layout/line_box_fragment.rs b/Libraries/LibWeb/Rust/src/layout/line_box_fragment.rsindex 2a1e1f3908c..8d37f879b62 100644--- a/Libraries/LibWeb/Rust/src/layout/line_box_fragment.rs+++ b/Libraries/LibWeb/Rust/src/layout/line_box_fragment.rs@@ -169,15 +169,16 @@ impl LineBoxFragmentData {}}- pub(crate) fn append_glyph_run(&mut self, run: GlyphData, run_inline_size: CssPixels) {+ pub(crate) fn append_glyph_run(&mut self, run: GlyphData, run_inline_size: CssPixels, text_offset: usize) {+ let text_offset = u32::try_from(text_offset).expect("text offset fits a shaping cluster index");match self.direction {- direction::LTR => self.append_glyph_run_ltr(run, run_inline_size),- direction::RTL => self.append_glyph_run_rtl(run, run_inline_size),+ direction::LTR => self.append_glyph_run_ltr(run, run_inline_size, text_offset),+ direction::RTL => self.append_glyph_run_rtl(run, run_inline_size, text_offset),_ => panic!("invalid direction"),}}- fn append_glyph_run_ltr(&mut self, run: GlyphData, run_inline_size: CssPixels) {+ fn append_glyph_run_ltr(&mut self, run: GlyphData, run_inline_size: CssPixels, text_offset: u32) {let run_direction = self.resolve_glyph_run_direction(run.text_type);let inline_offset = self.inline_length.to_double() as f32;@@ -199,6 +200,7 @@ impl LineBoxFragmentData {direction::LTR => {for mut glyph in run.glyphs.iter().copied() {glyph.x += inline_offset;+ glyph.cluster_start += text_offset;existing.push(glyph);}}@@ -211,6 +213,7 @@ impl LineBoxFragmentData {}for mut glyph in run.glyphs.iter().copied() {glyph.x += self.insert_position;+ glyph.cluster_start += text_offset;existing.push(glyph);}}@@ -219,7 +222,7 @@ impl LineBoxFragmentData {self.inline_length += run_inline_size;}- fn append_glyph_run_rtl(&mut self, run: GlyphData, run_inline_size: CssPixels) {+ fn append_glyph_run_rtl(&mut self, run: GlyphData, run_inline_size: CssPixels, text_offset: u32) {let run_direction = self.resolve_glyph_run_direction(run.text_type);let run_offset = run_inline_size.to_double() as f32;@@ -246,6 +249,7 @@ impl LineBoxFragmentData {}for mut glyph in run.glyphs.iter().copied() {glyph.x += self.insert_position;+ glyph.cluster_start += text_offset;existing.push(glyph);}}@@ -255,7 +259,10 @@ impl LineBoxFragmentData {glyph.x += run_offset;}}- existing.extend_from_slice(&run.glyphs);+ for mut glyph in run.glyphs.iter().copied() {+ glyph.cluster_start += text_offset;+ existing.push(glyph);+ }}_ => unreachable!(),}diff --git a/Libraries/LibWeb/Rust/src/layout/text_chunker.rs b/Libraries/LibWeb/Rust/src/layout/text_chunker.rsindex 8602272f945..e012f957968 100644--- a/Libraries/LibWeb/Rust/src/layout/text_chunker.rs+++ b/Libraries/LibWeb/Rust/src/layout/text_chunker.rs@@ -683,11 +683,9 @@ impl<'text> TextChunker<'text> {continue 'restart;}- // NB: The current index can sit past the end here after consuming trailing tabs; the retired C++- // iterator read the direction class through it anyway, so the bounds check turns an out-of-bounds- // read into a non-split.- if self.should_wrap_lines- && self.current_index < self.text.len()+ // Tabs can advance the cursor past the text. Split shaping runs at direction changes independently+ // of line wrapping, while keeping the direction lookup inside the text.+ if self.current_index < self.text.len()&& pending.text_type != self.current_text_type()&& let Some(chunk) = self.try_commit_chunk_at_cursor(&pending, can_break_at_current_position){diff --git a/Libraries/LibWeb/Rust/src/painting/caret.rs b/Libraries/LibWeb/Rust/src/painting/caret.rsindex f0e3a47b49b..1a708a42e75 100644--- a/Libraries/LibWeb/Rust/src/painting/caret.rs+++ b/Libraries/LibWeb/Rust/src/painting/caret.rs@@ -4,7 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/-use crate::css::css_pixels::CssPixelRect;+use crate::css::css_pixels::{CssPixelRect, CssPixels};use crate::layout::node_data::NodeSlotId;use crate::painting::paint_read::PaintRead;use crate::painting::paintable_data::{FragmentRecord, SELECTION_STATE_START_AND_END};@@ -22,9 +22,23 @@ fn caret_rect_in_fragment(owner: NodeSlotId,fragment: &FragmentRecord,offset: usize,+ affinity_is_downstream: bool,) -> CaretRectResult {+ let mut rect = text_fragment::range_rect(layout_arena, fragment, SELECTION_STATE_START_AND_END, offset, offset);+ if let Some(offsets) =+ text_fragment::compute_selection_offsets(layout_arena, fragment, SELECTION_STATE_START_AND_END, offset, offset)+ && let Some(coordinate) = text_fragment::caret_inline_offset(fragment, offsets.start, affinity_is_downstream)+ {+ let origin = text_fragment::absolute_rect(layout_arena, fragment);+ let coordinate = CssPixels::nearest_value_for_f32(coordinate);+ if text_fragment::is_horizontal(fragment) {+ rect.x = origin.x + coordinate;+ } else {+ rect.y = origin.y + coordinate;+ }+ }CaretRectResult {- rect: text_fragment::range_rect(layout_arena, fragment, SELECTION_STATE_START_AND_END, offset, offset),+ rect,style_source: text_fragment::style_source(layout_arena, fragment),owner,node: fragment.layout_node,@@ -57,7 +71,13 @@ pub(crate) fn caret_rect_for_position(let (block, index) = direct.or(fallback)?;let side = layout_arena.committed_side_data(block);let fragment = &side.fragments()[index as usize];- Some(caret_rect_in_fragment(layout_arena, block, fragment, offset))+ Some(caret_rect_in_fragment(+ layout_arena,+ block,+ fragment,+ offset,+ affinity_is_downstream,+ ))}pub(crate) fn caret_rect_in_dom_range(diff --git a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rsindex fa8ec0e784b..b5aa2d39856 100644--- a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs+++ b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs@@ -1195,15 +1195,30 @@ pub unsafe extern "C" fn layout_hit_test_caret_position_from_point(pub unsafe extern "C" fn layout_hit_test_caret_at_line_edge(host: &crate::render_state::DocumentHost,read: &crate::render_state::BegunRead,+ callbacks: crate::painting::host::FfiHitTestQueryCallbacks,query: crate::painting::host::FfiCaretPositionQuery,offset: usize,affinity_is_downstream: bool,edge: u8,+ physical: bool,+ scope: crate::painting::host::FfiNodeIdentity,out: &mut FfiCaretAt,) {let edge = crate::painting::hit_test::caret::CaretPositionType::from_u8(edge);+ // SAFETY: Guaranteed by the entry point's contract.+ let main_thread = unsafe { main_thread(host) };*out = with_hit_test_list_and_caret_lines(host, read, None, |list, arena| {- list.caret_at_line_edge(arena, &query, offset, affinity_is_downstream, edge)+ list.caret_at_line_edge(+ &main_thread,+ arena,+ &callbacks,+ &query,+ offset,+ affinity_is_downstream,+ edge,+ physical,+ scope,+ )}).unwrap_or_else(FfiCaretAt::none);}diff --git a/Libraries/LibWeb/Rust/src/painting/hit_test/caret.rs b/Libraries/LibWeb/Rust/src/painting/hit_test/caret.rsindex 11b3d6ba63c..b5a37c18f2f 100644--- a/Libraries/LibWeb/Rust/src/painting/hit_test/caret.rs+++ b/Libraries/LibWeb/Rust/src/painting/hit_test/caret.rs@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+use super::resolve::with_item_fragment;use super::*;use crate::painting::host::{FfiCaretAt, FfiCaretBoundaryKind, FfiCaretPositionQuery, FfiHitTestQueryCallbacks, FfiNodeIdentity,@@ -251,9 +252,18 @@ impl HitTestList {}pub fn item_at_line_edge(&self, line_index: usize, position_type: CaretPositionType) -> usize {- // INTEROP: Home and End operate on visual lines in other engines. Choose the furthest caret-capable painted- // item along the logical inline axis instead of assuming that display-list order or DOM order describes that- // edge.+ self.item_at_line_edge_matching(line_index, position_type, |_| true)+ .expect("a caret line has at least one item")+ }++ fn item_at_line_edge_matching(+ &self,+ line_index: usize,+ position_type: CaretPositionType,+ accepts_item: impl Fn(usize) -> bool,+ ) -> Option<usize> {+ // Choose the furthest caret-capable painted item along the logical inline axis. Display-list order and DOM+ // order don't necessarily describe that edge.debug_assert!(self.caret_lines_built);let line = self.caret_lines[line_index].clone();let first_item = self.first_item_of_line(&line);@@ -287,8 +297,9 @@ impl HitTestList {coordinate > best_coordinate}};- let mut best_item_index = self.caret_item_indices[line.first_caret_item_index];- let mut best_coordinate = coordinate_for_item(&self.items[best_item_index]);+ let first_index = self.caret_item_indices[line.first_caret_item_index];+ let mut best_item_index = accepts_item(first_index).then_some(first_index);+ let mut best_coordinate = coordinate_for_item(&self.items[first_index]);let item_is_on_line = |item: &HitTestItem| -> bool {if let Some(recorded_line) = first_item.recorded_caret_line() {return item.recorded_caret_line() == Some(recorded_line);@@ -305,12 +316,12 @@ impl HitTestList {// inferred visual line even when other caret runs separate them.for item_index in &self.caret_item_indices {let item = &self.items[*item_index];- if !item_is_on_line(item) {+ if !item_is_on_line(item) || !accepts_item(*item_index) {continue;}let coordinate = coordinate_for_item(item);- if coordinate_is_closer_to_line_edge(coordinate, best_coordinate) {- best_item_index = *item_index;+ if best_item_index.is_none() || coordinate_is_closer_to_line_edge(coordinate, best_coordinate) {+ best_item_index = Some(*item_index);best_coordinate = coordinate;}}@@ -882,21 +893,54 @@ impl HitTestList {/// The caret position at the start or end of the painted line holding the position. A visual line can span several/// DOM nodes and atomic inline boxes, so a text-node or block-element boundary is not necessarily a line boundary.+ #[allow(clippy::too_many_arguments)]pub(crate) fn caret_at_line_edge(&self,+ main_thread: &crate::stage::MainThread,arena: &impl PaintRead,+ callbacks: &FfiHitTestQueryCallbacks,query: &FfiCaretPositionQuery,offset: usize,affinity_is_downstream: bool,edge: CaretPositionType,+ physical: bool,+ scope: FfiNodeIdentity,) -> Option<FfiCaretAt> {let line_index = self.caret_line_for_position(arena, query, offset, affinity_is_downstream)?;- self.caret_at_item(- arena,- self.item_at_line_edge(line_index, edge),- CssPixelPoint::default(),- edge,- )+ let mut logical_edge = edge;+ if physical+ && self+ .first_item_of_line(&self.caret_lines[line_index])+ .inline_axis_is_reverse+ {+ logical_edge = if edge == CaretPositionType::Before {+ CaretPositionType::After+ } else {+ CaretPositionType::Before+ };+ }+ let item_index = self.item_at_line_edge_matching(line_index, logical_edge, |index| {+ scope.is_none() || callbacks.contains(main_thread, scope, self.item_target(arena, index))+ })?;+ let mut caret = self.caret_at_item(arena, item_index, CssPixelPoint::default(), logical_edge)?;+ if physical {+ let item = &self.items[item_index];+ if item.kind == HitTestItemKind::TextFragment+ && let Some((offset, upstream)) = with_item_fragment(arena, item, |fragment| {+ crate::painting::text_fragment::physical_edge_offset(+ arena,+ fragment,+ edge == CaretPositionType::Before,+ )+ })+ .flatten()+ {+ caret.caret.offset = offset;+ caret.caret.affinity_is_upstream = upstream;+ caret.caret.has_debug_rect = false;+ }+ }+ Some(caret)}/// The caret position on the visually adjacent line within `scope`, preserving the requested inline coordinate.diff --git a/Libraries/LibWeb/Rust/src/painting/text_fragment.rs b/Libraries/LibWeb/Rust/src/painting/text_fragment.rsindex 5e347b0b477..ce25c188385 100644--- a/Libraries/LibWeb/Rust/src/painting/text_fragment.rs+++ b/Libraries/LibWeb/Rust/src/painting/text_fragment.rs@@ -63,7 +63,7 @@ pub(crate) fn absolute_line_box_rect(rect}-fn is_horizontal(fragment: &FragmentRecord) -> bool {+pub(crate) fn is_horizontal(fragment: &FragmentRecord) -> bool {fragment.writing_mode == crate::css::css_enums::writing_mode::HORIZONTAL_TB}@@ -413,6 +413,58 @@ impl GraphemeEdgeTracker {}}+pub(crate) fn physical_edge_offset(+ arena: &impl PaintRead,+ fragment: &FragmentRecord,+ left: bool,+) -> Option<(usize, bool)> {+ let run = fragment.glyph_run.as_ref()?;+ let glyph = run+ .glyphs+ .iter()+ .filter(|glyph| glyph.length_in_code_units > 0 && glyph.glyph_width > 0.0)+ .min_by(|a, b| {+ if left {+ a.x.total_cmp(&b.x)+ } else {+ (b.x + b.glyph_width).total_cmp(&(a.x + a.glyph_width))+ }+ })?;+ let boundary = glyph.cluster_start as usize+ + if left == glyph.is_rtl {+ glyph.length_in_code_units+ } else {+ 0+ };+ Some((+ arena.dom_offset_for_rendered_text_offset(+ fragment.layout_node,+ fragment.start + boundary,+ crate::layout::RenderedTextBoundary::End,+ ),+ left == glyph.is_rtl,+ ))+}++pub(crate) fn caret_inline_offset(fragment: &FragmentRecord, offset: usize, downstream: bool) -> Option<f32> {+ let run = fragment.glyph_run.as_ref()?;+ let mut fallback = None;+ for glyph in run.glyphs.iter().filter(|glyph| glyph.length_in_code_units > 0) {+ let start = glyph.cluster_start as usize;+ let end = start + glyph.length_in_code_units;+ if offset < start || offset > end {+ continue;+ }+ let fraction = (offset - start) as f32 / glyph.length_in_code_units as f32;+ let coordinate = glyph.x + glyph.glyph_width * if glyph.is_rtl { 1.0 - fraction } else { fraction };+ if (offset > start && offset < end) || (downstream && offset == start) || (!downstream && offset == end) {+ return Some(coordinate);+ }+ fallback = Some(coordinate);+ }+ fallback+}+pub(crate) fn index_in_node_for_point(layout_arena: &impl PaintRead,fragment: &FragmentRecord,diff --git a/Libraries/LibWeb/Selection/CaretNavigation.cpp b/Libraries/LibWeb/Selection/CaretNavigation.cppindex 3489df1a1c9..ab14181ab15 100644--- a/Libraries/LibWeb/Selection/CaretNavigation.cpp+++ b/Libraries/LibWeb/Selection/CaretNavigation.cpp@@ -17,6 +17,7 @@#include <LibWeb/Editing/Internal/Algorithms.h>#include <LibWeb/HTML/HTMLBRElement.h>#include <LibWeb/HTML/Window.h>+#include <LibWeb/Layout/Box.h>#include <LibWeb/Layout/Node.h>#include <LibWeb/Painting/BoxViews.h>#include <LibWeb/Painting/HitTestDisplayList.h>@@ -625,6 +626,59 @@ Optional<CaretLocation> CaretNavigator::move_by_page(CaretLocation const& locatireturn result;}+Optional<CaretLocation> CaretNavigator::move_to_paragraph_boundary(CaretLocation const& location, SelectionDirection direction)+{+ auto editing_host = location.node->editing_host();+ if (!editing_host)+ return {};+ m_document->update_layout_if_needed_for_node(*editing_host, DOM::UpdateLayoutReason::CursorLineNavigation);+ auto current = canonical_location_for_editing(location);+ Layout::ForcedReadScope read { *m_document };+ for (;;) {+ auto* text = as_if<DOM::Text>(*current.node);+ if (!text)+ return current;+ auto data = text->data().utf16_view();+ auto offset = min(current.offset, data.length_in_code_units());+ auto white_space = Editing::resolved_keyword(*text, CSS::PropertyID::WhiteSpaceCollapse);+ auto preserves_newlines = white_space.has_value() && first_is_one_of(*white_space, CSS::Keyword::Preserve, CSS::Keyword::PreserveBreaks, CSS::Keyword::BreakSpaces);+ if (direction == SelectionDirection::Backward) {+ while (offset > 0 && (!preserves_newlines || data.code_unit_at(offset - 1) != '\n'))+ --offset;+ } else {+ while (offset < data.length_in_code_units() && (!preserves_newlines || data.code_unit_at(offset) != '\n'))+ ++offset;+ }+ current = { *text, offset, TextAffinity::Downstream };+ if ((direction == SelectionDirection::Backward && offset > 0) || (direction == SelectionDirection::Forward && offset < data.length_in_code_units()))+ return current;++ auto* node = static_cast<DOM::Node*>(text);+ GC::Ptr<DOM::Text> next_text;+ while (node) {+ node = direction == SelectionDirection::Forward ? node->next_in_pre_order(editing_host.ptr()) : node->previous_in_pre_order();+ if (!node || node == editing_host.ptr() || !editing_host->is_inclusive_ancestor_of(*node))+ return current;+ if (node->is_inclusive_ancestor_of(*text))+ continue;+ if (is<HTML::HTMLBRElement>(*node) && node->layout_node(read))+ return current;+ if (is_empty_line_host(*node))+ return current;+ auto* candidate = as_if<DOM::Text>(*node);+ if (!candidate || !candidate->is_editable() || candidate->editing_host() != editing_host || !text_node_has_rendered_text(*candidate))+ continue;+ if (!boundary_visual_lines_share_inline_context(*text, *candidate))+ return current;+ next_text = candidate;+ break;+ }+ if (!next_text)+ return current;+ current = { *next_text, direction == SelectionDirection::Forward ? 0 : next_text->length(), TextAffinity::Downstream };+ }+}+Optional<CaretLocation> CaretNavigator::move(CaretLocation const& location, SelectionAlteration alteration, SelectionDirection direction, SelectionGranularity granularity, Optional<CSSPixels> preferred_inline_coordinate){auto* text = as_if<DOM::Text>(*location.node);@@ -632,6 +686,9 @@ Optional<CaretLocation> CaretNavigator::move(CaretLocation const& location, Seleif (granularity == SelectionGranularity::DocumentBoundary)return move_to_editing_host_boundary(location, direction);+ if (granularity == SelectionGranularity::ParagraphBoundary)+ return move_to_paragraph_boundary(location, direction);+if (granularity == SelectionGranularity::Page) {if (!preferred_inline_coordinate.has_value())return {};@@ -679,10 +736,12 @@ Optional<CaretLocation> CaretNavigator::move(CaretLocation const& location, Selereturn move_by_word(location, alteration, direction);}- if (granularity == SelectionGranularity::LineBoundary) {+ if (granularity == SelectionGranularity::LineBoundary || granularity == SelectionGranularity::PhysicalLineBoundary) {Layout::ForcedReadScope read { *m_document };m_document->update_layout_if_needed_for_node(location.node, DOM::UpdateLayoutReason::CursorLineNavigation);auto edge = direction == SelectionDirection::Forward ? Painting::CaretLineEdge::End : Painting::CaretLineEdge::Start;+ if (granularity == SelectionGranularity::PhysicalLineBoundary)+ edge = direction == SelectionDirection::Forward ? Painting::CaretLineEdge::Right : Painting::CaretLineEdge::Left;auto position = m_document->caret_position_at_line_edge(read, location.node, location.offset, location.affinity, edge);if (!position.has_value())return {};diff --git a/Libraries/LibWeb/Selection/CaretNavigation.h b/Libraries/LibWeb/Selection/CaretNavigation.hindex b37020aaf1e..ccb692d3f0d 100644--- a/Libraries/LibWeb/Selection/CaretNavigation.h+++ b/Libraries/LibWeb/Selection/CaretNavigation.h@@ -31,6 +31,8 @@ enum class SelectionGranularity : u8 {Line,Page,LineBoundary,+ ParagraphBoundary,+ PhysicalLineBoundary,// The boundary of the active editing host, which is the effective document for contenteditable navigation.DocumentBoundary,};@@ -61,6 +63,7 @@ public:private:Optional<CaretLocation> move_to_adjacent_caret_host(CaretLocation const&, SelectionDirection);Optional<CaretLocation> move_to_editing_host_boundary(CaretLocation const&, SelectionDirection);+ Optional<CaretLocation> move_to_paragraph_boundary(CaretLocation const&, SelectionDirection);Optional<CaretLocation> move_by_page(CaretLocation const&, SelectionDirection, CSSPixels inline_coordinate);Optional<CaretLocation> move_by_word(CaretLocation const&, SelectionAlteration, SelectionDirection);GC::Ptr<DOM::Node> adjacent_caret_host(DOM::Node&, DOM::Node& editing_host, SelectionDirection);diff --git a/Libraries/LibWeb/Selection/Selection.cpp b/Libraries/LibWeb/Selection/Selection.cppindex 8403d7d531a..016d73ed44c 100644--- a/Libraries/LibWeb/Selection/Selection.cpp+++ b/Libraries/LibWeb/Selection/Selection.cpp@@ -605,7 +605,7 @@ GC::Ptr<DOM::Position> Selection::cursor_position() constif (!m_range || !is_collapsed())return nullptr;- return DOM::Position::create(*m_range->start_container(), m_range->start_offset());+ return DOM::Position::create(*m_range->start_container(), m_range->start_offset(), m_focus_affinity);}void Selection::move_offset_to_next_character(bool collapse_selection)diff --git a/Libraries/LibWeb/TextAffinity.h b/Libraries/LibWeb/TextAffinity.hindex 46003f7151f..fc5eb23e847 100644--- a/Libraries/LibWeb/TextAffinity.h+++ b/Libraries/LibWeb/TextAffinity.h@@ -10,9 +10,8 @@namespace Web {-// Disambiguates the visual position of a text offset at a soft wrap boundary, where the same offset can render both-// at the end of one line and at the start of the next: Upstream renders at the end of the earlier line, Downstream-// at the start of the later line. For all other offsets, affinity has no effect.+// Disambiguates the visual position of a text offset at soft wraps and bidirectional run boundaries. Upstream uses+// the edge of the preceding logical text; Downstream uses the edge of the following logical text.enum class TextAffinity : u8 {Downstream,Upstream,diff --git a/Libraries/LibWeb/UIEvents/InputTypes.h b/Libraries/LibWeb/UIEvents/InputTypes.hindex 28da806181a..b1a7c6ec99e 100644--- a/Libraries/LibWeb/UIEvents/InputTypes.h+++ b/Libraries/LibWeb/UIEvents/InputTypes.h@@ -15,6 +15,9 @@ namespace Web::UIEvents::InputTypes {#define ENUMERATE_INPUT_TYPES \__ENUMERATE_INPUT_TYPE(deleteByCut) \__ENUMERATE_INPUT_TYPE(deleteContentBackward) \+ __ENUMERATE_INPUT_TYPE(deleteWordBackward) \+ __ENUMERATE_INPUT_TYPE(deleteWordForward) \+ __ENUMERATE_INPUT_TYPE(deleteHardLineForward) \__ENUMERATE_INPUT_TYPE(deleteContentForward) \__ENUMERATE_INPUT_TYPE(historyRedo) \__ENUMERATE_INPUT_TYPE(historyUndo) \diff --git a/Libraries/LibWeb/VisualLines.cpp b/Libraries/LibWeb/VisualLines.cppindex 0e1babc2d14..678d5a35037 100644--- a/Libraries/LibWeb/VisualLines.cpp+++ b/Libraries/LibWeb/VisualLines.cpp@@ -139,6 +139,39 @@ static size_t offset_in_visual_line_closest_to_inline_coordinate(Layout::BegunRe*inline_coordinate, line.start_offset);}+Optional<CursorLinePosition> compute_cursor_position_by_page(DOM::Text& text, size_t offset, TextAffinity affinity, bool forward, CSSPixels page_distance)+{+ Layout::ForcedReadScope read { text.document() };+ auto lines = visual_lines_with_up_to_date_layout(text);+ auto origin_index = visual_line_index_for_offset(lines, offset, affinity);+ if (!origin_index.has_value())+ return {};+ auto inline_coordinate = caret_inline_coordinate(read, text, lines[*origin_index], offset);+ auto origin_coordinate = text.document().caret_line_block_coordinate(read, text, offset, affinity);+ if (!origin_coordinate.has_value())+ return {};+ CursorLinePosition result { offset, affinity };+ auto index = *origin_index;+ for (;;) {+ if ((forward && index + 1 == lines.size()) || (!forward && index == 0)) {+ result = { forward ? text.length() : 0, TextAffinity::Downstream };+ break;+ }+ auto next_index = forward ? index + 1 : index - 1;+ auto next_offset = offset_in_visual_line_closest_to_inline_coordinate(read, text, lines[next_index], inline_coordinate);+ auto next_affinity = affinity_for_offset_on_line(lines, next_index, next_offset);+ auto coordinate = text.document().caret_line_block_coordinate(read, text, next_offset, next_affinity);+ if (!coordinate.has_value())+ break;+ auto distance = *coordinate > *origin_coordinate ? *coordinate - *origin_coordinate : *origin_coordinate - *coordinate;+ if (distance > page_distance)+ break;+ result = { next_offset, next_affinity };+ index = next_index;+ }+ return result;+}+Optional<CursorLinePosition> compute_cursor_position_on_next_line(DOM::Text const& dom_node, size_t current_offset, TextAffinity affinity){Layout::ForcedReadScope read { dom_node.document() };diff --git a/Libraries/LibWeb/VisualLines.h b/Libraries/LibWeb/VisualLines.hindex c58523da5ce..59b3b841c4b 100644--- a/Libraries/LibWeb/VisualLines.h+++ b/Libraries/LibWeb/VisualLines.h@@ -40,6 +40,7 @@ struct CursorLinePosition {Optional<CursorLinePosition> compute_cursor_position_on_next_line(DOM::Text const&, size_t current_offset, TextAffinity);Optional<CursorLinePosition> compute_cursor_position_on_previous_line(DOM::Text const&, size_t current_offset, TextAffinity);+Optional<CursorLinePosition> compute_cursor_position_by_page(DOM::Text&, size_t current_offset, TextAffinity, bool forward, CSSPixels page_distance);// One cursor step right or left. At a soft wrap boundary, the same offset has two visual positions (the end of the// earlier line and the start of the next); stepping visits both before moving to the adjacent grapheme.diff --git a/Libraries/LibWebCommon/Page/InputEvent.cpp b/Libraries/LibWebCommon/Page/InputEvent.cppindex a331c2d1f7f..06573016bdb 100644--- a/Libraries/LibWebCommon/Page/InputEvent.cpp+++ b/Libraries/LibWebCommon/Page/InputEvent.cpp@@ -13,7 +13,7 @@ namespace Web {KeyEvent KeyEvent::clone_without_browser_data() const{- return { type, key, modifiers, code_point, repeat, should_insert_text, nullptr, async_scroll_performed_default_action, id };+ return { type, key, modifiers, code_point, repeat, should_insert_text, nullptr, async_scroll_performed_default_action, id, editing_commands, native_editing_binding_resolved };}MouseEvent MouseEvent::clone_without_browser_data() const@@ -23,6 +23,24 @@ MouseEvent MouseEvent::clone_without_browser_data() const}+template<>+ErrorOr<void> IPC::encode(Encoder& encoder, Web::TextEditingCommand const& command)+{+ TRY(encoder.encode(command.type));+ TRY(encoder.encode(command.extend_selection));+ return {};+}++template<>+ErrorOr<Web::TextEditingCommand> IPC::decode(Decoder& decoder)+{+ auto type = TRY(decoder.decode<Web::TextEditingCommand::Type>());+ if (to_underlying(type) > to_underlying(Web::TextEditingCommand::Type::DeleteToEndOfParagraph))+ return Error::from_string_literal("Invalid text editing command");+ auto extend_selection = TRY(decoder.decode<bool>());+ return Web::TextEditingCommand { type, extend_selection };+}+template<>ErrorOr<void> IPC::encode(Encoder& encoder, Web::KeyEvent const& event){@@ -34,6 +52,8 @@ ErrorOr<void> IPC::encode(Encoder& encoder, Web::KeyEvent const& event)TRY(encoder.encode(event.should_insert_text));TRY(encoder.encode(event.async_scroll_performed_default_action));TRY(encoder.encode(event.id));+ TRY(encoder.encode(event.editing_commands));+ TRY(encoder.encode(event.native_editing_binding_resolved));return {};}@@ -48,8 +68,10 @@ ErrorOr<Web::KeyEvent> IPC::decode(Decoder& decoder)auto should_insert_text = TRY(decoder.decode<bool>());auto async_scroll_performed_default_action = TRY(decoder.decode<bool>());auto id = TRY(decoder.decode<u64>());+ auto editing_commands = TRY(decoder.decode<Vector<Web::TextEditingCommand>>());+ auto native_editing_binding_resolved = TRY(decoder.decode<bool>());- return Web::KeyEvent { type, key, modifiers, code_point, repeat, should_insert_text, nullptr, async_scroll_performed_default_action, id };+ return Web::KeyEvent { type, key, modifiers, code_point, repeat, should_insert_text, nullptr, async_scroll_performed_default_action, id, move(editing_commands), native_editing_binding_resolved };}template<>diff --git a/Libraries/LibWebCommon/Page/InputEvent.h b/Libraries/LibWebCommon/Page/InputEvent.hindex 713fb6b0107..99310fe558e 100644--- a/Libraries/LibWebCommon/Page/InputEvent.h+++ b/Libraries/LibWebCommon/Page/InputEvent.h@@ -8,10 +8,12 @@#include <AK/GenericShorthands.h>#include <AK/OwnPtr.h>+#include <AK/Vector.h>#include <LibGfx/Point.h>#include <LibIPC/Forward.h>#include <LibWebCommon/Export.h>#include <LibWebCommon/Page/AsyncScrollNodeStableID.h>+#include <LibWebCommon/Page/TextEditingCommand.h>#include <LibWebCommon/PixelUnits.h>#include <LibWebCommon/UIEvents/KeyCode.h>#include <LibWebCommon/UIEvents/MouseButton.h>@@ -44,6 +46,8 @@ struct WEBCOMMON_API KeyEvent {// The UI process numbers the events it sends, and a completion names the event it finished.u64 id { 0 };+ Vector<TextEditingCommand> editing_commands {};+ bool native_editing_binding_resolved { false };};inline bool is_keyboard_scroll_key(Web::UIEvents::KeyCode key, u32 modifiers)diff --git a/Libraries/LibWebCommon/Page/TextEditingCommand.h b/Libraries/LibWebCommon/Page/TextEditingCommand.hnew file mode 100644index 00000000000..85751935825--- /dev/null+++ b/Libraries/LibWebCommon/Page/TextEditingCommand.h@@ -0,0 +1,54 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Types.h>+#include <LibIPC/Forward.h>+#include <LibWebCommon/Export.h>++namespace Web {++struct TextEditingCommand {+ enum class Type : u8 {+ MoveBackward,+ MoveForward,+ MoveWordBackward,+ MoveWordForward,+ MoveUp,+ MoveDown,+ MoveToBeginningOfParagraph,+ MoveToEndOfParagraph,+ MoveToBeginningOfLine,+ MoveToEndOfLine,+ MoveToLeftEndOfLine,+ MoveToRightEndOfLine,+ PageUp,+ PageDown,+ DeleteBackward,+ DeleteForward,+ DeleteWordBackward,+ DeleteWordForward,+ DeleteToEndOfParagraph,+ };++ Type type { Type::MoveBackward };+ bool extend_selection { false };++ bool operator==(TextEditingCommand const&) const = default;+};++}++namespace IPC {++template<>+WEBCOMMON_API ErrorOr<void> encode(Encoder&, Web::TextEditingCommand const&);++template<>+WEBCOMMON_API ErrorOr<Web::TextEditingCommand> decode(Decoder&);++}diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cppindex 1d93392f267..727b1af3cb5 100644--- a/Libraries/LibWebView/ViewImplementation.cpp+++ b/Libraries/LibWebView/ViewImplementation.cpp@@ -698,7 +698,7 @@ void ViewImplementation::enqueue_input_event(Web::InputEvent event)mouse_event->wheel_delta_y /= zoom_level();}- if (key_event && Web::is_keyboard_scroll_key(key_event->key, Web::UIEvents::Mod_None)) {+ if (key_event && !key_event->native_editing_binding_resolved && Web::is_keyboard_scroll_key(key_event->key, Web::UIEvents::Mod_None)) {bool preceding_input_may_change_target = false;for (auto const& pending : m_pending_input_events) {auto const* key = pending.event.get_pointer<Web::KeyEvent>();diff --git a/Tests/LibWeb/AccessibilityBridge/input/native-control-key-editing.html b/Tests/LibWeb/AccessibilityBridge/input/native-control-key-editing.htmlnew file mode 100644index 00000000000..1f387c89dbb--- /dev/null+++ b/Tests/LibWeb/AccessibilityBridge/input/native-control-key-editing.html@@ -0,0 +1,57 @@+<!DOCTYPE html>+<meta charset="utf-8">+<title>Native text editing test</title>+<style>textarea { width: 80px; } #rich { width: 80px; }</style>+<button onclick="prepare('input')">Input</button>+<button onclick="prepare('textarea')">Textarea</button>+<button onclick="prepare('rich')">Rich text</button>+<button onclick="prepare('iframe')">Iframe</button>+<button onclick="prepare('cancel')">Cancel deletion</button>+<button onclick="prepare('keyboard-cancel')">Cancel keydown</button>+<button onclick="prompt('Enter text', 'hello world')">Prompt</button>+<input id="input" value="hello world">+<textarea id="textarea">abc+def</textarea>+<div id="rich" contenteditable>hello world</div>+<iframe id="iframe" srcdoc='<input value="hello world">'></iframe>+<input id="result" aria-label="Result" readonly value="ready">+<script>+let target;+let events = [];+let cancelDeletion = false;+let cancelKeyboard = false;+let serial = 0;+const result = document.getElementById("result");+function report() {+ if (!target) return;+ const doc = target.ownerDocument;+ const selection = doc.getSelection();+ result.value = JSON.stringify({ serial, value: target.value ?? target.textContent,+ start: target.selectionStart ?? selection.anchorOffset,+ end: target.selectionEnd ?? selection.focusOffset, events });+}+function prepare(kind) {+ cancelDeletion = kind === "cancel";+ cancelKeyboard = kind === "keyboard-cancel";+ target = kind === "iframe" ? document.getElementById("iframe").contentDocument.querySelector("input")+ : document.getElementById(kind === "cancel" || kind === "keyboard-cancel" ? "input" : kind);+ if (target.value !== undefined) target.value = kind === "textarea" ? "abc\ndef" : "hello world";+ else target.textContent = "hello world";+ target.focus();+ if (target.setSelectionRange) target.setSelectionRange(target.value.length, target.value.length);+ else target.ownerDocument.getSelection().collapse(target.firstChild, target.textContent.length);+ events = [];+ target.onkeydown = event => {+ events.push(["keydown", event.key, event.ctrlKey, event.shiftKey]);+ if (cancelKeyboard) event.preventDefault();+ };+ target.onbeforeinput = event => {+ events.push(["beforeinput", event.inputType]);+ if (cancelDeletion) event.preventDefault();+ };+ target.oninput = event => events.push(["input", event.inputType]);+ target.onkeyup = () => { ++serial; report(); };+ ++serial;+ report();+}+</script>diff --git a/Tests/LibWeb/AccessibilityBridgeMac/harness/ladybird.py b/Tests/LibWeb/AccessibilityBridgeMac/harness/ladybird.pyindex 91843724d04..1beaa640d57 100644--- a/Tests/LibWeb/AccessibilityBridgeMac/harness/ladybird.py+++ b/Tests/LibWeb/AccessibilityBridgeMac/harness/ladybird.py@@ -14,6 +14,7 @@ from contextlib import contextmanagerfrom typing import Callablefrom typing import Optional+from AppKit import NSWorkspacefrom ApplicationServices import AXIsProcessTrustedfrom ApplicationServices import AXUIElementCopyAttributeValuefrom ApplicationServices import AXUIElementCreateApplication@@ -23,6 +24,8 @@ from ApplicationServices import kAXMainWindowAttributefrom ApplicationServices import kAXRoleAttributefrom ApplicationServices import kAXTitleAttributefrom ApplicationServices import kAXWindowsAttribute+from Foundation import NSDate+from Foundation import NSRunLoopREPO_ROOT = pathlib.Path(__file__).resolve().parents[4]@@ -83,13 +86,42 @@ def _make_profile_directory() -> str:return root+class LaunchServicesProcess:+ def __init__(self, launcher, application):+ self.launcher = launcher+ self.application = application+ self.pid = application.processIdentifier()++ def poll(self):+ return self.launcher.poll()++ def terminate(self):+ self.application.terminate()++ def kill(self):+ self.application.forceTerminate()++ def wait(self, timeout=None):+ return self.launcher.wait(timeout=timeout)++class LadybirdContext:"""A running Ladybird process wrapped with NSAccessibility/AXUIElement discovery helpers.One context per test class; a new Ladybird process is spawned per context — so state from a previous test cannotleak. Use via AccessibilityBridgeMacTestCase or the ladybird_for_fixture context manager."""- def __init__(self, url: str, binary: Optional[pathlib.Path] = None, *, wait_for_web_area: bool = True):+ def __init__(+ self,+ url: str,+ binary: Optional[pathlib.Path] = None,+ *,+ wait_for_web_area: bool = True,+ environment: Optional[dict[str, str]] = None,+ launch_via_launch_services: bool = False,+ ):+ self._launch_via_launch_services = launch_via_launch_services+ self._environment = environment or {}self._url = urlself._wait_for_web_area = wait_for_web_areaif binary is not None:@@ -103,6 +135,7 @@ class LadybirdContext:self._web = Noneself._stderr_file: Optional[tempfile.NamedTemporaryFile] = Noneself._profile_directory: Optional[str] = None+ self._initial_load_notifications = Nonedef __enter__(self) -> "LadybirdContext":self.start()@@ -137,6 +170,7 @@ class LadybirdContext:)env = os.environ.copy()+ env.update(self._environment)# Send stderr to a regular file rather than subprocess.PIPE: Ladybird debug builds (ENABLE_ALL_THE_DEBUG_MACROS)# produce huge stderr volumes (PROMISE_DEBUG, etc.). A pipe's kernel buffer is ~64 KB; once it fills, every@@ -151,15 +185,70 @@ class LadybirdContext:# A data directory of its own, so the launch stays out of the user's crash-report store: Ladybird offers the# newest pending report from that store in a popover on every launch, and a crash here would land in it.env["XDG_DATA_HOME"] = os.path.join(self._profile_directory, "xdg-data")- self._process = subprocess.Popen(- [str(self._binary), "--force-cpu-painting", "--profile-path", self._profile_directory, self._url],- env=env,- stdout=subprocess.DEVNULL,- stderr=self._stderr_file,- )+ env["XDG_DOWNLOAD_DIR"] = os.path.join(self._profile_directory, "downloads")+ os.makedirs(env["XDG_DOWNLOAD_DIR"], mode=0o700)+ arguments = ["--force-cpu-painting", "--profile-path", self._profile_directory, self._url]+ if self._launch_via_launch_services:+ bundle = self._binary.parents[2].resolve()+ if bundle.suffix != ".app":+ raise RuntimeError("Native-key tests require a Ladybird application bundle")+ workspace = NSWorkspace.sharedWorkspace()+ previous_pids = {application.processIdentifier() for application in workspace.runningApplications()}+ command = [+ "/usr/bin/open",+ "-n",+ "-W",+ "-a",+ str(bundle),+ "--stderr",+ self._stderr_file.name,+ "--stdout",+ "/dev/null",+ ]+ for key, value in {+ **self._environment,+ "XDG_DATA_HOME": env["XDG_DATA_HOME"],+ "XDG_DOWNLOAD_DIR": env["XDG_DOWNLOAD_DIR"],+ }.items():+ command.extend(["--env", f"{key}={value}"])+ command.extend(["--args", *arguments])+ launcher = subprocess.Popen(command, stdout=subprocess.DEVNULL, stderr=self._stderr_file)+ self._process = launcher++ def find_application():+ NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.01))+ for application in workspace.runningApplications():+ url = application.bundleURL()+ if (+ application.processIdentifier() not in previous_pids+ and url is not None+ and pathlib.Path(url.path()).resolve() == bundle+ ):+ return application+ return None++ application = wait_for(find_application, description="LaunchServices fixture application")+ if not application:+ raise RuntimeError(+ f"LaunchServices didn't register the native-key fixture (launcher status {launcher.poll()}): {pathlib.Path(self._stderr_file.name).read_text()}"+ )+ self._process = LaunchServicesProcess(launcher, application)+ else:+ self._process = subprocess.Popen(+ [str(self._binary), *arguments],+ env=env,+ stdout=subprocess.DEVNULL,+ stderr=self._stderr_file,+ )self._app = AXUIElementCreateApplication(self._process.pid)startup_timeout = float(os.environ.get("LADYBIRD_AX_STARTUP_TIMEOUT", "60"))+ if self._launch_via_launch_services:+ from .notifications import NotificationCollector++ if not wait_for(lambda: _ax_attr(self._app, kAXRoleAttribute), timeout=startup_timeout):+ raise RuntimeError("The fixture did not become responsive to accessibility requests")+ self._initial_load_notifications = NotificationCollector(self._process.pid, self._app, ["AXLoadComplete"])# A test that decides for itself when an assistive technology first reads the page waits for nothing here: Any# accessibility query into the window turns Qt's accessibility on, and with it the fetch of the page's tree.@@ -201,7 +290,26 @@ class LadybirdContext:f"Stderr:\n{stderr_excerpt}")+ if self._initial_load_notifications is not None:+ collector = self._initial_load_notifications+ try:++ def initial_focus_delivered():+ collector.collect(0.05)+ return "AXLoadComplete" in collector.names()++ if not wait_for(+ initial_focus_delivered, timeout=startup_timeout, description="initial accessibility focus delivery"+ ):+ raise RuntimeError("The fixture didn't finish its initial accessibility focus announcement")+ finally:+ collector.close()+ self._initial_load_notifications = None+def stop(self) -> None:+ if self._initial_load_notifications is not None:+ self._initial_load_notifications.close()+ self._initial_load_notifications = Noneif self._process is None:self._cleanup_stderr_file()self._cleanup_profile_directory()diff --git a/Tests/LibWeb/AccessibilityBridgeMac/tests/test_native_control_key_editing.py b/Tests/LibWeb/AccessibilityBridgeMac/tests/test_native_control_key_editing.pynew file mode 100644index 00000000000..1ba7d493e14--- /dev/null+++ b/Tests/LibWeb/AccessibilityBridgeMac/tests/test_native_control_key_editing.py@@ -0,0 +1,344 @@+"""Native Control-key events exercise AppKit bindings through the Qt view and WebContent."""++from __future__ import annotations++import json+import pathlib+import plistlib+import sys+import tempfile+import unittest++sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))++from AppKit import NSApplicationActivateIgnoringOtherApps # noqa: E402+from AppKit import NSRunningApplication # noqa: E402+from AppKit import NSWorkspace # noqa: E402+from ApplicationServices import AXUIElementPerformAction # noqa: E402+from ApplicationServices import AXUIElementSetAttributeValue # noqa: E402+from ApplicationServices import kAXFocusedAttribute # noqa: E402+from ApplicationServices import kAXFocusedUIElementAttribute # noqa: E402+from ApplicationServices import kAXPressAction # noqa: E402+from ApplicationServices import kAXRoleAttribute # noqa: E402+from ApplicationServices import kAXSelectedTextAttribute # noqa: E402+from ApplicationServices import kAXTitleAttribute # noqa: E402+from ApplicationServices import kAXValueAttribute # noqa: E402+from Foundation import NSDate # noqa: E402+from Foundation import NSRunLoop # noqa: E402+from harness import find_all_by_role # noqa: E402+from harness import wait_for # noqa: E402+from harness.ladybird import FIXTURE_DIR # noqa: E402+from harness.ladybird import LadybirdContext # noqa: E402+from harness.ladybird import _ax_attr # noqa: E402+from Quartz import CGEventCreateKeyboardEvent # noqa: E402+from Quartz import CGEventPostToPid # noqa: E402+from Quartz import CGEventSetFlags # noqa: E402+from Quartz import kCGEventFlagMaskAlternate # noqa: E402+from Quartz import kCGEventFlagMaskCommand # noqa: E402+from Quartz import kCGEventFlagMaskControl # noqa: E402+from Quartz import kCGEventFlagMaskShift # noqa: E402+++def activate_fixture(pid: int) -> None:+ def running_application():+ NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.01))+ return NSRunningApplication.runningApplicationWithProcessIdentifier_(pid)++ application = wait_for(running_application)+ if application is None or application is False:+ raise AssertionError("The native-event fixture is not registered with LaunchServices")+ application.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)++ def is_active():+ NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.01))+ return NSWorkspace.sharedWorkspace().frontmostApplication().processIdentifier() == pid++ if not wait_for(is_active):+ raise AssertionError("The native-event fixture couldn't become the active application")+++def send_native_key(pid: int, key_code: int, flags: int = 0) -> None:+ activate_fixture(pid)+ for down in (True, False):+ event = CGEventCreateKeyboardEvent(None, key_code, down)+ CGEventSetFlags(event, flags)+ CGEventPostToPid(pid, event)+++def send_native_control_key(pid: int, key_code: int, *, shift: bool = False, option: bool = False) -> None:+ flags = kCGEventFlagMaskControl+ if shift:+ flags |= kCGEventFlagMaskShift+ if option:+ flags |= kCGEventFlagMaskAlternate+ send_native_key(pid, key_code, flags)+++class NativeControlKeyEditingTests(unittest.TestCase):+ MODE = "default"++ def setUp(self):+ super().setUp()+ self._home = tempfile.TemporaryDirectory(prefix="ladybird-native-ui-bindings-")+ bindings = pathlib.Path(self._home.name) / "Library" / "KeyBindings"+ bindings.mkdir(parents=True)+ dictionary = (+ {}+ if self.MODE == "default"+ else {+ "^w": "deleteWordBackward:",+ "^g": "deleteWordBackward:",+ "^b": "moveWordBackward:",+ "^f": "moveWordForward:",+ "^s": "moveBackwardAndModifySelection:",+ "^z": ["moveToBeginningOfParagraph:", "moveForward:"],+ "^u": ["moveBackward:", "transpose:"],+ "^" + chr(0xF702): "noop:",+ }+ )+ (bindings / "DefaultKeyBinding.dict").write_bytes(plistlib.dumps(dictionary))+ self._previous_application = NSWorkspace.sharedWorkspace().frontmostApplication()+ self.ctx = LadybirdContext(+ (FIXTURE_DIR / "native-control-key-editing.html").as_uri(),+ environment={"CFFIXED_USER_HOME": self._home.name},+ launch_via_launch_services=True,+ )+ self.addCleanup(self._cleanup_fixture)+ self.ctx.start()+ activate_fixture(self.ctx.pid)++ def _cleanup_fixture(self):+ self.ctx.stop()+ self._home.cleanup()+ if self._previous_application:+ self._previous_application.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)++ def _button(self, name):+ return next(+ (+ button+ for button in find_all_by_role(self.ctx.web, "AXButton")+ if _ax_attr(button, kAXTitleAttribute) == name+ ),+ None,+ )++ def _result(self):+ for field in find_all_by_role(self.ctx.web, "AXTextField"):+ value = _ax_attr(field, kAXValueAttribute)+ if isinstance(value, str) and value.startswith('{"serial":'):+ return json.loads(value)+ return None++ def _prepare(self, name):+ previous = self._result()+ button = self._button(name)+ self.assertIsNotNone(button, name)+ self.assertEqual(AXUIElementPerformAction(button, kAXPressAction), 0)+ self.assertTrue(+ wait_for(lambda: self._result() is not None and self._result() != previous),+ "fixture did not focus the editor",+ )+ return self._result()++ def _control(self, key_code, *, shift=False):+ before = self._result()+ send_native_control_key(self.ctx.pid, key_code, shift=shift)+ self.assertTrue(+ wait_for(lambda: self._result() is not None and self._result()["serial"] > before["serial"]),+ f"fixture did not receive keyup: {self._result()!r}",+ )+ return self._result()++ def test_web_input_native_commands(self):+ self._prepare("Input")+ state = self._control(0) # A+ self.assertEqual([state["start"], state["end"]], [0, 0])+ self.assertIn(["keydown", "a", True, False], state["events"])+ state = self._control(14) # E+ self.assertEqual(state["end"], 11)+ state = self._control(13) # W+ self.assertEqual(state["value"], "hello " if self.MODE == "custom" else "hello world")+ self._control(0)+ state = self._control(40) # K+ self.assertEqual(state["value"], "")+ self.assertIn(["beforeinput", "deleteHardLineForward"], state["events"])++ def test_selector_overrides_and_selection(self):+ self._prepare("Input")+ state = self._control(11) # B+ self.assertEqual(state["end"], 6 if self.MODE == "custom" else 10)+ state = self._control(3) # F+ self.assertEqual(state["end"], 11)+ state = self._control(0, shift=True)+ self.assertEqual([state["start"], state["end"]], [0, 11])++ def test_paragraph_editors_and_iframe(self):+ self._prepare("Textarea")+ self.assertEqual(self._control(0)["start"], 4)+ self.assertEqual(self._control(40)["value"], "abc\n")+ for name in ("Rich text", "Iframe"):+ with self.subTest(editor=name):+ self._prepare(name)+ self.assertEqual(self._control(0)["end"], 0)+ self.assertEqual(self._control(14)["end"], 11)+ state = self._control(13)+ self.assertEqual(+ state["value"].replace(chr(0xA0), " "), "hello " if self.MODE == "custom" else "hello world"+ )+ self._control(0)+ self.assertEqual(self._control(40)["value"], "")++ def test_dom_cancellation(self):+ self._prepare("Cancel keydown")+ self.assertEqual(self._control(0)["end"], 11)+ self._prepare("Cancel deletion")+ self._control(0)+ state = self._control(40)+ self.assertEqual([state["value"], state["end"]], ["hello world", 0])+ self.assertNotIn(["input", "deleteHardLineForward"], state["events"])++ def test_supported_sequences_and_rejected_bindings(self):+ if self.MODE != "custom":+ self.skipTest("custom binding fixture")+ self._prepare("Input")+ self.assertEqual(self._control(6)["end"], 1) # Z: ordered sequence+ self._prepare("Input")+ self.assertEqual([self._control(32)["start"], self._result()["end"]], [11, 11]) # U: unsupported sequence+ self.assertEqual(self._control(123)["end"], 11) # Left: resolved noop+ self.assertEqual([self._control(1)["start"], self._result()["end"]], [10, 11]) # S: selection without Shift+ self._prepare("Input")+ self.assertEqual(self._control(5)["value"], "hello ") # G: alternate custom binding++ def _focused_ui_field(self):+ field = _ax_attr(self.ctx.app, kAXFocusedUIElementAttribute)+ return field if _ax_attr(field, kAXRoleAttribute) == "AXTextField" else None++ def _check_ui_commands(self, field):+ self.assertEqual(AXUIElementSetAttributeValue(field, kAXValueAttribute, "hello world"), 0)+ send_native_control_key(self.ctx.pid, 14) # E+ send_native_control_key(self.ctx.pid, 13) # W+ expected = "hello " if self.MODE == "custom" else "hello world"+ self.assertTrue(wait_for(lambda: _ax_attr(field, kAXValueAttribute) == expected))+ send_native_control_key(self.ctx.pid, 0) # A+ send_native_control_key(self.ctx.pid, 40) # K+ self.assertTrue(wait_for(lambda: _ax_attr(field, kAXValueAttribute) == ""))+ send_native_key(self.ctx.pid, 6, kCGEventFlagMaskCommand) # Command-Z+ self.assertTrue(wait_for(lambda: _ax_attr(field, kAXValueAttribute) == expected))+ send_native_key(self.ctx.pid, 0, kCGEventFlagMaskCommand) # Command-A+ send_native_key(self.ctx.pid, 7) # Ordinary X typing replaces the selection.+ self.assertTrue(wait_for(lambda: _ax_attr(field, kAXValueAttribute) == "x"))++ def test_search_field_native_commands(self):+ send_native_key(self.ctx.pid, 3, kCGEventFlagMaskCommand) # Command-F+ self.addCleanup(send_native_key, self.ctx.pid, 53)+ field = wait_for(self._focused_ui_field)+ self.assertTrue(field, "search field did not take focus")+ self._check_ui_commands(field)++ def test_prompt_native_commands(self):+ button = self._button("Prompt")+ self.assertIsNotNone(button)+ self.assertEqual(AXUIElementPerformAction(button, kAXPressAction), 0)+ self.addCleanup(send_native_key, self.ctx.pid, 53)+ field = wait_for(self._focused_ui_field)+ self.assertTrue(field, "prompt field did not take focus")+ self._check_ui_commands(field)++ def _leave_address_field(self, address):+ send_native_key(self.ctx.pid, 53) # Escape closes completion.+ send_native_key(self.ctx.pid, 53) # Escape returns focus to the page.+ self.assertTrue(wait_for(lambda: not _ax_attr(address, kAXFocusedAttribute)))++ def test_address_completion_native_commands(self):+ send_native_key(self.ctx.pid, 37, kCGEventFlagMaskCommand) # Command-L+ address = wait_for(self._focused_ui_field)+ self.assertTrue(address, "address field did not take focus")+ self.addCleanup(self._leave_address_field, address)++ def type_internal_page_prefix():+ prefix = ""+ for character, code in zip("about:", (0, 11, 31, 32, 17, 41)):+ prefix += character+ send_native_key(self.ctx.pid, code, kCGEventFlagMaskShift if character == ":" else 0)++ def typed_prefix(prefix=prefix):+ value = _ax_attr(address, kAXValueAttribute)+ return (+ isinstance(value, str)+ and value.startswith(prefix)+ and _ax_attr(address, kAXSelectedTextAttribute) == value[len(prefix) :]+ )++ self.assertTrue(+ wait_for(typed_prefix), f"prefix after typing {character}: {_ax_attr(address, kAXValueAttribute)!r}"+ )++ def completion():+ value = _ax_attr(address, kAXValueAttribute)+ if not isinstance(value, str) or not value.startswith("about:") or len(value) <= 6:+ return None+ if _ax_attr(address, kAXSelectedTextAttribute) != value[6:]:+ return None+ return value++ completed = wait_for(completion)+ self.assertTrue(completed, f"completion text: {_ax_attr(address, kAXValueAttribute)!r}")+ return completed++ completed = type_internal_page_prefix()+ send_native_control_key(self.ctx.pid, 3, shift=True) # F advances focus, preserving the suffix anchor.+ self.assertTrue(+ wait_for(lambda: _ax_attr(address, kAXSelectedTextAttribute) == completed[7:]),+ f"selection after Control-Shift-F: {_ax_attr(address, kAXSelectedTextAttribute)!r}",+ )+ self.assertEqual(_ax_attr(address, kAXValueAttribute), completed)+ send_native_control_key(self.ctx.pid, 0)+ send_native_control_key(self.ctx.pid, 40)+ self.assertTrue(wait_for(lambda: _ax_attr(address, kAXValueAttribute) == ""))+ previous = type_internal_page_prefix()+ send_native_key(self.ctx.pid, 125) # Down explicitly chooses a suggestion.+ self.assertTrue(wait_for(lambda: _ax_attr(address, kAXValueAttribute) != previous))+ send_native_control_key(self.ctx.pid, 0)+ send_native_control_key(self.ctx.pid, 40)+ self.assertTrue(wait_for(lambda: _ax_attr(address, kAXValueAttribute) == ""))++ def test_address_field_custom_deletion(self):+ fields = find_all_by_role(self.ctx.window(), "AXTextField")+ address = next(+ (field for field in fields if str(_ax_attr(field, kAXValueAttribute) or "").startswith("file://")), None+ )+ self.assertIsNotNone(address, "address field missing")+ self.addCleanup(self._leave_address_field, address)+ send_native_key(self.ctx.pid, 37, kCGEventFlagMaskCommand) # Command-L+ self.assertTrue(+ wait_for(lambda: bool(_ax_attr(address, kAXFocusedAttribute))),+ f"Command-L address focus: {_ax_attr(address, kAXFocusedAttribute)!r}",+ )+ self.assertEqual(AXUIElementSetAttributeValue(address, kAXValueAttribute, "hello world"), 0)+ send_native_control_key(self.ctx.pid, 14)+ send_native_control_key(self.ctx.pid, 13)+ expected = "hello " if self.MODE == "custom" else "hello world"+ self.assertTrue(+ wait_for(lambda: _ax_attr(address, kAXValueAttribute) == expected),+ f"address value: {_ax_attr(address, kAXValueAttribute)!r}",+ )+ send_native_control_key(self.ctx.pid, 0)+ send_native_control_key(self.ctx.pid, 40)+ self.assertTrue(+ wait_for(lambda: _ax_attr(address, kAXValueAttribute) == ""),+ f"address after Control-K: {_ax_attr(address, kAXValueAttribute)!r}",+ )+ send_native_key(self.ctx.pid, 6, kCGEventFlagMaskCommand) # Command-Z+ self.assertTrue(+ wait_for(lambda: _ax_attr(address, kAXValueAttribute) == expected),+ f"address after undo: {_ax_attr(address, kAXValueAttribute)!r}",+ )+++class NativeCustomControlKeyEditingTests(NativeControlKeyEditingTests):+ MODE = "custom"+++if __name__ == "__main__":+ unittest.main()diff --git a/Tests/LibWeb/Text/expected/Editing/native-text-deletion-lifetime.txt b/Tests/LibWeb/Text/expected/Editing/native-text-deletion-lifetime.txtnew file mode 100644index 00000000000..5cfa20ddbf0--- /dev/null+++ b/Tests/LibWeb/Text/expected/Editing/native-text-deletion-lifetime.txt@@ -0,0 +1,8 @@+canceled history: PASS+no-op history: PASS+repeated word deletion: PASS+granular undo unit: PASS+first granular undo: PASS+empty rich paragraph join: PASS+rich end no input: PASS+detached document: PASSdiff --git a/Tests/LibWeb/Text/expected/Editing/native-text-deletion.txt b/Tests/LibWeb/Text/expected/Editing/native-text-deletion.txtnew file mode 100644index 00000000000..79431df255f--- /dev/null+++ b/Tests/LibWeb/Text/expected/Editing/native-text-deletion.txt@@ -0,0 +1,30 @@+word backward: PASS+word event order: PASS+word undo: PASS+word redo: PASS+word forward: PASS+paragraph text: PASS+paragraph separator: PASS+empty paragraph separator: PASS+selected deletion: PASS+canceled value and caret: PASS+focus change: PASS+handler selection retained: PASS+handler value retained: PASS+password word deletion: PASS+read-only deletion: PASS+disabled deletion: PASS+combining deletion: PASS+surrogate deletion: PASS+boundary no events: PASS+beforeinput keeps caret: PASS+rich word deletion: PASS+rich target range: PASS+rich word undo: PASS+rich paragraph text: PASS+rich paragraph join: PASS+rich paragraph join structure: PASS+rich br join: PASS+rich br join structure: PASS+rich canceled caret: PASS+removed editor: PASSdiff --git a/Tests/LibWeb/Text/expected/Editing/native-text-keyboard-dispatch.txt b/Tests/LibWeb/Text/expected/Editing/native-text-keyboard-dispatch.txtnew file mode 100644index 00000000000..1e65fae60b9--- /dev/null+++ b/Tests/LibWeb/Text/expected/Editing/native-text-keyboard-dispatch.txt@@ -0,0 +1,7 @@+original keydown before movement: PASS+movement after keydown: PASS+keydown cancellation: PASS+post-keydown focus target: PASS+selector selection without Shift: PASS+blur cancels editing: PASS+removed focus target: PASSdiff --git a/Tests/LibWeb/Text/expected/Editing/native-text-navigation.txt b/Tests/LibWeb/Text/expected/Editing/native-text-navigation.txtnew file mode 100644index 00000000000..aff4bab7f0c--- /dev/null+++ b/Tests/LibWeb/Text/expected/Editing/native-text-navigation.txt@@ -0,0 +1,67 @@+input beginning: PASS+input end: PASS+textarea beginning: PASS+textarea end: PASS+extend backward: PASS+backward direction: PASS+repeated backward anchor: PASS+reverse extension anchor: PASS+extend forward: PASS+forward direction: PASS+soft wrap beginning: PASS+soft wrap end: PASS+empty paragraph beginning: PASS+empty paragraph end: PASS+single-line up: PASS+single-line down: PASS+textarea page distance: PASS+textarea page column: PASS+textarea page reverse: PASS+read-only movement: PASS+inline paragraph boundary: PASS+inline paragraph beginning: PASS+rich selection anchor: PASS+rich selection text: PASS+br paragraph beginning: PASS+noneditable boundary: PASS+empty rich paragraph: PASS+nested host end: PASS+nested host beginning: PASS+RTL physical left: PASS+RTL physical right: PASS+RTL logical beginning: PASS+RTL logical end: PASS+input opposite RTL run left: PASS+input opposite RTL run right: PASS+textarea opposite RTL run left: PASS+textarea opposite RTL run right: PASS+rich opposite RTL run left: PASS+rich opposite RTL run left geometry: PASS+rich opposite RTL run right: PASS+rich opposite RTL run right geometry: PASS+input opposite LTR run left: PASS+input opposite LTR run right: PASS+textarea opposite LTR run left: PASS+textarea opposite LTR run right: PASS+rich opposite LTR run left: PASS+rich opposite LTR run left geometry: PASS+rich opposite LTR run right: PASS+rich opposite LTR run right geometry: PASS+input mixed leading run left: PASS+input mixed leading run right: PASS+textarea mixed leading run left: PASS+textarea mixed leading run right: PASS+rich mixed leading run left: PASS+rich mixed leading run left geometry: PASS+rich mixed leading run right: PASS+rich mixed leading run right geometry: PASS+input mixed trailing run left: PASS+input mixed trailing run right: PASS+textarea mixed trailing run left: PASS+textarea mixed trailing run right: PASS+rich mixed trailing run left: PASS+rich mixed trailing run left geometry: PASS+rich mixed trailing run right: PASS+rich mixed trailing run right geometry: PASS+inline host left boundary: PASS+inline host right boundary: PASSdiff --git a/Tests/LibWeb/Text/expected/wpt-import/input-events/input-events-delete-selection.txt b/Tests/LibWeb/Text/expected/wpt-import/input-events/input-events-delete-selection.txtnew file mode 100644index 00000000000..36f79e791a5--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/input-events/input-events-delete-selection.txt@@ -0,0 +1,12 @@+Harness status: OK++Found 6 tests++4 Pass+2 Fail+Pass Ctrl+Backspace with non-collapsed selection should report deleteContentBackward+Fail Ctrl+Backspace with caret should report deleteWordBackward+Pass Ctrl+Delete with non-collapsed selection should report deleteContentForward+Fail Ctrl+Delete with caret should report deleteWordForward+Pass Regular Backspace with non-collapsed selection should report deleteContentBackward+Pass Regular Delete with non-collapsed selection should report deleteContentForwarddiff --git a/Tests/LibWeb/Text/input/Editing/native-text-deletion-lifetime.html b/Tests/LibWeb/Text/input/Editing/native-text-deletion-lifetime.htmlnew file mode 100644index 00000000000..9b0bc21aa8d--- /dev/null+++ b/Tests/LibWeb/Text/input/Editing/native-text-deletion-lifetime.html@@ -0,0 +1,52 @@+<!DOCTYPE html>+<meta charset="utf-8">+<script src="../include.js"></script>+<script>+asyncTest(async done => {+ function check(label, actual, expected) {+ println(`${label}: ${JSON.stringify(actual) === JSON.stringify(expected) ? "PASS" : JSON.stringify(actual)}`);+ }+ const iframe = document.createElement("iframe");+ const loaded = new Promise(resolve => iframe.onload = resolve);+ iframe.srcdoc = '<textarea>hello world</textarea><div contenteditable><p>abc</p><p><br></p><p>def</p></div>';+ document.body.append(iframe);+ await loaded;+ const doc = iframe.contentDocument;+ const textarea = doc.querySelector("textarea");+ textarea.focus();+ textarea.setSelectionRange(11, 11);+ const command = (target, name) => internals.sendTextEditingCommand(target, name);+ textarea.onbeforeinput = e => { internals.gc(); e.preventDefault(); };+ command(textarea, "DeleteWordBackward");+ check("canceled history", doc.queryCommandEnabled("undo"), false);+ textarea.onbeforeinput = null;+ command(textarea, "DeleteToEndOfParagraph");+ check("no-op history", doc.queryCommandEnabled("undo"), false);+ command(textarea, "DeleteWordBackward");+ command(textarea, "DeleteWordBackward");+ check("repeated word deletion", textarea.value, "");+ doc.execCommand("undo");+ check("granular undo unit", [textarea.value, textarea.selectionStart], ["hello ", 6]);+ doc.execCommand("undo");+ check("first granular undo", [textarea.value, textarea.selectionStart], ["hello world", 11]);+ const rich = doc.querySelector("div");+ rich.focus();+ const selection = doc.getSelection();+ selection.collapse(rich.children[1], 0);+ command(rich, "DeleteToEndOfParagraph");+ check("empty rich paragraph join", rich.children.length, 2);+ rich.innerHTML = "abc";+ selection.collapse(rich.firstChild, 3);+ let events = 0;+ rich.oninput = () => ++events;+ command(rich, "DeleteToEndOfParagraph");+ check("rich end no input", [rich.textContent, events], ["abc", 0]);+ textarea.value = "hello world";+ textarea.focus();+ textarea.setSelectionRange(11, 11);+ textarea.onbeforeinput = () => { iframe.remove(); internals.gc(); };+ command(textarea, "DeleteWordBackward");+ check("detached document", [iframe.isConnected, textarea.value], [false, "hello world"]);+ done();+});+</script>diff --git a/Tests/LibWeb/Text/input/Editing/native-text-deletion.html b/Tests/LibWeb/Text/input/Editing/native-text-deletion.htmlnew file mode 100644index 00000000000..5a1a355fd61--- /dev/null+++ b/Tests/LibWeb/Text/input/Editing/native-text-deletion.html@@ -0,0 +1,127 @@+<!DOCTYPE html>+<meta charset="utf-8">+<textarea id="textarea"></textarea><input id="input"><input id="other" value="other">+<div id="rich" contenteditable></div>+<script src="../include.js"></script>+<script>+test(() => {+ const textarea = document.getElementById("textarea");+ const input = document.getElementById("input");+ const other = document.getElementById("other");+ const rich = document.getElementById("rich");+ const selection = getSelection();+ function check(label, actual, expected) {+ println(`${label}: ${JSON.stringify(actual) === JSON.stringify(expected) ? "PASS" : JSON.stringify(actual)}`);+ }+ function reset(target, value, start, end = start) {+ target.value = value;+ target.focus();+ target.setSelectionRange(start, end);+ }+ function command(target, name) { internals.sendTextEditingCommand(target, name); }+ reset(textarea, "hello world", 11);+ let events = [];+ textarea.onbeforeinput = e => events.push([e.type, e.inputType, e.getTargetRanges().length]);+ textarea.oninput = e => events.push([e.type, e.inputType, e.getTargetRanges().length]);+ command(textarea, "DeleteWordBackward");+ check("word backward", [textarea.value, textarea.selectionStart], ["hello ", 6]);+ check("word event order", events, [["beforeinput", "deleteWordBackward", 0], ["input", "deleteWordBackward", 0]]);+ textarea.onbeforeinput = textarea.oninput = null;+ document.execCommand("undo");+ check("word undo", [textarea.value, textarea.selectionStart, textarea.selectionEnd], ["hello world", 11, 11]);+ document.execCommand("redo");+ check("word redo", [textarea.value, textarea.selectionStart], ["hello ", 6]);+ reset(textarea, "hello world", 0);+ command(textarea, "DeleteWordForward");+ check("word forward", [textarea.value, textarea.selectionStart], [" world", 0]);+ reset(textarea, "abc\ndef", 1);+ command(textarea, "DeleteToEndOfParagraph");+ check("paragraph text", [textarea.value, textarea.selectionStart], ["a\ndef", 1]);+ reset(textarea, "abc\ndef", 3);+ command(textarea, "DeleteToEndOfParagraph");+ check("paragraph separator", [textarea.value, textarea.selectionStart], ["abcdef", 3]);+ reset(textarea, "abc\n\ndef", 4);+ command(textarea, "DeleteToEndOfParagraph");+ check("empty paragraph separator", textarea.value, "abc\ndef");+ reset(textarea, "abcdef", 1, 4);+ let selectedType;+ textarea.onbeforeinput = e => selectedType = e.inputType;+ command(textarea, "DeleteWordBackward");+ check("selected deletion", [textarea.value, selectedType], ["aef", "deleteContentBackward"]);+ textarea.onbeforeinput = null;+ reset(textarea, "hello world", 11);+ textarea.onbeforeinput = e => { e.preventDefault(); };+ command(textarea, "DeleteWordBackward");+ check("canceled value and caret", [textarea.value, textarea.selectionStart, textarea.selectionEnd], ["hello world", 11, 11]);+ textarea.onbeforeinput = () => other.focus();+ command(textarea, "DeleteWordBackward");+ check("focus change", [textarea.value, other.value, document.activeElement === other], ["hello world", "other", true]);+ textarea.onbeforeinput = () => textarea.setSelectionRange(0, 0);+ command(textarea, "DeleteWordBackward");+ check("handler selection retained", [textarea.value, textarea.selectionStart], ["hello world", 0]);+ textarea.onbeforeinput = () => { textarea.value = "replacement"; textarea.setSelectionRange(0, 0); };+ reset(textarea, "hello world", 11);+ command(textarea, "DeleteWordBackward");+ check("handler value retained", [textarea.value, textarea.selectionStart], ["replacement", 0]);+ textarea.onbeforeinput = textarea.oninput = null;+ reset(input, "secret words", 12);+ input.type = "password";+ command(input, "DeleteWordBackward");+ check("password word deletion", input.value, "secret ");+ input.readOnly = true;+ command(input, "DeleteBackward");+ check("read-only deletion", input.value, "secret ");+ input.readOnly = false;+ input.disabled = true;+ command(input, "DeleteBackward");+ check("disabled deletion", input.value, "secret ");+ input.disabled = false;+ reset(textarea, "a\u{1f600}e\u0301", 5);+ command(textarea, "DeleteBackward");+ check("combining deletion", textarea.value, "a\u{1f600}");+ command(textarea, "DeleteBackward");+ check("surrogate deletion", textarea.value, "a");+ reset(textarea, "end", 3);+ events = [];+ textarea.onbeforeinput = e => events.push(e.type);+ textarea.oninput = e => events.push(e.type);+ command(textarea, "DeleteToEndOfParagraph");+ check("boundary no events", [textarea.value, events], ["end", []]);+ textarea.onbeforeinput = textarea.oninput = null;+ rich.innerHTML = "hello <span>world</span>";+ rich.focus();+ selection.collapse(rich.lastChild.firstChild, 5);+ events = [];+ rich.onbeforeinput = e => {+ const range = e.getTargetRanges()[0];+ events.push([e.type, e.inputType, range?.startOffset, range?.endOffset]);+ check("beforeinput keeps caret", selection.isCollapsed, true);+ };+ command(rich, "DeleteWordBackward");+ check("rich word deletion", rich.textContent, "hello" + String.fromCharCode(0xa0));+ check("rich target range", events, [["beforeinput", "deleteWordBackward", 0, 5]]);+ rich.onbeforeinput = null;+ document.execCommand("undo");+ check("rich word undo", [rich.textContent, selection.isCollapsed, selection.focusOffset], ["hello world", true, 5]);+ for (const [label, html, offset, expected] of [+ ["rich paragraph text", "<p>abc</p><p>def</p>", 1, "adef"],+ ["rich paragraph join", "<p>abc</p><p>def</p>", 3, "abcdef"],+ ["rich br join", "abc<br>def", 3, "abcdef"],+ ]) {+ rich.innerHTML = html;+ const node = rich.firstChild.nodeType === Node.TEXT_NODE ? rich.firstChild : rich.firstChild.firstChild;+ selection.collapse(node, offset);+ command(rich, "DeleteToEndOfParagraph");+ check(label, rich.textContent, expected);+ if (label !== "rich paragraph text") check(label + " structure", rich.querySelectorAll("p, br").length, label === "rich br join" ? 0 : 1);+ }+ rich.innerHTML = "hello world";+ selection.collapse(rich.firstChild, 11);+ rich.onbeforeinput = e => e.preventDefault();+ command(rich, "DeleteWordBackward");+ check("rich canceled caret", [rich.textContent, selection.isCollapsed, selection.focusOffset], ["hello world", true, 11]);+ rich.onbeforeinput = () => rich.remove();+ command(rich, "DeleteWordBackward");+ check("removed editor", [rich.isConnected, rich.textContent], [false, "hello world"]);+});+</script>diff --git a/Tests/LibWeb/Text/input/Editing/native-text-keyboard-dispatch.html b/Tests/LibWeb/Text/input/Editing/native-text-keyboard-dispatch.htmlnew file mode 100644index 00000000000..d98c8dbd91a--- /dev/null+++ b/Tests/LibWeb/Text/input/Editing/native-text-keyboard-dispatch.html@@ -0,0 +1,40 @@+<!DOCTYPE html>+<meta charset="utf-8">+<input id="first" value="abcdef"><input id="second" value="uvwxyz">+<script src="../include.js"></script>+<script>+test(() => {+ const first = document.getElementById("first");+ const second = document.getElementById("second");+ function check(label, actual, expected) {+ println(`${label}: ${JSON.stringify(actual) === JSON.stringify(expected) ? "PASS" : JSON.stringify(actual)}`);+ }+ function reset() { first.focus(); first.setSelectionRange(3, 3); }+ reset();+ let observed;+ first.onkeydown = e => { observed = [e.key, e.ctrlKey, e.shiftKey, first.selectionStart]; };+ internals.sendTextEditingCommand(first, "MoveToBeginningOfParagraph");+ check("original keydown before movement", observed, ["a", true, false, 3]);+ check("movement after keydown", first.selectionStart, 0);+ reset();+ first.onkeydown = e => e.preventDefault();+ internals.sendTextEditingCommand(first, "MoveToBeginningOfParagraph");+ check("keydown cancellation", [first.selectionStart, first.selectionEnd], [3, 3]);+ reset();+ first.onkeydown = () => { second.focus(); second.setSelectionRange(4, 4); };+ internals.sendTextEditingCommand(first, "MoveToBeginningOfParagraph");+ check("post-keydown focus target", [first.selectionStart, second.selectionStart], [3, 0]);+ first.onkeydown = null;+ reset();+ internals.sendTextEditingCommand(first, "MoveToEndOfParagraph", true);+ check("selector selection without Shift", [first.selectionStart, first.selectionEnd, first.selectionDirection], [3, 6, "forward"]);+ reset();+ first.onkeydown = () => first.blur();+ internals.sendTextEditingCommand(first, "MoveToBeginningOfParagraph");+ check("blur cancels editing", first.selectionStart, 3);+ first.onkeydown = () => first.remove();+ reset();+ internals.sendTextEditingCommand(first, "MoveToBeginningOfParagraph");+ check("removed focus target", [first.isConnected, first.selectionStart], [false, 3]);+});+</script>diff --git a/Tests/LibWeb/Text/input/Editing/native-text-navigation.html b/Tests/LibWeb/Text/input/Editing/native-text-navigation.htmlnew file mode 100644index 00000000000..a2fd437da55--- /dev/null+++ b/Tests/LibWeb/Text/input/Editing/native-text-navigation.html@@ -0,0 +1,143 @@+<!DOCTYPE html>+<meta charset="utf-8">+<style>+textarea { font: 16px monospace; width: 65px; }+#rich { width: 65px; font: 16px monospace; }+</style>+<input id="input" value="abcdef">+<textarea id="textarea">abc+def</textarea>+<div id="rich" contenteditable><p>ab<span>cd</span></p><p>ef</p></div>+<script src="../include.js"></script>+<script>+test(() => {+ const input = document.getElementById("input");+ const textarea = document.getElementById("textarea");+ const rich = document.getElementById("rich");+ if (!internals.sendTextEditingCommand) {+ println("Native text editing commands are unavailable");+ return;+ }+ function check(label, actual, expected) {+ println(`${label}: ${JSON.stringify(actual) === JSON.stringify(expected) ? "PASS" : JSON.stringify(actual)}`);+ }+ function control(label, target, command, offset, expected, extend = false) {+ target.focus();+ target.setSelectionRange(offset, offset);+ internals.sendTextEditingCommand(target, command, extend);+ check(label, [target.selectionStart, target.selectionEnd], expected);+ }+ control("input beginning", input, "MoveToBeginningOfParagraph", 3, [0, 0]);+ control("input end", input, "MoveToEndOfParagraph", 3, [6, 6]);+ control("textarea beginning", textarea, "MoveToBeginningOfParagraph", 5, [4, 4]);+ control("textarea end", textarea, "MoveToEndOfParagraph", 5, [7, 7]);+ control("extend backward", textarea, "MoveToBeginningOfParagraph", 5, [4, 5], true);+ check("backward direction", textarea.selectionDirection, "backward");+ internals.sendTextEditingCommand(textarea, "MoveToBeginningOfParagraph", true);+ check("repeated backward anchor", [textarea.selectionStart, textarea.selectionEnd, textarea.selectionDirection], [4, 5, "backward"]);+ internals.sendTextEditingCommand(textarea, "MoveToEndOfParagraph", true);+ check("reverse extension anchor", [textarea.selectionStart, textarea.selectionEnd, textarea.selectionDirection], [5, 7, "forward"]);+ control("extend forward", textarea, "MoveToEndOfParagraph", 5, [5, 7], true);+ check("forward direction", textarea.selectionDirection, "forward");+ textarea.value = "abcdef abcdef abcdef";+ control("soft wrap beginning", textarea, "MoveToBeginningOfParagraph", 10, [0, 0]);+ control("soft wrap end", textarea, "MoveToEndOfParagraph", 10, [20, 20]);+ textarea.value = "abc\n\ndef";+ control("empty paragraph beginning", textarea, "MoveToBeginningOfParagraph", 4, [4, 4]);+ control("empty paragraph end", textarea, "MoveToEndOfParagraph", 4, [4, 4]);+ control("single-line up", input, "MoveUp", 3, [0, 0]);+ control("single-line down", input, "MoveDown", 3, [6, 6]);+ textarea.style.height = "64px";+ textarea.style.lineHeight = "20px";+ textarea.value = "01\n02\n03\n04\n05\n06\n07\n08\n09\n10";+ textarea.focus();+ textarea.setSelectionRange(16, 16);+ internals.sendTextEditingCommand(textarea, "PageDown");+ check("textarea page distance", textarea.selectionStart > 16 && textarea.selectionStart < textarea.value.length, true);+ check("textarea page column", textarea.selectionStart % 3, 1);+ internals.sendTextEditingCommand(textarea, "PageUp");+ check("textarea page reverse", textarea.selectionStart, 16);+ input.readOnly = true;+ control("read-only movement", input, "MoveToBeginningOfParagraph", 3, [0, 0]);+ input.readOnly = false;+ rich.focus();+ const first = rich.firstChild.firstChild;+ const last = rich.firstChild.lastChild.firstChild;+ const selection = getSelection();+ selection.collapse(first, 1);+ internals.sendTextEditingCommand(rich, "MoveToEndOfParagraph");+ check("inline paragraph boundary", [selection.focusNode === last, selection.focusOffset], [true, 2]);+ internals.sendTextEditingCommand(rich, "MoveToBeginningOfParagraph");+ check("inline paragraph beginning", [selection.focusNode === first, selection.focusOffset], [true, 0]);+ selection.collapse(first, 1);+ internals.sendTextEditingCommand(rich, "MoveToEndOfParagraph", true);+ check("rich selection anchor", [selection.anchorNode === first, selection.anchorOffset], [true, 1]);+ check("rich selection text", selection.toString(), "bcd");+ rich.innerHTML = "ab<br>cd";+ selection.collapse(rich.lastChild, 1);+ internals.sendTextEditingCommand(rich, "MoveToBeginningOfParagraph");+ check("br paragraph beginning", [selection.focusNode === rich.lastChild, selection.focusOffset], [true, 0]);+ rich.innerHTML = '<span contenteditable="false">locked</span><span>ab</span>';+ selection.collapse(rich.lastChild.firstChild, 1);+ internals.sendTextEditingCommand(rich, "MoveToBeginningOfParagraph");+ check("noneditable boundary", selection.focusNode === rich.lastChild.firstChild, true);+ rich.innerHTML = '<p>ab</p><p><br></p><p>cd</p>';+ selection.collapse(rich.children[1], 0);+ internals.sendTextEditingCommand(rich, "MoveToEndOfParagraph");+ check("empty rich paragraph", rich.children[1].contains(selection.focusNode), true);+ rich.innerHTML = '<div contenteditable="false"><div contenteditable="true">nested</div></div>outside';+ const nested = rich.firstChild.firstChild;+ selection.collapse(nested.firstChild, 3);+ internals.sendTextEditingCommand(nested, "MoveToEndOfParagraph");+ check("nested host end", [selection.focusNode === nested.firstChild, selection.focusOffset], [true, 6]);+ internals.sendTextEditingCommand(nested, "MoveToBeginningOfParagraph");+ check("nested host beginning", [selection.focusNode === nested.firstChild, selection.focusOffset], [true, 0]);+ input.value = "\u05d0\u05d1\u05d2";+ input.dir = "rtl";+ control("RTL physical left", input, "MoveToLeftEndOfLine", 1, [3, 3]);+ control("RTL physical right", input, "MoveToRightEndOfLine", 1, [0, 0]);+ control("RTL logical beginning", input, "MoveToBeginningOfParagraph", 1, [0, 0]);+ control("RTL logical end", input, "MoveToEndOfParagraph", 1, [3, 3]);+ const hebrew = String.fromCodePoint(0x5d0, 0x5d1, 0x5d2);+ const bidiCases = [+ ["opposite RTL run", "ltr", hebrew, 3, 0],+ ["opposite LTR run", "rtl", "abc", 0, 3],+ ["mixed leading run", "ltr", hebrew + " abc", 3, 7],+ ["mixed trailing run", "ltr", "abc " + hebrew, 0, 4],+ ];+ for (const [label, direction, value, left, right] of bidiCases) {+ for (const target of [input, textarea]) {+ target.dir = direction;+ target.style.width = "300px";+ target.value = value;+ control(`${target.id} ${label} left`, target, "MoveToLeftEndOfLine", 1, [left, left]);+ control(`${target.id} ${label} right`, target, "MoveToRightEndOfLine", 1, [right, right]);+ }+ rich.dir = direction;+ rich.style.width = "300px";+ rich.textContent = value;+ rich.focus();+ for (const [edge, offset] of [["Left", left], ["Right", right]]) {+ selection.collapse(rich.firstChild, 1);+ internals.sendTextEditingCommand(rich, `MoveTo${edge}EndOfLine`);+ check(`rich ${label} ${edge.toLowerCase()}`, [selection.focusNode === rich.firstChild, selection.focusOffset], [true, offset]);+ const range = document.createRange();+ range.selectNodeContents(rich);+ const rect = range.getBoundingClientRect();+ const caret = internals.currentCaretRect();+ check(`rich ${label} ${edge.toLowerCase()} geometry`, caret !== null && Math.abs(caret.x - (edge === "Left" ? rect.left : rect.right)) < 1, true);+ }+ }++ const line = document.createElement("div");+ line.innerHTML = 'before<span contenteditable="true">edit</span>after';+ document.body.append(line);+ const inlineHost = line.children[0];+ inlineHost.focus();+ for (const [edge, offset] of [["Left", 0], ["Right", 4]]) {+ selection.collapse(inlineHost.firstChild, 2);+ internals.sendTextEditingCommand(inlineHost, `MoveTo${edge}EndOfLine`);+ check(`inline host ${edge.toLowerCase()} boundary`, [selection.focusNode === inlineHost.firstChild, selection.focusOffset], [true, offset]);+ }+});+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/input-events/input-events-delete-selection.html b/Tests/LibWeb/Text/input/wpt-import/input-events/input-events-delete-selection.htmlnew file mode 100644index 00000000000..dd45036462a--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/input-events/input-events-delete-selection.html@@ -0,0 +1,240 @@+<!DOCTYPE html>+<meta charset="utf-8" />+<title>+ Input Event tests for deletion with non-collapsed selection+</title>+<script src="../resources/testharness.js"></script>+<script src="../resources/testharnessreport.js"></script>+<script src="../resources/testdriver.js"></script>+<script src="../resources/testdriver-vendor.js"></script>+<script src="../resources/testdriver-actions.js"></script>+<div id="rich" contenteditable></div>+<script>+ let inputEventsLog = [];+ const rich = document.getElementById("rich");+ const isMacOS = navigator.platform.indexOf("Mac") === 0;+ const MODIFIER_KEY = isMacOS ? "\uE00A" : "\uE009"; // Alt on Mac, Ctrl on others++ function log(event) {+ inputEventsLog.push({+ type: event.type,+ inputType: event.inputType,+ data: event.data,+ });+ }++ function resetRich() {+ inputEventsLog = [];+ rich.innerHTML = "";+ }++ function selectText(startNode, startOffset, endNode, endOffset) {+ const selection = window.getSelection();+ const range = document.createRange();+ range.setStart(startNode, startOffset);+ range.setEnd(endNode, endOffset);+ selection.removeAllRanges();+ selection.addRange(range);+ }++ rich.addEventListener("beforeinput", log);+ rich.addEventListener("input", log);++ // Test Ctrl+Backspace with non-collapsed selection+ promise_test(async function () {+ this.add_cleanup(resetRich);+ rich.innerHTML = "hello world";+ rich.focus();++ const textNode = rich.firstChild;+ // Select "or" in "world"+ selectText(textNode, 6, textNode, 8);++ // Simulate Ctrl+Backspace (Alt+Backspace on Mac)+ await new test_driver.Actions()+ .keyDown(MODIFIER_KEY)+ .keyDown("\uE003") // Backspace+ .keyUp("\uE003")+ .keyUp(MODIFIER_KEY)+ .send();++ assert_equals(inputEventsLog.length, 2, "Should have 2 events");+ const [beforeInputEvent, inputEvent] = inputEventsLog;+ assert_equals(beforeInputEvent.type, "beforeinput");+ assert_equals(inputEvent.type, "input");+ // When deleting a selection, inputType should be deleteContentBackward+ assert_equals(+ beforeInputEvent.inputType,+ "deleteContentBackward",+ "Ctrl+Backspace with selection should report deleteContentBackward"+ );+ assert_equals(+ inputEvent.inputType,+ "deleteContentBackward",+ "Ctrl+Backspace with selection should report deleteContentBackward"+ );+ }, "Ctrl+Backspace with non-collapsed selection should report deleteContentBackward");++ // Test Ctrl+Backspace with caret (collapsed selection)+ promise_test(async function () {+ this.add_cleanup(resetRich);+ rich.innerHTML = "hello world";+ rich.focus();++ const textNode = rich.firstChild;+ // Place caret after "world"+ selectText(textNode, 11, textNode, 11);++ // Simulate Ctrl+Backspace (Alt+Backspace on Mac)+ await new test_driver.Actions()+ .keyDown(MODIFIER_KEY)+ .keyDown("\uE003") // Backspace+ .keyUp("\uE003")+ .keyUp(MODIFIER_KEY)+ .send();++ assert_equals(inputEventsLog.length, 2, "Should have 2 events");+ const [beforeInputEvent, inputEvent] = inputEventsLog;+ assert_equals(beforeInputEvent.type, "beforeinput");+ assert_equals(inputEvent.type, "input");+ // With caret, should be deleteWordBackward+ assert_equals(+ beforeInputEvent.inputType,+ "deleteWordBackward",+ "Ctrl+Backspace with caret should report deleteWordBackward"+ );+ assert_equals(+ inputEvent.inputType,+ "deleteWordBackward",+ "Ctrl+Backspace with caret should report deleteWordBackward"+ );+ }, "Ctrl+Backspace with caret should report deleteWordBackward");++ // Test Ctrl+Delete with non-collapsed selection+ promise_test(async function () {+ this.add_cleanup(resetRich);+ rich.innerHTML = "hello world";+ rich.focus();++ const textNode = rich.firstChild;+ // Select "ell" in "hello"+ selectText(textNode, 1, textNode, 4);++ // Simulate Ctrl+Delete (Alt+Delete on Mac)+ await new test_driver.Actions()+ .keyDown(MODIFIER_KEY)+ .keyDown("\uE017") // Delete+ .keyUp("\uE017")+ .keyUp(MODIFIER_KEY)+ .send();++ assert_equals(inputEventsLog.length, 2, "Should have 2 events");+ const [beforeInputEvent, inputEvent] = inputEventsLog;+ assert_equals(beforeInputEvent.type, "beforeinput");+ assert_equals(inputEvent.type, "input");+ // When deleting a selection, inputType should be deleteContentForward+ assert_equals(+ beforeInputEvent.inputType,+ "deleteContentForward",+ "Ctrl+Delete with selection should report deleteContentForward"+ );+ assert_equals(+ inputEvent.inputType,+ "deleteContentForward",+ "Ctrl+Delete with selection should report deleteContentForward"+ );+ }, "Ctrl+Delete with non-collapsed selection should report deleteContentForward");++ // Test Ctrl+Delete with caret (collapsed selection)+ promise_test(async function () {+ this.add_cleanup(resetRich);+ rich.innerHTML = "hello world";+ rich.focus();++ const textNode = rich.firstChild;+ // Place caret before "world"+ selectText(textNode, 6, textNode, 6);++ // Simulate Ctrl+Delete (Alt+Delete on Mac)+ await new test_driver.Actions()+ .keyDown(MODIFIER_KEY)+ .keyDown("\uE017") // Delete+ .keyUp("\uE017")+ .keyUp(MODIFIER_KEY)+ .send();++ assert_equals(inputEventsLog.length, 2, "Should have 2 events");+ const [beforeInputEvent, inputEvent] = inputEventsLog;+ assert_equals(beforeInputEvent.type, "beforeinput");+ assert_equals(inputEvent.type, "input");+ // With caret, should be deleteWordForward+ assert_equals(+ beforeInputEvent.inputType,+ "deleteWordForward",+ "Ctrl+Delete with caret should report deleteWordForward"+ );+ assert_equals(+ inputEvent.inputType,+ "deleteWordForward",+ "Ctrl+Delete with caret should report deleteWordForward"+ );+ }, "Ctrl+Delete with caret should report deleteWordForward");++ // Test regular Backspace with non-collapsed selection (should still be deleteContentBackward)+ promise_test(async function () {+ this.add_cleanup(resetRich);+ rich.innerHTML = "hello world";+ rich.focus();++ const textNode = rich.firstChild;+ // Select "lo wo"+ selectText(textNode, 3, textNode, 8);++ // Simulate Backspace (without Ctrl)+ await test_driver.send_keys(rich, "\uE003"); // Backspace++ assert_equals(inputEventsLog.length, 2, "Should have 2 events");+ const [beforeInputEvent, inputEvent] = inputEventsLog;+ assert_equals(beforeInputEvent.type, "beforeinput");+ assert_equals(inputEvent.type, "input");+ assert_equals(+ beforeInputEvent.inputType,+ "deleteContentBackward",+ "Regular Backspace with selection should report deleteContentBackward"+ );+ assert_equals(+ inputEvent.inputType,+ "deleteContentBackward",+ "Regular Backspace with selection should report deleteContentBackward"+ );+ }, "Regular Backspace with non-collapsed selection should report deleteContentBackward");++ // Test regular Delete with non-collapsed selection (should be deleteContentForward)+ promise_test(async function () {+ this.add_cleanup(resetRich);+ rich.innerHTML = "hello world";+ rich.focus();++ const textNode = rich.firstChild;+ // Select "lo wo"+ selectText(textNode, 3, textNode, 8);++ // Simulate Delete (without Ctrl)+ await test_driver.send_keys(rich, "\uE017"); // Delete++ assert_equals(inputEventsLog.length, 2, "Should have 2 events");+ const [beforeInputEvent, inputEvent] = inputEventsLog;+ assert_equals(beforeInputEvent.type, "beforeinput");+ assert_equals(inputEvent.type, "input");+ assert_equals(+ beforeInputEvent.inputType,+ "deleteContentForward",+ "Regular Delete with selection should report deleteContentForward"+ );+ assert_equals(+ inputEvent.inputType,+ "deleteContentForward",+ "Regular Delete with selection should report deleteContentForward"+ );+ }, "Regular Delete with non-collapsed selection should report deleteContentForward");+</script>diff --git a/Tests/LibWebCommon/CMakeLists.txt b/Tests/LibWebCommon/CMakeLists.txtindex b883c0458d0..c86767a1776 100644--- a/Tests/LibWebCommon/CMakeLists.txt+++ b/Tests/LibWebCommon/CMakeLists.txt@@ -2,6 +2,7 @@ set(TEST_SOURCESTestCSSPixels.cppTestGamepadSharedState.cppTestGamepadStateBuffer.cpp+ TestKeyEvent.cppTestSiteCompatibility.cppTestStrings.cpp)@@ -12,3 +13,4 @@ endforeach()target_link_libraries(TestSiteCompatibility PRIVATE LibURL)target_link_libraries(TestGamepadStateBuffer PRIVATE LibCore LibIPC)+target_link_libraries(TestKeyEvent PRIVATE LibIPC)diff --git a/Tests/LibWebCommon/TestKeyEvent.cpp b/Tests/LibWebCommon/TestKeyEvent.cppnew file mode 100644index 00000000000..17297efd2c2--- /dev/null+++ b/Tests/LibWebCommon/TestKeyEvent.cpp@@ -0,0 +1,61 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/MemoryStream.h>+#include <LibIPC/Decoder.h>+#include <LibIPC/Encoder.h>+#include <LibTest/TestCase.h>+#include <LibWebCommon/Page/InputEvent.h>++static Web::KeyEvent round_trip(Web::KeyEvent const& event)+{+ IPC::MessageBuffer message;+ IPC::Encoder encoder { message };+ MUST(encoder.encode(event));+ Queue<IPC::Attachment> attachments;+ FixedMemoryStream stream { message.data().span() };+ IPC::Decoder decoder { stream, attachments };+ return MUST(decoder.decode<Web::KeyEvent>());+}++TEST_CASE(editing_commands_survive_ipc_and_cloning)+{+ using Type = Web::TextEditingCommand::Type;+ Web::KeyEvent event;+ event.type = Web::KeyEvent::Type::KeyDown;+ event.key = Web::UIEvents::Key_A;+ event.modifiers = Web::UIEvents::Mod_Ctrl;+ event.code_point = 'a';+ event.repeat = true;+ event.id = 71;+ event.editing_commands = { { Type::MoveToBeginningOfParagraph, false }, { Type::MoveForward, true } };+ event.native_editing_binding_resolved = true;++ for (auto const& copy : { round_trip(event), event.clone_without_browser_data() }) {+ EXPECT(copy.editing_commands == event.editing_commands);+ EXPECT(copy.native_editing_binding_resolved);+ EXPECT_EQ(copy.key, Web::UIEvents::Key_A);+ EXPECT_EQ(copy.modifiers, Web::UIEvents::Mod_Ctrl);+ EXPECT_EQ(copy.code_point, static_cast<u32>('a'));+ EXPECT(copy.repeat);+ EXPECT_EQ(copy.id, 71u);+ EXPECT(!copy.browser_data);+ }+}++TEST_CASE(unsupported_native_bindings_remain_distinct_from_raw_keys)+{+ Web::KeyEvent native;+ native.type = Web::KeyEvent::Type::KeyDown;+ native.native_editing_binding_resolved = true;+ auto copy = round_trip(native);+ EXPECT(copy.native_editing_binding_resolved);+ EXPECT(copy.editing_commands.is_empty());++ Web::KeyEvent raw;+ raw.type = Web::KeyEvent::Type::KeyDown;+ EXPECT(!round_trip(raw).native_editing_binding_resolved);+}diff --git a/Tests/UI/Qt/CMakeLists.txt b/Tests/UI/Qt/CMakeLists.txtindex 894416256cc..f2f0444af25 100644--- a/Tests/UI/Qt/CMakeLists.txt+++ b/Tests/UI/Qt/CMakeLists.txt@@ -105,6 +105,21 @@ target_sources(TestProcessManagerWindow PRIVATEtarget_compile_definitions(TestProcessManagerWindow PRIVATE TEST_RESOURCE_ROOT="${LADYBIRD_SOURCE_DIR}/Base/res")deploy_qt_offscreen_platform_plugin(TestProcessManagerWindow)++ladybird_test("TestNativeTextEditingLineEdit.cpp" UI/Qt+ CUSTOM_MAIN "$<TARGET_OBJECTS:QtTestMain>"+ LIBS Qt::Core Qt::Gui Qt::Widgets+)+target_sources(TestNativeTextEditingLineEdit PRIVATE "${LADYBIRD_SOURCE_DIR}/UI/Qt/NativeTextEditingLineEdit.cpp")+if (APPLE)+ target_sources(TestNativeTextEditingLineEdit PRIVATE "${LADYBIRD_SOURCE_DIR}/UI/Qt/NativeTextEditingBindings.mm" "${LADYBIRD_SOURCE_DIR}/UI/Qt/MacWindowFocus.mm")+ target_link_libraries(TestNativeTextEditingLineEdit PRIVATE "-framework AppKit")+endif()+deploy_qt_offscreen_platform_plugin(TestNativeTextEditingLineEdit)++ladybird_test("TestWebContentViewInputMethod.cpp" UI/Qt LIBS LibWebView LibWeb LibGfx LibIPC LibURL Qt::Core Qt::Gui Qt::Widgets)+target_sources(TestWebContentViewInputMethod PRIVATE "${LADYBIRD_SOURCE_DIR}/UI/Qt/InputMethodUtils.cpp" "${LADYBIRD_SOURCE_DIR}/UI/Qt/StringUtils.cpp")+if (NOT LINUX)return()endif()@@ -119,11 +134,9 @@ ladybird_test("TestJavaScriptDialog.cpp" UI/Qttarget_sources(TestJavaScriptDialog PRIVATE"${LADYBIRD_SOURCE_DIR}/UI/Qt/ChromeStyle.cpp""${LADYBIRD_SOURCE_DIR}/UI/Qt/JavaScriptDialog.cpp"+ "${LADYBIRD_SOURCE_DIR}/UI/Qt/NativeTextEditingLineEdit.cpp""${LADYBIRD_SOURCE_DIR}/UI/Qt/StringUtils.cpp")ladybird_test("TestStringUtils.cpp" UI/Qt NAME TestQtStringUtils LIBS LibURL Qt::Core)target_sources(TestQtStringUtils PRIVATE "${LADYBIRD_SOURCE_DIR}/UI/Qt/StringUtils.cpp")--ladybird_test("TestWebContentViewInputMethod.cpp" UI/Qt LIBS LibWebView LibWeb LibGfx LibIPC LibURL Qt::Core Qt::Gui Qt::Widgets)-target_sources(TestWebContentViewInputMethod PRIVATE "${LADYBIRD_SOURCE_DIR}/UI/Qt/InputMethodUtils.cpp" "${LADYBIRD_SOURCE_DIR}/UI/Qt/StringUtils.cpp")diff --git a/Tests/UI/Qt/NativeTextEditingTestMain.mm b/Tests/UI/Qt/NativeTextEditingTestMain.mmnew file mode 100644index 00000000000..3a7936ad5a4--- /dev/null+++ b/Tests/UI/Qt/NativeTextEditingTestMain.mm@@ -0,0 +1,23 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Vector.h>+#include <LibTest/TestSuite.h>++#import <AppKit/AppKit.h>++int main(int argc, char** argv)+{+ @autoreleasepool {+ [NSApplication sharedApplication];+ Vector<StringView> arguments;+ for (int i = 0; i < argc; ++i)+ arguments.append({ argv[i], strlen(argv[i]) });+ auto result = Test::TestSuite::the().main(argv[0], arguments);+ Test::TestSuite::release();+ return result != 0;+ }+}diff --git a/Tests/UI/Qt/TestNativeTextEditingBindings.mm b/Tests/UI/Qt/TestNativeTextEditingBindings.mmnew file mode 100644index 00000000000..ac71ed391e5--- /dev/null+++ b/Tests/UI/Qt/TestNativeTextEditingBindings.mm@@ -0,0 +1,140 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibTest/TestCase.h>+#include <UI/Qt/NativeTextEditingBindings.mm>++#include <QKeyEvent>++static bool custom_bindings()+{+ auto* mode = getenv("LADYBIRD_TEST_BINDINGS_MODE");+ return mode && StringView { mode, strlen(mode) } == "custom"sv;+}++static Ladybird::NativeTextEditingBindingResult interpret(unichar letter, unsigned short key_code, NSEventModifierFlags flags = NSEventModifierFlagControl, NSEventType type = NSEventTypeKeyDown, bool repeat = false)+{+ unichar character = letter & 0x1f;+ unichar unmodified = flags & NSEventModifierFlagShift ? toupper(letter) : letter;+ auto* event = [NSEvent keyEventWithType:type location:NSZeroPoint modifierFlags:flags timestamp:42 windowNumber:0 context:nil characters:[NSString stringWithCharacters:&character length:1] charactersIgnoringModifiers:[NSString stringWithCharacters:&unmodified length:1] isARepeat:repeat keyCode:key_code];+ auto* recorder = [LadybirdNativeTextEditingRecorder new];+ auto result = [recorder commandsForEvent:event];+ [recorder release];+ return result;+}++static void expect_command(unichar letter, unsigned short key_code, Web::TextEditingCommand::Type type, bool extend_selection = false, NSEventModifierFlags flags = NSEventModifierFlagControl)+{+ auto result = interpret(letter, key_code, flags);+ EXPECT(result.binding_resolved);+ EXPECT_EQ(result.commands.size(), 1u);+ if (result.commands.size() != 1)+ return;+ EXPECT_EQ(result.commands[0].type, type);+ EXPECT_EQ(result.commands[0].extend_selection, extend_selection);+}++TEST_CASE(native_paragraph_and_line_bindings)+{+ using Type = Web::TextEditingCommand::Type;+ expect_command('a', 0, Type::MoveToBeginningOfParagraph);+ expect_command('e', 14, Type::MoveToEndOfParagraph);+ expect_command('p', 35, Type::MoveUp);+ expect_command('n', 45, Type::MoveDown);+ expect_command('v', 9, Type::PageDown);+ expect_command('k', 40, Type::DeleteToEndOfParagraph);+ expect_command('h', 4, Type::DeleteBackward);+ expect_command('d', 2, Type::DeleteForward);+}++TEST_CASE(native_character_bindings_honor_user_overrides)+{+ using Type = Web::TextEditingCommand::Type;+ expect_command('b', 11, custom_bindings() ? Type::MoveWordBackward : Type::MoveBackward);+ expect_command('f', 3, custom_bindings() ? Type::MoveWordForward : Type::MoveForward);+}++TEST_CASE(repeated_native_keys_preserve_bindings)+{+ using Type = Web::TextEditingCommand::Type;+ auto result = interpret('b', 11, NSEventModifierFlagControl, NSEventTypeKeyDown, true);+ EXPECT(result.binding_resolved);+ EXPECT_EQ(result.commands.size(), 1u);+ if (result.commands.size() == 1)+ EXPECT_EQ(result.commands[0].type, custom_bindings() ? Type::MoveWordBackward : Type::MoveBackward);+}++TEST_CASE(native_selection_and_option_bindings)+{+ using Type = Web::TextEditingCommand::Type;+ auto shift = NSEventModifierFlagControl | NSEventModifierFlagShift;+ expect_command('a', 0, Type::MoveToBeginningOfParagraph, true, shift);+ expect_command('e', 14, Type::MoveToEndOfParagraph, true, shift);+ expect_command('b', 11, Type::MoveBackward, true, shift);+ expect_command('f', 3, Type::MoveForward, true, shift);+ expect_command('p', 35, Type::MoveUp, true, shift);+ expect_command('n', 45, Type::MoveDown, true, shift);+ expect_command('v', 9, Type::PageDown, true, shift);+ auto option = NSEventModifierFlagControl | NSEventModifierFlagOption;+ expect_command('b', 11, Type::MoveWordBackward, false, option);+ expect_command('f', 3, Type::MoveWordForward, false, option);+ expect_command('b', 11, Type::MoveWordBackward, true, option | NSEventModifierFlagShift);+ expect_command('f', 3, Type::MoveWordForward, true, option | NSEventModifierFlagShift);+}++TEST_CASE(custom_shortcuts_are_interpreted_by_appkit)+{+ using Type = Web::TextEditingCommand::Type;+ if (custom_bindings()) {+ expect_command('w', 13, Type::DeleteWordBackward);+ expect_command('g', 5, Type::DeleteWordBackward);+ expect_command('s', 1, Type::MoveForward, true);+ auto sequence = interpret('z', 6);+ EXPECT(sequence.binding_resolved);+ EXPECT_EQ(sequence.commands.size(), 2u);+ if (sequence.commands.size() == 2) {+ EXPECT_EQ(sequence.commands[0].type, Type::MoveToBeginningOfParagraph);+ EXPECT_EQ(sequence.commands[1].type, Type::MoveForward);+ }+ auto unsupported_sequence = interpret('u', 32);+ EXPECT(unsupported_sequence.binding_resolved);+ EXPECT(unsupported_sequence.commands.is_empty());+ } else {+ auto result = interpret('w', 13);+ EXPECT(result.binding_resolved);+ EXPECT(result.commands.is_empty());+ }+}++TEST_CASE(unsupported_commands_do_not_become_partial_edits)+{+ auto result = interpret('t', 17);+ EXPECT(result.binding_resolved);+ EXPECT(result.commands.is_empty());+}++TEST_CASE(non_control_keys_and_keyups_are_not_interpreted)+{+ EXPECT(!interpret('a', 0, 0).binding_resolved);+ EXPECT(!interpret('a', 0, NSEventModifierFlagControl | NSEventModifierFlagCommand).binding_resolved);+ EXPECT(!interpret('a', 0, NSEventModifierFlagControl, NSEventTypeKeyUp).binding_resolved);+}++TEST_CASE(synthetic_qt_keys_do_not_borrow_the_current_native_event)+{+ Ladybird::NativeTextEditingBindings bindings;+ QKeyEvent key { QEvent::KeyPress, Qt::Key_A, Qt::MetaModifier };+ auto result = bindings.commands_for_key_event(key);+ EXPECT(!result.binding_resolved);+ EXPECT(result.commands.is_empty());+}++TEST_CASE(test_home_is_isolated_before_appkit_initializes)+{+ auto* expected = getenv("CFFIXED_USER_HOME");+ EXPECT(expected);+ EXPECT(expected && strcmp(NSHomeDirectory().UTF8String, expected) == 0);+}diff --git a/Tests/UI/Qt/TestNativeTextEditingLineEdit.cpp b/Tests/UI/Qt/TestNativeTextEditingLineEdit.cppnew file mode 100644index 00000000000..49a3885551d--- /dev/null+++ b/Tests/UI/Qt/TestNativeTextEditingLineEdit.cpp@@ -0,0 +1,88 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibTest/TestCase.h>+#include <UI/Qt/NativeTextEditingLineEdit.h>++using Type = Web::TextEditingCommand::Type;++class TestLineEdit : public Ladybird::NativeTextEditingLineEdit {+public:+ using NativeTextEditingLineEdit::apply_text_editing_command;+};++TEST_CASE(word_deletion_is_single_undoable_edit)+{+ TestLineEdit edit;+ edit.setText("hello world");+ edit.setCursorPosition(11);+ edit.apply_text_editing_command({ Type::DeleteWordBackward });+ EXPECT(edit.text() == "hello ");+ EXPECT_EQ(edit.cursorPosition(), 6);+ edit.undo();+ EXPECT(edit.text() == "hello world");+ edit.redo();+ EXPECT(edit.text() == "hello ");+}++TEST_CASE(paragraph_deletion_deletes_selection_directly)+{+ TestLineEdit edit;+ edit.setText("abcdef");+ edit.setSelection(1, 3);+ edit.apply_text_editing_command({ Type::DeleteToEndOfParagraph });+ EXPECT(edit.text() == "aef");+ EXPECT_EQ(edit.cursorPosition(), 1);+ edit.undo();+ EXPECT(edit.text() == "abcdef");+}++TEST_CASE(selector_selection_preserves_anchor)+{+ TestLineEdit edit;+ edit.setText("abcdef");+ edit.setCursorPosition(3);+ edit.apply_text_editing_command({ Type::MoveToBeginningOfParagraph, true });+ EXPECT(edit.selectedText() == "abc");+ EXPECT_EQ(edit.cursorPosition(), 0);+ edit.apply_text_editing_command({ Type::MoveToEndOfParagraph, true });+ EXPECT(edit.selectedText() == "def");+ EXPECT_EQ(edit.cursorPosition(), 6);+}++TEST_CASE(character_deletion_preserves_graphemes)+{+ TestLineEdit edit;+ edit.setText(QString::fromUtf8("a\xF0\x9F\x98\x80"));+ edit.setCursorPosition(3);+ edit.apply_text_editing_command({ Type::DeleteBackward });+ EXPECT(edit.text() == "a");+ EXPECT_EQ(edit.cursorPosition(), 1);+}++TEST_CASE(read_only_navigation_does_not_delete)+{+ TestLineEdit edit;+ edit.setText("abcdef");+ edit.setCursorPosition(3);+ edit.setReadOnly(true);+ edit.apply_text_editing_command({ Type::MoveToBeginningOfParagraph });+ EXPECT_EQ(edit.cursorPosition(), 0);+ edit.apply_text_editing_command({ Type::DeleteToEndOfParagraph });+ EXPECT(edit.text() == "abcdef");+}++TEST_CASE(no_op_deletion_keeps_history_empty)+{+ TestLineEdit edit;+ edit.setText("abc");+ edit.setCursorPosition(3);+ edit.apply_text_editing_command({ Type::DeleteToEndOfParagraph });+ EXPECT(!edit.isUndoAvailable());+ edit.setCursorPosition(0);+ edit.apply_text_editing_command({ Type::DeleteWordBackward });+ EXPECT(!edit.isUndoAvailable());+}diff --git a/Tests/UI/Qt/run-native-text-editing-tests.py b/Tests/UI/Qt/run-native-text-editing-tests.pynew file mode 100644index 00000000000..26419a22bc4--- /dev/null+++ b/Tests/UI/Qt/run-native-text-editing-tests.py@@ -0,0 +1,39 @@+#!/usr/bin/env python3++# Copyright (c) 2026-present, the Ladybird developers.+# SPDX-License-Identifier: BSD-2-Clause++import os+import plistlib+import subprocess+import sys+import tempfile++from pathlib import Path+++def main():+ binary, mode = sys.argv[1:3]+ with tempfile.TemporaryDirectory(prefix="ladybird-native-bindings-") as directory:+ bindings = Path(directory) / "Library" / "KeyBindings"+ bindings.mkdir(parents=True)+ dictionary = {}+ if mode == "custom":+ dictionary = {+ "^w": "deleteWordBackward:",+ "^g": "deleteWordBackward:",+ "^b": "moveWordBackward:",+ "^f": "moveWordForward:",+ "^s": "moveForwardAndModifySelection:",+ "^z": ["moveToBeginningOfParagraph:", "moveForward:"],+ "^u": ["moveBackward:", "transpose:"],+ }+ (bindings / "DefaultKeyBinding.dict").write_bytes(plistlib.dumps(dictionary))+ environment = os.environ.copy()+ environment["CFFIXED_USER_HOME"] = directory+ environment["LADYBIRD_TEST_BINDINGS_MODE"] = mode+ return subprocess.run([binary, *sys.argv[3:]], env=environment, check=False).returncode+++if __name__ == "__main__":+ sys.exit(main())diff --git a/UI/Qt/BookmarkDialog.cpp b/UI/Qt/BookmarkDialog.cppindex fb104e30c6f..8fc7df417a6 100644--- a/UI/Qt/BookmarkDialog.cpp+++ b/UI/Qt/BookmarkDialog.cpp@@ -8,6 +8,7 @@#include <UI/Qt/BookmarkDialog.h>#include <UI/Qt/ChromeStyle.h>#include <UI/Qt/Icon.h>+#include <UI/Qt/NativeTextEditingLineEdit.h>#include <UI/Qt/StringUtils.h>#include <QAbstractItemView>@@ -129,7 +130,7 @@ BookmarkDialog::BookmarkDialog(QWidget* parent, Type type, Optional<URL::URL conlayout->setVerticalSpacing(12);auto create_text_field = [this] {- auto* field = new QLineEdit(this);+ auto* field = new NativeTextEditingLineEdit(this);field->setMinimumWidth(320);field->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);return field;diff --git a/UI/Qt/CMakeLists.txt b/UI/Qt/CMakeLists.txtindex 8079a70ba18..d60b36ef0bb 100644--- a/UI/Qt/CMakeLists.txt+++ b/UI/Qt/CMakeLists.txt@@ -41,6 +41,7 @@ target_sources(ladybird PRIVATELocationEdit.cppMenu.cppNativeWindowContainer.cpp+ NativeTextEditingLineEdit.cppProcessManagerWindow.cppPerformanceMonitorWidget.cppPopover.cpp@@ -80,6 +81,8 @@ if (APPLE)ExternalURLHandler.mmLadybirdAccessibilityElement.mmMacWindow.mm+ MacWindowFocus.mm+ NativeTextEditingBindings.mmMenu.mmSpellCheckerMac.mmWebContentViewAccessibility.mm@@ -172,6 +175,26 @@ qt_deploy_runtime_dependencies(endif()if (BUILD_TESTING)+ if (APPLE)+ add_library(NativeTextEditingTestMain OBJECT+ ${LADYBIRD_SOURCE_DIR}/Tests/UI/Qt/NativeTextEditingTestMain.mm+ ${LADYBIRD_SOURCE_DIR}/Libraries/LibTest/AssertionHandler.cpp+ )+ target_link_libraries(NativeTextEditingTestMain PRIVATE AK LibTest "-framework AppKit")+ ladybird_test("${LADYBIRD_SOURCE_DIR}/Tests/UI/Qt/TestNativeTextEditingBindings.mm" UI/Qt+ NO_TEST+ CUSTOM_MAIN "$<TARGET_OBJECTS:NativeTextEditingTestMain>"+ LIBS LibWebCommon Qt::Widgets "-framework AppKit"+ )+ foreach(mode default custom)+ add_test(NAME TestNativeTextEditingBindings-${mode}+ COMMAND ${Python3_EXECUTABLE}+ ${LADYBIRD_SOURCE_DIR}/Tests/UI/Qt/run-native-text-editing-tests.py+ $<TARGET_FILE:TestNativeTextEditingBindings> ${mode}+ )+ endforeach()+ endif()+add_executable(TestPerformanceMonitorWidget${LADYBIRD_SOURCE_DIR}/Tests/LibWebView/TestPerformanceMonitorWidget.cppPerformanceMonitorWidget.cppdiff --git a/UI/Qt/FindInPageWidget.cpp b/UI/Qt/FindInPageWidget.cppindex 0e76c4e1b06..7a9d268c955 100644--- a/UI/Qt/FindInPageWidget.cpp+++ b/UI/Qt/FindInPageWidget.cpp@@ -7,6 +7,7 @@#include <UI/Qt/ChromeStyle.h>#include <UI/Qt/FindInPageWidget.h>#include <UI/Qt/Icon.h>+#include <UI/Qt/NativeTextEditingLineEdit.h>#include <UI/Qt/StringUtils.h>#include <UI/Qt/Tab.h>@@ -47,7 +48,7 @@ FindInPageWidget::FindInPageWidget(Tab* tab, WebContentView* content_view)layout->setContentsMargins(5, 5, 5, 5);layout->setAlignment(Qt::AlignmentFlag::AlignLeft);- m_find_text = new QLineEdit(this);+ m_find_text = new NativeTextEditingLineEdit(this);m_find_text->setFocusPolicy(Qt::FocusPolicy::StrongFocus);m_find_text->setSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Fixed);m_find_text->setPlaceholderText("Search");diff --git a/UI/Qt/JavaScriptDialog.cpp b/UI/Qt/JavaScriptDialog.cppindex 6e0284d8d32..0e2d54c2dbe 100644--- a/UI/Qt/JavaScriptDialog.cpp+++ b/UI/Qt/JavaScriptDialog.cpp@@ -6,6 +6,7 @@#include <UI/Qt/ChromeStyle.h>#include <UI/Qt/JavaScriptDialog.h>+#include <UI/Qt/NativeTextEditingLineEdit.h>#include <AK/Platform.h>#include <AK/StdLibExtras.h>@@ -85,7 +86,7 @@ JavaScriptDialog::JavaScriptDialog(QWidget* parent)m_message_scroll_area->setWidget(m_message_label);panel_layout->addWidget(m_message_scroll_area);- m_prompt_text = new QLineEdit(m_panel);+ m_prompt_text = new NativeTextEditingLineEdit(m_panel);m_prompt_text->setObjectName("LadybirdJavaScriptDialogPrompt");panel_layout->addWidget(m_prompt_text);diff --git a/UI/Qt/LocationEdit.cpp b/UI/Qt/LocationEdit.cppindex 3da49454c9f..d378247349d 100644--- a/UI/Qt/LocationEdit.cpp+++ b/UI/Qt/LocationEdit.cpp@@ -99,7 +99,7 @@ static constexpr int LOCATION_PILL_HEIGHT = 22;static constexpr int LOCATION_PILL_HORIZONTAL_PADDING = 18;LocationEdit::LocationEdit(QWidget* parent, WebView::IsPrivate is_private)- : QLineEdit(parent)+ : NativeTextEditingLineEdit(parent), m_omnibox(is_private), m_autocomplete(new Autocomplete(this)){@@ -343,7 +343,7 @@ void LocationEdit::contextMenuEvent(QContextMenuEvent* event)void LocationEdit::focusInEvent(QFocusEvent* event){if (event->reason() == Qt::PopupFocusReason) {- QLineEdit::focusInEvent(event);+ NativeTextEditingLineEdit::focusInEvent(event);m_omnibox.set_suspended(false);return;}@@ -352,7 +352,7 @@ void LocationEdit::focusInEvent(QFocusEvent* event)&& m_url.has_value()&& text() == display_url();- QLineEdit::focusInEvent(event);+ NativeTextEditingLineEdit::focusInEvent(event);m_should_show_full_url_on_mouse_release = should_defer_full_url;@@ -420,8 +420,43 @@ void LocationEdit::animate_focus_glow(int target_alpha)m_focus_glow_animation->start();}+void LocationEdit::native_text_editing_command_will_execute(Web::TextEditingCommand const& command)+{+ if (command.extend_selection) {+ auto focus = cursorPosition();+ auto anchor = hasSelectedText() ? (focus == selectionStart() ? selectionEnd() : selectionStart()) : focus;+ m_omnibox.accept_completion();+ setSelection(anchor, focus - anchor);+ return;+ }+ using Type = Web::TextEditingCommand::Type;+ switch (command.type) {+ case Type::DeleteBackward:+ case Type::DeleteForward:+ case Type::DeleteWordBackward:+ case Type::DeleteWordForward:+ case Type::DeleteToEndOfParagraph:+ m_omnibox.will_delete_text();+ break;+ case Type::MoveForward:+ case Type::MoveWordForward:+ case Type::MoveDown:+ case Type::MoveToEndOfParagraph:+ case Type::MoveToEndOfLine:+ case Type::MoveToRightEndOfLine:+ case Type::PageDown:+ m_omnibox.accept_completion();+ break;+ default:+ m_omnibox.cursor_moved(false);+ break;+ }+}+void LocationEdit::keyPressEvent(QKeyEvent* event){+ if (handle_native_text_editing_key(*event))+ return;if (event->key() == Qt::Key_Escape) {if (m_omnibox.escape_pressed() == WebView::Omnibox::EscapeAction::ClosedPopup)return;diff --git a/UI/Qt/LocationEdit.h b/UI/Qt/LocationEdit.hindex 37a2d4f12f8..31693f650c4 100644--- a/UI/Qt/LocationEdit.h+++ b/UI/Qt/LocationEdit.h@@ -13,8 +13,8 @@#include <LibWebView/Omnibox.h>#include <LibWebView/Settings.h>-#include <QLineEdit>#include <QString>+#include <UI/Qt/NativeTextEditingLineEdit.h>class QAction;class QEvent;@@ -29,7 +29,7 @@ namespace Ladybird {class Autocomplete;class LocationEdit final- : public QLineEdit+ : public NativeTextEditingLineEdit, public WebView::SettingsObserver {Q_OBJECT@@ -59,6 +59,7 @@ private:virtual void focusInEvent(QFocusEvent* event) override;virtual void focusOutEvent(QFocusEvent* event) override;virtual void keyPressEvent(QKeyEvent* event) override;+ virtual void native_text_editing_command_will_execute(Web::TextEditingCommand const&) override;virtual void mouseReleaseEvent(QMouseEvent* event) override;virtual void resizeEvent(QResizeEvent* event) override;diff --git a/UI/Qt/MacWindow.mm b/UI/Qt/MacWindow.mmindex 084017e1f1c..a0e92822168 100644--- a/UI/Qt/MacWindow.mm+++ b/UI/Qt/MacWindow.mm@@ -355,23 +355,6 @@ void offset_appkit_window_controls(QWidget& widget, int x_offset, int y_offset)[observer release];}-void make_appkit_window_first_responder(QWidget& widget)-{- auto* window_widget = widget.window();- if (!window_widget)- return;-- auto* view = reinterpret_cast<NSView*>(window_widget->winId());- if (!view)- return;-- auto* window = view.window;- if (!window)- return;-- [window makeFirstResponder:view];-}-bool start_appkit_window_drag(QWidget& widget){auto* window_widget = widget.window();diff --git a/UI/Qt/MacWindowFocus.mm b/UI/Qt/MacWindowFocus.mmnew file mode 100644index 00000000000..5711c3e1ef1--- /dev/null+++ b/UI/Qt/MacWindowFocus.mm@@ -0,0 +1,35 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <UI/Qt/MacWindow.h>++#include <QGuiApplication>+#include <QWidget>++#import <AppKit/AppKit.h>++namespace Ladybird {++void make_appkit_window_first_responder(QWidget& widget)+{+ if (QGuiApplication::platformName() != "cocoa")+ return;+ auto* window_widget = widget.window();+ if (!window_widget)+ return;++ auto* view = reinterpret_cast<NSView*>(window_widget->winId());+ if (!view)+ return;++ auto* window = view.window;+ if (!window)+ return;++ [window makeFirstResponder:view];+}++}diff --git a/UI/Qt/NativeTextEditingBindings.h b/UI/Qt/NativeTextEditingBindings.hnew file mode 100644index 00000000000..2d6136e81de--- /dev/null+++ b/UI/Qt/NativeTextEditingBindings.h@@ -0,0 +1,36 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Noncopyable.h>+#include <AK/Vector.h>+#include <LibWebCommon/Page/TextEditingCommand.h>++class QKeyEvent;++namespace Ladybird {++struct NativeTextEditingBindingResult {+ bool binding_resolved { false };+ Vector<Web::TextEditingCommand> commands;+};++class NativeTextEditingBindings {+ AK_MAKE_NONCOPYABLE(NativeTextEditingBindings);+ AK_MAKE_NONMOVABLE(NativeTextEditingBindings);++public:+ NativeTextEditingBindings();+ ~NativeTextEditingBindings();++ NativeTextEditingBindingResult commands_for_key_event(QKeyEvent const&);++private:+ void* m_recorder { nullptr };+};++}diff --git a/UI/Qt/NativeTextEditingBindings.mm b/UI/Qt/NativeTextEditingBindings.mmnew file mode 100644index 00000000000..d1e51779b22--- /dev/null+++ b/UI/Qt/NativeTextEditingBindings.mm@@ -0,0 +1,136 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <UI/Qt/NativeTextEditingBindings.h>++#include <AK/Optional.h>+#include <AK/ScopeGuard.h>++#include <QKeyEvent>++#import <AppKit/AppKit.h>++namespace Ladybird {++static Optional<Web::TextEditingCommand> command_for_selector(SEL selector)+{+ using Type = Web::TextEditingCommand::Type;+ struct SelectorCommand {+ SEL selector;+ SEL selection_selector;+ Type type;+ };+ static SelectorCommand const commands[] = {+ { @selector(moveBackward:), @selector(moveBackwardAndModifySelection:), Type::MoveBackward },+ { @selector(moveForward:), @selector(moveForwardAndModifySelection:), Type::MoveForward },+ { @selector(moveWordBackward:), @selector(moveWordBackwardAndModifySelection:), Type::MoveWordBackward },+ { @selector(moveWordForward:), @selector(moveWordForwardAndModifySelection:), Type::MoveWordForward },+ { @selector(moveUp:), @selector(moveUpAndModifySelection:), Type::MoveUp },+ { @selector(moveDown:), @selector(moveDownAndModifySelection:), Type::MoveDown },+ { @selector(moveToBeginningOfParagraph:), @selector(moveToBeginningOfParagraphAndModifySelection:), Type::MoveToBeginningOfParagraph },+ { @selector(moveToEndOfParagraph:), @selector(moveToEndOfParagraphAndModifySelection:), Type::MoveToEndOfParagraph },+ { @selector(moveToBeginningOfLine:), @selector(moveToBeginningOfLineAndModifySelection:), Type::MoveToBeginningOfLine },+ { @selector(moveToEndOfLine:), @selector(moveToEndOfLineAndModifySelection:), Type::MoveToEndOfLine },+ { @selector(moveToLeftEndOfLine:), @selector(moveToLeftEndOfLineAndModifySelection:), Type::MoveToLeftEndOfLine },+ { @selector(moveToRightEndOfLine:), @selector(moveToRightEndOfLineAndModifySelection:), Type::MoveToRightEndOfLine },+ { @selector(pageUp:), @selector(pageUpAndModifySelection:), Type::PageUp },+ { @selector(pageDown:), @selector(pageDownAndModifySelection:), Type::PageDown },+ { @selector(deleteBackward:), nullptr, Type::DeleteBackward },+ { @selector(deleteForward:), nullptr, Type::DeleteForward },+ { @selector(deleteWordBackward:), nullptr, Type::DeleteWordBackward },+ { @selector(deleteWordForward:), nullptr, Type::DeleteWordForward },+ { @selector(deleteToEndOfParagraph:), nullptr, Type::DeleteToEndOfParagraph },+ };+ for (auto const& command : commands) {+ if (selector == command.selector)+ return Web::TextEditingCommand { command.type, false };+ if (command.selection_selector && selector == command.selection_selector)+ return Web::TextEditingCommand { command.type, true };+ }+ return {};+}++struct NativeTextEditingRecording {+ NativeTextEditingBindingResult result;+ bool unsupported_command { false };+};++}++@interface LadybirdNativeTextEditingRecorder : NSResponder+{+ Ladybird::NativeTextEditingRecording* m_recording;+}+- (Ladybird::NativeTextEditingBindingResult)commandsForEvent:(NSEvent*)event;+@end++@implementation LadybirdNativeTextEditingRecorder+- (Ladybird::NativeTextEditingBindingResult)commandsForEvent:(NSEvent*)event+{+ if (event.type != NSEventTypeKeyDown || !(event.modifierFlags & NSEventModifierFlagControl) || (event.modifierFlags & NSEventModifierFlagCommand))+ return {};++ Ladybird::NativeTextEditingRecording recording;+ auto* previous_recording = m_recording;+ m_recording = &recording;+ ScopeGuard restore_recording = [&] { m_recording = previous_recording; };+ [self interpretKeyEvents:@[ event ]];+ if (recording.unsupported_command)+ recording.result.commands.clear();+ return move(recording.result);+}++- (void)doCommandBySelector:(SEL)selector+{+ if (!m_recording)+ return;+ m_recording->result.binding_resolved = true;+ if (auto command = Ladybird::command_for_selector(selector); command.has_value())+ m_recording->result.commands.append(*command);+ else+ m_recording->unsupported_command = true;+}++- (void)insertText:(id)text+{+ (void)text;+ if (m_recording) {+ m_recording->result.binding_resolved = true;+ m_recording->unsupported_command = true;+ }+}++@end++namespace Ladybird {++NativeTextEditingBindings::NativeTextEditingBindings()+ : m_recorder([LadybirdNativeTextEditingRecorder new])+{+}++NativeTextEditingBindings::~NativeTextEditingBindings()+{+ [static_cast<LadybirdNativeTextEditingRecorder*>(m_recorder) release];+}++NativeTextEditingBindingResult NativeTextEditingBindings::commands_for_key_event(QKeyEvent const& event)+{+ if (event.type() != QEvent::KeyPress || !(event.nativeModifiers() & NSEventModifierFlagControl) || (event.nativeModifiers() & NSEventModifierFlagCommand))+ return {};++ auto* native_event = NSApp.currentEvent;+ if (!native_event || native_event.type != NSEventTypeKeyDown+ || native_event.keyCode != event.nativeVirtualKey()+ || native_event.modifierFlags != event.nativeModifiers()+ || native_event.isARepeat != event.isAutoRepeat()+ || static_cast<quint64>(native_event.timestamp * 1000) != event.timestamp())+ return {};++ return [static_cast<LadybirdNativeTextEditingRecorder*>(m_recorder) commandsForEvent:native_event];+}++}diff --git a/UI/Qt/NativeTextEditingLineEdit.cpp b/UI/Qt/NativeTextEditingLineEdit.cppnew file mode 100644index 00000000000..da83858183f--- /dev/null+++ b/UI/Qt/NativeTextEditingLineEdit.cpp@@ -0,0 +1,137 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <QKeyEvent>+#include <QTextBoundaryFinder>+#include <QTextLayout>+#include <UI/Qt/NativeTextEditingLineEdit.h>++#ifdef AK_OS_MACOS+# include <UI/Qt/MacWindow.h>+#endif++namespace Ladybird {++NativeTextEditingLineEdit::NativeTextEditingLineEdit(QWidget* parent)+ : QLineEdit(parent)+{+}++void NativeTextEditingLineEdit::focusInEvent(QFocusEvent* event)+{+#ifdef AK_OS_MACOS+ make_appkit_window_first_responder(*this);+#endif+ QLineEdit::focusInEvent(event);+}++void NativeTextEditingLineEdit::keyPressEvent(QKeyEvent* event)+{+ if (!handle_native_text_editing_key(*event))+ QLineEdit::keyPressEvent(event);+}++bool NativeTextEditingLineEdit::handle_native_text_editing_key(QKeyEvent& event)+{+#ifdef AK_OS_MACOS+ auto binding = m_native_text_editing_bindings.commands_for_key_event(event);+ if (!binding.binding_resolved)+ return false;+ for (auto const& command : binding.commands) {+ native_text_editing_command_will_execute(command);+ apply_text_editing_command(command);+ }+ event.accept();+ return true;+#else+ (void)event;+ return false;+#endif+}++void NativeTextEditingLineEdit::apply_text_editing_command(Web::TextEditingCommand const& command)+{+ if (!isEnabled())+ return;+ auto extend = command.extend_selection;+ auto saved_move_style = cursorMoveStyle();+ setCursorMoveStyle(Qt::LogicalMoveStyle);+ using Type = Web::TextEditingCommand::Type;+ switch (command.type) {+ case Type::MoveBackward:+ cursorBackward(extend);+ break;+ case Type::MoveForward:+ cursorForward(extend);+ break;+ case Type::MoveWordBackward:+ cursorWordBackward(extend);+ break;+ case Type::MoveWordForward:+ cursorWordForward(extend);+ break;+ case Type::MoveUp:+ case Type::MoveToBeginningOfParagraph:+ case Type::MoveToBeginningOfLine:+ case Type::PageUp:+ home(extend);+ break;+ case Type::MoveDown:+ case Type::MoveToEndOfParagraph:+ case Type::MoveToEndOfLine:+ case Type::PageDown:+ end(extend);+ break;+ case Type::MoveToLeftEndOfLine:+ case Type::MoveToRightEndOfLine: {+ QTextLayout layout { displayText(), font() };+ QTextOption option;+ option.setTextDirection(layoutDirection());+ option.setFlags(QTextOption::IncludeTrailingSpaces);+ layout.setTextOption(option);+ layout.beginLayout();+ auto line = layout.createLine();+ layout.endLayout();+ auto position = line.isValid() ? line.xToCursor(command.type == Type::MoveToLeftEndOfLine ? -1 : line.horizontalAdvance() + 1) : 0;+ if (extend) {+ auto anchor = hasSelectedText() ? (cursorPosition() == selectionStart() ? selectionEnd() : selectionStart()) : cursorPosition();+ setSelection(anchor, position - anchor);+ } else {+ setCursorPosition(position);+ }+ break;+ }+ case Type::DeleteBackward:+ case Type::DeleteForward:+ case Type::DeleteWordBackward:+ case Type::DeleteWordForward:+ case Type::DeleteToEndOfParagraph:+ if (isReadOnly())+ break;+ if (!hasSelectedText()) {+ if (command.type == Type::DeleteWordBackward) {+ cursorWordBackward(true);+ } else if (command.type == Type::DeleteWordForward) {+ cursorWordForward(true);+ } else if (command.type == Type::DeleteToEndOfParagraph) {+ end(true);+ } else {+ QTextBoundaryFinder finder { QTextBoundaryFinder::Grapheme, text() };+ auto cursor = cursorPosition();+ finder.setPosition(cursor);+ auto boundary = command.type == Type::DeleteBackward ? finder.toPreviousBoundary() : finder.toNextBoundary();+ if (boundary >= 0)+ setSelection(cursor, boundary - cursor);+ }+ }+ if (hasSelectedText())+ del();+ break;+ }+ setCursorMoveStyle(saved_move_style);+}++}diff --git a/UI/Qt/NativeTextEditingLineEdit.h b/UI/Qt/NativeTextEditingLineEdit.hnew file mode 100644index 00000000000..6db299c96a7--- /dev/null+++ b/UI/Qt/NativeTextEditingLineEdit.h@@ -0,0 +1,38 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/kmalloc.h>+#include <LibWebCommon/Page/TextEditingCommand.h>+#include <QLineEdit>++#ifdef AK_OS_MACOS+# include <UI/Qt/NativeTextEditingBindings.h>+#endif++namespace Ladybird {++class NativeTextEditingLineEdit : public QLineEdit {+public:+ AK_ALLOC_WITH_KMALLOC;++ explicit NativeTextEditingLineEdit(QWidget* parent = nullptr);++protected:+ virtual void focusInEvent(QFocusEvent*) override;+ virtual void keyPressEvent(QKeyEvent*) override;+ bool handle_native_text_editing_key(QKeyEvent&);+ void apply_text_editing_command(Web::TextEditingCommand const&);+ virtual void native_text_editing_command_will_execute(Web::TextEditingCommand const&) { }++private:+#ifdef AK_OS_MACOS+ NativeTextEditingBindings m_native_text_editing_bindings;+#endif+};++}diff --git a/UI/Qt/WebContentView.cpp b/UI/Qt/WebContentView.cppindex 13188bbb738..3f8ec11dd05 100644--- a/UI/Qt/WebContentView.cpp+++ b/UI/Qt/WebContentView.cpp@@ -2084,7 +2084,15 @@ void WebContentView::enqueue_native_event(Web::KeyEvent::Type type, QKeyEvent coreturn { type, keycode, modifiers, code_point, event.isAutoRepeat(), should_insert_text, make<KeyData>(event) };};- enqueue_input_event(to_web_event());+ auto web_event = to_web_event();+#ifdef AK_OS_MACOS+ if (type == Web::KeyEvent::Type::KeyDown) {+ auto binding = m_native_text_editing_bindings.commands_for_key_event(event);+ web_event.editing_commands = AK::move(binding.commands);+ web_event.native_editing_binding_resolved = binding.binding_resolved;+ }+#endif+ enqueue_input_event(AK::move(web_event));}void WebContentView::finish_handling_key_event(Web::KeyEvent const& key_event)diff --git a/UI/Qt/WebContentView.h b/UI/Qt/WebContentView.hindex 8d3d6a0d0ca..0e81decf4a7 100644--- a/UI/Qt/WebContentView.h+++ b/UI/Qt/WebContentView.h@@ -13,6 +13,9 @@#include <AK/OwnPtr.h>#include <AK/Vector.h>#include <AK/kmalloc.h>+#ifdef AK_OS_MACOS+# include <UI/Qt/NativeTextEditingBindings.h>+#endif#include <LibGfx/Cursor.h>#include <LibGfx/Forward.h>#include <LibGfx/Rect.h>@@ -257,6 +260,10 @@ private:QWidget* m_crash_report_container { nullptr };CrashReportReviewWidget* m_crash_report_review { nullptr };+#ifdef AK_OS_MACOS+ NativeTextEditingBindings m_native_text_editing_bindings;+#endif+#ifdef LADYBIRD_QT_USE_IOSURFACE_LAYERbool ensure_iosurface_layer_attached_to_native_view();void present_current_paintable_as_layer_contents();