From 6b1a1fae3d7b1f5534d4b0b5904ad5beed61468a Mon Sep 17 00:00:00 2001 From: rgxdev Date: Wed, 25 Nov 2026 00:03:19 +0100 Subject: [PATCH 1/3] feat: move playing video into Picture in Picture on tab switch A video playing with sound moves into Picture in Picture when its tab leaves the screen (tab switch, space switch, start page, leaving a split) and back into the page when the tab returns. A window the user opened in that tab stays. Settings > Tabs has a switch, on by default. The engine's Picture in Picture script takes a mode (toggle, enter, exit). Entering runs only after the engine reports playback; on Chromium a check in the isolated world without a gesture comes first, and nothing runs under Lockdown. Linux and Android are documented gaps; iOS is in the port backlog. Signed-off-by: rgxdev --- CHANGELOG.md | 3 ++ README.md | 4 ++ crates/app/src/browser/events.rs | 3 +- crates/app/src/browser/views.rs | 4 ++ crates/app/src/capture.rs | 2 +- crates/app/src/mini_player.rs | 67 +++++++++++++++++++++++++++- crates/app/src/prefs.rs | 9 +++- crates/app/src/settings.rs | 8 ++++ crates/app/src/split.rs | 6 +++ crates/browser-core/src/media.rs | 37 ++++++++++++++++ crates/browser-core/src/prefs.rs | 2 + crates/engine/src/chromium/view.rs | 21 ++++++++- crates/engine/src/page_scripts.rs | 70 ++++++++++++++++++++++++++---- crates/engine/src/view.rs | 4 +- crates/engine/src/view_windows.rs | 4 +- crates/engine/src/webview.rs | 17 +++++--- docs/mobile-plan.md | 4 ++ docs/nsh-plan.md | 7 +-- docs/port-backlog.md | 14 ++++++ docs/shared-core.md | 3 +- docs/threat-model.md | 2 +- 21 files changed, 260 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 704480b7..374ca8b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,9 @@ All notable changes to Tarn are documented in this file. The format is based on ### Added +- A video playing with sound moves into Picture in Picture when you switch to another tab, and + back into its page when you return; a window you opened yourself in that tab stays. Settings › Tabs turns it + off. macOS (WebKit tabs) and Windows. - Assistant chats are kept: each profile lists its chats to search, open, rename and delete, and Settings › AI deletes them all. An answer can be copied and retried and its question edited; code blocks get Copy; `/` lists the commands; the chat header picks the provider and Claude diff --git a/README.md b/README.md index 65f9d31b..2eae4070 100644 --- a/README.md +++ b/README.md @@ -334,6 +334,10 @@ Trackpad (Settings › Tabs › Trackpad gestures): swipe left or right over the spaces; swipe over the address field to step through tabs; swipe right over the toolbar to show the sidebar. The mouse's back and forward buttons always navigate. +A video playing with sound moves into Picture in Picture when you switch to another tab, and back +into its page when you return (Settings › Tabs › Picture in Picture when switching tabs; macOS +WebKit tabs and Windows). +
diff --git a/crates/app/src/browser/events.rs b/crates/app/src/browser/events.rs index 3b410940..77fe12f7 100644 --- a/crates/app/src/browser/events.rs +++ b/crates/app/src/browser/events.rs @@ -391,8 +391,9 @@ impl Browser { link: Option>, cx: &mut Context, ) { - if self.model.tab(key).is_some() && self.views.remove(&key).is_some() { + if self.model.tab(key).is_some() && self.views.contains_key(&key) { self.forget_media(key); + self.views.remove(&key); // The old view's last events are dropped; the new one says when its load starts. let page = self.pages.entry(key).or_default(); page.loading = false; diff --git a/crates/app/src/browser/views.rs b/crates/app/src/browser/views.rs index 2011c4af..0ff3bacc 100644 --- a/crates/app/src/browser/views.rs +++ b/crates/app/src/browser/views.rs @@ -286,6 +286,7 @@ impl Browser { return; } let switched = self.model.active != Some(key); + let before = self.screen_tabs(); let _span = switched.then(|| engine::startup::span(engine::startup::TAB_SWITCH)).flatten(); if switched { self.leave_page_fullscreen(window); @@ -347,6 +348,7 @@ impl Browser { } } } + self.screen_changed(before, cx); self.model.touch(&self.core, key, now()); if !self.overlay_open() { window.focus(&self.focus); @@ -594,6 +596,7 @@ impl Browser { if self.command_mode.is_some() { self.close_command(window, cx); } + let before = self.screen_tabs(); if let Some(view) = self.active_view() { view.set_visible(false); } @@ -612,6 +615,7 @@ impl Browser { self.space_shown(&[]); self.slide_from(from, old); self.pick_active(window, cx); + self.screen_changed(before, cx); if burning && !self.model.burner_shown() { self.burn(cx); } diff --git a/crates/app/src/capture.rs b/crates/app/src/capture.rs index aff20fcd..0b185469 100644 --- a/crates/app/src/capture.rs +++ b/crates/app/src/capture.rs @@ -144,7 +144,7 @@ impl Browser { fn picture_in_picture(&mut self, cx: &mut Context) { let (Some(key), Some(view)) = (self.model.active, self.active_view()) else { return }; let (weak, (tx, mut rx)) = (Rc::downgrade(&view), mpsc::unbounded()); - view.picture_in_picture(move |result| drop(tx.unbounded_send(result))); + view.picture_in_picture(engine::page_scripts::PipMode::Toggle, move |result| drop(tx.unbounded_send(result))); cx.spawn(async move |this, cx| { let notice = match rx.next().await.as_deref() { Some("none") => "This page has no video", diff --git a/crates/app/src/mini_player.rs b/crates/app/src/mini_player.rs index 2446f80b..f1a19ee4 100644 --- a/crates/app/src/mini_player.rs +++ b/crates/app/src/mini_player.rs @@ -4,6 +4,7 @@ use std::rc::Rc; use browser_core::media::{Control, POLL}; use browser_core::page_ops::MediaState; +use engine::page_scripts::PipMode; use futures::StreamExt; use futures::channel::mpsc; use gpui::{AnyElement, Context, InteractiveElement, ParentElement, SharedString, StatefulInteractiveElement, Styled, Task, Window, div, px}; @@ -18,6 +19,7 @@ use crate::browser::{Browser, TabKey}; #[derive(Default)] pub struct MiniPlayer { pub(crate) player: browser_core::media::Player, + auto_pip: browser_core::media::AutoPip, poll: Option>, } @@ -59,9 +61,72 @@ impl Browser { })); } - /// Drops `key` from the mini-player once its view is gone. + /// Drops `key` from the mini-player once its view is gone; a video Tarn moved into Picture in + /// Picture comes back out, since the tab closes or shows in another window. pub(crate) fn forget_media(&mut self, key: TabKey) { self.mini_player.player.forget(key); + if self.mini_player.auto_pip.take(key) { + self.exit_pip(key); + } + } + + /// The tabs on screen: the active tab, or every pane of its split. + pub(crate) fn screen_tabs(&self) -> Vec { + let active = self.model.active; + active.and_then(|k| self.splits.of(k)).map_or_else(|| active.into_iter().collect(), |s| s.panes().to_vec()) + } + + /// After the tabs on screen changed from `before`: a playing video of a tab that left moves + /// into Picture in Picture, and one Tarn moved there comes back once its tab returns. + pub(crate) fn screen_changed(&mut self, before: Vec, cx: &mut Context) { + let now = self.screen_tabs(); + for gone in before.into_iter().filter(|k| !now.contains(k)) { + self.leave_for_pip(gone, cx); + } + for back in now { + if self.mini_player.auto_pip.take(back) { + self.exit_pip(back); + } + } + } + + /// Asks the engine first whether the page plays (on WebKit its own playback state), so a page + /// that plays nothing gets no script, and with it no gesture, when its tab leaves the screen. + fn leave_for_pip(&mut self, key: TabKey, cx: &mut Context) { + if !self.pref(crate::prefs::Pref::AutoPictureInPicture) { + return; + } + let Some(view) = self.views.get(&key) else { return }; + let (weak, (tx, mut rx)) = (Rc::downgrade(view), mpsc::unbounded()); + view.media_playing(move |playing| drop(tx.unbounded_send(playing))); + cx.spawn(async move |this, cx| { + if rx.next().await != Some(true) { + return; + } + this.update(cx, |b, cx| { + let Some(view) = weak.upgrade().filter(|_| b.same_view(key, &weak) && !b.screen_tabs().contains(&key)) else { return }; + let (tx, mut rx) = mpsc::unbounded(); + view.picture_in_picture(PipMode::Enter, move |result| drop(tx.unbounded_send(result))); + cx.spawn(async move |this, cx| { + let Some(result) = rx.next().await else { return }; + this.update(cx, |b, _| { + if b.same_view(key, &weak) && b.mini_player.auto_pip.answered(key, &result, b.screen_tabs().contains(&key)) { + b.exit_pip(key); + } + }) + .ok(); + }) + .detach(); + }) + .ok(); + }) + .detach(); + } + + fn exit_pip(&self, key: TabKey) { + if let Some(view) = self.views.get(&key) { + view.picture_in_picture(PipMode::Exit, |_| {}); + } } fn press_media(&mut self, control: Control, cx: &mut Context) { diff --git a/crates/app/src/prefs.rs b/crates/app/src/prefs.rs index 301d416b..805b1a95 100644 --- a/crates/app/src/prefs.rs +++ b/crates/app/src/prefs.rs @@ -34,10 +34,11 @@ pub enum Pref { Passkeys, FeatureHints, CompactDensity, + AutoPictureInPicture, } impl Pref { - pub const ALL: [Pref; 26] = [ + pub const ALL: [Pref; 27] = [ Pref::CompactToolbar, Pref::AutoHideSidebar, Pref::Gestures, @@ -64,6 +65,7 @@ impl Pref { Pref::Passkeys, Pref::FeatureHints, Pref::CompactDensity, + Pref::AutoPictureInPicture, ]; pub(crate) fn key(self) -> &'static str { @@ -94,6 +96,7 @@ impl Pref { Pref::Passkeys => browser_core::settings::PASSKEYS, Pref::FeatureHints => browser_core::prefs::FEATURE_HINTS.key, Pref::CompactDensity => browser_core::prefs::COMPACT.key, + Pref::AutoPictureInPicture => browser_core::prefs::AUTO_PICTURE_IN_PICTURE.key, } } @@ -115,6 +118,7 @@ impl Pref { | Pref::LocalhostFromApps | Pref::Passkeys | Pref::FeatureHints + | Pref::AutoPictureInPicture ) } @@ -353,10 +357,12 @@ impl Browser { pub fn new_tab_page(&mut self, window: &mut Window, cx: &mut Context) { let replaced = self.model.active.filter(|_| self.pref(Pref::NewTabStartPage) && !self.overlay_open() && !self.inline_editing()); if replaced.is_some() { + let before = self.screen_tabs(); if let Some(view) = self.active_view() { view.set_visible(false); } self.model.active = None; + self.screen_changed(before, cx); } // Before the sidebar closes, so a click in it still hands the field to the main window. self.open_command(CommandMode::NewTab, window, cx); @@ -498,6 +504,7 @@ mod tests { (Pref::TearOffTemporary, prefs::TEAR_OFF_TEMPORARY), (Pref::FeatureHints, prefs::FEATURE_HINTS), (Pref::CompactDensity, prefs::COMPACT), + (Pref::AutoPictureInPicture, prefs::AUTO_PICTURE_IN_PICTURE), ] { assert_eq!((pref.key(), pref.default()), (switch.key, switch.default), "{pref:?}"); } diff --git a/crates/app/src/settings.rs b/crates/app/src/settings.rs index c5f791d7..acfebe5d 100644 --- a/crates/app/src/settings.rs +++ b/crates/app/src/settings.rs @@ -1127,6 +1127,14 @@ impl SettingsWindow { }, s.prefs.get(Pref::Gestures), cx, + )) + .child(self.pref_row( + false, + Pref::AutoPictureInPicture, + "Picture in Picture when switching tabs", + "A playing video with sound keeps playing in a floating window while you are in another tab, and goes back into its page when you return.", + s.prefs.get(Pref::AutoPictureInPicture), + cx, )), ) .into_any_element() diff --git a/crates/app/src/split.rs b/crates/app/src/split.rs index 0d527eb1..d7135f0c 100644 --- a/crates/app/src/split.rs +++ b/crates/app/src/split.rs @@ -156,16 +156,22 @@ impl Browser { /// Takes `key` out of its split; the tab stays open and a split left with one pane ends. pub fn leave_split(&mut self, key: TabKey, window: &mut Window, cx: &mut Context) { + let before = self.screen_tabs(); let heir = self.splits.leave(key).filter(|_| self.model.active == Some(key)); if let Some(heir) = heir { self.activate(heir, window, cx); } self.split_moved(cx); + if heir.is_none() { + self.screen_changed(before, cx); + } } pub fn close_split(&mut self, key: TabKey, cx: &mut Context) { + let before = self.screen_tabs(); if self.splits.close(key) { self.split_moved(cx); + self.screen_changed(before, cx); } } diff --git a/crates/browser-core/src/media.rs b/crates/browser-core/src/media.rs index 099bffad..44ee1adf 100644 --- a/crates/browser-core/src/media.rs +++ b/crates/browser-core/src/media.rs @@ -2,6 +2,7 @@ //! ask `page_ops::MediaState` of a tab once the engine says it plays, and again every `POLL` only //! while the shown media plays, so nothing ticks while nothing plays. +use std::collections::HashSet; use std::time::Duration; use engine::page_scripts::MediaCommand; @@ -111,6 +112,30 @@ impl Player { } } +/// The tabs whose video Tarn moved into Picture in Picture when they left the screen, so only +/// those come back out when the tab returns; one the user moved there stays. +#[derive(Clone, Debug, Default)] +pub struct AutoPip { + entered: HashSet, +} + +impl AutoPip { + /// `key`'s page answered `result` to `PipMode::Enter`; true when its video should come back out + /// at once, because the tab is `visible` again before the answer arrived. + pub fn answered(&mut self, key: TabKey, result: &str, visible: bool) -> bool { + let entered = result == "pip"; + if entered && !visible { + self.entered.insert(key); + } + entered && visible + } + + /// True once for a tab Tarn moved into Picture in Picture: on its return, or when it goes. + pub fn take(&mut self, key: TabKey) -> bool { + self.entered.remove(&key) + } +} + #[cfg(test)] mod tests { use super::*; @@ -150,6 +175,18 @@ mod tests { assert!(player.forget(key(2)) && player.tab().is_none()); } + #[test] + fn only_video_tarn_moved_comes_back_out() { + let mut pip = AutoPip::default(); + assert!(!pip.answered(key(1), "pip", false)); + assert!(!pip.answered(key(2), "open", false), "the user's own window is not Tarn's"); + assert!(!pip.answered(key(3), "refused", false)); + assert!(pip.take(key(1)) && !pip.take(key(1)), "back out once"); + assert!(!pip.take(key(2)) && !pip.take(key(3))); + assert!(pip.answered(key(4), "pip", true), "back on screen before the answer: out at once"); + assert!(!pip.take(key(4))); + } + #[test] fn the_visible_tab_shows_no_mini_player() { let mut player = Player::default(); diff --git a/crates/browser-core/src/prefs.rs b/crates/browser-core/src/prefs.rs index 3bd5bd77..c19f39a9 100644 --- a/crates/browser-core/src/prefs.rs +++ b/crates/browser-core/src/prefs.rs @@ -13,6 +13,8 @@ pub const REDUCE_MOTION: Switch = Switch { key: "reduce_motion", default: false pub const NEW_TAB_START_PAGE: Switch = Switch { key: "new_tab_start_page", default: false }; pub const CLOSE_SELECTS_PREVIOUS: Switch = Switch { key: "close_selects_previous", default: false }; pub const TEAR_OFF_TEMPORARY: Switch = Switch { key: "tear_off_temporary", default: true }; +/// A playing video moves into Picture in Picture when its tab leaves the screen, and back after. +pub const AUTO_PICTURE_IN_PICTURE: Switch = Switch { key: "auto_picture_in_picture", default: true }; /// Settings' switch for the toasts that name a command's shortcut (`hints`), on every client. pub const FEATURE_HINTS: Switch = Switch { key: "feature_hints", default: true }; /// Settings' Appearance switch for compact density: tighter sidebar and tab strip rows on every client. diff --git a/crates/engine/src/chromium/view.rs b/crates/engine/src/chromium/view.rs index 26a9dd59..a1ba6fc4 100644 --- a/crates/engine/src/chromium/view.rs +++ b/crates/engine/src/chromium/view.rs @@ -2280,8 +2280,25 @@ impl WebView { } } - pub fn picture_in_picture(&self, done: impl Fn(String) + 'static) { - self.run_isolated_as_gesture(crate::page_scripts::PICTURE_IN_PICTURE, true, done); + /// Only entering needs the user's gesture, which the page shares: the automatic `Enter` lends + /// it only once a check without one found a video to take, and `Exit` lends none. The automatic + /// modes run no script of Tarn's under Lockdown. + pub fn picture_in_picture(&self, mode: crate::page_scripts::PipMode, done: impl Fn(String) + 'static) { + use crate::page_scripts::{PipMode, picture_in_picture_ready_script, picture_in_picture_script}; + if mode != PipMode::Toggle && self.lockdown_view() { + return done("refused".into()); + } + if mode != PipMode::Enter { + return self.run_isolated_as_gesture(&picture_in_picture_script(mode), mode == PipMode::Toggle, done); + } + let (inner, done) = (Rc::downgrade(&self.0), Rc::new(done)); + self.run_isolated(&picture_in_picture_ready_script(), move |answer| match (answer.as_str(), inner.upgrade()) { + ("ready", Some(inner)) => { + let done = done.clone(); + WebView(inner).run_isolated_as_gesture(&picture_in_picture_script(PipMode::Enter), true, move |a| done(a)); + } + _ => done(answer), + }); } /// The visible page as PNG, scaled to `width` points when given. diff --git a/crates/engine/src/page_scripts.rs b/crates/engine/src/page_scripts.rs index b61ebad3..d878709f 100644 --- a/crates/engine/src/page_scripts.rs +++ b/crates/engine/src/page_scripts.rs @@ -419,21 +419,61 @@ pub fn json_text_script(origin: &Url, max_bytes: usize) -> Option { )) } -/// Toggles picture in picture for the page's playing or largest video: "pip", "exit", "none" or -/// "refused". An async function body for the engine's isolated world. -pub const PICTURE_IN_PICTURE: &str = r"const area = v => v.clientWidth * v.clientHeight; - const videos = Array.from(document.querySelectorAll('video')).filter(v => v.readyState > 0).sort((a, b) => area(b) - area(a)); - const video = videos.find(v => !v.paused) || videos[0]; - if (!video) return 'none'; - if (document.pictureInPictureElement === video) { await document.exitPictureInPicture(); return 'exit'; } - if (video.webkitPresentationMode === 'picture-in-picture') { video.webkitSetPresentationMode('inline'); return 'exit'; } - try { await video.requestPictureInPicture(); return 'pip'; } catch (e) {} +/// What `picture_in_picture_script` does with the page's video. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PipMode { + /// The user's command: the playing or largest video goes in, or back out. + Toggle, + /// The tab left the screen: only a playing, audible video of at least 200 by 200 CSS pixels + /// goes in, and nothing while a video of the page already is in. + Enter, + /// The tab is back on screen: the video in picture in picture goes back into the page. + Exit, +} + +const PIP_ENTER_PICK: &str = + "videos.some(shown) ? 'open' : videos.find(v => !v.paused && !v.ended && !v.muted && v.volume > 0 && v.videoWidth > 0 && area(v) >= 40000)"; +const PIP_ENTER: &str = r"try { await video.requestPictureInPicture(); return 'pip'; } catch (e) {} if (!video.disablePictureInPicture && video.webkitSupportsPresentationMode && video.webkitSupportsPresentationMode('picture-in-picture')) { video.webkitSetPresentationMode('picture-in-picture'); return 'pip'; } return 'refused';"; +/// Picture in picture for the page's video, as `mode` says: "pip", "open" (one already in), +/// "exit", "none" or "refused". An async function body for the engine's isolated world. +pub fn picture_in_picture_script(mode: PipMode) -> String { + match mode { + PipMode::Toggle => pip_script("videos.find(v => !v.paused) || videos[0]", "return await leave(video);", PIP_ENTER), + PipMode::Enter => pip_script(PIP_ENTER_PICK, "return 'open';", PIP_ENTER), + PipMode::Exit => pip_script("videos.find(shown)", "return await leave(video);", ""), + } +} + +/// `PipMode::Enter`'s choice without entering: "ready" when it would ask for picture in picture. +/// Run without a gesture, so a page lends one only for a video Enter takes. +pub fn picture_in_picture_ready_script() -> String { + pip_script(PIP_ENTER_PICK, "return 'open';", "return 'ready';") +} + +fn pip_script(pick: &str, shown: &str, enter: &str) -> String { + format!( + r"const area = v => v.clientWidth * v.clientHeight; + const shown = v => document.pictureInPictureElement === v || v.webkitPresentationMode === 'picture-in-picture'; + const leave = async v => {{ + if (document.pictureInPictureElement === v) await document.exitPictureInPicture(); + else v.webkitSetPresentationMode('inline'); + return 'exit'; + }}; + const videos = Array.from(document.querySelectorAll('video')).filter(v => v.readyState > 0).sort((a, b) => area(b) - area(a)); + const video = {pick}; + if (video === 'open') return 'open'; + if (!video) return 'none'; + if (shown(video)) {shown} + {enter}" + ) +} + /// `lifecycle::Hang`'s ping: it reads nothing, and answers only once the page's main thread is free. pub const PING: &str = "return '';"; @@ -628,6 +668,18 @@ mod tests { use super::*; + #[test] + fn only_the_toggle_and_enter_ask_for_picture_in_picture() { + let [toggle, enter, exit] = [PipMode::Toggle, PipMode::Enter, PipMode::Exit].map(picture_in_picture_script); + assert!(toggle.contains("requestPictureInPicture") && toggle.contains("return await leave(video)")); + assert!(enter.contains("requestPictureInPicture") && enter.contains("!v.muted") && enter.contains("return 'open'")); + assert!(!enter.contains("return await leave(video)"), "entering never takes a video out"); + assert!(!exit.contains("requestPictureInPicture") && !exit.contains("webkitSetPresentationMode('picture-in-picture')")); + let ready = picture_in_picture_ready_script(); + assert!(ready.contains("videos.some(shown) ? 'open'") && ready.contains("return 'ready'")); + assert!(!ready.contains("requestPictureInPicture") && !ready.contains("webkitSetPresentationMode('picture-in-picture')")); + } + const HOSTILE_CSS: &str = "\"'`${x}\\\u{2028}\nbody{}"; #[test] diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index b1871d45..fd8cf830 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -257,8 +257,8 @@ impl WebView { webkit_only!(self, v => v.set_passkeys(on), ()) } - pub fn picture_in_picture(&self, done: impl Fn(String) + 'static) { - webkit_only!(self, v => v.picture_in_picture(done), done("refused".into())) + pub fn picture_in_picture(&self, mode: crate::page_scripts::PipMode, done: impl Fn(String) + 'static) { + webkit_only!(self, v => v.picture_in_picture(mode, done), done("refused".into())) } pub fn title(&self) -> String { diff --git a/crates/engine/src/view_windows.rs b/crates/engine/src/view_windows.rs index 52953863..9a975b03 100644 --- a/crates/engine/src/view_windows.rs +++ b/crates/engine/src/view_windows.rs @@ -211,8 +211,8 @@ impl WebView { self.view.pdf(done); } - pub fn picture_in_picture(&self, done: impl Fn(String) + 'static) { - self.view.picture_in_picture(done); + pub fn picture_in_picture(&self, mode: crate::page_scripts::PipMode, done: impl Fn(String) + 'static) { + self.view.picture_in_picture(mode, done); } pub fn title(&self) -> String { diff --git a/crates/engine/src/webview.rs b/crates/engine/src/webview.rs index bb3fdc8b..9ffba4db 100644 --- a/crates/engine/src/webview.rs +++ b/crates/engine/src/webview.rs @@ -26,8 +26,8 @@ use crate::delegates::{Delegate, DelegateState, serialized_origin, to_url}; use crate::extensions::Tab; use crate::handover::{self, Storage}; use crate::page_scripts::{ - PICKER, PICTURE_IN_PICTURE, fetch_icon_script, find_count, find_count_script, find_snippets, find_text_script, icon_links_script, json_text_script, - page_text_script, + PICKER, PipMode, fetch_icon_script, find_count, find_count_script, find_snippets, find_text_script, icon_links_script, json_text_script, page_text_script, + picture_in_picture_script, }; use crate::{DataStore, Event}; @@ -731,11 +731,14 @@ impl WebView { } } - /// Moves the largest playing video (else the largest video) into Picture in Picture, or back - /// out of it. WebKit treats the shell's script as a user gesture. `done` receives "pip", - /// "exit", "none" or "refused". - pub fn picture_in_picture(&self, done: impl Fn(String) + 'static) { - self.run_isolated(PICTURE_IN_PICTURE, done); + /// Moves the page's video into Picture in Picture or back out of it, as `mode` says. WebKit + /// treats the shell's script as a user gesture. `done` receives "pip", "open", "exit", "none" + /// or "refused"; the automatic modes run nothing under Lockdown. + pub fn picture_in_picture(&self, mode: PipMode, done: impl Fn(String) + 'static) { + if mode != PipMode::Toggle && self._delegate.level() == ShieldLevel::Lockdown { + return done("refused".into()); + } + self.run_isolated(&picture_in_picture_script(mode), done); } pub fn title(&self) -> String { diff --git a/docs/mobile-plan.md b/docs/mobile-plan.md index 7baa1b53..f661fd51 100644 --- a/docs/mobile-plan.md +++ b/docs/mobile-plan.md @@ -321,6 +321,10 @@ decisions come from `browser_core::tarn_ext`. - **Gap: Ollama on iOS.** Ollama does not run on iOS, so nothing answers on `127.0.0.1` there; Settings › AI offers the Claude API only and names this reason (`mobile/app/src/platform.rs` `ASSISTANT`). +- **Gap: Picture in Picture on Android.** Android System WebView does not support Picture in + Picture for a page's video; Android's own picture-in-picture mode + shrinks the whole activity, not one tab's video, so neither the command nor its automatic move on + a tab switch exists there. - **Gap: playing media on Android.** Android has no isolated world that runs as the user's gesture, so the `media` command's `play` is refused where the page's media needs one (`setMediaPlaybackRequiresUserGesture`); pause and seek work. diff --git a/docs/nsh-plan.md b/docs/nsh-plan.md index 58e8fbf9..0a071653 100644 --- a/docs/nsh-plan.md +++ b/docs/nsh-plan.md @@ -320,9 +320,10 @@ icons and brand mark are `crates/ui`'s own files. Deviations: and defaults from `browser_core::settings`; Never stops idle sleeping and the memory budget, short of memory too. Evidence: `linux/evidence/parity-sleeping-tabs.png`. -- Picture in Picture (macOS command and `⌘⌃P`) has no Linux command. Gap: WebKitGTK has no - Picture-in-Picture; WebKit's video presentation mode exists only on its Cocoa ports, and the - pinned `webkit6` 0.6.1 has no API for it. +- Picture in Picture (macOS command and `⌘⌃P`, and its automatic move when a tab with playing video + leaves the screen) has no Linux counterpart. Gap: WebKitGTK has no Picture-in-Picture; WebKit's + video presentation mode exists only on its Cocoa ports, and the pinned `webkit6` 0.6.1 has no API + for it. - Links from other apps: a launch that reaches the running Tarn before its first window opens is lost. Gap: NSH 0.5's `command-line` handler (nsh-platform-linux `app.rs`) forwards only URLs of the app's own `schemes` while no window is shown and emits no `SecondInstance` for it; Tarn diff --git a/docs/port-backlog.md b/docs/port-backlog.md index da4ef17e..756978b4 100644 --- a/docs/port-backlog.md +++ b/docs/port-backlog.md @@ -21,6 +21,20 @@ Reference: . ## Open +### Picture in Picture on tab switch (2026-11-24) + +What it does: a video playing with sound moves into Picture in Picture when its tab leaves the +screen, and back into the page when the tab returns; on by default, a switch in Settings › Tabs. +Shared API: `browser_core::prefs::AUTO_PICTURE_IN_PICTURE`, `browser_core::media::AutoPip`, +`engine::page_scripts::picture_in_picture_script(PipMode)`. +Reference: `crates/app/src/mini_player.rs` (`screen_tabs`, `screen_changed`), called where tabs +leave or reach the screen (`activate`, `switch_space`, `new_tab_page`, `leave_split`, `close_split`). Linux and Android are gaps (`docs/nsh-plan.md`, +`docs/mobile-plan.md`). + +- [ ] iOS — a `pictureInPicture` command on the `tarn.webview` component in `mobile/ios` running + the script for `Enter`/`Exit` (WKWebView with `allowsPictureInPictureMediaPlayback`), called by + `mobile/app` when a tab leaves or returns to the screen, and the Settings switch. + ### Insert an assistant answer into the page (2026-11-24) What it does: the chat's Insert into Page types the last answer into the page's focused field, as diff --git a/docs/shared-core.md b/docs/shared-core.md index 2e3f5374..6db70b45 100644 --- a/docs/shared-core.md +++ b/docs/shared-core.md @@ -38,7 +38,8 @@ Every shell's web view offers the same operations and reports the same events. T engine says (Chromium), the highlighted match (NSH components: the `clearFind` command, WebKitGTK `search_finish` on Linux, and `current` in `found` on Android); -- `find`, `print`, `snapshot_png`, `pdf`, `picture_in_picture`; Linux has `print` (the GTK print +- `find`, `print`, `snapshot_png`, `pdf`, `picture_in_picture` (`page_scripts::PipMode`: the user's + toggle, or enter and exit when a tab with playing video leaves and returns to the screen); Linux has `print` (the GTK print dialog) and `pdf` with the absolute `path` the user picked in the save dialog, printed there by WebKitGTK and reported on the download route as a finished download; iOS and Android have neither yet (`docs/port-backlog.md`); Linux's `snapshot` command answers with a `snapshot` event carrying a PNG diff --git a/docs/threat-model.md b/docs/threat-model.md index 9acb2186..f8a8452e 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -28,7 +28,7 @@ settings per client are in `cryptography.md`; the actors, components and externa | S21 | Medium | Memory-safety bugs in our FFI code | `unsafe` confined to two crates, each block documented with its invariant and enforced by lint. | `forbid(unsafe_code)` outside engine/platform, except `crates/app-dll`, whose only `unsafe` is its `RunWinMain` export for CEF's Windows launcher and the documented call inside it; `undocumented_unsafe_blocks` denied. | | S14 | Medium | Attacker-controlled titles and favicons parsed by the shell | Titles are bounded plain text. Favicons have byte and dimension caps and are decoded with limits. | Titles cut to 1024 characters in the engine, unchanged titles dropped, and bounded for display by `ui::text::bounded_title`. Find in Tabs snippets of page text (`WebView::find_text`), never from a Lockdown tab (found by title and address only): read in the same isolated world with the query as a JS string literal, at most 3 per tab of 320 characters each (cut again in Rust), shown as `bounded_title` plain text, never stored. Page text read for translation (feature `translation`) is capped at 2,000 nodes of 2,000 characters and 100,000 in all, handed only to Apple's on-device Translation framework and written back by the client world as text node data, never markup, only while the tab shows the offered page; never under Lockdown. The page can observe the rewrite and so learn the target language. Favicons (`engine::favicon`): links read and fetched in the engine's isolated world (WebKit's client content world, a DevTools isolated world in Chromium), hrefs over 2048 and `sizes` over 256 characters dropped there, so content rules, proxy and user agent apply; https URLs on the page's site, or on another site's host only when the page itself already loaded a resource from that exact host (default port; the isolated world reports at most 64 such hosts from Resource Timing, which lists only requests the page really made, so content rules have already applied to them), so a page cannot make the browser contact a server it has not used; cookies only for the page's own origin; another site's icon is fetched as a CORS request without credentials; no redirects are followed (`redirect: 'error'`), so no request goes past the checked URL; 10 s timeout, 256 KiB cap, and only while the tab still shows the requesting origin; SVG icons are rasterised to PNG by the engine (as an image, so no script runs); decoded with a 1024 px / 16 MiB limit and re-encoded as 64×64 PNG; stored per profile and wiped with history; a failed fetch is retried on the site's next page load, until three fetches have failed in a session; an icon stored over 30 days ago is fetched again the same way on the site's next load and replaced only on success; a subdomain without its own icon shows its registrable domain's, never across a public suffix; not fetched under Lockdown. Linux (`tarn.webview` `readIconLinks` and `fetchIcon`) runs the same scripts in its WebKitGTK script world `tarn` and iOS in its `WKContentWorld`, with the same Rust checks (`engine::favicon`); their components keep only https URLs, at most `favicon::MAX_CANDIDATES` (`favicon::fetch_urls`), and always fetch with the `favicon::MAX_BYTES` cap. Reader mode (`engine::reader`) reads the article in the same isolated world as plain strings, at most 200 KB and 10,000 characters a paragraph without control characters, re-checked by `Article::parse` (`serde_json`, input over 800 KB refused); the check for an article after each load runs only on http(s) pages and never under Lockdown, and GPUI draws them as text only; nothing of it is stored. Clean Up (`browser_core::cleanup`) reads only the http(s) host (at most 10 labels), the first 8 path segments and the first 1,024 characters of the title, never the query, fragment or user info, on the device; it keeps nothing but an in-memory undo record of tab and group ids and the names of the groups it made or opened, dropped with its toast. The link under the pointer (status bubble) is cut to 4,096 characters where the engine hands it over (`view_policy::MAX_HOVERED_LINK`; WebKit, CEF and the Linux web view component), parsed as a URL so its host shows as punycode and other characters percent-encoded, shown without user info (also inside `blob:`) with the host's end kept (`host_tail`) and the rest bounded by `bounded_url` (`browser_core::link_status`); the origin is drawn whole and only the rest is cut to fit, as plain text in a window the pointer passes through; never stored. The mini-player's title comes from the page's media session or document title through `page_ops::MediaState::parse` (cleaned and cut like a tab title); no artwork is fetched. | | S22 | Medium | Other local programs driving the browser | No listener by default, no remote-debugging port, no local HTTP API. Agent control is the sole exception: an opt-in OS-local endpoint restricted to the same OS user. The user must approve each agent connection and each site in Tarn before the agent can use it. By default Tarn isolates each session in a throwaway Strict profile. Two further modes, each off by default behind its own setting, let the agent open its own tabs in a profile the user picks (with its cookies and logins) or control tabs the user already has open; in them the approved site list starts empty for every session, the profile's Shield level is never lowered for the agent, private-space tabs are out of reach, every controlled tab shows an indicator with a one-click stop, form submissions, payments and filled secret fields need the user's confirmation, and the agent cannot read saved passwords, passkeys or autofill. Residual risk in these modes: page content the agent reads can steer it (prompt injection) while it acts with the user's logins on an approved site; per-site approval and the confirmations bound what it can do, not what it is told. Disabling closes the listener and ends the session: the throwaway profile is wiped, and in the other modes every tab is released with the user's data left as it was. | No listener exists in the current implementation, and the two modes on the user's profile or tabs are not built. The egress check continues to apply with agent control off. Chromium ignores Chromium and CEF switches on Tarn's argv (`command_line_args_disabled`), and the browser process also removes the switches that turn off a sandbox, site isolation or web security, run a program in front of a child (`renderer-cmd-prefix`, `gpu-launcher`, …) or open remote debugging, before its children start (`engine::chromium::runtime`, not yet run against a launch with those switches). `crates/app/tests/egress.rs` launches the shell with filter-list updates off, loads a page from a local server and fails if `lsof` (sampled every 500 ms) shows any socket of the shell process, listening or connected; it is ignored by default because it opens a window and runs by hand with `cargo test -p app --tests -- --ignored`; no workflow runs it. The filter-list download itself is not covered. | -| S23 | Low | Page floods the user with dialogs, popups or tabs | Rate limits and a "stop this page" option. Pop-ups only after a user gesture. | 5 prompts and 3 popups per tab per 10 s, shared with the popups that tab opens, at most 8 queued; pages cannot open windows without a user gesture (`javaScriptCanOpenWindowsAutomatically` false; WebKit's default is true); "Block requests from this page" declines the queue and further requests until the next navigation; sign-in requests only from the page's own origin (scheme, host and port), at most 3 attempts. A site's "Block" pop-up rule and the pop-up, malware and adult sets refuse the rest, with a notice that offers to open it once (`app/tests/blocking.rs`). The mini-player's Play runs as the user's gesture, which the page's own scripts share for that moment as after a click; Pause and Seek do not on Chromium. Residual: WebKit treats every script of the shell's isolated world as a gesture, so on macOS with WebKit, Linux and iOS a Pause or Seek also lends the page one gesture. | +| S23 | Low | Page floods the user with dialogs, popups or tabs | Rate limits and a "stop this page" option. Pop-ups only after a user gesture. | 5 prompts and 3 popups per tab per 10 s, shared with the popups that tab opens, at most 8 queued; pages cannot open windows without a user gesture (`javaScriptCanOpenWindowsAutomatically` false; WebKit's default is true); "Block requests from this page" declines the queue and further requests until the next navigation; sign-in requests only from the page's own origin (scheme, host and port), at most 3 attempts. A site's "Block" pop-up rule and the pop-up, malware and adult sets refuse the rest, with a notice that offers to open it once (`app/tests/blocking.rs`). The mini-player's Play runs as the user's gesture, which the page's own scripts share for that moment as after a click; Pause and Seek do not on Chromium. Automatic Picture in Picture (Settings › Tabs, on by default, macOS WebKit tabs and Windows) runs nothing under Lockdown and runs its script on a tab that leaves the screen only once the engine says the tab plays media or uses the camera or microphone (WebKit: its own playback and capture state, which is not limited to an unmuted video); on Chromium it then lends one gesture only after a check in Tarn's isolated world, run without one, found a playing, unmuted video with non-zero volume of at least 200 by 200 CSS pixels and none already in Picture in Picture, and taking the video back out on return lends none. Residual: WebKit treats every script of the shell's isolated world as a gesture, so on macOS with WebKit, Linux and iOS a Pause or Seek also lends the page one gesture, and on macOS with WebKit so do automatic Picture in Picture's scripts on such a tab when it leaves the screen, for the whole script even when it enters nothing, and on its return. On Chromium the page can pause after the check and keep the gesture, and on both engines a navigation committing between the check and the entry would receive it. | | S24 | High | A page abuses or subverts Tarn's YouTube script in the page world | The script is compiled into the app, runs only on YouTube's hosts (exact match or dot-suffix, never `accounts.youtube.com`), captures the built-ins it uses before any page script runs, removes only allowlisted keys, never touches the DOM, storage, cookies or the network, defines no global and has no bridge to the shell. The signed bundle may change only which keys it removes. | `shield::youtube` and `youtube.js`; `youtube::parse` accepts at most 32 ASCII-letter keys and refuses keys playback needs; `data_store::install_scripts` rebuilds a controller's scripts in one place, so the referrer script, the Bitwarden passkey script (S15, S18) and the Netflix visibility script survive every change. Node sandbox test (`shield/tests/youtube.rs`) covers host gating, poisoned built-ins and every hook. The page can detect and undo the YouTube script on its own pages; that only brings its ads back. The Netflix script runs only on `netflix.com` hosts, makes the page see itself visible and focused, defines no global and has no bridge to the shell. Undoing it only lets Netflix stop playback again. On Windows both scripts reach Chromium's main world through `Page.addScriptToEvaluateOnNewDocument`, registered before a view's first load: the Netflix script in every view but Lockdown's, the YouTube script only in views made for a site where blocking is not paused; a new or switched-off YouTube script replaces the registered one for each view's next document. On Linux both are WebKitGTK page-world user scripts at document start in every frame (`linux/src/webview/scripts.rs` `apply_page_scripts`), installed in no Lockdown view and wrapped by `page_scripts::outside_lockdown` so they skip hosts set to Lockdown; the YouTube one only while Block YouTube ads is on (`youtube` prop), built by `youtube::script` from the bundle's `youtube::config`. Linux has no per-site pause, so blocking is never paused there. Display test `youtube_and_netflix_scripts_run_only_on_their_hosts_and_never_under_lockdown`. | | S25 | Medium | User opens a malware, phishing or scam site | Domain sets from curated lists checked on every navigation in every frame, including redirects and downloads, before the request is made; WebKit's fraudulent-website check stays on with the malware switch. | `nav_policy::gate` runs in `decide_policy` before the sub-frame and download branches; main frames get a native warning page (`app::blocking`) with "Go Back" as the default button, and "Visit Anyway" only for malware, ignoring clicks for 700 ms from when its tab becomes visible, and remembered per host and profile in memory until quit. Subresources from the two most curated malware lists are blocked by a content rule list that pausing a site does not lift. Sets of categories switched off are not loaded. New domains are missed until the next daily bundle. | | S26 | High | The cookie bridge moves credentials between WebKit and Chromium: wrong profile, weakened attributes, values on disk or in logs, cookies coming back after logout or a clear | Bridge only for the profile that owns Chromium, per site, only after a shell load or a user-gesture navigation; three-way merge where only a cookie confirmed on both sides can be deleted; no write that removes `HttpOnly` or `Secure` from an overlapping cookie of the same name; prefix and public-suffix checks before writing; cookies that cannot be written faithfully are skipped; script-readable cookies from Chromium capped at seven days; per-site caps; the bridge keeps values in memory only; bridge stopped before clears of its own store. | `engine::cookies` (rules, unit-tested), `cookies_webkit.rs`, `chromium::cookies`. WebKit reports a cookie without `SameSite` as `none`, the same as an explicit `SameSite=None`; the bridge reads both as `Lax` (`cookies_webkit::same_site`, tested), so no cookie reaches Chromium with fewer restrictions than Chromium's default. Chromium's jar is emptied when CEF's context starts and on quit, so a killed run's cookies never come back; until then persistent ones sit in Chromium's cookie file, encrypted with its Keychain key. A site's first merge deletes what Chromium collected for it before it was bridged. A cut-short Chromium read is discarded; a single empty read, or a read while Chromium's jar is at its eviction level or was at the previous read, deletes nothing in WebKit and copies nothing back; a page that keeps the jar there holds back Chromium logouts for that long, and a page that pushes it past the level and back below between two reads can make Chromium evict a bridged session, which then reads as a logout and signs the site out in WebKit too (no value leaks). A site's first Chromium request is held on CEF's IO thread until WebKit's cookies are written, at most two seconds. `remove_all_data` and `wipe_persistent` stop the bridge for the session, `clear_site_data` that site; Chromium-side clears suspend the bridge before they run. Partitioned cookies are not recognised in Chromium's jar (CEF does not mark them) and would be copied as first-party ones. No WebKit-side wait yet: a WebKit load of a bridged site can be up to two seconds behind Chromium. Checked by hand in a development bundle. | From 77eb4cdd9207958c99c089c142cbb6c89cbec16c Mon Sep 17 00:00:00 2001 From: rgxdev Date: Wed, 25 Nov 2026 00:18:27 +0100 Subject: [PATCH 2/3] fix: detect tabs leaving the screen in one place for automatic Picture in Picture The tabs on screen are compared on every render (AutoPip::screen), which also covers tearing off a split pane and every other path that hides a tab; a tab still fading out counts as on screen. The size gate is 200 by 200 CSS pixels as documented, a late answer for a view that moved windows takes its video back out, and Chromium lends no gesture to a view that is visible again. Signed-off-by: rgxdev --- crates/app/src/browser/views.rs | 4 ---- crates/app/src/content.rs | 1 + crates/app/src/mini_player.rs | 34 ++++++++++++++++++------------ crates/app/src/prefs.rs | 2 -- crates/app/src/split.rs | 6 ------ crates/browser-core/src/media.rs | 22 +++++++++++++++++++ crates/engine/src/chromium/view.rs | 2 ++ crates/engine/src/page_scripts.rs | 3 +-- docs/port-backlog.md | 4 ++-- 9 files changed, 48 insertions(+), 30 deletions(-) diff --git a/crates/app/src/browser/views.rs b/crates/app/src/browser/views.rs index 0ff3bacc..2011c4af 100644 --- a/crates/app/src/browser/views.rs +++ b/crates/app/src/browser/views.rs @@ -286,7 +286,6 @@ impl Browser { return; } let switched = self.model.active != Some(key); - let before = self.screen_tabs(); let _span = switched.then(|| engine::startup::span(engine::startup::TAB_SWITCH)).flatten(); if switched { self.leave_page_fullscreen(window); @@ -348,7 +347,6 @@ impl Browser { } } } - self.screen_changed(before, cx); self.model.touch(&self.core, key, now()); if !self.overlay_open() { window.focus(&self.focus); @@ -596,7 +594,6 @@ impl Browser { if self.command_mode.is_some() { self.close_command(window, cx); } - let before = self.screen_tabs(); if let Some(view) = self.active_view() { view.set_visible(false); } @@ -615,7 +612,6 @@ impl Browser { self.space_shown(&[]); self.slide_from(from, old); self.pick_active(window, cx); - self.screen_changed(before, cx); if burning && !self.model.burner_shown() { self.burn(cx); } diff --git a/crates/app/src/content.rs b/crates/app/src/content.rs index 91b4af99..988d62b7 100644 --- a/crates/app/src/content.rs +++ b/crates/app/src/content.rs @@ -137,6 +137,7 @@ fn banner(text: impl Into) -> gpui::Div { pub fn render(b: &mut Browser, window: &mut Window, cx: &mut Context) -> AnyElement { b.settle_motion(window, cx); b.settle_split(); + b.settle_screen(cx); if b.capture_overlay.as_ref().is_some_and(|o| b.model.active != Some(o.key)) { b.capture_overlay = None; } diff --git a/crates/app/src/mini_player.rs b/crates/app/src/mini_player.rs index f1a19ee4..7b3ba89f 100644 --- a/crates/app/src/mini_player.rs +++ b/crates/app/src/mini_player.rs @@ -70,23 +70,24 @@ impl Browser { } } - /// The tabs on screen: the active tab, or every pane of its split. - pub(crate) fn screen_tabs(&self) -> Vec { + /// The tabs on screen: the active tab, or every pane of its split, and a tab still fading out. + fn screen_tabs(&self) -> Vec { let active = self.model.active; - active.and_then(|k| self.splits.of(k)).map_or_else(|| active.into_iter().collect(), |s| s.panes().to_vec()) + let mut tabs = active.and_then(|k| self.splits.of(k)).map_or_else(|| active.into_iter().collect(), |s| s.panes().to_vec()); + let fading = self.page_fade.as_ref().and_then(|(view, _)| self.views.iter().find(|(_, v)| Rc::ptr_eq(v, view))); + tabs.extend(fading.map(|(k, _)| *k).filter(|k| !tabs.contains(k))); + tabs } - /// After the tabs on screen changed from `before`: a playing video of a tab that left moves - /// into Picture in Picture, and one Tarn moved there comes back once its tab returns. - pub(crate) fn screen_changed(&mut self, before: Vec, cx: &mut Context) { - let now = self.screen_tabs(); - for gone in before.into_iter().filter(|k| !now.contains(k)) { - self.leave_for_pip(gone, cx); + /// Called on every render, after whatever changed the tabs on screen: a playing video of a tab + /// that left moves into Picture in Picture, and one Tarn moved there comes back with its tab. + pub(crate) fn settle_screen(&mut self, cx: &mut Context) { + let (left, back) = self.mini_player.auto_pip.screen(self.screen_tabs()); + for key in left { + self.leave_for_pip(key, cx); } - for back in now { - if self.mini_player.auto_pip.take(back) { - self.exit_pip(back); - } + for key in back { + self.exit_pip(key); } } @@ -110,7 +111,12 @@ impl Browser { cx.spawn(async move |this, cx| { let Some(result) = rx.next().await else { return }; this.update(cx, |b, _| { - if b.same_view(key, &weak) && b.mini_player.auto_pip.answered(key, &result, b.screen_tabs().contains(&key)) { + if !b.same_view(key, &weak) { + // The view moved to another window or was replaced meanwhile. + if let Some(view) = weak.upgrade().filter(|_| result == "pip") { + view.picture_in_picture(PipMode::Exit, |_| {}); + } + } else if b.mini_player.auto_pip.answered(key, &result, b.screen_tabs().contains(&key)) { b.exit_pip(key); } }) diff --git a/crates/app/src/prefs.rs b/crates/app/src/prefs.rs index 805b1a95..9fb815f0 100644 --- a/crates/app/src/prefs.rs +++ b/crates/app/src/prefs.rs @@ -357,12 +357,10 @@ impl Browser { pub fn new_tab_page(&mut self, window: &mut Window, cx: &mut Context) { let replaced = self.model.active.filter(|_| self.pref(Pref::NewTabStartPage) && !self.overlay_open() && !self.inline_editing()); if replaced.is_some() { - let before = self.screen_tabs(); if let Some(view) = self.active_view() { view.set_visible(false); } self.model.active = None; - self.screen_changed(before, cx); } // Before the sidebar closes, so a click in it still hands the field to the main window. self.open_command(CommandMode::NewTab, window, cx); diff --git a/crates/app/src/split.rs b/crates/app/src/split.rs index d7135f0c..0d527eb1 100644 --- a/crates/app/src/split.rs +++ b/crates/app/src/split.rs @@ -156,22 +156,16 @@ impl Browser { /// Takes `key` out of its split; the tab stays open and a split left with one pane ends. pub fn leave_split(&mut self, key: TabKey, window: &mut Window, cx: &mut Context) { - let before = self.screen_tabs(); let heir = self.splits.leave(key).filter(|_| self.model.active == Some(key)); if let Some(heir) = heir { self.activate(heir, window, cx); } self.split_moved(cx); - if heir.is_none() { - self.screen_changed(before, cx); - } } pub fn close_split(&mut self, key: TabKey, cx: &mut Context) { - let before = self.screen_tabs(); if self.splits.close(key) { self.split_moved(cx); - self.screen_changed(before, cx); } } diff --git a/crates/browser-core/src/media.rs b/crates/browser-core/src/media.rs index 44ee1adf..9916ce82 100644 --- a/crates/browser-core/src/media.rs +++ b/crates/browser-core/src/media.rs @@ -117,9 +117,20 @@ impl Player { #[derive(Clone, Debug, Default)] pub struct AutoPip { entered: HashSet, + screen: Vec, } impl AutoPip { + /// The tabs on screen are now `now`: answers those that left it, whose playing video should + /// move into Picture in Picture, and those Tarn moved there that are back, whose video + /// should come out. + pub fn screen(&mut self, now: Vec) -> (Vec, Vec) { + let left = self.screen.iter().copied().filter(|k| !now.contains(k)).collect(); + let back = now.iter().copied().filter(|k| self.entered.remove(k)).collect(); + self.screen = now; + (left, back) + } + /// `key`'s page answered `result` to `PipMode::Enter`; true when its video should come back out /// at once, because the tab is `visible` again before the answer arrived. pub fn answered(&mut self, key: TabKey, result: &str, visible: bool) -> bool { @@ -175,6 +186,17 @@ mod tests { assert!(player.forget(key(2)) && player.tab().is_none()); } + #[test] + fn tabs_leave_and_return_once_each() { + let mut pip = AutoPip::default(); + assert_eq!(pip.screen(vec![key(1), key(2)]), (vec![], vec![])); + assert_eq!(pip.screen(vec![key(1), key(2)]), (vec![], vec![]), "nothing changed"); + assert_eq!(pip.screen(vec![key(3)]), (vec![key(1), key(2)], vec![]), "a whole split leaves"); + pip.answered(key(1), "pip", false); + assert_eq!(pip.screen(vec![key(1)]), (vec![key(3)], vec![key(1)])); + assert_eq!(pip.screen(vec![key(1), key(2)]), (vec![], vec![]), "back out only once"); + } + #[test] fn only_video_tarn_moved_comes_back_out() { let mut pip = AutoPip::default(); diff --git a/crates/engine/src/chromium/view.rs b/crates/engine/src/chromium/view.rs index a1ba6fc4..996cc6d5 100644 --- a/crates/engine/src/chromium/view.rs +++ b/crates/engine/src/chromium/view.rs @@ -2293,6 +2293,8 @@ impl WebView { } let (inner, done) = (Rc::downgrade(&self.0), Rc::new(done)); self.run_isolated(&picture_in_picture_ready_script(), move |answer| match (answer.as_str(), inner.upgrade()) { + // Back on screen before the check answered: no gesture for a video that stays inline. + ("ready", Some(inner)) if inner.visible.get() => done("none".into()), ("ready", Some(inner)) => { let done = done.clone(); WebView(inner).run_isolated_as_gesture(&picture_in_picture_script(PipMode::Enter), true, move |a| done(a)); diff --git a/crates/engine/src/page_scripts.rs b/crates/engine/src/page_scripts.rs index d878709f..d32cdaaf 100644 --- a/crates/engine/src/page_scripts.rs +++ b/crates/engine/src/page_scripts.rs @@ -431,8 +431,7 @@ pub enum PipMode { Exit, } -const PIP_ENTER_PICK: &str = - "videos.some(shown) ? 'open' : videos.find(v => !v.paused && !v.ended && !v.muted && v.volume > 0 && v.videoWidth > 0 && area(v) >= 40000)"; +const PIP_ENTER_PICK: &str = "videos.some(shown) ? 'open' : videos.find(v => !v.paused && !v.ended && !v.muted && v.volume > 0 && v.videoWidth > 0 && v.clientWidth >= 200 && v.clientHeight >= 200)"; const PIP_ENTER: &str = r"try { await video.requestPictureInPicture(); return 'pip'; } catch (e) {} if (!video.disablePictureInPicture && video.webkitSupportsPresentationMode && video.webkitSupportsPresentationMode('picture-in-picture')) { video.webkitSetPresentationMode('picture-in-picture'); diff --git a/docs/port-backlog.md b/docs/port-backlog.md index 756978b4..49c2b31b 100644 --- a/docs/port-backlog.md +++ b/docs/port-backlog.md @@ -27,8 +27,8 @@ What it does: a video playing with sound moves into Picture in Picture when its screen, and back into the page when the tab returns; on by default, a switch in Settings › Tabs. Shared API: `browser_core::prefs::AUTO_PICTURE_IN_PICTURE`, `browser_core::media::AutoPip`, `engine::page_scripts::picture_in_picture_script(PipMode)`. -Reference: `crates/app/src/mini_player.rs` (`screen_tabs`, `screen_changed`), called where tabs -leave or reach the screen (`activate`, `switch_space`, `new_tab_page`, `leave_split`, `close_split`). Linux and Android are gaps (`docs/nsh-plan.md`, +Reference: `crates/app/src/mini_player.rs` (`settle_screen`, called on every render from +`crates/app/src/content.rs`), which hands the tabs on screen to `AutoPip::screen`. Linux and Android are gaps (`docs/nsh-plan.md`, `docs/mobile-plan.md`). - [ ] iOS — a `pictureInPicture` command on the `tarn.webview` component in `mobile/ios` running From 71304432385fb8673665f14b509673bac5490cf0 Mon Sep 17 00:00:00 2001 From: rgxdev Date: Wed, 25 Nov 2026 00:41:31 +0100 Subject: [PATCH 3/3] fix: skip automatic Picture in Picture for muted, Lockdown and already-floating tabs The setting, the tab's mute in Tarn and its Shield level are checked before the playback probe and again before entering, and a page whose document already has a Picture in Picture element is left as it is. Signed-off-by: rgxdev --- crates/app/src/mini_player.rs | 13 ++++++++----- crates/engine/src/page_scripts.rs | 4 ++-- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/crates/app/src/mini_player.rs b/crates/app/src/mini_player.rs index 7b3ba89f..4dc7ef76 100644 --- a/crates/app/src/mini_player.rs +++ b/crates/app/src/mini_player.rs @@ -94,10 +94,7 @@ impl Browser { /// Asks the engine first whether the page plays (on WebKit its own playback state), so a page /// that plays nothing gets no script, and with it no gesture, when its tab leaves the screen. fn leave_for_pip(&mut self, key: TabKey, cx: &mut Context) { - if !self.pref(crate::prefs::Pref::AutoPictureInPicture) { - return; - } - let Some(view) = self.views.get(&key) else { return }; + let Some(view) = self.views.get(&key).filter(|v| self.may_pip(key, v)) else { return }; let (weak, (tx, mut rx)) = (Rc::downgrade(view), mpsc::unbounded()); view.media_playing(move |playing| drop(tx.unbounded_send(playing))); cx.spawn(async move |this, cx| { @@ -105,7 +102,7 @@ impl Browser { return; } this.update(cx, |b, cx| { - let Some(view) = weak.upgrade().filter(|_| b.same_view(key, &weak) && !b.screen_tabs().contains(&key)) else { return }; + let Some(view) = weak.upgrade().filter(|v| b.same_view(key, &weak) && !b.screen_tabs().contains(&key) && b.may_pip(key, v)) else { return }; let (tx, mut rx) = mpsc::unbounded(); view.picture_in_picture(PipMode::Enter, move |result| drop(tx.unbounded_send(result))); cx.spawn(async move |this, cx| { @@ -129,6 +126,12 @@ impl Browser { .detach(); } + /// The switch is on, the tab is not muted in Tarn, and no script of Tarn's may run under Lockdown. + fn may_pip(&self, key: TabKey, view: &engine::WebView) -> bool { + let url = view.url().map(|u| u.to_string()).unwrap_or_default(); + self.pref(crate::prefs::Pref::AutoPictureInPicture) && !view.is_muted() && self.level_for_tab(key, &url) != shield::ShieldLevel::Lockdown + } + fn exit_pip(&self, key: TabKey) { if let Some(view) = self.views.get(&key) { view.picture_in_picture(PipMode::Exit, |_| {}); diff --git a/crates/engine/src/page_scripts.rs b/crates/engine/src/page_scripts.rs index d32cdaaf..795de506 100644 --- a/crates/engine/src/page_scripts.rs +++ b/crates/engine/src/page_scripts.rs @@ -431,7 +431,7 @@ pub enum PipMode { Exit, } -const PIP_ENTER_PICK: &str = "videos.some(shown) ? 'open' : videos.find(v => !v.paused && !v.ended && !v.muted && v.volume > 0 && v.videoWidth > 0 && v.clientWidth >= 200 && v.clientHeight >= 200)"; +const PIP_ENTER_PICK: &str = "document.pictureInPictureElement || videos.some(shown) ? 'open' : videos.find(v => !v.paused && !v.ended && !v.muted && v.volume > 0 && v.videoWidth > 0 && v.clientWidth >= 200 && v.clientHeight >= 200)"; const PIP_ENTER: &str = r"try { await video.requestPictureInPicture(); return 'pip'; } catch (e) {} if (!video.disablePictureInPicture && video.webkitSupportsPresentationMode && video.webkitSupportsPresentationMode('picture-in-picture')) { video.webkitSetPresentationMode('picture-in-picture'); @@ -675,7 +675,7 @@ mod tests { assert!(!enter.contains("return await leave(video)"), "entering never takes a video out"); assert!(!exit.contains("requestPictureInPicture") && !exit.contains("webkitSetPresentationMode('picture-in-picture')")); let ready = picture_in_picture_ready_script(); - assert!(ready.contains("videos.some(shown) ? 'open'") && ready.contains("return 'ready'")); + assert!(ready.contains("document.pictureInPictureElement || videos.some(shown) ? 'open'") && ready.contains("return 'ready'")); assert!(!ready.contains("requestPictureInPicture") && !ready.contains("webkitSetPresentationMode('picture-in-picture')")); }