Truly independent web browser
LibWebView+LibWeb: Check Picture-in-Picture activation in the UI
Luke Wilded9a8b24cec8a
diff --git a/Libraries/LibWeb/PictureInPicture/PictureInPictureController.cpp b/Libraries/LibWeb/PictureInPicture/PictureInPictureController.cppindex 2e1034e7a8e..51ca5fd1a99 100644--- a/Libraries/LibWeb/PictureInPicture/PictureInPictureController.cpp+++ b/Libraries/LibWeb/PictureInPicture/PictureInPictureController.cpp@@ -177,10 +177,17 @@ void PictureInPictureController::run_request_steps(Request const& request)}// 2. Attempt to associate a Picture-in-Picture window with this.- // NB: The window shows a page of its own, which the UI process creates along with the window.- HTML::WebViewHints hints;- hints.picture_in_picture_video_size = Gfx::Size<u32> { video.video_width(), video.video_height() }.to_type<int>();- auto new_web_view = m_page->client().page_did_request_new_web_view(HTML::ActivateTab::No, hints, {}, {}, {}, {});+ // NB: The window shows a page of its own, which the UI process creates along with the window. The UI process lets a+ // document replace its open window without user activation, as step 7 does, so it is told doc's navigable.+ PageClient::NewWebViewResult new_web_view;+ if (auto navigable = video.document().navigable()) {+ HTML::WebViewHints hints;+ hints.picture_in_picture_window = HTML::PictureInPictureWindowHints {+ .navigable_id = navigable->id(),+ .video_size = Gfx::Size<u32> { video.video_width(), video.video_height() }.to_type<int>(),+ };+ new_web_view = m_page->client().page_did_request_new_web_view(HTML::ActivateTab::No, hints, {}, {}, {}, {});+ }// 3. If the previous step failed:if (!new_web_view.page) {diff --git a/Libraries/LibWebCommon/HTML/WebViewHints.cpp b/Libraries/LibWebCommon/HTML/WebViewHints.cppindex 647a5e9ab9f..0451866d54d 100644--- a/Libraries/LibWebCommon/HTML/WebViewHints.cpp+++ b/Libraries/LibWebCommon/HTML/WebViewHints.cpp@@ -10,11 +10,27 @@namespace IPC {+template<>+ErrorOr<void> encode(Encoder& encoder, ::Web::HTML::PictureInPictureWindowHints const& hints)+{+ TRY(encoder.encode(hints.navigable_id));+ TRY(encoder.encode(hints.video_size));+ return {};+}++template<>+ErrorOr<::Web::HTML::PictureInPictureWindowHints> decode(Decoder& decoder)+{+ auto navigable_id = TRY(decoder.decode<Web::HTML::CrossProcessId>());+ auto video_size = TRY(decoder.decode<Gfx::IntSize>());+ return ::Web::HTML::PictureInPictureWindowHints { navigable_id, video_size };+}+template<>ErrorOr<void> encode(Encoder& encoder, ::Web::HTML::WebViewHints const& data_holder){TRY(encoder.encode(data_holder.popup));- TRY(encoder.encode(data_holder.picture_in_picture_video_size));+ TRY(encoder.encode(data_holder.picture_in_picture_window));TRY(encoder.encode(data_holder.width));TRY(encoder.encode(data_holder.height));TRY(encoder.encode(data_holder.screen_x));@@ -27,7 +43,7 @@ template<>ErrorOr<::Web::HTML::WebViewHints> decode(Decoder& decoder){auto popup = TRY(decoder.decode<bool>());- auto picture_in_picture_video_size = TRY(decoder.decode<Optional<Gfx::IntSize>>());+ auto picture_in_picture_window = TRY(decoder.decode<Optional<Web::HTML::PictureInPictureWindowHints>>());auto width = TRY(decoder.decode<Optional<Web::DevicePixels>>());auto height = TRY(decoder.decode<Optional<Web::DevicePixels>>());auto screen_x = TRY(decoder.decode<Optional<Web::DevicePixels>>());@@ -35,7 +51,7 @@ ErrorOr<::Web::HTML::WebViewHints> decode(Decoder& decoder)return ::Web::HTML::WebViewHints {.popup = popup,- .picture_in_picture_video_size = picture_in_picture_video_size,+ .picture_in_picture_window = picture_in_picture_window,.width = width,.height = height,.screen_x = screen_x,diff --git a/Libraries/LibWebCommon/HTML/WebViewHints.h b/Libraries/LibWebCommon/HTML/WebViewHints.hindex 6f0f99c959e..715c040a7cd 100644--- a/Libraries/LibWebCommon/HTML/WebViewHints.h+++ b/Libraries/LibWebCommon/HTML/WebViewHints.h@@ -11,13 +11,20 @@#include <LibGfx/Size.h>#include <LibIPC/Forward.h>#include <LibWebCommon/Export.h>+#include <LibWebCommon/HTML/CrossProcessId.h>#include <LibWebCommon/PixelUnits.h>namespace Web::HTML {+struct PictureInPictureWindowHints {+ // The navigable whose active document requests the window for one of its videos.+ CrossProcessId navigable_id;+ Gfx::IntSize video_size;+};+struct WebViewHints {bool popup = false;- Optional<Gfx::IntSize> picture_in_picture_video_size;+ Optional<PictureInPictureWindowHints> picture_in_picture_window;Optional<DevicePixels> width;Optional<DevicePixels> height;Optional<DevicePixels> screen_x;@@ -28,6 +35,12 @@ struct WebViewHints {namespace IPC {+template<>+WEBCOMMON_API ErrorOr<void> encode(Encoder&, Web::HTML::PictureInPictureWindowHints const&);++template<>+WEBCOMMON_API ErrorOr<Web::HTML::PictureInPictureWindowHints> decode(Decoder&);+template<>WEBCOMMON_API ErrorOr<void> encode(Encoder&, Web::HTML::WebViewHints const&);diff --git a/Libraries/LibWebView/CanonicalNavigable.cpp b/Libraries/LibWebView/CanonicalNavigable.cppindex 177bcdd1008..d919b82f11f 100644--- a/Libraries/LibWebView/CanonicalNavigable.cpp+++ b/Libraries/LibWebView/CanonicalNavigable.cpp@@ -20,6 +20,7 @@#include <LibWebView/CanonicalDocument.h>#include <LibWebView/CanonicalTraversable.h>#include <LibWebView/CanonicalWindow.h>+#include <LibWebView/PictureInPictureManager.h>#include <LibWebView/ViewImplementation.h>#include <LibWebView/WebContentClient.h>@@ -1226,6 +1227,8 @@ void CanonicalNavigable::did_commit_navigation(CanonicalSessionHistoryEntry& enttraversable.remove_child_navigables_of(*this, *previous_document);if (auto previous_host = previous_document->host(); previous_host && previous_host != document->host() && previous_host->is_open())traversable.stop_hosting_in_page(*this, previous_host.release_nonnull());+ // The Picture-in-Picture window of the displaced document, or of a document it embedded, closes with it.+ PictureInPictureManager::the().active_documents_did_change();}// A navigation can commit while a newer navigation is already in flight. In that case update the replicateddiff --git a/Libraries/LibWebView/PictureInPictureManager.cpp b/Libraries/LibWebView/PictureInPictureManager.cppindex ca8b812ca30..2fb919eb879 100644--- a/Libraries/LibWebView/PictureInPictureManager.cpp+++ b/Libraries/LibWebView/PictureInPictureManager.cpp@@ -6,6 +6,9 @@#include <LibCore/EventLoop.h>#include <LibWebView/Application.h>+#include <LibWebView/CanonicalDocument.h>+#include <LibWebView/CanonicalNavigable.h>+#include <LibWebView/CanonicalSessionHistoryEntry.h>#include <LibWebView/PictureInPictureManager.h>#include <LibWebView/PictureInPictureWindow.h>#include <LibWebView/WebContentClient.h>@@ -19,7 +22,7 @@ PictureInPictureManager& PictureInPictureManager::the()return manager;}-String PictureInPictureManager::open_window(WebContentPage& requesting_page, CanonicalTraversable& traversable, Gfx::IntSize video_size)+String PictureInPictureManager::open_window(WebContentPage& requesting_page, CanonicalNavigable& requesting_navigable, CanonicalTraversable& traversable, Gfx::IntSize video_size){// A page that already has a window replaces it itself, so only other pages are told that they lost theirs.if (auto index = index_of_window_for(requesting_page); index.has_value())@@ -51,7 +54,7 @@ String PictureInPictureManager::open_window(WebContentPage& requesting_page, Can};auto& opened_window = *window;- m_windows.append({ requesting_page, window.release_nonnull() });+ m_windows.append({ requesting_page, requesting_navigable, requesting_navigable.active_document(), window.release_nonnull() });requesting_page.async_did_open_picture_in_picture_window(opened_window.size());return opened_window.handle();}@@ -68,6 +71,35 @@ void PictureInPictureManager::video_size_did_change(WebContentPage& page, Gfx::Im_windows[*index].window->set_video_size(video_size);}+// A document with a window open may replace it without user activation, until the window closes.+bool PictureInPictureManager::document_has_open_window(CanonicalNavigable const& navigable) const+{+ return any_of(m_windows, [&](auto const& window) {+ return window.navigable.ptr() == &navigable && window.document_is_active();+ });+}++// A window closes once the document it was opened for is no longer active, as that document's unloading steps close it.+void PictureInPictureManager::active_documents_did_change()+{+ for (size_t index = m_windows.size(); index-- > 0;) {+ if (m_windows[index].document_is_active())+ continue;+ auto page = m_windows[index].page;+ retire_window(index);+ if (page->is_open())+ page->async_picture_in_picture_window_did_close(false);+ }+}++bool PictureInPictureManager::Window::document_is_active() const+{+ if (!navigable || !document)+ return false;+ auto const& entry = navigable->active_session_history_entry();+ return entry && entry->document_state->document == document.ptr();+}+Optional<size_t> PictureInPictureManager::index_of_window_for(WebContentPage const& page) const{return m_windows.find_first_index_if([&](auto const& window) { return window.page.ptr() == &page; });@@ -88,7 +120,7 @@ void PictureInPictureManager::retire_window(size_t index)}// The window is gone as soon as the user closes it, and its page only learns of that after, so a page that is busy or-// misbehaves cannot keep it open.+// misbehaves cannot keep it open, or replace it as the window it has open.void PictureInPictureManager::window_did_close(PictureInPictureWindow& window, PictureInPictureWindow::VideoKeepsPlaying video_keeps_playing){auto index = index_of(window);diff --git a/Libraries/LibWebView/PictureInPictureManager.h b/Libraries/LibWebView/PictureInPictureManager.hindex 3a78373b24d..227b878f174 100644--- a/Libraries/LibWebView/PictureInPictureManager.h+++ b/Libraries/LibWebView/PictureInPictureManager.h@@ -12,6 +12,7 @@#include <AK/String.h>#include <AK/Types.h>#include <AK/Vector.h>+#include <AK/WeakPtr.h>#include <AK/kmalloc.h>#include <LibGfx/Size.h>#include <LibWebCommon/Page/PageId.h>@@ -20,9 +21,9 @@namespace WebView {-// Owns the Picture-in-Picture windows the browser shows, each with the page whose video it shows. A page that opens a-// window takes it from any other page that had one. A window shows a page of its own, which the requesting page created-// in its process.+// Owns the Picture-in-Picture windows the browser shows, each with the page whose video it shows, and the document of+// that video. A page that opens a window takes it from any other page that had one. A window shows a page of its own,+// which the requesting page created in its process.class WEBVIEW_API PictureInPictureManager {public:AK_ALLOC_WITH_KMALLOC;@@ -30,14 +31,21 @@ public:static PictureInPictureManager& the();// Returns the window's handle, or an empty string when no window could be opened.- String open_window(WebContentPage& requesting_page, CanonicalTraversable&, Gfx::IntSize video_size);+ String open_window(WebContentPage& requesting_page, CanonicalNavigable& requesting_navigable, CanonicalTraversable&, Gfx::IntSize video_size);void close_window(WebContentPage&);void video_size_did_change(WebContentPage&, Gfx::IntSize);+ bool document_has_open_window(CanonicalNavigable const&) const;+ void active_documents_did_change();+private:struct Window {NonnullRefPtr<WebContentPage> page;+ WeakPtr<CanonicalNavigable> navigable;+ WeakPtr<CanonicalDocument> document;NonnullOwnPtr<PictureInPictureWindow> window;++ bool document_is_active() const;};Optional<size_t> index_of_window_for(WebContentPage const&) const;diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cppindex 7fb1f126090..b7385e1b63e 100644--- a/Libraries/LibWebView/WebContentPage.cpp+++ b/Libraries/LibWebView/WebContentPage.cpp@@ -2537,10 +2537,24 @@ Messages::WebContentClient::DidRequestNewWebViewResponse WebContentPage::did_reqreturn { {}, {}, {}, {}, {}, {}, Web::HTML::VisibilityState::Hidden, {} };}- // The popup blocker runs in the renderer, which a compromised renderer skips. Each popup takes the activation of- // input the UI process delivered to the page, as the renderer's popup consumes the activation of its window.- if (Application::the().blocks_pop_ups() && !consume_transient_user_activation())- return { {}, {}, {}, {}, {}, {}, Web::HTML::VisibilityState::Hidden, {} };+ Optional<CanonicalNavigable&> picture_in_picture_navigable;+ if (hints.picture_in_picture_window.has_value()) {+ picture_in_picture_navigable = hosted_navigable(hints.picture_in_picture_window->navigable_id);+ if (!picture_in_picture_navigable.has_value())+ return { {}, {}, {}, {}, {}, {}, Web::HTML::VisibilityState::Hidden, {} };++ // https://w3c.github.io/picture-in-picture/#request-picture-in-picture+ // A window needs and consumes the activation of the user's input, which the renderer checks, unless the document+ // asking for it has one open. A compromised renderer skips that check, so whatever the popup setting, the UI+ // process checks the activation of input it delivered, and the window it opened for the navigable's document.+ if (!PictureInPictureManager::the().document_has_open_window(*picture_in_picture_navigable) && !consume_transient_user_activation())+ return { {}, {}, {}, {}, {}, {}, Web::HTML::VisibilityState::Hidden, {} };+ } else {+ // The popup blocker runs in the renderer, which a compromised renderer skips. Each popup takes the activation of+ // input the UI process delivered to the page, as the renderer's popup consumes the activation of its window.+ if (Application::the().blocks_pop_ups() && !consume_transient_user_activation())+ return { {}, {}, {}, {}, {}, {}, Web::HTML::VisibilityState::Hidden, {} };+ }auto root_navigable_id = Application::the().allocate_ui_process_cross_process_id();auto initial_history_entry = Web::HTML::create_initial_session_history_entry_descriptor(@@ -2564,8 +2578,8 @@ Messages::WebContentClient::DidRequestNewWebViewResponse WebContentPage::did_reqclient().open_page_for_new_top_level_traversable(new_page_id, traversable);String window_handle;- if (hints.picture_in_picture_video_size.has_value()) {- window_handle = PictureInPictureManager::the().open_window(*this, traversable, *hints.picture_in_picture_video_size);+ if (picture_in_picture_navigable.has_value()) {+ window_handle = PictureInPictureManager::the().open_window(*this, *picture_in_picture_navigable, traversable, hints.picture_in_picture_window->video_size);} else if (view().on_new_web_view) {window_handle = view().on_new_web_view(activate_tab, hints, traversable);}diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txtindex 03aa3e7e2a4..58e989b3633 100644--- a/Tests/LibWebView/CMakeLists.txt+++ b/Tests/LibWebView/CMakeLists.txt@@ -176,6 +176,13 @@ if (NOT WIN32)target_compile_definitions(TestUserActivation PRIVATE LADYBIRD_BINARY_PATH="$<TARGET_FILE_DIR:ladybird>")endif()+ add_executable(TestPictureInPictureUserActivation TestPictureInPictureUserActivation.cpp)+ add_dependencies(TestPictureInPictureUserActivation ladybird_build_resource_files ${ladybird_helper_processes})+ target_link_libraries(TestPictureInPictureUserActivation PRIVATE AK LibCore LibDiff LibFileSystem LibGfx LibImageDecoders LibImageDecoderClient LibIPC LibJS LibMain LibRequests LibURL LibWeb LibWebView)+ if (APPLE)+ target_compile_definitions(TestPictureInPictureUserActivation PRIVATE LADYBIRD_BINARY_PATH="$<TARGET_FILE_DIR:ladybird>")+ endif()+add_executable(TestPictureInPictureWindowControls TestPictureInPictureWindowControls.cpp)add_dependencies(TestPictureInPictureWindowControls ladybird_build_resource_files ${ladybird_helper_processes})target_link_libraries(TestPictureInPictureWindowControls PRIVATE AK LibCore LibDiff LibFileSystem LibGfx LibImageDecoders LibImageDecoderClient LibIPC LibJS LibMain LibRequests LibURL LibWeb LibWebView)@@ -371,6 +378,9 @@ if (BUILD_TESTING AND NOT WIN32)add_test(NAME TestUserActivation COMMAND $<TARGET_FILE:TestUserActivation>)set_tests_properties(TestUserActivation PROPERTIES TIMEOUT 60 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})+ add_test(NAME TestPictureInPictureUserActivation COMMAND $<TARGET_FILE:TestPictureInPictureUserActivation>)+ set_tests_properties(TestPictureInPictureUserActivation PROPERTIES TIMEOUT 60 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})+add_test(NAME TestPictureInPictureWindowControls COMMAND $<TARGET_FILE:TestPictureInPictureWindowControls>)set_tests_properties(TestPictureInPictureWindowControls PROPERTIES TIMEOUT 60 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})diff --git a/Tests/LibWebView/TestPictureInPictureUserActivation.cpp b/Tests/LibWebView/TestPictureInPictureUserActivation.cppnew file mode 100644index 00000000000..92ab3b1af53--- /dev/null+++ b/Tests/LibWebView/TestPictureInPictureUserActivation.cpp@@ -0,0 +1,222 @@+/*+ * 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/Vector.h>+#include <LibCore/Directory.h>+#include <LibCore/Environment.h>+#include <LibCore/EventLoop.h>+#include <LibCore/StandardPaths.h>+#include <LibCore/System.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 <signal.h>++namespace {++// A headless window is never shown, so this records whether the browser hid it.+class RecordingPictureInPictureWindow final : public WebView::PictureInPictureWindow {+public:+ AK_ALLOC_WITH_KMALLOC;++ explicit RecordingPictureInPictureWindow(NonnullOwnPtr<WebView::PictureInPictureWindow> window)+ : m_window(move(window))+ {+ m_window->on_resize = [this](auto size) {+ if (on_resize)+ on_resize(size);+ };+ m_window->on_page_close = [this] {+ if (on_page_close)+ on_page_close();+ };+ }++ virtual Gfx::IntSize size() const override { return m_window->size(); }+ virtual String handle() const override { return m_window->handle(); }+ virtual void set_video_size(Gfx::IntSize video_size) override { m_window->set_video_size(video_size); }++ virtual void hide() override+ {+ is_hidden = true;+ m_window->hide();+ }++ bool is_hidden { false };++private:+ NonnullOwnPtr<WebView::PictureInPictureWindow> m_window;+};++class TestApplication : public WebView::Application {+ WEB_VIEW_APPLICATION(TestApplication)++public:+ explicit TestApplication(Optional<ByteString> ladybird_binary_path)+ : WebView::Application(move(ladybird_binary_path))+ {+ }++ // NB: Outside test mode, automation, and the internals object, a renderer cannot synthesize input, so the UI process+ // honors only user activation from input it delivered. Pop-ups are allowed, so that only the check for a+ // Picture-in-Picture window can refuse one.+ virtual void create_platform_options(WebView::BrowserOptions& browser_options, WebView::RequestServerOptions&, WebView::WebContentOptions&) override+ {+ browser_options.headless_mode = WebView::HeadlessMode::Test;+ browser_options.disable_sql_database = WebView::DisableSQLDatabase::Yes;+ browser_options.allow_popups = WebView::AllowPopups::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)+ return {};+ auto recording_window = make<RecordingPictureInPictureWindow>(window.release_nonnull());+ opened_windows.append(recording_window.ptr());+ return recording_window;+ }++ Vector<RecordingPictureInPictureWindow*> opened_windows;+};++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(WebView::ViewImplementation& view, Web::DevicePixelPoint position)+{+ view.enqueue_input_event(Web::MouseEvent {+ .type = Web::MouseEvent::Type::MouseDown,+ .position = position,+ .screen_position = position,+ .button = Web::UIEvents::MouseButton::Primary,+ .buttons = Web::UIEvents::MouseButton::Primary,+ .click_count = 1,+ .browser_data = nullptr,+ });+ view.enqueue_input_event(Web::MouseEvent {+ .type = Web::MouseEvent::Type::MouseUp,+ .position = position,+ .screen_position = position,+ .button = Web::UIEvents::MouseButton::Primary,+ .click_count = 1,+ .browser_data = nullptr,+ });+}++// 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;++}++// A document needs the activation of the user's input to open a Picture-in-Picture window, unless it has one open, which+// it may replace with one for another of its videos. The window is gone as soon as the user closes it, whatever its+// renderer does, and the document needs that activation again, even before its page has heard that the window closed.++ErrorOr<int> ladybird_main(Main::Arguments arguments)+{+ auto test_config_directory = ByteString::formatted("{}/Ladybird-TestPictureInPictureUserActivation-{}", 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+ VERIFY(!app->blocks_pop_ups());++ 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 view = WebView::HeadlessWebView::create(move(theme), { 800, 600 });++ size_t loads_finished = 0;+ view->on_load_finish = [&](auto const&) { ++loads_finished; };++ Utf16String last_title;+ view->on_title_change = [&](auto const& title) { last_title = title; };++ // Wait out the initial about:blank load; navigating before it completes would drop the navigation.+ Core::EventLoop::current().spin_until([&]() { return loads_finished >= 1; });++ // A button filling the viewport asks for a window for the first of two videos, and the page reports how each request+ // went through its title.+ view->load_html(MUST(String::formatted(+ "<!DOCTYPE html>"+ "<button onclick=\"enter(first)\" style=\"position:fixed;left:0;top:0;width:800px;height:600px\">Enter</button>"+ "<video id=first src=\"{0}\"></video>"+ "<video id=second src=\"{0}\"></video>"+ "<script>"+ "function enter(video) {{"+ " video.requestPictureInPicture().then(() => {{ document.title = `${{video.id}} entered`; }}, error => {{ document.title = `${{video.id}} ${{error.name}}`; }});"+ "}}"+ "Promise.all([first, second].map(video => new Promise(resolve => {{"+ " if (video.readyState >= HTMLMediaElement.HAVE_METADATA) resolve(); else video.addEventListener('loadedmetadata', resolve, {{ once: true }});"+ "}}))).then(() => {{ document.title = 'ready'; }});"+ "</script>",+ video_url)));+ Core::EventLoop::current().spin_until([&]() { return last_title == "ready"sv; });++ click(*view, { 400, 300 });+ Core::EventLoop::current().spin_until([&]() { return last_title.starts_with("first "sv); });+ VERIFY(last_title == "first entered"sv);+ VERIFY(app->opened_windows.size() == 1);+ outln("a click opens a window");++ // The window took the click's activation, so the document opens the next window as the one with a window open.+ view->run_javascript("enter(second)"_string);+ Core::EventLoop::current().spin_until([&]() { return last_title.starts_with("second "sv); });+ VERIFY(last_title == "second entered"sv);+ VERIFY(app->opened_windows.size() == 2);+ outln("a document replaces its window without a click");++ // The window is gone as soon as the user closes it, even while its renderer cannot answer.+ auto& closed_window = *app->opened_windows.last();+ signal_renderers(SIGSTOP);+ closed_window.on_close(WebView::PictureInPictureWindow::VideoKeepsPlaying::Yes);+ VERIFY(closed_window.is_hidden);+ outln("the window hides as the user closes it, while its renderer is stopped");++ // The page hears that the user closed the window only after it asks for another, so it asks as a document that has a+ // window open.+ view->run_javascript("enter(first)"_string);+ signal_renderers(SIGCONT);+ Core::EventLoop::current().spin_until([&]() { return last_title.starts_with("first "sv); });+ VERIFY(last_title == "first InvalidStateError"sv);+ VERIFY(app->opened_windows.size() == 2);+ outln("a document needs a click again once the user closes its window");++ return 0;+}