Truly independent web browser
LibWebView: Close a Picture-in-Picture window's page with its tab
Luke Wilde4dd37dbc7b33
diff --git a/Libraries/LibWebView/PictureInPictureManager.cpp b/Libraries/LibWebView/PictureInPictureManager.cppindex 2fb919eb879..a87f0102a8b 100644--- a/Libraries/LibWebView/PictureInPictureManager.cpp+++ b/Libraries/LibWebView/PictureInPictureManager.cpp@@ -65,6 +65,17 @@ void PictureInPictureManager::close_window(WebContentPage& page)retire_window(*index);}+// A page that is closed before its process unloads it never runs the unloading steps that close its window's page, so+// that page is closed here, or it would keep the process running.+void PictureInPictureManager::close_window_and_its_page(WebContentPage& page)+{+ auto index = index_of_window_for(page);+ if (!index.has_value())+ return;+ m_windows[*index].window->close_page();+ retire_window(*index);+}+void PictureInPictureManager::video_size_did_change(WebContentPage& page, Gfx::IntSize video_size){if (auto index = index_of_window_for(page); index.has_value())diff --git a/Libraries/LibWebView/PictureInPictureManager.h b/Libraries/LibWebView/PictureInPictureManager.hindex 227b878f174..9c5a543f016 100644--- a/Libraries/LibWebView/PictureInPictureManager.h+++ b/Libraries/LibWebView/PictureInPictureManager.h@@ -33,6 +33,7 @@ public:// Returns the window's handle, or an empty string when no window could be opened.String open_window(WebContentPage& requesting_page, CanonicalNavigable& requesting_navigable, CanonicalTraversable&, Gfx::IntSize video_size);void close_window(WebContentPage&);+ void close_window_and_its_page(WebContentPage&);void video_size_did_change(WebContentPage&, Gfx::IntSize);bool document_has_open_window(CanonicalNavigable const&) const;diff --git a/Libraries/LibWebView/PictureInPictureWindow.cpp b/Libraries/LibWebView/PictureInPictureWindow.cppindex d218e811e42..9cd70f0642a 100644--- a/Libraries/LibWebView/PictureInPictureWindow.cpp+++ b/Libraries/LibWebView/PictureInPictureWindow.cpp@@ -69,8 +69,17 @@ Gfx::IntSize PictureInPictureWindow::size_for_video_size(Gfx::IntSize window_sizreturn size_with_width(aspect_ratio(video_size), window_size.width());}+void PictureInPictureWindow::close_page()+{+ if (!m_page_view)+ return;+ if (auto& page = m_page_view->page(); page.is_open())+ page.async_request_close_without_prompting();+}+void PictureInPictureWindow::report_page_close_of(ViewImplementation& view){+ m_page_view = &view;view.on_close = [this] {if (on_page_close)on_page_close();diff --git a/Libraries/LibWebView/PictureInPictureWindow.h b/Libraries/LibWebView/PictureInPictureWindow.hindex 07e08786888..4b595108a25 100644--- a/Libraries/LibWebView/PictureInPictureWindow.h+++ b/Libraries/LibWebView/PictureInPictureWindow.h@@ -34,6 +34,8 @@ public:virtual void hide() = 0;virtual void set_video_size(Gfx::IntSize) = 0;+ void close_page();+// The user closes the window to stop watching its video, or to go back to the video's tab and watch it there.enum class VideoKeepsPlaying : bool {No,@@ -46,6 +48,9 @@ public:protected:void report_page_close_of(ViewImplementation&);++private:+ ViewImplementation* m_page_view { nullptr };};}diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cppindex 6750a6c3118..b9cd693054a 100644--- a/Libraries/LibWebView/WebContentClient.cpp+++ b/Libraries/LibWebView/WebContentClient.cpp@@ -38,6 +38,7 @@#include <LibWebView/HelperProcess.h>#include <LibWebView/HistoryStore.h>#include <LibWebView/NavigationLoader.h>+#include <LibWebView/PictureInPictureManager.h>#include <LibWebView/RequestServerManager.h>#include <LibWebView/ViewImplementation.h>#include <LibWebView/WebContentClient.h>@@ -283,6 +284,7 @@ void WebContentClient::close_page_of_closed_tab(Web::PageId page_id)// e.g. because the user requested a forced close.if (page->needs_beforeunload_check())page->set_detached_close_pending(false);+ PictureInPictureManager::the().close_window_and_its_page(*page);page->close();}// Forgotten once the page is closed, so nothing registers it again.diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txtindex 58e989b3633..4d5d82ebfd9 100644--- a/Tests/LibWebView/CMakeLists.txt+++ b/Tests/LibWebView/CMakeLists.txt@@ -190,6 +190,13 @@ if (NOT WIN32)target_compile_definitions(TestPictureInPictureWindowControls PRIVATE LADYBIRD_BINARY_PATH="$<TARGET_FILE_DIR:ladybird>")endif()+ add_executable(TestPictureInPictureWindowLifetime TestPictureInPictureWindowLifetime.cpp)+ add_dependencies(TestPictureInPictureWindowLifetime ladybird_build_resource_files ${ladybird_helper_processes})+ target_link_libraries(TestPictureInPictureWindowLifetime PRIVATE AK LibCore LibFileSystem LibGfx LibIPC LibMain LibURL LibWeb LibWebView)+ if (APPLE)+ target_compile_definitions(TestPictureInPictureWindowLifetime PRIVATE LADYBIRD_BINARY_PATH="$<TARGET_FILE_DIR:ladybird>")+ endif()+add_executable(TestShadowTreeTooltipsAndLinks TestShadowTreeTooltipsAndLinks.cpp)add_dependencies(TestShadowTreeTooltipsAndLinks ladybird_build_resource_files ${ladybird_helper_processes})target_link_libraries(TestShadowTreeTooltipsAndLinks PRIVATE AK LibCore LibDiff LibFileSystem LibGfx LibImageDecoders LibImageDecoderClient LibIPC LibJS LibMain LibRequests LibURL LibWeb LibWebView)@@ -384,6 +391,9 @@ if (BUILD_TESTING AND NOT WIN32)add_test(NAME TestPictureInPictureWindowControls COMMAND $<TARGET_FILE:TestPictureInPictureWindowControls>)set_tests_properties(TestPictureInPictureWindowControls PROPERTIES TIMEOUT 60 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})+ add_test(NAME TestPictureInPictureWindowLifetime COMMAND $<TARGET_FILE:TestPictureInPictureWindowLifetime>)+ set_tests_properties(TestPictureInPictureWindowLifetime PROPERTIES TIMEOUT 60 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})+add_test(NAME TestShadowTreeTooltipsAndLinks COMMAND $<TARGET_FILE:TestShadowTreeTooltipsAndLinks>)set_tests_properties(TestShadowTreeTooltipsAndLinks PROPERTIES TIMEOUT 60 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})diff --git a/Tests/LibWebView/TestPictureInPictureWindowLifetime.cpp b/Tests/LibWebView/TestPictureInPictureWindowLifetime.cppnew file mode 100644index 00000000000..93b52c9380e--- /dev/null+++ b/Tests/LibWebView/TestPictureInPictureWindowLifetime.cpp@@ -0,0 +1,208 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/LexicalPath.h>+#include <AK/Random.h>+#include <AK/ScopeGuard.h>+#include <AK/String.h>+#include <AK/Utf16String.h>+#include <LibCore/Directory.h>+#include <LibCore/Environment.h>+#include <LibCore/EventLoop.h>+#include <LibCore/StandardPaths.h>+#include <LibCore/System.h>+#include <LibCore/Timer.h>+#include <LibFileSystem/FileSystem.h>+#include <LibGfx/SystemTheme.h>+#include <LibMain/Main.h>+#include <LibWebCommon/Page/InputEvent.h>+#include <LibWebView/Application.h>+#include <LibWebView/HeadlessWebView.h>+#include <LibWebView/PictureInPictureWindow.h>+#include <LibWebView/ProcessManager.h>+#include <LibWebView/Utilities.h>+#include <LibWebView/WebContentClient.h>+#include <signal.h>++namespace {++class TestApplication : public WebView::Application {+ WEB_VIEW_APPLICATION(TestApplication)++public:+ explicit TestApplication(Optional<ByteString> ladybird_binary_path)+ : WebView::Application(move(ladybird_binary_path))+ {+ }++ virtual void create_platform_options(WebView::BrowserOptions& browser_options, WebView::RequestServerOptions&, WebView::WebContentOptions& web_content_options) override+ {+ browser_options.headless_mode = WebView::HeadlessMode::Test;+ browser_options.disable_sql_database = WebView::DisableSQLDatabase::Yes;+ web_content_options.is_test_mode = WebView::IsTestMode::Yes;+ }++ virtual bool should_coordinate_browser_process() const override { return false; }++ virtual OwnPtr<WebView::PictureInPictureWindow> create_picture_in_picture_window(WebView::WebContentPage& requesting_page, WebView::CanonicalTraversable& traversable, Gfx::IntSize video_size) override+ {+ auto window = WebView::Application::create_picture_in_picture_window(requesting_page, traversable, video_size);+ if (window) {+ picture_in_picture_window = window.ptr();+ picture_in_picture_window_handle = window->handle();+ }+ return window;+ }++ bool has_spare_web_content_process() const+ {+ return WebView::Application::has_spare_web_content_process();+ }++ WebView::PictureInPictureWindow* picture_in_picture_window { nullptr };+ String picture_in_picture_window_handle;+};++// Tests/LibWeb/Assets/solid-blue-160x120.webm+constexpr auto video_url = "data:video/webm;base64,"+ "GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAJHEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHYTb"+ "uMU6uEElTDZ1OsggElTbuMU6uEHFO7a1OsggIx7AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmsirXsYMPQkBNgI1MYXZmNjIuMTIuMTAwV0GNTGF2ZjYyLj"+ "EyLjEwMESJiEBUAAAAAAAAFlSua8iuAQAAAAAAAD/XgQFzxYi7y8SD17A9dpyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDgkLCBoLqB"+ "eJqBAlWwhFW5gQESVMNnQIBzc6BjwIBnyJpFo4dFTkNPREVSRIeNTGF2ZjYyLjEyLjEwMHNz2mPAi2PFiLvLxIPXsD12Z8ilRaOHRU5DT0RFUk"+ "SHmExhdmM2Mi4yOC4xMDAgbGlidnB4LXZwOWfIoUWjiERVUkFUSU9ORIeTMDA6MDA6MDAuMDgwMDAwMDAwAB9DtnVAgOeBAKPkgQAAgIJJg0IA"+ "CfAHdgY4JBwYQgAA8EfY/WIM2+nMNg69o5wAAGsolj+HwagtlxsozzSBUQjvp5qKfWffW0n9FjLeyZR10gJc8B6pWRwBd9w2DbjItsNWdXtxBq"+ "bMrifsah2MQKOVgQAoAIYAQJKcKElAAANwAABZ79oAHFO7a5G7j7OBALeK94EB8YIBq/CBAw=="sv;++bool spin_until_or_timeout(Function<bool()> condition, int timeout_ms)+{+ bool timed_out = false;+ auto timer = Core::Timer::create_single_shot(timeout_ms, [&] { timed_out = true; });+ timer->start();+ Core::EventLoop::current().spin_until([&] { return condition() || timed_out; });+ return condition();+}++void signal_renderers(int signal)+{+ WebView::Application::process_manager().for_each_process([&](WebView::Process& process) {+ if (process.type() == WebView::ProcessType::WebContent)+ MUST(Core::System::kill(process.pid(), signal));+ });+}++void click_at(WebView::ViewImplementation& view, Web::DevicePixelPoint position)+{+ for (auto type : { Web::MouseEvent::Type::MouseDown, Web::MouseEvent::Type::MouseUp }) {+ view.enqueue_input_event(Web::MouseEvent {+ .type = type,+ .position = position,+ .screen_position = position,+ .button = Web::UIEvents::MouseButton::Primary,+ .buttons = type == Web::MouseEvent::Type::MouseDown ? Web::UIEvents::MouseButton::Primary : Web::UIEvents::MouseButton::None,+ .click_count = type == Web::MouseEvent::Type::MouseDown ? 1 : 0,+ .browser_data = nullptr,+ });+ }+}++bool process_is_running(pid_t pid)+{+ return ::kill(pid, 0) == 0;+}++NonnullOwnPtr<WebView::HeadlessWebView> open_tab_with_picture_in_picture_window(TestApplication& app, Core::AnonymousBuffer theme)+{+ // A view that takes the spare process finds its initial document loaded already.+ auto takes_spare_process = app.has_spare_web_content_process();+ auto view = WebView::HeadlessWebView::create(move(theme), { 800, 600 });+ size_t loads_finished = 0;+ view->on_load_finish = [&](auto const&) { ++loads_finished; };+ if (!takes_spare_process)+ Core::EventLoop::current().spin_until([&] { return loads_finished >= 1; });++ Utf16String title;+ view->on_title_change = [&](auto const& new_title) { title = new_title; };+ view->load_html(MUST(String::formatted(+ "<!DOCTYPE html>"+ "<button onclick=\"video.requestPictureInPicture().then(() => {{ document.title = 'entered'; }})\" style=\"position:fixed;left:0;top:0;width:800px;height:600px\"></button>"+ "<video id=video src=\"{}\"></video>"+ "<script>"+ "video.addEventListener('loadeddata', () => {{ document.title = 'ready'; }}, {{ once: true }});"+ "</script>",+ video_url)));+ Core::EventLoop::current().spin_until([&] { return title == "ready"sv; });++ app.picture_in_picture_window = nullptr;+ click_at(*view, { 400, 300 });+ Core::EventLoop::current().spin_until([&] { return title == "entered"sv && app.picture_in_picture_window; });+ view->on_title_change = {};+ view->on_load_finish = {};+ return view;+}++// A browser window closes its tabs without waiting for their processes, and destroys their views at once.+void close_tab_as_a_browser_window_does(NonnullOwnPtr<WebView::HeadlessWebView> view)+{+ auto close = view->prepare_for_close_without_prompting();+ close();+}++}++// A Picture-in-Picture window's page lives in the process of the tab that opened it, so it must not outlive that tab.++ErrorOr<int> ladybird_main(Main::Arguments arguments)+{+ auto test_config_directory = ByteString::formatted("{}/Ladybird-TestPictureInPictureWindowLifetime-{}", Core::StandardPaths::tempfile_directory(), generate_random_uuid());+ TRY(Core::Directory::create(test_config_directory, Core::Directory::CreateDirectories::Yes));+ auto cleanup_test_config_directory = ScopeGuard([&] {+ MUST(FileSystem::remove(test_config_directory, FileSystem::RecursionMode::Allowed));+ });+ MUST(Core::Environment::set("XDG_CONFIG_HOME"sv, test_config_directory, Core::Environment::Overwrite::Yes));++#if defined(LADYBIRD_BINARY_PATH)+ auto app = TRY(TestApplication::create(arguments, LADYBIRD_BINARY_PATH));+#else+ auto app = TRY(TestApplication::create(arguments, OptionalNone {}));+#endif++ auto theme_path = LexicalPath::join(WebView::s_ladybird_resource_root, "themes"sv, "Default.ini"sv);+ auto theme = TRY(Gfx::load_system_theme(theme_path.string()));++ auto window_and_process_are_gone = [&](StringView window_handle, pid_t pid) {+ return spin_until_or_timeout([&] {+ return !WebView::ViewImplementation::find_view_by_handle(window_handle).has_value() && !process_is_running(pid);+ },+ 3000);+ };++ {+ auto view = open_tab_with_picture_in_picture_window(*app, theme);+ auto window_handle = app->picture_in_picture_window_handle;+ auto pid = view->page().client().pid();++ close_tab_as_a_browser_window_does(move(view));+ VERIFY(window_and_process_are_gone(window_handle, pid));+ outln("the window and the process of a closed tab go away, even when the tab's process never unloads it");+ }++ {+ auto view = open_tab_with_picture_in_picture_window(*app, theme);+ auto window_handle = app->picture_in_picture_window_handle;+ auto pid = view->page().client().pid();++ // The user closes the window while the tab's renderer cannot answer, so the window is retired with its page open.+ signal_renderers(SIGSTOP);+ app->picture_in_picture_window->on_close(WebView::PictureInPictureWindow::VideoKeepsPlaying::Yes);+ close_tab_as_a_browser_window_does(move(view));+ signal_renderers(SIGCONT);+ VERIFY(window_and_process_are_gone(window_handle, pid));+ outln("a window the user closed before its tab goes away with the tab's process too");+ }++ return 0;+}