1930 lines
85 KiB
Rust
1930 lines
85 KiB
Rust
//! The browser: owns Servo, the windows, the stores and the background services, and runs the
|
|
//! winit event loop. Servo's events come in through `hub::Hub`; UI clicks and shortcuts become
|
|
//! `Command`s handled in `actions.rs`.
|
|
|
|
use std::cell::RefCell;
|
|
use std::collections::HashMap;
|
|
use std::path::PathBuf;
|
|
use std::rc::Rc;
|
|
use std::sync::atomic::AtomicU8;
|
|
use std::sync::mpsc::{self, Receiver, Sender};
|
|
use std::sync::Arc;
|
|
use std::time::{Duration, Instant};
|
|
|
|
use servo::{EventLoopWaker, LoadStatus, Opts, Preferences, Servo, ServoBuilder, UserContentManager, UserScript, WebView, WebViewId};
|
|
use url::Url;
|
|
use winit::application::ApplicationHandler;
|
|
use winit::event::{ElementState, StartCause, WindowEvent};
|
|
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoopProxy};
|
|
use winit::window::WindowId;
|
|
|
|
use crate::actions::{Command, Disposition};
|
|
use crate::adblock::AdBlocker;
|
|
use crate::discord::Presence;
|
|
use crate::hub::{Event, Hub, HubConfig};
|
|
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::{self, BrowserWindow, Kind};
|
|
use crate::{inject, theme, util};
|
|
|
|
/// Wakes the event loop from other threads (Servo, workers, downloads).
|
|
#[derive(Debug, Clone, Copy)]
|
|
pub enum AppEvent {
|
|
Wake,
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct Waker(pub EventLoopProxy<AppEvent>);
|
|
|
|
impl EventLoopWaker for Waker {
|
|
fn clone_box(&self) -> Box<dyn EventLoopWaker> {
|
|
Box::new(self.clone())
|
|
}
|
|
fn wake(&self) {
|
|
let _ = self.0.send_event(AppEvent::Wake);
|
|
}
|
|
}
|
|
|
|
/// Work finished on another thread, run on the main thread.
|
|
pub type Job = Box<dyn FnOnce(&mut App) + Send>;
|
|
|
|
/// What the command line asked for.
|
|
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
|
|
pub struct Launch {
|
|
pub urls: Vec<String>,
|
|
pub new_window: bool,
|
|
pub app: Option<String>,
|
|
pub incognito: bool,
|
|
pub profile: Option<String>,
|
|
}
|
|
|
|
/// 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<Settings>,
|
|
pub history: RefCell<History>,
|
|
pub bookmarks: RefCell<Bookmarks>,
|
|
pub reading: RefCell<ReadingList>,
|
|
pub downloads: RefCell<Downloads>,
|
|
pub permissions: RefCell<Permissions>,
|
|
pub session: RefCell<Session>,
|
|
pub vault: RefCell<Vault>,
|
|
pub apps: RefCell<Apps>,
|
|
pub scripts: RefCell<Scripts>,
|
|
pub keymap: RefCell<Keymap>,
|
|
pub adblock: Arc<AdBlocker>,
|
|
pub bridge: Option<Arc<Bridge>>,
|
|
pub tor: Tor,
|
|
pub vpn_status: RefCell<VpnStatus>,
|
|
pub speller: RefCell<Option<Speller>>,
|
|
pub spell_status: RefCell<String>,
|
|
pub system_accent: Option<egui::Color32>,
|
|
pub user_agent: RefCell<String>,
|
|
pub devtools: RefCell<Option<(u16, String)>>,
|
|
pub update: RefCell<Option<crate::updates::Release>>,
|
|
pub update_status: RefCell<String>,
|
|
pub dlm_status: RefCell<HashMap<String, Result<String, String>>>,
|
|
pub import_sources: RefCell<Vec<crate::importer::Source>>,
|
|
pub import_status: RefCell<String>,
|
|
pub toasts: RefCell<Vec<Toast>>,
|
|
pub weather: RefCell<Option<(String, f64, u32)>>,
|
|
pub adblock_status: RefCell<String>,
|
|
pub system_dark: RefCell<bool>,
|
|
/// Hosts the user chose to open over plain http this session.
|
|
pub http_allowed: RefCell<Vec<String>>,
|
|
/// Address-bar search suggestions for the last query: (query, suggestions).
|
|
pub suggestions: RefCell<(String, Vec<String>)>,
|
|
/// 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<Option<MediaNow>>,
|
|
/// Real audio levels (visualizer).
|
|
pub cava: RefCell<Cava>,
|
|
/// Downloaded artwork, decoded: url -> image (None while loading or failed).
|
|
pub art_images: RefCell<HashMap<String, Option<egui::ColorImage>>>,
|
|
/// Discord Rich Presence connection status.
|
|
pub presence_status: RefCell<String>,
|
|
/// Page sources for nacre://source: url -> text or error (None while loading).
|
|
pub sources: RefCell<HashMap<String, Option<Result<String, String>>>>,
|
|
}
|
|
|
|
#[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<String>) {
|
|
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<String>, label: impl Into<String>, command: Command) {
|
|
self.toasts.borrow_mut().push(Toast { text: text.into(), action: Some((label.into(), command)), until: Instant::now() + Duration::from_secs(8) });
|
|
}
|
|
}
|
|
|
|
pub struct App {
|
|
pub proxy: EventLoopProxy<AppEvent>,
|
|
pub jobs_tx: Sender<Job>,
|
|
jobs_rx: Receiver<Job>,
|
|
pub downloads_tx: Sender<download::Msg>,
|
|
downloads_rx: Receiver<download::Msg>,
|
|
pub servo: Option<Servo>,
|
|
pub hub: Rc<Hub>,
|
|
pub shared: Rc<Shared>,
|
|
pub windows: HashMap<WindowId, BrowserWindow>,
|
|
/// Most recently focused normal window.
|
|
pub last_window: Option<WindowId>,
|
|
pub ucm: Option<Rc<UserContentManager>>,
|
|
pub user_scripts: Vec<Rc<UserScript>>,
|
|
pub next_tab_id: u64,
|
|
pub launch: Launch,
|
|
pub pending_launches: Vec<Launch>,
|
|
pub pending_nav: HashMap<u64, servo::NavigationRequest>,
|
|
pub pending_files: HashMap<u64, servo::FilePicker>,
|
|
pub next_pending: u64,
|
|
pub download_controls: HashMap<u64, Arc<AtomicU8>>,
|
|
pub presence: Option<Presence>,
|
|
pub presence_started: Option<(u64, String, i64)>,
|
|
pub gilrs: Option<gilrs::Gilrs>,
|
|
pub gamepads: HashMap<gilrs::GamepadId, usize>,
|
|
pub applied: Settings,
|
|
pub exiting: bool,
|
|
last_tick: Instant,
|
|
last_save: Instant,
|
|
last_slow: Instant,
|
|
last_presence: Instant,
|
|
pub crashed_last_time: bool,
|
|
pub instance: Option<crate::instance::Server>,
|
|
/// Windows that commands asked for; opened when the event loop is at hand.
|
|
pub window_requests: Vec<WindowRequest>,
|
|
pub selftest: Option<crate::selftest::SelfTest>,
|
|
/// Commands waiting for a window to exist.
|
|
pub pending_commands: Vec<Command>,
|
|
/// Picture-in-picture windows to close after their tab went away.
|
|
pub window_closes: Vec<Kind>,
|
|
}
|
|
|
|
pub struct WindowRequest {
|
|
pub kind: Kind,
|
|
pub tabs: Vec<Tab>,
|
|
pub active: usize,
|
|
pub size: Option<(u32, u32)>,
|
|
}
|
|
|
|
pub fn wake_fn(proxy: &EventLoopProxy<AppEvent>) -> Arc<dyn Fn() + Send + Sync> {
|
|
let proxy = proxy.clone();
|
|
Arc::new(move || {
|
|
let _ = proxy.send_event(AppEvent::Wake);
|
|
})
|
|
}
|
|
|
|
impl App {
|
|
pub fn new(proxy: EventLoopProxy<AppEvent>, paths: Paths, launch: Launch) -> App {
|
|
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())),
|
|
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()),
|
|
presence_status: RefCell::new("Off".into()),
|
|
incognito,
|
|
paths,
|
|
};
|
|
let (jobs_tx, jobs_rx) = mpsc::channel();
|
|
let (downloads_tx, downloads_rx) = mpsc::channel();
|
|
App {
|
|
proxy,
|
|
jobs_tx,
|
|
jobs_rx,
|
|
downloads_tx,
|
|
downloads_rx,
|
|
servo: None,
|
|
hub,
|
|
shared: Rc::new(shared),
|
|
windows: HashMap::new(),
|
|
last_window: None,
|
|
ucm: None,
|
|
user_scripts: Vec::new(),
|
|
next_tab_id: 1,
|
|
launch,
|
|
pending_launches: Vec::new(),
|
|
pending_nav: HashMap::new(),
|
|
pending_files: HashMap::new(),
|
|
next_pending: 1,
|
|
download_controls: HashMap::new(),
|
|
presence: None,
|
|
presence_started: None,
|
|
gilrs: None,
|
|
gamepads: HashMap::new(),
|
|
applied: settings,
|
|
exiting: false,
|
|
last_tick: Instant::now(),
|
|
last_save: Instant::now(),
|
|
last_slow: Instant::now() - Duration::from_secs(3600),
|
|
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(),
|
|
}
|
|
}
|
|
|
|
pub fn wake(&self) -> Arc<dyn Fn() + Send + Sync> {
|
|
wake_fn(&self.proxy)
|
|
}
|
|
|
|
/// Run `work` on a worker thread, then `done` with its result on the main thread.
|
|
pub fn spawn<T: Send + 'static>(&self, name: &str, work: impl FnOnce() -> T + Send + 'static, done: impl FnOnce(&mut App, T) + Send + 'static) {
|
|
let tx = self.jobs_tx.clone();
|
|
let proxy = self.proxy.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)));
|
|
let _ = proxy.send_event(AppEvent::Wake);
|
|
});
|
|
}
|
|
|
|
pub fn new_tab_id(&mut self) -> u64 {
|
|
let id = self.next_tab_id;
|
|
self.next_tab_id += 1;
|
|
id
|
|
}
|
|
|
|
// ── Servo ──────────────────────────────────────────────────────────
|
|
|
|
fn start_servo(&mut self) {
|
|
let settings = self.shared.settings.borrow().clone();
|
|
let mut prefs = Preferences::default();
|
|
if let Some(bridge) = &self.shared.bridge {
|
|
let proxy = bridge.proxy_url();
|
|
prefs.network_http_proxy_uri = proxy.clone();
|
|
prefs.network_https_proxy_uri = proxy;
|
|
prefs.network_http_no_proxy = String::new();
|
|
}
|
|
if !settings.web.user_agent.trim().is_empty() {
|
|
prefs.user_agent = settings.web.user_agent.trim().to_owned();
|
|
}
|
|
*self.shared.user_agent.borrow_mut() = prefs.user_agent.clone();
|
|
crate::net::fetch::set_user_agent(&prefs.user_agent);
|
|
prefs.dom_webxr_enabled = false;
|
|
prefs.dom_webgpu_enabled = false;
|
|
prefs.dom_bluetooth_enabled = true;
|
|
prefs.dom_gamepad_enabled = true;
|
|
prefs.dom_notification_enabled = true;
|
|
prefs.dom_geolocation_enabled = true;
|
|
prefs.thread_pool_webrender_workers_max = 2;
|
|
if crate::perf::lite(&settings) {
|
|
prefs.layout_threads = 1;
|
|
prefs.thread_pool_webrender_workers_max = 1;
|
|
prefs.session_history_max_length = 10;
|
|
prefs.network_http_cache_size = 1000;
|
|
}
|
|
if !self.shared.incognito {
|
|
prefs.network_http_disk_cache = self.shared.paths.data.join("http-cache").to_string_lossy().into_owned();
|
|
}
|
|
if settings.web.remote_debugging {
|
|
prefs.devtools_server_enabled = true;
|
|
prefs.devtools_server_listen_address = "127.0.0.1:6080".to_owned();
|
|
}
|
|
let dark = theme::is_dark(&settings, *self.shared.system_dark.borrow());
|
|
prefs.shell_background_color_rgba = if dark { [0.1, 0.1, 0.1, 1.0] } else { [1.0, 1.0, 1.0, 1.0] };
|
|
let opts = Opts { config_dir: Some(self.shared.paths.engine()), temporary_storage: self.shared.incognito, multiprocess: false, ..Opts::default() };
|
|
let _ = std::fs::create_dir_all(self.shared.paths.engine());
|
|
let servo = ServoBuilder::default().opts(opts).preferences(prefs).event_loop_waker(Box::new(Waker(self.proxy.clone()))).build();
|
|
servo.set_delegate(self.hub.clone());
|
|
servo.setup_logging();
|
|
*self.hub.servo.borrow_mut() = Some(servo.clone());
|
|
self.ucm = Some(Rc::new(UserContentManager::new(&servo)));
|
|
self.servo = Some(servo);
|
|
self.refresh_hub_config();
|
|
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.user_agent.borrow(), self.shared.http_allowed.borrow().clone());
|
|
}
|
|
|
|
/// (Re)build the scripts every page gets. Applies on each page's next load.
|
|
pub fn install_page_scripts(&mut self) {
|
|
let Some(ucm) = self.ucm.clone() else { return };
|
|
for script in self.user_scripts.drain(..) {
|
|
ucm.remove_script(script);
|
|
}
|
|
let s = self.shared.settings.borrow().clone();
|
|
let privacy = s.privacy.mode || (self.shared.incognito && s.privacy.mode_incognito);
|
|
let options = inject::Options {
|
|
token: &self.hub.token,
|
|
privacy_mode: privacy,
|
|
seed: &self.shared.seed,
|
|
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,
|
|
animate_removal: s.adblock.animate && !crate::perf::still(&s),
|
|
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);
|
|
sources.extend(self.shared.scripts.borrow().page_scripts());
|
|
for source in sources {
|
|
let script = Rc::new(UserScript::new(source, None));
|
|
ucm.add_script(script.clone());
|
|
self.user_scripts.push(script);
|
|
}
|
|
}
|
|
|
|
pub fn build_webview(&self, win: &BrowserWindow, url: Url) -> Web {
|
|
let context = win.new_context();
|
|
let servo = self.servo.as_ref().expect("Servo is running");
|
|
let mut builder = servo::WebViewBuilder::new(servo, context.clone() as Rc<dyn servo::RenderingContext>).url(url.clone()).hidpi_scale_factor(win.hidpi()).delegate(self.hub.clone()).gamepad_delegate(Rc::new(crate::hub::Gamepads));
|
|
if let Some(ucm) = &self.ucm {
|
|
builder = builder.user_content_manager(ucm.clone());
|
|
}
|
|
let webview = builder.build();
|
|
let zoom = self.shared.settings.borrow().zoom_for(&util::host_of(&url));
|
|
if (zoom - 1.0).abs() > 0.001 {
|
|
webview.set_page_zoom(zoom);
|
|
}
|
|
let dark = self.web_dark();
|
|
webview.notify_theme_change(if dark { servo::Theme::Dark } else { servo::Theme::Light });
|
|
Web { webview, context, dirty: true }
|
|
}
|
|
|
|
/// 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()),
|
|
}
|
|
}
|
|
|
|
pub fn spin(&mut self) {
|
|
if let Some(servo) = &self.servo {
|
|
servo.spin_event_loop();
|
|
}
|
|
// Handling events can make Servo do more work; loop until quiet (bounded).
|
|
for _ in 0..8 {
|
|
let events = self.hub.take_events();
|
|
if events.is_empty() {
|
|
break;
|
|
}
|
|
for event in events {
|
|
self.handle_event(event);
|
|
}
|
|
if let Some(servo) = &self.servo {
|
|
servo.spin_event_loop();
|
|
}
|
|
}
|
|
}
|
|
|
|
// ── finding things ────────────────────────────────────────────────
|
|
|
|
pub fn find_webview(&self, id: WebViewId) -> Option<(WindowId, usize)> {
|
|
self.windows.iter().find_map(|(wid, w)| w.tab_by_webview(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: WebViewId) -> 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_mut(&window) {
|
|
w.needs_redraw = true;
|
|
w.window.request_redraw();
|
|
}
|
|
}
|
|
|
|
pub fn redraw_all(&mut self) {
|
|
for w in self.windows.values_mut() {
|
|
w.needs_redraw = true;
|
|
w.window.request_redraw();
|
|
}
|
|
}
|
|
|
|
/// The normal window commands should go to: the focused one, else the last used, else any.
|
|
pub fn current_window(&self) -> Option<WindowId> {
|
|
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))
|
|
}
|
|
|
|
// ── Servo 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.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);
|
|
if host_changed {
|
|
let zoom = self.shared.settings.borrow().zoom_for(&util::host_of(&url));
|
|
if let Some(tab) = self.tab_mut(id) {
|
|
tab.zoom = zoom;
|
|
if 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, upgraded) = {
|
|
let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i];
|
|
tab.title = title.clone();
|
|
(tab.url.clone(), tab.upgraded_from.clone())
|
|
};
|
|
if title == crate::resources::ERROR_TITLE {
|
|
if let Some(from) = upgraded {
|
|
let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i];
|
|
tab.prompts.push_back(crate::tabs::Prompt::HttpFallback { url: from });
|
|
tab.upgraded_from = None;
|
|
}
|
|
} else if title != crate::resources::BAD_CERT_TITLE && title != crate::resources::CRASH_TITLE {
|
|
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.window.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::LoadStatus(id, status) => self.on_load_status(id, status),
|
|
Event::Cursor(id, cursor) => {
|
|
if let Some(tab) = self.tab_mut(id) {
|
|
tab.cursor = cursor;
|
|
}
|
|
if let Some((w, i)) = self.find_webview(id)
|
|
&& let Some(win) = self.windows.get(&w)
|
|
&& win.active == i
|
|
{
|
|
let over = win.pointer.and_then(|p| win.page_point(p)).is_some();
|
|
win.update_cursor(over);
|
|
}
|
|
},
|
|
Event::Favicon(id) => self.on_favicon(id),
|
|
Event::FrameReady(id) => self.on_frame(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_id = self.windows[&w].tabs[i].id;
|
|
self.close_tab(w, tab_id, false);
|
|
}
|
|
},
|
|
Event::Crashed(id, reason, backtrace) => {
|
|
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{}\n", util::format_stamp(util::now()), backtrace.unwrap_or_default());
|
|
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);
|
|
}
|
|
if let Some((w, _)) = self.find_webview(id) {
|
|
self.redraw(w);
|
|
}
|
|
},
|
|
Event::MediaSession(id, event) => {
|
|
if let Some(tab) = self.tab_mut(id) {
|
|
let (state, _) = tab.media.get_or_insert_with(|| (Default::default(), util::now_ms()));
|
|
match event {
|
|
servo::MediaSessionEvent::SetMetadata(meta) => {
|
|
state.title = meta.title;
|
|
state.artist = meta.artist;
|
|
state.album = meta.album;
|
|
},
|
|
servo::MediaSessionEvent::PlaybackStateChange(playback) => state.paused = !matches!(playback, servo::MediaSessionPlaybackState::Playing),
|
|
servo::MediaSessionEvent::SetPositionState(pos) => {
|
|
state.duration = pos.duration;
|
|
state.position = pos.position;
|
|
},
|
|
}
|
|
if let Some(m) = tab.media.as_mut() {
|
|
m.1 = util::now_ms();
|
|
}
|
|
}
|
|
self.redraw_all();
|
|
},
|
|
Event::Fullscreen(id, on) => {
|
|
if let Some((w, i)) = self.find_webview(id)
|
|
&& let Some(win) = self.windows.get_mut(&w)
|
|
{
|
|
win.tabs[i].fullscreen = on;
|
|
win.fullscreen = on;
|
|
win.window.set_fullscreen(on.then_some(winit::window::Fullscreen::Borderless(None)));
|
|
win.needs_redraw = true;
|
|
}
|
|
},
|
|
Event::Animating(id, animating) => {
|
|
if let Some(tab) = self.tab_mut(id) {
|
|
tab.animating = animating;
|
|
}
|
|
},
|
|
Event::Navigation(id, request) => self.on_navigation(id, request),
|
|
Event::Unload(id, request) => {
|
|
match self.tab_mut(id) {
|
|
Some(tab) => tab.dialog = Some(crate::tabs::Dialog::LeavePage(request)),
|
|
None => request.allow(),
|
|
}
|
|
if let Some((w, _)) = self.find_webview(id) {
|
|
self.redraw(w);
|
|
}
|
|
},
|
|
Event::CreateNew(parent, request) => self.on_create_new(parent, request),
|
|
Event::Permission(id, request) => self.on_permission(id, request),
|
|
Event::Auth(id, request) => {
|
|
let origin = request.url().origin().ascii_serialization();
|
|
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()
|
|
};
|
|
if let Some(tab) = self.tab_mut(id) {
|
|
tab.dialog = Some(crate::tabs::Dialog::Auth { request, username, password });
|
|
}
|
|
if let Some((w, _)) = self.find_webview(id) {
|
|
self.redraw(w);
|
|
}
|
|
},
|
|
Event::Bluetooth(id, request) => {
|
|
if let Some(tab) = self.tab_mut(id) {
|
|
tab.dialog = Some(crate::tabs::Dialog::Bluetooth(request));
|
|
}
|
|
if let Some((w, _)) = self.find_webview(id) {
|
|
self.redraw(w);
|
|
}
|
|
},
|
|
Event::ProtocolHandler(id, registration, request) => {
|
|
let host = self.tab_mut(id).map(|t| t.host()).unwrap_or_default();
|
|
match self.tab_mut(id) {
|
|
Some(tab) => tab.prompts.push_back(crate::tabs::Prompt::ProtocolHandler { host, scheme: registration.scheme, request }),
|
|
None => request.deny(),
|
|
}
|
|
},
|
|
Event::Control(id, control) => self.on_control(id, control),
|
|
Event::HideControl(id, control) => {
|
|
let _ = control;
|
|
if let Some((w, i)) = self.find_webview(id)
|
|
&& let Some(win) = self.windows.get_mut(&w)
|
|
{
|
|
let tab = &mut win.tabs[i];
|
|
let matches = match &tab.dialog {
|
|
Some(crate::tabs::Dialog::Select(s)) => s.id() == control,
|
|
Some(crate::tabs::Dialog::Color(c, _)) => c.id() == control,
|
|
Some(crate::tabs::Dialog::ContextMenu(m)) => m.control_id() == Some(control),
|
|
_ => false,
|
|
};
|
|
if matches {
|
|
tab.dialog = None;
|
|
}
|
|
if win.ui.ime_control == Some(control) {
|
|
win.ui.ime_control = None;
|
|
win.set_ime(false, None);
|
|
}
|
|
win.needs_redraw = true;
|
|
}
|
|
},
|
|
Event::Notification(id, notification) => self.on_notification(id, notification),
|
|
Event::Page(id, message) => self.on_page_message(id, message),
|
|
Event::Console(id, level, text) => {
|
|
if let Some(tab) = self.tab_mut(id) {
|
|
tab.push_console(level, text);
|
|
}
|
|
},
|
|
Event::ResizeTo(id, size) => {
|
|
if let Some((w, _)) = self.find_webview(id)
|
|
&& let Some(win) = self.windows.get(&w)
|
|
&& matches!(win.kind, Kind::App(_))
|
|
{
|
|
let _ = win.window.request_inner_size(winit::dpi::PhysicalSize::new(size.width.clamp(320, 4000) as u32, size.height.clamp(240, 3000) as u32));
|
|
}
|
|
},
|
|
Event::UpgradedToHttps(id, from) => {
|
|
if let Some(tab) = self.tab_mut(id) {
|
|
tab.upgraded_from = Some(from);
|
|
}
|
|
},
|
|
Event::DevtoolsStarted(port, token) => {
|
|
*self.shared.devtools.borrow_mut() = Some((port, token));
|
|
self.shared.toast(format!("Remote debugging is on: in Firefox open about:debugging and connect to localhost:{port}"));
|
|
},
|
|
Event::DevtoolsConnection(request) => {
|
|
// The user switched remote debugging on in settings; that is the consent.
|
|
if self.shared.settings.borrow().web.remote_debugging { request.allow() } else { request.deny() }
|
|
},
|
|
Event::ServoError(error) => {
|
|
log::error!("engine error: {error}");
|
|
self.shared.toast(format!("The engine reported a problem: {error}"));
|
|
},
|
|
}
|
|
}
|
|
|
|
fn on_load_status(&mut self, id: WebViewId, status: LoadStatus) {
|
|
let Some((w, i)) = self.find_webview(id) else { return };
|
|
match status {
|
|
LoadStatus::Started => {
|
|
self.hub.blocked.borrow_mut().insert(id, 0);
|
|
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.blocked = 0;
|
|
tab.hidden_elements = 0;
|
|
tab.crashed = None;
|
|
tab.find = Default::default();
|
|
tab.media = None;
|
|
tab.dialog = None;
|
|
tab.prompts.retain(|p| matches!(p, crate::tabs::Prompt::SaveLogin { .. }));
|
|
},
|
|
LoadStatus::HeadParsed => {
|
|
self.windows.get_mut(&w).expect("found").tabs[i].load_status = Some(status);
|
|
self.apply_cosmetic(id);
|
|
},
|
|
LoadStatus::Complete => {
|
|
let (url, title) = {
|
|
let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i];
|
|
tab.load_status = Some(status);
|
|
tab.load_started = None;
|
|
(tab.url.clone(), tab.title.clone())
|
|
};
|
|
if title != crate::resources::ERROR_TITLE {
|
|
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))).unwrap_or(false);
|
|
if muted && let Some(tab) = self.tab_mut(id) {
|
|
tab.muted = true;
|
|
if let Some(web) = &tab.web {
|
|
web.webview.evaluate_javascript(inject::call("media.act", &["mute".into(), true.into()]), |_| {});
|
|
}
|
|
}
|
|
},
|
|
}
|
|
self.redraw(w);
|
|
}
|
|
|
|
/// Hide the elements the lists name for this page.
|
|
fn apply_cosmetic(&mut self, id: WebViewId) {
|
|
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;
|
|
}
|
|
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)]), |_| {});
|
|
}
|
|
}
|
|
|
|
fn on_favicon(&mut self, id: WebViewId) {
|
|
let Some((w, i)) = self.find_webview(id) else { return };
|
|
let win = self.windows.get_mut(&w).expect("found");
|
|
let ctx = win.egui.egui_ctx.clone();
|
|
let tab = &mut win.tabs[i];
|
|
let Some(web) = &tab.web else { return };
|
|
let Some(image) = web.webview.favicon() else { return };
|
|
let (width, height) = (image.width, image.height);
|
|
let data = image.data();
|
|
let rgba: Vec<u8> = match image.format {
|
|
servo::PixelFormat::RGBA8 => data.to_vec(),
|
|
servo::PixelFormat::BGRA8 => data.chunks_exact(4).flat_map(|p| [p[2], p[1], p[0], p[3]]).collect(),
|
|
servo::PixelFormat::RGB8 => data.chunks_exact(3).flat_map(|p| [p[0], p[1], p[2], 255]).collect(),
|
|
servo::PixelFormat::K8 => data.iter().flat_map(|v| [*v, *v, *v, 255]).collect(),
|
|
servo::PixelFormat::KA8 => data.chunks_exact(2).flat_map(|p| [p[0], p[0], p[0], p[1]]).collect(),
|
|
};
|
|
drop(image);
|
|
if rgba.len() != (width * height * 4) as usize || width == 0 {
|
|
return;
|
|
}
|
|
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.needs_redraw = true;
|
|
win.window.request_redraw();
|
|
}
|
|
|
|
fn on_frame(&mut self, id: WebViewId) {
|
|
let Some((w, i)) = self.find_webview(id) else { return };
|
|
let pip_target = {
|
|
let win = self.windows.get_mut(&w).expect("found");
|
|
let tab = &mut win.tabs[i];
|
|
if let Some(web) = tab.web.as_mut() {
|
|
web.dirty = true;
|
|
}
|
|
if i == win.active {
|
|
win.needs_redraw = true;
|
|
win.window.request_redraw();
|
|
}
|
|
tab.pip_size.map(|_| tab.id)
|
|
};
|
|
// A tab shown in picture-in-picture: paint it now and hand the frame to the PiP window.
|
|
if let Some(tab_id) = pip_target {
|
|
let source = {
|
|
let win = self.windows.get_mut(&w).expect("found");
|
|
win.paint_tab(i);
|
|
let tab = &win.tabs[i];
|
|
tab.web.as_ref().map(|web| (web.context.clone(), win.rendering.clone()))
|
|
};
|
|
let pip = self.windows.iter().find(|(_, x)| x.kind == (Kind::Pip { window: w, tab: tab_id })).map(|(id, _)| *id);
|
|
if let (Some((context, rendering)), Some(pip)) = (source, pip)
|
|
&& let Some(pip_win) = self.windows.get_mut(&pip)
|
|
{
|
|
pip_win.take_pip_frame(&context, &rendering);
|
|
pip_win.window.request_redraw();
|
|
}
|
|
}
|
|
}
|
|
|
|
fn on_create_new(&mut self, parent: WebViewId, request: servo::CreateNewWebViewRequest) {
|
|
let Some((w, i)) = self.find_webview(parent) else { return };
|
|
let host = self.windows[&w].tabs[i].host();
|
|
let answer = self.shared.permissions.borrow().answer(&self.shared.settings.borrow(), &host, crate::store::permissions::Kind::Popups);
|
|
if answer == crate::store::permissions::Answer::Block {
|
|
self.windows.get_mut(&w).expect("found").tabs[i].prompts.push_back(crate::tabs::Prompt::PopupBlocked { url: String::new() });
|
|
self.redraw(w);
|
|
return;
|
|
}
|
|
let opener = self.windows[&w].tabs[i].id;
|
|
let tab_id = self.new_tab_id();
|
|
let (webview, context) = {
|
|
let win = &self.windows[&w];
|
|
let context = win.new_context();
|
|
let mut builder = request.builder(context.clone() as Rc<dyn servo::RenderingContext>).hidpi_scale_factor(win.hidpi()).delegate(self.hub.clone()).gamepad_delegate(Rc::new(crate::hub::Gamepads));
|
|
if let Some(ucm) = &self.ucm {
|
|
builder = builder.user_content_manager(ucm.clone());
|
|
}
|
|
(builder.build(), context)
|
|
};
|
|
let mut tab = Tab::new(tab_id);
|
|
tab.page = None;
|
|
tab.url = String::new();
|
|
tab.title = String::new();
|
|
tab.opener = Some(opener);
|
|
tab.web = Some(Web { webview, context, dirty: true });
|
|
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.needs_redraw = true;
|
|
win.window.request_redraw();
|
|
}
|
|
|
|
fn on_permission(&mut self, id: WebViewId, request: servo::PermissionRequest) {
|
|
use crate::store::permissions::{Answer, Kind as P};
|
|
let Some((w, i)) = self.find_webview(id) else { return };
|
|
let kind = match request.feature() {
|
|
servo::PermissionFeature::Geolocation => P::Location,
|
|
servo::PermissionFeature::Notifications | servo::PermissionFeature::Push => P::Notifications,
|
|
servo::PermissionFeature::Midi => P::Midi,
|
|
servo::PermissionFeature::Camera => P::Camera,
|
|
servo::PermissionFeature::Microphone => P::Microphone,
|
|
servo::PermissionFeature::Speaker => P::Sound,
|
|
servo::PermissionFeature::DeviceInfo => P::DeviceInfo,
|
|
servo::PermissionFeature::BackgroundSync => P::BackgroundSync,
|
|
servo::PermissionFeature::Bluetooth => P::Bluetooth,
|
|
servo::PermissionFeature::PersistentStorage => P::Storage,
|
|
servo::PermissionFeature::ScreenWakeLock(_) => P::WakeLock,
|
|
servo::PermissionFeature::Gamepad => P::Gamepad,
|
|
};
|
|
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.needs_redraw = true;
|
|
win.window.request_redraw();
|
|
},
|
|
}
|
|
}
|
|
|
|
fn on_control(&mut self, id: WebViewId, control: servo::EmbedderControl) {
|
|
use servo::EmbedderControl as C;
|
|
let Some((w, i)) = self.find_webview(id) else { return };
|
|
match control {
|
|
C::SelectElement(select) => self.windows.get_mut(&w).expect("found").tabs[i].dialog = Some(crate::tabs::Dialog::Select(select)),
|
|
C::ColorPicker(picker) => {
|
|
let c = picker.current_color().map(|c| [c.red, c.green, c.blue]).unwrap_or([0, 0, 0]);
|
|
self.windows.get_mut(&w).expect("found").tabs[i].dialog = Some(crate::tabs::Dialog::Color(picker, c));
|
|
},
|
|
C::FilePicker(picker) => {
|
|
let key = self.next_pending;
|
|
self.next_pending += 1;
|
|
let filters: Vec<String> = picker.filter_patterns().iter().map(|f| f.0.trim_start_matches('.').to_owned()).filter(|f| !f.is_empty() && !f.contains('/')).collect();
|
|
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<Vec<PathBuf>>| {
|
|
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(),
|
|
}
|
|
}
|
|
},
|
|
);
|
|
},
|
|
C::InputMethod(ime) => {
|
|
let win = self.windows.get_mut(&w).expect("found");
|
|
if i == win.active {
|
|
let rect = win.device_rect_to_ui(ime.position());
|
|
let scale = win.egui.egui_ctx.pixels_per_point() as f64;
|
|
let pos = winit::dpi::PhysicalPosition::new(rect.min.x as f64 * scale, rect.max.y as f64 * scale);
|
|
let size = winit::dpi::PhysicalSize::new((rect.width() as f64 * scale) as u32, (rect.height() as f64 * scale) as u32);
|
|
win.ui.ime_control = Some(ime.id());
|
|
win.set_ime(true, Some((pos, size)));
|
|
}
|
|
},
|
|
C::SimpleDialog(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));
|
|
},
|
|
C::ContextMenu(menu) => {
|
|
let win = self.windows.get_mut(&w).expect("found");
|
|
let tab = &mut win.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<WebViewId>, notification: servo::Notification) {
|
|
let host = id.and_then(|id| self.tab_mut(id).map(|t| t.host())).unwrap_or_default();
|
|
let allowed = self.shared.permissions.borrow().answer(&self.shared.settings.borrow(), &host, crate::store::permissions::Kind::Notifications) == crate::store::permissions::Answer::Allow;
|
|
if !allowed {
|
|
return;
|
|
}
|
|
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: WebViewId, 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(1);
|
|
}
|
|
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);
|
|
}
|
|
// Blocked counts for the toolbar.
|
|
let counts: Vec<(WebViewId, 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.poll_gamepads();
|
|
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<WindowId> = 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(30) {
|
|
self.last_slow = now;
|
|
self.slow_tick();
|
|
}
|
|
}
|
|
|
|
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 wanted = self.windows.values().any(|w| w.ui.flyout == Some(crate::ui::Flyout::Media)) && 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 stop drawing after `freeze_min` and are 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;
|
|
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() / 60;
|
|
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());
|
|
if let Some(web) = tab.web.take() {
|
|
self.hub.forget(web.webview.id());
|
|
}
|
|
tab.load_status = None;
|
|
} else if freeze > 0 && idle >= freeze as u64 && !tab.frozen {
|
|
tab.frozen = true;
|
|
if let Some(web) = &tab.web {
|
|
web.webview.hide();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn save_session(&mut self) {
|
|
if self.shared.incognito {
|
|
return;
|
|
}
|
|
let windows: Vec<crate::store::session::SavedWindow> = self
|
|
.windows
|
|
.values()
|
|
.filter(|w| w.kind == Kind::Normal)
|
|
.map(|w| {
|
|
let size = w.window.inner_size();
|
|
let scale = w.window.scale_factor();
|
|
crate::store::session::SavedWindow {
|
|
tabs: w.tabs.iter().map(Tab::saved).collect(),
|
|
active: w.active,
|
|
width: (size.width as f64 / scale) as u32,
|
|
height: (size.height as f64 / scale) as u32,
|
|
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();
|
|
}
|
|
}
|
|
|
|
fn poll_gamepads(&mut self) {
|
|
use servo::{GamepadEvent, GamepadIndex, GamepadInputBounds, GamepadSupportedHapticEffects, GamepadUpdateType, InputEvent};
|
|
let Some(gilrs) = self.gilrs.as_mut() else { return };
|
|
let mut events = Vec::new();
|
|
while let Some(gilrs::Event { id, event, .. }) = gilrs.next_event() {
|
|
events.push((id, event));
|
|
}
|
|
if events.is_empty() {
|
|
return;
|
|
}
|
|
let Some(target) = self.current_window().and_then(|w| self.windows.get(&w)).and_then(|w| w.active_webview().cloned()) else { return };
|
|
for (id, event) in events {
|
|
let next_index = self.gamepads.len();
|
|
let index = *self.gamepads.entry(id).or_insert(next_index);
|
|
let index = GamepadIndex(index);
|
|
let servo_event = match event {
|
|
gilrs::EventType::Connected => {
|
|
let name = self.gilrs.as_ref().map(|g| g.gamepad(id).name().to_owned()).unwrap_or_default();
|
|
Some(GamepadEvent::Connected(index, name, GamepadInputBounds { axis_bounds: (-1.0, 1.0), button_bounds: (0.0, 1.0) }, GamepadSupportedHapticEffects { supports_dual_rumble: false, supports_trigger_rumble: false }))
|
|
},
|
|
gilrs::EventType::Disconnected => {
|
|
self.gamepads.remove(&id);
|
|
Some(GamepadEvent::Disconnected(index))
|
|
},
|
|
gilrs::EventType::ButtonChanged(button, value, _) => standard_button(button).map(|b| GamepadEvent::Updated(index, GamepadUpdateType::Button(b, value as f64))),
|
|
gilrs::EventType::AxisChanged(axis, value, _) => standard_axis(axis).map(|a| GamepadEvent::Updated(index, GamepadUpdateType::Axis(a, value as f64))),
|
|
_ => None,
|
|
};
|
|
if let Some(e) = servo_event {
|
|
target.notify_input_event(InputEvent::Gamepad(e));
|
|
}
|
|
}
|
|
}
|
|
|
|
// ── windows ───────────────────────────────────────────────────────
|
|
|
|
pub fn open_window(&mut self, event_loop: &ActiveEventLoop, kind: Kind, tabs: Vec<Tab>, active: usize, size: Option<(u32, u32)>) -> Option<WindowId> {
|
|
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, class) = match &kind {
|
|
Kind::App(id) => {
|
|
let apps = self.shared.apps.borrow();
|
|
let app = apps.get(id);
|
|
(app.map(|a| a.name.clone()).unwrap_or_else(|| "Nacre".into()), app.map(crate::store::apps::window_class))
|
|
},
|
|
Kind::Pip { .. } => ("Picture in picture — Nacre".to_owned(), None),
|
|
Kind::Normal => (if self.shared.incognito { "Nacre (incognito)".to_owned() } else { "Nacre".to_owned() }, None),
|
|
};
|
|
let attrs = window::attributes(&kind, &title, size, decorated, class.as_deref());
|
|
let mut win = match BrowserWindow::create(event_loop, kind.clone(), attrs) {
|
|
Ok(win) => win,
|
|
Err(error) => {
|
|
log::error!("{error}");
|
|
return None;
|
|
},
|
|
};
|
|
if settings.window.maximized && kind == Kind::Normal && self.windows.is_empty() {
|
|
win.window.set_maximized(true);
|
|
}
|
|
self.style_window(&mut win);
|
|
let id = win.id;
|
|
win.tabs = tabs;
|
|
win.active = active.min(win.tabs.len().saturating_sub(1));
|
|
if self.servo.is_none() {
|
|
self.start_servo();
|
|
}
|
|
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);
|
|
Some(id)
|
|
}
|
|
|
|
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(|t| t.theme_color);
|
|
let palette = theme::Palette::new(theme::seed(&settings, site, self.shared.system_accent), dark, &settings.theme.variant, settings.theme.contrast);
|
|
let ctx = &win.egui.egui_ctx;
|
|
// Pin egui's theme to ours so a system theme change can't swap in egui's default style.
|
|
ctx.set_theme(if dark { egui::Theme::Dark } else { egui::Theme::Light });
|
|
ctx.set_visuals(theme::visuals(&palette, theme::corner(&settings)));
|
|
ctx.all_styles_mut(|style| style.animation_time = theme::animation_time(&settings));
|
|
if (settings.ui.scale - 1.0).abs() > 0.01 {
|
|
ctx.set_zoom_factor(settings.ui.scale.clamp(0.5, 3.0));
|
|
}
|
|
win.ui.palette = Some(palette);
|
|
}
|
|
|
|
/// 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 = win.active;
|
|
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 web = self.build_webview(&self.windows[&window], parsed);
|
|
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(LoadStatus::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, String)> = win.tabs.iter().enumerate().filter_map(|(i, t)| t.pending_url.clone().map(|u| (i, u))).collect();
|
|
for (i, url) in pending {
|
|
let Ok(parsed) = Url::parse(&url) else { continue };
|
|
if Page::from_url(&url).is_some() {
|
|
continue;
|
|
}
|
|
let web = self.build_webview(&self.windows[&window], parsed);
|
|
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(LoadStatus::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 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.drain(..) {
|
|
if let Some(web) = &tab.web {
|
|
self.hub.forget(web.webview.id());
|
|
}
|
|
}
|
|
win.egui.destroy();
|
|
if self.last_window == Some(window) {
|
|
self.last_window = None;
|
|
}
|
|
}
|
|
|
|
pub fn quit(&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 size = w.window.inner_size();
|
|
let scale = w.window.scale_factor();
|
|
let mut s = self.shared.settings.borrow_mut();
|
|
s.window.maximized = w.window.is_maximized();
|
|
if !s.window.maximized {
|
|
s.window.width = (size.width as f64 / scale) as u32;
|
|
s.window.height = (size.height as f64 / scale) as u32;
|
|
}
|
|
}
|
|
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();
|
|
self.flush_stores();
|
|
for control in self.download_controls.values() {
|
|
control.store(download::PAUSE, std::sync::atomic::Ordering::Relaxed);
|
|
}
|
|
self.shared.tor.stop();
|
|
self.shared.cava.borrow_mut().stop();
|
|
if let Some(mut presence) = self.presence.take() {
|
|
presence.stop();
|
|
}
|
|
for (_, mut win) in self.windows.drain() {
|
|
win.tabs.clear();
|
|
win.egui.destroy();
|
|
}
|
|
let _ = std::fs::remove_file(self.shared.paths.running_marker());
|
|
if let Some(server) = self.instance.take() {
|
|
server.stop();
|
|
}
|
|
self.shared.paths.remove_incognito();
|
|
}
|
|
|
|
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(servo) = &self.servo {
|
|
if what.iter().any(|w| w == "cookies") {
|
|
servo.site_data_manager().clear_cookies(None);
|
|
let sites: Vec<String> = servo.site_data_manager().site_data(servo::StorageType::all()).iter().map(|s| s.name()).collect();
|
|
let refs: Vec<&str> = sites.iter().map(String::as_str).collect();
|
|
servo.site_data_manager().clear_site_data(&refs, servo::StorageType::all());
|
|
}
|
|
if what.iter().any(|w| w == "cache") {
|
|
servo.network_manager().clear_cache();
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The first windows: restored session, an app window, or a new tab.
|
|
fn open_initial(&mut self, event_loop: &ActiveEventLoop) {
|
|
let launch = self.launch.clone();
|
|
self.servo_first_setup();
|
|
if let Some(app_id) = &launch.app {
|
|
self.open_app_window(event_loop, 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<Tab> = 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(event_loop, 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(event_loop, 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 });
|
|
}
|
|
}
|
|
|
|
fn servo_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.gilrs = gilrs::Gilrs::new().ok();
|
|
self.ping_download_managers();
|
|
if !self.shared.incognito {
|
|
let paths = self.shared.paths.clone();
|
|
self.spawn("import-scan", crate::importer::find_sources, move |app, sources| {
|
|
let _ = &paths;
|
|
*app.shared.import_sources.borrow_mut() = sources;
|
|
});
|
|
}
|
|
}
|
|
|
|
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();
|
|
match Page::from_url(&saved.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 ───────────────────────────────────────────────────────
|
|
|
|
fn draw(&mut self, window: WindowId) {
|
|
let Some(win) = self.windows.get_mut(&window) else { return };
|
|
win.needs_redraw = false;
|
|
win.sync_webviews();
|
|
win.paint_page();
|
|
let page_rect_before = win.page_rect;
|
|
let mut commands = Vec::new();
|
|
let shared = self.shared.clone();
|
|
let hub = self.hub.clone();
|
|
{
|
|
let BrowserWindow { egui, window: w, tabs, active, ui, page_rect, kind, fullscreen, pip_frame, pip_size, .. } = win;
|
|
let mut frame = crate::ui::Frame { shared: &shared, hub: &hub, tabs, active, ui, page_rect, kind, fullscreen: *fullscreen, pip_frame: pip_frame.as_ref(), pip_size: *pip_size, commands: &mut commands, window_id: window };
|
|
egui.run(w, |ui| crate::ui::draw(ui, &mut frame));
|
|
}
|
|
let clear = win.ui.palette.map(|p| p.surface).unwrap_or(egui::Color32::from_gray(24));
|
|
win.present(clear);
|
|
// The page area moved or changed size: resize the web view and draw again.
|
|
if win.page_rect != page_rect_before {
|
|
win.needs_redraw = true;
|
|
win.window.request_redraw();
|
|
}
|
|
// egui asks for another frame while it animates.
|
|
let repaint = win.egui.egui_ctx.has_requested_repaint();
|
|
if repaint {
|
|
win.window.request_redraw();
|
|
}
|
|
for command in commands {
|
|
self.run_in(window, command);
|
|
}
|
|
self.apply_settings_if_changed();
|
|
}
|
|
}
|
|
|
|
fn standard_button(button: gilrs::Button) -> Option<usize> {
|
|
use gilrs::Button as B;
|
|
// The W3C "standard gamepad" layout.
|
|
Some(match button {
|
|
B::South => 0,
|
|
B::East => 1,
|
|
B::West => 2,
|
|
B::North => 3,
|
|
B::LeftTrigger => 4,
|
|
B::RightTrigger => 5,
|
|
B::LeftTrigger2 => 6,
|
|
B::RightTrigger2 => 7,
|
|
B::Select => 8,
|
|
B::Start => 9,
|
|
B::LeftThumb => 10,
|
|
B::RightThumb => 11,
|
|
B::DPadUp => 12,
|
|
B::DPadDown => 13,
|
|
B::DPadLeft => 14,
|
|
B::DPadRight => 15,
|
|
B::Mode => 16,
|
|
_ => return None,
|
|
})
|
|
}
|
|
|
|
fn standard_axis(axis: gilrs::Axis) -> Option<usize> {
|
|
use gilrs::Axis as A;
|
|
Some(match axis {
|
|
A::LeftStickX => 0,
|
|
A::LeftStickY => 1,
|
|
A::RightStickX => 2,
|
|
A::RightStickY => 3,
|
|
_ => return None,
|
|
})
|
|
}
|
|
|
|
impl ApplicationHandler<AppEvent> for App {
|
|
fn new_events(&mut self, _event_loop: &ActiveEventLoop, cause: StartCause) {
|
|
if let StartCause::ResumeTimeReached { .. } = cause {
|
|
self.tick();
|
|
}
|
|
}
|
|
|
|
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
|
if !self.windows.is_empty() || self.exiting {
|
|
return;
|
|
}
|
|
*self.shared.system_dark.borrow_mut() = theme::system_dark(event_loop.system_theme());
|
|
rustls_provider();
|
|
match crate::instance::Server::start(&self.shared.paths, self.jobs_tx.clone(), self.proxy.clone()) {
|
|
Ok(server) => self.instance = Some(server),
|
|
Err(error) => log::warn!("single instance: {error}"),
|
|
}
|
|
self.open_initial(event_loop);
|
|
if self.windows.is_empty() {
|
|
log::error!("no window could be opened");
|
|
event_loop.exit();
|
|
}
|
|
}
|
|
|
|
fn user_event(&mut self, event_loop: &ActiveEventLoop, _event: AppEvent) {
|
|
self.spin();
|
|
self.tick();
|
|
for launch in std::mem::take(&mut self.pending_launches) {
|
|
self.handle_launch(event_loop, launch);
|
|
}
|
|
self.open_pending_windows(event_loop);
|
|
if self.exiting {
|
|
event_loop.exit();
|
|
}
|
|
}
|
|
|
|
fn window_event(&mut self, event_loop: &ActiveEventLoop, window_id: WindowId, event: WindowEvent) {
|
|
self.spin();
|
|
if !self.windows.contains_key(&window_id) {
|
|
return;
|
|
}
|
|
match &event {
|
|
WindowEvent::RedrawRequested => {
|
|
self.draw(window_id);
|
|
},
|
|
WindowEvent::CloseRequested => {
|
|
self.close_window(window_id);
|
|
},
|
|
WindowEvent::Resized(size) => {
|
|
let pip = self.windows.get(&window_id).and_then(|w| if let Kind::Pip { window, tab } = w.kind { Some((window, tab)) } else { None });
|
|
if let Some(win) = self.windows.get_mut(&window_id) {
|
|
win.resized(*size);
|
|
let _ = win.egui.on_window_event(&win.window, &event);
|
|
}
|
|
if let Some((source, tab)) = pip
|
|
&& let Some(src) = self.windows.get_mut(&source)
|
|
&& let Some(i) = src.tab_index(tab)
|
|
{
|
|
src.tabs[i].pip_size = Some(dpi::PhysicalSize::new(size.width.max(1), size.height.max(1)));
|
|
src.sync_webviews();
|
|
}
|
|
self.redraw(window_id);
|
|
},
|
|
WindowEvent::ScaleFactorChanged { .. } => {
|
|
if let Some(win) = self.windows.get_mut(&window_id) {
|
|
let _ = win.egui.on_window_event(&win.window, &event);
|
|
}
|
|
self.redraw(window_id);
|
|
},
|
|
WindowEvent::Focused(focused) => {
|
|
if let Some(win) = self.windows.get_mut(&window_id) {
|
|
win.focused = *focused;
|
|
let _ = win.egui.on_window_event(&win.window, &event);
|
|
if let Some(webview) = win.active_webview() {
|
|
webview.set_focused(*focused && win.page_focused);
|
|
}
|
|
if *focused && win.kind == Kind::Normal {
|
|
self.last_window = Some(window_id);
|
|
}
|
|
}
|
|
},
|
|
WindowEvent::ThemeChanged(t) => {
|
|
*self.shared.system_dark.borrow_mut() = *t == winit::window::Theme::Dark;
|
|
self.restyle_all();
|
|
},
|
|
_ => self.window_input(window_id, &event),
|
|
}
|
|
self.tick();
|
|
self.open_pending_windows(event_loop);
|
|
if self.exiting {
|
|
event_loop.exit();
|
|
}
|
|
}
|
|
|
|
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
|
self.spin();
|
|
// Wake regularly for timers (session save, toasts, media position, gamepads).
|
|
let animating = self.windows.values().any(|w| w.tabs.iter().any(|t| t.animating));
|
|
let interval = if self.gilrs.is_some() && !self.gamepads.is_empty() || animating { 16 } else { 250 };
|
|
event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + Duration::from_millis(interval)));
|
|
if animating {
|
|
for (id, w) in &self.windows {
|
|
if w.tabs.get(w.active).is_some_and(|t| t.animating) {
|
|
let _ = id;
|
|
w.window.request_redraw();
|
|
}
|
|
}
|
|
}
|
|
if self.exiting {
|
|
event_loop.exit();
|
|
}
|
|
}
|
|
|
|
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
|
|
self.quit();
|
|
}
|
|
}
|
|
|
|
impl App {
|
|
/// Keyboard and pointer input that isn't a redraw, resize or focus change.
|
|
fn window_input(&mut self, window_id: WindowId, event: &WindowEvent) {
|
|
let keymap_action = if let WindowEvent::KeyboardInput { event: key, .. } = event {
|
|
let mods = self.windows.get(&window_id).map(|w| w.modifiers).unwrap_or_default();
|
|
Shortcut::from_event(key, mods).and_then(|s| self.shared.keymap.borrow().action_for(&s))
|
|
} else {
|
|
None
|
|
};
|
|
let Some(win) = self.windows.get_mut(&window_id) else { return };
|
|
win.last_input = Instant::now();
|
|
let egui_wants_keys = win.egui.egui_ctx.egui_wants_keyboard_input();
|
|
let pointer_over_ui = win.egui.egui_ctx.is_pointer_over_egui();
|
|
let dialog_open = win.tab().is_some_and(|t| t.dialog.is_some()) || win.ui.blocks_page();
|
|
match event {
|
|
WindowEvent::ModifiersChanged(mods) => {
|
|
win.modifiers = mods.state();
|
|
let _ = win.egui.on_window_event(&win.window, event);
|
|
},
|
|
WindowEvent::CursorMoved { position, .. } => {
|
|
win.pointer = Some(*position);
|
|
let response = win.egui.on_window_event(&win.window, event);
|
|
let over_page = win.page_point(*position).is_some() && !pointer_over_ui;
|
|
if (over_page || win.page_grab > 0) && !dialog_open {
|
|
win.send_mouse_move(*position);
|
|
win.update_cursor(true);
|
|
} else {
|
|
win.send_mouse_move(*position);
|
|
}
|
|
if response.repaint {
|
|
win.window.request_redraw();
|
|
}
|
|
},
|
|
WindowEvent::CursorLeft { .. } => {
|
|
win.pointer = None;
|
|
let _ = win.egui.on_window_event(&win.window, event);
|
|
if let Some(webview) = win.active_webview() {
|
|
webview.notify_input_event(servo::InputEvent::MouseLeftViewport(servo::MouseLeftViewportEvent { focus_moving_to_another_iframe: false }));
|
|
}
|
|
win.window.request_redraw();
|
|
},
|
|
WindowEvent::MouseInput { state, button, .. } => {
|
|
let on_page = win.pointer.and_then(|p| win.page_point(p)).is_some() && !pointer_over_ui && !dialog_open;
|
|
if on_page || (win.page_grab > 0 && *state == ElementState::Released) {
|
|
// Back/forward mouse buttons navigate.
|
|
if *state == ElementState::Pressed && matches!(button, winit::event::MouseButton::Back | winit::event::MouseButton::Forward) {
|
|
let back = *button == winit::event::MouseButton::Back;
|
|
self.run_in(window_id, if back { Command::Back } else { Command::Forward });
|
|
return;
|
|
}
|
|
if *state == ElementState::Pressed {
|
|
win.ui.close_popups();
|
|
win.egui.egui_ctx.memory_mut(|m| m.stop_text_input());
|
|
}
|
|
win.send_mouse_button(*state, *button);
|
|
win.window.request_redraw();
|
|
} else {
|
|
if *state == ElementState::Pressed {
|
|
win.page_focused = false;
|
|
if let Some(webview) = win.active_webview() {
|
|
webview.set_focused(false);
|
|
}
|
|
}
|
|
let _ = win.egui.on_window_event(&win.window, event);
|
|
win.window.request_redraw();
|
|
}
|
|
},
|
|
WindowEvent::MouseWheel { delta, .. } => {
|
|
let on_page = win.pointer.and_then(|p| win.page_point(p)).is_some() && !pointer_over_ui && !dialog_open;
|
|
if on_page && win.modifiers.control_key() {
|
|
// Ctrl+wheel zooms the page.
|
|
let up = match delta {
|
|
winit::event::MouseScrollDelta::LineDelta(_, y) => *y > 0.0,
|
|
winit::event::MouseScrollDelta::PixelDelta(p) => p.y > 0.0,
|
|
};
|
|
self.run_in(window_id, Command::Zoom(if up { 1 } else { -1 }));
|
|
} else if on_page {
|
|
win.send_wheel(*delta);
|
|
} else {
|
|
let _ = win.egui.on_window_event(&win.window, event);
|
|
win.window.request_redraw();
|
|
}
|
|
},
|
|
WindowEvent::Touch(touch) => {
|
|
if !win.send_touch(touch) {
|
|
let _ = win.egui.on_window_event(&win.window, event);
|
|
}
|
|
},
|
|
WindowEvent::KeyboardInput { event: key, .. } => {
|
|
// Browser shortcuts first: always for "reserved" ones, otherwise unless a text
|
|
// field in the browser UI is being typed in and the key is plain.
|
|
// Recording a shortcut in settings: every key goes to that page.
|
|
let keymap_action = keymap_action.filter(|_| win.ui.pages.capture_key.is_none());
|
|
if let Some(action) = keymap_action {
|
|
let typing_ui = egui_wants_keys && !win.page_focused;
|
|
let plain = !win.modifiers.control_key() && !win.modifiers.alt_key() && !win.modifiers.super_key();
|
|
let skip = typing_ui && plain || (action == crate::keys::Action::Stop && (dialog_open || win.ui.has_popup() || typing_ui));
|
|
if !skip && (crate::keys::reserved(action) || !(win.page_focused && plain && action == crate::keys::Action::Stop && win.fullscreen)) {
|
|
if key.state == ElementState::Pressed {
|
|
self.run_in(window_id, Command::Action(action));
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
if win.page_focused && !dialog_open && !egui_wants_keys {
|
|
if let Some(webview) = win.active_webview() {
|
|
let ev = crate::keys::to_servo(key, win.modifiers);
|
|
webview.notify_input_event(servo::InputEvent::Keyboard(servo::KeyboardEvent::new(ev)));
|
|
}
|
|
} else {
|
|
let _ = win.egui.on_window_event(&win.window, event);
|
|
win.window.request_redraw();
|
|
}
|
|
},
|
|
WindowEvent::Ime(ime) => {
|
|
if win.page_focused && !egui_wants_keys {
|
|
if let Some(webview) = win.active_webview() {
|
|
use servo::{CompositionEvent, CompositionState, ImeEvent, InputEvent};
|
|
let ev = match ime {
|
|
winit::event::Ime::Preedit(text, _) => Some(ImeEvent::Composition(CompositionEvent { state: CompositionState::Update, data: text.clone() })),
|
|
winit::event::Ime::Commit(text) => Some(ImeEvent::Composition(CompositionEvent { state: CompositionState::End, data: text.clone() })),
|
|
winit::event::Ime::Disabled => Some(ImeEvent::Dismissed),
|
|
winit::event::Ime::Enabled => None,
|
|
};
|
|
if let Some(ev) = ev {
|
|
webview.notify_input_event(InputEvent::Ime(ev));
|
|
}
|
|
}
|
|
} else {
|
|
let _ = win.egui.on_window_event(&win.window, event);
|
|
win.window.request_redraw();
|
|
}
|
|
},
|
|
WindowEvent::DroppedFile(path) => {
|
|
let url = Url::from_file_path(path).map(|u| u.to_string()).unwrap_or_default();
|
|
if !url.is_empty() {
|
|
self.run_in(window_id, Command::Open { url, how: Disposition::NewForegroundTab, from: None });
|
|
}
|
|
},
|
|
_ => {
|
|
let response = win.egui.on_window_event(&win.window, event);
|
|
if response.repaint {
|
|
win.window.request_redraw();
|
|
}
|
|
},
|
|
}
|
|
}
|
|
|
|
pub fn restyle_all(&mut self) {
|
|
let ids: Vec<WindowId> = 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);
|
|
}
|
|
}
|
|
let dark = self.web_dark();
|
|
for win in self.windows.values() {
|
|
for tab in &win.tabs {
|
|
if let Some(web) = &tab.web {
|
|
web.webview.notify_theme_change(if dark { servo::Theme::Dark } else { servo::Theme::Light });
|
|
}
|
|
}
|
|
}
|
|
self.redraw_all();
|
|
}
|
|
}
|
|
|
|
/// rustls needs a process-wide crypto provider before Servo or ureq make a TLS connection.
|
|
pub fn rustls_provider() {
|
|
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
|
|
}
|
|
|
|
/// For WebView in closures.
|
|
pub type WebViewHandle = WebView;
|