- tests/smoke/painters.txt (5 tabs, switch, resize, PiP, close) and painters-perf.txt (memory, frame time, threads with 1/5/15 tabs, idle discard); test pages color.html, video.html, clip.webm. - selftest: `resize <w> <h>`, `shot <name> pip`, status gets frames (median/max ms), painters, threads. - Fix: a closing window's egui was destroyed with another window's GL context current, deleting the main window's font texture (chrome text/icons blank after PiP). BrowserWindow::destroy() makes its own context current first. - Fix: PiP CSS resets the video's margin (video was shifted down in the PiP frame). Co-Authored-By: Claude Opus 5.5 <[email protected]>
2415 lines
112 KiB
Rust
2415 lines
112 KiB
Rust
//! What the browser does when asked: commands from the UI and shortcuts, tab operations,
|
|
//! navigation decisions, page messages, downloads, and applying changed settings.
|
|
|
|
use std::path::PathBuf;
|
|
use std::sync::atomic::{AtomicU8, Ordering};
|
|
use std::sync::Arc;
|
|
use std::time::Duration;
|
|
|
|
use servo::{ContextMenuAction, WebViewId};
|
|
use url::Url;
|
|
use winit::event_loop::ActiveEventLoop;
|
|
use winit::window::WindowId;
|
|
|
|
use crate::app::{App, Launch, WindowRequest};
|
|
use crate::inject::{self, PageMessage};
|
|
use crate::keys::Action;
|
|
use crate::net::download;
|
|
use crate::spell::Speller;
|
|
use crate::store::downloads::State as DlState;
|
|
use crate::store::permissions::{Decision, Kind as Perm};
|
|
use crate::tabs::{Dialog, Page, Prompt, Tab};
|
|
use crate::window::Kind;
|
|
use crate::util;
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum Disposition {
|
|
Current,
|
|
NewForegroundTab,
|
|
NewBackgroundTab,
|
|
NewWindow,
|
|
Incognito,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub enum PromptAnswer {
|
|
Allow { remember: bool },
|
|
Deny { remember: bool },
|
|
/// Save login / open external app / open over http.
|
|
Yes,
|
|
/// "Never for this site".
|
|
Never,
|
|
Dismiss,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub enum DialogResult {
|
|
Ok(Option<String>),
|
|
Cancel,
|
|
Auth { username: String, password: String },
|
|
Select(Vec<usize>),
|
|
Color(Option<[u8; 3]>),
|
|
Device(Option<usize>),
|
|
Leave(bool),
|
|
Close,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub enum MenuAction {
|
|
Servo(ContextMenuAction),
|
|
OpenLink(String, Disposition),
|
|
CopyText(String),
|
|
SaveLink(String),
|
|
SearchFor(String),
|
|
SpellReplace(String, String),
|
|
SpellAdd(String),
|
|
Pip,
|
|
ViewSource,
|
|
DevTools,
|
|
QrCode,
|
|
SavePage,
|
|
LoopMedia,
|
|
Dismiss,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub enum DownloadOp {
|
|
Pause(u64),
|
|
Resume(u64),
|
|
Cancel(u64),
|
|
Retry(u64),
|
|
Remove(u64),
|
|
Open(u64),
|
|
ShowInFolder(u64),
|
|
ClearFinished,
|
|
OpenFolder,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub enum Command {
|
|
/// What was typed in the address bar.
|
|
Navigate(String),
|
|
Open { url: String, how: Disposition, from: Option<u64> },
|
|
ShowPage(Page),
|
|
NewTab,
|
|
CloseTab(u64),
|
|
CloseOtherTabs(u64),
|
|
CloseTabsRight(u64),
|
|
SelectTab(usize),
|
|
MoveTab { from: usize, to: usize },
|
|
MoveTabToNewWindow(u64),
|
|
DuplicateTab(u64),
|
|
PinTab(u64),
|
|
MuteTab(u64),
|
|
ReloadTab(u64),
|
|
ReopenClosed(Option<usize>),
|
|
RestoreSession,
|
|
Back,
|
|
Forward,
|
|
HistoryJump(usize),
|
|
Reload { hard: bool },
|
|
Stop,
|
|
Home,
|
|
Zoom(i32),
|
|
SetZoom(f32),
|
|
Find { text: String, forward: bool, case: bool },
|
|
FindClose,
|
|
ToggleBookmark,
|
|
BookmarkAllTabs,
|
|
Action(Action),
|
|
Media { tab: u64, action: String, value: f64 },
|
|
ToggleMuteSite(String),
|
|
Download(DownloadOp),
|
|
DownloadUrl { url: String, page: String, name: String },
|
|
Prompt { tab: u64, answer: PromptAnswer },
|
|
Dialog { tab: u64, result: DialogResult },
|
|
Menu { tab: u64, action: MenuAction },
|
|
FillLogin { tab: u64, id: u64 },
|
|
FillPassword { tab: u64, password: String },
|
|
FillAddress { tab: u64, id: u64 },
|
|
FillCard { tab: u64, id: u64 },
|
|
InstallApp,
|
|
OpenApp(String),
|
|
UninstallApp(String),
|
|
SetAppLauncher { id: String, on: bool },
|
|
CreateShortcut,
|
|
Import { source: usize, bookmarks: bool, history: bool, settings: bool },
|
|
ImportBookmarksFile,
|
|
ExportBookmarks,
|
|
ImportPasswords,
|
|
ExportPasswords,
|
|
InstallScript(String),
|
|
/// User scripts changed: rebuild what pages get.
|
|
ReloadScripts,
|
|
EnterPip,
|
|
ExitPip,
|
|
/// Close the picture-in-picture window showing this tab.
|
|
ClosePip(u64),
|
|
PipAct { action: String, value: f64 },
|
|
UpdateFilterLists,
|
|
CheckUpdates,
|
|
OpenUpdate,
|
|
ClearData { since: u64, what: Vec<String> },
|
|
ClearSiteData(String),
|
|
SwitchProfile(String),
|
|
NewWindow,
|
|
NewIncognito,
|
|
FreeMemory,
|
|
QrCode,
|
|
SavePage,
|
|
PrintPage,
|
|
ViewSource,
|
|
DevToolsEval(String),
|
|
SpellReplace { word: String, by: String },
|
|
Suggest(String),
|
|
Weather,
|
|
FetchArt(String),
|
|
FetchSource(String),
|
|
ToggleRemoteDebugging,
|
|
PingManagers,
|
|
ReloadSpeller,
|
|
WindowMinimize,
|
|
WindowMaximize,
|
|
WindowClose,
|
|
WindowDrag,
|
|
FocusPage,
|
|
CrashReload,
|
|
Quit,
|
|
RestartBrowser,
|
|
Toast(String),
|
|
}
|
|
|
|
impl App {
|
|
/// Run a command for the current window.
|
|
pub fn run(&mut self, command: Command) {
|
|
match self.current_window() {
|
|
Some(w) => self.run_in(w, command),
|
|
None => {
|
|
// No window yet (startup) or only app windows: open a normal one first.
|
|
let tab = Tab::new(self.new_tab_id());
|
|
self.window_requests.push(WindowRequest { kind: Kind::Normal, tabs: vec![tab], active: 0, size: None });
|
|
self.pending_commands.push(command);
|
|
},
|
|
}
|
|
}
|
|
|
|
fn active_index(&self, window: WindowId) -> Option<usize> {
|
|
self.windows.get(&window).map(|w| w.active)
|
|
}
|
|
|
|
fn active_tab_id(&self, window: WindowId) -> Option<u64> {
|
|
self.windows.get(&window).and_then(|w| w.tab()).map(|t| t.id)
|
|
}
|
|
|
|
fn active_url(&self, window: WindowId) -> String {
|
|
self.windows.get(&window).and_then(|w| w.tab()).map(|t| t.url.clone()).unwrap_or_default()
|
|
}
|
|
|
|
/// Evaluate script in a tab's page (no-op for internal pages).
|
|
pub fn eval(&self, tab_id: u64, script: String) {
|
|
if let Some((w, i)) = self.find_tab(tab_id)
|
|
&& let Some(web) = &self.windows[&w].tabs[i].web
|
|
{
|
|
web.webview.evaluate_javascript(script, |_| {});
|
|
}
|
|
}
|
|
|
|
pub fn run_in(&mut self, window: WindowId, command: Command) {
|
|
match command {
|
|
Command::Navigate(text) => {
|
|
let template = self.shared.settings.borrow().search_template();
|
|
if let Some(url) = util::address_to_url(&text, &template) {
|
|
self.navigate(window, url.to_string());
|
|
}
|
|
},
|
|
Command::Open { url, how, from } => self.open(window, url, how, from),
|
|
Command::ShowPage(page) => self.show_page(window, page),
|
|
Command::NewTab => self.new_tab(window, None, true),
|
|
Command::CloseTab(id) => self.close_tab(window, id, true),
|
|
Command::CloseOtherTabs(id) => {
|
|
let ids: Vec<u64> = self.windows.get(&window).map(|w| w.tabs.iter().filter(|t| t.id != id && !t.pinned).map(|t| t.id).collect()).unwrap_or_default();
|
|
for other in ids {
|
|
self.close_tab(window, other, true);
|
|
}
|
|
},
|
|
Command::CloseTabsRight(id) => {
|
|
let ids: Vec<u64> = self.windows.get(&window).map(|w| w.tabs.iter().skip_while(|t| t.id != id).skip(1).map(|t| t.id).collect()).unwrap_or_default();
|
|
for other in ids {
|
|
self.close_tab(window, other, true);
|
|
}
|
|
},
|
|
Command::SelectTab(index) => self.select_tab(window, index),
|
|
Command::MoveTab { from, to } => {
|
|
if let Some(win) = self.windows.get_mut(&window)
|
|
&& from < win.tabs.len()
|
|
{
|
|
let to = to.min(win.tabs.len() - 1);
|
|
let active_id = win.tab().map(|t| t.id);
|
|
let tab = win.tabs.remove(from);
|
|
win.tabs.insert(to, tab);
|
|
if let Some(id) = active_id {
|
|
win.active = win.tab_index(id).unwrap_or(0);
|
|
}
|
|
}
|
|
self.redraw(window);
|
|
},
|
|
Command::MoveTabToNewWindow(id) => {
|
|
let Some(win) = self.windows.get_mut(&window) else { return };
|
|
if win.tabs.len() <= 1 {
|
|
return;
|
|
}
|
|
let Some(i) = win.tab_index(id) else { return };
|
|
// A web view is tied to this window's GL context, so the page reloads in the new window.
|
|
let tab = win.tabs.remove(i);
|
|
win.active = win.active.min(win.tabs.len() - 1);
|
|
let saved = tab.saved();
|
|
if let Some(web) = &tab.web {
|
|
self.hub.forget(web.webview.id());
|
|
}
|
|
drop(tab);
|
|
let new_tab = self.tab_from_saved(&saved);
|
|
self.window_requests.push(WindowRequest { kind: Kind::Normal, tabs: vec![new_tab], active: 0, size: None });
|
|
self.redraw(window);
|
|
},
|
|
Command::DuplicateTab(id) => {
|
|
let url = self.find_tab(id).map(|(w, i)| self.windows[&w].tabs[i].shown_url());
|
|
if let Some(url) = url {
|
|
self.open(window, url, Disposition::NewForegroundTab, Some(id));
|
|
}
|
|
},
|
|
Command::PinTab(id) => {
|
|
if let Some(win) = self.windows.get_mut(&window)
|
|
&& let Some(i) = win.tab_index(id)
|
|
{
|
|
let active_id = win.tab().map(|t| t.id);
|
|
win.tabs[i].pinned = !win.tabs[i].pinned;
|
|
// Pinned tabs sit at the start, unpinned ones right after them.
|
|
let tab = win.tabs.remove(i);
|
|
let pinned_count = win.tabs.iter().filter(|t| t.pinned).count();
|
|
win.tabs.insert(pinned_count.min(win.tabs.len()), tab);
|
|
win.active = active_id.and_then(|a| win.tab_index(a)).unwrap_or(0);
|
|
}
|
|
self.redraw(window);
|
|
},
|
|
Command::MuteTab(id) => {
|
|
let muted = self.find_tab(id).map(|(w, i)| {
|
|
let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i];
|
|
tab.muted = !tab.muted;
|
|
tab.muted
|
|
});
|
|
if let Some(muted) = muted {
|
|
self.eval(id, inject::call("media.act", &["mute".into(), muted.into()]));
|
|
}
|
|
self.redraw(window);
|
|
},
|
|
Command::ReloadTab(id) => {
|
|
if let Some((w, i)) = self.find_tab(id)
|
|
&& let Some(web) = &self.windows[&w].tabs[i].web
|
|
{
|
|
web.webview.reload();
|
|
}
|
|
},
|
|
Command::ReopenClosed(index) => {
|
|
let saved = match index {
|
|
Some(i) => self.shared.session.borrow_mut().take_closed(i),
|
|
None => self.shared.session.borrow_mut().pop_closed(),
|
|
};
|
|
if let Some(saved) = saved {
|
|
let mut tab = self.tab_from_saved(&saved);
|
|
if tab.pending_url.is_none() && tab.page.is_none() {
|
|
tab.pending_url = Some(saved.url.clone());
|
|
}
|
|
self.insert_tab(window, tab, true);
|
|
}
|
|
},
|
|
Command::RestoreSession => {
|
|
let previous = self.shared.session.borrow().previous.clone();
|
|
for saved_window in previous.windows {
|
|
let tabs: Vec<Tab> = saved_window.tabs.iter().map(|s| self.tab_from_saved(s)).collect();
|
|
if !tabs.is_empty() {
|
|
self.window_requests.push(WindowRequest { kind: Kind::Normal, tabs, active: saved_window.active, size: None });
|
|
}
|
|
}
|
|
},
|
|
Command::Back => self.go_back(window),
|
|
Command::Forward => {
|
|
if let Some(web) = self.windows.get(&window).and_then(|w| w.active_webview())
|
|
&& web.can_go_forward()
|
|
{
|
|
web.go_forward(1);
|
|
}
|
|
},
|
|
Command::HistoryJump(target) => {
|
|
if let Some(win) = self.windows.get(&window)
|
|
&& let Some(tab) = win.tab()
|
|
&& let Some(web) = tab.webview()
|
|
{
|
|
let current = tab.history_index;
|
|
if target < current {
|
|
web.go_back(current - target);
|
|
} else if target > current {
|
|
web.go_forward(target - current);
|
|
}
|
|
}
|
|
},
|
|
Command::Reload { hard } => {
|
|
if let Some(win) = self.windows.get_mut(&window)
|
|
&& let Some(tab) = win.tab_mut()
|
|
{
|
|
tab.crashed = None;
|
|
if hard {
|
|
if let Some(servo) = &self.servo {
|
|
servo.network_manager().clear_cache();
|
|
}
|
|
}
|
|
if let Some(web) = &tab.web {
|
|
web.webview.reload();
|
|
}
|
|
}
|
|
},
|
|
Command::Stop => {
|
|
// Servo 0.7 has no "stop loading"; loading the current URL's entry again isn't
|
|
// right either, so the closest thing is to close open dialogs and leave fullscreen.
|
|
if let Some(win) = self.windows.get_mut(&window) {
|
|
if win.fullscreen
|
|
&& let Some(web) = win.active_webview()
|
|
{
|
|
web.exit_fullscreen();
|
|
}
|
|
if let Some(tab) = win.tab_mut() {
|
|
tab.find.open = false;
|
|
}
|
|
win.ui.close_popups();
|
|
}
|
|
self.redraw(window);
|
|
},
|
|
Command::Home => {
|
|
let home = self.shared.settings.borrow().startup.home_url.clone();
|
|
self.navigate(window, home);
|
|
},
|
|
Command::Zoom(step) => {
|
|
let Some(win) = self.windows.get(&window) else { return };
|
|
let Some(tab) = win.tab() else { return };
|
|
const STEPS: &[f32] = &[0.25, 0.33, 0.5, 0.67, 0.75, 0.8, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0];
|
|
let current = tab.zoom;
|
|
let next = match step {
|
|
0 => 1.0,
|
|
s if s > 0 => STEPS.iter().copied().find(|z| *z > current + 0.001).unwrap_or(5.0),
|
|
_ => STEPS.iter().rev().copied().find(|z| *z < current - 0.001).unwrap_or(0.25),
|
|
};
|
|
self.run_in(window, Command::SetZoom(next));
|
|
},
|
|
Command::SetZoom(zoom) => {
|
|
let host = {
|
|
let Some(win) = self.windows.get_mut(&window) else { return };
|
|
let Some(tab) = win.tab_mut() else { return };
|
|
tab.zoom = zoom;
|
|
if let Some(web) = &tab.web {
|
|
web.webview.set_page_zoom(zoom);
|
|
}
|
|
tab.host()
|
|
};
|
|
// Remembered per site, like other browsers.
|
|
self.shared.settings.borrow_mut().set_zoom_for(&host, zoom);
|
|
self.redraw(window);
|
|
},
|
|
Command::Find { text, forward, case } => {
|
|
let Some(id) = self.active_tab_id(window) else { return };
|
|
if let Some(win) = self.windows.get_mut(&window)
|
|
&& let Some(tab) = win.tab_mut()
|
|
{
|
|
tab.find.open = true;
|
|
tab.find.text = text.clone();
|
|
tab.find.case_sensitive = case;
|
|
}
|
|
if text.is_empty() {
|
|
self.eval(id, inject::call("find.stop", &[]));
|
|
if let Some(tab) = self.windows.get_mut(&window).and_then(|w| w.tab_mut()) {
|
|
tab.find.count = 0;
|
|
tab.find.index = 0;
|
|
}
|
|
} else {
|
|
self.eval(id, inject::call("find.run", &[text.into(), case.into(), (if forward { 1 } else { -1 }).into()]));
|
|
}
|
|
},
|
|
Command::FindClose => {
|
|
if let Some(id) = self.active_tab_id(window) {
|
|
self.eval(id, inject::call("find.stop", &[]));
|
|
}
|
|
if let Some(tab) = self.windows.get_mut(&window).and_then(|w| w.tab_mut()) {
|
|
tab.find = Default::default();
|
|
}
|
|
self.redraw(window);
|
|
},
|
|
Command::ToggleBookmark => {
|
|
let Some(win) = self.windows.get(&window) else { return };
|
|
let Some(tab) = win.tab() else { return };
|
|
if tab.page.is_some() {
|
|
return;
|
|
}
|
|
let (url, title) = (tab.url.clone(), tab.display_title());
|
|
let mut bookmarks = self.shared.bookmarks.borrow_mut();
|
|
if bookmarks.is_bookmarked(&url) {
|
|
bookmarks.remove_url(&url);
|
|
drop(bookmarks);
|
|
self.shared.toast("Bookmark removed");
|
|
} else {
|
|
bookmarks.add(crate::store::bookmarks::BAR, &title, &url);
|
|
drop(bookmarks);
|
|
if let Some(win) = self.windows.get_mut(&window) {
|
|
win.ui.flyout = Some(crate::ui::Flyout::EditBookmark(url));
|
|
}
|
|
}
|
|
self.redraw(window);
|
|
},
|
|
Command::BookmarkAllTabs => {
|
|
let tabs: Vec<(String, String)> = self.windows.get(&window).map(|w| w.tabs.iter().filter(|t| t.page.is_none()).map(|t| (t.display_title(), t.url.clone())).collect()).unwrap_or_default();
|
|
let mut b = self.shared.bookmarks.borrow_mut();
|
|
let folder = b.add_folder(crate::store::bookmarks::OTHER, &format!("Tabs, {}", util::format_date(util::now())));
|
|
for (title, url) in tabs {
|
|
b.add(folder, &title, &url);
|
|
}
|
|
drop(b);
|
|
self.shared.toast("All tabs bookmarked in Other bookmarks");
|
|
},
|
|
Command::Action(action) => self.run_action(window, action),
|
|
Command::Media { tab, action, value } => {
|
|
let arg = if action == "mute" { serde_json::Value::from(value > 0.5) } else { serde_json::Value::from(value) };
|
|
self.eval(tab, inject::call("media.act", &[action.into(), arg]));
|
|
},
|
|
Command::ToggleMuteSite(host) => {
|
|
let muted = {
|
|
let mut s = self.shared.settings.borrow_mut();
|
|
if s.media.muted_sites.contains(&host) {
|
|
s.media.muted_sites.retain(|h| h != &host);
|
|
false
|
|
} else {
|
|
s.media.muted_sites.push(host.clone());
|
|
true
|
|
}
|
|
};
|
|
let ids: Vec<u64> = self.windows.values().flat_map(|w| w.tabs.iter().filter(|t| t.host() == host).map(|t| t.id)).collect();
|
|
for id in ids {
|
|
if let Some((w, i)) = self.find_tab(id) {
|
|
self.windows.get_mut(&w).expect("found").tabs[i].muted = muted;
|
|
}
|
|
self.eval(id, inject::call("media.act", &["mute".into(), muted.into()]));
|
|
}
|
|
},
|
|
Command::Download(op) => self.download_op(op),
|
|
Command::DownloadUrl { url, page, name } => {
|
|
if let Ok(url) = Url::parse(&url) {
|
|
self.start_download(url, page, (!name.is_empty()).then_some(name));
|
|
}
|
|
},
|
|
Command::Prompt { tab, answer } => self.answer_prompt(tab, answer),
|
|
Command::Dialog { tab, result } => self.finish_dialog(tab, result),
|
|
Command::Menu { tab, action } => self.menu_action(window, tab, action),
|
|
Command::FillLogin { tab, id } => {
|
|
let login = self.shared.vault.borrow().contents.logins.iter().find(|l| l.id == id).cloned();
|
|
if let Some(login) = login {
|
|
self.eval(tab, inject::call("fill.login", &[login.username.into(), login.password.into()]));
|
|
self.shared.vault.borrow_mut().mark_used(id);
|
|
}
|
|
self.close_dialog(tab);
|
|
},
|
|
Command::FillPassword { tab, password } => {
|
|
self.eval(tab, inject::call("fill.password", &[password.into()]));
|
|
self.close_dialog(tab);
|
|
},
|
|
Command::FillAddress { tab, id } => {
|
|
let address = self.shared.vault.borrow().contents.addresses.iter().find(|a| a.id == id).cloned();
|
|
if let Some(a) = address {
|
|
self.eval(tab, inject::call("fill.address", &[serde_json::to_value(&a).unwrap_or_default()]));
|
|
}
|
|
self.close_dialog(tab);
|
|
},
|
|
Command::FillCard { tab, id } => {
|
|
let card = self.shared.vault.borrow().contents.cards.iter().find(|c| c.id == id).cloned();
|
|
if let Some(c) = card {
|
|
self.eval(tab, inject::call("fill.card", &[serde_json::to_value(&c).unwrap_or_default()]));
|
|
}
|
|
self.close_dialog(tab);
|
|
},
|
|
Command::InstallApp => self.install_app(window),
|
|
Command::OpenApp(id) => {
|
|
let app = self.shared.apps.borrow().get(&id).cloned();
|
|
if let Some(app) = app {
|
|
let mut tab = Tab::new(self.new_tab_id());
|
|
tab.page = None;
|
|
tab.pending_url = Some(app.start_url.clone());
|
|
self.window_requests.push(WindowRequest { kind: Kind::App(id), tabs: vec![tab], active: 0, size: Some((app.width, app.height)) });
|
|
}
|
|
},
|
|
Command::UninstallApp(id) => {
|
|
self.shared.apps.borrow_mut().uninstall(&id);
|
|
self.shared.toast("App removed");
|
|
},
|
|
Command::SetAppLauncher { id, on } => {
|
|
let profile = self.shared.paths.profile.clone();
|
|
self.shared.apps.borrow_mut().set_launcher(&id, on, &profile);
|
|
},
|
|
Command::CreateShortcut => {
|
|
let Some(tab) = self.windows.get(&window).and_then(|w| w.tab()) else { return };
|
|
let (name, url) = (tab.display_title(), tab.url.clone());
|
|
let icon = tab.favicon_png.clone();
|
|
let icons = self.shared.paths.app_icons();
|
|
let icon_path = icon.and_then(|png| {
|
|
let path = icons.join(format!("shortcut-{}.png", util::random_hex(4)));
|
|
std::fs::create_dir_all(&icons).ok()?;
|
|
std::fs::write(&path, png).ok()?;
|
|
Some(path)
|
|
});
|
|
match crate::store::apps::create_desktop_shortcut(&name, &url, &icon_path.unwrap_or_default()) {
|
|
Ok(path) => self.shared.toast(format!("Shortcut created: {}", path.display())),
|
|
Err(error) => self.shared.toast(format!("The shortcut couldn't be created ({error})")),
|
|
}
|
|
},
|
|
Command::Import { source, bookmarks, history, settings } => self.import_from(source, bookmarks, history, settings),
|
|
Command::ImportBookmarksFile => {
|
|
self.spawn(
|
|
"import-bookmarks",
|
|
|| rfd::FileDialog::new().add_filter("Bookmarks (HTML)", &["html", "htm"]).pick_file().and_then(|p| std::fs::read_to_string(p).ok()),
|
|
|app, text: Option<String>| {
|
|
if let Some(text) = text {
|
|
let n = app.shared.bookmarks.borrow_mut().import_html(&text, "file");
|
|
app.shared.toast(format!("{n} bookmarks imported"));
|
|
}
|
|
},
|
|
);
|
|
},
|
|
Command::ExportBookmarks => {
|
|
let html = self.shared.bookmarks.borrow().export_html();
|
|
self.spawn(
|
|
"export-bookmarks",
|
|
move || {
|
|
let path = rfd::FileDialog::new().set_file_name("bookmarks.html").save_file()?;
|
|
std::fs::write(&path, html).ok().map(|_| path)
|
|
},
|
|
|app, path: Option<PathBuf>| {
|
|
if let Some(path) = path {
|
|
app.shared.toast(format!("Bookmarks saved to {}", path.display()));
|
|
}
|
|
},
|
|
);
|
|
},
|
|
Command::ImportPasswords => {
|
|
self.spawn(
|
|
"import-passwords",
|
|
|| rfd::FileDialog::new().add_filter("Passwords (CSV)", &["csv"]).pick_file().and_then(|p| std::fs::read_to_string(p).ok()),
|
|
|app, text: Option<String>| {
|
|
if let Some(text) = text {
|
|
let result = app.shared.vault.borrow_mut().import_csv(&text);
|
|
match result {
|
|
Ok((added, skipped)) => app.shared.toast(format!("{added} passwords imported, {skipped} skipped")),
|
|
Err(error) => app.shared.toast(error.to_string()),
|
|
}
|
|
}
|
|
},
|
|
);
|
|
},
|
|
Command::ExportPasswords => {
|
|
let csv = self.shared.vault.borrow().export_csv();
|
|
match csv {
|
|
Ok(csv) => self.spawn(
|
|
"export-passwords",
|
|
move || {
|
|
let path = rfd::FileDialog::new().set_file_name("nacre-passwords.csv").save_file()?;
|
|
util::write_atomic(&path, csv.as_bytes(), true).ok().map(|_| path)
|
|
},
|
|
|app, path: Option<PathBuf>| {
|
|
if let Some(path) = path {
|
|
app.shared.toast(format!("Passwords saved to {} — anyone who can read this file can see them", path.display()));
|
|
}
|
|
},
|
|
),
|
|
Err(error) => self.shared.toast(error.to_string()),
|
|
}
|
|
},
|
|
Command::InstallScript(url) => {
|
|
let kind = if url.ends_with(".user.css") { crate::store::scripts::Kind::Style } else { crate::store::scripts::Kind::Script };
|
|
let fetch_url = url.clone();
|
|
self.spawn(
|
|
"install-script",
|
|
move || crate::net::fetch::get(&fetch_url, &[], 4 * 1024 * 1024, Duration::from_secs(30)),
|
|
move |app, result| match result {
|
|
Ok(fetched) if fetched.ok() => {
|
|
app.shared.scripts.borrow_mut().add(kind, &fetched.text(), &url);
|
|
app.install_page_scripts();
|
|
app.shared.toast("Installed. It runs on matching pages from their next load.");
|
|
},
|
|
Ok(fetched) => app.shared.toast(format!("The script couldn't be downloaded (the server answered {})", fetched.status)),
|
|
Err(error) => app.shared.toast(format!("The script couldn't be downloaded ({error})")),
|
|
},
|
|
);
|
|
},
|
|
Command::ReloadScripts => self.install_page_scripts(),
|
|
Command::EnterPip => self.enter_pip(window),
|
|
Command::ExitPip => {
|
|
if let Some(win) = self.windows.get(&window)
|
|
&& let Kind::Pip { window: source, tab } = win.kind.clone()
|
|
{
|
|
self.close_window(window);
|
|
let _ = (source, tab);
|
|
}
|
|
},
|
|
Command::ClosePip(tab) => {
|
|
let pip = self.windows.iter().find(|(_, w)| matches!(w.kind, Kind::Pip { tab: t, .. } if t == tab)).map(|(id, _)| *id);
|
|
if let Some(pip) = pip {
|
|
self.close_window(pip);
|
|
}
|
|
},
|
|
Command::PipAct { action, value } => {
|
|
if let Some(win) = self.windows.get(&window)
|
|
&& let Kind::Pip { tab, .. } = win.kind.clone()
|
|
{
|
|
self.eval(tab, inject::call("pip.act", &[action.into(), value.into()]));
|
|
}
|
|
},
|
|
Command::UpdateFilterLists => self.update_filter_lists(0),
|
|
Command::CheckUpdates => self.check_updates(true),
|
|
Command::OpenUpdate => {
|
|
let release = self.shared.update.borrow().clone();
|
|
if let Some(release) = release {
|
|
let target = if release.asset.is_empty() { release.page } else { release.asset };
|
|
self.open(window, target, Disposition::NewForegroundTab, None);
|
|
}
|
|
},
|
|
Command::ClearData { since, what } => self.clear_data(since, &what),
|
|
Command::ClearSiteData(host) => {
|
|
if let Some(servo) = &self.servo {
|
|
let sites: Vec<String> = servo.site_data_manager().site_data(servo::StorageType::all()).into_iter().map(|s| s.name()).filter(|n| util::host_matches(n, &host) || util::host_matches(&host, n)).collect();
|
|
let refs: Vec<&str> = sites.iter().map(String::as_str).collect();
|
|
servo.site_data_manager().clear_site_data(&refs, servo::StorageType::all());
|
|
}
|
|
self.shared.permissions.borrow_mut().clear_host(&host);
|
|
self.shared.toast(format!("Data for {host} deleted"));
|
|
},
|
|
Command::SwitchProfile(name) => {
|
|
if let Ok(exe) = std::env::current_exe() {
|
|
let _ = std::process::Command::new(exe).args(["--profile", &name]).spawn();
|
|
}
|
|
},
|
|
Command::NewWindow => {
|
|
let tab = Tab::new(self.new_tab_id());
|
|
self.window_requests.push(WindowRequest { kind: Kind::Normal, tabs: vec![tab], active: 0, size: None });
|
|
},
|
|
Command::NewIncognito => {
|
|
if self.shared.incognito {
|
|
self.run_in(window, Command::NewWindow);
|
|
} else if let Ok(exe) = std::env::current_exe() {
|
|
let _ = std::process::Command::new(exe).args(["--incognito", "--profile", &self.shared.paths.profile]).spawn();
|
|
}
|
|
},
|
|
Command::FreeMemory => {
|
|
let mut freed = 0;
|
|
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_some() && !tab.audible() && tab.pip_size.is_none() {
|
|
tab.pending_url = Some(tab.url.clone());
|
|
if let Some(web) = tab.web.take() {
|
|
self.hub.forget(web.webview.id());
|
|
}
|
|
freed += 1;
|
|
}
|
|
}
|
|
}
|
|
if let Some(servo) = &self.servo {
|
|
servo.network_manager().clear_cache();
|
|
}
|
|
self.shared.toast(format!("{freed} background tabs unloaded; they load again when you open them"));
|
|
},
|
|
Command::QrCode => {
|
|
let url = self.active_url(window);
|
|
if let Some(win) = self.windows.get_mut(&window) {
|
|
win.ui.flyout = Some(crate::ui::Flyout::Qr(url));
|
|
}
|
|
self.redraw(window);
|
|
},
|
|
Command::SavePage => self.save_page(window),
|
|
Command::PrintPage => self.print_page(window),
|
|
Command::ViewSource => {
|
|
let url = self.active_url(window);
|
|
if !url.is_empty() {
|
|
self.open(window, Page::Source(url).url(), Disposition::NewForegroundTab, None);
|
|
}
|
|
},
|
|
Command::DevToolsEval(script) => {
|
|
// Developer tools run against the last web tab that was active in this window.
|
|
let target = self.windows.get(&window).and_then(|w| w.ui.devtools_target);
|
|
if let Some(tab) = target
|
|
&& let Some((w, i)) = self.find_tab(tab)
|
|
&& let Some(web) = &self.windows[&w].tabs[i].web
|
|
{
|
|
let webview = web.webview.clone();
|
|
let jobs = self.jobs_tx.clone();
|
|
let proxy = self.proxy.clone();
|
|
self.windows.get_mut(&w).expect("found").tabs[i].push_console(servo::ConsoleLogLevel::Log, format!("> {script}"));
|
|
webview.evaluate_javascript(script, move |result| {
|
|
let text = match result {
|
|
Ok(value) => format!("{value:?}"),
|
|
Err(error) => format!("Error: {error:?}"),
|
|
};
|
|
let _ = jobs.send(Box::new(move |app: &mut App| {
|
|
if let Some((w, i)) = app.find_tab(tab) {
|
|
app.windows.get_mut(&w).expect("found").tabs[i].push_console(servo::ConsoleLogLevel::Info, text);
|
|
app.redraw(w);
|
|
}
|
|
}));
|
|
let _ = proxy.send_event(crate::app::AppEvent::Wake);
|
|
});
|
|
}
|
|
},
|
|
Command::SpellReplace { word, by } => {
|
|
if let Some(id) = self.active_tab_id(window) {
|
|
self.eval(id, inject::call("spell.replace", &[word.into(), by.into()]));
|
|
}
|
|
},
|
|
Command::Suggest(query) => self.fetch_suggestions(query),
|
|
Command::Weather => self.fetch_weather(),
|
|
Command::FetchSource(url) => {
|
|
if self.shared.sources.borrow().contains_key(&url) {
|
|
return;
|
|
}
|
|
self.shared.sources.borrow_mut().insert(url.clone(), None);
|
|
let headers = Url::parse(&url).map(|u| self.request_headers(&u, "")).unwrap_or_default();
|
|
let fetch_url = url.clone();
|
|
self.spawn("source", move || {
|
|
let refs: Vec<(&str, &str)> = headers.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
|
|
crate::net::fetch::get(&fetch_url, &refs, 16 * 1024 * 1024, Duration::from_secs(30)).map(|f| f.text())
|
|
}, move |app, result| {
|
|
app.shared.sources.borrow_mut().insert(url, Some(result));
|
|
app.redraw_all();
|
|
});
|
|
},
|
|
Command::ToggleRemoteDebugging => {
|
|
let on = {
|
|
let mut s = self.shared.settings.borrow_mut();
|
|
s.web.remote_debugging = !s.web.remote_debugging;
|
|
s.web.remote_debugging
|
|
};
|
|
self.shared.toast_with(if on { "Remote debugging turns on after a restart" } else { "Remote debugging turns off after a restart" }, "Restart now", Command::RestartBrowser);
|
|
},
|
|
Command::FetchArt(url) => {
|
|
if self.shared.art_images.borrow().contains_key(&url) || !url.starts_with("http") {
|
|
return;
|
|
}
|
|
self.shared.art_images.borrow_mut().insert(url.clone(), None);
|
|
let fetch_url = url.clone();
|
|
self.spawn("art", move || {
|
|
let fetched = crate::net::fetch::get(&fetch_url, &[], 8 * 1024 * 1024, Duration::from_secs(20)).ok()?;
|
|
let image = image::load_from_memory(&fetched.body).ok()?.thumbnail(256, 256).to_rgba8();
|
|
Some(egui::ColorImage::from_rgba_unmultiplied([image.width() as usize, image.height() as usize], image.as_raw()))
|
|
}, move |app, image| {
|
|
app.shared.art_images.borrow_mut().insert(url, image);
|
|
app.redraw_all();
|
|
});
|
|
},
|
|
Command::PingManagers => self.ping_download_managers(),
|
|
Command::ReloadSpeller => self.load_speller(),
|
|
Command::WindowMinimize => {
|
|
if let Some(w) = self.windows.get(&window) {
|
|
w.window.set_minimized(true);
|
|
}
|
|
},
|
|
Command::WindowMaximize => {
|
|
if let Some(w) = self.windows.get(&window) {
|
|
w.window.set_maximized(!w.window.is_maximized());
|
|
}
|
|
},
|
|
Command::WindowClose => self.close_window(window),
|
|
Command::WindowDrag => {
|
|
if let Some(w) = self.windows.get(&window) {
|
|
let _ = w.window.drag_window();
|
|
}
|
|
},
|
|
Command::FocusPage => {
|
|
if let Some(win) = self.windows.get_mut(&window) {
|
|
win.page_focused = true;
|
|
if let Some(web) = win.active_webview() {
|
|
web.set_focused(true);
|
|
}
|
|
}
|
|
},
|
|
Command::CrashReload => {
|
|
if let Some(win) = self.windows.get_mut(&window)
|
|
&& let Some(tab) = win.tab_mut()
|
|
{
|
|
tab.crashed = None;
|
|
if let Some(web) = &tab.web {
|
|
web.webview.reload();
|
|
}
|
|
}
|
|
},
|
|
Command::Quit => self.quit(),
|
|
Command::RestartBrowser => {
|
|
self.quit();
|
|
if let Ok(exe) = std::env::current_exe() {
|
|
let mut command = std::process::Command::new(exe);
|
|
command.args(["--profile", &self.shared.paths.profile]);
|
|
let _ = command.spawn();
|
|
}
|
|
},
|
|
Command::Toast(text) => self.shared.toast(text),
|
|
}
|
|
}
|
|
|
|
fn run_action(&mut self, window: WindowId, action: Action) {
|
|
let tab_id = self.active_tab_id(window);
|
|
let tab_count = self.windows.get(&window).map(|w| w.tabs.len()).unwrap_or(0);
|
|
let active = self.active_index(window).unwrap_or(0);
|
|
let select = |i: usize| Command::SelectTab(i);
|
|
let command = match action {
|
|
Action::NewTab => Command::NewTab,
|
|
Action::NewWindow => Command::NewWindow,
|
|
Action::NewIncognito => Command::NewIncognito,
|
|
Action::CloseTab => match tab_id {
|
|
Some(id) => Command::CloseTab(id),
|
|
None => return,
|
|
},
|
|
Action::CloseWindow => Command::WindowClose,
|
|
Action::ReopenClosed => Command::ReopenClosed(None),
|
|
Action::NextTab => select((active + 1) % tab_count.max(1)),
|
|
Action::PrevTab => select((active + tab_count.max(1) - 1) % tab_count.max(1)),
|
|
Action::Tab1 => select(0),
|
|
Action::Tab2 => select(1),
|
|
Action::Tab3 => select(2),
|
|
Action::Tab4 => select(3),
|
|
Action::Tab5 => select(4),
|
|
Action::Tab6 => select(5),
|
|
Action::Tab7 => select(6),
|
|
Action::Tab8 => select(7),
|
|
Action::LastTab => select(tab_count.saturating_sub(1)),
|
|
Action::MoveTabLeft => Command::MoveTab { from: active, to: active.saturating_sub(1) },
|
|
Action::MoveTabRight => Command::MoveTab { from: active, to: active + 1 },
|
|
Action::DuplicateTab => match tab_id {
|
|
Some(id) => Command::DuplicateTab(id),
|
|
None => return,
|
|
},
|
|
Action::PinTab => match tab_id {
|
|
Some(id) => Command::PinTab(id),
|
|
None => return,
|
|
},
|
|
Action::MuteTab => match tab_id {
|
|
Some(id) => Command::MuteTab(id),
|
|
None => return,
|
|
},
|
|
Action::Back => Command::Back,
|
|
Action::Forward => Command::Forward,
|
|
Action::Reload => Command::Reload { hard: false },
|
|
Action::HardReload => Command::Reload { hard: true },
|
|
Action::Stop => Command::Stop,
|
|
Action::Home => Command::Home,
|
|
Action::FocusAddress => {
|
|
if let Some(win) = self.windows.get_mut(&window) {
|
|
win.ui.focus_omnibox = true;
|
|
win.page_focused = false;
|
|
if let Some(web) = win.active_webview() {
|
|
web.set_focused(false);
|
|
}
|
|
}
|
|
self.redraw(window);
|
|
return;
|
|
},
|
|
Action::Find | Action::FindNext | Action::FindPrev => {
|
|
if let Some(win) = self.windows.get_mut(&window)
|
|
&& let Some(tab) = win.tab_mut()
|
|
{
|
|
let open = tab.find.open;
|
|
tab.find.open = true;
|
|
tab.find.focus = action == Action::Find || !open;
|
|
let (text, case) = (tab.find.text.clone(), tab.find.case_sensitive);
|
|
win.page_focused = false;
|
|
if action != Action::Find && !text.is_empty() {
|
|
self.run_in(window, Command::Find { text, forward: action == Action::FindNext, case });
|
|
}
|
|
}
|
|
self.redraw(window);
|
|
return;
|
|
},
|
|
Action::Bookmark => Command::ToggleBookmark,
|
|
Action::BookmarkAll => Command::BookmarkAllTabs,
|
|
Action::BookmarksManager => Command::ShowPage(Page::Bookmarks),
|
|
Action::ToggleBookmarksBar => {
|
|
use crate::store::settings::BookmarksBar;
|
|
let mut s = self.shared.settings.borrow_mut();
|
|
s.ui.bookmarks_bar = if s.ui.bookmarks_bar == BookmarksBar::Always { BookmarksBar::Never } else { BookmarksBar::Always };
|
|
drop(s);
|
|
self.redraw_all();
|
|
return;
|
|
},
|
|
Action::History => Command::ShowPage(Page::History),
|
|
Action::Downloads => Command::ShowPage(Page::Downloads),
|
|
Action::Passwords => Command::ShowPage(Page::Passwords),
|
|
Action::Settings => Command::ShowPage(Page::Settings(String::new())),
|
|
Action::ZoomIn => Command::Zoom(1),
|
|
Action::ZoomOut => Command::Zoom(-1),
|
|
Action::ZoomReset => Command::Zoom(0),
|
|
Action::Fullscreen => {
|
|
if let Some(win) = self.windows.get_mut(&window) {
|
|
let on = win.window.fullscreen().is_none();
|
|
win.window.set_fullscreen(on.then_some(winit::window::Fullscreen::Borderless(None)));
|
|
win.fullscreen = on;
|
|
if !on && let Some(web) = win.active_webview() {
|
|
web.exit_fullscreen();
|
|
}
|
|
}
|
|
self.redraw(window);
|
|
return;
|
|
},
|
|
Action::DevTools => {
|
|
if let Some(win) = self.windows.get_mut(&window) {
|
|
win.ui.devtools_target = win.tab().filter(|t| t.web.is_some()).map(|t| t.id).or(win.ui.devtools_target);
|
|
}
|
|
Command::ShowPage(Page::DevTools)
|
|
},
|
|
Action::ViewSource => Command::ViewSource,
|
|
Action::SavePage => Command::SavePage,
|
|
Action::Print => Command::PrintPage,
|
|
Action::PictureInPicture => Command::EnterPip,
|
|
Action::MediaPlayPause => {
|
|
if let Some(tab) = self.media_tab() {
|
|
Command::Media { tab, action: "toggle".into(), value: 0.0 }
|
|
} else {
|
|
return;
|
|
}
|
|
},
|
|
Action::QrCode => Command::QrCode,
|
|
Action::ClearData => Command::ShowPage(Page::ClearData),
|
|
Action::TaskManager => Command::ShowPage(Page::TaskManager),
|
|
Action::Quit => Command::Quit,
|
|
};
|
|
self.run_in(window, command);
|
|
}
|
|
|
|
// ── tabs and navigation ───────────────────────────────────────────
|
|
|
|
pub fn insert_tab(&mut self, window: WindowId, tab: Tab, foreground: bool) {
|
|
let Some(win) = self.windows.get_mut(&window) else { return };
|
|
// New tabs go right after the current one (after its other children, like Chrome).
|
|
let index = (win.active + 1).min(win.tabs.len());
|
|
win.tabs.insert(index, tab);
|
|
if foreground || win.tabs.len() == 1 {
|
|
win.active = index;
|
|
} else if index <= win.active {
|
|
win.active += 1;
|
|
}
|
|
if foreground {
|
|
self.ensure_loaded(window);
|
|
if let Some(win) = self.windows.get_mut(&window) {
|
|
win.ui.omnibox_edit = None;
|
|
if win.tab().is_some_and(|t| t.page == Some(Page::NewTab)) {
|
|
win.ui.focus_omnibox = true;
|
|
}
|
|
}
|
|
}
|
|
self.redraw(window);
|
|
}
|
|
|
|
pub fn new_tab(&mut self, window: WindowId, url: Option<String>, foreground: bool) {
|
|
let mut tab = Tab::new(self.new_tab_id());
|
|
if let Some(url) = url {
|
|
match Page::from_url(&url) {
|
|
Some(page) => tab.page = Some(page),
|
|
None => {
|
|
tab.page = None;
|
|
tab.url = url.clone();
|
|
tab.title = url.clone();
|
|
tab.pending_url = Some(url);
|
|
},
|
|
}
|
|
}
|
|
if !foreground && tab.pending_url.is_some() {
|
|
// Background tabs start loading at once (lazy loading is only for restored tabs).
|
|
let url = tab.pending_url.take().unwrap_or_default();
|
|
if let (Some(win), Ok(parsed)) = (self.windows.get(&window), Url::parse(&url)) {
|
|
tab.web = Some(self.build_webview(win, parsed));
|
|
tab.load_status = Some(servo::LoadStatus::Started);
|
|
}
|
|
}
|
|
self.insert_tab(window, tab, foreground);
|
|
}
|
|
|
|
pub fn select_tab(&mut self, window: WindowId, index: usize) {
|
|
if let Some(win) = self.windows.get_mut(&window)
|
|
&& index < win.tabs.len()
|
|
{
|
|
win.active = index;
|
|
win.ui.omnibox_edit = win.tabs[index].draft.clone();
|
|
win.ui.close_popups();
|
|
win.tabs[index].last_shown = std::time::Instant::now();
|
|
if win.tabs[index].page.is_none() {
|
|
win.ui.devtools_target = Some(win.tabs[index].id);
|
|
}
|
|
}
|
|
self.ensure_loaded(window);
|
|
if let Some(mut win) = self.windows.remove(&window) {
|
|
// Theme follows the site colour when that is the colour source.
|
|
self.style_window(&mut win);
|
|
self.windows.insert(window, win);
|
|
}
|
|
self.redraw(window);
|
|
}
|
|
|
|
pub fn close_tab(&mut self, window: WindowId, tab_id: u64, remember: bool) {
|
|
let Some((w, i)) = self.find_tab(tab_id) else { return };
|
|
let _ = window;
|
|
let (empty, kind) = {
|
|
let win = self.windows.get_mut(&w).expect("found");
|
|
let tab = win.tabs.remove(i);
|
|
if remember && win.kind == Kind::Normal {
|
|
self.shared.session.borrow_mut().push_closed(tab.saved());
|
|
}
|
|
if let Some(web) = &tab.web {
|
|
self.hub.forget(web.webview.id());
|
|
}
|
|
let opener = tab.opener;
|
|
if tab.pip_size.is_some() {
|
|
self.window_closes.push(Kind::Pip { window: w, tab: tab_id });
|
|
}
|
|
drop(tab);
|
|
// Go back to the tab that opened this one, else the one to the right.
|
|
if let Some(opener) = opener.and_then(|o| win.tab_index(o)) {
|
|
if i == win.active || win.active >= win.tabs.len() {
|
|
win.active = opener;
|
|
}
|
|
} else if i < win.active || win.active >= win.tabs.len() {
|
|
win.active = win.active.saturating_sub(1);
|
|
}
|
|
(win.tabs.is_empty(), win.kind.clone())
|
|
};
|
|
if empty {
|
|
match kind {
|
|
Kind::Normal if self.windows.values().filter(|x| x.kind == Kind::Normal).count() <= 1 => {
|
|
// Closing the last tab of the last window quits, like other browsers.
|
|
self.quit();
|
|
},
|
|
_ => self.close_window(w),
|
|
}
|
|
return;
|
|
}
|
|
let closes: Vec<Kind> = std::mem::take(&mut self.window_closes);
|
|
for kind in closes {
|
|
if let Some(id) = self.windows.iter().find(|(_, x)| x.kind == kind).map(|(id, _)| *id) {
|
|
if let Some(mut pip) = self.windows.remove(&id) {
|
|
pip.destroy();
|
|
}
|
|
}
|
|
}
|
|
self.ensure_loaded(w);
|
|
self.redraw(w);
|
|
}
|
|
|
|
/// Load a URL (or internal page) in the window's current tab.
|
|
pub fn navigate(&mut self, window: WindowId, url: String) {
|
|
let Some(win) = self.windows.get(&window) else { return };
|
|
if win.tabs.is_empty() {
|
|
self.new_tab(window, Some(url), true);
|
|
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].draft = None;
|
|
win.ui.omnibox_edit = None;
|
|
self.redraw(window);
|
|
return;
|
|
}
|
|
let Ok(parsed) = Url::parse(&url) else { return };
|
|
if parsed.scheme() == "javascript" {
|
|
let script = util::percent_decode(parsed.as_str().trim_start_matches("javascript:"));
|
|
if let Some(web) = win.tabs[i].webview() {
|
|
web.evaluate_javascript(script, |_| {});
|
|
}
|
|
return;
|
|
}
|
|
let has_web = win.tabs[i].web.is_some();
|
|
if has_web {
|
|
let win = self.windows.get_mut(&window).expect("found");
|
|
let tab = &mut win.tabs[i];
|
|
tab.page = None;
|
|
tab.draft = None;
|
|
tab.url = url.clone();
|
|
if let Some(web) = &tab.web {
|
|
web.webview.load(parsed);
|
|
}
|
|
win.ui.omnibox_edit = None;
|
|
win.page_focused = true;
|
|
} else {
|
|
let web = self.build_webview(win, parsed);
|
|
let win = self.windows.get_mut(&window).expect("found");
|
|
let tab = &mut win.tabs[i];
|
|
tab.web = Some(web);
|
|
tab.page = None;
|
|
tab.draft = None;
|
|
tab.url = url;
|
|
tab.load_status = Some(servo::LoadStatus::Started);
|
|
win.ui.omnibox_edit = None;
|
|
win.page_focused = true;
|
|
}
|
|
self.redraw(window);
|
|
}
|
|
|
|
pub fn open(&mut self, window: WindowId, url: String, how: Disposition, from: Option<u64>) {
|
|
match how {
|
|
Disposition::Current => self.navigate(window, url),
|
|
Disposition::NewForegroundTab | Disposition::NewBackgroundTab => {
|
|
// App windows open links in the browser.
|
|
let target = if self.windows.get(&window).is_some_and(|w| w.kind != Kind::Normal) { self.windows.iter().find(|(_, w)| w.kind == Kind::Normal).map(|(id, _)| *id) } else { Some(window) };
|
|
match target {
|
|
Some(target) => {
|
|
self.new_tab(target, Some(url), how == Disposition::NewForegroundTab);
|
|
if let (Some(from), Some(win)) = (from, self.windows.get_mut(&target)) {
|
|
let index = if how == Disposition::NewForegroundTab { win.active } else { (win.active + 1).min(win.tabs.len() - 1) };
|
|
win.tabs[index].opener = Some(from);
|
|
}
|
|
if let Some(win) = self.windows.get(&target) {
|
|
win.window.focus_window();
|
|
}
|
|
},
|
|
None => {
|
|
let mut tab = Tab::new(self.new_tab_id());
|
|
tab.pending_url = Some(url);
|
|
tab.page = None;
|
|
self.window_requests.push(WindowRequest { kind: Kind::Normal, tabs: vec![tab], active: 0, size: None });
|
|
},
|
|
}
|
|
},
|
|
Disposition::NewWindow => {
|
|
let mut tab = Tab::new(self.new_tab_id());
|
|
match Page::from_url(&url) {
|
|
Some(page) => tab.page = Some(page),
|
|
None => {
|
|
tab.page = None;
|
|
tab.pending_url = Some(url);
|
|
},
|
|
}
|
|
self.window_requests.push(WindowRequest { kind: Kind::Normal, tabs: vec![tab], active: 0, size: None });
|
|
},
|
|
Disposition::Incognito => {
|
|
if let Ok(exe) = std::env::current_exe() {
|
|
let _ = std::process::Command::new(exe).args(["--incognito", "--profile", &self.shared.paths.profile, &url]).spawn();
|
|
}
|
|
},
|
|
}
|
|
}
|
|
|
|
/// Show an internal page: switch to a tab already showing it, else open it in a new tab
|
|
/// (or in the current tab if that is a new tab page).
|
|
pub fn show_page(&mut self, window: WindowId, page: Page) {
|
|
let Some(win) = self.windows.get(&window) else { return };
|
|
let same = |p: &Page| std::mem::discriminant(p) == std::mem::discriminant(&page);
|
|
if let Some(i) = win.tabs.iter().position(|t| t.page.as_ref().is_some_and(same)) {
|
|
self.windows.get_mut(&window).expect("found").tabs[i].page = Some(page);
|
|
self.select_tab(window, i);
|
|
return;
|
|
}
|
|
if win.tab().is_some_and(|t| t.page == Some(Page::NewTab) && t.web.is_none()) {
|
|
let i = win.active;
|
|
self.windows.get_mut(&window).expect("found").tabs[i].page = Some(page);
|
|
self.redraw(window);
|
|
return;
|
|
}
|
|
let mut tab = Tab::new(self.new_tab_id());
|
|
tab.page = Some(page);
|
|
self.insert_tab(window, tab, true);
|
|
}
|
|
|
|
fn go_back(&mut self, window: WindowId) {
|
|
let Some(win) = self.windows.get_mut(&window) else { return };
|
|
let Some(tab) = win.tab_mut() else { return };
|
|
if tab.page.is_some() && tab.web.is_some() {
|
|
// From an internal page back to the web page behind it.
|
|
tab.page = None;
|
|
self.redraw(window);
|
|
return;
|
|
}
|
|
if let Some(web) = &tab.web
|
|
&& web.webview.can_go_back()
|
|
{
|
|
web.webview.go_back(1);
|
|
} else if let Some(opener) = tab.opener {
|
|
// Nothing to go back to in a tab opened from another: close it and return there.
|
|
let id = tab.id;
|
|
let _ = opener;
|
|
self.close_tab(window, id, true);
|
|
}
|
|
}
|
|
|
|
pub fn on_navigation(&mut self, id: WebViewId, request: servo::NavigationRequest) {
|
|
let url = request.url.clone();
|
|
let Some((window, index)) = self.find_webview(id) else {
|
|
request.allow();
|
|
return;
|
|
};
|
|
match url.scheme() {
|
|
"nacre" => {
|
|
request.deny();
|
|
if let Some(page) = Page::from_url(url.as_str()) {
|
|
let win = self.windows.get_mut(&window).expect("found");
|
|
win.tabs[index].page = Some(page);
|
|
self.redraw(window);
|
|
}
|
|
},
|
|
"view-source" => {
|
|
request.deny();
|
|
let inner = url.as_str().trim_start_matches("view-source:").to_owned();
|
|
self.open(window, Page::Source(inner).url(), Disposition::NewForegroundTab, None);
|
|
},
|
|
"http" | "https" => {
|
|
// User scripts: offer to install .user.js / .user.css files.
|
|
let path = url.path().to_ascii_lowercase();
|
|
if path.ends_with(".user.js") || path.ends_with(".user.css") {
|
|
request.deny();
|
|
let text = format!("Install the user script from {}?", util::host_of(&url));
|
|
self.shared.toast_with(text, "Install", Command::InstallScript(url.to_string()));
|
|
self.redraw(window);
|
|
return;
|
|
}
|
|
let page = self.windows[&window].tabs[index].url.clone();
|
|
if download::looks_like_download(&url) {
|
|
request.deny();
|
|
self.start_download(url, page, None);
|
|
} else if download::worth_probing(&url) {
|
|
let key = self.next_pending;
|
|
self.next_pending += 1;
|
|
self.pending_nav.insert(key, request);
|
|
let headers = self.request_headers(&url, &page);
|
|
let probe_url = url.clone();
|
|
self.spawn("probe", move || download::probe(&probe_url, &headers), move |app, result| {
|
|
let Some(request) = app.pending_nav.remove(&key) else { return };
|
|
match result {
|
|
Ok(probe) if probe.is_download => {
|
|
request.deny();
|
|
app.start_download(url, page, Some(probe.file_name));
|
|
},
|
|
_ => request.allow(),
|
|
}
|
|
});
|
|
} else {
|
|
request.allow();
|
|
}
|
|
},
|
|
"about" | "data" | "blob" | "file" | "javascript" => request.allow(),
|
|
_ => {
|
|
// Another app's link (mailto:, tel:, magnet:, steam:, ...).
|
|
request.deny();
|
|
let host = self.windows[&window].tabs[index].host();
|
|
let answer = self.shared.permissions.borrow().answer(&self.shared.settings.borrow(), &host, Perm::ExternalApps);
|
|
match answer {
|
|
crate::store::permissions::Answer::Allow => {
|
|
util::open_external(url.as_str());
|
|
},
|
|
crate::store::permissions::Answer::Block => {},
|
|
crate::store::permissions::Answer::Ask => {
|
|
self.windows.get_mut(&window).expect("found").tabs[index].prompts.push_back(Prompt::External { url: url.to_string() });
|
|
self.redraw(window);
|
|
},
|
|
}
|
|
},
|
|
}
|
|
}
|
|
|
|
/// Cookie, Referer and User-Agent for a request Nacre makes on a page's behalf.
|
|
pub fn request_headers(&self, url: &Url, page: &str) -> Vec<(String, String)> {
|
|
let mut headers = vec![("user-agent".to_owned(), self.shared.user_agent.borrow().clone())];
|
|
if let Some(servo) = &self.servo {
|
|
let cookies = servo.site_data_manager().cookies_for_url(url.clone(), servo::CookieSource::HTTP);
|
|
let header: Vec<String> = cookies.iter().map(|c| format!("{}={}", c.name(), c.value())).collect();
|
|
if !header.is_empty() {
|
|
headers.push(("cookie".to_owned(), header.join("; ")));
|
|
}
|
|
}
|
|
if page.starts_with("http") {
|
|
headers.push(("referer".to_owned(), page.to_owned()));
|
|
}
|
|
headers
|
|
}
|
|
|
|
// ── prompts and dialogs ───────────────────────────────────────────
|
|
|
|
fn answer_prompt(&mut self, tab_id: u64, answer: PromptAnswer) {
|
|
let Some((w, i)) = self.find_tab(tab_id) else { return };
|
|
let Some(prompt) = self.windows.get_mut(&w).expect("found").tabs[i].prompts.pop_front() else { return };
|
|
match prompt {
|
|
Prompt::Permission { host, kind, request } => match answer {
|
|
PromptAnswer::Allow { remember } => {
|
|
if remember {
|
|
self.shared.permissions.borrow_mut().set(&host, kind, Some(Decision::Allow));
|
|
}
|
|
request.allow();
|
|
},
|
|
PromptAnswer::Deny { remember } => {
|
|
if remember {
|
|
self.shared.permissions.borrow_mut().set(&host, kind, Some(Decision::Block));
|
|
}
|
|
request.deny();
|
|
},
|
|
_ => request.deny(),
|
|
},
|
|
Prompt::ProtocolHandler { request, .. } => {
|
|
if matches!(answer, PromptAnswer::Allow { .. } | PromptAnswer::Yes) { request.allow() } else { request.deny() }
|
|
},
|
|
Prompt::SaveLogin { origin, username, password, .. } => match answer {
|
|
PromptAnswer::Yes | PromptAnswer::Allow { .. } => {
|
|
let result = self.shared.vault.borrow_mut().upsert_login(&origin, &username, &password, "");
|
|
if let Err(error) = result {
|
|
self.shared.toast(error.to_string());
|
|
}
|
|
},
|
|
PromptAnswer::Never => {
|
|
let _ = self.shared.vault.borrow_mut().add_never(&origin);
|
|
},
|
|
_ => {},
|
|
},
|
|
Prompt::HttpFallback { url } => {
|
|
if matches!(answer, PromptAnswer::Yes | PromptAnswer::Allow { .. }) {
|
|
let host = util::host_of(&url);
|
|
self.shared.http_allowed.borrow_mut().push(host.clone());
|
|
if let PromptAnswer::Allow { remember: true } = answer {
|
|
self.shared.settings.borrow_mut().privacy.https_exceptions.push(host);
|
|
}
|
|
self.refresh_hub_config();
|
|
if let Some(web) = &self.windows[&w].tabs[i].web {
|
|
web.webview.load(url);
|
|
}
|
|
}
|
|
},
|
|
Prompt::External { url } => {
|
|
let host = self.windows[&w].tabs[i].host();
|
|
match answer {
|
|
PromptAnswer::Allow { remember } | PromptAnswer::Deny { remember } if remember => {
|
|
let allow = matches!(answer, PromptAnswer::Allow { .. });
|
|
self.shared.permissions.borrow_mut().set(&host, Perm::ExternalApps, Some(if allow { Decision::Allow } else { Decision::Block }));
|
|
if allow {
|
|
util::open_external(&url);
|
|
}
|
|
},
|
|
PromptAnswer::Allow { .. } | PromptAnswer::Yes => {
|
|
util::open_external(&url);
|
|
},
|
|
_ => {},
|
|
}
|
|
},
|
|
Prompt::PopupBlocked { .. } | Prompt::Info { .. } => {
|
|
if let PromptAnswer::Allow { .. } = answer {
|
|
let host = self.windows[&w].tabs[i].host();
|
|
self.shared.permissions.borrow_mut().set(&host, Perm::Popups, Some(Decision::Allow));
|
|
}
|
|
},
|
|
}
|
|
self.redraw(w);
|
|
}
|
|
|
|
pub fn close_dialog(&mut self, tab_id: u64) {
|
|
if let Some((w, i)) = self.find_tab(tab_id) {
|
|
self.windows.get_mut(&w).expect("found").tabs[i].dialog = None;
|
|
self.redraw(w);
|
|
}
|
|
}
|
|
|
|
fn finish_dialog(&mut self, tab_id: u64, result: DialogResult) {
|
|
let Some((w, i)) = self.find_tab(tab_id) else { return };
|
|
let Some(dialog) = self.windows.get_mut(&w).expect("found").tabs[i].dialog.take() else { return };
|
|
match dialog {
|
|
Dialog::Simple(dialog, _) => match (dialog, result) {
|
|
(servo::SimpleDialog::Prompt(mut prompt), DialogResult::Ok(Some(value))) => {
|
|
prompt.set_current_value(&value);
|
|
prompt.confirm();
|
|
},
|
|
(dialog, DialogResult::Ok(_)) => dialog.confirm(),
|
|
(dialog, _) => dialog.dismiss(),
|
|
},
|
|
Dialog::Auth { request, .. } => {
|
|
if let DialogResult::Auth { username, password } = result {
|
|
request.authenticate(username, password);
|
|
}
|
|
},
|
|
Dialog::Select(mut select) => {
|
|
if let DialogResult::Select(chosen) = result {
|
|
select.select(chosen);
|
|
}
|
|
select.submit();
|
|
},
|
|
Dialog::Color(mut picker, _) => {
|
|
if let DialogResult::Color(Some([r, g, b])) = result {
|
|
picker.select(Some(servo::RgbColor { red: r, green: g, blue: b }));
|
|
}
|
|
picker.submit();
|
|
},
|
|
Dialog::ContextMenu(menu) => menu.dismiss(),
|
|
Dialog::Bluetooth(request) => {
|
|
let device = if let DialogResult::Device(Some(n)) = result { request.devices().get(n).cloned() } else { None };
|
|
let _ = match device {
|
|
Some(device) => request.pick_device(&device),
|
|
None => request.cancel(),
|
|
};
|
|
},
|
|
Dialog::LeavePage(request) => {
|
|
if matches!(result, DialogResult::Leave(true)) { request.allow() } else { request.deny() }
|
|
},
|
|
Dialog::Logins { .. } | Dialog::Forms { .. } => {},
|
|
}
|
|
self.redraw(w);
|
|
}
|
|
|
|
fn menu_action(&mut self, window: WindowId, tab_id: u64, action: MenuAction) {
|
|
let Some((w, i)) = self.find_tab(tab_id) else { return };
|
|
let menu = match self.windows.get_mut(&w).expect("found").tabs[i].dialog.take() {
|
|
Some(Dialog::ContextMenu(menu)) => Some(menu),
|
|
other => {
|
|
self.windows.get_mut(&w).expect("found").tabs[i].dialog = other;
|
|
None
|
|
},
|
|
};
|
|
let page_url = self.windows[&w].tabs[i].url.clone();
|
|
match action {
|
|
MenuAction::Servo(servo_action) => {
|
|
if let Some(menu) = menu {
|
|
menu.select(servo_action);
|
|
}
|
|
return;
|
|
},
|
|
other => {
|
|
if let Some(menu) = menu {
|
|
menu.dismiss();
|
|
}
|
|
match other {
|
|
MenuAction::OpenLink(url, how) => self.open(window, url, how, Some(tab_id)),
|
|
MenuAction::CopyText(text) => {
|
|
if let Ok(mut clipboard) = arboard::Clipboard::new() {
|
|
let _ = clipboard.set_text(text);
|
|
}
|
|
},
|
|
MenuAction::SaveLink(url) => {
|
|
if let Ok(url) = Url::parse(&url) {
|
|
let name = util::file_name_from_url(&url);
|
|
self.start_download_ask(url, page_url, Some(name));
|
|
}
|
|
},
|
|
MenuAction::SearchFor(text) => {
|
|
let template = self.shared.settings.borrow().search_template();
|
|
let url = template.replace("%s", &util::encode_query(&text));
|
|
self.open(window, url, Disposition::NewForegroundTab, Some(tab_id));
|
|
},
|
|
MenuAction::SpellReplace(word, by) => self.eval(tab_id, inject::call("spell.replace", &[word.into(), by.into()])),
|
|
MenuAction::SpellAdd(word) => {
|
|
if let Some(speller) = self.shared.speller.borrow_mut().as_mut() {
|
|
speller.add_word(&word);
|
|
}
|
|
},
|
|
MenuAction::Pip => self.enter_pip(window),
|
|
MenuAction::ViewSource => self.open(window, Page::Source(page_url).url(), Disposition::NewForegroundTab, None),
|
|
MenuAction::DevTools => self.run_action(window, Action::DevTools),
|
|
MenuAction::QrCode => self.run_in(window, Command::QrCode),
|
|
MenuAction::SavePage => self.save_page(window),
|
|
MenuAction::LoopMedia => self.eval(tab_id, inject::call("media.act", &["loop".into(), 0.into()])),
|
|
MenuAction::Dismiss | MenuAction::Servo(_) => {},
|
|
}
|
|
},
|
|
}
|
|
self.redraw(w);
|
|
}
|
|
|
|
// ── page messages ─────────────────────────────────────────────────
|
|
|
|
pub fn on_page_message(&mut self, id: WebViewId, message: PageMessage) {
|
|
let Some((w, i)) = self.find_webview(id) else { return };
|
|
let tab_id = self.windows[&w].tabs[i].id;
|
|
let data = message.data;
|
|
let s = |v: &serde_json::Value, k: &str| v.get(k).and_then(|x| x.as_str()).unwrap_or("").to_owned();
|
|
let f = |v: &serde_json::Value, k: &str| v.get(k).and_then(|x| x.as_f64()).unwrap_or(0.0) as f32;
|
|
match message.kind.as_str() {
|
|
"ready" => {},
|
|
"meta" => {
|
|
let color = crate::theme::parse_css_color(&s(&data, "theme_color")).or_else(|| crate::theme::parse_css_color(&s(&data, "background")));
|
|
let icon = data.get("icons").and_then(|v| v.as_array()).and_then(|a| a.first()).map(|i| s(i, "href")).unwrap_or_default();
|
|
let changed;
|
|
{
|
|
let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i];
|
|
changed = tab.theme_color != color;
|
|
tab.theme_color = color;
|
|
tab.site_name = s(&data, "site_name");
|
|
tab.page_image = s(&data, "image");
|
|
tab.manifest = s(&data, "manifest");
|
|
if !icon.is_empty() {
|
|
tab.favicon_url = icon;
|
|
}
|
|
}
|
|
if changed && self.shared.settings.borrow().theme.source == crate::store::settings::ColourSource::Website && self.windows[&w].active == i {
|
|
if let Some(mut win) = self.windows.remove(&w) {
|
|
self.style_window(&mut win);
|
|
self.windows.insert(w, win);
|
|
}
|
|
self.redraw(w);
|
|
}
|
|
},
|
|
"media" => {
|
|
let state: Option<crate::media::MediaState> = serde_json::from_value(data).ok();
|
|
let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i];
|
|
tab.media = state.map(|s| (s, util::now_ms()));
|
|
self.redraw_all();
|
|
},
|
|
"find" => {
|
|
let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i];
|
|
tab.find.count = data.get("count").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
|
|
tab.find.index = data.get("index").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
|
|
self.redraw(w);
|
|
},
|
|
"download" => {
|
|
if let Ok(url) = Url::parse(&s(&data, "url")) {
|
|
let name = s(&data, "name");
|
|
let page = self.windows[&w].tabs[i].url.clone();
|
|
self.start_download(url, page, (!name.is_empty()).then(|| util::safe_file_name(&name)));
|
|
}
|
|
},
|
|
"context" => {
|
|
self.windows.get_mut(&w).expect("found").tabs[i].context = Some(data);
|
|
},
|
|
"login_form" | "login_focus" => {
|
|
let settings = self.shared.settings.borrow().vault.clone();
|
|
if !settings.enabled {
|
|
return;
|
|
}
|
|
let url = s(&data, "url");
|
|
let logins: Vec<(u64, String, String)> = self.shared.vault.borrow().logins_for(&url).iter().map(|l| (l.id, l.username.clone(), l.password.clone())).collect();
|
|
if self.shared.vault.borrow().locked() && message.kind == "login_focus" {
|
|
let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i];
|
|
tab.dialog = Some(Dialog::Logins { x: f(&data, "x"), y: f(&data, "y"), items: Vec::new() });
|
|
} else if message.kind == "login_form" && settings.autofill && logins.len() == 1 {
|
|
let (login_id, username, password) = logins[0].clone();
|
|
self.eval(tab_id, inject::call("fill.login", &[username.into(), password.into()]));
|
|
self.shared.vault.borrow_mut().mark_used(login_id);
|
|
} else if message.kind == "login_focus" && (!logins.is_empty() || data.get("new_password").is_some()) {
|
|
let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i];
|
|
if tab.dialog.is_none() {
|
|
tab.dialog = Some(Dialog::Logins { x: f(&data, "x"), y: f(&data, "y"), items: logins.iter().map(|(id, user, _)| (*id, user.clone())).collect() });
|
|
}
|
|
}
|
|
self.redraw(w);
|
|
},
|
|
"login_submit" => {
|
|
if !self.shared.settings.borrow().vault.enabled || self.shared.incognito {
|
|
return;
|
|
}
|
|
let url = s(&data, "url");
|
|
let (username, password) = (s(&data, "username"), s(&data, "password"));
|
|
let vault = self.shared.vault.borrow();
|
|
if password.is_empty() || vault.never_for(&url) {
|
|
return;
|
|
}
|
|
let existing = vault.find(&url, &username).map(|l| l.password.clone());
|
|
drop(vault);
|
|
if existing.as_deref() == Some(password.as_str()) {
|
|
return;
|
|
}
|
|
let origin = crate::store::vault::origin_of(&url);
|
|
let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i];
|
|
tab.prompts.retain(|p| !matches!(p, Prompt::SaveLogin { .. }));
|
|
tab.prompts.push_back(Prompt::SaveLogin { origin, username, password, update: existing.is_some() });
|
|
self.redraw(w);
|
|
},
|
|
"form_focus" => {
|
|
if !self.shared.settings.borrow().vault.autofill_forms {
|
|
return;
|
|
}
|
|
let kind = s(&data, "kind");
|
|
let has = {
|
|
let v = self.shared.vault.borrow();
|
|
if kind == "card" { !v.contents.cards.is_empty() } else { !v.contents.addresses.is_empty() }
|
|
};
|
|
if has {
|
|
let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i];
|
|
if tab.dialog.is_none() {
|
|
tab.dialog = Some(Dialog::Forms { kind, x: f(&data, "x"), y: f(&data, "y") });
|
|
}
|
|
self.redraw(w);
|
|
}
|
|
},
|
|
"cosmetic_ids" => {
|
|
let url = self.windows[&w].tabs[i].url.clone();
|
|
if self.shared.settings.borrow().adblock_paused_on(&util::host_of_str(&url)) {
|
|
return;
|
|
}
|
|
let list = |k: &str| -> Vec<String> { data.get(k).and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_owned)).collect()).unwrap_or_default() };
|
|
let (_, exceptions, generichide) = self.shared.adblock.page_selectors(&url);
|
|
if generichide {
|
|
return;
|
|
}
|
|
let selectors = self.shared.adblock.generic_selectors(&list("classes"), &list("ids"), &exceptions);
|
|
if !selectors.is_empty() {
|
|
self.eval(tab_id, inject::call("cosmetic.hide", &[serde_json::json!(selectors)]));
|
|
}
|
|
},
|
|
"cosmetic_removed" => {
|
|
let n = data.as_u64().unwrap_or(0) as u32;
|
|
self.windows.get_mut(&w).expect("found").tabs[i].hidden_elements += n;
|
|
},
|
|
"preload" => {
|
|
let hosts: Vec<String> = data.as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_owned)).take(24).collect()).unwrap_or_default();
|
|
if let Some(bridge) = self.shared.bridge.clone() {
|
|
let route = bridge.route();
|
|
// With the VPN on, names are looked up by the VPN; nothing to warm up here.
|
|
if route.upstream == crate::net::bridge::Upstream::Direct {
|
|
std::thread::spawn(move || {
|
|
for host in hosts {
|
|
let _ = bridge.resolver.resolve(&route.doh, &host, 443);
|
|
}
|
|
});
|
|
}
|
|
}
|
|
},
|
|
"spell" => {
|
|
let words: Vec<String> = data.as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_owned)).collect()).unwrap_or_default();
|
|
let bad = self.shared.speller.borrow().as_ref().map(|s| s.misspelled(&words)).unwrap_or_default();
|
|
self.eval(tab_id, inject::call("spell.mark", &[serde_json::json!(bad)]));
|
|
},
|
|
_ => {},
|
|
}
|
|
}
|
|
|
|
// ── downloads ─────────────────────────────────────────────────────
|
|
|
|
/// Start a download, asking where to save it when the settings say so.
|
|
pub fn start_download(&mut self, url: Url, page: String, name: Option<String>) {
|
|
let ask = self.shared.settings.borrow().downloads.ask;
|
|
if ask {
|
|
self.start_download_ask(url, page, name);
|
|
} else {
|
|
self.start_download_to(url, page, name, None);
|
|
}
|
|
}
|
|
|
|
pub fn start_download_ask(&mut self, url: Url, page: String, name: Option<String>) {
|
|
let name = name.unwrap_or_else(|| util::file_name_from_url(&url));
|
|
let dir = self.shared.settings.borrow().downloads.dir.clone();
|
|
self.spawn("save-as", move || rfd::FileDialog::new().set_directory(&dir).set_file_name(&name).save_file(), move |app, path: Option<PathBuf>| {
|
|
if let Some(path) = path {
|
|
app.start_download_to(url, page, None, Some(path));
|
|
}
|
|
});
|
|
}
|
|
|
|
fn start_download_to(&mut self, url: Url, page: String, name: Option<String>, path: Option<PathBuf>) {
|
|
let settings = self.shared.settings.borrow().downloads.clone();
|
|
let name = name.unwrap_or_else(|| util::file_name_from_url(&url));
|
|
// An external download manager takes it, if one is chosen and turned on.
|
|
if settings.manager != "builtin" && settings.managers.contains(&settings.manager) && path.is_none() {
|
|
let key = settings.manager.clone();
|
|
let headers = self.request_headers(&url, &page);
|
|
let cookie = headers.iter().find(|(k, _)| k == "cookie").map(|(_, v)| v.clone()).unwrap_or_default();
|
|
let item = crate::net::dlm::Handoff { url: url.to_string(), file_name: name.clone(), page_url: page.clone(), cookie, user_agent: self.shared.user_agent.borrow().clone() };
|
|
let manager_name = crate::net::dlm::by_key(&key).map(|m| m.name).unwrap_or("the download manager").to_owned();
|
|
self.spawn("dlm", move || crate::net::dlm::add(&key, &settings, &item), move |app, result| match result {
|
|
Ok(()) => {
|
|
app.shared.downloads.borrow_mut().add_handed_off(url.as_str(), &page, &name, &manager_name);
|
|
app.shared.toast(format!("Sent to {manager_name}"));
|
|
},
|
|
Err(error) => {
|
|
// Fall back to Nacre's own downloader so the file still arrives.
|
|
app.shared.toast(format!("{manager_name} didn't take it ({error}); Nacre is downloading it instead"));
|
|
app.start_download_to(url, page, Some(name), Some(PathBuf::new()));
|
|
},
|
|
});
|
|
return;
|
|
}
|
|
let path = match path {
|
|
Some(p) if !p.as_os_str().is_empty() => p,
|
|
_ => util::unused_path(&settings.dir, &util::safe_file_name(&name)),
|
|
};
|
|
let id = self.shared.downloads.borrow_mut().add(url.as_str(), &page, path.clone());
|
|
self.begin_transfer(id);
|
|
if settings.auto_open
|
|
&& let Some(w) = self.current_window()
|
|
&& let Some(win) = self.windows.get_mut(&w)
|
|
{
|
|
win.ui.flyout = Some(crate::ui::Flyout::Downloads);
|
|
}
|
|
self.redraw_all();
|
|
}
|
|
|
|
fn begin_transfer(&mut self, id: u64) {
|
|
let Some(item) = self.shared.downloads.borrow().get(id).cloned() else { return };
|
|
let Ok(url) = Url::parse(&item.url) else { return };
|
|
let headers = self.request_headers(&url, &item.page_url);
|
|
let control = Arc::new(AtomicU8::new(download::RUN));
|
|
self.download_controls.insert(id, control.clone());
|
|
if let Some(d) = self.shared.downloads.borrow_mut().get_mut(id) {
|
|
d.state = DlState::Running;
|
|
d.error.clear();
|
|
}
|
|
download::start(download::Job { id, url: item.url, path: item.path, headers, control }, self.downloads_tx.clone(), self.wake());
|
|
}
|
|
|
|
pub fn on_download_msg(&mut self, msg: download::Msg) {
|
|
let mut downloads = self.shared.downloads.borrow_mut();
|
|
match msg {
|
|
download::Msg::Progress { id, received, total, speed } => {
|
|
if let Some(d) = downloads.get_mut(id) {
|
|
d.received = received;
|
|
d.total = total;
|
|
d.speed = speed;
|
|
}
|
|
},
|
|
download::Msg::Done { id, path } => {
|
|
self.download_controls.remove(&id);
|
|
if let Some(d) = downloads.get_mut(id) {
|
|
d.state = DlState::Done;
|
|
d.path = path.clone();
|
|
d.finished = util::now();
|
|
d.received = d.received.max(d.total);
|
|
d.speed = 0;
|
|
}
|
|
drop(downloads);
|
|
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
|
self.shared.toast_with(format!("{name} downloaded"), "Open", Command::Download(DownloadOp::Open(id)));
|
|
self.redraw_all();
|
|
return;
|
|
},
|
|
download::Msg::Failed { id, error } => {
|
|
self.download_controls.remove(&id);
|
|
if let Some(d) = downloads.get_mut(id) {
|
|
d.state = DlState::Failed;
|
|
d.error = error;
|
|
d.speed = 0;
|
|
}
|
|
},
|
|
download::Msg::Paused { id, received } => {
|
|
self.download_controls.remove(&id);
|
|
if let Some(d) = downloads.get_mut(id) {
|
|
d.state = DlState::Paused;
|
|
d.received = received;
|
|
d.speed = 0;
|
|
}
|
|
},
|
|
download::Msg::Cancelled { id } => {
|
|
self.download_controls.remove(&id);
|
|
if let Some(d) = downloads.get_mut(id) {
|
|
d.state = DlState::Cancelled;
|
|
d.speed = 0;
|
|
}
|
|
},
|
|
}
|
|
drop(downloads);
|
|
self.redraw_all();
|
|
}
|
|
|
|
fn download_op(&mut self, op: DownloadOp) {
|
|
match op {
|
|
DownloadOp::Pause(id) => {
|
|
if let Some(c) = self.download_controls.get(&id) {
|
|
c.store(download::PAUSE, Ordering::Relaxed);
|
|
}
|
|
},
|
|
DownloadOp::Resume(id) | DownloadOp::Retry(id) => {
|
|
if !self.download_controls.contains_key(&id) {
|
|
self.begin_transfer(id);
|
|
}
|
|
},
|
|
DownloadOp::Cancel(id) => match self.download_controls.get(&id) {
|
|
Some(c) => c.store(download::CANCEL, Ordering::Relaxed),
|
|
None => {
|
|
let path = self.shared.downloads.borrow().get(id).map(|d| download::part_path(&d.path));
|
|
if let Some(path) = path {
|
|
let _ = std::fs::remove_file(path);
|
|
}
|
|
if let Some(d) = self.shared.downloads.borrow_mut().get_mut(id) {
|
|
d.state = DlState::Cancelled;
|
|
}
|
|
},
|
|
},
|
|
DownloadOp::Remove(id) => {
|
|
if let Some(c) = self.download_controls.remove(&id) {
|
|
c.store(download::CANCEL, Ordering::Relaxed);
|
|
}
|
|
self.shared.downloads.borrow_mut().remove(id);
|
|
},
|
|
DownloadOp::Open(id) => {
|
|
if let Some(d) = self.shared.downloads.borrow().get(id) {
|
|
util::open_external(&d.path.to_string_lossy());
|
|
}
|
|
},
|
|
DownloadOp::ShowInFolder(id) => {
|
|
if let Some(d) = self.shared.downloads.borrow().get(id)
|
|
&& let Some(dir) = d.path.parent()
|
|
{
|
|
util::open_external(&dir.to_string_lossy());
|
|
}
|
|
},
|
|
DownloadOp::ClearFinished => self.shared.downloads.borrow_mut().clear_inactive(),
|
|
DownloadOp::OpenFolder => {
|
|
let dir = self.shared.settings.borrow().downloads.dir.clone();
|
|
util::open_external(&dir.to_string_lossy());
|
|
},
|
|
}
|
|
self.redraw_all();
|
|
}
|
|
|
|
pub fn ping_download_managers(&mut self) {
|
|
let settings = self.shared.settings.borrow().downloads.clone();
|
|
for manager in crate::net::dlm::available() {
|
|
let key = manager.key;
|
|
let cfg = settings.clone();
|
|
self.spawn("dlm-ping", move || crate::net::dlm::ping(key, &cfg), move |app, result| {
|
|
app.shared.dlm_status.borrow_mut().insert(key.to_owned(), result);
|
|
app.redraw_all();
|
|
});
|
|
}
|
|
}
|
|
|
|
// ── background services ───────────────────────────────────────────
|
|
|
|
pub fn rebuild_adblock(&mut self) {
|
|
let settings = self.shared.settings.borrow().adblock.clone();
|
|
let blocker = self.shared.adblock.clone();
|
|
let dir = self.shared.paths.filter_lists();
|
|
let cache = self.shared.paths.adblock_engine();
|
|
*self.shared.adblock_status.borrow_mut() = "Preparing the filter lists…".into();
|
|
self.spawn("adblock-build", move || {
|
|
blocker.build(&settings, &dir, &cache);
|
|
blocker.rule_count()
|
|
}, |app, rules| {
|
|
*app.shared.adblock_status.borrow_mut() = format!("{} rules", fmt_count(rules));
|
|
app.redraw_all();
|
|
});
|
|
}
|
|
|
|
pub fn update_filter_lists(&mut self, max_age: u64) {
|
|
let settings = self.shared.settings.borrow().adblock.clone();
|
|
let blocker = self.shared.adblock.clone();
|
|
let dir = self.shared.paths.filter_lists();
|
|
let cache = self.shared.paths.adblock_engine();
|
|
*self.shared.adblock_status.borrow_mut() = "Updating the filter lists…".into();
|
|
self.redraw_all();
|
|
self.spawn("adblock-update", move || {
|
|
let refreshed = blocker.update_lists(&settings, &dir, max_age);
|
|
if refreshed > 0 {
|
|
blocker.build(&settings, &dir, &cache);
|
|
}
|
|
(refreshed, blocker.rule_count())
|
|
}, |app, (refreshed, rules)| {
|
|
app.shared.settings.borrow_mut().adblock.last_update = util::now();
|
|
app.applied.adblock.last_update = app.shared.settings.borrow().adblock.last_update;
|
|
app.save_settings();
|
|
let failures = app.shared.adblock.failures.read().map(|f| f.len()).unwrap_or(0);
|
|
*app.shared.adblock_status.borrow_mut() = if failures > 0 { format!("{} rules · {failures} lists couldn't be downloaded", fmt_count(rules)) } else { format!("{} rules · {refreshed} lists updated", fmt_count(rules)) };
|
|
app.redraw_all();
|
|
});
|
|
}
|
|
|
|
pub fn check_updates(&mut self, manual: bool) {
|
|
let repo = self.shared.settings.borrow().update.repo.clone();
|
|
*self.shared.update_status.borrow_mut() = "Checking…".into();
|
|
self.spawn("update-check", move || crate::updates::check(&repo), move |app, result| {
|
|
app.shared.settings.borrow_mut().update.last_check = util::now();
|
|
app.applied.update.last_check = app.shared.settings.borrow().update.last_check;
|
|
match result {
|
|
Ok(release) if crate::updates::is_newer(&release.version) => {
|
|
*app.shared.update_status.borrow_mut() = format!("Version {} is available", release.version);
|
|
app.shared.settings.borrow_mut().update.available = release.version.clone();
|
|
app.shared.toast_with(format!("Nacre {} is available", release.version), "Get it", Command::OpenUpdate);
|
|
*app.shared.update.borrow_mut() = Some(release);
|
|
},
|
|
Ok(release) => {
|
|
*app.shared.update_status.borrow_mut() = format!("Up to date (latest is {})", release.version);
|
|
if manual {
|
|
app.shared.toast("Nacre is up to date");
|
|
}
|
|
},
|
|
Err(error) => {
|
|
*app.shared.update_status.borrow_mut() = format!("Couldn't check: {error}");
|
|
if manual {
|
|
app.shared.toast(format!("Couldn't check for updates: {error}"));
|
|
}
|
|
},
|
|
}
|
|
app.save_settings();
|
|
app.redraw_all();
|
|
});
|
|
}
|
|
|
|
pub fn load_speller(&mut self) {
|
|
let langs = self.shared.settings.borrow().spell.langs.clone();
|
|
let cache = self.shared.paths.dictionaries();
|
|
let personal = self.shared.paths.config_root.join("words.txt");
|
|
*self.shared.spell_status.borrow_mut() = "Loading dictionaries…".into();
|
|
self.spawn("spell", move || Speller::load(&langs, &cache, personal), |app, speller| {
|
|
let status = if speller.languages().is_empty() {
|
|
let why = speller.missing.first().map(|(l, e)| format!("{l}: {e}")).unwrap_or_default();
|
|
format!("No dictionary loaded ({why})")
|
|
} else {
|
|
speller.languages().join(", ")
|
|
};
|
|
*app.shared.spell_status.borrow_mut() = status;
|
|
*app.shared.speller.borrow_mut() = Some(speller);
|
|
app.redraw_all();
|
|
});
|
|
}
|
|
|
|
fn fetch_suggestions(&mut self, query: String) {
|
|
let Some(template) = self.shared.settings.borrow().search_suggest_template() else { return };
|
|
if query.trim().len() < 2 || self.shared.incognito {
|
|
return;
|
|
}
|
|
let url = template.replace("%s", &util::encode_query(&query));
|
|
self.spawn("suggest", move || crate::net::fetch::get_json(&url, Duration::from_secs(4)), move |app, result| {
|
|
let Ok(json) = result else { return };
|
|
// OpenSearch: ["query", ["a", "b"]]; DuckDuckGo's list type is the same.
|
|
let list: Vec<String> = json.get(1).and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_owned)).take(6).collect()).unwrap_or_default();
|
|
*app.shared.suggestions.borrow_mut() = (query, list);
|
|
app.redraw_all();
|
|
});
|
|
}
|
|
|
|
fn fetch_weather(&mut self) {
|
|
let (city, loc, units) = {
|
|
let s = self.shared.settings.borrow();
|
|
(s.ntp.city.clone(), s.ntp.city_loc, s.ntp.units.clone())
|
|
};
|
|
if city.trim().is_empty() {
|
|
return;
|
|
}
|
|
self.spawn("weather", move || -> Result<(String, f64, u32, Option<(f64, f64)>), String> {
|
|
let (lat, lon) = match loc {
|
|
Some(l) => l,
|
|
None => {
|
|
let geo = crate::net::fetch::get_json(&format!("https://geocoding-api.open-meteo.com/v1/search?count=1&name={}", util::encode_query(&city)), Duration::from_secs(10))?;
|
|
let r = geo.get("results").and_then(|r| r.get(0)).ok_or("city not found")?;
|
|
(r.get("latitude").and_then(|v| v.as_f64()).unwrap_or(0.0), r.get("longitude").and_then(|v| v.as_f64()).unwrap_or(0.0))
|
|
},
|
|
};
|
|
let unit = if units == "f" || (units == "auto" && std::env::var("LANG").unwrap_or_default().contains("US")) { "&temperature_unit=fahrenheit" } else { "" };
|
|
let w = crate::net::fetch::get_json(&format!("https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}¤t=temperature_2m,weather_code{unit}"), Duration::from_secs(10))?;
|
|
let temp = w.pointer("/current/temperature_2m").and_then(|v| v.as_f64()).unwrap_or(0.0);
|
|
let code = w.pointer("/current/weather_code").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
|
|
Ok((city, temp, code, Some((lat, lon))))
|
|
}, |app, result| {
|
|
if let Ok((city, temp, code, loc)) = result {
|
|
*app.shared.weather.borrow_mut() = Some((city, temp, code));
|
|
if app.shared.settings.borrow().ntp.city_loc.is_none() {
|
|
app.shared.settings.borrow_mut().ntp.city_loc = loc;
|
|
}
|
|
app.redraw_all();
|
|
}
|
|
});
|
|
}
|
|
|
|
/// The tab media controls and Discord follow: the playing one, else the last that played.
|
|
pub fn media_tab(&self) -> Option<u64> {
|
|
let tabs: Vec<&Tab> = self.windows.values().flat_map(|w| w.tabs.iter()).filter(|t| t.media.is_some()).collect();
|
|
tabs.iter().find(|t| t.audible()).or_else(|| tabs.iter().max_by_key(|t| t.media.as_ref().map(|m| m.1).unwrap_or(0))).map(|t| t.id)
|
|
}
|
|
|
|
pub fn update_presence(&mut self) {
|
|
let settings = self.shared.settings.borrow().rpc.clone();
|
|
if !settings.enabled || self.shared.incognito {
|
|
if let Some(p) = self.presence.as_mut() {
|
|
p.stop();
|
|
}
|
|
return;
|
|
}
|
|
let presence_missing = self.presence.is_none();
|
|
if presence_missing {
|
|
self.presence = Some(crate::discord::Presence::start(self.wake()));
|
|
}
|
|
// A media tab on a supported site, else the current tab as "browsing".
|
|
let media = self.media_tab().and_then(|id| self.find_tab(id)).map(|(w, i)| &self.windows[&w].tabs[i]);
|
|
let mut activity: Option<(serde_json::Value, String)> = None;
|
|
if let Some(tab) = media
|
|
&& let Some((state, received)) = &tab.media
|
|
&& let Ok(url) = Url::parse(&tab.url)
|
|
{
|
|
if state.ad {
|
|
return;
|
|
}
|
|
let mut state = state.clone();
|
|
state.position = state.position_at(*received);
|
|
activity = crate::discord::media_activity(&settings, &url, &tab.title, &tab.favicon_url, &state, tab.id, &mut self.presence_started);
|
|
}
|
|
if activity.is_none()
|
|
&& let Some(win) = self.current_window().and_then(|w| self.windows.get(&w))
|
|
&& let Some(tab) = win.tab()
|
|
&& tab.page.is_none()
|
|
&& let Ok(url) = Url::parse(&tab.url)
|
|
&& let Some(act) = crate::discord::browse_activity(&settings, &url, &tab.title, &tab.site_name, if tab.page_image.is_empty() { &tab.favicon_url } else { &tab.page_image }, tab.arrived_ms as i64)
|
|
{
|
|
activity = Some((act, settings.client_id.clone()));
|
|
}
|
|
let target = settings.target;
|
|
let client_id = activity.as_ref().map(|(_, id)| id.clone()).unwrap_or_else(|| settings.client_id.clone());
|
|
if let Some(p) = self.presence.as_mut() {
|
|
p.set(&client_id, target, activity.map(|(a, _)| a));
|
|
*self.shared.presence_status.borrow_mut() = p.status();
|
|
}
|
|
}
|
|
|
|
fn import_from(&mut self, index: usize, bookmarks: bool, history: bool, settings: bool) {
|
|
let Some(source) = self.shared.import_sources.borrow().get(index).cloned() else { return };
|
|
*self.shared.import_status.borrow_mut() = format!("Importing from {}…", source.name());
|
|
let name = source.name();
|
|
self.spawn("import", move || {
|
|
let b = if bookmarks { Some(crate::importer::read_bookmarks(&source)) } else { None };
|
|
let h = if history { Some(crate::importer::read_history(&source, 20_000)) } else { None };
|
|
let s = if settings { Some(crate::importer::read_settings(&source)) } else { None };
|
|
(b, h, s)
|
|
}, move |app, (b, h, s)| {
|
|
let mut parts = Vec::new();
|
|
if let Some(tree) = b {
|
|
let n = app.shared.bookmarks.borrow_mut().import_tree(tree, &name);
|
|
parts.push(format!("{n} bookmarks"));
|
|
}
|
|
if let Some(visits) = h {
|
|
let n = app.shared.history.borrow_mut().import(visits);
|
|
parts.push(format!("{n} history entries"));
|
|
}
|
|
if let Some((home, engine)) = s {
|
|
let mut st = app.shared.settings.borrow_mut();
|
|
if let Some(home) = home {
|
|
st.startup.home_url = home;
|
|
parts.push("home page".into());
|
|
}
|
|
if let Some(engine) = engine {
|
|
st.startup.search_engine = engine;
|
|
parts.push("search engine".into());
|
|
}
|
|
st.startup.import_done.push(name.clone());
|
|
}
|
|
let text = if parts.is_empty() { format!("Nothing to import from {name}") } else { format!("Imported from {name}: {}", parts.join(", ")) };
|
|
*app.shared.import_status.borrow_mut() = text.clone();
|
|
app.shared.toast(text);
|
|
app.redraw_all();
|
|
});
|
|
}
|
|
|
|
fn clear_data(&mut self, since: u64, what: &[String]) {
|
|
let has = |k: &str| what.iter().any(|w| w == k);
|
|
if has("history") {
|
|
self.shared.history.borrow_mut().clear_since(since);
|
|
self.shared.session.borrow_mut().clear();
|
|
}
|
|
if has("downloads") {
|
|
self.shared.downloads.borrow_mut().clear_inactive();
|
|
}
|
|
if let Some(servo) = &self.servo {
|
|
if has("cookies") {
|
|
servo.site_data_manager().clear_cookies(None);
|
|
let sites: Vec<String> = servo.site_data_manager().site_data(servo::StorageType::all()).into_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 has("cache") {
|
|
servo.network_manager().clear_cache();
|
|
let _ = std::fs::remove_dir_all(self.shared.paths.data.join("http-cache"));
|
|
}
|
|
}
|
|
if has("permissions") {
|
|
self.shared.permissions.borrow_mut().clear_all();
|
|
}
|
|
if has("passwords") {
|
|
let ids: Vec<u64> = self.shared.vault.borrow().contents.logins.iter().map(|l| l.id).collect();
|
|
for id in ids {
|
|
let _ = self.shared.vault.borrow_mut().delete_login(id);
|
|
}
|
|
}
|
|
if has("autofill") {
|
|
let (a, c): (Vec<u64>, Vec<u64>) = {
|
|
let v = self.shared.vault.borrow();
|
|
(v.contents.addresses.iter().map(|x| x.id).collect(), v.contents.cards.iter().map(|x| x.id).collect())
|
|
};
|
|
for id in a {
|
|
let _ = self.shared.vault.borrow_mut().delete_address(id);
|
|
}
|
|
for id in c {
|
|
let _ = self.shared.vault.borrow_mut().delete_card(id);
|
|
}
|
|
}
|
|
self.flush_stores();
|
|
self.shared.toast("Browsing data deleted");
|
|
}
|
|
|
|
fn install_app(&mut self, window: WindowId) {
|
|
let Some(tab) = self.windows.get(&window).and_then(|w| w.tab()) else { return };
|
|
let Ok(url) = Url::parse(&tab.url) else { return };
|
|
if !matches!(url.scheme(), "http" | "https") {
|
|
return;
|
|
}
|
|
let name = if tab.site_name.is_empty() { tab.display_title() } else { tab.site_name.clone() };
|
|
let icon = tab.favicon_png.clone();
|
|
let profile = self.shared.paths.profile.clone();
|
|
let launcher = !self.shared.incognito;
|
|
let app = self.shared.apps.borrow_mut().install(&name, &url, icon.as_deref(), launcher, &profile);
|
|
self.shared.toast_with(format!("{} installed as an app", app.name), "Open", Command::OpenApp(app.id.clone()));
|
|
}
|
|
|
|
pub fn open_app_window(&mut self, event_loop: &ActiveEventLoop, id: &str) {
|
|
let app = self.shared.apps.borrow().get(id).cloned();
|
|
let Some(app) = app else {
|
|
self.shared.toast(format!("There is no app called {id}"));
|
|
return;
|
|
};
|
|
let mut tab = Tab::new(self.new_tab_id());
|
|
tab.page = None;
|
|
tab.pending_url = Some(app.start_url.clone());
|
|
self.open_window(event_loop, Kind::App(app.id.clone()), vec![tab], 0, Some((app.width, app.height)));
|
|
}
|
|
|
|
pub fn handle_launch(&mut self, event_loop: &ActiveEventLoop, launch: Launch) {
|
|
if let Some(app) = &launch.app {
|
|
self.open_app_window(event_loop, app);
|
|
return;
|
|
}
|
|
if launch.new_window || self.current_window().is_none() {
|
|
let mut tabs: Vec<Tab> = Vec::new();
|
|
for url in &launch.urls {
|
|
let mut tab = Tab::new(self.new_tab_id());
|
|
match Page::from_url(url) {
|
|
Some(page) => tab.page = Some(page),
|
|
None => {
|
|
tab.page = None;
|
|
tab.pending_url = Some(url.clone());
|
|
},
|
|
}
|
|
tabs.push(tab);
|
|
}
|
|
if tabs.is_empty() {
|
|
tabs.push(Tab::new(self.new_tab_id()));
|
|
}
|
|
self.open_window(event_loop, Kind::Normal, tabs, 0, None);
|
|
return;
|
|
}
|
|
let window = self.current_window();
|
|
for url in launch.urls {
|
|
self.run(Command::Open { url, how: Disposition::NewForegroundTab, from: None });
|
|
}
|
|
if let Some(w) = window.and_then(|w| self.windows.get(&w)) {
|
|
w.window.focus_window();
|
|
}
|
|
}
|
|
|
|
pub fn open_pending_windows(&mut self, event_loop: &ActiveEventLoop) {
|
|
let requests = std::mem::take(&mut self.window_requests);
|
|
for request in requests {
|
|
self.open_window(event_loop, request.kind, request.tabs, request.active, request.size);
|
|
}
|
|
let commands = std::mem::take(&mut self.pending_commands);
|
|
for command in commands {
|
|
self.run(command);
|
|
}
|
|
}
|
|
|
|
// ── picture in picture ────────────────────────────────────────────
|
|
|
|
fn enter_pip(&mut self, window: WindowId) {
|
|
let Some(tab_id) = self.active_tab_id(window) else { return };
|
|
let Some((w, i)) = self.find_tab(tab_id) else { return };
|
|
if self.windows[&w].tabs[i].pip_size.is_some() {
|
|
return;
|
|
}
|
|
let Some(web) = self.windows[&w].tabs[i].web.as_ref().map(|web| web.webview.clone()) else { return };
|
|
let jobs = self.jobs_tx.clone();
|
|
let proxy = self.proxy.clone();
|
|
web.evaluate_javascript(inject::call("pip.enter", &[]), move |result| {
|
|
let size = match result {
|
|
Ok(servo::JSValue::Object(map)) => {
|
|
let num = |k: &str| match map.get(k) {
|
|
Some(servo::JSValue::Number(n)) => *n,
|
|
_ => 0.0,
|
|
};
|
|
Some((num("w").max(16.0), num("h").max(9.0)))
|
|
},
|
|
_ => None,
|
|
};
|
|
let _ = jobs.send(Box::new(move |app: &mut App| {
|
|
let Some((vw, vh)) = size else {
|
|
app.shared.toast("There's no video on this page to show in picture in picture");
|
|
return;
|
|
};
|
|
let width = 480u32;
|
|
let height = ((width as f64) * vh / vw).round().clamp(120.0, 900.0) as u32;
|
|
if let Some((w, i)) = app.find_tab(tab_id) {
|
|
let scale = app.windows[&w].window.scale_factor();
|
|
app.windows.get_mut(&w).expect("found").tabs[i].pip_size = Some(dpi::PhysicalSize::new((width as f64 * scale) as u32, (height as f64 * scale) as u32));
|
|
app.windows.get_mut(&w).expect("found").sync_webviews();
|
|
app.window_requests.push(WindowRequest { kind: Kind::Pip { window: w, tab: tab_id }, tabs: Vec::new(), active: 0, size: Some((width, height)) });
|
|
app.redraw(w);
|
|
}
|
|
}));
|
|
let _ = proxy.send_event(crate::app::AppEvent::Wake);
|
|
});
|
|
}
|
|
|
|
pub fn exit_pip(&mut self, source: WindowId, tab_id: u64) {
|
|
if let Some(win) = self.windows.get_mut(&source)
|
|
&& let Some(i) = win.tab_index(tab_id)
|
|
{
|
|
win.tabs[i].pip_size = None;
|
|
if let Some(web) = win.tabs[i].web.as_mut() {
|
|
web.dirty = true;
|
|
}
|
|
win.sync_webviews();
|
|
}
|
|
self.eval(tab_id, inject::call("pip.exit", &[]));
|
|
self.redraw(source);
|
|
}
|
|
|
|
// ── saving pages ──────────────────────────────────────────────────
|
|
|
|
fn save_page(&mut self, window: WindowId) {
|
|
let Some(tab) = self.windows.get(&window).and_then(|w| w.tab()) else { return };
|
|
let Some(web) = tab.webview().cloned() else { return };
|
|
let name = format!("{}.html", util::safe_file_name(&tab.display_title()));
|
|
let dir = self.shared.settings.borrow().downloads.dir.clone();
|
|
let jobs = self.jobs_tx.clone();
|
|
let proxy = self.proxy.clone();
|
|
web.evaluate_javascript("document.documentElement.outerHTML", move |result| {
|
|
let html = match result {
|
|
Ok(servo::JSValue::String(s)) => s,
|
|
_ => return,
|
|
};
|
|
let _ = jobs.send(Box::new(move |app: &mut App| {
|
|
app.spawn("save-page", move || {
|
|
let path = rfd::FileDialog::new().set_directory(&dir).set_file_name(&name).save_file()?;
|
|
std::fs::write(&path, format!("<!DOCTYPE html>\n{html}")).ok().map(|_| path)
|
|
}, |app, path: Option<PathBuf>| {
|
|
if let Some(path) = path {
|
|
app.shared.toast(format!("Page saved to {}", path.display()));
|
|
}
|
|
});
|
|
}));
|
|
let _ = proxy.send_event(crate::app::AppEvent::Wake);
|
|
});
|
|
}
|
|
|
|
/// "Print": save what's on screen as a PDF or PNG (Servo 0.7 can't print).
|
|
fn print_page(&mut self, window: WindowId) {
|
|
let Some(tab) = self.windows.get(&window).and_then(|w| w.tab()) else { return };
|
|
let Some(web) = tab.webview().cloned() else { return };
|
|
let name = util::safe_file_name(&tab.display_title());
|
|
let dir = self.shared.settings.borrow().downloads.dir.clone();
|
|
let jobs = self.jobs_tx.clone();
|
|
let proxy = self.proxy.clone();
|
|
web.take_screenshot(None, move |result| {
|
|
let Ok(image) = result else { return };
|
|
let (w, h, raw) = (image.width(), image.height(), image.into_raw());
|
|
let _ = jobs.send(Box::new(move |app: &mut App| {
|
|
app.spawn("print", move || {
|
|
let path = rfd::FileDialog::new().set_directory(&dir).set_file_name(format!("{name}.pdf")).add_filter("PDF", &["pdf"]).add_filter("PNG image", &["png"]).save_file()?;
|
|
let image = image::RgbaImage::from_raw(w, h, raw)?;
|
|
let is_png = path.extension().is_some_and(|e| e.eq_ignore_ascii_case("png"));
|
|
let ok = if is_png { image.save(&path).is_ok() } else { crate::pdf::write_image_pdf(&path, &image).is_ok() };
|
|
ok.then_some(path)
|
|
}, |app, path: Option<PathBuf>| {
|
|
if let Some(path) = path {
|
|
app.shared.toast(format!("Saved to {}", path.display()));
|
|
}
|
|
});
|
|
}));
|
|
let _ = proxy.send_event(crate::app::AppEvent::Wake);
|
|
});
|
|
}
|
|
|
|
// ── settings ──────────────────────────────────────────────────────
|
|
|
|
/// The UI edits settings in place; this notices and applies what changed.
|
|
pub fn apply_settings_if_changed(&mut self) {
|
|
let current = self.shared.settings.borrow().clone();
|
|
if current == self.applied {
|
|
return;
|
|
}
|
|
let old = std::mem::replace(&mut self.applied, current.clone());
|
|
let new = current;
|
|
self.save_settings();
|
|
if old.keys != new.keys {
|
|
*self.shared.keymap.borrow_mut() = crate::keys::Keymap::new(&new.keys);
|
|
}
|
|
if old.theme != new.theme || old.ui.roundness != new.ui.roundness || old.ui.motion != new.ui.motion || old.ui.scale != new.ui.scale || old.web.scheme != new.web.scheme {
|
|
self.restyle_all();
|
|
}
|
|
if old.vpn != new.vpn || old.privacy.doh != new.privacy.doh || old.privacy.doh_custom != new.privacy.doh_custom {
|
|
let want_tor = new.vpn.enabled && new.vpn.provider == crate::store::settings::VpnProvider::Tor;
|
|
if want_tor {
|
|
self.shared.tor.start(&self.shared.paths.tor_data(), self.wake());
|
|
} else {
|
|
self.shared.tor.stop();
|
|
}
|
|
}
|
|
let scripts_changed = old.privacy.mode != new.privacy.mode
|
|
|| old.privacy.mode_incognito != new.privacy.mode_incognito
|
|
|| old.privacy.dnt != new.privacy.dnt
|
|
|| old.privacy.save_data != new.privacy.save_data
|
|
|| old.privacy.google_signin != new.privacy.google_signin
|
|
|| old.web.force_dark != new.web.force_dark
|
|
|| old.web.smooth_scroll != new.web.smooth_scroll
|
|
|| old.web.preload != new.web.preload
|
|
|| old.adblock.enabled != new.adblock.enabled
|
|
|| old.adblock.cosmetic != new.adblock.cosmetic
|
|
|| old.adblock.animate != new.adblock.animate
|
|
|| old.adblock.youtube != new.adblock.youtube
|
|
|| old.vault.enabled != new.vault.enabled
|
|
|| old.spell.enabled != new.spell.enabled
|
|
|| old.perf != new.perf;
|
|
if scripts_changed {
|
|
self.install_page_scripts();
|
|
}
|
|
if old.adblock.lists != new.adblock.lists || old.adblock.custom != new.adblock.custom || old.adblock.own_rules != new.adblock.own_rules {
|
|
let missing = new.adblock.lists.iter().any(|k| crate::adblock::AdBlocker::list_age(&self.shared.paths.filter_lists(), k).is_none()) || !new.adblock.custom.is_empty();
|
|
if missing { self.update_filter_lists(new.adblock.update_days.max(1) as u64 * 86_400) } else { self.rebuild_adblock() }
|
|
}
|
|
if old.web.user_agent != new.web.user_agent
|
|
&& let Some(servo) = &self.servo
|
|
{
|
|
let ua = if new.web.user_agent.trim().is_empty() { servo::UserAgentPlatform::default().to_user_agent_string() } else { new.web.user_agent.trim().to_owned() };
|
|
servo.set_preference("user_agent", servo::PrefValue::Str(ua.clone()));
|
|
*self.shared.user_agent.borrow_mut() = ua.clone();
|
|
crate::net::fetch::set_user_agent(&ua);
|
|
}
|
|
if old.spell.langs != new.spell.langs || (!old.spell.enabled && new.spell.enabled) {
|
|
self.load_speller();
|
|
}
|
|
if old.rpc.enabled && !new.rpc.enabled
|
|
&& let Some(p) = self.presence.as_mut()
|
|
{
|
|
p.stop();
|
|
}
|
|
if old.rpc != new.rpc {
|
|
self.update_presence();
|
|
}
|
|
if old.downloads.managers != new.downloads.managers || old.downloads.abdm_port != new.downloads.abdm_port || old.downloads.aria2_port != new.downloads.aria2_port || old.downloads.jd_port != new.downloads.jd_port || old.downloads.fdm_path != new.downloads.fdm_path || old.downloads.idm_path != new.downloads.idm_path {
|
|
self.ping_download_managers();
|
|
}
|
|
if old.web.zoom != new.web.zoom {
|
|
for win in self.windows.values_mut() {
|
|
for tab in &mut win.tabs {
|
|
tab.zoom = new.zoom_for(&tab.host());
|
|
if let Some(web) = &tab.web {
|
|
web.webview.set_page_zoom(tab.zoom);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if old.media.visualizer != new.media.visualizer && new.media.visualizer == crate::store::settings::Visualizer::Off {
|
|
self.shared.cava.borrow_mut().stop();
|
|
}
|
|
if old.ntp.city != new.ntp.city {
|
|
self.shared.settings.borrow_mut().ntp.city_loc = None;
|
|
self.applied.ntp.city_loc = None;
|
|
self.fetch_weather();
|
|
}
|
|
self.refresh_hub_config();
|
|
self.redraw_all();
|
|
}
|
|
}
|
|
|
|
fn fmt_count(n: usize) -> String {
|
|
let s = n.to_string();
|
|
let mut out = String::new();
|
|
for (i, c) in s.chars().enumerate() {
|
|
if i > 0 && (s.len() - i) % 3 == 0 {
|
|
out.push(',');
|
|
}
|
|
out.push(c);
|
|
}
|
|
out
|
|
}
|