//! 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, 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, pub active: usize, pub ui: WindowUi, /// Where the page is drawn, in egui points (set by the UI each frame). pub page_rect: Option, pub modifiers: ModifiersState, pub pointer: Option>, /// 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, pub pip_size: [u32; 2], pub focused: bool, /// Save the next frame to this file (self-test screenshots). pub shot_request: Option, /// How long the last frames took to draw, in ms (self-test status). pub frame_times: std::collections::VecDeque, /// Frames drawn since the window opened (self-test status). pub frames_drawn: u64, /// When egui wants the next frame (it asked for a repaint after a delay); see `repaint_wanted`. pub redraw_at: Option, /// The earliest time egui asked to repaint since this was last taken, from any thread. pub repaint_wanted: std::sync::Arc>>, /// Hidden (minimised or covered, as the compositor tells it): scheduled frames wait. pub occluded: bool, } /// 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 { 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); egui.egui_ctx.set_fonts(crate::ui::fonts()); let repaint_wanted = std::sync::Arc::new(std::sync::Mutex::new(None::)); let wanted = repaint_wanted.clone(); egui.egui_ctx.set_repaint_observer(move |info| { let at = Instant::now() + info.delay.min(std::time::Duration::from_secs(3600)); if let Ok(mut slot) = wanted.lock() { *slot = Some(slot.map_or(at, |t| t.min(at))); } }); 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(), 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(), frames_drawn: 0, redraw_at: None, repaint_wanted, occluded: false, }) } 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 { self.tabs.iter().position(|t| t.id == id) } pub fn tab_by_webview(&self, webview: servo::WebViewId) -> Option { 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 { 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)) }, } } /// 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 { 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. 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 }; 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 { web.webview.set_hidpi_scale_factor(scale); } 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 { web.webview.hide(); } } } /// 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 _ = self.rendering.make_current(); 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 } /// 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) { 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) -> Option { 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)) } /// A flyout, menu, toast or other floating egui layer is under the pointer (the chrome's panels and the page /// area are background layers and don't count). pub fn over_overlay(&self, pos: PhysicalPosition) -> bool { let scale = self.egui.egui_ctx.pixels_per_point() as f64; let p = egui::pos2((pos.x / scale) as f32, (pos.y / scale) as f32); self.egui.egui_ctx.layer_id_at(p).is_some_and(|l| l.order != egui::Order::Background) } /// Like `page_point` but clamped, for drags that leave the page. pub fn page_point_clamped(&self, pos: PhysicalPosition) -> Option { 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) -> 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, PhysicalSize)>) { 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 { 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 { 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); })), }) }