Skip to content

Truly independent web browser

LibWeb+LibWebView+WebContent: Implement the Picture-in-Picture API

Luke Wildedada435df113
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index d0d012fd3f1..40e56bddfb7 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -812,6 +812,9 @@ set(SOURCES
PermissionsAPI/Permissions.cpp
PermissionsAPI/PermissionStore.cpp
PermissionsAPI/PermissionStatus.cpp
+ PictureInPicture/PictureInPictureController.cpp
+ PictureInPicture/PictureInPictureEvent.cpp
+ PictureInPicture/PictureInPictureWindow.cpp
Platform/EventLoopPlugin.cpp
Platform/FontPlugin.cpp
Platform/ImageCodecPlugin.cpp
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index 9720c91f6b4..faf3af248f1 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -229,6 +229,7 @@
#include <LibWeb/Painting/HitTestDisplayList.h>
#include <LibWeb/Painting/PaintableTypes.h>
#include <LibWeb/Painting/PaintingRustBridge.h>
+#include <LibWeb/PictureInPicture/PictureInPictureController.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/ResizeObserver/ResizeObserver.h>
#include <LibWeb/ResizeObserver/ResizeObserverEntry.h>
@@ -1033,6 +1034,7 @@ void Document::visit_edges(Cell::Visitor& visitor)
visitor.visit(view_transition);
visitor.visit(m_top_layer_elements);
+ visitor.visit(m_picture_in_picture_element);
visitor.visit(m_top_layer_pending_removals);
visitor.visit(m_elements_with_pending_top_layer_membership_change);
visitor.visit(m_showing_auto_popover_list);
@@ -6312,6 +6314,7 @@ void Document::run_unloading_cleanup_steps()
FileAPI::run_unloading_cleanup_steps(*this);
fully_exit_fullscreen();
+ PictureInPicture::run_unloading_cleanup_steps(*this);
}
// https://html.spec.whatwg.org/multipage/document-lifecycle.html#destroy-a-document
@@ -6823,6 +6826,9 @@ bool Document::is_allowed_to_use_feature(PolicyControlledFeature feature) const
case PolicyControlledFeature::Microphone:
// FIXME: Implement allowlist for this.
return true;
+ case PolicyControlledFeature::PictureInPicture:
+ // FIXME: Implement allowlist for this.
+ return true;
case PolicyControlledFeature::WindowManagement:
// FIXME: Implement allowlist for this.
return true;
@@ -10546,6 +10552,66 @@ GC::Ref<GC::HeapVector<GC::Ref<Document>>> Document::collect_documents_to_unfull
return docs;
}
+void Document::set_picture_in_picture_element(GC::Ptr<Element> element)
+{
+ m_picture_in_picture_element = element;
+}
+
+// https://w3c.github.io/picture-in-picture/#dom-documentorshadowroot-pictureinpictureelement
+GC::Ptr<Element> Document::retargeted_picture_in_picture_element() const
+{
+ // 1. If this is a shadow root and its host is not connected, return null and abort these steps.
+ // NB: We're not a shadow root. See ShadowRoot::retargeted_picture_in_picture_element().
+
+ // 2. Let candidate be the result of retargeting Picture-in-Picture element against this.
+ auto* candidate = as_if<Element>(retarget(m_picture_in_picture_element.ptr(), const_cast<Document*>(this)));
+ if (!candidate)
+ return nullptr;
+
+ // 3. If candidate and this are in the same tree, return candidate and abort these steps.
+ if (&candidate->root() == &root())
+ return candidate;
+
+ // AD-HOC: An element that was never inserted into this document is not in its tree, but the spec intends to
+ // return it all the same. This adds the step proposed in
+ // https://github.com/w3c/picture-in-picture/pull/253.
+ // If this is a Document and candidate's node document is this, return candidate.
+ if (&candidate->document() == this)
+ return candidate;
+
+ // 4. Return null.
+ return nullptr;
+}
+
+// https://w3c.github.io/picture-in-picture/#dom-document-pictureinpictureenabled
+bool Document::picture_in_picture_enabled() const
+{
+ // The pictureInPictureEnabled attribute's getter must return true if Picture-in-Picture support is true and this
+ // is allowed to use the feature indicated by attribute name picture-in-picture, and false otherwise.
+ return page().picture_in_picture_controller().has_picture_in_picture_support()
+ && is_allowed_to_use_feature(PolicyControlledFeature::PictureInPicture);
+}
+
+// https://w3c.github.io/picture-in-picture/#dom-document-exitpictureinpicture
+// AD-HOC: This follows the overhaul proposed in https://github.com/w3c/picture-in-picture/pull/260, since the current
+// text mutates the DOM from its parallel steps.
+GC::Ref<WebIDL::Promise> Document::exit_picture_in_picture()
+{
+ auto& realm = HTML::relevant_realm(*this);
+
+ // 1. If this's Picture-in-Picture element is null or this is not fully active, return a promise rejected with
+ // InvalidStateError DOMException.
+ if (!m_picture_in_picture_element || !is_fully_active())
+ return WebIDL::create_rejected_promise(realm, WebIDL::InvalidStateError::create("There is no Picture-in-Picture element to exit"_utf16));
+
+ // 2. Let p be a new promise created in this's relevant realm.
+ auto promise = WebIDL::create_promise(realm);
+
+ // 3. Return p, and enqueue the following steps to this's picture-in-picture parallel queue:
+ page().picture_in_picture_controller().enqueue_exit(*this, promise);
+ return promise;
+}
+
// https://fullscreen.spec.whatwg.org/#unfullscreen-an-element
void Document::unfullscreen_element(GC::Ref<Element> element)
{
diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.h
index a8520afb408..3178dd342d1 100644
--- a/Libraries/LibWeb/DOM/Document.h
+++ b/Libraries/LibWeb/DOM/Document.h
@@ -265,6 +265,7 @@ enum class PolicyControlledFeature : u8 {
Fullscreen,
Gamepad,
Microphone,
+ PictureInPicture,
WindowManagement,
};
@@ -1617,6 +1618,12 @@ public:
bool is_simple_fullscreen_document() const;
GC::Ref<GC::HeapVector<GC::Ref<Document>>> collect_documents_to_unfullscreen();
+ GC::Ptr<Element> picture_in_picture_element() const { return m_picture_in_picture_element; }
+ void set_picture_in_picture_element(GC::Ptr<Element>);
+ GC::Ptr<Element> retargeted_picture_in_picture_element() const;
+ bool picture_in_picture_enabled() const;
+ GC::Ref<WebIDL::Promise> exit_picture_in_picture();
+
auto& script_blocking_style_sheet_set() { return m_script_blocking_style_sheet_set; }
auto const& script_blocking_style_sheet_set() const { return m_script_blocking_style_sheet_set; }
void remove_from_script_blocking_style_sheet_set(Element&);
@@ -2352,6 +2359,9 @@ private:
// https://fullscreen.spec.whatwg.org/#list-of-pending-fullscreen-events
Vector<PendingFullscreenEvent> m_pending_fullscreen_events;
+ // https://w3c.github.io/picture-in-picture/#picture-in-picture-element
+ GC::Ptr<Element> m_picture_in_picture_element;
+
// https://dom.spec.whatwg.org/#document-custom-element-registry
GC::Ptr<HTML::CustomElementRegistry> m_custom_element_registry;
diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cpp
index a7508e270c9..90538daa618 100644
--- a/Libraries/LibWeb/DOM/Element.cpp
+++ b/Libraries/LibWeb/DOM/Element.cpp
@@ -6951,6 +6951,11 @@ void Element::set_fullscreen_flag(bool is_fullscreen)
CSS::record_element_state_changed(*this, CSS::PseudoClass::Fullscreen, is_fullscreen);
}
+bool Element::is_picture_in_picture_element() const
+{
+ return document().picture_in_picture_element().ptr() == this;
+}
+
void Element::set_fullscreen_request_type(Fullscreen::RequestType request_type)
{
if (request_type == Fullscreen::RequestType::Standard) {
diff --git a/Libraries/LibWeb/DOM/Element.h b/Libraries/LibWeb/DOM/Element.h
index ffd80fd08e0..9ff384c0113 100644
--- a/Libraries/LibWeb/DOM/Element.h
+++ b/Libraries/LibWeb/DOM/Element.h
@@ -551,6 +551,8 @@ public:
GC::Ptr<WebIDL::CallbackType> onwebkitfullscreenerror();
void set_onwebkitfullscreenerror(GC::Ptr<WebIDL::CallbackType>);
+ bool is_picture_in_picture_element() const;
+
WebIDL::ExceptionOr<Utf16String> outer_html() const;
WebIDL::ExceptionOr<void> set_outer_html(StringView html);
diff --git a/Libraries/LibWeb/DOM/ShadowRoot.cpp b/Libraries/LibWeb/DOM/ShadowRoot.cpp
index e41eb1361ad..f86d5f002a2 100644
--- a/Libraries/LibWeb/DOM/ShadowRoot.cpp
+++ b/Libraries/LibWeb/DOM/ShadowRoot.cpp
@@ -110,6 +110,27 @@ GC::Ptr<Element> ShadowRoot::retargeted_fullscreen_element() const
return nullptr;
}
+// https://w3c.github.io/picture-in-picture/#dom-documentorshadowroot-pictureinpictureelement
+GC::Ptr<Element> ShadowRoot::retargeted_picture_in_picture_element() const
+{
+ // 1. If this is a shadow root and its host is not connected, return null and abort these steps.
+ if (!host() || !host()->is_connected())
+ return nullptr;
+
+ // 2. Let candidate be the result of retargeting Picture-in-Picture element against this.
+ // NB: Only a document has its Picture-in-Picture element set, so this retargets the one of this' document.
+ auto* candidate = as_if<Element>(retarget(document().picture_in_picture_element().ptr(), const_cast<ShadowRoot*>(this)));
+ if (!candidate)
+ return nullptr;
+
+ // 3. If candidate and this are in the same tree, return candidate and abort these steps.
+ if (&candidate->root() == &root())
+ return candidate;
+
+ // 4. Return null.
+ return nullptr;
+}
+
// https://dom.spec.whatwg.org/#dom-shadowroot-onslotchange
void ShadowRoot::set_onslotchange(WebIDL::CallbackType* event_handler)
{
diff --git a/Libraries/LibWeb/DOM/ShadowRoot.h b/Libraries/LibWeb/DOM/ShadowRoot.h
index 6bdc32c8bc8..5ca3ab73c68 100644
--- a/Libraries/LibWeb/DOM/ShadowRoot.h
+++ b/Libraries/LibWeb/DOM/ShadowRoot.h
@@ -116,6 +116,7 @@ public:
virtual void finalize() override;
GC::Ptr<Element> retargeted_fullscreen_element() const;
+ GC::Ptr<Element> retargeted_picture_in_picture_element() const;
// A shadow root is not an element and has no style of its own, but it is a parent in the style
// tree: it is what a shadow-tree element's relations name, and it is what bounds the region a
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index fd2c3f75643..6776c2440b0 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -1017,6 +1017,14 @@ class PermissionStatus;
}
+namespace Web::PictureInPicture {
+
+class PictureInPictureController;
+class PictureInPictureEvent;
+class PictureInPictureWindow;
+
+}
+
namespace Web::Platform {
class Timer;
diff --git a/Libraries/LibWeb/HTML/EventNames.h b/Libraries/LibWeb/HTML/EventNames.h
index c144654ad2e..764fa9245b5 100644
--- a/Libraries/LibWeb/HTML/EventNames.h
+++ b/Libraries/LibWeb/HTML/EventNames.h
@@ -64,6 +64,7 @@ namespace Web::HTML::EventNames {
__ENUMERATE_HTML_EVENT(end) \
__ENUMERATE_HTML_EVENT(ended) \
__ENUMERATE_HTML_EVENT(enter) \
+ __ENUMERATE_HTML_EVENT(enterpictureinpicture) \
__ENUMERATE_HTML_EVENT(error) \
__ENUMERATE_HTML_EVENT(exit) \
__ENUMERATE_HTML_EVENT(finish) \
@@ -77,6 +78,7 @@ namespace Web::HTML::EventNames {
__ENUMERATE_HTML_EVENT(input) \
__ENUMERATE_HTML_EVENT(invalid) \
__ENUMERATE_HTML_EVENT(languagechange) \
+ __ENUMERATE_HTML_EVENT(leavepictureinpicture) \
__ENUMERATE_HTML_EVENT(load) \
__ENUMERATE_HTML_EVENT(loaded) \
__ENUMERATE_HTML_EVENT(loadeddata) \
diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.h b/Libraries/LibWeb/HTML/HTMLMediaElement.h
index e570547e6ae..0fef7801a55 100644
--- a/Libraries/LibWeb/HTML/HTMLMediaElement.h
+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.h
@@ -74,6 +74,7 @@ public:
// NOTE: The function is wrapped in a GC::HeapFunction immediately.
void queue_a_media_element_task(Function<void(HTMLMediaElement&)>);
+ Task::Source media_element_event_task_source() const { return m_media_element_event_task_source.source; }
void cancel_the_fetching_process();
bool is_fetching() const;
@@ -218,8 +219,6 @@ private:
};
using ByteRange = Variant<EntireResource, UntilEnd>;
- Task::Source media_element_event_task_source() const { return m_media_element_event_task_source.source; }
-
WebIDL::ExceptionOr<void> load_element();
void select_resource_for_current_load();
void promote_current_resource_selection_to_explicit();
diff --git a/Libraries/LibWeb/HTML/HTMLVideoElement.cpp b/Libraries/LibWeb/HTML/HTMLVideoElement.cpp
index 000f7fbb3ea..b24b425f69c 100644
--- a/Libraries/LibWeb/HTML/HTMLVideoElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLVideoElement.cpp
@@ -13,6 +13,8 @@
#include <LibGfx/YUVData.h>
#include <LibMedia/VideoFrame.h>
#include <LibMedia/VideoSurface.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/CSS/ElementBoxKind.h>
#include <LibWeb/CSS/StyleEngineInput.h>
#include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
@@ -29,10 +31,16 @@
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/VideoTrack.h>
#include <LibWeb/HTML/VideoTrackList.h>
+#include <LibWeb/HTML/Window.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/Layout/Box.h>
+#include <LibWeb/Page/Page.h>
#include <LibWeb/Painting/PaintFacts.h>
+#include <LibWeb/PictureInPicture/PictureInPictureController.h>
+#include <LibWeb/PictureInPicture/PictureInPictureWindow.h>
#include <LibWeb/Platform/ImageCodecPlugin.h>
+#include <LibWeb/WebIDL/DOMException.h>
+#include <LibWeb/WebIDL/Promise.h>
namespace Web::HTML {
@@ -55,6 +63,7 @@ void HTMLVideoElement::visit_edges(Cell::Visitor& visitor)
Base::visit_edges(visitor);
visitor.visit(m_video_track);
visitor.visit(m_fetch_controller);
+ visitor.visit(m_picture_in_picture_window);
}
void HTMLVideoElement::adopted_from(DOM::Document& old_document)
@@ -362,4 +371,86 @@ Optional<Gfx::DecodedImageFrame> HTMLVideoElement::current_decoded_image_frame()
return Gfx::DecodedImageFrame { NonnullRefPtr<Gfx::Bitmap const> { *bitmap }, move(color_space) };
}
+// https://w3c.github.io/picture-in-picture/#request-picture-in-picture
+GC::Ref<WebIDL::Promise> HTMLVideoElement::request_picture_in_picture()
+{
+ auto& realm = HTML::relevant_realm(*this);
+ auto& controller = document().page().picture_in_picture_controller();
+
+ // 1. If Picture-in-Picture support is false, return a promise rejected with NotSupportedError DOMException.
+ if (!controller.has_picture_in_picture_support())
+ return WebIDL::create_rejected_promise(realm, WebIDL::NotSupportedError::create("Picture-in-Picture is not supported"_utf16));
+
+ // 2. Let doc be this's node document.
+ auto& document = this->document();
+
+ // 3. If doc is not allowed to use the policy-controlled feature named "picture-in-picture", return a promise
+ // rejected with NotAllowedError DOMException.
+ if (!document.is_allowed_to_use_feature(DOM::PolicyControlledFeature::PictureInPicture))
+ return WebIDL::create_rejected_promise(realm, WebIDL::NotAllowedError::create("Picture-in-Picture is not allowed in this document"_utf16));
+
+ // 4. If this's readyState attribute is HAVE_NOTHING, return a promise rejected with InvalidStateError DOMException.
+ if (ready_state() == ReadyState::HaveNothing)
+ return WebIDL::create_rejected_promise(realm, WebIDL::InvalidStateError::create("The video has no data"_utf16));
+
+ // 5. If this has no video track, return a promise rejected with InvalidStateError DOMException.
+ if (video_tracks()->length() == 0)
+ return WebIDL::create_rejected_promise(realm, WebIDL::InvalidStateError::create("The video has no video track"_utf16));
+
+ // 6. If this's disablePictureInPicture is true, user agent may return a promise rejected with InvalidStateError
+ // DOMException.
+ if (has_attribute(AttributeNames::disablepictureinpicture))
+ return WebIDL::create_rejected_promise(realm, WebIDL::InvalidStateError::create("Picture-in-Picture is disabled for the video"_utf16));
+
+ // 7. If doc's Picture-in-Picture element is null:
+ if (!document.picture_in_picture_element()) {
+ auto& window = relevant_window(*this);
+
+ // 1. If this's relevant global object does not have a transient activation, then return a promise rejected
+ // with NotAllowedError DOMException.
+ if (!window.has_transient_activation())
+ return WebIDL::create_rejected_promise(realm, WebIDL::NotAllowedError::create("Picture-in-Picture requires a user gesture"_utf16));
+
+ // 2. Consume user activation given this's relevant global object.
+ window.consume_user_activation();
+ }
+
+ // 8. If this is doc's Picture-in-Picture element:
+ if (is_picture_in_picture_element()) {
+ // 1. Return a promise resolved with the Picture-in-Picture window associated with doc's Picture-in-Picture
+ // element.
+ return WebIDL::create_resolved_promise(realm, Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, GC::Ref { *m_picture_in_picture_window }));
+ }
+
+ // 9. Let global be this's relevant global object.
+ // NB: The controller takes the global from this when it queues its tasks.
+
+ // 10. Let p be a new promise created in this's relevant realm.
+ auto promise = WebIDL::create_promise(realm);
+
+ // 11. Return p, and enqueue the following steps to doc's picture-in-picture parallel queue:
+ controller.enqueue_request(*this, promise);
+ return promise;
+}
+
+WebIDL::CallbackType* HTMLVideoElement::onenterpictureinpicture()
+{
+ return event_handler_attribute(HTML::EventNames::enterpictureinpicture);
+}
+
+void HTMLVideoElement::set_onenterpictureinpicture(WebIDL::CallbackType* event_handler)
+{
+ set_event_handler_attribute(HTML::EventNames::enterpictureinpicture, event_handler);
+}
+
+WebIDL::CallbackType* HTMLVideoElement::onleavepictureinpicture()
+{
+ return event_handler_attribute(HTML::EventNames::leavepictureinpicture);
+}
+
+void HTMLVideoElement::set_onleavepictureinpicture(WebIDL::CallbackType* event_handler)
+{
+ set_event_handler_attribute(HTML::EventNames::leavepictureinpicture, event_handler);
+}
+
}
diff --git a/Libraries/LibWeb/HTML/HTMLVideoElement.h b/Libraries/LibWeb/HTML/HTMLVideoElement.h
index 145118a011e..81c4e8780ea 100644
--- a/Libraries/LibWeb/HTML/HTMLVideoElement.h
+++ b/Libraries/LibWeb/HTML/HTMLVideoElement.h
@@ -56,6 +56,16 @@ public:
Optional<Gfx::DecodedImageFrame> current_decoded_image_frame() const;
+ GC::Ref<WebIDL::Promise> request_picture_in_picture();
+
+ GC::Ptr<PictureInPicture::PictureInPictureWindow> picture_in_picture_window() const { return m_picture_in_picture_window; }
+ void set_picture_in_picture_window(GC::Ptr<PictureInPicture::PictureInPictureWindow> window) { m_picture_in_picture_window = window; }
+
+ WebIDL::CallbackType* onenterpictureinpicture();
+ void set_onenterpictureinpicture(WebIDL::CallbackType*);
+ WebIDL::CallbackType* onleavepictureinpicture();
+ void set_onleavepictureinpicture(WebIDL::CallbackType*);
+
private:
HTMLVideoElement(DOM::Document&, DOM::QualifiedName);
virtual void finalize() override;
@@ -84,6 +94,8 @@ private:
GC::Ptr<Fetch::Infrastructure::FetchController> m_fetch_controller;
Optional<DOM::DocumentLoadEventDelayer> m_load_event_delayer;
+
+ GC::Ptr<PictureInPicture::PictureInPictureWindow> m_picture_in_picture_window;
};
}
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cpp
index 9ca5d8dfc2f..e95ce84323d 100644
--- a/Libraries/LibWeb/Internals/Internals.cpp
+++ b/Libraries/LibWeb/Internals/Internals.cpp
@@ -101,6 +101,7 @@
#include <LibWeb/Painting/HitTestResult.h>
#include <LibWeb/Painting/PaintingRustBridge.h>
#include <LibWeb/Painting/Scrolling.h>
+#include <LibWeb/PictureInPicture/PictureInPictureController.h>
#include <LibWeb/ResizeObserver/ResizeObserver.h>
#include <LibWeb/StyleValueRustFFI.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
@@ -1585,6 +1586,16 @@ bool Internals::screen_wake_lock_active()
return page().is_screen_wake_lock_active();
}
+Utf16String Internals::picture_in_picture_window_state()
+{
+ auto const& controller = page().picture_in_picture_controller();
+ if (controller.is_waiting_for_window_to_open())
+ return "opening"_utf16;
+ if (controller.has_open_window())
+ return "open"_utf16;
+ return "none"_utf16;
+}
+
static Utf16String dump_string_to_utf16(String const& string)
{
return Utf16String::from_utf8_without_validation(string.bytes_as_string_view());
diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.h
index e7851e7e4f1..afdc5e1f098 100644
--- a/Libraries/LibWeb/Internals/Internals.h
+++ b/Libraries/LibWeb/Internals/Internals.h
@@ -193,6 +193,7 @@ public:
bool headless();
bool screen_wake_lock_active();
+ Utf16String picture_in_picture_window_state();
bool needs_repaint();
bool needs_display_list_record();
diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idl
index 1b78fa45830..7ce265ba551 100644
--- a/Libraries/LibWeb/Internals/Internals.idl
+++ b/Libraries/LibWeb/Internals/Internals.idl
@@ -189,6 +189,7 @@ interface Internals {
readonly attribute boolean headless;
readonly attribute boolean screenWakeLockActive;
+ readonly attribute DOMString pictureInPictureWindowState;
readonly attribute boolean needsRepaint;
readonly attribute boolean needsDisplayListRecord;
diff --git a/Libraries/LibWeb/Page/Page.cpp b/Libraries/LibWeb/Page/Page.cpp
index ba1a727b8ea..ec599a3a457 100644
--- a/Libraries/LibWeb/Page/Page.cpp
+++ b/Libraries/LibWeb/Page/Page.cpp
@@ -43,6 +43,7 @@
#include <LibWeb/Page/Page.h>
#include <LibWeb/Painting/BoxViews.h>
#include <LibWeb/Painting/PaintFacts.h>
+#include <LibWeb/PictureInPicture/PictureInPictureController.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/Selection/Selection.h>
#include <LibWebCommon/Clipboard/SystemClipboard.h>
@@ -62,6 +63,7 @@ GC::Ref<Page> Page::create(GC::Ref<PageClient> page_client)
Page::Page(GC::Ref<PageClient> client)
: m_client(client)
, m_history_executor(GC::Heap::the().allocate<HTML::HistoryExecutor>(*this))
+ , m_picture_in_picture_controller(GC::Heap::the().allocate<PictureInPicture::PictureInPictureController>(*this))
{
}
@@ -130,6 +132,7 @@ void Page::visit_edges(JS::Cell::Visitor& visitor)
visitor.visit(m_top_level_traversable);
visitor.visit(m_navigables_being_destroyed);
visitor.visit(m_history_executor);
+ visitor.visit(m_picture_in_picture_controller);
visitor.visit(m_client);
visitor.visit(m_window_rect_observer);
visitor.visit(m_on_pending_dialog_closed);
diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.h
index e5012a2be4d..3bf540fd438 100644
--- a/Libraries/LibWeb/Page/Page.h
+++ b/Libraries/LibWeb/Page/Page.h
@@ -169,6 +169,8 @@ public:
HTML::HistoryExecutor& history_executor();
+ PictureInPicture::PictureInPictureController& picture_in_picture_controller() const { return *m_picture_in_picture_controller; }
+
GC::Ptr<HTML::Navigable> focused_navigable() const;
GC::Ptr<HTML::LocalNavigable> hosted_focused_navigable() const;
void set_focused_navigable(HTML::Navigable&);
@@ -491,6 +493,7 @@ private:
HTML::VisibilityState m_system_visibility_state { HTML::VisibilityState::Hidden };
GC::Ref<HTML::HistoryExecutor> m_history_executor;
+ GC::Ref<PictureInPicture::PictureInPictureController> m_picture_in_picture_controller;
struct ScreenshotTask {
Optional<UniqueNodeID> node_id;
@@ -709,6 +712,7 @@ public:
virtual void page_did_request_minimize_window() { }
virtual void page_did_request_fullscreen_window() { }
virtual void page_did_request_exit_fullscreen() { }
+ virtual void page_did_exit_picture_in_picture() { }
virtual void page_did_change_active_document_in_top_level_browsing_context(Web::DOM::Document&) { }
virtual void page_did_finish_loading(HTML::CrossProcessId, Optional<Utf16String> const&) { }
virtual Optional<u64> page_did_start_download(HTML::CrossProcessId navigable_id, Optional<Utf16String> const& navigation_id, URL::URL const&, ByteString const& suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data)
diff --git a/Libraries/LibWeb/PictureInPicture/HTMLVideoElementExtensions.idl b/Libraries/LibWeb/PictureInPicture/HTMLVideoElementExtensions.idl
index bc5199b0d66..e7010f2b836 100644
--- a/Libraries/LibWeb/PictureInPicture/HTMLVideoElementExtensions.idl
+++ b/Libraries/LibWeb/PictureInPicture/HTMLVideoElementExtensions.idl
@@ -1,4 +1,9 @@
// https://w3c.github.io/picture-in-picture/#htmlvideoelement-extensions
partial interface HTMLVideoElement {
+ [NewObject] Promise<PictureInPictureWindow> requestPictureInPicture();
+
+ attribute EventHandler onenterpictureinpicture;
+ attribute EventHandler onleavepictureinpicture;
+
[CEReactions, Reflect=disablepictureinpicture] attribute boolean disablePictureInPicture;
};
diff --git a/Libraries/LibWeb/PictureInPicture/PictureInPictureController.cpp b/Libraries/LibWeb/PictureInPicture/PictureInPictureController.cpp
new file mode 100644
index 00000000000..37aafcb7e2d
--- /dev/null
+++ b/Libraries/LibWeb/PictureInPicture/PictureInPictureController.cpp
@@ -0,0 +1,367 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Bindings/WrapperWorld.h>
+#include <LibWeb/DOM/Document.h>
+#include <LibWeb/HTML/EventLoop/EventLoop.h>
+#include <LibWeb/HTML/EventNames.h>
+#include <LibWeb/HTML/HTMLVideoElement.h>
+#include <LibWeb/HTML/LocalTraversableNavigable.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
+#include <LibWeb/HighResolutionTime/TimeOrigin.h>
+#include <LibWeb/Page/Page.h>
+#include <LibWeb/PictureInPicture/PictureInPictureController.h>
+#include <LibWeb/PictureInPicture/PictureInPictureEvent.h>
+#include <LibWeb/PictureInPicture/PictureInPictureWindow.h>
+#include <LibWeb/WebIDL/DOMException.h>
+#include <LibWeb/WebIDL/Promise.h>
+
+namespace Web::PictureInPicture {
+
+GC_DEFINE_ALLOCATOR(PictureInPictureController);
+
+PictureInPictureController::PictureInPictureController(Page& page)
+ : m_page(page)
+{
+}
+
+void PictureInPictureController::visit_edges(Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_page);
+ visitor.visit(m_pending_operations);
+ visitor.visit(m_window_awaiting_open);
+ visitor.visit(m_open_window);
+}
+
+void PictureInPictureController::WindowAwaitingOpen::visit_edges(GC::Cell::Visitor& visitor)
+{
+ request.visit_edges(visitor);
+ visitor.visit(traversable);
+}
+
+static void resolve_promise(WebIDL::Promise& promise, GC::Ptr<PictureInPictureWindow> window = nullptr)
+{
+ auto& realm = WebIDL::promise_realm(promise);
+ HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+ if (window)
+ WebIDL::resolve_promise(promise, Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, GC::Ref { *window }));
+ else
+ WebIDL::resolve_promise(promise);
+}
+
+static void reject_promise_with_invalid_state_error(WebIDL::Promise& promise, Utf16String const& message)
+{
+ auto& realm = WebIDL::promise_realm(promise);
+ HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+ WebIDL::reject_promise(promise, WebIDL::InvalidStateError::create(message));
+}
+
+static void fire_picture_in_picture_event(DOM::Element& element, Utf16FlyString const& event_name, PictureInPictureWindow& window)
+{
+ PictureInPictureEventInit event_init { { .bubbles = true }, window };
+ auto event = PictureInPictureEvent::create(event_name, event_init, HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(element)));
+ element.dispatch_event(event);
+}
+
+void PictureInPictureController::enqueue_request(HTML::HTMLVideoElement& video, WebIDL::Promise& promise)
+{
+ enqueue(Request { video, promise });
+}
+
+void PictureInPictureController::enqueue_exit(DOM::Document& document, WebIDL::Promise& promise)
+{
+ enqueue(Exit { document, promise });
+}
+
+void PictureInPictureController::enqueue_close_window(PictureInPictureWindow& window)
+{
+ enqueue(CloseWindow { window });
+}
+
+void PictureInPictureController::enqueue(Operation operation)
+{
+ m_pending_operations.append(move(operation));
+ process_pending_operations();
+}
+
+void PictureInPictureController::process_pending_operations()
+{
+ // A request suspends the queue until the UI process has opened the window for it.
+ while (!m_window_awaiting_open.has_value() && !m_pending_operations.is_empty()) {
+ auto operation = m_pending_operations.take_first();
+ operation.visit(
+ [&](Request const& request) {
+ run_request_steps(request);
+ },
+ [&](Exit const& exit) {
+ // https://w3c.github.io/picture-in-picture/#dom-document-exitpictureinpicture
+ // AD-HOC: These are the parallel steps of exitPictureInPicture() in the overhaul proposed in
+ // https://github.com/w3c/picture-in-picture/pull/260.
+ // 1. If this's Picture-in-Picture element is null:
+ if (!exit.document->picture_in_picture_element()) {
+ // 1. Queue a global task on the media element event task source given this's relevant global
+ // object to resolve p.
+ // AD-HOC: There is no media element to take the task source from, so this uses the DOM
+ // manipulation task source. The promise is rejected, as the overhaul's reviewers asked.
+ HTML::queue_global_task(HTML::Task::Source::DOMManipulation, HTML::relevant_global_object(*exit.document), GC::create_function(GC::Heap::the(), [promise = exit.promise] {
+ reject_promise_with_invalid_state_error(promise, "There is no Picture-in-Picture element to exit"_utf16);
+ }));
+
+ // 2. Return.
+ return;
+ }
+
+ // 2. Run the exit Picture-in-Picture algorithm given this and p.
+ run_exit_steps(exit.document, exit.promise, WindowIsOpenInUserInterface::Yes);
+ },
+ [&](CloseWindow const& close_window) {
+ // https://w3c.github.io/picture-in-picture/#unloading-steps
+ // 1. Run the close window algorithm with window.
+ this->close_window(close_window.window, WindowIsOpenInUserInterface::Yes);
+ },
+ [&](UserInterfaceClosedWindow const& closed_window) {
+ auto& window = *closed_window.window;
+ if (!window.is_open())
+ return;
+
+ // AD-HOC: The spec leaves closing the window to the user agent. When the user closes it, or the UI
+ // process gives it to another page, run the exit algorithm for the document it belongs to.
+ auto& video = window.video();
+ auto& document = video.document();
+ if (video.is_picture_in_picture_element())
+ run_exit_steps(document, nullptr, WindowIsOpenInUserInterface::No);
+ else
+ this->close_window(window, WindowIsOpenInUserInterface::No);
+ });
+ }
+}
+
+// https://w3c.github.io/picture-in-picture/#request-picture-in-picture
+void PictureInPictureController::run_request_steps(Request const& request)
+{
+ auto& video = *request.video;
+
+ // 1. If this is doc's Picture-in-Picture element:
+ if (video.is_picture_in_picture_element()) {
+ // 1. Queue a global task on the media element event task source given global to resolve p with the
+ // Picture-in-Picture window associated with this.
+ HTML::queue_global_task(video.media_element_event_task_source(), HTML::relevant_global_object(video), GC::create_function(GC::Heap::the(), [video = request.video, promise = request.promise] {
+ resolve_promise(promise, video->picture_in_picture_window());
+ }));
+
+ // 2. Abort these steps.
+ return;
+ }
+
+ // 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, {}, {}, {}, {});
+
+ // 3. If the previous step failed:
+ if (!new_web_view.page) {
+ // 1. Queue a global task on the media element event task source given global to reject p with
+ // InvalidStateError DOMException.
+ HTML::queue_global_task(video.media_element_event_task_source(), HTML::relevant_global_object(video), GC::create_function(GC::Heap::the(), [promise = request.promise] {
+ reject_promise_with_invalid_state_error(promise, "Unable to open a Picture-in-Picture window"_utf16);
+ }));
+
+ // 2. Abort these steps.
+ return;
+ }
+
+ auto traversable = HTML::LocalTraversableNavigable::create_for_new_web_view(move(new_web_view), nullptr);
+ m_window_awaiting_open = WindowAwaitingOpen { request, traversable };
+}
+
+void PictureInPictureController::did_open_window(Gfx::IntSize window_size)
+{
+ if (!m_window_awaiting_open.has_value())
+ return;
+
+ // https://w3c.github.io/picture-in-picture/#request-picture-in-picture
+ auto [request, traversable] = m_window_awaiting_open.release_value();
+ auto& video = *request.video;
+ auto& document = video.document();
+ auto& global = HTML::relevant_global_object(video);
+
+ // 4. Let pipWindow be a new instance of PictureInPictureWindow that represents this's associated
+ // Picture-in-Picture window.
+ auto picture_in_picture_window = PictureInPictureWindow::create(video, window_size, traversable);
+
+ // NB: The UI process opened the new window in place of any window this page had open. When that window belongs
+ // to doc's Picture-in-Picture element, the next step exits it.
+ if (m_open_window) {
+ auto& previous_video = m_open_window->video();
+ auto& previous_document = previous_video.document();
+
+ // AD-HOC: The spec assumes that each document has its own window. When another document's
+ // Picture-in-Picture element loses its window, run the exit algorithm for that document too.
+ if (&previous_document != &document && previous_video.is_picture_in_picture_element())
+ run_exit_steps(previous_document, nullptr, WindowIsOpenInUserInterface::No);
+ else
+ close_window(*m_open_window, WindowIsOpenInUserInterface::No);
+ }
+
+ // AD-HOC: This follows the overhaul proposed in https://github.com/w3c/picture-in-picture/pull/260, which runs
+ // the exit algorithm here rather than in the task below, so that leavepictureinpicture fires first.
+ // 5. If doc's Picture-in-Picture element is not null, run the exit Picture-in-Picture algorithm given doc and
+ // null.
+ if (document.picture_in_picture_element())
+ run_exit_steps(document, nullptr, WindowIsOpenInUserInterface::No);
+
+ video.set_picture_in_picture_window(picture_in_picture_window);
+ m_open_window = picture_in_picture_window;
+
+ // NB: A document that stopped being fully active while the window opened, such as by unloading, never runs the
+ // task below, so the window would stay open without entering Picture-in-Picture. It is closed again instead.
+ if (!document.is_fully_active()) {
+ close_window(picture_in_picture_window, WindowIsOpenInUserInterface::Yes);
+ process_pending_operations();
+ return;
+ }
+
+ // 6. Queue a global task on the media element event task source given global, to perform the following steps:
+ HTML::queue_global_task(video.media_element_event_task_source(), global, GC::create_function(GC::Heap::the(), [video = request.video, promise = request.promise, picture_in_picture_window] {
+ auto& document = video->document();
+
+ // 1. Set doc's Picture-in-Picture element to this.
+ document.set_picture_in_picture_element(video);
+
+ // 2. Append relevant settings object's origin to initiators of active Picture-in-Picture sessions.
+ // NB: Nothing reads this list, and https://github.com/w3c/picture-in-picture/issues/263 proposes its removal.
+
+ // 3. If this is fullscreenElement, then exit fullscreen.
+ // FIXME: Exit fullscreen.
+
+ // 4. Fire an event named enterpictureinpicture using PictureInPictureEvent at this with its bubbles attribute
+ // initialized to true and its pictureInPictureWindow attribute initialized to Picture-in-Picture window.
+ fire_picture_in_picture_event(video, HTML::EventNames::enterpictureinpicture, picture_in_picture_window);
+
+ // 5. Resolve p with pipWindow.
+ resolve_promise(promise, picture_in_picture_window);
+ }));
+
+ process_pending_operations();
+}
+
+// https://w3c.github.io/picture-in-picture/#exit-picture-in-picture-algorithm
+// AD-HOC: This follows the overhaul proposed in https://github.com/w3c/picture-in-picture/pull/260. The current text
+// fires leavepictureinpicture from a separately queued task, and does not say which document to exit. See
+// https://github.com/w3c/picture-in-picture/issues/252.
+void PictureInPictureController::run_exit_steps(DOM::Document& document, GC::Ptr<WebIDL::Promise> promise, WindowIsOpenInUserInterface window_is_open_in_user_interface)
+{
+ // 1. Assert that these steps are running on the picture-in-picture parallel queue.
+
+ // 2. Let global be doc's relevant global object.
+ auto& global = HTML::relevant_global_object(document);
+
+ // 3. Run the close window algorithm with the Picture-in-Picture window associated with doc's Picture-in-Picture
+ // element.
+ auto& video = as<HTML::HTMLVideoElement>(*document.picture_in_picture_element());
+ close_window(*video.picture_in_picture_window(), window_is_open_in_user_interface);
+
+ // 4. Queue a global task on the media element event task source given global, to perform the following steps:
+ HTML::queue_global_task(video.media_element_event_task_source(), global, GC::create_function(GC::Heap::the(), [document = GC::Ref { document }, promise] {
+ // 1. If doc is not fully active or doc's Picture-in-Picture element is null:
+ if (!document->is_fully_active() || !document->picture_in_picture_element()) {
+ // 1. If p is not null, resolve p with undefined.
+ // AD-HOC: Reject p instead, as the overhaul's reviewers asked.
+ if (promise)
+ reject_promise_with_invalid_state_error(*promise, "There is no Picture-in-Picture element to exit"_utf16);
+
+ // 2. Return.
+ return;
+ }
+
+ // 2. Let element be doc's Picture-in-Picture element.
+ auto& element = as<HTML::HTMLVideoElement>(*document->picture_in_picture_element());
+
+ // 3. Set doc's Picture-in-Picture element to null.
+ document->set_picture_in_picture_element(nullptr);
+
+ // 4. Fire an event named leavepictureinpicture using PictureInPictureEvent at the element with its bubbles
+ // attribute initialized to true and its pictureInPictureWindow attribute initialized to Picture-in-Picture
+ // window associated with element.
+ fire_picture_in_picture_event(element, HTML::EventNames::leavepictureinpicture, *element.picture_in_picture_window());
+
+ // 5. Remove one item matching relevant settings object's origin from initiators of active Picture-in-Picture
+ // sessions.
+ // NB: Nothing reads this list, and https://github.com/w3c/picture-in-picture/issues/263 proposes its removal.
+
+ // 6. If p is not null, resolve p with undefined.
+ if (promise)
+ resolve_promise(*promise);
+ }));
+}
+
+// https://w3c.github.io/picture-in-picture/#close-window-algorithm
+void PictureInPictureController::close_window(PictureInPictureWindow& window, WindowIsOpenInUserInterface window_is_open_in_user_interface)
+{
+ if (window.is_open()) {
+ window.close();
+ window.traversable().close_top_level_traversable(HTML::LocalTraversableNavigable::PromptToUnload::No);
+ }
+
+ if (m_open_window.ptr() != &window)
+ return;
+ m_open_window = nullptr;
+ if (window_is_open_in_user_interface == WindowIsOpenInUserInterface::Yes)
+ m_page->client().page_did_exit_picture_in_picture();
+}
+
+void PictureInPictureController::window_did_resize(Gfx::IntSize window_size)
+{
+ if (!m_open_window)
+ return;
+ m_open_window->set_size(window_size);
+
+ // https://w3c.github.io/picture-in-picture/#interface-picture-in-picture-window
+ // When the size of a Picture-in-Picture window pipWindow changes, the user agent MUST queue a task to fire an
+ // event named resize at pipWindow.
+ auto& video = m_open_window->video();
+ HTML::queue_global_task(video.media_element_event_task_source(), HTML::relevant_global_object(video), GC::create_function(GC::Heap::the(), [window = GC::Ref { *m_open_window }] {
+ window->dispatch_event(DOM::Event::create(HTML::relevant_global_object(window->video()), HTML::EventNames::resize));
+ }));
+}
+
+void PictureInPictureController::window_did_close()
+{
+ if (m_open_window)
+ enqueue(UserInterfaceClosedWindow { *m_open_window });
+}
+
+// https://w3c.github.io/picture-in-picture/#unloading-steps
+// AD-HOC: These are the unloading steps from the overhaul proposed in
+// https://github.com/w3c/picture-in-picture/pull/260. The current text runs the exit algorithm, which throws
+// when there is no Picture-in-Picture element.
+void run_unloading_cleanup_steps(DOM::Document& document)
+{
+ // 1. If doc's Picture-in-Picture element is null, return.
+ auto element = document.picture_in_picture_element();
+ if (!element)
+ return;
+
+ // 2. Let window be the Picture-in-Picture window associated with doc's Picture-in-Picture element.
+ auto window = as<HTML::HTMLVideoElement>(*element).picture_in_picture_window();
+
+ // 3. Set doc's Picture-in-Picture element to null.
+ document.set_picture_in_picture_element(nullptr);
+
+ // 4. Remove one item matching relevant settings object's origin from initiators of active Picture-in-Picture
+ // sessions.
+ // NB: Nothing reads this list, and https://github.com/w3c/picture-in-picture/issues/263 proposes its removal.
+
+ // 5. Enqueue the following steps to doc's picture-in-picture parallel queue:
+ document.page().picture_in_picture_controller().enqueue_close_window(*window);
+}
+
+}
diff --git a/Libraries/LibWeb/PictureInPicture/PictureInPictureController.h b/Libraries/LibWeb/PictureInPicture/PictureInPictureController.h
new file mode 100644
index 00000000000..5d5b2e76d46
--- /dev/null
+++ b/Libraries/LibWeb/PictureInPicture/PictureInPictureController.h
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Optional.h>
+#include <AK/Variant.h>
+#include <AK/Vector.h>
+#include <LibGC/Cell.h>
+#include <LibGC/CellAllocator.h>
+#include <LibGfx/Size.h>
+#include <LibWeb/Export.h>
+#include <LibWeb/Forward.h>
+#include <LibWeb/PictureInPicture/PictureInPictureWindow.h>
+
+namespace Web::PictureInPicture {
+
+// Runs the steps that the spec enqueues to a traversable navigable's picture-in-picture parallel queue, and tracks
+// the window that the UI process shows for this page. The UI shows a single window, so a page has at most one open.
+class WEB_API PictureInPictureController final : public GC::Cell {
+ GC_CELL(PictureInPictureController, GC::Cell);
+ GC_DECLARE_ALLOCATOR(PictureInPictureController);
+
+public:
+ bool has_picture_in_picture_support() const { return m_has_picture_in_picture_support; }
+ void set_has_picture_in_picture_support(bool has_support) { m_has_picture_in_picture_support = has_support; }
+
+ void enqueue_request(HTML::HTMLVideoElement&, WebIDL::Promise&);
+ void enqueue_exit(DOM::Document&, WebIDL::Promise&);
+ void enqueue_close_window(PictureInPictureWindow&);
+
+ void did_open_window(Gfx::IntSize window_size);
+ void window_did_resize(Gfx::IntSize);
+ void window_did_close();
+
+ bool is_waiting_for_window_to_open() const { return m_window_awaiting_open.has_value(); }
+ bool has_open_window() const { return m_open_window != nullptr; }
+
+private:
+ explicit PictureInPictureController(Page&);
+
+ virtual void visit_edges(Cell::Visitor&) override;
+
+ struct Request {
+ GC::Ref<HTML::HTMLVideoElement> video;
+ GC::Ref<WebIDL::Promise> promise;
+
+ void visit_edges(GC::Cell::Visitor& visitor)
+ {
+ visitor.visit(video);
+ visitor.visit(promise);
+ }
+ };
+
+ struct Exit {
+ GC::Ref<DOM::Document> document;
+ GC::Ref<WebIDL::Promise> promise;
+
+ void visit_edges(GC::Cell::Visitor& visitor)
+ {
+ visitor.visit(document);
+ visitor.visit(promise);
+ }
+ };
+
+ struct CloseWindow {
+ GC::Ref<PictureInPictureWindow> window;
+
+ void visit_edges(GC::Cell::Visitor& visitor) { visitor.visit(window); }
+ };
+
+ struct UserInterfaceClosedWindow {
+ GC::Ref<PictureInPictureWindow> window;
+
+ void visit_edges(GC::Cell::Visitor& visitor) { visitor.visit(window); }
+ };
+
+ using Operation = Variant<Request, Exit, CloseWindow, UserInterfaceClosedWindow>;
+
+ struct WindowAwaitingOpen {
+ Request request;
+ GC::Ref<HTML::LocalTraversableNavigable> traversable;
+
+ void visit_edges(GC::Cell::Visitor&);
+ };
+
+ enum class WindowIsOpenInUserInterface : bool {
+ No,
+ Yes,
+ };
+
+ void enqueue(Operation);
+ void process_pending_operations();
+
+ void run_request_steps(Request const&);
+ void run_exit_steps(DOM::Document&, GC::Ptr<WebIDL::Promise>, WindowIsOpenInUserInterface);
+ void close_window(PictureInPictureWindow&, WindowIsOpenInUserInterface);
+
+ GC::Ref<Page> m_page;
+ bool m_has_picture_in_picture_support { false };
+
+ Vector<Operation> m_pending_operations;
+ Optional<WindowAwaitingOpen> m_window_awaiting_open;
+
+ GC::Ptr<PictureInPictureWindow> m_open_window;
+};
+
+void run_unloading_cleanup_steps(DOM::Document&);
+
+}
diff --git a/Libraries/LibWeb/PictureInPicture/PictureInPictureDocumentExtensions.idl b/Libraries/LibWeb/PictureInPicture/PictureInPictureDocumentExtensions.idl
new file mode 100644
index 00000000000..c77b76a7c01
--- /dev/null
+++ b/Libraries/LibWeb/PictureInPicture/PictureInPictureDocumentExtensions.idl
@@ -0,0 +1,6 @@
+// https://w3c.github.io/picture-in-picture/#document-extensions
+partial interface Document {
+ readonly attribute boolean pictureInPictureEnabled;
+
+ [NewObject] Promise<undefined> exitPictureInPicture();
+};
diff --git a/Libraries/LibWeb/PictureInPicture/PictureInPictureDocumentOrShadowRootExtensions.idl b/Libraries/LibWeb/PictureInPicture/PictureInPictureDocumentOrShadowRootExtensions.idl
new file mode 100644
index 00000000000..3cd49c257c3
--- /dev/null
+++ b/Libraries/LibWeb/PictureInPicture/PictureInPictureDocumentOrShadowRootExtensions.idl
@@ -0,0 +1,4 @@
+// https://w3c.github.io/picture-in-picture/#documentorshadowroot-extension
+partial interface mixin DocumentOrShadowRoot {
+ [ImplementedAs=retargeted_picture_in_picture_element] readonly attribute Element? pictureInPictureElement;
+};
diff --git a/Libraries/LibWeb/PictureInPicture/PictureInPictureEvent.cpp b/Libraries/LibWeb/PictureInPicture/PictureInPictureEvent.cpp
new file mode 100644
index 00000000000..60591b7d8f2
--- /dev/null
+++ b/Libraries/LibWeb/PictureInPicture/PictureInPictureEvent.cpp
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/PictureInPicture/PictureInPictureEvent.h>
+
+namespace Web::PictureInPicture {
+
+GC_DEFINE_ALLOCATOR(PictureInPictureEvent);
+
+GC::Ref<PictureInPictureEvent> PictureInPictureEvent::create(Utf16FlyString const& event_name, PictureInPictureEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
+{
+ return GC::Heap::the().allocate<PictureInPictureEvent>(event_name, event_init, time_stamp);
+}
+
+PictureInPictureEvent::PictureInPictureEvent(Utf16FlyString const& event_name, PictureInPictureEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
+ : DOM::Event(event_name, event_init, time_stamp)
+ , m_picture_in_picture_window(event_init.picture_in_picture_window)
+{
+}
+
+PictureInPictureEvent::~PictureInPictureEvent() = default;
+
+void PictureInPictureEvent::visit_edges(GC::Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_picture_in_picture_window);
+}
+
+}
diff --git a/Libraries/LibWeb/PictureInPicture/PictureInPictureEvent.h b/Libraries/LibWeb/PictureInPicture/PictureInPictureEvent.h
new file mode 100644
index 00000000000..79c2c3f4027
--- /dev/null
+++ b/Libraries/LibWeb/PictureInPicture/PictureInPictureEvent.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/Bindings/PictureInPictureEvent.h>
+#include <LibWeb/DOM/Event.h>
+#include <LibWeb/PictureInPicture/PictureInPictureWindow.h>
+
+namespace Web::PictureInPicture {
+
+using PictureInPictureEventInit = Bindings::PictureInPictureEventInit;
+
+// https://w3c.github.io/picture-in-picture/#pictureinpictureevent
+class PictureInPictureEvent final : public DOM::Event {
+ WEB_WRAPPABLE(PictureInPictureEvent, DOM::Event);
+ GC_DECLARE_ALLOCATOR(PictureInPictureEvent);
+
+public:
+ static constexpr size_t picture_in_picture_window_offset() { return offsetof(PictureInPictureEvent, m_picture_in_picture_window); }
+ [[nodiscard]] static GC::Ref<PictureInPictureEvent> create(Utf16FlyString const& event_name, PictureInPictureEventInit const&, HighResolutionTime::DOMHighResTimeStamp);
+
+ virtual ~PictureInPictureEvent() override;
+
+ GC::Ref<PictureInPictureWindow> picture_in_picture_window() const { return m_picture_in_picture_window; }
+
+private:
+ PictureInPictureEvent(Utf16FlyString const& event_name, PictureInPictureEventInit const&, HighResolutionTime::DOMHighResTimeStamp);
+
+ virtual void visit_edges(GC::Cell::Visitor&) override;
+
+ GC::Ref<PictureInPictureWindow> m_picture_in_picture_window;
+};
+
+}
diff --git a/Libraries/LibWeb/PictureInPicture/PictureInPictureEvent.idl b/Libraries/LibWeb/PictureInPicture/PictureInPictureEvent.idl
new file mode 100644
index 00000000000..df5e42cbedd
--- /dev/null
+++ b/Libraries/LibWeb/PictureInPicture/PictureInPictureEvent.idl
@@ -0,0 +1,10 @@
+// https://w3c.github.io/picture-in-picture/#event-types
+[Exposed=Window]
+interface PictureInPictureEvent : Event {
+ constructor(DOMString type, PictureInPictureEventInit eventInitDict);
+ [DirectGetter, SameObject] readonly attribute PictureInPictureWindow pictureInPictureWindow;
+};
+
+dictionary PictureInPictureEventInit : EventInit {
+ required PictureInPictureWindow pictureInPictureWindow;
+};
diff --git a/Libraries/LibWeb/PictureInPicture/PictureInPictureWindow.cpp b/Libraries/LibWeb/PictureInPicture/PictureInPictureWindow.cpp
new file mode 100644
index 00000000000..37fc867a768
--- /dev/null
+++ b/Libraries/LibWeb/PictureInPicture/PictureInPictureWindow.cpp
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/DOM/Document.h>
+#include <LibWeb/HTML/EventNames.h>
+#include <LibWeb/HTML/HTMLVideoElement.h>
+#include <LibWeb/HTML/LocalTraversableNavigable.h>
+#include <LibWeb/HTML/Window.h>
+#include <LibWeb/PictureInPicture/PictureInPictureWindow.h>
+
+namespace Web::PictureInPicture {
+
+GC_DEFINE_ALLOCATOR(PictureInPictureWindow);
+
+GC::Ref<PictureInPictureWindow> PictureInPictureWindow::create(HTML::HTMLVideoElement& video, Gfx::IntSize size, HTML::LocalTraversableNavigable& traversable)
+{
+ return GC::Heap::the().allocate<PictureInPictureWindow>(video, size, traversable);
+}
+
+// When instantiated, an instance of PictureInPictureWindow has its state set to opened.
+PictureInPictureWindow::PictureInPictureWindow(HTML::HTMLVideoElement& video, Gfx::IntSize size, HTML::LocalTraversableNavigable& traversable)
+ : m_video(video)
+ , m_traversable(traversable)
+ , m_size(size)
+{
+}
+
+PictureInPictureWindow::~PictureInPictureWindow() = default;
+
+void PictureInPictureWindow::visit_edges(Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_video);
+ visitor.visit(m_traversable);
+}
+
+GC::Ptr<Bindings::Wrappable> PictureInPictureWindow::relevant_global_impl() const
+{
+ return m_video->document().window();
+}
+
+// https://w3c.github.io/picture-in-picture/#dom-pictureinpicturewindow-width
+WebIDL::Long PictureInPictureWindow::width() const
+{
+ // The width attribute MUST return the width in CSS pixels of the Picture-in-Picture window associated with
+ // pictureInPictureElement if the state is opened. Otherwise, it MUST return 0.
+ return is_open() ? m_size.width() : 0;
+}
+
+// https://w3c.github.io/picture-in-picture/#dom-pictureinpicturewindow-height
+WebIDL::Long PictureInPictureWindow::height() const
+{
+ // The height attribute MUST return the height in CSS pixels of the Picture-in-Picture window associated with
+ // pictureInPictureElement if the state is opened. Otherwise, it MUST return 0.
+ return is_open() ? m_size.height() : 0;
+}
+
+// https://w3c.github.io/picture-in-picture/#close-window-algorithm
+void PictureInPictureWindow::close()
+{
+ // When the close window algorithm with an instance of PictureInPictureWindow is invoked, its state is set to
+ // closed.
+ m_state = State::Closed;
+}
+
+void PictureInPictureWindow::set_onresize(WebIDL::CallbackType* event_handler)
+{
+ set_event_handler_attribute(HTML::EventNames::resize, event_handler);
+}
+
+WebIDL::CallbackType* PictureInPictureWindow::onresize()
+{
+ return event_handler_attribute(HTML::EventNames::resize);
+}
+
+}
diff --git a/Libraries/LibWeb/PictureInPicture/PictureInPictureWindow.h b/Libraries/LibWeb/PictureInPicture/PictureInPictureWindow.h
new file mode 100644
index 00000000000..edc3591dc3c
--- /dev/null
+++ b/Libraries/LibWeb/PictureInPicture/PictureInPictureWindow.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibGfx/Size.h>
+#include <LibWeb/DOM/EventTarget.h>
+#include <LibWeb/Forward.h>
+#include <LibWebCommon/WebIDL/Types.h>
+
+namespace Web::PictureInPicture {
+
+// https://w3c.github.io/picture-in-picture/#interface-picture-in-picture-window
+class PictureInPictureWindow final : public DOM::EventTarget {
+ WEB_WRAPPABLE(PictureInPictureWindow, DOM::EventTarget);
+ GC_DECLARE_ALLOCATOR(PictureInPictureWindow);
+
+public:
+ [[nodiscard]] static GC::Ref<PictureInPictureWindow> create(HTML::HTMLVideoElement&, Gfx::IntSize, HTML::LocalTraversableNavigable&);
+
+ virtual ~PictureInPictureWindow() override;
+
+ HTML::HTMLVideoElement& video() const { return m_video; }
+ HTML::LocalTraversableNavigable& traversable() const { return m_traversable; }
+
+ WebIDL::Long width() const;
+ WebIDL::Long height() const;
+
+ bool is_open() const { return m_state == State::Opened; }
+ void set_size(Gfx::IntSize size) { m_size = size; }
+ void close();
+
+ void set_onresize(WebIDL::CallbackType*);
+ WebIDL::CallbackType* onresize();
+
+private:
+ PictureInPictureWindow(HTML::HTMLVideoElement&, Gfx::IntSize, HTML::LocalTraversableNavigable&);
+
+ virtual void visit_edges(Cell::Visitor&) override;
+ virtual GC::Ptr<Bindings::Wrappable> relevant_global_impl() const override;
+
+ enum class State : u8 {
+ Opened,
+ Closed,
+ };
+
+ GC::Ref<HTML::HTMLVideoElement> m_video;
+ GC::Ref<HTML::LocalTraversableNavigable> m_traversable;
+ Gfx::IntSize m_size;
+ State m_state { State::Opened };
+};
+
+}
diff --git a/Libraries/LibWeb/PictureInPicture/PictureInPictureWindow.idl b/Libraries/LibWeb/PictureInPicture/PictureInPictureWindow.idl
new file mode 100644
index 00000000000..462225439a7
--- /dev/null
+++ b/Libraries/LibWeb/PictureInPicture/PictureInPictureWindow.idl
@@ -0,0 +1,8 @@
+// https://w3c.github.io/picture-in-picture/#interface-picture-in-picture-window
+[Exposed=Window]
+interface PictureInPictureWindow : EventTarget {
+ readonly attribute long width;
+ readonly attribute long height;
+
+ attribute EventHandler onresize;
+};
diff --git a/Libraries/LibWeb/idl_files.cmake b/Libraries/LibWeb/idl_files.cmake
index 2b94b8be574..1fce0ddfecf 100644
--- a/Libraries/LibWeb/idl_files.cmake
+++ b/Libraries/LibWeb/idl_files.cmake
@@ -432,6 +432,10 @@ libweb_js_bindings(PerformanceTimeline/PerformanceObserverEntryList)
libweb_js_bindings(PermissionsAPI/Permissions)
libweb_js_bindings(PermissionsAPI/PermissionStatus)
libweb_js_bindings(PictureInPicture/HTMLVideoElementExtensions)
+libweb_js_bindings(PictureInPicture/PictureInPictureDocumentExtensions)
+libweb_js_bindings(PictureInPicture/PictureInPictureDocumentOrShadowRootExtensions)
+libweb_js_bindings(PictureInPicture/PictureInPictureEvent)
+libweb_js_bindings(PictureInPicture/PictureInPictureWindow)
libweb_js_bindings(RequestIdleCallback/IdleDeadline)
libweb_js_bindings(RequestIdleCallback/IdleRequest)
libweb_js_bindings(ResizeObserver/ResizeObserver)
diff --git a/Libraries/LibWebCommon/HTML/WebViewHints.cpp b/Libraries/LibWebCommon/HTML/WebViewHints.cpp
index 08d19746a15..647a5e9ab9f 100644
--- a/Libraries/LibWebCommon/HTML/WebViewHints.cpp
+++ b/Libraries/LibWebCommon/HTML/WebViewHints.cpp
@@ -14,6 +14,7 @@ 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.width));
TRY(encoder.encode(data_holder.height));
TRY(encoder.encode(data_holder.screen_x));
@@ -26,6 +27,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 width = TRY(decoder.decode<Optional<Web::DevicePixels>>());
auto height = TRY(decoder.decode<Optional<Web::DevicePixels>>());
auto screen_x = TRY(decoder.decode<Optional<Web::DevicePixels>>());
@@ -33,6 +35,7 @@ ErrorOr<::Web::HTML::WebViewHints> decode(Decoder& decoder)
return ::Web::HTML::WebViewHints {
.popup = popup,
+ .picture_in_picture_video_size = picture_in_picture_video_size,
.width = width,
.height = height,
.screen_x = screen_x,
diff --git a/Libraries/LibWebCommon/HTML/WebViewHints.h b/Libraries/LibWebCommon/HTML/WebViewHints.h
index 957f875923c..6f0f99c959e 100644
--- a/Libraries/LibWebCommon/HTML/WebViewHints.h
+++ b/Libraries/LibWebCommon/HTML/WebViewHints.h
@@ -8,6 +8,7 @@
#include <AK/Optional.h>
#include <AK/Types.h>
+#include <LibGfx/Size.h>
#include <LibIPC/Forward.h>
#include <LibWebCommon/Export.h>
#include <LibWebCommon/PixelUnits.h>
@@ -16,6 +17,7 @@ namespace Web::HTML {
struct WebViewHints {
bool popup = false;
+ Optional<Gfx::IntSize> picture_in_picture_video_size;
Optional<DevicePixels> width;
Optional<DevicePixels> height;
Optional<DevicePixels> screen_x;
diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cpp
index be85b30aa47..1c427e7a4de 100644
--- a/Libraries/LibWebView/Application.cpp
+++ b/Libraries/LibWebView/Application.cpp
@@ -58,6 +58,7 @@
#include <LibWebView/HelperProcess.h>
#include <LibWebView/HistoryStore.h>
#include <LibWebView/Menu.h>
+#include <LibWebView/PictureInPictureWindow.h>
#include <LibWebView/ProcessType.h>
#include <LibWebView/RequestServerManager.h>
#include <LibWebView/SessionStore.h>
@@ -2288,6 +2289,21 @@ bool Application::supports_clipboard_type(ClipboardType type) const
return type == ClipboardType::Text;
}
+bool Application::supports_picture_in_picture() const
+{
+ return browser_options().headless_mode.has_value();
+}
+
+OwnPtr<PictureInPictureWindow> Application::create_picture_in_picture_window(WebContentPage& requesting_page, CanonicalTraversable& traversable, Gfx::IntSize video_size)
+{
+ if (!browser_options().headless_mode.has_value())
+ return {};
+
+ // Every view in a headless browser is a HeadlessWebView.
+ auto& requesting_view = static_cast<HeadlessWebView&>(requesting_page.view());
+ return HeadlessWebView::create_picture_in_picture_window(requesting_view, traversable, video_size);
+}
+
Utf16String Application::clipboard_text(ClipboardType) const
{
for (auto const& representation : m_clipboard.system_clipboard_representations) {
diff --git a/Libraries/LibWebView/Application.h b/Libraries/LibWebView/Application.h
index 688ec1de125..17f3b4f80ef 100644
--- a/Libraries/LibWebView/Application.h
+++ b/Libraries/LibWebView/Application.h
@@ -131,6 +131,7 @@ public:
virtual bool supports_content_blocking_controls() const { return false; }
virtual bool supports_private_browsing_windows() const { return false; }
virtual bool supports_client_side_window_decorations() const { return false; }
+ virtual bool supports_picture_in_picture() const;
// Returns true if the platform sends momentum scroll events after a touchpad flick.
// If it does not, the compositor makes the fling.
virtual bool platform_reports_scroll_momentum() const { return true; }
@@ -138,6 +139,8 @@ public:
// This needs the platform to say when the fingers lift from the touchpad, or the scroller would stay stretched.
virtual bool platform_scrolls_elastically() const { return false; }
+ virtual OwnPtr<PictureInPictureWindow> create_picture_in_picture_window(WebContentPage& requesting_page, CanonicalTraversable&, Gfx::IntSize video_size);
+
void appearance_changed(Badge<ApplicationSettingsObserver>);
void tab_settings_changed(Badge<ApplicationSettingsObserver>);
diff --git a/Libraries/LibWebView/CMakeLists.txt b/Libraries/LibWebView/CMakeLists.txt
index 95c51e5dfca..7de5f2c6f3e 100644
--- a/Libraries/LibWebView/CMakeLists.txt
+++ b/Libraries/LibWebView/CMakeLists.txt
@@ -44,6 +44,8 @@ set(SOURCES
NavigationLoader.cpp
Omnibox.cpp
OmniboxEngagement.cpp
+ PictureInPictureManager.cpp
+ PictureInPictureWindow.cpp
Process.cpp
ProcessManager.cpp
TabPerformanceStats.cpp
diff --git a/Libraries/LibWebView/Forward.h b/Libraries/LibWebView/Forward.h
index d41d5a03143..43dff122459 100644
--- a/Libraries/LibWebView/Forward.h
+++ b/Libraries/LibWebView/Forward.h
@@ -46,6 +46,8 @@ class HSTSStore;
class Menu;
class NavigationLoader;
class OutOfProcessWebView;
+class PictureInPictureManager;
+class PictureInPictureWindow;
class ProcessManager;
class RequestServerInstance;
class RequestServerManager;
diff --git a/Libraries/LibWebView/HeadlessWebView.cpp b/Libraries/LibWebView/HeadlessWebView.cpp
index 6f95ae3bdc4..a0433a57402 100644
--- a/Libraries/LibWebView/HeadlessWebView.cpp
+++ b/Libraries/LibWebView/HeadlessWebView.cpp
@@ -6,12 +6,42 @@
#include <LibCore/EventLoop.h>
#include <LibWebView/HeadlessWebView.h>
+#include <LibWebView/PictureInPictureWindow.h>
namespace WebView {
static Web::DevicePixelRect const screen_rect { 0, 0, 1920, 1080 };
static constexpr auto child_close_timeout_ms = 1000;
+// A headless window is never shown, so it keeps the size it opens with until it is closed.
+class HeadlessPictureInPictureWindow final : public PictureInPictureWindow {
+public:
+ AK_ALLOC_WITH_KMALLOC;
+
+ HeadlessPictureInPictureWindow(Gfx::IntSize size, NonnullOwnPtr<HeadlessWebView> view)
+ : m_size(size)
+ , m_view(move(view))
+ {
+ report_page_close_of(*m_view);
+ }
+
+ virtual Gfx::IntSize size() const override { return m_size; }
+ virtual String handle() const override { return m_view->handle(); }
+ virtual void hide() override { }
+
+private:
+ Gfx::IntSize m_size;
+ NonnullOwnPtr<HeadlessWebView> m_view;
+};
+
+NonnullOwnPtr<PictureInPictureWindow> HeadlessWebView::create_picture_in_picture_window(HeadlessWebView& requesting_view, CanonicalTraversable& traversable, Gfx::IntSize video_size)
+{
+ auto size = PictureInPictureWindow::initial_size(video_size, screen_rect.size().to_type<int>());
+ auto view = create_child(requesting_view, traversable);
+ view->reset_viewport_size(size.to_type<Web::DevicePixels>());
+ return make<HeadlessPictureInPictureWindow>(size, move(view));
+}
+
NonnullOwnPtr<HeadlessWebView> HeadlessWebView::create(Core::AnonymousBuffer theme, Web::DevicePixelSize window_size, IsPrivate is_private)
{
auto view = adopt_own(*new HeadlessWebView(move(theme), window_size, is_private));
diff --git a/Libraries/LibWebView/HeadlessWebView.h b/Libraries/LibWebView/HeadlessWebView.h
index d78208ec832..0894375ff2e 100644
--- a/Libraries/LibWebView/HeadlessWebView.h
+++ b/Libraries/LibWebView/HeadlessWebView.h
@@ -23,6 +23,7 @@ public:
static NonnullOwnPtr<HeadlessWebView> create(Core::AnonymousBuffer theme, Web::DevicePixelSize window_size, IsPrivate = IsPrivate::No);
static NonnullOwnPtr<HeadlessWebView> create_child(HeadlessWebView&, CanonicalTraversable&);
+ static NonnullOwnPtr<PictureInPictureWindow> create_picture_in_picture_window(HeadlessWebView& requesting_view, CanonicalTraversable&, Gfx::IntSize video_size);
void reset_viewport_size(Web::DevicePixelSize);
diff --git a/Libraries/LibWebView/PictureInPictureManager.cpp b/Libraries/LibWebView/PictureInPictureManager.cpp
new file mode 100644
index 00000000000..68ce216b95b
--- /dev/null
+++ b/Libraries/LibWebView/PictureInPictureManager.cpp
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibCore/EventLoop.h>
+#include <LibWebView/Application.h>
+#include <LibWebView/PictureInPictureManager.h>
+#include <LibWebView/PictureInPictureWindow.h>
+#include <LibWebView/WebContentClient.h>
+#include <LibWebView/WebContentPage.h>
+
+namespace WebView {
+
+PictureInPictureManager& PictureInPictureManager::the()
+{
+ static auto& manager = *new PictureInPictureManager;
+ return manager;
+}
+
+String PictureInPictureManager::open_window(WebContentPage& requesting_page, 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())
+ retire_window(*index);
+
+ // Test mode loads unrelated pages side by side, so there they do not take the window from one another.
+ if (Application::web_content_options().is_test_mode == IsTestMode::No) {
+ while (!m_windows.is_empty()) {
+ auto page = m_windows.last().page;
+ retire_window(m_windows.size() - 1);
+ if (page->is_open())
+ page->async_picture_in_picture_window_did_close();
+ }
+ }
+
+ auto window = Application::the().create_picture_in_picture_window(requesting_page, traversable, video_size);
+ if (!window)
+ return {};
+
+ window->on_resize = [this, window = window.ptr()](Gfx::IntSize size) {
+ if (auto index = index_of(*window); index.has_value() && m_windows[*index].page->is_open())
+ m_windows[*index].page->async_picture_in_picture_window_did_resize(size);
+ };
+ window->on_close = [this, window = window.ptr()] {
+ window_did_close(*window);
+ };
+ window->on_page_close = [this, window = window.ptr()] {
+ window_page_did_close(*window);
+ };
+
+ auto& opened_window = *window;
+ m_windows.append({ requesting_page, window.release_nonnull() });
+ requesting_page.async_did_open_picture_in_picture_window(opened_window.size());
+ return opened_window.handle();
+}
+
+void PictureInPictureManager::close_window(WebContentPage& page)
+{
+ if (auto index = index_of_window_for(page); index.has_value())
+ retire_window(*index);
+}
+
+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; });
+}
+
+Optional<size_t> PictureInPictureManager::index_of(PictureInPictureWindow const& window) const
+{
+ return m_windows.find_first_index_if([&](auto const& entry) { return entry.window.ptr() == &window; });
+}
+
+// The page that a window shows outlives the window's place as another page's window, so a retired window stays hidden
+// until the page that it shows has closed.
+void PictureInPictureManager::retire_window(size_t index)
+{
+ auto window = m_windows.take(index).window;
+ window->hide();
+ m_retired_windows.append(move(window));
+}
+
+void PictureInPictureManager::window_did_close(PictureInPictureWindow& window)
+{
+ auto index = index_of(window);
+ if (!index.has_value())
+ return;
+ auto page = m_windows[*index].page;
+ retire_window(*index);
+
+ if (page->is_open())
+ page->async_picture_in_picture_window_did_close();
+}
+
+void PictureInPictureManager::window_page_did_close(PictureInPictureWindow& window)
+{
+ OwnPtr<PictureInPictureWindow> closed_window;
+ if (auto index = index_of(window); index.has_value()) {
+ closed_window = m_windows.take(*index).window;
+ } else if (auto index = m_retired_windows.find_first_index_if([&](auto const& retired_window) { return retired_window.ptr() == &window; }); index.has_value()) {
+ closed_window = m_retired_windows.take(*index);
+ }
+
+ // The window's page closes from within a callback of its view, so the window is destroyed once that returns.
+ Core::deferred_invoke([closed_window = move(closed_window)] { });
+}
+
+}
diff --git a/Libraries/LibWebView/PictureInPictureManager.h b/Libraries/LibWebView/PictureInPictureManager.h
new file mode 100644
index 00000000000..a5de3001cd4
--- /dev/null
+++ b/Libraries/LibWebView/PictureInPictureManager.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/NonnullOwnPtr.h>
+#include <AK/NonnullRefPtr.h>
+#include <AK/Optional.h>
+#include <AK/String.h>
+#include <AK/Types.h>
+#include <AK/Vector.h>
+#include <AK/kmalloc.h>
+#include <LibGfx/Size.h>
+#include <LibWebCommon/Page/PageId.h>
+#include <LibWebView/Forward.h>
+
+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.
+class WEBVIEW_API PictureInPictureManager {
+public:
+ AK_ALLOC_WITH_KMALLOC;
+
+ 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);
+ void close_window(WebContentPage&);
+
+private:
+ struct Window {
+ NonnullRefPtr<WebContentPage> page;
+ NonnullOwnPtr<PictureInPictureWindow> window;
+ };
+
+ Optional<size_t> index_of_window_for(WebContentPage const&) const;
+ Optional<size_t> index_of(PictureInPictureWindow const&) const;
+ void retire_window(size_t index);
+ void window_did_close(PictureInPictureWindow&);
+ void window_page_did_close(PictureInPictureWindow&);
+
+ Vector<Window> m_windows;
+ Vector<NonnullOwnPtr<PictureInPictureWindow>> m_retired_windows;
+};
+
+}
diff --git a/Libraries/LibWebView/PictureInPictureWindow.cpp b/Libraries/LibWebView/PictureInPictureWindow.cpp
new file mode 100644
index 00000000000..5313a6b26ae
--- /dev/null
+++ b/Libraries/LibWebView/PictureInPictureWindow.cpp
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibWebView/PictureInPictureWindow.h>
+#include <LibWebView/ViewImplementation.h>
+
+namespace WebView {
+
+Gfx::IntSize PictureInPictureWindow::initial_size(Gfx::IntSize video_size, Gfx::IntSize screen_size)
+{
+ if (video_size.is_empty())
+ video_size = { 16, 9 };
+
+ // https://w3c.github.io/picture-in-picture/#pip
+ // It is also RECOMMENDED that the Picture-in-Picture window has a maximum and minimum size. For example, it could
+ // be restricted to be between a quarter and a half of one dimension of the screen.
+ auto width = screen_size.width() / 4;
+ auto height = width * video_size.height() / video_size.width();
+
+ if (auto maximum_height = screen_size.height() / 2; height > maximum_height) {
+ height = maximum_height;
+ width = height * video_size.width() / video_size.height();
+ }
+
+ return { width, height };
+}
+
+void PictureInPictureWindow::report_page_close_of(ViewImplementation& view)
+{
+ view.on_close = [this] {
+ if (on_page_close)
+ on_page_close();
+ };
+ view.on_web_content_crashed = [this](auto) {
+ if (on_page_close)
+ on_page_close();
+ };
+}
+
+}
diff --git a/Libraries/LibWebView/PictureInPictureWindow.h b/Libraries/LibWebView/PictureInPictureWindow.h
new file mode 100644
index 00000000000..27f0a5674cb
--- /dev/null
+++ b/Libraries/LibWebView/PictureInPictureWindow.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Function.h>
+#include <AK/String.h>
+#include <AK/kmalloc.h>
+#include <LibGfx/Size.h>
+#include <LibWebView/Forward.h>
+
+namespace WebView {
+
+// The floating window that shows a page's Picture-in-Picture video. Sizes are in CSS pixels.
+class WEBVIEW_API PictureInPictureWindow {
+public:
+ AK_ALLOC_WITH_KMALLOC;
+
+ static Gfx::IntSize initial_size(Gfx::IntSize video_size, Gfx::IntSize screen_size);
+
+ virtual ~PictureInPictureWindow() = default;
+
+ virtual Gfx::IntSize size() const = 0;
+ virtual String handle() const = 0;
+ virtual void hide() = 0;
+
+ Function<void(Gfx::IntSize)> on_resize;
+ Function<void()> on_close;
+ Function<void()> on_page_close;
+
+protected:
+ void report_page_close_of(ViewImplementation&);
+};
+
+}
diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cpp
index 8cbc0a25b0d..324746fbcc6 100644
--- a/Libraries/LibWebView/ViewImplementation.cpp
+++ b/Libraries/LibWebView/ViewImplementation.cpp
@@ -1169,6 +1169,7 @@ void ViewImplementation::send_preferences_to_page(WebContentPage& page)
send_global_privacy_control(page);
page.async_set_spell_checking_available(Application::the().spell_checker() != nullptr);
send_geolocation_emulated_position(page);
+ page.async_set_has_picture_in_picture_support(Application::the().supports_picture_in_picture());
}
void ViewImplementation::notify_cookies_changed(HashTable<String> const& changed_domains, ReadonlySpan<HTTP::Cookie::Cookie> page_cookies, ReadonlySpan<HTTP::Cookie::Cookie> host_cookies)
diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cpp
index 6da96e868c7..7759ba50946 100644
--- a/Libraries/LibWebView/WebContentPage.cpp
+++ b/Libraries/LibWebView/WebContentPage.cpp
@@ -27,6 +27,7 @@
#include <LibWebView/CookieJar.h>
#include <LibWebView/HistoryStore.h>
#include <LibWebView/NavigationLoader.h>
+#include <LibWebView/PictureInPictureManager.h>
#include <LibWebView/RequestServerManager.h>
#include <LibWebView/StorageJar.h>
#include <LibWebView/URL.h>
@@ -620,6 +621,7 @@ void WebContentPage::fail_renderer_owned_downloads()
void WebContentPage::close()
{
+ PictureInPictureManager::the().close_window(*this);
m_is_open = false;
m_needs_beforeunload_check = true;
m_history_recorded_url_for_current_load.clear();
@@ -1419,6 +1421,11 @@ void WebContentPage::did_request_exit_fullscreen()
view().on_exit_fullscreen_window();
}
+void WebContentPage::did_exit_picture_in_picture()
+{
+ PictureInPictureManager::the().close_window(*this);
+}
+
// A navigation's population steps run in the process with its source document, which need not have hosted local file
// content. For a navigation to a file: URL the UI process admitted, that process reads the file the URL names, as it does
// for a history step to an entry of one.
@@ -2546,8 +2553,11 @@ Messages::WebContentClient::DidRequestNewWebViewResponse WebContentPage::did_req
client().open_page_for_new_top_level_traversable(new_page_id, traversable);
String window_handle;
- if (view().on_new_web_view)
+ if (hints.picture_in_picture_video_size.has_value()) {
+ window_handle = PictureInPictureManager::the().open_window(*this, traversable, *hints.picture_in_picture_video_size);
+ } else if (view().on_new_web_view) {
window_handle = view().on_new_web_view(activate_tab, hints, traversable);
+ }
if (!traversable.view().has_value()) {
client().discard_page_of_undisplayed_top_level_traversable(new_page_id);
diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.h
index 78b065c2ec6..509170dfd32 100644
--- a/Libraries/LibWebView/WebContentPage.h
+++ b/Libraries/LibWebView/WebContentPage.h
@@ -244,6 +244,7 @@ private:
virtual void did_request_minimize_window() override;
virtual void did_request_fullscreen_window() override;
virtual void did_request_exit_fullscreen() override;
+ virtual void did_exit_picture_in_picture() override;
virtual void did_request_file(ByteString path, i32 request_id) override;
virtual void did_request_color_picker(Color current_color) override;
virtual void did_request_geolocation_position(u64 request_id) override;
diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cpp
index 68e67b64bea..d25b8346c3f 100644
--- a/Services/WebContent/ConnectionFromClient.cpp
+++ b/Services/WebContent/ConnectionFromClient.cpp
@@ -87,6 +87,7 @@
#include <LibWeb/Painting/DocumentPaintState.h>
#include <LibWeb/Painting/FlexboxInspectorOverlay.h>
#include <LibWeb/Painting/PaintingRustBridge.h>
+#include <LibWeb/PictureInPicture/PictureInPictureController.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/Platform/FontPlugin.h>
#include <LibWeb/Selection/Selection.h>
@@ -3636,4 +3637,28 @@ void ConnectionFromClient::exit_fullscreen(Web::PageId page_id)
}
}
+void ConnectionFromClient::set_has_picture_in_picture_support(Web::PageId page_id, bool has_support)
+{
+ if (auto page = this->page(page_id); page.has_value())
+ page->page().picture_in_picture_controller().set_has_picture_in_picture_support(has_support);
+}
+
+void ConnectionFromClient::did_open_picture_in_picture_window(Web::PageId page_id, Gfx::IntSize window_size)
+{
+ if (auto page = this->page(page_id); page.has_value())
+ page->page().picture_in_picture_controller().did_open_window(window_size);
+}
+
+void ConnectionFromClient::picture_in_picture_window_did_resize(Web::PageId page_id, Gfx::IntSize window_size)
+{
+ if (auto page = this->page(page_id); page.has_value())
+ page->page().picture_in_picture_controller().window_did_resize(window_size);
+}
+
+void ConnectionFromClient::picture_in_picture_window_did_close(Web::PageId page_id)
+{
+ if (auto page = this->page(page_id); page.has_value())
+ page->page().picture_in_picture_controller().window_did_close();
+}
+
}
diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.h
index fc55c0442be..395cd202cfe 100644
--- a/Services/WebContent/ConnectionFromClient.h
+++ b/Services/WebContent/ConnectionFromClient.h
@@ -342,6 +342,11 @@ private:
virtual void exit_fullscreen(Web::PageId page_id) override;
+ virtual void set_has_picture_in_picture_support(Web::PageId page_id, bool has_support) override;
+ virtual void did_open_picture_in_picture_window(Web::PageId page_id, Gfx::IntSize window_size) override;
+ virtual void picture_in_picture_window_did_resize(Web::PageId page_id, Gfx::IntSize window_size) override;
+ virtual void picture_in_picture_window_did_close(Web::PageId page_id) override;
+
RefPtr<TestConnection> m_test_connection;
RefPtr<Web::Compositor::CompositorConnection> m_compositor_connection;
NonnullOwnPtr<PageHost> m_page_host;
diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cpp
index c7ed0e201c0..d4776e91bf8 100644
--- a/Services/WebContent/PageClient.cpp
+++ b/Services/WebContent/PageClient.cpp
@@ -907,6 +907,11 @@ void PageClient::page_did_request_exit_fullscreen()
client().async_did_request_exit_fullscreen(m_id);
}
+void PageClient::page_did_exit_picture_in_picture()
+{
+ client().async_did_exit_picture_in_picture(m_id);
+}
+
void PageClient::page_did_request_tooltip_override(Web::CSSPixelPoint position, ByteString const& title)
{
auto device_position = page().css_to_device_point(position);
diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.h
index 1fc8798b304..80489424482 100644
--- a/Services/WebContent/PageClient.h
+++ b/Services/WebContent/PageClient.h
@@ -236,6 +236,7 @@ private:
virtual void page_did_request_minimize_window() override;
virtual void page_did_request_fullscreen_window() override;
virtual void page_did_request_exit_fullscreen() override;
+ virtual void page_did_exit_picture_in_picture() override;
virtual void page_did_request_tooltip_override(Web::CSSPixelPoint, ByteString const&) override;
virtual void page_did_stop_tooltip_override() override;
virtual void page_did_enter_tooltip_area(ByteString const&) override;
diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipc
index b1e20a1ca00..7cc436ff293 100644
--- a/Services/WebContent/WebContentClient.ipc
+++ b/Services/WebContent/WebContentClient.ipc
@@ -222,6 +222,7 @@ endpoint WebContentClient routed by Web::PageId page_id
did_request_minimize_window(Web::PageId page_id) =|
did_request_fullscreen_window(Web::PageId page_id) =|
did_request_exit_fullscreen(Web::PageId page_id) =|
+ did_exit_picture_in_picture(Web::PageId page_id) =|
did_request_file(Web::PageId page_id, ByteString path, i32 request_id) =|
did_request_color_picker(Web::PageId page_id, Color current_color) =|
did_request_geolocation_position(Web::PageId page_id, u64 request_id) =|
diff --git a/Services/WebContent/WebContentServer.ipc b/Services/WebContent/WebContentServer.ipc
index 5943be3c0f9..e97bc83c52c 100644
--- a/Services/WebContent/WebContentServer.ipc
+++ b/Services/WebContent/WebContentServer.ipc
@@ -319,4 +319,9 @@ endpoint WebContentServer routed by Web::PageId page_id
force_close(Web::PageId page_id) =|
exit_fullscreen(Web::PageId page_id) =|
+
+ set_has_picture_in_picture_support(Web::PageId page_id, bool has_support) =|
+ did_open_picture_in_picture_window(Web::PageId page_id, Gfx::IntSize window_size) =|
+ picture_in_picture_window_did_resize(Web::PageId page_id, Gfx::IntSize window_size) =|
+ picture_in_picture_window_did_close(Web::PageId page_id) =|
}
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index edfb87edfaf..1fe44216cda 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -39,6 +39,9 @@ Text/input/SiteIsolation/iframe/isolated-iframe-finds-a-popup-of-its-top-level-b
Text/input/SiteIsolation/popup-navigating-to-a-coop-page-leaves-its-opener.html
Text/input/SiteIsolation/popup-opened-onto-a-coop-page-leaves-its-opener.html
+; Loads videos from absolute /media/ URLs.
+Text/input/wpt-import/picture-in-picture/
+
; fetching a file only works from an HTTP server.
Crash/HTML/media-element-load-with-pending-source-buffer-append.html
Text/input/HTML/HTMLMediaElement-failed-range-response-after-metadata.html
diff --git a/Tests/LibWeb/Text/expected/PictureInPicture/window-closes-when-its-document-goes-away-while-opening.txt b/Tests/LibWeb/Text/expected/PictureInPicture/window-closes-when-its-document-goes-away-while-opening.txt
new file mode 100644
index 00000000000..4f7687e1886
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/PictureInPicture/window-closes-when-its-document-goes-away-while-opening.txt
@@ -0,0 +1,2 @@
+While the window opens: opening
+Once it has opened: none
diff --git a/Tests/LibWeb/Text/expected/all-window-properties.txt b/Tests/LibWeb/Text/expected/all-window-properties.txt
index 1a76db8e0c3..7e4beba3df3 100644
--- a/Tests/LibWeb/Text/expected/all-window-properties.txt
+++ b/Tests/LibWeb/Text/expected/all-window-properties.txt
@@ -370,6 +370,8 @@ PerformanceTiming
PeriodicWave
PermissionStatus
Permissions
+PictureInPictureEvent
+PictureInPictureWindow
Plugin
PluginArray
PointerEvent
diff --git a/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/disable-picture-in-picture.txt b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/disable-picture-in-picture.txt
index aee5752cd99..5c6faeaa602 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/disable-picture-in-picture.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/disable-picture-in-picture.txt
@@ -2,11 +2,11 @@ Harness status: OK
Found 6 tests
-1 Pass
-5 Fail
+5 Pass
+1 Fail
Pass Test disablePictureInPicture IDL attribute
-Fail Request Picture-in-Picture rejects if disablePictureInPicture is true
+Pass Request Picture-in-Picture rejects if disablePictureInPicture is true
Fail Request Picture-in-Picture rejects if disablePictureInPicture becomes true before promise resolves.
-Fail pictureInPictureElement is unset if disablePictureInPicture becomes true
-Fail pictureInPictureElement is unchanged if disablePictureInPicture becomes false
-Fail pictureInPictureElement is unchanged if disablePictureInPicture becomes true for another video
\ No newline at end of file
+Pass pictureInPictureElement is unset if disablePictureInPicture becomes true
+Pass pictureInPictureElement is unchanged if disablePictureInPicture becomes false
+Pass pictureInPictureElement is unchanged if disablePictureInPicture becomes true for another video
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/enter-picture-in-picture.txt b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/enter-picture-in-picture.txt
new file mode 100644
index 00000000000..12adb1b4c64
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/enter-picture-in-picture.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Test enterpictureinpicture event
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/exit-picture-in-picture.txt b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/exit-picture-in-picture.txt
new file mode 100644
index 00000000000..e04ff1119cd
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/exit-picture-in-picture.txt
@@ -0,0 +1,7 @@
+Harness status: OK
+
+Found 2 tests
+
+2 Pass
+Pass Exit Picture-in-Picture resolves when there is a Picture-in-Picture video
+Pass Exit Picture-in-Picture rejects when there is no Picture-in-Picture video
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/idlharness.window.txt b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/idlharness.window.txt
new file mode 100644
index 00000000000..e255a2e5374
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/idlharness.window.txt
@@ -0,0 +1,72 @@
+Harness status: OK
+
+Found 67 tests
+
+67 Pass
+Pass idl_test setup
+Pass idl_test validation
+Pass Partial interface HTMLVideoElement: original interface defined
+Pass Partial interface HTMLVideoElement: member names are unique
+Pass Partial interface Document: original interface defined
+Pass Partial interface Document: member names are unique
+Pass Partial interface mixin DocumentOrShadowRoot: original interface mixin defined
+Pass Partial interface mixin DocumentOrShadowRoot: member names are unique
+Pass Partial interface Document[2]: member names are unique
+Pass Partial interface mixin DocumentOrShadowRoot[2]: member names are unique
+Pass Partial interface Element: member names are unique
+Pass Partial interface Document[3]: member names are unique
+Pass Document includes GlobalEventHandlers: member names are unique
+Pass HTMLElement includes GlobalEventHandlers: member names are unique
+Pass HTMLElement includes ElementContentEditable: member names are unique
+Pass HTMLElement includes HTMLOrSVGElement: member names are unique
+Pass Document includes NonElementParentNode: member names are unique
+Pass DocumentFragment includes NonElementParentNode: member names are unique
+Pass Document includes DocumentOrShadowRoot: member names are unique
+Pass ShadowRoot includes DocumentOrShadowRoot: member names are unique
+Pass Document includes ParentNode: member names are unique
+Pass DocumentFragment includes ParentNode: member names are unique
+Pass Element includes ParentNode: member names are unique
+Pass Element includes NonDocumentTypeChildNode: member names are unique
+Pass Element includes ChildNode: member names are unique
+Pass Element includes Slottable: member names are unique
+Pass Document includes XPathEvaluatorBase: member names are unique
+Pass PictureInPictureWindow interface: existence and properties of interface object
+Pass PictureInPictureWindow interface object length
+Pass PictureInPictureWindow interface object name
+Pass PictureInPictureWindow interface: existence and properties of interface prototype object
+Pass PictureInPictureWindow interface: existence and properties of interface prototype object's "constructor" property
+Pass PictureInPictureWindow interface: existence and properties of interface prototype object's @@unscopables property
+Pass PictureInPictureWindow interface: attribute width
+Pass PictureInPictureWindow interface: attribute height
+Pass PictureInPictureWindow interface: attribute onresize
+Pass PictureInPictureWindow must be primary interface of pipw
+Pass Stringification of pipw
+Pass PictureInPictureWindow interface: pipw must inherit property "width" with the proper type
+Pass PictureInPictureWindow interface: pipw must inherit property "height" with the proper type
+Pass PictureInPictureWindow interface: pipw must inherit property "onresize" with the proper type
+Pass PictureInPictureEvent interface: existence and properties of interface object
+Pass PictureInPictureEvent interface object length
+Pass PictureInPictureEvent interface object name
+Pass PictureInPictureEvent interface: existence and properties of interface prototype object
+Pass PictureInPictureEvent interface: existence and properties of interface prototype object's "constructor" property
+Pass PictureInPictureEvent interface: existence and properties of interface prototype object's @@unscopables property
+Pass PictureInPictureEvent interface: attribute pictureInPictureWindow
+Pass PictureInPictureEvent must be primary interface of new PictureInPictureEvent("type", { pictureInPictureWindow: pipw })
+Pass Stringification of new PictureInPictureEvent("type", { pictureInPictureWindow: pipw })
+Pass PictureInPictureEvent interface: new PictureInPictureEvent("type", { pictureInPictureWindow: pipw }) must inherit property "pictureInPictureWindow" with the proper type
+Pass HTMLVideoElement interface: operation requestPictureInPicture()
+Pass HTMLVideoElement interface: attribute onenterpictureinpicture
+Pass HTMLVideoElement interface: attribute onleavepictureinpicture
+Pass HTMLVideoElement interface: attribute disablePictureInPicture
+Pass HTMLVideoElement interface: video must inherit property "requestPictureInPicture()" with the proper type
+Pass HTMLVideoElement interface: video must inherit property "onenterpictureinpicture" with the proper type
+Pass HTMLVideoElement interface: video must inherit property "onleavepictureinpicture" with the proper type
+Pass HTMLVideoElement interface: video must inherit property "disablePictureInPicture" with the proper type
+Pass DocumentOrShadowRoot interface: document must inherit property "pictureInPictureElement" with the proper type
+Pass Document interface: attribute pictureInPictureEnabled
+Pass Document interface: operation exitPictureInPicture()
+Pass Document interface: attribute pictureInPictureElement
+Pass Document interface: document must inherit property "pictureInPictureEnabled" with the proper type
+Pass Document interface: document must inherit property "exitPictureInPicture()" with the proper type
+Pass Document interface: document must inherit property "pictureInPictureElement" with the proper type
+Pass ShadowRoot interface: attribute pictureInPictureElement
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/leave-picture-in-picture.txt b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/leave-picture-in-picture.txt
new file mode 100644
index 00000000000..6d56e2e1fce
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/leave-picture-in-picture.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass leavepictureinpicture event is fired if document.exitPictureInPicture
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/mediastream.txt b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/mediastream.txt
new file mode 100644
index 00000000000..4976a2afe01
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/mediastream.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Fail
+Fail request Picture-in-Picture resolves on user click with Picture-in-Picture window
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/picture-in-picture-element.txt b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/picture-in-picture-element.txt
new file mode 100644
index 00000000000..0fab6d86515
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/picture-in-picture-element.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Test Picture-in-Picture element
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/picture-in-picture-window.txt b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/picture-in-picture-window.txt
new file mode 100644
index 00000000000..1f390cb77c6
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/picture-in-picture-window.txt
@@ -0,0 +1,10 @@
+Harness status: OK
+
+Found 5 tests
+
+5 Pass
+Pass Picture-in-Picture window dimensions are set after entering Picture-in-Picture
+Pass Picture-in-Picture window dimensions are set to 0 after entering Picture-in-Picture for another video
+Pass Picture-in-Picture window is unchanged after entering Picture-in-Picture for video already in Picture-in-Picture
+Pass Picture-in-Picture window dimensions are set to 0 after exiting Picture-in-Picture
+Pass Picture-in-Picture window dimensions are set to 0 if disablePictureInPicture becomes true
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/removed-from-document.txt b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/removed-from-document.txt
new file mode 100644
index 00000000000..721b9c3c491
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/removed-from-document.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Fail
+Fail Picture-in-Picture video does not pause when removed from document
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/request-picture-in-picture-consumes-user-activation.txt b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/request-picture-in-picture-consumes-user-activation.txt
new file mode 100644
index 00000000000..62c81834011
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/request-picture-in-picture-consumes-user-activation.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass request Picture-in-Picture consumes the user activation, denying a fullscreen request from the same activation
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/request-picture-in-picture-exits-existing.txt b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/request-picture-in-picture-exits-existing.txt
new file mode 100644
index 00000000000..c46709678ff
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/request-picture-in-picture-exits-existing.txt
@@ -0,0 +1,9 @@
+Harness status: OK
+
+Found 4 tests
+
+4 Pass
+Pass Step 11.5.1 runs the inline exit algorithm, so leavepictureinpicture fires synchronously before enterpictureinpicture
+Pass Inline exit algorithm unsets pictureInPictureElement before firing leavepictureinpicture
+Pass Step 11.5.2 sets pictureInPictureElement to the new element before step 11.5.5 fires enterpictureinpicture
+Pass Inline exit algorithm still runs the close window algorithm on the displaced Picture-in-Picture window
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/request-picture-in-picture-twice.txt b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/request-picture-in-picture-twice.txt
new file mode 100644
index 00000000000..8e557454f67
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/request-picture-in-picture-twice.txt
@@ -0,0 +1,7 @@
+Harness status: OK
+
+Found 2 tests
+
+2 Pass
+Pass request Picture-in-Picture consumes user gesture
+Pass request Picture-in-Picture does not require user gesture if document.pictureInPictureElement is set
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/request-picture-in-picture.txt b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/request-picture-in-picture.txt
new file mode 100644
index 00000000000..de67abf4f5a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/request-picture-in-picture.txt
@@ -0,0 +1,9 @@
+Harness status: OK
+
+Found 4 tests
+
+4 Pass
+Pass request Picture-in-Picture requires a user gesture
+Pass request Picture-in-Picture requires loaded metadata for the video element
+Pass request Picture-in-Picture requires video track for the video element
+Pass request Picture-in-Picture resolves on user click
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/shadow-dom.txt b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/shadow-dom.txt
new file mode 100644
index 00000000000..4e3082fbb74
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/shadow-dom.txt
@@ -0,0 +1,11 @@
+Harness status: OK
+
+Found 5 tests
+
+4 Pass
+1 Fail
+Fail Test for Picture-In-Picture and Shadow DOM
+Pass Picture-in-Picture on a video inside an open shadow root attached to a disconnected host
+Pass Picture-in-Picture on a video inside a closed shadow root attached to a disconnected host
+Pass Connecting a previously-disconnected shadow host after Picture-in-Picture starts exposes the video through shadowRoot.pictureInPictureElement
+Pass Picture-in-Picture on a video inside nested shadow roots whose outer host is disconnected
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/unload-document-exits-picture-in-picture.txt b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/unload-document-exits-picture-in-picture.txt
new file mode 100644
index 00000000000..748a01bc781
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/picture-in-picture/unload-document-exits-picture-in-picture.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass exit Picture-in-Picture algorithm runs as part of unloading document cleanup steps
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/PictureInPicture/window-closes-when-its-document-goes-away-while-opening.html b/Tests/LibWeb/Text/input/PictureInPicture/window-closes-when-its-document-goes-away-while-opening.html
new file mode 100644
index 00000000000..240ae72de56
--- /dev/null
+++ b/Tests/LibWeb/Text/input/PictureInPicture/window-closes-when-its-document-goes-away-while-opening.html
@@ -0,0 +1,31 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ function nextFrame() {
+ return new Promise(resolve => requestAnimationFrame(resolve));
+ }
+
+ asyncTest(async done => {
+ const iframe = document.createElement("iframe");
+ iframe.srcdoc = '<video src="../../../Assets/test-webm.webm"></video>';
+ const loaded = new Promise(resolve => iframe.addEventListener("load", resolve, { once: true }));
+ document.body.appendChild(iframe);
+ await loaded;
+
+ const video = iframe.contentDocument.querySelector("video");
+ if (video.readyState === HTMLMediaElement.HAVE_NOTHING)
+ await new Promise(resolve => video.addEventListener("loadedmetadata", resolve, { once: true }));
+
+ // The UI process opens the window while the request runs, and the video's document goes away before the window
+ // has been acknowledged as open.
+ iframe.contentWindow.internals.grantTransientActivation();
+ video.requestPictureInPicture();
+ println(`While the window opens: ${internals.pictureInPictureWindowState}`);
+ iframe.remove();
+
+ while (internals.pictureInPictureWindowState === "opening")
+ await nextFrame();
+ println(`Once it has opened: ${internals.pictureInPictureWindowState}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/interfaces/picture-in-picture.idl b/Tests/LibWeb/Text/input/wpt-import/interfaces/picture-in-picture.idl
new file mode 100644
index 00000000000..516fb59d8d4
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/interfaces/picture-in-picture.idl
@@ -0,0 +1,41 @@
+// GENERATED CONTENT - DO NOT EDIT
+// Content was automatically extracted by Reffy into webref
+// (https://github.com/w3c/webref)
+// Source: Picture-in-Picture (https://w3c.github.io/picture-in-picture/)
+
+partial interface HTMLVideoElement {
+ [NewObject] Promise<PictureInPictureWindow> requestPictureInPicture();
+
+ attribute EventHandler onenterpictureinpicture;
+ attribute EventHandler onleavepictureinpicture;
+
+ [CEReactions] attribute boolean disablePictureInPicture;
+};
+
+partial interface Document {
+ readonly attribute boolean pictureInPictureEnabled;
+
+ [NewObject] Promise<undefined> exitPictureInPicture();
+};
+
+partial interface mixin DocumentOrShadowRoot {
+ readonly attribute Element? pictureInPictureElement;
+};
+
+[Exposed=Window]
+interface PictureInPictureWindow : EventTarget {
+ readonly attribute long width;
+ readonly attribute long height;
+
+ attribute EventHandler onresize;
+};
+
+[Exposed=Window]
+interface PictureInPictureEvent : Event {
+ constructor(DOMString type, PictureInPictureEventInit eventInitDict);
+ [SameObject] readonly attribute PictureInPictureWindow pictureInPictureWindow;
+};
+
+dictionary PictureInPictureEventInit : EventInit {
+ required PictureInPictureWindow pictureInPictureWindow;
+};
diff --git a/Tests/LibWeb/Text/input/wpt-import/media/sound_5.oga b/Tests/LibWeb/Text/input/wpt-import/media/sound_5.oga
new file mode 100644
index 00000000000..239ad2bd08c
Binary files /dev/null and b/Tests/LibWeb/Text/input/wpt-import/media/sound_5.oga differ
diff --git a/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/enter-picture-in-picture.html b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/enter-picture-in-picture.html
new file mode 100644
index 00000000000..dbd6b2b413d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/enter-picture-in-picture.html
@@ -0,0 +1,30 @@
+<!DOCTYPE html>
+<title>Test enterpictureinpicture event</title>
+<script src="../common/media.js"></script>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../resources/testdriver.js"></script>
+<script src="../resources/testdriver-vendor.js"></script>
+<script src="resources/picture-in-picture-helpers.js"></script>
+<body></body>
+<script>
+promise_test(async t => {
+ let pictureInPictureWindow;
+ const video = await loadVideo();
+
+ video.addEventListener('enterpictureinpicture', t.step_func_done(event => {
+ pictureInPictureWindow = event.pictureInPictureWindow;
+
+ assert_equals(event.target, video);
+ assert_equals(event.bubbles, true);
+ assert_equals(event.cancelable, false);
+ assert_equals(event.composed, false);
+ assert_equals(document.pictureInPictureElement, video);
+ }));
+
+ return requestPictureInPictureWithTrustedClick(video)
+ .then(pipWindow => {
+ assert_equals(pipWindow, pictureInPictureWindow);
+ })
+});
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/exit-picture-in-picture.html b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/exit-picture-in-picture.html
new file mode 100644
index 00000000000..d7101baa47a
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/exit-picture-in-picture.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<title>Test exit Picture-in-Picture</title>
+<script src="../common/media.js"></script>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../resources/testdriver.js"></script>
+<script src="../resources/testdriver-vendor.js"></script>
+<script src="resources/picture-in-picture-helpers.js"></script>
+<body></body>
+<script>
+promise_test(async t => {
+ const video = await loadVideo();
+ return requestPictureInPictureWithTrustedClick(video)
+ .then(() => document.exitPictureInPicture());
+}, 'Exit Picture-in-Picture resolves when there is a Picture-in-Picture video');
+
+promise_test(t => {
+ return promise_rejects_dom(t, 'InvalidStateError',
+ document.exitPictureInPicture());
+}, 'Exit Picture-in-Picture rejects when there is no Picture-in-Picture video');
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/idlharness.window.html b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/idlharness.window.html
new file mode 100644
index 00000000000..a77ff5cc48d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/idlharness.window.html
@@ -0,0 +1,13 @@
+<!doctype html>
+<meta charset=utf-8>
+<meta name="timeout" content="long">
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../common/media.js"></script>
+<script src="../resources/WebIDLParser.js"></script>
+<script src="../resources/idlharness.js"></script>
+<script src="../resources/testdriver.js"></script>
+<script src="../resources/testdriver-vendor.js"></script>
+<script src="resources/picture-in-picture-helpers.js"></script>
+<div id=log></div>
+<script src="../picture-in-picture/idlharness.window.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/idlharness.window.js b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/idlharness.window.js
new file mode 100644
index 00000000000..89775884788
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/idlharness.window.js
@@ -0,0 +1,28 @@
+// META: script=/common/media.js
+// META: script=/resources/WebIDLParser.js
+// META: script=/resources/idlharness.js
+// META: script=/resources/testdriver.js
+// META: script=/resources/testdriver-vendor.js
+// META: script=resources/picture-in-picture-helpers.js
+// META: timeout=long
+
+'use strict';
+
+// https://wicg.github.io/picture-in-picture/
+
+idl_test(
+ ['picture-in-picture'],
+ ['html', 'dom'],
+ async idl_array => {
+ idl_array.add_objects({
+ Document: ['document'],
+ DocumentOrShadowRoot: ['document'],
+ HTMLVideoElement: ['video'],
+ PictureInPictureWindow: ['pipw'],
+ PictureInPictureEvent: ['new PictureInPictureEvent("type", { pictureInPictureWindow: pipw })'],
+ });
+
+ self.video = await loadVideo();
+ self.pipw = await requestPictureInPictureWithTrustedClick(video);
+ }
+);
diff --git a/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/leave-picture-in-picture.html b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/leave-picture-in-picture.html
new file mode 100644
index 00000000000..8bf7e1c7320
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/leave-picture-in-picture.html
@@ -0,0 +1,36 @@
+<!DOCTYPE html>
+<title>Test leavepictureinpicture event</title>
+<meta name="timeout" content="long">
+<script src="../common/media.js"></script>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../resources/testdriver.js"></script>
+<script src="../resources/testdriver-vendor.js"></script>
+<script src="resources/picture-in-picture-helpers.js"></script>
+<body></body>
+<script>
+promise_test(async () => {
+ const video = await loadVideo();
+
+ const enterPipEventPromise = new Promise((resolve) =>
+ video.addEventListener('enterpictureinpicture', resolve),
+ );
+
+ const leavePipEventPromise = new Promise((resolve) =>
+ video.addEventListener('leavepictureinpicture', resolve),
+ );
+
+ await requestPictureInPictureWithTrustedClick(video);
+ const { pictureInPictureWindow } = await enterPipEventPromise;
+
+ await document.exitPictureInPicture();
+
+ const event = await leavePipEventPromise;
+ assert_equals(pictureInPictureWindow, event.pictureInPictureWindow);
+ assert_equals(event.target, video);
+ assert_equals(event.bubbles, true);
+ assert_equals(event.cancelable, false);
+ assert_equals(event.composed, false);
+ assert_equals(document.pictureInPictureElement, null);
+}, 'leavepictureinpicture event is fired if document.exitPictureInPicture');
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/mediastream.html b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/mediastream.html
new file mode 100644
index 00000000000..8c0456d4587
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/mediastream.html
@@ -0,0 +1,24 @@
+<!DOCTYPE html>
+<title>Test mediastream video in Picture-in-Picture</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../resources/testdriver.js"></script>
+<script src="../resources/testdriver-vendor.js"></script>
+<script src="resources/picture-in-picture-helpers.js"></script>
+<body></body>
+<script>
+promise_test(async t => {
+ const canvas = document.createElement('canvas');
+ const video = document.createElement('video');
+ canvas.getContext('2d').fillRect(0, 0, canvas.width, canvas.height);
+ video.muted = true;
+ video.srcObject = canvas.captureStream(60 /* fps */);
+ await video.play();
+
+ return requestPictureInPictureWithTrustedClick(video)
+ .then(pipWindow => {
+ assert_not_equals(pipWindow.width, 0);
+ assert_not_equals(pipWindow.height, 0);
+ });
+}, 'request Picture-in-Picture resolves on user click with Picture-in-Picture window');
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/picture-in-picture-element.html b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/picture-in-picture-element.html
new file mode 100644
index 00000000000..81b2b462d46
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/picture-in-picture-element.html
@@ -0,0 +1,24 @@
+<!DOCTYPE html>
+<title>Test Picture-in-Picture element</title>
+<script src="../common/media.js"></script>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../resources/testdriver.js"></script>
+<script src="../resources/testdriver-vendor.js"></script>
+<script src="resources/picture-in-picture-helpers.js"></script>
+<body></body>
+<script>
+promise_test(async t => {
+ assert_equals(document.pictureInPictureElement, null);
+ const video = await loadVideo();
+
+ return requestPictureInPictureWithTrustedClick(video)
+ .then(() => {
+ assert_equals(document.pictureInPictureElement, video);
+ return document.exitPictureInPicture();
+ })
+ .then(() => {
+ assert_equals(document.pictureInPictureElement, null);
+ });
+});
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/picture-in-picture-window.html b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/picture-in-picture-window.html
new file mode 100644
index 00000000000..352cceb2118
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/picture-in-picture-window.html
@@ -0,0 +1,96 @@
+<!DOCTYPE html>
+<title>Test Picture-in-Picture window</title>
+<meta name="timeout" content="long">
+<script src="../common/media.js"></script>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../resources/testdriver.js"></script>
+<script src="../resources/testdriver-vendor.js"></script>
+<script src="resources/picture-in-picture-helpers.js"></script>
+<body></body>
+<script>
+promise_test(async t => {
+ const video = await loadVideo();
+ return requestPictureInPictureWithTrustedClick(video)
+ .then(pipWindow => {
+ assert_not_equals(pipWindow.width, 0);
+ assert_not_equals(pipWindow.height, 0);
+ const videoAspectRatio = video.videoWidth / video.videoHeight;
+ const pipWindowAspectRatio = pipWindow.width / pipWindow.height;
+ assert_approx_equals(videoAspectRatio, pipWindowAspectRatio, 0.01);
+ });
+}, 'Picture-in-Picture window dimensions are set after entering Picture-in-Picture');
+
+promise_test(async t => {
+ const video1 = await loadVideo();
+ const video2 = await loadVideo();
+ return requestPictureInPictureWithTrustedClick(video1)
+ .then(pipWindow1 => {
+ return requestPictureInPictureWithTrustedClick(video2)
+ .then(pipWindow2 => {
+ assert_equals(pipWindow1.width, 0);
+ assert_equals(pipWindow1.height, 0);
+ assert_not_equals(pipWindow2.width, 0);
+ assert_not_equals(pipWindow2.height, 0);
+ });
+ });
+}, 'Picture-in-Picture window dimensions are set to 0 after entering ' +
+ 'Picture-in-Picture for another video');
+
+promise_test(async t => {
+ const video = await loadVideo();
+
+ video.addEventListener('leavepictureinpicture', t.step_func_done(event => {
+ assert_unreached('leavepictureinpicture event should not fire.')
+ }));
+
+ let enterCounts = 0;
+ video.addEventListener('enterpictureinpicture', event => {
+ enterCounts++;
+ });
+
+ return requestPictureInPictureWithTrustedClick(video)
+ .then(pipWindow1 => {
+ pipWindow1.onresize = function foo() {};
+ return requestPictureInPictureWithTrustedClick(video)
+ .then(pipWindow2 => {
+ assert_equals(pipWindow1, pipWindow2);
+ assert_equals(pipWindow1.width, pipWindow2.width);
+ assert_equals(pipWindow1.height, pipWindow2.height);
+ assert_equals(pipWindow1.onresize, pipWindow2.onresize);
+ assert_equals(enterCounts, 1);
+ });
+ });
+}, 'Picture-in-Picture window is unchanged after entering ' +
+ 'Picture-in-Picture for video already in Picture-in-Picture');
+
+promise_test(async t => {
+ const video = await loadVideo();
+
+ return requestPictureInPictureWithTrustedClick(video)
+ .then(pipWindow => {
+ return document.exitPictureInPicture()
+ .then(() => {
+ assert_equals(pipWindow.width, 0);
+ assert_equals(pipWindow.height, 0);
+ });
+ });
+}, 'Picture-in-Picture window dimensions are set to 0 after exiting Picture-in-Picture');
+
+promise_test(async t => {
+ const video = await loadVideo();
+ let thePipWindow;
+
+ video.addEventListener('leavepictureinpicture', t.step_func_done(event => {
+ assert_equals(thePipWindow.width, 0);
+ assert_equals(thePipWindow.height, 0);
+ }));
+
+ return requestPictureInPictureWithTrustedClick(video)
+ .then(pipWindow => {
+ thePipWindow = pipWindow;
+ video.disablePictureInPicture = true;
+ });
+}, 'Picture-in-Picture window dimensions are set to 0 if ' +
+ 'disablePictureInPicture becomes true');
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/removed-from-document.html b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/removed-from-document.html
new file mode 100644
index 00000000000..dd264c10c0a
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/removed-from-document.html
@@ -0,0 +1,24 @@
+<!DOCTYPE html>
+<title>Test Picture-in-Picture when removed from document</title>
+<script src="../common/media.js"></script>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../resources/testdriver.js"></script>
+<script src="../resources/testdriver-vendor.js"></script>
+<script src="resources/picture-in-picture-helpers.js"></script>
+<body></body>
+<script>
+promise_test(async t => {
+ const video = await loadVideo();
+ document.body.appendChild(video);
+ video.muted = true;
+ await video.play();
+ await requestPictureInPictureWithTrustedClick(video);
+
+ assert_false(video.paused);
+ document.body.offsetLeft;
+ document.body.removeChild(video);
+ await new Promise(resolve => step_timeout(resolve, 1000));
+ assert_false(video.paused);
+}, 'Picture-in-Picture video does not pause when removed from document');
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/request-picture-in-picture-consumes-user-activation.html b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/request-picture-in-picture-consumes-user-activation.html
new file mode 100644
index 00000000000..23542314dff
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/request-picture-in-picture-consumes-user-activation.html
@@ -0,0 +1,66 @@
+<!DOCTYPE html>
+<title>Test that request Picture-in-Picture consumes the user activation</title>
+<script src="../common/media.js"></script>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../resources/testdriver.js"></script>
+<script src="../resources/testdriver-vendor.js"></script>
+<script src="resources/picture-in-picture-helpers.js"></script>
+<body></body>
+<script>
+// Runs `action` synchronously from a click event handler, so that the requests
+// below are made while the user activation is live, as a page would make them.
+async function runFromClickHandler(t, action) {
+ const button = document.createElement('button');
+ button.textContent = 'This test requires user interaction. Please click here.';
+ document.body.appendChild(button);
+ t.add_cleanup(() => button.remove());
+
+ const result = new Promise(resolve => {
+ button.addEventListener('click', () => { resolve(action()); }, { once: true });
+ });
+ await test_driver.click(button);
+ return result;
+}
+
+promise_test(async t => {
+ const video = await loadVideo();
+ document.body.appendChild(video);
+ t.add_cleanup(async () => {
+ if (document.fullscreenElement)
+ await document.exitFullscreen();
+ if (document.pictureInPictureElement)
+ await document.exitPictureInPicture();
+ video.remove();
+ });
+
+ // https://w3c.github.io/picture-in-picture/#dom-htmlvideoelement-requestpictureinpicture
+ // requestPictureInPicture() consumes the user activation, so a fullscreen
+ // request made from the same activation must be denied.
+ //
+ // Each outcome is captured with handlers attached synchronously: the requests
+ // settle while the click is still being dispatched, so awaiting them later
+ // would report an unhandled rejection. Awaiting the outcomes rather than the
+ // requests themselves also keeps a wrongly granted fullscreen request from
+ // timing out the test: in that case the Picture-in-Picture request, whose
+ // presentation mode change is superseded by fullscreen, never settles.
+ const settled = promise => promise.then(() => 'fulfilled', error => error);
+ const outcomes = await runFromClickHandler(t, () => ({
+ // play() is only here to mirror how a page enters Picture-in-Picture from a
+ // click; its result is not what is under test.
+ play: settled(video.play()),
+ pictureInPicture: settled(video.requestPictureInPicture()),
+ fullscreen: settled(video.requestFullscreen()),
+ }));
+
+ const fullscreenOutcome = await outcomes.fullscreen;
+ assert_true(fullscreenOutcome instanceof TypeError,
+ 'requestFullscreen() should be denied with a TypeError: requestPictureInPicture() ' +
+ `consumed the user activation (got ${fullscreenOutcome})`);
+ assert_equals(document.fullscreenElement, null, 'there should be no fullscreen element');
+
+ assert_equals(await outcomes.pictureInPicture, 'fulfilled', 'requestPictureInPicture()');
+ assert_equals(document.pictureInPictureElement, video,
+ 'video should be the Picture-in-Picture element');
+}, 'request Picture-in-Picture consumes the user activation, denying a fullscreen request from the same activation');
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/request-picture-in-picture-exits-existing.html b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/request-picture-in-picture-exits-existing.html
new file mode 100644
index 00000000000..e5c99c14ee9
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/request-picture-in-picture-exits-existing.html
@@ -0,0 +1,104 @@
+<!DOCTYPE html>
+<title>Test request Picture-in-Picture exits existing element via inline exit algorithm (anticipated spec refactor)</title>
+<meta name="timeout" content="long">
+<script src="../common/media.js"></script>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../resources/testdriver.js"></script>
+<script src="../resources/testdriver-vendor.js"></script>
+<script src="resources/picture-in-picture-helpers.js"></script>
+<body></body>
+<script>
+
+// Test 1: When video1 enters pip followed by video2 requesting pip
+// video1 should be observed leaving first, before video2 enters.
+promise_test(async t => {
+ const video1 = await loadVideo();
+ const video2 = await loadVideo();
+
+ await requestPictureInPictureWithTrustedClick(video1);
+
+ const events = [];
+ video1.addEventListener('leavepictureinpicture',
+ () => { events.push('leave1'); });
+ video2.addEventListener('enterpictureinpicture',
+ () => { events.push('enter2'); });
+
+ await requestPictureInPictureWithTrustedClick(video2);
+
+ assert_array_equals(events, ['leave1', 'enter2'],
+ 'leavepictureinpicture on the displaced element fires before ' +
+ 'enterpictureinpicture on the new element, both within the same task');
+}, 'Step 11.5.1 runs the inline exit algorithm, so leavepictureinpicture ' +
+ 'fires synchronously before enterpictureinpicture');
+
+// Test 2: When video1 enters pip followed by video2 requesting pip
+// in video1's leavepictureinpicture handler it should be observed that
+// document.pictureInPictureElement is null, unset by video1's exit algorithm
+// and not yet set by video2's enter algorithm.
+promise_test(async t => {
+ const video1 = await loadVideo();
+ const video2 = await loadVideo();
+
+ await requestPictureInPictureWithTrustedClick(video1);
+
+ let pipElementDuringLeave = video1;
+ video1.addEventListener('leavepictureinpicture', () => {
+ pipElementDuringLeave = document.pictureInPictureElement;
+ });
+
+ await requestPictureInPictureWithTrustedClick(video2);
+
+ assert_equals(pipElementDuringLeave, null,
+ 'document.pictureInPictureElement is null inside the displaced ' +
+ 'element\'s leavepictureinpicture handler (inline exit has unset ' +
+ 'it, and 11.5.2 has not yet set it to the new element)');
+}, 'Inline exit algorithm unsets pictureInPictureElement before firing ' +
+ 'leavepictureinpicture');
+
+// Test 3: When video1 enters pip followed by video2 requesting pip
+// video2 enterpictureinpicture handler should observe itself having been set
+// as document.pictureInPictureElement
+promise_test(async t => {
+ const video1 = await loadVideo();
+ const video2 = await loadVideo();
+
+ await requestPictureInPictureWithTrustedClick(video1);
+
+ let pipElementDuringEnter = video1;
+ video2.addEventListener('enterpictureinpicture', () => {
+ pipElementDuringEnter = document.pictureInPictureElement;
+ });
+
+ await requestPictureInPictureWithTrustedClick(video2);
+
+ assert_equals(pipElementDuringEnter, video2,
+ 'document.pictureInPictureElement is the new element inside its ' +
+ 'enterpictureinpicture handler');
+}, 'Step 11.5.2 sets pictureInPictureElement to the new element before ' +
+ 'step 11.5.5 fires enterpictureinpicture');
+
+// Test 4: When video1 enters pip followed by video2 requesting pip
+// it's always observed that pipWindow1 has closed before video2's enterpictureinpicture
+// handler runs
+promise_test(async t => {
+ const video1 = await loadVideo();
+ const video2 = await loadVideo();
+
+ const pipWindow1 = await requestPictureInPictureWithTrustedClick(video1);
+ assert_not_equals(pipWindow1.width, 0);
+ assert_not_equals(pipWindow1.height, 0);
+ let enteredPromise = new Promise(r => {
+ video2.addEventListener('enterpictureinpicture', () => {
+ assert_equals(pipWindow1.width, 0,
+ 'previous Picture-in-Picture window width is reset to 0');
+ assert_equals(pipWindow1.height, 0,
+ 'previous Picture-in-Picture window height is reset to 0');
+ r();
+ });
+ });
+ await requestPictureInPictureWithTrustedClick(video2);
+ await enteredPromise;
+}, 'Inline exit algorithm still runs the close window algorithm on the ' +
+ 'displaced Picture-in-Picture window');
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/request-picture-in-picture-twice.html b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/request-picture-in-picture-twice.html
new file mode 100644
index 00000000000..91dd4a8bfa5
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/request-picture-in-picture-twice.html
@@ -0,0 +1,29 @@
+<!DOCTYPE html>
+<title>Test request Picture-in-Picture on two videos</title>
+<meta name="timeout" content="long">
+<script src="../common/media.js"></script>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../resources/testdriver.js"></script>
+<script src="../resources/testdriver-vendor.js"></script>
+<script src="resources/picture-in-picture-helpers.js"></script>
+<body></body>
+<script>
+promise_test(async t => {
+ const video1 = await loadVideo();
+ const video2 = await loadVideo();
+ await test_driver.bless('request Picture-in-Picture');
+ const promise = video1.requestPictureInPicture();
+ await promise_rejects_dom(t, 'NotAllowedError', video2.requestPictureInPicture());
+ return promise;
+}, 'request Picture-in-Picture consumes user gesture');
+
+promise_test(async t => {
+ const video1 = await loadVideo();
+ const video2 = await loadVideo();
+ await test_driver.bless('request Picture-in-Picture');
+ await video1.requestPictureInPicture();
+ assert_equals(document.pictureInPictureElement, video1);
+ return video2.requestPictureInPicture();
+}, 'request Picture-in-Picture does not require user gesture if document.pictureInPictureElement is set');
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/request-picture-in-picture.html b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/request-picture-in-picture.html
new file mode 100644
index 00000000000..b212488507c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/request-picture-in-picture.html
@@ -0,0 +1,37 @@
+<!DOCTYPE html>
+<title>Test request Picture-in-Picture</title>
+<script src="../common/media.js"></script>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../resources/testdriver.js"></script>
+<script src="../resources/testdriver-vendor.js"></script>
+<script src="resources/picture-in-picture-helpers.js"></script>
+<body></body>
+<script>
+promise_test(async t => {
+ const video = await loadVideo();
+ return promise_rejects_dom(t, 'NotAllowedError', video.requestPictureInPicture());
+}, 'request Picture-in-Picture requires a user gesture');
+
+promise_test(t => {
+ const video = document.createElement('video');
+ return promise_rejects_dom(t, 'InvalidStateError',
+ requestPictureInPictureWithTrustedClick(video));
+}, 'request Picture-in-Picture requires loaded metadata for the video element');
+
+promise_test(async t => {
+ const video = document.createElement('video');
+ await new Promise(resolve => {
+ video.src = getAudioURI('/media/sound_5');
+ video.onloadeddata = resolve;
+ }).then(() => {
+ return promise_rejects_dom(t, 'InvalidStateError',
+ requestPictureInPictureWithTrustedClick(video));
+ })
+}, 'request Picture-in-Picture requires video track for the video element');
+
+promise_test(async t => {
+ const video = await loadVideo();
+ return requestPictureInPictureWithTrustedClick(video);
+}, 'request Picture-in-Picture resolves on user click');
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/resources/unload-document-helper.html b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/resources/unload-document-helper.html
new file mode 100644
index 00000000000..22562af5453
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/resources/unload-document-helper.html
@@ -0,0 +1,15 @@
+<!DOCTYPE html>
+<title>Picture-in-Picture unload-document helper</title>
+<script src="/common/media.js"></script>
+<body></body>
+<script>
+'use strict';
+
+window.video = document.createElement('video');
+window.video.src = getVideoURI('/media/movie_5');
+window.videoReady = new Promise((resolve, reject) => {
+ window.video.onloadedmetadata = () => resolve(window.video);
+ window.video.onerror = reject;
+});
+document.body.appendChild(window.video);
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/shadow-dom.html b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/shadow-dom.html
new file mode 100644
index 00000000000..e705acdbd90
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/shadow-dom.html
@@ -0,0 +1,175 @@
+<!DOCTYPE html>
+<title>Test for Picture-In-Picture and Shadow DOM</title>
+<script src="../common/media.js"></script>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../resources/testdriver.js"></script>
+<script src="../resources/testdriver-vendor.js"></script>
+<script src="resources/picture-in-picture-helpers.js"></script>
+<script src="../shadow-dom/resources/shadow-dom.js"></script>
+<style>
+ #host2 { color: rgb(0, 0, 254); }
+ #host2:picture-in-picture { color: rgb(0, 0, 255); }
+</style>
+<body>
+<div id='host'>
+ <template data-mode='open' id='root'>
+ <slot></slot>
+ </template>
+ <div id='host2'>
+ <template data-mode='open' id='root2'>
+ <style>
+ #host3 { color: rgb(0, 0, 127); }
+ #host3:picture-in-picture { color: rgb(0, 0, 128); }
+ </style>
+ <div id='host3'>
+ <template data-mode='open' id='root3'>
+ <style>
+ video { color: rgb(0, 254, 0); }
+ video:picture-in-picture { color: rgb(0, 255, 0); }
+ </style>
+ <video id='video'></video>
+ <div id='host4'>
+ <template data-mode='open' id='root4'>
+ <div></div>
+ </template>
+ </div>
+ </template>
+ </div>
+ <div id='host5'>
+ <template data-mode='open' id='root5'>
+ <div></div>
+ </template>
+ </div>
+ </template>
+ </div>
+</div>
+</body>
+<script>
+promise_test(async t => {
+ const ids = createTestTree(host);
+ document.body.appendChild(ids.host);
+
+ assert_equals(document.pictureInPictureElement, null);
+ assert_equals(ids.root.pictureInPictureElement, null);
+ assert_equals(ids.root2.pictureInPictureElement, null);
+ assert_equals(ids.root3.pictureInPictureElement, null);
+ assert_equals(ids.root4.pictureInPictureElement, null);
+ assert_equals(ids.root5.pictureInPictureElement, null);
+
+ assert_equals(getComputedStyle(ids.video).color, 'rgb(0, 254, 0)');
+ assert_equals(getComputedStyle(ids.host3).color, 'rgb(0, 0, 127)');
+ assert_equals(getComputedStyle(ids.host2).color, 'rgb(0, 0, 254)');
+
+ await new Promise(resolve => {
+ ids.video.src = getVideoURI('/media/movie_5');
+ ids.video.onloadeddata = resolve;
+ })
+ .then(() => requestPictureInPictureWithTrustedClick(ids.video))
+ .then(() => {
+ assert_equals(document.pictureInPictureElement, ids.host2);
+ assert_equals(ids.root.pictureInPictureElement, null);
+ assert_equals(ids.root2.pictureInPictureElement, ids.host3);
+ assert_equals(ids.root3.pictureInPictureElement, ids.video);
+ assert_equals(ids.root4.pictureInPictureElement, null);
+ assert_equals(ids.root5.pictureInPictureElement, null);
+
+ assert_equals(getComputedStyle(ids.video).color, 'rgb(0, 255, 0)');
+ assert_equals(getComputedStyle(ids.host3).color, 'rgb(0, 0, 127)');
+ assert_equals(getComputedStyle(ids.host2).color, 'rgb(0, 0, 254)');
+ })
+ .then(() => document.exitPictureInPicture())
+ .then(() => {
+ assert_equals(getComputedStyle(ids.video).color, 'rgb(0, 254, 0)');
+ assert_equals(getComputedStyle(ids.host3).color, 'rgb(0, 0, 127)');
+ assert_equals(getComputedStyle(ids.host2).color, 'rgb(0, 0, 254)');
+ });
+});
+
+async function shadowRootTest(mode) {
+ const video = await loadVideo();
+ const host = document.createElement('div');
+ const shadow = host.attachShadow({ mode });
+ shadow.appendChild(video);
+ await requestPictureInPictureWithTrustedClick(video);
+
+ assert_equals(document.pictureInPictureElement, host,
+ 'document.pictureInPictureElement is the disconnected shadow host ' +
+ '(retargeted across the shadow boundary from the unbound video)');
+
+ // Test the step 1 of the pictureInPictureElement getter algorithm:
+ // If this is a shadow root and its host is not connected,
+ // return null and abort these steps.
+ // Which looks odd, given that document.pictureInPictureElement returns non-null.
+ // See https://github.com/w3c/picture-in-picture/pull/253
+ assert_equals(shadow.pictureInPictureElement, null,
+ 'shadowRoot.pictureInPictureElement is null while the shadow root\'s ' +
+ 'host is not connected');
+
+ return { video, host, shadow };
+}
+
+promise_test(async t => {
+ const { shadow } = await shadowRootTest('open');
+ await document.exitPictureInPicture();
+ assert_equals(document.pictureInPictureElement, null);
+ assert_equals(shadow.pictureInPictureElement, null);
+}, 'Picture-in-Picture on a video inside an open shadow root attached to a ' +
+ 'disconnected host');
+
+promise_test(async t => {
+ const { shadow } = await shadowRootTest('closed');
+ await document.exitPictureInPicture();
+ assert_equals(document.pictureInPictureElement, null);
+ assert_equals(shadow.pictureInPictureElement, null);
+}, 'Picture-in-Picture on a video inside a closed shadow root attached to a ' +
+ 'disconnected host');
+
+promise_test(async t => {
+ const { video, host, shadow } = await shadowRootTest('open');
+ document.body.appendChild(host);
+
+ assert_equals(document.pictureInPictureElement, host,
+ 'after connect: document.pictureInPictureElement is still the host');
+ assert_equals(shadow.pictureInPictureElement, video,
+ 'after connect: shadow.pictureInPictureElement is the video, because ' +
+ 'the shadow root is now in a composed document and the video is in ' +
+ 'this shadow\'s tree');
+
+ await document.exitPictureInPicture();
+ assert_equals(document.pictureInPictureElement, null);
+ assert_equals(shadow.pictureInPictureElement, null);
+}, 'Connecting a previously-disconnected shadow host after Picture-in-Picture ' +
+ 'starts exposes the video through shadowRoot.pictureInPictureElement');
+
+// Nested shadow roots where the outermost host is disconnected: retargeting
+// must walk all the way up to the outermost (disconnected) host, and neither
+// inner nor outer shadow root must expose the element because both are
+// outside the composed tree.
+promise_test(async t => {
+ const video = await loadVideo();
+ const outerHost = document.createElement('div');
+ const outerShadow = outerHost.attachShadow({ mode: 'open' });
+ const innerHost = document.createElement('div');
+ outerShadow.appendChild(innerHost);
+ const innerShadow = innerHost.attachShadow({ mode: 'open' });
+ innerShadow.appendChild(video);
+
+ assert_false(outerHost.isConnected);
+ assert_equals(document.pictureInPictureElement, null);
+
+ await requestPictureInPictureWithTrustedClick(video);
+
+ assert_equals(document.pictureInPictureElement, outerHost,
+ 'document.pictureInPictureElement is the outermost disconnected host');
+ assert_equals(outerShadow.pictureInPictureElement, null,
+ 'outerShadow.pictureInPictureElement is null while the outer host is ' +
+ 'not connected');
+ assert_equals(innerShadow.pictureInPictureElement, null,
+ 'innerShadow.pictureInPictureElement is null while the outer host is ' +
+ 'not connected (the inner shadow is not in a composed document either)');
+
+ await document.exitPictureInPicture();
+}, 'Picture-in-Picture on a video inside nested shadow roots whose outer ' +
+ 'host is disconnected');
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/unload-document-exits-picture-in-picture.html b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/unload-document-exits-picture-in-picture.html
new file mode 100644
index 00000000000..98190606474
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/picture-in-picture/unload-document-exits-picture-in-picture.html
@@ -0,0 +1,57 @@
+<!DOCTYPE html>
+<title>Exit Picture-in-Picture runs during unloading document cleanup steps</title>
+<meta name="timeout" content="long">
+<link rel="help" href="https://w3c.github.io/picture-in-picture/#exit-pip">
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../resources/testdriver.js"></script>
+<script src="../resources/testdriver-vendor.js"></script>
+<body></body>
+<script>
+'use strict';
+
+const HELPER = '/picture-in-picture/resources/unload-document-helper.html';
+
+function loadIframe(src) {
+ return new Promise(resolve => {
+ const iframe = document.createElement('iframe');
+ iframe.addEventListener('load', () => resolve(iframe), { once: true });
+ iframe.src = src;
+ document.body.appendChild(iframe);
+ });
+}
+
+function navigateIframe(iframe, src) {
+ return new Promise(resolve => {
+ iframe.addEventListener('load', resolve, { once: true });
+ iframe.src = src;
+ });
+}
+
+promise_test(async t => {
+ const iframe = await loadIframe(HELPER);
+ t.add_cleanup(() => iframe.remove());
+ const video = await iframe.contentWindow.videoReady;
+
+ await test_driver.bless('enter Picture-in-Picture from iframe', null,
+ iframe.contentWindow);
+ const pipWindow = await video.requestPictureInPicture();
+
+ assert_equals(iframe.contentDocument.pictureInPictureElement, video,
+ 'pictureInPictureElement is set inside the iframe document');
+
+ assert_not_equals(pipWindow.width, 0,
+ 'pipWindow.width is non-zero before the iframe is unloaded');
+ assert_not_equals(pipWindow.height, 0,
+ 'pipWindow.height is non-zero before the iframe is unloaded');
+
+ await navigateIframe(iframe, '/common/blank.html');
+
+ assert_equals(iframe.contentDocument.pictureInPictureElement, null,
+ 'the new iframe document has no pictureInPictureElement');
+ await t.step_wait(
+ () => pipWindow.width === 0 && pipWindow.height === 0,
+ 'pipWindow.width and pipWindow.height become 0 after the iframe ' +
+ 'document is unloaded');
+}, 'exit Picture-in-Picture algorithm runs as part of unloading document cleanup steps');
+</script>