Nacre/src/window.rs
astar76 802a745e78 S005: painter smoke tests; fix chrome blanking after PiP closes
- tests/smoke/painters.txt (5 tabs, switch, resize, PiP, close) and painters-perf.txt (memory, frame
  time, threads with 1/5/15 tabs, idle discard); test pages color.html, video.html, clip.webm.
- selftest: `resize <w> <h>`, `shot <name> pip`, status gets frames (median/max ms), painters, threads.
- Fix: a closing window's egui was destroyed with another window's GL context current, deleting the
  main window's font texture (chrome text/icons blank after PiP). BrowserWindow::destroy() makes its
  own context current first.
- Fix: PiP CSS resets the video's margin (video was shifted down in the PiP frame).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 18:34:37 -06:00

457 lines
20 KiB
Rust

//! A browser window: the winit window, its GL context, egui, and its tabs. This file owns
//! rendering (page framebuffers blitted under the egui chrome) and turning window input into
//! page input. Deciding what input means for the browser (shortcuts, UI) is the app's job.
use std::rc::Rc;
use std::time::Instant;
use dpi::PhysicalSize;
use euclid::{Point2D, Scale};
use servo::{
InputEvent, MouseButton as SMouseButton, MouseButtonAction, MouseButtonEvent, MouseLeftViewportEvent, MouseMoveEvent, OffscreenRenderingContext, RenderingContext, TouchEvent, TouchEventType, TouchId, TouchPointerType, WebView, WebViewPoint, WheelDelta, WheelEvent, WheelMode, WindowRenderingContext,
};
use winit::dpi::{LogicalSize, PhysicalPosition};
use winit::event::{ElementState, MouseButton, MouseScrollDelta, Touch, TouchPhase};
use winit::event_loop::ActiveEventLoop;
use winit::keyboard::ModifiersState;
use winit::raw_window_handle::{HasDisplayHandle, HasWindowHandle};
use winit::window::{CursorIcon, Window, WindowAttributes, WindowId, WindowLevel};
use crate::tabs::Tab;
use crate::ui::WindowUi;
/// Pixels per wheel "line" (the value Servo's own example uses).
const LINE_PX: f64 = 76.0;
#[derive(Clone, Debug, PartialEq)]
pub enum Kind {
Normal,
/// A site installed as an app (no toolbar). The app id.
App(String),
/// Picture-in-picture for a tab of another window.
Pip { window: WindowId, tab: u64 },
}
pub struct BrowserWindow {
pub id: WindowId,
pub window: Rc<Window>,
pub rendering: Rc<WindowRenderingContext>,
pub egui: egui_glow::EguiGlow,
pub kind: Kind,
pub tabs: Vec<Tab>,
pub active: usize,
pub ui: WindowUi,
/// Where the page is drawn, in egui points (set by the UI each frame).
pub page_rect: Option<egui::Rect>,
pub modifiers: ModifiersState,
pub pointer: Option<PhysicalPosition<f64>>,
/// Pointer buttons held down that started on the page (so drags keep going to it).
pub page_grab: u32,
pub page_focused: bool,
pub needs_redraw: bool,
pub ime_enabled: bool,
pub fullscreen: bool,
pub last_input: Instant,
/// Picture-in-picture: the latest frame of the tab being shown.
pub pip_frame: Option<egui::TextureHandle>,
pub pip_size: [u32; 2],
pub focused: bool,
/// Save the next frame to this file (self-test screenshots).
pub shot_request: Option<std::path::PathBuf>,
/// How long the last frames took to draw, in ms (self-test status).
pub frame_times: std::collections::VecDeque<f32>,
}
/// Choose the winit window attributes for a kind of window.
pub fn attributes(kind: &Kind, title: &str, size: (u32, u32), decorated: bool, app_class: Option<&str>) -> WindowAttributes {
let mut attrs = Window::default_attributes().with_title(title).with_inner_size(LogicalSize::new(size.0.max(320), size.1.max(240))).with_min_inner_size(LogicalSize::new(320, 240)).with_decorations(decorated);
if let Kind::Pip { .. } = kind {
attrs = attrs.with_window_level(WindowLevel::AlwaysOnTop).with_min_inner_size(LogicalSize::new(200, 120));
}
#[cfg(target_os = "linux")]
{
let class = app_class.unwrap_or("nacre");
{
use winit::platform::wayland::WindowAttributesExtWayland;
attrs = WindowAttributesExtWayland::with_name(attrs, class, class);
}
{
use winit::platform::x11::WindowAttributesExtX11;
attrs = WindowAttributesExtX11::with_name(attrs, class, class);
}
}
#[cfg(not(target_os = "linux"))]
let _ = app_class;
attrs
}
impl BrowserWindow {
pub fn create(event_loop: &ActiveEventLoop, kind: Kind, attrs: WindowAttributes) -> Result<BrowserWindow, String> {
let window = event_loop.create_window(attrs).map_err(|e| format!("can't open a window: {e}"))?;
let size = window.inner_size();
let size = PhysicalSize::new(size.width.max(1), size.height.max(1));
let display = window.display_handle().map_err(|e| e.to_string())?;
let handle = window.window_handle().map_err(|e| e.to_string())?;
let rendering = WindowRenderingContext::new(display, handle, size).map_err(|e| format!("can't set up OpenGL for the window ({e:?}); try LIBGL_ALWAYS_SOFTWARE=1"))?;
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 id = window.id();
Ok(BrowserWindow {
id,
window: Rc::new(window),
rendering,
egui,
kind,
tabs: Vec::new(),
active: 0,
ui: WindowUi::default(),
page_rect: None,
modifiers: ModifiersState::empty(),
pointer: None,
page_grab: 0,
page_focused: false,
needs_redraw: true,
ime_enabled: false,
fullscreen: false,
last_input: Instant::now(),
pip_frame: None,
pip_size: [0, 0],
focused: true,
shot_request: None,
frame_times: Default::default(),
})
}
pub fn scale(&self) -> f32 {
self.window.scale_factor() as f32
}
pub fn tab(&self) -> Option<&Tab> {
self.tabs.get(self.active)
}
pub fn tab_mut(&mut self) -> Option<&mut Tab> {
self.tabs.get_mut(self.active)
}
pub fn tab_index(&self, id: u64) -> Option<usize> {
self.tabs.iter().position(|t| t.id == id)
}
pub fn tab_by_webview(&self, webview: servo::WebViewId) -> Option<usize> {
self.tabs.iter().position(|t| t.webview_id() == Some(webview))
}
pub fn active_webview(&self) -> Option<&WebView> {
self.tab().filter(|t| t.page.is_none()).and_then(Tab::webview)
}
/// Size of the page area in physical pixels (at least 1x1).
pub fn page_size(&self) -> PhysicalSize<u32> {
let scale = self.egui.egui_ctx.pixels_per_point();
match self.page_rect {
Some(r) => PhysicalSize::new(((r.width() * scale).round() as u32).max(1), ((r.height() * scale).round() as u32).max(1)),
None => {
let s = self.window.inner_size();
PhysicalSize::new(s.width.max(1), s.height.saturating_sub((96.0 * scale) as u32).max(1))
},
}
}
/// A fresh offscreen context for a new tab, sized like the page area.
pub fn new_context(&self) -> Rc<OffscreenRenderingContext> {
Rc::new(self.rendering.offscreen_context(self.page_size()))
}
pub fn hidpi(&self) -> Scale<f32, servo::DeviceIndependentPixel, servo::DevicePixel> {
Scale::new(self.scale())
}
/// Keep the active tab's web view the size of the page area; show it, hide the others.
pub fn sync_webviews(&mut self) {
let page_size = self.page_size();
let scale = self.hidpi();
let active = self.active;
for (i, tab) in self.tabs.iter_mut().enumerate() {
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);
web.dirty = true;
}
if web.webview.hidpi_scale_factor() != scale {
web.webview.set_hidpi_scale_factor(scale);
}
if tab.frozen {
tab.frozen = false;
}
web.webview.show();
tab.last_shown = Instant::now();
} else {
web.webview.hide();
}
}
}
/// Paint the active tab's page into its 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())
&& let Some(web) = tab.web.as_mut()
&& web.dirty
{
web.webview.paint();
web.dirty = false;
return true;
}
false
}
/// Draw the egui output to the window and present it.
pub fn present(&mut self, clear: egui::Color32) {
let _ = self.rendering.make_current();
self.rendering.prepare_for_rendering();
let size = self.window.inner_size();
let rgba = egui::Rgba::from(clear);
egui_glow::painter::clear(self.egui.painter.gl(), [size.width, size.height], [rgba.r(), rgba.g(), rgba.b(), 1.0]);
self.egui.paint(&self.window);
if let Some(path) = self.shot_request.take() {
let rect = servo::DeviceIntRect::from_origin_and_size(Point2D::new(0, 0), euclid::Size2D::new(size.width as i32, size.height as i32));
match self.rendering.read_to_image(rect) {
Some(image) => {
if let Err(error) = image.save(&path) {
log::error!("screenshot {}: {error}", path.display());
}
},
None => log::error!("screenshot {}: the window couldn't be read", path.display()),
}
}
self.rendering.present();
}
/// Free egui's GL objects. Its texture and buffer ids are only valid in this window's context, so make
/// it current first: deleting them while another window's context is current deletes that window's.
pub fn destroy(&mut self) {
let _ = self.rendering.make_current();
self.egui.destroy();
}
pub fn resized(&mut self, size: PhysicalSize<u32>) {
if size.width == 0 || size.height == 0 {
return;
}
let _ = self.rendering.make_current();
self.rendering.resize(size);
self.needs_redraw = true;
}
/// The pointer position relative to the page, in device pixels, if it is over the page.
pub fn page_point(&self, pos: PhysicalPosition<f64>) -> Option<servo::DevicePoint> {
let rect = self.page_rect?;
let scale = self.egui.egui_ctx.pixels_per_point() as f64;
let (x, y) = (pos.x - rect.min.x as f64 * scale, pos.y - rect.min.y as f64 * scale);
let (w, h) = (rect.width() as f64 * scale, rect.height() as f64 * scale);
(x >= 0.0 && y >= 0.0 && x < w && y < h).then(|| servo::DevicePoint::new(x as f32, y as f32))
}
/// Like `page_point` but clamped, for drags that leave the page.
pub fn page_point_clamped(&self, pos: PhysicalPosition<f64>) -> Option<servo::DevicePoint> {
let rect = self.page_rect?;
let scale = self.egui.egui_ctx.pixels_per_point() as f64;
let x = (pos.x - rect.min.x as f64 * scale).clamp(0.0, rect.width() as f64 * scale - 1.0);
let y = (pos.y - rect.min.y as f64 * scale).clamp(0.0, rect.height() as f64 * scale - 1.0);
Some(servo::DevicePoint::new(x as f32, y as f32))
}
pub fn send_mouse_move(&mut self, pos: PhysicalPosition<f64>) -> bool {
let point = if self.page_grab > 0 { self.page_point_clamped(pos) } else { self.page_point(pos) };
let Some(webview) = self.active_webview() else { return false };
match point {
Some(p) => {
webview.notify_input_event(InputEvent::MouseMove(MouseMoveEvent::new(WebViewPoint::Device(p))));
true
},
None => {
webview.notify_input_event(InputEvent::MouseLeftViewport(MouseLeftViewportEvent { focus_moving_to_another_iframe: false }));
false
},
}
}
pub fn send_mouse_button(&mut self, state: ElementState, button: MouseButton) -> bool {
let Some(pos) = self.pointer else { return false };
let point = if self.page_grab > 0 && state == ElementState::Released { self.page_point_clamped(pos) } else { self.page_point(pos) };
let Some(point) = point else { return false };
let button = match button {
MouseButton::Left => SMouseButton::Primary,
MouseButton::Right => SMouseButton::Secondary,
MouseButton::Middle => SMouseButton::Auxiliary,
MouseButton::Back => SMouseButton::Back,
MouseButton::Forward => SMouseButton::Forward,
MouseButton::Other(n) => SMouseButton::Other(n),
};
let action = if state == ElementState::Pressed { MouseButtonAction::Down } else { MouseButtonAction::Up };
if state == ElementState::Pressed {
self.page_grab += 1;
self.page_focused = true;
} else {
self.page_grab = self.page_grab.saturating_sub(1);
}
let Some(webview) = self.active_webview() else { return false };
if state == ElementState::Pressed && !webview.focused() {
webview.set_focused(true);
}
webview.notify_input_event(InputEvent::MouseButton(MouseButtonEvent::new(action, button, WebViewPoint::Device(point))));
true
}
pub fn send_wheel(&mut self, delta: MouseScrollDelta) -> bool {
let Some(pos) = self.pointer else { return false };
let Some(point) = self.page_point(pos) else { return false };
let Some(webview) = self.active_webview() else { return false };
let (x, y) = match delta {
MouseScrollDelta::LineDelta(dx, dy) => (dx as f64 * LINE_PX, dy as f64 * LINE_PX),
MouseScrollDelta::PixelDelta(d) => (d.x, d.y),
};
// Shift turns a vertical wheel into horizontal scrolling, like other browsers.
let (x, y) = if self.modifiers.shift_key() && x == 0.0 { (y, 0.0) } else { (x, y) };
webview.notify_input_event(InputEvent::Wheel(WheelEvent::new(WheelDelta { x, y, z: 0.0, mode: WheelMode::DeltaPixel }, WebViewPoint::Device(point))));
true
}
pub fn send_touch(&mut self, touch: &Touch) -> bool {
let pos = touch.location;
let Some(point) = self.page_point_clamped(pos).filter(|_| self.page_point(pos).is_some() || touch.phase != TouchPhase::Started) else { return false };
let Some(webview) = self.active_webview() else { return false };
let kind = match touch.phase {
TouchPhase::Started => TouchEventType::Down,
TouchPhase::Moved => TouchEventType::Move,
TouchPhase::Ended => TouchEventType::Up,
TouchPhase::Cancelled => TouchEventType::Cancel,
};
webview.notify_input_event(InputEvent::Touch(TouchEvent::new(kind, TouchId(touch.id as i32), WebViewPoint::Device(point), TouchPointerType::Touch)));
true
}
/// Show the page's cursor while the pointer is over it.
pub fn update_cursor(&self, over_page: bool) {
if !over_page {
return;
}
let Some(tab) = self.tab() else { return };
let icon = cursor_icon(tab.cursor);
match icon {
Some(icon) => {
self.window.set_cursor_visible(true);
self.window.set_cursor(icon);
},
None => self.window.set_cursor_visible(false),
}
}
pub fn set_ime(&mut self, enabled: bool, area: Option<(PhysicalPosition<f64>, PhysicalSize<u32>)>) {
if self.ime_enabled != enabled {
self.window.set_ime_allowed(enabled);
self.ime_enabled = enabled;
}
if let Some((pos, size)) = area {
self.window.set_ime_cursor_area(pos, size);
}
}
/// Convert a rectangle Servo reports (device pixels relative to the page) to egui points.
pub fn device_rect_to_ui(&self, rect: servo::DeviceIntRect) -> egui::Rect {
let scale = self.egui.egui_ctx.pixels_per_point();
let origin = self.page_rect.map(|r| r.min).unwrap_or(egui::Pos2::ZERO);
egui::Rect::from_min_max(
origin + egui::vec2(rect.min.x as f32 / scale, rect.min.y as f32 / scale),
origin + egui::vec2(rect.max.x as f32 / scale, rect.max.y as f32 / scale),
)
}
/// Convert a point in CSS pixels of the page (from page scripts) to egui points.
pub fn css_point_to_ui(&self, x: f32, y: f32, zoom: f32) -> egui::Pos2 {
let origin = self.page_rect.map(|r| r.min).unwrap_or(egui::Pos2::ZERO);
origin + egui::vec2(x * zoom, y * zoom)
}
/// Read the picture-in-picture tab's frame and keep it as a texture in this (PiP) window.
pub fn take_pip_frame(&mut self, source: &OffscreenRenderingContext, source_window: &WindowRenderingContext) {
let _ = source_window.make_current();
let size = source.size();
let rect = servo::DeviceIntRect::from_origin_and_size(Point2D::new(0, 0), euclid::Size2D::new(size.width as i32, size.height as i32));
let Some(image) = source.read_to_image(rect) else { return };
let _ = self.rendering.make_current();
let color = egui::ColorImage::from_rgba_unmultiplied([image.width() as usize, image.height() as usize], image.as_raw());
self.pip_size = [image.width(), image.height()];
match &mut self.pip_frame {
Some(texture) => texture.set(color, egui::TextureOptions::LINEAR),
None => self.pip_frame = Some(self.egui.egui_ctx.load_texture("pip-frame", color, egui::TextureOptions::LINEAR)),
}
self.needs_redraw = true;
}
}
pub fn cursor_icon(cursor: servo::Cursor) -> Option<CursorIcon> {
use servo::Cursor as C;
Some(match cursor {
C::None => return None,
C::Default => CursorIcon::Default,
C::Pointer => CursorIcon::Pointer,
C::ContextMenu => CursorIcon::ContextMenu,
C::Help => CursorIcon::Help,
C::Progress => CursorIcon::Progress,
C::Wait => CursorIcon::Wait,
C::Cell => CursorIcon::Cell,
C::Crosshair => CursorIcon::Crosshair,
C::Text => CursorIcon::Text,
C::VerticalText => CursorIcon::VerticalText,
C::Alias => CursorIcon::Alias,
C::Copy => CursorIcon::Copy,
C::Move => CursorIcon::Move,
C::NoDrop => CursorIcon::NoDrop,
C::NotAllowed => CursorIcon::NotAllowed,
C::Grab => CursorIcon::Grab,
C::Grabbing => CursorIcon::Grabbing,
C::EResize => CursorIcon::EResize,
C::NResize => CursorIcon::NResize,
C::NeResize => CursorIcon::NeResize,
C::NwResize => CursorIcon::NwResize,
C::SResize => CursorIcon::SResize,
C::SeResize => CursorIcon::SeResize,
C::SwResize => CursorIcon::SwResize,
C::WResize => CursorIcon::WResize,
C::EwResize => CursorIcon::EwResize,
C::NsResize => CursorIcon::NsResize,
C::NeswResize => CursorIcon::NeswResize,
C::NwseResize => CursorIcon::NwseResize,
C::ColResize => CursorIcon::ColResize,
C::RowResize => CursorIcon::RowResize,
C::AllScroll => CursorIcon::AllScroll,
C::ZoomIn => CursorIcon::ZoomIn,
C::ZoomOut => CursorIcon::ZoomOut,
})
}
/// The egui paint callback that draws a tab's framebuffer into the page rectangle.
pub fn page_callback(rect: egui::Rect, context: &OffscreenRenderingContext) -> Option<egui::PaintCallback> {
let blit = std::sync::Arc::new(context.render_to_parent_callback()?);
Some(egui::PaintCallback {
rect,
callback: std::sync::Arc::new(egui_glow::CallbackFn::new(move |info, painter| {
let vp = info.viewport_in_pixels();
let target = euclid::default::Rect::new(Point2D::new(vp.left_px, vp.from_bottom_px), euclid::default::Size2D::new(vp.width_px, vp.height_px));
blit(painter.gl(), target);
})),
})
}