Skip to content

Truly independent web browser

LibWebView: Use weak references for observer cleanup

Timothy Flynne6b1ad5e28ad
diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cpp
index 716e700206b..cf3596f8abe 100644
--- a/Libraries/LibWebView/Application.cpp
+++ b/Libraries/LibWebView/Application.cpp
@@ -210,15 +210,12 @@ Application::Application(Optional<ByteString> ladybird_binary_path)
Application::~Application()
{
#if defined(AK_OS_MACOS)
- // NB: Stop bootstrap callbacks before destroying the state they use.
+ // Stop bootstrap callbacks before destroying the state they use.
m_mach_port_server.clear();
#endif
m_autocomplete_service.clear();
- // Explicitly delete the observers first, as the observer destructors will refer to Application::the().
- m_settings_observer.clear();
- m_bookmark_store_observer.clear();
if (m_compositor_client)
m_compositor_client->on_death = nullptr;
@@ -244,7 +241,7 @@ Application::~Application()
m_spare_web_content_process = nullptr;
- // NB: Connection die() handlers use the process manager, so destroy the processes while it is still reachable.
+ // Connection die() handlers use the process manager, so destroy the processes while it is still reachable.
if (m_process_manager)
m_process_manager->remove_all_processes();
m_process_manager = nullptr;
diff --git a/Libraries/LibWebView/BookmarkStore.cpp b/Libraries/LibWebView/BookmarkStore.cpp
index 8e5d595675e..123b563cee3 100644
--- a/Libraries/LibWebView/BookmarkStore.cpp
+++ b/Libraries/LibWebView/BookmarkStore.cpp
@@ -533,25 +533,27 @@ void BookmarkStore::notify_observers()
void BookmarkStore::add_observer(Badge<BookmarkStoreObserver>, BookmarkStoreObserver& observer)
{
- Application::bookmark_store().m_observers.append(observer);
+ m_observers.append(observer);
}
void BookmarkStore::remove_observer(Badge<BookmarkStoreObserver>, BookmarkStoreObserver& observer)
{
- auto was_removed = Application::bookmark_store().m_observers.remove_first_matching([&](auto const& candidate) {
+ auto was_removed = m_observers.remove_first_matching([&](auto const& candidate) {
return &candidate == &observer;
});
VERIFY(was_removed);
}
BookmarkStoreObserver::BookmarkStoreObserver()
+ : m_bookmark_store(Application::bookmark_store())
{
- BookmarkStore::add_observer({}, *this);
+ m_bookmark_store->add_observer({}, *this);
}
BookmarkStoreObserver::~BookmarkStoreObserver()
{
- BookmarkStore::remove_observer({}, *this);
+ if (m_bookmark_store)
+ m_bookmark_store->remove_observer({}, *this);
}
}
diff --git a/Libraries/LibWebView/BookmarkStore.h b/Libraries/LibWebView/BookmarkStore.h
index 5d33a75037a..ebb65349936 100644
--- a/Libraries/LibWebView/BookmarkStore.h
+++ b/Libraries/LibWebView/BookmarkStore.h
@@ -13,6 +13,8 @@
#include <AK/Time.h>
#include <AK/Variant.h>
#include <AK/Vector.h>
+#include <AK/WeakPtr.h>
+#include <AK/Weakable.h>
#include <LibURL/URL.h>
#include <LibWebView/Forward.h>
@@ -51,9 +53,12 @@ public:
virtual ~BookmarkStoreObserver();
virtual void bookmarks_changed() { }
+
+private:
+ WeakPtr<BookmarkStore> m_bookmark_store;
};
-class WEBVIEW_API BookmarkStore {
+class WEBVIEW_API BookmarkStore : public Weakable<BookmarkStore> {
public:
AK_ALLOC_WITH_KMALLOC;
@@ -82,8 +87,8 @@ public:
JsonValue serialize_items(Optional<FaviconStore&> favicon_store = {}) const;
HashTable<String> favicon_hashes() const;
- static void add_observer(Badge<BookmarkStoreObserver>, BookmarkStoreObserver&);
- static void remove_observer(Badge<BookmarkStoreObserver>, BookmarkStoreObserver&);
+ void add_observer(Badge<BookmarkStoreObserver>, BookmarkStoreObserver&);
+ void remove_observer(Badge<BookmarkStoreObserver>, BookmarkStoreObserver&);
private:
explicit BookmarkStore(ByteString bookmarks_path);
diff --git a/Libraries/LibWebView/FileDownloader.cpp b/Libraries/LibWebView/FileDownloader.cpp
index 2e7d4776042..7004350663c 100644
--- a/Libraries/LibWebView/FileDownloader.cpp
+++ b/Libraries/LibWebView/FileDownloader.cpp
@@ -1668,25 +1668,27 @@ void FileDownloader::notify_download_removed(u64 id, IsPrivate is_private)
void FileDownloader::add_observer(Badge<FileDownloaderObserver>, FileDownloaderObserver& observer)
{
- Application::the().file_downloader().m_observers.append(observer);
+ m_observers.append(observer);
}
void FileDownloader::remove_observer(Badge<FileDownloaderObserver>, FileDownloaderObserver& observer)
{
- auto was_removed = Application::the().file_downloader().m_observers.remove_first_matching([&](auto const& candidate) {
+ auto was_removed = m_observers.remove_first_matching([&](auto const& candidate) {
return &candidate == &observer;
});
VERIFY(was_removed);
}
FileDownloaderObserver::FileDownloaderObserver()
+ : m_file_downloader(Application::the().file_downloader())
{
- FileDownloader::add_observer({}, *this);
+ m_file_downloader->add_observer({}, *this);
}
FileDownloaderObserver::~FileDownloaderObserver()
{
- FileDownloader::remove_observer({}, *this);
+ if (m_file_downloader)
+ m_file_downloader->remove_observer({}, *this);
}
}
diff --git a/Libraries/LibWebView/FileDownloader.h b/Libraries/LibWebView/FileDownloader.h
index 6332c75d6e5..73547f67e1c 100644
--- a/Libraries/LibWebView/FileDownloader.h
+++ b/Libraries/LibWebView/FileDownloader.h
@@ -17,6 +17,8 @@
#include <AK/Span.h>
#include <AK/String.h>
#include <AK/Time.h>
+#include <AK/WeakPtr.h>
+#include <AK/Weakable.h>
#include <LibHTTP/Forward.h>
#include <LibRequests/CacheState.h>
#include <LibRequests/Forward.h>
@@ -35,7 +37,7 @@ namespace WebView {
class FileDownloaderObserver;
-class WEBVIEW_API FileDownloader {
+class WEBVIEW_API FileDownloader : public Weakable<FileDownloader> {
public:
enum class DownloadStatus : u8 {
InProgress,
@@ -113,8 +115,8 @@ public:
void adopt_download_store(Badge<Application>, DownloadStore&);
- static void add_observer(Badge<FileDownloaderObserver>, FileDownloaderObserver&);
- static void remove_observer(Badge<FileDownloaderObserver>, FileDownloaderObserver&);
+ void add_observer(Badge<FileDownloaderObserver>, FileDownloaderObserver&);
+ void remove_observer(Badge<FileDownloaderObserver>, FileDownloaderObserver&);
private:
struct ActiveDownload;
@@ -178,6 +180,9 @@ public:
virtual void download_added(FileDownloader::Download const&) { }
virtual void download_updated(FileDownloader::Download const&) { }
virtual void download_removed(u64, IsPrivate) { }
+
+private:
+ WeakPtr<FileDownloader> m_file_downloader;
};
}
diff --git a/Libraries/LibWebView/Settings.cpp b/Libraries/LibWebView/Settings.cpp
index d12d2914a5e..812c3793b4b 100644
--- a/Libraries/LibWebView/Settings.cpp
+++ b/Libraries/LibWebView/Settings.cpp
@@ -1354,25 +1354,27 @@ void Settings::persist_settings()
void Settings::add_observer(Badge<SettingsObserver>, SettingsObserver& observer)
{
- Application::settings().m_observers.append(observer);
+ m_observers.append(observer);
}
void Settings::remove_observer(Badge<SettingsObserver>, SettingsObserver& observer)
{
- auto was_removed = Application::settings().m_observers.remove_first_matching([&](auto const& candidate) {
+ auto was_removed = m_observers.remove_first_matching([&](auto const& candidate) {
return &candidate == &observer;
});
VERIFY(was_removed);
}
SettingsObserver::SettingsObserver()
+ : m_settings(Application::settings())
{
- Settings::add_observer({}, *this);
+ m_settings->add_observer({}, *this);
}
SettingsObserver::~SettingsObserver()
{
- Settings::remove_observer({}, *this);
+ if (m_settings)
+ m_settings->remove_observer({}, *this);
}
}
diff --git a/Libraries/LibWebView/Settings.h b/Libraries/LibWebView/Settings.h
index 776aa13a94a..927bdd6b323 100644
--- a/Libraries/LibWebView/Settings.h
+++ b/Libraries/LibWebView/Settings.h
@@ -11,6 +11,8 @@
#include <AK/HashTable.h>
#include <AK/JsonValue.h>
#include <AK/Optional.h>
+#include <AK/WeakPtr.h>
+#include <AK/Weakable.h>
#include <LibGfx/Point.h>
#include <LibGfx/Size.h>
#include <LibHTTP/Cache/DiskCacheSettings.h>
@@ -144,9 +146,12 @@ public:
virtual void background_networking_settings_changed() { }
virtual void content_blocker_settings_changed() { }
virtual void content_blocker_count_visibility_changed() { }
+
+private:
+ WeakPtr<Settings> m_settings;
};
-class WEBVIEW_API Settings {
+class WEBVIEW_API Settings : public Weakable<Settings> {
public:
AK_ALLOC_WITH_KMALLOC;
@@ -261,8 +266,8 @@ public:
return value.value_or_lazy_evaluated([&] { return variable.default_value.get_integer<T>().value(); });
}
- static void add_observer(Badge<SettingsObserver>, SettingsObserver&);
- static void remove_observer(Badge<SettingsObserver>, SettingsObserver&);
+ void add_observer(Badge<SettingsObserver>, SettingsObserver&);
+ void remove_observer(Badge<SettingsObserver>, SettingsObserver&);
private:
explicit Settings(ByteString settings_path);
diff --git a/Tests/LibWebView/TestApplicationDestruction.cpp b/Tests/LibWebView/TestApplicationDestruction.cpp
index a785748184a..10bca342382 100644
--- a/Tests/LibWebView/TestApplicationDestruction.cpp
+++ b/Tests/LibWebView/TestApplicationDestruction.cpp
@@ -7,13 +7,19 @@
#include <LibTest/TestCase.h>
#include <LibCore/Directory.h>
+#include <LibCore/Environment.h>
+#include <LibCore/EventLoop.h>
#include <LibCore/StandardPaths.h>
+#include <LibCore/ThreadEventQueue.h>
#include <LibFileSystem/FileSystem.h>
#include <LibGfx/SystemTheme.h>
#include <LibWebView/Application.h>
#include <LibWebView/HSTSStore.h>
#include <LibWebView/HeadlessWebView.h>
#include <LibWebView/Utilities.h>
+#include <LibWebView/WebContentClient.h>
+#include <LibWebView/WebContentPage.h>
+#include <LibWebView/WebUI.h>
class TestApplication : public WebView::Application {
WEB_VIEW_APPLICATION(TestApplication)
@@ -31,57 +37,120 @@ public:
web_content_options.is_test_mode = WebView::IsTestMode::Yes;
}
+ virtual Core::EventLoop& create_platform_event_loop() override { return Core::EventLoop::current(); }
virtual bool should_coordinate_browser_process() const override { return false; }
};
-TEST_CASE(hsts_store_synchronized_on_destruction)
-{
- auto test_directory_prefix = ByteString::formatted("{}/Ladybird-TestApplicationDestruction-{}", Core::StandardPaths::tempfile_directory(), generate_random_uuid());
-
- auto config_directory = ByteString::formatted("{}-config", test_directory_prefix);
- auto data_directory = ByteString::formatted("{}-data", test_directory_prefix);
-
- TRY_OR_FAIL(Core::Directory::create(config_directory, Core::Directory::CreateDirectories::Yes));
- TRY_OR_FAIL(Core::Directory::create(data_directory, Core::Directory::CreateDirectories::Yes));
-
- ScopeGuard cleanup = [&] {
- MUST(FileSystem::remove(config_directory, FileSystem::RecursionMode::Allowed));
- MUST(FileSystem::remove(data_directory, FileSystem::RecursionMode::Allowed));
- };
-
- VERIFY(setenv("XDG_CONFIG_HOME", config_directory.characters(), 1) == 0);
- VERIFY(setenv("XDG_DATA_HOME", data_directory.characters(), 1) == 0);
+class TestEnvironment {
+public:
+ TestEnvironment()
+ : m_test_directory(ByteString::formatted("{}/Ladybird-TestApplicationDestruction-{}", Core::StandardPaths::tempfile_directory(), generate_random_uuid()))
+ {
+ }
- ByteString database_path;
+ ~TestEnvironment()
+ {
+ Core::ThreadEventQueue::destroy_current();
+ if (FileSystem::exists(m_test_directory))
+ (void)FileSystem::remove(m_test_directory, FileSystem::RecursionMode::Allowed);
+ }
+ ErrorOr<NonnullOwnPtr<TestApplication>> create_application()
{
- auto executable = "ladybird"sv;
+ auto make_test_dir = [&](auto dir, auto env) -> ErrorOr<void> {
+ auto path = ByteString::formatted("{}/{}", m_test_directory, dir);
+ TRY(Core::Directory::create(path, Core::Directory::CreateDirectories::Yes));
+ TRY(Core::Environment::set(env, path, Core::Environment::Overwrite::Yes));
+ return {};
+ };
+
+ TRY(make_test_dir("config"sv, "XDG_CONFIG_HOME"sv));
+ TRY(make_test_dir("data"sv, "XDG_DATA_HOME"sv));
Main::Arguments arguments {
.argc = 0,
.argv = nullptr,
- .strings = Span<StringView> { &executable, 1 }
+ .strings = Span<StringView> { &m_executable, 1 }
};
#if defined(LADYBIRD_BINARY_PATH)
- auto app = TRY_OR_FAIL(TestApplication::create(arguments, LADYBIRD_BINARY_PATH));
+ return TestApplication::create(arguments, LADYBIRD_BINARY_PATH);
#else
- auto app = TRY_OR_FAIL(TestApplication::create(arguments, OptionalNone {}));
+ return TestApplication::create(arguments, OptionalNone {});
#endif
+ }
+
+private:
+ Core::EventLoop m_event_loop;
+ StringView m_executable { "ladybird"sv };
+ ByteString m_test_directory;
+};
- auto theme_path = LexicalPath::join(WebView::s_ladybird_resource_root, "themes"sv, "Default.ini"sv);
- auto theme = TRY_OR_FAIL(Gfx::load_system_theme(theme_path.string()));
- auto view = WebView::HeadlessWebView::create(theme, { 1000, 700 });
+static ErrorOr<Core::AnonymousBuffer> load_test_theme()
+{
+ auto theme_path = LexicalPath::join(WebView::s_ladybird_resource_root, "themes"sv, "Default.ini"sv);
+ return Gfx::load_system_theme(theme_path.string());
+}
+TEST_CASE(hsts_store_synchronized_on_destruction)
+{
+ TestEnvironment environment;
+ ByteString database_path;
+ {
+ auto app = TRY_OR_FAIL(environment.create_application());
+ auto view = WebView::HeadlessWebView::create(TRY_OR_FAIL(load_test_theme()), { 1000, 700 });
database_path = app->profile().paths().data;
- // Push a HSTS policy into the transient storage and then immediately destruct the application to test whether
- // it gets synchronized to the persistent storage.
+ // Push a HSTS policy into transient storage and immediately destroy the application to check persistence.
view->session().hsts_store->store_policy("example.test"_string, HTTP::HSTS::ParsedHSTSPolicy { AK::Duration::from_seconds(3600), false });
}
auto database = TRY_OR_FAIL(Database::Database::create(database_path, "Ladybird"sv));
auto hsts_store = TRY_OR_FAIL(WebView::HSTSStore::create(database));
-
VERIFY(hsts_store->is_known_hsts_host("example.test"_string));
}
+
+TEST_CASE(application_destruction_with_pending_web_ui_callbacks)
+{
+ TestEnvironment environment;
+ struct WebUILifetime {
+ WeakPtr<WebView::WebContentClient> client;
+ WeakPtr<WebView::WebUI> web_ui;
+ bool retained_by_callback { false };
+ };
+ Vector<WebUILifetime> web_ui_lifetimes;
+
+ {
+ auto app = TRY_OR_FAIL(environment.create_application());
+ auto theme = TRY_OR_FAIL(load_test_theme());
+ for (auto host : { "settings"sv, "bookmarks"sv, "downloads"sv }) {
+ for (bool retained_by_callback : { false, true }) {
+ auto view = WebView::HeadlessWebView::create(theme, { 1000, 700 });
+ auto& page = view->page();
+ auto web_ui = TRY_OR_FAIL(WebView::WebUI::create(page.client(), page.id(), MUST(String::from_utf8(host))));
+ VERIFY(web_ui);
+ web_ui_lifetimes.append({ page.client(), web_ui, retained_by_callback });
+ page.client().set_web_ui(move(web_ui));
+
+ if (retained_by_callback) {
+ // EventReceiver::deferred_invoke() retains its receiver until the callback is run or discarded.
+ page.client().deferred_invoke([] { });
+ page.client().web_ui()->deferred_invoke([] { });
+ }
+ }
+ }
+ }
+
+ VERIFY(!WebView::Application::is_initialized());
+ for (auto const& lifetime : web_ui_lifetimes) {
+ EXPECT_EQ(static_cast<bool>(lifetime.client), lifetime.retained_by_callback);
+ EXPECT_EQ(static_cast<bool>(lifetime.web_ui), lifetime.retained_by_callback);
+ }
+
+ // The Qt event loop discards queued callbacks after the application has been destroyed.
+ Core::ThreadEventQueue::destroy_current();
+ for (auto const& lifetime : web_ui_lifetimes) {
+ EXPECT(!lifetime.client);
+ EXPECT(!lifetime.web_ui);
+ }
+}