Skip to content

Truly independent web browser

LibWeb+LibWebView+WebContent: Put spelling guesses in the menu

sideshowbarkerc684e5d5e788
diff --git a/Libraries/LibWeb/Editing/SpellCheckController.cpp b/Libraries/LibWeb/Editing/SpellCheckController.cpp
index 08455a1bf86..c1db3522f85 100644
--- a/Libraries/LibWeb/Editing/SpellCheckController.cpp
+++ b/Libraries/LibWeb/Editing/SpellCheckController.cpp
@@ -483,6 +483,16 @@ bool SpellCheckController::overlaps_exempt_word(DOM::Text const& text, size_t st
void SpellCheckController::apply(Request const& request, Vector<SpellingError> const& errors)
{
+ // NB: An answer can come back after the user told the spellchecker to ignore or learn one of its words, since the
+ // check ran before that. So, no answer marks a word the user accepted.
+ auto request_text = request.text.utf16_view();
+ Vector<SpellingError> misspellings;
+ for (auto const& error : errors) {
+ bool in_range = size_t { error.offset } + error.length <= request_text.length_in_code_units();
+ if (!in_range || !m_document->page().is_accepted_spelling_word(request_text.substring_view(error.offset, error.length)))
+ misspellings.append(error);
+ }
+
auto& markers = m_document->spelling_markers();
for (auto const& piece : request.pieces) {
auto text = piece.text.ptr();
@@ -497,7 +507,7 @@ void SpellCheckController::apply(Request const& request, Vector<SpellingError> c
continue;
markers.remove_overlapping(*text, piece.node_start, piece.node_end);
auto piece_length = piece.node_end - piece.node_start;
- for (auto const& error : errors) {
+ for (auto const& error : misspellings) {
auto error_start = max<size_t>(error.offset, piece.offset);
auto error_end = min<size_t>(error.offset + error.length, piece.offset + piece_length);
if (error_start >= error_end)
diff --git a/Libraries/LibWeb/Editing/SpellingMarkers.h b/Libraries/LibWeb/Editing/SpellingMarkers.h
index 256177181c5..2d5c3199ddb 100644
--- a/Libraries/LibWeb/Editing/SpellingMarkers.h
+++ b/Libraries/LibWeb/Editing/SpellingMarkers.h
@@ -9,6 +9,7 @@
#include <AK/Noncopyable.h>
#include <AK/Optional.h>
#include <AK/Span.h>
+#include <AK/Utf16String.h>
#include <AK/Utf16View.h>
#include <AK/Vector.h>
#include <LibGC/Weak.h>
@@ -31,6 +32,14 @@ struct SpellingMarker {
bool operator==(SpellingMarker const&) const = default;
};
+// The misspelling a right-click landed on, which the context menu's guesses replace.
+struct ContextMenuMisspelling {
+ GC::Weak<DOM::Text> text;
+ size_t start { 0 };
+ size_t end { 0 };
+ Utf16String word;
+};
+
// The spelling markers of a document's text nodes. Script never reaches them:
// "UAs that implement ::spelling-error and ::grammar-error must prevent pages from being able to read the styling of
// such highlighted segments."
diff --git a/Libraries/LibWeb/HTML/FormAssociatedElement.cpp b/Libraries/LibWeb/HTML/FormAssociatedElement.cpp
index 08c68fc43ea..5b9fd16f8b6 100644
--- a/Libraries/LibWeb/HTML/FormAssociatedElement.cpp
+++ b/Libraries/LibWeb/HTML/FormAssociatedElement.cpp
@@ -1279,7 +1279,7 @@ void FormAssociatedTextControlElement::handle_insert(Utf16FlyString const& input
// Record the edit on the document's editing history so the user can undo it. Pastes never
// coalesce with typing, like in the editing host path.
auto& html_element = text_control_to_html_element();
- auto category = input_type == UIEvents::InputTypes::insertFromPaste
+ auto category = first_is_one_of(input_type, UIEvents::InputTypes::insertFromPaste, UIEvents::InputTypes::insertReplacementText)
? Editing::UndoStep::Category::Other
: Editing::UndoStep::Category::Insertion;
auto history = html_element.document().editing_history();
@@ -1307,7 +1307,7 @@ void FormAssociatedTextControlElement::handle_insert(Utf16FlyString const& input
// The input event's data attribute is only set for certain input types according to:
// https://w3c.github.io/input-events/#overview
Optional<Utf16String> data_for_input_event;
- if (first_is_one_of(input_type, UIEvents::InputTypes::insertText, UIEvents::InputTypes::insertCompositionText, UIEvents::InputTypes::insertFromPaste))
+ if (first_is_one_of(input_type, UIEvents::InputTypes::insertText, UIEvents::InputTypes::insertCompositionText, UIEvents::InputTypes::insertFromPaste, UIEvents::InputTypes::insertReplacementText))
data_for_input_event = Utf16String::from_utf16(data_for_insertion);
did_edit_text_node(input_type, data_for_input_event);
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cpp
index 3f45c453f77..a0db902cfd4 100644
--- a/Libraries/LibWeb/Internals/Internals.cpp
+++ b/Libraries/LibWeb/Internals/Internals.cpp
@@ -2641,6 +2641,30 @@ GC::Ref<WebIDL::Promise> Internals::spell_check_settled()
return promise;
}
+GC::Ref<WebIDL::Promise> Internals::activate_spelling_menu_item(Bindings::SpellingMenuItem item, WebIDL::UnsignedLong guess_index)
+{
+ auto& realm = window().principal_realm();
+ auto promise = WebIDL::create_promise_for(window());
+ auto action = [&] {
+ switch (item) {
+ case Bindings::SpellingMenuItem::None:
+ return SpellingMenuActionForTesting::None;
+ case Bindings::SpellingMenuItem::Guess:
+ return SpellingMenuActionForTesting::Guess;
+ case Bindings::SpellingMenuItem::Ignore:
+ return SpellingMenuActionForTesting::IgnoreSpelling;
+ case Bindings::SpellingMenuItem::Learn:
+ return SpellingMenuActionForTesting::LearnSpelling;
+ }
+ VERIFY_NOT_REACHED();
+ }();
+ page().request_spelling_menu_action_for_testing(action, guess_index, GC::create_function(heap(), [&realm, promise](String menu) {
+ HTML::TemporaryExecutionContext execution_context { realm };
+ WebIDL::resolve_promise(realm, promise, JS::PrimitiveString::create(realm.vm(), Utf16String::from_utf8(menu)));
+ }));
+ return promise;
+}
+
GC::Ptr<JS::Object> Internals::hit_test_result(double x, double y)
{
auto& realm = HTML::relevant_realm(window());
diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.h
index 05152afe514..d572cb85466 100644
--- a/Libraries/LibWeb/Internals/Internals.h
+++ b/Libraries/LibWeb/Internals/Internals.h
@@ -86,6 +86,7 @@ public:
Utf16String spelling_error_ranges(GC::Ref<DOM::Node>);
GC::Ref<WebIDL::Promise> check_spelling_for_testing(Utf16String const& text);
GC::Ref<WebIDL::Promise> spell_check_settled();
+ GC::Ref<WebIDL::Promise> activate_spelling_menu_item(Bindings::SpellingMenuItem, WebIDL::UnsignedLong guess_index);
void send_text(HTML::HTMLElement&, Utf16String const&, WebIDL::UnsignedShort modifiers);
void send_text_through_ui_process(Utf16String const&);
diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idl
index c0ae0d43efd..f0320d4ac81 100644
--- a/Libraries/LibWeb/Internals/Internals.idl
+++ b/Libraries/LibWeb/Internals/Internals.idl
@@ -49,6 +49,7 @@ interface Internals {
DOMString spellingErrorRanges(Node node);
Promise<DOMString> checkSpellingForTesting(DOMString text);
Promise<undefined> spellCheckSettled();
+ Promise<DOMString> activateSpellingMenuItem(SpellingMenuItem item, optional unsigned long guessIndex = 0);
const unsigned short MOD_NONE = 0;
const unsigned short MOD_ALT = 1;
@@ -368,4 +369,5 @@ interface Internals {
};
+enum SpellingMenuItem { "none", "guess", "ignore", "learn" };
enum ScrollGesturePhase { "none", "ongoing", "momentum", "ended" };
diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cpp
index 871d469cef8..e139a807d65 100644
--- a/Libraries/LibWeb/Page/EventHandler.cpp
+++ b/Libraries/LibWeb/Page/EventHandler.cpp
@@ -2434,6 +2434,26 @@ EventResult EventHandler::insert_pasted_content(Utf16View plain_text, Optional<U
return EventResult::Handled;
}
+// https://w3c.github.io/input-events/#interface-InputEvent-Attributes
+// "insertReplacementText": insert or replace existing content by means of a spell checker, auto-correct, writing
+// suggestions or similar
+EventResult EventHandler::insert_replacement_text(Utf16String const& text)
+{
+ auto active_document = m_navigable->active_document();
+ if (!active_document || !active_document->is_fully_active())
+ return EventResult::Dropped;
+
+ auto* target = active_document->active_input_events_target();
+ if (!target)
+ return EventResult::Dropped;
+
+ // FIXME: For an editing host, data should be null and dataTransfer should hold the text, but InputEvent has no
+ // dataTransfer yet.
+ FIRE(input_event(UIEvents::EventNames::beforeinput, UIEvents::InputTypes::insertReplacementText, m_navigable, text));
+ target->handle_insert(UIEvents::InputTypes::insertReplacementText, text);
+ return EventResult::Handled;
+}
+
void EventHandler::handle_gamepad_connected(Gamepad::GamepadDescription const& description)
{
auto active_document = m_navigable->active_document();
@@ -3239,11 +3259,17 @@ void EventHandler::maybe_show_context_menu(GC::Ref<DOM::Node> node, MouseEventCo
m_navigable->page().record_context_menu_request({}, { .kind = Page::ContextMenuRequest::Kind::Media, .target = media_element });
m_navigable->page().did_request_media_context_menu(media_element.unique_id(), local_root_id, page_viewport_position, "", modifiers, menu, move(navigation));
} else {
- select_context_menu_text(read, document, coordinates.visual_viewport_position);
+ auto misspelling = select_context_menu_misspelling(read, document, coordinates.visual_viewport_position);
+ if (!misspelling.has_value())
+ select_context_menu_text(read, document, coordinates.visual_viewport_position);
+ Optional<Utf16String> misspelled_word;
+ if (misspelling.has_value())
+ misspelled_word = misspelling->word;
+ m_navigable->page().record_context_menu_misspelling({}, move(misspelling));
auto for_input_events_target = document->active_input_events_target() ? ContextMenuForInputEventsTarget::Yes : ContextMenuForInputEventsTarget::No;
m_navigable->page().record_context_menu_request({}, { .kind = Page::ContextMenuRequest::Kind::Page, .target = context_menu_node });
- m_navigable->page().client().page_did_request_context_menu(local_root_id, page_viewport_position, for_input_events_target);
+ m_navigable->page().client().page_did_request_context_menu(local_root_id, page_viewport_position, for_input_events_target, move(misspelled_word));
}
}
}
@@ -3484,6 +3510,50 @@ bool EventHandler::initiate_character_selection(DOM::Document& document, Paintin
return true;
}
+// A right-click on a misspelled word selects exactly the misspelling, so the menu's guesses replace just that.
+Optional<Editing::ContextMenuMisspelling> EventHandler::select_context_menu_misspelling(Layout::BegunRead const& read, DOM::Document& document, CSSPixelPoint visual_viewport_position)
+{
+ if (!document.has_spelling_markers())
+ return {};
+ auto caret_position = document.caret_position_from_point_for_selection_start(read, visual_viewport_position);
+ if (!caret_position.has_value())
+ return {};
+ auto* text = as_if<DOM::Text>(caret_position->boundary_node().ptr());
+ if (!text)
+ return {};
+ auto marker = document.spelling_markers().marker_containing(*text, caret_position->boundary.offset);
+ if (!marker.has_value())
+ return {};
+
+ // A misspelling in a field the user has left gets the field focused first, so the guess the user picks can replace
+ // it there.
+ if (!document.active_input_events_target(text)) {
+ if (auto focus_candidate = focus_candidate_for_position(read, visual_viewport_position))
+ HTML::run_focusing_steps(focus_candidate, nullptr, HTML::FocusTrigger::Click);
+ else if (auto editing_host = text->editing_host())
+ HTML::run_focusing_steps(editing_host, nullptr, HTML::FocusTrigger::Click);
+
+ // NB: Focusing may have invalidated layout.
+ document.update_layout(DOM::UpdateLayoutReason::EventHandlerShowContextMenu);
+
+ // A focus listener runs inside the focusing steps, and an edit it makes moves or drops the text's markers — so
+ // the misspelling the click landed on counts only if its marker is still where it was.
+ if (!document.spelling_markers().markers_for(*text).contains_slow(*marker))
+ return {};
+ }
+
+ // A field that didn't take focus has nowhere for a guess to go.
+ auto* target = document.active_input_events_target(text);
+ if (!target)
+ return {};
+ target->set_selection_anchor(*text, marker->start);
+ target->set_selection_focus(*text, marker->end);
+ stop_updating_selection();
+
+ auto word = Utf16String::from_utf16(text->data().utf16_view().substring_view(marker->start, marker->end - marker->start));
+ return Editing::ContextMenuMisspelling { *text, marker->start, marker->end, move(word) };
+}
+
bool EventHandler::initiate_word_selection(Layout::BegunRead const& read, DOM::Document& document, Painting::CaretPosition const& caret_position, CSS::UserSelect user_select)
{
auto* boundary_node = as_if<DOM::Text>(caret_position.boundary_node().ptr());
diff --git a/Libraries/LibWeb/Page/EventHandler.h b/Libraries/LibWeb/Page/EventHandler.h
index 6dca3bac0b4..32a6f4fdce1 100644
--- a/Libraries/LibWeb/Page/EventHandler.h
+++ b/Libraries/LibWeb/Page/EventHandler.h
@@ -22,6 +22,7 @@
#include <LibWeb/CSS/PseudoElement.h>
#include <LibWeb/DOM/HoverEventData.h>
#include <LibWeb/DOM/NodeIdentity.h>
+#include <LibWeb/Editing/SpellingMarkers.h>
#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
#include <LibWeb/Layout/LayoutRustFFI.h>
@@ -68,6 +69,7 @@ public:
EventResult handle_mouseup(CSSPixelPoint, CSSPixelPoint screen_position, unsigned button, unsigned buttons, unsigned modifiers, Optional<RemoteInputEventTarget>* remote_target = nullptr);
EventResult handle_mousewheel(CSSPixelPoint, CSSPixelPoint screen_position, unsigned button, unsigned buttons, unsigned modifiers, double wheel_delta_x, double wheel_delta_y, Web::WheelDeltaPrecision = Web::WheelDeltaPrecision::Discrete, Web::ScrollGesturePhase = Web::ScrollGesturePhase::None, bool async_scroll_performed_default_action = false, Optional<AsyncScrollOperation>* async_scroll_operation = nullptr, Optional<RemoteInputEventTarget>* remote_target = nullptr);
EventResult handle_mouseleave();
+ EventResult insert_replacement_text(Utf16String const&);
#if defined(AK_OS_MACOS)
bool select_word_for_dictionary_lookup(CSSPixelPoint visual_viewport_position);
#endif
@@ -172,6 +174,7 @@ private:
bool initiate_word_selection(Layout::BegunRead const& read, DOM::Document&, Painting::CaretPosition const&, CSS::UserSelect);
bool initiate_paragraph_selection(DOM::Document&, Painting::CaretPosition const&, CSS::UserSelect);
bool select_context_menu_text(Layout::BegunRead const& read, DOM::Document&, CSSPixelPoint visual_viewport_position);
+ Optional<Editing::ContextMenuMisspelling> select_context_menu_misspelling(Layout::BegunRead const& read, DOM::Document&, CSSPixelPoint visual_viewport_position);
bool select_context_menu_url_token(DOM::Document&, Painting::CaretPosition const&, CSS::UserSelect);
#if defined(AK_OS_MACOS)
bool select_word_at_position(Layout::BegunRead const& read, DOM::Document&, CSSPixelPoint visual_viewport_position);
diff --git a/Libraries/LibWeb/Page/Page.cpp b/Libraries/LibWeb/Page/Page.cpp
index 966e43b02aa..42503cb8e5f 100644
--- a/Libraries/LibWeb/Page/Page.cpp
+++ b/Libraries/LibWeb/Page/Page.cpp
@@ -19,6 +19,7 @@
#include <LibWeb/DOM/Element.h>
#include <LibWeb/DOM/Range.h>
#include <LibWeb/Editing/SpellCheckController.h>
+#include <LibWeb/Editing/SpellingMarkers.h>
#include <LibWeb/HTML/BrowsingContext.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/EventNames.h>
@@ -134,6 +135,7 @@ void Page::visit_edges(JS::Cell::Visitor& visitor)
visitor.visit(m_pending_clipboard_requests);
visitor.visit(m_pending_spell_check_requests);
visitor.visit(m_spell_checking_settled_callbacks);
+ visitor.visit(m_on_spelling_menu_action_for_testing);
visitor.visit(m_emulated_position_data);
visitor.visit(m_emulated_position_data_observers);
visitor.visit(m_offscreen_canvases_pending_placeholder_commit);
@@ -1292,6 +1294,58 @@ static bool spell_checking_is_settled(Page& page)
return true;
}
+void Page::replace_context_menu_misspelling(Utf16String const& replacement)
+{
+ // A menu takes one action, so the misspelling it was opened on is used up here.
+ if (!m_context_menu_misspelling.has_value())
+ return;
+ auto misspelling = m_context_menu_misspelling.release_value();
+ auto text = misspelling.text.ptr();
+ if (!text)
+ return;
+ // The text may have changed while the menu was open; replace only the word the menu was for.
+ auto data = text->data().utf16_view();
+ if (misspelling.end > data.length_in_code_units()
+ || data.substring_view(misspelling.start, misspelling.end - misspelling.start) != misspelling.word.utf16_view())
+ return;
+ auto& document = text->document();
+ auto* navigable = as_if<HTML::LocalNavigable>(document.navigable().ptr());
+ auto* target = document.active_input_events_target(text.ptr());
+ if (!navigable || !target)
+ return;
+ target->set_selection_anchor(*text, misspelling.start);
+ target->set_selection_focus(*text, misspelling.end);
+ (void)navigable->event_handler().insert_replacement_text(replacement);
+}
+
+// The user told the spellchecker to ignore or learn a word. Its markers come off, and no answer marks it again, including
+// the answers to checks that ran before the spellchecker knew.
+void Page::accept_spelling_word(Utf16String const& word)
+{
+ m_accepted_spelling_words.set(word);
+ for (auto const& navigable : hosted_navigables()) {
+ if (auto document = navigable->active_document(); document && document->has_spelling_markers())
+ document->spelling_markers().remove_markers_for_word(word);
+ }
+}
+
+bool Page::is_accepted_spelling_word(Utf16View word) const
+{
+ return m_accepted_spelling_words.contains(Utf16String::from_utf16(word));
+}
+
+void Page::request_spelling_menu_action_for_testing(SpellingMenuActionForTesting action, u32 guess_index, GC::Ref<GC::Function<void(String)>> on_complete)
+{
+ m_on_spelling_menu_action_for_testing = on_complete;
+ client().page_did_request_spelling_menu_action_for_testing(action, guess_index);
+}
+
+void Page::did_complete_spelling_menu_action_for_testing(String menu)
+{
+ if (auto callback = exchange(m_on_spelling_menu_action_for_testing, nullptr))
+ callback->function()(move(menu));
+}
+
void Page::when_spell_checking_settled(GC::Ref<GC::Function<void()>> callback)
{
m_spell_checking_settled_callbacks.append(callback);
diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.h
index 806b5aaa081..7d99588528e 100644
--- a/Libraries/LibWeb/Page/Page.h
+++ b/Libraries/LibWeb/Page/Page.h
@@ -39,6 +39,7 @@
#include <LibWeb/Bindings/AgentType.h>
#include <LibWeb/Bindings/Navigation.h>
#include <LibWeb/DOM/RequestFullscreenError.h>
+#include <LibWeb/Editing/SpellingMarkers.h>
#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
#include <LibWeb/Geolocation/Geolocation.h>
@@ -368,6 +369,14 @@ public:
};
void record_context_menu_request(Badge<EventHandler>, ContextMenuRequest);
void clear_context_menu_request() { m_context_menu_request.clear(); }
+ void record_context_menu_misspelling(Badge<EventHandler>, Optional<Editing::ContextMenuMisspelling> misspelling) { m_context_menu_misspelling = move(misspelling); }
+ void replace_context_menu_misspelling(Utf16String const& replacement);
+ void accept_spelling_word(Utf16String const& word);
+ bool is_accepted_spelling_word(Utf16View word) const;
+ void forget_accepted_spelling_words() { m_accepted_spelling_words.clear(); }
+
+ void request_spelling_menu_action_for_testing(SpellingMenuActionForTesting, u32 guess_index, GC::Ref<GC::Function<void(String)>> on_complete);
+ void did_complete_spelling_menu_action_for_testing(String menu);
Optional<ContextMenuRequest> take_context_menu_request();
using MediaContextMenu = Web::MediaContextMenu;
@@ -547,6 +556,9 @@ private:
Web::HTML::MuteState m_mute_state { Web::HTML::MuteState::Unmuted };
Optional<ContextMenuRequest> m_context_menu_request;
+ Optional<Editing::ContextMenuMisspelling> m_context_menu_misspelling;
+ HashTable<Utf16String> m_accepted_spelling_words;
+ GC::Ptr<GC::Function<void(String)>> m_on_spelling_menu_action_for_testing;
size_t m_active_screen_wake_lock_count { 0 };
Optional<Utf16String> m_user_style_sheet_source;
@@ -711,7 +723,7 @@ public:
// The node an assistive technology should treat as focused: the focused element, or the document element once
// nothing in the document is focused.
virtual void page_did_change_accessibility_focus(Web::UniqueNodeID) { }
- virtual void page_did_request_context_menu([[maybe_unused]] HTML::CrossProcessId local_root_id, CSSPixelPoint, ContextMenuForInputEventsTarget) { }
+ virtual void page_did_request_context_menu([[maybe_unused]] HTML::CrossProcessId local_root_id, CSSPixelPoint, ContextMenuForInputEventsTarget, [[maybe_unused]] Optional<Utf16String> misspelled_word) { }
virtual void page_did_request_link_context_menu([[maybe_unused]] HTML::CrossProcessId local_root_id, CSSPixelPoint, HTML::PreparedNavigationDescriptor, [[maybe_unused]] ByteString const& target, [[maybe_unused]] unsigned modifiers) { }
virtual void page_did_request_image_context_menu([[maybe_unused]] HTML::CrossProcessId local_root_id, CSSPixelPoint, HTML::PreparedNavigationDescriptor, [[maybe_unused]] ByteString const& target, [[maybe_unused]] unsigned modifiers, Optional<Gfx::Bitmap const*>) { }
virtual void page_did_request_media_context_menu([[maybe_unused]] HTML::CrossProcessId local_root_id, CSSPixelPoint, [[maybe_unused]] ByteString const& target, [[maybe_unused]] unsigned modifiers, Page::MediaContextMenu const&, HTML::PreparedNavigationDescriptor) { }
@@ -779,6 +791,7 @@ public:
virtual void page_did_request_set_system_focus([[maybe_unused]] bool has_system_focus) { }
virtual void page_did_change_focused_navigable([[maybe_unused]] HTML::CrossProcessId navigable_id) { }
virtual void page_did_request_key_event_for_testing([[maybe_unused]] Web::KeyEvent event) { }
+ virtual void page_did_request_spelling_menu_action_for_testing([[maybe_unused]] SpellingMenuActionForTesting action, [[maybe_unused]] u32 guess_index) { }
virtual void page_did_request_webdriver_mouse_event([[maybe_unused]] HTML::CrossProcessId local_root_id, [[maybe_unused]] Web::MouseEvent event, GC::Ref<GC::Function<void()>> on_handled) { on_handled->function()(); }
virtual void page_did_request_set_system_visibility_state([[maybe_unused]] HTML::VisibilityState visibility_state) { }
virtual String page_did_request_ui_process_session_history_for_testing() { return "{}"_string; }
diff --git a/Libraries/LibWeb/UIEvents/InputTypes.h b/Libraries/LibWeb/UIEvents/InputTypes.h
index 03e61425820..28da806181a 100644
--- a/Libraries/LibWeb/UIEvents/InputTypes.h
+++ b/Libraries/LibWeb/UIEvents/InputTypes.h
@@ -22,6 +22,7 @@ namespace Web::UIEvents::InputTypes {
__ENUMERATE_INPUT_TYPE(insertFromPaste) \
__ENUMERATE_INPUT_TYPE(insertLineBreak) \
__ENUMERATE_INPUT_TYPE(insertParagraph) \
+ __ENUMERATE_INPUT_TYPE(insertReplacementText) \
__ENUMERATE_INPUT_TYPE(insertText)
#define __ENUMERATE_INPUT_TYPE(name) extern WEB_API Utf16FlyString const& name;
diff --git a/Libraries/LibWebView/Menu.h b/Libraries/LibWebView/Menu.h
index a927d42a6de..989c5a1ff5b 100644
--- a/Libraries/LibWebView/Menu.h
+++ b/Libraries/LibWebView/Menu.h
@@ -41,6 +41,10 @@ enum class ActionID {
LookUpSelectedText,
SearchSelectedText,
+ SpellingGuess,
+ NoSpellingGuesses,
+ IgnoreSpelling,
+ LearnSpelling,
TakeVisibleScreenshot,
TakeFullScreenshot,
diff --git a/Libraries/LibWebView/SpellChecker.h b/Libraries/LibWebView/SpellChecker.h
index 92936b74c56..0a45c6f939a 100644
--- a/Libraries/LibWebView/SpellChecker.h
+++ b/Libraries/LibWebView/SpellChecker.h
@@ -33,6 +33,9 @@ public:
virtual Vector<Utf16String> guesses(DocumentTag, Utf16String const& word) = 0;
virtual void ignore(DocumentTag, Utf16String const& word) = 0;
virtual void learn(DocumentTag, Utf16String const& word) = 0;
+
+ // Whether a learned word holds for every document tag, as it does in a user dictionary that every app shares.
+ virtual bool learns_for_every_tag() const { return true; }
};
}
diff --git a/Libraries/LibWebView/TestSpellChecker.cpp b/Libraries/LibWebView/TestSpellChecker.cpp
index c3d741f6eae..34d922844b5 100644
--- a/Libraries/LibWebView/TestSpellChecker.cpp
+++ b/Libraries/LibWebView/TestSpellChecker.cpp
@@ -18,6 +18,7 @@ static constexpr Array s_misspelled_words {
u"wrod"sv,
u"speling"sv,
u"lernword"sv,
+ u"lernagain"sv,
};
static Vector<Utf16String> guesses_for(Utf16View word)
diff --git a/Libraries/LibWebView/TestSpellChecker.h b/Libraries/LibWebView/TestSpellChecker.h
index 2ae05ec15d1..b14d10d89c7 100644
--- a/Libraries/LibWebView/TestSpellChecker.h
+++ b/Libraries/LibWebView/TestSpellChecker.h
@@ -21,6 +21,7 @@ public:
virtual Vector<Utf16String> guesses(DocumentTag, Utf16String const& word) override;
virtual void ignore(DocumentTag, Utf16String const& word) override;
virtual void learn(DocumentTag, Utf16String const& word) override;
+ virtual bool learns_for_every_tag() const override { return false; }
private:
bool is_misspelled(DocumentTag, Utf16View word) const;
diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cpp
index 9d2b8beef80..1d93392f267 100644
--- a/Libraries/LibWebView/ViewImplementation.cpp
+++ b/Libraries/LibWebView/ViewImplementation.cpp
@@ -3801,7 +3801,31 @@ void ViewImplementation::initialize_context_menus()
menu.add_action(application.select_all_action());
};
+ for (size_t index = 0; index < MAX_SPELLING_GUESSES; ++index) {
+ auto action = Action::create(""sv, ActionID::SpellingGuess, [this, index] {
+ if (index >= m_spelling_guesses.size() || !m_spelling_context_menu_page || !m_spelling_context_menu_page->is_open())
+ return;
+ m_spelling_context_menu_page->async_replace_context_menu_misspelling(m_spelling_guesses[index]);
+ });
+ action->set_visible(false);
+ m_spelling_guess_actions.append(move(action));
+ }
+ m_no_spelling_guesses_action = Action::create("No Guesses Found"sv, ActionID::NoSpellingGuesses, [] { });
+ m_no_spelling_guesses_action->set_enabled(false);
+ m_no_spelling_guesses_action->set_visible(false);
+ m_ignore_spelling_action = Action::create("Ignore Spelling"sv, ActionID::IgnoreSpelling, [this] { ignore_context_menu_misspelling(); });
+ m_ignore_spelling_action->set_visible(false);
+ m_learn_spelling_action = Action::create("Learn Spelling"sv, ActionID::LearnSpelling, [this] { learn_context_menu_misspelling(); });
+ m_learn_spelling_action->set_visible(false);
+
m_page_context_menu = Menu::create("Page Context Menu"sv);
+ for (auto& action : m_spelling_guess_actions)
+ m_page_context_menu->add_action(action);
+ m_page_context_menu->add_action(*m_no_spelling_guesses_action);
+ m_page_context_menu->add_separator();
+ m_page_context_menu->add_action(*m_ignore_spelling_action);
+ m_page_context_menu->add_action(*m_learn_spelling_action);
+ m_page_context_menu->add_separator();
m_page_context_menu->add_action(*m_look_up_selected_text_action);
m_page_context_menu->add_action(*m_navigate_back_action);
m_page_context_menu->add_action(*m_navigate_forward_action);
@@ -4061,10 +4085,122 @@ void ViewImplementation::reset_spell_checking()
if (auto* spell_checker = Application::the().spell_checker(); spell_checker && m_spell_document_tag.has_value())
spell_checker->close_document_tag(*m_spell_document_tag);
m_spell_document_tag.clear();
+ if (m_top_level_traversable) {
+ traversable().for_each_hosting_page([](WebContentPage& page) {
+ if (page.is_open())
+ page.async_forget_accepted_spelling_words();
+ });
+ }
+}
+
+void ViewImplementation::update_spelling_menu_actions(Optional<Utf16String> misspelled_word)
+{
+ auto* spell_checker = Application::the().spell_checker();
+ m_context_menu_misspelled_word = spell_checker ? move(misspelled_word) : OptionalNone {};
+ m_spelling_guesses.clear();
+ if (m_context_menu_misspelled_word.has_value())
+ m_spelling_guesses = spell_checker->guesses(spell_document_tag(), *m_context_menu_misspelled_word);
+ if (m_spelling_guesses.size() > MAX_SPELLING_GUESSES)
+ m_spelling_guesses.shrink(MAX_SPELLING_GUESSES);
+
+ auto shows_block = m_context_menu_misspelled_word.has_value();
+ for (size_t index = 0; index < m_spelling_guess_actions.size(); ++index) {
+ auto shows_guess = shows_block && index < m_spelling_guesses.size();
+ if (shows_guess)
+ m_spelling_guess_actions[index]->set_text(MUST(m_spelling_guesses[index].utf16_view().to_utf8()));
+ m_spelling_guess_actions[index]->set_visible(shows_guess);
+ }
+ m_no_spelling_guesses_action->set_visible(shows_block && m_spelling_guesses.is_empty());
+ m_ignore_spelling_action->set_visible(shows_block);
+ m_learn_spelling_action->set_visible(shows_block);
+}
+
+void ViewImplementation::ignore_context_menu_misspelling()
+{
+ auto* spell_checker = Application::the().spell_checker();
+ if (!spell_checker || !m_context_menu_misspelled_word.has_value())
+ return;
+ auto word = *m_context_menu_misspelled_word;
+ spell_checker->ignore(spell_document_tag(), word);
+ // An ignored word holds for this tab, so every page of the tab drops its markers for it.
+ traversable().for_each_hosting_page([&](WebContentPage& page) {
+ page.async_accept_spelling_word(word);
+ });
}
-void ViewImplementation::did_request_page_context_menu(Badge<WebContentPage>, Gfx::IntPoint content_position, Web::ContextMenuForInputEventsTarget for_input_events_target)
+void ViewImplementation::learn_context_menu_misspelling()
{
+ auto* spell_checker = Application::the().spell_checker();
+ if (!spell_checker || !m_context_menu_misspelled_word.has_value())
+ return;
+ auto word = *m_context_menu_misspelled_word;
+ spell_checker->learn(spell_document_tag(), word);
+ // A learned word goes in the user's dictionary for every app, so every page of every tab drops its markers for it.
+ // A spellchecker that learns for this tab's tag alone gets the word dropped from this tab alone.
+ if (!spell_checker->learns_for_every_tag()) {
+ traversable().for_each_hosting_page([&](WebContentPage& page) {
+ page.async_accept_spelling_word(word);
+ });
+ return;
+ }
+ for_each_view([&](ViewImplementation& view) {
+ if (view.m_top_level_traversable) {
+ view.traversable().for_each_hosting_page([&](WebContentPage& page) {
+ page.async_accept_spelling_word(word);
+ });
+ }
+ return IterationDecision::Continue;
+ });
+}
+
+String ViewImplementation::describe_spelling_menu_for_testing() const
+{
+ StringBuilder builder;
+ auto append = [&](Action const& action) {
+ if (!action.visible())
+ return;
+ if (!builder.is_empty())
+ builder.append(" | "sv);
+ builder.append(action.text());
+ };
+ for (auto const& action : m_spelling_guess_actions)
+ append(action);
+ append(*m_no_spelling_guesses_action);
+ append(*m_ignore_spelling_action);
+ append(*m_learn_spelling_action);
+ if (builder.is_empty())
+ return "(no spelling items)"_string;
+ return MUST(builder.to_string());
+}
+
+void ViewImplementation::activate_spelling_menu_action_for_testing(Badge<WebContentPage>, WebContentPage& requesting_page, Web::SpellingMenuActionForTesting action, u32 guess_index)
+{
+ auto menu = describe_spelling_menu_for_testing();
+ switch (action) {
+ case Web::SpellingMenuActionForTesting::None:
+ break;
+ case Web::SpellingMenuActionForTesting::Guess:
+ if (guess_index < m_spelling_guess_actions.size() && m_spelling_guess_actions[guess_index]->visible())
+ m_spelling_guess_actions[guess_index]->activate();
+ break;
+ case Web::SpellingMenuActionForTesting::IgnoreSpelling:
+ if (m_ignore_spelling_action->visible())
+ m_ignore_spelling_action->activate();
+ break;
+ case Web::SpellingMenuActionForTesting::LearnSpelling:
+ if (m_learn_spelling_action->visible())
+ m_learn_spelling_action->activate();
+ break;
+ }
+ // The page gets this after whatever the action sent it, on the same connection.
+ requesting_page.async_did_complete_spelling_menu_action_for_testing(menu);
+}
+
+void ViewImplementation::did_request_page_context_menu(Badge<WebContentPage>, WebContentPage& requesting_page, Gfx::IntPoint content_position, Web::ContextMenuForInputEventsTarget for_input_events_target, Optional<Utf16String> misspelled_word)
+{
+ m_spelling_context_menu_page = requesting_page;
+ update_spelling_menu_actions(move(misspelled_word));
+
auto request_id = ++m_context_menu_request_id;
auto weak_this = make_weak_ptr();
request_context_menu_dictionary_lookup([weak_this, request_id, content_position, for_input_events_target](auto const& lookup) {
diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.h
index 941116629a7..cf0444e8d76 100644
--- a/Libraries/LibWebView/ViewImplementation.h
+++ b/Libraries/LibWebView/ViewImplementation.h
@@ -529,7 +529,8 @@ public:
Menu& bookmark_context_menu() { return *m_bookmark_context_menu; }
Menu& bookmark_folder_context_menu() { return *m_bookmark_folder_context_menu; }
- void did_request_page_context_menu(Badge<WebContentPage>, Gfx::IntPoint content_position, Web::ContextMenuForInputEventsTarget for_input_events_target);
+ void did_request_page_context_menu(Badge<WebContentPage>, WebContentPage& requesting_page, Gfx::IntPoint content_position, Web::ContextMenuForInputEventsTarget for_input_events_target, Optional<Utf16String> misspelled_word);
+ void activate_spelling_menu_action_for_testing(Badge<WebContentPage>, WebContentPage& requesting_page, Web::SpellingMenuActionForTesting, u32 guess_index);
void did_request_spell_check(Badge<WebContentPage>, WebContentPage& requesting_page, u64 request_id, Utf16String text);
void reset_spell_checking();
@@ -894,6 +895,20 @@ protected:
RefPtr<WebContentPage> m_select_dropdown_page;
RefPtr<WebContentPage> m_media_context_menu_page;
+ static constexpr size_t MAX_SPELLING_GUESSES = 5;
+ void update_spelling_menu_actions(Optional<Utf16String> misspelled_word);
+ void ignore_context_menu_misspelling();
+ void learn_context_menu_misspelling();
+ String describe_spelling_menu_for_testing() const;
+
+ Vector<NonnullRefPtr<Action>> m_spelling_guess_actions;
+ RefPtr<Action> m_no_spelling_guesses_action;
+ RefPtr<Action> m_ignore_spelling_action;
+ RefPtr<Action> m_learn_spelling_action;
+ Optional<Utf16String> m_context_menu_misspelled_word;
+ Vector<Utf16String> m_spelling_guesses;
+ RefPtr<WebContentPage> m_spelling_context_menu_page;
+
HashMap<GeolocationRequestKey, Core::GeolocationProvider::RequestId> m_geolocation_position_request_ids;
HashMap<GeolocationRequestKey, Core::GeolocationProvider::WatchId> m_geolocation_watch_ids;
diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cpp
index b4313490431..49cad869cdb 100644
--- a/Libraries/LibWebView/WebContentPage.cpp
+++ b/Libraries/LibWebView/WebContentPage.cpp
@@ -2310,10 +2310,20 @@ void WebContentPage::did_change_title(Utf16String title)
}
}
-void WebContentPage::did_request_context_menu(Web::HTML::CrossProcessId local_root_id, Gfx::IntPoint content_position, Web::ContextMenuForInputEventsTarget for_input_events_target)
+void WebContentPage::did_request_context_menu(Web::HTML::CrossProcessId local_root_id, Gfx::IntPoint content_position, Web::ContextMenuForInputEventsTarget for_input_events_target, Optional<Utf16String> misspelled_word)
{
if (auto target = view_position(local_root_id, content_position); target.has_value())
- target->view.did_request_page_context_menu({}, target->position, for_input_events_target);
+ target->view.did_request_page_context_menu({}, *this, target->position, for_input_events_target, move(misspelled_word));
+}
+
+void WebContentPage::did_request_spelling_menu_action_for_testing(Web::SpellingMenuActionForTesting action, u32 guess_index)
+{
+ // NB: This activates the tab's own menu actions, so only automation may ask for it.
+ if (!WebContentClient::renderers_may_synthesize_input()) {
+ client().did_misbehave("did_request_spelling_menu_action_for_testing"sv, "not driven by WebDriver or a test"sv);
+ return;
+ }
+ view().activate_spelling_menu_action_for_testing({}, *this, action, guess_index);
}
void WebContentPage::did_request_link_context_menu(Web::HTML::CrossProcessId local_root_id, Gfx::IntPoint content_position, Web::HTML::PreparedNavigationDescriptor navigation, ByteString, unsigned)
diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.h
index 29ff613a4d8..597fedd6c18 100644
--- a/Libraries/LibWebView/WebContentPage.h
+++ b/Libraries/LibWebView/WebContentPage.h
@@ -264,6 +264,7 @@ private:
virtual void did_set_session_history_entry_document_state_reload_pending(Web::HTML::CrossProcessId navigable_id, Utf16String navigation_api_key, bool reload_pending) override;
virtual void did_change_focused_navigable(Web::HTML::CrossProcessId navigable_id) override;
virtual void did_request_key_event_for_testing(Web::KeyEvent event) override;
+ virtual void did_request_spelling_menu_action_for_testing(Web::SpellingMenuActionForTesting action, u32 guess_index) override;
virtual void request_history_operation(Web::HTML::CrossProcessId operation_id, Web::HistoryOperationParameters parameters) override;
virtual void revoke_history_operation(Web::HTML::CrossProcessId operation_id) override;
virtual void beforeunload_check_result(Web::HTML::CrossProcessId operation_id, Web::HTML::CheckIfUnloadingIsCanceledResult result, Web::HTML::UnloadPromptShown unload_prompt_shown) override;
@@ -312,7 +313,7 @@ private:
virtual void did_fail_download(u64 download_id, String error) override;
virtual void did_finish_loading(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id) override;
virtual void did_change_title(Utf16String title) override;
- virtual void did_request_context_menu(Web::HTML::CrossProcessId local_root_id, Gfx::IntPoint content_position, Web::ContextMenuForInputEventsTarget for_input_events_target) override;
+ virtual void did_request_context_menu(Web::HTML::CrossProcessId local_root_id, Gfx::IntPoint content_position, Web::ContextMenuForInputEventsTarget for_input_events_target, Optional<Utf16String> misspelled_word) override;
virtual void did_request_link_context_menu(Web::HTML::CrossProcessId local_root_id, Gfx::IntPoint content_position, Web::HTML::PreparedNavigationDescriptor navigation, ByteString, unsigned) override;
virtual void did_request_image_context_menu(Web::HTML::CrossProcessId local_root_id, Gfx::IntPoint content_position, Web::HTML::PreparedNavigationDescriptor navigation, ByteString, unsigned, Optional<Gfx::ShareableBitmap> bitmap) override;
virtual void did_request_media_context_menu(Web::HTML::CrossProcessId local_root_id, Gfx::IntPoint content_position, ByteString, unsigned, Web::MediaContextMenu menu, Web::HTML::PreparedNavigationDescriptor navigation) override;
diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cpp
index 64197bd34de..1d84df85b53 100644
--- a/Services/WebContent/ConnectionFromClient.cpp
+++ b/Services/WebContent/ConnectionFromClient.cpp
@@ -3350,6 +3350,30 @@ void ConnectionFromClient::did_check_spelling(Web::PageId page_id, u64 request_i
page->page().did_check_spelling(request_id, move(errors));
}
+void ConnectionFromClient::replace_context_menu_misspelling(Web::PageId page_id, Utf16String replacement)
+{
+ if (auto page = this->page(page_id); page.has_value())
+ page->page().replace_context_menu_misspelling(replacement);
+}
+
+void ConnectionFromClient::accept_spelling_word(Web::PageId page_id, Utf16String word)
+{
+ if (auto page = this->page(page_id); page.has_value())
+ page->page().accept_spelling_word(word);
+}
+
+void ConnectionFromClient::forget_accepted_spelling_words(Web::PageId page_id)
+{
+ if (auto page = this->page(page_id); page.has_value())
+ page->page().forget_accepted_spelling_words();
+}
+
+void ConnectionFromClient::did_complete_spelling_menu_action_for_testing(Web::PageId page_id, String menu)
+{
+ if (auto page = this->page(page_id); page.has_value())
+ page->page().did_complete_spelling_menu_action_for_testing(move(menu));
+}
+
void ConnectionFromClient::did_delete_all_cookies(Web::PageId page_id, u64 request_id)
{
if (auto page = this->page(page_id); page.has_value())
diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.h
index 86ddbff240b..97f563bbe46 100644
--- a/Services/WebContent/ConnectionFromClient.h
+++ b/Services/WebContent/ConnectionFromClient.h
@@ -272,6 +272,10 @@ private:
virtual void retrieved_clipboard_entries(Web::PageId page_id, u64 request_id, Vector<Web::Clipboard::SystemClipboardItem>) override;
virtual void did_check_spelling(Web::PageId page_id, u64 request_id, Vector<Web::SpellingError> errors) override;
+ virtual void replace_context_menu_misspelling(Web::PageId page_id, Utf16String replacement) override;
+ virtual void accept_spelling_word(Web::PageId page_id, Utf16String word) override;
+ virtual void forget_accepted_spelling_words(Web::PageId page_id) override;
+ virtual void did_complete_spelling_menu_action_for_testing(Web::PageId page_id, String menu) override;
virtual void toggle_media_play_state(Web::PageId page_id) override;
virtual void toggle_media_mute_state(Web::PageId page_id) override;
diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cpp
index 6011a380710..7b10084942a 100644
--- a/Services/WebContent/PageClient.cpp
+++ b/Services/WebContent/PageClient.cpp
@@ -1137,9 +1137,14 @@ void PageClient::page_did_set_device_pixel_ratio_for_testing(double ratio)
}));
}
-void PageClient::page_did_request_context_menu(Web::HTML::CrossProcessId local_root_id, Web::CSSPixelPoint content_position, Web::ContextMenuForInputEventsTarget for_input_events_target)
+void PageClient::page_did_request_context_menu(Web::HTML::CrossProcessId local_root_id, Web::CSSPixelPoint content_position, Web::ContextMenuForInputEventsTarget for_input_events_target, Optional<Utf16String> misspelled_word)
{
- client().async_did_request_context_menu(m_id, local_root_id, page().css_to_device_point(content_position).to_type<int>(), for_input_events_target);
+ client().async_did_request_context_menu(m_id, local_root_id, page().css_to_device_point(content_position).to_type<int>(), for_input_events_target, move(misspelled_word));
+}
+
+void PageClient::page_did_request_spelling_menu_action_for_testing(Web::SpellingMenuActionForTesting action, u32 guess_index)
+{
+ client().async_did_request_spelling_menu_action_for_testing(m_id, action, guess_index);
}
void PageClient::page_did_request_link_context_menu(Web::HTML::CrossProcessId local_root_id, Web::CSSPixelPoint content_position, Web::HTML::PreparedNavigationDescriptor navigation, ByteString const& target, unsigned modifiers)
diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.h
index 09a90422c9e..93ee2580807 100644
--- a/Services/WebContent/PageClient.h
+++ b/Services/WebContent/PageClient.h
@@ -243,7 +243,8 @@ private:
virtual void page_did_click_link(Web::HTML::PreparedNavigationDescriptor, ByteString const& target, unsigned modifiers) override;
virtual void page_did_middle_click_link(Web::HTML::PreparedNavigationDescriptor, ByteString const& target, unsigned modifiers) override;
virtual void page_did_request_external_url(URL::URL const&, URL::Origin const& initiator_origin, bool has_transient_activation) override;
- virtual void page_did_request_context_menu(Web::HTML::CrossProcessId local_root_id, Web::CSSPixelPoint, Web::ContextMenuForInputEventsTarget) override;
+ virtual void page_did_request_context_menu(Web::HTML::CrossProcessId local_root_id, Web::CSSPixelPoint, Web::ContextMenuForInputEventsTarget, Optional<Utf16String> misspelled_word) override;
+ virtual void page_did_request_spelling_menu_action_for_testing(Web::SpellingMenuActionForTesting, u32 guess_index) override;
virtual void page_did_request_link_context_menu(Web::HTML::CrossProcessId local_root_id, Web::CSSPixelPoint, Web::HTML::PreparedNavigationDescriptor, ByteString const& target, unsigned modifiers) override;
virtual void page_did_request_image_context_menu(Web::HTML::CrossProcessId local_root_id, Web::CSSPixelPoint, Web::HTML::PreparedNavigationDescriptor, ByteString const& target, unsigned modifiers, Optional<Gfx::Bitmap const*>) override;
virtual void page_did_request_media_context_menu(Web::HTML::CrossProcessId local_root_id, Web::CSSPixelPoint, ByteString const& target, unsigned modifiers, Web::Page::MediaContextMenu const&, Web::HTML::PreparedNavigationDescriptor) override;
diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipc
index 65ea2d7d729..bd1c30828d5 100644
--- a/Services/WebContent/WebContentClient.ipc
+++ b/Services/WebContent/WebContentClient.ipc
@@ -123,7 +123,7 @@ endpoint WebContentClient routed by Web::PageId page_id
did_click_link(Web::PageId page_id, Web::HTML::PreparedNavigationDescriptor navigation, ByteString target, unsigned modifiers) =|
did_middle_click_link(Web::PageId page_id, Web::HTML::PreparedNavigationDescriptor navigation, ByteString target, unsigned modifiers) =|
did_request_external_url(Web::PageId page_id, URL::URL url, URL::Origin initiator_origin, bool has_transient_activation) =|
- did_request_context_menu(Web::PageId page_id, Web::HTML::CrossProcessId local_root_id, Gfx::IntPoint content_position, Web::ContextMenuForInputEventsTarget for_input_events_target) =|
+ did_request_context_menu(Web::PageId page_id, Web::HTML::CrossProcessId local_root_id, Gfx::IntPoint content_position, Web::ContextMenuForInputEventsTarget for_input_events_target, Optional<Utf16String> misspelled_word) =|
did_request_link_context_menu(Web::PageId page_id, Web::HTML::CrossProcessId local_root_id, Gfx::IntPoint content_position, Web::HTML::PreparedNavigationDescriptor navigation, ByteString target, unsigned modifiers) =|
did_request_image_context_menu(Web::PageId page_id, Web::HTML::CrossProcessId local_root_id, Gfx::IntPoint content_position, Web::HTML::PreparedNavigationDescriptor navigation, ByteString target, unsigned modifiers, Optional<Gfx::ShareableBitmap> bitmap) =|
did_request_media_context_menu(Web::PageId page_id, Web::HTML::CrossProcessId local_root_id, Gfx::IntPoint content_position, ByteString target, unsigned modifiers, Web::MediaContextMenu menu, Web::HTML::PreparedNavigationDescriptor navigation) =|
@@ -244,6 +244,7 @@ endpoint WebContentClient routed by Web::PageId page_id
did_request_set_system_focus(Web::PageId page_id, bool has_system_focus) =|
did_change_focused_navigable(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id) =|
did_request_key_event_for_testing(Web::PageId page_id, Web::KeyEvent event) =|
+ did_request_spelling_menu_action_for_testing(Web::PageId page_id, Web::SpellingMenuActionForTesting action, u32 guess_index) =|
did_request_webdriver_mouse_event(Web::PageId page_id, u64 request_id, Web::HTML::CrossProcessId local_root_id, Web::MouseEvent event) =|
did_request_set_system_visibility_state(Web::PageId page_id, Web::HTML::VisibilityState visibility_state) =|
request_history_operation(Web::PageId page_id, Web::HTML::CrossProcessId operation_id, Web::HistoryOperationParameters parameters) =|
diff --git a/Services/WebContent/WebContentServer.ipc b/Services/WebContent/WebContentServer.ipc
index 02ce5d49df9..98feceb5d30 100644
--- a/Services/WebContent/WebContentServer.ipc
+++ b/Services/WebContent/WebContentServer.ipc
@@ -278,6 +278,10 @@ endpoint WebContentServer routed by Web::PageId page_id
retrieved_clipboard_entries(Web::PageId page_id, u64 request_id, Vector<Web::Clipboard::SystemClipboardItem> items) =|
did_check_spelling(Web::PageId page_id, u64 request_id, Vector<Web::SpellingError> errors) =|
+ replace_context_menu_misspelling(Web::PageId page_id, Utf16String replacement) =|
+ accept_spelling_word(Web::PageId page_id, Utf16String word) =|
+ forget_accepted_spelling_words(Web::PageId page_id) =|
+ did_complete_spelling_menu_action_for_testing(Web::PageId page_id, String menu) =|
toggle_media_play_state(Web::PageId page_id) =|
toggle_media_mute_state(Web::PageId page_id) =|
diff --git a/Tests/LibWeb/Text/expected/Editing/spellcheck-accepted-word-while-checking.txt b/Tests/LibWeb/Text/expected/Editing/spellcheck-accepted-word-while-checking.txt
new file mode 100644
index 00000000000..27005c4979e
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Editing/spellcheck-accepted-word-while-checking.txt
@@ -0,0 +1,6 @@
+area flagged: 4-8
+menu on wrod: word | rod | wrong | wood | ford | Ignore Spelling | Learn Spelling
+area flagged after ignore: (none)
+editable flagged: 6-15
+menu on lernagain: No Guesses Found | Ignore Spelling | Learn Spelling
+editable flagged after learn: (none)
diff --git a/Tests/LibWeb/Text/expected/Editing/spellcheck-context-menu-focus-listener-edits.txt b/Tests/LibWeb/Text/expected/Editing/spellcheck-context-menu-focus-listener-edits.txt
new file mode 100644
index 00000000000..0f123501281
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Editing/spellcheck-context-menu-focus-listener-edits.txt
@@ -0,0 +1,10 @@
+area flagged: 4-8
+editable flagged: 4-11
+away flagged: 4-8
+menu after a focus listener shortened the text: (no spelling items)
+value: x
+editable flagged after the insert: 6-13
+menu after a focus listener moved the misspelling: (no spelling items)
+text: zzone speling two
+menu after a focus listener moved focus away: (no spelling items)
+focused: other
diff --git a/Tests/LibWeb/Text/expected/Editing/spellcheck-context-menu-unfocused.txt b/Tests/LibWeb/Text/expected/Editing/spellcheck-context-menu-unfocused.txt
new file mode 100644
index 00000000000..8d576fad548
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Editing/spellcheck-context-menu-unfocused.txt
@@ -0,0 +1,3 @@
+flagged: 4-8
+menu: text | teat | tet | Ignore Spelling | Learn Spelling
+value: one text two
diff --git a/Tests/LibWeb/Text/expected/Editing/spellcheck-context-menu.txt b/Tests/LibWeb/Text/expected/Editing/spellcheck-context-menu.txt
new file mode 100644
index 00000000000..24eb55dcc91
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Editing/spellcheck-context-menu.txt
@@ -0,0 +1,25 @@
+area flagged: 4-8 13-17 18-23
+selection: 4-8
+area beforeinput insertReplacementText data=text
+area input insertReplacementText data=text
+menu on txet: text | teat | tet | Ignore Spelling | Learn Spelling
+value: one text two wrod quikc
+area flagged: 13-17 18-23
+menu on wrod: word | rod | wrong | wood | ford | Ignore Spelling | Learn Spelling
+menu on quikc: No Guesses Found | Ignore Spelling | Learn Spelling
+area flagged after ignore: 13-17
+menu on one: (no spelling items)
+area flagged after a new check: 13-17
+editable flagged: 0-7 8-16
+menu on lernword: learnword | Ignore Spelling | Learn Spelling
+editable flagged after learn: 0-7
+menu on speling: spelling | spieling | Ignore Spelling | Learn Spelling
+canceled replacement: speling lernword
+same menu again: spelling | spieling | Ignore Spelling | Learn Spelling
+after a second activation: speling lernword
+editable input insertReplacementText data=null
+menu on speling: spelling | spieling | Ignore Spelling | Learn Spelling
+replaced: spelling lernword
+editable input historyUndo data=null
+undone: speling lernword
+editable flagged after a new check: 0-7
diff --git a/Tests/LibWeb/Text/input/Editing/spellcheck-accepted-word-while-checking.html b/Tests/LibWeb/Text/input/Editing/spellcheck-accepted-word-while-checking.html
new file mode 100644
index 00000000000..ff2fe244916
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Editing/spellcheck-accepted-word-while-checking.html
@@ -0,0 +1,60 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ body { margin: 0; font: 20px/30px monospace; }
+ textarea { display: block; font: inherit; width: 600px; height: 30px; padding: 0; border: 0; resize: none; }
+ div { width: 600px; }
+</style>
+<textarea id="area">one wrod two</textarea>
+<div id="editable" contenteditable>three lernagain four</div>
+<span id="probe">xxxxxxxxxx</span>
+<script>
+ promiseTest(async () => {
+ const probe = document.getElementById("probe");
+ const characterWidth = probe.getBoundingClientRect().width / 10;
+ probe.remove();
+ const clickAt = (x, y, button = 0) => {
+ internals.mouseDown(x, y, 1, button);
+ internals.mouseUp(x, y, button);
+ };
+ const pointInTextControl = (element, index) => {
+ const rect = element.getBoundingClientRect();
+ return [rect.left + (index + 0.5) * characterWidth, rect.top + 15];
+ };
+ const pointInText = (text, index) => {
+ const range = document.createRange();
+ range.setStart(text, index);
+ range.setEnd(text, index + 1);
+ const rect = range.getBoundingClientRect();
+ return [rect.left + rect.width / 2, rect.top + rect.height / 2];
+ };
+ const leaveField = () => document.activeElement.blur();
+ const ranges = node => internals.spellingErrorRanges(node) || "(none)";
+
+ // Focus coming back to the field checks its text again, and the menu action follows before that check's
+ // answer, which was worked out while the word was still misspelled.
+ const area = document.getElementById("area");
+ clickAt(...pointInTextControl(area, 0));
+ await internals.spellCheckSettled();
+ println(`area flagged: ${ranges(area)}`);
+ clickAt(...pointInTextControl(area, 5), 2);
+ leaveField();
+ clickAt(...pointInTextControl(area, 0));
+ println(`menu on wrod: ${await internals.activateSpellingMenuItem("ignore")}`);
+ await internals.spellCheckSettled();
+ println(`area flagged after ignore: ${ranges(area)}`);
+
+ // Learn Spelling reaches every tab, so this word is one no other test uses.
+ const editable = document.getElementById("editable");
+ leaveField();
+ clickAt(...pointInText(editable.firstChild, 0));
+ await internals.spellCheckSettled();
+ println(`editable flagged: ${ranges(editable.firstChild)}`);
+ clickAt(...pointInText(editable.firstChild, 8), 2);
+ leaveField();
+ clickAt(...pointInText(editable.firstChild, 0));
+ println(`menu on lernagain: ${await internals.activateSpellingMenuItem("learn")}`);
+ await internals.spellCheckSettled();
+ println(`editable flagged after learn: ${ranges(editable.firstChild)}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Editing/spellcheck-context-menu-focus-listener-edits.html b/Tests/LibWeb/Text/input/Editing/spellcheck-context-menu-focus-listener-edits.html
new file mode 100644
index 00000000000..3967a5eac78
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Editing/spellcheck-context-menu-focus-listener-edits.html
@@ -0,0 +1,62 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ body { margin: 0; font: 20px/30px monospace; }
+ textarea { display: block; font: inherit; width: 600px; height: 30px; padding: 0; border: 0; resize: none; }
+ div { height: 30px; }
+</style>
+<textarea id="area">one txet two</textarea>
+<div id="editable" contenteditable>one speling two</div>
+<textarea id="away">one wrod two</textarea>
+<textarea id="other"></textarea>
+<span id="probe">xxxxxxxxxx</span>
+<script>
+ promiseTest(async () => {
+ const probe = document.getElementById("probe");
+ const characterWidth = probe.getBoundingClientRect().width / 10;
+ probe.remove();
+ const clickAt = (x, y, button = 0) => {
+ internals.mouseDown(x, y, 1, button);
+ internals.mouseUp(x, y, button);
+ };
+ const pointIn = (element, index) => {
+ const rect = element.getBoundingClientRect();
+ return [rect.left + (index + 0.5) * characterWidth, rect.top + 15];
+ };
+ const ranges = node => internals.spellingErrorRanges(node) || "(none)";
+
+ const area = document.getElementById("area");
+ const editable = document.getElementById("editable");
+ const away = document.getElementById("away");
+ const other = document.getElementById("other");
+ for (const element of [area, editable, away]) {
+ clickAt(...pointIn(element, 0));
+ await internals.spellCheckSettled();
+ }
+ println(`area flagged: ${ranges(area)}`);
+ println(`editable flagged: ${ranges(editable.firstChild)}`);
+ println(`away flagged: ${ranges(away)}`);
+
+ // A focus listener that shortens the text leaves the misspelling's offsets past its end.
+ clickAt(...pointIn(other, 0));
+ area.addEventListener("focus", () => { area.value = "x"; }, { once: true });
+ clickAt(...pointIn(area, 5), 2);
+ println(`menu after a focus listener shortened the text: ${await internals.activateSpellingMenuItem("none")}`);
+ println(`value: ${area.value}`);
+
+ // A focus listener that inserts text before the misspelling moves it away from the offsets the click found.
+ clickAt(...pointIn(other, 0));
+ editable.addEventListener("focus", () => { editable.firstChild.insertData(0, "zz"); }, { once: true });
+ clickAt(...pointIn(editable, 6), 2);
+ println(`editable flagged after the insert: ${ranges(editable.firstChild)}`);
+ println(`menu after a focus listener moved the misspelling: ${await internals.activateSpellingMenuItem("none")}`);
+ println(`text: ${editable.textContent}`);
+
+ // A focus listener that moves focus elsewhere leaves no field for a guess to replace the misspelling in.
+ clickAt(...pointIn(other, 0));
+ away.addEventListener("focus", () => { other.focus(); }, { once: true });
+ clickAt(...pointIn(away, 5), 2);
+ println(`menu after a focus listener moved focus away: ${await internals.activateSpellingMenuItem("none")}`);
+ println(`focused: ${document.activeElement.id}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Editing/spellcheck-context-menu-unfocused.html b/Tests/LibWeb/Text/input/Editing/spellcheck-context-menu-unfocused.html
new file mode 100644
index 00000000000..165c7935794
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Editing/spellcheck-context-menu-unfocused.html
@@ -0,0 +1,35 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ body { margin: 0; font: 20px/30px monospace; }
+ textarea { display: block; font: inherit; width: 600px; height: 30px; padding: 0; border: 0; resize: none; }
+</style>
+<textarea id="area">one txet two</textarea>
+<textarea id="other"></textarea>
+<span id="probe">xxxxxxxxxx</span>
+<script>
+ promiseTest(async () => {
+ const probe = document.getElementById("probe");
+ const characterWidth = probe.getBoundingClientRect().width / 10;
+ probe.remove();
+ const clickAt = (x, y, button = 0) => {
+ internals.mouseDown(x, y, 1, button);
+ internals.mouseUp(x, y, button);
+ };
+ const pointInTextControl = (element, index) => {
+ const rect = element.getBoundingClientRect();
+ return [rect.left + (index + 0.5) * characterWidth, rect.top + 15];
+ };
+
+ const area = document.getElementById("area");
+ clickAt(...pointInTextControl(area, 0));
+ await internals.spellCheckSettled();
+ println(`flagged: ${internals.spellingErrorRanges(area) || "(none)"}`);
+
+ // A guess picked for a misspelling in a field the user has left still replaces it.
+ clickAt(...pointInTextControl(document.getElementById("other"), 0));
+ clickAt(...pointInTextControl(area, 5), 2);
+ println(`menu: ${await internals.activateSpellingMenuItem("guess", 0)}`);
+ println(`value: ${area.value}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Editing/spellcheck-context-menu.html b/Tests/LibWeb/Text/input/Editing/spellcheck-context-menu.html
new file mode 100644
index 00000000000..c146e39e0e5
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Editing/spellcheck-context-menu.html
@@ -0,0 +1,90 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ body { margin: 0; font: 20px/30px monospace; }
+ textarea { display: block; font: inherit; width: 600px; height: 30px; padding: 0; border: 0; resize: none; }
+ div { width: 600px; }
+</style>
+<textarea id="area">one txet two wrod quikc</textarea>
+<div id="editable" contenteditable>speling lernword</div>
+<span id="probe">xxxxxxxxxx</span>
+<script>
+ promiseTest(async () => {
+ const probe = document.getElementById("probe");
+ const characterWidth = probe.getBoundingClientRect().width / 10;
+ probe.remove();
+ const clickAt = (x, y, button = 0) => {
+ internals.mouseDown(x, y, 1, button);
+ internals.mouseUp(x, y, button);
+ };
+ const pointInTextControl = (element, index) => {
+ const rect = element.getBoundingClientRect();
+ return [rect.left + (index + 0.5) * characterWidth, rect.top + 15];
+ };
+ const pointInText = (text, index) => {
+ const range = document.createRange();
+ range.setStart(text, index);
+ range.setEnd(text, index + 1);
+ const rect = range.getBoundingClientRect();
+ return [rect.left + rect.width / 2, rect.top + rect.height / 2];
+ };
+ // Checks run only on the user's behalf, so the user focuses fields with clicks.
+ const leaveField = () => document.activeElement.blur();
+ const ranges = node => internals.spellingErrorRanges(node) || "(none)";
+
+ const area = document.getElementById("area");
+ area.addEventListener("beforeinput", event => println(`area beforeinput ${event.inputType} data=${event.data}`));
+ area.addEventListener("input", event => println(`area input ${event.inputType} data=${event.data}`));
+ clickAt(...pointInTextControl(area, 0));
+ await internals.spellCheckSettled();
+ println(`area flagged: ${ranges(area)}`);
+
+ clickAt(...pointInTextControl(area, 5), 2);
+ println(`selection: ${area.selectionStart}-${area.selectionEnd}`);
+ println(`menu on txet: ${await internals.activateSpellingMenuItem("guess", 0)}`);
+ println(`value: ${area.value}`);
+ await internals.spellCheckSettled();
+ println(`area flagged: ${ranges(area)}`);
+
+ clickAt(...pointInTextControl(area, 14), 2);
+ println(`menu on wrod: ${await internals.activateSpellingMenuItem("none")}`);
+ clickAt(...pointInTextControl(area, 19), 2);
+ println(`menu on quikc: ${await internals.activateSpellingMenuItem("ignore")}`);
+ println(`area flagged after ignore: ${ranges(area)}`);
+ clickAt(...pointInTextControl(area, 1), 2);
+ println(`menu on one: ${await internals.activateSpellingMenuItem("none")}`);
+ leaveField();
+ clickAt(...pointInTextControl(area, 0));
+ await internals.spellCheckSettled();
+ println(`area flagged after a new check: ${ranges(area)}`);
+
+ const editable = document.getElementById("editable");
+ clickAt(...pointInText(editable.firstChild, 0));
+ await internals.spellCheckSettled();
+ println(`editable flagged: ${ranges(editable.firstChild)}`);
+ clickAt(...pointInText(editable.firstChild, 10), 2);
+ println(`menu on lernword: ${await internals.activateSpellingMenuItem("learn")}`);
+ println(`editable flagged after learn: ${ranges(editable.firstChild)}`);
+
+ const cancel = event => event.preventDefault();
+ editable.addEventListener("beforeinput", cancel);
+ clickAt(...pointInText(editable.firstChild, 2), 2);
+ println(`menu on speling: ${await internals.activateSpellingMenuItem("guess", 0)}`);
+ println(`canceled replacement: ${editable.textContent}`);
+ editable.removeEventListener("beforeinput", cancel);
+ // A menu takes one action: Activating the guess again, with no new right-click, replaces nothing.
+ println(`same menu again: ${await internals.activateSpellingMenuItem("guess", 0)}`);
+ println(`after a second activation: ${editable.textContent}`);
+
+ editable.addEventListener("input", event => println(`editable input ${event.inputType} data=${event.data}`));
+ clickAt(...pointInText(editable.firstChild, 2), 2);
+ println(`menu on speling: ${await internals.activateSpellingMenuItem("guess", 0)}`);
+ println(`replaced: ${editable.textContent}`);
+ document.execCommand("undo");
+ println(`undone: ${editable.textContent}`);
+ leaveField();
+ clickAt(...pointInText(editable.firstChild, 0));
+ await internals.spellCheckSettled();
+ println(`editable flagged after a new check: ${ranges(editable.firstChild)}`);
+ });
+</script>