Truly independent web browser
LibWeb+LibWebView: Remember force-dark choices for each host
sideshowbarker68a7175e8ee3
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cppindex e201db8f9df..05696f3dfb5 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp@@ -1643,6 +1643,7 @@ void LocalNavigable::set_active_document(GC::Ptr<DOM::Document> document)DOM::Document::invalidate_full_activity();if (document)document->set_navigable(this);+ update_force_dark_for_active_document();set_needs_to_record_display_list();VERIFY(m_active_session_history_entry);@@ -6734,6 +6735,26 @@ void LocalNavigable::set_should_show_line_box_borders(bool value)child_navigable->set_should_show_line_box_borders(value);}+void LocalNavigable::set_force_dark_settings(bool enabled, HashMap<String, bool> per_host)+{+ m_force_dark_default = enabled;+ m_force_dark_per_host = move(per_host);+ update_force_dark_for_active_document();+}++void LocalNavigable::update_force_dark_for_active_document()+{+ if (!is_top_level_traversable())+ return;+ auto enabled = m_force_dark_default;+ if (auto document = active_document(); document && document->url().host().has_value()) {+ auto host = MUST(String::from_utf8(document->url().serialized_host()));+ if (!host.is_empty())+ enabled = m_force_dark_per_host.get(host).value_or(enabled);+ }+ set_force_dark_enabled(enabled);+}+void LocalNavigable::set_force_dark_enabled(bool value){if (m_force_dark_enabled == value)diff --git a/Libraries/LibWeb/HTML/LocalNavigable.h b/Libraries/LibWeb/HTML/LocalNavigable.hindex 7c729fb6cd9..ae45577827a 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.h+++ b/Libraries/LibWeb/HTML/LocalNavigable.h@@ -370,6 +370,8 @@ public:OwnPtr<Compositor::CompositorContextHandle> take_compositor_context();void set_should_show_line_box_borders(bool);+ void set_force_dark_settings(bool, HashMap<String, bool>);+ void update_force_dark_for_active_document();void set_force_dark_enabled(bool);void set_force_dark_thresholds(i32 foreground, i32 background);bool active_document_opts_out_of_force_dark() const;@@ -658,6 +660,8 @@ private:bool m_should_show_line_box_borders { false };bool m_force_dark_enabled { false };+ bool m_force_dark_default { false };+ HashMap<String, bool> m_force_dark_per_host;i32 m_force_dark_foreground_threshold { default_force_dark_foreground_threshold };i32 m_force_dark_background_threshold { default_force_dark_background_threshold };bool m_should_show_caret_hit_test_debug_overlay { false };diff --git a/Libraries/LibWebView/Settings.cpp b/Libraries/LibWebView/Settings.cppindex 879cb11bdb8..d7e5a92189c 100644--- a/Libraries/LibWebView/Settings.cpp+++ b/Libraries/LibWebView/Settings.cpp@@ -47,6 +47,7 @@ static constexpr auto WINDOW_MAXIMIZED_KEY = "maximized"sv;static constexpr auto CONTENT_SETTINGS_KEY = "content"sv;static constexpr auto DEFAULT_ZOOM_LEVEL_FACTOR_KEY = "defaultZoomLevelFactor"sv;+static constexpr auto FORCE_DARK_PER_HOST_KEY = "forceDarkPerHost"sv;static constexpr auto ZOOM_PER_HOST_KEY = "zoomPerHost"sv;static constexpr auto ENABLE_FORCE_DARK_KEY = "enableForceDark"sv;@@ -595,6 +596,10 @@ JsonValue Settings::serialize_json() constcontent_settings.set(DEFAULT_ZOOM_LEVEL_FACTOR_KEY, m_content_settings.default_zoom_level_factor);content_settings.set(ZOOM_PER_HOST_KEY, move(zoom_per_host));content_settings.set(ENABLE_FORCE_DARK_KEY, m_content_settings.enable_force_dark);+ JsonObject force_dark_per_host;+ for (auto const& [host, enabled] : m_content_settings.force_dark_per_host)+ force_dark_per_host.set(host, enabled);+ content_settings.set(FORCE_DARK_PER_HOST_KEY, move(force_dark_per_host));settings.set(CONTENT_SETTINGS_KEY, move(content_settings));JsonObject tab_settings;@@ -894,6 +899,13 @@ ContentSettings Settings::parse_content_settings(JsonValue const& settings)if (auto enable_force_dark = settings.as_object().get_bool(ENABLE_FORCE_DARK_KEY); enable_force_dark.has_value())content_settings.enable_force_dark = *enable_force_dark;+ if (auto per_host = settings.as_object().get_object(FORCE_DARK_PER_HOST_KEY); per_host.has_value()) {+ per_host->for_each_member([&](auto const& host, JsonValue const& value) {+ if (!host.is_empty() && value.is_bool())+ content_settings.force_dark_per_host.set(host, value.as_bool());+ });+ }+return content_settings;}@@ -906,6 +918,32 @@ void Settings::set_content_settings(ContentSettings content_settings)observer.content_settings_changed();}+bool Settings::force_dark_for_host(StringView host) const+{+ if (host.is_empty())+ return m_content_settings.enable_force_dark;+ return m_content_settings.force_dark_per_host.get(host).value_or(m_content_settings.enable_force_dark);+}++void Settings::set_force_dark_for_host(String const& host, bool enabled)+{+ if (host.is_empty() || m_content_settings.force_dark_per_host.get(host) == enabled)+ return;+ m_content_settings.force_dark_per_host.set(host, enabled);+ persist_settings();+ for (auto& observer : m_observers)+ observer.content_settings_changed();+}++void Settings::reset_force_dark_for_host(StringView host)+{+ if (!m_content_settings.force_dark_per_host.remove(host))+ return;+ persist_settings();+ for (auto& observer : m_observers)+ observer.content_settings_changed();+}+double Settings::zoom_for_host(StringView host) const{auto default_zoom_level_factor = m_content_settings.default_zoom_level_factor;@@ -1388,7 +1426,12 @@ void Settings::remove_observer(Badge<SettingsObserver>, SettingsObserver& observ}SettingsObserver::SettingsObserver()- : m_settings(Application::settings())+ : SettingsObserver(Application::settings())+{+}++SettingsObserver::SettingsObserver(Settings& settings)+ : m_settings(settings){m_settings->add_observer({}, *this);}diff --git a/Libraries/LibWebView/Settings.h b/Libraries/LibWebView/Settings.hindex f323be723f4..e1a5ccb21e9 100644--- a/Libraries/LibWebView/Settings.h+++ b/Libraries/LibWebView/Settings.h@@ -56,6 +56,7 @@ struct ContentSettings {HashMap<String, double> zoom_per_host;bool enable_force_dark { false };+ HashMap<String, bool> force_dark_per_host;};enum class VerticalTabsPosition : u8 {@@ -148,6 +149,7 @@ WEBVIEW_API Optional<ConfigVariableID> config_variable_id_from_name(StringView);class WEBVIEW_API SettingsObserver {public:explicit SettingsObserver();+ explicit SettingsObserver(Settings&);virtual ~SettingsObserver();virtual void new_tab_page_url_changed() { }@@ -207,6 +209,10 @@ public:ContentSettings const& content_settings() const { return m_content_settings; }void set_content_settings(ContentSettings);+ bool force_dark_for_host(StringView host) const;+ void set_force_dark_for_host(String const& host, bool enabled);+ void reset_force_dark_for_host(StringView host);+double zoom_for_host(StringView host) const;void set_zoom_for_host(String const& host, double zoom_level);diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cppindex 24f170b492a..b57ce914d15 100644--- a/Libraries/LibWebView/ViewImplementation.cpp+++ b/Libraries/LibWebView/ViewImplementation.cpp@@ -1559,8 +1559,8 @@ static void send_global_privacy_control(WebContentPage const& page)// embedding an out-of-process iframe doesn't have.static void send_force_dark(WebContentPage const& page){- // FIXME: This is not a "debug request". Add a proper endpoint for this toggle.- page.async_debug_request("set-force-dark"sv, Application::settings().content_settings().enable_force_dark ? "on"sv : "off"sv);+ auto const& settings = Application::settings().content_settings();+ page.async_set_force_dark_settings(settings.enable_force_dark, settings.force_dark_per_host);}void ViewImplementation::send_preferences_to_page(WebContentPage& page)diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cppindex 5e9c485bb4d..745a6bc54bd 100644--- a/Services/WebContent/ConnectionFromClient.cpp+++ b/Services/WebContent/ConnectionFromClient.cpp@@ -3214,6 +3214,12 @@ void ConnectionFromClient::set_content_blockers(Core::AnonymousBuffer patterns_bm_page_host->invalidate_user_style();}+void ConnectionFromClient::set_force_dark_settings(Web::PageId page_id, bool enabled, HashMap<String, bool> per_host)+{+ if (auto page = this->page(page_id); page.has_value() && page->page().has_local_traversable())+ page->page().local_traversable()->set_force_dark_settings(enabled, move(per_host));+}+void ConnectionFromClient::set_autoplay_settings(Web::PageId, Web::HTML::AutoplayPolicy policy, Vector<Utf16String> allowlist){Web::HTML::AutoplaySettings::the().set_policy(policy, allowlist);diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.hindex ec0cefa1766..cc89ca837f3 100644--- a/Services/WebContent/ConnectionFromClient.h+++ b/Services/WebContent/ConnectionFromClient.h@@ -247,6 +247,7 @@ private:virtual void set_content_blocking_policy(Web::PageId page_id, bool enabled, Vector<String> disabled_sites) override;virtual void set_content_blockers(Core::AnonymousBuffer patterns) override;+ virtual void set_force_dark_settings(Web::PageId page_id, bool enabled, HashMap<String, bool> per_host) override;virtual void set_autoplay_settings(Web::PageId page_id, Web::HTML::AutoplayPolicy policy, Vector<Utf16String> allowlist) override;virtual void set_preferred_color_scheme(Web::PageId page_id, Web::CSS::PreferredColorScheme) override;virtual void set_preferred_contrast(Web::PageId page_id, Web::CSS::PreferredContrast) override;diff --git a/Services/WebContent/WebContentServer.ipc b/Services/WebContent/WebContentServer.ipcindex 211cdebe9b4..472b10e3dda 100644--- a/Services/WebContent/WebContentServer.ipc+++ b/Services/WebContent/WebContentServer.ipc@@ -255,6 +255,7 @@ endpoint WebContentServer routed by Web::PageId page_idset_content_blocking_policy(Web::PageId page_id, bool enabled, Vector<String> disabled_sites) =|set_content_blockers(Core::AnonymousBuffer patterns) =|+ set_force_dark_settings(Web::PageId page_id, bool enabled, HashMap<String, bool> per_host) =|set_autoplay_settings(Web::PageId page_id, Web::HTML::AutoplayPolicy policy, Vector<Utf16String> allowlist) =|set_preferred_color_scheme(Web::PageId page_id, Web::CSS::PreferredColorScheme color_scheme) =|set_preferred_contrast(Web::PageId page_id, Web::CSS::PreferredContrast contrast) =|diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txtindex bb594a03554..b0fddc6f91a 100644--- a/Tests/LibWebView/CMakeLists.txt+++ b/Tests/LibWebView/CMakeLists.txt@@ -177,6 +177,7 @@ set(TEST_SOURCESTestDownloadStore.cppTestExternalURLHandler.cppTestFaviconStore.cpp+ TestForceDarkSettings.cppTestHelperProcessEnvironment.cppTestHistoryStore.cppTestHSTSStore.cppdiff --git a/Tests/LibWebView/TestForceDarkSettings.cpp b/Tests/LibWebView/TestForceDarkSettings.cppnew file mode 100644index 00000000000..f00def98538--- /dev/null+++ b/Tests/LibWebView/TestForceDarkSettings.cpp@@ -0,0 +1,82 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/LexicalPath.h>+#include <LibCore/StandardPaths.h>+#include <LibCore/System.h>+#include <LibFileSystem/FileSystem.h>+#include <LibTest/TestCase.h>+#include <LibWebView/Settings.h>++TEST_CASE(force_dark_choices_survive_default_changes_and_restart)+{+ auto path = LexicalPath::join(Core::StandardPaths::tempfile_directory(), ByteString::formatted("test-force-dark-{}.json", Core::System::getpid())).string();+ if (FileSystem::exists(path))+ MUST(FileSystem::remove(path, FileSystem::RecursionMode::Disallowed));+ {+ auto settings = WebView::Settings::create(path);+ EXPECT(!settings.force_dark_for_host("example.com"sv));+ settings.set_force_dark_for_host("example.com"_string, false);+ settings.set_force_dark_for_host("other.example"_string, true);+ settings.set_force_dark_for_host(String {}, true);+ EXPECT_EQ(settings.content_settings().force_dark_per_host.size(), 2u);+ auto content = settings.content_settings();+ content.enable_force_dark = true;+ settings.set_content_settings(move(content));+ EXPECT(!settings.force_dark_for_host("example.com"sv));+ EXPECT(settings.force_dark_for_host("other.example"sv));+ EXPECT(settings.force_dark_for_host("sub.example.com"sv));+ EXPECT(settings.force_dark_for_host({}));+ }+ {+ auto settings = WebView::Settings::create(path);+ EXPECT(!settings.force_dark_for_host("example.com"sv));+ EXPECT(settings.force_dark_for_host("other.example"sv));+ settings.reset_force_dark_for_host("example.com"sv);+ EXPECT(settings.force_dark_for_host("example.com"sv));+ EXPECT_EQ(settings.content_settings().force_dark_per_host.size(), 1u);+ }+ auto settings = WebView::Settings::create(path);+ EXPECT(settings.force_dark_for_host("example.com"sv));+ EXPECT_EQ(settings.content_settings().force_dark_per_host.size(), 1u);+ MUST(FileSystem::remove(path, FileSystem::RecursionMode::Disallowed));+}++TEST_CASE(force_dark_ignores_invalid_saved_choices)+{+ auto json = MUST(JsonValue::from_string(R"({"enableForceDark":true,"forceDarkPerHost":{"on.example":true,"off.example":false,"string.example":"false","number.example":1,"null.example":null,"":false}})"sv));+ auto content = WebView::Settings::parse_content_settings(json);+ EXPECT(content.enable_force_dark);+ EXPECT_EQ(content.force_dark_per_host.size(), 2u);+ EXPECT_EQ(content.force_dark_per_host.get("on.example"sv), true);+ EXPECT_EQ(content.force_dark_per_host.get("off.example"sv), false);+}++TEST_CASE(force_dark_notifies_only_when_a_choice_changes)+{+ auto path = LexicalPath::join(Core::StandardPaths::tempfile_directory(), ByteString::formatted("test-force-dark-observer-{}.json", Core::System::getpid())).string();+ if (FileSystem::exists(path))+ MUST(FileSystem::remove(path, FileSystem::RecursionMode::Disallowed));+ auto settings = WebView::Settings::create(path);+ struct Observer : WebView::SettingsObserver {+ explicit Observer(WebView::Settings& settings)+ : SettingsObserver(settings)+ {+ }+ virtual void content_settings_changed() override { ++changes; }+ size_t changes { 0 };+ } observer(settings);+ settings.set_force_dark_for_host("example.com"_string, false);+ EXPECT_EQ(observer.changes, 1u);+ settings.set_force_dark_for_host("example.com"_string, false);+ settings.set_force_dark_for_host({}, true);+ settings.reset_force_dark_for_host("missing.example"sv);+ EXPECT_EQ(observer.changes, 1u);+ settings.set_force_dark_for_host("example.com"_string, true);+ settings.reset_force_dark_for_host("example.com"sv);+ EXPECT_EQ(observer.changes, 3u);+ MUST(FileSystem::remove(path, FileSystem::RecursionMode::Disallowed));+}diff --git a/Tests/LibWebView/test-webdriver-force-dark.py b/Tests/LibWebView/test-webdriver-force-dark.pyindex fd469301ed8..49555c7a748 100755--- a/Tests/LibWebView/test-webdriver-force-dark.py+++ b/Tests/LibWebView/test-webdriver-force-dark.py@@ -30,7 +30,11 @@ class Handler(http.server.BaseHTTPRequestHandler):self.send_header("Content-Type", "text/html")self.send_header("Cache-Control", "no-store")self.end_headers()- self.wfile.write(b"<!doctype html><title>Force-dark test</title><body style='background: white'>")+ self.wfile.write(+ b"<!doctype html><title>Force-dark test</title><body style='background: white'>"+ b"<script>window.initialDark = matchMedia('(prefers-color-scheme: dark)').matches;</script>"+ b"<iframe srcdoc=\"<body style='background:white'>\" style='position:absolute;left:100px;top:100px;border:0'></iframe>"+ )def log_message(self, format, *args):pass@@ -73,75 +77,112 @@ def png_pixel(png, x, y):return tuple(previous[x * channels : x * channels + 3])-with tempfile.TemporaryDirectory() as directory:- config = Path(directory) / "config"- config.mkdir()- (config / "Settings.json").write_text(json.dumps({"content": {"enableForceDark": True}}))- server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)- threading.Thread(target=server.serve_forever, daemon=True).start()- process, port = helpers["launch_webdriver"](sys.argv[1], "--headless", "--profile-path", directory)- session = None- try:- session = helpers["create_session"](port)-- def command(method, path, body=None):- status, payload, raw = helpers["request"](port, method, f"/session/{session}/{path}", body)- return status, payload, raw-- def wait_for_page(url):- deadline = time.monotonic() + 30- state = None- while time.monotonic() < deadline:+def run_test(default):+ with tempfile.TemporaryDirectory() as directory:+ config = Path(directory) / "config"+ config.mkdir()+ (config / "Settings.json").write_text(+ json.dumps(+ {+ "appearance": {"websiteColorScheme": "light"},+ "content": {"enableForceDark": default, "forceDarkPerHost": {"localhost": not default}},+ }+ )+ )+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ process, port = helpers["launch_webdriver"](sys.argv[1], "--headless", "--profile-path", directory)+ session = None+ try:+ session = helpers["create_session"](port)++ def command(method, path, body=None):+ status, payload, raw = helpers["request"](port, method, f"/session/{session}/{path}", body)+ return status, payload, raw++ def wait_for_page(url):+ deadline = time.monotonic() + 30+ state = None+ while time.monotonic() < deadline:+ status, payload, raw = command(+ "POST", "execute/sync", {"script": "return [location.href, document.readyState]", "args": []}+ )+ if (+ status == 500+ and payload["value"]["message"] == "WebContent was replaced while executing the command"+ ):+ continue+ assert status == 200, raw+ state = payload["value"]+ if state == [url, "complete"]:+ return+ time.sleep(0.01)+ raise AssertionError(f"Expected {url}, got {state}")++ def assert_force_dark(description, expected, check_initial=True):+ status, payload, raw = command("GET", "screenshot")+ assert status == 200, raw+ color = png_pixel(base64.b64decode(payload["value"]), 10, 10)+ assert (max(color) < 128) == expected, f"{description} expected dark={expected}, got {color}"+ iframe_color = png_pixel(base64.b64decode(payload["value"]), 110, 110)+ assert (max(iframe_color) < 128) == expected, f"{description} iframe painted {iframe_color}"status, payload, raw = command(- "POST", "execute/sync", {"script": "return [location.href, document.readyState]", "args": []}+ "POST",+ "execute/sync",+ {+ "script": "return window.initialDark"+ if check_initial+ else "return matchMedia('(prefers-color-scheme: dark)').matches",+ "args": [],+ },)- if (- status == 500- and payload["value"]["message"] == "WebContent was replaced while executing the command"- ):- continueassert status == 200, raw- state = payload["value"]- if state == [url, "complete"]:- return- time.sleep(0.01)- raise AssertionError(f"Expected {url}, got {state}")-- def assert_force_dark(description):- status, payload, raw = command("GET", "screenshot")+ assert payload["value"] == expected, f"{description} initial color preference was {payload['value']}"++ source_url = f"http://127.0.0.1:{server.server_port}/source"+ target_url = f"http://localhost:{server.server_port}/target"++ status, _, raw = command("POST", "url", {"url": source_url})assert status == 200, raw- color = png_pixel(base64.b64decode(payload["value"]), 10, 10)- assert max(color) < 128, f"{description} painted its white background as {color}"-- source_url = f"http://127.0.0.1:{server.server_port}/source"- target_url = f"http://localhost:{server.server_port}/target"-- status, _, raw = command("POST", "url", {"url": source_url})- assert status == 200, raw- wait_for_page(source_url)- assert_force_dark("The tab's first page")-- # A cross-site navigation moves the tab into a page of another process.- status, _, raw = command("POST", "url", {"url": target_url})- assert status == 200, raw- wait_for_page(target_url)- assert_force_dark("A cross-site navigation's page")-- status, _, raw = command("POST", "back", {})- assert status == 200, raw- wait_for_page(source_url)- assert_force_dark("A cross-site traversal's page")- print("PASS: force-dark follows the tab into every page")- finally:- try:- if session is not None:- helpers["request"](port, "DELETE", f"/session/{session}")+ wait_for_page(source_url)+ assert_force_dark("The tab's first page", default)++ # A cross-site navigation moves the tab into a page of another process.+ status, _, raw = command("POST", "url", {"url": target_url})+ assert status == 200, raw+ wait_for_page(target_url)+ assert_force_dark("A cross-site navigation's page", not default)++ status, _, raw = command("POST", "back", {})+ assert status == 200, raw+ wait_for_page(source_url)+ assert_force_dark("A cross-site traversal's page", default)+ status, _, raw = command("POST", "url", {"url": target_url + "-same-host"})+ assert status == 200, raw+ wait_for_page(target_url + "-same-host")+ status, _, raw = command("POST", "url", {"url": target_url + "-same-host-next"})+ assert status == 200, raw+ wait_for_page(target_url + "-same-host-next")+ assert_force_dark("Same-host navigation", not default)+ status, _, raw = command("POST", "refresh", {})+ assert status == 200, raw+ wait_for_page(target_url + "-same-host-next")+ assert_force_dark("Reload", not default)+ print(f"PASS: per-host force-dark across navigation (default={default})")finally:- process.terminate()try:- process.wait(timeout=5)- except subprocess.TimeoutExpired:- process.kill()- process.wait()- server.shutdown()- server.server_close()+ 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()+ server.shutdown()+ server.server_close()+++for default in (True, False):+ run_test(default)