//! The browser: owns the engine, the windows, the stores and the background services. GTK owns the main loop //! (D-033): the `App` lives in an `Rc>` on the main thread; engine signals queue `Event`s on the hub and //! `pump` (a GLib idle) handles them, runs queued commands and keeps the web views placed. UI clicks and shortcuts //! become `Command`s handled in `actions.rs`. use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::path::PathBuf; use std::rc::{Rc, Weak}; use std::sync::atomic::{AtomicU64, AtomicU8, Ordering}; use std::sync::mpsc::{self, Receiver, Sender}; use std::sync::Arc; use std::time::{Duration, Instant}; use gtk::prelude::*; use gtk::{gdk, glib}; use url::Url; use crate::actions::{Command, Disposition}; use crate::adblock::AdBlocker; use crate::discord::Presence; use crate::engine::{Control, Engine, Event, Hub, HubConfig, LoadState, View, ViewId}; use crate::keys::{Keymap, Shortcut}; use crate::media::Cava; use crate::net::bridge::Bridge; use crate::net::tor::Tor; use crate::net::{download, VpnStatus}; use crate::paths::Paths; use crate::spell::Speller; use crate::store::apps::Apps; use crate::store::bookmarks::{Bookmarks, ReadingList}; use crate::store::downloads::Downloads; use crate::store::history::History; use crate::store::permissions::Permissions; use crate::store::scripts::Scripts; use crate::store::session::Session; use crate::store::settings::Settings; use crate::store::vault::Vault; use crate::tabs::{Page, Tab, Web}; use crate::window::{BrowserWindow, Kind, WindowId}; use crate::{inject, theme, util}; /// Ids for tabs and web views (one counter, so a view's id never meets another tab's). static NEXT_ID: AtomicU64 = AtomicU64::new(1); pub fn next_id() -> u64 { NEXT_ID.fetch_add(1, Ordering::Relaxed) } thread_local! { /// Nacre is changing GTK's dark preference itself (not a system change). static SETTING_SCHEME: Cell = const { Cell::new(false) }; } thread_local! { static APP: RefCell>> = RefCell::new(Weak::new()); static PUMP_QUEUED: Cell = const { Cell::new(false) }; } /// Run `pump` soon (main thread only). Many calls before it runs make one run. pub fn schedule_pump() { if !PUMP_QUEUED.with(|q| q.replace(true)) { glib::idle_add_local_once(|| { PUMP_QUEUED.with(|q| q.set(false)); pump(); }); } } /// Handle what is waiting: engine events, finished jobs, commands from the interface, timers. pub fn pump() { let Some(app) = APP.with(|a| a.borrow().upgrade()) else { return }; let shots = match app.try_borrow_mut() { Ok(mut app) => { app.step(); app.take_shots() }, // WebKit emitted a signal while the app was busy: come back right after. Err(_) => { schedule_pump(); return; }, }; // Screenshots render the window (the egui area too, which draws through the app), so outside the borrow. for (window, path) in shots { if let Err(error) = crate::window::save_shot(&window, &path) { eprintln!("screenshot {}: {error}", path.display()); } } } /// Wakes the main loop from other threads (workers, downloads, the single-instance server). #[derive(Clone)] pub struct Waker; impl Waker { pub fn wake(&self) { glib::MainContext::default().invoke(schedule_pump); } } /// Work finished on another thread, run on the main thread. pub type Job = Box; /// What the command line asked for. #[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct Launch { pub urls: Vec, pub new_window: bool, pub app: Option, pub incognito: bool, pub profile: Option, } /// A short message at the bottom of the window. pub struct Toast { pub text: String, pub action: Option<(String, Command)>, pub until: Instant, } /// Everything the UI may read and the stores it may edit directly. pub struct Shared { pub paths: Paths, pub incognito: bool, pub settings: RefCell, pub history: RefCell, pub bookmarks: RefCell, pub reading: RefCell, pub downloads: RefCell, pub permissions: RefCell, pub session: RefCell, pub vault: RefCell, pub apps: RefCell, pub scripts: RefCell, pub keymap: RefCell, pub adblock: Arc, pub bridge: Option>, pub tor: Tor, pub vpn_status: RefCell, pub speller: RefCell>, pub spell_status: RefCell, pub system_accent: Option, pub user_agent: RefCell, pub devtools: RefCell>, pub update: RefCell>, pub update_status: RefCell, pub dlm_status: RefCell>>, pub import_sources: RefCell>, pub import_status: RefCell, pub toasts: RefCell>, /// Last weather answer for the new tab page, or why it failed. pub weather: RefCell>>, pub adblock_status: RefCell, pub system_dark: RefCell, /// Hosts the user chose to open over plain http this session. pub http_allowed: RefCell>, /// Address-bar search suggestions for the last query: (query, suggestions). pub suggestions: RefCell<(String, Vec)>, /// Weather place suggestions for the last name typed in the Customize panel: (name, places). pub places: RefCell<(String, Vec)>, /// Seed for privacy-mode noise; new every run. pub seed: String, pub started: Instant, /// The media the media button and Discord follow, from any window. pub media_now: RefCell>, /// Real audio levels (visualizer). pub cava: RefCell, /// Downloaded artwork, decoded: url -> image (None while loading or failed). pub art_images: RefCell>>, /// Discord Rich Presence connection status. pub presence_status: RefCell, /// Page sources for nacre://source: url -> text or error (None while loading). pub sources: RefCell>>>, /// Site info flyout: the host asked about and what it keeps (None while the engine answers). pub site_data: RefCell<(String, Option)>, } #[derive(Clone, Debug)] pub struct MediaNow { pub tab: u64, pub title: String, pub url: String, pub host: String, pub state: crate::media::MediaState, pub received_ms: u64, pub muted: bool, } impl Shared { pub fn toast(&self, text: impl Into) { self.toasts.borrow_mut().push(Toast { text: text.into(), action: None, until: Instant::now() + Duration::from_secs(5) }); } pub fn toast_with(&self, text: impl Into, label: impl Into, command: Command) { self.toasts.borrow_mut().push(Toast { text: text.into(), action: Some((label.into(), command)), until: Instant::now() + Duration::from_secs(8) }); } } /// Quit (`window` None) or closing one window, while its pages run `beforeunload` (WebKit `try_close`). The tabs /// stay until every page has answered: if one stays, the others are reloaded and nothing was closed. pub struct Shutdown { window: Option, waiting: Vec, answered: Vec, } pub struct App { pub gtk: gtk::Application, /// This app's own handle, for interface closures. me: Weak>, pub jobs_tx: Sender, jobs_rx: Receiver, pub downloads_tx: Sender, downloads_rx: Receiver, pub engine: Option>, pub hub: Rc, pub shared: Rc, pub windows: HashMap, /// Most recently focused normal window. pub last_window: Option, next_window_id: u64, pub launch: Launch, pub pending_launches: Vec, pub pending_files: HashMap, pub next_pending: u64, /// Page notifications shown this run (self-test status). pub notifications_shown: u32, pub download_controls: HashMap>, /// Downloads WebKit makes itself (`blob:`, `data:`), by downloads list id. pub web_downloads: HashMap, pub presence: Option, pub presence_started: Option<(u64, String, i64)>, pub applied: Settings, /// `Permissions::revision` the hub and the file were last updated for. pub permissions_seen: u64, pub exiting: bool, /// A quit or window close waiting for the pages' `beforeunload`. pub shutdown: Option, last_tick: Instant, last_save: Instant, last_slow: Instant, /// Sealed cookies (D-037), `None` when they are kept for the run only. cookies: Option, last_presence: Instant, pub crashed_last_time: bool, pub instance: Option, /// Windows that commands asked for; opened when the event loop is at hand. pub window_requests: Vec, pub selftest: Option, /// Commands waiting for a window to exist. pub pending_commands: Vec, /// Picture-in-picture windows to close after their tab went away. pub window_closes: Vec, /// Commands from the interface, run after the frame that made them. ui_commands: Vec<(WindowId, Command)>, } pub struct WindowRequest { pub kind: Kind, pub tabs: Vec, pub active: usize, pub size: Option<(u32, u32)>, } pub fn wake_fn() -> Arc { Arc::new(|| Waker.wake()) } impl App { pub fn new(gtk: gtk::Application, paths: Paths, launch: Launch) -> Rc> { let incognito = paths.incognito; let settings = Settings::load(&paths.settings()); let adblock = Arc::new(AdBlocker::new()); let hub = Hub::new(adblock.clone()); let bridge = if std::env::var_os("NACRE_NO_BRIDGE").is_some() { None } else { match Bridge::start() { Ok(bridge) => Some(bridge), Err(error) => { log::error!("could not start the network bridge ({error}); VPN and secure DNS won't work"); None }, } }; if let Some(bridge) = &bridge { crate::net::fetch::set_proxy(&bridge.proxy_url()); } let keymap = Keymap::new(&settings.keys); let crashed_last_time = !incognito && paths.running_marker().exists(); if !incognito { let _ = std::fs::write(paths.running_marker(), std::process::id().to_string()); } let shared = Shared { history: RefCell::new(History::load(paths.history(), incognito)), bookmarks: RefCell::new(Bookmarks::load(paths.bookmarks(), incognito)), reading: RefCell::new(ReadingList::load(paths.reading_list(), incognito)), downloads: RefCell::new(Downloads::load(paths.downloads(), incognito)), permissions: RefCell::new(Permissions::load(paths.permissions(), incognito)), session: RefCell::new(Session::load(paths.session(), incognito)), vault: RefCell::new(Vault::load(paths.vault(), paths.vault_key(), incognito)), apps: RefCell::new(Apps::load(paths.apps(), paths.app_icons(), incognito)), scripts: RefCell::new(Scripts::load(paths.scripts(), incognito)), keymap: RefCell::new(keymap), settings: RefCell::new(settings.clone()), adblock, bridge, tor: Tor::new(), vpn_status: RefCell::new(VpnStatus::Off), speller: RefCell::new(None), spell_status: RefCell::new(String::new()), system_accent: theme::system_accent(), user_agent: RefCell::new(String::new()), devtools: RefCell::new(None), update: RefCell::new(None), update_status: RefCell::new(String::new()), dlm_status: RefCell::new(HashMap::new()), import_sources: RefCell::new(Vec::new()), import_status: RefCell::new(String::new()), toasts: RefCell::new(Vec::new()), weather: RefCell::new(None), adblock_status: RefCell::new(String::new()), system_dark: RefCell::new(true), http_allowed: RefCell::new(Vec::new()), suggestions: RefCell::new((String::new(), Vec::new())), places: RefCell::new((String::new(), Vec::new())), seed: util::random_hex(8), started: Instant::now(), media_now: RefCell::new(None), cava: RefCell::new(Cava::new()), art_images: RefCell::new(HashMap::new()), sources: RefCell::new(HashMap::new()), site_data: RefCell::default(), presence_status: RefCell::new("Off".into()), incognito, paths, }; let (jobs_tx, jobs_rx) = mpsc::channel(); let (downloads_tx, downloads_rx) = mpsc::channel(); let app = Rc::new(RefCell::new(App { gtk, me: Weak::new(), jobs_tx, jobs_rx, downloads_tx, downloads_rx, engine: None, hub, shared: Rc::new(shared), windows: HashMap::new(), last_window: None, next_window_id: 1, launch, pending_launches: Vec::new(), pending_files: HashMap::new(), next_pending: 1, notifications_shown: 0, download_controls: HashMap::new(), web_downloads: HashMap::new(), presence: None, presence_started: None, applied: settings, permissions_seen: 0, exiting: false, shutdown: None, last_tick: Instant::now(), last_save: Instant::now(), last_slow: Instant::now() - Duration::from_secs(3600), cookies: None, last_presence: Instant::now(), crashed_last_time, instance: None, window_requests: Vec::new(), selftest: crate::selftest::SelfTest::from_env(), pending_commands: Vec::new(), window_closes: Vec::new(), ui_commands: Vec::new(), })); app.borrow_mut().me = Rc::downgrade(&app); APP.with(|a| *a.borrow_mut() = Rc::downgrade(&app)); app } pub fn wake(&self) -> Arc { wake_fn() } /// Run `work` on a worker thread, then `done` with its result on the main thread. pub fn spawn(&self, name: &str, work: impl FnOnce() -> T + Send + 'static, done: impl FnOnce(&mut App, T) + Send + 'static) { let tx = self.jobs_tx.clone(); let _ = std::thread::Builder::new().name(format!("nacre-{name}")).spawn(move || { let result = work(); let _ = tx.send(Box::new(move |app: &mut App| done(app, result))); Waker.wake(); }); } pub fn new_tab_id(&mut self) -> u64 { next_id() } // ── engine ───────────────────────────────────────────────────────── fn start_engine(&mut self) { let settings = self.shared.settings.borrow().clone(); let dark = self.web_dark(); // WebKit's cookie store on tmpfs, sealed into cookies.bin (D-037); without it cookies stay in memory. self.cookies = crate::store::cookies::start(&self.shared.paths.data, &self.shared.paths.profile, self.shared.incognito); let paths = &self.shared.paths; let setup = crate::engine::host::Setup { dirs: (!self.shared.incognito).then(|| (paths.webkit_data(), paths.webkit_cache())), proxy: self.shared.bridge.as_ref().map(|b| b.socks_url()), user_agent: settings.web.user_agent.clone(), dark_background: dark, developer_extras: true, remote_inspector: settings.web.remote_debugging.then(|| "127.0.0.1:6080".to_owned()), filter_store: paths.cache.join("content-filters"), cookie_db: self.cookies.as_ref().map(|c| c.db().to_path_buf()), }; let engine = Engine::new(self.hub.clone(), &setup); { use crate::store::permissions::{Decision, Kind}; let saved: Vec<(String, Decision)> = self.shared.permissions.borrow().all().into_iter().filter(|(_, k, _)| *k == Kind::Notifications).map(|(h, _, d)| (h, d)).collect(); let hosts = |want: Decision| saved.iter().filter(|(_, d)| *d == want).map(|(h, _)| h.clone()).collect(); engine.set_notification_answers(hosts(Decision::Allow), hosts(Decision::Block)); } let ua = engine.user_agent(); *self.shared.user_agent.borrow_mut() = ua.clone(); crate::net::fetch::set_user_agent(&ua); self.engine = Some(engine); self.apply_web_scheme(); self.refresh_hub_config(); if let (Some(engine), Some(filter)) = (&self.engine, self.shared.adblock.content_filter()) { engine.set_content_filter(filter); } self.install_page_scripts(); } pub fn refresh_hub_config(&self) { let settings = self.shared.settings.borrow(); *self.hub.config.borrow_mut() = HubConfig::from_settings(&settings, &self.shared.permissions.borrow(), &self.shared.user_agent.borrow(), self.shared.http_allowed.borrow().clone()); // Headers, tracking parameters on sub-resources and ad blocker stand-ins are the web process extension's // (D-036); third-party cookies, languages and the Images permission are WebKit's own settings. if let Some(engine) = &self.engine { let privacy = self.privacy_mode_on(&settings); engine.set_block_third_party_cookies(settings.privacy.block_third_party || privacy); let languages = crate::net::privacy::languages(&crate::net::privacy::locale()); engine.set_languages(&languages); engine.set_images_filter(crate::net::policy::images_filter(&self.hub.config.borrow())); let mut headers: Vec<(String, String)> = crate::net::privacy::privacy_headers(&settings).into_iter().map(|(k, v)| (k.to_owned(), v.to_owned())).collect(); // Privacy mode: Accept-Language as Firefox sends it (WebKit weighs the same list its own way). if privacy { headers.push(("Accept-Language".to_owned(), crate::net::privacy::accept_language(&languages))); } let config = crate::net::rules::Config { headers, strip: settings.privacy.strip_params, adblock: settings.adblock.enabled, paused: settings.adblock.allow.clone(), redirects: self.shared.adblock.content_filter().map(|f| f.redirects).unwrap_or_default(), }; engine.set_extension_config(serde_json::to_string(&config).unwrap_or_default()); engine.refresh_filters(); } } /// Privacy mode: on everywhere, or in incognito windows when the user chose that. fn privacy_mode_on(&self, s: &Settings) -> bool { s.privacy.mode || (self.shared.incognito && s.privacy.mode_incognito) } /// (Re)build the scripts every page gets. Applies on each page's next load. pub fn install_page_scripts(&mut self) { let Some(engine) = self.engine.clone() else { return }; let s = self.shared.settings.borrow().clone(); let privacy = self.privacy_mode_on(&s); let options = inject::Options { token: &self.hub.token, privacy_mode: privacy, seed: &self.shared.seed, user_agent: &self.shared.user_agent.borrow(), privacy_paused: &s.privacy.mode_off, languages: &crate::net::privacy::languages(&crate::net::privacy::locale()), block_third_party: s.privacy.block_third_party || privacy, dnt: s.privacy.dnt, force_dark: s.web.force_dark, smooth_scroll: s.web.smooth_scroll && !crate::perf::lite(&s), preload: s.web.preload, save_data: s.privacy.save_data, cosmetic: s.adblock.enabled && s.adblock.cosmetic, youtube_ads: s.adblock.enabled && s.adblock.youtube, autofill: s.vault.enabled, spell: s.spell.enabled, google_signin: s.privacy.google_signin, }; let mut sources = inject::page_scripts(&options); let scripts = self.shared.scripts.borrow(); sources.extend(scripts.page_scripts()); engine.set_page_content(sources, scripts.page_styles()); } /// A web view for a tab, loading `url` (after the back/forward list of the tab's previous view, if any). pub fn build_webview(&mut self, tab_id: u64, url: Url, history: Option) -> Web { if self.engine.is_none() { self.start_engine(); } let engine = self.engine.clone().expect("engine runs"); let webview = engine.create_view(ViewId(tab_id), None); let zoom = self.shared.settings.borrow().zoom_for(&util::host_of(&url)); webview.set_page_zoom(zoom); match &history { Some(history) => webview.restore_history(history, &url), None => webview.load(&url), } Web { webview } } /// What sites see as prefers-color-scheme. pub fn web_dark(&self) -> bool { let s = self.shared.settings.borrow(); match s.web.scheme { crate::store::settings::WebScheme::Dark => true, crate::store::settings::WebScheme::Light => false, crate::store::settings::WebScheme::Auto => theme::is_dark(&s, *self.shared.system_dark.borrow()), } } /// WebKitGTK takes prefers-color-scheme from GTK's dark preference (one value for every page). fn apply_web_scheme(&self) { let dark = self.web_dark(); // Pages follow GTK's dark preference (prefers-color-scheme). Setting it changes GTK's colour scheme too, so // the system-scheme watcher (first_setup) ignores what Nacre sets itself. if let Some(settings) = gtk::Settings::default() { #[allow(deprecated)] if settings.is_gtk_application_prefer_dark_theme() != dark { SETTING_SCHEME.set(true); settings.set_gtk_application_prefer_dark_theme(dark); SETTING_SCHEME.set(false); } } if let Some(engine) = &self.engine { engine.set_dark_background(dark); } } /// One round of work: engine events (until quiet, bounded), jobs, timers, interface commands, view placement. fn step(&mut self) { for _ in 0..8 { let events = self.hub.take_events(); if events.is_empty() { break; } for event in events { self.handle_event(event); } } self.tick(); for (window, command) in std::mem::take(&mut self.ui_commands) { self.run_in(window, command); } for launch in std::mem::take(&mut self.pending_launches) { self.handle_launch(launch); } self.open_pending_windows(); self.apply_settings_if_changed(); for win in self.windows.values_mut() { win.sync_webviews(); } if self.exiting { self.gtk.quit(); } } fn take_shots(&mut self) -> Vec<(gtk::ApplicationWindow, PathBuf)> { // Shoot only after two frames drawn since the request, so the shot shows what the commands before it did. let mut shots = Vec::new(); for w in self.windows.values_mut() { if w.shot_request.is_none() { continue; } match w.shot_frame { None => w.shot_frame = Some(w.frames_drawn + 2), Some(frame) if w.frames_drawn >= frame => { w.shot_frame = None; shots.extend(w.shot_request.take().map(|p| (w.window.clone(), p))); continue; }, Some(_) => {}, } w.redraw(); } shots } // ── finding things ──────────────────────────────────────────────── pub fn find_webview(&self, id: ViewId) -> Option<(WindowId, usize)> { self.windows.iter().find_map(|(wid, w)| w.tab_by_view(id).map(|i| (*wid, i))) } pub fn find_tab(&self, tab_id: u64) -> Option<(WindowId, usize)> { self.windows.iter().find_map(|(wid, w)| w.tab_index(tab_id).map(|i| (*wid, i))) } pub fn tab_mut(&mut self, id: ViewId) -> Option<&mut Tab> { let (w, i) = self.find_webview(id)?; self.windows.get_mut(&w)?.tabs.get_mut(i) } pub fn redraw(&mut self, window: WindowId) { if let Some(w) = self.windows.get(&window) { w.redraw(); } } pub fn redraw_all(&mut self) { for w in self.windows.values() { w.redraw(); } } /// The normal window commands should go to: the focused one, else the last used, else any. pub fn current_window(&self) -> Option { self.windows.iter().find(|(_, w)| w.focused && w.kind == Kind::Normal).map(|(id, _)| *id).or(self.last_window.filter(|id| self.windows.get(id).is_some_and(|w| w.kind == Kind::Normal))).or_else(|| self.windows.iter().find(|(_, w)| w.kind == Kind::Normal).map(|(id, _)| *id)) } // ── engine events ───────────────────────────────────────────────── fn handle_event(&mut self, event: Event) { match event { Event::UrlChanged(id, url) => { let host_changed; let window; { let Some((w, i)) = self.find_webview(id) else { return }; window = w; let win = self.windows.get_mut(&w).expect("found"); let tab = &mut win.tabs[i]; host_changed = util::host_of_str(&tab.url) != util::host_of(&url); tab.url = url.to_string(); tab.page = None; tab.draft = None; if host_changed { tab.arrived_ms = util::now_ms(); tab.theme_color = None; tab.favicon_colour = None; tab.site_name.clear(); tab.favicon = None; tab.favicon_png = None; } if i == win.active { win.ui.omnibox_edit = None; } } self.check_app_scope(window, id, &url); // A zoom change is saved for the site at once, so the site's value is always the right one. Not only // when the host changed: a new tab already holds its address when the first event arrives. let zoom = self.shared.settings.borrow().zoom_for(&util::host_of(&url)); if let Some(tab) = self.tab_mut(id) { let differs = (tab.zoom - zoom).abs() > 0.001; tab.zoom = zoom; if (host_changed || differs) && let Some(web) = &tab.web { web.webview.set_page_zoom(zoom); } } self.redraw(window); }, Event::TitleChanged(id, title) => { let Some((w, i)) = self.find_webview(id) else { return }; let title = title.unwrap_or_default(); let url = { let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i]; tab.title = title.clone(); tab.url.clone() }; if !title.is_empty() { self.shared.history.borrow_mut().set_title(&url, &title); } if let Some(win) = self.windows.get(&w) && win.active == i && win.kind != Kind::Normal { win.set_title(&title); } self.redraw(w); }, Event::StatusText(id, text) => { if let Some(tab) = self.tab_mut(id) { tab.status_text = text; } if let Some((w, _)) = self.find_webview(id) { self.redraw(w); } }, Event::Load(id, state) => self.on_load_status(id, state), Event::Progress(id, progress) => { if let Some(tab) = self.tab_mut(id) { tab.progress = progress; } if let Some((w, _)) = self.find_webview(id) { self.redraw(w); } }, Event::Favicon(id) => self.on_favicon(id), Event::History(id, entries, current) => { if let Some(tab) = self.tab_mut(id) { tab.back_forward = entries; tab.history_index = current; } if let Some((w, _)) = self.find_webview(id) { self.redraw(w); } }, Event::Closed(id) => { if let Some((w, i)) = self.find_webview(id) { let tab = &self.windows[&w].tabs[i]; // Closed by the user (after beforeunload): kept in recently closed; by `window.close()`: not. let (tab_id, remember) = (tab.id, tab.closing.is_some()); if remember && self.shutdown_answered(tab_id) { return; } self.close_tab(w, tab_id, remember); } }, Event::Crashed(id, reason) => { let url = self.tab_mut(id).map(|t| t.url.clone()).unwrap_or_default(); if !self.shared.incognito { let line = format!("{} crash {url}: {reason}\n", util::format_stamp(util::now())); use std::io::Write as _; if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(self.shared.paths.crash_log()) { let _ = f.write_all(line.as_bytes()); } } if let Some(tab) = self.tab_mut(id) { tab.crashed = Some(reason); tab.load_status = None; } if let Some((w, _)) = self.find_webview(id) { self.redraw(w); } }, Event::Fullscreen(id, on) => { if let Some((w, i)) = self.find_webview(id) && let Some(win) = self.windows.get_mut(&w) { let tab = &mut win.tabs[i]; // In picture in picture the video's full screen stays inside the PiP window; the page leaving it // (its own button, Escape) ends picture in picture. if tab.pip_size.is_some() { let (was, tab_id) = (std::mem::replace(&mut tab.fullscreen, on), tab.id); if was && !on { self.run(Command::ClosePip(tab_id)); } return; } // Picture in picture already ended (`exit_pip`): nothing to undo here. if !on && !tab.fullscreen { return; } win.tabs[i].fullscreen = on; win.fullscreen = on; if on { win.window.fullscreen() } else { win.window.unfullscreen() } win.redraw(); } }, Event::Navigation(id, request) => self.on_navigation(id, request), Event::Download(id, url, name) => { let page = self.tab_mut(id).map(|t| t.url.clone()).unwrap_or_default(); self.start_download(url, page, name); }, Event::WebDownload(id, download) => self.on_web_download(id, download), Event::CertError(id, error) => { let Some((w, i)) = self.find_webview(id) else { return }; let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i]; if let Some(view) = tab.webview() { view.show_html(&crate::resources::bad_cert_page(&error.url, &error.why), &error.url); } tab.cert_error = Some(error); self.redraw(w); }, Event::LoadFailed(id, url, why) => { let Some((w, i)) = self.find_webview(id) else { return }; let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i]; match (tab.upgraded_from.take(), Url::parse(&url)) { // HTTPS-only: the secure version didn't load. (Some(from), _) => tab.prompts.push_back(crate::tabs::Prompt::HttpFallback { url: from }), (None, Ok(_)) => tab.page = Some(Page::Error(url, why)), _ => {}, } self.redraw(w); }, Event::CreateNew(parent, view, url, gesture) => self.on_create_new(parent, view, url, gesture), Event::OpenLink(id, url, front) => { if let Some((w, i)) = self.find_webview(id) { let from = Some(self.windows[&w].tabs[i].id); self.run_in(w, Command::Open { url: url.to_string(), how: if front { Disposition::NewForegroundTab } else { Disposition::NewBackgroundTab }, from }); } }, Event::Permission(id, kind, request) => self.on_permission(id, kind, request), Event::Auth(id, request) => { let origin = request.origin(); let (username, password) = { let vault = self.shared.vault.borrow(); vault.logins_for(&origin).first().map(|l| (l.username.clone(), l.password.clone())).unwrap_or_default() }; match self.tab_mut(id) { Some(tab) => tab.dialog = Some(crate::tabs::Dialog::Auth { request, username, password }), None => request.cancel(), } if let Some((w, _)) = self.find_webview(id) { self.redraw(w); } }, Event::Control(id, control) => self.on_control(id, control), Event::Notification(id, notification) => self.on_notification(id, notification), Event::Page(id, message) => self.on_page_message(id, message), Event::Find(id, count) => self.on_find(id, count), Event::Audio(id, playing) => { let Some((w, i)) = self.find_webview(id) else { return }; self.windows.get_mut(&w).expect("found").tabs[i].playing_audio = playing; self.redraw(w); }, Event::SiteData(host, data) => { let mut current = self.shared.site_data.borrow_mut(); if current.0 == host { current.1 = Some(data); drop(current); self.redraw_all(); } }, Event::CookiesChanged => { self.shared.site_data.borrow_mut().0.clear(); if let Some(cookies) = &mut self.cookies { cookies.changed(Instant::now()); } }, } } fn on_load_status(&mut self, id: ViewId, status: LoadState) { let Some((w, i)) = self.find_webview(id) else { return }; match status { LoadState::Started => { let win = self.windows.get_mut(&w).expect("found"); let tab = &mut win.tabs[i]; tab.load_status = Some(status); tab.load_started = Some(Instant::now()); tab.progress = 0.0; tab.blocked = 0; tab.hidden_elements = 0; tab.crashed = None; tab.find = Default::default(); tab.media = None; tab.dialog = None; if matches!(tab.page, Some(Page::Error(..))) { tab.page = None; } tab.prompts.retain(|p| matches!(p, crate::tabs::Prompt::SaveLogin { .. })); if let Some(redo) = tab.redo.take() && let Some(view) = tab.webview() && view.url().as_ref() == Some(&redo) { view.load(&redo); } }, LoadState::Committed => { self.windows.get_mut(&w).expect("found").tabs[i].load_status = Some(status); self.apply_cosmetic(id); }, LoadState::Complete => { let (url, title, failed) = { let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i]; tab.load_status = Some(status); tab.load_started = None; tab.progress = 1.0; (tab.url.clone(), tab.title.clone(), matches!(tab.page, Some(Page::Error(..)))) }; if !failed { self.shared.history.borrow_mut().add(&url, &title); if let Some(tab) = self.tab_mut(id) { tab.upgraded_from = None; } } // Mute state survives navigation. let shared = self.shared.clone(); let muted = self.tab_mut(id).map(|t| t.muted || shared.settings.borrow().site_muted(&util::host_of_str(&t.url)) || shared.permissions.borrow().answer(&shared.settings.borrow(), &util::host_of_str(&t.url), crate::store::permissions::Kind::Sound) == crate::store::permissions::Answer::Block).unwrap_or(false); if let Some(tab) = self.tab_mut(id) { tab.muted = muted; if let Some(web) = &tab.web { web.webview.set_muted(muted); } } }, } self.redraw(w); } /// Hide the elements the lists name for this page. fn apply_cosmetic(&mut self, id: ViewId) { let (enabled, cosmetic) = { let s = self.shared.settings.borrow(); (s.adblock.enabled, s.adblock.cosmetic) }; if !enabled || !cosmetic { return; } let Some(tab) = self.tab_mut(id) else { return }; let url = tab.url.clone(); if self.shared.settings.borrow().adblock_paused_on(&util::host_of_str(&url)) { return; } let (selectors, _, _) = self.shared.adblock.page_selectors(&url); if selectors.is_empty() { return; } let Some((w, _)) = self.find_webview(id) else { return }; let options = self.zap_options(w); if let Some(tab) = self.tab_mut(id) && let Some(web) = &tab.web { web.webview.evaluate_javascript(inject::call("cosmetic.hide", &[serde_json::json!(selectors), options]), |_| {}); } } /// How a page removes the ads it hides (`cosmetic.hide`): animated in the window's theme colours unless the /// setting, Motion or still mode says no. pub fn zap_options(&self, w: WindowId) -> serde_json::Value { let s = self.shared.settings.borrow(); let motion = crate::theme::motion_scale(&s); let palette = self.windows.get(&w).map(|win| win.ui.palette()).unwrap_or_else(|| crate::ui::WindowUi::default().palette()); let c = palette.primary_container; serde_json::json!({ "animate": s.adblock.animate && motion > 0.0 && !crate::perf::still(&s), "ms": (900.0 * motion.max(0.3)).round() as u32, "bg": format!("rgba({},{},{},0.92)", c.r(), c.g(), c.b()), "badge": crate::theme::zap_badge(palette.primary, palette.on_primary), }) } fn on_favicon(&mut self, id: ViewId) { let Some((w, i)) = self.find_webview(id) else { return }; let win = self.windows.get_mut(&w).expect("found"); let ctx = win.ctx(); let tab = &mut win.tabs[i]; let Some(web) = &tab.web else { return }; let Some((width, height, rgba)) = web.webview.favicon_rgba() else { return }; if rgba.len() != (width * height * 4) as usize || width == 0 { return; } let colour = theme::dominant_vivid(&rgba); let changed = tab.favicon_colour != colour; tab.favicon_colour = colour; let color = egui::ColorImage::from_rgba_unmultiplied([width as usize, height as usize], &rgba); tab.favicon = Some(ctx.load_texture(format!("favicon-{}", tab.id), color, egui::TextureOptions::LINEAR)); let mut png = Vec::new(); if let Some(img) = image::RgbaImage::from_raw(width, height, rgba) && img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_ok() { tab.favicon_png = Some(png); } win.redraw(); if changed && self.shared.settings.borrow().theme.source == crate::store::settings::ColourSource::Website && self.windows[&w].active == i { self.restyle(w); } } /// Rebuilds a window's palette (the site colour changed). pub fn restyle(&mut self, w: WindowId) { if let Some(mut win) = self.windows.remove(&w) { self.style_window(&mut win); self.windows.insert(w, win); } self.redraw(w); } /// A pop-up opened as a tab next to its opener (WebKit already made its view, related to the opener's). /// Pop-ups open as tabs next to their opener (a related view keeps `window.opener`). /// As in Chromium, a site that wasn't asked about gets pop-ups only from a click or key press (S061). Pop-ups to /// addresses the ad lists block never get here: WebKit's content filters stop them. fn on_create_new(&mut self, parent: ViewId, view: View, url: Option, gesture: bool) { use crate::store::permissions::{Answer, Kind}; // D-049: a pop-up never opens one of Nacre's pages (WebKit's policy check denies it first; this is the // backstop). if url.as_ref().is_some_and(|u| !crate::tabs::web_may_open(u.as_str())) { eprintln!("pop-up to {} denied: web pages can't open Nacre's pages", url.as_ref().map(Url::as_str).unwrap_or("")); if let Some(engine) = &self.engine { engine.forget(view.id()); } view.close(); return; } let found = self.find_webview(parent); let blocked = found.is_some_and(|(w, i)| { let host = self.windows[&w].tabs[i].host(); match self.shared.permissions.borrow().answer(&self.shared.settings.borrow(), &host, Kind::Popups) { Answer::Allow => false, Answer::Block => true, Answer::Ask => !gesture, } }); let Some((w, i)) = found.filter(|_| !blocked) else { // WebKit already holds the view: the page sees its window close at once. if let Some(engine) = &self.engine { engine.forget(view.id()); } view.close(); if let Some((w, i)) = found { let url = url.map(|u| u.to_string()).unwrap_or_default(); self.windows.get_mut(&w).expect("found").tabs[i].prompts.push_back(crate::tabs::Prompt::PopupBlocked { url }); self.redraw(w); } return; }; let opener = self.windows[&w].tabs[i].id; let mut tab = Tab::new(view.id().0); tab.page = None; tab.url = String::new(); tab.title = String::new(); tab.opener = Some(opener); tab.load_status = Some(LoadState::Started); tab.web = Some(Web { webview: view }); let win = self.windows.get_mut(&w).expect("found"); let index = (i + 1).min(win.tabs.len()); win.tabs.insert(index, tab); win.active = index; win.focus_page(); win.redraw(); } fn on_permission(&mut self, id: ViewId, kind: crate::store::permissions::Kind, request: crate::engine::PermissionAsk) { use crate::store::permissions::Answer; let Some((w, i)) = self.find_webview(id) else { request.deny(); return; }; let host = self.windows[&w].tabs[i].host(); let answer = self.shared.permissions.borrow().answer(&self.shared.settings.borrow(), &host, kind); match answer { Answer::Allow => request.allow(), Answer::Block => request.deny(), Answer::Ask => { let win = self.windows.get_mut(&w).expect("found"); win.tabs[i].prompts.push_back(crate::tabs::Prompt::Permission { host, kind, request }); win.redraw(); }, } } fn on_control(&mut self, id: ViewId, control: Control) { let Some((w, i)) = self.find_webview(id) else { return }; match control { Control::Select(select) => self.windows.get_mut(&w).expect("found").tabs[i].dialog = Some(crate::tabs::Dialog::Select(select)), Control::Color(picker) => { let c = picker.current_color().unwrap_or([0, 0, 0]); self.windows.get_mut(&w).expect("found").tabs[i].dialog = Some(crate::tabs::Dialog::Color(picker, c)); }, Control::File(picker) => { let key = self.next_pending; self.next_pending += 1; let filters = picker.filter_patterns(); let multiple = picker.allow_select_multiple(); self.pending_files.insert(key, picker); self.spawn( "file-picker", move || { let mut dialog = rfd::FileDialog::new(); if !filters.is_empty() { dialog = dialog.add_filter("Allowed files", &filters); } if multiple { dialog.pick_files() } else { dialog.pick_file().map(|f| vec![f]) } }, move |app, picked: Option>| { if let Some(mut picker) = app.pending_files.remove(&key) { match picked { Some(paths) if !paths.is_empty() => { picker.select(&paths); picker.submit(); }, _ => picker.dismiss(), } } }, ); }, Control::Dialog(dialog) => { let win = self.windows.get_mut(&w).expect("found"); let origin = Url::parse(&win.tabs[i].url).map(|u| u.origin().ascii_serialization()).unwrap_or_default(); win.tabs[i].dialog = Some(crate::tabs::Dialog::Simple(dialog, origin)); }, Control::LeavePage(request) => { self.windows.get_mut(&w).expect("found").tabs[i].dialog = Some(crate::tabs::Dialog::LeavePage(request)); // A quit or window close asks tab by tab: show the one that asks. if self.shutdown.is_some() { self.select_tab(w, i); } }, Control::ContextMenu(menu) => { // Only when the page didn't cancel the right click (its own menu): WebKit asks either way once it // has shown one menu on the page. The page's answer comes from the bridge script, before or after. let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i]; match std::mem::take(&mut tab.menu_wait) { crate::tabs::MenuWait::Answer(true) => tab.context = None, crate::tabs::MenuWait::Answer(false) => self.show_page_menu(w, i, menu), _ => tab.menu_wait = crate::tabs::MenuWait::Menu(Box::new(menu), Instant::now()), } }, } self.redraw(w); } /// Nacre's right-click menu for a tab's page. pub fn show_page_menu(&mut self, w: WindowId, i: usize, menu: crate::engine::PageMenuRequest) { let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i]; let extra = tab.context.take(); let page_menu = crate::ui::menus::PageMenu::new(menu, extra, &tab.url, tab.media.is_some()); tab.dialog = Some(crate::tabs::Dialog::ContextMenu(Box::new(page_menu))); self.redraw(w); } fn on_notification(&mut self, id: Option, notification: crate::engine::Notification) { let host = id.and_then(|id| self.tab_mut(id).map(|t| t.host())).unwrap_or_default(); // WebKit shows only what the page was granted (a prompt answer, or the saved ones); a site blocked since stays quiet. let blocked = self.shared.permissions.borrow().answer(&self.shared.settings.borrow(), &host, crate::store::permissions::Kind::Notifications) == crate::store::permissions::Answer::Block; if blocked { return; } self.notifications_shown += 1; let title = if notification.title.is_empty() { host.clone() } else { notification.title.clone() }; let shown = cfg!(unix) && util::which("notify-send").is_some() && std::process::Command::new("notify-send").args(["-a", "Nacre", &title, ¬ification.body]).spawn().is_ok(); if !shown { self.shared.toast(format!("{title}: {}", notification.body)); } } fn check_app_scope(&mut self, window: WindowId, id: ViewId, url: &Url) { let app_id = match self.windows.get(&window).map(|w| &w.kind) { Some(Kind::App(app_id)) => app_id.clone(), _ => return, }; let Some(app) = self.shared.apps.borrow().get(&app_id).cloned() else { return }; if !matches!(url.scheme(), "http" | "https") || app.in_scope(url) { return; } // Left the app's site: go back in the app window and show the page in the browser. if let Some(tab) = self.tab_mut(id) && let Some(web) = &tab.web && web.webview.can_go_back() { web.webview.go_back(); } self.run(Command::Open { url: url.to_string(), how: Disposition::NewForegroundTab, from: None }); } // ── periodic work ───────────────────────────────────────────────── fn tick(&mut self) { let now = Instant::now(); // Finished work from other threads. while let Ok(job) = self.jobs_rx.try_recv() { job(self); } while let Ok(msg) = self.downloads_rx.try_recv() { self.on_download_msg(msg); } // A closing tab whose page doesn't answer goes after 3 s, unless it is asking. let hung: Vec<(WindowId, u64)> = self.windows.iter().flat_map(|(w, win)| win.tabs.iter().filter(|t| t.close_overdue(now)).map(|t| (*w, t.id))).collect(); for (w, tab) in hung { if self.shutdown_answered(tab) { continue; } self.close_tab(w, tab, true); } // A right click whose page never answered (no bridge script: scripts off): the menu shows after 300 ms. let unanswered: Vec<(WindowId, usize)> = self.windows.iter().flat_map(|(w, win)| win.tabs.iter().enumerate().filter(|(_, t)| matches!(t.menu_wait, crate::tabs::MenuWait::Menu(_, at) if now - at > Duration::from_millis(300))).map(|(i, _)| (*w, i))).collect(); for (w, i) in unanswered { if let crate::tabs::MenuWait::Menu(menu, _) = std::mem::take(&mut self.windows.get_mut(&w).expect("found").tabs[i].menu_wait) { self.show_page_menu(w, i, *menu); } } // Blocked counts for the toolbar. let counts: Vec<(ViewId, u32)> = self.hub.blocked.borrow().iter().map(|(k, v)| (*k, *v)).collect(); for (id, n) in counts { if let Some(tab) = self.tab_mut(id) && tab.blocked != n { tab.blocked = n; if let Some((w, _)) = self.find_webview(id) { self.redraw(w); } } } self.update_vpn_route(); self.update_media_now(); if self.selftest.is_some() { self.selftest_step(); } if now.duration_since(self.last_tick) >= Duration::from_millis(900) { self.last_tick = now; let before = self.shared.toasts.borrow().len(); self.shared.toasts.borrow_mut().retain(|t| t.until > now); if self.shared.toasts.borrow().len() != before { self.redraw_all(); } // Loading spinners and media position need regular redraws. let busy: Vec = self.windows.iter().filter(|(_, w)| w.tabs.iter().any(|t| t.loading() || t.audible())).map(|(id, _)| *id).collect(); for w in busy { self.redraw(w); } } if now.duration_since(self.last_presence) >= Duration::from_secs(5) { self.last_presence = now; self.update_presence(); } if now.duration_since(self.last_save) >= Duration::from_secs(3) { self.last_save = now; self.save_session(); self.flush_stores(); } if now.duration_since(self.last_slow) >= Duration::from_secs((crate::perf::rest_unit_secs() / 2).clamp(1, 30)) { self.last_slow = now; self.slow_tick(); } if let Some(cookies) = &mut self.cookies { cookies.tick(now); } } fn update_media_now(&mut self) { let now = self.media_tab().and_then(|id| self.find_tab(id)).and_then(|(w, i)| { let tab = &self.windows[&w].tabs[i]; tab.media.as_ref().map(|(state, received)| MediaNow { tab: tab.id, title: tab.display_title(), url: tab.url.clone(), host: tab.host(), state: state.clone(), received_ms: *received, muted: tab.muted }) }); let changed = match (&*self.shared.media_now.borrow(), &now) { (None, None) => false, (Some(a), Some(b)) => a.tab != b.tab || a.state != b.state || a.muted != b.muted, _ => true, }; if changed { *self.shared.media_now.borrow_mut() = now; self.redraw_all(); } // The visualizer runs only while someone looks at it. let ntp_media = self.shared.settings.borrow().ntp.elements.iter().any(|(k, on)| k == "media" && *on); let looked_at = self.windows.values().any(|w| w.ui.flyout == Some(crate::ui::Flyout::Media) || (ntp_media && w.tab().is_some_and(|t| t.page == Some(crate::tabs::Page::NewTab)))); let wanted = looked_at && self.shared.settings.borrow().media.visualizer == crate::store::settings::Visualizer::Auto && self.shared.media_now.borrow().as_ref().is_some_and(|m| !m.state.paused); let mut cava = self.shared.cava.borrow_mut(); if wanted && !cava.running() && Cava::available() { cava.start(&self.shared.paths.cache); } else if !wanted && cava.running() { cava.stop(); } } fn slow_tick(&mut self) { let settings = self.shared.settings.borrow().clone(); self.shared.vault.borrow_mut().autolock(settings.vault.autolock_min); self.rest_background_tabs(&settings); // Filter lists: refresh when they're older than the chosen interval. if settings.adblock.enabled && settings.adblock.update_days > 0 { let max_age = settings.adblock.update_days as u64 * 86_400; let dir = self.shared.paths.filter_lists(); let stale = settings.adblock.lists.iter().any(|k| AdBlocker::list_age(&dir, k).is_none_or(|age| age > max_age)); if stale && !self.shared.adblock.updating.load(std::sync::atomic::Ordering::Relaxed) && self.shared.started.elapsed() > Duration::from_secs(20) { self.update_filter_lists(max_age); } } // Update check, at most once a day. if settings.update.auto_check && !settings.update.repo.is_empty() && util::now().saturating_sub(settings.update.last_check) > crate::updates::DAY && self.shared.started.elapsed() > Duration::from_secs(20) && !self.shared.incognito { self.check_updates(false); } // Total blocked count. let total = std::mem::take(&mut *self.hub.blocked_total.borrow_mut()); if total > 0 { self.shared.settings.borrow_mut().adblock.total += total; self.applied.adblock.total = self.shared.settings.borrow().adblock.total; self.save_settings(); } } /// Memory saver: hidden tabs are marked frozen after `freeze_min` and unloaded after `discard_min`. fn rest_background_tabs(&mut self, settings: &Settings) { let (freeze, discard) = crate::perf::tab_rest_minutes(settings); let now = Instant::now(); for win in self.windows.values_mut() { let active = win.active; let mut win_detach = Vec::new(); for (i, tab) in win.tabs.iter_mut().enumerate() { if i == active || tab.web.is_none() || tab.audible() || tab.pip_size.is_some() || settings.keeps_active(&tab.host()) || tab.pinned && discard == 0 { continue; } let idle = now.duration_since(tab.last_shown).as_secs() / crate::perf::rest_unit_secs(); if discard > 0 && idle >= discard as u64 && !tab.pinned { // Unload: forget the web view, keep the address to load it again when shown. tab.pending_url = Some(tab.url.clone()); win_detach.extend(tab.take_web()); } else if freeze > 0 && idle >= freeze as u64 && !tab.frozen { // WebKit throttles hidden views by itself (bg-tabs.txt) and has no suspend call; the flag only drives the tab strip. tab.frozen = true; } } for view in win_detach { win.detach(&view); if let Some(engine) = &self.engine { engine.forget(view.id()); } } } } pub fn save_session(&mut self) { if self.shared.incognito { return; } let windows: Vec = self .windows .values() .filter(|w| w.kind == Kind::Normal) .map(|w| { let (width, height) = w.size(); crate::store::session::SavedWindow { tabs: w.tabs.iter().map(Tab::saved).collect(), active: w.active, width, height, maximized: w.window.is_maximized() } }) .collect(); if !windows.is_empty() { self.shared.session.borrow_mut().save(windows); } } pub fn flush_stores(&self) { self.shared.history.borrow_mut().flush(); self.shared.bookmarks.borrow_mut().flush(); self.shared.reading.borrow_mut().flush(); self.shared.downloads.borrow_mut().flush(); self.shared.permissions.borrow_mut().flush(); } pub fn save_settings(&self) { if !self.shared.incognito { self.shared.settings.borrow().save(&self.shared.paths.settings()); } } fn update_vpn_route(&mut self) { let Some(bridge) = &self.shared.bridge else { return }; let settings = self.shared.settings.borrow(); let tor_state = self.shared.tor.state(); let (route, status) = crate::net::route_for(&settings, &tor_state); drop(settings); let current = bridge.route(); if current.upstream != route.upstream || current.doh != route.doh { bridge.set_route(route); } if *self.shared.vpn_status.borrow() != status { *self.shared.vpn_status.borrow_mut() = status; self.redraw_all(); } } // ── windows ─────────────────────────────────────────────────────── pub fn open_window(&mut self, kind: Kind, tabs: Vec, active: usize, size: Option<(u32, u32)>) -> Option { let settings = self.shared.settings.borrow().clone(); let size = size.unwrap_or((settings.window.width, settings.window.height)); let decorated = !settings.ui.custom_title_bar || !matches!(kind, Kind::Normal); let title = match &kind { Kind::App(id) => self.shared.apps.borrow().get(id).map(|a| a.name.clone()).unwrap_or_else(|| "Nacre".into()), Kind::Pip { .. } => "Picture in picture — Nacre".to_owned(), Kind::Normal => (if self.shared.incognito { "Nacre (incognito)" } else { "Nacre" }).to_owned(), }; if self.engine.is_none() { self.start_engine(); } let id = WindowId(self.next_window_id); self.next_window_id += 1; let me = self.me.clone(); let ui: crate::egui_area::UiFn = Box::new(move |ui| match me.upgrade() { Some(app) => app.try_borrow_mut().map(|mut app| app.draw_ui(id, ui)).map_err(|_| ()), None => Ok(None), }); let me = self.me.clone(); let busy = Box::new(move || me.upgrade().is_some_and(|app| app.try_borrow_mut().is_err())); let mut win = BrowserWindow::create(&self.gtk, id, kind.clone(), &title, size, decorated, ui, busy); if let Kind::Pip { window: source, .. } = &kind && let Some(parent) = self.windows.get(source) { // A window with a parent floats on tiling compositors (niri) without a user rule; its own app id lets a // rule still pick it out. win.window.set_transient_for(Some(&parent.window)); crate::window::set_app_id(&win.window, "dev.nacre.Nacre.Pip"); } if settings.window.maximized && kind == Kind::Normal && self.windows.is_empty() { win.window.maximize(); } self.style_window(&mut win); self.connect_window(&win); win.tabs = tabs; win.active = active.min(win.tabs.len().saturating_sub(1)); win.window.present(); win.area.grab_focus(); self.windows.insert(id, win); if kind == Kind::Normal { self.last_window = Some(id); } // Load what the active tab needs now; other restored tabs load when first shown. self.ensure_loaded(id); self.redraw(id); schedule_pump(); Some(id) } /// Window-level GTK handlers: close, focus, browser shortcuts (capture phase, so they work while the page has /// the keyboard), Ctrl+wheel zoom over the page. fn connect_window(&self, win: &BrowserWindow) { let id = win.id; let me = self.me.clone(); win.window.connect_close_request(move |_| { if let Some(app) = me.upgrade() { with_app(&app, move |app| app.close_window(id)); } glib::Propagation::Stop }); let me = self.me.clone(); win.window.connect_is_active_notify(move |w| { let focused = w.is_active(); if let Some(app) = me.upgrade() { with_app(&app, move |app| { if let Some(win) = app.windows.get_mut(&id) { win.focused = focused; win.area.set_window_focused(focused); if focused && win.kind == Kind::Normal { app.last_window = Some(id); } } }); } }); let keys = gtk::EventControllerKey::new(); keys.set_propagation_phase(gtk::PropagationPhase::Capture); let me = self.me.clone(); keys.connect_key_pressed(move |c, key, code, state| { let Some(app) = me.upgrade() else { return glib::Propagation::Proceed }; let Ok(mut app) = app.try_borrow_mut() else { return glib::Propagation::Proceed }; let base = c.current_event().and_then(|e| e.display()).and_then(|d| d.translate_key(code, gdk::ModifierType::empty(), 0)).map(|(k, ..)| k).unwrap_or(key); if app.window_key(id, base, state) { drop(app); schedule_pump(); glib::Propagation::Stop } else { glib::Propagation::Proceed } }); win.window.add_controller(keys); let scroll = gtk::EventControllerScroll::new(gtk::EventControllerScrollFlags::VERTICAL); scroll.set_propagation_phase(gtk::PropagationPhase::Capture); let me = self.me.clone(); let area = win.area.downgrade(); scroll.connect_scroll(move |c, _dx, dy| { let ctrl = c.current_event_state().contains(gdk::ModifierType::CONTROL_MASK); let over_ui = area.upgrade().is_some_and(|a| { let ptr = c.current_event().and_then(|e| e.position()); ptr.is_some_and(|(x, y)| a.contains(x, y)) }); if !ctrl || over_ui || dy == 0.0 { return glib::Propagation::Proceed; } if let Some(app) = me.upgrade() { with_app(&app, move |app| app.run_in(id, Command::Zoom(if dy < 0.0 { 1 } else { -1 }))); } glib::Propagation::Stop }); win.window.add_controller(scroll); // Mouse back/forward buttons (8/9) navigate over the page and the chrome; WebKit has no use for them. let sides = gtk::GestureClick::new(); sides.set_button(0); sides.set_propagation_phase(gtk::PropagationPhase::Capture); let me = self.me.clone(); sides.connect_pressed(move |g, _, _, _| { let back = match g.current_button() { 8 => true, 9 => false, _ => return, }; g.set_state(gtk::EventSequenceState::Claimed); if let Some(app) = me.upgrade() { with_app(&app, move |app| { let blocked = app.windows.get(&id).is_some_and(|w| w.tab().is_some_and(|t| t.dialog.is_some()) || w.ui.blocks_page()); if !blocked { app.run_in(id, if back { Command::Back } else { Command::Forward }); } }); } }); win.window.add_controller(sides); } /// A key press anywhere in the window, before the focused widget sees it. True: it was a browser shortcut. fn window_key(&mut self, window: WindowId, key: gdk::Key, state: gdk::ModifierType) -> bool { // The page's right-click menu answers arrows, Enter and Escape wherever the keyboard is: the page keeps it // (WebKit takes it back after the right click), so they go to the menu before the page sees them (S061). if let Some(win) = self.windows.get_mut(&window) && win.tab().is_some_and(|t| matches!(t.dialog, Some(crate::tabs::Dialog::ContextMenu(_)))) && let Some(k) = match key { gdk::Key::Escape => Some(egui::Key::Escape), gdk::Key::Up | gdk::Key::KP_Up => Some(egui::Key::ArrowUp), gdk::Key::Down | gdk::Key::KP_Down => Some(egui::Key::ArrowDown), gdk::Key::Return | gdk::Key::KP_Enter => Some(egui::Key::Enter), _ => None, } { for pressed in [true, false] { win.area.push(egui::Event::Key { key: k, physical_key: Some(k), pressed, repeat: false, modifiers: egui::Modifiers::NONE }); } win.redraw(); return true; } let Some(shortcut) = crate::keys::Shortcut::from_gdk(key, state) else { return false }; let Some(action) = self.shared.keymap.borrow().action_for(&shortcut) else { return false }; let Some(win) = self.windows.get_mut(&window) else { return false }; win.last_input = Instant::now(); // Recording a shortcut in settings: every key goes to that page. if win.ui.pages.capture_key.is_some() { return false; } // Escape ends picture in picture, wherever the window's keyboard is (the overlay takes it on every click). if matches!(win.kind, Kind::Pip { .. }) && action == crate::keys::Action::Stop { self.ui_commands.push((window, Command::ExitPip)); return true; } win.page_focused = !win.area.has_focus(); let egui_wants_keys = win.area.ctx().egui_wants_keyboard_input(); let dialog_open = win.tab().is_some_and(|t| t.dialog.is_some()) || win.ui.blocks_page(); let typing_ui = egui_wants_keys && !win.page_focused; let plain = !shortcut.ctrl && !shortcut.alt && !shortcut.meta; let skip = typing_ui && plain || (action == crate::keys::Action::Stop && (dialog_open || win.ui.has_popup() || typing_ui)); if skip || crate::keys::page_gets_key(action, win.page_focused && plain, win.fullscreen) { return false; } self.ui_commands.push((window, Command::Action(action))); true } pub fn style_window(&self, win: &mut BrowserWindow) { let settings = self.shared.settings.borrow(); let dark = theme::is_dark(&settings, *self.shared.system_dark.borrow()); let site = win.tab().and_then(Tab::site_colour); let palette = theme::Palette::new(theme::seed(&settings, site, self.shared.system_accent), dark, &settings.theme.variant, settings.theme.contrast); let ctx = win.ctx(); theme::apply(&ctx, &palette, &settings); // Always, so going back to 100 % takes effect too. ctx.set_zoom_factor(settings.ui.scale.clamp(0.5, 3.0)); win.ui.palette = Some(palette); win.ui.site_colour = site; win.redraw(); } /// Create the web view for the active tab if it doesn't have one yet (lazy restore, unloaded tab). pub fn ensure_loaded(&mut self, window: WindowId) { let Some(win) = self.windows.get(&window) else { return }; let Some(tab) = win.tab() else { return }; let Some(url) = tab.pending_url.clone() else { return }; let (i, tab_id) = (win.active, tab.id); if let Some(page) = Page::from_url(&url) { let win = self.windows.get_mut(&window).expect("found"); win.tabs[i].page = Some(page); win.tabs[i].pending_url = None; return; } let Ok(parsed) = Url::parse(&url) else { let win = self.windows.get_mut(&window).expect("found"); win.tabs[i].pending_url = None; return; }; let history = self.windows.get_mut(&window).expect("found").tabs[i].history_state.take(); let web = self.build_webview(tab_id, parsed, history); let win = self.windows.get_mut(&window).expect("found"); let tab = &mut win.tabs[i]; tab.web = Some(web); tab.page = None; tab.pending_url = None; tab.url = url; tab.load_status = Some(LoadState::Started); } /// Load every tab of a window that is waiting for its page (restore without lazy loading). pub fn load_all_pending(&mut self, window: WindowId) { let Some(win) = self.windows.get(&window) else { return }; let pending: Vec<(usize, u64, String)> = win.tabs.iter().enumerate().filter_map(|(i, t)| t.pending_url.clone().map(|u| (i, t.id, u))).collect(); for (i, tab_id, url) in pending { let Ok(parsed) = Url::parse(&url) else { continue }; if Page::from_url(&url).is_some() { continue; } let history = self.windows.get_mut(&window).expect("found").tabs[i].history_state.take(); let web = self.build_webview(tab_id, parsed, history); let win = self.windows.get_mut(&window).expect("found"); let tab = &mut win.tabs[i]; tab.web = Some(web); tab.page = None; tab.pending_url = None; tab.url = url; tab.load_status = Some(LoadState::Started); } } pub fn close_window(&mut self, window: WindowId) { let Some(win) = self.windows.get(&window) else { return }; let normal_left = self.windows.values().filter(|w| w.kind == Kind::Normal).count(); if win.kind == Kind::Normal && normal_left <= 1 { // Closing the last browser window quits. self.quit(); return; } if !self.begin_shutdown(Some(window)) { self.close_window_now(window); } } /// Asks every page of the window (all windows when None) to run `beforeunload`; false when none needs asking. /// Pages that don't mind answer at once (`Event::Closed`), one that asks shows Nacre's "Leave this page?". fn begin_shutdown(&mut self, window: Option) -> bool { if self.shutdown.is_some() { return true; } let mut waiting = Vec::new(); for (_, win) in self.windows.iter_mut().filter(|(id, _)| window.is_none_or(|w| w == **id)) { for tab in win.tabs.iter_mut() { if tab.closing.is_none() && tab.crashed.is_none() && tab.page.is_none() && let Some(view) = tab.web.as_ref().map(|web| web.webview.clone()) { tab.closing = Some(Instant::now()); waiting.push(tab.id); view.close(); } } } if waiting.is_empty() { return false; } if window.is_none() { // The tabs stay in the session whatever the pages answer. self.save_session(); } self.shutdown = Some(Shutdown { window, waiting, answered: Vec::new() }); true } /// A page answered `beforeunload` with yes (or hung); when all have, the quit or window close goes on. /// False when the tab isn't part of a shutdown. fn shutdown_answered(&mut self, tab_id: u64) -> bool { let Some(s) = self.shutdown.as_mut() else { return false }; let Some(at) = s.waiting.iter().position(|t| *t == tab_id) else { return false }; s.answered.push(s.waiting.remove(at)); if s.waiting.is_empty() && let Some(s) = self.shutdown.take() { for tab in self.windows.values_mut().flat_map(|w| w.tabs.iter_mut()) { tab.closing = None; } match s.window { Some(w) => self.close_window_now(w), None => self.quit_now(), } } true } /// A page said "Stay": the quit or window close is off, and the pages that had already said yes are reloaded. pub fn cancel_shutdown(&mut self) { let Some(s) = self.shutdown.take() else { return }; for tab in self.windows.values_mut().flat_map(|w| w.tabs.iter_mut()) { if s.answered.contains(&tab.id) { if let Some(web) = &tab.web { web.webview.reload(); } } if s.answered.contains(&tab.id) || s.waiting.contains(&tab.id) { tab.closing = None; } } } fn close_window_now(&mut self, window: WindowId) { let Some(win) = self.windows.get(&window) else { return }; let normal_left = self.windows.values().filter(|w| w.kind == Kind::Normal).count(); if win.kind == Kind::Normal && normal_left <= 1 { self.quit_now(); return; } if let Kind::Pip { window: source, tab } = win.kind.clone() { self.exit_pip(source, tab); } let Some(mut win) = self.windows.remove(&window) else { return }; if win.kind == Kind::Normal { for tab in &win.tabs { self.shared.session.borrow_mut().push_closed(tab.saved()); } } for tab in &win.tabs { if let (Some(web), Some(engine)) = (&tab.web, &self.engine) { engine.forget(web.webview.id()); } } win.destroy(); if self.last_window == Some(window) { self.last_window = None; } } /// Quit, after the pages had their say on `beforeunload`. pub fn quit(&mut self) { if self.exiting { return; } if !self.begin_shutdown(None) { self.quit_now(); } } /// Quit without asking the pages. pub fn quit_now(&mut self) { if self.exiting { return; } self.exiting = true; self.save_session(); // Remember the size of the main window. if let Some(w) = self.current_window().and_then(|w| self.windows.get(&w)) { let (width, height) = w.size(); let mut s = self.shared.settings.borrow_mut(); s.window.maximized = w.window.is_maximized(); if !s.window.maximized { s.window.width = width; s.window.height = height; } } let total = std::mem::take(&mut *self.hub.blocked_total.borrow_mut()); self.shared.settings.borrow_mut().adblock.total += total; self.save_settings(); self.clear_on_exit(); if let Some(cookies) = self.cookies.take() { cookies.finish(self.shared.settings.borrow().privacy.clear_on_exit.iter().any(|w| w == "cookies")); } self.flush_stores(); for control in self.download_controls.values() { control.store(download::PAUSE, Ordering::Relaxed); } self.shared.tor.stop(); self.shared.cava.borrow_mut().stop(); if let Some(mut presence) = self.presence.take() { presence.stop(); } // Views first (they leave their windows), then the windows; the engine goes last. self.window_requests.clear(); self.pending_files.clear(); self.hub.clear(); for (_, mut win) in self.windows.drain() { win.destroy(); win.tabs.clear(); } let _ = std::fs::remove_file(self.shared.paths.running_marker()); if let Some(server) = self.instance.take() { server.stop(); } self.shared.paths.remove_incognito(); self.gtk.quit(); } fn clear_on_exit(&mut self) { let what = self.shared.settings.borrow().privacy.clear_on_exit.clone(); if what.is_empty() { return; } if what.iter().any(|w| w == "history") { self.shared.history.borrow_mut().clear_since(0); } if what.iter().any(|w| w == "downloads") { self.shared.downloads.borrow_mut().clear_inactive(); } if let Some(engine) = &self.engine { engine.clear_data(what.iter().any(|w| w == "cookies"), what.iter().any(|w| w == "cache"), 0, None); } } /// The first windows: restored session, an app window, or a new tab. pub fn open_initial(&mut self) { *self.shared.system_dark.borrow_mut() = theme::system_dark(gtk_dark()); // Without a font DPI from the desktop (gtk-xft-dpi -1, as in a bare session), WebKit gave every view after // the first a NaN zoom level: blank pages, innerWidth 0. 96 dpi is GTK's own default. if let Some(settings) = gtk::Settings::default() && settings.gtk_xft_dpi() <= 0 { settings.set_gtk_xft_dpi(96 * 1024); } rustls_provider(); match crate::instance::Server::start(&self.shared.paths, self.jobs_tx.clone()) { Ok(server) => self.instance = Some(server), Err(error) => log::warn!("single instance: {error}"), } let launch = self.launch.clone(); self.first_setup(); if let Some(app_id) = &launch.app { self.open_app_window(app_id); if !self.windows.is_empty() { return; } } let settings = self.shared.settings.borrow().clone(); let restore = !self.shared.incognito && (settings.startup.mode == crate::store::settings::StartupMode::Restore) && self.shared.session.borrow().has_previous(); if restore { let previous = self.shared.session.borrow().previous.clone(); for saved in previous.windows { if saved.tabs.is_empty() { continue; } let tabs: Vec = saved.tabs.iter().map(|s| self.tab_from_saved(s)).collect(); let size = (saved.width > 0).then_some((saved.width, saved.height)); if let Some(id) = self.open_window(Kind::Normal, tabs, saved.active, size) && !settings.perf.lazy_restore { self.load_all_pending(id); } } } if self.windows.is_empty() { let mut tab = Tab::new(self.new_tab_id()); if !settings.startup.welcome_done && !self.shared.incognito { tab.page = Some(Page::Welcome); } else if settings.startup.mode == crate::store::settings::StartupMode::Home { tab.pending_url = Some(settings.startup.home_url.clone()); } self.open_window(Kind::Normal, vec![tab], 0, None); } if self.crashed_last_time && !restore && self.shared.session.borrow().has_previous() { self.shared.toast_with("Nacre didn't close properly last time.", "Restore tabs", Command::RestoreSession); } for url in launch.urls { self.run(Command::Open { url, how: Disposition::NewForegroundTab, from: None }); } if self.windows.is_empty() { log::error!("no window could be opened"); self.gtk.quit(); } } fn first_setup(&mut self) { // Ad blocker: compile from the cached lists in the background. self.rebuild_adblock(); // Tor and other background services that settings ask for. let settings = self.shared.settings.borrow().clone(); if settings.vpn.enabled && settings.vpn.provider == crate::store::settings::VpnProvider::Tor { self.shared.tor.start(&self.shared.paths.tor_data(), self.wake()); } if settings.rpc.enabled && !self.shared.incognito { self.presence = Some(Presence::start(self.wake())); } if settings.spell.enabled { self.load_speller(); } self.ping_download_managers(); if !self.shared.incognito { self.spawn("import-scan", crate::importer::find_sources, move |app, sources| { *app.shared.import_sources.borrow_mut() = sources; }); } // The system's light/dark choice, live. if let Some(gtk_settings) = gtk::Settings::default() { let me = self.me.clone(); gtk_settings.connect_gtk_interface_color_scheme_notify(move |_| { if SETTING_SCHEME.get() { return; } if let Some(app) = me.upgrade() { with_app(&app, |app| { *app.shared.system_dark.borrow_mut() = theme::system_dark(gtk_dark()); app.restyle_all(); }); } }); } } pub fn tab_from_saved(&mut self, saved: &crate::store::session::SavedTab) -> Tab { let mut tab = Tab::new(self.new_tab_id()); tab.pinned = saved.pinned; tab.muted = saved.muted; tab.title = saved.title.clone(); let url = crate::store::session::kept_url(&saved.url); if url != saved.url { tab.title = String::new(); } match Page::from_url(url) { Some(page) => tab.page = Some(page), None => { tab.page = None; tab.url = saved.url.clone(); tab.pending_url = Some(saved.url.clone()); }, } tab } // ── drawing ─────────────────────────────────────────────────────── /// One frame of a window's interface (called by its egui area while GTK paints). Returns the page rect. fn draw_ui(&mut self, window: WindowId, root: &mut egui::Ui) -> Option { // An internal page shown in a web tab, or Back to the page behind it, changes the site colour. if self.windows.get(&window).is_some_and(|w| w.tab().and_then(Tab::site_colour) != w.ui.site_colour) && let Some(mut win) = self.windows.remove(&window) { self.style_window(&mut win); self.windows.insert(window, win); } let win = self.windows.get_mut(&window)?; let started = Instant::now(); let page_rect_before = win.page_rect; let mut commands = Vec::new(); let shared = self.shared.clone(); let hub = self.hub.clone(); { let BrowserWindow { tabs, active, ui, page_rect, kind, fullscreen, .. } = win; let mut frame = crate::ui::Frame { shared: &shared, hub: &hub, tabs, active, ui, page_rect, kind, fullscreen: *fullscreen, commands: &mut commands, window_id: window }; crate::ui::draw(root, &mut frame); } if win.frame_times.len() >= 120 { win.frame_times.pop_front(); } win.frame_times.push_back(started.elapsed().as_secs_f32() * 1000.0); win.frames_drawn += 1; let page = win.page_rect; if page != page_rect_before || !commands.is_empty() { schedule_pump(); } self.ui_commands.extend(commands.into_iter().map(|c| (window, c))); // While the tab shows a dialog or a page menu, egui takes the pointer over the page too, so a click beside a // menu closes it (and the page under a dialog gets no clicks). if win.tab().is_some_and(|t| t.dialog.is_some()) { return None; } page } pub fn restyle_all(&mut self) { let ids: Vec = self.windows.keys().copied().collect(); for id in ids { if let Some(mut win) = self.windows.remove(&id) { self.style_window(&mut win); self.windows.insert(id, win); } } self.apply_web_scheme(); self.redraw_all(); } } /// Run `f` on the app now, or right after whatever holds it. pub fn with_app(app: &Rc>, f: impl FnOnce(&mut App) + 'static) { match app.try_borrow_mut() { Ok(mut a) => { f(&mut a); drop(a); schedule_pump(); }, Err(_) => { let weak = Rc::downgrade(app); glib::idle_add_local_once(move || { if let Some(app) = weak.upgrade() { with_app(&app, f); } }); }, } } /// GTK's view of the system colour scheme (None: GTK doesn't know). fn gtk_dark() -> Option { let settings = gtk::Settings::default()?; match settings.gtk_interface_color_scheme() { gtk::InterfaceColorScheme::Dark => Some(true), gtk::InterfaceColorScheme::Light => Some(false), _ => None, } } /// rustls needs a process-wide crypto provider before ureq makes a TLS connection. pub fn rustls_provider() { let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); }