diff --git a/Plans/02 Verify/S005-gl-painters.md b/Plans/02 Verify/S005-gl-painters.md index 1708f30..b30bcfb 100644 --- a/Plans/02 Verify/S005-gl-painters.md +++ b/Plans/02 Verify/S005-gl-painters.md @@ -15,9 +15,9 @@ Settle the riskiest design question (REVIEW.md: several painters on one GL conte - [x] Run it under software GL; check every screenshot shows the right tab with no garbage, black frames or stale content - [x] Check GL state isolation: egui chrome still draws right after page blits (scissor, blend, bound framebuffer); fix by saving/restoring state around `render_to_parent_callback` if needed - [x] Measure memory and frame time with 5 and 15 tabs (log `perf.rs` numbers); check idle tabs release painters per the perf settings -- [ ] Decision: keep per-tab painters, or implement the one-painter-per-window fallback (PiP then reuses a dedicated painter); implement it if needed -- [ ] Run `painters.txt` and `launch.txt` green; record the decision in `docs/DECISIONS.md` and remove the item from `docs/REVIEW.md` -- [ ] PROGRESS entry, INDEX line, commit `S005: …` and push +- [x] Decision: keep per-tab painters, or implement the one-painter-per-window fallback (PiP then reuses a dedicated painter); implement it if needed +- [x] Run `painters.txt` and `launch.txt` green; record the decision in `docs/DECISIONS.md` and remove the item from `docs/REVIEW.md` +- [x] PROGRESS entry, INDEX line, commit `S005: …` and push ## End criteria - `tools/smoke.sh tests/smoke/painters.txt ` exits 0; screenshots checked by eye (list them in PROGRESS). diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 270cdcf..1a6fcb4 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -11,7 +11,7 @@ Tracker: https://claude.ai/artifact/9AD7fPfwJ4ASFzVTJGKU4h - [x] [S004 — Phase 1 review with the user](01%20First%20build/S004-phase1-review.md) · Sonnet medium · 🧑 ## 02 Verify -- [ ] [S005 — Per-tab painters on one GL context](02%20Verify/S005-gl-painters.md) · Opus high +- [x] [S005 — Per-tab painters on one GL context](02%20Verify/S005-gl-painters.md) · Opus high - [ ] [S006 — Browser basics pass](02%20Verify/S006-verify-basics.md) · Opus medium - [ ] [S007 — Network pass](02%20Verify/S007-verify-network.md) · Opus medium - [ ] [S008 — Stores and pages pass](02%20Verify/S008-verify-stores.md) · Sonnet high diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 84b587e..fb9ee6a 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -50,16 +50,21 @@ src/ui/ egui: chrome (tab strip, toolbar, omnibox, bookmarks bar), me `BrowserWindow`s. Window kinds: Normal, App (site installed as app: no toolbar), Pip (always on top, one video). - Incognito is a second process (`nacre --incognito`) with a temporary profile that is deleted on exit, because Servo 0.7 has no per-WebView private mode. -- Rendering: per window one `WindowRenderingContext` (surfman). Each tab gets its own - `OffscreenRenderingContext` made from it, so Servo gives each tab its own painter (WebRender instance). - egui (egui_glow on the window context's glow API) draws the chrome and a paint callback blits the tab's +- Rendering (D-008): per window one `WindowRenderingContext` (surfman) and one `OffscreenRenderingContext` + made from it (`BrowserWindow::page_context`), shared by all the window's tabs, so Servo makes one painter + (WebRender instance) per window. Only the active tab's web view is shown; `painted_tab` records whose page is + in the framebuffer, so a tab switch forces a repaint. While no tab shows a page (internal page, PiP + placeholder) `paint_unshown` still paints, because Servo keeps reporting the frame until it is painted. + egui (egui_glow on the window context's glow API) draws the chrome and a paint callback blits the page framebuffer into the page rectangle (`render_to_parent_callback`). glow is 0.17 on both sides. - Why per tab and not per window like servoshell: Servo 0.7 always draws a painter's visible webviews at the - origin at full size, so only separate painters allow picture-in-picture (the PiP tab's context is resized to - the PiP window, read back with `read_to_image` and shown as a texture in the PiP window) and split view. - Cost: a WebRender instance per tab. Kept in check by `thread_pool_webrender_workers_max = 2` and by unloading - idle tabs (perf settings). If shared-GL painters misbehave at first build, fall back to one per window and - drop split view; PiP then becomes "reopen the video in the PiP window at the same time". + Why not one painter per tab: each painter is a full WebRender instance (~56 MB and ~6 threads; 15 tabs took + 1128 MB vs 341 MB shared, same frame time; S005). Servo 0.7 draws a painter's visible web views at the origin + at full size, so one shared painter rules out split view. + Picture in picture: `pip.take` pauses the tab's video and returns its time; a second web view (`Tab::pip`) + with a context and painter of its own loads the same URL at the PiP window's size, `pip.start` seeks and + plays it once loaded, and its frames are read back (`read_to_image`) into the PiP window. On exit `pip.state` + hands the time back to the tab (`pip.resume`). The page is reloaded, so its state (logins aside) is lost. + Servo 0.7 freezes a playing video that is seeked and then `play()`ed: pause before seeking. - Servo callbacks arrive on the main thread inside `servo.spin_event_loop()`. The delegate (`hub::Hub`) answers the synchronous ones right there (resource loads -> ad blocker, navigation requests -> HTTPS-only / downloads / external schemes) and queues the rest as `Event`s that `App` drains after each spin. @@ -128,6 +133,8 @@ picture-in-picture, extensions, password capture, printing. ## Engine limits (shown as unavailable, not hidden) +- Picture in picture reloads the page in its own web view (one painter per window, D-008): page state is + lost and the video restarts loading before it jumps to the same time. - Widevine / DRM video: Servo has no EME. The setting stays, marked "not available with this engine". - Chrome extensions: not possible. Replaced by user scripts and user styles (Apps -> Scripts). - Hardware acceleration switch: Servo needs GL; "Off" selects software GL (LIBGL_ALWAYS_SOFTWARE) on next start. diff --git a/docs/FEATURES.md b/docs/FEATURES.md index a6a7465..1703a6b 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -97,7 +97,8 @@ managers (AB Download Manager, aria2/Motrix, JDownloader 2, FDM, IDM) with ping ## Media Media button (when playing/always/never), player flyout (art, seek, controls, mute tab/site, PiP), visualizer (cava / simulated / off), spin artwork, Discord Rich Presence (arRPC/Discord, per-site app IDs, browsing activity, -buttons, paused state), picture in picture (own always-on-top window): written. Protected content (Widevine): engine +buttons, paused state): written. Picture in picture (own always-on-top window; reloads the page in a web view +of its own and seeks the video, page state lost, D-008): verified on Xvfb (S005). Protected content (Widevine): engine limit, shown as unavailable. ## Passwords and autofill diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 9f9be83..b3a761d 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -41,6 +41,19 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Not done: no fixes (none trivial); the user's session tried only a short run. - Later: R1-05/R1-06 feed the Phase 4 redesign (look of old Python Nacre, animations). +## S005 — Painters (2026-11-11) +- Done: D-008 one painter per window (`window.rs` `page_context`/`painted_tab`/`paint_unshown`); PiP = second web + view with its own painter that reloads the page and seeks (`Tab::pip`, `actions.rs` enter/exit_pip, PIP_JS + take/start/state/resume). Fixed: egui destroy in the wrong GL context (chrome blank after PiP); PiP video frozen + (Servo 0.7 freezes a playing video seeked then play()ed: `pip.start` pauses first). +- Measured (llvmpipe, 15 tabs): per-tab painters 1128 MB / 141 threads vs shared 349 MB / 71 threads; ~56 MB per + painter; frame median ~13 ms either way. glibc keeps freed memory after discard. +- Verified: painters.txt, launch.txt, painters-perf.txt exit 0; 30 unit tests green. Shots checked by eye + (target/smoke/painters-final): s1-s6 tabs, r1-r3 resize, p1 placeholder, p2/p4 PiP playing (1.33 s -> 3.40 s), + p3 tab 1, p5 tab 5 resumed, c1-c3 closes. +- Not done: real-GPU check (S010). PiP loses page state (in DESIGN engine limits). Split view now impossible. +- Later: status field `painters` counts web views, not painters; rename. malloc_trim after discard. + ## Later - Reader mode, split view, translate, real gamepad rumble (D-002: not planned for now). - Packaging and first release (D-001: plan when the user asks). diff --git a/docs/REVIEW.md b/docs/REVIEW.md index 59180ad..a84607d 100644 --- a/docs/REVIEW.md +++ b/docs/REVIEW.md @@ -13,8 +13,6 @@ Things to check or fix in the review passes before the first build. Remove an it that calls `location.replace()` instead of a 30x. - Google sign-in quirk: the user agent is a global pref; switching it for accounts.google.com affects requests of other tabs made at that moment. -- First build: check that several painters on one GL context (one per tab) render correctly and don't fight over - GL state. Fallback plan is in DESIGN.md. - Settings → Downloads "Save to" and the new tab image picker open rfd dialogs on the main thread, which stalls page rendering while they are open. Move them to `App::spawn` like the other file dialogs. - Autofill fills logins with `evaluate_javascript`, which runs in the top document only: login forms inside diff --git a/src/actions.rs b/src/actions.rs index e3db100..9a6b5a9 100644 --- a/src/actions.rs +++ b/src/actions.rs @@ -663,7 +663,7 @@ impl App { if let Some(win) = self.windows.get(&window) && let Kind::Pip { tab, .. } = win.kind.clone() { - self.eval(tab, inject::call("pip.act", &[action.into(), value.into()])); + self.eval_pip(tab, inject::call("pip.act", &[action.into(), value.into()])); } }, Command::UpdateFilterLists => self.update_filter_lists(0), @@ -2201,6 +2201,8 @@ impl App { // ── picture in picture ──────────────────────────────────────────── + /// Picture in picture (D-008): the tab hands over its video and pauses; a second web view with a painter + /// of its own loads the same page at the PiP window's size and plays the video from the same time. fn enter_pip(&mut self, window: WindowId) { let Some(tab_id) = self.active_tab_id(window) else { return }; let Some((w, i)) = self.find_tab(tab_id) else { return }; @@ -2210,48 +2212,99 @@ impl App { let Some(web) = self.windows[&w].tabs[i].web.as_ref().map(|web| web.webview.clone()) else { return }; let jobs = self.jobs_tx.clone(); let proxy = self.proxy.clone(); - web.evaluate_javascript(inject::call("pip.enter", &[]), move |result| { - let size = match result { + web.evaluate_javascript(inject::call("pip.take", &[]), move |result| { + let video = match result { Ok(servo::JSValue::Object(map)) => { let num = |k: &str| match map.get(k) { Some(servo::JSValue::Number(n)) => *n, _ => 0.0, }; - Some((num("w").max(16.0), num("h").max(9.0))) + let paused = matches!(map.get("paused"), Some(servo::JSValue::Boolean(true))); + Some((num("w").max(16.0), num("h").max(9.0), num("t"), !paused)) }, _ => None, }; let _ = jobs.send(Box::new(move |app: &mut App| { - let Some((vw, vh)) = size else { + let Some((vw, vh, time, play)) = video else { app.shared.toast("There's no video on this page to show in picture in picture"); return; }; let width = 480u32; let height = ((width as f64) * vh / vw).round().clamp(120.0, 900.0) as u32; - if let Some((w, i)) = app.find_tab(tab_id) { - let scale = app.windows[&w].window.scale_factor(); - app.windows.get_mut(&w).expect("found").tabs[i].pip_size = Some(dpi::PhysicalSize::new((width as f64 * scale) as u32, (height as f64 * scale) as u32)); - app.windows.get_mut(&w).expect("found").sync_webviews(); - app.window_requests.push(WindowRequest { kind: Kind::Pip { window: w, tab: tab_id }, tabs: Vec::new(), active: 0, size: Some((width, height)) }); - app.redraw(w); + let Some((w, i)) = app.find_tab(tab_id) else { return }; + let Ok(url) = Url::parse(&app.windows[&w].tabs[i].url) else { return }; + let scale = app.windows[&w].window.scale_factor(); + let size = dpi::PhysicalSize::new((width as f64 * scale) as u32, (height as f64 * scale) as u32); + let pip = { + let win = &app.windows[&w]; + app.build_webview_in(win, url, win.pip_context(size)) + }; + let win = app.windows.get_mut(&w).expect("found"); + let tab = &mut win.tabs[i]; + tab.pip_size = Some(size); + tab.pip_start = Some((time, play)); + tab.pip = Some(pip); + win.sync_webviews(); + app.window_requests.push(WindowRequest { kind: Kind::Pip { window: w, tab: tab_id }, tabs: Vec::new(), active: 0, size: Some((width, height)) }); + app.redraw(w); + })); + let _ = proxy.send_event(crate::app::AppEvent::Wake); + }); + } + + /// Back from picture in picture: the tab's own video goes on from where the PiP video got to. + pub fn exit_pip(&mut self, source: WindowId, tab_id: u64) { + let Some(win) = self.windows.get_mut(&source) else { return }; + let Some(i) = win.tab_index(tab_id) else { return }; + let tab = &mut win.tabs[i]; + tab.pip_size = None; + tab.pip_start = None; + if let Some(web) = tab.web.as_mut() { + web.dirty = true; + } + let pip = tab.pip.as_ref().map(|p| p.webview.clone()); + win.sync_webviews(); + self.redraw(source); + let Some(pip) = pip else { return }; + pip.hide(); + let jobs = self.jobs_tx.clone(); + let proxy = self.proxy.clone(); + pip.evaluate_javascript(inject::call("pip.state", &[]), move |result| { + let state = match result { + Ok(servo::JSValue::Object(map)) => { + let time = match map.get("t") { + Some(servo::JSValue::Number(n)) => *n, + _ => 0.0, + }; + Some((time, !matches!(map.get("paused"), Some(servo::JSValue::Boolean(true))))) + }, + _ => None, + }; + // Drop the PiP web view (and its painter) outside of Servo's callback. + let _ = jobs.send(Box::new(move |app: &mut App| { + let Some((w, i)) = app.find_tab(tab_id) else { return }; + let tab = &mut app.windows.get_mut(&w).expect("found").tabs[i]; + if tab.pip_size.is_some() { + return; + } + if let Some(pip) = tab.pip.take() { + app.hub.forget(pip.webview.id()); + } + if let Some((time, play)) = state { + app.eval(tab_id, inject::call("pip.resume", &[time.into(), play.into()])); } })); let _ = proxy.send_event(crate::app::AppEvent::Wake); }); } - pub fn exit_pip(&mut self, source: WindowId, tab_id: u64) { - if let Some(win) = self.windows.get_mut(&source) - && let Some(i) = win.tab_index(tab_id) + /// Run a script in a tab's picture-in-picture web view. + fn eval_pip(&self, tab_id: u64, script: String) { + if let Some((w, i)) = self.find_tab(tab_id) + && let Some(pip) = &self.windows[&w].tabs[i].pip { - win.tabs[i].pip_size = None; - if let Some(web) = win.tabs[i].web.as_mut() { - web.dirty = true; - } - win.sync_webviews(); + pip.webview.evaluate_javascript(script, |_| {}); } - self.eval(tab_id, inject::call("pip.exit", &[])); - self.redraw(source); } // ── saving pages ────────────────────────────────────────────────── diff --git a/src/app.rs b/src/app.rs index dd0a32a..07207a8 100644 --- a/src/app.rs +++ b/src/app.rs @@ -427,7 +427,11 @@ impl App { } pub fn build_webview(&self, win: &BrowserWindow, url: Url) -> Web { - let context = win.new_context(); + self.build_webview_in(win, url, win.new_context()) + } + + /// A web view drawing into `context` (the window's shared page context, or a PiP context). + pub fn build_webview_in(&self, win: &BrowserWindow, url: Url, context: Rc) -> Web { let servo = self.servo.as_ref().expect("Servo is running"); let mut builder = servo::WebViewBuilder::new(servo, context.clone() as Rc).url(url.clone()).hidpi_scale_factor(win.hidpi()).delegate(self.hub.clone()).gamepad_delegate(Rc::new(crate::hub::Gamepads)); if let Some(ucm) = &self.ucm { @@ -656,8 +660,9 @@ impl App { } }, Event::Animating(id, animating) => { - if let Some(tab) = self.tab_mut(id) { - tab.animating = animating; + // A picture-in-picture web view animates for its tab (the tab's own video is paused meanwhile). + if let Some((w, i)) = self.find_webview(id).or_else(|| self.find_pip(id)) { + self.windows.get_mut(&w).expect("found").tabs[i].animating = animating; } }, Event::Navigation(id, request) => self.on_navigation(id, request), @@ -759,6 +764,16 @@ impl App { } fn on_load_status(&mut self, id: WebViewId, status: LoadStatus) { + // The picture-in-picture page loaded: show its video from where the tab left off. + if status == LoadStatus::Complete + && let Some((w, i)) = self.find_pip(id) + { + let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i]; + if let (Some((time, play)), Some(pip)) = (tab.pip_start.take(), tab.pip.as_ref()) { + pip.webview.evaluate_javascript(inject::call("pip.start", &[time.into(), play.into()]), |_| {}); + } + return; + } let Some((w, i)) = self.find_webview(id) else { return }; match status { LoadStatus::Started => { @@ -863,27 +878,40 @@ impl App { win.window.request_redraw(); } + /// The tab whose picture-in-picture web view this is. + fn find_pip(&self, id: WebViewId) -> Option<(WindowId, usize)> { + self.windows.iter().find_map(|(wid, w)| w.tabs.iter().position(|t| t.pip.as_ref().is_some_and(|p| p.webview.id() == id)).map(|i| (*wid, i))) + } + fn on_frame(&mut self, id: WebViewId) { - let Some((w, i)) = self.find_webview(id) else { return }; - let pip_target = { + if let Some((w, i)) = self.find_webview(id) { + // Servo reports a frame for every tab of the window's shared painter and keeps reporting it until + // the painter is painted. let win = self.windows.get_mut(&w).expect("found"); - let tab = &mut win.tabs[i]; - if let Some(web) = tab.web.as_mut() { - web.dirty = true; + let active = win.active; + match win.tabs.get_mut(active).filter(|t| t.page.is_none() && t.pip_size.is_none()).and_then(|t| t.web.as_mut()) { + Some(web) => { + web.dirty = true; + win.needs_redraw = true; + win.window.request_redraw(); + }, + // No tab shows its page (internal page, PiP placeholder): paint anyway so Servo stops asking. + None => win.paint_unshown(i), } - if i == win.active { - win.needs_redraw = true; - win.window.request_redraw(); - } - tab.pip_size.map(|_| tab.id) - }; - // A tab shown in picture-in-picture: paint it now and hand the frame to the PiP window. - if let Some(tab_id) = pip_target { + return; + } + // A picture-in-picture web view: paint it now and hand the frame to the PiP window. + let Some((w, i)) = self.find_pip(id) else { return }; + let tab_id = self.windows[&w].tabs[i].id; + { let source = { let win = self.windows.get_mut(&w).expect("found"); - win.paint_tab(i); + if let Some(pip) = win.tabs[i].pip.as_mut() { + pip.dirty = true; + } + win.paint_pip(i); let tab = &win.tabs[i]; - tab.web.as_ref().map(|web| (web.context.clone(), win.rendering.clone())) + tab.pip.as_ref().map(|web| (web.context.clone(), win.rendering.clone())) }; let pip = self.windows.iter().find(|(_, x)| x.kind == (Kind::Pip { window: w, tab: tab_id })).map(|(id, _)| *id); if let (Some((context, rendering)), Some(pip)) = (source, pip) diff --git a/src/inject.rs b/src/inject.rs index 96a2e4e..8a3478f 100644 --- a/src/inject.rs +++ b/src/inject.rs @@ -257,14 +257,28 @@ const FIND_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.find) re }; })();"#; -/// Picture-in-picture inside the page: the chosen video fills the viewport. +/// Picture-in-picture. The tab's own page hands over its video (`take`, later `resume`); a second web view +/// with its own painter loads the same page and shows only that video (`start`, D-008). const PIP_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.pip) return; + const pick = () => { + const vs = [...document.querySelectorAll('video')].filter(v => v.readyState > 0); + const area = v => v.offsetWidth * v.offsetHeight; + return vs.filter(v => !v.paused).sort((a, b) => area(b) - area(a))[0] || vs.sort((a, b) => area(b) - area(a))[0] || null; + }; window.__nacre.pip = { + take() { const v = pick(); if (!v) return null; window.__nacrePipV = v; + const r = { w: v.videoWidth || 16, h: v.videoHeight || 9, t: v.currentTime, paused: v.paused }; v.pause(); return r; }, + resume(t, play) { const v = window.__nacrePipV; window.__nacrePipV = null; if (!v || !v.isConnected) return; + try { v.currentTime = t; } catch (e) {} if (play) v.play().catch(() => {}); }, + // The page may build its video late (players): keep looking for up to 30 s. + start(t, play, tries) { const pip = window.__nacre.pip; + if (!pip.enter()) { if ((tries || 0) < 150) setTimeout(() => pip.start(t, play, (tries || 0) + 1), 200); return; } + // Servo 0.7 freezes a playing video that is seeked and then play()ed: pause before the seek. + const v = window.__nacrePipV; v.pause(); try { v.currentTime = t; } catch (e) {} + if (play) v.play().catch(() => {}); else v.pause(); }, enter() { - const vs = [...document.querySelectorAll('video')].filter(v => v.readyState > 0); - if (!vs.length) return null; - const area = v => v.offsetWidth * v.offsetHeight; - const v = vs.filter(v => !v.paused).sort((a, b) => area(b) - area(a))[0] || vs.sort((a, b) => area(b) - area(a))[0]; + const v = pick(); + if (!v) return null; window.__nacrePipV = v; v.setAttribute('data-nacre-pip', ''); if (!document.getElementById('__nacre_pip_css')) { const st = document.createElement('style'); st.id = '__nacre_pip_css'; @@ -283,9 +297,7 @@ const PIP_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.pip) retu else if (what === 'skip') v.currentTime = Math.max(0, v.currentTime + arg); else if (what === 'to') v.currentTime = arg; else if (what === 'mute') v.muted = !v.muted; - else if (what === 'vol') { v.volume = Math.min(1, Math.max(0, arg)); v.muted = false; } }, - exit() { const v = window.__nacrePipV; if (v) v.removeAttribute('data-nacre-pip'); - document.documentElement.classList.remove('__nacre_pip'); window.__nacrePipV = null; } + else if (what === 'vol') { v.volume = Math.min(1, Math.max(0, arg)); v.muted = false; } } }; })();"#; diff --git a/src/tabs.rs b/src/tabs.rs index 00f4e2e..06f1786 100644 --- a/src/tabs.rs +++ b/src/tabs.rs @@ -206,6 +206,10 @@ pub struct Tab { pub hidden_elements: u32, /// Shown in a picture-in-picture window at this size (physical pixels). pub pip_size: Option>, + /// The picture-in-picture web view: the same page loaded again with its own painter (D-008). + pub pip: Option, + /// Video time and playing state to start the PiP video at once its page has loaded. + pub pip_start: Option<(f64, bool)>, } impl Tab { @@ -251,6 +255,8 @@ impl Tab { animating: false, hidden_elements: 0, pip_size: None, + pip: None, + pip_start: None, } } diff --git a/src/window.rs b/src/window.rs index 7801074..482d3b3 100644 --- a/src/window.rs +++ b/src/window.rs @@ -36,6 +36,10 @@ pub struct BrowserWindow { pub id: WindowId, pub window: Rc, pub rendering: Rc, + /// The page framebuffer every tab of this window draws into: one painter per window (D-008). + pub page_context: Rc, + /// The tab whose page is in `page_context` now. + pub painted_tab: Option, pub egui: egui_glow::EguiGlow, pub kind: Kind, pub tabs: Vec, @@ -96,11 +100,14 @@ impl BrowserWindow { let rendering = Rc::new(rendering); let _ = rendering.make_current(); let egui = egui_glow::EguiGlow::new(event_loop, rendering.glow_gl_api(), None, Some(window.scale_factor() as f32), true); + let page_context = Rc::new(rendering.offscreen_context(size)); let id = window.id(); Ok(BrowserWindow { id, window: Rc::new(window), rendering, + page_context, + painted_tab: None, egui, kind, tabs: Vec::new(), @@ -159,27 +166,40 @@ impl BrowserWindow { } } - /// A fresh offscreen context for a new tab, sized like the page area. + /// The rendering context for a new tab: the window's shared page framebuffer. Servo makes one painter + /// per context, so all tabs of a window share one painter; only the shown tab is drawn. pub fn new_context(&self) -> Rc { - Rc::new(self.rendering.offscreen_context(self.page_size())) + self.page_context.clone() + } + + /// A context of its own (so a painter of its own) for a picture-in-picture web view. + pub fn pip_context(&self, size: PhysicalSize) -> Rc { + Rc::new(self.rendering.offscreen_context(size)) } pub fn hidpi(&self) -> Scale { Scale::new(self.scale()) } - /// Keep the active tab's web view the size of the page area; show it, hide the others. + /// Keep the active tab's web view the size of the page area; show it, hide the others. A tab in + /// picture-in-picture shows a placeholder here; its PiP web view is kept at the PiP window's size. pub fn sync_webviews(&mut self) { let page_size = self.page_size(); let scale = self.hidpi(); let active = self.active; + let painted = self.painted_tab; for (i, tab) in self.tabs.iter_mut().enumerate() { + if let (Some(pip), Some(size)) = (tab.pip.as_mut(), tab.pip_size) { + if pip.context.size() != size { + pip.webview.resize(size); + pip.dirty = true; + } + pip.webview.show(); + } let Some(web) = tab.web.as_mut() else { continue }; - let showing = (i == active && tab.page.is_none()) || tab.pip_size.is_some(); - let size = tab.pip_size.unwrap_or(page_size); - if showing { - if web.context.size() != size { - web.webview.resize(size); + if i == active && tab.page.is_none() && tab.pip_size.is_none() { + if web.context.size() != page_size { + web.webview.resize(page_size); web.dirty = true; } if web.webview.hidpi_scale_factor() != scale { @@ -188,6 +208,10 @@ impl BrowserWindow { if tab.frozen { tab.frozen = false; } + // The shared framebuffer still holds another tab's page. + if painted != Some(tab.id) { + web.dirty = true; + } web.webview.show(); tab.last_shown = Instant::now(); } else { @@ -196,22 +220,38 @@ impl BrowserWindow { } } - /// Paint the active tab's page into its framebuffer if a new frame is waiting. + /// Paint the active tab's page into the window's page framebuffer if a new frame is waiting. pub fn paint_page(&mut self) { - let active = self.active; - self.paint_tab(active); - } - - /// Paint one tab into its own framebuffer (the active tab, or one shown in picture-in-picture). - pub fn paint_tab(&mut self, index: usize) -> bool { let _ = self.rendering.make_current(); - if let Some(tab) = self.tabs.get_mut(index) - && (tab.page.is_none() || tab.pip_size.is_some()) + if let Some(tab) = self.tabs.get_mut(self.active) + && tab.page.is_none() + && tab.pip_size.is_none() && let Some(web) = tab.web.as_mut() && web.dirty { web.webview.paint(); web.dirty = false; + self.painted_tab = Some(tab.id); + } + } + + /// Paint the shared painter while no tab shows its page (Servo keeps asking until it is painted). + pub fn paint_unshown(&mut self, index: usize) { + let _ = self.rendering.make_current(); + if let Some(web) = self.tabs.get(index).and_then(|t| t.web.as_ref()) { + web.webview.paint(); + } + self.painted_tab = None; + } + + /// Paint a tab's picture-in-picture web view into its own framebuffer. + pub fn paint_pip(&mut self, index: usize) -> bool { + let _ = self.rendering.make_current(); + if let Some(pip) = self.tabs.get_mut(index).and_then(|t| t.pip.as_mut()) + && pip.dirty + { + pip.webview.paint(); + pip.dirty = false; return true; } false