Truly independent web browser
LibWebView+Hub+UI/Qt: Offer to make Ladybird the default browser
Luke Wilde0dfc63258726
diff --git a/Base/res/ladybird/about-pages/settings.html b/Base/res/ladybird/about-pages/settings.htmlindex 416c1963b45..df54754683f 100644--- a/Base/res/ladybird/about-pages/settings.html+++ b/Base/res/ladybird/about-pages/settings.html@@ -78,7 +78,8 @@flex-shrink: 0;}- .inline-container input[type="checkbox"] {+ .inline-container input[type="checkbox"],+ .inline-container > button {flex-shrink: 0;}@@ -1166,6 +1167,13 @@<h3 class="card-title">Startup</h3><div class="card"><div class="card-body">+ <div class="card-group inline-container hidden" id="default-browser-group">+ <label id="default-browser-label">+ Default browser+ <p id="default-browser-status" class="description" role="status"></p>+ </label>+ <button id="make-default-browser" class="secondary-button">Make default</button>+ </div><div class="card-group inline-container control-row"><label for="restore-previous-session">Restore previous windows and tabs</label><input id="restore-previous-session" type="checkbox" switch />diff --git a/Base/res/ladybird/about-pages/settings/startup.js b/Base/res/ladybird/about-pages/settings/startup.jsindex 396853eb07f..0307993f1fe 100644--- a/Base/res/ladybird/about-pages/settings/startup.js+++ b/Base/res/ladybird/about-pages/settings/startup.js@@ -1,8 +1,45 @@const restorePreviousSession = document.querySelector("#restore-previous-session");const newTabPageURL = document.querySelector("#new-tab-page-url");const newTabPageURLReset = document.querySelector("#new-tab-page-url-reset");+const defaultBrowserGroup = document.querySelector("#default-browser-group");+const defaultBrowserLabel = document.querySelector("#default-browser-label");+const defaultBrowserStatus = document.querySelector("#default-browser-status");+const makeDefaultBrowser = document.querySelector("#make-default-browser");++const DEFAULT_BROWSER_STATUS = {+ default: "Links from other apps open in Ladybird.",+ "not-default": "Links from other apps open in another browser.",+ unavailable: "Ladybird cannot determine or set the default browser on this system.",+};++let defaultBrowser;+// Why the last attempt to make Ladybird the default browser failed, which is shown in place of the status.+let defaultBrowserFailure = null;++const updateDefaultBrowser = () => {+ const canMakeDefault = defaultBrowser === "not-default";++ defaultBrowserGroup.classList.toggle("hidden", !defaultBrowser);+ defaultBrowserStatus.textContent = defaultBrowserFailure ?? DEFAULT_BROWSER_STATUS[defaultBrowser] ?? "";+ makeDefaultBrowser.classList.toggle("hidden", !canMakeDefault);++ // A control row is filled under the pointer, and a click anywhere on it reaches the control its label names. This+ // row is one only while there is something for the button to do.+ defaultBrowserGroup.classList.toggle("control-row", canMakeDefault);+ if (canMakeDefault) {+ defaultBrowserLabel.htmlFor = makeDefaultBrowser.id;+ } else {+ defaultBrowserLabel.removeAttribute("for");+ }+};const loadSettings = settings => {+ if (Object.hasOwn(settings, "defaultBrowser")) {+ defaultBrowser = settings.defaultBrowser;+ defaultBrowserFailure = null;+ updateDefaultBrowser();+ }+if (Object.hasOwn(settings, "restorePreviousSession")) {restorePreviousSession.checked = settings.restorePreviousSession === true;}@@ -17,6 +54,15 @@ const loadSettings = settings => {}};+// The system may ask before it changes the default browser, so the button waits for its answer.+makeDefaultBrowser.addEventListener("click", () => {+ makeDefaultBrowser.disabled = true;+ defaultBrowserFailure = null;+ updateDefaultBrowser();++ ladybird.sendMessage("makeDefaultBrowser");+});+restorePreviousSession.addEventListener("change", () => {ladybird.sendMessage("setRestorePreviousSession", restorePreviousSession.checked);});@@ -48,5 +94,9 @@ newTabPageURLReset.addEventListener("click", () => {document.addEventListener("WebUIMessage", event => {if (event.detail.name === "loadSettings") {loadSettings(event.detail.data);+ } else if (event.detail.name === "defaultBrowserResult") {+ makeDefaultBrowser.disabled = false;+ defaultBrowserFailure = event.detail.data;+ updateDefaultBrowser();}});diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cppindex 1294b1f84cf..dc04180ea1a 100644--- a/Libraries/LibWebView/Application.cpp+++ b/Libraries/LibWebView/Application.cpp@@ -60,6 +60,7 @@#include <LibWebView/HeadlessWebView.h>#include <LibWebView/HelperProcess.h>#include <LibWebView/ImageDecoderManager.h>+#include <LibWebView/NoOpDefaultBrowser.h>#include <LibWebView/NoOpMicrophoneAuthorizer.h>#include <LibWebView/NoOpNotificationBackend.h>#include <LibWebView/PageTranslation.h>@@ -83,6 +84,7 @@#include <LibWebView/WebContentClient.h>#include <LibWebView/WebDriverBiDi.h>#include <LibWebView/WebDriverBrowserConnection.h>+#include <LibWebView/WebUI/SettingsUI.h>#include <LibWebView/WebUI/SupportUI.h>#include <LibWebView/WorkerAgentManager.h>@@ -2614,6 +2616,11 @@ NonnullOwnPtr<MicrophoneAuthorizer> Application::create_microphone_authorizer()return make<NoOpMicrophoneAuthorizer>();}+NonnullOwnPtr<DefaultBrowser> Application::create_default_browser()+{+ return make<NoOpDefaultBrowser>();+}+ChildIdentity Application::add_child_process(WebView::Process&& process){return m_process_manager->add_process(move(process));@@ -3310,6 +3317,25 @@ MicrophoneAuthorizer& Application::microphone_authorizer()return *m_microphone_authorizer;}+DefaultBrowser& Application::default_browser()+{+ if (m_default_browser)+ return *m_default_browser;++ m_default_browser = create_default_browser();+ m_default_browser->on_status_change = [] {+ WebContentClient::for_each_client([](WebContentClient& client) {+ client.for_each_page([](WebContentPage& page) {+ if (auto* settings_ui = as_if<SettingsUI>(page.web_ui().ptr()))+ settings_ui->default_browser_status_changed({});+ return IterationDecision::Continue;+ });+ return IterationDecision::Continue;+ });+ };+ return *m_default_browser;+}+ErrorOr<NonnullRawPtr<Core::GeolocationProvider>> Application::ensure_geolocation_provider(){if (!m_geolocation_provider) {diff --git a/Libraries/LibWebView/Application.h b/Libraries/LibWebView/Application.hindex cd069b83ab2..c9da6f0c809 100644--- a/Libraries/LibWebView/Application.h+++ b/Libraries/LibWebView/Application.h@@ -115,6 +115,7 @@ public:Translator* translator() { return m_translator.ptr(); }void set_translator(OwnPtr<Translator>);MicrophoneAuthorizer& microphone_authorizer();+ DefaultBrowser& default_browser();static FontService& font_service() { return *the().m_font_service; }static FontServiceHost& font_service_host() { return *the().m_font_service_host; }JsonValue const& site_compatibility_data() const { return m_site_compatibility_data; }@@ -435,6 +436,7 @@ protected:virtual void create_platform_actions() { }virtual Core::EventLoop& create_platform_event_loop();virtual NonnullOwnPtr<MicrophoneAuthorizer> create_microphone_authorizer();+ virtual NonnullOwnPtr<DefaultBrowser> create_default_browser();virtual bool should_coordinate_browser_process() const { return true; }// The process that shows this browser to the user, if that is not this process.@@ -708,6 +710,7 @@ private:OwnPtr<SpellChecker> m_spell_checker;OwnPtr<Translator> m_translator;OwnPtr<MicrophoneAuthorizer> m_microphone_authorizer;+ OwnPtr<DefaultBrowser> m_default_browser;OwnPtr<Core::TimeZoneWatcher> m_time_zone_watcher;Core::EventLoop* m_event_loop { nullptr };diff --git a/Libraries/LibWebView/DefaultBrowser.h b/Libraries/LibWebView/DefaultBrowser.hnew file mode 100644index 00000000000..fd1c2df501d--- /dev/null+++ b/Libraries/LibWebView/DefaultBrowser.h@@ -0,0 +1,64 @@+/*+ * 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 <LibWebView/Export.h>++namespace WebView {++// Whether the system opens the links of other applications in this browser.+enum class DefaultBrowserStatus : u8 {+ // The system has not answered yet.+ Unknown,+ // The system cannot tell, or the browser cannot change it.+ Unavailable,+ NotDefault,+ Default,+};++// How asking the system to make this browser the default ended. A user who turns the system's question down is not a+// failure.+struct MakeDefaultBrowserResult {+ bool failed { false };+ // What the system said of the failure, in its own words, if it said anything.+ Optional<String> system_message;+};++// The last status read from the system, and the way to change it.+class WEBVIEW_API DefaultBrowser {+ AK_ALLOC_WITH_KMALLOC;++public:+ virtual ~DefaultBrowser() = default;++ DefaultBrowserStatus status() const { return m_status; }++ void did_read_status(DefaultBrowserStatus status)+ {+ if (m_status == status)+ return;+ m_status = status;+ if (on_status_change)+ on_status_change();+ }++ virtual void refresh() = 0;++ // The system may ask the user first. on_complete runs on the main thread once it has answered, possibly before+ // this returns.+ virtual void make_default(Function<void(MakeDefaultBrowserResult const&)> on_complete) = 0;++ Function<void()> on_status_change;++private:+ DefaultBrowserStatus m_status { DefaultBrowserStatus::Unknown };+};++}diff --git a/Libraries/LibWebView/Forward.h b/Libraries/LibWebView/Forward.hindex ab6016cf53e..2f6cf6b03ff 100644--- a/Libraries/LibWebView/Forward.h+++ b/Libraries/LibWebView/Forward.h@@ -35,6 +35,7 @@ class CanonicalWindow;class CompositorClient;class CompositorPresentationClient;class CookieJar;+class DefaultBrowser;class DownloadStore;class ExternalURLHandler;class FaviconStore;diff --git a/Libraries/LibWebView/NoOpDefaultBrowser.h b/Libraries/LibWebView/NoOpDefaultBrowser.hnew file mode 100644index 00000000000..19113d683f3--- /dev/null+++ b/Libraries/LibWebView/NoOpDefaultBrowser.h@@ -0,0 +1,22 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <LibWebView/DefaultBrowser.h>++namespace WebView {++// The default browser of a platform that has no way to tell or change which browser opens links.+class NoOpDefaultBrowser final : public DefaultBrowser {+public:+ NoOpDefaultBrowser() { did_read_status(DefaultBrowserStatus::Unavailable); }++ virtual void refresh() override { }+ virtual void make_default(Function<void(MakeDefaultBrowserResult const&)> on_complete) override { on_complete({ .failed = true, .system_message = {} }); }+};++}diff --git a/Libraries/LibWebView/WebUI/SettingsUI.cpp b/Libraries/LibWebView/WebUI/SettingsUI.cppindex e7259cec66f..61cacbd255c 100644--- a/Libraries/LibWebView/WebUI/SettingsUI.cpp+++ b/Libraries/LibWebView/WebUI/SettingsUI.cpp@@ -17,6 +17,7 @@#include <LibWebView/BrowsingSession.h>#include <LibWebView/CrashReport.h>#include <LibWebView/CrashReportStore.h>+#include <LibWebView/DefaultBrowser.h>#include <LibWebView/PermissionManager.h>#include <LibWebView/SearchEngine.h>#include <LibWebView/WebContentClient.h>@@ -118,6 +119,9 @@ void SettingsUI::register_interfaces()register_interface("setAppearance"sv, [this](auto const& data) {set_appearance(data);});+ register_interface("makeDefaultBrowser"sv, [this](auto const& data) {+ make_default_browser(data);+ });if (host() == "welcome"sv) {register_interface("completeFirstRun"sv, [this](auto const& data) {@@ -240,6 +244,20 @@ JsonObject SettingsUI::serialize_settings() constsettings.set("defaultNewTabPageURL"sv, Settings::default_new_tab_page_url().serialize());+ switch (Application::the().default_browser().status()) {+ case DefaultBrowserStatus::Unknown:+ break;+ case DefaultBrowserStatus::Unavailable:+ settings.set("defaultBrowser"sv, "unavailable"_string);+ break;+ case DefaultBrowserStatus::NotDefault:+ settings.set("defaultBrowser"sv, "not-default"_string);+ break;+ case DefaultBrowserStatus::Default:+ settings.set("defaultBrowser"sv, "default"_string);+ break;+ }+// The sites the user allowed or blocked, for each permission.JsonObject site_settings;site_settings.set("autoplay"sv, settings.get("autoplay"sv).value());@@ -361,6 +379,25 @@ void SettingsUI::complete_first_run(JsonValue const&)async_send_message("firstRunCompleted"sv, settings.new_tab_page_url().serialize());}+void SettingsUI::make_default_browser(JsonValue const&)+{+ Application::the().default_browser().make_default([weak_this = make_weak_ptr<SettingsUI>()](MakeDefaultBrowserResult const& result) {+ auto self = weak_this.strong_ref();+ if (!self)+ return;++ if (!result.failed) {+ self->async_send_message("defaultBrowserResult"sv, JsonValue {});+ return;+ }++ auto failure = result.system_message.has_value()+ ? MUST(String::formatted("Could not make Ladybird the default browser. The system reported: {}", *result.system_message))+ : "Could not make Ladybird the default browser. Choose it in your system settings instead."_string;+ self->async_send_message("defaultBrowserResult"sv, move(failure));+ });+}+void SettingsUI::set_new_tab_page_url(JsonValue const& new_tab_page_url){if (!new_tab_page_url.is_string())diff --git a/Libraries/LibWebView/WebUI/SettingsUI.h b/Libraries/LibWebView/WebUI/SettingsUI.hindex 534d5d46c2b..b2d83cce2e1 100644--- a/Libraries/LibWebView/WebUI/SettingsUI.h+++ b/Libraries/LibWebView/WebUI/SettingsUI.h@@ -39,6 +39,9 @@ class WEBVIEW_API SettingsUI finalWEB_UI(SettingsUI);friend class SettingsUISitePermissionsObserver;+public:+ void default_browser_status_changed(Badge<Application>) { broadcast_settings_change(); }+private:virtual void register_interfaces() override;@@ -67,6 +70,7 @@ private:void broadcast_settings_change();void complete_first_run(JsonValue const&);+ void make_default_browser(JsonValue const&);void set_new_tab_page_url(JsonValue const&);void set_restore_previous_session(JsonValue const&);diff --git a/Services/Hub/Application.cpp b/Services/Hub/Application.cppindex d46353fd4eb..672e10651ae 100644--- a/Services/Hub/Application.cpp+++ b/Services/Hub/Application.cpp@@ -355,6 +355,13 @@ Core::EventLoop& Application::create_platform_event_loop()return event_loop;}+NonnullOwnPtr<WebView::DefaultBrowser> Application::create_default_browser()+{+ if (ui_info())+ return make<DefaultBrowserInUI>();+ return WebView::Application::create_default_browser();+}+NonnullOwnPtr<WebView::MicrophoneAuthorizer> Application::create_microphone_authorizer(){// NB: The UI tells of no authorization where the system has no say over the microphone.diff --git a/Services/Hub/Application.h b/Services/Hub/Application.hindex 7d1ffbfb4b2..2f753baef28 100644--- a/Services/Hub/Application.h+++ b/Services/Hub/Application.h@@ -10,6 +10,7 @@#include <LibCore/Promise.h>#include <LibMain/Main.h>#include <LibWebView/Application.h>+#include <LibWebView/DefaultBrowser.h>#include <LibWebView/MicrophoneAuthorizer.h>#include <LibWebView/NotificationBackend.h>#include <LibWebView/PictureInPictureWindow.h>@@ -99,6 +100,7 @@ private:virtual void update_tabs_display() const override;virtual void did_clear_history_since(UnixDateTime) const override;virtual void quit_for_signal() override;+ virtual NonnullOwnPtr<WebView::DefaultBrowser> create_default_browser() override;virtual NonnullOwnPtr<WebView::MicrophoneAuthorizer> create_microphone_authorizer() override;virtual NonnullOwnPtr<WebView::NotificationBackend> create_notification_backend() override;virtual OwnPtr<WebView::MediaSessionPlatformBackend> create_media_session_platform_backend() override;diff --git a/Services/Hub/ConnectionFromUI.cpp b/Services/Hub/ConnectionFromUI.cppindex bb19812244e..51cf8cbbd95 100644--- a/Services/Hub/ConnectionFromUI.cpp+++ b/Services/Hub/ConnectionFromUI.cpp@@ -15,6 +15,7 @@#include <LibRequests/RequestClient.h>#include <LibWebView/BrowsingSession.h>#include <LibWebView/CrashReportStore.h>+#include <LibWebView/DefaultBrowser.h>#include <LibWebView/GamepadManager.h>#include <LibWebView/MicrophoneAuthorizer.h>#include <LibWebView/PageTranslation.h>@@ -287,6 +288,17 @@ void ConnectionFromUI::microphone_authorization_changed(WebView::MicrophoneAuthoauthorizer->did_change_authorization(authorization);}+void ConnectionFromUI::default_browser_status_changed(WebView::DefaultBrowserStatus status)+{+ Application::the().default_browser().did_read_status(status);+}++void ConnectionFromUI::default_browser_make_default_finished(bool failed, Optional<String> system_message)+{+ if (auto* default_browser = DefaultBrowserInUI::the())+ default_browser->did_make_default({ .failed = failed, .system_message = move(system_message) });+}+void ConnectionFromUI::gamepad_connected(Web::Gamepad::GamepadDescription description, Web::Gamepad::GamepadState state){if (auto* source = GamepadSourceInUI::the(); source && source->on_gamepad_connected)diff --git a/Services/Hub/ConnectionFromUI.h b/Services/Hub/ConnectionFromUI.hindex c0b37f75563..9c5cd613935 100644--- a/Services/Hub/ConnectionFromUI.h+++ b/Services/Hub/ConnectionFromUI.h@@ -124,6 +124,8 @@ private:virtual void geolocation_error(u64 id, Core::GeolocationError error) override;virtual void geolocation_authorization_changed(Core::GeolocationAuthorization authorization) override;virtual void microphone_authorization_changed(WebView::MicrophoneAuthorization authorization) override;+ virtual void default_browser_status_changed(WebView::DefaultBrowserStatus status) override;+ virtual void default_browser_make_default_finished(bool failed, Optional<String> system_message) override;virtual void gamepad_connected(Web::Gamepad::GamepadDescription description, Web::Gamepad::GamepadState state) override;virtual void gamepad_disconnected(u32 handle) override;virtual void gamepad_states_changed(Vector<Web::Gamepad::GamepadState> states) override;diff --git a/Services/Hub/HubClient.ipc b/Services/Hub/HubClient.ipcindex b2be55ec5dd..8eb17af6ba6 100644--- a/Services/Hub/HubClient.ipc+++ b/Services/Hub/HubClient.ipc@@ -25,6 +25,7 @@#include <LibWebCommon/HTML/SelectItem.h>#include <LibWebView/AccessibilityTreeManager.h>#include <LibWebView/ContextMenuRequest.h>+#include <LibWebView/DefaultBrowser.h>#include <LibWebView/FileDownloader.h>#include <LibWebView/HistoryVisitTransition.h>#include <LibWebView/MicrophoneAuthorizer.h>@@ -269,6 +270,7 @@ endpoint HubClienttranslator_translate(u64 request_id, u64 session_id, Web::TranslationUnit unit) =|translator_open_language_download_settings() =|microphone_request_authorization() =|+ default_browser_make_default() =|gamepad_start(bool ignore_system_gamepads) =|gamepad_set_polling(bool polling) =|gamepad_rumble(u32 handle, u16 low_frequency_magnitude, u16 high_frequency_magnitude, u32 duration_ms) =|diff --git a/Services/Hub/HubServer.ipc b/Services/Hub/HubServer.ipcindex 7645533b408..5861d57eccd 100644--- a/Services/Hub/HubServer.ipc+++ b/Services/Hub/HubServer.ipc@@ -23,6 +23,7 @@#include <LibWebCommon/Page/SpellingError.h>#include <LibWebCommon/Page/WritingSuggestion.h>#include <LibWebCommon/Clipboard/SystemClipboard.h>+#include <LibWebView/DefaultBrowser.h>#include <LibWebView/HistoryVisitTransition.h>#include <LibWebView/MicrophoneAuthorizer.h>#include <LibWebView/ProcessSnapshot.h>@@ -208,6 +209,8 @@ endpoint HubServergeolocation_error(u64 id, Core::GeolocationError error) =|geolocation_authorization_changed(Core::GeolocationAuthorization authorization) =|microphone_authorization_changed(WebView::MicrophoneAuthorization authorization) =|+ default_browser_status_changed(WebView::DefaultBrowserStatus status) =|+ default_browser_make_default_finished(bool failed, Optional<String> system_message) =|gamepad_connected(Web::Gamepad::GamepadDescription description, Web::Gamepad::GamepadState state) =|gamepad_disconnected(u32 handle) =|gamepad_states_changed(Vector<Web::Gamepad::GamepadState> states) =|diff --git a/Services/Hub/Proxies.cpp b/Services/Hub/Proxies.cppindex 3323d2a8080..f73ff8903c6 100644--- a/Services/Hub/Proxies.cpp+++ b/Services/Hub/Proxies.cpp@@ -227,6 +227,46 @@ void MicrophoneAuthorizerInUI::did_change_authorization(WebView::MicrophoneAuthoon_complete(authorization);}+static DefaultBrowserInUI* s_default_browser = nullptr;++DefaultBrowserInUI::DefaultBrowserInUI()+{+ s_default_browser = this;+}++DefaultBrowserInUI::~DefaultBrowserInUI()+{+ s_default_browser = nullptr;+}++DefaultBrowserInUI* DefaultBrowserInUI::the()+{+ return s_default_browser;+}++void DefaultBrowserInUI::make_default(Function<void(WebView::MakeDefaultBrowserResult const&)> on_complete)+{+ // With no UI to ask, nothing would ever answer, and every later request would wait behind this one.+ auto* ui = ConnectionFromUI::the();+ if (!ui) {+ on_complete({ .failed = true, .system_message = {} });+ return;+ }++ // Requests made while the system is asking share its answer.+ m_pending_requests.append(move(on_complete));+ if (m_pending_requests.size() > 1)+ return;+ ui->async_default_browser_make_default();+}++void DefaultBrowserInUI::did_make_default(WebView::MakeDefaultBrowserResult const& result)+{+ auto pending_requests = move(m_pending_requests);+ for (auto& on_complete : pending_requests)+ on_complete(result);+}+static GamepadSourceInUI* s_gamepad_source = nullptr;GamepadSourceInUI::GamepadSourceInUI()diff --git a/Services/Hub/Proxies.h b/Services/Hub/Proxies.hindex e0946ee80c3..82ad5814dfb 100644--- a/Services/Hub/Proxies.h+++ b/Services/Hub/Proxies.h@@ -11,6 +11,7 @@#include <AK/RefCounted.h>#include <Hub/View.h>#include <LibCore/GeolocationProvider.h>+#include <LibWebView/DefaultBrowser.h>#include <LibWebView/ExternalURLHandler.h>#include <LibWebView/GamepadSource.h>#include <LibWebView/MediaSessionCoordinator.h>@@ -125,6 +126,23 @@ private:Vector<Function<void(WebView::MicrophoneAuthorization)>> m_pending_requests;};+class DefaultBrowserInUI final : public WebView::DefaultBrowser {+public:+ DefaultBrowserInUI();+ virtual ~DefaultBrowserInUI() override;++ static DefaultBrowserInUI* the();++ void did_make_default(WebView::MakeDefaultBrowserResult const&);++private:+ // The UI reads the status again whenever it may have changed, and tells the Hub.+ virtual void refresh() override { }+ virtual void make_default(Function<void(WebView::MakeDefaultBrowserResult const&)> on_complete) override;++ Vector<Function<void(WebView::MakeDefaultBrowserResult const&)>> m_pending_requests;+};+class GamepadSourceInUI final : public WebView::GamepadSource {public:GamepadSourceInUI();diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txtindex a26d7f0b893..43c166c4ffa 100644--- a/Tests/LibWebView/CMakeLists.txt+++ b/Tests/LibWebView/CMakeLists.txt@@ -27,6 +27,7 @@ if (BUILD_TESTING AND NOT WIN32)ladybird_python_test(test-webdriver-bidi.py ARGS $<TARGET_FILE:WebDriver>)ladybird_python_test(test-webdriver-command-privileges.py ARGS $<TARGET_FILE:WebDriver>)ladybird_python_test(test-webdriver-content-blockers.py ARGS $<TARGET_FILE:WebDriver> TIMEOUT 180)+ ladybird_python_test(test-webdriver-default-browser.py ARGS $<TARGET_FILE:WebDriver>)ladybird_python_test(test-webdriver-delete-session.py ARGS $<TARGET_FILE:WebDriver>)ladybird_python_test(test-webdriver-element-screenshot.py ARGS $<TARGET_FILE:WebDriver>)ladybird_python_test(test-webdriver-error-keep-alive.py ARGS $<TARGET_FILE:WebDriver>)diff --git a/Tests/LibWebView/test-webdriver-default-browser.py b/Tests/LibWebView/test-webdriver-default-browser.pynew file mode 100644index 00000000000..3e3bba3aade--- /dev/null+++ b/Tests/LibWebView/test-webdriver-default-browser.py@@ -0,0 +1,181 @@+#!/usr/bin/env python3+#+# Copyright (c) 2026-present, the Ladybird developers.+#+# SPDX-License-Identifier: BSD-2-Clause++import argparse+import runpy+import subprocess+import tempfile++from pathlib import Path++helpers = runpy.run_path(str(Path(__file__).with_name("test-webdriver-delete-session.py")))++# Clicks a part of the row, and resolves with what that sent to the browser. A click that asks the browser to become+# the default waits for the browser's answer, and tells whether the button was disabled until then and after it.+CLICK = """+ const done = arguments[arguments.length - 1];+ const [target, button] = Array.from(arguments).slice(0, 2).map(selector => document.querySelector(selector));+ const sent = [];+ const sendMessage = ladybird.sendMessage;+ ladybird.sendMessage = (name, data) => {+ sent.push(name);+ sendMessage.call(ladybird, name, data);+ };+ target.click();+ ladybird.sendMessage = sendMessage;++ if (sent.length === 0) return done({sent});+ const waited = button.disabled;+ document.addEventListener('WebUIMessage', function listener(event) {+ if (event.detail.name !== 'defaultBrowserResult') return;+ document.removeEventListener('WebUIMessage', listener);+ done({sent, waited, waiting: button.disabled});+ });+"""++# What a headless browser answers, as it has no UI to ask the system.+FAILURE = "Could not make Ladybird the default browser. Choose it in your system settings instead."+++def run_test(webdriver_binary):+ with tempfile.TemporaryDirectory() as directory:+ process, port = helpers["launch_webdriver"](webdriver_binary, "--headless", "--profile-path", directory)+ session = None+ try:+ session = helpers["create_session"](port)++ def command(path, body):+ status, payload, raw = helpers["request"](port, "POST", f"/session/{session}/{path}", body)+ assert status == 200, raw+ return payload["value"]++ def script(source, *args):+ return command("execute/sync", {"script": source, "args": list(args)})++ # The page handles a message before dispatchEvent returns.+ def message(name, data):+ script(+ """+ const [name, data] = arguments;+ document.dispatchEvent(new CustomEvent('WebUIMessage', {detail: {name, data}}));+ """,+ name,+ data,+ )++ def report(status):+ message("loadSettings", {"defaultBrowser": status})++ def row(selectors):+ return script(+ """+ const [group, label, description, button] = Array.from(arguments, id => document.querySelector(id));+ return {+ shown: !group.classList.contains('hidden'),+ text: description.textContent,+ offersToMakeDefault: !button.classList.contains('hidden'),+ labelNamesButton: label.htmlFor === button.id,+ actsAsOneControl: group.classList.contains('control-row'),+ };+ """,+ selectors["group"],+ selectors["label"],+ selectors["description"],+ selectors["button"],+ )++ def click(selectors, target):+ return command("execute/async", {"script": CLICK, "args": [selectors[target], selectors["button"]]})++ settings_row = {+ "group": "#default-browser-group",+ "label": "#default-browser-label",+ "description": "#default-browser-status",+ "button": "#make-default-browser",+ }++ # A headless browser has no UI to ask the system, so the page is told that the status is unavailable.+ command("url", {"url": "about:settings#browsing"})+ command(+ "execute/async",+ {+ "script": """+ const done = arguments[0];+ const group = document.querySelector('#default-browser-group');+ if (!group.classList.contains('hidden')) return done();+ const observer = new MutationObserver(() => {+ if (group.classList.contains('hidden')) return;+ observer.disconnect();+ done();+ });+ observer.observe(group, {attributes: true, attributeFilter: ['class']});+ """,+ "args": [],+ },+ )+ assert row(settings_row) == {+ "shown": True,+ "text": "Ladybird cannot determine or set the default browser on this system.",+ "offersToMakeDefault": False,+ "labelNamesButton": False,+ "actsAsOneControl": False,+ }+ assert click(settings_row, "label") == {"sent": []}++ not_default = {+ "shown": True,+ "text": "Links from other apps open in another browser.",+ "offersToMakeDefault": True,+ "labelNamesButton": True,+ "actsAsOneControl": True,+ }+ report("not-default")+ assert row(settings_row) == not_default++ # The button waits for the browser's answer, and the row says why the browser could not do it.+ asked = {"sent": ["makeDefaultBrowser"], "waited": True, "waiting": False}+ assert click(settings_row, "label") == asked+ assert row(settings_row) == not_default | {"text": FAILURE}++ # A user who turns the system's question down is answered with no failure.+ message("defaultBrowserResult", None)+ assert row(settings_row) == not_default++ assert click(settings_row, "button") == asked+ assert row(settings_row) == not_default | {"text": FAILURE}++ report("default")+ assert row(settings_row) == {+ "shown": True,+ "text": "Links from other apps open in Ladybird.",+ "offersToMakeDefault": False,+ "labelNamesButton": False,+ "actsAsOneControl": False,+ }+ assert click(settings_row, "label") == {"sent": []}++ # A status the browser stops reporting is sent as null.+ report(None)+ assert not row(settings_row)["shown"]++ print("PASS: the settings page shows the default browser status and offers to change it")+ finally:+ try:+ if session is not None:+ helpers["request"](port, "DELETE", f"/session/{session}")+ finally:+ process.terminate()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait()+++if __name__ == "__main__":+ parser = argparse.ArgumentParser()+ parser.add_argument("webdriver_binary")+ run_test(parser.parse_args().webdriver_binary)diff --git a/UI/Qt/Application.cpp b/UI/Qt/Application.cppindex 17075529d18..297f718f534 100644--- a/UI/Qt/Application.cpp+++ b/UI/Qt/Application.cpp@@ -77,6 +77,7 @@#if defined(AK_OS_MACOS)# include <UI/Qt/ApplicationIcon.h>+# include <UI/Qt/DefaultBrowserMacOS.h># include <UI/Qt/LaunchURLsMacOS.h># include <UI/Qt/MacWindow.h># include <UI/Qt/MicrophoneAuthorizerMacOS.h>@@ -822,6 +823,7 @@ ErrorOr<void> Application::connect_to_hub(Main::Arguments const& arguments)# if defined(AK_OS_MACOS)m_spell_checker = create_platform_spell_checker();m_microphone_authorizer = make<MicrophoneAuthorizerMacOS>();+ m_default_browser = make<DefaultBrowserMacOS>();# endifIPC::MessageBuffer ui_info_buffer;@@ -1001,6 +1003,20 @@ ErrorOr<void> Application::connect_to_hub(Main::Arguments const& arguments)});}+ // The user can choose another default browser in the system settings at any time, and comes back to the browser+ // after doing it.+ if (m_default_browser) {+ m_default_browser->on_status_change = [this] {+ if (auto* hub = HubConnection::the_if_connected())+ hub->async_default_browser_status_changed(m_default_browser->status());+ };+ QObject::connect(qGuiApp, &QGuiApplication::applicationStateChanged, [this](Qt::ApplicationState state) {+ if (state == Qt::ApplicationActive)+ m_default_browser->refresh();+ });+ m_default_browser->refresh();+ }+// NB: The UI info holds the interface color scheme, which changes with the interface theme as well as with the// system's appearance. The views take it from the Hub only after this, as they update their palettes later.auto send_ui_info = [this] {diff --git a/UI/Qt/Application.h b/UI/Qt/Application.hindex 1e2866c3af8..3e4e5ddd2cd 100644--- a/UI/Qt/Application.h+++ b/UI/Qt/Application.h@@ -89,6 +89,7 @@ public:Optional<u16> devtools_port() const { return m_devtools_port; }bool has_translator() const;WebView::MicrophoneAuthorizer* microphone_authorizer() { return m_microphone_authorizer.ptr(); }+ WebView::DefaultBrowser* default_browser() { return m_default_browser.ptr(); }// The status to exit with right away, if the browser has nothing for this process to do.Optional<int> exit_status_if_done() const;ErrorOr<int> execute();@@ -351,6 +352,7 @@ private:OwnPtr<WebView::Translator> m_translator;OwnPtr<WebView::SpellChecker> m_spell_checker;OwnPtr<WebView::MicrophoneAuthorizer> m_microphone_authorizer;+ OwnPtr<WebView::DefaultBrowser> m_default_browser;OwnPtr<WebView::Settings> m_settings;#if defined(AK_OS_MACOS)OwnPtr<SoftwareUpdater> m_software_updater;diff --git a/UI/Qt/CMakeLists.txt b/UI/Qt/CMakeLists.txtindex 62575535353..da63a38e4c1 100644--- a/UI/Qt/CMakeLists.txt+++ b/UI/Qt/CMakeLists.txt@@ -143,6 +143,7 @@ if (APPLE)target_sources(ladybird_impl PRIVATEApplicationIcon.mmConversions.mm+ DefaultBrowserMacOS.mmDictionaryLookup.mmExternalURLHandler.mmLaunchURLsMacOS.cpp@@ -164,6 +165,7 @@ if (APPLE)find_package(unofficial-sparkle CONFIG REQUIRED)target_link_libraries(ladybird_impl PRIVATE Qt::GuiPrivate unofficial::sparkle::Sparkle "-framework ApplicationServices" "-framework AVFoundation" "-framework Carbon" "-framework Cocoa" "-framework CoreServices" "-framework IOSurface" "-framework QuartzCore")set_source_files_properties(+ DefaultBrowserMacOS.mmLadybirdAccessibilityElement.mmMicrophoneAuthorizerMacOS.mmPlatformColorsMac.mmdiff --git a/UI/Qt/DefaultBrowserMacOS.h b/UI/Qt/DefaultBrowserMacOS.hnew file mode 100644index 00000000000..71163708ea7--- /dev/null+++ b/UI/Qt/DefaultBrowserMacOS.h@@ -0,0 +1,36 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/NonnullRefPtr.h>+#include <AK/Vector.h>+#include <LibWebView/DefaultBrowser.h>++namespace Ladybird {++namespace Detail {++struct DefaultBrowserMacOSLink;++}++class DefaultBrowserMacOS final : public WebView::DefaultBrowser {+public:+ DefaultBrowserMacOS();+ virtual ~DefaultBrowserMacOS() override;++ virtual void refresh() override;+ virtual void make_default(Function<void(WebView::MakeDefaultBrowserResult const&)> on_complete) override;++private:+ void system_did_answer(WebView::MakeDefaultBrowserResult const&);++ NonnullRefPtr<Detail::DefaultBrowserMacOSLink> m_link;+ Vector<Function<void(WebView::MakeDefaultBrowserResult const&)>> m_pending_requests;+};++}diff --git a/UI/Qt/DefaultBrowserMacOS.mm b/UI/Qt/DefaultBrowserMacOS.mmnew file mode 100644index 00000000000..72079e8c200--- /dev/null+++ b/UI/Qt/DefaultBrowserMacOS.mm@@ -0,0 +1,149 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/AtomicRefCounted.h>+#include <AK/RefPtr.h>+#include <LibCore/EventLoop.h>+#include <UI/Qt/DefaultBrowserMacOS.h>++#import <Cocoa/Cocoa.h>+#import <CoreServices/CoreServices.h>+#import <UI/Qt/Conversions.h>++namespace Ladybird {++using WebView::DefaultBrowserStatus;+using WebView::MakeDefaultBrowserResult;++namespace Detail {++// The system answers on an arbitrary queue, possibly after the browser has quit. Only this atomically counted link+// crosses threads, and only the main thread follows it.+struct DefaultBrowserMacOSLink : public AtomicRefCounted<DefaultBrowserMacOSLink> {+ DefaultBrowserMacOS* default_browser { nullptr };+};++}++static bool opens_urls_with_scheme(NSString* scheme)+{+ auto* url = [NSURL URLWithString:[scheme stringByAppendingString:@"://"]];+ auto* handler_url = [[NSWorkspace sharedWorkspace] URLForApplicationToOpenURL:url];+ if (handler_url == nil)+ return false;++ auto* handler_identifier = [[NSBundle bundleWithURL:handler_url] bundleIdentifier];+ auto* own_identifier = [[NSBundle mainBundle] bundleIdentifier];+ if (handler_identifier == nil)+ return false;++ return [handler_identifier caseInsensitiveCompare:own_identifier] == NSOrderedSame;+}++// The system may ask the user before it changes the handler of a scheme. Asking for one scheme at a time, and stopping+// at the first error, keeps a user who turns it down from being asked again for the next scheme.+static void make_default_for_schemes(NSArray<NSString*>* schemes, NSUInteger index, void (^on_complete)(NSError*))+{+ if (index == schemes.count) {+ on_complete(nil);+ return;+ }++ [[NSWorkspace sharedWorkspace] setDefaultApplicationAtURL:[[NSBundle mainBundle] bundleURL]+ toOpenURLsWithScheme:schemes[index]+ completionHandler:^(NSError* error) {+ if (error != nil) {+ on_complete(error);+ return;+ }+ make_default_for_schemes(schemes, index + 1, on_complete);+ }];+}++// The system wraps whatever went wrong in an error about a file that could not be opened, so what it says of the+// cause is beneath that one.+static NSError* cause_of(NSError* error)+{+ while (auto* underlying_error = error.underlyingErrors.firstObject)+ error = underlying_error;+ return error;+}++static bool is_user_cancellation(NSError* error)+{+ if ([error.domain isEqualToString:NSCocoaErrorDomain])+ return error.code == NSUserCancelledError;+ if ([error.domain isEqualToString:NSOSStatusErrorDomain])+ return error.code == userCanceledErr;+ return false;+}++static MakeDefaultBrowserResult result_from_error(NSError* error)+{+ if (error == nil)+ return {};++ auto* cause = cause_of(error);+ if (is_user_cancellation(cause))+ return {};++ warnln("Unable to make Ladybird the default browser: {}", ns_string_to_string(error.description));+ return { .failed = true, .system_message = ns_string_to_string(cause.localizedDescription) };+}++DefaultBrowserMacOS::DefaultBrowserMacOS()+ : m_link(adopt_ref(*new Detail::DefaultBrowserMacOSLink))+{+ m_link->default_browser = this;+}++DefaultBrowserMacOS::~DefaultBrowserMacOS()+{+ m_link->default_browser = nullptr;+}++void DefaultBrowserMacOS::refresh()+{+ // The system knows applications by their bundles, and a browser run from outside of one has none.+ if ([[NSBundle mainBundle] bundleIdentifier] == nil) {+ did_read_status(DefaultBrowserStatus::Unavailable);+ return;+ }++ auto is_default = opens_urls_with_scheme(@"http") && opens_urls_with_scheme(@"https");+ did_read_status(is_default ? DefaultBrowserStatus::Default : DefaultBrowserStatus::NotDefault);+}++void DefaultBrowserMacOS::make_default(Function<void(MakeDefaultBrowserResult const&)> on_complete)+{+ // Requests made while the system is asking share its answer.+ m_pending_requests.append(move(on_complete));+ if (m_pending_requests.size() > 1)+ return;++ RefPtr<Detail::DefaultBrowserMacOSLink> link = m_link;+ RefPtr<Core::WeakEventLoopReference> event_loop = Core::EventLoop::current_weak();+ make_default_for_schemes(@[ @"http", @"https" ], 0, ^(NSError* error) {+ auto strong_event_loop = event_loop->take();+ if (!strong_event_loop)+ return;+ strong_event_loop->deferred_invoke([link, error] {+ if (link->default_browser)+ link->default_browser->system_did_answer(result_from_error(error));+ });+ });+}++void DefaultBrowserMacOS::system_did_answer(MakeDefaultBrowserResult const& result)+{+ refresh();++ auto pending_requests = move(m_pending_requests);+ for (auto& on_complete : pending_requests)+ on_complete(result);+}++}diff --git a/UI/Qt/HubConnection.cpp b/UI/Qt/HubConnection.cppindex 153ecb36c60..f5ce0b735fa 100644--- a/UI/Qt/HubConnection.cpp+++ b/UI/Qt/HubConnection.cpp@@ -583,6 +583,18 @@ void HubConnection::microphone_request_authorization()});}+void HubConnection::default_browser_make_default()+{+ auto* default_browser = Application::the().default_browser();+ if (!default_browser) {+ async_default_browser_make_default_finished(true, {});+ return;+ }+ default_browser->make_default([this](WebView::MakeDefaultBrowserResult const& result) {+ async_default_browser_make_default_finished(result.failed, result.system_message);+ });+}+// NB: The gamepads are read here, as the Hub links no platform input library. The Hub decides which pages learn of them.void HubConnection::gamepad_start(bool ignore_system_gamepads){diff --git a/UI/Qt/HubConnection.h b/UI/Qt/HubConnection.hindex 6d94b64da00..ec91c4845f5 100644--- a/UI/Qt/HubConnection.h+++ b/UI/Qt/HubConnection.h@@ -107,6 +107,7 @@ private:virtual void translator_translate(u64 request_id, u64 session_id, Web::TranslationUnit unit) override;virtual void translator_open_language_download_settings() override;virtual void microphone_request_authorization() override;+ virtual void default_browser_make_default() override;virtual void gamepad_start(bool ignore_system_gamepads) override;virtual void gamepad_set_polling(bool polling) override;virtual void gamepad_rumble(u32 handle, u16 low_frequency_magnitude, u16 high_frequency_magnitude, u32 duration_ms) override;