WebKit asks for a menu on cancelled right clicks once it has shown one; the bridge script's answer decides now. Script navigations that may be a frame's are no longer rewritten into loads in the tab (an ad frame took the tab over on the user's site). Co-Authored-By: Claude Opus 5.5 <[email protected]>
2639 lines
122 KiB
Rust
2639 lines
122 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 gtk::prelude::*;
|
|
use url::Url;
|
|
|
|
use crate::engine::{PageAction, ViewId};
|
|
|
|
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, WindowId};
|
|
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]>),
|
|
Leave(bool),
|
|
Close,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub enum MenuAction {
|
|
Page(PageAction),
|
|
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),
|
|
/// Ask the engine what a host keeps, for the site info flyout.
|
|
SiteData(String),
|
|
SwitchProfile(String),
|
|
NewWindow,
|
|
NewIncognito,
|
|
FreeMemory,
|
|
QrCode,
|
|
SavePage,
|
|
PrintPage,
|
|
ViewSource,
|
|
/// Open WebKit's Web Inspector for this tab.
|
|
Inspect(u64),
|
|
SpellReplace { word: String, by: String },
|
|
Suggest(String),
|
|
Weather,
|
|
/// Places matching a name, for the Weather place field.
|
|
SuggestPlaces(String),
|
|
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) => {
|
|
// A web page may ask first ("Leave this page?"): WebKit runs its beforeunload and then closes it
|
|
// (`Event::Closed`), or the tick closes it if the page hangs.
|
|
if let Some((w, i)) = self.find_tab(id)
|
|
&& let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i]
|
|
&& tab.closing.is_none()
|
|
&& tab.crashed.is_none()
|
|
&& tab.page.is_none()
|
|
&& let Some(view) = tab.web.as_ref().map(|web| web.webview.clone())
|
|
{
|
|
tab.closing = Some(std::time::Instant::now());
|
|
view.close();
|
|
return;
|
|
}
|
|
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 };
|
|
// The page loads again in the new window (moving a live view between windows is a later step).
|
|
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 {
|
|
win.detach(&web.webview);
|
|
if let Some(engine) = &self.engine {
|
|
engine.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
|
|
&& let Some((w, i)) = self.find_tab(id)
|
|
&& let Some(web) = self.windows[&w].tabs[i].webview()
|
|
{
|
|
web.set_muted(muted);
|
|
}
|
|
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();
|
|
}
|
|
},
|
|
Command::HistoryJump(target) => {
|
|
if let Some(win) = self.windows.get(&window)
|
|
&& let Some(tab) = win.tab()
|
|
&& let Some(web) = tab.webview()
|
|
{
|
|
web.go_to(target as i32 - tab.history_index as i32);
|
|
}
|
|
},
|
|
Command::Reload { hard } => {
|
|
if let Some(win) = self.windows.get_mut(&window)
|
|
&& let Some(tab) = win.tab_mut()
|
|
{
|
|
tab.crashed = None;
|
|
// WebKit is running the page's beforeunload for a close: loading into that view crashed (S054). The
|
|
// tick ends a close nobody answers, so this only shows while "Leave this page?" is up.
|
|
if let Some(since) = tab.closing {
|
|
eprintln!("tab {}: Reload ignored, the tab is closing ({:.1} s, dialog {})", tab.id, since.elapsed().as_secs_f32(), tab.dialog.is_some());
|
|
return;
|
|
}
|
|
if let Some(web) = &tab.web {
|
|
if hard { web.webview.reload_bypass_cache() } else { web.webview.reload() }
|
|
}
|
|
}
|
|
},
|
|
Command::Stop => {
|
|
// Stop a load in progress, else leave full screen and close the find bar and popups.
|
|
if let Some(win) = self.windows.get_mut(&window) {
|
|
if let Some(web) = win.active_webview()
|
|
&& web.is_loading()
|
|
{
|
|
web.stop();
|
|
} else if win.fullscreen {
|
|
win.fullscreen = false;
|
|
if let Some(tab) = win.tab_mut() {
|
|
tab.fullscreen = false;
|
|
}
|
|
win.window.unfullscreen();
|
|
}
|
|
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(win) = self.windows.get_mut(&window) else { return };
|
|
let Some(tab) = win.tab_mut() else { return };
|
|
let find = &mut tab.find;
|
|
// The same words again step through the matches; new words (or match case) search afresh.
|
|
let fresh = find.searched.as_ref() != Some(&(text.clone(), case)) || find.count == 0;
|
|
find.open = true;
|
|
find.text = text.clone();
|
|
find.case_sensitive = case;
|
|
find.searched = (!text.is_empty()).then(|| (text.clone(), case));
|
|
if fresh {
|
|
// `on_find` puts a fresh search on the first match, or the last one searching backwards.
|
|
find.count = 0;
|
|
find.index = if forward { 0 } else { u32::MAX };
|
|
} else {
|
|
find.index = step_match(find.index, find.count, forward);
|
|
}
|
|
let Some(web) = &tab.web else { return };
|
|
if text.is_empty() {
|
|
web.webview.find_finish();
|
|
} else {
|
|
web.webview.find(&text, case, forward, fresh);
|
|
}
|
|
self.redraw(window);
|
|
},
|
|
Command::FindClose => {
|
|
if let Some(tab) = self.windows.get_mut(&window).and_then(|w| w.tab_mut()) {
|
|
if let Some(web) = &tab.web {
|
|
web.webview.find_finish();
|
|
}
|
|
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 } => self.eval(tab, inject::call("media.act", &[action.into(), value.into()])),
|
|
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) {
|
|
let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i];
|
|
tab.muted = muted;
|
|
if let Some(web) = tab.webview() {
|
|
web.set_muted(muted);
|
|
}
|
|
}
|
|
}
|
|
},
|
|
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_pip(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(engine) = &self.engine {
|
|
engine.clear_data(true, false, 0, Some(vec![host.clone()]));
|
|
}
|
|
self.shared.permissions.borrow_mut().clear_host(&host);
|
|
self.shared.site_data.borrow_mut().0.clear();
|
|
self.shared.toast(format!("Data for {host} deleted"));
|
|
},
|
|
Command::SiteData(host) => {
|
|
let url = self.active_url(window);
|
|
if let Some(engine) = &self.engine {
|
|
engine.site_data(host, &url);
|
|
}
|
|
},
|
|
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;
|
|
let mut unloaded = Vec::new();
|
|
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());
|
|
unloaded.extend(tab.take_web());
|
|
freed += 1;
|
|
}
|
|
}
|
|
for view in unloaded {
|
|
win.detach(&view);
|
|
if let Some(engine) = &self.engine {
|
|
engine.forget(view.id());
|
|
}
|
|
}
|
|
}
|
|
if let Some(engine) = &self.engine {
|
|
engine.clear_data(false, true, 0, None);
|
|
}
|
|
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::Inspect(tab) => {
|
|
if let Some((w, i)) = self.find_tab(tab)
|
|
&& let Some(web) = &self.windows[&w].tabs[i].web
|
|
{
|
|
web.webview.show_inspector();
|
|
}
|
|
},
|
|
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::SuggestPlaces(name) => self.suggest_places(name),
|
|
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 || {
|
|
// Local files are read from disk: the HTTP client only speaks http(s).
|
|
if let Some(path) = Url::parse(&fetch_url).ok().filter(|u| u.scheme() == "file").and_then(|u| u.to_file_path().ok()) {
|
|
return std::fs::read(&path).map(|bytes| String::from_utf8_lossy(&bytes).into_owned()).map_err(|e| e.to_string());
|
|
}
|
|
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.minimize();
|
|
}
|
|
},
|
|
Command::WindowMaximize => {
|
|
if let Some(w) = self.windows.get(&window) {
|
|
if w.window.is_maximized() { w.window.unmaximize() } else { w.window.maximize() }
|
|
}
|
|
},
|
|
Command::WindowClose => self.close_window(window),
|
|
Command::WindowDrag => {
|
|
if let Some(w) = self.windows.get(&window) {
|
|
w.area.begin_move();
|
|
}
|
|
},
|
|
Command::FocusPage => {
|
|
if let Some(win) = self.windows.get_mut(&window) {
|
|
win.focus_page();
|
|
}
|
|
},
|
|
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_now();
|
|
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.focus_ui();
|
|
}
|
|
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.focus_ui();
|
|
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.is_fullscreen();
|
|
if on { win.window.fullscreen() } else { win.window.unfullscreen() }
|
|
win.fullscreen = on;
|
|
if !on && let Some(tab) = win.tab_mut() {
|
|
tab.fullscreen = false;
|
|
}
|
|
}
|
|
self.redraw(window);
|
|
return;
|
|
},
|
|
// On a web page the inspector opens at once; elsewhere the page lists the tabs to inspect.
|
|
Action::DevTools => match self.windows.get(&window).and_then(|w| w.tab()).filter(|t| t.page.is_none() && t.web.is_some()) {
|
|
Some(tab) => Command::Inspect(tab.id),
|
|
None => 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;
|
|
} else if win.tab().is_some_and(|t| t.page.is_none()) {
|
|
win.focus_page();
|
|
}
|
|
}
|
|
}
|
|
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 Ok(parsed) = Url::parse(&url) {
|
|
tab.web = Some(self.build_webview(tab.id, parsed, None));
|
|
tab.load_status = Some(crate::engine::LoadState::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();
|
|
}
|
|
self.ensure_loaded(window);
|
|
// A web page tab takes the keyboard back (the address field doesn't keep another tab's focus).
|
|
if let Some(win) = self.windows.get_mut(&window)
|
|
&& win.tab().is_some_and(|t| t.page.is_none() && t.draft.is_none())
|
|
{
|
|
win.focus_page();
|
|
}
|
|
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 {
|
|
win.detach(&web.webview);
|
|
if let Some(engine) = &self.engine {
|
|
engine.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;
|
|
// A tab on its way out (WebKit is running its beforeunload) takes no new page: loading into a view WebKit
|
|
// is closing crashed the UI process (S054). The page opens in a new tab instead.
|
|
if win.tabs[i].closing.is_some() {
|
|
self.new_tab(window, Some(url), true);
|
|
return;
|
|
}
|
|
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;
|
|
// The web page doesn't run on hidden behind Nacre's page; Back loads it again with its history.
|
|
if let Some(view) = win.tabs[i].take_web() {
|
|
win.detach(&view);
|
|
if let Some(engine) = &self.engine {
|
|
engine.forget(view.id());
|
|
}
|
|
}
|
|
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;
|
|
}
|
|
// Plain download links go to the download manager at once; anything else WebKit can't show comes back as
|
|
// `Event::Download`.
|
|
if matches!(parsed.scheme(), "http" | "https") && download::looks_like_download(&parsed) {
|
|
let page = win.tabs[i].url.clone();
|
|
self.start_download(parsed, page, None);
|
|
return;
|
|
}
|
|
self.load_in_active_tab(window, url, parsed);
|
|
}
|
|
|
|
fn load_in_active_tab(&mut self, window: WindowId, url: String, parsed: Url) {
|
|
let Some(win) = self.windows.get(&window) else { return };
|
|
let Some(i) = (!win.tabs.is_empty()).then_some(win.active) else { 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.focus_page();
|
|
} else {
|
|
let tab_id = win.tabs[i].id;
|
|
let history = self.windows.get_mut(&window).expect("found").tabs[i].history_state.take();
|
|
let web = self.build_webview(tab_id, parsed, history);
|
|
let win = self.windows.get_mut(&window).expect("found");
|
|
let tab = &mut win.tabs[i];
|
|
tab.web = Some(web);
|
|
tab.page = None;
|
|
tab.draft = None;
|
|
tab.url = url;
|
|
tab.load_status = Some(crate::engine::LoadState::Started);
|
|
win.ui.omnibox_edit = None;
|
|
win.focus_page();
|
|
}
|
|
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.present();
|
|
}
|
|
},
|
|
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.has_web_behind() {
|
|
// From an internal page back to the web page it was opened from.
|
|
tab.page = None;
|
|
if tab.web.is_none() {
|
|
tab.pending_url = Some(tab.url.clone());
|
|
self.ensure_loaded(window);
|
|
}
|
|
self.redraw(window);
|
|
return;
|
|
}
|
|
if let Some(web) = &tab.web
|
|
&& web.webview.can_go_back()
|
|
{
|
|
web.webview.go_back();
|
|
} 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: ViewId, request: crate::engine::NavigationRequest) {
|
|
let url = request.url.clone();
|
|
let Some((window, index)) = self.find_webview(id) else {
|
|
request.allow();
|
|
return;
|
|
};
|
|
// The certificate warning: its own load goes through, its "Open anyway" counts only from this tab while it
|
|
// shows; any other navigation ends it.
|
|
let tab = &mut self.windows.get_mut(&window).expect("found").tabs[index];
|
|
if tab.cert_error.as_ref().is_some_and(|e| e.url == url) {
|
|
request.allow();
|
|
return;
|
|
}
|
|
let cert_error = tab.cert_error.take();
|
|
if url.as_str() == "nacre://allowcert" {
|
|
request.deny();
|
|
if let (Some(error), Some(engine)) = (cert_error, &self.engine) {
|
|
engine.allow_certificate(&error);
|
|
if let Some(view) = tab.webview() {
|
|
view.load(&error.url);
|
|
}
|
|
}
|
|
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);
|
|
return;
|
|
}
|
|
let tab = &mut self.windows.get_mut(&window).expect("found").tabs[index];
|
|
// HTTPS-only: the secure version sent the page back to plain http; ask rather than loop.
|
|
if request.redirect && url.scheme() == "http" && self.hub.config.borrow().https_only && tab.upgraded_from.as_ref().is_some_and(|from| from.host_str() == url.host_str()) {
|
|
request.deny();
|
|
tab.upgraded_from = None;
|
|
tab.prompts.push_back(Prompt::HttpFallback { url });
|
|
self.redraw(window);
|
|
return;
|
|
}
|
|
let outcome = crate::net::policy::decide(&self.hub.config.borrow(), &url);
|
|
let Some(view) = tab.webview().cloned() else { return request.allow() };
|
|
// Maybe a frame's: let it load where it was going; if it turns out to be the tab's own load, it is
|
|
// loaded again from the browser then (`redo`). An ad frame never takes the tab over this way.
|
|
if request.maybe_frame {
|
|
let quirk = self.hub.config.borrow().wants_ua_quirk(&url);
|
|
let ua_change = self.engine.as_ref().is_some_and(|e| e.own_user_agent(&view) != quirk);
|
|
if !matches!(outcome, crate::net::policy::Outcome::Allow) || ua_change && request.reloadable {
|
|
tab.redo = Some(url);
|
|
}
|
|
return request.allow();
|
|
}
|
|
match outcome {
|
|
crate::net::policy::Outcome::Upgrade(secure) => {
|
|
request.deny();
|
|
tab.upgraded_from = Some(url);
|
|
view.load(&secure);
|
|
},
|
|
crate::net::policy::Outcome::Strip(clean) => {
|
|
request.deny();
|
|
view.load(&clean);
|
|
},
|
|
crate::net::policy::Outcome::Allow => {
|
|
let quirk = self.hub.config.borrow().wants_ua_quirk(&url);
|
|
let changed = self.engine.as_ref().is_some_and(|e| e.set_view_user_agent(&view, quirk.then_some(crate::inject::FIREFOX_UA)));
|
|
// The request was made with the old user agent: load it again with the new one.
|
|
if changed && request.reloadable {
|
|
request.deny();
|
|
view.load(&url);
|
|
} 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())];
|
|
// Cookies for Nacre's own downloads come from WebKit's cookie manager in S051 (it answers asynchronously).
|
|
let _ = url;
|
|
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::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 { url } => {
|
|
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));
|
|
// The blocked one opens now (without its opener, which WebKit already let go).
|
|
if !url.is_empty() {
|
|
let from = Some(self.windows[&w].tabs[i].id);
|
|
self.open(w, url, Disposition::NewForegroundTab, from);
|
|
}
|
|
}
|
|
},
|
|
Prompt::Info { .. } => {},
|
|
}
|
|
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) {
|
|
(crate::engine::SimpleDialog::Prompt(mut prompt), DialogResult::Ok(Some(value))) => {
|
|
prompt.set_current_value(&value);
|
|
crate::engine::SimpleDialog::Prompt(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, _) => match result {
|
|
DialogResult::Color(Some(rgb)) => {
|
|
picker.select(Some(rgb));
|
|
picker.submit();
|
|
},
|
|
_ => picker.cancel(),
|
|
},
|
|
Dialog::ContextMenu(menu) => drop(menu),
|
|
Dialog::LeavePage(request) => {
|
|
if matches!(result, DialogResult::Leave(true)) {
|
|
request.allow();
|
|
} else {
|
|
// Stay: a close waiting for this answer is off.
|
|
self.windows.get_mut(&w).expect("found").tabs[i].closing = None;
|
|
self.cancel_shutdown();
|
|
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::Page(page_action) => {
|
|
if let Some(menu) = menu {
|
|
menu.select(page_action);
|
|
}
|
|
return;
|
|
},
|
|
other => {
|
|
drop(menu);
|
|
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::Page(_) => {},
|
|
}
|
|
},
|
|
}
|
|
self.redraw(w);
|
|
}
|
|
|
|
/// WebKit counted the matches of the find bar's search (or of a step through them).
|
|
pub fn on_find(&mut self, id: ViewId, count: u32) {
|
|
let Some((w, i)) = self.find_webview(id) else { return };
|
|
let find = &mut self.windows.get_mut(&w).expect("found").tabs[i].find;
|
|
if find.text.is_empty() {
|
|
return;
|
|
}
|
|
find.count = count;
|
|
find.index = match (count, find.index) {
|
|
(0, _) => 0,
|
|
(_, 0) => 1,
|
|
(n, i) => i.min(n),
|
|
};
|
|
self.redraw(w);
|
|
}
|
|
|
|
// ── page messages ─────────────────────────────────────────────────
|
|
|
|
pub fn on_page_message(&mut self, id: ViewId, 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"));
|
|
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 {
|
|
self.restyle(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();
|
|
},
|
|
"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" => {
|
|
let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i];
|
|
// A new right click: what was waiting for the last one is stale.
|
|
tab.context = Some(data);
|
|
tab.menu_wait = crate::tabs::MenuWait::None;
|
|
},
|
|
"context_end" => {
|
|
let prevented = data.get("prevented").and_then(|v| v.as_bool()).unwrap_or(false);
|
|
let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i];
|
|
match std::mem::take(&mut tab.menu_wait) {
|
|
crate::tabs::MenuWait::Menu(request, _) if !prevented => self.show_page_menu(w, i, *request),
|
|
crate::tabs::MenuWait::Menu(..) => tab.context = None,
|
|
_ => tab.menu_wait = crate::tabs::MenuWait::Answer(prevented),
|
|
}
|
|
},
|
|
"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() {
|
|
let options = self.zap_options(w);
|
|
self.eval(tab_id, inject::call("cosmetic.hide", &[serde_json::json!(selectors), options]));
|
|
}
|
|
},
|
|
"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());
|
|
}
|
|
|
|
/// A download only WebKit can fetch (a page's `blob:` or `data:` file): saved in the downloads folder under the
|
|
/// name the page gave it (no "ask where", no pause: WebKit can't resume these).
|
|
pub fn on_web_download(&mut self, view: Option<ViewId>, item: crate::engine::WebDownload) {
|
|
let page = view.and_then(|v| self.tab_mut(v)).map(|t| t.url.clone()).unwrap_or_default();
|
|
let settings = self.shared.settings.borrow().downloads.clone();
|
|
let name = if item.suggested_name().is_empty() { "download".to_owned() } else { util::safe_file_name(item.suggested_name()) };
|
|
let path = util::unused_path(&settings.dir, &name);
|
|
let _ = std::fs::create_dir_all(&settings.dir);
|
|
let id = self.shared.downloads.borrow_mut().add(&item.url(), &page, path.clone());
|
|
let wake = self.wake();
|
|
item.save_to(&path, id, self.downloads_tx.clone(), move || wake());
|
|
self.web_downloads.insert(id, item);
|
|
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();
|
|
}
|
|
|
|
pub fn on_download_msg(&mut self, msg: download::Msg) {
|
|
if !matches!(msg, download::Msg::Progress { .. }) {
|
|
let id = match &msg {
|
|
download::Msg::Progress { id, .. } | download::Msg::Done { id, .. } | download::Msg::Failed { id, .. } | download::Msg::Paused { id, .. } | download::Msg::Cancelled { id } => *id,
|
|
};
|
|
self.web_downloads.remove(&id);
|
|
}
|
|
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();
|
|
// A small file finishes before its first progress report: take the size from the file.
|
|
let size = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
|
|
d.received = d.received.max(d.total).max(size);
|
|
d.total = d.total.max(d.received);
|
|
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) if self.web_downloads.contains_key(&id) => self.web_downloads[&id].cancel(),
|
|
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);
|
|
}
|
|
if let Some(d) = self.web_downloads.remove(&id) {
|
|
d.cancel();
|
|
}
|
|
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.use_content_filter();
|
|
app.redraw_all();
|
|
});
|
|
}
|
|
|
|
/// Hand the ad blocker's latest build to WebKit (content filter) and the web process extension (redirects).
|
|
fn use_content_filter(&mut self) {
|
|
if let (Some(engine), Some(filter)) = (&self.engine, self.shared.adblock.content_filter()) {
|
|
engine.set_content_filter(filter);
|
|
}
|
|
self.refresh_hub_config();
|
|
}
|
|
|
|
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);
|
|
// Also when nothing was downloaded: own rules may have changed (unchanged lists load from the cache).
|
|
blocker.build(&settings, &dir, &cache);
|
|
(refreshed, blocker.rule_count())
|
|
}, |app, (refreshed, rules)| {
|
|
app.use_content_filter();
|
|
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} list{} couldn't be downloaded", fmt_count(rules), if failures == 1 { "" } else { "s" }) } else { format!("{} rules · {refreshed} list{} updated", fmt_count(rules), if refreshed == 1 { "" } else { "s" }) };
|
|
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 suggest_places(&mut self, name: String) {
|
|
let url = format!("https://geocoding-api.open-meteo.com/v1/search?count=5&name={}", util::encode_query(&name));
|
|
self.spawn("places", move || crate::net::fetch::get_json(&url, Duration::from_secs(6)), move |app, result| {
|
|
// A failed lookup shows no suggestions; the field still takes what was typed.
|
|
let places = result.map(|json| crate::ui::pages::customize::Place::from_open_meteo(&json)).unwrap_or_default();
|
|
*app.shared.places.borrow_mut() = (name, places);
|
|
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<(crate::ui::pages::newtab::Weather, (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("no place with that name")?;
|
|
(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 fahrenheit = crate::ui::pages::newtab::fahrenheit(&units);
|
|
let unit = if fahrenheit { "&temperature_unit=fahrenheit&wind_speed_unit=mph" } else { "" };
|
|
let w = crate::net::fetch::get_json(
|
|
&format!(
|
|
"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}&timezone=auto&forecast_days=1\
|
|
¤t=temperature_2m,apparent_temperature,relative_humidity_2m,weather_code,wind_speed_10m,is_day\
|
|
&daily=temperature_2m_max,temperature_2m_min,precipitation_probability_max{unit}"
|
|
),
|
|
Duration::from_secs(10),
|
|
)?;
|
|
Ok((crate::ui::pages::newtab::Weather::from_open_meteo(&city, &w, fahrenheit), (lat, lon)))
|
|
}, |app, result| {
|
|
match result {
|
|
Ok((weather, loc)) => {
|
|
// The place may have changed while this ran; keep the coordinates only for the place asked about.
|
|
let mut s = app.shared.settings.borrow_mut();
|
|
if s.ntp.city == weather.place && s.ntp.city_loc.is_none() {
|
|
s.ntp.city_loc = Some(loc);
|
|
}
|
|
drop(s);
|
|
*app.shared.weather.borrow_mut() = Some(Ok(weather));
|
|
},
|
|
Err(error) => *app.shared.weather.borrow_mut() = Some(Err(error)),
|
|
}
|
|
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, &tab.page_image, &tab.favicon_url, 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(engine) = &self.engine {
|
|
engine.clear_data(has("cookies"), has("cache"), since, None);
|
|
}
|
|
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, 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(Kind::App(app.id.clone()), vec![tab], 0, Some((app.width, app.height)));
|
|
}
|
|
|
|
pub fn handle_launch(&mut self, launch: Launch) {
|
|
if let Some(app) = &launch.app {
|
|
self.open_app_window(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(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.present();
|
|
}
|
|
}
|
|
|
|
pub fn open_pending_windows(&mut self) {
|
|
let requests = std::mem::take(&mut self.window_requests);
|
|
for request in requests {
|
|
self.open_window(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 ────────────────────────────────────────────
|
|
|
|
/// Picture in picture: the tab's own view moves into a small window of its own and shows only its video; the
|
|
/// page keeps playing as it was (no reload).
|
|
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 };
|
|
let tab = &self.windows[&w].tabs[i];
|
|
if tab.pip_size.is_some() || tab.page.is_some() {
|
|
return;
|
|
}
|
|
let Some(view) = tab.web.as_ref().map(|web| web.webview.clone()) else { return };
|
|
let jobs = self.jobs_tx.clone();
|
|
view.evaluate_javascript(inject::call("pip.enter", &[]), move |result| {
|
|
let video = result.ok().and_then(|v| Some((v.get("w")?.as_f64()?, v.get("h")?.as_f64()?)));
|
|
let _ = jobs.send(Box::new(move |app: &mut App| {
|
|
let Some((vw, vh)) = video else {
|
|
app.shared.toast("There's no video on this page to show in picture in picture");
|
|
return;
|
|
};
|
|
let Some((w, i)) = app.find_tab(tab_id) else { return };
|
|
let Some(view) = app.windows[&w].tabs[i].web.as_ref().map(|web| web.webview.clone()) else { return };
|
|
let width = app.shared.settings.borrow().window.pip_width.clamp(200, 1600);
|
|
let height = pip_height(width, vw, vh);
|
|
let win = app.windows.get_mut(&w).expect("found");
|
|
win.tabs[i].pip_size = Some([width, height]);
|
|
win.detach(&view);
|
|
win.sync_webviews();
|
|
if let Some(pip) = app.open_window(Kind::Pip { window: w, tab: tab_id }, Vec::new(), 0, Some((width, height)))
|
|
&& let Some(win) = app.windows.get_mut(&pip)
|
|
{
|
|
win.pip_view = Some(view.clone());
|
|
win.sync_webviews();
|
|
// The keyboard goes to the page (the player's own keys), not the overlay `open_window` focused.
|
|
win.page_focused = true;
|
|
view.focus();
|
|
// Only the video now: it goes full screen inside this window (see `Event::Fullscreen`).
|
|
view.evaluate_javascript(inject::call("pip.full", &[]), |_| {});
|
|
}
|
|
app.redraw(w);
|
|
}));
|
|
crate::app::schedule_pump();
|
|
});
|
|
}
|
|
|
|
/// Back from picture in picture: the view goes back into its tab, the page as it was before.
|
|
pub fn exit_pip(&mut self, source: WindowId, tab_id: u64) {
|
|
let pip = self.windows.iter_mut().find(|(_, w)| matches!(w.kind, Kind::Pip { tab, .. } if tab == tab_id)).and_then(|(_, w)| w.pip_view.take().map(|v| (v, w)));
|
|
if let Some((view, pip)) = pip {
|
|
let width = pip.size().0;
|
|
if width >= 200 {
|
|
self.shared.settings.borrow_mut().window.pip_width = width;
|
|
}
|
|
pip.detach(&view);
|
|
view.evaluate_javascript(inject::call("pip.leave", &[]), |_| {});
|
|
}
|
|
let Some(win) = self.windows.get_mut(&source) else { return };
|
|
let Some(i) = win.tab_index(tab_id) else { return };
|
|
win.tabs[i].pip_size = None;
|
|
// The page leaves its full screen too; that news then belongs to nobody.
|
|
win.tabs[i].fullscreen = false;
|
|
win.sync_webviews();
|
|
self.redraw(source);
|
|
}
|
|
|
|
/// Run a script in the page of a tab shown in picture in picture.
|
|
fn eval_pip(&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, |_| {});
|
|
}
|
|
}
|
|
|
|
// ── 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();
|
|
web.evaluate_javascript("document.documentElement.outerHTML", move |result| {
|
|
let html = match result {
|
|
Ok(serde_json::Value::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()));
|
|
}
|
|
});
|
|
}));
|
|
crate::app::Waker.wake();
|
|
});
|
|
}
|
|
|
|
/// Print with WebKit's print dialog.
|
|
fn print_page(&mut self, window: WindowId) {
|
|
let Some(win) = self.windows.get(&window) else { return };
|
|
let Some(web) = win.active_webview() else { return };
|
|
web.print(win.window.upcast_ref());
|
|
}
|
|
|
|
// ── settings ──────────────────────────────────────────────────────
|
|
|
|
/// The UI edits settings in place; this notices and applies what changed.
|
|
pub fn apply_settings_if_changed(&mut self) {
|
|
let revision = self.shared.permissions.borrow().revision();
|
|
if revision != self.permissions_seen {
|
|
self.permissions_seen = revision;
|
|
self.shared.permissions.borrow_mut().flush();
|
|
self.refresh_hub_config();
|
|
}
|
|
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.mode_off != new.privacy.mode_off
|
|
|| old.privacy.block_third_party != new.privacy.block_third_party
|
|
|| 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.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(engine) = &self.engine
|
|
{
|
|
engine.set_user_agent(&new.web.user_agent);
|
|
let ua = engine.user_agent();
|
|
*self.shared.user_agent.borrow_mut() = ua.clone();
|
|
crate::net::fetch::set_user_agent(&ua);
|
|
// Privacy mode's navigator values follow the user agent.
|
|
self.install_page_scripts();
|
|
}
|
|
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();
|
|
}
|
|
}
|
|
|
|
/// The find bar's "n of m" after a step forward or back (WebKit wraps around; it doesn't say where it is).
|
|
fn step_match(index: u32, count: u32, forward: bool) -> u32 {
|
|
match (forward, index) {
|
|
(_, _) if count == 0 => 0,
|
|
(true, i) if i >= count => 1,
|
|
(true, i) => i + 1,
|
|
(false, i) if i <= 1 => count,
|
|
(false, i) => i - 1,
|
|
}
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
/// The picture-in-picture window's height for a width: the video's aspect ratio (16:9 when the page didn't say).
|
|
fn pip_height(width: u32, video_w: f64, video_h: f64) -> u32 {
|
|
let (vw, vh) = if video_w >= 1.0 && video_h >= 1.0 { (video_w, video_h) } else { (16.0, 9.0) };
|
|
((width as f64) * vh / vw).round().clamp(120.0, 1200.0) as u32
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::{pip_height, step_match};
|
|
|
|
#[test]
|
|
fn pip_window_follows_the_video_aspect() {
|
|
assert_eq!(pip_height(480, 1920.0, 1080.0), 270);
|
|
assert_eq!(pip_height(480, 1080.0, 1920.0), 853);
|
|
// No size from the page yet: 16:9.
|
|
assert_eq!(pip_height(480, 0.0, 0.0), 270);
|
|
assert_eq!(pip_height(200, 4000.0, 100.0), 120);
|
|
}
|
|
|
|
#[test]
|
|
fn find_steps_wrap_around() {
|
|
assert_eq!(step_match(1, 3, true), 2);
|
|
assert_eq!(step_match(3, 3, true), 1);
|
|
assert_eq!(step_match(1, 3, false), 3);
|
|
assert_eq!(step_match(2, 3, false), 1);
|
|
assert_eq!(step_match(0, 0, true), 0);
|
|
}
|
|
}
|
|
|