Truly independent web browser
LibWebView: Notify all open about:settings pages about setting changes
Timothy Flynnf3951da3b6fc
diff --git a/Base/res/ladybird/about-pages/settings/advanced.js b/Base/res/ladybird/about-pages/settings/advanced.jsindex 3ce81b1ce2e..c3998ed69b8 100644--- a/Base/res/ladybird/about-pages/settings/advanced.js+++ b/Base/res/ladybird/about-pages/settings/advanced.js@@ -1,6 +1,8 @@const configFilter = document.querySelector("#config-filter");const configList = document.querySelector("#config-list");+const CONFIG_VARIABLES = new Map();+function sendConfigVariableValue(variable, value) {ladybird.sendMessage("setConfigVariable", {name: variable.name,@@ -95,11 +97,26 @@ function applyFilter() {}function loadConfigVariables(settings) {- const configVariables = settings.configVariableDefinitions || [];- configList.innerHTML = "";+ if (!Object.hasOwn(settings, "configVariableDefinitions")) {+ return;+ }+ const configVariables = settings.configVariableDefinitions || [];configVariables.forEach(variable => {- configList.append(createRow(variable));+ const previous = CONFIG_VARIABLES.get(variable.name);+ if (previous && JSON.stringify(previous.value) === JSON.stringify(variable.value)) {+ return;+ }++ CONFIG_VARIABLES.set(variable.name, variable);++ const row = createRow(variable);+ const existing = document.getElementById(variable.name)?.closest(".config-row");+ if (existing) {+ existing.replaceWith(row);+ } else {+ configList.append(row);+ }});applyFilter();diff --git a/Base/res/ladybird/about-pages/settings/appearance.js b/Base/res/ladybird/about-pages/settings/appearance.jsindex 53d53a2f744..b1a560e5916 100644--- a/Base/res/ladybird/about-pages/settings/appearance.js+++ b/Base/res/ladybird/about-pages/settings/appearance.js@@ -9,6 +9,10 @@ const loadFeatures = features => {};const loadSettings = settings => {+ if (!Object.hasOwn(settings, "appearance")) {+ return;+ }+APPEARANCE = settings.appearance || {};showMenuBar.checked = !!APPEARANCE.showMenuBar;diff --git a/Base/res/ladybird/about-pages/settings/blocking.js b/Base/res/ladybird/about-pages/settings/blocking.jsindex fa07592ebba..06b7afe9966 100644--- a/Base/res/ladybird/about-pages/settings/blocking.js+++ b/Base/res/ladybird/about-pages/settings/blocking.js@@ -80,40 +80,50 @@ function loadFeatures(features) {}function loadSettings(settings) {- const contentBlockers = settings.contentBlockers;- if (!contentBlockers) {- return;- }- enableContentBlocking.checked = contentBlockers.enabled;- showContentBlockerCount.checked = contentBlockers.showBlockedCount ?? true;+ if (Object.hasOwn(settings, "contentBlockers")) {+ const contentBlockers = settings.contentBlockers;+ enableContentBlocking.checked = contentBlockers.enabled;+ showContentBlockerCount.checked = contentBlockers.showBlockedCount ?? true;- for (const container of [builtInLists, languageLists, customSubscriptions, localLists]) {- container.replaceChildren();- }- for (const list of settings.contentBlockerLists) {- const container = list.builtIn- ? list.languageSpecific- ? languageLists- : builtInLists- : list.url- ? customSubscriptions- : localLists;- container.append(createListRow(list, !list.builtIn));+ if (customFilters.value === savedCustomFilters) {+ customFilters.value = contentBlockers.customFilters;+ }++ savedCustomFilters = contentBlockers.customFilters;}- if (!customSubscriptions.children.length) showEmptyState(customSubscriptions, "No custom subscriptions added.");- if (!localLists.children.length) showEmptyState(localLists, "No local lists imported.");- if (customFilters.value === savedCustomFilters) {- customFilters.value = contentBlockers.customFilters;+ if (Object.hasOwn(settings, "contentBlockerLists")) {+ for (const container of [builtInLists, languageLists, customSubscriptions, localLists]) {+ container.replaceChildren();+ }++ for (const list of settings.contentBlockerLists) {+ const container = list.builtIn+ ? list.languageSpecific+ ? languageLists+ : builtInLists+ : list.url+ ? customSubscriptions+ : localLists;+ container.append(createListRow(list, !list.builtIn));+ }++ if (!customSubscriptions.children.length) {+ showEmptyState(customSubscriptions, "No custom subscriptions added.");+ }+ if (!localLists.children.length) {+ showEmptyState(localLists, "No local lists imported.");+ }}- savedCustomFilters = contentBlockers.customFilters;- updateLists.disabled = settings.contentBlockerListUpdateInProgress;- updateLists.innerText = settings.contentBlockerListUpdateInProgress ? "Updating…" : "Update enabled lists";+ if (Object.hasOwn(settings, "contentBlockerListUpdateInProgress")) {+ updateLists.disabled = settings.contentBlockerListUpdateInProgress;+ updateLists.innerText = settings.contentBlockerListUpdateInProgress ? "Updating…" : "Update enabled lists";- clearTimeout(updateTimer);- if (settings.contentBlockerListUpdateInProgress) {- updateTimer = setTimeout(() => ladybird.sendMessage("loadCurrentSettings"), 1000);+ clearInterval(updateTimer);+ if (settings.contentBlockerListUpdateInProgress) {+ updateTimer = setInterval(() => ladybird.sendMessage("refreshSettings"), 1000);+ }}}@@ -135,8 +145,6 @@ addSubscription.addEventListener("click", () => {});updateLists.addEventListener("click", () => {- updateLists.disabled = true;- updateLists.innerText = "Updating…";ladybird.sendMessage("updateContentBlockerLists");});diff --git a/Base/res/ladybird/about-pages/settings/browsing-behavior.js b/Base/res/ladybird/about-pages/settings/browsing-behavior.jsindex 04ca43cfa4d..600a8c01655 100644--- a/Base/res/ladybird/about-pages/settings/browsing-behavior.js+++ b/Base/res/ladybird/about-pages/settings/browsing-behavior.js@@ -9,6 +9,10 @@ const loadFeatures = features => {};const loadSettings = settings => {+ if (!Object.hasOwn(settings, "browsingBehavior")) {+ return;+ }+BROWSING_BEHAVIOR = settings.browsingBehavior || {};enableAutoscroll.checked = !!BROWSING_BEHAVIOR.enableAutoscroll;diff --git a/Base/res/ladybird/about-pages/settings/content.js b/Base/res/ladybird/about-pages/settings/content.jsindex 94e03803b7f..1b0bf72d609 100644--- a/Base/res/ladybird/about-pages/settings/content.js+++ b/Base/res/ladybird/about-pages/settings/content.js@@ -4,6 +4,10 @@ const enableForceDark = document.querySelector("#enable-force-dark");let CONTENT = {};const loadSettings = settings => {+ if (!Object.hasOwn(settings, "content")) {+ return;+ }+CONTENT = settings.content || {};const snapped = snapToClosestFactor(CONTENT.defaultZoomLevelFactor);diff --git a/Base/res/ladybird/about-pages/settings/geolocation.js b/Base/res/ladybird/about-pages/settings/geolocation.jsindex 601f41b4de4..a7998f6a853 100644--- a/Base/res/ladybird/about-pages/settings/geolocation.js+++ b/Base/res/ladybird/about-pages/settings/geolocation.js@@ -10,7 +10,12 @@ document.addEventListener("WebUIMessage", event => {return;}- if (event.detail.name !== "loadSettings") return;+ if (event.detail.name !== "loadSettings") {+ return;+ }+ if (!Object.hasOwn(event.detail.data, "geolocationEnabled")) {+ return;+ }enableGeolocation.checked = event.detail.data.geolocationEnabled === true;});diff --git a/Base/res/ladybird/about-pages/settings/languages.js b/Base/res/ladybird/about-pages/settings/languages.jsindex 296d5e2baf5..7240950736d 100644--- a/Base/res/ladybird/about-pages/settings/languages.js+++ b/Base/res/ladybird/about-pages/settings/languages.js@@ -10,6 +10,10 @@ const languagesSettings = document.querySelector("#languages-settings");let LANGUAGES = [];function loadSettings(settings) {+ if (!Object.hasOwn(settings, "languages")) {+ return;+ }+LANGUAGES = settings.languages;if (languagesDialog.open) {diff --git a/Base/res/ladybird/about-pages/settings/network.js b/Base/res/ladybird/about-pages/settings/network.jsindex e777142aa15..0a4bb815803 100644--- a/Base/res/ladybird/about-pages/settings/network.js+++ b/Base/res/ladybird/about-pages/settings/network.js@@ -11,6 +11,10 @@ const dnssecToggle = document.querySelector("#dnssec-toggle");let DNS_SETTINGS = {};function loadSettings(settings) {+ if (!Object.hasOwn(settings, "dnsSettings")) {+ return;+ }+DNS_SETTINGS = settings.dnsSettings || {};loadDnsSettings();}diff --git a/Base/res/ladybird/about-pages/settings/new-tab-page.js b/Base/res/ladybird/about-pages/settings/new-tab-page.jsindex 3d88744e70e..ae29468bc6c 100644--- a/Base/res/ladybird/about-pages/settings/new-tab-page.js+++ b/Base/res/ladybird/about-pages/settings/new-tab-page.js@@ -2,6 +2,10 @@ const newTabPageURL = document.querySelector("#new-tab-page-url");const newTabPageURLReset = document.querySelector("#new-tab-page-url-reset");const loadSettings = settings => {+ if (!Object.hasOwn(settings, "newTabPageURL")) {+ return;+ }+newTabPageURL.classList.remove("error");newTabPageURL.value = settings.newTabPageURL;};diff --git a/Base/res/ladybird/about-pages/settings/permissions.js b/Base/res/ladybird/about-pages/settings/permissions.jsindex 18ab3ad559b..1670f3d3c97 100644--- a/Base/res/ladybird/about-pages/settings/permissions.js+++ b/Base/res/ladybird/about-pages/settings/permissions.js@@ -22,6 +22,10 @@ const SITE_SETTING_POLICY_OPTIONS = {let AUTOPLAY_SETTINGS = {};function loadSiteSettings(settings) {+ if (!Object.hasOwn(settings, "autoplay")) {+ return;+ }+AUTOPLAY_SETTINGS = settings.autoplay;const siteSetting = currentSiteSetting();diff --git a/Base/res/ladybird/about-pages/settings/privacy.js b/Base/res/ladybird/about-pages/settings/privacy.jsindex 37f4cbbe844..e48c473c78b 100644--- a/Base/res/ladybird/about-pages/settings/privacy.js+++ b/Base/res/ladybird/about-pages/settings/privacy.js@@ -32,12 +32,15 @@ const GiB = MiB * 1024;let BROWSING_DATA = {};function loadSettings(settings) {- BROWSING_DATA = settings.browsingData || {};-- globalPrivacyControlToggle.checked = settings.globalPrivacyControl;+ if (Object.hasOwn(settings, "globalPrivacyControl")) {+ globalPrivacyControlToggle.checked = settings.globalPrivacyControl;+ }- showBrowsingDataSettings();- estimateBrowsingDataSizes();+ if (Object.hasOwn(settings, "browsingData")) {+ BROWSING_DATA = settings.browsingData;+ showBrowsingDataSettings();+ estimateBrowsingDataSizes();+ }}function updateBrowsingDataSizes(sizes) {diff --git a/Base/res/ladybird/about-pages/settings/search.js b/Base/res/ladybird/about-pages/settings/search.jsindex 52c0e36072d..1ff52093ab2 100644--- a/Base/res/ladybird/about-pages/settings/search.js+++ b/Base/res/ladybird/about-pages/settings/search.js@@ -162,6 +162,10 @@ document.addEventListener("WebUILoaded", () => {document.addEventListener("WebUIMessage", event => {if (event.detail.name === "loadSettings") {+ if (!Object.hasOwn(event.detail.data, "searchEngine")) {+ return;+ }+SEARCH_ENGINE = event.detail.data.searchEngine || {};renderEngineSettings();} else if (event.detail.name === "loadEngines") {diff --git a/Base/res/ladybird/about-pages/settings/services.js b/Base/res/ladybird/about-pages/settings/services.jsindex 3107241a532..032ae6dda2a 100644--- a/Base/res/ladybird/about-pages/settings/services.js+++ b/Base/res/ladybird/about-pages/settings/services.js@@ -9,7 +9,13 @@ filterListUpdates.addEventListener("change", () => {});document.addEventListener("WebUIMessage", event => {- if (event.detail.name !== "loadSettings") return;+ if (event.detail.name !== "loadSettings") {+ return;+ }+ if (!Object.hasOwn(event.detail.data, "backgroundNetworking")) {+ return;+ }+const settings = event.detail.data.backgroundNetworking;allowServicesNetworkAccess.checked = settings.enabled;filterListUpdates.checked = settings.features.contentBlockerSubscriptionUpdates;diff --git a/Base/res/ladybird/about-pages/settings/tabs.js b/Base/res/ladybird/about-pages/settings/tabs.jsindex 6f89b60c2e3..a28efd96207 100644--- a/Base/res/ladybird/about-pages/settings/tabs.js+++ b/Base/res/ladybird/about-pages/settings/tabs.js@@ -17,6 +17,10 @@ const updateVerticalTabsDependentSettings = () => {};const loadSettings = settings => {+ if (!Object.hasOwn(settings, "tabs")) {+ return;+ }+TAB_SETTINGS = settings.tabs || {};enableVerticalTabs.checked = !!TAB_SETTINGS.verticalTabsEnabled;diff --git a/Base/res/ladybird/about-pages/welcome.js b/Base/res/ladybird/about-pages/welcome.jsindex ecc75c91603..8d97c79c1d2 100644--- a/Base/res/ladybird/about-pages/welcome.js+++ b/Base/res/ladybird/about-pages/welcome.js@@ -131,14 +131,46 @@ document.addEventListener("WebUILoaded", () => {document.addEventListener("WebUIMessage", event => {const { name, data } = event.detail;- if (name === "loadSettings") settings = data;- else if (name === "loadEngines") engines = data;- else if (name === "loadFeatures") features = data;- else if (name === "firstRunCompleted") location.replace(data);- else if (name === "firstRunError") {++ if (name === "loadSettings") {+ settings = { ...settings, ...data };++ if (initialized) {+ if (Object.hasOwn(data, "tabs")) {+ const mode = settings.tabs.verticalTabsEnabled ? "vertical" : "horizontal";+ document.querySelector(`input[name="tab-mode"][value="${mode}"]`).checked = true;+ }+ if (Object.hasOwn(data, "searchEngine")) {+ populateSearchEngineSelect(searchEngine, engines.search, settings.searchEngine);+ searchSuggestions.checked = settings.searchEngine.suggestions;+ updateSearchSuggestionsControl(searchEngine, searchSuggestions, searchSuggestionsDescription);+ }+ if (Object.hasOwn(data, "contentBlockers")) {+ enableContentBlocking.checked = settings.contentBlockers.enabled;+ updateBlockingOptions();+ }+ if (Object.hasOwn(data, "contentBlockerLists")) {+ for (const checkbox of contentBlockerLists.querySelectorAll("input")) {+ const list = settings.contentBlockerLists.find(+ list => list.identifier === checkbox.dataset.identifier+ );+ if (list) {+ checkbox.checked = list.enabled;+ }+ }+ }+ }+ } else if (name === "loadEngines") {+ engines = data;+ } else if (name === "loadFeatures") {+ features = data;+ } else if (name === "firstRunCompleted") {+ location.replace(data);+ } else if (name === "firstRunError") {saveStatus.textContent = data;setupOptions.disabled = false;startBrowsing.disabled = false;}+initialize();});diff --git a/Libraries/LibWebView/Settings.cpp b/Libraries/LibWebView/Settings.cppindex 812c3793b4b..ccce1fb3cf6 100644--- a/Libraries/LibWebView/Settings.cpp+++ b/Libraries/LibWebView/Settings.cpp@@ -1010,6 +1010,9 @@ void Settings::add_custom_search_engine(SearchEngine search_engine)m_custom_search_engines.append(move(search_engine));persist_settings();++ for (auto& observer : m_observers)+ observer.search_engine_settings_changed();}void Settings::remove_custom_search_engine(SearchEngine const& search_engine)@@ -1024,10 +1027,8 @@ void Settings::remove_custom_search_engine(SearchEngine const& search_engine)persist_settings();- if (reset_default_search_engine) {- for (auto& observer : m_observers)- observer.search_engine_settings_changed();- }+ for (auto& observer : m_observers)+ observer.search_engine_settings_changed();}Optional<SearchEngine> Settings::find_search_engine_by_name(StringView name) constdiff --git a/Libraries/LibWebView/WebUI/SettingsUI.cpp b/Libraries/LibWebView/WebUI/SettingsUI.cppindex f59c63991eb..a7d77828968 100644--- a/Libraries/LibWebView/WebUI/SettingsUI.cpp+++ b/Libraries/LibWebView/WebUI/SettingsUI.cpp@@ -7,6 +7,7 @@#include <AK/JsonArray.h>#include <AK/Platform.h>#include <AK/Utf16String.h>+#include <LibCore/EventLoop.h>#include <LibCore/GeolocationProvider.h>#include <LibCore/Promise.h>#include <LibURL/Parser.h>@@ -56,6 +57,9 @@ void SettingsUI::register_interfaces()register_interface("loadCurrentSettings"sv, [this](auto const&) {load_current_settings();});+ register_interface("refreshSettings"sv, [this](auto const&) {+ broadcast_settings_change();+ });register_interface("loadAvailableEngines"sv, [this](auto const&) {load_available_engines();});@@ -191,7 +195,7 @@ void SettingsUI::load_features()async_send_message("loadFeatures"sv, move(features));}-void SettingsUI::load_current_settings()+JsonObject SettingsUI::serialize_settings() const{auto settings = Application::settings().serialize_json();@@ -232,7 +236,46 @@ void SettingsUI::load_current_settings()settings.as_object().set("contentBlockerLists"sv, move(lists));settings.as_object().set("contentBlockerListUpdateInProgress"sv, Application::the().content_blocker_list_update_in_progress());- async_send_message("loadSettings"sv, settings);+ return move(settings.as_object());+}++void SettingsUI::load_current_settings()+{+ m_current_settings = serialize_settings();+ async_send_message("loadSettings"sv, *m_current_settings);+}++void SettingsUI::broadcast_settings_change()+{+ if (!m_current_settings.has_value() || m_settings_change_scheduled)+ return;+ m_settings_change_scheduled = true;++ // Defer to allow the current handler to finish, including any downloads started after changing a setting.+ Core::deferred_invoke([weak_this = make_weak_ptr<SettingsUI>()] {+ auto* self = weak_this.ptr();+ if (!self)+ return;++ auto settings = self->serialize_settings();+ JsonObject changes;++ settings.for_each_member([&](auto const& name, auto const& value) {+ auto previous = self->m_current_settings->get(name);+ if (!previous.has_value() || !previous->equals(value))+ changes.set(name, value);+ });++ self->m_current_settings->for_each_member([&](auto const& name, auto const&) {+ if (!settings.has(name))+ changes.set(name, JsonValue {});+ });+ self->m_current_settings = move(settings);+ self->m_settings_change_scheduled = false;++ if (!changes.is_empty())+ self->async_send_message("loadSettings"sv, changes);+ });}void SettingsUI::complete_first_run(JsonValue const&)@@ -263,16 +306,12 @@ void SettingsUI::set_languages(JsonValue const& languages){auto parsed_languages = Settings::parse_json_languages(languages);Application::settings().set_languages(move(parsed_languages));-- load_current_settings();}void SettingsUI::set_appearance(JsonValue const& appearance){auto parsed_appearance = Settings::parse_appearance(appearance);Application::settings().set_appearance(parsed_appearance);-- load_current_settings();}void SettingsUI::set_content_settings(JsonValue const& content_settings)@@ -285,7 +324,6 @@ void SettingsUI::set_content_settings(JsonValue const& content_settings)parsed_content_settings.zoom_per_host = current_content_settings.zoom_per_host;Application::settings().set_content_settings(move(parsed_content_settings));- load_current_settings();}void SettingsUI::set_tab_settings(JsonValue const& tab_settings)@@ -299,15 +337,12 @@ void SettingsUI::set_tab_settings(JsonValue const& tab_settings)parsed_tab_settings.vertical_tabs_expanded_width = current_tab_settings.vertical_tabs_expanded_width;settings.set_tab_settings(parsed_tab_settings);- load_current_settings();}void SettingsUI::set_browsing_behavior(JsonValue const& browsing_behavior){auto parsed_browsing_behavior = Settings::parse_browsing_behavior(browsing_behavior);Application::settings().set_browsing_behavior(parsed_browsing_behavior);-- load_current_settings();}void SettingsUI::set_config_variable(JsonValue const& variable)@@ -321,8 +356,6 @@ void SettingsUI::set_config_variable(JsonValue const& variable)return;Application::settings().set_config_variable(*name, *value);-- load_current_settings();}void SettingsUI::load_available_engines()@@ -357,23 +390,18 @@ void SettingsUI::set_search_engine_settings(JsonValue const& data)search_engine_settings.engine = settings.find_search_engine_by_name(engine->as_string());search_engine_settings.suggestions = *suggestions;settings.set_search_engine_settings(move(search_engine_settings));- load_current_settings();}void SettingsUI::add_custom_search_engine(JsonValue const& search_engine){if (auto custom_engine = Settings::parse_custom_search_engine(search_engine); custom_engine.has_value())Application::settings().add_custom_search_engine(custom_engine.release_value());-- load_current_settings();}void SettingsUI::remove_custom_search_engine(JsonValue const& search_engine){if (auto custom_engine = Settings::parse_custom_search_engine(search_engine); custom_engine.has_value())Application::settings().remove_custom_search_engine(*custom_engine);-- load_current_settings();}enum class SiteSettingType {@@ -430,8 +458,6 @@ void SettingsUI::set_site_setting_policy(JsonValue const& site_setting)Application::settings().set_autoplay_policy(*parsed);break;}-- load_current_settings();}void SettingsUI::add_site_setting_filter(JsonValue const& site_setting)@@ -449,8 +475,6 @@ void SettingsUI::add_site_setting_filter(JsonValue const& site_setting)Application::settings().add_autoplay_site_filter(*filter);break;}-- load_current_settings();}void SettingsUI::remove_site_setting_filter(JsonValue const& site_setting)@@ -468,8 +492,6 @@ void SettingsUI::remove_site_setting_filter(JsonValue const& site_setting)Application::settings().remove_autoplay_site_filter(*filter);break;}-- load_current_settings();}void SettingsUI::remove_all_site_setting_filters(JsonValue const& site_setting)@@ -483,8 +505,6 @@ void SettingsUI::remove_all_site_setting_filters(JsonValue const& site_setting)Application::settings().remove_all_autoplay_site_filters();break;}-- load_current_settings();}void SettingsUI::set_geolocation_enabled(JsonValue const& enabled)@@ -493,7 +513,6 @@ void SettingsUI::set_geolocation_enabled(JsonValue const& enabled)return;Application::settings().set_geolocation_enabled(enabled.as_bool());- load_current_settings();}void SettingsUI::estimate_browsing_data_sizes(JsonValue const& options)@@ -530,7 +549,6 @@ void SettingsUI::estimate_browsing_data_sizes(JsonValue const& options)void SettingsUI::set_browsing_data_settings(JsonValue const& settings){Application::settings().set_browsing_data_settings(Settings::parse_browsing_data_settings(settings));- load_current_settings();}void SettingsUI::clear_browsing_data(JsonValue const& options)@@ -585,7 +603,6 @@ void SettingsUI::set_services_network_access_enabled(JsonValue const& enabled)return;Application::settings().set_background_networking_enabled(enabled.as_bool());- load_current_settings();}void SettingsUI::set_filter_list_updates_enabled(JsonValue const& enabled)@@ -594,27 +611,27 @@ void SettingsUI::set_filter_list_updates_enabled(JsonValue const& enabled)return;Application::settings().set_filter_list_updates_enabled(enabled.as_bool());- load_current_settings();}void SettingsUI::update_content_blocker_lists(JsonValue const&){Application::the().update_content_blocker_lists({});- load_current_settings();+ broadcast_settings_change();}void SettingsUI::set_content_blocker_enabled(JsonValue const& enabled){if (!enabled.is_bool())return;+Application::settings().set_content_blocker_enabled(enabled.as_bool());+if (enabled.as_bool()) {for (auto const& list : Application::settings().content_blocker_lists()) {if (list.enabled)Application::the().download_content_blocker_list_if_needed({}, list.identifier);}}- load_current_settings();}void SettingsUI::set_show_content_blocker_count(JsonValue const& show)@@ -623,7 +640,6 @@ void SettingsUI::set_show_content_blocker_count(JsonValue const& show)return;Application::settings().set_show_content_blocker_count(show.as_bool());- load_current_settings();}void SettingsUI::set_content_blocker_list_enabled(JsonValue const& value)@@ -639,7 +655,6 @@ void SettingsUI::set_content_blocker_list_enabled(JsonValue const& value)Application::settings().set_content_blocker_list_enabled(*identifier, *enabled);if (*enabled && Application::settings().content_blocker_enabled())Application::the().download_content_blocker_list_if_needed({}, *identifier);- load_current_settings();}void SettingsUI::add_custom_content_blocker_subscription(JsonValue const& value)@@ -656,7 +671,6 @@ void SettingsUI::add_custom_content_blocker_subscription(JsonValue const& value)for (auto const& subscription : Application::settings().content_blocker_lists()) {if (!subscription.built_in && subscription.url == url) {report_content_blocker_result("subscription"_string, "Subscription already added."_string);- load_current_settings();return;}}@@ -664,7 +678,6 @@ void SettingsUI::add_custom_content_blocker_subscription(JsonValue const& value)auto identifier = Application::settings().add_content_blocker_list(url->serialize(), url);Application::the().download_content_blocker_list_if_needed({}, identifier);report_content_blocker_result("subscription"_string, "Subscription added."_string);- load_current_settings();}void SettingsUI::remove_content_blocker_list(JsonValue const& value)@@ -673,7 +686,6 @@ void SettingsUI::remove_content_blocker_list(JsonValue const& value)return;Application::the().remove_content_blocker_list({}, value.as_string());- load_current_settings();}void SettingsUI::import_local_content_blocker_list(JsonValue const& value)@@ -690,8 +702,6 @@ void SettingsUI::import_local_content_blocker_list(JsonValue const& value)report_content_blocker_result("import"_string, MUST(String::formatted("Unable to import list: {}", result.error())));elsereport_content_blocker_result("import"_string, MUST(String::formatted("{} imported.", *name)));-- load_current_settings();}void SettingsUI::set_custom_content_blocker_filters(JsonValue const& value)@@ -700,7 +710,6 @@ void SettingsUI::set_custom_content_blocker_filters(JsonValue const& value)return;Application::settings().set_custom_content_blocker_filters(value.as_string());- load_current_settings();}void SettingsUI::report_content_blocker_result(String operation, String message)@@ -714,7 +723,6 @@ void SettingsUI::report_content_blocker_result(String operation, String message)void SettingsUI::set_dns_settings(JsonValue const& dns_settings){Application::settings().set_dns_settings(Settings::parse_dns_settings(dns_settings));- load_current_settings();}}diff --git a/Libraries/LibWebView/WebUI/SettingsUI.h b/Libraries/LibWebView/WebUI/SettingsUI.hindex 897c631a6e1..416a9701d0e 100644--- a/Libraries/LibWebView/WebUI/SettingsUI.h+++ b/Libraries/LibWebView/WebUI/SettingsUI.h@@ -6,19 +6,44 @@#pragma once+#include <AK/JsonObject.h>#include <LibWebView/Forward.h>+#include <LibWebView/Settings.h>#include <LibWebView/WebUI.h>namespace WebView {-class WEBVIEW_API SettingsUI : public WebUI {+class WEBVIEW_API SettingsUI final+ : public WebUI+ , public SettingsObserver {WEB_UI(SettingsUI);private:virtual void register_interfaces() override;+ virtual void new_tab_page_url_changed() override { broadcast_settings_change(); }+ virtual void languages_changed() override { broadcast_settings_change(); }+ virtual void appearance_changed() override { broadcast_settings_change(); }+ virtual void content_settings_changed() override { broadcast_settings_change(); }+ virtual void tab_settings_changed() override { broadcast_settings_change(); }+ virtual void browsing_behavior_changed() override { broadcast_settings_change(); }+ virtual void search_engine_settings_changed() override { broadcast_settings_change(); }+ virtual void autoplay_settings_changed() override { broadcast_settings_change(); }+ virtual void browsing_data_settings_changed() override { broadcast_settings_change(); }+ virtual void global_privacy_control_changed() override { broadcast_settings_change(); }+ virtual void dns_settings_changed() override { broadcast_settings_change(); }+ virtual void config_variable_changed(ConfigVariableID) override { broadcast_settings_change(); }+ virtual void geolocation_settings_changed() override { broadcast_settings_change(); }+ virtual void background_networking_settings_changed() override { broadcast_settings_change(); }+ virtual void content_blocker_settings_changed() override { broadcast_settings_change(); }+ virtual void content_blocker_count_visibility_changed() override { broadcast_settings_change(); }+void load_features();++ JsonObject serialize_settings() const;void load_current_settings();+ void broadcast_settings_change();+void complete_first_run(JsonValue const&);void set_new_tab_page_url(JsonValue const&);@@ -59,6 +84,9 @@ private:void report_content_blocker_result(String operation, String message);void set_dns_settings(JsonValue const&);++ Optional<JsonObject> m_current_settings;+ bool m_settings_change_scheduled { false };};}diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txtindex 696f4bf7589..ca8959399e5 100644--- a/Tests/LibWebView/CMakeLists.txt+++ b/Tests/LibWebView/CMakeLists.txt@@ -351,6 +351,12 @@ if (BUILD_TESTING AND NOT WIN32))set_tests_properties(TestWebDriverSearchEngineSettings PROPERTIES TIMEOUT 120)+ add_test(+ NAME TestWebDriverSettingsChanges+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test-webdriver-settings-changes.py $<TARGET_FILE:WebDriver>+ )+ set_tests_properties(TestWebDriverSettingsChanges PROPERTIES TIMEOUT 120)+add_test(NAME TestWebDriverSessionHistoryCOMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test-webdriver-session-history.py $<TARGET_FILE:WebDriver>diff --git a/Tests/LibWebView/test-webdriver-content-blockers.py b/Tests/LibWebView/test-webdriver-content-blockers.pyindex 319656a2895..062bd6a4d42 100755--- a/Tests/LibWebView/test-webdriver-content-blockers.py+++ b/Tests/LibWebView/test-webdriver-content-blockers.py@@ -98,6 +98,8 @@ with tempfile.TemporaryDirectory() as directory:const [name, data, waitForIdle, done] = arguments;const receive = event => {if (event.detail.name !== 'loadSettings') return;+ // Wait for the requested full snapshot rather than a partial broadcast.+ if (!Object.hasOwn(event.detail.data, 'firstRunComplete')) return;if (waitForIdle && event.detail.data.contentBlockerListUpdateInProgress) {setTimeout(() => ladybird.sendMessage('loadCurrentSettings'), 50);return;@@ -107,6 +109,7 @@ with tempfile.TemporaryDirectory() as directory:};document.addEventListener('WebUIMessage', receive);ladybird.sendMessage(name, data);+ if (name !== 'loadCurrentSettings') ladybird.sendMessage('loadCurrentSettings');""","args": [name, data, wait_for_idle],},diff --git a/Tests/LibWebView/test-webdriver-search-engine-settings.py b/Tests/LibWebView/test-webdriver-search-engine-settings.pyindex 852fd18b294..95b621c8abf 100755--- a/Tests/LibWebView/test-webdriver-search-engine-settings.py+++ b/Tests/LibWebView/test-webdriver-search-engine-settings.py@@ -62,6 +62,7 @@ def run_test(webdriver_binary, graphical):const done = parameters.pop();document.addEventListener('WebUIMessage', function listener(event) {{if (event.detail.name !== 'loadSettings') return;+ if (!Object.hasOwn(event.detail.data, 'searchEngine')) return;const settings = event.detail.data;if (!({condition})) return;document.removeEventListener('WebUIMessage', listener);diff --git a/Tests/LibWebView/test-webdriver-settings-changes.py b/Tests/LibWebView/test-webdriver-settings-changes.pynew file mode 100644index 00000000000..d277cdf6fbf--- /dev/null+++ b/Tests/LibWebView/test-webdriver-settings-changes.py@@ -0,0 +1,215 @@+#!/usr/bin/env python3+#+# Copyright (c) 2026-present, the Ladybird developers.+#+# SPDX-License-Identifier: BSD-2-Clause++import argparse+import http.server+import json+import runpy+import subprocess+import tempfile+import threading++from pathlib import Path++helpers = runpy.run_path(str(Path(__file__).with_name("test-webdriver-delete-session.py")))+++def run_test(webdriver_binary):+ release_download = threading.Event()++ class Handler(http.server.BaseHTTPRequestHandler):+ def do_GET(self):+ release_download.wait(30)+ self.send_response(200)+ self.end_headers()+ self.wfile.write(b"! Test filter list\n")++ def log_message(self, format, *args):+ pass++ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ threading.Thread(target=server.serve_forever, daemon=True).start()++ with tempfile.TemporaryDirectory() as directory:+ config = Path(directory) / "config"+ config.mkdir()+ (config / "Settings.json").write_text(json.dumps({"contentBlockers": {"enabled": True}}))+ port = helpers["unused_port"]()+ process = subprocess.Popen(+ [webdriver_binary, "--headless", "-l", "127.0.0.1", "-p", str(port), "--profile-path", directory]+ )+ session = None+ try:+ helpers["wait_for_port"](port)+ 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)})++ def change(name, data):+ return command(+ "execute/async",+ {+ "script": """+ const [name, data, done] = arguments;+ document.addEventListener('WebUIMessage', function listener(event) {+ if (event.detail.name !== 'loadSettings') return;+ document.removeEventListener('WebUIMessage', listener);+ done(event.detail.data);+ });+ ladybird.sendMessage(name, data);+ """,+ "args": [name, data],+ },+ )++ command("url", {"url": "about:settings#advanced"})+ command(+ "execute/async",+ {+ "script": """+ const done = arguments[0];+ function ready() { return document.querySelector('#config-list input[type=number]'); }+ if (ready()) return done();+ const observer = new MutationObserver(() => {+ if (!ready()) return;+ observer.disconnect();+ done();+ });+ observer.observe(document.documentElement, {childList: true, subtree: true});+ """,+ "args": [],+ },+ )+ script("""+ window.draftInput = document.querySelector('#config-list input[type=number]');+ draftInput.value = '999';+ draftInput.focus();+ document.querySelector('#dns-server').value = 'unfinished.example';+ """)++ changes = change("setAppearance", {"showBookmarksBar": "never"})+ assert set(changes) == {"appearance"}, changes+ assert changes["appearance"]["showBookmarksBar"] == "never"+ assert script("""+ return draftInput === document.getElementById(draftInput.id)+ && draftInput === document.activeElement && draftInput.value === '999'+ && document.querySelector('#dns-server').value === 'unfinished.example';+ """), "An unrelated update replaced an unfinished edit"++ # No enabled lists means no download starts, and no loadSettings message is needed.+ assert command(+ "execute/async",+ {+ "script": """+ const done = arguments[0];+ const button = document.querySelector('#update-content-blocker-lists');+ button.click();+ setTimeout(() => done(!button.disabled && button.textContent === 'Update enabled lists'), 100);+ """,+ "args": [],+ },+ ), "An update with no eligible lists left the button waiting for a notification"++ variable = script("""+ const input = [...document.querySelectorAll('#config-list input[type=number]')]+ .find(input => input !== draftInput);+ return {name: input.id, value: Number(input.value) + 1};+ """)+ changes = change("setConfigVariable", variable)+ assert set(changes) == {"configVariables", "configVariableDefinitions"}, changes+ assert script("return draftInput === document.getElementById(draftInput.id) && draftInput.value === '999';")++ # A false boolean must update its own section without clearing any other controls.+ assert change("setGlobalPrivacyControl", True) == {"globalPrivacyControl": True}+ assert change("setGlobalPrivacyControl", False) == {"globalPrivacyControl": False}+ assert script("return !document.querySelector('#global-privacy-control-toggle').checked;")++ engine = {"name": "Test custom engine", "url": "https://example.com/search?q=%s"}+ changes = change("addCustomSearchEngine", engine)+ assert set(changes) == {"searchEngine"}, changes+ assert engine in changes["searchEngine"]["custom"]+ changes = change("removeCustomSearchEngine", engine)+ assert set(changes) == {"searchEngine"}, changes+ assert not changes["searchEngine"].get("custom")++ changes = change("addCustomContentBlockerSubscription", f"http://127.0.0.1:{server.server_port}/list")+ assert set(changes) == {+ "contentBlockers",+ "contentBlockerLists",+ "contentBlockerListUpdateInProgress",+ }, changes+ assert changes["contentBlockerListUpdateInProgress"] is True+ assert script("return document.querySelector('#update-content-blocker-lists').disabled;")+ script("""+ window.finalSettingsChanges = new Promise(resolve => {+ document.addEventListener('WebUIMessage', function listener(event) {+ if (event.detail.name !== 'loadSettings') return;+ if (event.detail.data.contentBlockerListUpdateInProgress !== false) return;+ document.removeEventListener('WebUIMessage', listener);+ resolve(event.detail.data);+ });+ });+ """)+ release_download.set()+ final_changes = command(+ "execute/async",+ {"script": "window.finalSettingsChanges.then(arguments[0]);", "args": []},+ )+ assert set(final_changes) == {"contentBlockerLists", "contentBlockerListUpdateInProgress"}, final_changes+ assert any(item["lastUpdatedAt"] is not None for item in final_changes["contentBlockerLists"])+ assert script("return draftInput === document.getElementById(draftInput.id) && draftInput.value === '999';")++ command("url", {"url": "about:welcome"})+ command(+ "execute/async",+ {+ "script": """+ const done = arguments[0];+ const button = document.querySelector('#start-browsing');+ if (!button.disabled) return done();+ const observer = new MutationObserver(() => {+ if (button.disabled) return;+ observer.disconnect();+ done();+ });+ observer.observe(button, {attributes: true, attributeFilter: ['disabled']});+ """,+ "args": [],+ },+ )+ changes = change("setSearchEngineSettings", {"engine": "Google", "suggestions": True})+ assert set(changes) == {"searchEngine"}, changes+ assert script("""+ return document.querySelector('#search-engine').value === 'Google'+ && document.querySelector('#search-suggestions-enabled').checked;+ """), "The welcome page did not apply a partial search setting"+ changes = change("setContentBlockerEnabled", False)+ assert set(changes) == {"contentBlockers"}, changes+ assert script("return !document.querySelector('#enable-content-blocking').checked;")+ print("PASS: settings changes contain only changed fields, preserve edits, and track downloads")+ finally:+ release_download.set()+ if session is not None:+ helpers["request"](port, "DELETE", f"/session/{session}")+ process.terminate()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait()+ server.shutdown()+++if __name__ == "__main__":+ parser = argparse.ArgumentParser()+ parser.add_argument("webdriver_binary")+ run_test(parser.parse_args().webdriver_binary)