From 21aef028c06f96ef981ba3cc583a99c2b0864124 Mon Sep 17 00:00:00 2001 From: rgxdev Date: Tue, 24 Nov 2026 06:35:07 +0100 Subject: [PATCH 1/2] perf: cut idle wakeups, redraws and database work on every client The start page's fog and search bar effect hold their frame after a minute without input in the window, stop their timers and continue from the held frame at the next input (browser_core::effects::{IDLE, awake, moved, Clock}). AppKit repeats mouse moves of a resting pointer a point apart, so a move counts only once the pointer travelled a few points. The hang ping is skipped, and a pending hang forgotten, while Tarn is not the active app (macOS, Windows, Linux, iOS, Android). Extension messages, unchanged titles and memory samples no longer redraw the window; it redraws when the heavy tabs change or the Memory page shows the costs. Linux rebuilds its snapshot for pings, pongs and samples only when the hung card or heavy tabs change. Extension ticks do nothing without an installed extension on Linux and mobile (Runtime::has_installs). Chromium's Shield counts are written in one transaction a minute with Store::count_many, and only when something was blocked. Measured on macOS (release build, warm profile, start page untouched for 75 s): shell CPU 7.8% -> 0.6%, context switches 325/s -> 141/s. Signed-off-by: rgxdev --- CHANGELOG.md | 8 + crates/app/src/browser.rs | 7 +- crates/app/src/browser/events.rs | 9 +- crates/app/src/content.rs | 159 ++++++++++++++------ crates/app/src/lib.rs | 3 + crates/app/src/library.rs | 7 +- crates/app/src/memory.rs | 4 +- crates/app/src/shared.rs | 19 ++- crates/app/src/tabs.rs | 15 +- crates/browser-core/src/effects.rs | 60 ++++++++ crates/browser-core/src/tarn_ext/runtime.rs | 6 + crates/engine/src/lifecycle.rs | 6 + crates/store/src/db.rs | 48 +++++- docs/nsh-plan.md | 4 +- docs/shared-core.md | 7 +- linux/src/browser.rs | 3 + linux/src/browser/feature_tests.rs | 11 +- linux/src/browser/tab_actions.rs | 11 +- linux/src/extensions/mod.rs | 3 + linux/src/snapshot.rs | 2 +- linux/src/ui.rs | 68 ++++++++- mobile/app/src/extensions.rs | 4 + mobile/app/src/shell.rs | 9 +- mobile/app/src/ui/extensions.rs | 6 +- mobile/app/src/ui/mod.rs | 7 +- mobile/app/tests/shell.rs | 10 +- nsh-shared/src/fog.rs | 5 +- nsh-shared/src/motion.rs | 78 +++++++++- nsh-shared/src/search_fx.rs | 28 +--- 29 files changed, 482 insertions(+), 125 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b369be63..bc0523e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -85,6 +85,14 @@ All notable changes to Tarn are documented in this file. The format is based on ### Changed +- Less work while idle, for battery, on every client: the start page's fog and search bar effect + hold their frame after a minute without input in the window, stop their timers, and move on from + that frame at the next input; while Tarn is not the active app it no longer checks every two + seconds whether the shown page still answers; extension messages, a title that did not change + and memory samples no longer redraw the window unless the heavy tabs or the Memory page change; + the extension timer on Linux, iOS and Android does nothing without an installed extension; + Chromium's Shield counts are written once a minute in one transaction, and only when something + was blocked. - The sidebar's New Tab row has one Organize Tabs button (…) in place of four: New Tab Group, New Folder, Clean Up and Group with Assistant are in its menu, on every client. - Enter on an address Tarn cannot open shakes the field instead of going anywhere, on every diff --git a/crates/app/src/browser.rs b/crates/app/src/browser.rs index 83e3e8e5..519d37b4 100644 --- a/crates/app/src/browser.rs +++ b/crates/app/src/browser.rs @@ -391,6 +391,7 @@ pub struct Browser { pub(crate) drawn_at: Option, pub(crate) page_fade: Option<(Rc, Instant)>, pub(crate) overlay_exit: Option, + pub(crate) watch: crate::content::Watch, pub(crate) fog: gpui::Entity, pub(crate) search_fx: gpui::Entity, pub(crate) floating: crate::content::Floating, @@ -509,6 +510,7 @@ impl Browser { let tab_placement = browser_core::layout::TabPlacement::load(disk); let sidebar_open = crate::prefs::sidebar_open(disk) && tab_placement == browser_core::layout::TabPlacement::Side; let sidebar_width = crate::prefs::sidebar_width(disk); + let watch = crate::content::Watch::default(); let mut browser = Browser { core, warning: None, @@ -607,8 +609,9 @@ impl Browser { drawn_at: None, page_fade: None, overlay_exit: None, - fog: cx.new(|_| Default::default()), - search_fx: cx.new(|_| Default::default()), + fog: cx.new(|_| watch.fog()), + search_fx: cx.new(|_| watch.search_fx()), + watch, floating: Default::default(), bookmarks: Vec::new(), motion: Default::default(), diff --git a/crates/app/src/browser/events.rs b/crates/app/src/browser/events.rs index 161cdb07..3b410940 100644 --- a/crates/app/src/browser/events.rs +++ b/crates/app/src/browser/events.rs @@ -122,13 +122,19 @@ impl Browser { } } Event::TitleChanged(title) => { - self.store(key.private).set_tab_title(key.id, &title).ok(); + let unchanged = self.model.tab(key).is_some_and(|t| t.title == title); + if !unchanged { + self.store(key.private).set_tab_title(key.id, &title).ok(); + } // WebKit can report an empty title for the outgoing page just before the next one commits. if let (false, Some(profile_id), Some((visit, url))) = (title.is_empty(), self.profile_of(key), self.pages.get(&key).and_then(|p| p.visit.clone())) { self.store(key.private).retitle_visit(profile_id, visit, &url, &title).ok(); } + if unchanged { + return; + } if self.private_matches(key) && let Some(t) = self.model.tabs.iter_mut().find(|t| t.id == key.id) { @@ -259,6 +265,7 @@ impl Browser { if let Some(profile) = self.profile_of(key).filter(|_| !key.private) { self.core.tarn.borrow().send(crate::tarn_ext::Msg::Tab { profile, tab: key.id as u64, world, frame, origin, json }); } + return; } Event::ContentProcessTerminated => { self.link_hovered(key, None, cx); diff --git a/crates/app/src/content.rs b/crates/app/src/content.rs index b996ece0..1cb8cd3e 100644 --- a/crates/app/src/content.rs +++ b/crates/app/src/content.rs @@ -796,17 +796,118 @@ type FogLine = (SharedString, Vec<(std::ops::Range, HighlightStyle)>); /// Columns, rows, animation step and theme generation of a cached frame. type FogKey = (usize, usize, u32, u32); -/// The ASCII cloud bank behind the start card, redrawn every `fog::FRAME`; its own view, so -/// windows that observe the `Browser` are not notified. One still frame while motion is reduced -/// or the theme asks for it; none when the theme turns it off. Paused unless its window is the -/// active one of the active app, so a frame redraws one window only. +type Input = Rc>>; + +/// The window's last input, recorded by listeners the `Browser` always paints, so the start page +/// counts input from before it appeared. `None` once the animations went idle. #[derive(Default)] +pub(crate) struct Watch { + input: Input, + pointer: Rc>>>, + keys: Option, + start: bool, +} + +impl Watch { + pub(crate) fn fog(&self) -> Fog { + Fog { reduce: false, left: 0., motion: Motion::new(self.input.clone()), frame: None } + } + + pub(crate) fn search_fx(&self) -> SearchFx { + SearchFx { reduce: false, motion: Motion::new(self.input.clone()) } + } + + /// Counts the start page appearing as input and returns the element that records the rest and + /// wakes `views` on the first input after idle; a pointer move counts once `effects::moved` says it travelled. + pub(crate) fn element(&mut self, start: bool, views: [gpui::EntityId; 2], window: &Window, cx: &mut Context) -> impl IntoElement + use<> { + fn on(window: &mut Window, input: &Input, views: [gpui::EntityId; 2], counts: impl Fn(&E) -> bool + 'static) { + let input = input.clone(); + window.on_mouse_event(move |event: &E, phase, _, cx| { + if phase == gpui::DispatchPhase::Capture && counts(event) && input.replace(Some(Instant::now())).is_none() { + views.into_iter().for_each(|id| cx.notify(id)); + } + }); + } + if std::mem::replace(&mut self.start, start) != start && start { + self.input.set(Some(Instant::now())); + } + if self.keys.is_none() { + let (input, handle) = (self.input.clone(), window.window_handle()); + self.keys = Some(cx.observe_keystrokes(move |_, _, window, cx| { + if window.window_handle() == handle && input.replace(Some(Instant::now())).is_none() { + views.into_iter().for_each(|id| gpui::App::notify(cx, id)); + } + })); + } + let (input, pointer) = (self.input.clone(), self.pointer.clone()); + canvas( + |_, _, _| {}, + move |_, (), window, _| { + let pointer = pointer.clone(); + on(window, &input, views, move |e: &gpui::MouseMoveEvent| { + let moved = + pointer.get().is_some_and(|p| browser_core::effects::moved((p.x.into(), p.y.into()), (e.position.x.into(), e.position.y.into()))); + if moved || pointer.get().is_none() { + pointer.set(Some(e.position)); + } + moved + }); + on(window, &input, views, |_: &gpui::MouseDownEvent| true); + on(window, &input, views, |_: &gpui::ScrollWheelEvent| true); + }, + ) + .absolute() + } +} + +/// The clock of a start page animation. It runs while its window is the active one of the +/// active app and has had input within `effects::IDLE`, so a frame redraws one window only and +/// an untouched start page stops drawing; it holds its frame otherwise and continues from it. +struct Motion { + input: Input, + clock: browser_core::effects::Clock, + ticking: Rc>, + active: bool, +} + +impl Motion { + fn new(input: Input) -> Self { + Motion { input, clock: Default::default(), ticking: Default::default(), active: false } + } + + /// Animation time shown now, redrawing the view every `frame` while `run` and awake. + fn elapsed(&mut self, run: bool, frame: std::time::Duration, window: &Window, cx: &mut Context) -> std::time::Duration { + let now = Instant::now(); + let active = engine::app_active() && window.is_window_active(); + if active && !self.active { + self.input.set(Some(now)); + } + self.active = active; + if !self.input.get().is_some_and(|at| browser_core::effects::awake(now - at)) { + self.input.set(None); + } + let Some(elapsed) = self.clock.tick(now, run && active && self.input.get().is_some()) else { return self.clock.held() }; + if !self.ticking.replace(true) { + let ticking = self.ticking.clone(); + cx.spawn(async move |this, cx| { + cx.background_executor().timer(frame).await; + ticking.set(false); + this.update(cx, |_, cx| cx.notify()).ok(); + }) + .detach(); + } + elapsed + } +} + +/// The ASCII cloud bank behind the start card, redrawn every `fog::FRAME` on the `Motion` clock; +/// its own view, so windows that observe the `Browser` are not notified. One still frame while +/// motion is reduced or the theme asks for it; none when the theme turns it off. pub struct Fog { pub(crate) reduce: bool, /// The window's width left of the content area, which the fog does not cover. pub(crate) left: f32, - started: Option, - ticking: bool, + motion: Motion, frame: Option<(FogKey, Vec)>, } @@ -817,24 +918,8 @@ impl gpui::Render for Fog { let (cols, rows) = (((f32::from(size.width) - self.left).max(0.) / FOG_FONT.1) as usize, (f32::from(size.height) / FOG_LINE) as usize); let mode = Theme::fog_mode(); let still = self.reduce || mode != browser_core::theme::Fog::On; - let active = engine::app_active() && window.is_window_active(); - let step = match (still, active) { - (true, _) => 0, - (false, true) => fog::step(self.started.get_or_insert_with(Instant::now).elapsed()), - (false, false) => self.frame.as_ref().map_or(0, |(key, _)| key.2), - }; - if !still && !self.ticking && active { - self.ticking = true; - cx.spawn(async move |this, cx| { - cx.background_executor().timer(std::time::Duration::from_secs_f32(fog::FRAME)).await; - this.update(cx, |fog, cx| { - fog.ticking = false; - cx.notify(); - }) - .ok(); - }) - .detach(); - } + let elapsed = self.motion.elapsed(!still, std::time::Duration::from_secs_f32(fog::FRAME), window, cx); + let step = if still { 0 } else { fog::step(elapsed) }; let key = (cols, rows, step, Theme::generation()); if mode == browser_core::theme::Fog::Off { self.frame = None; @@ -891,34 +976,20 @@ fn start_shield(level: shield::ShieldLevel) -> Stateful { const SEARCH_ROW: f32 = 54.; /// The theme's search bar effect behind the start and command card (`browser_core::effects`), -/// redrawn at `effects::FPS` while its window is the active one of the active app; its own view, -/// like `Fog`. One still frame while motion is reduced or the window is in the background. -#[derive(Default)] +/// redrawn at `effects::FPS` on the `Motion` clock; its own view, like `Fog`. One still frame +/// while motion is reduced. pub struct SearchFx { pub(crate) reduce: bool, - started: Option, - ticking: bool, + motion: Motion, } impl gpui::Render for SearchFx { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { use browser_core::effects::{self, Effect}; let effect = Theme::search_effect(); - let animate = !self.reduce && effect.fps() > 0. && engine::app_active() && window.is_window_active(); - let t = if animate { effects::clock(self.started.get_or_insert_with(Instant::now).elapsed()) } else { effects::STILL }; - if animate && !self.ticking { - self.ticking = true; - let frame = std::time::Duration::from_secs_f32(1. / effect.fps()); - cx.spawn(async move |this, cx| { - cx.background_executor().timer(frame).await; - this.update(cx, |fx, cx| { - fx.ticking = false; - cx.notify(); - }) - .ok(); - }) - .detach(); - } + let animate = !self.reduce && effect.fps() > 0.; + let elapsed = self.motion.elapsed(animate, std::time::Duration::from_secs_f32(1. / effect.fps().max(1.)), window, cx); + let t = if animate { effects::clock(elapsed + std::time::Duration::from_secs_f32(effects::STILL)) } else { effects::STILL }; let (side, rise) = effects::reach(effect, SEARCH_ROW); let color = Theme::search_color(); let layer = div().absolute().top(px(-rise)).left(px(-side)).right(px(-side)).bottom(px(-side)).overflow_hidden(); diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs index 49a02c64..2aff9052 100644 --- a/crates/app/src/lib.rs +++ b/crates/app/src/lib.rs @@ -221,6 +221,8 @@ impl Browser { if self.hidden_field_focused(window, cx) || (std::mem::take(&mut self.refocus) || stranded) && !self.overlay_open() && self.active_prompt().is_none() { window.focus(&self.focus_handle(cx)); } + let start = (self.command_mode.is_some() && !self.inline_editing()) || self.model.active.is_none(); + let watch = self.watch.element(start, [self.fog.entity_id(), self.search_fx.entity_id()], window, cx); let mut root = self.root_shell(cx); root = self.root_tab_actions(root, cx); root = self.root_listeners(root, cx); @@ -268,6 +270,7 @@ impl Browser { .child(timed("content", || content::render(self, window, cx))), ) .children(assistant::render(self, window, cx)) + .child(watch) .into_any_element() } diff --git a/crates/app/src/library.rs b/crates/app/src/library.rs index ddd2d246..2ebdfa9d 100644 --- a/crates/app/src/library.rs +++ b/crates/app/src/library.rs @@ -353,7 +353,12 @@ impl LibraryWindow { fn sample_on_memory_page(&self, cx: &mut Context) { if self.page == Page::Memory { - self.browser.update(cx, |b, cx| b.sample_processes(cx)).ok(); + self.browser + .update(cx, |b, cx| { + b.sample_processes(); + cx.notify(); + }) + .ok(); } } diff --git a/crates/app/src/memory.rs b/crates/app/src/memory.rs index 03fe9799..7d9cc407 100644 --- a/crates/app/src/memory.rs +++ b/crates/app/src/memory.rs @@ -5,7 +5,6 @@ use std::collections::{HashMap, VecDeque}; use std::hash::Hash; use std::time::{Duration, Instant}; -use gpui::Context; use platform::memory::Usage; use crate::browser::{Browser, TabKey}; @@ -86,10 +85,9 @@ impl Browser { } /// Samples every tab's process; the CPU figures come from the change between samples. - pub(crate) fn sample_processes(&mut self, cx: &mut Context) { + pub(crate) fn sample_processes(&mut self) { let live = self.tab_processes().into_iter().filter_map(|(_, pid)| Some((pid, platform::memory::usage(pid)?))).collect(); self.samples.record(live, Instant::now()); - cx.notify(); } pub(crate) fn tab_costs(&self) -> HashMap { diff --git a/crates/app/src/shared.rs b/crates/app/src/shared.rs index 639a174a..37171633 100644 --- a/crates/app/src/shared.rs +++ b/crates/app/src/shared.rs @@ -293,21 +293,30 @@ pub(crate) fn start(cx: &mut App) -> bool { pub(crate) fn count_chromium_blocks(core: &AppCore) { let blocked = engine::chromium::take_blocked(); let Some(profile_id) = core.chromium_profile.get() else { return }; - for (host, n) in blocked { - core.disk.count(profile_id, store::Counter::ChromiumRequests, n, Some(&host)).ok(); + if blocked.is_empty() { + return; } + let items: Vec<_> = blocked.iter().map(|(host, n)| (Some(host.as_str()), *n)).collect(); + core.disk.count_many(profile_id, store::Counter::ChromiumRequests, &items).ok(); crate::shield_card::touch(); } /// Each profile has its own Chromium profile on Windows, so each counts its own blocks. #[cfg(windows)] pub(crate) fn count_chromium_blocks(core: &AppCore) { + let mut counted = false; for (&(private, profile_id), rt) in core.profiles.borrow().iter() { - for (host, n) in rt.data.take_blocked() { - core.store(private).count(profile_id, store::Counter::ChromiumRequests, n, Some(&host)).ok(); + let blocked = rt.data.take_blocked(); + if blocked.is_empty() { + continue; } + let items: Vec<_> = blocked.iter().map(|(host, n)| (Some(host.as_str()), *n)).collect(); + core.store(private).count_many(profile_id, store::Counter::ChromiumRequests, &items).ok(); + counted = true; + } + if counted { + crate::shield_card::touch(); } - crate::shield_card::touch(); } fn toast_front(tone: browser_core::toast::Tone, text: impl Into, action: Option, cx: &mut App) { diff --git a/crates/app/src/tabs.rs b/crates/app/src/tabs.rs index c5c70bc6..b37e9b22 100644 --- a/crates/app/src/tabs.rs +++ b/crates/app/src/tabs.rs @@ -213,12 +213,15 @@ impl Browser { pub(crate) fn sleep_idle_tabs(&mut self, cx: &mut Context) { // Short of memory, a tab left for five minutes sleeps; the web processes are what holds the memory. let max_idle = browser_core::settings::max_idle(crate::prefs::sleep_after(&self.core.disk), platform::memory::pressure()); - let (now, keys) = (Instant::now(), self.views.keys().copied().collect::>()); + let (now, keys, heavy) = (Instant::now(), self.views.keys().copied().collect::>(), self.heavy.clone()); self.seen.retain(|k, _| keys.contains(k)); self.typed_in.retain(|k| keys.contains(k)); let mut background = Vec::new(); for key in keys { - let pinned = self.store(key.private).tab(key.id).is_ok_and(|t| t.kind != TabKind::Ephemeral); + let pinned = match self.model.tab(key) { + Some(t) => t.kind != TabKind::Ephemeral, + None => self.store(key.private).tab(key.id).is_ok_and(|t| t.kind != TabKind::Ephemeral), + }; let on_screen = self.model.active == Some(key) || self.in_split(key); let seen = self.seen.entry(key).or_insert(now); if on_screen { @@ -232,7 +235,7 @@ impl Browser { self.sleep_unless_playing(key, cx); } } - self.sample_processes(cx); + self.sample_processes(); if max_idle.is_some() { let costs = self.tab_costs(); // A tab kept for typed input counts like a playing one, so the budget sleeps others instead. @@ -243,6 +246,9 @@ impl Browser { } } self.probe_heavy(cx); + if self.heavy != heavy { + cx.notify(); + } } /// Asks each awake background tab, in every space for the memory budget, whether it is playing, @@ -564,7 +570,8 @@ impl Browser { fn ping_page(&mut self, cx: &mut Context) { let now = Instant::now(); let was = self.hang.hung(now); - match self.model.active.and_then(|k| Some((k, self.views.get(&k)?.clone()))) { + let active = engine::app_active(); + match self.model.active.filter(|_| active).and_then(|k| Some((k, self.views.get(&k)?.clone()))) { Some((key, view)) if self.hang.ping(key, now) => { let (tx, mut rx) = mpsc::unbounded(); view.ping(move || drop(tx.unbounded_send(()))); diff --git a/crates/browser-core/src/effects.rs b/crates/browser-core/src/effects.rs index e2862d1c..f9153e1b 100644 --- a/crates/browser-core/src/effects.rs +++ b/crates/browser-core/src/effects.rs @@ -4,6 +4,42 @@ pub const STILL: f32 = 0.4; /// Frames per second the shells request while an effect is on screen in the active window. pub const FPS: f32 = 24.; +/// Time without input in a window after which its start page animations hold their frame. +pub const IDLE: std::time::Duration = std::time::Duration::from_secs(60); + +/// Whether a start page animation keeps moving `since_input` after its window's last input. +pub fn awake(since_input: std::time::Duration) -> bool { + since_input < IDLE +} + +/// Whether a pointer at `to`, last counted at `from`, has moved for `awake`: AppKit repeats the +/// moves of a resting pointer a point apart, which must not keep an animation running. +pub fn moved(from: (f32, f32), to: (f32, f32)) -> bool { + (from.0 - to.0).abs() + (from.1 - to.1).abs() >= 4. +} +/// Time a start page animation has run, counted only between consecutive awake ticks, so a tick +/// after a pause or an idle spell adds nothing and the frame resumes where it was held. +#[derive(Default)] +pub struct Clock { + held: std::time::Duration, + last: Option, +} + +impl Clock { + /// The time shown at `now` while `awake`; `None` while not, when the clock holds `held`. + pub fn tick(&mut self, now: std::time::Instant, awake: bool) -> Option { + if !awake { + self.last = None; + return None; + } + self.held += self.last.replace(now).map_or(std::time::Duration::ZERO, |last| now.saturating_duration_since(last)); + Some(self.held) + } + + pub fn held(&self) -> std::time::Duration { + self.held + } +} const MAX_PARTICLES: usize = 480; /// Circles stacked in one flame tongue, base to tip. const TONGUE: usize = 7; @@ -308,6 +344,30 @@ mod tests { assert_eq!((Effect::None.fps(), Effect::Glow.fps(), Effect::Flames.fps()), (0., FPS, FPS)); } + #[test] + fn animations_hold_after_a_minute_without_input() { + assert!(awake(std::time::Duration::ZERO)); + assert!(awake(IDLE - std::time::Duration::from_millis(1))); + assert!(!awake(IDLE)); + assert!(!awake(std::time::Duration::from_secs(3600))); + assert!(!moved((10., 10.), (11., 10.))); + assert!(moved((10., 10.), (14., 10.))); + assert!(moved((10., 10.), (8., 8.))); + } + + #[test] + fn the_clock_adds_time_only_between_awake_ticks() { + use std::time::{Duration, Instant}; + let (mut clock, t0) = (Clock::default(), Instant::now()); + let at = |s| t0 + Duration::from_secs(s); + assert_eq!(clock.tick(at(0), true), Some(Duration::ZERO)); + assert_eq!(clock.tick(at(1), true), Some(Duration::from_secs(1))); + assert_eq!(clock.tick(at(100), false), None); + assert_eq!(clock.held(), Duration::from_secs(1)); + assert_eq!(clock.tick(at(200), true), Some(Duration::from_secs(1)), "the first tick after a pause adds nothing"); + assert_eq!(clock.tick(at(201), true), Some(Duration::from_secs(2))); + } + #[test] fn names_round_trip_and_none_draws_nothing() { for e in Effect::ALL { diff --git a/crates/browser-core/src/tarn_ext/runtime.rs b/crates/browser-core/src/tarn_ext/runtime.rs index 0fdaf663..9ff8045b 100644 --- a/crates/browser-core/src/tarn_ext/runtime.rs +++ b/crates/browser-core/src/tarn_ext/runtime.rs @@ -181,6 +181,10 @@ impl Runtime { self.profiles.get(&profile).into_iter().flat_map(|p| p.loaded.values()) } + pub fn has_installs(&self) -> bool { + self.profiles.keys().any(|&p| self.installs(p).next().is_some()) + } + pub fn scripts(&self, profile: Id) -> Vec> { self.installs(profile).map(|l| l.scripts.clone()).collect() } @@ -557,6 +561,8 @@ mod tests { assert_eq!(actions.len(), 1); assert_eq!((actions[0].install_id.as_str(), actions[0].state.title.as_str(), actions[0].icon), ("aa", "Shop helper", Some(7))); assert!(rt.actions(2, None).is_empty()); + assert!(rt.has_installs()); + assert!(!Rt::default().has_installs()); assert_eq!(rt.loaded(1, "bb").map(|l| l.package.manifest.version.as_str()), Some("2.1")); } diff --git a/crates/engine/src/lifecycle.rs b/crates/engine/src/lifecycle.rs index 0f6fc39e..b57ddfc1 100644 --- a/crates/engine/src/lifecycle.rs +++ b/crates/engine/src/lifecycle.rs @@ -171,6 +171,11 @@ impl Hang { (now.saturating_duration_since(from) >= HANG_AFTER).then_some(self.tab).flatten() } + /// Whether the shown tab `active` is the hung one. + pub fn hung_on(&self, active: Option, now: Instant) -> bool { + active.is_some() && self.hung(now) == active + } + /// Wait: the card goes until the page has stayed silent for another `HANG_AFTER`. pub fn wait(&mut self, now: Instant) { self.waited = Some(now); @@ -200,6 +205,7 @@ mod tests { hang.wait(at(HANG_AFTER)); assert_eq!(hang.hung(at(HANG_AFTER * 2 - PING)), None, "Wait hides the card"); assert_eq!(hang.hung(at(HANG_AFTER * 2)), Some(1), "and it comes back while the page stays silent"); + assert!(hang.hung_on(Some(1), at(HANG_AFTER * 2)) && !hang.hung_on(Some(2), at(HANG_AFTER * 2)) && !hang.hung_on(None, at(HANG_AFTER * 2))); hang.answered(1); assert_eq!(hang.hung(at(HANG_AFTER * 3)), None); assert!(hang.ping(1, at(HANG_AFTER * 3))); diff --git a/crates/store/src/db.rs b/crates/store/src/db.rs index 92972f04..3f59a754 100644 --- a/crates/store/src/db.rs +++ b/crates/store/src/db.rs @@ -464,27 +464,41 @@ impl Store { /// Adds `n` to the counter's total, to today's bucket (local time) and, with `host`, to that /// site's total; every profile's buckets older than the last seven days are dropped. pub fn count(&self, profile_id: Id, counter: Counter, n: i64, host: Option<&str>) -> Result<()> { + self.count_many(profile_id, counter, &[(host, n)]) + } + + /// `count` for several `(host, n)` pairs in one transaction, pruning once. + pub fn count_many(&self, profile_id: Id, counter: Counter, items: &[(Option<&str>, i64)]) -> Result<()> { + if items.is_empty() { + return Ok(()); + } let column = counter.column(); + let total: i64 = items.iter().map(|(_, n)| n).sum(); let tx = self.conn.unchecked_transaction()?; tx.execute( &format!( "INSERT INTO shield_stats (profile_id, seed, {column}) SELECT id, random() & 0x7fffffffffff, ?2 FROM profiles WHERE id = ?1 ON CONFLICT(profile_id) DO UPDATE SET {column} = {column} + ?2" ), - params![profile_id, n], + params![profile_id, total], )?; tx.execute( "INSERT INTO shield_daily (profile_id, day, counter, n) SELECT id, date('now', 'localtime'), ?2, ?3 FROM profiles WHERE id = ?1 ON CONFLICT DO UPDATE SET n = n + excluded.n", - params![profile_id, column, n], + params![profile_id, column, total], )?; tx.execute("DELETE FROM shield_daily WHERE day < date('now', 'localtime', '-6 days')", [])?; - if let Some(host) = host.filter(|h| !h.is_empty() && h.len() <= 253) { + let mut sites = false; + for (host, n) in items { + let Some(host) = host.filter(|h| !h.is_empty() && h.len() <= 253) else { continue }; tx.execute( "INSERT INTO shield_sites (profile_id, host, n) SELECT id, ?2, ?3 FROM profiles WHERE id = ?1 ON CONFLICT DO UPDATE SET n = n + excluded.n", params![profile_id, host, n], )?; + sites = true; + } + if sites { // A page can choose the hosts it is upgraded to, so only the busiest sites are kept. tx.execute( "DELETE FROM shield_sites WHERE profile_id = ?1 AND host NOT IN @@ -2114,6 +2128,34 @@ mod tests { Store { conn, settings_rev: Default::default() } } + #[test] + fn count_many_matches_repeated_count() { + let dump = |s: &Store| -> Vec { + let mut rows = Vec::new(); + for q in [ + "SELECT profile_id || ':' || https_upgrades FROM shield_stats", + "SELECT counter || ':' || n FROM shield_daily", + "SELECT host || ':' || n FROM shield_sites ORDER BY host", + ] { + let mut stmt = s.conn.prepare(q).unwrap(); + rows.extend(stmt.query_map([], |r| r.get::<_, String>(0)).unwrap().map(|r| r.unwrap())); + } + rows + }; + let items = [(Some("a.test"), 2), (Some("b.test"), 3), (Some("a.test"), 1), (None, 4), (Some(""), 1)]; + let one = Store::open_in_memory().unwrap(); + let many = Store::open_in_memory().unwrap(); + for s in [&one, &many] { + s.create_profile("P", "u1", false).unwrap(); + } + for (host, n) in items { + one.count(1, Counter::HttpsUpgrades, n, host).unwrap(); + } + many.count_many(1, Counter::HttpsUpgrades, &items).unwrap(); + assert_eq!(dump(&one), dump(&many)); + assert!(dump(&many).contains(&"a.test:3".to_owned())); + } + #[test] fn shield_stats_count_survive_reopening_and_reset_with_the_profile() { let mut store = store_before("CREATE TABLE shield_stats"); diff --git a/docs/nsh-plan.md b/docs/nsh-plan.md index 546b96e1..58e8fbf9 100644 --- a/docs/nsh-plan.md +++ b/docs/nsh-plan.md @@ -254,8 +254,8 @@ tests use a test-signed bundle and no network). backdrop gradient in the brand mark's lake blues, an inset sidebar card with the blue gradient, lake-blue 16 % edge and elevation shadow, a Safari-style address capsule that shows the host at rest (`Not Secure — host` in amber for http, long hosts cut at the start), a Spotlight-style start card with the brand mark over -the drifting ASCII fog (`tarn_nsh_shared::fog`, a canvas redrawn every `browser_core::fog::FRAME`, one -still frame under the desktop's reduced motion), an accent edge on the active tab row, an accent-tinted New Tab +the drifting ASCII fog (`tarn_nsh_shared::fog`, a canvas redrawn every `browser_core::fog::FRAME` that holds its frame after `browser_core::effects::IDLE` +without input, one still frame under the desktop's reduced motion), an accent edge on the active tab row, an accent-tinted New Tab pill, a tab close button that slides in on hover (`ElementRef::animate_layout`), flat surface cards for prompts, banners and the find bar, and System Settings-style panels. Its tokens are mirrored by name in `nsh-shared/src/theme.rs`, shared with the mobile app (a test checks them against the GPUI source) and the icons and brand mark are `crates/ui`'s own files. Deviations: diff --git a/docs/shared-core.md b/docs/shared-core.md index bec355e5..4ba84243 100644 --- a/docs/shared-core.md +++ b/docs/shared-core.md @@ -387,8 +387,11 @@ world, Chromium one `Runtime.evaluate` of a constant in the page's world; NSH co answered by `pong`: the isolated world on Linux and iOS, the page world on Android, which has no other). A page whose main thread is stuck never answers, and the shell shows a card (`HANG_NOTE`) once a ping has gone unanswered for `HANG_AFTER`. Blind spot: under Lockdown no script of Tarn's -runs, so every engine answers a ping at once and a hung Lockdown page shows no card. iOS and -Android redraw only when the card appears or goes, never for a ping or its answer. +runs, so every engine answers a ping at once and a hung Lockdown page shows no card. The ping +is skipped, and an unanswered one forgotten, while the app is in the background on every client +(not only the window being in the background, so a link peek or other window of the app does not +stop it). Linux, iOS and Android redraw only when the card appears or goes, never for a ping or +its answer. Wait hides it for another `HANG_AFTER`; Reload gives the page a fresh start: macOS and Windows rebuild the tab's view, Linux's component takes `reloadFresh`, which ends the view's web process (`webkit_web_view_terminate_web_process`) and reloads, and iOS and Android give the tab a new view diff --git a/linux/src/browser.rs b/linux/src/browser.rs index a6bf5e42..49918164 100644 --- a/linux/src/browser.rs +++ b/linux/src/browser.rs @@ -149,6 +149,8 @@ pub struct Browser { pub processes: HashMap, pub samples: crate::memory::Samples, pub used: HashMap, + /// The heavy tabs the snapshot last showed. + pub heavy_shown: HashSet, pub playing: HashSet, pub player: browser_core::media::Player, /// The tab and committed address Insert Snippet opened on. @@ -247,6 +249,7 @@ impl Browser { processes: HashMap::new(), samples: Default::default(), used: HashMap::new(), + heavy_shown: HashSet::new(), playing: HashSet::new(), player: Default::default(), snippet_page: None, diff --git a/linux/src/browser/feature_tests.rs b/linux/src/browser/feature_tests.rs index 49a9b1e6..9c8d1a5b 100644 --- a/linux/src/browser/feature_tests.rs +++ b/linux/src/browser/feature_tests.rs @@ -1909,20 +1909,23 @@ fn the_shown_page_is_pinged_and_offers_wait_and_reload_once_it_stops_answering() b.outbox.clear(); let silent = std::time::Instant::now() - engine::lifecycle::HANG_AFTER; let hung = |b: &Browser| crate::snapshot::snapshot(b, true).hung; - b.ping_page(silent); - b.ping_page(std::time::Instant::now()); + b.ping_page(silent, true); + b.ping_page(std::time::Instant::now(), true); assert_eq!(asked(&b, "ping").len(), 1, "one ping at a time"); assert!(asked(&b, "readSelection").is_empty(), "the ping reads nothing of the page"); assert!(hung(&b)); b.wait_for_page(); assert!(!hung(&b), "Wait hides the card"); b.on_event(key, "pong", &json!({ "seq": 0 })); - b.ping_page(silent); + b.ping_page(silent, true); assert_eq!(asked(&b, "ping").len(), 2, "an answer lets the next ping go"); assert!(hung(&b)); b.on_event(key, "pong", &json!({ "seq": 0 })); assert!(!hung(&b), "the answer hides the card"); - b.ping_page(silent); + b.ping_page(silent, true); + b.ping_page(silent, false); + assert!(!hung(&b), "an inactive app forgets the unanswered ping"); + b.ping_page(silent, true); b.reload_hung(); assert_eq!(b.outbox.last().map(|(k, n, _)| (*k, *n)), Some((key, "reloadFresh"))); assert!(!hung(&b)); diff --git a/linux/src/browser/tab_actions.rs b/linux/src/browser/tab_actions.rs index 357ecdf2..6558683d 100644 --- a/linux/src/browser/tab_actions.rs +++ b/linux/src/browser/tab_actions.rs @@ -62,15 +62,20 @@ impl Browser { self.model.reload_space(&self.core); } - /// Pings the shown page, as `engine::lifecycle::Hang` asks, every `PING_EVERY`. - pub fn ping_page(&mut self, now: std::time::Instant) { - match self.model.active { + /// Pings the shown page, as `engine::lifecycle::Hang` asks, every `PING_EVERY`; while the app + /// is not `active` nothing is pinged and an unanswered ping is forgotten. + pub fn ping_page(&mut self, now: std::time::Instant, active: bool) { + match self.model.active.filter(|_| active) { Some(key) if self.hang.ping(key, now) => self.outbox.push((key, "ping", serde_json::json!({ "seq": 0 }))), Some(_) => {} None => self.hang.forget(), } } + pub fn hung(&self) -> bool { + self.hang.hung_on(self.model.active, std::time::Instant::now()) + } + pub fn wait_for_page(&mut self) { self.hang.wait(std::time::Instant::now()); } diff --git a/linux/src/extensions/mod.rs b/linux/src/extensions/mod.rs index 46b93011..82f6b095 100644 --- a/linux/src/extensions/mod.rs +++ b/linux/src/extensions/mod.rs @@ -393,6 +393,9 @@ pub fn navigated(profile: Id, tab: u64) { pub fn tick() { let effects = with(|rt| { + if !rt.rt.has_installs() { + return Vec::new(); + } let (effects, expired) = rt.rt.tick(Instant::now()); if expired { rt.push_all_rules(); diff --git a/linux/src/snapshot.rs b/linux/src/snapshot.rs index 58725eb4..064d7df6 100644 --- a/linux/src/snapshot.rs +++ b/linux/src/snapshot.rs @@ -497,7 +497,7 @@ pub fn snapshot(b: &Browser, web_shown: bool) -> Snapshot { zoom: if page.zoom > 0.0 { page.zoom } else { 1.0 }, found: page.found, error: page.error.clone(), - hung: b.model.active.is_some() && b.hang.hung(std::time::Instant::now()) == b.model.active, + hung: b.hung(), blocked: page.blocked.clone(), prompt: page.prompts.front().cloned(), notice: b.notice.clone(), diff --git a/linux/src/ui.rs b/linux/src/ui.rs index d6b0e820..7433e59a 100644 --- a/linux/src/ui.rs +++ b/linux/src/ui.rs @@ -255,6 +255,7 @@ fn act_dyn(ui: Ui, f: &mut dyn FnMut(&mut Browser), rebuild: bool) { let regrouped = b.regrouped_space.take(); let shown = shown && b.reader.as_ref().is_none_or(|r| b.model.active != Some(r.key)) && b.active_json().is_none(); let snap = snapshot::snapshot(b, shown); + b.heavy_shown = b.heavy_tabs(); if ui.snap.with_untracked(|s| s.notice != snap.notice || s.prompt != snap.prompt || s.error != snap.error) { b.settle_downloads(); } @@ -308,11 +309,7 @@ fn act_dyn(ui: Ui, f: &mut dyn FnMut(&mut Browser), rebuild: bool) { ui.root.run(|| drop(set_timeout(RETIRE_DELAY, || crate::data::wipe_retired(&crate::data::root(), &core().disk)))); } tools::expire_toast(ui); - for (key, name, args) in commands { - if let Some(r) = REFS.with_borrow(|refs| refs.get(&(ui.window, key)).map(|(_, r)| *r)) { - r.command(name, args); - } - } + send_commands(ui, commands); if rebuild { ui.rev.update(|r| *r += 1); } @@ -329,6 +326,56 @@ fn act_dyn(ui: Ui, f: &mut dyn FnMut(&mut Browser), rebuild: bool) { } } +fn send_commands(ui: Ui, commands: Vec<(TabKey, &'static str, serde_json::Value)>) { + for (key, name, args) in commands { + if let Some(r) = REFS.with_borrow(|refs| refs.get(&(ui.window, key)).map(|(_, r)| *r)) { + r.command(name, args); + } + } +} + +/// Pings the shown page while the app is in front; the snapshot is rebuilt only when the hung-page card appears or goes. +fn ping(ui: Ui) { + let active = untracked(lifecycle) == nsh_core::platform::Lifecycle::Active; + let sent = BROWSERS.with_borrow_mut(|windows| { + let b = windows.get_mut(&ui.window)?; + b.ping_page(std::time::Instant::now(), active); + Some((std::mem::take(&mut b.outbox), b.hung())) + }); + let Some((commands, hung)) = sent else { return }; + send_commands(ui, commands); + if ui.snap.with_untracked(|s| s.hung) != hung { + act_quietly(ui, |_| {}); + } +} + +/// A page's answer to `ping`; the snapshot is rebuilt only when the hung-page card goes. +fn pong(ui: Ui, key: TabKey, data: &serde_json::Value) { + let hung = BROWSERS.with_borrow_mut(|windows| { + let b = windows.get_mut(&ui.window)?; + b.on_event(key, "pong", data); + Some(b.hung()) + }); + if hung.is_some_and(|hung| ui.snap.with_untracked(|s| s.hung) != hung) { + act_quietly(ui, |_| {}); + } +} + +/// Samples the page processes; the snapshot is rebuilt only when the heavy tabs change or the Memory panel shows the costs. +fn sample(ui: Ui) { + let changed = BROWSERS.with_borrow_mut(|windows| { + let b = windows.get_mut(&ui.window)?; + b.sample_processes(); + let heavy = b.heavy_tabs(); + let changed = heavy != b.heavy_shown; + b.heavy_shown = heavy; + Some(changed) + }); + if changed == Some(true) || ui.panel.get_untracked() == Panel::Memory { + act_quietly(ui, |_| {}); + } +} + /// Drops every window's assistant chat (a profile was deleted or reset). fn forget_chats() { tarn_nsh_shared::assistant::forget_chats(); @@ -548,6 +595,9 @@ fn web_views(ui: Ui) -> View { if &*event.name == "snapshot" { return peek::shot(ui, key, &event.data["png"]); } + if &*event.name == "pong" { + return pong(ui, key, &event.data); + } if &*event.name == "jsonText" { return devtools::json_text(ui, key, event.data.clone()); } @@ -2032,6 +2082,7 @@ fn start_card(ui: Ui) -> AnyElement { } let field = input() .value(move || ui.command.get()) + .on_key_press(|_: &str| tarn_nsh_shared::motion::touched()) .on_change(move |v: &str| { let _span = engine::startup::span(engine::startup::PALETTE_QUERY); // A new query reads the history again, so visits since the last one show. @@ -2483,6 +2534,7 @@ const NEED_A_TAB: [Action; 16] = [ ]; fn run_action(ui: Ui, action: Action) { + tarn_nsh_shared::motion::touched(); if NEED_A_TAB.contains(&action) && !ui.snap.with_untracked(|s| s.tab) { return; } @@ -2998,12 +3050,12 @@ fn browser_window(ui: Ui) -> AnyElement { b.idle_tick(windows); }) })); - drop(set_interval(engine::lifecycle::PING_EVERY, move || act_quietly(ui, |b| b.ping_page(std::time::Instant::now())))); + drop(set_interval(engine::lifecycle::PING_EVERY, move || ping(ui))); drop(set_interval(SAMPLE_TICK, move || { if ui.speaking.get_untracked() && !crate::speech::speaking() { ui.speaking.set(false); } - act_quietly(ui, |b| b.sample_processes()); + sample(ui); })); drop(set_interval(browser_core::closed::ARCHIVE_INTERVAL, move || { act_quietly(ui, |b| { @@ -3027,7 +3079,7 @@ fn browser_window(ui: Ui) -> AnyElement { untracked(|| apply_color_scheme(ui, light)); }); let full = computed(move || ui.snap.with(|s| s.fullscreen)); - view() + tarn_nsh_shared::motion::watching(view()) .flex_row() .size_full() .relative() diff --git a/mobile/app/src/extensions.rs b/mobile/app/src/extensions.rs index 6daa5e69..673496fc 100644 --- a/mobile/app/src/extensions.rs +++ b/mobile/app/src/extensions.rs @@ -310,6 +310,10 @@ impl Shell { if allow { vec![Effect::Command(ask.tab, "reload", Value::Null)] } else { Vec::new() } } + pub fn has_extensions(&self) -> bool { + self.ext.rt.has_installs() + } + /// Stops idle background pages and renews the network rules when a Once answer ends. pub fn extensions_tick(&mut self, now: Instant) -> Vec { let (outs, expired) = self.ext.rt.tick(now); diff --git a/mobile/app/src/shell.rs b/mobile/app/src/shell.rs index 2a5f59a7..62468bce 100644 --- a/mobile/app/src/shell.rs +++ b/mobile/app/src/shell.rs @@ -988,9 +988,10 @@ impl Shell { self.model.active.map(|k| vec![Effect::Command(k, name, args)]).unwrap_or_default() } - /// Pings the shown page, as `engine::lifecycle::Hang` asks, every `PING_EVERY`. - pub fn ping_page(&mut self, now: std::time::Instant) -> Vec { - match self.model.active { + /// Pings the shown page, as `engine::lifecycle::Hang` asks, every `PING_EVERY`; while the app + /// is not `active` nothing is pinged and an unanswered ping is forgotten. + pub fn ping_page(&mut self, now: std::time::Instant, active: bool) -> Vec { + match self.model.active.filter(|_| active) { Some(key) if self.hang.ping(key, now) => vec![Effect::Command(key, "ping", serde_json::json!({ "seq": 0 }))], Some(_) => Vec::new(), None => { @@ -1001,7 +1002,7 @@ impl Shell { } pub fn hung(&self) -> bool { - self.model.active.is_some() && self.hang.hung(std::time::Instant::now()) == self.model.active + self.hang.hung_on(self.model.active, std::time::Instant::now()) } pub fn wait_for_page(&mut self) -> Vec { diff --git a/mobile/app/src/ui/extensions.rs b/mobile/app/src/ui/extensions.rs index e0eb09ed..740882eb 100644 --- a/mobile/app/src/ui/extensions.rs +++ b/mobile/app/src/ui/extensions.rs @@ -136,7 +136,11 @@ pub(super) fn start(ui: Ui) { } run })); - drop(set_interval(TICK, move || ui.act(|s| s.extensions_tick(Instant::now())))); + drop(set_interval(TICK, move || { + if ui.read(|s| s.has_extensions()) { + ui.act(|s| s.extensions_tick(Instant::now())); + } + })); } fn page_view(ui: Ui, page: PageView, hidden: bool) -> impl IntoElement { diff --git a/mobile/app/src/ui/mod.rs b/mobile/app/src/ui/mod.rs index 77467772..df2afa36 100644 --- a/mobile/app/src/ui/mod.rs +++ b/mobile/app/src/ui/mod.rs @@ -680,10 +680,13 @@ pub fn App() -> impl IntoElement { }; follow(); set_interval(Duration::from_secs(60), follow); - set_interval(engine::lifecycle::PING_EVERY, move || ui.run_quietly(|s| s.ping_page(Instant::now()))); + set_interval(engine::lifecycle::PING_EVERY, move || { + let active = untracked(lifecycle) == nsh_core::platform::Lifecycle::Active; + ui.run_quietly(|s| s.ping_page(Instant::now(), active)); + }); media::poll(ui); extensions::start(ui); - view() + tarn_nsh_shared::motion::watching(view()) .flex_1() .pt_safe_area() .px_safe_area() diff --git a/mobile/app/tests/shell.rs b/mobile/app/tests/shell.rs index c35a985a..34c393a4 100644 --- a/mobile/app/tests/shell.rs +++ b/mobile/app/tests/shell.rs @@ -1152,18 +1152,20 @@ fn the_shown_page_is_pinged_and_offers_wait_and_reload_once_it_stops_answering() finish(&mut shell, "https://slow.test/", "Slow"); let key = active(&shell); let silent = std::time::Instant::now() - engine::lifecycle::HANG_AFTER; - let pinged = shell.ping_page(silent); + let pinged = shell.ping_page(silent, true); assert!(matches!(pinged.as_slice(), [Effect::Command(k, "ping", _)] if *k == key), "{pinged:?}"); - assert!(shell.ping_page(std::time::Instant::now()).is_empty(), "one ping at a time"); + assert!(shell.ping_page(std::time::Instant::now(), true).is_empty(), "one ping at a time"); assert!(shell.hung()); shell.wait_for_page(); assert!(!shell.hung(), "Wait hides the card"); shell.event(key, "pong", &json!({ "seq": 0 }), 3); - assert_eq!(shell.ping_page(silent).len(), 1, "an answer lets the next ping go"); + assert_eq!(shell.ping_page(silent, true).len(), 1, "an answer lets the next ping go"); assert!(shell.hung()); shell.event(key, "pong", &json!({ "seq": 0 }), 4); assert!(!shell.hung(), "the answer hides the card"); - shell.ping_page(silent); + shell.ping_page(silent, true); + assert!(shell.ping_page(silent, false).is_empty() && !shell.hung(), "an inactive app forgets the unanswered ping"); + shell.ping_page(silent, true); let born = shell.views()[0].born; shell.reload_hung(); assert!(!shell.hung()); diff --git a/nsh-shared/src/fog.rs b/nsh-shared/src/fog.rs index d5ec7357..5e44fda8 100644 --- a/nsh-shared/src/fog.rs +++ b/nsh-shared/src/fog.rs @@ -1,5 +1,5 @@ use std::ops::Range; -use std::time::{Duration, Instant}; +use std::time::Duration; use nsh_core::canvas::CanvasTextBaseline; use nsh_core::prelude::*; @@ -50,8 +50,7 @@ pub fn fog(frame: impl Fn(usize, usize, Duration) -> Vec + 'static, period: fn layer(frame: impl Fn(usize, usize, Duration) -> Vec + 'static, period: Duration, moving: bool) -> View { let size = signal((0f32, 0f32)); let elapsed = signal(Duration::ZERO); - let start = Instant::now(); - crate::motion::while_active(period, move || moving, move || elapsed.set(start.elapsed())); + crate::motion::while_active(period, move || moving, move |held| elapsed.set(held)); let painter = move || { let (width, height) = size.get(); let (cols, rows) = grid(width, height); diff --git a/nsh-shared/src/motion.rs b/nsh-shared/src/motion.rs index eae5f0ba..f64ec51c 100644 --- a/nsh-shared/src/motion.rs +++ b/nsh-shared/src/motion.rs @@ -1,13 +1,54 @@ -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::time::Duration; +use std::sync::LazyLock; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::{Duration, Instant}; use nsh_core::platform::Lifecycle; use nsh_core::prelude::*; use nsh_core::{LayoutAnimation, LayoutCurve, LayoutTransition}; static REDUCED: AtomicBool = AtomicBool::new(false); +static EPOCH: LazyLock = LazyLock::new(Instant::now); +static TOUCHED: AtomicU64 = AtomicU64::new(0); + +#[derive(Clone, Copy, Default)] +struct Woke; + +/// Counts an input; the first after `effects::IDLE` wakes the animations that went to sleep. +pub fn touched() { + let asleep = !browser_core::effects::awake(since_input()); + TOUCHED.store(EPOCH.elapsed().as_millis() as u64, Ordering::Relaxed); + if asleep && let Some(woke) = try_global::() { + Owner::detached().run(|| drop(spawn(async move { woke.set(Woke) }))); + } +} + +fn since_input() -> Duration { + EPOCH.elapsed().saturating_sub(Duration::from_millis(TOUCHED.load(Ordering::Relaxed))) +} + +thread_local! { + static POINTER: Cell> = const { Cell::new(None) }; +} + +fn pointer_moved(e: &MouseEvent) { + let at = (e.page_position.x.0, e.page_position.y.0); + let moved = POINTER.get().is_some_and(|from| browser_core::effects::moved(from, at)); + if moved || POINTER.get().is_none() { + POINTER.set(Some(at)); + } + if moved { + touched(); + } +} + +pub fn watching(view: View) -> View { + view.on_mouse_move(pointer_moved) + .on_mouse_up(|_: &MouseEvent| touched()) + .on_wheel(|_: &WheelEvent| touched()) + .on_touch(|_: &nsh_core::TouchEvent| touched()) +} #[derive(Clone, Copy, Default)] struct Revision; @@ -31,15 +72,32 @@ pub fn animates(reduced: bool, lifecycle: Lifecycle) -> bool { !reduced && lifecycle == Lifecycle::Active } -pub fn while_active(period: Duration, running: impl Fn() -> bool + 'static, tick: impl Fn() + Clone + 'static) { +/// Calls `tick` with the time the animation has run, every `period` while the app is active, +/// `running` and the user has been active within `effects::IDLE`. The timer stops when the user +/// goes idle and starts again at the next input, so an idle start page wakes nothing. +pub fn while_active(period: Duration, running: impl Fn() -> bool + 'static, tick: impl Fn(Duration) + Clone + 'static) { let timer: Rc>>> = Rc::default(); + let clock = Rc::new(RefCell::new(browser_core::effects::Clock::default())); + let rest = signal(0u32); + touched(); effect(move || { + global::().get(); + rest.get(); + clock.borrow_mut().tick(Instant::now(), false); if let Some(old) = timer.borrow_mut().take() { old.cancel(); } - if animates(reduced(), lifecycle()) && running() { - let tick = tick.clone(); - *timer.borrow_mut() = Some(untracked(|| set_interval(period, tick))); + if animates(reduced(), lifecycle()) && running() && browser_core::effects::awake(since_input()) { + let (clock, tick) = (clock.clone(), tick.clone()); + *timer.borrow_mut() = Some(untracked(|| { + set_interval(period, move || { + let held = clock.borrow_mut().tick(Instant::now(), browser_core::effects::awake(since_input())); + match held { + Some(held) => tick(held), + None => rest.update(|n| *n += 1), + } + }) + })); } }); } @@ -158,6 +216,12 @@ mod tests { assert!(!animates(false, Lifecycle::Background)); } + #[test] + fn touching_resets_the_time_since_input() { + touched(); + assert!(since_input() < Duration::from_secs(1)); + } + #[test] fn the_durations_match_the_gpui_motion() { for (name, duration) in [("POP", POP), ("FADE", FADE), ("EXIT", EXIT), ("SLIDE", SLIDE)] { diff --git a/nsh-shared/src/search_fx.rs b/nsh-shared/src/search_fx.rs index d7bd3524..bbf10a13 100644 --- a/nsh-shared/src/search_fx.rs +++ b/nsh-shared/src/search_fx.rs @@ -1,19 +1,14 @@ use std::f32::consts::TAU; -use std::time::{Duration, Instant}; +use std::time::Duration; use browser_core::effects::{self, Effect, Particle}; use nsh_core::element::{BoxShadow, Color}; -use nsh_core::platform::Lifecycle; use nsh_core::prelude::*; use crate::theme::{Theme, themed}; pub use effects::STILL; -pub fn animates(effect: Effect, reduce_motion: bool, lifecycle: Lifecycle) -> bool { - effect.fps() > 0. && !reduce_motion && lifecycle == Lifecycle::Active -} - #[derive(Clone, Copy, Debug, PartialEq)] pub struct Dot { pub x: f32, @@ -74,12 +69,13 @@ pub fn search_fx(row: f32) -> AnyElement { } let t = signal(STILL); let size = signal((0f32, 0f32)); + crate::motion::while_active( + Duration::from_secs_f32(1. / effect.fps().max(1.)), + || true, + move |held| t.set(effects::clock(held + Duration::from_secs_f32(STILL))), + ); nsh_core::prelude::effect(move || { - if animates(effect, crate::motion::reduced(), lifecycle()) { - let start = Instant::now(); - let task = set_interval(Duration::from_secs_f32(1. / effect.fps()), move || t.set(effects::clock(start.elapsed()))); - cleanup(move || task.cancel()); - } else { + if crate::motion::reduced() { t.set(STILL); } }); @@ -120,16 +116,6 @@ pub fn search_fx(row: f32) -> AnyElement { mod tests { use super::*; - #[test] - fn effects_animate_only_in_the_active_window_without_reduce_motion() { - assert!(animates(Effect::Flames, false, Lifecycle::Active)); - assert!(animates(Effect::Glow, false, Lifecycle::Active)); - assert!(!animates(Effect::Flames, true, Lifecycle::Active), "Reduce Motion keeps a still frame"); - assert!(!animates(Effect::Flames, false, Lifecycle::Inactive), "a window in the background stops"); - assert!(!animates(Effect::Sparkle, false, Lifecycle::Background)); - assert!(!animates(Effect::None, false, Lifecycle::Active)); - } - #[test] fn every_particle_is_a_soft_glow_and_sparks_add_a_glint() { let blue = rgba(0x1f75b0ff); From 179704b8e9e9f3ef8bc7b57a9e893e6840be26c8 Mon Sep 17 00:00:00 2001 From: rgxdev Date: Tue, 24 Nov 2026 07:21:18 +0100 Subject: [PATCH 2/2] perf: hold less GPU and heap memory; address review comments macOS browser windows keep two Metal drawables instead of GPUI's three and turn the next-drawable timeout back on, so GPUI skips a frame instead of blocking the main thread when both are in use. Windows keeps three: GPUI resizes its DXGI swap chain with that count (docs/windows-plan.md section 8). Freed heap memory goes back to the system once a minute when tabs closed or slept since the last tick, and once when Tarn leaves the front (engine::lifecycle::release_memory): malloc_zone_pressure_relief on macOS, glibc malloc_trim on Linux. iOS and Android are listed in docs/port-backlog.md. Review comments: the Memory page's samples notify the Library window instead of the browser window; Linux builds each snapshot from one heavy-tab set; doc comments added by the previous commit are removed and the docs it rewrote are restored and corrected. Measured on macOS (release, warm profile, three runs each): window IOSurface memory 49 MB -> 33 MB; shell footprint 70 s after leaving the front, median 108 MB -> 82 MB; start page frame intervals unchanged (median 133 ms, p99 150 ms). Signed-off-by: rgxdev --- CHANGELOG.md | 3 +++ crates/app/src/browser.rs | 4 +++- crates/app/src/content.rs | 20 +++++++------------- crates/app/src/library.rs | 8 ++------ crates/app/src/shared.rs | 8 +++++++- crates/app/src/tabs.rs | 5 ++++- crates/browser-core/src/effects.rs | 11 +++-------- crates/engine/src/host_windows.rs | 2 ++ crates/engine/src/lib.rs | 2 ++ crates/engine/src/lifecycle.rs | 13 ++++++++++++- crates/engine/src/trim.rs | 10 ++++++++++ crates/engine/src/webview.rs | 13 +++++++++++++ crates/store/src/db.rs | 1 - docs/port-backlog.md | 15 +++++++++++++++ docs/windows-plan.md | 3 +++ linux/src/browser.rs | 1 - linux/src/browser/tab_actions.rs | 3 +-- linux/src/snapshot.rs | 12 ++++++++---- linux/src/ui.rs | 17 ++++++++++++----- mobile/app/src/shell.rs | 3 +-- nsh-shared/src/motion.rs | 4 ---- 21 files changed, 108 insertions(+), 50 deletions(-) create mode 100644 crates/engine/src/trim.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index bc0523e0..837b7cdf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -93,6 +93,9 @@ All notable changes to Tarn are documented in this file. The format is based on the extension timer on Linux, iOS and Android does nothing without an installed extension; Chromium's Shield counts are written once a minute in one transaction, and only when something was blocked. +- Less memory: on macOS a browser window keeps two screen buffers instead of three (16 MB less GPU + memory for a large window), and on macOS and Linux Tarn hands memory it freed back to the system + after tabs close or sleep and once when it leaves the front. - The sidebar's New Tab row has one Organize Tabs button (…) in place of four: New Tab Group, New Folder, Clean Up and Group with Assistant are in its menu, on every client. - Enter on an address Tarn cannot open shakes the field instead of going anywhere, on every diff --git a/crates/app/src/browser.rs b/crates/app/src/browser.rs index 519d37b4..795178ce 100644 --- a/crates/app/src/browser.rs +++ b/crates/app/src/browser.rs @@ -511,10 +511,12 @@ impl Browser { let sidebar_open = crate::prefs::sidebar_open(disk) && tab_placement == browser_core::layout::TabPlacement::Side; let sidebar_width = crate::prefs::sidebar_width(disk); let watch = crate::content::Watch::default(); + let host = Host::from_window(window); + host.iter().for_each(Host::double_buffer); let mut browser = Browser { core, warning: None, - host: Host::from_window(window), + host, model: browser_core::tabs::Model::new(live_tabs), views: HashMap::new(), theme_generation: ui::theme::Theme::generation(), diff --git a/crates/app/src/content.rs b/crates/app/src/content.rs index 1cb8cd3e..91b4af99 100644 --- a/crates/app/src/content.rs +++ b/crates/app/src/content.rs @@ -798,8 +798,6 @@ type FogKey = (usize, usize, u32, u32); type Input = Rc>>; -/// The window's last input, recorded by listeners the `Browser` always paints, so the start page -/// counts input from before it appeared. `None` once the animations went idle. #[derive(Default)] pub(crate) struct Watch { input: Input, @@ -817,8 +815,6 @@ impl Watch { SearchFx { reduce: false, motion: Motion::new(self.input.clone()) } } - /// Counts the start page appearing as input and returns the element that records the rest and - /// wakes `views` on the first input after idle; a pointer move counts once `effects::moved` says it travelled. pub(crate) fn element(&mut self, start: bool, views: [gpui::EntityId; 2], window: &Window, cx: &mut Context) -> impl IntoElement + use<> { fn on(window: &mut Window, input: &Input, views: [gpui::EntityId; 2], counts: impl Fn(&E) -> bool + 'static) { let input = input.clone(); @@ -860,9 +856,6 @@ impl Watch { } } -/// The clock of a start page animation. It runs while its window is the active one of the -/// active app and has had input within `effects::IDLE`, so a frame redraws one window only and -/// an untouched start page stops drawing; it holds its frame otherwise and continues from it. struct Motion { input: Input, clock: browser_core::effects::Clock, @@ -875,7 +868,6 @@ impl Motion { Motion { input, clock: Default::default(), ticking: Default::default(), active: false } } - /// Animation time shown now, redrawing the view every `frame` while `run` and awake. fn elapsed(&mut self, run: bool, frame: std::time::Duration, window: &Window, cx: &mut Context) -> std::time::Duration { let now = Instant::now(); let active = engine::app_active() && window.is_window_active(); @@ -900,9 +892,11 @@ impl Motion { } } -/// The ASCII cloud bank behind the start card, redrawn every `fog::FRAME` on the `Motion` clock; -/// its own view, so windows that observe the `Browser` are not notified. One still frame while -/// motion is reduced or the theme asks for it; none when the theme turns it off. +/// The ASCII cloud bank behind the start card, redrawn every `fog::FRAME`; its own view, so +/// windows that observe the `Browser` are not notified. One still frame while motion is reduced +/// or the theme asks for it; none when the theme turns it off. Paused unless its window is the +/// active one of the active app, so a frame redraws one window only, and held after +/// `effects::IDLE` without input. pub struct Fog { pub(crate) reduce: bool, /// The window's width left of the content area, which the fog does not cover. @@ -976,8 +970,8 @@ fn start_shield(level: shield::ShieldLevel) -> Stateful { const SEARCH_ROW: f32 = 54.; /// The theme's search bar effect behind the start and command card (`browser_core::effects`), -/// redrawn at `effects::FPS` on the `Motion` clock; its own view, like `Fog`. One still frame -/// while motion is reduced. +/// redrawn at `effects::FPS` while its window is the active one of the active app; its own view, +/// like `Fog`, and held like it. One still frame while motion is reduced. pub struct SearchFx { pub(crate) reduce: bool, motion: Motion, diff --git a/crates/app/src/library.rs b/crates/app/src/library.rs index 2ebdfa9d..95a5e3c9 100644 --- a/crates/app/src/library.rs +++ b/crates/app/src/library.rs @@ -353,12 +353,8 @@ impl LibraryWindow { fn sample_on_memory_page(&self, cx: &mut Context) { if self.page == Page::Memory { - self.browser - .update(cx, |b, cx| { - b.sample_processes(); - cx.notify(); - }) - .ok(); + self.browser.update(cx, |b, _| b.sample_processes()).ok(); + cx.notify(); } } diff --git a/crates/app/src/shared.rs b/crates/app/src/shared.rs index 37171633..24e0ff3a 100644 --- a/crates/app/src/shared.rs +++ b/crates/app/src/shared.rs @@ -242,13 +242,19 @@ pub(crate) fn start(cx: &mut App) -> bool { }) .detach(); cx.spawn(async move |cx| { + let mut was_active = true; loop { cx.background_executor().timer(MINUTE).await; let ticked = cx.update(|cx| { + let mut closed = false; each(cx, |b, window, cx| { - b.sleep_idle_tabs(cx); + closed |= b.sleep_idle_tabs(cx); b.follow_schedule(window, cx); }); + let active = engine::app_active(); + if engine::lifecycle::release_memory(closed, std::mem::replace(&mut was_active, active), active) { + platform::memory::release_free(); + } #[cfg(any(feature = "chromium", windows))] count_chromium_blocks(&self::core(cx)); }); diff --git a/crates/app/src/tabs.rs b/crates/app/src/tabs.rs index b37e9b22..b3ffccec 100644 --- a/crates/app/src/tabs.rs +++ b/crates/app/src/tabs.rs @@ -210,11 +210,13 @@ impl Browser { /// Keeps `seen` even when sleeping is Never, since the heavy marker ranks by it. Unless sleeping /// is Never, background tabs over their window's equal part of the memory budget sleep too, the /// heaviest first; pinned tabs only for the budget, once unused for `PINNED_IDLE`. - pub(crate) fn sleep_idle_tabs(&mut self, cx: &mut Context) { + pub(crate) fn sleep_idle_tabs(&mut self, cx: &mut Context) -> bool { // Short of memory, a tab left for five minutes sleeps; the web processes are what holds the memory. let max_idle = browser_core::settings::max_idle(crate::prefs::sleep_after(&self.core.disk), platform::memory::pressure()); let (now, keys, heavy) = (Instant::now(), self.views.keys().copied().collect::>(), self.heavy.clone()); + let seen = self.seen.len(); self.seen.retain(|k, _| keys.contains(k)); + let closed = self.seen.len() < seen; self.typed_in.retain(|k| keys.contains(k)); let mut background = Vec::new(); for key in keys { @@ -249,6 +251,7 @@ impl Browser { if self.heavy != heavy { cx.notify(); } + closed } /// Asks each awake background tab, in every space for the memory budget, whether it is playing, diff --git a/crates/browser-core/src/effects.rs b/crates/browser-core/src/effects.rs index f9153e1b..1d357e8c 100644 --- a/crates/browser-core/src/effects.rs +++ b/crates/browser-core/src/effects.rs @@ -4,21 +4,17 @@ pub const STILL: f32 = 0.4; /// Frames per second the shells request while an effect is on screen in the active window. pub const FPS: f32 = 24.; -/// Time without input in a window after which its start page animations hold their frame. pub const IDLE: std::time::Duration = std::time::Duration::from_secs(60); -/// Whether a start page animation keeps moving `since_input` after its window's last input. pub fn awake(since_input: std::time::Duration) -> bool { since_input < IDLE } -/// Whether a pointer at `to`, last counted at `from`, has moved for `awake`: AppKit repeats the -/// moves of a resting pointer a point apart, which must not keep an animation running. +const APPKIT_RESTING_POINTER_JITTER: f32 = 4.; + pub fn moved(from: (f32, f32), to: (f32, f32)) -> bool { - (from.0 - to.0).abs() + (from.1 - to.1).abs() >= 4. + (from.0 - to.0).abs() + (from.1 - to.1).abs() >= APPKIT_RESTING_POINTER_JITTER } -/// Time a start page animation has run, counted only between consecutive awake ticks, so a tick -/// after a pause or an idle spell adds nothing and the frame resumes where it was held. #[derive(Default)] pub struct Clock { held: std::time::Duration, @@ -26,7 +22,6 @@ pub struct Clock { } impl Clock { - /// The time shown at `now` while `awake`; `None` while not, when the clock holds `held`. pub fn tick(&mut self, now: std::time::Instant, awake: bool) -> Option { if !awake { self.last = None; diff --git a/crates/engine/src/host_windows.rs b/crates/engine/src/host_windows.rs index 6411d34b..899ddce8 100644 --- a/crates/engine/src/host_windows.rs +++ b/crates/engine/src/host_windows.rs @@ -59,6 +59,8 @@ impl Host { unsafe { SetFocus(self.hwnd) }; } + pub fn double_buffer(&self) {} + /// GPUI's pop-up windows have no frame on Windows. pub fn strip_frame(&self) {} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b654d850..afd37614 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -18,6 +18,8 @@ pub mod request_filter; pub mod startup; pub mod tarn_ext; pub mod translation; +#[cfg(target_os = "linux")] +pub mod trim; pub mod view_policy; #[cfg(target_os = "macos")] diff --git a/crates/engine/src/lifecycle.rs b/crates/engine/src/lifecycle.rs index b57ddfc1..470f3746 100644 --- a/crates/engine/src/lifecycle.rs +++ b/crates/engine/src/lifecycle.rs @@ -123,6 +123,10 @@ pub fn over_budget(awake: impl IntoIterator, sleep } +pub fn release_memory(closed: bool, was_active: bool, active: bool) -> bool { + closed || (was_active && !active) +} + /// How long the shown page may leave a ping unanswered before the shell offers Wait or Reload. pub const HANG_AFTER: Duration = Duration::from_secs(8); /// How often the shell pings the shown page with `page_scripts::PING`, which the page's own busy @@ -171,7 +175,6 @@ impl Hang { (now.saturating_duration_since(from) >= HANG_AFTER).then_some(self.tab).flatten() } - /// Whether the shown tab `active` is the hung one. pub fn hung_on(&self, active: Option, now: Instant) -> bool { active.is_some() && self.hung(now) == active } @@ -333,4 +336,12 @@ mod tests { assert_eq!(lc.live().collect::>(), [3, 2, 1]); assert_eq!(lc.activate(2), [1]); } + + #[test] + fn memory_is_released_after_closing_tabs_and_once_on_leaving_the_front() { + assert!(super::release_memory(true, true, true)); + assert!(super::release_memory(false, true, false)); + assert!(!super::release_memory(false, false, false), "once per stay in the background"); + assert!(!super::release_memory(false, true, true)); + } } diff --git a/crates/engine/src/trim.rs b/crates/engine/src/trim.rs new file mode 100644 index 00000000..7fcf7411 --- /dev/null +++ b/crates/engine/src/trim.rs @@ -0,0 +1,10 @@ +pub fn release_free() { + #[cfg(target_env = "gnu")] + { + unsafe extern "C" { + fn malloc_trim(pad: usize) -> std::ffi::c_int; + } + // SAFETY: glibc's malloc_trim only returns free pages to the system and may be called from any thread. + unsafe { malloc_trim(0) }; + } +} diff --git a/crates/engine/src/webview.rs b/crates/engine/src/webview.rs index b043aa6a..bb3fdc8b 100644 --- a/crates/engine/src/webview.rs +++ b/crates/engine/src/webview.rs @@ -75,6 +75,19 @@ impl Host { Some(Host { view }) } + pub fn double_buffer(&self) { + let Some(layer) = self.view.layer() else { return }; + if layer.respondsToSelector(sel!(setMaximumDrawableCount:)) { + // SAFETY: main thread; the layer answers the selector, which takes an NSUInteger. + let _: () = unsafe { msg_send![&*layer, setMaximumDrawableCount: 2usize] }; + } + if layer.respondsToSelector(sel!(setAllowsNextDrawableTimeout:)) { + // SAFETY: as above; with a timeout GPUI skips a frame instead of blocking the main + // thread while both drawables are still in use. + let _: () = unsafe { msg_send![&*layer, setAllowsNextDrawableTimeout: true] }; + } + } + /// Gives keyboard focus back to the shell view, e.g. when the command bar opens. pub fn focus(&self) { if let Some(window) = self.view.window() { diff --git a/crates/store/src/db.rs b/crates/store/src/db.rs index 3f59a754..3cc832c0 100644 --- a/crates/store/src/db.rs +++ b/crates/store/src/db.rs @@ -467,7 +467,6 @@ impl Store { self.count_many(profile_id, counter, &[(host, n)]) } - /// `count` for several `(host, n)` pairs in one transaction, pruning once. pub fn count_many(&self, profile_id: Id, counter: Counter, items: &[(Option<&str>, i64)]) -> Result<()> { if items.is_empty() { return Ok(()); diff --git a/docs/port-backlog.md b/docs/port-backlog.md index 608aba56..d819030e 100644 --- a/docs/port-backlog.md +++ b/docs/port-backlog.md @@ -21,6 +21,21 @@ Reference: . ## Open +### Hand freed memory back to the system (2026-11-24) + +What it does: once a minute, after tabs closed or slept, and once when Tarn leaves the front, the +shell returns memory it freed to the system, so it holds less while idle. +Shared API: `engine::lifecycle::release_memory(closed, was_active, active)`; macOS calls +`platform::memory::release_free`, Linux `engine::trim::release_free`. +Reference: `crates/app/src/shared.rs` (minute tick), `linux/src/ui.rs` (`SCHEDULE_TICK`). + +- [x] Windows — same code in `crates/app`; the Windows heap decommits free pages itself +- [x] Linux — `malloc_trim` through `engine::trim` +- [ ] iOS — call `malloc_zone_pressure_relief` from the shell's minute tick or memory warning in + `mobile/app` +- [ ] Android — no allocator call needed beyond `onTrimMemory`; wire the decision into + `mobile/android` once the shell has a minute tick + ### Client certificate picker (2026-11-23) What it does: when the page's own site asks for a TLS client certificate, a tab-modal prompt lists diff --git a/docs/windows-plan.md b/docs/windows-plan.md index 0231dd68..edac38df 100644 --- a/docs/windows-plan.md +++ b/docs/windows-plan.md @@ -354,6 +354,9 @@ If item 1 fails, the fallback is a sidebar in its own WebView2 with the stricter - **Hung pages:** the hung-page card's Reload builds a new view; Chromium may place it in the same renderer process as the hung page when the site matches, and CEF offers no call to end one view's renderer, so such a page can stay hung until it lets go. +- **Window buffers:** on macOS a browser window keeps two Metal drawables instead of GPUI's three + (`Host::double_buffer`). GPUI's DXGI swap chain is created with three buffers and resized with + the same count, so a Windows window keeps three until GPUI lets the count be set. - **AppContainer:** may not be feasible with WebView2 and GPUI's DirectX device; then S12 is weaker on Windows than on macOS. - **Request filtering cost:** `WebResourceRequested` for every request is slower than compiled diff --git a/linux/src/browser.rs b/linux/src/browser.rs index 49918164..a6667a2d 100644 --- a/linux/src/browser.rs +++ b/linux/src/browser.rs @@ -149,7 +149,6 @@ pub struct Browser { pub processes: HashMap, pub samples: crate::memory::Samples, pub used: HashMap, - /// The heavy tabs the snapshot last showed. pub heavy_shown: HashSet, pub playing: HashSet, pub player: browser_core::media::Player, diff --git a/linux/src/browser/tab_actions.rs b/linux/src/browser/tab_actions.rs index 6558683d..1688cbe6 100644 --- a/linux/src/browser/tab_actions.rs +++ b/linux/src/browser/tab_actions.rs @@ -62,8 +62,7 @@ impl Browser { self.model.reload_space(&self.core); } - /// Pings the shown page, as `engine::lifecycle::Hang` asks, every `PING_EVERY`; while the app - /// is not `active` nothing is pinged and an unanswered ping is forgotten. + /// Pings the shown page, as `engine::lifecycle::Hang` asks, every `PING_EVERY` while `active`. pub fn ping_page(&mut self, now: std::time::Instant, active: bool) { match self.model.active.filter(|_| active) { Some(key) if self.hang.ping(key, now) => self.outbox.push((key, "ping", serde_json::json!({ "seq": 0 }))), diff --git a/linux/src/snapshot.rs b/linux/src/snapshot.rs index 064d7df6..9f88e171 100644 --- a/linux/src/snapshot.rs +++ b/linux/src/snapshot.rs @@ -445,9 +445,13 @@ fn peek_item(b: &Browser) -> Option { Some(PeekItem { view, tab, title: browser_core::text::bounded_title(&peek.title), host, insecure }) } +#[cfg(test)] pub fn snapshot(b: &Browser, web_shown: bool) -> Snapshot { + snapshot_with(b, web_shown, &b.heavy_tabs()) +} + +pub fn snapshot_with(b: &Browser, web_shown: bool, heavy: &HashSet) -> Snapshot { let key = b.model.active; - let heavy = b.heavy_tabs(); let page = b.active_page().cloned().unwrap_or_default(); let host = b.site_host().unwrap_or_default(); let profile_id = b.model.profile().map(|p| p.1); @@ -479,10 +483,10 @@ pub fn snapshot(b: &Browser, web_shown: bool) -> Snapshot { tab: key.is_some(), secure: !page.url.starts_with("http:"), private, - rows: rows_with(b, &heavy), - strip: strip_rows(b, &heavy), + rows: rows_with(b, heavy), + strip: strip_rows(b, heavy), tabs_top: b.tabs_on_top(), - tiles: tiles_with(b, &heavy), + tiles: tiles_with(b, heavy), views: views(b, web_shown && !blank), split: split.filter(|_| web_shown).map(|s| split_view(b, s)), url: page.url.clone(), diff --git a/linux/src/ui.rs b/linux/src/ui.rs index 7433e59a..0a7d3ecb 100644 --- a/linux/src/ui.rs +++ b/linux/src/ui.rs @@ -65,6 +65,10 @@ const LIST_WIDTH: f32 = SIDEBAR_WIDTH - 2. - 16.; use crate::webview; const PLACEMENT: &str = "linux.window_placement"; +thread_local! { + static WAS_ACTIVE: Cell = const { Cell::new(true) }; +} + const SCHEDULE_TICK: std::time::Duration = std::time::Duration::from_secs(60); const SAMPLE_TICK: std::time::Duration = std::time::Duration::from_secs(5); const RETIRE_DELAY: std::time::Duration = std::time::Duration::from_secs(3); @@ -254,8 +258,8 @@ fn act_dyn(ui: Ui, f: &mut dyn FnMut(&mut Browser), rebuild: bool) { let groups = std::mem::take(&mut b.forgotten_groups); let regrouped = b.regrouped_space.take(); let shown = shown && b.reader.as_ref().is_none_or(|r| b.model.active != Some(r.key)) && b.active_json().is_none(); - let snap = snapshot::snapshot(b, shown); b.heavy_shown = b.heavy_tabs(); + let snap = snapshot::snapshot_with(b, shown, &b.heavy_shown); if ui.snap.with_untracked(|s| s.notice != snap.notice || s.prompt != snap.prompt || s.error != snap.error) { b.settle_downloads(); } @@ -334,7 +338,6 @@ fn send_commands(ui: Ui, commands: Vec<(TabKey, &'static str, serde_json::Value) } } -/// Pings the shown page while the app is in front; the snapshot is rebuilt only when the hung-page card appears or goes. fn ping(ui: Ui) { let active = untracked(lifecycle) == nsh_core::platform::Lifecycle::Active; let sent = BROWSERS.with_borrow_mut(|windows| { @@ -349,7 +352,6 @@ fn ping(ui: Ui) { } } -/// A page's answer to `ping`; the snapshot is rebuilt only when the hung-page card goes. fn pong(ui: Ui, key: TabKey, data: &serde_json::Value) { let hung = BROWSERS.with_borrow_mut(|windows| { let b = windows.get_mut(&ui.window)?; @@ -361,7 +363,6 @@ fn pong(ui: Ui, key: TabKey, data: &serde_json::Value) { } } -/// Samples the page processes; the snapshot is rebuilt only when the heavy tabs change or the Memory panel shows the costs. fn sample(ui: Ui) { let changed = BROWSERS.with_borrow_mut(|windows| { let b = windows.get_mut(&ui.window)?; @@ -3043,12 +3044,18 @@ fn browser_window(ui: Ui) -> AnyElement { if read(ui, Browser::devtools_on) == Some(true) { devtools::refresh_servers(ui); } + let live_before = Cell::new(0); drop(set_interval(SCHEDULE_TICK, move || { let windows = WINDOWS.with_borrow(|windows| windows.len()); + let active = untracked(lifecycle) == nsh_core::platform::Lifecycle::Active; act_quietly(ui, |b| { b.schedule_tick(); b.idle_tick(windows); - }) + }); + let live = read(ui, |b| b.model.lifecycle.live().count()).unwrap_or(0); + if engine::lifecycle::release_memory(live < live_before.replace(live), WAS_ACTIVE.replace(active), active) { + engine::trim::release_free(); + } })); drop(set_interval(engine::lifecycle::PING_EVERY, move || ping(ui))); drop(set_interval(SAMPLE_TICK, move || { diff --git a/mobile/app/src/shell.rs b/mobile/app/src/shell.rs index 62468bce..41d45dc4 100644 --- a/mobile/app/src/shell.rs +++ b/mobile/app/src/shell.rs @@ -988,8 +988,7 @@ impl Shell { self.model.active.map(|k| vec![Effect::Command(k, name, args)]).unwrap_or_default() } - /// Pings the shown page, as `engine::lifecycle::Hang` asks, every `PING_EVERY`; while the app - /// is not `active` nothing is pinged and an unanswered ping is forgotten. + /// Pings the shown page, as `engine::lifecycle::Hang` asks, every `PING_EVERY` while `active`. pub fn ping_page(&mut self, now: std::time::Instant, active: bool) -> Vec { match self.model.active.filter(|_| active) { Some(key) if self.hang.ping(key, now) => vec![Effect::Command(key, "ping", serde_json::json!({ "seq": 0 }))], diff --git a/nsh-shared/src/motion.rs b/nsh-shared/src/motion.rs index f64ec51c..ae25ccfc 100644 --- a/nsh-shared/src/motion.rs +++ b/nsh-shared/src/motion.rs @@ -15,7 +15,6 @@ static TOUCHED: AtomicU64 = AtomicU64::new(0); #[derive(Clone, Copy, Default)] struct Woke; -/// Counts an input; the first after `effects::IDLE` wakes the animations that went to sleep. pub fn touched() { let asleep = !browser_core::effects::awake(since_input()); TOUCHED.store(EPOCH.elapsed().as_millis() as u64, Ordering::Relaxed); @@ -72,9 +71,6 @@ pub fn animates(reduced: bool, lifecycle: Lifecycle) -> bool { !reduced && lifecycle == Lifecycle::Active } -/// Calls `tick` with the time the animation has run, every `period` while the app is active, -/// `running` and the user has been active within `effects::IDLE`. The timer stops when the user -/// goes idle and starts again at the next input, so an idle start page wakes nothing. pub fn while_active(period: Duration, running: impl Fn() -> bool + 'static, tick: impl Fn(Duration) + Clone + 'static) { let timer: Rc>>> = Rc::default(); let clock = Rc::new(RefCell::new(browser_core::effects::Clock::default()));