Nacre/src/window.rs

270 lines
11 KiB
Rust

//! A browser window: a `gtk::ApplicationWindow` holding `Gtk.Overlay { Gtk.Stack of the tabs' web views placed at
//! egui's page rect by its margins, EguiArea }` (D-033, D-035), and its tabs. (Margins, not a `Gtk.Fixed` with a
//! size request: a size request taller than the window during a layout change grew the window's minimum size.) egui draws all of Nacre's chrome in the overlay;
//! WebKit draws the page and gets the page's input directly from GTK.
use std::time::Instant;
use gtk::prelude::*;
use crate::egui_area::{EguiArea, UiFn};
use crate::engine::{View, ViewId};
use crate::tabs::Tab;
use crate::ui::WindowUi;
/// Nacre's own window id (GTK windows have none that fits a map key).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct WindowId(pub u64);
#[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: gtk::ApplicationWindow,
/// The egui overlay: every piece of Nacre's interface.
pub area: EguiArea,
/// The tabs' web views; the active one is the visible child.
/// Every tab's view, all allocated at the page rect; only the active one is child-visible (mapped).
stack: gtk::Overlay,
/// Where the stack sits now (logical pixels), so it moves only when the page rect changes.
placed: Option<egui::Rect>,
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; `None` = no web page shown).
pub page_rect: Option<egui::Rect>,
/// The web page has the keyboard (not the interface).
pub page_focused: bool,
pub fullscreen: bool,
pub last_input: Instant,
/// Picture-in-picture windows: the tab's own view, moved here while it plays (filling the window).
pub pip_view: Option<View>,
pub focused: bool,
/// Save the window to this file after the next frame (self-test screenshots).
pub shot_request: Option<std::path::PathBuf>,
/// The frame count the shot waits for.
pub shot_frame: Option<u64>,
/// How long the last frames took to draw, in ms (self-test status).
pub frame_times: std::collections::VecDeque<f32>,
/// Frames drawn since the window opened (self-test status).
pub frames_drawn: u64,
}
impl BrowserWindow {
pub fn create(app: &gtk::Application, id: WindowId, kind: Kind, title: &str, size: (u32, u32), decorated: bool, ui: UiFn, busy: Box<dyn Fn() -> bool>) -> BrowserWindow {
let window = gtk::ApplicationWindow::builder().application(app).title(title).default_width(size.0.max(320) as i32).default_height(size.1.max(240) as i32).build();
window.set_decorated(decorated);
window.set_size_request(320, 240);
let stack = gtk::Overlay::new();
stack.set_visible(false);
stack.set_hexpand(true);
stack.set_vexpand(true);
let overlay = gtk::Overlay::new();
overlay.set_child(Some(&stack));
let area = EguiArea::new(id.0, ui, busy);
area.ctx().set_fonts(crate::ui::fonts());
overlay.add_overlay(&area);
window.set_child(Some(&overlay));
// For screenshots (save_shot): a paintable that tracks what the window's content draws.
unsafe { window.set_data("nacre-shot", gtk::WidgetPaintable::new(Some(&overlay))) };
BrowserWindow {
id,
window,
area,
stack,
placed: None,
kind,
tabs: Vec::new(),
active: 0,
ui: WindowUi::default(),
page_rect: None,
page_focused: false,
fullscreen: false,
last_input: Instant::now(),
pip_view: None,
focused: true,
shot_request: None,
shot_frame: None,
frame_times: Default::default(),
frames_drawn: 0,
}
}
pub fn ctx(&self) -> egui::Context {
self.area.ctx().clone()
}
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_view(&self, view: ViewId) -> Option<usize> {
self.tabs.iter().position(|t| t.view_id() == Some(view))
}
pub fn active_webview(&self) -> Option<&View> {
self.tab().filter(|t| t.page.is_none()).and_then(Tab::webview)
}
pub fn redraw(&self) {
self.area.repaint();
}
/// Put every tab's web view into the stack, show the active tab's at the page rect, hide the stack when the
/// active tab shows no web page.
pub fn sync_webviews(&mut self) {
if let Some(view) = &self.pip_view {
let widget = view.widget();
if widget.parent().as_ref() != Some(self.stack.upcast_ref()) {
widget.unparent();
widget.set_child_visible(true);
self.stack.add_overlay(&widget);
}
self.stack.set_visible(true);
return;
}
for tab in &self.tabs {
if let Some(web) = &tab.web {
let widget = web.webview.widget();
if widget.parent().is_none() {
widget.set_child_visible(false);
self.stack.add_overlay(&widget);
}
}
}
let zoom = self.area.ctx().zoom_factor();
let shown = self.tabs.get_mut(self.active).filter(|t| t.page.is_none() && t.pip_size.is_none() && t.crashed.is_none());
let rect = self.page_rect.map(|r| egui::Rect::from_min_max(r.min * zoom, r.max * zoom)).filter(|r| r.is_positive());
match (shown.and_then(|t| { t.frozen = false; t.last_shown = Instant::now(); t.web.as_ref() }), rect) {
(Some(web), Some(rect)) => {
let widget = web.webview.widget();
if !widget.is_child_visible() {
let mut child = self.stack.first_child();
while let Some(c) = child {
c.set_child_visible(c == widget);
child = c.next_sibling();
}
}
if self.placed != Some(rect) {
self.placed = Some(rect);
let (w, h) = self.window.child().map(|c| (c.width() as f32, c.height() as f32)).unwrap_or((rect.max.x, rect.max.y));
self.stack.set_margin_start(rect.min.x.round().max(0.0) as i32);
self.stack.set_margin_top(rect.min.y.round().max(0.0) as i32);
self.stack.set_margin_end((w - rect.max.x).round().max(0.0) as i32);
self.stack.set_margin_bottom((h - rect.max.y).round().max(0.0) as i32);
}
self.stack.set_visible(true);
if self.page_focused && !web.webview.focused() && !self.area.has_focus() {
web.webview.focus();
}
},
_ => self.stack.set_visible(false),
}
}
/// Take a tab's web view out of the window (closing or moving the tab).
pub fn detach(&self, view: &View) {
let widget = view.widget();
if widget.parent().as_ref() == Some(self.stack.upcast_ref()) {
self.stack.remove_overlay(&widget);
}
}
/// Give the keyboard to the page.
pub fn focus_page(&mut self) {
self.page_focused = true;
// The interface's text field (the address field after a new tab) lets go.
self.area.ctx().memory_mut(|m| m.stop_text_input());
// A new tab's view may not be in the window yet: put it there so it can take the focus.
self.sync_webviews();
if let Some(web) = self.active_webview() {
web.focus();
}
// Not shown yet (no page rect): drop the interface's focus so `sync_webviews` focuses the page once placed.
if self.area.has_focus() {
GtkWindowExt::set_focus(&self.window, None::<&gtk::Widget>);
}
self.area.repaint();
}
/// Give the keyboard to the interface.
pub fn focus_ui(&mut self) {
self.page_focused = false;
self.area.grab_focus();
}
pub fn destroy(&mut self) {
for tab in &self.tabs {
if let Some(web) = &tab.web {
self.detach(&web.webview);
}
}
if let Some(view) = self.pip_view.take() {
self.detach(&view);
}
EguiArea::forget(self.id.0);
self.window.destroy();
}
pub fn set_title(&self, title: &str) {
self.window.set_title(Some(title));
}
/// The window's size in logical pixels.
pub fn size(&self) -> (u32, u32) {
let (w, h) = (self.window.width(), self.window.height());
if w > 0 && h > 0 { (w as u32, h as u32) } else { let (w, h) = self.window.default_size(); (w.max(1) as u32, h.max(1) as u32) }
}
/// 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) / self.area.ctx().zoom_factor()
}
}
/// Save what the window shows (interface and page) as a PNG.
pub fn save_shot(window: &gtk::ApplicationWindow, path: &std::path::Path) -> Result<(), String> {
// A paintable made just now has no frame of the widget yet; the window keeps one that follows its content.
let paintable: gtk::WidgetPaintable = unsafe { window.data::<gtk::WidgetPaintable>("nacre-shot").map(|p| p.as_ref().clone()) }.ok_or("no paintable")?;
let (w, h) = (window.child().map(|c| c.width()).unwrap_or(0), window.child().map(|c| c.height()).unwrap_or(0));
let snapshot = gtk::Snapshot::new();
paintable.snapshot(&snapshot, w as f64, h as f64);
let node = snapshot.to_node().ok_or("nothing drawn")?;
let renderer = window.renderer().ok_or("no renderer")?;
let texture = renderer.render_texture(&node, Some(&gtk::graphene::Rect::new(0.0, 0.0, w as f32, h as f32)));
texture.save_to_png(path).map_err(|e| e.to_string())
}
/// Give a window its own Wayland app id (GTK gives every window the application's when it maps, so this follows
/// right after). Nothing on other backends.
pub fn set_app_id(window: &gtk::ApplicationWindow, app_id: &str) {
unsafe extern "C" {
fn gdk_wayland_toplevel_set_application_id(toplevel: *mut gtk::gdk::ffi::GdkToplevel, application_id: *const std::ffi::c_char);
}
let app_id = std::ffi::CString::new(app_id).expect("no NUL");
window.connect_map(move |w| {
let Some(surface) = w.surface() else { return };
if surface.type_().name() != "GdkWaylandToplevel" {
return;
}
let Ok(toplevel) = surface.downcast::<gtk::gdk::Toplevel>() else { return };
unsafe { gdk_wayland_toplevel_set_application_id(gtk::glib::translate::ToGlibPtr::to_glib_none(&toplevel).0, app_id.as_ptr()) };
});
}