Skip to content

Truly independent web browser

LibWeb+LibWebView: Translate pages through a platform translator

sideshowbarker2bb2e63c24d1
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index b4ddadcdef0..2a27f632280 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -889,6 +889,7 @@ set(SOURCES
SVG/SVGViewElement.cpp
SVG/TagNames.cpp
SVG/TimeEvent.cpp
+ Translation/DocumentTranslator.cpp
TrustedTypes/InjectionSink.cpp
TrustedTypes/RequireTrustedTypesForDirective.cpp
TrustedTypes/TrustedHTML.cpp
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index ed4d1168141..3fce33625d5 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -271,6 +271,7 @@
#include <LibWeb/SVG/SVGUseElement.h>
#include <LibWeb/SVG/TagNames.h>
#include <LibWeb/Selection/Selection.h>
+#include <LibWeb/Translation/DocumentTranslator.h>
#include <LibWeb/TrustedTypes/RequireTrustedTypesForDirective.h>
#include <LibWeb/TrustedTypes/TrustedTypePolicy.h>
#include <LibWeb/UIEvents/CompositionEvent.h>
@@ -1120,6 +1121,8 @@ void Document::visit_edges(Cell::Visitor& visitor)
m_spelling_markers->visit_edges(visitor);
if (m_spell_check_controller)
m_spell_check_controller->visit_edges(visitor);
+ if (m_document_translator)
+ m_document_translator->visit_edges(visitor);
if (m_writing_suggestion_controller)
m_writing_suggestion_controller->visit_edges(visitor);
@@ -1415,6 +1418,18 @@ Editing::SpellCheckController& Document::spell_check_controller()
return *m_spell_check_controller;
}
+Translation::DocumentTranslator& Document::document_translator()
+{
+ if (!m_document_translator)
+ m_document_translator = make<Translation::DocumentTranslator>(*this);
+ return *m_document_translator;
+}
+
+void Document::forget_document_translator()
+{
+ m_document_translator = nullptr;
+}
+
Editing::WritingSuggestionController& Document::writing_suggestion_controller()
{
if (!m_writing_suggestion_controller)
@@ -5522,6 +5537,7 @@ void Document::completely_finish_loading()
// document, reached through the UI process, which mirrors that the document is completely loaded.
if (container)
container->content_navigable_completely_finished_loading();
+ navigable->page().did_completely_load_document(*this);
navigable->page().client().page_did_completely_finish_loading(navigable->id(), *this);
}
diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.h
index dd1badb9c6a..118ee5812b5 100644
--- a/Libraries/LibWeb/DOM/Document.h
+++ b/Libraries/LibWeb/DOM/Document.h
@@ -373,6 +373,10 @@ public:
Editing::SpellingMarkers& spelling_markers();
Editing::SpellCheckController& spell_check_controller();
Editing::SpellCheckController* spell_check_controller_if_exists() { return m_spell_check_controller.ptr(); }
+
+ Translation::DocumentTranslator& document_translator();
+ Translation::DocumentTranslator* document_translator_if_exists() { return m_document_translator.ptr(); }
+ void forget_document_translator();
Editing::WritingSuggestionController& writing_suggestion_controller();
Editing::WritingSuggestionController* writing_suggestion_controller_if_exists() { return m_writing_suggestion_controller.ptr(); }
Editing::WritingSuggestionController const* writing_suggestion_controller_if_exists() const { return m_writing_suggestion_controller.ptr(); }
@@ -2351,6 +2355,7 @@ private:
Vector<GC::Ref<Range>> m_find_in_page_highlighted_matches;
OwnPtr<Editing::SpellingMarkers> m_spelling_markers;
OwnPtr<Editing::SpellCheckController> m_spell_check_controller;
+ OwnPtr<Translation::DocumentTranslator> m_document_translator;
OwnPtr<Editing::WritingSuggestionController> m_writing_suggestion_controller;
Vector<Utf16String> m_find_in_page_highlighted_match_texts;
u64 m_find_in_page_highlighted_matches_dom_tree_version { 0 };
diff --git a/Libraries/LibWeb/DOM/Node.cpp b/Libraries/LibWeb/DOM/Node.cpp
index 38b1d6f5c54..c0284c32d06 100644
--- a/Libraries/LibWeb/DOM/Node.cpp
+++ b/Libraries/LibWeb/DOM/Node.cpp
@@ -107,6 +107,7 @@
#include <LibWeb/Painting/BoxViews.h>
#include <LibWeb/SVG/SVGElement.h>
#include <LibWeb/SVG/SVGTitleElement.h>
+#include <LibWeb/Translation/DocumentTranslator.h>
#include <LibWeb/TrustedTypes/RequireTrustedTypesForDirective.h>
#include <LibWeb/TrustedTypes/TrustedTypePolicy.h>
#include <LibWeb/VisualLines.h>
@@ -4128,6 +4129,11 @@ void Node::queue_mutation_record(Utf16FlyString const& type, Optional<Utf16FlySt
page.client().page_did_change_accessibility_tree();
}
+ // A translated document translates the text the page adds or changes, which it learns of here, whether or not any
+ // MutationObserver is registered.
+ if (auto* translator = document.document_translator_if_exists())
+ translator->did_mutate(*this, type, attribute_name, old_value);
+
// OPTIMIZATION: Without an observer of this type in the document, interestedObservers stays empty.
if (!document.has_mutation_observers_of_type(type) && !page.listen_for_dom_mutations())
return;
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 104ff8e83ca..ebc9d27c788 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -507,6 +507,12 @@ using SlotAssignmentMode = Bindings::SlotAssignmentMode;
}
+namespace Web::Translation {
+
+class DocumentTranslator;
+
+}
+
namespace Web::Editing {
class EditCommand;
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cpp
index 512a766413b..e7348f7d260 100644
--- a/Libraries/LibWeb/Internals/Internals.cpp
+++ b/Libraries/LibWeb/Internals/Internals.cpp
@@ -3773,6 +3773,22 @@ GC::Ref<WebIDL::Promise> Internals::spell_check_settled()
return promise;
}
+void Internals::translate_page(Utf16String const& target_language)
+{
+ page().request_translation_for_testing(target_language.to_utf8_but_should_be_ported_to_utf16());
+}
+
+GC::Ref<WebIDL::Promise> Internals::translation_settled()
+{
+ auto& realm = window().principal_realm();
+ auto promise = WebIDL::create_promise_for(window());
+ page().when_translation_settled(GC::create_function(heap(), [&realm, promise] {
+ HTML::TemporaryExecutionContext execution_context { realm };
+ WebIDL::resolve_promise(promise);
+ }));
+ return promise;
+}
+
GC::Ref<WebIDL::Promise> Internals::request_writing_suggestion_for_testing(Utf16String const& text, WebIDL::UnsignedLong caret_offset)
{
auto& realm = window().principal_realm();
diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.h
index 031aa060d34..5f812f50774 100644
--- a/Libraries/LibWeb/Internals/Internals.h
+++ b/Libraries/LibWeb/Internals/Internals.h
@@ -93,6 +93,9 @@ public:
GC::Ref<WebIDL::Promise> check_spelling_for_testing(Utf16String const& text);
GC::Ref<WebIDL::Promise> spell_check_settled();
+ void translate_page(Utf16String const& target_language);
+ GC::Ref<WebIDL::Promise> translation_settled();
+
GC::Ref<WebIDL::Promise> request_writing_suggestion_for_testing(Utf16String const& text, WebIDL::UnsignedLong caret_offset);
Utf16String writing_suggestion();
GC::Ref<WebIDL::Promise> writing_suggestion_settled();
diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idl
index 39e61a8a887..b245ee45141 100644
--- a/Libraries/LibWeb/Internals/Internals.idl
+++ b/Libraries/LibWeb/Internals/Internals.idl
@@ -54,6 +54,10 @@ interface Internals {
Promise<DOMString> checkSpellingForTesting(DOMString text);
Promise<undefined> spellCheckSettled();
+ // Translation
+ undefined translatePage(DOMString targetLanguage);
+ Promise<undefined> translationSettled();
+
// Writing suggestions
Promise<DOMString> requestWritingSuggestionForTesting(DOMString text, unsigned long caretOffset);
DOMString writingSuggestion();
diff --git a/Libraries/LibWeb/Page/Page.cpp b/Libraries/LibWeb/Page/Page.cpp
index abbe51d3c19..f799cf40566 100644
--- a/Libraries/LibWeb/Page/Page.cpp
+++ b/Libraries/LibWeb/Page/Page.cpp
@@ -7,6 +7,7 @@
*/
#include <AK/SourceLocation.h>
+#include <AK/Utf16StringBuilder.h>
#include <LibGC/Heap.h>
#include <LibGC/HeapVector.h>
#include <LibGfx/Bitmap.h>
@@ -19,6 +20,7 @@
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Element.h>
#include <LibWeb/DOM/Range.h>
+#include <LibWeb/DOM/Text.h>
#include <LibWeb/Editing/SpellCheckController.h>
#include <LibWeb/Editing/SpellingMarkers.h>
#include <LibWeb/Editing/WritingSuggestionController.h>
@@ -40,6 +42,7 @@
#include <LibWeb/HTML/RemoteNavigable.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
+#include <LibWeb/HTML/TagNames.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HTML/WindowProxy.h>
#include <LibWeb/Layout/Viewport.h>
@@ -53,6 +56,7 @@
#include <LibWeb/PictureInPicture/PictureInPictureController.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/Selection/Selection.h>
+#include <LibWeb/Translation/DocumentTranslator.h>
#include <LibWeb/WebIDL/Promise.h>
#include <LibWebCommon/Clipboard/SystemClipboard.h>
#include <LibWebCommon/HTML/NavigationPopulationRequest.h>
@@ -153,6 +157,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_translation_settled_callbacks);
visitor.visit(m_pending_writing_suggestion_requests);
visitor.visit(m_writing_suggestions_settled_callbacks);
visitor.visit(m_writing_suggestion_requested_callbacks);
@@ -2632,4 +2637,149 @@ void PageClient::rebind_media_playback_manager(MediaClient::RemotePlaybackManage
VERIFY_NOT_REACHED();
}
+// The UI process asks for the language of the tab's document, which a page hosting it answers.
+TranslationLanguageSample Page::translation_language_sample()
+{
+ // Enough text to tell its language by, but no more.
+ static constexpr size_t MAXIMUM_SAMPLE_LENGTH = 4096;
+
+ TranslationLanguageSample sample;
+ for (auto const& navigable : hosted_navigables()) {
+ if (!navigable->is_top_level_traversable())
+ continue;
+ auto document = navigable->active_document();
+ if (!document)
+ break;
+ if (auto* document_element = document->document_element()) {
+ if (auto language = document_element->lang(); language.has_value() && !language->is_empty())
+ sample.declared_language = language->to_utf8_but_should_be_ported_to_utf16();
+ }
+ // NB: The sample is the text in the tree, rather than the rendered text, so taking it never lays the page out: It's
+ // taken from every page that loads, and a layout would change when the page itself sees its layout happen.
+ if (auto* body = document->body()) {
+ Utf16StringBuilder builder;
+ body->for_each_in_subtree([&](DOM::Node const& node) {
+ if (builder.length_in_code_units() >= MAXIMUM_SAMPLE_LENGTH)
+ return TraversalDecision::Break;
+ if (auto const* element = as_if<DOM::Element>(node)) {
+ if (first_is_one_of(element->local_name(), HTML::TagNames::script, HTML::TagNames::style, HTML::TagNames::template_, HTML::TagNames::noscript))
+ return TraversalDecision::SkipChildrenAndContinue;
+ return TraversalDecision::Continue;
+ }
+ if (auto const* text = as_if<DOM::Text>(node)) {
+ builder.append(text->data());
+ builder.append_code_point(' ');
+ }
+ return TraversalDecision::Continue;
+ });
+ auto text = builder.to_string();
+ if (text.length_in_code_units() > MAXIMUM_SAMPLE_LENGTH)
+ text = Utf16String::from_utf16(text.substring_view(0, MAXIMUM_SAMPLE_LENGTH));
+ sample.text = move(text);
+ }
+ break;
+ }
+ return sample;
+}
+
+void Page::start_translation(String source_language, String target_language)
+{
+ if (is_translating())
+ return;
+ m_translation_source_language = move(source_language);
+ m_translation_target_language = move(target_language);
+ // NB: A document still loading starts too: The text its parser adds later is translated as the page adds it.
+ for (auto const& navigable : hosted_navigables()) {
+ if (auto document = navigable->active_document())
+ document->document_translator().start(*m_translation_source_language, *m_translation_target_language);
+ }
+ notify_translation_progress();
+}
+
+// The UI process stops the translation as the tab's document changes, and as the user shows the original. So the page
+// forgets it, and the next document isn't translated unless the UI process asks again.
+void Page::stop_translation()
+{
+ m_translation_source_language.clear();
+ m_translation_target_language.clear();
+ m_translation_units_in_flight.clear();
+ for (auto const& navigable : hosted_navigables()) {
+ if (auto document = navigable->active_document())
+ document->forget_document_translator();
+ }
+}
+
+// A document that finishes loading in a translated page is translated too, e.g. an iframe's. The tab's own document is
+// translated only as the UI process asks, since the translation applies to the document it was asked for.
+void Page::did_completely_load_document(DOM::Document& document)
+{
+ auto navigable = document.navigable();
+ if (is_translating() && navigable && !navigable->is_top_level_traversable())
+ document.document_translator().start(*m_translation_source_language, *m_translation_target_language);
+}
+
+void Page::did_translate(TranslatedUnit unit)
+{
+ if (auto document = m_translation_units_in_flight.take(unit.id); document.has_value()) {
+ if (auto strong_document = document->ptr()) {
+ if (auto* translator = strong_document->document_translator_if_exists())
+ translator->did_translate(unit);
+ }
+ }
+ notify_translation_progress();
+}
+
+void Page::notify_translation_progress()
+{
+ // The translator takes one unit at a time, so only a few are sent ahead: The next one to send is picked when one
+ // comes back, which is when the page may have scrolled, or changed.
+ static constexpr size_t MAXIMUM_UNITS_IN_FLIGHT = 2;
+
+ while (is_translating() && m_translation_units_in_flight.size() < MAXIMUM_UNITS_IN_FLIGHT) {
+ GC::Ptr<DOM::Document> best_document;
+ Optional<Translation::DocumentTranslator::Candidate> best_candidate;
+ for (auto const& navigable : hosted_navigables()) {
+ auto document = navigable->active_document();
+ if (!document)
+ continue;
+ auto* translator = document->document_translator_if_exists();
+ if (!translator || !translator->is_started())
+ continue;
+ auto candidate = translator->next_candidate();
+ if (candidate.has_value() && (!best_candidate.has_value() || candidate->priority < best_candidate->priority)) {
+ best_candidate = candidate;
+ best_document = document;
+ }
+ }
+ if (!best_candidate.has_value())
+ break;
+ auto unit = best_document->document_translator().take_unit_for_translation(best_candidate->unit_id);
+ m_translation_units_in_flight.set(unit.id, *best_document);
+ client().page_did_request_translation(unit);
+ }
+
+ if (m_translation_settled_callbacks.is_empty() || !is_translating() || !m_translation_units_in_flight.is_empty())
+ return;
+ for (auto const& navigable : hosted_navigables()) {
+ if (auto document = navigable->active_document()) {
+ if (auto* translator = document->document_translator_if_exists(); translator && !translator->is_settled())
+ return;
+ }
+ }
+ GC::RootVector callbacks { exchange(m_translation_settled_callbacks, {}) };
+ for (auto& callback : callbacks)
+ callback->function()();
+}
+
+void Page::request_translation_for_testing(String const& target_language)
+{
+ client().page_did_request_page_translation_for_testing(target_language);
+}
+
+void Page::when_translation_settled(GC::Ref<GC::Function<void()>> callback)
+{
+ m_translation_settled_callbacks.append(callback);
+ notify_translation_progress();
+}
+
}
diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.h
index c5f381463a2..0acf7a674a3 100644
--- a/Libraries/LibWeb/Page/Page.h
+++ b/Libraries/LibWeb/Page/Page.h
@@ -97,6 +97,7 @@
#include <LibWebCommon/Page/QueuedInputEvent.h>
#include <LibWebCommon/Page/SpellingError.h>
#include <LibWebCommon/Page/TextEditingCommand.h>
+#include <LibWebCommon/Page/Translation.h>
#include <LibWebCommon/Page/ViewportIsFullscreen.h>
#include <LibWebCommon/Page/WritingSuggestion.h>
#include <LibWebCommon/Permissions/Permissions.h>
@@ -334,6 +335,23 @@ public:
void when_spell_checking_settled(GC::Ref<GC::Function<void()>>);
void notify_spell_check_progress();
+ // Translating the page's documents: The UI process decides the languages, and translates each unit of text the
+ // documents send it.
+ TranslationLanguageSample translation_language_sample();
+ void start_translation(String source_language, String target_language);
+ void stop_translation();
+ bool is_translating() const { return m_translation_target_language.has_value(); }
+ void did_translate(TranslatedUnit);
+ void did_completely_load_document(DOM::Document&);
+ u64 allocate_translation_unit_id() { return m_next_translation_unit_id++; }
+ // Sends the most urgent units of the page's documents, as many as may be in flight at once.
+ void notify_translation_progress();
+
+ // For tests: Translates the page as its translation menu would, and calls the callback once no document of the
+ // page has text waiting to be translated or in flight.
+ void request_translation_for_testing(String const& target_language);
+ void when_translation_settled(GC::Ref<GC::Function<void()>>);
+
using WritingSuggestionRequest = GC::Ref<GC::Function<void(Optional<WritingSuggestion>)>>;
bool writing_suggestions_available() const { return m_writing_suggestions_available; }
void set_writing_suggestions_available(bool available) { m_writing_suggestions_available = available; }
@@ -597,6 +615,12 @@ private:
u64 m_next_spell_check_request_id { 0 };
Vector<GC::Ref<GC::Function<void()>>> m_spell_checking_settled_callbacks;
+ Optional<String> m_translation_source_language;
+ Optional<String> m_translation_target_language;
+ u64 m_next_translation_unit_id { 1 };
+ HashMap<u64, GC::Weak<DOM::Document>> m_translation_units_in_flight;
+ Vector<GC::Ref<GC::Function<void()>>> m_translation_settled_callbacks;
+
bool m_writing_suggestions_available { false };
HashMap<u64, WritingSuggestionRequest> m_pending_writing_suggestion_requests;
u64 m_next_writing_suggestion_request_id { 0 };
@@ -944,6 +968,8 @@ public:
virtual void page_did_insert_clipboard_item(Clipboard::SystemClipboardItem const&, [[maybe_unused]] StringView presentation_style) { }
virtual void page_did_request_clipboard_entries([[maybe_unused]] u64 request_id) { }
virtual void page_did_request_spell_check([[maybe_unused]] u64 request_id, [[maybe_unused]] Utf16String const& text) { }
+ virtual void page_did_request_translation([[maybe_unused]] TranslationUnit const&) { }
+ virtual void page_did_request_page_translation_for_testing([[maybe_unused]] String const& target_language) { }
virtual void page_did_request_writing_suggestion([[maybe_unused]] u64 request_id, [[maybe_unused]] Utf16String const& text, [[maybe_unused]] u32 caret_offset) { }
virtual void page_did_request_primary_paste() { }
virtual void page_did_complete_paste_action() { }
diff --git a/Libraries/LibWeb/Translation/DocumentTranslator.cpp b/Libraries/LibWeb/Translation/DocumentTranslator.cpp
new file mode 100644
index 00000000000..890579891f7
--- /dev/null
+++ b/Libraries/LibWeb/Translation/DocumentTranslator.cpp
@@ -0,0 +1,1232 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/AnyOf.h>
+#include <AK/CharacterTypes.h>
+#include <AK/ScopeGuard.h>
+#include <AK/TemporaryChange.h>
+#include <AK/Utf16StringBuilder.h>
+#include <LibGC/ConservativeVector.h>
+#include <LibGC/RootHashMap.h>
+#include <LibGC/RootHashTable.h>
+#include <LibGC/RootVector.h>
+#include <LibUnicode/CharacterTypes.h>
+#include <LibWeb/ARIA/AttributeNames.h>
+#include <LibWeb/DOM/Document.h>
+#include <LibWeb/DOM/Element.h>
+#include <LibWeb/DOM/MutationType.h>
+#include <LibWeb/DOM/ShadowRoot.h>
+#include <LibWeb/DOM/Text.h>
+#include <LibWeb/Editing/Internal/Algorithms.h>
+#include <LibWeb/HTML/AttributeNames.h>
+#include <LibWeb/HTML/EventLoop/EventLoop.h>
+#include <LibWeb/HTML/HTMLInputElement.h>
+#include <LibWeb/HTML/HTMLOptionElement.h>
+#include <LibWeb/HTML/HTMLTitleElement.h>
+#include <LibWeb/HTML/LocalNavigable.h>
+#include <LibWeb/HTML/TagNames.h>
+#include <LibWeb/HTML/Window.h>
+#include <LibWeb/MathML/MathMLElement.h>
+#include <LibWeb/Namespace.h>
+#include <LibWeb/Page/Page.h>
+#include <LibWeb/SVG/SVGElement.h>
+#include <LibWeb/Translation/DocumentTranslator.h>
+
+namespace Web::Translation {
+
+// Lower is more urgent: The title first, then the text the user can see, then the rest of the rendered text, and the
+// text that isn't rendered last, so a menu shown later is still translated.
+enum class PriorityClass : u64 {
+ Title,
+ InViewport,
+ Rendered,
+ NotRendered,
+};
+
+static ReadonlySpan<Utf16FlyString const*> translated_attributes()
+{
+ static auto const names = to_array<Utf16FlyString const*>({
+ &HTML::AttributeNames::title,
+ &HTML::AttributeNames::alt,
+ &HTML::AttributeNames::placeholder,
+ &HTML::AttributeNames::value,
+ &ARIA::AttributeNames::aria_label,
+ &ARIA::AttributeNames::aria_description,
+ &ARIA::AttributeNames::aria_placeholder,
+ &ARIA::AttributeNames::aria_role_description,
+ &ARIA::AttributeNames::aria_value_text,
+ });
+ return names;
+}
+
+// Attributes whose change can decide whether, or how, an element's text is translated.
+static ReadonlySpan<Utf16FlyString const*> attributes_that_change_translation()
+{
+ static auto const names = to_array<Utf16FlyString const*>({
+ &HTML::AttributeNames::class_,
+ &HTML::AttributeNames::contenteditable,
+ &HTML::AttributeNames::hidden,
+ &HTML::AttributeNames::lang,
+ &HTML::AttributeNames::style,
+ &HTML::AttributeNames::translate,
+ });
+ return names;
+}
+
+static bool is_same_language(StringView a, StringView b)
+{
+ auto primary_subtag = [](StringView language) {
+ if (auto separator = language.find_any_of("-_"sv); separator.has_value())
+ return language.substring_view(0, *separator);
+ return language;
+ };
+ return primary_subtag(a).equals_ignoring_ascii_case(primary_subtag(b));
+}
+
+static bool is_html_element_named(DOM::Element const& element, Utf16FlyString const& name)
+{
+ return element.namespace_uri() == Namespace::HTML && element.local_name() == name;
+}
+
+static bool is_attribute_translated(DOM::Element const& element, Utf16FlyString const& name)
+{
+ if (name == HTML::AttributeNames::title)
+ return true;
+ if (name == ARIA::AttributeNames::aria_label || name == ARIA::AttributeNames::aria_description || name == ARIA::AttributeNames::aria_placeholder
+ || name == ARIA::AttributeNames::aria_role_description || name == ARIA::AttributeNames::aria_value_text)
+ return true;
+ if (name == HTML::AttributeNames::alt)
+ return is_html_element_named(element, HTML::TagNames::img) || is_html_element_named(element, HTML::TagNames::area) || is_html_element_named(element, HTML::TagNames::input);
+ if (name == HTML::AttributeNames::placeholder)
+ return is_html_element_named(element, HTML::TagNames::input) || is_html_element_named(element, HTML::TagNames::textarea);
+ if (name == HTML::AttributeNames::value) {
+ auto const* input = as_if<HTML::HTMLInputElement>(element);
+ if (!input)
+ return false;
+ switch (input->type_state()) {
+ case HTML::HTMLInputElement::TypeAttributeState::Button:
+ case HTML::HTMLInputElement::TypeAttributeState::ResetButton:
+ return true;
+ case HTML::HTMLInputElement::TypeAttributeState::SubmitButton:
+ // A named submit button's value is submitted with its form, which translating it would change.
+ return !input->has_attribute(HTML::AttributeNames::name);
+ default:
+ return false;
+ }
+ }
+ return false;
+}
+
+// Whether the text has anything to translate, rather than only spaces, digits, and punctuation.
+static bool has_translatable_text(Utf16View const& text)
+{
+ return any_of(text, [](u32 code_point) { return Unicode::code_point_has_letter_general_category(code_point); });
+}
+
+// Collapsible white space reads as one space, so it's sent as one.
+static Utf16String text_to_send(DOM::Text& text)
+{
+ auto const& data = text.data();
+ auto white_space_collapse = Editing::resolved_keyword(text, CSS::PropertyID::WhiteSpaceCollapse);
+ if (white_space_collapse.has_value() && *white_space_collapse != CSS::Keyword::Collapse)
+ return data;
+
+ Utf16StringBuilder builder;
+ bool last_was_space = false;
+ for (auto code_point : data.utf16_view()) {
+ if (is_ascii_space(code_point)) {
+ if (!last_was_space)
+ builder.append_code_point(' ');
+ last_was_space = true;
+ continue;
+ }
+ builder.append_code_point(code_point);
+ last_was_space = false;
+ }
+ return builder.to_string();
+}
+
+static Utf16String joined_text(Vector<Web::TranslationRun> const& runs)
+{
+ Utf16StringBuilder builder;
+ for (auto const& run : runs)
+ builder.append(run.text);
+ return builder.to_string();
+}
+
+// Content that's never shown as text, or that isn't text at all, e.g. a script or an image.
+static bool is_untranslatable_content(DOM::Element const& element)
+{
+ if (is<SVG::SVGElement>(element) || is<MathML::MathMLElement>(element))
+ return true;
+ static auto const tags = to_array<Utf16FlyString const*>({
+ &HTML::TagNames::audio,
+ &HTML::TagNames::base,
+ &HTML::TagNames::canvas,
+ &HTML::TagNames::datalist,
+ &HTML::TagNames::embed,
+ &HTML::TagNames::frame,
+ &HTML::TagNames::head,
+ &HTML::TagNames::iframe,
+ &HTML::TagNames::img,
+ &HTML::TagNames::input,
+ &HTML::TagNames::link,
+ &HTML::TagNames::meta,
+ &HTML::TagNames::meter,
+ &HTML::TagNames::noscript,
+ &HTML::TagNames::object,
+ &HTML::TagNames::param,
+ &HTML::TagNames::picture,
+ &HTML::TagNames::progress,
+ &HTML::TagNames::script,
+ &HTML::TagNames::select,
+ &HTML::TagNames::source,
+ &HTML::TagNames::style,
+ &HTML::TagNames::template_,
+ &HTML::TagNames::textarea,
+ &HTML::TagNames::title,
+ &HTML::TagNames::track,
+ &HTML::TagNames::video,
+ });
+ return element.namespace_uri() == Namespace::HTML && any_of(tags, [&](auto const* tag) { return element.local_name() == *tag; });
+}
+
+// An element with no style of its own, e.g. in a hidden subtree, is taken to be laid out the way it is by default.
+static bool is_block_by_default(DOM::Element const& element)
+{
+ static auto const tags = to_array<Utf16FlyString const*>({
+ &HTML::TagNames::address,
+ &HTML::TagNames::article,
+ &HTML::TagNames::aside,
+ &HTML::TagNames::blockquote,
+ &HTML::TagNames::body,
+ &HTML::TagNames::button,
+ &HTML::TagNames::caption,
+ &HTML::TagNames::dd,
+ &HTML::TagNames::details,
+ &HTML::TagNames::dialog,
+ &HTML::TagNames::div,
+ &HTML::TagNames::dl,
+ &HTML::TagNames::dt,
+ &HTML::TagNames::fieldset,
+ &HTML::TagNames::figcaption,
+ &HTML::TagNames::figure,
+ &HTML::TagNames::footer,
+ &HTML::TagNames::form,
+ &HTML::TagNames::h1,
+ &HTML::TagNames::h2,
+ &HTML::TagNames::h3,
+ &HTML::TagNames::h4,
+ &HTML::TagNames::h5,
+ &HTML::TagNames::h6,
+ &HTML::TagNames::header,
+ &HTML::TagNames::hgroup,
+ &HTML::TagNames::hr,
+ &HTML::TagNames::html,
+ &HTML::TagNames::legend,
+ &HTML::TagNames::li,
+ &HTML::TagNames::main,
+ &HTML::TagNames::menu,
+ &HTML::TagNames::nav,
+ &HTML::TagNames::ol,
+ &HTML::TagNames::p,
+ &HTML::TagNames::pre,
+ &HTML::TagNames::search,
+ &HTML::TagNames::section,
+ &HTML::TagNames::summary,
+ &HTML::TagNames::table,
+ &HTML::TagNames::tbody,
+ &HTML::TagNames::td,
+ &HTML::TagNames::tfoot,
+ &HTML::TagNames::th,
+ &HTML::TagNames::thead,
+ &HTML::TagNames::tr,
+ &HTML::TagNames::ul,
+ });
+ return element.namespace_uri() == Namespace::HTML && any_of(tags, [&](auto const* tag) { return element.local_name() == *tag; });
+}
+
+// Content that loses its state when it's taken out of the document: An iframe's document is discarded, a video pauses,
+// and a form control loses its focus. A paragraph rebuilt around it would take it out, so it ends the paragraph instead.
+static bool is_stateful_content(DOM::Element const& element)
+{
+ static auto const tags = to_array<Utf16FlyString const*>({
+ &HTML::TagNames::audio,
+ &HTML::TagNames::embed,
+ &HTML::TagNames::frame,
+ &HTML::TagNames::iframe,
+ &HTML::TagNames::input,
+ &HTML::TagNames::object,
+ &HTML::TagNames::select,
+ &HTML::TagNames::textarea,
+ &HTML::TagNames::video,
+ });
+ return element.namespace_uri() == Namespace::HTML && any_of(tags, [&](auto const* tag) { return element.local_name() == *tag; });
+}
+
+static bool is_hidden(DOM::Element const& element)
+{
+ auto display = Editing::resolved_display(const_cast<DOM::Element&>(element));
+ return !display.has_value() || display->is_none();
+}
+
+// The child of parent that node is in, if node is in parent at all.
+static GC::Ptr<DOM::Node> child_containing(DOM::Node& parent, DOM::Node& node)
+{
+ for (GC::Ptr<DOM::Node> current = node; current; current = current->parent()) {
+ if (current->parent() == &parent)
+ return current;
+ }
+ return nullptr;
+}
+
+DocumentTranslator::DocumentTranslator(DOM::Document& document)
+ : m_document(document)
+{
+}
+
+void DocumentTranslator::Unit::visit_edges(GC::Cell::Visitor& visitor)
+{
+ visitor.visit(container);
+ visitor.visit(range);
+ visitor.visit(nodes);
+ for (auto& piece : pieces) {
+ visitor.visit(piece.node);
+ visitor.visit(piece.owner);
+ }
+ visitor.visit(inline_elements);
+ for (auto& anchored_node : anchored_nodes) {
+ visitor.visit(anchored_node.node);
+ visitor.visit(anchored_node.owner);
+ }
+ visitor.visit(element);
+}
+
+void DocumentTranslator::visit_edges(GC::Cell::Visitor& visitor)
+{
+ visitor.visit(m_document);
+ for (auto& it : m_units)
+ it.value.visit_edges(visitor);
+}
+
+void DocumentTranslator::start(String source_language, String target_language)
+{
+ if (is_started())
+ return;
+ m_source_language = move(source_language);
+ m_target_language = move(target_language);
+
+ // The page's text is in the target language once it's translated, which decides e.g. its fonts and hyphenation.
+ if (auto* document_element = m_document->document_element()) {
+ TemporaryChange applying { m_is_applying, true };
+ document_element->set_attribute_value(HTML::AttributeNames::lang, Utf16String::from_utf8(m_target_language->bytes_as_string_view()));
+ }
+
+ scan_title();
+ if (auto* document_element = m_document->document_element())
+ scan(*document_element);
+ m_document->page().notify_translation_progress();
+}
+
+// Builds the paragraphs of one container. Each paragraph spans a run of the container's children that flow inline.
+class DocumentTranslator::ParagraphBuilder {
+public:
+ ParagraphBuilder(DocumentTranslator& translator, DOM::Node& container)
+ : m_translator(translator)
+ , m_container(container)
+ {
+ }
+
+ // Adds a child of the container that flows inline: text, an inline element, or a node anchored among them.
+ void add_child(DOM::Node& child, NodeRole role)
+ {
+ if (role == NodeRole::Anchored) {
+ // A node before the paragraph's first text isn't part of the paragraph.
+ if (!m_unit_id.has_value()) {
+ m_translator.scan_anchored(child);
+ return;
+ }
+ unit().range.append(child);
+ add_anchored(child);
+ ++m_trailing_anchored_count;
+ return;
+ }
+ if (!m_unit_id.has_value())
+ m_unit_id = m_translator.create_unit(UnitKind::Paragraph);
+ unit().range.append(child);
+ m_trailing_anchored_count = 0;
+ add_node(child, role);
+ }
+
+ void finish()
+ {
+ ScopeGuard reset = [&] {
+ m_unit_id.clear();
+ m_open_elements.clear();
+ m_last_token_inside.clear();
+ m_anchored_awaiting_text.clear();
+ m_trailing_anchored_count = 0;
+ };
+ if (!m_unit_id.has_value())
+ return;
+ auto& unit = this->unit();
+
+ // A paragraph ends at its last text: The nodes after it stay where they are.
+ for (; m_trailing_anchored_count > 0; --m_trailing_anchored_count) {
+ unit.range.take_last();
+ unit.nodes.take_last();
+ unit.anchored_nodes.take_last();
+ }
+
+ // A paragraph whose translation is on its way isn't sent again. If the page changed it, the translation is
+ // dropped as it comes back, and the paragraph is scanned again then.
+ auto has_new_text = any_of(unit.runs, [](auto const& run) { return !run.keep_as_is && has_translatable_text(run.text); });
+ if (!has_new_text || m_translator.is_paragraph_in_flight(unit.range)) {
+ m_translator.m_units.remove(*m_unit_id);
+ return;
+ }
+ for (auto& anchored_node : unit.anchored_nodes)
+ anchored_node.following_token = first_token_inside(unit, anchored_node.owner, anchored_node.following_token);
+ unit.container = m_container;
+ }
+
+private:
+ Unit& unit() { return m_translator.unit(*m_unit_id); }
+
+ Optional<size_t> current_owner_index() const
+ {
+ if (m_open_elements.is_empty())
+ return {};
+ return m_open_elements.last();
+ }
+
+ GC::Ptr<DOM::Element> current_owner()
+ {
+ if (auto index = current_owner_index(); index.has_value())
+ return unit().inline_elements[*index];
+ return nullptr;
+ }
+
+ void add_node(DOM::Node& node, NodeRole role)
+ {
+ unit().nodes.append(node);
+
+ if (auto* text = as_if<DOM::Text>(node)) {
+ // Text the translator wrote goes along for context, but isn't translated again.
+ auto is_translated = m_translator.is_translated_text(*text);
+ add_piece({ node, current_owner(), current_owner_index(), text->data(), is_translated }, text_to_send(*text));
+ return;
+ }
+
+ auto& element = as<DOM::Element>(node);
+ m_translator.scan_attributes(element);
+ if (role == NodeRole::Kept) {
+ add_piece({ node, current_owner(), current_owner_index(), {}, true }, element.text_content().value_or({}));
+ return;
+ }
+
+ auto& unit = this->unit();
+ unit.inline_elements.append(element);
+ unit.inline_element_parents.append(current_owner_index());
+ m_open_elements.append(unit.inline_elements.size() - 1);
+ for (auto* child = element.first_child(); child; child = child->next_sibling()) {
+ auto child_role = m_translator.role_of(*child);
+ if (child_role == NodeRole::Anchored)
+ add_anchored(*child);
+ else
+ add_node(*child, child_role);
+ }
+ m_open_elements.take_last();
+ }
+
+ void add_piece(Piece piece, Utf16String text)
+ {
+ auto& unit = this->unit();
+ auto starts_with_space = !text.is_empty() && is_ascii_space(text.code_unit_at(0));
+ for (auto index : m_anchored_awaiting_text)
+ unit.anchored_nodes[index].space_after = starts_with_space;
+ m_anchored_awaiting_text.clear();
+ auto keep_as_is = piece.keep_as_is;
+ unit.pieces.append(move(piece));
+ auto token = static_cast<u32>(unit.pieces.size());
+ unit.runs.append({ move(text), token, keep_as_is });
+ // The token is inside the container, and inside every inline element open around it.
+ m_last_token_inside.set(CONTAINER, token);
+ for (auto index : m_open_elements)
+ m_last_token_inside.set(index, token);
+ }
+
+ void add_anchored(DOM::Node& node)
+ {
+ m_translator.scan_anchored(node);
+ auto& unit = this->unit();
+ unit.nodes.append(node);
+ auto owner_index = current_owner_index();
+ auto preceding_token = m_last_token_inside.get(owner_index.value_or(CONTAINER)).value_or(0);
+ auto space_before = !unit.runs.is_empty() && !unit.runs.last().text.is_empty()
+ && is_ascii_space(unit.runs.last().text.code_unit_at(unit.runs.last().text.length_in_code_units() - 1));
+ // NB: The following token is found once every token is known; until then, this is the number of tokens so far.
+ unit.anchored_nodes.append({ node, current_owner(), owner_index, preceding_token, static_cast<u32>(unit.pieces.size()), space_before, false });
+ m_anchored_awaiting_text.append(unit.anchored_nodes.size() - 1);
+ }
+
+ // The first token after the given one whose text is inside the owner; 0 if there's none.
+ static u32 first_token_inside(Unit const& unit, GC::Ptr<DOM::Element> owner, u32 after_token)
+ {
+ for (size_t index = after_token; index < unit.pieces.size(); ++index) {
+ if (!owner || owner->is_ancestor_of(*unit.pieces[index].node))
+ return static_cast<u32>(index + 1);
+ }
+ return 0;
+ }
+
+ // The key of the container itself, among the keys of its inline elements, which are their indices.
+ static constexpr size_t CONTAINER = NumericLimits<size_t>::max();
+
+ DocumentTranslator& m_translator;
+ GC::Ref<DOM::Node> m_container;
+ Optional<u64> m_unit_id;
+ Vector<size_t> m_open_elements;
+ HashMap<size_t, u32> m_last_token_inside;
+ Vector<size_t> m_anchored_awaiting_text;
+ size_t m_trailing_anchored_count { 0 };
+};
+
+DocumentTranslator::NodeRole DocumentTranslator::role_of(DOM::Node const& node) const
+{
+ if (is<DOM::Text>(node))
+ return NodeRole::Text;
+ auto const* element = as_if<DOM::Element>(node);
+ if (element && (is_html_element_named(*element, HTML::TagNames::br) || is_stateful_content(*element)))
+ return NodeRole::Break;
+ if (!element || is_untranslatable_content(*element))
+ return NodeRole::Anchored;
+
+ auto flows_inline = is_inline(*element);
+ // An element with a shadow tree shows that tree's content, which has paragraphs of its own. And a custom element
+ // runs its callbacks again when it's taken out and put back, which may make it render its content again. So its
+ // text is translated where it is, rather than in the paragraph around it.
+ if (auto shadow_root = element->shadow_root(); (shadow_root && !shadow_root->is_user_agent_internal()) || element->is_custom())
+ flows_inline = false;
+ // So does an inline element that holds a block or a line break.
+ if (flows_inline && contains_paragraph_boundary(*element))
+ flows_inline = false;
+
+ if (is_excluded(*element))
+ return flows_inline ? NodeRole::Kept : NodeRole::Excluded;
+ if (!flows_inline)
+ return NodeRole::Container;
+
+ // An inline element that can't be seen, or that has no text, e.g. a link around an image, stays as it is.
+ if (is_hidden(*element))
+ return NodeRole::Anchored;
+ bool has_text = false;
+ element->for_each_in_subtree([&](DOM::Node const& descendant) {
+ if (auto const* descendant_element = as_if<DOM::Element>(descendant); descendant_element && is_untranslatable_content(*descendant_element))
+ return TraversalDecision::SkipChildrenAndContinue;
+ if (auto const* text = as_if<DOM::Text>(descendant); text && has_translatable_text(text->data())) {
+ has_text = true;
+ return TraversalDecision::Break;
+ }
+ return TraversalDecision::Continue;
+ });
+ return has_text ? NodeRole::Inline : NodeRole::Anchored;
+}
+
+bool DocumentTranslator::is_inline(DOM::Element const& element) const
+{
+ auto display = Editing::resolved_display(const_cast<DOM::Element&>(element));
+ if (!display.has_value() || display->is_none())
+ return !is_block_by_default(element);
+ return (display->is_inline_outside() && display->is_flow_inside()) || display->is_contents();
+}
+
+bool DocumentTranslator::contains_paragraph_boundary(DOM::Element const& element) const
+{
+ bool contains_boundary = false;
+ element.for_each_in_subtree([&](DOM::Node const& descendant) {
+ auto const* descendant_element = as_if<DOM::Element>(descendant);
+ if (!descendant_element)
+ return TraversalDecision::Continue;
+ if (is_stateful_content(*descendant_element)) {
+ contains_boundary = true;
+ return TraversalDecision::Break;
+ }
+ if (is_untranslatable_content(*descendant_element))
+ return TraversalDecision::SkipChildrenAndContinue;
+ // An element with a shadow tree shows that tree's content, which has paragraphs of its own.
+ auto shadow_root = descendant_element->shadow_root();
+ auto has_author_shadow_tree = shadow_root && !shadow_root->is_user_agent_internal();
+ if (is_html_element_named(*descendant_element, HTML::TagNames::br) || has_author_shadow_tree || descendant_element->is_custom() || !is_inline(*descendant_element)) {
+ contains_boundary = true;
+ return TraversalDecision::Break;
+ }
+ return TraversalDecision::Continue;
+ });
+ return contains_boundary;
+}
+
+bool DocumentTranslator::is_excluded(DOM::Element const& element) const
+{
+ if (element.translation_mode() == DOM::Element::TranslationMode::NoTranslate)
+ return true;
+ // Sites mark text that machine translation should leave alone with this class.
+ if (element.has_class(u"notranslate"sv))
+ return true;
+ // Computer code, keyboard input, sample output, and variable names read the same in any language.
+ for (auto const* tag : { &HTML::TagNames::code, &HTML::TagNames::kbd, &HTML::TagNames::samp, &HTML::TagNames::var }) {
+ if (is_html_element_named(element, *tag))
+ return true;
+ }
+ // Translating text the user edits would change what they wrote.
+ if (element.is_editable_or_editing_host())
+ return true;
+ // Text marked as being in another language isn't the page's language, so the translation can't translate it. The
+ // root's language isn't trusted for this, since the page's text may say otherwise.
+ if (&element != m_document->document_element()) {
+ if (auto language = element.get_attribute(HTML::AttributeNames::lang); language.has_value() && !language->is_empty()) {
+ auto language_utf8 = language->to_utf8_but_should_be_ported_to_utf16();
+ if (!is_same_language(language_utf8.bytes_as_string_view(), m_source_language->bytes_as_string_view()))
+ return true;
+ }
+ }
+ return false;
+}
+
+bool DocumentTranslator::is_translated_text(DOM::Text const& text) const
+{
+ return m_translated_text.contains(const_cast<DOM::Text&>(text));
+}
+
+void DocumentTranslator::scan(DOM::Node& root)
+{
+ scan_container(root);
+}
+
+void DocumentTranslator::scan_container(DOM::Node& container)
+{
+ if (auto* element = as_if<DOM::Element>(container)) {
+ scan_attributes(*element);
+ if (auto shadow_root = element->shadow_root(); shadow_root && !shadow_root->is_user_agent_internal())
+ scan_container(*shadow_root);
+ }
+
+ ParagraphBuilder builder { *this, container };
+ for (auto* child = container.first_child(); child; child = child->next_sibling()) {
+ auto role = role_of(*child);
+ switch (role) {
+ case NodeRole::Text:
+ case NodeRole::Inline:
+ case NodeRole::Kept:
+ case NodeRole::Anchored:
+ builder.add_child(*child, role);
+ break;
+ case NodeRole::Container:
+ builder.finish();
+ scan_container(*child);
+ break;
+ case NodeRole::Break:
+ builder.finish();
+ scan_anchored(*child);
+ break;
+ case NodeRole::Excluded:
+ builder.finish();
+ break;
+ }
+ }
+ builder.finish();
+}
+
+void DocumentTranslator::scan_anchored(DOM::Node& node)
+{
+ auto* element = as_if<DOM::Element>(node);
+ if (!element || is_excluded(*element))
+ return;
+ scan_attributes(*element);
+ if (is_html_element_named(*element, HTML::TagNames::select))
+ scan_options(*element);
+}
+
+void DocumentTranslator::scan_attributes(DOM::Element& element)
+{
+ if (is_excluded(element) && !element.is_editable_or_editing_host())
+ return;
+ for (auto const* name : translated_attributes()) {
+ if (!is_attribute_translated(element, *name))
+ continue;
+ auto value = element.get_attribute(*name);
+ if (!value.has_value() || !has_translatable_text(*value))
+ continue;
+ if (auto written = m_written_attributes.get(element); written.has_value()) {
+ if (auto written_value = written->get(*name); written_value.has_value() && *written_value == *value)
+ continue;
+ }
+ auto& unit = this->unit(create_unit(UnitKind::Attribute));
+ unit.element = element;
+ unit.attribute = *name;
+ unit.original_text = *value;
+ unit.runs.append({ *value, 1, false });
+ }
+}
+
+void DocumentTranslator::scan_options(DOM::Element& select)
+{
+ select.for_each_in_subtree_of_type<HTML::HTMLOptionElement>([&](HTML::HTMLOptionElement& option) {
+ if (is_excluded(option))
+ return TraversalDecision::Continue;
+ auto text = option.text();
+ if (!has_translatable_text(text) || m_written_text.get(option) == text)
+ return TraversalDecision::Continue;
+ auto& unit = this->unit(create_unit(UnitKind::OptionText));
+ unit.element = option;
+ unit.original_text = text;
+ unit.runs.append({ move(text), 1, false });
+ return TraversalDecision::Continue;
+ });
+}
+
+void DocumentTranslator::scan_title()
+{
+ auto title = m_document->title_element();
+ if (!title || is_excluded(*title))
+ return;
+ auto text = title->text_content().value_or({});
+ if (!has_translatable_text(text) || m_written_text.get(*title) == text)
+ return;
+ auto& unit = this->unit(create_unit(UnitKind::Title));
+ unit.element = title;
+ unit.original_text = text;
+ unit.runs.append({ move(text), 1, false });
+}
+
+u64 DocumentTranslator::create_unit(UnitKind kind)
+{
+ auto id = m_document->page().allocate_translation_unit_id();
+ m_units.ensure(id).kind = kind;
+ return id;
+}
+
+bool DocumentTranslator::is_paragraph_in_flight(Vector<GC::Ref<DOM::Node>> const& range) const
+{
+ for (auto const& [id, unit] : m_units) {
+ if (unit.in_flight && unit.kind == UnitKind::Paragraph && unit.range == range)
+ return true;
+ }
+ return false;
+}
+
+Optional<DocumentTranslator::Candidate> DocumentTranslator::next_candidate()
+{
+ // Units whose text has left the document are dropped.
+ m_units.remove_all_matching([](u64, Unit const& unit) {
+ if (unit.in_flight)
+ return false;
+ auto node = unit.kind == UnitKind::Paragraph ? GC::Ptr<DOM::Node> { unit.container } : GC::Ptr<DOM::Node> { unit.element };
+ return !node || !node->is_connected();
+ });
+
+ // OPTIMIZATION: A unit's priority comes from where it's laid out, which takes a layout to tell. So it's worked out
+ // once, and again only when the viewport moves, rather than for every unit each time one is sent.
+ auto navigable = m_document->navigable();
+ auto viewport_rect = navigable ? navigable->viewport_rect() : CSSPixelRect {};
+ auto viewport_moved = m_prioritized_viewport_rect != viewport_rect;
+ m_prioritized_viewport_rect = viewport_rect;
+
+ Optional<Candidate> best;
+ for (auto& [id, unit] : m_units) {
+ if (unit.in_flight)
+ continue;
+ if (viewport_moved || !unit.priority.has_value())
+ unit.priority = priority_of(unit);
+ // NB: Ties go to the earlier unit, which comes first in the document when both were found in the same scan.
+ Candidate candidate { id, *unit.priority };
+ if (!best.has_value() || candidate.priority < best->priority || (candidate.priority == best->priority && candidate.unit_id < best->unit_id))
+ best = candidate;
+ }
+ return best;
+}
+
+u64 DocumentTranslator::priority_of(Unit const& unit) const
+{
+ auto priority = [](PriorityClass priority_class, u64 distance) {
+ return (to_underlying(priority_class) << 32) | min(distance, static_cast<u64>(0xffffffff));
+ };
+ if (unit.kind == UnitKind::Title)
+ return priority(PriorityClass::Title, 0);
+
+ GC::Ptr<DOM::Element> element = unit.element;
+ if (unit.kind == UnitKind::Paragraph) {
+ if (auto* first_element = as_if<DOM::Element>(*unit.range.first()))
+ element = first_element;
+ else if (auto* shadow_root = as_if<DOM::ShadowRoot>(*unit.container))
+ element = shadow_root->host();
+ else
+ element = as_if<DOM::Element>(*unit.container);
+ }
+ auto navigable = m_document->navigable();
+ if (!element || !navigable)
+ return priority(PriorityClass::NotRendered, 0);
+
+ auto rect = element->get_bounding_client_rect();
+ if (rect.is_empty())
+ return priority(PriorityClass::NotRendered, 0);
+ auto viewport_size = navigable->viewport_rect().size();
+ CSSPixelRect viewport { {}, viewport_size };
+ if (rect.intersects(viewport))
+ return priority(PriorityClass::InViewport, 0);
+ // Text just below or above the viewport is likelier to be read next than text far from it.
+ auto distance = rect.bottom() < 0 ? -rect.bottom() : rect.top() - viewport_size.height();
+ return priority(PriorityClass::Rendered, max(distance, CSSPixels(0)).to_int());
+}
+
+Web::TranslationUnit DocumentTranslator::take_unit_for_translation(u64 unit_id)
+{
+ auto& unit = m_units.find(unit_id)->value;
+ unit.in_flight = true;
+ return { unit_id, unit.runs };
+}
+
+void DocumentTranslator::did_translate(Web::TranslatedUnit const& translated_unit)
+{
+ auto it = m_units.find(translated_unit.id);
+ if (it == m_units.end())
+ return;
+ // NB: The unit stays where visit_edges() reaches it until it's applied, since applying it detaches the nodes it holds
+ // before putting them back, and a collection in between would otherwise free them.
+ ScopeGuard forget_unit = [&] { m_units.remove(translated_unit.id); };
+ if (!translated_unit.runs.has_value())
+ return;
+ TemporaryChange applying { m_is_applying, true };
+ apply(it->value, *translated_unit.runs);
+}
+
+bool DocumentTranslator::is_in_excluded_element(DOM::Node const& node) const
+{
+ for (auto const* ancestor = &node; ancestor; ancestor = ancestor->parent()) {
+ if (auto const* element = as_if<DOM::Element>(*ancestor); element && is_excluded(*element))
+ return true;
+ }
+ return false;
+}
+
+void DocumentTranslator::apply(Unit& unit, Vector<Web::TranslationRun> const& runs)
+{
+ // Text the page made ineligible while its translation was on its way, e.g. by marking it not to be translated, is
+ // left as it is.
+ if (unit.kind == UnitKind::Paragraph) {
+ if (!unit.container || is_in_excluded_element(*unit.container) || any_of(unit.inline_elements, [&](auto const& element) { return is_excluded(*element); }))
+ return;
+ apply_paragraph(unit, runs);
+ return;
+ }
+
+ auto element = unit.element;
+ if (!element || !element->is_connected() || is_in_excluded_element(*element))
+ return;
+ if (unit.kind == UnitKind::Attribute && !is_attribute_translated(*element, *unit.attribute))
+ return;
+ auto translated_text = joined_text(runs);
+
+ switch (unit.kind) {
+ case UnitKind::Attribute: {
+ // An attribute the page changed since it was sent is left with the page's value.
+ if (element->get_attribute(*unit.attribute) != unit.original_text)
+ return;
+ element->set_attribute_value(*unit.attribute, translated_text);
+ m_written_attributes.ensure(*element).set(*unit.attribute, move(translated_text));
+ break;
+ }
+ case UnitKind::Title: {
+ if (element->text_content() != unit.original_text)
+ return;
+ element->string_replace_all(translated_text);
+ m_written_text.set(*element, move(translated_text));
+ break;
+ }
+ case UnitKind::OptionText: {
+ auto& option = as<HTML::HTMLOptionElement>(*element);
+ if (option.text() != unit.original_text)
+ return;
+ // An option without a value submits its text, so the text it had is kept as its value.
+ if (!option.has_attribute(HTML::AttributeNames::value))
+ option.set_attribute_value(HTML::AttributeNames::value, unit.original_text);
+ option.set_text(translated_text);
+ m_written_text.set(option, move(translated_text));
+ break;
+ }
+ case UnitKind::Paragraph:
+ VERIFY_NOT_REACHED();
+ }
+}
+
+bool DocumentTranslator::paragraph_is_unchanged(Unit const& unit) const
+{
+ auto& container = *unit.container;
+ for (size_t index = 0; index < unit.range.size(); ++index) {
+ auto& node = *unit.range[index];
+ if (node.parent() != &container)
+ return false;
+ if (index + 1 < unit.range.size() && node.next_sibling() != unit.range[index + 1].ptr())
+ return false;
+ }
+
+ // The nodes are the same, in the same order, and the pieces' text is what was sent.
+ size_t next_node = 0;
+ bool unchanged = true;
+ Function<void(DOM::Node const&)> visit = [&](DOM::Node const& node) {
+ if (!unchanged)
+ return;
+ if (next_node == unit.nodes.size() || unit.nodes[next_node].ptr() != &node) {
+ unchanged = false;
+ return;
+ }
+ ++next_node;
+ if (any_of(unit.inline_elements, [&](auto const& element) { return element.ptr() == &node; })) {
+ for (auto const* child = node.first_child(); child; child = child->next_sibling())
+ visit(*child);
+ }
+ };
+ for (auto const& node : unit.range)
+ visit(*node);
+ if (!unchanged || next_node != unit.nodes.size())
+ return false;
+
+ return all_of(unit.pieces, [](Piece const& piece) {
+ auto const* text = as_if<DOM::Text>(*piece.node);
+ return !text || text->data() == piece.original_text;
+ });
+}
+
+// Rebuilds a paragraph from its translation. Each run's text goes into the inline elements its token's text was in:
+// The first time an element is needed, it's the element itself, so it keeps its identity and its event listeners; an
+// element the translation needs a second time, apart from the first, is a shallow clone of it. The nodes that aren't
+// translated, e.g. images, are put back among the translated text next to the text they were next to.
+void DocumentTranslator::apply_paragraph(Unit& unit, Vector<Web::TranslationRun> const& runs)
+{
+ // A paragraph the page changed is scanned again, so this translation is dropped.
+ if (!paragraph_is_unchanged(unit)) {
+ m_dirty_nodes.append(*unit.container);
+ schedule_rescan();
+ return;
+ }
+ if (!any_of(runs, [](auto const& run) { return !run.keep_as_is && !run.text.is_empty(); }))
+ return;
+
+ auto& container = *unit.container;
+ auto& document = *m_document;
+
+ // The inline elements a piece's text is in, from the outermost to its owner, as indices among the inline elements.
+ auto chain_of = [&](Optional<size_t> owner_index) {
+ Vector<size_t> chain;
+ for (auto index = owner_index; index.has_value(); index = unit.inline_element_parents[*index])
+ chain.prepend(*index);
+ return chain;
+ };
+ auto piece_for = [&](u32 token) -> Piece* {
+ if (token == 0 || token > unit.pieces.size())
+ return nullptr;
+ return &unit.pieces[token - 1];
+ };
+
+ // The elements the translation puts text into. An element it puts none into stays as it was, text and all.
+ Vector<bool> is_used;
+ is_used.resize(unit.inline_elements.size());
+ for (auto const& run : runs) {
+ if (auto* piece = piece_for(run.token)) {
+ for (auto index : chain_of(piece->owner_index))
+ is_used[index] = true;
+ }
+ }
+ auto is_used_element = [&](Optional<size_t> index) { return !index.has_value() || is_used[*index]; };
+
+ // Take the paragraph apart.
+ GC::Ptr<DOM::Node> range_end = unit.range.last()->next_sibling();
+ for (auto const& node : unit.range)
+ node->remove();
+ for (size_t index = 0; index < unit.inline_elements.size(); ++index) {
+ if (!is_used[index])
+ continue;
+ while (auto* child = unit.inline_elements[index]->first_child())
+ child->remove();
+ }
+
+ // Put the translated text together.
+ struct OpenElement {
+ size_t index { 0 };
+ GC::Ref<DOM::Node> output;
+ };
+ GC::ConservativeVector<OpenElement> open_elements;
+ Vector<bool> is_opened;
+ is_opened.resize(unit.inline_elements.size());
+ Vector<bool> is_placed;
+ is_placed.resize(unit.pieces.size());
+ GC::RootHashMap<u32, GC::Ref<DOM::Node>> first_placed;
+ GC::RootHashMap<u32, GC::Ref<DOM::Node>> last_placed;
+
+ auto insert = [&](DOM::Node& node) {
+ if (open_elements.is_empty())
+ container.insert_before(node, range_end);
+ else
+ open_elements.last().output->insert_before(node, nullptr);
+ };
+
+ for (auto const& run : runs) {
+ auto* piece = piece_for(run.token);
+ // Text the translator leaves as it is goes back once, as it was.
+ if (piece && piece->keep_as_is && is_placed[run.token - 1])
+ continue;
+ auto chain = chain_of(piece ? piece->owner_index : Optional<size_t> {});
+
+ size_t common_depth = 0;
+ while (common_depth < open_elements.size() && common_depth < chain.size() && open_elements[common_depth].index == chain[common_depth])
+ ++common_depth;
+ open_elements.shrink(common_depth);
+ for (size_t depth = common_depth; depth < chain.size(); ++depth) {
+ auto index = chain[depth];
+ auto& original = *unit.inline_elements[index];
+ GC::Ptr<DOM::Node> output;
+ if (!is_opened[index]) {
+ is_opened[index] = true;
+ output = original;
+ } else if (auto clone = original.clone_node(nullptr, false); !clone.is_error()) {
+ output = clone.release_value();
+ } else {
+ break;
+ }
+ insert(*output);
+ open_elements.append({ index, *output });
+ }
+
+ GC::Ptr<DOM::Node> placed;
+ if (piece && (piece->keep_as_is || (is<DOM::Text>(*piece->node) && !is_placed[run.token - 1]))) {
+ placed = piece->node;
+ if (!piece->keep_as_is)
+ as<DOM::Text>(*placed).set_data(run.text);
+ is_placed[run.token - 1] = true;
+ } else {
+ placed = document.create_text_node(run.text);
+ }
+ insert(*placed);
+ if (auto* text = as_if<DOM::Text>(*placed); text && !(piece && piece->keep_as_is))
+ m_translated_text.set(*text);
+ first_placed.ensure(run.token, [&] { return GC::Ref { *placed }; });
+ last_placed.set(run.token, *placed);
+ }
+
+ // Put back the nodes that aren't translated: the anchored ones, the kept text the translation left out, and the
+ // inline elements it put no text into.
+ GC::ConservativeVector<AnchoredNode> nodes_to_place;
+ for (auto const& anchored_node : unit.anchored_nodes)
+ nodes_to_place.append(anchored_node);
+ for (size_t index = 0; index < unit.pieces.size(); ++index) {
+ auto const& piece = unit.pieces[index];
+ if (!piece.keep_as_is || is_placed[index])
+ continue;
+ auto token = static_cast<u32>(index + 1);
+ nodes_to_place.append({ piece.node, piece.owner, piece.owner_index, token > 1 ? token - 1 : 0, token < unit.pieces.size() ? token + 1 : 0 });
+ }
+ for (size_t element_index = 0; element_index < unit.inline_elements.size(); ++element_index) {
+ if (is_used[element_index])
+ continue;
+ auto& element = *unit.inline_elements[element_index];
+ auto parent_index = unit.inline_element_parents[element_index];
+ GC::Ptr<DOM::Element> parent = parent_index.has_value() ? unit.inline_elements[*parent_index].ptr() : nullptr;
+ u32 first_inside = 0;
+ u32 last_inside = 0;
+ for (size_t index = 0; index < unit.pieces.size(); ++index) {
+ if (element.is_ancestor_of(*unit.pieces[index].node)) {
+ if (first_inside == 0)
+ first_inside = index + 1;
+ last_inside = index + 1;
+ }
+ }
+ nodes_to_place.append({ element, parent, parent_index, first_inside > 1 ? first_inside - 1 : 0, last_inside < unit.pieces.size() ? last_inside + 1 : 0 });
+ }
+
+ GC::RootHashMap<GC::Ptr<DOM::Node>, GC::Ref<DOM::Node>> last_inserted_after;
+ auto is_space = [](Utf16View const& text, size_t index) { return is_ascii_space(text.code_unit_at(index)); };
+ auto restore_spaces = [&](AnchoredNode const& placed) {
+ auto& node = *placed.node;
+ auto* parent = node.parent();
+ if (!parent)
+ return;
+ if (placed.space_after) {
+ if (auto* next = as_if<DOM::Text>(node.next_sibling())) {
+ if (!next->data().is_empty() && !is_space(next->data(), 0))
+ next->set_data(Utf16String::formatted(" {}", next->data()));
+ } else if (node.next_sibling()) {
+ auto space = document.create_text_node(" "_utf16);
+ parent->insert_before(space, node.next_sibling());
+ m_translated_text.set(space);
+ }
+ }
+ if (placed.space_before) {
+ if (auto* previous = as_if<DOM::Text>(node.previous_sibling())) {
+ auto const& data = previous->data();
+ if (!data.is_empty() && !is_space(data, data.length_in_code_units() - 1))
+ previous->set_data(Utf16String::formatted("{} ", data));
+ } else if (node.previous_sibling()) {
+ auto space = document.create_text_node(" "_utf16);
+ parent->insert_before(space, node);
+ m_translated_text.set(space);
+ }
+ }
+ };
+
+ for (auto const& node_to_place : nodes_to_place) {
+ ScopeGuard restore_spaces_around_node = [&] { restore_spaces(node_to_place); };
+ auto owner = node_to_place.owner;
+ // A node in an element the translation didn't use is still in that element.
+ if (!is_used_element(node_to_place.owner_index))
+ continue;
+ if (owner && !owner->is_inclusive_ancestor_of(*node_to_place.node) && node_to_place.node->parent())
+ continue;
+ DOM::Node& parent = owner ? static_cast<DOM::Node&>(*owner) : container;
+
+ if (auto anchor = last_placed.get(node_to_place.preceding_token); node_to_place.preceding_token && anchor.has_value()) {
+ if (auto child = child_containing(parent, **anchor)) {
+ auto after = last_inserted_after.get(child).value_or(*child);
+ parent.insert_before(*node_to_place.node, after->next_sibling());
+ last_inserted_after.set(child, *node_to_place.node);
+ continue;
+ }
+ }
+ if (auto anchor = first_placed.get(node_to_place.following_token); node_to_place.following_token && anchor.has_value()) {
+ if (auto child = child_containing(parent, **anchor)) {
+ parent.insert_before(*node_to_place.node, child);
+ continue;
+ }
+ }
+ if (owner)
+ owner->insert_before(*node_to_place.node, nullptr);
+ else
+ container.insert_before(*node_to_place.node, range_end);
+ }
+}
+
+void DocumentTranslator::did_mutate(DOM::Node& target, Utf16FlyString const& type, Optional<Utf16FlyString> const& attribute_name, Optional<Utf16String> const& old_value)
+{
+ if (m_is_applying || !is_started())
+ return;
+
+ if (type == DOM::MutationType::attributes) {
+ auto matches = [&](auto const* name) { return attribute_name == *name; };
+ if (!any_of(translated_attributes(), matches) && !any_of(attributes_that_change_translation(), matches))
+ return;
+ auto* element = as_if<DOM::Element>(target);
+ if (!element)
+ return;
+ // OPTIMIZATION: Pages change the classes and styles of the root and the body all the time, e.g. as they scroll,
+ // and scanning the whole page again for each change would be costly. So a class change counts only
+ // if it marks text as not to be translated, or stops marking it, and a change of the root's or the
+ // body's style counts not at all.
+ if (attribute_name == HTML::AttributeNames::class_) {
+ auto had_notranslate = old_value.has_value() && any_of(old_value->utf16_view().split_view(' ', SplitBehavior::Nothing), [](auto const& name) { return name == u"notranslate"sv; });
+ if (had_notranslate == element->has_class(u"notranslate"sv))
+ return;
+ }
+ if ((attribute_name == HTML::AttributeNames::style || attribute_name == HTML::AttributeNames::hidden)
+ && (element == m_document->document_element() || element == m_document->body()))
+ return;
+ } else if (type == DOM::MutationType::characterData) {
+ // Text the page changed is the page's own again, and is translated again.
+ if (auto* text = as_if<DOM::Text>(target))
+ m_translated_text.remove(*text);
+ }
+ // NB: A change that only removes nodes leaves nothing new to translate. But it drops the translation still on its way
+ // for the paragraph it changed, so the paragraph is scanned again, to translate what's left of it.
+
+ m_dirty_nodes.append(target);
+ schedule_rescan();
+}
+
+void DocumentTranslator::schedule_rescan()
+{
+ if (m_rescan_scheduled)
+ return;
+ m_rescan_scheduled = true;
+ HTML::queue_global_task(HTML::Task::Source::DOMManipulation, HTML::relevant_global_object(m_document), GC::create_function(m_document->heap(), [document = GC::Weak<DOM::Document> { m_document }] {
+ auto strong_document = document.ptr();
+ if (!strong_document)
+ return;
+ if (auto* translator = strong_document->document_translator_if_exists()) {
+ translator->rescan();
+ strong_document->page().notify_translation_progress();
+ }
+ }));
+}
+
+void DocumentTranslator::rescan()
+{
+ m_rescan_scheduled = false;
+ auto dirty_nodes = move(m_dirty_nodes);
+
+ // Each changed node's container is scanned again, once, however many of its nodes changed.
+ GC::RootVector<GC::Ref<DOM::Node>> candidates;
+ GC::RootHashTable<GC::Ptr<DOM::Node>> candidate_set;
+ bool title_changed = false;
+ for (auto const& weak_node : dirty_nodes) {
+ auto node = weak_node.ptr();
+ if (!node || !node->is_connected() || &node->document() != m_document.ptr())
+ continue;
+ if (auto title = m_document->title_element(); title && title->is_inclusive_ancestor_of(*node)) {
+ title_changed = true;
+ continue;
+ }
+
+ // A node in an excluded element isn't translated, so nothing is scanned for it.
+ if (is_in_excluded_element(*node))
+ continue;
+
+ GC::Ptr<DOM::Node> container = node;
+ while (container) {
+ if (is<DOM::ShadowRoot>(*container) || container.ptr() == m_document->document_element())
+ break;
+ if (is<DOM::Element>(*container) && role_of(*container) == NodeRole::Container)
+ break;
+ container = container->parent();
+ }
+ if (!container)
+ continue;
+ if (candidate_set.set(container) == HashSetResult::InsertedNewEntry)
+ candidates.append(*container);
+ }
+
+ // A container inside another that's scanned again is scanned with it.
+ GC::RootVector<GC::Ref<DOM::Node>> containers;
+ for (auto const& candidate : candidates) {
+ bool is_inside_another = false;
+ for (auto ancestor = candidate->parent(); ancestor && !is_inside_another; ancestor = ancestor->parent())
+ is_inside_another = candidate_set.contains(ancestor);
+ if (!is_inside_another)
+ containers.append(candidate);
+ }
+
+ if (title_changed)
+ scan_title();
+ for (auto const& container : containers) {
+ forget_units_within(*container);
+ scan_container(*container);
+ }
+}
+
+void DocumentTranslator::forget_units_within(DOM::Node& container)
+{
+ // A unit in flight is checked when its translation comes back, so it's kept.
+ m_units.remove_all_matching([&](u64, Unit const& unit) {
+ if (unit.in_flight)
+ return false;
+ auto node = unit.kind == UnitKind::Paragraph ? GC::Ptr<DOM::Node> { unit.container } : GC::Ptr<DOM::Node> { unit.element };
+ return node && container.is_inclusive_ancestor_of(*node);
+ });
+}
+
+bool DocumentTranslator::is_settled() const
+{
+ return m_units.is_empty() && !m_rescan_scheduled;
+}
+
+}
diff --git a/Libraries/LibWeb/Translation/DocumentTranslator.h b/Libraries/LibWeb/Translation/DocumentTranslator.h
new file mode 100644
index 00000000000..89b68672b7c
--- /dev/null
+++ b/Libraries/LibWeb/Translation/DocumentTranslator.h
@@ -0,0 +1,186 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/HashMap.h>
+#include <AK/Noncopyable.h>
+#include <AK/Optional.h>
+#include <AK/String.h>
+#include <AK/Utf16FlyString.h>
+#include <AK/Utf16String.h>
+#include <AK/Vector.h>
+#include <LibGC/Ptr.h>
+#include <LibGC/Weak.h>
+#include <LibGC/WeakHashMap.h>
+#include <LibGC/WeakHashSet.h>
+#include <LibWeb/Forward.h>
+#include <LibWebCommon/Page/Translation.h>
+#include <LibWebCommon/PixelUnits.h>
+
+namespace Web::Translation {
+
+// Translates a document's text: It splits the text into units the translator takes one at a time, puts each unit's
+// translation back where the text came from, and translates the text the page adds or changes while it's translated.
+//
+// A paragraph's inline elements, e.g. links and emphasis, are kept: Each run of a paragraph's text carries a token
+// that the translation carries over to the words that translate it, so each translated word goes back into the
+// element its source text came from, even when the translation puts the words in another order.
+class DocumentTranslator {
+ AK_MAKE_NONCOPYABLE(DocumentTranslator);
+ AK_MAKE_NONMOVABLE(DocumentTranslator);
+ AK_ALLOC_WITH_KMALLOC;
+
+public:
+ explicit DocumentTranslator(DOM::Document&);
+
+ bool is_started() const { return m_source_language.has_value(); }
+ void start(String source_language, String target_language);
+
+ // The unit that should be translated next, if any is waiting, and how urgent it is; lower is more urgent.
+ struct Candidate {
+ u64 unit_id { 0 };
+ u64 priority { 0 };
+ };
+ Optional<Candidate> next_candidate();
+ // Hands over the unit, which is then in flight until its translation comes back.
+ Web::TranslationUnit take_unit_for_translation(u64 unit_id);
+ void did_translate(Web::TranslatedUnit const&);
+
+ // A mutation the page made; the translator's own mutations never get here.
+ void did_mutate(DOM::Node& target, Utf16FlyString const& type, Optional<Utf16FlyString> const& attribute_name, Optional<Utf16String> const& old_value);
+
+ bool is_settled() const;
+
+ void visit_edges(GC::Cell::Visitor&);
+
+private:
+ // How the translator treats a node it comes across among a container's children.
+ enum class NodeRole : u8 {
+ // Text, which is translated.
+ Text,
+ // An element whose content flows inline with the text around it, e.g. a link.
+ Inline,
+ // An inline element whose text the translator sees but leaves as it is.
+ Kept,
+ // A node that stays as it is, wherever the translation puts the text around it, e.g. an image.
+ Anchored,
+ // An element that holds paragraphs of its own, e.g. a block or an inline-block.
+ Container,
+ // An element whose content isn't translated at all.
+ Excluded,
+ // A forced line break, which ends a paragraph.
+ Break,
+ };
+
+ enum class UnitKind : u8 {
+ Paragraph,
+ Attribute,
+ Title,
+ OptionText,
+ };
+
+ // The text of a paragraph's run, or the element whose text the translator keeps as it is.
+ struct Piece {
+ GC::Ref<DOM::Node> node;
+ // The inline element of the paragraph the piece's node is in, or nothing if it's directly in the container, and
+ // that element's index in the paragraph's inline elements.
+ GC::Ptr<DOM::Element> owner;
+ Optional<size_t> owner_index;
+ Utf16String original_text;
+ bool keep_as_is { false };
+ };
+
+ // A node of a paragraph that isn't translated, e.g. an image, which stays in place among the translated text.
+ struct AnchoredNode {
+ GC::Ref<DOM::Node> node;
+ GC::Ptr<DOM::Element> owner;
+ Optional<size_t> owner_index;
+ // The last token before the node and the first after it, among the tokens of its owner's text; 0 for none.
+ u32 preceding_token { 0 };
+ u32 following_token { 0 };
+ // Whether the text was set apart from the node by white space, which a translation drops at the ends of runs.
+ bool space_before { false };
+ bool space_after { false };
+ };
+
+ struct Unit {
+ UnitKind kind { UnitKind::Paragraph };
+ Vector<Web::TranslationRun> runs;
+ bool in_flight { false };
+ // How urgent the unit is, as of the last time the viewport moved.
+ Optional<u64> priority;
+
+ // A paragraph: The container's children it spans, and every node in them that isn't anchored or kept, in tree
+ // order, to tell whether the page changed the paragraph before its translation came back.
+ GC::Ptr<DOM::Node> container;
+ Vector<GC::Ref<DOM::Node>> range;
+ Vector<GC::Ref<DOM::Node>> nodes;
+ // The piece of each token, at index token - 1.
+ Vector<Piece> pieces;
+ // Every inline element of the paragraph, in tree order, and the index of each one's parent among them; nothing
+ // for a child of the container.
+ Vector<GC::Ref<DOM::Element>> inline_elements;
+ Vector<Optional<size_t>> inline_element_parents;
+ Vector<AnchoredNode> anchored_nodes;
+
+ // An attribute, the title, or an option's text.
+ GC::Ptr<DOM::Element> element;
+ Optional<Utf16FlyString> attribute;
+ Utf16String original_text;
+
+ void visit_edges(GC::Cell::Visitor&);
+ };
+
+ class ParagraphBuilder;
+
+ void scan(DOM::Node& root);
+ void scan_container(DOM::Node& container);
+ void scan_anchored(DOM::Node&);
+ void scan_attributes(DOM::Element&);
+ void scan_options(DOM::Element& select);
+ void scan_title();
+ // NB: Units are made in place, rather than built up elsewhere and moved in, since only here does the collector see the
+ // nodes they hold.
+ u64 create_unit(UnitKind);
+ Unit& unit(u64 id) { return m_units.find(id)->value; }
+ bool is_paragraph_in_flight(Vector<GC::Ref<DOM::Node>> const& range) const;
+ void schedule_rescan();
+ void rescan();
+ void forget_units_within(DOM::Node&);
+
+ NodeRole role_of(DOM::Node const&) const;
+ bool is_excluded(DOM::Element const&) const;
+ bool is_in_excluded_element(DOM::Node const&) const;
+ bool is_inline(DOM::Element const&) const;
+ bool contains_paragraph_boundary(DOM::Element const&) const;
+ bool is_translated_text(DOM::Text const&) const;
+
+ void apply(Unit&, Vector<Web::TranslationRun> const&);
+ void apply_paragraph(Unit&, Vector<Web::TranslationRun> const&);
+ bool paragraph_is_unchanged(Unit const&) const;
+ u64 priority_of(Unit const&) const;
+
+ GC::Ref<DOM::Document> m_document;
+ Optional<String> m_source_language;
+ Optional<String> m_target_language;
+
+ HashMap<u64, Unit> m_units;
+
+ // The text the translator wrote, which isn't translated again unless the page changes it.
+ GC::WeakHashSet<DOM::Text> m_translated_text;
+ GC::WeakHashMap<DOM::Element, HashMap<Utf16FlyString, Utf16String>> m_written_attributes;
+ // The title's or an option's text.
+ GC::WeakHashMap<DOM::Element, Utf16String> m_written_text;
+ // The nodes the page added or changed, whose containers get scanned again.
+ Vector<GC::Weak<DOM::Node>> m_dirty_nodes;
+ bool m_rescan_scheduled { false };
+ Optional<CSSPixelRect> m_prioritized_viewport_rect;
+ // Set while the translator changes the document, so it doesn't take its own changes for the page's.
+ bool m_is_applying { false };
+};
+
+}
diff --git a/Libraries/LibWebCommon/CMakeLists.txt b/Libraries/LibWebCommon/CMakeLists.txt
index 749b47537a4..801dbdb7875 100644
--- a/Libraries/LibWebCommon/CMakeLists.txt
+++ b/Libraries/LibWebCommon/CMakeLists.txt
@@ -58,6 +58,7 @@ set(SOURCES
Page/InputTrace.cpp
Page/MediaContextMenu.cpp
Page/SpellingError.cpp
+ Page/Translation.cpp
Page/WritingSuggestion.cpp
Permissions/Permissions.cpp
PermissionsPolicy/PermissionsPolicy.cpp
diff --git a/Libraries/LibWebCommon/Page/Translation.cpp b/Libraries/LibWebCommon/Page/Translation.cpp
new file mode 100644
index 00000000000..ee7c1fdae54
--- /dev/null
+++ b/Libraries/LibWebCommon/Page/Translation.cpp
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibIPC/Decoder.h>
+#include <LibIPC/Encoder.h>
+#include <LibWebCommon/Page/Translation.h>
+
+template<>
+ErrorOr<void> IPC::encode(Encoder& encoder, Web::TranslationRun const& run)
+{
+ TRY(encoder.encode(run.text));
+ TRY(encoder.encode(run.token));
+ TRY(encoder.encode(run.keep_as_is));
+ return {};
+}
+
+template<>
+ErrorOr<Web::TranslationRun> IPC::decode(Decoder& decoder)
+{
+ auto text = TRY(decoder.decode<Utf16String>());
+ auto token = TRY(decoder.decode<u32>());
+ auto keep_as_is = TRY(decoder.decode<bool>());
+ return Web::TranslationRun { move(text), token, keep_as_is };
+}
+
+template<>
+ErrorOr<void> IPC::encode(Encoder& encoder, Web::TranslationUnit const& unit)
+{
+ TRY(encoder.encode(unit.id));
+ TRY(encoder.encode(unit.runs));
+ return {};
+}
+
+template<>
+ErrorOr<Web::TranslationUnit> IPC::decode(Decoder& decoder)
+{
+ auto id = TRY(decoder.decode<u64>());
+ auto runs = TRY(decoder.decode<Vector<Web::TranslationRun>>());
+ return Web::TranslationUnit { id, move(runs) };
+}
+
+template<>
+ErrorOr<void> IPC::encode(Encoder& encoder, Web::TranslatedUnit const& unit)
+{
+ TRY(encoder.encode(unit.id));
+ TRY(encoder.encode(unit.runs));
+ return {};
+}
+
+template<>
+ErrorOr<Web::TranslatedUnit> IPC::decode(Decoder& decoder)
+{
+ auto id = TRY(decoder.decode<u64>());
+ auto runs = TRY(decoder.decode<Optional<Vector<Web::TranslationRun>>>());
+ return Web::TranslatedUnit { id, move(runs) };
+}
+
+template<>
+ErrorOr<void> IPC::encode(Encoder& encoder, Web::TranslationLanguageSample const& sample)
+{
+ TRY(encoder.encode(sample.declared_language));
+ TRY(encoder.encode(sample.text));
+ return {};
+}
+
+template<>
+ErrorOr<Web::TranslationLanguageSample> IPC::decode(Decoder& decoder)
+{
+ auto declared_language = TRY(decoder.decode<Optional<String>>());
+ auto text = TRY(decoder.decode<Utf16String>());
+ return Web::TranslationLanguageSample { move(declared_language), move(text) };
+}
diff --git a/Libraries/LibWebCommon/Page/Translation.h b/Libraries/LibWebCommon/Page/Translation.h
new file mode 100644
index 00000000000..017bf84815e
--- /dev/null
+++ b/Libraries/LibWebCommon/Page/Translation.h
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Optional.h>
+#include <AK/String.h>
+#include <AK/Types.h>
+#include <AK/Utf16String.h>
+#include <AK/Vector.h>
+#include <LibIPC/Forward.h>
+#include <LibWebCommon/Export.h>
+
+namespace Web {
+
+// A stretch of a translation unit's text that comes from one place in the document. The translator carries each
+// run's token over to the words that translate it, so the translated text can be put back where it came from, even
+// when the translation reorders those words.
+struct TranslationRun {
+ Utf16String text;
+ u32 token { 0 };
+ // Text the translator must leave exactly as it is, e.g. the text of an element whose translation mode is
+ // no-translate, inside a paragraph that's otherwise translated.
+ bool keep_as_is { false };
+
+ bool operator==(TranslationRun const&) const = default;
+};
+
+// A piece of a document's text that's translated as a whole, e.g. a paragraph.
+struct TranslationUnit {
+ u64 id { 0 };
+ Vector<TranslationRun> runs;
+};
+
+// A unit's translation; nothing if the translator couldn't translate it.
+struct TranslatedUnit {
+ u64 id { 0 };
+ Optional<Vector<TranslationRun>> runs;
+};
+
+// What a page offers for working out which language it's in.
+struct TranslationLanguageSample {
+ // The language of the document element, from its lang attribute or the Content-Language header.
+ Optional<String> declared_language;
+ Utf16String text;
+};
+
+}
+
+namespace IPC {
+
+template<>
+WEBCOMMON_API ErrorOr<void> encode(Encoder&, Web::TranslationRun const&);
+
+template<>
+WEBCOMMON_API ErrorOr<Web::TranslationRun> decode(Decoder&);
+
+template<>
+WEBCOMMON_API ErrorOr<void> encode(Encoder&, Web::TranslationUnit const&);
+
+template<>
+WEBCOMMON_API ErrorOr<Web::TranslationUnit> decode(Decoder&);
+
+template<>
+WEBCOMMON_API ErrorOr<void> encode(Encoder&, Web::TranslatedUnit const&);
+
+template<>
+WEBCOMMON_API ErrorOr<Web::TranslatedUnit> decode(Decoder&);
+
+template<>
+WEBCOMMON_API ErrorOr<void> encode(Encoder&, Web::TranslationLanguageSample const&);
+
+template<>
+WEBCOMMON_API ErrorOr<Web::TranslationLanguageSample> decode(Decoder&);
+
+}
diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cpp
index d52b32b7474..af57c79d42e 100644
--- a/Libraries/LibWebView/Application.cpp
+++ b/Libraries/LibWebView/Application.cpp
@@ -72,6 +72,7 @@
#include <LibWebView/SpellChecker.h>
#include <LibWebView/StorageAreaRegistry.h>
#include <LibWebView/TabPerformanceMonitor.h>
+#include <LibWebView/Translator.h>
#include <LibWebView/URL.h>
#include <LibWebView/UserAgent.h>
#include <LibWebView/Utilities.h>
@@ -3310,6 +3311,11 @@ void Application::set_spell_checker(OwnPtr<SpellChecker> spell_checker)
m_spell_checker = move(spell_checker);
}
+void Application::set_translator(OwnPtr<Translator> translator)
+{
+ m_translator = move(translator);
+}
+
MicrophoneAuthorizer& Application::microphone_authorizer()
{
if (!m_microphone_authorizer)
diff --git a/Libraries/LibWebView/Application.h b/Libraries/LibWebView/Application.h
index 28206dfc508..df60aec398f 100644
--- a/Libraries/LibWebView/Application.h
+++ b/Libraries/LibWebView/Application.h
@@ -105,6 +105,9 @@ public:
SpellChecker* spell_checker() { return m_spell_checker.ptr(); }
void set_spell_checker(OwnPtr<SpellChecker>);
+
+ Translator* translator() { return m_translator.ptr(); }
+ void set_translator(OwnPtr<Translator>);
MicrophoneAuthorizer& microphone_authorizer();
static FontService& font_service() { return *the().m_font_service; }
static FontServiceHost& font_service_host() { return *the().m_font_service_host; }
@@ -708,6 +711,7 @@ private:
OwnPtr<Core::GeolocationProvider> m_geolocation_provider;
OwnPtr<SpellChecker> m_spell_checker;
+ OwnPtr<Translator> m_translator;
OwnPtr<MicrophoneAuthorizer> m_microphone_authorizer;
OwnPtr<Core::TimeZoneWatcher> m_time_zone_watcher;
diff --git a/Libraries/LibWebView/CMakeLists.txt b/Libraries/LibWebView/CMakeLists.txt
index 73255813250..b7ab7add8b9 100644
--- a/Libraries/LibWebView/CMakeLists.txt
+++ b/Libraries/LibWebView/CMakeLists.txt
@@ -50,6 +50,7 @@ set(SOURCES
NotificationAttribution.cpp
NotificationFreedesktopArguments.cpp
NotificationManager.cpp
+ PageTranslation.cpp
PictureInPictureManager.cpp
PictureInPictureWindow.cpp
PermissionManager.cpp
@@ -75,6 +76,8 @@ set(SOURCES
StorageAreaRegistry.cpp
StorageJar.cpp
TestSpellChecker.cpp
+ TestTranslator.cpp
+ Translator.cpp
URL.cpp
UserAgent.cpp
Utilities.cpp
diff --git a/Libraries/LibWebView/Forward.h b/Libraries/LibWebView/Forward.h
index 6460b6816c7..a4fd8ccdb66 100644
--- a/Libraries/LibWebView/Forward.h
+++ b/Libraries/LibWebView/Forward.h
@@ -50,6 +50,7 @@ class NavigationLoader;
class OutOfProcessWebView;
class NotificationBackend;
class NotificationManager;
+class PageTranslation;
class PictureInPictureManager;
class RecordingNotificationBackend;
class PictureInPictureWindow;
@@ -62,6 +63,7 @@ class SessionStore;
class Settings;
class SettingsUI;
class SpellChecker;
+class Translator;
class StorageJar;
class TraversableSessionHistory;
class VideoDecoderServerControlClient;
diff --git a/Libraries/LibWebView/Menu.h b/Libraries/LibWebView/Menu.h
index 8988c492674..daaa7b2b737 100644
--- a/Libraries/LibWebView/Menu.h
+++ b/Libraries/LibWebView/Menu.h
@@ -102,6 +102,12 @@ enum class ActionID {
EnterPictureInPicture,
ExitPictureInPicture,
+ TranslatePage,
+ TranslateTo,
+ ShowOriginal,
+ DownloadTranslationLanguages,
+ EditPreferredLanguages,
+
ZoomIn,
ZoomOut,
ResetZoom,
diff --git a/Libraries/LibWebView/PageTranslation.cpp b/Libraries/LibWebView/PageTranslation.cpp
new file mode 100644
index 00000000000..5c3fb71a18a
--- /dev/null
+++ b/Libraries/LibWebView/PageTranslation.cpp
@@ -0,0 +1,327 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/AnyOf.h>
+#include <LibURL/InternalURLs.h>
+#include <LibURL/URL.h>
+#include <LibUnicode/DisplayNames.h>
+#include <LibWebView/Application.h>
+#include <LibWebView/CanonicalTraversable.h>
+#include <LibWebView/Menu.h>
+#include <LibWebView/PageTranslation.h>
+#include <LibWebView/Settings.h>
+#include <LibWebView/URL.h>
+#include <LibWebView/ViewImplementation.h>
+#include <LibWebView/WebContentPage.h>
+
+namespace WebView {
+
+// The browser's own strings are English, so languages are named in English.
+static String language_display_name(StringView language)
+{
+ auto primary_language = primary_language_subtag(language);
+ if (auto name = Unicode::language_display_name("en"sv, primary_language, Unicode::LanguageDisplay::Standard); name.has_value())
+ return name->to_utf8();
+ return MUST(String::from_utf8(primary_language));
+}
+
+// The languages the user reads, most preferred first, one per language whatever its regions.
+static Vector<String> languages_the_user_reads()
+{
+ Vector<String> languages;
+ for (auto const& language : Application::settings().languages()) {
+ if (!any_of(languages, [&](auto const& existing) { return is_same_language(existing, language); }))
+ languages.append(language);
+ }
+ return languages;
+}
+
+PageTranslation::PageTranslation(ViewImplementation& view)
+ : m_view(view)
+{
+ m_translate_action = Action::create("Translate"sv, ActionID::TranslatePage, [] { });
+ m_translate_action->set_tooltip("Translate this page"sv);
+ m_translate_action->set_visible(false);
+
+ m_translation_menu = Menu::create("Translation"sv);
+ for (size_t index = 0; index < MAXIMUM_OFFERED_LANGUAGES; ++index) {
+ auto action = Action::create_checkable("Translate"sv, ActionID::TranslateTo, [this, index] {
+ if (auto target_language = ready_target_language(index); target_language.has_value())
+ translate_to(*target_language);
+ // NB: The check mark shows the language the page is in, which activating an action doesn't change by itself.
+ update_actions();
+ });
+ action->set_visible(false);
+ m_translation_menu->add_action(action);
+ m_translate_to_actions.append(move(action));
+ }
+ m_show_original_action = Action::create("Show Original"sv, ActionID::ShowOriginal, [this] { show_original(); });
+ m_translation_menu->add_action(*m_show_original_action);
+ m_translation_menu->add_separator();
+ m_download_languages_action = Action::create("Download Languages…"sv, ActionID::DownloadTranslationLanguages, [] {
+ if (auto* translator = Application::the().translator())
+ translator->open_language_download_settings();
+ });
+ m_translation_menu->add_action(*m_download_languages_action);
+ m_translation_menu->add_action(Action::create("Preferred Languages…"sv, ActionID::EditPreferredLanguages, [] {
+ auto url = URL::about_settings();
+ url.set_fragment("editLanguages"sv);
+ Application::the().activate_or_open_tab_with_url(url);
+ }));
+
+ update_actions();
+}
+
+PageTranslation::~PageTranslation()
+{
+ close_session();
+}
+
+bool PageTranslation::is_offered() const
+{
+ if (is_translated())
+ return true;
+ return any_of(m_target_languages, [](auto const& target) { return !target.needs_download; });
+}
+
+void PageTranslation::translate_to(String const& target_language)
+{
+ auto* translator = Application::the().translator();
+ if (!translator || !m_page_language.has_value())
+ return;
+ if (m_target_language.has_value() && is_same_language(*m_target_language, target_language))
+ return;
+
+ // A page translated into another language is shown in the original first, since its text is already translated.
+ if (is_translated()) {
+ m_previous_translation = PreviousTranslation { *m_page_language, target_language, current_site() };
+ show_original();
+ return;
+ }
+
+ m_session_id = translator->create_session(*m_page_language, target_language);
+ m_target_language = target_language;
+ m_translated_site = current_site();
+
+ m_view.traversable().for_each_hosting_page([&](WebContentPage& page) {
+ if (page.is_open())
+ page.async_start_translation(*m_page_language, target_language);
+ });
+
+ update_actions();
+}
+
+void PageTranslation::show_original()
+{
+ if (!is_translated())
+ return;
+ // The reload brings the original back; the translation the user turned off isn't carried over to it. The page stays
+ // translated until the reload replaces its document, which may not happen, e.g. if the page asks the user to stay.
+ if (!m_previous_translation.has_value() || is_same_language(m_previous_translation->target_language, *m_target_language))
+ m_skip_continuation_for_next_document = true;
+ stop_translating_pages();
+ m_view.reload();
+}
+
+void PageTranslation::did_finish_loading()
+{
+ if (is_translated() || !Application::the().translator())
+ return;
+
+ detect_page_language([this] {
+ // NB: This runs from detect_page_language()'s callbacks, which check that the translation is still alive.
+ auto previous_translation = exchange(m_previous_translation, {});
+ if (!previous_translation.has_value() || !m_page_language.has_value())
+ return;
+ // A translated page's next page is translated too, if it's in the same language on the same site.
+ if (!is_same_language(previous_translation->source_language, *m_page_language) || previous_translation->site != current_site())
+ return;
+ auto target = m_target_languages.find_if([&](auto const& target) { return !target.needs_download && is_same_language(target.language, previous_translation->target_language); });
+ if (!target.is_end())
+ translate_to(target->language);
+ });
+}
+
+void PageTranslation::did_change_active_document()
+{
+ ++m_generation;
+ m_pending_samples.clear();
+
+ // The next page continues the translation, unless the user showed the original. A translation into another language
+ // that the user asked for while the page was translated is recorded already, and is kept.
+ if (exchange(m_skip_continuation_for_next_document, false))
+ m_previous_translation.clear();
+ else if (is_translated() && !m_previous_translation.has_value())
+ m_previous_translation = PreviousTranslation { *m_page_language, *m_target_language, m_translated_site };
+
+ if (is_translated())
+ stop_translating_pages();
+ close_session();
+ m_page_language.clear();
+ m_target_languages.clear();
+ m_target_language.clear();
+ update_actions();
+}
+
+void PageTranslation::did_create_page(WebContentPage& page)
+{
+ if (is_translated())
+ page.async_start_translation(*m_page_language, *m_target_language);
+}
+
+void PageTranslation::did_get_language_sample(Badge<WebContentPage>, u64 request_id, Web::TranslationLanguageSample sample)
+{
+ if (sample.text.length_in_code_units() > MAXIMUM_LANGUAGE_SAMPLE_LENGTH)
+ sample.text = Utf16String::from_utf16(sample.text.substring_view(0, MAXIMUM_LANGUAGE_SAMPLE_LENGTH));
+ if (auto callback = m_pending_samples.take(request_id); callback.has_value())
+ (*callback)(move(sample));
+}
+
+void PageTranslation::did_request_translation(Badge<WebContentPage>, WebContentPage& requesting_page, Web::TranslationUnit unit)
+{
+ auto* translator = Application::the().translator();
+ if (!translator || !m_session_id.has_value()) {
+ requesting_page.async_did_translate({ unit.id, {} });
+ return;
+ }
+
+ size_t unit_length = 0;
+ for (auto const& run : unit.runs)
+ unit_length += run.text.length_in_code_units();
+ auto& units_in_flight = m_units_in_flight.ensure(&requesting_page);
+ if (units_in_flight >= MAXIMUM_UNITS_IN_FLIGHT_PER_PAGE || unit_length > MAXIMUM_UNIT_LENGTH) {
+ requesting_page.async_did_translate({ unit.id, {} });
+ return;
+ }
+ ++units_in_flight;
+
+ auto unit_id = unit.id;
+ // NB: Closing the session drops this callback, and the session is closed before the translation is destroyed.
+ translator->translate(*m_session_id, move(unit), [this, page = NonnullRefPtr { requesting_page }, unit_id](Optional<Vector<Web::TranslationRun>> runs) {
+ if (auto it = m_units_in_flight.find(page.ptr()); it != m_units_in_flight.end() && --it->value == 0)
+ m_units_in_flight.remove(it);
+ if (page->is_open())
+ page->async_did_translate({ unit_id, move(runs) });
+ });
+}
+
+void PageTranslation::translate_for_testing(Badge<WebContentPage>, String target_language)
+{
+ detect_page_language([this, target_language = move(target_language)] {
+ translate_to(target_language);
+ });
+}
+
+void PageTranslation::detect_page_language(Function<void()> on_complete)
+{
+ auto request_id = m_next_sample_request_id++;
+ auto generation = m_generation;
+ m_pending_samples.set(request_id, [this, generation, on_complete = move(on_complete)](Web::TranslationLanguageSample sample) mutable {
+ auto* translator = Application::the().translator();
+ if (!translator || generation != m_generation)
+ return;
+ // The tab may be closed before the translator answers.
+ translator->detect_language(sample, [weak_this = make_weak_ptr(), generation, on_complete = move(on_complete)](Optional<String> language) mutable {
+ if (weak_this)
+ weak_this->did_detect_page_language(generation, move(language), move(on_complete));
+ });
+ });
+ m_view.page().async_request_translation_language_sample(request_id);
+}
+
+void PageTranslation::did_detect_page_language(u64 generation, Optional<String> language, Function<void()> on_complete)
+{
+ auto* translator = Application::the().translator();
+ if (!translator || generation != m_generation)
+ return;
+
+ m_page_language = move(language);
+ m_target_languages.clear();
+ update_actions();
+
+ // A page in a language the user reads isn't offered for translation.
+ auto languages = languages_the_user_reads();
+ if (!m_page_language.has_value() || any_of(languages, [&](auto const& language) { return is_same_language(language, *m_page_language); })) {
+ if (on_complete)
+ on_complete();
+ return;
+ }
+ if (languages.size() > MAXIMUM_OFFERED_LANGUAGES)
+ languages.shrink(MAXIMUM_OFFERED_LANGUAGES);
+
+ translator->target_languages(*m_page_language, languages, [weak_this = make_weak_ptr(), generation, on_complete = move(on_complete)](Vector<Translator::TargetLanguage> target_languages) {
+ if (!weak_this || generation != weak_this->m_generation)
+ return;
+ weak_this->m_target_languages = move(target_languages);
+ weak_this->update_actions();
+ if (on_complete)
+ on_complete();
+ });
+}
+
+Optional<String> PageTranslation::ready_target_language(size_t index) const
+{
+ for (auto const& target : m_target_languages) {
+ if (target.needs_download)
+ continue;
+ if (index-- == 0)
+ return target.language;
+ }
+ return {};
+}
+
+// The pages forget the translation, so a document they load next isn't translated unless it's asked for.
+void PageTranslation::stop_translating_pages()
+{
+ m_view.traversable().for_each_hosting_page([](WebContentPage& page) {
+ if (page.is_open())
+ page.async_stop_translation();
+ });
+}
+
+void PageTranslation::close_session()
+{
+ m_units_in_flight.clear();
+ if (!m_session_id.has_value())
+ return;
+ if (auto* translator = Application::the().translator())
+ translator->close_session(*m_session_id);
+ m_session_id.clear();
+}
+
+void PageTranslation::update_actions()
+{
+ m_translate_action->set_visible(is_offered());
+ m_translate_action->set_engaged(is_translated());
+ m_translate_action->set_tooltip(is_translated() ? "Showing translation"sv : "Translate this page"sv);
+
+ size_t slot = 0;
+ for (auto const& target : m_target_languages) {
+ if (target.needs_download || slot == m_translate_to_actions.size())
+ continue;
+ auto& action = m_translate_to_actions[slot++];
+ action->set_text(MUST(String::formatted("Translate to {}", language_display_name(target.language))));
+ action->set_checked(m_target_language.has_value() && is_same_language(*m_target_language, target.language));
+ action->set_visible(true);
+ }
+ for (; slot < m_translate_to_actions.size(); ++slot)
+ m_translate_to_actions[slot]->set_visible(false);
+
+ m_show_original_action->set_enabled(is_translated());
+ m_download_languages_action->set_visible(any_of(m_target_languages, [](auto const& target) { return target.needs_download; }));
+}
+
+Optional<String> PageTranslation::current_site() const
+{
+ auto url = m_view.url();
+ if (!url.host().has_value())
+ return {};
+ if (auto domain = url.host()->registrable_domain(); domain.has_value())
+ return domain;
+ return url.host()->serialize();
+}
+
+}
diff --git a/Libraries/LibWebView/PageTranslation.h b/Libraries/LibWebView/PageTranslation.h
new file mode 100644
index 00000000000..27ca94348ee
--- /dev/null
+++ b/Libraries/LibWebView/PageTranslation.h
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Function.h>
+#include <AK/HashMap.h>
+#include <AK/NonnullRefPtr.h>
+#include <AK/Optional.h>
+#include <AK/String.h>
+#include <AK/Vector.h>
+#include <AK/Weakable.h>
+#include <LibWebCommon/Page/Translation.h>
+#include <LibWebView/Forward.h>
+#include <LibWebView/Translator.h>
+
+namespace WebView {
+
+// Translating one tab's page: working out which language the page is in, offering to translate it into a language the
+// user reads, translating it with the platform translator, and showing the original again.
+//
+// The pages of every process that hosts a document of the tab translate their own documents. They send their text here
+// one unit at a time, and get each unit's translation back.
+class PageTranslation : public Weakable<PageTranslation> {
+ AK_MAKE_NONCOPYABLE(PageTranslation);
+ AK_MAKE_NONMOVABLE(PageTranslation);
+ AK_ALLOC_WITH_KMALLOC;
+
+public:
+ // How many languages the translation menu offers at most.
+ static constexpr size_t MAXIMUM_OFFERED_LANGUAGES = 5;
+ // A page sends a few units at a time, of a paragraph's text each. One that sends more is answered without them being
+ // translated, so a misbehaving WebContent process can't queue up unbounded work for the translator.
+ static constexpr size_t MAXIMUM_UNITS_IN_FLIGHT_PER_PAGE = 8;
+ static constexpr size_t MAXIMUM_UNIT_LENGTH = 65536;
+ // The language sample is enough text to tell its language by, and no more is looked at.
+ static constexpr size_t MAXIMUM_LANGUAGE_SAMPLE_LENGTH = 4096;
+
+ explicit PageTranslation(ViewImplementation&);
+ ~PageTranslation();
+
+ // The language of the tab's document, once it's known.
+ Optional<String> const& page_language() const { return m_page_language; }
+ // The language the page is shown in, if it's translated.
+ Optional<String> const& target_language() const { return m_target_language; }
+ bool is_translated() const { return m_target_language.has_value(); }
+
+ // Whether the page can be translated into a language the user reads, or already is.
+ bool is_offered() const;
+
+ Action& translate_action() { return *m_translate_action; }
+ Menu& translation_menu() { return *m_translation_menu; }
+
+ void translate_to(String const& target_language);
+ // Shows the page as it was before it was translated, by loading it again.
+ void show_original();
+
+ void did_finish_loading();
+ void did_change_active_document();
+ // A page that hosts a document of the tab starts translating it if the tab is translated.
+ void did_create_page(WebContentPage&);
+
+ void did_get_language_sample(Badge<WebContentPage>, u64 request_id, Web::TranslationLanguageSample);
+ void did_request_translation(Badge<WebContentPage>, WebContentPage&, Web::TranslationUnit);
+ // For tests: Works out which language the page is in, then translates it into the target language.
+ void translate_for_testing(Badge<WebContentPage>, String target_language);
+
+private:
+ struct PreviousTranslation {
+ String source_language;
+ String target_language;
+ Optional<String> site;
+ };
+
+ // The target the n-th of the translation menu's languages stands for; only targets ready to translate get one.
+ Optional<String> ready_target_language(size_t index) const;
+ void stop_translating_pages();
+ void detect_page_language(Function<void()> on_complete = {});
+ void did_detect_page_language(u64 generation, Optional<String> language, Function<void()> on_complete);
+ void close_session();
+ void update_actions();
+ Optional<String> current_site() const;
+
+ ViewImplementation& m_view;
+
+ Optional<String> m_page_language;
+ Vector<Translator::TargetLanguage> m_target_languages;
+ Optional<String> m_target_language;
+ // The site of the page that was translated, for continuing on the next page of that site.
+ Optional<String> m_translated_site;
+ Optional<Translator::SessionId> m_session_id;
+ HashMap<WebContentPage const*, size_t> m_units_in_flight;
+
+ // A translation in force when the user followed a link, which the next page of the same site continues.
+ Optional<PreviousTranslation> m_previous_translation;
+ // Set when the original is shown again, so the reload that shows it isn't translated straight away.
+ bool m_skip_continuation_for_next_document { false };
+
+ // Answers to requests made for an earlier document are ignored.
+ u64 m_generation { 0 };
+ u64 m_next_sample_request_id { 0 };
+ HashMap<u64, Function<void(Web::TranslationLanguageSample)>> m_pending_samples;
+
+ RefPtr<Action> m_translate_action;
+ RefPtr<Menu> m_translation_menu;
+ Vector<NonnullRefPtr<Action>> m_translate_to_actions;
+ RefPtr<Action> m_show_original_action;
+ RefPtr<Action> m_download_languages_action;
+};
+
+}
diff --git a/Libraries/LibWebView/TestTranslator.cpp b/Libraries/LibWebView/TestTranslator.cpp
new file mode 100644
index 00000000000..c45e4fb76fc
--- /dev/null
+++ b/Libraries/LibWebView/TestTranslator.cpp
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibCore/EventLoop.h>
+#include <LibWebView/TestTranslator.h>
+
+namespace WebView {
+
+void TestTranslator::detect_language(Web::TranslationLanguageSample const& sample, Function<void(Optional<String>)> on_complete)
+{
+ Core::deferred_invoke([on_complete = move(on_complete), language = sample.declared_language]() mutable {
+ on_complete(move(language));
+ });
+}
+
+void TestTranslator::target_languages(String const& source_language, Vector<String> const& candidates, Function<void(Vector<TargetLanguage>)> on_complete)
+{
+ Vector<TargetLanguage> target_languages;
+ for (auto const& candidate : candidates) {
+ if (is_same_language(candidate, source_language))
+ continue;
+ target_languages.append({ candidate, is_same_language(candidate, "xx"sv) });
+ }
+ Core::deferred_invoke([on_complete = move(on_complete), target_languages = move(target_languages)]() mutable {
+ on_complete(move(target_languages));
+ });
+}
+
+Translator::SessionId TestTranslator::create_session(String const&, String const& target_language)
+{
+ auto session_id = ++m_last_session_id;
+ m_target_languages.set(session_id, target_language);
+ return session_id;
+}
+
+void TestTranslator::close_session(SessionId session_id)
+{
+ m_target_languages.remove(session_id);
+}
+
+void TestTranslator::translate(SessionId session_id, Web::TranslationUnit unit, Function<void(Optional<Vector<Web::TranslationRun>>)> on_complete)
+{
+ Vector<Web::TranslationRun> runs;
+ runs.ensure_capacity(unit.runs.size());
+ for (auto& run : unit.runs.in_reverse()) {
+ if (!run.keep_as_is) {
+ auto uppercase = run.text.to_ascii_uppercase();
+ run.text = Utf16String::from_utf16(uppercase.utf16_view().trim_ascii_whitespace());
+ }
+ runs.unchecked_append(move(run));
+ }
+ if (auto target_language = m_target_languages.get(session_id); target_language.has_value() && !runs.is_empty()) {
+ if (target_language->ends_with_bytes("-x-repeat"sv))
+ runs.append(runs.first());
+ else if (target_language->ends_with_bytes("-x-drop"sv) && runs.size() > 1)
+ runs.take_last();
+ }
+
+ // Answer on a later turn of the event loop, as platform translators do, and never for a closed session.
+ Core::deferred_invoke([this, session_id, on_complete = move(on_complete), runs = move(runs)]() mutable {
+ if (m_target_languages.contains(session_id))
+ on_complete(move(runs));
+ });
+}
+
+}
diff --git a/Libraries/LibWebView/TestTranslator.h b/Libraries/LibWebView/TestTranslator.h
new file mode 100644
index 00000000000..ce4f688455d
--- /dev/null
+++ b/Libraries/LibWebView/TestTranslator.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/HashMap.h>
+#include <LibWebView/Translator.h>
+
+namespace WebView {
+
+// A translator that gives the same answers on every platform, so tests can check what translating a page does to it.
+// It "translates" a unit by putting its runs in reverse order, and by uppercasing the ASCII letters of every run it may
+// translate and trimming the white space at its ends, as a real translation does. Reversing the runs means every test
+// exercises the reordering a real translation can bring. A target language with the private use subtag "x-repeat" also
+// gets the first run of each translation a second time, at its end, and one with "x-drop" loses its last run, as real
+// translations sometimes do.
+class WEBVIEW_API TestTranslator final : public Translator {
+public:
+ // The page's declared language, or nothing.
+ virtual void detect_language(Web::TranslationLanguageSample const&, Function<void(Optional<String>)> on_complete) override;
+ // Every candidate in another language; one whose primary language subtag is "xx" needs downloading first.
+ virtual void target_languages(String const& source_language, Vector<String> const& candidates, Function<void(Vector<TargetLanguage>)> on_complete) override;
+ virtual SessionId create_session(String const& source_language, String const& target_language) override;
+ virtual void close_session(SessionId) override;
+ virtual void translate(SessionId, Web::TranslationUnit, Function<void(Optional<Vector<Web::TranslationRun>>)> on_complete) override;
+ virtual void open_language_download_settings() override { }
+
+private:
+ SessionId m_last_session_id { 0 };
+ HashMap<SessionId, String> m_target_languages;
+};
+
+}
diff --git a/Libraries/LibWebView/Translator.cpp b/Libraries/LibWebView/Translator.cpp
new file mode 100644
index 00000000000..f6faa8e511f
--- /dev/null
+++ b/Libraries/LibWebView/Translator.cpp
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibWebView/Translator.h>
+
+namespace WebView {
+
+StringView primary_language_subtag(StringView language)
+{
+ if (auto separator = language.find_any_of("-_"sv); separator.has_value())
+ return language.substring_view(0, *separator);
+ return language;
+}
+
+bool is_same_language(StringView a, StringView b)
+{
+ return primary_language_subtag(a).equals_ignoring_ascii_case(primary_language_subtag(b));
+}
+
+}
diff --git a/Libraries/LibWebView/Translator.h b/Libraries/LibWebView/Translator.h
new file mode 100644
index 00000000000..1897ef2864f
--- /dev/null
+++ b/Libraries/LibWebView/Translator.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Function.h>
+#include <AK/Optional.h>
+#include <AK/String.h>
+#include <AK/Vector.h>
+#include <LibWebCommon/Page/Translation.h>
+#include <LibWebView/Export.h>
+
+namespace WebView {
+
+// The primary language subtag of a BCP 47 language tag, e.g. "pt" for "pt-BR".
+WEBVIEW_API StringView primary_language_subtag(StringView language);
+// Whether two language tags name the same language, whatever their regions or scripts.
+WEBVIEW_API bool is_same_language(StringView, StringView);
+
+// The platform translator the UI process asks on behalf of every page. Languages are BCP 47 tags.
+class WEBVIEW_API Translator {
+ AK_ALLOC_WITH_KMALLOC;
+
+public:
+ using SessionId = u64;
+
+ virtual ~Translator() = default;
+
+ // Works out which language a page is in. Asynchronous; on_complete runs on the main thread, with nothing if the
+ // sample doesn't say.
+ virtual void detect_language(Web::TranslationLanguageSample const&, Function<void(Optional<String>)> on_complete) = 0;
+
+ struct TargetLanguage {
+ String language;
+ // The platform supports the pair, but the user has to download its languages before it can be translated.
+ bool needs_download { false };
+ };
+
+ // Which of the candidate languages text in the source language can be translated into, in the candidates' order.
+ // Asynchronous; on_complete runs on the main thread.
+ virtual void target_languages(String const& source_language, Vector<String> const& candidates, Function<void(Vector<TargetLanguage>)> on_complete) = 0;
+
+ // A session translates from one language to another, one unit at a time, in the order the units are given.
+ virtual SessionId create_session(String const& source_language, String const& target_language) = 0;
+ // Drops the units the session hasn't translated yet; their callbacks never run.
+ virtual void close_session(SessionId) = 0;
+ // Asynchronous; on_complete runs on the main thread, with nothing if the unit couldn't be translated.
+ virtual void translate(SessionId, Web::TranslationUnit, Function<void(Optional<Vector<Web::TranslationRun>>)> on_complete) = 0;
+
+ // Opens the platform's settings where the user downloads the languages a translation needs.
+ virtual void open_language_download_settings() = 0;
+};
+
+}
diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cpp
index fa9edf7cbfb..3ecf2b94a91 100644
--- a/Libraries/LibWebView/ViewImplementation.cpp
+++ b/Libraries/LibWebView/ViewImplementation.cpp
@@ -38,6 +38,7 @@
#include <LibWebView/HistoryDebug.h>
#include <LibWebView/HistoryStore.h>
#include <LibWebView/Menu.h>
+#include <LibWebView/PageTranslation.h>
#include <LibWebView/PermissionManager.h>
#include <LibWebView/SessionHistory.h>
#include <LibWebView/TabPerformanceMonitor.h>
@@ -94,6 +95,7 @@ ViewImplementation::ViewImplementation(IsPrivate is_private)
all_views().set(m_view_id, this);
initialize_context_menus();
+ m_page_translation = make<PageTranslation>(*this);
m_repeated_crash_timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(1000), [this] {
// Reset the "crashing a lot" counter after 1 second in case we just
@@ -347,6 +349,7 @@ void ViewImplementation::did_change_ongoing_navigation(Badge<CanonicalNavigable>
void ViewImplementation::did_change_active_document(Badge<CanonicalTraversable>)
{
+ m_page_translation->did_change_active_document();
// A prompt the document that asked has left behind goes unanswered: the user ignored it.
ignore_pending_permission_prompts();
report_permission_presence();
@@ -1620,6 +1623,7 @@ void ViewImplementation::send_preferences_to_page(WebContentPage& page)
auto* spell_checker = Application::the().spell_checker();
page.async_set_spell_checking_available(spell_checker != nullptr);
page.async_set_writing_suggestions_available(spell_checker && spell_checker->can_suggest());
+ m_page_translation->did_create_page(page);
send_geolocation_emulated_position(page);
page.async_set_has_picture_in_picture_support(Application::the().supports_picture_in_picture());
}
@@ -3341,6 +3345,7 @@ void ViewImplementation::did_cancel_loading(Badge<CanonicalNavigable>, bool canc
void ViewImplementation::did_finish_navigation()
{
set_loading_state(false);
+ m_page_translation->did_finish_loading();
if (!m_webdriver_navigation_observation.has_value())
return;
diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.h
index 3fd42fe28c1..f47b8e88129 100644
--- a/Libraries/LibWebView/ViewImplementation.h
+++ b/Libraries/LibWebView/ViewImplementation.h
@@ -712,6 +712,8 @@ public:
Action& toggle_bookmark_action() { return *m_toggle_bookmark_action; }
Action& reset_zoom_action() { return *m_reset_zoom_action; }
+ PageTranslation& page_translation() { return *m_page_translation; }
+
WebContentPage& page() const;
virtual Web::DevicePixelSize viewport_size() const = 0;
@@ -937,6 +939,7 @@ protected:
RefPtr<Action> m_navigate_forward_action;
RefPtr<Action> m_toggle_bookmark_action;
+ OwnPtr<PageTranslation> m_page_translation;
RefPtr<Action> m_reset_zoom_action;
diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cpp
index 026ae7a84d2..46d936fe1b4 100644
--- a/Libraries/LibWebView/WebContentPage.cpp
+++ b/Libraries/LibWebView/WebContentPage.cpp
@@ -32,6 +32,7 @@
#include <LibWebView/MicrophoneAuthorizer.h>
#include <LibWebView/NavigationLoader.h>
#include <LibWebView/NotificationManager.h>
+#include <LibWebView/PageTranslation.h>
#include <LibWebView/PermissionManager.h>
#include <LibWebView/PictureInPictureManager.h>
#include <LibWebView/RecordingNotificationBackend.h>
@@ -2443,6 +2444,16 @@ void WebContentPage::did_request_writing_suggestion(u64 request_id, Utf16String
view().did_request_writing_suggestion({}, *this, request_id, move(text), caret_offset);
}
+void WebContentPage::did_get_translation_language_sample(u64 request_id, Web::TranslationLanguageSample sample)
+{
+ view().page_translation().did_get_language_sample({}, request_id, move(sample));
+}
+
+void WebContentPage::did_request_translation(Web::TranslationUnit unit)
+{
+ view().page_translation().did_request_translation({}, *this, move(unit));
+}
+
void WebContentPage::did_request_set_system_focus(bool has_system_focus)
{
if (!may_change_window(*this, "did_request_set_system_focus"sv))
@@ -2961,6 +2972,16 @@ void WebContentPage::did_request_spelling_menu_action_for_testing(Web::SpellingM
view().activate_spelling_menu_action_for_testing({}, *this, action, guess_index);
}
+void WebContentPage::did_request_page_translation_for_testing(String target_language)
+{
+ // NB: This translates the tab as its menu would, so only automation may ask for it.
+ if (!WebContentClient::renderers_may_synthesize_input()) {
+ client().did_misbehave("did_request_page_translation_for_testing"sv, "not driven by WebDriver or a test"sv);
+ return;
+ }
+ view().page_translation().translate_for_testing({}, move(target_language));
+}
+
void WebContentPage::did_request_link_context_menu(Web::HTML::CrossProcessId local_root_id, Gfx::IntPoint content_position, Web::HTML::PreparedNavigationDescriptor navigation, ByteString, unsigned, Optional<u64> text_fragment_generation_id)
{
auto verified_navigation = navigation_from_page(client(), move(navigation));
diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.h
index 43266466105..5ab8102291a 100644
--- a/Libraries/LibWebView/WebContentPage.h
+++ b/Libraries/LibWebView/WebContentPage.h
@@ -307,6 +307,7 @@ private:
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 did_request_page_translation_for_testing(String target_language) 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;
@@ -336,6 +337,8 @@ private:
virtual void did_request_clipboard_entries(u64 request_id) override;
virtual void did_request_spell_check(u64 request_id, Utf16String text) override;
virtual void did_request_writing_suggestion(u64 request_id, Utf16String text, u32 caret_offset) override;
+ virtual void did_get_translation_language_sample(u64 request_id, Web::TranslationLanguageSample sample) override;
+ virtual void did_request_translation(Web::TranslationUnit unit) override;
virtual void did_request_set_system_focus(bool has_system_focus) override;
virtual void did_request_set_system_visibility_state(Web::HTML::VisibilityState visibility_state) override;
virtual void did_request_navigation_start(Web::HTML::CrossProcessId navigable_id, Web::NavigationTarget target, URL::URL url, Utf16String navigation_id, Optional<Web::HTML::NavigationStartRequest> start_request) override;
diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cpp
index a73635dca0f..b66ad932179 100644
--- a/Services/WebContent/ConnectionFromClient.cpp
+++ b/Services/WebContent/ConnectionFromClient.cpp
@@ -3628,6 +3628,30 @@ void ConnectionFromClient::did_get_writing_suggestion(Web::PageId page_id, u64 r
page->page().did_get_writing_suggestion(request_id, move(suggestion));
}
+void ConnectionFromClient::request_translation_language_sample(Web::PageId page_id, u64 request_id)
+{
+ if (auto page = this->page(page_id); page.has_value())
+ async_did_get_translation_language_sample(page_id, request_id, page->page().translation_language_sample());
+}
+
+void ConnectionFromClient::start_translation(Web::PageId page_id, String source_language, String target_language)
+{
+ if (auto page = this->page(page_id); page.has_value())
+ page->page().start_translation(move(source_language), move(target_language));
+}
+
+void ConnectionFromClient::stop_translation(Web::PageId page_id)
+{
+ if (auto page = this->page(page_id); page.has_value())
+ page->page().stop_translation();
+}
+
+void ConnectionFromClient::did_translate(Web::PageId page_id, Web::TranslatedUnit unit)
+{
+ if (auto page = this->page(page_id); page.has_value())
+ page->page().did_translate(move(unit));
+}
+
void ConnectionFromClient::replace_context_menu_misspelling(Web::PageId page_id, Utf16String replacement)
{
if (auto page = this->page(page_id); page.has_value())
diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.h
index b49ea4504d4..8b876e62556 100644
--- a/Services/WebContent/ConnectionFromClient.h
+++ b/Services/WebContent/ConnectionFromClient.h
@@ -302,6 +302,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 did_get_writing_suggestion(Web::PageId page_id, u64 request_id, Optional<Web::WritingSuggestion> suggestion) override;
+ virtual void request_translation_language_sample(Web::PageId page_id, u64 request_id) override;
+ virtual void start_translation(Web::PageId page_id, String source_language, String target_language) override;
+ virtual void stop_translation(Web::PageId page_id) override;
+ virtual void did_translate(Web::PageId page_id, Web::TranslatedUnit unit) 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;
diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cpp
index d759f706701..391c72571e3 100644
--- a/Services/WebContent/PageClient.cpp
+++ b/Services/WebContent/PageClient.cpp
@@ -2135,6 +2135,16 @@ void PageClient::page_did_request_spell_check(u64 request_id, Utf16String const&
client().async_did_request_spell_check(m_id, request_id, text);
}
+void PageClient::page_did_request_translation(Web::TranslationUnit const& unit)
+{
+ client().async_did_request_translation(m_id, unit);
+}
+
+void PageClient::page_did_request_page_translation_for_testing(String const& target_language)
+{
+ client().async_did_request_page_translation_for_testing(m_id, target_language);
+}
+
void PageClient::page_did_request_writing_suggestion(u64 request_id, Utf16String const& text, u32 caret_offset)
{
client().async_did_request_writing_suggestion(m_id, request_id, text, caret_offset);
diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.h
index e58f19ffeb9..6936ff8b790 100644
--- a/Services/WebContent/PageClient.h
+++ b/Services/WebContent/PageClient.h
@@ -392,6 +392,8 @@ private:
virtual void page_did_insert_clipboard_item(Web::Clipboard::SystemClipboardItem const&, StringView presentation_style) override;
virtual void page_did_request_clipboard_entries(u64 request_id) override;
virtual void page_did_request_spell_check(u64 request_id, Utf16String const& text) override;
+ virtual void page_did_request_translation(Web::TranslationUnit const&) override;
+ virtual void page_did_request_page_translation_for_testing(String const& target_language) override;
virtual void page_did_request_writing_suggestion(u64 request_id, Utf16String const& text, u32 caret_offset) override;
virtual void page_did_request_primary_paste() override;
virtual void page_did_complete_paste_action() override;
diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipc
index 6df58c7baef..f762890ef65 100644
--- a/Services/WebContent/WebContentClient.ipc
+++ b/Services/WebContent/WebContentClient.ipc
@@ -62,6 +62,7 @@
#include <LibWebCommon/Page/PendingDialog.h>
#include <LibWebCommon/Page/ScreenWakeLockState.h>
#include <LibWebCommon/Page/SpellingError.h>
+#include <LibWebCommon/Page/Translation.h>
#include <LibWebCommon/Page/WritingSuggestion.h>
#include <LibWebCommon/ReferrerPolicy/ReferrerPolicy.h>
#include <LibWebCommon/StorageAPI/StorageAreaId.h>
@@ -263,6 +264,8 @@ endpoint WebContentClient routed by Web::PageId page_id
did_request_clipboard_entries(Web::PageId page_id, u64 request_id) =|
did_request_spell_check(Web::PageId page_id, u64 request_id, Utf16String text) =|
did_request_writing_suggestion(Web::PageId page_id, u64 request_id, Utf16String text, u32 caret_offset) =|
+ did_get_translation_language_sample(Web::PageId page_id, u64 request_id, Web::TranslationLanguageSample sample) =|
+ did_request_translation(Web::PageId page_id, Web::TranslationUnit unit) =|
did_request_primary_paste(Web::PageId page_id) =|
did_update_primary_selection(Web::PageId page_id, String text) =|
@@ -274,6 +277,7 @@ endpoint WebContentClient routed by Web::PageId page_id
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_page_translation_for_testing(Web::PageId page_id, String target_language) =|
did_request_webdriver_mouse_event(Web::PageId page_id, u64 request_id, Web::HTML::CrossProcessId local_root_id, Web::MouseEvent event) =|
did_request_pinch_event_for_testing(Web::PageId page_id, Web::HTML::CrossProcessId local_root_id, Web::PinchEvent event) =|
did_request_set_system_visibility_state(Web::PageId page_id, Web::HTML::VisibilityState visibility_state) =|
diff --git a/Services/WebContent/WebContentServer.ipc b/Services/WebContent/WebContentServer.ipc
index 5ac2415cd11..268952c326e 100644
--- a/Services/WebContent/WebContentServer.ipc
+++ b/Services/WebContent/WebContentServer.ipc
@@ -48,6 +48,7 @@
#include <LibWebCommon/Page/PageId.h>
#include <LibWebCommon/Page/PendingDialog.h>
#include <LibWebCommon/Page/SpellingError.h>
+#include <LibWebCommon/Page/Translation.h>
#include <LibWebCommon/Page/WritingSuggestion.h>
#include <LibWebCommon/Page/ViewportIsFullscreen.h>
#include <LibWebCommon/ReferrerPolicy/ReferrerPolicy.h>
@@ -308,6 +309,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) =|
did_get_writing_suggestion(Web::PageId page_id, u64 request_id, Optional<Web::WritingSuggestion> suggestion) =|
+ request_translation_language_sample(Web::PageId page_id, u64 request_id) =|
+ start_translation(Web::PageId page_id, String source_language, String target_language) =|
+ stop_translation(Web::PageId page_id) =|
+ did_translate(Web::PageId page_id, Web::TranslatedUnit unit) =|
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) =|
diff --git a/Tests/LibWeb/Text/expected/Translation/translate-page-dropped-run.txt b/Tests/LibWeb/Text/expected/Translation/translate-page-dropped-run.txt
new file mode 100644
index 00000000000..e297fb9d501
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Translation/translate-page-dropped-run.txt
@@ -0,0 +1,2 @@
+<a id="link" href="#x">Lien</a>TEXTE
+same link: true
diff --git a/Tests/LibWeb/Text/expected/Translation/translate-page-repeated-run.txt b/Tests/LibWeb/Text/expected/Translation/translate-page-repeated-run.txt
new file mode 100644
index 00000000000..1ff430c2751
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Translation/translate-page-repeated-run.txt
@@ -0,0 +1,2 @@
+<b class="word">DEUX</b>UN<b class="word">DEUX</b>
+first is the original: true
diff --git a/Tests/LibWeb/Text/expected/Translation/translate-page.txt b/Tests/LibWeb/Text/expected/Translation/translate-page.txt
new file mode 100644
index 00000000000..050ed7476ee
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Translation/translate-page.txt
@@ -0,0 +1,23 @@
+inline: ENTIER.<a id="link" href="#x">LE MONDE</a>BONJOUR
+same link: true
+kept: ICI<span translate="no">ACME</span>GARDER
+image: ICIVOIR <img id="cat" alt="UN CHAT" src="data:,">
+title attribute: UNE NOTE
+hidden: LE MENU
+shadow host: BONJOURLUMIEREICI / OMBRE
+iframe paragraph: AVANTAPRES, same window: true
+form paragraph: NOMREQUIS, input focused: true
+custom element: AVANTINTERNEAPRES, connections: 1
+code: let x = 1;
+other language: Hallo Welt
+notranslate: Ne pas traduire
+editable: Le texte
+button: ENVOYER
+named submit: Valider
+placeholder: CHERCHER
+options: LUNDI=Lundi, MARDI=2
+document.title: LES NOUVELLES
+html lang: en
+iframe: DANS LE CADRE
+added: BONSOIR
+changed: UN AUTRE TITRE
diff --git a/Tests/LibWeb/Text/input/Translation/translate-page-dropped-run.html b/Tests/LibWeb/Text/input/Translation/translate-page-dropped-run.html
new file mode 100644
index 00000000000..cf4eacf7fa1
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Translation/translate-page-dropped-run.html
@@ -0,0 +1,24 @@
+<!DOCTYPE html>
+<html lang="fr">
+<head>
+<title>Titre</title>
+<script src="../include.js"></script>
+</head>
+<body>
+<p id="paragraph"><a id="link" href="#x">Lien</a> texte</p>
+<script>
+ promiseTest(async () => {
+ document.getElementById("out").setAttribute("translate", "no");
+ const link = document.getElementById("link");
+
+ // The test translator's "x-drop" target loses the last run of each translation. The link's text is that run,
+ // so the link stays as it was, next to the text it was next to.
+ internals.translatePage("en-x-drop");
+ await internals.translationSettled();
+ const paragraph = document.getElementById("paragraph");
+ println(paragraph.innerHTML);
+ println(`same link: ${paragraph.querySelector("a") === link}`);
+ });
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/Translation/translate-page-repeated-run.html b/Tests/LibWeb/Text/input/Translation/translate-page-repeated-run.html
new file mode 100644
index 00000000000..74204084910
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Translation/translate-page-repeated-run.html
@@ -0,0 +1,24 @@
+<!DOCTYPE html>
+<html lang="fr">
+<head>
+<title>Titre</title>
+<script src="../include.js"></script>
+</head>
+<body>
+<p id="paragraph">Un <b class="word">deux</b></p>
+<script>
+ promiseTest(async () => {
+ document.getElementById("out").setAttribute("translate", "no");
+ const word = document.querySelector("b");
+
+ // The test translator's "x-repeat" target gives the first run of each translation a second time, at its end.
+ // The element that run's text came from is needed twice, so its second use is a shallow clone.
+ internals.translatePage("en-x-repeat");
+ await internals.translationSettled();
+ const paragraph = document.getElementById("paragraph");
+ println(paragraph.innerHTML);
+ println(`first is the original: ${paragraph.querySelector("b") === word}`);
+ });
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/Translation/translate-page.html b/Tests/LibWeb/Text/input/Translation/translate-page.html
new file mode 100644
index 00000000000..c521f6662d1
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Translation/translate-page.html
@@ -0,0 +1,92 @@
+<!DOCTYPE html>
+<html lang="fr">
+<head>
+<title>Les nouvelles</title>
+<script src="../include.js"></script>
+</head>
+<body>
+<p id="inline">Bonjour <a id="link" href="#x">le monde</a> entier.</p>
+<p id="kept">Garder <span translate="no">ACME</span> ici</p>
+<p id="image">Voir <img id="cat" alt="un chat" src="data:,"> ici</p>
+<p id="title-attribute" title="Une note">Le titre</p>
+<div id="hidden" hidden><p>Le menu</p></div>
+<p><span id="shadow-outer">Bonjour <span id="shadow-host">Lumiere</span> ici</span></p>
+<p id="iframe-paragraph">Avant <iframe id="inline-frame" srcdoc="<p>42</p>"></iframe> apres</p>
+<p id="form-paragraph">Nom <input id="name-input"> requis</p>
+<p id="custom-paragraph">Avant <x-light id="light">Interne</x-light> apres</p>
+<pre id="code-block"><code>let x = 1;</code></pre>
+<p id="other-language" lang="de">Hallo Welt</p>
+<p id="not-translated" class="notranslate">Ne pas traduire</p>
+<div id="editable" contenteditable>Le texte</div>
+<form>
+<input id="button" type="button" value="Envoyer">
+<input id="named-submit" type="submit" name="action" value="Valider">
+<input id="search" placeholder="Chercher">
+<select id="select"><option>Lundi</option><option value="2">Mardi</option></select>
+</form>
+<iframe id="frame" srcdoc="<html lang=fr><p>Dans le cadre</p></html>"></iframe>
+<script>
+ promiseTest(async () => {
+ document.getElementById("out").setAttribute("translate", "no");
+ const frame = document.getElementById("frame");
+ if (!frame.contentDocument?.querySelector("p"))
+ await new Promise(resolve => frame.addEventListener("load", resolve, { once: true }));
+ const inlineFrame = document.getElementById("inline-frame");
+ if (!inlineFrame.contentDocument?.querySelector("p"))
+ await new Promise(resolve => inlineFrame.addEventListener("load", resolve, { once: true }));
+ const inlineFrameWindow = inlineFrame.contentWindow;
+ customElements.define("x-light", class extends HTMLElement {
+ connectedCallback() { this.connections = (this.connections ?? 0) + 1; }
+ });
+ const nameInput = document.getElementById("name-input");
+ nameInput.focus();
+ const link = document.getElementById("link");
+ const shadowHost = document.getElementById("shadow-host");
+ shadowHost.attachShadow({ mode: "open" }).innerHTML = "<b>Ombre</b> <slot></slot>";
+
+ internals.translatePage("en");
+ await internals.translationSettled();
+
+ // The test translator reverses each unit's runs and uppercases them, so the link's text comes back in the
+ // middle, inside the same link element.
+ println(`inline: ${document.getElementById("inline").innerHTML}`);
+ println(`same link: ${document.getElementById("link") === link}`);
+ println(`kept: ${document.getElementById("kept").innerHTML}`);
+ println(`image: ${document.getElementById("image").innerHTML}`);
+ println(`title attribute: ${document.getElementById("title-attribute").title}`);
+ println(`hidden: ${document.getElementById("hidden").textContent}`);
+ // An inline element with a shadow tree has paragraphs of its own, so its light tree and its shadow tree are
+ // translated apart from the text around it.
+ println(`shadow host: ${document.getElementById("shadow-outer").textContent} / ${shadowHost.shadowRoot.textContent}`);
+ // An iframe ends a paragraph, so translating the text around it doesn't take it out of the document, which would
+ // load it again.
+ println(`iframe paragraph: ${document.getElementById("iframe-paragraph").textContent}, same window: ${inlineFrame.contentWindow === inlineFrameWindow}`);
+ // A form control and a custom element stay where they are, so the input keeps its focus, and the custom element
+ // isn't connected again.
+ println(`form paragraph: ${document.getElementById("form-paragraph").textContent}, input focused: ${document.activeElement === nameInput}`);
+ println(`custom element: ${document.getElementById("custom-paragraph").textContent}, connections: ${document.getElementById("light").connections}`);
+ println(`code: ${document.getElementById("code-block").textContent}`);
+ println(`other language: ${document.getElementById("other-language").textContent}`);
+ println(`notranslate: ${document.getElementById("not-translated").textContent}`);
+ println(`editable: ${document.getElementById("editable").textContent}`);
+ println(`button: ${document.getElementById("button").value}`);
+ println(`named submit: ${document.getElementById("named-submit").value}`);
+ println(`placeholder: ${document.getElementById("search").placeholder}`);
+ const options = document.getElementById("select").options;
+ println(`options: ${options[0].text}=${options[0].value}, ${options[1].text}=${options[1].value}`);
+ println(`document.title: ${document.title}`);
+ println(`html lang: ${document.documentElement.lang}`);
+ println(`iframe: ${frame.contentDocument.body.textContent}`);
+
+ // Text the page adds or changes after the page is translated is translated too.
+ const added = document.createElement("p");
+ added.textContent = "Bonsoir";
+ document.body.insertBefore(added, document.getElementById("out"));
+ document.getElementById("title-attribute").textContent = "Un autre titre";
+ await internals.translationSettled();
+ println(`added: ${added.textContent}`);
+ println(`changed: ${document.getElementById("title-attribute").textContent}`);
+ });
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/test-web/Application.cpp b/Tests/LibWeb/test-web/Application.cpp
index ca3ed4f2e45..7b8482d5304 100644
--- a/Tests/LibWeb/test-web/Application.cpp
+++ b/Tests/LibWeb/test-web/Application.cpp
@@ -17,6 +17,7 @@
#include <LibWebView/NotificationManager.h>
#include <LibWebView/RecordingNotificationBackend.h>
#include <LibWebView/TestSpellChecker.h>
+#include <LibWebView/TestTranslator.h>
#include <LibWebView/WebContentPage.h>
#include <errno.h>
@@ -34,6 +35,7 @@ Application::Application(Optional<ByteString> ladybird_binary_path)
quiet = true;
set_spell_checker(make<WebView::TestSpellChecker>());
+ set_translator(make<WebView::TestTranslator>());
}
Application::~Application()