diff --git a/CHANGELOG.md b/CHANGELOG.md index c49b455c..5360bc33 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. - Agent control: turn on Settings › AI › Let AI agents control Tarn and add Tarn to Claude Code or Codex (`tarn --mcp`), and the agent can browse for you in a window of its own that keeps nothing. You allow the agent (look only, or act), each site it uses and each click on a page holding a diff --git a/README.md b/README.md index b1883919..ed0ff25a 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 37191ff7..d13f0c5b 100644 --- a/crates/app/src/browser/events.rs +++ b/crates/app/src/browser/events.rs @@ -404,8 +404,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/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/content.rs b/crates/app/src/content.rs index be022ca8..5e60c775 100644 --- a/crates/app/src/content.rs +++ b/crates/app/src/content.rs @@ -137,6 +137,7 @@ pub(crate) 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 2446f80b..4dc7ef76 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,81 @@ 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, and a tab still fading out. + fn screen_tabs(&self) -> Vec { + let active = self.model.active; + 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 + } + + /// 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 key in back { + self.exit_pip(key); + } + } + + /// 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) { + 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| { + if rx.next().await != Some(true) { + return; + } + this.update(cx, |b, cx| { + 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| { + let Some(result) = rx.next().await else { return }; + this.update(cx, |b, _| { + 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); + } + }) + .ok(); + }) + .detach(); + }) + .ok(); + }) + .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, |_| {}); + } } 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 00e43617..0c00a92e 100644 --- a/crates/app/src/prefs.rs +++ b/crates/app/src/prefs.rs @@ -37,10 +37,11 @@ pub enum Pref { AgentControl, AgentProfile, AgentTabs, + AutoPictureInPicture, } impl Pref { - pub const ALL: [Pref; 29] = [ + pub const ALL: [Pref; 30] = [ Pref::CompactToolbar, Pref::AutoHideSidebar, Pref::Gestures, @@ -70,6 +71,7 @@ impl Pref { Pref::AgentControl, Pref::AgentProfile, Pref::AgentTabs, + Pref::AutoPictureInPicture, ]; pub(crate) fn key(self) -> &'static str { @@ -103,6 +105,7 @@ impl Pref { Pref::AgentControl => browser_core::agent::SETTING, Pref::AgentProfile => browser_core::agent::SETTING_PROFILE, Pref::AgentTabs => browser_core::agent::SETTING_TABS, + Pref::AutoPictureInPicture => browser_core::prefs::AUTO_PICTURE_IN_PICTURE.key, } } @@ -124,6 +127,7 @@ impl Pref { | Pref::LocalhostFromApps | Pref::Passkeys | Pref::FeatureHints + | Pref::AutoPictureInPicture ) } @@ -513,6 +517,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/browser-core/src/media.rs b/crates/browser-core/src/media.rs index 099bffad..9916ce82 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,41 @@ 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, + 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 { + 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 +186,29 @@ 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(); + 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 569a7e13..b5f553e0 100644 --- a/crates/engine/src/chromium/view.rs +++ b/crates/engine/src/chromium/view.rs @@ -2295,8 +2295,27 @@ 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()) { + // 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)); + } + _ => 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..795de506 100644 --- a/crates/engine/src/page_scripts.rs +++ b/crates/engine/src/page_scripts.rs @@ -419,21 +419,60 @@ 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 = "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'); 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 +667,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("document.pictureInPictureElement || 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 18ea25af..8db63a3b 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -284,8 +284,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 4b51338c..ac784e65 100644 --- a/crates/engine/src/view_windows.rs +++ b/crates/engine/src/view_windows.rs @@ -232,8 +232,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 fe2dd455..657db28c 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}; @@ -758,11 +758,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 9d304605..8f79e110 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 a40a3a96..178aabb4 100644 --- a/docs/nsh-plan.md +++ b/docs/nsh-plan.md @@ -323,9 +323,10 @@ icons and brand mark are `crates/ui`'s own files. Deviations: - A background tab off screen for a minute or two drops the processes WebKit keeps for its earlier pages on macOS and iOS (`engine::lifecycle::BackForwardTrim`). Gap: WebKitGTK has no call to drop one view's back/forward cache, so a Linux tab keeps them until it sleeps. -- 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 130de219..49c226eb 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` (`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 + 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. + ### Ask before sending a form again (2026-11-24) What it does: the user's own Back, Forward or Reload to a page a form was sent for, no longer kept, asks diff --git a/docs/shared-core.md b/docs/shared-core.md index cfc36534..da5c70f8 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 a36a8fe9..18e72696 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 within the limits S31 states (a page that sends by `form.submit()`, a script request or a delayed submit is asked only while a password, payment or one-time-code field holds a value), 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 while agent control is off, the default, and the egress check continues to apply then; with it on, only the agent socket or pipe of S31 (`engine::agent_socket`), closed when the switch goes 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. |