Truly independent web browser
UI/Qt: Translate pages with the macOS Translation framework
sideshowbarker5a25e6b651cc
diff --git a/UI/Qt/Application.cpp b/UI/Qt/Application.cppindex 446e9e72120..42e37a7268a 100644--- a/UI/Qt/Application.cpp+++ b/UI/Qt/Application.cpp@@ -10,6 +10,7 @@#include <LibWebView/CanonicalTraversable.h>#include <LibWebView/MicrophoneAuthorizer.h>#include <LibWebView/NotificationBackend.h>+#include <LibWebView/PageTranslation.h>#if defined(AK_OS_MACOS)# include <LibWebView/MicrophoneAuthorizerMacOS.h># include <LibWebView/NotificationBackendMacOS.h>@@ -1943,6 +1944,17 @@ QMenuBar* Application::create_application_menu_bar(ForBrowserWindow for_browser_zoom_menu->addAction(zoom_in_action());zoom_menu->addAction(zoom_out_action());zoom_menu->addAction(reset_zoom_action());++ // The translation menu is the active tab's, so it's filled in as it opens.+ if (WebView::Application::the().translator()) {+ auto* translation_menu = view_menu->addMenu("&Translation");+ QObject::connect(translation_menu, &QMenu::aboutToShow, translation_menu, [translation_menu] {+ if (auto* tab = Application::the().active_tab())+ repopulate_application_menu(*translation_menu, tab->view().page_translation().translation_menu());+ else+ translation_menu->clear();+ });+ }view_menu->addSeparator();}view_menu->addMenu(create_application_menu(*view_menu, application.color_scheme_menu()));diff --git a/UI/Qt/CMakeLists.txt b/UI/Qt/CMakeLists.txtindex 54333b423a5..59140801126 100644--- a/UI/Qt/CMakeLists.txt+++ b/UI/Qt/CMakeLists.txt@@ -133,6 +133,7 @@ if (APPLE)ScrollbarPreferencesMac.mmSpellCheckerMac.mmSystemAppearanceMac.mm+ TranslateIconMac.mmWebContentViewAccessibility.mmWebContentViewMac.mm)@@ -140,9 +141,42 @@ if (APPLE)set_source_files_properties(LadybirdAccessibilityElement.mmSpellCheckerMac.mm+ TranslateIconMac.mm+ TranslatorMac.mmWebContentViewAccessibility.mmPROPERTIES COMPILE_FLAGS "-fobjc-arc")++ # The Translation framework has no Objective-C API, so the browser reaches it through a small Swift library. The+ # API it uses came in the macOS 26.4 SDK, and CMake builds Swift for one architecture at a time. So a build with an+ # older SDK, or a universal build, leaves the translator out, and the browser doesn't offer to translate pages.+ include(CheckLanguage)+ check_language(Swift)+ list(LENGTH CMAKE_OSX_ARCHITECTURES ladybird_architecture_count)+ set(ladybird_sdk "${CMAKE_OSX_SYSROOT}")+ if (NOT ladybird_sdk)+ set(ladybird_sdk macosx)+ endif()+ execute_process(COMMAND xcrun --sdk "${ladybird_sdk}" --show-sdk-version OUTPUT_VARIABLE ladybird_sdk_version OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)+ if (CMAKE_Swift_COMPILER AND ladybird_architecture_count LESS_EQUAL 1 AND ladybird_sdk_version VERSION_GREATER_EQUAL 26.4)+ set(ladybird_swift_architecture "${CMAKE_SYSTEM_PROCESSOR}")+ if (CMAKE_OSX_ARCHITECTURES)+ set(ladybird_swift_architecture "${CMAKE_OSX_ARCHITECTURES}")+ endif()+ set(CMAKE_Swift_COMPILER_TARGET "${ladybird_swift_architecture}-apple-macosx${CMAKE_OSX_DEPLOYMENT_TARGET}")+ enable_language(Swift)+ # NB: Whatever links the library keeps linking as C++, so it keeps the link options that only apply to C and C+++ # links.+ set(CMAKE_Swift_LINKER_PREFERENCE_PROPAGATES OFF)+ add_library(ladybird_translation_service STATIC TranslationServiceMac.swift)+ target_sources(ladybird_impl PRIVATE TranslatorMac.mm)+ target_link_libraries(ladybird_impl PRIVATE ladybird_translation_service "-framework NaturalLanguage")+ target_compile_definitions(ladybird_impl PUBLIC LADYBIRD_HAS_TRANSLATOR)+ # The framework only exists from macOS 15, and the browser runs on older versions without it.+ target_link_options(ladybird_impl INTERFACE "LINKER:-weak_framework,Translation")+ else()+ message(STATUS "Building without page translation, which needs Swift, the macOS 26.4 SDK, and a single architecture")+ endif()endif()if (NOT APPLE AND USE_VULKAN_DMABUF_IMAGES)diff --git a/UI/Qt/Icon.cpp b/UI/Qt/Icon.cppindex a3dbc624fe5..f40101ea56b 100644--- a/UI/Qt/Icon.cpp+++ b/UI/Qt/Icon.cpp@@ -675,6 +675,14 @@ QIcon create_site_settings_icon(QPalette const& palette, qreal knob_travel)return create_chrome_icon(ChromeIcon::SiteSettings, path, palette, ChromeStyle::WindowActivity::Active, CHROME_ICON_CANVAS_SIZE);}+#if !defined(AK_OS_MACOS)+// NB: Pages are only translated on macOS, where the system draws the icon; see TranslateIconMac.mm.+QIcon create_translate_icon(QPalette const& palette, bool)+{+ return create_chrome_icon(ChromeIcon::Globe, palette);+}+#endif+QIcon create_chrome_icon(ChromeIcon icon, QColor const& color){return QIcon(new ChromeIconEngine(icon, chrome_icon_painter_path(icon), { color, color, color, color }, CHROME_ICON_CANVAS_SIZE));diff --git a/UI/Qt/Icon.h b/UI/Qt/Icon.hindex 705efc3de14..cab606d6bc5 100644--- a/UI/Qt/Icon.h+++ b/UI/Qt/Icon.h@@ -79,6 +79,8 @@ QIcon favicon_with_rounded_corners(QIcon const&, int logical_size);QIcon create_chrome_icon(ChromeIcon, QPalette const&, ChromeStyle::WindowActivity = ChromeStyle::WindowActivity::Active, int logical_size = CHROME_ICON_CANVAS_SIZE);// The site settings icon with its two knobs moved toward each other's place, by a travel from 0 to 1.QIcon create_site_settings_icon(QPalette const&, qreal knob_travel);+// The translate button's icon, in the accent color once the page is translated.+QIcon create_translate_icon(QPalette const&, bool page_is_translated);// The icon in one color, whatever its state.QIcon create_chrome_icon(ChromeIcon, QColor const&);QPixmap create_chrome_icon_pixmap(ChromeIcon, QColor, qreal device_pixel_ratio);diff --git a/UI/Qt/LocationEdit.cpp b/UI/Qt/LocationEdit.cppindex 9209ecbe97f..ef9dfaac27f 100644--- a/UI/Qt/LocationEdit.cpp+++ b/UI/Qt/LocationEdit.cpp@@ -235,6 +235,20 @@ LocationEdit::LocationEdit(QWidget* parent, WebView::IsPrivate is_private)m_trailing_action_button->setCursor(Qt::ArrowCursor);m_trailing_action_button->hide();+ m_translate_button = new QToolButton(this);+ m_translate_button->setObjectName("LadybirdLocationTranslate");+ m_translate_button->setToolButtonStyle(Qt::ToolButtonIconOnly);+ m_translate_button->setIconSize({ 16, 16 });+ m_translate_button->setFixedSize(LOCATION_TRAILING_ACTION_WIDTH, LOCATION_TRAILING_ACTION_HEIGHT);+ m_translate_button->setAutoRaise(true);+ m_translate_button->setFocusPolicy(Qt::NoFocus);+ m_translate_button->setCursor(Qt::ArrowCursor);+ m_translate_button->hide();+ connect(m_translate_button, &QToolButton::clicked, this, [this] {+ if (on_translate_requested)+ on_translate_requested();+ });+// While the text is inline completed to a page, the page's title stands where the bookmark star does.m_completion_title = new QLabel(this);m_completion_title->setObjectName("LadybirdLocationCompletionTitle");@@ -297,7 +311,7 @@ LocationEdit::LocationEdit(QWidget* parent, WebView::IsPrivate is_private)update_trailing_item_positions();});- for (auto* button : { m_leading_icon_button, m_trailing_action_button, m_zoom_indicator_button, m_location_in_use_button })+ for (auto* button : { m_leading_icon_button, m_trailing_action_button, m_translate_button, m_zoom_indicator_button, m_location_in_use_button })button->installEventFilter(this);update_text_margins();@@ -453,6 +467,7 @@ void LocationEdit::slide_site_settings_knobs(qreal travel)void LocationEdit::update_trailing_action_visibility(){m_trailing_action_button->setVisible(m_trailing_action_button->defaultAction() && !m_is_editing_location && !m_url_is_hidden);+ update_translate_button();update_text_margins();update_trailing_item_positions();}@@ -477,6 +492,38 @@ QAction* LocationEdit::trailing_action() constreturn m_trailing_action_button->defaultAction();}+void LocationEdit::set_translate_action(QAction* action)+{+ if (m_translate_action == action)+ return;+ if (m_translate_action)+ QObject::disconnect(m_translate_action, nullptr, this, nullptr);+ m_translate_action = action;+ if (m_translate_action)+ connect(m_translate_action, &QAction::changed, this, &LocationEdit::update_translate_button);+ update_translate_button();+}++QWidget& LocationEdit::translate_button() const+{+ return *m_translate_button;+}++// Like the bookmark star, the translate button is about the page, so it stands aside while the text is being edited.+void LocationEdit::update_translate_button()+{+ auto visible = m_translate_action && m_translate_action->isVisible() && !m_is_editing_location && !m_url_is_hidden;+ if (m_translate_action) {+ m_translate_button->setIcon(m_translate_action->icon());+ m_translate_button->setToolTip(m_translate_action->toolTip());+ }+ if (m_translate_button->isHidden() != visible)+ return;+ m_translate_button->setVisible(visible);+ update_text_margins();+ update_trailing_item_positions();+}+void LocationEdit::set_zoom_action(QAction* action){if (m_zoom_action == action)@@ -884,6 +931,12 @@ void LocationEdit::update_trailing_item_positions()// NB: The items before the star are placed from the star's place, whether it shows or not.auto items_x = trailing_x;+ auto translate_button_size = m_translate_button->size();+ m_translate_button->move(items_x - translate_button_size.width(), (height() - translate_button_size.height()) / 2);+ m_translate_button->raise();+ if (!m_translate_button->isHidden())+ items_x -= translate_button_size.width();+auto completion_title_size = m_completion_title->size();m_completion_title->move(width() - LOCATION_TRAILING_EDGE_MARGIN - LOCATION_TEXT_PADDING - completion_title_size.width(), (height() - completion_title_size.height()) / 2);@@ -918,6 +971,8 @@ int LocationEdit::trailing_text_margin() constif (m_completion_title && !m_completion_title->isHidden())margin = max(margin, LOCATION_TRAILING_EDGE_MARGIN + m_completion_title->width() + LOCATION_TRAILING_ITEM_GAP);+ if (m_translate_button && !m_translate_button->isHidden())+ margin += m_translate_button->width();if (m_zoom_indicator_button && !m_zoom_indicator_button->isHidden())margin += m_zoom_indicator_button->width() + LOCATION_ZOOM_CHIP_GAP;if (m_location_in_use_button && !m_location_in_use_button->isHidden())diff --git a/UI/Qt/LocationEdit.h b/UI/Qt/LocationEdit.hindex 052e84400a5..5b28aaf4cc6 100644--- a/UI/Qt/LocationEdit.h+++ b/UI/Qt/LocationEdit.h@@ -55,6 +55,9 @@ public:// The knobs of the site settings icon slide past each other while the given popover is open.void follow_site_settings_popover(QWidget&);void set_zoom_action(QAction*);+ // The translate button stands in the field, before the bookmark star, while the page can be translated.+ void set_translate_action(QAction*);+ QWidget& translate_button() const;// Shows, while the page uses the user's location, a chip that says so.void set_location_in_use(bool);@@ -73,6 +76,8 @@ public:Function<void()> on_site_settings_requested;// Asks for the page's zoom controls, shown when the zoom level in the field is clicked.Function<void()> on_zoom_requested;+ // Asks for the page's translation menu, shown when the translate button is clicked.+ Function<void()> on_translate_requested;QWidget& trailing_action_button() const;QWidget& site_settings_button() const;Function<void(String, Optional<URL::URL>, WebView::OmniboxDestinationKind)> on_navigation;@@ -102,6 +107,7 @@ private:void update_chrome_style();void update_location_icon();void update_zoom_indicator();+ void update_translate_button();void update_location_in_use_chip();void update_focus_ring(qreal opacity);void set_field_hovered(bool);@@ -126,6 +132,8 @@ private:QVariantAnimation* m_site_settings_knob_animation { nullptr };qreal m_site_settings_knob_travel { 0 };QToolButton* m_trailing_action_button { nullptr };+ QToolButton* m_translate_button { nullptr };+ QAction* m_translate_action { nullptr };QToolButton* m_zoom_indicator_button { nullptr };QGraphicsOpacityEffect* m_zoom_indicator_opacity { nullptr };QVariantAnimation* m_zoom_indicator_fade { nullptr };diff --git a/UI/Qt/Menu.cpp b/UI/Qt/Menu.cppindex 10e6b61a76e..aacf19e3207 100644--- a/UI/Qt/Menu.cpp+++ b/UI/Qt/Menu.cpp@@ -95,6 +95,11 @@ public:}break;+ case WebView::ActionID::TranslatePage:+ if (auto* parent = as_if<QWidget>(m_action->parent()))+ m_action->setIcon(create_translate_icon(parent->palette(), action.engaged()));+ break;+default:break;}@@ -236,6 +241,10 @@ static WebView::Action::Observer& initialize_native_control(WebView::Action& actcase WebView::ActionID::ToggleBookmarksBar:qaction.setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_B));break;+ case WebView::ActionID::TranslatePage:+ if (include_action_icon == IncludeActionIcon::Yes)+ qaction.setIcon(create_translate_icon(palette, action.engaged()));+ break;case WebView::ActionID::ToggleVerticalTabsExpanded:#if defined(AK_OS_MACOS)qaction.setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_S));diff --git a/UI/Qt/Tab.cpp b/UI/Qt/Tab.cppindex e0e5556f7c4..14024ed1ea2 100644--- a/UI/Qt/Tab.cpp+++ b/UI/Qt/Tab.cpp@@ -15,6 +15,7 @@#include <LibWebCommon/HTML/SelectedFile.h>#include <LibWebView/Application.h>#include <LibWebView/MicrophoneAuthorizer.h>+#include <LibWebView/PageTranslation.h>#include <LibWebView/URL.h>#include <LibWebView/Utilities.h>#include <LibWebView/WebContentClient.h>@@ -261,6 +262,9 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)QObject::connect(bookmark_action, &QAction::triggered, this, [this] { show_bookmark_popover(); });m_location_edit->set_trailing_action(bookmark_action);m_location_edit->set_zoom_action(create_application_action(*m_location_edit, view().reset_zoom_action(), IncludeActionIcon::No));+ // The translate button shows the page's translation menu, rather than translating the page at once.+ m_translate_action = create_application_action(*m_location_edit, view().page_translation().translate_action());+ m_location_edit->set_translate_action(m_translate_action);view().on_performance_stats = [this](WebView::TabPerformanceStats const& stats) {m_performance_stats = stats;@@ -276,6 +280,9 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)m_location_edit->on_zoom_requested = [this] {show_zoom_popover();};+ m_location_edit->on_translate_requested = [this] {+ show_translation_menu();+ };QObject::connect(m_view, &WebContentView::crash_overlay_changed, this, [this] {update_tab_icon();@@ -1411,6 +1418,16 @@ void Tab::recreate_location_edit_icons()auto engaged = view().toggle_bookmark_action().engaged();action->setIcon(create_chrome_icon(engaged ? ChromeIcon::StarFilled : ChromeIcon::Star, Theme::chrome_palette(*this), ChromeStyle::window_activity(*this)));}+ if (m_translate_action)+ m_translate_action->setIcon(create_translate_icon(Theme::chrome_palette(*this), view().page_translation().is_translated()));+}++void Tab::show_translation_menu()+{+ if (!m_translation_menu)+ m_translation_menu = create_application_menu(*this, view().page_translation().translation_menu());+ auto& button = m_location_edit->translate_button();+ m_translation_menu->popup(button.mapToGlobal(QPoint { 0, button.height() }));}void Tab::show_zoom_popover()diff --git a/UI/Qt/Tab.h b/UI/Qt/Tab.hindex 9e53330f9d2..2bfd8b5205d 100644--- a/UI/Qt/Tab.h+++ b/UI/Qt/Tab.h@@ -176,6 +176,7 @@ public:void show_site_settings_popover();void refresh_site_settings_popover();void show_zoom_popover();+ void show_translation_menu();void show_bookmark_popover();void close_popovers();@@ -227,6 +228,8 @@ private:Optional<URL::Origin> m_site_settings_popover_origin;QTimer* m_content_blocking_update_timer { nullptr };QPointer<Popover> m_zoom_popover;+ QPointer<QAction> m_translate_action;+ QPointer<QMenu> m_translation_menu;QPointer<BookmarkPopover> m_bookmark_popover;QPointer<Tab> m_tab_to_activate_on_close;QPointer<LocationEdit> m_location_edit;diff --git a/UI/Qt/TranslateIconMac.mm b/UI/Qt/TranslateIconMac.mmnew file mode 100644index 00000000000..60ed5c61550--- /dev/null+++ b/UI/Qt/TranslateIconMac.mm@@ -0,0 +1,72 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <UI/Qt/ChromeStyle.h>+#include <UI/Qt/Icon.h>+#include <UI/Qt/Theme.h>++#include <QImage>+#include <QPixmap>++#import <AppKit/AppKit.h>++namespace Ladybird {++// Draws an SF Symbol in one color, centered on a square canvas of the given size.+static QPixmap system_symbol_pixmap(NSString* name, QColor const& color, int logical_size, qreal device_pixel_ratio)+{+ NSImage* symbol = [NSImage imageWithSystemSymbolName:name accessibilityDescription:nil];+ if (!symbol)+ return {};++ auto* ns_color = [NSColor colorWithSRGBRed:color.redF() green:color.greenF() blue:color.blueF() alpha:color.alphaF()];+ auto* configuration = [[NSImageSymbolConfiguration configurationWithPointSize:logical_size * 0.8 weight:NSFontWeightRegular]+ configurationByApplyingConfiguration:[NSImageSymbolConfiguration configurationWithPaletteColors:@[ ns_color ]]];+ NSImage* image = [symbol imageWithSymbolConfiguration:configuration];++ auto pixel_size = static_cast<NSInteger>(ceil(logical_size * device_pixel_ratio));+ auto* representation = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nullptr+ pixelsWide:pixel_size+ pixelsHigh:pixel_size+ bitsPerSample:8+ samplesPerPixel:4+ hasAlpha:YES+ isPlanar:NO+ colorSpaceName:NSCalibratedRGBColorSpace+ bytesPerRow:pixel_size * 4+ bitsPerPixel:32];+ representation.size = NSMakeSize(logical_size, logical_size);++ [NSGraphicsContext saveGraphicsState];+ NSGraphicsContext.currentContext = [NSGraphicsContext graphicsContextWithBitmapImageRep:representation];+ auto image_size = image.size;+ auto scale = MIN(1.0, MIN(logical_size / image_size.width, logical_size / image_size.height));+ auto width = image_size.width * scale;+ auto height = image_size.height * scale;+ [image drawInRect:NSMakeRect((logical_size - width) / 2, (logical_size - height) / 2, width, height)];+ [NSGraphicsContext restoreGraphicsState];++ QImage qimage { representation.bitmapData, static_cast<int>(pixel_size), static_cast<int>(pixel_size), static_cast<qsizetype>(representation.bytesPerRow), QImage::Format_RGBA8888_Premultiplied };+ auto pixmap = QPixmap::fromImage(qimage.copy());+ pixmap.setDevicePixelRatio(device_pixel_ratio);+ return pixmap;+}++// NB: The system's translate symbol may only be used for Apple's translation features, which this button offers.+QIcon create_translate_icon(QPalette const& palette, bool page_is_translated)+{+ auto color = page_is_translated ? ChromeStyle::chrome_accent() : Theme::chrome(palette).muted;+ QIcon icon;+ for (auto device_pixel_ratio : ICON_DEVICE_PIXEL_RATIOS) {+ if (auto pixmap = system_symbol_pixmap(@"translate", color, CHROME_ICON_CANVAS_SIZE, device_pixel_ratio); !pixmap.isNull())+ icon.addPixmap(pixmap);+ }+ if (icon.isNull())+ return create_chrome_icon(ChromeIcon::Globe, palette);+ return icon;+}++}diff --git a/UI/Qt/TranslationServiceMac.h b/UI/Qt/TranslationServiceMac.hnew file mode 100644index 00000000000..21bac208f66--- /dev/null+++ b/UI/Qt/TranslationServiceMac.h@@ -0,0 +1,44 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++// The Objective-C interface of the classes TranslationServiceMac.swift defines. The names here must match the @objc+// names there.++#import <Foundation/Foundation.h>++NS_ASSUME_NONNULL_BEGIN++typedef NS_ENUM(NSInteger, LadybirdTranslationLanguageStatus) {+ LadybirdTranslationLanguageStatusUnsupported,+ LadybirdTranslationLanguageStatusNeedsDownload,+ LadybirdTranslationLanguageStatusReady,+};++API_AVAILABLE(macos(26.4))+@interface LadybirdTranslationRun : NSObject+@property (nonatomic, readonly) NSString* text;+@property (nonatomic, readonly) uint32_t token;+@property (nonatomic, readonly) BOOL keepAsIs;+- (instancetype)initWithText:(NSString*)text token:(uint32_t)token keepAsIs:(BOOL)keepAsIs;+- (instancetype)init NS_UNAVAILABLE;+@end++API_AVAILABLE(macos(26.4))+@interface LadybirdTranslationService : NSObject++ (void)statusesFrom:(NSString*)source to:(NSArray<NSString*>*)targets completion:(void (^)(NSArray<NSNumber*>*))completion;+@end++API_AVAILABLE(macos(26.4))+@interface LadybirdTranslationSession : NSObject+- (instancetype)initWithSource:(NSString*)source target:(NSString*)target;+- (instancetype)init NS_UNAVAILABLE;+- (void)translate:(NSArray<LadybirdTranslationRun*>*)runs completion:(void (^)(NSArray<LadybirdTranslationRun*>* _Nullable))completion;+- (void)cancel;+@end++NS_ASSUME_NONNULL_ENDdiff --git a/UI/Qt/TranslationServiceMac.swift b/UI/Qt/TranslationServiceMac.swiftnew file mode 100644index 00000000000..c252d3e18e5--- /dev/null+++ b/UI/Qt/TranslationServiceMac.swift@@ -0,0 +1,153 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++// The Translation framework has no Objective-C API, so this exposes the parts the browser uses to Objective-C++. Its+// Objective-C interface is declared by hand in TranslationServiceMac.h, which must match the names given here.++import Foundation+import Translation++@available(macOS 26.4, *)+@objc(LadybirdTranslationRun)+public final class TranslationRun: NSObject {+ @objc public let text: String+ @objc public let token: UInt32+ @objc public let keepAsIs: Bool++ @objc public init(text: String, token: UInt32, keepAsIs: Bool)+ {+ self.text = text+ self.token = token+ self.keepAsIs = keepAsIs+ }+}++@available(macOS 26.4, *)+@objc(LadybirdTranslationLanguageStatus)+public enum TranslationLanguageStatus: Int {+ case unsupported+ case needsDownload+ case ready+}++// The run's token, which the translation carries over to the words that translate the run.+@available(macOS 26.4, *)+enum TranslationRunTokenKey: CodableAttributedStringKey {+ typealias Value = UInt32+ static let name = "LadybirdTranslationRunToken"+}++@available(macOS 26.4, *)+private func status(from source: Locale.Language, to target: Locale.Language) async -> TranslationLanguageStatus+{+ var status = TranslationLanguageStatus.unsupported+ for strategy in [TranslationSession.Strategy.highFidelity, .lowLatency] {+ switch await LanguageAvailability(preferredStrategy: strategy).status(from: source, to: target) {+ case .installed:+ return .ready+ case .supported:+ status = .needsDownload+ default:+ break+ }+ }+ return status+}++@available(macOS 26.4, *)+@objc(LadybirdTranslationService)+public final class TranslationService: NSObject {+ // Calls completion with one status per target, in the order given, on an arbitrary thread.+ @objc public static func statuses(from source: String, to targets: [String], completion: @escaping @Sendable ([NSNumber]) -> Void)+ {+ Task.detached {+ let source_language = Locale.Language(identifier: source)+ var statuses: [NSNumber] = []+ for target in targets {+ let target_language = Locale.Language(identifier: target)+ if source_language.languageCode == target_language.languageCode {+ statuses.append(NSNumber(value: TranslationLanguageStatus.unsupported.rawValue))+ continue+ }+ statuses.append(NSNumber(value: await status(from: source_language, to: target_language).rawValue))+ }+ completion(statuses)+ }+ }+}++// Translates from one language to another, one unit at a time, in the order the units are given.+@available(macOS 26.4, *)+@objc(LadybirdTranslationSession)+public final class TranslationSessionWrapper: NSObject {+ private let source: Locale.Language+ private let target: Locale.Language+ private let lock = NSLock()+ private var previous: Task<Void, Never>?+ private var session: TranslationSession?++ @objc public init(source: String, target: String)+ {+ self.source = Locale.Language(identifier: source)+ self.target = Locale.Language(identifier: target)+ }++ // Calls completion with the translated runs, or with nil if the unit couldn't be translated, on an arbitrary thread.+ @objc public func translate(_ runs: [TranslationRun], completion: @escaping @Sendable ([TranslationRun]?) -> Void)+ {+ lock.withLock {+ let previous = self.previous+ self.previous = Task.detached { [self] in+ await previous?.value+ completion(await translate_unit(runs))+ }+ }+ }++ @objc public func cancel()+ {+ lock.withLock { session }?.cancel()+ }++ // NB: Units are translated one after another, so only one call at a time gets here.+ private func translation_session() async -> TranslationSession+ {+ if let session = lock.withLock({ session }) {+ return session+ }++ // The Apple Intelligence models translate more fluently, so they're used wherever they're installed.+ let high_fidelity_ready = await LanguageAvailability(preferredStrategy: .highFidelity).status(from: source, to: target) == .installed+ let session = TranslationSession(installedSource: source, target: target, preferredStrategy: high_fidelity_ready ? .highFidelity : .lowLatency)+ lock.withLock { self.session = session }+ return session+ }++ private func translate_unit(_ runs: [TranslationRun]) async -> [TranslationRun]?+ {+ var source_text = AttributedString()+ for run in runs {+ var attributed_run = AttributedString(run.text)+ attributed_run[TranslationRunTokenKey.self] = run.token+ if run.keepAsIs {+ attributed_run.translation.skipsTranslation = true+ }+ source_text += attributed_run+ }++ let session = await translation_session()+ guard let response = try? await session.translate(source_text), let translated_text = response.attributedTargetText else {+ return nil+ }++ var translated_runs: [TranslationRun] = []+ for run in translated_text.runs {+ let text = String(translated_text[run.range].characters)+ translated_runs.append(TranslationRun(text: text, token: run[TranslationRunTokenKey.self] ?? 0, keepAsIs: run.translation.skipsTranslation ?? false))+ }+ return translated_runs+ }+}diff --git a/UI/Qt/TranslatorMac.h b/UI/Qt/TranslatorMac.hnew file mode 100644index 00000000000..0437649a488--- /dev/null+++ b/UI/Qt/TranslatorMac.h@@ -0,0 +1,17 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/OwnPtr.h>+#include <LibWebView/Translator.h>++namespace Ladybird {++// Nothing where the platform can't translate pages, i.e. before macOS 26.4.+OwnPtr<WebView::Translator> create_platform_translator();++}diff --git a/UI/Qt/TranslatorMac.mm b/UI/Qt/TranslatorMac.mmnew file mode 100644index 00000000000..718e69bc3a1--- /dev/null+++ b/UI/Qt/TranslatorMac.mm@@ -0,0 +1,174 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/AtomicRefCounted.h>+#include <AK/HashMap.h>+#include <AK/RefPtr.h>+#include <LibCore/EventLoop.h>+#include <UI/Qt/Conversions.h>+#include <UI/Qt/TranslationServiceMac.h>+#include <UI/Qt/TranslatorMac.h>++#import <AppKit/AppKit.h>+#import <NaturalLanguage/NaturalLanguage.h>++namespace Ladybird {++// A sample shorter than this says too little about its language, so the language the page declares decides.+static constexpr size_t minimum_detection_sample_length = 25;+// The detected language has to be more likely than this to be taken over the language the page declares.+static constexpr double minimum_detection_confidence = 0.7;++// Translations come back on an arbitrary queue. The callbacks that take them stay on the main thread, keyed by request,+// so only this atomically counted holder crosses threads.+struct PendingTranslations : public AtomicRefCounted<PendingTranslations> {+ struct Request {+ WebView::Translator::SessionId session_id { 0 };+ Function<void(Optional<Vector<Web::TranslationRun>>)> callback;+ };+ HashMap<u64, Request> requests;+ u64 next_id { 0 };+};++struct PendingTargetLanguages : public AtomicRefCounted<PendingTargetLanguages> {+ HashMap<u64, Function<void(Vector<WebView::Translator::TargetLanguage>)>> callbacks;+ u64 next_id { 0 };+};++API_AVAILABLE(macos(26.4))+static NSArray<LadybirdTranslationRun*>* ns_runs_from_runs(Vector<Web::TranslationRun> const& runs)+{+ auto* ns_runs = [NSMutableArray arrayWithCapacity:runs.size()];+ for (auto const& run : runs)+ [ns_runs addObject:[[LadybirdTranslationRun alloc] initWithText:utf16_string_to_ns_string(run.text) token:run.token keepAsIs:run.keep_as_is]];+ return ns_runs;+}++API_AVAILABLE(macos(26.4))+static Vector<Web::TranslationRun> runs_from_ns_runs(NSArray<LadybirdTranslationRun*>* ns_runs)+{+ Vector<Web::TranslationRun> runs;+ runs.ensure_capacity(ns_runs.count);+ for (LadybirdTranslationRun* run in ns_runs)+ runs.unchecked_append({ ns_string_to_utf16_string(run.text), run.token, static_cast<bool>(run.keepAsIs) });+ return runs;+}++class API_AVAILABLE(macos(26.4)) MacTranslator final : public WebView::Translator {+public:+ virtual void detect_language(Web::TranslationLanguageSample const& sample, Function<void(Optional<String>)> on_complete) override+ {+ Optional<String> detected_language;+ if (sample.text.length_in_code_units() >= minimum_detection_sample_length) {+ auto* recognizer = [[NLLanguageRecognizer alloc] init];+ [recognizer processString:utf16_string_to_ns_string(sample.text)];+ NSDictionary<NLLanguage, NSNumber*>* hypotheses = [recognizer languageHypothesesWithMaximum:1];+ for (NLLanguage language in hypotheses) {+ if (hypotheses[language].doubleValue > minimum_detection_confidence && ![language isEqualToString:NLLanguageUndetermined])+ detected_language = ns_string_to_string(language);+ }+ }+ on_complete(detected_language.has_value() ? move(detected_language) : sample.declared_language);+ }++ virtual void target_languages(String const& source_language, Vector<String> const& candidates, Function<void(Vector<TargetLanguage>)> on_complete) override+ {+ auto id = m_pending_target_languages->next_id++;+ m_pending_target_languages->callbacks.set(id, move(on_complete));+ RefPtr<PendingTargetLanguages> pending = m_pending_target_languages;+ RefPtr<Core::WeakEventLoopReference> event_loop = Core::EventLoop::current_weak();++ auto* targets = [NSMutableArray arrayWithCapacity:candidates.size()];+ for (auto const& candidate : candidates)+ [targets addObject:string_to_ns_string(candidate)];++ [LadybirdTranslationService statusesFrom:string_to_ns_string(source_language)+ to:targets+ completion:^(NSArray<NSNumber*>* statuses) {+ Vector<TargetLanguage> target_languages;+ for (NSUInteger index = 0; index < statuses.count && index < targets.count; ++index) {+ auto status = static_cast<LadybirdTranslationLanguageStatus>(statuses[index].integerValue);+ if (status == LadybirdTranslationLanguageStatusUnsupported)+ continue;+ target_languages.append({ ns_string_to_string(targets[index]), status == LadybirdTranslationLanguageStatusNeedsDownload });+ }+ auto strong_event_loop = event_loop->take();+ if (!strong_event_loop)+ return;+ strong_event_loop->deferred_invoke([pending, id, target_languages = move(target_languages)]() mutable {+ if (auto callback = pending->callbacks.take(id); callback.has_value())+ (*callback)(move(target_languages));+ });+ }];+ }++ virtual SessionId create_session(String const& source_language, String const& target_language) override+ {+ auto session_id = ++m_last_session_id;+ m_sessions.set(session_id, [[LadybirdTranslationSession alloc] initWithSource:string_to_ns_string(source_language) target:string_to_ns_string(target_language)]);+ return session_id;+ }++ virtual void close_session(SessionId session_id) override+ {+ if (auto it = m_sessions.find(session_id); it != m_sessions.end()) {+ [it->value cancel];+ m_sessions.remove(it);+ }+ m_pending_translations->requests.remove_all_matching([&](auto, auto const& request) {+ return request.session_id == session_id;+ });+ }++ virtual void translate(SessionId session_id, Web::TranslationUnit unit, Function<void(Optional<Vector<Web::TranslationRun>>)> on_complete) override+ {+ auto session = m_sessions.find(session_id);+ if (session == m_sessions.end()) {+ on_complete({});+ return;+ }++ auto id = m_pending_translations->next_id++;+ m_pending_translations->requests.set(id, { session_id, move(on_complete) });+ RefPtr<PendingTranslations> pending = m_pending_translations;+ RefPtr<Core::WeakEventLoopReference> event_loop = Core::EventLoop::current_weak();++ [session->value translate:ns_runs_from_runs(unit.runs)+ completion:^(NSArray<LadybirdTranslationRun*>* ns_runs) {+ Optional<Vector<Web::TranslationRun>> runs;+ if (ns_runs)+ runs = runs_from_ns_runs(ns_runs);+ auto strong_event_loop = event_loop->take();+ if (!strong_event_loop)+ return;+ strong_event_loop->deferred_invoke([pending, id, runs = move(runs)]() mutable {+ if (auto request = pending->requests.take(id); request.has_value())+ request->callback(move(runs));+ });+ }];+ }++ // NB: Translation languages are downloaded from the Language & Region pane.+ virtual void open_language_download_settings() override+ {+ [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"x-apple.systempreferences:com.apple.Localization-Settings.extension"]];+ }++private:+ NonnullRefPtr<PendingTranslations> m_pending_translations { adopt_ref(*new PendingTranslations) };+ NonnullRefPtr<PendingTargetLanguages> m_pending_target_languages { adopt_ref(*new PendingTargetLanguages) };+ HashMap<SessionId, LadybirdTranslationSession*> m_sessions;+ SessionId m_last_session_id { 0 };+};++OwnPtr<WebView::Translator> create_platform_translator()+{+ if (@available(macOS 26.4, *))+ return make<MacTranslator>();+ return nullptr;+}++}diff --git a/UI/Qt/main.cpp b/UI/Qt/main.cppindex 772f7ece48a..7d39a6fd10c 100644--- a/UI/Qt/main.cpp+++ b/UI/Qt/main.cpp@@ -32,6 +32,9 @@# include <UI/Qt/MacWindow.h># include <UI/Qt/SpellCheckerMac.h>#endif+#if defined(LADYBIRD_HAS_TRANSLATOR)+# include <UI/Qt/TranslatorMac.h>+#endifErrorOr<int> ladybird_main(Main::Arguments arguments){@@ -61,6 +64,9 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)Ladybird::ChromeStyle::install_application_style();#if defined(AK_OS_MACOS)app->set_spell_checker(Ladybird::create_platform_spell_checker());+#endif+#if defined(LADYBIRD_HAS_TRANSLATOR)+ app->set_translator(Ladybird::create_platform_translator());#endifif (app->should_exit_after_profile_coordination()) {outln("Opening in existing process");