diff --git a/crates/ai/src/claude_api.rs b/crates/ai/src/claude_api.rs index 9eb177d1..60457f3d 100644 --- a/crates/ai/src/claude_api.rs +++ b/crates/ai/src/claude_api.rs @@ -4,7 +4,8 @@ use std::sync::atomic::AtomicBool; use serde_json::json; -use crate::provider::{self, AiError, Provider, Request}; +use crate::error::AiError; +use crate::provider::{self, Provider, Request}; use crate::transport::Transport; const URL: &str = "https://api.anthropic.com/v1/messages"; @@ -159,11 +160,11 @@ mod tests { crate::secrets::store_token(&secrets, &token()).unwrap(); let outputs = [ format!("{:?}", crate::secrets::load_token(&secrets)), - format!("{:?}", crate::provider::AiError::Secrets("x".into())), + format!("{:?}", crate::error::AiError::Secrets("x".into())), format!("{:?}", token()), format!("{:#?}", ClaudeApi::new(token(), Some("m".into()), Arc::new(UreqTransport))), format!("{:?}", req()), - format!("{:?}", crate::provider::AiError::Status(401, "x".into())), + format!("{:?}", crate::error::AiError::Status(401, "x".into())), format!("{:?}", crate::ollama::Ollama::new("m", Arc::new(UreqTransport))), format!("{:?}", crate::claude_cli::ClaudeCli::new("/usr/bin/false".into(), None)), ]; diff --git a/crates/ai/src/claude_cli.rs b/crates/ai/src/claude_cli.rs index 7f169165..a29cf430 100644 --- a/crates/ai/src/claude_cli.rs +++ b/crates/ai/src/claude_cli.rs @@ -7,7 +7,8 @@ use std::time::Duration; use serde_json::json; -use crate::provider::{AiError, Provider, Request}; +use crate::error::AiError; +use crate::provider::{Provider, Request}; const HELPER: &str = "tarn-cli-bridge"; diff --git a/crates/ai/src/error.rs b/crates/ai/src/error.rs new file mode 100644 index 00000000..ea77a45b --- /dev/null +++ b/crates/ai/src/error.rs @@ -0,0 +1,30 @@ +use std::fmt; + +#[derive(Debug)] +pub enum AiError { + Cancelled, + Network(String), + Status(u16, String), + Protocol(String), + Refused, + Secrets(String), + Cli(String), + Unavailable(String), +} + +impl fmt::Display for AiError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Cancelled => f.write_str("cancelled"), + Self::Network(e) => write!(f, "network error: {e}"), + Self::Status(code, msg) => write!(f, "HTTP {code}: {msg}"), + Self::Protocol(e) => write!(f, "unexpected response: {e}"), + Self::Refused => f.write_str("the model declined to answer"), + Self::Secrets(e) => write!(f, "secret store: {e}"), + Self::Cli(e) => write!(f, "claude cli: {e}"), + Self::Unavailable(why) => f.write_str(why), + } + } +} + +impl std::error::Error for AiError {} diff --git a/crates/ai/src/lib.rs b/crates/ai/src/lib.rs index c7129251..e4b9f4d5 100644 --- a/crates/ai/src/lib.rs +++ b/crates/ai/src/lib.rs @@ -2,6 +2,7 @@ pub mod claude_api; pub mod claude_cli; +pub mod error; pub mod grouping; pub mod local; pub mod markdown; @@ -13,10 +14,11 @@ pub mod transport; pub use claude_api::{ApiToken, ClaudeApi}; pub use claude_cli::ClaudeCli; +pub use error::AiError; pub use local::{Availability, LocalModel}; pub use ollama::Ollama; pub use page_context::PageContext; -pub use provider::{AiError, Provider, Request}; +pub use provider::{Provider, Request}; pub use secrets::Secrets; pub use transport::Transport; #[cfg(not(target_os = "android"))] diff --git a/crates/ai/src/local.rs b/crates/ai/src/local.rs index 33d6926c..d1044ce8 100644 --- a/crates/ai/src/local.rs +++ b/crates/ai/src/local.rs @@ -4,7 +4,8 @@ use std::sync::atomic::AtomicBool; -use crate::provider::{AiError, Provider, Request}; +use crate::error::AiError; +use crate::provider::{Provider, Request}; #[derive(Clone, Debug, PartialEq, Eq)] pub enum Availability { @@ -102,7 +103,7 @@ mod tests { use std::sync::{Arc, Mutex}; use super::*; - use crate::Ollama; + use crate::ollama::Ollama; use crate::transport::{Response, Transport}; /// Answers `/api/show` with `show` (none: Ollama is not running) and `/api/chat` with one word, diff --git a/crates/ai/src/ollama.rs b/crates/ai/src/ollama.rs index ea2971a7..89b42a68 100644 --- a/crates/ai/src/ollama.rs +++ b/crates/ai/src/ollama.rs @@ -4,8 +4,9 @@ use std::sync::atomic::AtomicBool; use serde_json::json; +use crate::error::AiError; use crate::local::{Availability, Checked, LocalModel}; -use crate::provider::{self, AiError, Request}; +use crate::provider::{self, Request}; use crate::transport::Transport; const BASE: &str = "http://127.0.0.1:11434"; diff --git a/crates/ai/src/provider.rs b/crates/ai/src/provider.rs index b67780c2..7b1746fb 100644 --- a/crates/ai/src/provider.rs +++ b/crates/ai/src/provider.rs @@ -1,7 +1,7 @@ -use std::fmt; use std::io::{BufRead, Read}; use std::sync::atomic::{AtomicBool, Ordering}; +use crate::error::AiError; use crate::page_context::PageContext; use crate::transport::{self, Transport}; @@ -20,35 +20,6 @@ pub trait Provider { fn stream(&self, req: &Request, cancel: &AtomicBool, on_text: &mut dyn FnMut(&str)) -> Result<(), AiError>; } -#[derive(Debug)] -pub enum AiError { - Cancelled, - Network(String), - Status(u16, String), - Protocol(String), - Refused, - Secrets(String), - Cli(String), - Unavailable(String), -} - -impl fmt::Display for AiError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Cancelled => f.write_str("cancelled"), - Self::Network(e) => write!(f, "network error: {e}"), - Self::Status(code, msg) => write!(f, "HTTP {code}: {msg}"), - Self::Protocol(e) => write!(f, "unexpected response: {e}"), - Self::Refused => f.write_str("the model declined to answer"), - Self::Secrets(e) => write!(f, "secret store: {e}"), - Self::Cli(e) => write!(f, "claude cli: {e}"), - Self::Unavailable(why) => f.write_str(why), - } - } -} - -impl std::error::Error for AiError {} - impl Request { pub fn user_message(&self) -> String { match &self.page { diff --git a/crates/ai/src/secrets.rs b/crates/ai/src/secrets.rs index bd9c5644..626bbb0a 100644 --- a/crates/ai/src/secrets.rs +++ b/crates/ai/src/secrets.rs @@ -1,5 +1,5 @@ use crate::claude_api::ApiToken; -use crate::provider::AiError; +use crate::error::AiError; const SERVICE: &str = "de.quavon.tarn"; const ACCOUNT: &str = "anthropic-api-token"; @@ -35,7 +35,7 @@ mod apple { use security_framework::passwords::{delete_generic_password, get_generic_password}; use super::{Keyring, Secrets}; - use crate::provider::AiError; + use crate::error::AiError; const ERR_SEC_ITEM_NOT_FOUND: i32 = -25300; @@ -77,7 +77,7 @@ mod apple { #[cfg(windows)] mod windows { use super::{Keyring, Secrets}; - use crate::provider::AiError; + use crate::error::AiError; fn target(service: &str, account: &str) -> String { format!("{service}/{account}") @@ -110,7 +110,7 @@ mod linux { use oo7::dbus::{Collection, Service}; use super::{Keyring, Secrets}; - use crate::provider::AiError; + use crate::error::AiError; fn failed(e: oo7::dbus::Error) -> AiError { AiError::Secrets(e.to_string()) diff --git a/crates/ai/src/transport.rs b/crates/ai/src/transport.rs index c3930ff3..9f0ba87f 100644 --- a/crates/ai/src/transport.rs +++ b/crates/ai/src/transport.rs @@ -4,7 +4,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use url::{Host, Url}; -use crate::provider::AiError; +use crate::error::AiError; pub struct Response<'a> { pub status: u16, @@ -63,7 +63,7 @@ mod ureq_transport { use ureq::tls::{RootCerts, TlsConfig}; use super::{Response, Transport, guard}; - use crate::provider::AiError; + use crate::error::AiError; /// Talks TLS itself with the platform's certificate verifier; Android's needs JNI setup, so /// the Android host brings its own transport. diff --git a/crates/app/src/browser.rs b/crates/app/src/browser.rs index 10f35694..83e3e8e5 100644 --- a/crates/app/src/browser.rs +++ b/crates/app/src/browser.rs @@ -24,7 +24,11 @@ use crate::filters; use crate::settings::SettingsWindow; use engine::favicon; +mod command_bar; mod context; +mod events; +mod profile; +mod views; const MAX_SUGGESTIONS: usize = 8; type FaviconMemo = HashMap>>; @@ -922,2875 +926,6 @@ impl Browser { self.model.lifecycle.remove(key); Some((view, self.pages.remove(&key).unwrap_or_default())) } - - pub(crate) fn store(&self, private: bool) -> &Store { - self.core.store(private) - } - - pub fn page(&self, key: TabKey) -> PageState { - self.pages.get(&key).cloned().unwrap_or_default() - } - - pub fn loading(&self, key: TabKey) -> bool { - self.pages.get(&key).is_some_and(|p| p.loading) - } - - /// Books the redraw of the spinners' next step while a spinner of this space turns. - pub(crate) fn keep_spinning(&mut self, window: &mut Window, cx: &mut Context) { - let reloading = self.reload_spin.is_some_and(|(_, at)| at.elapsed() < crate::toolbar::SPIN); - if self.spinning || self.still() || !reloading && !self.model.tabs.iter().any(|t| self.loading(self.model.key(t))) { - return; - } - self.spinning = true; - spin_step(window, cx.entity().downgrade(), Instant::now()); - } - - /// Whether spinners stand still: motion is reduced or Tarn is in the background. - pub(crate) fn still(&self) -> bool { - !engine::app_active() || self.pref(crate::prefs::Pref::ReduceMotion) - } - - pub(crate) fn reload_spaces(&mut self) { - self.model.reload_spaces(&self.core); - } - - pub(crate) fn reload_space(&mut self) { - let old = self.model.reload_space(&self.core); - self.space_shown(&old); - } - - /// Catches the shell up with the current space's lists: its profile's site icons, the tabs - /// that fade in and its bookmarks. - pub(crate) fn space_shown(&mut self, old: &[Tab]) { - self.note_new_tabs(old); - let profile = self.model.profile(); - if let Some((private, profile_id)) = profile { - self.load_favicons(private, profile_id); - } - if profile != self.bookmarks_of { - self.bookmarks_of = profile; - self.set_bookmarks(profile.map(|(private, id)| self.store(private).bookmarks(id).unwrap_or_default()).unwrap_or_default()); - } - } - - /// A space's tabs, folders and groups as stored, with its profile's site icons loaded. - pub(crate) fn space_lists(&mut self, ix: usize) -> browser_core::tabs::Lists { - if let Some(space) = self.model.spaces.get(ix) { - self.load_favicons(space.private, space.space.profile_id); - } - self.model.space_lists(&self.core, ix) - } - - /// Stored icons are small 64 px PNGs, so a profile's set is read once and kept in memory. - fn load_favicons(&mut self, private: bool, profile_id: Id) { - let store = self.core.store(private); - self.favicons.load(&(private, profile_id), || { - let icons = store.favicons(profile_id).unwrap_or_default(); - let icons = icons.into_iter().map(|(host, png)| (host, Arc::new(Image::from_bytes(ImageFormat::Png, png)))).collect(); - (icons, store.stale_favicons(profile_id, now() - favicon::MAX_AGE).unwrap_or_default()) - }); - self.favicon_memo.take(); - } - - fn runtime(&mut self, private: bool, profile_id: Id) -> Option> { - let downloads = || -> Rc { - let events = self.core.downloads.clone(); - Rc::new(move |event| drop(events.unbounded_send((private, profile_id, event)))) - }; - if self.core.open_profile(private, profile_id, downloads)? { - let profiles = self.core.profiles.borrow(); - let data = &profiles[&(private, profile_id)].data; - self.core.apply_blocking_to(data); - data.set_sort_downloads(self.pref(crate::prefs::Pref::SortDownloads)); - drop(profiles); - self.core.apply_extensions(private, profile_id); - if !private { - crate::tarn_ext::opened(&self.core, profile_id); - } - self.apply_site_styles(private, profile_id); - crate::zaps::apply(&self.core, private, profile_id); - // Chromium refuses a profile's requests until its Shield choices arrive. - #[cfg(windows)] - self.core.sync_shield(); - } - self.loaded(private, profile_id) - } - - /// The runtime of a profile already opened; the borrow ends with the returned guard. - pub(crate) fn loaded(&self, private: bool, profile_id: Id) -> Option> { - Ref::filter_map(self.core.profiles.borrow(), |p| p.get(&(private, profile_id))).ok() - } - - pub fn set_filter_updates(&mut self, on: bool, cx: &mut Context) { - match self.core.disk.set_setting(filters::SETTING, if on { "on" } else { "off" }) { - Ok(()) => { - self.core.filters.borrow_mut().updates = on; - if self.warning.as_deref().is_some_and(|w| w.starts_with(FILTER_SETTING_WARNING)) { - self.warning = None; - } - } - Err(e) => self.warning = Some(format!("{FILTER_SETTING_WARNING} ({e}).")), - } - cx.notify(); - } - - fn current_runtime(&mut self) -> Option> { - let space = self.model.current_space()?; - let (private, profile_id) = (space.private, space.space.profile_id); - self.runtime(private, profile_id) - } - - pub fn level_for(&self, url: &str) -> ShieldLevel { - let Some((private, profile_id)) = self.model.profile() else { return ShieldLevel::default() }; - self.core.level(private, profile_id, Url::parse(url).ok().as_ref()).unwrap_or_default() - } - - pub fn has_override(&self, host: &str) -> bool { - self.model.profile().is_some_and(|(private, profile_id)| self.core.has_override(private, profile_id, host)) - } - - /// Events are tagged with the view that sent them, so a replaced view's late events are dropped. - pub(crate) fn sink(&mut self, key: TabKey) -> Rc { - self.next_generation += 1; - let generation = self.next_generation; - self.view_generation.insert(key, generation); - let events = self.events.clone(); - Rc::new(move |event| { - events.unbounded_send(Msg::Tab(key, generation, event)).ok(); - }) - } - - /// Events of the link peek's view, tagged so a closed peek's late events are dropped. - pub(crate) fn peek_sink(&mut self) -> (u64, Rc) { - self.next_generation += 1; - let (generation, events) = (self.next_generation, self.events.clone()); - (generation, Rc::new(move |event| drop(events.unbounded_send(Msg::Peek(generation, event))))) - } - - #[cfg(feature = "chromium")] - pub(crate) fn web_engine_for(&mut self, key: TabKey, url: &str) -> WebEngine { - let tab = self.model.tab(key).and_then(|t| t.web_engine); - let Some((private, profile_id)) = self.model.profile() else { return WebEngine::WebKit }; - self.runtime(private, profile_id); - self.core.web_engine(private, profile_id, tab, Url::parse(url).ok().as_ref()).unwrap_or(WebEngine::WebKit) - } - - /// A web view of the profile's data store with the Shield rules for `url`. - pub(crate) fn web_view(&mut self, host: &Host, private: bool, profile_id: Id, url: &str, sink: Rc) -> Option { - let developer = self.developer; - let sets = self.core.sets.clone(); - let rt = self.runtime(private, profile_id)?; - let site_for = browser_core::site::site_for(rt.profile.clone(), rt.overrides.clone(), rt.rules.clone(), sets); - let site = Url::parse(url).map_or(nav_policy::Site::new(rt.profile.shield_level), |u| site_for(&u)); - let inspectable = (developer || rt.profile.is_dev) && site.level != ShieldLevel::Lockdown; - Some(WebView::new(host, &rt.data, site.level, site.filtered, inspectable, site_for, sink)) - } - - #[cfg_attr(not(feature = "chromium"), allow(unused_variables))] - pub(crate) fn create_view(&mut self, key: TabKey, url: &str, cx: &mut Context) -> Option> { - let host = self.host.clone()?; - let sink = self.sink(key); - let space = self.model.current_space()?; - let (private, profile_id) = (space.private, space.space.profile_id); - if self.core.awaits_extensions(private, profile_id) { - return None; - } - #[cfg(feature = "chromium")] - let wants_chromium = !private && self.web_engine_for(key, url) == WebEngine::Chromium; - #[cfg(feature = "chromium")] - if wants_chromium && !self.chromium_current(key, cx) { - return None; - } - #[cfg(feature = "chromium")] - let developer = self.developer; - #[cfg(feature = "chromium")] - let chromium = wants_chromium - .then(|| self.runtime(private, profile_id)) - .flatten() - .and_then(|rt| WebView::chromium(&host, &rt.data, &data_dir().join("Chromium"), &rt.own_store, developer || rt.profile.is_dev, sink.clone())); - #[cfg(not(feature = "chromium"))] - let chromium = None; - #[cfg(feature = "chromium")] - if chromium.is_some() { - if self.core.chromium_profile.get() != Some(profile_id) { - crate::shared::count_chromium_blocks(&self.core); - } - let owner_changed = self.core.chromium_profile.replace(Some(profile_id)) != Some(profile_id); - self.core.sync_shield(); - if owner_changed { - crate::tarn_ext::chromium_owner_changed(&self.core, profile_id); - } - let ageing = browser_core::staleness::Staleness::Ageing; - if self.core.chromium_staleness.get() == ageing && self.pages.get(&key).is_none_or(|p| p.notice.is_none()) { - self.notify_offer(key, ageing.message().to_owned(), None); - } - } - let view = Rc::new(match chromium { - Some(view) => view, - None => self.web_view(&host, private, profile_id, url, sink)?, - }); - view.set_corner_radius(page_corner()); - view.set_dark(!ui::theme::Theme::is_light()); - self.view_prefs(&view); - self.views.insert(key, view.clone()); - self.attach_tarn(key); - Some(view) - } - - /// Typed and incoming URLs are user-initiated, so stripping tracking parameters here keeps - /// the request's context; links from pages are left alone. - pub fn clean_user_url(&self, url: Url) -> Url { - self.core.clean_user_url(self.model.profile(), url) - } - - /// `clean_user_url` for a load the user starts now; removed parameters count on the current - /// profile's Shield card. - fn clean_user_load(&mut self, url: Url, cx: &mut Context) -> Url { - let clean = self.clean_user_url(url.clone()); - if let Some((private, profile_id)) = self.model.current_space().map(|s| (s.private, s.space.profile_id)) { - self.count_shield(private, profile_id, Counter::TrackingParams, shield::url_clean::removed_params(&url, &clean), clean.host_str(), cx); - } - clean - } - - /// Counts one event for the site the tab shows, as the page that caused it. - fn count_on_page(&mut self, key: TabKey, counter: Counter, cx: &mut Context) { - let host = self.tab_url(key).and_then(|u| Url::parse(&u).ok()).and_then(|u| page_host(&u)); - if let Some(profile_id) = self.profile_of(key) { - self.count_shield(key.private, profile_id, counter, 1, host.as_deref(), cx); - } - } - - /// Adds to a Shield card counter and repaints every window, so an open card follows. - pub(crate) fn count_shield(&mut self, private: bool, profile_id: Id, counter: Counter, n: i64, host: Option<&str>, cx: &mut Context) { - if n <= 0 || self.store(private).count(profile_id, counter, n, host).is_err() { - return; - } - crate::shield_card::touch(); - crate::shared::others(cx, |_, _, cx| cx.notify()); - cx.notify(); - } - - /// Shows how a download ended over the active tab: a passing toast in the window in front, or a - /// warning in every window, held until dismissed (S11) and, while the window shows another - /// profile's space, waiting for that profile's space. - pub(crate) fn notify_download( - &mut self, - private: bool, - profile_id: Id, - result: &Result<(std::path::PathBuf, bool), String>, - front: bool, - cx: &mut Context, - ) { - let here = self.model.current_space().is_some_and(|s| (s.private, s.space.profile_id) == (private, profile_id)); - let mark = if cfg!(windows) { "the mark of the web" } else { "macOS quarantine" }; - let (tone, text) = match result { - Ok((path, quarantined)) => { - let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - browser_core::toast::download(&ui::text::bounded_title(&name), Ok((*quarantined, engine::downloads::is_dangerous(&name))), mark) - } - Err(message) => browser_core::toast::download("", Err(&ui::text::bounded_title(message)), mark), - }; - if tone == browser_core::toast::Tone::Warning { - self.hold_toast(text, self.model.active.filter(|_| here), (private, profile_id), cx); - } else if here && front { - let reveal = result.as_ref().ok().map(|(path, _)| crate::toast::Action::Reveal(path.clone())); - self.show_tab_toast(tone, text, reveal, (private, profile_id), cx); - } - } - - pub fn active_view(&self) -> Option> { - self.views.get(&self.model.active?).cloned() - } - - pub fn activate(&mut self, key: TabKey, window: &mut Window, cx: &mut Context) { - if self.model.tab(key).is_none() { - return; - } - let switched = self.model.active != Some(key); - let _span = switched.then(|| engine::startup::span(engine::startup::TAB_SWITCH)).flatten(); - if switched { - self.leave_page_fullscreen(window); - } - let mut fading = false; - if switched - && let Some((outgoing, _)) = self.page_fade.take() - && !self.views.get(&key).is_some_and(|v| Rc::ptr_eq(v, &outgoing)) - { - outgoing.set_visible(false); - } - let partners = self.split_partners(key, cx); - if let Some(prev) = self.model.active.filter(|p| *p != key && !partners.contains(p)).and_then(|p| self.views.get(&p)).cloned() { - fading = partners.is_empty() && !self.pref(crate::prefs::Pref::ReduceMotion) && !self.overlay_open() && self.active_json().is_none(); - if fading { - self.page_fade = Some((prev, Instant::now())); - } else { - prev.set_visible(false); - } - } - if let Some(prev) = self.model.active.filter(|p| *p != key) { - self.ask_media(prev, cx); - } - let left = Instant::now(); - self.seen.extend(self.model.active.into_iter().chain([key]).map(|k| (k, left))); - self.typed_in.remove(&key); - let evicted = self.model.lifecycle.activate_with(&partners, key); - for evicted in evicted { - if evicted == key || partners.contains(&evicted) || self.typed_in.contains(&evicted) { - // The split's panes, and tabs with typed input, stay awake above the live-tab limit. - self.model.lifecycle.keep(evicted); - } else { - self.sleep_unless_playing(evicted, cx); - } - } - let view = self.wake(key, cx); - self.model.active = Some(key); - if let Some(view) = view { - if fading { - view.raise(); - view.set_alpha(0.); - } else if switched { - view.set_alpha(1.); - } - view.set_visible(!self.overlay_open()); - if !self.overlay_open() { - view.focus(); - } - } - if !partners.is_empty() { - // A page still fading out would show between the panes. - if let Some((outgoing, _)) = self.page_fade.take() { - outgoing.set_visible(false); - } - for pane in &partners { - if let Some(view) = self.wake(*pane, cx) { - view.set_alpha(1.); - view.set_visible(!self.overlay_open()); - } - } - } - self.model.touch(&self.core, key, now()); - if !self.overlay_open() { - window.focus(&self.focus); - } - if switched { - self.layout_changed(); - if self.active_prompt().is_some() { - self.prepare_prompt(window, cx); - } - } - cx.notify(); - } - - /// The tab's view: this window's, else one taken over from another window, else a new one - /// that restores the tab's saved state or loads its page. - fn wake(&mut self, key: TabKey, cx: &mut Context) -> Option> { - if let Some(view) = self.views.get(&key).cloned().or_else(|| self.adopt_view(key, cx)) { - return Some(view); - } - let tab = self.model.tab(key).cloned()?; - self.create_view(key, &tab.url, cx).inspect(|view| { - let restorable = self.level_for(&tab.url).policy().save_interaction_state; - let saved = self.store(key.private).interaction_state(key.id).ok().flatten(); - // Windows saves Tarn's own format; anything else loads the tab's page instead. - let ours = |state: &&[u8]| !cfg!(windows) || engine::view_policy::SavedHistory::from_bytes(state).is_some(); - let url = Url::parse(&tab.url).ok(); - // A restored history is never an Open File (S6), so an opened file loads afresh. - let opened = url.as_ref().is_some_and(|u| self.opened_file(key, u)); - match saved.as_deref().filter(|state| !opened && restorable && !view.is_chromium() && ours(state)) { - Some(state) => view.restore_interaction_state(state), - None => { - if let Some(url) = url { - self.load_tab_url(key, view, url); - } - } - } - }) - } - - fn opened_file(&self, key: TabKey, url: &Url) -> bool { - self.pages.get(&key).and_then(|p| p.opened_file.as_ref()) == Some(url) - } - - fn load_tab_url(&self, key: TabKey, view: &WebView, url: Url) { - match self.link_loads.get(&key) { - _ if self.opened_file(key, &url) => view.load_file(&url), - // Says why a file tab no Open File vouches for stays empty. - _ if url.scheme() == "file" => view.load(&url), - _ if nav_policy::decide(&url, Source::Sync) != Decision::Allow => {} - Some(from) => view.load_link(&url, from.as_ref()), - None => view.load(&url), - } - } - - fn save_state(&self, key: TabKey) { - let Some(view) = self.views.get(&key) else { return }; - let url = view.url().map(String::from).unwrap_or_default(); - let state = self.level_for_tab(key, &url).policy().save_interaction_state.then(|| view.interaction_state()).flatten(); - self.store(key.private).set_interaction_state(key.id, state.as_deref()).ok(); - } - - /// Whether `key` still shows the view a request was sent to; tab ids are reused after a close. - pub(crate) fn same_view(&self, key: TabKey, asked: &std::rc::Weak) -> bool { - asked.upgrade().is_some_and(|v| self.views.get(&key).is_some_and(|live| Rc::ptr_eq(live, &v))) - } - - /// Drops this window's view of `key`, and the fade still showing it. - fn take_view(&mut self, key: TabKey) -> Option> { - self.typed_in.remove(&key); - self.forget_media(key); - let view = self.views.remove(&key)?; - if self.page_fade.as_ref().is_some_and(|(fading, _)| Rc::ptr_eq(fading, &view)) { - self.page_fade = None; - } - Some(view) - } - - pub(crate) fn hibernate(&mut self, key: TabKey, cx: &mut Context) { - self.save_state(key); - self.take_view(key); - self.json_pages.remove(&key); - self.drop_reader(key); - self.view_generation.remove(&key); - self.drop_prompts(key, cx); - self.model.lifecycle.remove(key); - if let Some(page) = self.pages.get_mut(&key) { - page.loading = false; - page.retry = None; - } - if self.model.active == Some(key) { - self.model.active = None; - } - } - - pub(crate) fn save_all(&self) { - for key in self.views.keys() { - self.save_state(*key); - } - } - - pub fn new_tab(&mut self, url: &Url, window: &mut Window, cx: &mut Context) { - self.new_tab_in(url, None, Opened::Typed, window, cx); - } - - /// A new tab whose `tabs.web_engine` is `web_engine`, as for a copy or a pop-up of a tab, - /// placed as `opened` says. - pub(crate) fn new_tab_in(&mut self, url: &Url, web_engine: Option, opened: Opened, window: &mut Window, cx: &mut Context) { - if self.model.burner_shown() - && let Some(key) = self.model.tabs.first().map(|t| self.model.key(t)) - { - self.activate(key, window, cx); - return self.navigate(url, window, cx); - } - let Some(key) = self.model.open_tab(&self.core, url.as_str(), web_engine.or(self.saved.web_engine), opened) else { return }; - self.reload_space(); - self.activate(key, window, cx); - } - - pub fn navigate(&mut self, url: &Url, window: &mut Window, cx: &mut Context) { - if let Some(key) = self.model.active { - self.link_loads.remove(&key); - self.pages.entry(key).or_default().retry = Some(url.clone()); - } - match (self.active_view(), self.model.active) { - (Some(view), Some(key)) if view.is_chromium() && self.level_for(url.as_str()) == ShieldLevel::Lockdown => self.rebuild_view(key, url, cx), - (Some(view), _) => view.load(url), - (None, Some(key)) => { - self.store(key.private).update_tab_page(key.id, url.as_str(), "").ok(); - self.reload_space(); - self.activate(key, window, cx); - } - (None, None) => self.new_tab(url, window, cx), - } - } - - pub fn close_tab(&mut self, key: TabKey, window: &mut Window, cx: &mut Context) { - self.close_tabs(vec![key], window, cx); - } - - /// Unloads a pinned tab, or closes an unpinned one and returns what reopening it needs. The - /// caller reloads the space and picks the next active tab. - fn close_one(&mut self, key: TabKey, cx: &mut Context) -> Option { - let tab = self.model.tab(key).cloned()?; - self.splits.leave(key); - if tab.kind != TabKind::Ephemeral { - self.hibernate(key, cx); - return None; - } - let closed = self.closed_tab(&tab, key); - self.tab_leaving(&tab, cx); - if !key.private { - self.core.tarn.borrow().send(crate::tarn_ext::Msg::TabClosed(key.id as u64)); - } - self.take_view(key); - self.link_loads.remove(&key); - self.json_pages.remove(&key); - self.drop_reader(key); - self.view_generation.remove(&key); - self.drop_prompts(key, cx); - self.model.lifecycle.remove(key); - self.pages.remove(&key); - self.store(key.private).delete_tab(key.id).ok(); - if self.model.active == Some(key) { - self.model.active = None; - } - Some(closed) - } - - pub(crate) fn pick_active(&mut self, window: &mut Window, cx: &mut Context) { - let adopting = self.adopting; - match self.model.pick(|k| Some(k) != adopting && crate::shared::live_elsewhere(k, cx)) { - Some(key) => self.activate(key, window, cx), - None => { - self.model.active = None; - cx.notify(); - } - } - } - - pub fn move_tab(&mut self, key: TabKey, kind: TabKind, folder: Option, index: usize, cx: &mut Context) { - if self.model.burner_shown() && kind != TabKind::Ephemeral { - return; - } - if self.store(key.private).move_tab(key.id, kind, folder, index).is_ok() { - self.reload_space(); - cx.notify(); - } - } - - /// The `n`th visible tab, counted from 1; 9 is the last, as in other browsers. - pub fn select_tab(&mut self, n: usize, window: &mut Window, cx: &mut Context) { - if let Some(key) = self.model.slot(n) { - self.switch_to(key, window, cx); - } - } - - pub fn cycle_tab(&mut self, forward: bool, window: &mut Window, cx: &mut Context) { - if let Some(key) = self.model.cycled(forward) { - self.switch_to(key, window, cx); - } - } - - /// A tab the user picks; an open address field or launcher closes so the tab shows. - pub fn switch_to(&mut self, key: TabKey, window: &mut Window, cx: &mut Context) { - if self.in_main(window, cx, move |b, window, cx| b.switch_to(key, window, cx)) { - return; - } - if self.command_mode.is_some() { - self.close_command(window, cx); - } - self.activate(key, window, cx); - } - - pub fn toggle_pin(&mut self, cx: &mut Context) { - if let Some(key) = self.model.active_tab().map(|t| self.model.key(t)) { - self.toggle_pin_tab(key, cx); - } - } - - pub fn new_folder(&mut self, parent: Option, window: &mut Window, cx: &mut Context) { - let Some(folder) = self.model.new_folder(&self.core, parent) else { return }; - self.reload_space(); - self.begin_rename(crate::groups::RenameTarget::Folder(folder.id), window, cx); - } - - pub fn move_folder(&mut self, id: Id, parent: Option, cx: &mut Context) { - if self.model.move_folder(&self.core, id, parent) { - self.reload_space(); - cx.notify(); - } - } - - pub fn toggle_folder(&mut self, id: Id, cx: &mut Context) { - self.model.toggle_folder(id); - cx.notify(); - } - - pub fn switch_space(&mut self, ix: usize, window: &mut Window, cx: &mut Context) { - if self.abandoned || ix >= self.model.spaces.len() || self.in_main(window, cx, move |b, window, cx| b.switch_space(ix, window, cx)) { - return; - } - let _span = (ix != self.model.space_ix).then(|| engine::startup::span(engine::startup::SPACE_SWITCH)).flatten(); - self.commit_rename(cx); - self.hide_hover_card(cx); - if self.command_mode.is_some() { - self.close_command(window, cx); - } - if let Some(view) = self.active_view() { - view.set_visible(false); - } - self.motion = Default::default(); - self.floating = Default::default(); - let burning = self.model.burner_shown(); - let Some((from, old)) = self.model.switch_space(&self.core, ix) else { return }; - self.motion.forget_pointer(); - if from != ix { - self.space_switched_at = Some(now()); - } - self.current_runtime(); - if self.responsive.is_some() && !self.devtools_on() { - self.set_responsive(None, cx); - } - self.space_shown(&[]); - self.slide_from(from, old); - self.pick_active(window, cx); - if burning && !self.model.burner_shown() { - self.burn(cx); - } - cx.notify(); - } - - pub fn open_private_space(&mut self, window: &mut Window, cx: &mut Context) { - if let Some(ix) = self.model.private_space(&self.core) { - self.switch_space(ix, window, cx); - } - } - - pub fn open_command(&mut self, mode: CommandMode, window: &mut Window, cx: &mut Context) { - if self.in_main(window, cx, move |b, window, cx| b.open_command(mode, window, cx)) { - return; - } - self.new_tab_group = None; - self.overlay_exit = None; - self.shortcuts_open = false; - let text = match mode { - CommandMode::Current => { - self.active_view().and_then(|v| v.url()).map(String::from).or_else(|| self.model.active_tab().map(|t| t.url.clone())).unwrap_or_default() - } - CommandMode::NewTab | CommandMode::FindInTabs | CommandMode::Snippets => String::new(), - }; - let placeholder = match mode { - CommandMode::FindInTabs => "Find in this space's tabs", - CommandMode::Snippets => "Insert a snippet", - _ => "Search or enter address", - }; - let private = self.model.private(); - self.history_cache = self.model.current_space().map(|s| s.space.profile_id).and_then(|p| self.store(private).history(p, 2000).ok()).unwrap_or_default(); - self.history_text = None; - self.command_mode = Some(mode); - if self.devtools_on() { - self.refresh_local_servers(cx); - } - self.command.update(cx, |input, cx| { - input.set_placeholder(placeholder); - input.set_text(text, cx); - }); - if self.model.active.is_some() && !self.profile_editor.as_ref().is_some_and(|e| !e.floating) { - self.open_inline(window, cx); - } else if let Some(view) = self.active_view() { - view.set_visible(false); - } - if let Some(host) = &self.host { - host.focus(); - } - let focus = self.command.focus_handle(cx); - window.focus(&focus); - self.update_suggestions(cx); - cx.notify(); - } - - /// F6 and Shift+F6: moves the keyboard between the page, the address field and the sidebar. - pub(crate) fn cycle_focus(&mut self, back: bool, window: &mut Window, cx: &mut Context) { - use browser_core::focus::{Region, next_region}; - let open = self.command_mode.is_some(); - let from = if open { - Region::Address - } else if self.focus.is_focused(window) { - Region::Page - } else { - Region::Sidebar - }; - match next_region(from, back, self.active_view().is_some(), self.sidebar_shown() > 0.) { - Region::Address => self.open_command(CommandMode::Current, window, cx), - Region::Page if open => self.close_command(window, cx), - Region::Page => { - window.focus(&self.focus); - if let Some(view) = self.active_view() { - view.focus(); - } - } - Region::Sidebar => { - if open { - self.close_command(window, cx); - } - if let Some(host) = &self.host { - host.focus(); - } - window.focus(&self.focus); - window.focus_next(); - } - } - } - - pub fn close_command(&mut self, window: &mut Window, cx: &mut Context) { - let field = self.command_mode.is_some(); - let covered = field || self.shortcuts_open; - self.launcher_from = None; - self.actions_page = None; - self.rejected = 0; - self.close_inline(cx); - self.overlay_exit = None; - self.command_mode = None; - self.history_text_search = None; - self.profile_editor = None; - self.shortcuts_open = false; - self.reader = self.reader.take().filter(|r| field || crate::reader::keeps_reader(covered, r.speaking())); - window.focus(&self.focus); - for key in self.model.active.and_then(|a| Some(self.splits.of(a)?.others(a))).unwrap_or_default() { - if let Some(view) = self.views.get(&key) { - view.set_visible(true); - } - } - if let Some(view) = self.active_view().filter(|_| !self.overlay_open()) { - view.set_visible(true); - view.focus(); - } - self.layout_changed(); - self.prepare_prompt(window, cx); - cx.notify(); - } - - /// The command card and profile editor replace the page, so the native web view is hidden under - /// them; the address field opened in the toolbar leaves it visible. - pub fn overlay_open(&self) -> bool { - self.card_open() || self.reader_shown() - } - - /// An overlay other than the reader. - pub(crate) fn card_open(&self) -> bool { - (self.command_mode.is_some() && !self.inline_editing()) || self.profile_editor.as_ref().is_some_and(|e| !e.floating) || self.shortcuts_open - } - - pub(crate) fn reader_shown(&self) -> bool { - self.reader.as_ref().is_some_and(|r| self.model.active == Some(r.key)) - } - - pub(crate) fn select_suggestion(&mut self, forward: bool, cx: &mut Context) { - self.select_suggestion_at(suggest::step_selection(self.selected, self.suggestions.len(), forward), cx); - } - - pub(crate) fn select_suggestion_at(&mut self, ix: usize, cx: &mut Context) { - self.selected = ix.min(self.suggestions.len().saturating_sub(1)); - self.suggestions_scroll.scroll_to_item(self.selected); - cx.notify(); - } - - /// Tab, Page Up and Page Down move the highlight in the field's suggestion list. - pub(crate) fn suggestion_key(&mut self, event: &gpui::KeyDownEvent, cx: &mut Context) { - let last = self.suggestions.len().saturating_sub(1); - match event.keystroke.key.as_str() { - "tab" => self.select_suggestion(!event.keystroke.modifiers.shift, cx), - "pageup" => self.select_suggestion_at(0, cx), - "pagedown" => self.select_suggestion_at(last, cx), - _ => return, - } - cx.stop_propagation(); - } - - fn on_command_event(&mut self, _: &Entity, event: &TextInputEvent, window: &mut Window, cx: &mut Context) { - match event { - TextInputEvent::Changed => { - self.rejected = 0; - if self.command_mode != Some(CommandMode::Snippets) { - self.expand_snippet(cx); - } - self.update_suggestions(cx) - } - TextInputEvent::Submit => self.submit_command(self.selected, window, cx), - TextInputEvent::Cancel if self.actions_page.is_some() => self.leave_actions(cx), - TextInputEvent::Cancel => self.dismiss_overlay(window, cx), - TextInputEvent::PastEnd => self.open_actions(self.selected, cx), - TextInputEvent::Up => self.select_suggestion(false, cx), - TextInputEvent::Down => self.select_suggestion(true, cx), - TextInputEvent::MenuClosed if !window.is_window_active() && self.inline_editing() => self.close_command(window, cx), - TextInputEvent::MenuClosed => {} - } - } - - /// "Switch to" and "Move Tab to" rows for the other spaces, ranked like the command table. - fn space_commands(&self, query: &str) -> Vec { - let mut rows: Vec<(String, Box)> = Vec::new(); - for (ix, s) in self.model.spaces.iter().enumerate().filter(|(ix, _)| *ix != self.model.space_ix) { - rows.push((format!("Switch to {}", ui::text::bounded_title(&s.space.name)), Box::new(crate::menubar::SwitchToSpace { ix }))); - } - if let Some(key) = self.model.active { - for ix in self.model.move_targets(&self.core, key) { - let name = ui::text::bounded_title(&self.model.spaces[ix].space.name); - rows.push((format!("Move Tab to {name}"), Box::new(crate::menubar::MoveToSpace { ix }))); - } - } - command::rank_commands(query, rows.iter().map(|(label, _)| (label.as_str(), "space workspace"))) - .into_iter() - .map(|ix| Suggestion { section: None, label: rows[ix].0.clone(), detail: String::new(), target: Target::Action(rows[ix].1.boxed_clone()) }) - .collect() - } - - fn update_suggestions(&mut self, cx: &mut Context) { - self.suggest(None, cx); - } - - /// What an actions page can act on for a row, if anything. - pub(crate) fn row_item(&self, s: &Suggestion) -> Option { - use browser_core::command::Section; - match &s.target { - Target::Tab(key) | Target::Find(key, _) => Some(Item::Tab(key.id)), - Target::Url(u) if s.section == Some(Section::Favorites) => Some(Item::Bookmark(u.to_string())), - Target::Url(u) => Some(Item::History(u.to_string())), - Target::Input(Input::Command(ix)) => browser_core::palette::COMMANDS.get(*ix).map(|c| Item::Command(c.2)), - _ => None, - } - } - - /// Lists the actions of row `ix` in place of the rows; Esc goes back to them. - pub(crate) fn open_actions(&mut self, ix: usize, cx: &mut Context) { - if !matches!(self.command_mode, Some(CommandMode::NewTab | CommandMode::Current)) || self.actions_page.is_some() { - return; - } - let Some((row, item)) = self.suggestions.get(ix).and_then(|s| Some((s, self.row_item(s)?))) else { return }; - let title = row.label.clone(); - let spaces: Vec = match item { - Item::Tab(id) => { - let key = TabKey { private: self.model.private(), id }; - self.model.move_targets(&self.core, key).into_iter().map(|ix| self.model.spaces[ix].space.name.clone()).collect() - } - _ => Vec::new(), - }; - let names: Vec<&str> = spaces.iter().map(String::as_str).collect(); - let shortcut = match item { - Item::Command(c) => crate::command_action(c).map(|a| crate::shortcuts::shown(a, cx)).unwrap_or_default(), - _ => String::new(), - }; - self.suggestions = browser_core::palette::actions(&item, &names) - .into_iter() - .map(|(label, action)| { - let detail = if action == browser_core::palette::Action::Run { shortcut.clone() } else { String::new() }; - Suggestion { section: None, label, detail, target: Target::Act(item.clone(), action) } - }) - .collect(); - self.actions_page = Some((title, ix)); - self.select_suggestion_at(0, cx); - } - - pub(crate) fn leave_actions(&mut self, cx: &mut Context) { - let Some((_, back)) = self.actions_page.take() else { return }; - self.suggest(self.suggested.clone(), cx); - self.select_suggestion_at(back, cx); - } - - /// Runs an action of the actions page, mostly as the row it stands for would run. - fn run_action(&mut self, ix: usize, item: Item, action: browser_core::palette::Action, window: &mut Window, cx: &mut Context) { - use browser_core::palette::Action; - let private = self.model.private(); - let url = match &item { - Item::Tab(id) => self.tab_url(TabKey { private, id: *id }).map(|u| u.to_string()), - Item::Bookmark(u) | Item::History(u) => Some(u.clone()), - Item::Command(_) => None, - }; - let target = match (item, action) { - (Item::Command(c), Action::Run) => Target::Input(Input::Command(c.index())), - (Item::Tab(id), Action::Switch) => Target::Tab(TabKey { private, id }), - (Item::Tab(id), Action::Close) => { - self.close_command(window, cx); - return self.close_tab(TabKey { private, id }, window, cx); - } - (Item::Tab(id), Action::MoveToSpace(n)) => { - let key = TabKey { private, id }; - let Some(space) = self.model.move_targets(&self.core, key).get(n).copied() else { return }; - self.close_command(window, cx); - return self.move_to_space(key, space, window, cx); - } - (Item::History(u), Action::RemoveFromHistory) => { - self.remove_history_url(&u, cx); - self.actions_page = None; - return self.suggest(None, cx); - } - (_, Action::CopyLink) => match url { - Some(u) => Target::Copy(u), - None => return, - }, - (_, Action::OpenInNewTab) => { - self.command_mode = Some(CommandMode::NewTab); - match url.and_then(|u| Url::parse(&u).ok()) { - Some(u) => Target::Url(u), - None => return, - } - } - (_, Action::Open) => match url.and_then(|u| Url::parse(&u).ok()) { - Some(u) => Target::Url(u), - None => return, - }, - _ => return, - }; - self.actions_page = None; - self.suggestions[ix].target = target; - self.submit_command(ix, window, cx); - } - - pub(crate) fn refresh_open_suggestions(&mut self, cx: &mut Context) { - if self.command_mode.is_some() - && self.actions_page.is_none() - && let Some(again) = self.suggested.clone() - { - self.suggest(Some(again), cx); - } - } - - /// Builds the suggestions for the field's text, or `again` for the query and completion they - /// were last built for. - fn suggest(&mut self, again: Option<(String, Option)>, cx: &mut Context) { - let _span = - (again.is_none() && self.command_mode != Some(CommandMode::FindInTabs)).then(|| engine::startup::span(engine::startup::PALETTE_QUERY)).flatten(); - let rebuilt = again.is_some(); - if rebuilt && self.actions_page.is_some() { - return; - } - self.actions_page = None; - let (query, kept) = again.map_or_else(|| (self.command.read(cx).text().trim().to_owned(), None), |(q, c)| (q, Some(c))); - if !rebuilt { - (self.history_text_search, self.suggested) = (None, None); - } - match self.command_mode { - Some(CommandMode::FindInTabs) => return self.find_in_tabs(query, cx), - Some(CommandMode::Snippets) => return self.snippet_rows(&query, cx), - _ => {} - } - let mut out = Vec::new(); - let site = self.site(); - let tab = self.model.active_tab(); - let idle = |a: &dyn gpui::Action| self.idle(a); - let state = browser_core::palette::State { - pinned: tab.is_some_and(|t| t.kind != store::TabKind::Ephemeral), - split: self.model.active.is_some_and(|a| self.splits.contains(a)), - reopenable: !idle(&crate::ReopenClosedTab), - duplicates: !self.duplicate_tabs().is_empty(), - no_tab: tab.is_none(), - no_page: self.model.active.and_then(|k| self.tab_url(k)).is_none(), - private: self.model.private(), - muted: self.model.active.filter(|_| !idle(&crate::menubar::ToggleMute)).map(|k| self.tab_muted(k)), - custom_title: tab.is_some_and(|t| !t.custom_title.is_empty()), - renamable: tab.is_some(), - drifted: self.model.active.and_then(|k| self.pinned_drift(k)).is_some(), - sleep_others: true, - unpinned: !idle(&crate::CloseAllTabs), - loading: !idle(&crate::StopLoading), - toast: self.toast_command(), - reader: Some(self.reader_shown()), - developer: self.devtools_on(), - assistant: self.assistant_allowed(), - ..Default::default() - }; - let zappable = site.as_ref().is_some_and(|(k, u)| self.zappable(*k, u)); - let offered = |c: Command| { - crate::command_action(c).is_some() - && match c { - Command::ZapElement => zappable, - Command::SiteSettings => site.is_some(), - Command::ImportBrowserData => browser_core::import::available(), - _ => true, - } - }; - let mut commands: Vec<(String, Command)> = browser_core::palette::ranked(&query, &state, offered, &[]) - .into_iter() - .filter_map(|(label, row)| match row { - browser_core::palette::Row::Command(c) => Some((label, c)), - browser_core::palette::Row::Extra(_) => None, - }) - .collect(); - // Reading the switch target costs a profile and lock file read. - if commands.iter().any(|(_, c)| matches!(c, Command::ReloadInChromium | Command::ReloadInWebKit)) { - let to = self.model.active.and_then(|k| self.web_engine_switch(k)); - commands.retain(|(_, c)| match c { - Command::ReloadInChromium => to == Some(WebEngine::Chromium), - Command::ReloadInWebKit => to == Some(WebEngine::WebKit), - _ => true, - }); - } - let command = |(label, c): (String, Command)| { - let detail = crate::command_action(c).map(|a| crate::shortcuts::shown(a, cx)).unwrap_or_default(); - Suggestion { section: None, label, detail, target: Target::Input(Input::Command(c.index())) } - }; - if browser_core::palette::sectioned(&query) { - let private = self.model.private(); - let data = browser_core::palette::Data { - tabs: &self.model.tabs, - active: self.model.active.map(|k| k.id), - bookmarks: &self.bookmarks, - history: &self.history_cache, - now: now(), - }; - let mut out = Vec::new(); - for (section, entries) in browser_core::palette::sections(&state, offered, &data) { - for entry in entries { - let row = match entry.item { - Item::Command(c) => command((entry.label, c)), - Item::Tab(id) => Suggestion { section: None, label: entry.label, detail: entry.detail, target: Target::Tab(TabKey { private, id }) }, - Item::Bookmark(url) | Item::History(url) => { - let Ok(url) = Url::parse(&url) else { continue }; - Suggestion { section: None, label: entry.label, detail: entry.detail, target: Target::Url(url) } - } - }; - out.push(Suggestion { section: Some(section), ..row }); - } - } - self.suggestions = out; - self.selected = usize::MAX; - self.suggested = Some((query, None)); - cx.notify(); - return; - } - let space_rows = self.space_commands(&query); - if query.starts_with('>') { - self.suggestions = commands.into_iter().map(command).chain(space_rows).collect(); - self.select_suggestion_at(0, cx); - return; - } - let shortcuts = self.pref(crate::prefs::Pref::SearchShortcuts); - let default = &command::ENGINES[self.search_engine()]; - let engine = command::search_engine(&query, default, shortcuts); - let input = command::classify_input(&query, default, shortcuts); - if let Some(Input::Navigate(u)) = &input { - out.extend(self.open_tabs_at(&self.clean_user_url(u.clone()))); - } - let exact = commands.first().is_some_and(|(label, c)| label.eq_ignore_ascii_case(&query) || c.label().eq_ignore_ascii_case(&query)); - if exact { - out.extend(commands.iter().cloned().map(command)); - } - if let Some(input) = input { - let (label, detail) = match &input { - Input::Navigate(u) => (u.to_string(), "Open".to_owned()), - Input::Search(_) => (query.clone(), format!("Search {}", engine.name)), - Input::External(u) => (u.to_string(), format!("Open in another app ({})", u.scheme())), - Input::Rejected => (query.clone(), "This kind of address cannot be opened".to_owned()), - Input::Command(_) => unreachable!("classify_input never names a command"), - }; - out.push(Suggestion { section: None, label, detail, target: Target::Input(input) }); - } - if !exact { - out.extend(commands.into_iter().map(command)); - } - out.extend(space_rows); - let suggest_on = self.pref(crate::prefs::Pref::Suggestions); - let private = self.model.private(); - let tabs = &self.model.tabs; - let mut pages: Vec = tabs.iter().map(Page::from).collect(); - if !query.is_empty() { - pages.extend(self.history_cache.iter().map(Page::from)); - } - let field = self.command.read(cx); - let completion = kept.unwrap_or_else(|| { - (suggest_on && !exact && suggest::may_complete(field.text(), field.inserted(), field.caret_at_end())) - .then(|| suggest::inline_completion(&query, &pages, now())) - .flatten() - }); - if let Some(c) = &completion { - let shown = format!("{query}{}", c.suffix); - // Enter opens the visited page the field completes to, or the tab already showing it. - let (target, detail) = match tabs.iter().find(|t| t.url == c.url.as_str() && self.model.active != Some(TabKey { private, id: t.id })) { - Some(t) => (Target::Tab(TabKey { private, id: t.id }), "Switch to Tab".to_owned()), - None => { - let detail = self.clean_user_url(c.url.clone()).as_str().trim_start_matches("https://").trim_end_matches('/').to_owned(); - (Target::Input(Input::Navigate(c.url.clone())), detail) - } - }; - out.insert(0, Suggestion { section: None, label: ui::text::bounded_url(&shown), detail: ui::text::bounded_url(&detail), target }); - } - let answers = browser_core::palette::answers(&query); - let answered = answers.len(); - out.splice( - 0..0, - answers.into_iter().map(|a| Suggestion { - section: None, - label: a.label, - detail: browser_core::palette::ANSWER_DETAIL.to_owned(), - target: Target::Copy(a.copy), - }), - ); - let typed = out.len(); - let listed: HashSet = out.iter().filter_map(|s| if let Target::Tab(k) = s.target { Some(k) } else { None }).collect(); - let completed = completion.as_ref().map(|c| c.url.as_str()); - let skip = |ix: usize| { - if ix < tabs.len() { - let key = TabKey { private, id: tabs[ix].id }; - listed.contains(&key) || self.model.active == Some(key) - } else { - Some(pages[ix].url) == completed - } - }; - let mut ranked: Vec = suggest::rank_rows(&query, &pages, tabs.len(), skip, now()); - let search_text = !private && suggest::searches_text(&query) && suggest_on && self.pref(crate::prefs::Pref::HistoryText); - let text_profile = self.model.current_space().filter(|_| search_text).map(|s| s.space.profile_id); - let cached = self.history_text.as_ref().filter(|(p, q, _)| Some(*p) == text_profile && *q == query).map(|(_, _, found)| found.clone()); - let search_later = text_profile.filter(|_| cached.is_none()); - let found = cached.unwrap_or_default(); - // Text matches get up to half the room left; a page in both lists shows once, where it ranks if it stays there. - let room = MAX_SUGGESTIONS.saturating_sub(out.len()); - let open: HashSet<&str> = tabs.iter().map(|t| t.url.as_str()).collect(); - let found: Vec<&HistoryEntry> = found.iter().filter(|f| !open.contains(f.url.as_str()) && Some(f.url.as_str()) != completed).collect(); - let top = &ranked[..ranked.len().min(room)]; - let extra = found.iter().filter(|f| !top.iter().any(|&ix| pages[ix].url == f.url)).count(); - ranked.truncate(room - extra.min(room / 2)); - let mut found: Vec<&HistoryEntry> = found.into_iter().filter(|f| !ranked.iter().any(|&ix| pages[ix].url == f.url)).collect(); - found.truncate(room - ranked.len()); - let history_row = |url: &str, title: &str| { - Url::parse(url).ok().map(|target| Suggestion { - section: None, - label: ui::text::bounded_title(if title.is_empty() { url } else { title }), - detail: ui::text::bounded_url(url.trim_start_matches("https://").trim_end_matches('/')), - target: Target::Url(target), - }) - }; - for ix in ranked { - let page = pages[ix]; - if ix < tabs.len() { - out.push(Suggestion { - section: None, - label: ui::text::bounded_title(if page.title.is_empty() { page.url } else { page.title }), - detail: "Switch to Tab".to_owned(), - target: Target::Tab(TabKey { private, id: tabs[ix].id }), - }); - } else { - out.extend(history_row(page.url, page.title)); - } - } - out.extend(found.into_iter().filter_map(|h| history_row(&h.url, &h.title))); - out.truncate(if suggest_on { MAX_SUGGESTIONS } else { typed }); - // Late text matches move rows; the highlight stays on the row the user chose, if it is still listed. - // An empty field highlights nothing, so Enter opens nothing until the user picks a row. - let chosen = self.suggestions.get(self.selected).filter(|_| rebuilt).map(|s| (s.label.clone(), s.detail.clone())); - self.suggestions = out; - let first = if query.is_empty() { None } else { browser_core::palette::default_row(answered, self.suggestions.len()) }.unwrap_or(usize::MAX); - self.selected = chosen.and_then(|(label, detail)| self.suggestions.iter().position(|s| s.label == label && s.detail == detail)).unwrap_or(first); - self.suggested = Some((query.clone(), completion.clone())); - self.history_text_search = search_later.map(|profile| self.search_history_text_later(profile, query, cx)); - if let (Some(c), false) = (completion, rebuilt) { - self.command.update(cx, |input, cx| input.append_selected(&c.suffix, cx)); - } - cx.notify(); - } - - pub(crate) fn forget_text_matches(&mut self) { - (self.history_text, self.history_text_search) = (None, None); - } - - fn search_history_text_later(&self, profile: Id, query: String, cx: &mut Context) -> Task<()> { - cx.spawn(async move |this, cx| { - cx.background_executor().timer(suggest::TEXT_SEARCH_DELAY).await; - this.update(cx, |b, cx| { - let found = b.core.disk.search_history_text(profile, &query, MAX_TEXT_MATCHES).unwrap_or_default(); - b.history_text = Some((profile, query.clone(), found)); - if b.command_mode.is_some() - && let Some(again) = b.suggested.clone().filter(|(q, _)| *q == query) - { - b.suggest(Some(again), cx); - } - }) - .ok(); - }) - } - - pub fn submit_command(&mut self, ix: usize, window: &mut Window, cx: &mut Context) { - let Some(mode) = self.command_mode else { return }; - let Some(suggestion) = self.suggestions.get(ix) else { return }; - // A search's results page is not an address the user typed, so it earns no completion credit. - let credit = !matches!(suggestion.target, Target::Input(Input::Search(_))); - let url = match &suggestion.target { - Target::Tab(key) => { - let key = *key; - self.close_command(window, cx); - if self.model.tab(key).is_none() - && let Ok(tab) = self.store(key.private).tab(key.id) - && let Some(ix) = self.model.spaces.iter().position(|s| s.private == key.private && s.space.id == tab.space_id) - { - self.switch_space(ix, window, cx); - } - self.activate(key, window, cx); - return; - } - Target::Find(key, query) => { - let (key, query) = (*key, query.clone()); - self.close_command(window, cx); - return self.open_text_match(key, query, window, cx); - } - Target::Input(Input::Command(ix)) => { - let Some((name, action)) = browser_core::palette::COMMANDS.get(*ix).and_then(|c| Some((c.0, crate::command_action(c.2)?))) else { return }; - let keys = crate::shortcuts::shown(action, cx); - self.close_command(window, cx); - window.dispatch_action(action.boxed_clone(), cx); - cx.defer_in(window, move |b, window, cx| b.offer_hint(name, &keys, window, cx)); - return; - } - Target::Action(action) => { - let action = action.boxed_clone(); - self.close_command(window, cx); - window.dispatch_action(action, cx); - return; - } - Target::Snippet(body) => { - let body = body.clone(); - self.close_command(window, cx); - return self.type_snippet(&body, cx); - } - Target::Act(item, action) => { - let (item, action) = (item.clone(), *action); - return self.run_action(ix, item, action, window, cx); - } - Target::Copy(text) => { - cx.write_to_clipboard(gpui::ClipboardItem::new_string(text.clone())); - self.close_command(window, cx); - return self.show_toast_as(browser_core::toast::Tone::Success, "Copied", None, cx); - } - Target::Url(u) => u.clone(), - Target::Input(Input::Navigate(u)) => self.clean_user_load(u.clone(), cx), - Target::Input(Input::Search(u)) => u.clone(), - Target::Input(Input::External(u)) => { - self.pending_external = Some(PendingExternal { tab: None, origin: None, url: u.clone() }); - self.layout_changed(); - self.close_command(window, cx); - return; - } - Target::Input(Input::Rejected) => { - self.rejected += 1; - return cx.notify(); - } - }; - let group = self.new_tab_group.take(); - self.close_command(window, cx); - match mode { - CommandMode::NewTab => { - let before = self.model.active; - let routed = self.open_routed(&url, window, cx); - if !routed { - self.new_tab(&url, window, cx); - if credit && self.model.active != before { - self.mark_typed(&url); - } - } - if let Some((key, group)) = self.model.active.filter(|k| !routed && Some(*k) != before).zip(group) { - self.set_tab_group(key, Some(group), cx); - } - } - CommandMode::Current | CommandMode::FindInTabs | CommandMode::Snippets => { - self.navigate(&url, window, cx); - if credit { - self.mark_typed(&url); - } - } - } - } - - pub(crate) fn mark_typed(&mut self, url: &Url) { - if let Some(key) = self.model.active { - self.pages.entry(key).or_default().typed = Some(url.to_string()); - } - } - - /// "Switch to Tab" rows for open tabs showing `url`: the current space's first, then other - /// spaces of the same profile and privacy, named in the detail. - fn open_tabs_at(&self, url: &Url) -> Vec { - self.model - .tabs_showing(&self.core, url) - .into_iter() - .map(|(key, t, space)| Suggestion { - section: None, - label: ui::text::bounded_title(if t.title.is_empty() { &t.url } else { &t.title }), - detail: browser_core::tabs::switch_detail(space.as_deref()), - target: Target::Tab(key), - }) - .collect() - } - - pub fn resolve_external(&mut self, open: bool, cx: &mut Context) { - if open && (self.pending_external.is_none() || !self.layout_stable()) { - return; - } - if let Some(pending) = self.pending_external.take() - && open - { - engine::open_external(&pending.url); - } - cx.notify(); - } - - pub fn dismiss_error(&mut self, cx: &mut Context) { - if let Some(page) = self.model.active.and_then(|k| self.pages.get_mut(&k)) { - page.error = None; - page.notice = None; - page.offer = None; - } - cx.notify(); - } - - fn on_event(&mut self, key: TabKey, event: Event, window: &mut Window, cx: &mut Context) { - // A local-network refusal is counted once, as `Event::Protected`. - match &event { - Event::Blocked { category: Some(_), .. } => self.count_on_page(key, Counter::ListedStopped, cx), - Event::PopupBlocked(url) if !url.as_ref().is_some_and(shield::rules::local_target) => self.count_on_page(key, Counter::PopupsBlocked, cx), - _ => {} - } - match event { - Event::Loading(on) => self.pages.entry(key).or_default().loading = on, - Event::LinkHovered(link) => return self.link_hovered(key, link.as_deref(), cx), - Event::AssistantSelection(command) => return self.ask_selection(key, command, cx), - Event::Committed { url, title, can_go_back, can_go_forward } => { - self.link_hovered(key, None, cx); - engine::startup::mark("first page commit"); - // A link stays the page's until it shows a page: a view slept or never made loads it as a link again. - if url.as_str() != "about:blank" { - self.link_loads.remove(&key); - self.pages.entry(key).or_default().retry = None; - } - self.drop_prompts(key, cx); - self.tarn_committed(key, &url, window, cx); - self.json_pages.remove(&key); - let previous = self.store(key.private).tab(key.id).ok().and_then(|t| tab_host(&t.url)); - self.page_changed(key, &url, &title, can_go_back, can_go_forward, true); - self.sync_assistant_menu(key); - // An Open Anyway offer belongs to the page that was refused, not to the next one; the - // blank document a new view starts with is no page. - if let Some(page) = self.pages.get_mut(&key).filter(|p| url.as_str() != "about:blank" && matches!(p.offer, Some(Offer::Open(_)))) { - (page.notice, page.offer) = (None, None); - } - let left_host = previous.as_deref() != url.host_str(); - self.apply_site_zoom(key, Some(&url), left_host); - self.apply_site_mute(key, &url, left_host); - let page = self.pages.entry(key).or_default(); - page.blocked = None; - page.visit = None; - (page.local_counted, page.https_counted) = (false, false); - self.forget_article(key, window, cx); - let unfiltered = self.views.get(&key).is_some_and(|v| !v.is_chromium() && !v.filtered()); - if unfiltered && !crate::blocking::site_host(&url).is_some_and(|h| self.site_paused_in(key, h)) { - let message = "Ad, tracker and cookie-banner blocking is off in this tab since it left a site where you paused it.".to_owned(); - self.notify_offer(key, message, Some(Offer::Reload)); - } - } - Event::Finished { url, title, can_go_back, can_go_forward } => { - self.page_changed(key, &url, &title, can_go_back, can_go_forward, false); - let page = self.pages.entry(key).or_default(); - page.crashed = false; - if let Some((_, offset)) = page.scroll_back.take().filter(|(slept, _)| slept == url.as_str()) - && let Some(view) = self.views.get(&key) - { - view.scroll_to(offset); - } - let typed = suggest::typed_visit(&mut page.typed, url.as_str()); - self.record_visit(key, &url, &title, typed); - self.request_page_text(key, &url); - self.request_favicon(key, &url); - #[cfg(feature = "translation")] - self.offer_translation(key, &url, cx); - self.probe_article(key, &url); - self.save_state(key); - self.after_load_devtools(key, &url); - if self.find_after_load.take_if(|k| *k == key).is_some() && self.find_open && self.model.active == Some(key) { - self.find(false, cx); - } - } - Event::Blocked { url, message, category } => { - suggest::typed_visit(&mut self.pages.entry(key).or_default().typed, url.as_str()); - match category { - Some(category) if category.warns() => self.show_blocked(key, url, category), - Some(_) => self.notify_offer(key, message, Some(Offer::Open(url))), - // Open Anyway loads it as the user's own navigation, which S10 lets through; the - // notice names the address, since the page chose it. - None if message == nav_policy::LOCAL_NETWORK_BLOCKED => match nav_policy::open_anyway_notice(&url) { - Some(notice) => self.notify_offer(key, notice, Some(Offer::Open(url))), - None => self.notify_offer(key, message, None), - }, - None => self.notify_offer(key, message, None), - } - } - Event::StoreInstall(id) => self.store_link(key, id, window, cx), - Event::PopupBlocked(url) => { - let message = nav_policy::popup_blocked_notice(url.as_ref()); - let offer = url.filter(|u| nav_policy::decide(u, Source::Typed) == Decision::Allow).map(Offer::NewTab); - self.notify_offer(key, message, offer); - } - Event::PopupOffered(url) => { - let message = nav_policy::popup_blocked_notice(Some(&url)); - let offer = (nav_policy::decide(&url, Source::Typed) == Decision::Allow).then_some(Offer::NewTab(url)); - self.notify_offer(key, message, offer); - } - Event::WebEngineOutdated => { - #[cfg(any(feature = "chromium", windows))] - crate::shared::check_chromium(cx); - #[cfg(windows)] - if let Some(message) = self.chromium_closed() { - self.notify_offer(key, message.to_owned(), None); - } - } - Event::WebEngineRequired(url) => { - let host = |u: &Url| ui::text::bounded_origin(u.host_str().unwrap_or_default()); - let target = host(&url); - let message = match self.views.get(&key).and_then(|v| v.url()).filter(|u| u.host_str().is_some()) { - Some(from) => format!("{} asked to open {target}. This site is set to Lockdown and opens in WebKit.", host(&from)), - None => format!("{target} is set to Lockdown and opens in WebKit."), - }; - self.notify_offer(key, message, Some(Offer::WebKit(url))); - } - Event::Failed { url, code, message } => { - // The latches stay: a page can make a load fail at will while it keeps showing, and an - // undercount after a failed upgrade beats a counter a page can run up. - let page = self.pages.entry(key).or_default(); - page.loading = false; - if let Some(url) = url { - suggest::typed_visit(&mut page.typed, url.as_str()); - } - if !IGNORED_LOAD_ERRORS.contains(&code) { - page.error = Some(message); - } - } - Event::TitleChanged(title) => { - self.store(key.private).set_tab_title(key.id, &title).ok(); - // WebKit can report an empty title for the outgoing page just before the next one commits. - if let (false, Some(profile_id), Some((visit, url))) = - (title.is_empty(), self.profile_of(key), self.pages.get(&key).and_then(|p| p.visit.clone())) - { - self.store(key.private).retitle_visit(profile_id, visit, &url, &title).ok(); - } - if self.private_matches(key) - && let Some(t) = self.model.tabs.iter_mut().find(|t| t.id == key.id) - { - t.title = title; - } - } - Event::UrlChanged { url, can_go_back, can_go_forward } => { - let page = self.pages.entry(key).or_default(); - page.can_back = can_go_back; - page.can_forward = can_go_forward; - if let Ok(tab) = self.store(key.private).tab(key.id) - && tab.url != url.as_str() - && nav_policy::decide(&url, Source::Link) == Decision::Allow - { - self.store(key.private).update_tab_page(key.id, url.as_str(), &tab.title).ok(); - if self.private_matches(key) - && let Some(t) = self.model.tabs.iter_mut().find(|t| t.id == key.id) - { - t.url = url.to_string(); - } - // A same-document navigation (pushState) is a visit like a page load, but pages - // rewrite their URL constantly (maps, anchors, search as you type): fragment - // changes, very long URLs and more than one visit per tab per interval are not - // recorded. - let mut previous = Url::parse(&tab.url).ok(); - if let Some(p) = previous.as_mut() { - p.set_fragment(None); - } - let mut target = url.clone(); - target.set_fragment(None); - // A page that rewrites its own address shows another article, or none; it is asked - // again once it has had a moment to render, as no load finishes to tell. - if previous.as_ref() != Some(&target) { - self.forget_article(key, window, cx); - let url = url.clone(); - cx.spawn(async move |this, cx| { - cx.background_executor().timer(std::time::Duration::from_secs(1)).await; - this.update(cx, |b, _| { - if b.views.get(&key).and_then(|v| v.url()).as_ref() == Some(&url) { - b.probe_article(key, &url); - } - }) - .ok(); - }) - .detach(); - } - let page = self.pages.entry(key).or_default(); - let due = page.last_visit.is_none_or(|at| at.elapsed() >= SAME_DOCUMENT_VISIT_INTERVAL); - if previous.as_ref() != Some(&target) && url.as_str().len() <= MAX_SAME_DOCUMENT_URL && due { - page.last_visit = Some(Instant::now()); - self.record_visit(key, &url, &tab.title, false); - } else { - page.visit = None; - } - } - } - Event::Prompt(prompt) => { - // A prompt shows with the shell's origin chip, never over a full-screen page. - if self.model.active == Some(key) { - self.leave_page_fullscreen(window); - } - self.queue_prompt(key, prompt, window, cx); - } - Event::Popup(popup) => self.adopt_popup(key, popup, window, cx), - Event::ShieldLevelChanged(url) => self.rebuild_view(key, &url, cx), - Event::RebuildForLink(url) => self.rebuild_view_for_link(key, &url, cx), - Event::PeekLink(url, from) => { - if self.model.active == Some(key) { - self.open_link_peek(key, url, from, window, cx); - } - } - // As a pop-up's tab: never in the burner, and its first load is the page's link, so S10 judges every hop. - Event::OpenTab { url, from, background, split } => { - let Some(opener) = self.model.tab(key).filter(|_| !self.model.burner_shown()) else { return cx.notify() }; - let engine = opener.web_engine.or(self.saved.web_engine); - let routed = self.routed_space(&url); - if let Some(ix) = routed { - self.switch_space(ix, window, cx); - } - if let Some(tab) = self.model.open_tab(&self.core, url.as_str(), engine, Opened::Link(key)) { - self.reload_space(); - self.link_loads.insert(tab, from.clone()); - if split && routed.is_none() { - self.split_link(key, tab, window, cx); - } else if !background || routed.is_some() { - self.activate(tab, window, cx); - } else if let Some(view) = self.create_view(tab, url.as_str(), cx) { - // Loaded now, as a pop-up is: a tab restored later would load its URL as the user's own. - view.set_visible(false); - view.load_link(&url, from.as_ref()); - } - } - } - Event::ExternalScheme { url, origin } => { - let showing = self.pending_external.as_ref().is_some_and(|p| p.tab.is_none_or(|t| t == key)); - if self.model.active == Some(key) && !showing { - self.pending_external = Some(PendingExternal { tab: Some(key), origin, url }); - self.layout_changed(); - } - } - event @ (Event::DownloadFinished { .. } - | Event::DownloadFailed { .. } - | Event::DownloadCancelled(_) - | Event::DownloadsActive(_) - | Event::DownloadProgress { .. }) => { - if let Some(profile_id) = self.profile_of(key) { - self.core.downloads.unbounded_send((key.private, profile_id, event)).ok(); - } - return; - } - Event::Protected(protection, target) => { - let page = self.pages.entry(key).or_default(); - let (latch, counter) = match protection { - engine::Protection::HttpsUpgrade => (&mut page.https_counted, Counter::HttpsUpgrades), - engine::Protection::LocalNetwork => (&mut page.local_counted, Counter::LocalBlocked), - }; - let counter = (!std::mem::replace(latch, true)).then_some(counter); - // An upgrade is the upgraded site's; a refusal is the page's that tried it, unless the - // tab shows nothing but the refused address (a link from another app). - let page = self.tab_url(key).and_then(|u| Url::parse(&u).ok()).filter(|u| !shield::rules::local_target(u)); - let host = target.or_else(|| page.as_ref().and_then(page_host)); - if let (Some(counter), Some(profile_id)) = (counter, self.profile_of(key)) { - self.count_shield(key.private, profile_id, counter, 1, host.as_deref(), cx); - } - } - Event::FullScreen(on) => self.set_page_fullscreen(key, on, window), - Event::ExtensionMessage { world, frame, origin, json } => { - if let Some(profile) = self.profile_of(key).filter(|_| !key.private) { - self.core.tarn.borrow().send(crate::tarn_ext::Msg::Tab { profile, tab: key.id as u64, world, frame, origin, json }); - } - } - Event::ContentProcessTerminated => { - self.link_hovered(key, None, cx); - if self.model.active == Some(key) { - self.leave_page_fullscreen(window); - } - self.drop_prompts(key, cx); - let page = self.pages.entry(key).or_default(); - if page.crashed { - page.loading = false; - page.error = Some("The page crashed again and was not reloaded.".into()); - } else if let Some(view) = self.views.get(&key) { - page.crashed = true; - view.recover(); - } - } - } - cx.notify(); - } - - /// The active tab's page alone fills the window, in full screen, while it shows an element - /// full screen; leaving restores the window as it was. - fn set_page_fullscreen(&mut self, key: TabKey, on: bool, window: &mut Window) { - if self.model.active != Some(key) { - return; - } - if !on { - return self.leave_page_fullscreen(window); - } - let Some(view) = self.views.get(&key).cloned() else { return }; - // Nothing the shell must show may be hidden: a pending prompt keeps the toolbar and its origin. - let Some(entered) = self.page_fullscreen.enter(self.active_prompt().is_some(), window.is_fullscreen()) else { return }; - if entered { - window.toggle_fullscreen(); - } - view.set_corner_radius(0.); - view.raise(); - self.layout_changed(); - } - - /// Whether the window may show the full-screen page alone: no prompt, overlay, address field, - /// find bar or notice of the shell waits to be seen, and the page is still the active one. - pub(crate) fn page_fullscreen_holds(&self) -> bool { - browser_core::fullscreen::Shell { - page: self.active_view().is_some(), - prompt: self.active_prompt().is_some(), - overlay: self.overlay_open(), - address: self.command_mode.is_some(), - find: self.find_open, - notice: self.model.active.and_then(|k| self.pages.get(&k)).is_some_and(|p| p.notice.is_some() || p.blocked.is_some()), - } - .lets_page_fill_window() - } - - /// Gives the window back its sidebar, toolbar and size: when the page leaves full screen, and - /// when a prompt, another tab or a crash needs the shell. The page itself may stay full screen - /// inside the tab until it is put away. - pub(crate) fn leave_page_fullscreen(&mut self, window: &mut Window) { - let Some(entered) = self.page_fullscreen.leave() else { return }; - if entered && window.is_fullscreen() { - window.toggle_fullscreen(); - } - if let Some(view) = self.active_view() { - view.set_corner_radius(page_corner()); - } - self.layout_changed(); - } - - fn record_visit(&mut self, key: TabKey, url: &Url, title: &str, typed: bool) { - if let Some(profile_id) = self.profile_of(key) - && matches!(url.scheme(), "http" | "https") - && self.core.keeps_records(key.private, profile_id) - { - let visit = self.store(key.private).add_history(profile_id, url.as_str(), title, now(), typed).ok().map(|id| (id, url.to_string())); - self.menu.visited(url.as_str()); - self.pages.entry(key).or_default().visit = visit; - } - } - - /// Only after a full load: a same-document visit would read the previous route's text. - fn request_page_text(&mut self, key: TabKey, url: &Url) { - let visit = self.pages.get(&key).and_then(|p| p.visit.clone()).filter(|(_, u)| u == url.as_str()); - let (Some(profile_id), Some((visit, page)), Some(view)) = (self.profile_of(key), visit, self.views.get(&key)) else { return }; - if key.private || !self.pref(crate::prefs::Pref::HistoryText) || self.level_for_tab(key, url.as_str()) == ShieldLevel::Lockdown { - return; - } - let events = self.events.clone(); - view.page_text(url, store::MAX_HISTORY_TEXT, move |_, text| { - events.unbounded_send(Msg::PageText(profile_id, visit, page.clone(), text)).ok(); - }); - } - - /// Only the disk store keeps page text, so the private space never does. - fn store_page_text(&mut self, profile_id: Id, visit: Id, url: &str, text: String) { - if text.is_empty() || !self.pref(crate::prefs::Pref::HistoryText) { - return; - } - self.core.disk.set_history_text(profile_id, visit, url, store::clip_history_text(&text)).ok(); - } - - /// Replaces the tab's view with one built for `url`'s Shield level and rules, then loads it. - pub(crate) fn rebuild_view(&mut self, key: TabKey, url: &Url, cx: &mut Context) { - self.rebuild_view_with(key, url, None, cx); - } - - /// Rebuilds the tab's view for a page's navigation, which the new view judges as the page's link. - fn rebuild_view_for_link(&mut self, key: TabKey, url: &Url, cx: &mut Context) { - let opener = self.link_loads.get(&key).cloned().unwrap_or_else(|| self.views.get(&key).and_then(|v| v.url())); - self.rebuild_view_loading(key, url, None, Some(opener), cx); - } - - /// Rebuilds the tab's view, handing `storage` to the new one before its first load. - pub(crate) fn rebuild_view_with(&mut self, key: TabKey, url: &Url, storage: Option, cx: &mut Context) { - self.rebuild_view_loading(key, url, storage, None, cx); - } - - /// With `link`, the URL loads as a link from that page (or from none), not as typed. - fn rebuild_view_loading(&mut self, key: TabKey, url: &Url, storage: Option, link: Option>, cx: &mut Context) { - if self.model.tab(key).is_some() && self.views.remove(&key).is_some() { - self.forget_media(key); - // The old view's last events are dropped; the new one says when its load starts. - let page = self.pages.entry(key).or_default(); - page.loading = false; - page.retry = link.is_none().then(|| url.clone()); - self.drop_prompts(key, cx); - let active = self.model.active == Some(key); - let visible = (active || self.in_split(key)) && !self.overlay_open(); - if let Some(view) = self.create_view(key, url.as_str(), cx) { - if let Some(storage) = storage { - view.hand_over(storage); - } - match &link { - None if self.pages.get(&key).and_then(|p| p.opened_file.as_ref()) == Some(url) => view.load_file(url), - Some(opener) => view.load_link(url, opener.as_ref()), - None => view.load(url), - } - view.set_visible(visible); - if visible && active { - view.focus(); - } - } - } - } - - fn site_paused_in(&self, key: TabKey, host: &str) -> bool { - self.profile_of(key).and_then(|p| self.loaded(key.private, p)).is_some_and(|rt| rt.rules.paused.borrow().contains(host)) - } - - /// Shield level for `url` under the profile that owns `key`, which may not be the current space's. - pub fn level_for_tab(&self, key: TabKey, url: &str) -> ShieldLevel { - self.profile_of(key).and_then(|p| self.core.level(key.private, p, Url::parse(url).ok().as_ref())).unwrap_or(ShieldLevel::Lockdown) - } - - pub(crate) fn queue_prompt(&mut self, key: TabKey, prompt: Prompt, window: &mut Window, cx: &mut Context) { - if !self.views.contains_key(&key) { - return; - } - if let Some(permission) = prompt.kind.permission_key() { - let page = prompt.top_origin.as_deref().unwrap_or(&prompt.origin); - let level = self.level_for_tab(key, page).max(self.level_for_tab(key, &prompt.origin)); - if level == ShieldLevel::Lockdown { - return; - } - let stored = (level == ShieldLevel::Standard).then(|| self.profile_of(key)).flatten().and_then(|p| { - self.store(key.private).permission(p, &permission_origin(&prompt.origin, prompt.top_origin.as_deref()), permission).ok().flatten() - }); - match stored.as_deref() { - Some("allow") => return prompt.accept("", None), - Some("deny") => return, - _ => {} - } - } - let queue = self.prompts.entry(key).or_default(); - if queue.len() >= MAX_QUEUED_PROMPTS { - return; - } - queue.push_back(prompt); - if queue.len() == 1 && self.model.active == Some(key) { - self.prepare_prompt(window, cx); - } - } - - /// Discards a tab's prompts (each declines on drop) and its external-app request, and clears what - /// the user typed into them. - fn drop_prompts(&mut self, key: TabKey, cx: &mut Context) { - if self.pending_external.as_ref().is_some_and(|p| p.tab == Some(key)) { - self.pending_external = None; - } - if self.prompts.remove(&key).is_none_or(|q| q.is_empty()) || self.model.active != Some(key) { - return; - } - for input in [&self.prompt_input, &self.auth_user, &self.auth_pass] { - input.update(cx, |i, cx| i.set_text("", cx)); - } - self.refocus = true; - if self.model.active == Some(key) - && let Some(view) = self.views.get(&key) - { - view.focus(); - } - } - - /// The find, prompt or command field has focus while the bar or card holding it is not drawn. - pub(crate) fn hidden_field_focused(&self, window: &Window, cx: &App) -> bool { - let focused = |input: &Entity| input.focus_handle(cx).is_focused(window); - let card = !self.overlay_open(); - (focused(&self.find_input) && !(card && self.find_open && self.active_json().is_none())) - || ([&self.prompt_input, &self.auth_user, &self.auth_pass].into_iter().any(focused) && !(card && self.active_prompt().is_some())) - || (focused(&self.command) && self.command_mode.is_none()) - } - - pub fn active_prompt(&self) -> Option<&Prompt> { - self.prompts.get(&self.model.active?)?.front() - } - - fn prepare_prompt(&mut self, window: &mut Window, cx: &mut Context) { - if self.overlay_open() { - return; - } - let Some(kind) = self.active_prompt().map(|p| p.kind.clone()) else { return }; - self.remember_permission = false; - self.layout_changed(); - if let Some(host) = &self.host { - host.focus(); - } - let focus = match kind { - PromptKind::Text { default } => { - self.prompt_input.update(cx, |i, cx| i.set_text(default, cx)); - self.prompt_input.focus_handle(cx) - } - PromptKind::Credentials { .. } => { - self.auth_user.update(cx, |i, cx| i.set_text("", cx)); - self.auth_pass.update(cx, |i, cx| i.set_text("", cx)); - self.auth_user.focus_handle(cx) - } - _ => self.focus.clone(), - }; - window.focus(&focus); - cx.notify(); - } - - pub fn answer_prompt(&mut self, accept: bool, silence: bool, window: &mut Window, cx: &mut Context) { - let Some(key) = self.model.active else { return }; - if accept && self.prompt_guarded() { - return; - } - let Some(prompt) = self.prompts.get_mut(&key).and_then(VecDeque::pop_front) else { return }; - let page = prompt.top_origin.clone().unwrap_or_else(|| prompt.origin.clone()); - if matches!(prompt.kind, PromptKind::ExtensionAccess { .. }) { - match (self.remember_permission, silence) { - (true, false) => prompt.remember(accept), - (false, false) if accept => prompt.accept("", None), - _ => prompt.decline(), - } - return self.after_prompt(window, cx); - } - if let Some(permission) = prompt.kind.permission_key() - && self.remember_permission - && self.level_for_tab(key, &page).max(self.level_for_tab(key, &prompt.origin)) == ShieldLevel::Standard - && let Some(profile_id) = self.profile_of(key) - { - let decision = if accept { "allow" } else { "deny" }; - self.store(key.private).set_permission(profile_id, &permission_origin(&prompt.origin, prompt.top_origin.as_deref()), permission, decision).ok(); - } - match (accept, silence) { - (_, true) => { - prompt.decline_and_silence_page(); - self.drop_prompts(key, cx); - } - (true, _) => { - let text = self.prompt_input.read(cx).text().to_owned(); - let user = self.auth_user.read(cx).text().to_owned(); - let pass = self.auth_pass.read(cx).text().to_owned(); - let credentials = matches!(prompt.kind, PromptKind::Credentials { .. }).then_some((user.as_str(), pass.as_str())); - prompt.accept(&text, credentials); - } - (false, _) => prompt.decline(), - } - self.after_prompt(window, cx); - } - - /// Esc declines the prompt in front, as Cancel or Deny does, without remembering the answer. - pub(crate) fn dismiss_prompt(&mut self, window: &mut Window, cx: &mut Context) { - self.remember_permission = false; - self.answer_prompt(false, false, window, cx); - } - - /// Enter answers an alert or confirm whose card holds the focus; permission and download - /// warnings stay mouse-only, behind their click guard. - pub(crate) fn prompt_key(&mut self, event: &gpui::KeyDownEvent, window: &mut Window, cx: &mut Context) { - let simple = self.active_prompt().is_some_and(|p| matches!(p.kind, PromptKind::Alert | PromptKind::Confirm)); - let plain = !event.keystroke.modifiers.modified(); - if event.keystroke.key == "enter" && !event.is_held && plain && simple && !self.overlay_open() && self.focus.is_focused(window) { - cx.stop_propagation(); - self.answer_prompt(true, false, window, cx); - } - } - - fn after_prompt(&mut self, window: &mut Window, cx: &mut Context) { - for input in [&self.prompt_input, &self.auth_user, &self.auth_pass] { - input.update(cx, |i, cx| i.set_text("", cx)); - } - if self.active_prompt().is_some() { - self.prepare_prompt(window, cx); - } else { - window.focus(&self.focus); - if let Some(view) = self.active_view() { - view.focus(); - } - cx.notify(); - } - } - - /// A permission prompt's Allow and Remember, and Keep Anyway on a malware warning, ignore clicks for a - /// moment after they appear, so a page cannot time a click to land on them. - pub(crate) fn prompt_guarded(&self) -> bool { - self.active_prompt().is_some_and(|p| p.kind.is_permission() || matches!(p.kind, PromptKind::MaliciousDownload { .. })) && !self.layout_stable() - } - - fn on_prompt_input_event(&mut self, input: &Entity, event: &TextInputEvent, window: &mut Window, cx: &mut Context) { - match event { - TextInputEvent::Submit if input == &self.auth_user => { - let focus = self.auth_pass.focus_handle(cx); - window.focus(&focus); - } - TextInputEvent::Submit => self.answer_prompt(true, false, window, cx), - TextInputEvent::Cancel => self.answer_prompt(false, false, window, cx), - _ => {} - } - } - - /// In the reader, finds on the page it was made from, which the reader then gives way to. - pub fn open_find(&mut self, window: &mut Window, cx: &mut Context) { - if self.active_view().is_none() || self.card_open() || self.active_json().is_some() { - return; - } - if self.reader_shown() { - self.toggle_reader(window, cx); - } - self.find_open = true; - self.find_count = None; - let text = self.find_input.read(cx).text().to_owned(); - self.find_input.update(cx, |i, cx| i.set_text(text, cx)); - if let Some(host) = &self.host { - host.focus(); - } - let focus = self.find_input.focus_handle(cx); - window.focus(&focus); - cx.notify(); - } - - pub fn close_find(&mut self, window: &mut Window, cx: &mut Context) { - self.find_open = false; - self.find_typing = None; - window.focus(&self.focus); - if let Some(view) = self.active_view() { - view.clear_find(); - view.focus(); - } - cx.notify(); - } - - pub fn find(&mut self, backwards: bool, cx: &mut Context) { - let text = self.find_input.read(cx).text().to_owned(); - let Some(view) = self.active_view().filter(|_| !text.is_empty()) else { return }; - let events = self.events.clone(); - view.find(&text, backwards, move |found, current| { - events.unbounded_send(Msg::Found(found, current)).ok(); - }); - } - - fn on_find_event(&mut self, _: &Entity, event: &TextInputEvent, window: &mut Window, cx: &mut Context) { - match event { - TextInputEvent::Submit | TextInputEvent::Down => { - self.find_typing = None; - self.find(false, cx) - } - TextInputEvent::Up => { - self.find_typing = None; - self.find(true, cx) - } - TextInputEvent::Cancel => self.close_find(window, cx), - TextInputEvent::Changed => { - self.find_count = None; - if self.find_input.read(cx).text().is_empty() { - self.find_typing = None; - if let Some(view) = self.active_view() { - view.clear_find(); - } - } else { - self.find_typing = Some(cx.spawn(async move |this, cx| { - cx.background_executor().timer(browser_core::find::TYPING_DELAY).await; - this.update(cx, |b, cx| { - if b.find_open { - b.find(false, cx); - } - }) - .ok(); - })); - } - cx.notify(); - } - TextInputEvent::MenuClosed | TextInputEvent::PastEnd => {} - } - } - - pub fn print(&mut self) { - if let Some(view) = self.active_view() { - view.print(); - } - } - - fn adopt_popup(&mut self, opener: TabKey, popup: Popup, window: &mut Window, cx: &mut Context) { - let Some(host) = self.host.clone() else { return }; - if self.model.tab(opener).is_none() || self.model.burner_shown() { - return; - } - // A script's window.open keeps its opener, which sign-in and payment pop-ups need, so only links are routed. - if popup.link && popup.url.clone().is_some_and(|url| self.open_routed(&url, window, cx)) { - return; - } - let Some(space) = self.model.current_space() else { return }; - let (private, space_id) = (space.private, space.space.id); - let url = popup.url.as_ref().map_or("about:blank".to_owned(), Url::to_string); - let Ok(tab) = self.store(private).create_tab(space_id, TabKind::Ephemeral, None, &url, "") else { - return; - }; - let key = TabKey { private, id: tab.id }; - // On macOS only WebKit views adopt pop-ups, so an opener with an engine of its own ran in WebKit. - if cfg!(target_os = "macos") { - self.store(private).set_tab_web_engine(tab.id, self.model.tab(opener).and_then(|t| t.web_engine).map(|_| WebEngine::WebKit)).ok(); - } - let inspectable = self.developer || self.is_dev_tab(opener); - let Some(view) = WebView::adopt(popup, &host, inspectable, self.sink(key)) else { - self.store(private).delete_tab(tab.id).ok(); - return; - }; - view.set_corner_radius(page_corner()); - view.set_dark(!ui::theme::Theme::is_light()); - self.view_prefs(&view); - self.views.insert(key, Rc::new(view)); - self.link_loads.insert(key, None); - self.attach_tarn(key); - self.reload_space(); - self.activate(key, window, cx); - } - - fn page_changed(&mut self, key: TabKey, url: &Url, title: &str, back: bool, forward: bool, loading: bool) { - let page = self.pages.entry(key).or_default(); - page.can_back = back; - page.can_forward = forward; - page.loading = loading; - page.error = None; - self.store(key.private).update_tab_page(key.id, url.as_str(), title).ok(); - if self.private_matches(key) - && let Some(t) = self.model.tabs.iter_mut().find(|t| t.id == key.id) - { - t.url = url.to_string(); - t.title = title.to_owned(); - } - } - - fn private_matches(&self, key: TabKey) -> bool { - key.private == self.model.private() - } - - pub(crate) fn profile_of(&self, key: TabKey) -> Option { - self.model.profile_of(&self.core, key) - } - - pub fn back(&mut self) { - if let Some(v) = self.active_view() { - v.back(); - } - } - - pub fn forward(&mut self) { - if let Some(v) = self.active_view() { - v.forward(); - } - } - - pub fn reload(&mut self, cx: &mut Context) { - let dev = self.model.active.is_some_and(|k| self.is_dev_tab(k)); - self.reload_page(dev, cx); - } - - pub fn reload_page(&mut self, from_origin: bool, cx: &mut Context) { - let Some(key) = self.model.active else { return }; - if !self.reload_view(key, from_origin) { - return; - } - self.reload_spin = Some((key, Instant::now())); - cx.spawn(async move |this, cx| { - cx.background_executor().timer(crate::toolbar::SPIN).await; - this.update(cx, |_, cx| cx.notify()).ok(); - }) - .detach(); - cx.notify(); - } - - pub(crate) fn reload_view(&self, key: TabKey, from_origin: bool) -> bool { - let Some(v) = self.views.get(&key) else { return false }; - let page = self.pages.get(&key); - let unloaded = (v.url().is_none() && !page.is_some_and(|p| p.loading)) - .then(|| page.and_then(|p| p.retry.clone()).or_else(|| self.model.tab(key).and_then(|t| Url::parse(&t.url).ok()))) - .flatten(); - if let Some(url) = unloaded { - self.load_tab_url(key, v, url) - } else if from_origin { - v.reload_from_origin() - } else { - v.reload() - } - true - } - - pub fn stop_loading(&mut self, cx: &mut Context) { - self.reload_spin = None; - if let Some(view) = self.active_view() { - view.stop(); - } - cx.notify(); - } - - fn is_dev_tab(&self, key: TabKey) -> bool { - self.profile_of(key).and_then(|p| self.loaded(key.private, p)).is_some_and(|rt| rt.profile.is_dev) - } - - fn after_load_devtools(&mut self, key: TabKey, url: &Url) { - let dev = self.is_dev_tab(key); - if dev && let Some(rt) = self.profile_of(key).and_then(|p| self.loaded(key.private, p)) { - rt.data.clear_cache(); - #[cfg(feature = "chromium")] - engine::chromium::clear_cache(&data_dir().join("Chromium"), &rt.own_store); - } - if !(self.developer || dev) { - return; - } - let Some(view) = self.views.get(&key) else { return }; - let (events, page) = (self.events.clone(), url.clone()); - view.json_text(url, devkit::json_view::MAX_BYTES, move |text| { - if !text.is_empty() { - events.unbounded_send(Msg::Json(key, page.clone(), text)).ok(); - } - }); - } - - fn show_json(&mut self, key: TabKey, url: Url, text: String, cx: &mut Context) { - cx.spawn(async move |this, cx| { - let page = cx.background_spawn(async move { JsonPage::parse(url, &text) }).await; - this.update(cx, |b, cx| { - let current = b.views.get(&key).and_then(|v| v.url()); - if let Ok(page) = page - && current.as_ref() == Some(&page.url) - { - b.json_pages.insert(key, page); - cx.notify(); - } - }) - .ok(); - }) - .detach(); - } - - pub fn set_json_raw(&mut self, key: TabKey, raw: bool, cx: &mut Context) { - if let Some(page) = self.json_pages.get_mut(&key) { - page.set_raw(raw); - cx.notify(); - } - } - - pub fn toggle_json_node(&mut self, key: TabKey, path: Vec, cx: &mut Context) { - if let Some(page) = self.json_pages.get_mut(&key) { - page.toggle(path); - cx.notify(); - } - } - - pub fn active_json(&self) -> Option<(TabKey, &JsonPage)> { - let key = self.model.active?; - self.json_pages.get(&key).map(|p| (key, p)) - } - - pub fn current_is_dev(&self) -> bool { - self.current_loaded().is_some_and(|rt| rt.profile.is_dev) - } - - pub fn devtools_on(&self) -> bool { - self.developer || self.current_is_dev() - } - - /// Web Inspector availability is fixed when a view is created, so every live view is rebuilt. - pub fn set_developer(&mut self, on: bool, window: &mut Window, cx: &mut Context) { - if self.core.disk.set_setting(DEVELOPER_SETTING, if on { "on" } else { "off" }).is_err() { - return; - } - self.apply_developer(on, cx); - crate::shared::others(cx, |b, _, cx| b.apply_developer(on, cx)); - let profiles: Vec<(bool, Id)> = self.core.profiles.borrow().iter().filter(|(_, rt)| !rt.profile.is_dev).map(|(k, _)| *k).collect(); - for (private, id) in profiles { - self.restart_profile_views(private, id, None, false, window, cx); - } - cx.notify(); - } - - fn apply_developer(&mut self, on: bool, cx: &mut Context) { - self.developer = on; - if on { - self.refresh_local_servers(cx); - } else if !self.current_is_dev() { - self.set_responsive(None, cx); - } - cx.notify(); - } - - pub fn create_dev_profile(&mut self, window: &mut Window, cx: &mut Context) { - let existing = self.core.disk.profiles().unwrap_or_default().into_iter().find(|p| p.is_dev); - let space = match existing { - Some(p) => self.core.disk.spaces(p.id).ok().and_then(|s| s.into_iter().next()), - None => self.core.disk.create_dev_profile(&uuid::Uuid::new_v4().to_string()).ok().map(|(_, space)| space), - }; - let Some(space) = space else { return }; - self.refresh_local_servers(cx); - self.reload_spaces(); - let ix = self.model.spaces.iter().position(|s| !s.private && s.space.id == space.id).unwrap_or(0); - self.switch_space(ix, window, cx); - } - - pub fn refresh_local_servers(&mut self, cx: &mut Context) { - cx.spawn(async move |this, cx| { - let ports = cx.background_spawn(async { devkit::localhost::open_dev_ports() }).await; - this.update(cx, |b, cx| { - b.local_servers = Some(ports); - cx.notify(); - }) - .ok(); - }) - .detach(); - } - - pub fn open_local_server(&mut self, port: u16, window: &mut Window, cx: &mut Context) { - if let Ok(url) = Url::parse(&format!("http://localhost:{port}/")) { - self.new_tab(&url, window, cx); - } - } - - pub fn cycle_responsive(&mut self, cx: &mut Context) { - let next = match self.responsive { - None => Some(0), - Some(i) if i + 1 < devkit::responsive::PRESETS.len() => Some(i + 1), - Some(_) => None, - }; - self.set_responsive(next, cx); - } - - fn set_responsive(&mut self, preset: Option, cx: &mut Context) { - match (self.responsive.is_some(), preset.is_some()) { - (false, true) => self.zoom_before_responsive = self.views.iter().map(|(k, v)| (*k, v.zoom())).collect(), - (true, false) => { - for (key, view) in &self.views { - view.set_zoom(self.zoom_before_responsive.get(key).copied().unwrap_or(1.0)); - } - self.zoom_before_responsive.clear(); - } - _ => {} - } - self.responsive = preset; - cx.notify(); - } - - /// The preset applies only while the developer tools that control it are shown. - pub fn responsive_preset(&self) -> Option { - self.responsive.filter(|_| self.devtools_on()).and_then(|i| devkit::responsive::PRESETS.get(i)).copied() - } - - fn responsive_active(&self) -> bool { - self.responsive_preset().is_some() - } - - /// The first click asks; a second click on the same tab and host clears. - pub fn clear_site_data(&mut self, cx: &mut Context) { - let Some(key) = self.model.active else { return }; - let Some(host) = self.active_view().and_then(|v| v.url()).and_then(|u| u.host_str().map(str::to_owned)) else { return }; - if self.clear_site_armed.take() != Some((key, host.clone())) { - self.clear_site_armed = Some((key, host.clone())); - self.notify_offer(key, format!("Click Clear Site Data again to remove cookies, storage and caches of {host}."), None); - cx.notify(); - return; - } - self.clear_site(key, host, cx); - } - - /// Removes every WebKit data type of `host` in the tab's profile, then reloads the tab. - pub(crate) fn clear_site(&mut self, key: TabKey, host: String, cx: &mut Context) { - if let Some(profile_id) = self.profile_of(key).filter(|_| !key.private) - && self.core.disk.unzap_element(profile_id, &host, None).is_ok() - { - crate::zaps::apply(&self.core, false, profile_id); - } - let Some(rt) = self.profile_of(key).and_then(|p| self.loaded(key.private, p)) else { return }; - #[cfg(feature = "chromium")] - self.clear_chromium_site(&rt.own_store, &host); - let this = cx.entity().downgrade(); - let mut async_cx = cx.to_async(); - rt.data.clear_site_data(&host.clone(), move |count| { - this.update(&mut async_cx, |b, cx| { - let message = if count == 0 { format!("{host} had no stored data.") } else { format!("Cleared stored data for {host}.") }; - b.notify_offer(key, message, None); - b.reload_view(key, false); - cx.notify(); - }) - .ok(); - }); - } - - pub fn toggle_sidebar(&mut self, cx: &mut Context) { - if self.tab_placement == browser_core::layout::TabPlacement::Top { - return self.toggle_tabs_on_top(cx); - } - self.set_sidebar_open(!self.sidebar_open, cx); - } - - /// Tabs on top hide this window's sidebar without forgetting whether it was open. - pub fn toggle_tabs_on_top(&mut self, cx: &mut Context) { - self.tab_placement = self.tab_placement.toggled(&self.core.disk); - let open = self.tab_placement == browser_core::layout::TabPlacement::Side && crate::prefs::sidebar_open(&self.core.disk); - self.slide_sidebar(open); - self.close_peek(cx); - self.hide_hover_card(cx); - cx.notify(); - } - - pub fn open_settings(&mut self, window: &mut Window, cx: &mut Context) { - if self.in_main(window, cx, |b, window, cx| b.open_settings(window, cx)) { - return; - } - if let Some(handle) = self.settings_window - && handle.update(cx, |_, settings_window, _| settings_window.activate_window()).is_ok() - { - return; - } - let Some(main) = window.window_handle().downcast::() else { return }; - let browser = cx.entity().downgrade(); - // The new window renders from the browser at once, so it must open after this update ends. - cx.defer(move |cx| { - let handle = SettingsWindow::open(browser.clone(), main, cx); - browser.update(cx, |b, _| b.settings_window = handle).ok(); - }); - } - - pub fn open_settings_pane(&mut self, pane: crate::settings::SettingsPane, window: &mut Window, cx: &mut Context) { - if self.in_main(window, cx, move |b, window, cx| b.open_settings_pane(pane, window, cx)) { - return; - } - self.open_settings(window, cx); - let browser = cx.entity().downgrade(); - cx.defer(move |cx| { - if let Some(handle) = browser.upgrade().and_then(|b| b.read(cx).settings_window) { - handle.update(cx, |settings, _, cx| settings.set_pane(pane, cx)).ok(); - } - }); - } - - pub fn current_profile(&self) -> Option { - self.current_loaded().map(|rt| rt.profile.clone()) - } - - /// The current profile without copying it, for checks that run every frame. - pub(crate) fn current_loaded(&self) -> Option> { - let space = self.model.current_space()?; - self.loaded(space.private, space.space.profile_id) - } - - pub fn site_overrides(&self) -> Vec<(String, ShieldLevel)> { - let Some(space) = self.model.current_space() else { return Vec::new() }; - let Some(rt) = self.loaded(space.private, space.space.profile_id) else { return Vec::new() }; - let mut list: Vec<_> = rt.overrides.borrow().iter().map(|(h, l)| (h.clone(), *l)).collect(); - list.sort(); - list - } - - pub fn all_profiles(&self) -> Vec { - let burners = self.core.burners.borrow(); - [false, true] - .into_iter() - .flat_map(|private| self.store(private).profiles().unwrap_or_default()) - .filter(|p| !(p.is_private && burners.contains(&p.id))) - .collect() - } - - pub(crate) fn shield_wipes_data(&self, level: ShieldLevel) -> bool { - self.current_loaded().is_some_and(|rt| browser_core::profiles::shield_wipes_data(level, self.model.private(), rt.profile.shield_level)) - } - - pub(crate) fn shield_target(&self) -> Option<(bool, Id)> { - self.model.current_space().map(|space| (space.private, space.space.profile_id)) - } - - pub fn set_profile_shield(&mut self, level: ShieldLevel, window: &mut Window, cx: &mut Context) { - let Some(target) = self.shield_target() else { return }; - if !self.shield_wipes_data(level) { - return self.apply_profile_shield(target, level, window, cx); - } - let name = self.current_profile().map(|p| ui::text::bounded_title(&p.name)).unwrap_or_default(); - let question = crate::settings::lockdown_question(&name); - let answer = window.prompt(gpui::PromptLevel::Warning, &question, Some(crate::settings::LOCKDOWN_WIPE), &["Use Lockdown", "Cancel"], cx); - cx.spawn_in(window, async move |this, cx| { - if answer.await == Ok(0) { - this.update_in(cx, |b, window, cx| b.apply_profile_shield(target, level, window, cx)).ok(); - } - }) - .detach(); - } - - pub(crate) fn apply_profile_shield(&mut self, (private, profile_id): (bool, Id), level: ShieldLevel, window: &mut Window, cx: &mut Context) { - if self.store(private).set_profile_shield_level(profile_id, level).is_err() { - return; - } - let new_store = match self.core.profiles.borrow_mut().get_mut(&(private, profile_id)) { - Some(rt) => { - let crossing = !private && (rt.profile.shield_level == ShieldLevel::Lockdown) != (level == ShieldLevel::Lockdown); - rt.profile.shield_level = level; - crossing - } - None => false, - }; - if !new_store { - self.core.apply_extensions(private, profile_id); - } - if !private { - crate::tarn_ext::level_changed(&self.core, profile_id, cx); - } - self.restart_profile_views(private, profile_id, None, new_store, window, cx); - #[cfg(feature = "chromium")] - if new_store - && level == ShieldLevel::Lockdown - && let Some(own_store) = self.loaded(private, profile_id).map(|rt| rt.own_store.clone()) - { - self.wipe_chromium(&own_store, &own_store); - } - } - - pub fn remove_site_override(&mut self, host: &str, window: &mut Window, cx: &mut Context) { - self.set_site_shield(host, None, window, cx); - } - - /// Content rules are fixed when a web view is created, so a level change needs new views, in - /// every window. `new_store` also replaces the profile's data store, for a move into or out of - /// Lockdown. - pub(crate) fn restart_profile_views( - &mut self, - private: bool, - profile_id: Id, - host: Option<&str>, - new_store: bool, - window: &mut Window, - cx: &mut Context, - ) { - self.core.sync_shield(); - self.restart_views_here(private, profile_id, host, new_store, window, cx); - crate::shared::others(cx, |b, window, cx| b.restart_views_here(private, profile_id, host, false, window, cx)); - } - - pub(crate) fn restart_views_here( - &mut self, - private: bool, - profile_id: Id, - host: Option<&str>, - new_store: bool, - window: &mut Window, - cx: &mut Context, - ) { - let on_host = |view: &WebView| host.is_none_or(|h| view.url().is_some_and(|u| u.host_str().map(|s| s.trim_end_matches('.')) == Some(h))); - let keys: Vec = - self.views.iter().filter(|(k, v)| k.private == private && self.profile_of(**k) == Some(profile_id) && on_host(v)).map(|(k, _)| *k).collect(); - self.remake_views(keys, window, cx, |b| { - #[cfg(windows)] - if new_store { - crate::shared::count_chromium_blocks(&b.core); - } - let old = if new_store { b.core.profiles.borrow_mut().remove(&(private, profile_id)) } else { None }; - if let Some(old) = old { - // WebKit holds a download's delegate weakly, so the old store outlives its downloads. - // shortcut: kept until quit; crossings are rare, prune by active downloads if that changes. - old.data.set_extensions(&[], &[], old.profile.shield_level); - b.core.retired_stores.borrow_mut().push(old.data); - } - b.runtime(private, profile_id); - }); - } - - /// Makes the views of `profiles` again so their pages load with the profile's new style - /// script; with `chromium_only`, only Chromium views, which keep the script they were created - /// with, while WebKit views take it on their next load. Windows never asks: its Chromium - /// views are restyled in place. - pub(crate) fn restart_views_of(&mut self, profiles: &[(bool, Id)], chromium_only: bool, window: &mut Window, cx: &mut Context) { - let keys: Vec = self - .views - .iter() - .filter(|(k, v)| (!chromium_only || v.is_chromium()) && self.profile_of(**k).is_some_and(|id| profiles.contains(&(k.private, id)))) - .map(|(k, _)| *k) - .collect(); - if !keys.is_empty() { - self.remake_views(keys, window, cx, |_| {}); - } - } - - /// Drops the views of `keys` (their pages reload when shown), runs `between`, then shows the - /// active tab and split again. - fn remake_views(&mut self, keys: Vec, window: &mut Window, cx: &mut Context, between: impl FnOnce(&mut Self)) { - let active = self.model.active; - let split = self.shown_split().is_some_and(|s| s.panes().iter().any(|p| keys.contains(p))); - for key in keys { - self.hibernate(key, cx); - } - between(self); - if let Some(key) = active.filter(|_| split || self.model.active.is_none()) { - self.activate(key, window, cx); - } - cx.notify(); - } - - /// Tabs of the profile stop renaming visits that were just deleted. - fn forget_visits(&mut self, private: bool, profile_id: Id) { - let keys: Vec = self.pages.keys().copied().filter(|k| k.private == private && self.profile_of(*k) == Some(profile_id)).collect(); - for key in keys { - if let Some(page) = self.pages.get_mut(&key) { - page.visit = None; - } - } - } - - pub fn clear_history(&mut self, private: bool, profile_id: Id, range: browser_core::library::HistoryRange, cx: &mut Context) { - browser_core::library::clear_history(self.store(private), profile_id, range, now()).ok(); - let all = range == browser_core::library::HistoryRange::All; - if all { - crate::zaps::apply(&self.core, private, profile_id); - } - let forget = move |b: &mut Self, cx: &mut Context| { - b.forget_history(private, profile_id); - if all { - b.reapply_site_zooms(private, profile_id, None); - b.set_site_muted(private, profile_id, None, false, false); - } - cx.notify(); - }; - forget(self, cx); - crate::shared::others(cx, |b, _, cx| forget(b, cx)); - } - - pub fn remove_history_url(&mut self, url: &str, cx: &mut Context) { - let Some((private, profile_id)) = self.model.profile() else { return }; - self.store(private).delete_history_url(profile_id, url).ok(); - let forget = move |b: &mut Self, cx: &mut Context| { - b.forget_visits(private, profile_id); - b.history_cache.clear(); - b.forget_text_matches(); - b.menu.history_cleared(); - cx.notify(); - }; - forget(self, cx); - crate::shared::others(cx, |b, _, cx| forget(b, cx)); - } - - /// Forgets what this window keeps in memory of a profile's history: visits, suggestions, - /// recently closed tabs and site icons. - pub(crate) fn forget_history(&mut self, private: bool, profile_id: Id) { - self.forget_visits(private, profile_id); - self.history_cache.clear(); - self.forget_text_matches(); - self.menu.history_cleared(); - self.model.closed_tabs.clear_profile(private, profile_id); - self.forget_favicons((private, profile_id)); - } - - /// The private profile is never written to disk. - pub fn export_profile(&mut self, private: bool, profile_id: Id, cx: &mut Context) { - let notice = match self.write_export(private, profile_id) { - Ok(path) => format!("Exported to {}.", path.display()), - Err(e) => format!("Export failed: {e}."), - }; - self.privacy_notice = Some(((private, profile_id), notice)); - cx.notify(); - } - - fn write_export(&self, private: bool, profile_id: Id) -> Result { - use std::io::Write; - #[cfg(unix)] - use std::os::unix::fs::OpenOptionsExt; - if private { - return Err("private data is not saved".into()); - } - let store = self.store(private); - let name = store.profile(profile_id).map_err(|e| e.to_string())?.name; - let json = store.export_profile(profile_id).map_err(|e| e.to_string())?; - let dir = std::env::home_dir().ok_or("no home folder")?.join("Downloads"); - let file = browser_core::profile_data::export_name(&name); - let path = engine::downloads::free_path(&dir, &file, |_| false); - let mut options = std::fs::OpenOptions::new(); - #[cfg(unix)] - options.mode(0o600); - options.write(true).create_new(true).open(&path).and_then(|mut f| f.write_all(json.as_bytes())).map_err(|e| e.to_string())?; - Ok(path) - } - - /// Files already saved to Downloads stay; the profile row (name, Shield level) stays. - pub fn delete_profile_data(&mut self, private: bool, profile_id: Id, window: &mut Window, cx: &mut Context) { - let target = (private, profile_id); - self.forget_visits(private, profile_id); - let keys: Vec = self.views.keys().filter(|k| k.private == private && self.profile_of(**k) == Some(profile_id)).copied().collect(); - let folders: Vec = self - .model - .spaces - .iter() - .filter(|s| s.private == private && s.space.profile_id == profile_id) - .flat_map(|s| self.store(private).folders(s.space.id).unwrap_or_default()) - .map(|f| f.id) - .collect(); - let reset = match self.core.reset_profile_data(private, profile_id) { - Ok(reset) => reset, - Err(e) => { - self.privacy_notice = Some((target, format!("Deleting failed ({e})."))); - cx.notify(); - return; - } - }; - let space = reset.space; - Self::sync_other_windows(cx); - crate::shared::others(cx, |b, _, cx| { - b.forget_history(private, profile_id); - b.toast.forget(target); - b.forget_assistant(profile_id); - cx.notify(); - }); - self.forget_assistant(profile_id); - for key in keys { - self.hibernate(key, cx); - } - self.model.forget_folders(private, &folders); - self.toast.forget(target); - self.pending_external = None; - self.refocus |= std::mem::take(&mut self.find_open); - self.suggestions.clear(); - let store = self.core.store(private); - self.pages.retain(|k, _| k.private != private || store.tab(k.id).is_ok()); - self.history_cache.clear(); - self.forget_text_matches(); - self.model.closed_tabs.clear_profile(private, profile_id); - self.forget_favicons(target); - self.privacy_notice = Some((target, "Deleting website data…".into())); - let own_store = reset.own_store; - // WebKit's data removal leaves its tracking-prevention and site-security databases behind, - // so a profile with a store of its own moves to a new one and the old one goes as a whole. - if reset.fresh_store.is_some() { - #[cfg(feature = "chromium")] - self.wipe_chromium(&own_store, reset.fresh_store.as_deref().unwrap_or_default()); - #[cfg(windows)] - crate::shared::count_chromium_blocks(&self.core); - if let Some(old) = self.core.profiles.borrow_mut().remove(&(false, profile_id)) { - old.data.set_extensions(&[], &[], old.profile.shield_level); - if self.downloads_popover.active.get(&target).is_some_and(|n| *n > 0) { - self.core.retired_stores.borrow_mut().push(old.data); - } - } - self.core.extensions.borrow_mut().forget_running(false, profile_id); - DataStore::wipe_persistent(&own_store); - DataStore::wipe_extensions(&own_store); - crate::zaps::forget(&own_store); - self.retire_store(&own_store, cx); - self.runtime(false, profile_id); - self.core.sync_shield(); - self.privacy_notice = Some((target, "All data of this profile was deleted.".into())); - self.reload_spaces(); - let ix = self.model.spaces.iter().position(|s| !s.private && s.space.id == space.id).unwrap_or(0); - self.switch_space(ix, window, cx); - return; - } - #[cfg(feature = "chromium")] - if !private { - self.wipe_chromium(&own_store, &own_store); - } - let (core, app_cx) = (self.core.clone(), cx.to_async()); - let reached = match self.runtime(private, profile_id) { - Some(rt) => { - rt.overrides.borrow_mut().clear(); - rt.data.set_site_styles(&crate::themes::page_sheets(&core, private, profile_id)); - if !private { - crate::zaps::forget(&own_store); - rt.data.set_rule_lists("zaps", None, false); - #[cfg(windows)] - rt.data.set_hidden_elements(&[]); - } - rt.rules.clear(); - if !private && rt.profile.shield_level == ShieldLevel::Lockdown { - DataStore::wipe_persistent(&rt.profile.data_store_uuid); - DataStore::wipe_extensions(&own_store); - } - let this = cx.entity().downgrade(); - let mut async_cx = cx.to_async(); - rt.data.remove_extension_data(move || { - core.extensions.borrow_mut().forget_running(private, profile_id); - if core.apply_extensions(private, profile_id) { - core.sync_shield(); - app_cx.update(|cx| crate::shared::each(cx, |b, window, cx| b.restart_views_here(private, profile_id, None, false, window, cx))).ok(); - } - }); - rt.data.remove_all_data(move || { - this.update(&mut async_cx, |b, cx| { - b.privacy_notice = Some((target, "All data of this profile was deleted.".into())); - cx.notify(); - }) - .ok(); - }); - true - } - None => false, - }; - if !reached { - self.privacy_notice = Some((target, "Stored data was deleted; website data could not be reached.".into())); - } - self.core.sync_shield(); - self.reload_spaces(); - let ix = self.model.spaces.iter().position(|s| s.private == private && s.space.id == space.id).unwrap_or(0); - self.switch_space(ix, window, cx); - } - - pub(crate) fn forget_favicons(&mut self, profile: (bool, Id)) { - self.favicons.forget(&profile); - self.favicon_memo.take(); - #[cfg(feature = "translation")] - self.translation_offered.retain(|(p, id, _)| (*p, *id) != profile); - } - - /// The host's icon, else the nearest parent's within its site, so a subdomain never visited - /// still shows its site's icon. - /// Every tab row asks once per frame, so answers are kept until an icon arrives or goes. - pub fn favicon(&self, url: &str) -> Option> { - let space = self.model.current_space()?; - let profile = (space.private, space.space.profile_id); - let mut memo = self.favicon_memo.borrow_mut(); - // shortcut: a full memo starts over, so URLs a long session visited do not pile up. - if memo.as_ref().is_none_or(|(p, urls)| *p != profile || urls.len() >= 4096) { - *memo = Some((profile, HashMap::new())); - } - let urls = &mut memo.as_mut()?.1; - if let Some(found) = urls.get(url) { - return found.clone(); - } - let found = self.find_favicon(profile, url); - urls.insert(url.to_owned(), found.clone()); - found - } - - fn find_favicon(&self, profile: (bool, Id), url: &str) -> Option> { - self.favicons.find(&profile, &tab_host(url)?).cloned() - } - - /// Lockdown pages get no extra requests. - fn request_favicon(&mut self, key: TabKey, url: &Url) { - let lockdown = self.level_for_tab(key, url.as_str()) == ShieldLevel::Lockdown; - let (Some(profile_id), Some(host)) = (self.profile_of(key), favicon::icon_host(url, lockdown)) else { return }; - self.load_favicons(key.private, profile_id); - let Some(view) = self.views.get(&key) else { return }; - let profile = (key.private, profile_id); - let Some(ticket) = self.favicons.request(&profile, &host) else { return }; - let icon = (profile, host, ticket); - let (events, page) = (self.events.clone(), url.clone()); - view.icon_links(url, move |links| { - events.unbounded_send(Msg::IconLinks(key, icon.clone(), page.clone(), links)).ok(); - }); - } - - fn fetch_favicon(&mut self, key: TabKey, icon: IconKey, page: &Url, links: &str) { - let urls = favicon::candidates(page, links); - let still_there = |v: &&Rc| v.url().is_some_and(|u| u.origin() == page.origin()); - let view = self.views.get(&key).filter(still_there).filter(|_| !urls.is_empty() && self.favicons.is_requested(&icon.0, &icon.1, icon.2)); - let Some(view) = view else { - self.favicons.withdraw(&icon.0, &icon.1, icon.2); - return; - }; - let events = self.events.clone(); - view.fetch_icon(page, &urls, favicon::MAX_BYTES, move |data| { - events.unbounded_send(Msg::IconData(icon.clone(), data)).ok(); - }); - } - - fn store_favicon(&mut self, icon: IconKey, data: String, cx: &mut Context) { - cx.spawn(async move |this, cx| { - let png = cx.background_spawn(async move { favicon::normalize(&data) }).await; - this.update(cx, |b, cx| { - let (profile, host, ticket) = icon; - // A history clear while the icon was loading withdraws the request. - let wanted = b.favicons.is_requested(&profile, &host, ticket); - if let Some(png) = png.as_ref().filter(|_| wanted && b.core.keeps_records(profile.0, profile.1)) { - b.store(profile.0).set_favicon(profile.1, &host, png).ok(); - } - if b.favicons.accept(&profile, &host, ticket, png.map(|png| Arc::new(Image::from_bytes(ImageFormat::Png, png)))) { - b.favicon_memo.take(); - cx.notify(); - } - }) - .ok(); - }) - .detach(); - } - - /// The zoom is kept per host and profile and shared by its open tabs; Lockdown pages keep none. - pub fn zoom(&mut self, factor: Option, cx: &mut Context) { - if self.responsive_active() { - return self.show_toast("Zoom is off while Responsive Size is on", None, cx); - } - let (Some(key), Some(v)) = (self.model.active, self.active_view()) else { return }; - v.set_zoom(factor.map_or(1.0, |f| v.zoom() * f)); - self.show_toast(format!("Zoom {}%", (v.zoom() * 100.).round()), None, cx); - let (Some(profile_id), Some(url)) = (self.profile_of(key), v.url()) else { return }; - let Some(host) = url.host_str() else { return }; - let Some(zoom) = zoom_to_save(v.zoom(), self.level_for_tab(key, url.as_str()) == ShieldLevel::Lockdown) else { return }; - if self.store(key.private).set_site_zoom(profile_id, host, zoom).is_ok() { - self.reapply_site_zooms(key.private, profile_id, Some(host)); - } - cx.notify(); - } - - /// Sets the host's saved zoom; without one, `reset` returns the page to 100% and otherwise leaves it. - fn apply_site_zoom(&mut self, key: TabKey, url: Option<&Url>, reset: bool) { - let Some(view) = self.views.get(&key).cloned() else { return }; - let saved = self.profile_of(key).zip(url.and_then(Url::host_str)).and_then(|(p, host)| self.store(key.private).site_zoom(p, host).ok().flatten()); - let Some(zoom) = saved.or(reset.then_some(1.0)) else { return }; - if self.responsive_active() { - self.zoom_before_responsive.insert(key, zoom); - } else { - view.set_zoom(zoom); - } - } - - /// Re-applies saved zooms to the profile's open pages on `host`, or on every host. - fn reapply_site_zooms(&mut self, private: bool, profile_id: Id, host: Option<&str>) { - let views: Vec<(TabKey, Option)> = self - .views - .iter() - .filter(|(k, _)| k.private == private && self.profile_of(**k) == Some(profile_id)) - .map(|(k, v)| (*k, v.url())) - .filter(|(_, url)| host.is_none() || url.as_ref().and_then(Url::host_str) == host) - .collect(); - for (key, url) in views { - self.apply_site_zoom(key, url.as_ref(), true); - } - } - - fn saved_mute(&self, key: TabKey, host: &str) -> bool { - self.profile_of(key).is_some_and(|p| self.store(key.private).muted_sites(p).unwrap_or_default().iter().any(|h| h == host)) - } - - /// A page starts muted on a muted host; like zoom, an unsaved Lockdown mute lasts until the tab leaves the host. - fn apply_site_mute(&self, key: TabKey, url: &Url, left_host: bool) { - let saved = url.host_str().is_some_and(|host| self.saved_mute(key, host)); - if let Some(view) = self.views.get(&key).filter(|v| saved || left_host || v.is_muted()) { - view.set_muted(saved || !left_host); - } - } - - pub fn tab_muted(&self, key: TabKey) -> bool { - match self.views.get(&key) { - Some(view) => view.is_muted(), - None => self.tab_url(key).and_then(|u| tab_host(&u)).is_some_and(|host| self.saved_mute(key, &host)), - } - } - - /// Mutes or unmutes the tab's host in its profile, for its open tabs and later visits; Lockdown saves nothing. - pub fn toggle_site_muted(&mut self, key: TabKey, cx: &mut Context) { - let Some(url) = self.tab_url(key).and_then(|u| Url::parse(&u).ok()) else { return }; - let (Some(profile_id), Some(host)) = (self.profile_of(key), url.host_str()) else { return }; - let muted = !self.tab_muted(key); - let save = browser_core::site::saves_mute(muted, self.level_for_tab(key, url.as_str())); - self.set_site_muted(key.private, profile_id, Some(host), muted, save); - let host = crate::toolbar::host_tail(host.trim_start_matches("www."), 40); - self.show_toast(if muted { format!("Muted {host}") } else { format!("Unmuted {host}") }, None, cx); - } - - /// Applies a mute to the profile's open pages on `host`, or on every host, saving it when `save` is set. - pub fn set_site_muted(&mut self, private: bool, profile_id: Id, host: Option<&str>, muted: bool, save: bool) { - if let Some(host) = host.filter(|_| save) { - self.store(private).set_site_muted(profile_id, host, muted).ok(); - } - for (key, view) in &self.views { - let on_host = host.is_none() || view.url().as_ref().and_then(Url::host_str) == host; - if key.private == private && on_host && self.profile_of(*key) == Some(profile_id) { - view.set_muted(muted); - } - } - } - - pub fn muted_sites(&self) -> Vec { - let Some(space) = self.model.current_space() else { return Vec::new() }; - self.store(space.private).muted_sites(space.space.profile_id).unwrap_or_default() - } - - pub fn site_zooms(&self) -> Vec<(String, f64)> { - let Some(space) = self.model.current_space() else { return Vec::new() }; - self.store(space.private).site_zooms(space.space.profile_id).unwrap_or_default() - } - - pub fn remove_site_zoom(&mut self, private: bool, profile_id: Id, host: Option<&str>, cx: &mut Context) { - let store = self.store(private); - match host { - Some(host) => store.set_site_zoom(profile_id, host, None), - None => store.clear_site_zooms(profile_id), - } - .ok(); - self.reapply_site_zooms(private, profile_id, host); - cx.notify(); - } } pub fn tab_host(url: &str) -> Option { diff --git a/crates/app/src/browser/command_bar.rs b/crates/app/src/browser/command_bar.rs new file mode 100644 index 00000000..6205cc33 --- /dev/null +++ b/crates/app/src/browser/command_bar.rs @@ -0,0 +1,707 @@ +use super::*; + +impl Browser { + pub fn open_command(&mut self, mode: CommandMode, window: &mut Window, cx: &mut Context) { + if self.in_main(window, cx, move |b, window, cx| b.open_command(mode, window, cx)) { + return; + } + self.new_tab_group = None; + self.overlay_exit = None; + self.shortcuts_open = false; + let text = match mode { + CommandMode::Current => { + self.active_view().and_then(|v| v.url()).map(String::from).or_else(|| self.model.active_tab().map(|t| t.url.clone())).unwrap_or_default() + } + CommandMode::NewTab | CommandMode::FindInTabs | CommandMode::Snippets => String::new(), + }; + let placeholder = match mode { + CommandMode::FindInTabs => "Find in this space's tabs", + CommandMode::Snippets => "Insert a snippet", + _ => "Search or enter address", + }; + let private = self.model.private(); + self.history_cache = self.model.current_space().map(|s| s.space.profile_id).and_then(|p| self.store(private).history(p, 2000).ok()).unwrap_or_default(); + self.history_text = None; + self.command_mode = Some(mode); + if self.devtools_on() { + self.refresh_local_servers(cx); + } + self.command.update(cx, |input, cx| { + input.set_placeholder(placeholder); + input.set_text(text, cx); + }); + if self.model.active.is_some() && !self.profile_editor.as_ref().is_some_and(|e| !e.floating) { + self.open_inline(window, cx); + } else if let Some(view) = self.active_view() { + view.set_visible(false); + } + if let Some(host) = &self.host { + host.focus(); + } + let focus = self.command.focus_handle(cx); + window.focus(&focus); + self.update_suggestions(cx); + cx.notify(); + } + + /// F6 and Shift+F6: moves the keyboard between the page, the address field and the sidebar. + pub(crate) fn cycle_focus(&mut self, back: bool, window: &mut Window, cx: &mut Context) { + use browser_core::focus::{Region, next_region}; + let open = self.command_mode.is_some(); + let from = if open { + Region::Address + } else if self.focus.is_focused(window) { + Region::Page + } else { + Region::Sidebar + }; + match next_region(from, back, self.active_view().is_some(), self.sidebar_shown() > 0.) { + Region::Address => self.open_command(CommandMode::Current, window, cx), + Region::Page if open => self.close_command(window, cx), + Region::Page => { + window.focus(&self.focus); + if let Some(view) = self.active_view() { + view.focus(); + } + } + Region::Sidebar => { + if open { + self.close_command(window, cx); + } + if let Some(host) = &self.host { + host.focus(); + } + window.focus(&self.focus); + window.focus_next(); + } + } + } + + pub fn close_command(&mut self, window: &mut Window, cx: &mut Context) { + let field = self.command_mode.is_some(); + let covered = field || self.shortcuts_open; + self.launcher_from = None; + self.actions_page = None; + self.rejected = 0; + self.close_inline(cx); + self.overlay_exit = None; + self.command_mode = None; + self.history_text_search = None; + self.profile_editor = None; + self.shortcuts_open = false; + self.reader = self.reader.take().filter(|r| field || crate::reader::keeps_reader(covered, r.speaking())); + window.focus(&self.focus); + for key in self.model.active.and_then(|a| Some(self.splits.of(a)?.others(a))).unwrap_or_default() { + if let Some(view) = self.views.get(&key) { + view.set_visible(true); + } + } + if let Some(view) = self.active_view().filter(|_| !self.overlay_open()) { + view.set_visible(true); + view.focus(); + } + self.layout_changed(); + self.prepare_prompt(window, cx); + cx.notify(); + } + + /// The command card and profile editor replace the page, so the native web view is hidden under + /// them; the address field opened in the toolbar leaves it visible. + pub fn overlay_open(&self) -> bool { + self.card_open() || self.reader_shown() + } + + /// An overlay other than the reader. + pub(crate) fn card_open(&self) -> bool { + (self.command_mode.is_some() && !self.inline_editing()) || self.profile_editor.as_ref().is_some_and(|e| !e.floating) || self.shortcuts_open + } + + pub(crate) fn reader_shown(&self) -> bool { + self.reader.as_ref().is_some_and(|r| self.model.active == Some(r.key)) + } + + pub(crate) fn select_suggestion(&mut self, forward: bool, cx: &mut Context) { + self.select_suggestion_at(suggest::step_selection(self.selected, self.suggestions.len(), forward), cx); + } + + pub(crate) fn select_suggestion_at(&mut self, ix: usize, cx: &mut Context) { + self.selected = ix.min(self.suggestions.len().saturating_sub(1)); + self.suggestions_scroll.scroll_to_item(self.selected); + cx.notify(); + } + + /// Tab, Page Up and Page Down move the highlight in the field's suggestion list. + pub(crate) fn suggestion_key(&mut self, event: &gpui::KeyDownEvent, cx: &mut Context) { + let last = self.suggestions.len().saturating_sub(1); + match event.keystroke.key.as_str() { + "tab" => self.select_suggestion(!event.keystroke.modifiers.shift, cx), + "pageup" => self.select_suggestion_at(0, cx), + "pagedown" => self.select_suggestion_at(last, cx), + _ => return, + } + cx.stop_propagation(); + } + + pub(super) fn on_command_event(&mut self, _: &Entity, event: &TextInputEvent, window: &mut Window, cx: &mut Context) { + match event { + TextInputEvent::Changed => { + self.rejected = 0; + if self.command_mode != Some(CommandMode::Snippets) { + self.expand_snippet(cx); + } + self.update_suggestions(cx) + } + TextInputEvent::Submit => self.submit_command(self.selected, window, cx), + TextInputEvent::Cancel if self.actions_page.is_some() => self.leave_actions(cx), + TextInputEvent::Cancel => self.dismiss_overlay(window, cx), + TextInputEvent::PastEnd => self.open_actions(self.selected, cx), + TextInputEvent::Up => self.select_suggestion(false, cx), + TextInputEvent::Down => self.select_suggestion(true, cx), + TextInputEvent::MenuClosed if !window.is_window_active() && self.inline_editing() => self.close_command(window, cx), + TextInputEvent::MenuClosed => {} + } + } + + /// "Switch to" and "Move Tab to" rows for the other spaces, ranked like the command table. + pub(super) fn space_commands(&self, query: &str) -> Vec { + let mut rows: Vec<(String, Box)> = Vec::new(); + for (ix, s) in self.model.spaces.iter().enumerate().filter(|(ix, _)| *ix != self.model.space_ix) { + rows.push((format!("Switch to {}", ui::text::bounded_title(&s.space.name)), Box::new(crate::menubar::SwitchToSpace { ix }))); + } + if let Some(key) = self.model.active { + for ix in self.model.move_targets(&self.core, key) { + let name = ui::text::bounded_title(&self.model.spaces[ix].space.name); + rows.push((format!("Move Tab to {name}"), Box::new(crate::menubar::MoveToSpace { ix }))); + } + } + command::rank_commands(query, rows.iter().map(|(label, _)| (label.as_str(), "space workspace"))) + .into_iter() + .map(|ix| Suggestion { section: None, label: rows[ix].0.clone(), detail: String::new(), target: Target::Action(rows[ix].1.boxed_clone()) }) + .collect() + } + + pub(super) fn update_suggestions(&mut self, cx: &mut Context) { + self.suggest(None, cx); + } + + /// What an actions page can act on for a row, if anything. + pub(crate) fn row_item(&self, s: &Suggestion) -> Option { + use browser_core::command::Section; + match &s.target { + Target::Tab(key) | Target::Find(key, _) => Some(Item::Tab(key.id)), + Target::Url(u) if s.section == Some(Section::Favorites) => Some(Item::Bookmark(u.to_string())), + Target::Url(u) => Some(Item::History(u.to_string())), + Target::Input(Input::Command(ix)) => browser_core::palette::COMMANDS.get(*ix).map(|c| Item::Command(c.2)), + _ => None, + } + } + + /// Lists the actions of row `ix` in place of the rows; Esc goes back to them. + pub(crate) fn open_actions(&mut self, ix: usize, cx: &mut Context) { + if !matches!(self.command_mode, Some(CommandMode::NewTab | CommandMode::Current)) || self.actions_page.is_some() { + return; + } + let Some((row, item)) = self.suggestions.get(ix).and_then(|s| Some((s, self.row_item(s)?))) else { return }; + let title = row.label.clone(); + let spaces: Vec = match item { + Item::Tab(id) => { + let key = TabKey { private: self.model.private(), id }; + self.model.move_targets(&self.core, key).into_iter().map(|ix| self.model.spaces[ix].space.name.clone()).collect() + } + _ => Vec::new(), + }; + let names: Vec<&str> = spaces.iter().map(String::as_str).collect(); + let shortcut = match item { + Item::Command(c) => crate::command_action(c).map(|a| crate::shortcuts::shown(a, cx)).unwrap_or_default(), + _ => String::new(), + }; + self.suggestions = browser_core::palette::actions(&item, &names) + .into_iter() + .map(|(label, action)| { + let detail = if action == browser_core::palette::Action::Run { shortcut.clone() } else { String::new() }; + Suggestion { section: None, label, detail, target: Target::Act(item.clone(), action) } + }) + .collect(); + self.actions_page = Some((title, ix)); + self.select_suggestion_at(0, cx); + } + + pub(crate) fn leave_actions(&mut self, cx: &mut Context) { + let Some((_, back)) = self.actions_page.take() else { return }; + self.suggest(self.suggested.clone(), cx); + self.select_suggestion_at(back, cx); + } + + /// Runs an action of the actions page, mostly as the row it stands for would run. + pub(super) fn run_action(&mut self, ix: usize, item: Item, action: browser_core::palette::Action, window: &mut Window, cx: &mut Context) { + use browser_core::palette::Action; + let private = self.model.private(); + let url = match &item { + Item::Tab(id) => self.tab_url(TabKey { private, id: *id }).map(|u| u.to_string()), + Item::Bookmark(u) | Item::History(u) => Some(u.clone()), + Item::Command(_) => None, + }; + let target = match (item, action) { + (Item::Command(c), Action::Run) => Target::Input(Input::Command(c.index())), + (Item::Tab(id), Action::Switch) => Target::Tab(TabKey { private, id }), + (Item::Tab(id), Action::Close) => { + self.close_command(window, cx); + return self.close_tab(TabKey { private, id }, window, cx); + } + (Item::Tab(id), Action::MoveToSpace(n)) => { + let key = TabKey { private, id }; + let Some(space) = self.model.move_targets(&self.core, key).get(n).copied() else { return }; + self.close_command(window, cx); + return self.move_to_space(key, space, window, cx); + } + (Item::History(u), Action::RemoveFromHistory) => { + self.remove_history_url(&u, cx); + self.actions_page = None; + return self.suggest(None, cx); + } + (_, Action::CopyLink) => match url { + Some(u) => Target::Copy(u), + None => return, + }, + (_, Action::OpenInNewTab) => { + self.command_mode = Some(CommandMode::NewTab); + match url.and_then(|u| Url::parse(&u).ok()) { + Some(u) => Target::Url(u), + None => return, + } + } + (_, Action::Open) => match url.and_then(|u| Url::parse(&u).ok()) { + Some(u) => Target::Url(u), + None => return, + }, + _ => return, + }; + self.actions_page = None; + self.suggestions[ix].target = target; + self.submit_command(ix, window, cx); + } + + pub(crate) fn refresh_open_suggestions(&mut self, cx: &mut Context) { + if self.command_mode.is_some() + && self.actions_page.is_none() + && let Some(again) = self.suggested.clone() + { + self.suggest(Some(again), cx); + } + } + + /// Builds the suggestions for the field's text, or `again` for the query and completion they + /// were last built for. + pub(super) fn suggest(&mut self, again: Option<(String, Option)>, cx: &mut Context) { + let _span = + (again.is_none() && self.command_mode != Some(CommandMode::FindInTabs)).then(|| engine::startup::span(engine::startup::PALETTE_QUERY)).flatten(); + let rebuilt = again.is_some(); + if rebuilt && self.actions_page.is_some() { + return; + } + self.actions_page = None; + let (query, kept) = again.map_or_else(|| (self.command.read(cx).text().trim().to_owned(), None), |(q, c)| (q, Some(c))); + if !rebuilt { + (self.history_text_search, self.suggested) = (None, None); + } + match self.command_mode { + Some(CommandMode::FindInTabs) => return self.find_in_tabs(query, cx), + Some(CommandMode::Snippets) => return self.snippet_rows(&query, cx), + _ => {} + } + let site = self.site(); + let state = self.palette_state(); + let zappable = site.as_ref().is_some_and(|(k, u)| self.zappable(*k, u)); + let offered = |c: Command| { + crate::command_action(c).is_some() + && match c { + Command::ZapElement => zappable, + Command::SiteSettings => site.is_some(), + Command::ImportBrowserData => browser_core::import::available(), + _ => true, + } + }; + let commands = self.ranked_commands(&query, &state, offered); + if browser_core::palette::sectioned(&query) { + self.suggestions = self.sectioned_rows(&state, offered, cx); + self.selected = usize::MAX; + self.suggested = Some((query, None)); + cx.notify(); + return; + } + let space_rows = self.space_commands(&query); + if query.starts_with('>') { + self.suggestions = commands.into_iter().map(|c| command_row(c, cx)).chain(space_rows).collect(); + self.select_suggestion_at(0, cx); + return; + } + let (mut out, exact) = self.typed_rows(&query, commands, space_rows, cx); + let suggest_on = self.pref(crate::prefs::Pref::Suggestions); + let mut pages: Vec = self.model.tabs.iter().map(Page::from).collect(); + if !query.is_empty() { + pages.extend(self.history_cache.iter().map(Page::from)); + } + let field = self.command.read(cx); + let completion = kept.unwrap_or_else(|| { + (suggest_on && !exact && suggest::may_complete(field.text(), field.inserted(), field.caret_at_end())) + .then(|| suggest::inline_completion(&query, &pages, now())) + .flatten() + }); + if let Some(c) = &completion { + out.insert(0, self.completion_row(&query, c)); + } + let answers = browser_core::palette::answers(&query); + let answered = answers.len(); + out.splice( + 0..0, + answers.into_iter().map(|a| Suggestion { + section: None, + label: a.label, + detail: browser_core::palette::ANSWER_DETAIL.to_owned(), + target: Target::Copy(a.copy), + }), + ); + let typed = out.len(); + let (history, search_later) = self.history_rows(&query, &pages, &out, completion.as_ref().map(|c| c.url.as_str()), suggest_on); + out.extend(history); + out.truncate(if suggest_on { MAX_SUGGESTIONS } else { typed }); + // Late text matches move rows; the highlight stays on the row the user chose, if it is still listed. + // An empty field highlights nothing, so Enter opens nothing until the user picks a row. + let chosen = self.suggestions.get(self.selected).filter(|_| rebuilt).map(|s| (s.label.clone(), s.detail.clone())); + self.suggestions = out; + let first = if query.is_empty() { None } else { browser_core::palette::default_row(answered, self.suggestions.len()) }.unwrap_or(usize::MAX); + self.selected = chosen.and_then(|(label, detail)| self.suggestions.iter().position(|s| s.label == label && s.detail == detail)).unwrap_or(first); + self.suggested = Some((query.clone(), completion.clone())); + self.history_text_search = search_later.map(|profile| self.search_history_text_later(profile, query, cx)); + if let (Some(c), false) = (completion, rebuilt) { + self.command.update(cx, |input, cx| input.append_selected(&c.suffix, cx)); + } + cx.notify(); + } + + fn palette_state(&self) -> browser_core::palette::State { + let tab = self.model.active_tab(); + let idle = |a: &dyn gpui::Action| self.idle(a); + browser_core::palette::State { + pinned: tab.is_some_and(|t| t.kind != store::TabKind::Ephemeral), + split: self.model.active.is_some_and(|a| self.splits.contains(a)), + reopenable: !idle(&crate::ReopenClosedTab), + duplicates: !self.duplicate_tabs().is_empty(), + no_tab: tab.is_none(), + no_page: self.model.active.and_then(|k| self.tab_url(k)).is_none(), + private: self.model.private(), + muted: self.model.active.filter(|_| !idle(&crate::menubar::ToggleMute)).map(|k| self.tab_muted(k)), + custom_title: tab.is_some_and(|t| !t.custom_title.is_empty()), + renamable: tab.is_some(), + drifted: self.model.active.and_then(|k| self.pinned_drift(k)).is_some(), + sleep_others: true, + unpinned: !idle(&crate::CloseAllTabs), + loading: !idle(&crate::StopLoading), + toast: self.toast_command(), + reader: Some(self.reader_shown()), + developer: self.devtools_on(), + assistant: self.assistant_allowed(), + ..Default::default() + } + } + + fn ranked_commands(&self, query: &str, state: &browser_core::palette::State, offered: impl Fn(Command) -> bool) -> Vec<(String, Command)> { + let mut commands: Vec<(String, Command)> = browser_core::palette::ranked(query, state, offered, &[]) + .into_iter() + .filter_map(|(label, row)| match row { + browser_core::palette::Row::Command(c) => Some((label, c)), + browser_core::palette::Row::Extra(_) => None, + }) + .collect(); + // Reading the switch target costs a profile and lock file read. + if commands.iter().any(|(_, c)| matches!(c, Command::ReloadInChromium | Command::ReloadInWebKit)) { + let to = self.model.active.and_then(|k| self.web_engine_switch(k)); + commands.retain(|(_, c)| match c { + Command::ReloadInChromium => to == Some(WebEngine::Chromium), + Command::ReloadInWebKit => to == Some(WebEngine::WebKit), + _ => true, + }); + } + commands + } + + fn sectioned_rows(&self, state: &browser_core::palette::State, offered: impl Fn(Command) -> bool, cx: &App) -> Vec { + let private = self.model.private(); + let data = browser_core::palette::Data { + tabs: &self.model.tabs, + active: self.model.active.map(|k| k.id), + bookmarks: &self.bookmarks, + history: &self.history_cache, + now: now(), + }; + let mut out = Vec::new(); + for (section, entries) in browser_core::palette::sections(state, offered, &data) { + for entry in entries { + let row = match entry.item { + Item::Command(c) => command_row((entry.label, c), cx), + Item::Tab(id) => Suggestion { section: None, label: entry.label, detail: entry.detail, target: Target::Tab(TabKey { private, id }) }, + Item::Bookmark(url) | Item::History(url) => { + let Ok(url) = Url::parse(&url) else { continue }; + Suggestion { section: None, label: entry.label, detail: entry.detail, target: Target::Url(url) } + } + }; + out.push(Suggestion { section: Some(section), ..row }); + } + } + out + } + + fn typed_rows(&self, query: &str, commands: Vec<(String, Command)>, space_rows: Vec, cx: &App) -> (Vec, bool) { + let mut out = Vec::new(); + let shortcuts = self.pref(crate::prefs::Pref::SearchShortcuts); + let default = &command::ENGINES[self.search_engine()]; + let engine = command::search_engine(query, default, shortcuts); + let input = command::classify_input(query, default, shortcuts); + if let Some(Input::Navigate(u)) = &input { + out.extend(self.open_tabs_at(&self.clean_user_url(u.clone()))); + } + let exact = commands.first().is_some_and(|(label, c)| label.eq_ignore_ascii_case(query) || c.label().eq_ignore_ascii_case(query)); + if exact { + out.extend(commands.iter().cloned().map(|c| command_row(c, cx))); + } + if let Some(input) = input { + let (label, detail) = match &input { + Input::Navigate(u) => (u.to_string(), "Open".to_owned()), + Input::Search(_) => (query.to_owned(), format!("Search {}", engine.name)), + Input::External(u) => (u.to_string(), format!("Open in another app ({})", u.scheme())), + Input::Rejected => (query.to_owned(), "This kind of address cannot be opened".to_owned()), + Input::Command(_) => unreachable!("classify_input never names a command"), + }; + out.push(Suggestion { section: None, label, detail, target: Target::Input(input) }); + } + if !exact { + out.extend(commands.into_iter().map(|c| command_row(c, cx))); + } + out.extend(space_rows); + (out, exact) + } + + fn completion_row(&self, query: &str, c: &suggest::Completion) -> Suggestion { + let private = self.model.private(); + let shown = format!("{query}{}", c.suffix); + // Enter opens the visited page the field completes to, or the tab already showing it. + let (target, detail) = match self.model.tabs.iter().find(|t| t.url == c.url.as_str() && self.model.active != Some(TabKey { private, id: t.id })) { + Some(t) => (Target::Tab(TabKey { private, id: t.id }), "Switch to Tab".to_owned()), + None => { + let detail = self.clean_user_url(c.url.clone()).as_str().trim_start_matches("https://").trim_end_matches('/').to_owned(); + (Target::Input(Input::Navigate(c.url.clone())), detail) + } + }; + Suggestion { section: None, label: ui::text::bounded_url(&shown), detail: ui::text::bounded_url(&detail), target } + } + + fn history_rows(&self, query: &str, pages: &[Page], out: &[Suggestion], completed: Option<&str>, suggest_on: bool) -> (Vec, Option) { + let private = self.model.private(); + let tabs = &self.model.tabs; + let listed: HashSet = out.iter().filter_map(|s| if let Target::Tab(k) = s.target { Some(k) } else { None }).collect(); + let skip = |ix: usize| { + if ix < tabs.len() { + let key = TabKey { private, id: tabs[ix].id }; + listed.contains(&key) || self.model.active == Some(key) + } else { + Some(pages[ix].url) == completed + } + }; + let mut ranked: Vec = suggest::rank_rows(query, pages, tabs.len(), skip, now()); + let search_text = !private && suggest::searches_text(query) && suggest_on && self.pref(crate::prefs::Pref::HistoryText); + let text_profile = self.model.current_space().filter(|_| search_text).map(|s| s.space.profile_id); + let cached = self.history_text.as_ref().filter(|(p, q, _)| Some(*p) == text_profile && q == query).map(|(_, _, found)| found.clone()); + let search_later = text_profile.filter(|_| cached.is_none()); + let found = cached.unwrap_or_default(); + // Text matches get up to half the room left; a page in both lists shows once, where it ranks if it stays there. + let room = MAX_SUGGESTIONS.saturating_sub(out.len()); + let open: HashSet<&str> = tabs.iter().map(|t| t.url.as_str()).collect(); + let found: Vec<&HistoryEntry> = found.iter().filter(|f| !open.contains(f.url.as_str()) && Some(f.url.as_str()) != completed).collect(); + let top = &ranked[..ranked.len().min(room)]; + let extra = found.iter().filter(|f| !top.iter().any(|&ix| pages[ix].url == f.url)).count(); + ranked.truncate(room - extra.min(room / 2)); + let mut found: Vec<&HistoryEntry> = found.into_iter().filter(|f| !ranked.iter().any(|&ix| pages[ix].url == f.url)).collect(); + found.truncate(room - ranked.len()); + let history_row = |url: &str, title: &str| { + Url::parse(url).ok().map(|target| Suggestion { + section: None, + label: ui::text::bounded_title(if title.is_empty() { url } else { title }), + detail: ui::text::bounded_url(url.trim_start_matches("https://").trim_end_matches('/')), + target: Target::Url(target), + }) + }; + let mut rows = Vec::new(); + for ix in ranked { + let page = pages[ix]; + if ix < tabs.len() { + rows.push(Suggestion { + section: None, + label: ui::text::bounded_title(if page.title.is_empty() { page.url } else { page.title }), + detail: "Switch to Tab".to_owned(), + target: Target::Tab(TabKey { private, id: tabs[ix].id }), + }); + } else { + rows.extend(history_row(page.url, page.title)); + } + } + rows.extend(found.into_iter().filter_map(|h| history_row(&h.url, &h.title))); + (rows, search_later) + } + + pub(crate) fn forget_text_matches(&mut self) { + (self.history_text, self.history_text_search) = (None, None); + } + + pub(super) fn search_history_text_later(&self, profile: Id, query: String, cx: &mut Context) -> Task<()> { + cx.spawn(async move |this, cx| { + cx.background_executor().timer(suggest::TEXT_SEARCH_DELAY).await; + this.update(cx, |b, cx| { + let found = b.core.disk.search_history_text(profile, &query, MAX_TEXT_MATCHES).unwrap_or_default(); + b.history_text = Some((profile, query.clone(), found)); + if b.command_mode.is_some() + && let Some(again) = b.suggested.clone().filter(|(q, _)| *q == query) + { + b.suggest(Some(again), cx); + } + }) + .ok(); + }) + } + + pub fn submit_command(&mut self, ix: usize, window: &mut Window, cx: &mut Context) { + let Some(mode) = self.command_mode else { return }; + let Some(suggestion) = self.suggestions.get(ix) else { return }; + // A search's results page is not an address the user typed, so it earns no completion credit. + let credit = !matches!(suggestion.target, Target::Input(Input::Search(_))); + let url = match &suggestion.target { + Target::Tab(key) => { + let key = *key; + self.close_command(window, cx); + if self.model.tab(key).is_none() + && let Ok(tab) = self.store(key.private).tab(key.id) + && let Some(ix) = self.model.spaces.iter().position(|s| s.private == key.private && s.space.id == tab.space_id) + { + self.switch_space(ix, window, cx); + } + self.activate(key, window, cx); + return; + } + Target::Find(key, query) => { + let (key, query) = (*key, query.clone()); + self.close_command(window, cx); + return self.open_text_match(key, query, window, cx); + } + Target::Input(Input::Command(ix)) => { + let Some((name, action)) = browser_core::palette::COMMANDS.get(*ix).and_then(|c| Some((c.0, crate::command_action(c.2)?))) else { return }; + let keys = crate::shortcuts::shown(action, cx); + self.close_command(window, cx); + window.dispatch_action(action.boxed_clone(), cx); + cx.defer_in(window, move |b, window, cx| b.offer_hint(name, &keys, window, cx)); + return; + } + Target::Action(action) => { + let action = action.boxed_clone(); + self.close_command(window, cx); + window.dispatch_action(action, cx); + return; + } + Target::Snippet(body) => { + let body = body.clone(); + self.close_command(window, cx); + return self.type_snippet(&body, cx); + } + Target::Act(item, action) => { + let (item, action) = (item.clone(), *action); + return self.run_action(ix, item, action, window, cx); + } + Target::Copy(text) => { + cx.write_to_clipboard(gpui::ClipboardItem::new_string(text.clone())); + self.close_command(window, cx); + return self.show_toast_as(browser_core::toast::Tone::Success, "Copied", None, cx); + } + Target::Url(u) => u.clone(), + Target::Input(Input::Navigate(u)) => self.clean_user_load(u.clone(), cx), + Target::Input(Input::Search(u)) => u.clone(), + Target::Input(Input::External(u)) => { + self.pending_external = Some(PendingExternal { tab: None, origin: None, url: u.clone() }); + self.layout_changed(); + self.close_command(window, cx); + return; + } + Target::Input(Input::Rejected) => { + self.rejected += 1; + return cx.notify(); + } + }; + let group = self.new_tab_group.take(); + self.close_command(window, cx); + match mode { + CommandMode::NewTab => { + let before = self.model.active; + let routed = self.open_routed(&url, window, cx); + if !routed { + self.new_tab(&url, window, cx); + if credit && self.model.active != before { + self.mark_typed(&url); + } + } + if let Some((key, group)) = self.model.active.filter(|k| !routed && Some(*k) != before).zip(group) { + self.set_tab_group(key, Some(group), cx); + } + } + CommandMode::Current | CommandMode::FindInTabs | CommandMode::Snippets => { + self.navigate(&url, window, cx); + if credit { + self.mark_typed(&url); + } + } + } + } + + pub(crate) fn mark_typed(&mut self, url: &Url) { + if let Some(key) = self.model.active { + self.pages.entry(key).or_default().typed = Some(url.to_string()); + } + } + + /// "Switch to Tab" rows for open tabs showing `url`: the current space's first, then other + /// spaces of the same profile and privacy, named in the detail. + pub(super) fn open_tabs_at(&self, url: &Url) -> Vec { + self.model + .tabs_showing(&self.core, url) + .into_iter() + .map(|(key, t, space)| Suggestion { + section: None, + label: ui::text::bounded_title(if t.title.is_empty() { &t.url } else { &t.title }), + detail: browser_core::tabs::switch_detail(space.as_deref()), + target: Target::Tab(key), + }) + .collect() + } + + pub fn resolve_external(&mut self, open: bool, cx: &mut Context) { + if open && (self.pending_external.is_none() || !self.layout_stable()) { + return; + } + if let Some(pending) = self.pending_external.take() + && open + { + engine::open_external(&pending.url); + } + cx.notify(); + } + + pub fn dismiss_error(&mut self, cx: &mut Context) { + if let Some(page) = self.model.active.and_then(|k| self.pages.get_mut(&k)) { + page.error = None; + page.notice = None; + page.offer = None; + } + cx.notify(); + } +} + +fn command_row((label, c): (String, Command), cx: &App) -> Suggestion { + let detail = crate::command_action(c).map(|a| crate::shortcuts::shown(a, cx)).unwrap_or_default(); + Suggestion { section: None, label, detail, target: Target::Input(Input::Command(c.index())) } +} diff --git a/crates/app/src/browser/events.rs b/crates/app/src/browser/events.rs new file mode 100644 index 00000000..9589cf52 --- /dev/null +++ b/crates/app/src/browser/events.rs @@ -0,0 +1,984 @@ +use super::*; + +impl Browser { + pub(super) fn on_event(&mut self, key: TabKey, event: Event, window: &mut Window, cx: &mut Context) { + // A local-network refusal is counted once, as `Event::Protected`. + match &event { + Event::Blocked { category: Some(_), .. } => self.count_on_page(key, Counter::ListedStopped, cx), + Event::PopupBlocked(url) if !url.as_ref().is_some_and(shield::rules::local_target) => self.count_on_page(key, Counter::PopupsBlocked, cx), + _ => {} + } + match event { + Event::Loading(on) => self.pages.entry(key).or_default().loading = on, + Event::LinkHovered(link) => return self.link_hovered(key, link.as_deref(), cx), + Event::AssistantSelection(command) => return self.ask_selection(key, command, cx), + Event::Committed { url, title, can_go_back, can_go_forward } => { + self.link_hovered(key, None, cx); + engine::startup::mark("first page commit"); + // A link stays the page's until it shows a page: a view slept or never made loads it as a link again. + if url.as_str() != "about:blank" { + self.link_loads.remove(&key); + self.pages.entry(key).or_default().retry = None; + } + self.drop_prompts(key, cx); + self.tarn_committed(key, &url, window, cx); + self.json_pages.remove(&key); + let previous = self.store(key.private).tab(key.id).ok().and_then(|t| tab_host(&t.url)); + self.page_changed(key, &url, &title, can_go_back, can_go_forward, true); + self.sync_assistant_menu(key); + // An Open Anyway offer belongs to the page that was refused, not to the next one; the + // blank document a new view starts with is no page. + if let Some(page) = self.pages.get_mut(&key).filter(|p| url.as_str() != "about:blank" && matches!(p.offer, Some(Offer::Open(_)))) { + (page.notice, page.offer) = (None, None); + } + let left_host = previous.as_deref() != url.host_str(); + self.apply_site_zoom(key, Some(&url), left_host); + self.apply_site_mute(key, &url, left_host); + let page = self.pages.entry(key).or_default(); + page.blocked = None; + page.visit = None; + (page.local_counted, page.https_counted) = (false, false); + self.forget_article(key, window, cx); + let unfiltered = self.views.get(&key).is_some_and(|v| !v.is_chromium() && !v.filtered()); + if unfiltered && !crate::blocking::site_host(&url).is_some_and(|h| self.site_paused_in(key, h)) { + let message = "Ad, tracker and cookie-banner blocking is off in this tab since it left a site where you paused it.".to_owned(); + self.notify_offer(key, message, Some(Offer::Reload)); + } + } + Event::Finished { url, title, can_go_back, can_go_forward } => { + self.page_changed(key, &url, &title, can_go_back, can_go_forward, false); + let page = self.pages.entry(key).or_default(); + page.crashed = false; + if let Some((_, offset)) = page.scroll_back.take().filter(|(slept, _)| slept == url.as_str()) + && let Some(view) = self.views.get(&key) + { + view.scroll_to(offset); + } + let typed = suggest::typed_visit(&mut page.typed, url.as_str()); + self.record_visit(key, &url, &title, typed); + self.request_page_text(key, &url); + self.request_favicon(key, &url); + #[cfg(feature = "translation")] + self.offer_translation(key, &url, cx); + self.probe_article(key, &url); + self.save_state(key); + self.after_load_devtools(key, &url); + if self.find_after_load.take_if(|k| *k == key).is_some() && self.find_open && self.model.active == Some(key) { + self.find(false, cx); + } + } + Event::Blocked { url, message, category } => { + suggest::typed_visit(&mut self.pages.entry(key).or_default().typed, url.as_str()); + match category { + Some(category) if category.warns() => self.show_blocked(key, url, category), + Some(_) => self.notify_offer(key, message, Some(Offer::Open(url))), + // Open Anyway loads it as the user's own navigation, which S10 lets through; the + // notice names the address, since the page chose it. + None if message == nav_policy::LOCAL_NETWORK_BLOCKED => match nav_policy::open_anyway_notice(&url) { + Some(notice) => self.notify_offer(key, notice, Some(Offer::Open(url))), + None => self.notify_offer(key, message, None), + }, + None => self.notify_offer(key, message, None), + } + } + Event::StoreInstall(id) => self.store_link(key, id, window, cx), + Event::PopupBlocked(url) => { + let message = nav_policy::popup_blocked_notice(url.as_ref()); + let offer = url.filter(|u| nav_policy::decide(u, Source::Typed) == Decision::Allow).map(Offer::NewTab); + self.notify_offer(key, message, offer); + } + Event::PopupOffered(url) => { + let message = nav_policy::popup_blocked_notice(Some(&url)); + let offer = (nav_policy::decide(&url, Source::Typed) == Decision::Allow).then_some(Offer::NewTab(url)); + self.notify_offer(key, message, offer); + } + Event::WebEngineOutdated => { + #[cfg(any(feature = "chromium", windows))] + crate::shared::check_chromium(cx); + #[cfg(windows)] + if let Some(message) = self.chromium_closed() { + self.notify_offer(key, message.to_owned(), None); + } + } + Event::WebEngineRequired(url) => { + let host = |u: &Url| ui::text::bounded_origin(u.host_str().unwrap_or_default()); + let target = host(&url); + let message = match self.views.get(&key).and_then(|v| v.url()).filter(|u| u.host_str().is_some()) { + Some(from) => format!("{} asked to open {target}. This site is set to Lockdown and opens in WebKit.", host(&from)), + None => format!("{target} is set to Lockdown and opens in WebKit."), + }; + self.notify_offer(key, message, Some(Offer::WebKit(url))); + } + Event::Failed { url, code, message } => { + // The latches stay: a page can make a load fail at will while it keeps showing, and an + // undercount after a failed upgrade beats a counter a page can run up. + let page = self.pages.entry(key).or_default(); + page.loading = false; + if let Some(url) = url { + suggest::typed_visit(&mut page.typed, url.as_str()); + } + if !IGNORED_LOAD_ERRORS.contains(&code) { + page.error = Some(message); + } + } + Event::TitleChanged(title) => { + self.store(key.private).set_tab_title(key.id, &title).ok(); + // WebKit can report an empty title for the outgoing page just before the next one commits. + if let (false, Some(profile_id), Some((visit, url))) = + (title.is_empty(), self.profile_of(key), self.pages.get(&key).and_then(|p| p.visit.clone())) + { + self.store(key.private).retitle_visit(profile_id, visit, &url, &title).ok(); + } + if self.private_matches(key) + && let Some(t) = self.model.tabs.iter_mut().find(|t| t.id == key.id) + { + t.title = title; + } + } + Event::UrlChanged { url, can_go_back, can_go_forward } => { + let page = self.pages.entry(key).or_default(); + page.can_back = can_go_back; + page.can_forward = can_go_forward; + if let Ok(tab) = self.store(key.private).tab(key.id) + && tab.url != url.as_str() + && nav_policy::decide(&url, Source::Link) == Decision::Allow + { + self.store(key.private).update_tab_page(key.id, url.as_str(), &tab.title).ok(); + if self.private_matches(key) + && let Some(t) = self.model.tabs.iter_mut().find(|t| t.id == key.id) + { + t.url = url.to_string(); + } + // A same-document navigation (pushState) is a visit like a page load, but pages + // rewrite their URL constantly (maps, anchors, search as you type): fragment + // changes, very long URLs and more than one visit per tab per interval are not + // recorded. + let mut previous = Url::parse(&tab.url).ok(); + if let Some(p) = previous.as_mut() { + p.set_fragment(None); + } + let mut target = url.clone(); + target.set_fragment(None); + // A page that rewrites its own address shows another article, or none; it is asked + // again once it has had a moment to render, as no load finishes to tell. + if previous.as_ref() != Some(&target) { + self.forget_article(key, window, cx); + let url = url.clone(); + cx.spawn(async move |this, cx| { + cx.background_executor().timer(std::time::Duration::from_secs(1)).await; + this.update(cx, |b, _| { + if b.views.get(&key).and_then(|v| v.url()).as_ref() == Some(&url) { + b.probe_article(key, &url); + } + }) + .ok(); + }) + .detach(); + } + let page = self.pages.entry(key).or_default(); + let due = page.last_visit.is_none_or(|at| at.elapsed() >= SAME_DOCUMENT_VISIT_INTERVAL); + if previous.as_ref() != Some(&target) && url.as_str().len() <= MAX_SAME_DOCUMENT_URL && due { + page.last_visit = Some(Instant::now()); + self.record_visit(key, &url, &tab.title, false); + } else { + page.visit = None; + } + } + } + Event::Prompt(prompt) => { + // A prompt shows with the shell's origin chip, never over a full-screen page. + if self.model.active == Some(key) { + self.leave_page_fullscreen(window); + } + self.queue_prompt(key, prompt, window, cx); + } + Event::Popup(popup) => self.adopt_popup(key, popup, window, cx), + Event::ShieldLevelChanged(url) => self.rebuild_view(key, &url, cx), + Event::RebuildForLink(url) => self.rebuild_view_for_link(key, &url, cx), + Event::PeekLink(url, from) => { + if self.model.active == Some(key) { + self.open_link_peek(key, url, from, window, cx); + } + } + // As a pop-up's tab: never in the burner, and its first load is the page's link, so S10 judges every hop. + Event::OpenTab { url, from, background, split } => { + let Some(opener) = self.model.tab(key).filter(|_| !self.model.burner_shown()) else { return cx.notify() }; + let engine = opener.web_engine.or(self.saved.web_engine); + let routed = self.routed_space(&url); + if let Some(ix) = routed { + self.switch_space(ix, window, cx); + } + if let Some(tab) = self.model.open_tab(&self.core, url.as_str(), engine, Opened::Link(key)) { + self.reload_space(); + self.link_loads.insert(tab, from.clone()); + if split && routed.is_none() { + self.split_link(key, tab, window, cx); + } else if !background || routed.is_some() { + self.activate(tab, window, cx); + } else if let Some(view) = self.create_view(tab, url.as_str(), cx) { + // Loaded now, as a pop-up is: a tab restored later would load its URL as the user's own. + view.set_visible(false); + view.load_link(&url, from.as_ref()); + } + } + } + Event::ExternalScheme { url, origin } => { + let showing = self.pending_external.as_ref().is_some_and(|p| p.tab.is_none_or(|t| t == key)); + if self.model.active == Some(key) && !showing { + self.pending_external = Some(PendingExternal { tab: Some(key), origin, url }); + self.layout_changed(); + } + } + event @ (Event::DownloadFinished { .. } + | Event::DownloadFailed { .. } + | Event::DownloadCancelled(_) + | Event::DownloadsActive(_) + | Event::DownloadProgress { .. }) => { + if let Some(profile_id) = self.profile_of(key) { + self.core.downloads.unbounded_send((key.private, profile_id, event)).ok(); + } + return; + } + Event::Protected(protection, target) => { + let page = self.pages.entry(key).or_default(); + let (latch, counter) = match protection { + engine::Protection::HttpsUpgrade => (&mut page.https_counted, Counter::HttpsUpgrades), + engine::Protection::LocalNetwork => (&mut page.local_counted, Counter::LocalBlocked), + }; + let counter = (!std::mem::replace(latch, true)).then_some(counter); + // An upgrade is the upgraded site's; a refusal is the page's that tried it, unless the + // tab shows nothing but the refused address (a link from another app). + let page = self.tab_url(key).and_then(|u| Url::parse(&u).ok()).filter(|u| !shield::rules::local_target(u)); + let host = target.or_else(|| page.as_ref().and_then(page_host)); + if let (Some(counter), Some(profile_id)) = (counter, self.profile_of(key)) { + self.count_shield(key.private, profile_id, counter, 1, host.as_deref(), cx); + } + } + Event::FullScreen(on) => self.set_page_fullscreen(key, on, window), + Event::ExtensionMessage { world, frame, origin, json } => { + if let Some(profile) = self.profile_of(key).filter(|_| !key.private) { + self.core.tarn.borrow().send(crate::tarn_ext::Msg::Tab { profile, tab: key.id as u64, world, frame, origin, json }); + } + } + Event::ContentProcessTerminated => { + self.link_hovered(key, None, cx); + if self.model.active == Some(key) { + self.leave_page_fullscreen(window); + } + self.drop_prompts(key, cx); + let page = self.pages.entry(key).or_default(); + if page.crashed { + page.loading = false; + page.error = Some("The page crashed again and was not reloaded.".into()); + } else if let Some(view) = self.views.get(&key) { + page.crashed = true; + view.recover(); + } + } + } + cx.notify(); + } + + /// The active tab's page alone fills the window, in full screen, while it shows an element + /// full screen; leaving restores the window as it was. + pub(super) fn set_page_fullscreen(&mut self, key: TabKey, on: bool, window: &mut Window) { + if self.model.active != Some(key) { + return; + } + if !on { + return self.leave_page_fullscreen(window); + } + let Some(view) = self.views.get(&key).cloned() else { return }; + // Nothing the shell must show may be hidden: a pending prompt keeps the toolbar and its origin. + let Some(entered) = self.page_fullscreen.enter(self.active_prompt().is_some(), window.is_fullscreen()) else { return }; + if entered { + window.toggle_fullscreen(); + } + view.set_corner_radius(0.); + view.raise(); + self.layout_changed(); + } + + /// Whether the window may show the full-screen page alone: no prompt, overlay, address field, + /// find bar or notice of the shell waits to be seen, and the page is still the active one. + pub(crate) fn page_fullscreen_holds(&self) -> bool { + browser_core::fullscreen::Shell { + page: self.active_view().is_some(), + prompt: self.active_prompt().is_some(), + overlay: self.overlay_open(), + address: self.command_mode.is_some(), + find: self.find_open, + notice: self.model.active.and_then(|k| self.pages.get(&k)).is_some_and(|p| p.notice.is_some() || p.blocked.is_some()), + } + .lets_page_fill_window() + } + + /// Gives the window back its sidebar, toolbar and size: when the page leaves full screen, and + /// when a prompt, another tab or a crash needs the shell. The page itself may stay full screen + /// inside the tab until it is put away. + pub(crate) fn leave_page_fullscreen(&mut self, window: &mut Window) { + let Some(entered) = self.page_fullscreen.leave() else { return }; + if entered && window.is_fullscreen() { + window.toggle_fullscreen(); + } + if let Some(view) = self.active_view() { + view.set_corner_radius(page_corner()); + } + self.layout_changed(); + } + + pub(super) fn record_visit(&mut self, key: TabKey, url: &Url, title: &str, typed: bool) { + if let Some(profile_id) = self.profile_of(key) + && matches!(url.scheme(), "http" | "https") + && self.core.keeps_records(key.private, profile_id) + { + let visit = self.store(key.private).add_history(profile_id, url.as_str(), title, now(), typed).ok().map(|id| (id, url.to_string())); + self.menu.visited(url.as_str()); + self.pages.entry(key).or_default().visit = visit; + } + } + + /// Only after a full load: a same-document visit would read the previous route's text. + pub(super) fn request_page_text(&mut self, key: TabKey, url: &Url) { + let visit = self.pages.get(&key).and_then(|p| p.visit.clone()).filter(|(_, u)| u == url.as_str()); + let (Some(profile_id), Some((visit, page)), Some(view)) = (self.profile_of(key), visit, self.views.get(&key)) else { return }; + if key.private || !self.pref(crate::prefs::Pref::HistoryText) || self.level_for_tab(key, url.as_str()) == ShieldLevel::Lockdown { + return; + } + let events = self.events.clone(); + view.page_text(url, store::MAX_HISTORY_TEXT, move |_, text| { + events.unbounded_send(Msg::PageText(profile_id, visit, page.clone(), text)).ok(); + }); + } + + /// Only the disk store keeps page text, so the private space never does. + pub(super) fn store_page_text(&mut self, profile_id: Id, visit: Id, url: &str, text: String) { + if text.is_empty() || !self.pref(crate::prefs::Pref::HistoryText) { + return; + } + self.core.disk.set_history_text(profile_id, visit, url, store::clip_history_text(&text)).ok(); + } + + /// Replaces the tab's view with one built for `url`'s Shield level and rules, then loads it. + pub(crate) fn rebuild_view(&mut self, key: TabKey, url: &Url, cx: &mut Context) { + self.rebuild_view_with(key, url, None, cx); + } + + /// Rebuilds the tab's view for a page's navigation, which the new view judges as the page's link. + pub(super) fn rebuild_view_for_link(&mut self, key: TabKey, url: &Url, cx: &mut Context) { + let opener = self.link_loads.get(&key).cloned().unwrap_or_else(|| self.views.get(&key).and_then(|v| v.url())); + self.rebuild_view_loading(key, url, None, Some(opener), cx); + } + + /// Rebuilds the tab's view, handing `storage` to the new one before its first load. + pub(crate) fn rebuild_view_with(&mut self, key: TabKey, url: &Url, storage: Option, cx: &mut Context) { + self.rebuild_view_loading(key, url, storage, None, cx); + } + + /// With `link`, the URL loads as a link from that page (or from none), not as typed. + pub(super) fn rebuild_view_loading( + &mut self, + key: TabKey, + url: &Url, + storage: Option, + link: Option>, + cx: &mut Context, + ) { + if self.model.tab(key).is_some() && self.views.remove(&key).is_some() { + self.forget_media(key); + // The old view's last events are dropped; the new one says when its load starts. + let page = self.pages.entry(key).or_default(); + page.loading = false; + page.retry = link.is_none().then(|| url.clone()); + self.drop_prompts(key, cx); + let active = self.model.active == Some(key); + let visible = (active || self.in_split(key)) && !self.overlay_open(); + if let Some(view) = self.create_view(key, url.as_str(), cx) { + if let Some(storage) = storage { + view.hand_over(storage); + } + match &link { + None if self.pages.get(&key).and_then(|p| p.opened_file.as_ref()) == Some(url) => view.load_file(url), + Some(opener) => view.load_link(url, opener.as_ref()), + None => view.load(url), + } + view.set_visible(visible); + if visible && active { + view.focus(); + } + } + } + } + + pub(super) fn site_paused_in(&self, key: TabKey, host: &str) -> bool { + self.profile_of(key).and_then(|p| self.loaded(key.private, p)).is_some_and(|rt| rt.rules.paused.borrow().contains(host)) + } + + /// Shield level for `url` under the profile that owns `key`, which may not be the current space's. + pub fn level_for_tab(&self, key: TabKey, url: &str) -> ShieldLevel { + self.profile_of(key).and_then(|p| self.core.level(key.private, p, Url::parse(url).ok().as_ref())).unwrap_or(ShieldLevel::Lockdown) + } + + pub(crate) fn queue_prompt(&mut self, key: TabKey, prompt: Prompt, window: &mut Window, cx: &mut Context) { + if !self.views.contains_key(&key) { + return; + } + if let Some(permission) = prompt.kind.permission_key() { + let page = prompt.top_origin.as_deref().unwrap_or(&prompt.origin); + let level = self.level_for_tab(key, page).max(self.level_for_tab(key, &prompt.origin)); + if level == ShieldLevel::Lockdown { + return; + } + let stored = (level == ShieldLevel::Standard).then(|| self.profile_of(key)).flatten().and_then(|p| { + self.store(key.private).permission(p, &permission_origin(&prompt.origin, prompt.top_origin.as_deref()), permission).ok().flatten() + }); + match stored.as_deref() { + Some("allow") => return prompt.accept("", None), + Some("deny") => return, + _ => {} + } + } + let queue = self.prompts.entry(key).or_default(); + if queue.len() >= MAX_QUEUED_PROMPTS { + return; + } + queue.push_back(prompt); + if queue.len() == 1 && self.model.active == Some(key) { + self.prepare_prompt(window, cx); + } + } + + /// Discards a tab's prompts (each declines on drop) and its external-app request, and clears what + /// the user typed into them. + pub(super) fn drop_prompts(&mut self, key: TabKey, cx: &mut Context) { + if self.pending_external.as_ref().is_some_and(|p| p.tab == Some(key)) { + self.pending_external = None; + } + if self.prompts.remove(&key).is_none_or(|q| q.is_empty()) || self.model.active != Some(key) { + return; + } + for input in [&self.prompt_input, &self.auth_user, &self.auth_pass] { + input.update(cx, |i, cx| i.set_text("", cx)); + } + self.refocus = true; + if self.model.active == Some(key) + && let Some(view) = self.views.get(&key) + { + view.focus(); + } + } + + /// The find, prompt or command field has focus while the bar or card holding it is not drawn. + pub(crate) fn hidden_field_focused(&self, window: &Window, cx: &App) -> bool { + let focused = |input: &Entity| input.focus_handle(cx).is_focused(window); + let card = !self.overlay_open(); + (focused(&self.find_input) && !(card && self.find_open && self.active_json().is_none())) + || ([&self.prompt_input, &self.auth_user, &self.auth_pass].into_iter().any(focused) && !(card && self.active_prompt().is_some())) + || (focused(&self.command) && self.command_mode.is_none()) + } + + pub fn active_prompt(&self) -> Option<&Prompt> { + self.prompts.get(&self.model.active?)?.front() + } + + pub(super) fn prepare_prompt(&mut self, window: &mut Window, cx: &mut Context) { + if self.overlay_open() { + return; + } + let Some(kind) = self.active_prompt().map(|p| p.kind.clone()) else { return }; + self.remember_permission = false; + self.layout_changed(); + if let Some(host) = &self.host { + host.focus(); + } + let focus = match kind { + PromptKind::Text { default } => { + self.prompt_input.update(cx, |i, cx| i.set_text(default, cx)); + self.prompt_input.focus_handle(cx) + } + PromptKind::Credentials { .. } => { + self.auth_user.update(cx, |i, cx| i.set_text("", cx)); + self.auth_pass.update(cx, |i, cx| i.set_text("", cx)); + self.auth_user.focus_handle(cx) + } + _ => self.focus.clone(), + }; + window.focus(&focus); + cx.notify(); + } + + pub fn answer_prompt(&mut self, accept: bool, silence: bool, window: &mut Window, cx: &mut Context) { + let Some(key) = self.model.active else { return }; + if accept && self.prompt_guarded() { + return; + } + let Some(prompt) = self.prompts.get_mut(&key).and_then(VecDeque::pop_front) else { return }; + let page = prompt.top_origin.clone().unwrap_or_else(|| prompt.origin.clone()); + if matches!(prompt.kind, PromptKind::ExtensionAccess { .. }) { + match (self.remember_permission, silence) { + (true, false) => prompt.remember(accept), + (false, false) if accept => prompt.accept("", None), + _ => prompt.decline(), + } + return self.after_prompt(window, cx); + } + if let Some(permission) = prompt.kind.permission_key() + && self.remember_permission + && self.level_for_tab(key, &page).max(self.level_for_tab(key, &prompt.origin)) == ShieldLevel::Standard + && let Some(profile_id) = self.profile_of(key) + { + let decision = if accept { "allow" } else { "deny" }; + self.store(key.private).set_permission(profile_id, &permission_origin(&prompt.origin, prompt.top_origin.as_deref()), permission, decision).ok(); + } + match (accept, silence) { + (_, true) => { + prompt.decline_and_silence_page(); + self.drop_prompts(key, cx); + } + (true, _) => { + let text = self.prompt_input.read(cx).text().to_owned(); + let user = self.auth_user.read(cx).text().to_owned(); + let pass = self.auth_pass.read(cx).text().to_owned(); + let credentials = matches!(prompt.kind, PromptKind::Credentials { .. }).then_some((user.as_str(), pass.as_str())); + prompt.accept(&text, credentials); + } + (false, _) => prompt.decline(), + } + self.after_prompt(window, cx); + } + + /// Esc declines the prompt in front, as Cancel or Deny does, without remembering the answer. + pub(crate) fn dismiss_prompt(&mut self, window: &mut Window, cx: &mut Context) { + self.remember_permission = false; + self.answer_prompt(false, false, window, cx); + } + + /// Enter answers an alert or confirm whose card holds the focus; permission and download + /// warnings stay mouse-only, behind their click guard. + pub(crate) fn prompt_key(&mut self, event: &gpui::KeyDownEvent, window: &mut Window, cx: &mut Context) { + let simple = self.active_prompt().is_some_and(|p| matches!(p.kind, PromptKind::Alert | PromptKind::Confirm)); + let plain = !event.keystroke.modifiers.modified(); + if event.keystroke.key == "enter" && !event.is_held && plain && simple && !self.overlay_open() && self.focus.is_focused(window) { + cx.stop_propagation(); + self.answer_prompt(true, false, window, cx); + } + } + + pub(super) fn after_prompt(&mut self, window: &mut Window, cx: &mut Context) { + for input in [&self.prompt_input, &self.auth_user, &self.auth_pass] { + input.update(cx, |i, cx| i.set_text("", cx)); + } + if self.active_prompt().is_some() { + self.prepare_prompt(window, cx); + } else { + window.focus(&self.focus); + if let Some(view) = self.active_view() { + view.focus(); + } + cx.notify(); + } + } + + /// A permission prompt's Allow and Remember, and Keep Anyway on a malware warning, ignore clicks for a + /// moment after they appear, so a page cannot time a click to land on them. + pub(crate) fn prompt_guarded(&self) -> bool { + self.active_prompt().is_some_and(|p| p.kind.is_permission() || matches!(p.kind, PromptKind::MaliciousDownload { .. })) && !self.layout_stable() + } + + pub(super) fn on_prompt_input_event(&mut self, input: &Entity, event: &TextInputEvent, window: &mut Window, cx: &mut Context) { + match event { + TextInputEvent::Submit if input == &self.auth_user => { + let focus = self.auth_pass.focus_handle(cx); + window.focus(&focus); + } + TextInputEvent::Submit => self.answer_prompt(true, false, window, cx), + TextInputEvent::Cancel => self.answer_prompt(false, false, window, cx), + _ => {} + } + } + + /// In the reader, finds on the page it was made from, which the reader then gives way to. + pub fn open_find(&mut self, window: &mut Window, cx: &mut Context) { + if self.active_view().is_none() || self.card_open() || self.active_json().is_some() { + return; + } + if self.reader_shown() { + self.toggle_reader(window, cx); + } + self.find_open = true; + self.find_count = None; + let text = self.find_input.read(cx).text().to_owned(); + self.find_input.update(cx, |i, cx| i.set_text(text, cx)); + if let Some(host) = &self.host { + host.focus(); + } + let focus = self.find_input.focus_handle(cx); + window.focus(&focus); + cx.notify(); + } + + pub fn close_find(&mut self, window: &mut Window, cx: &mut Context) { + self.find_open = false; + self.find_typing = None; + window.focus(&self.focus); + if let Some(view) = self.active_view() { + view.clear_find(); + view.focus(); + } + cx.notify(); + } + + pub fn find(&mut self, backwards: bool, cx: &mut Context) { + let text = self.find_input.read(cx).text().to_owned(); + let Some(view) = self.active_view().filter(|_| !text.is_empty()) else { return }; + let events = self.events.clone(); + view.find(&text, backwards, move |found, current| { + events.unbounded_send(Msg::Found(found, current)).ok(); + }); + } + + pub(super) fn on_find_event(&mut self, _: &Entity, event: &TextInputEvent, window: &mut Window, cx: &mut Context) { + match event { + TextInputEvent::Submit | TextInputEvent::Down => { + self.find_typing = None; + self.find(false, cx) + } + TextInputEvent::Up => { + self.find_typing = None; + self.find(true, cx) + } + TextInputEvent::Cancel => self.close_find(window, cx), + TextInputEvent::Changed => { + self.find_count = None; + if self.find_input.read(cx).text().is_empty() { + self.find_typing = None; + if let Some(view) = self.active_view() { + view.clear_find(); + } + } else { + self.find_typing = Some(cx.spawn(async move |this, cx| { + cx.background_executor().timer(browser_core::find::TYPING_DELAY).await; + this.update(cx, |b, cx| { + if b.find_open { + b.find(false, cx); + } + }) + .ok(); + })); + } + cx.notify(); + } + TextInputEvent::MenuClosed | TextInputEvent::PastEnd => {} + } + } + + pub fn print(&mut self) { + if let Some(view) = self.active_view() { + view.print(); + } + } + + pub(super) fn adopt_popup(&mut self, opener: TabKey, popup: Popup, window: &mut Window, cx: &mut Context) { + let Some(host) = self.host.clone() else { return }; + if self.model.tab(opener).is_none() || self.model.burner_shown() { + return; + } + // A script's window.open keeps its opener, which sign-in and payment pop-ups need, so only links are routed. + if popup.link && popup.url.clone().is_some_and(|url| self.open_routed(&url, window, cx)) { + return; + } + let Some(space) = self.model.current_space() else { return }; + let (private, space_id) = (space.private, space.space.id); + let url = popup.url.as_ref().map_or("about:blank".to_owned(), Url::to_string); + let Ok(tab) = self.store(private).create_tab(space_id, TabKind::Ephemeral, None, &url, "") else { + return; + }; + let key = TabKey { private, id: tab.id }; + // On macOS only WebKit views adopt pop-ups, so an opener with an engine of its own ran in WebKit. + if cfg!(target_os = "macos") { + self.store(private).set_tab_web_engine(tab.id, self.model.tab(opener).and_then(|t| t.web_engine).map(|_| WebEngine::WebKit)).ok(); + } + let inspectable = self.developer || self.is_dev_tab(opener); + let Some(view) = WebView::adopt(popup, &host, inspectable, self.sink(key)) else { + self.store(private).delete_tab(tab.id).ok(); + return; + }; + view.set_corner_radius(page_corner()); + view.set_dark(!ui::theme::Theme::is_light()); + self.view_prefs(&view); + self.views.insert(key, Rc::new(view)); + self.link_loads.insert(key, None); + self.attach_tarn(key); + self.reload_space(); + self.activate(key, window, cx); + } + + pub(super) fn page_changed(&mut self, key: TabKey, url: &Url, title: &str, back: bool, forward: bool, loading: bool) { + let page = self.pages.entry(key).or_default(); + page.can_back = back; + page.can_forward = forward; + page.loading = loading; + page.error = None; + self.store(key.private).update_tab_page(key.id, url.as_str(), title).ok(); + if self.private_matches(key) + && let Some(t) = self.model.tabs.iter_mut().find(|t| t.id == key.id) + { + t.url = url.to_string(); + t.title = title.to_owned(); + } + } + + pub(super) fn private_matches(&self, key: TabKey) -> bool { + key.private == self.model.private() + } + + pub(crate) fn profile_of(&self, key: TabKey) -> Option { + self.model.profile_of(&self.core, key) + } + + pub fn back(&mut self) { + if let Some(v) = self.active_view() { + v.back(); + } + } + + pub fn forward(&mut self) { + if let Some(v) = self.active_view() { + v.forward(); + } + } + + pub fn reload(&mut self, cx: &mut Context) { + let dev = self.model.active.is_some_and(|k| self.is_dev_tab(k)); + self.reload_page(dev, cx); + } + + pub fn reload_page(&mut self, from_origin: bool, cx: &mut Context) { + let Some(key) = self.model.active else { return }; + if !self.reload_view(key, from_origin) { + return; + } + self.reload_spin = Some((key, Instant::now())); + cx.spawn(async move |this, cx| { + cx.background_executor().timer(crate::toolbar::SPIN).await; + this.update(cx, |_, cx| cx.notify()).ok(); + }) + .detach(); + cx.notify(); + } + + pub(crate) fn reload_view(&self, key: TabKey, from_origin: bool) -> bool { + let Some(v) = self.views.get(&key) else { return false }; + let page = self.pages.get(&key); + let unloaded = (v.url().is_none() && !page.is_some_and(|p| p.loading)) + .then(|| page.and_then(|p| p.retry.clone()).or_else(|| self.model.tab(key).and_then(|t| Url::parse(&t.url).ok()))) + .flatten(); + if let Some(url) = unloaded { + self.load_tab_url(key, v, url) + } else if from_origin { + v.reload_from_origin() + } else { + v.reload() + } + true + } + + pub fn stop_loading(&mut self, cx: &mut Context) { + self.reload_spin = None; + if let Some(view) = self.active_view() { + view.stop(); + } + cx.notify(); + } + + pub(super) fn is_dev_tab(&self, key: TabKey) -> bool { + self.profile_of(key).and_then(|p| self.loaded(key.private, p)).is_some_and(|rt| rt.profile.is_dev) + } + + pub(super) fn after_load_devtools(&mut self, key: TabKey, url: &Url) { + let dev = self.is_dev_tab(key); + if dev && let Some(rt) = self.profile_of(key).and_then(|p| self.loaded(key.private, p)) { + rt.data.clear_cache(); + #[cfg(feature = "chromium")] + engine::chromium::clear_cache(&data_dir().join("Chromium"), &rt.own_store); + } + if !(self.developer || dev) { + return; + } + let Some(view) = self.views.get(&key) else { return }; + let (events, page) = (self.events.clone(), url.clone()); + view.json_text(url, devkit::json_view::MAX_BYTES, move |text| { + if !text.is_empty() { + events.unbounded_send(Msg::Json(key, page.clone(), text)).ok(); + } + }); + } + + pub(super) fn show_json(&mut self, key: TabKey, url: Url, text: String, cx: &mut Context) { + cx.spawn(async move |this, cx| { + let page = cx.background_spawn(async move { JsonPage::parse(url, &text) }).await; + this.update(cx, |b, cx| { + let current = b.views.get(&key).and_then(|v| v.url()); + if let Ok(page) = page + && current.as_ref() == Some(&page.url) + { + b.json_pages.insert(key, page); + cx.notify(); + } + }) + .ok(); + }) + .detach(); + } + + pub fn set_json_raw(&mut self, key: TabKey, raw: bool, cx: &mut Context) { + if let Some(page) = self.json_pages.get_mut(&key) { + page.set_raw(raw); + cx.notify(); + } + } + + pub fn toggle_json_node(&mut self, key: TabKey, path: Vec, cx: &mut Context) { + if let Some(page) = self.json_pages.get_mut(&key) { + page.toggle(path); + cx.notify(); + } + } + + pub fn active_json(&self) -> Option<(TabKey, &JsonPage)> { + let key = self.model.active?; + self.json_pages.get(&key).map(|p| (key, p)) + } + + pub fn current_is_dev(&self) -> bool { + self.current_loaded().is_some_and(|rt| rt.profile.is_dev) + } + + pub fn devtools_on(&self) -> bool { + self.developer || self.current_is_dev() + } + + /// Web Inspector availability is fixed when a view is created, so every live view is rebuilt. + pub fn set_developer(&mut self, on: bool, window: &mut Window, cx: &mut Context) { + if self.core.disk.set_setting(DEVELOPER_SETTING, if on { "on" } else { "off" }).is_err() { + return; + } + self.apply_developer(on, cx); + crate::shared::others(cx, |b, _, cx| b.apply_developer(on, cx)); + let profiles: Vec<(bool, Id)> = self.core.profiles.borrow().iter().filter(|(_, rt)| !rt.profile.is_dev).map(|(k, _)| *k).collect(); + for (private, id) in profiles { + self.restart_profile_views(private, id, None, false, window, cx); + } + cx.notify(); + } + + pub(super) fn apply_developer(&mut self, on: bool, cx: &mut Context) { + self.developer = on; + if on { + self.refresh_local_servers(cx); + } else if !self.current_is_dev() { + self.set_responsive(None, cx); + } + cx.notify(); + } + + pub fn create_dev_profile(&mut self, window: &mut Window, cx: &mut Context) { + let existing = self.core.disk.profiles().unwrap_or_default().into_iter().find(|p| p.is_dev); + let space = match existing { + Some(p) => self.core.disk.spaces(p.id).ok().and_then(|s| s.into_iter().next()), + None => self.core.disk.create_dev_profile(&uuid::Uuid::new_v4().to_string()).ok().map(|(_, space)| space), + }; + let Some(space) = space else { return }; + self.refresh_local_servers(cx); + self.reload_spaces(); + let ix = self.model.spaces.iter().position(|s| !s.private && s.space.id == space.id).unwrap_or(0); + self.switch_space(ix, window, cx); + } + + pub fn refresh_local_servers(&mut self, cx: &mut Context) { + cx.spawn(async move |this, cx| { + let ports = cx.background_spawn(async { devkit::localhost::open_dev_ports() }).await; + this.update(cx, |b, cx| { + b.local_servers = Some(ports); + cx.notify(); + }) + .ok(); + }) + .detach(); + } + + pub fn open_local_server(&mut self, port: u16, window: &mut Window, cx: &mut Context) { + if let Ok(url) = Url::parse(&format!("http://localhost:{port}/")) { + self.new_tab(&url, window, cx); + } + } + + pub fn cycle_responsive(&mut self, cx: &mut Context) { + let next = match self.responsive { + None => Some(0), + Some(i) if i + 1 < devkit::responsive::PRESETS.len() => Some(i + 1), + Some(_) => None, + }; + self.set_responsive(next, cx); + } + + pub(super) fn set_responsive(&mut self, preset: Option, cx: &mut Context) { + match (self.responsive.is_some(), preset.is_some()) { + (false, true) => self.zoom_before_responsive = self.views.iter().map(|(k, v)| (*k, v.zoom())).collect(), + (true, false) => { + for (key, view) in &self.views { + view.set_zoom(self.zoom_before_responsive.get(key).copied().unwrap_or(1.0)); + } + self.zoom_before_responsive.clear(); + } + _ => {} + } + self.responsive = preset; + cx.notify(); + } + + /// The preset applies only while the developer tools that control it are shown. + pub fn responsive_preset(&self) -> Option { + self.responsive.filter(|_| self.devtools_on()).and_then(|i| devkit::responsive::PRESETS.get(i)).copied() + } + + pub(super) fn responsive_active(&self) -> bool { + self.responsive_preset().is_some() + } + + /// The first click asks; a second click on the same tab and host clears. + pub fn clear_site_data(&mut self, cx: &mut Context) { + let Some(key) = self.model.active else { return }; + let Some(host) = self.active_view().and_then(|v| v.url()).and_then(|u| u.host_str().map(str::to_owned)) else { return }; + if self.clear_site_armed.take() != Some((key, host.clone())) { + self.clear_site_armed = Some((key, host.clone())); + self.notify_offer(key, format!("Click Clear Site Data again to remove cookies, storage and caches of {host}."), None); + cx.notify(); + return; + } + self.clear_site(key, host, cx); + } + + /// Removes every WebKit data type of `host` in the tab's profile, then reloads the tab. + pub(crate) fn clear_site(&mut self, key: TabKey, host: String, cx: &mut Context) { + if let Some(profile_id) = self.profile_of(key).filter(|_| !key.private) + && self.core.disk.unzap_element(profile_id, &host, None).is_ok() + { + crate::zaps::apply(&self.core, false, profile_id); + } + let Some(rt) = self.profile_of(key).and_then(|p| self.loaded(key.private, p)) else { return }; + #[cfg(feature = "chromium")] + self.clear_chromium_site(&rt.own_store, &host); + let this = cx.entity().downgrade(); + let mut async_cx = cx.to_async(); + rt.data.clear_site_data(&host.clone(), move |count| { + this.update(&mut async_cx, |b, cx| { + let message = if count == 0 { format!("{host} had no stored data.") } else { format!("Cleared stored data for {host}.") }; + b.notify_offer(key, message, None); + b.reload_view(key, false); + cx.notify(); + }) + .ok(); + }); + } +} diff --git a/crates/app/src/browser/profile.rs b/crates/app/src/browser/profile.rs new file mode 100644 index 00000000..4db7a4ad --- /dev/null +++ b/crates/app/src/browser/profile.rs @@ -0,0 +1,601 @@ +use super::*; + +impl Browser { + pub fn toggle_sidebar(&mut self, cx: &mut Context) { + if self.tab_placement == browser_core::layout::TabPlacement::Top { + return self.toggle_tabs_on_top(cx); + } + self.set_sidebar_open(!self.sidebar_open, cx); + } + + /// Tabs on top hide this window's sidebar without forgetting whether it was open. + pub fn toggle_tabs_on_top(&mut self, cx: &mut Context) { + self.tab_placement = self.tab_placement.toggled(&self.core.disk); + let open = self.tab_placement == browser_core::layout::TabPlacement::Side && crate::prefs::sidebar_open(&self.core.disk); + self.slide_sidebar(open); + self.close_peek(cx); + self.hide_hover_card(cx); + cx.notify(); + } + + pub fn open_settings(&mut self, window: &mut Window, cx: &mut Context) { + if self.in_main(window, cx, |b, window, cx| b.open_settings(window, cx)) { + return; + } + if let Some(handle) = self.settings_window + && handle.update(cx, |_, settings_window, _| settings_window.activate_window()).is_ok() + { + return; + } + let Some(main) = window.window_handle().downcast::() else { return }; + let browser = cx.entity().downgrade(); + // The new window renders from the browser at once, so it must open after this update ends. + cx.defer(move |cx| { + let handle = SettingsWindow::open(browser.clone(), main, cx); + browser.update(cx, |b, _| b.settings_window = handle).ok(); + }); + } + + pub fn open_settings_pane(&mut self, pane: crate::settings::SettingsPane, window: &mut Window, cx: &mut Context) { + if self.in_main(window, cx, move |b, window, cx| b.open_settings_pane(pane, window, cx)) { + return; + } + self.open_settings(window, cx); + let browser = cx.entity().downgrade(); + cx.defer(move |cx| { + if let Some(handle) = browser.upgrade().and_then(|b| b.read(cx).settings_window) { + handle.update(cx, |settings, _, cx| settings.set_pane(pane, cx)).ok(); + } + }); + } + + pub fn current_profile(&self) -> Option { + self.current_loaded().map(|rt| rt.profile.clone()) + } + + /// The current profile without copying it, for checks that run every frame. + pub(crate) fn current_loaded(&self) -> Option> { + let space = self.model.current_space()?; + self.loaded(space.private, space.space.profile_id) + } + + pub fn site_overrides(&self) -> Vec<(String, ShieldLevel)> { + let Some(space) = self.model.current_space() else { return Vec::new() }; + let Some(rt) = self.loaded(space.private, space.space.profile_id) else { return Vec::new() }; + let mut list: Vec<_> = rt.overrides.borrow().iter().map(|(h, l)| (h.clone(), *l)).collect(); + list.sort(); + list + } + + pub fn all_profiles(&self) -> Vec { + let burners = self.core.burners.borrow(); + [false, true] + .into_iter() + .flat_map(|private| self.store(private).profiles().unwrap_or_default()) + .filter(|p| !(p.is_private && burners.contains(&p.id))) + .collect() + } + + pub(crate) fn shield_wipes_data(&self, level: ShieldLevel) -> bool { + self.current_loaded().is_some_and(|rt| browser_core::profiles::shield_wipes_data(level, self.model.private(), rt.profile.shield_level)) + } + + pub(crate) fn shield_target(&self) -> Option<(bool, Id)> { + self.model.current_space().map(|space| (space.private, space.space.profile_id)) + } + + pub fn set_profile_shield(&mut self, level: ShieldLevel, window: &mut Window, cx: &mut Context) { + let Some(target) = self.shield_target() else { return }; + if !self.shield_wipes_data(level) { + return self.apply_profile_shield(target, level, window, cx); + } + let name = self.current_profile().map(|p| ui::text::bounded_title(&p.name)).unwrap_or_default(); + let question = crate::settings::lockdown_question(&name); + let answer = window.prompt(gpui::PromptLevel::Warning, &question, Some(crate::settings::LOCKDOWN_WIPE), &["Use Lockdown", "Cancel"], cx); + cx.spawn_in(window, async move |this, cx| { + if answer.await == Ok(0) { + this.update_in(cx, |b, window, cx| b.apply_profile_shield(target, level, window, cx)).ok(); + } + }) + .detach(); + } + + pub(crate) fn apply_profile_shield(&mut self, (private, profile_id): (bool, Id), level: ShieldLevel, window: &mut Window, cx: &mut Context) { + if self.store(private).set_profile_shield_level(profile_id, level).is_err() { + return; + } + let new_store = match self.core.profiles.borrow_mut().get_mut(&(private, profile_id)) { + Some(rt) => { + let crossing = !private && (rt.profile.shield_level == ShieldLevel::Lockdown) != (level == ShieldLevel::Lockdown); + rt.profile.shield_level = level; + crossing + } + None => false, + }; + if !new_store { + self.core.apply_extensions(private, profile_id); + } + if !private { + crate::tarn_ext::level_changed(&self.core, profile_id, cx); + } + self.restart_profile_views(private, profile_id, None, new_store, window, cx); + #[cfg(feature = "chromium")] + if new_store + && level == ShieldLevel::Lockdown + && let Some(own_store) = self.loaded(private, profile_id).map(|rt| rt.own_store.clone()) + { + self.wipe_chromium(&own_store, &own_store); + } + } + + pub fn remove_site_override(&mut self, host: &str, window: &mut Window, cx: &mut Context) { + self.set_site_shield(host, None, window, cx); + } + + /// Content rules are fixed when a web view is created, so a level change needs new views, in + /// every window. `new_store` also replaces the profile's data store, for a move into or out of + /// Lockdown. + pub(crate) fn restart_profile_views( + &mut self, + private: bool, + profile_id: Id, + host: Option<&str>, + new_store: bool, + window: &mut Window, + cx: &mut Context, + ) { + self.core.sync_shield(); + self.restart_views_here(private, profile_id, host, new_store, window, cx); + crate::shared::others(cx, |b, window, cx| b.restart_views_here(private, profile_id, host, false, window, cx)); + } + + pub(crate) fn restart_views_here( + &mut self, + private: bool, + profile_id: Id, + host: Option<&str>, + new_store: bool, + window: &mut Window, + cx: &mut Context, + ) { + let on_host = |view: &WebView| host.is_none_or(|h| view.url().is_some_and(|u| u.host_str().map(|s| s.trim_end_matches('.')) == Some(h))); + let keys: Vec = + self.views.iter().filter(|(k, v)| k.private == private && self.profile_of(**k) == Some(profile_id) && on_host(v)).map(|(k, _)| *k).collect(); + self.remake_views(keys, window, cx, |b| { + #[cfg(windows)] + if new_store { + crate::shared::count_chromium_blocks(&b.core); + } + let old = if new_store { b.core.profiles.borrow_mut().remove(&(private, profile_id)) } else { None }; + if let Some(old) = old { + // WebKit holds a download's delegate weakly, so the old store outlives its downloads. + // shortcut: kept until quit; crossings are rare, prune by active downloads if that changes. + old.data.set_extensions(&[], &[], old.profile.shield_level); + b.core.retired_stores.borrow_mut().push(old.data); + } + b.runtime(private, profile_id); + }); + } + + /// Makes the views of `profiles` again so their pages load with the profile's new style + /// script; with `chromium_only`, only Chromium views, which keep the script they were created + /// with, while WebKit views take it on their next load. Windows never asks: its Chromium + /// views are restyled in place. + pub(crate) fn restart_views_of(&mut self, profiles: &[(bool, Id)], chromium_only: bool, window: &mut Window, cx: &mut Context) { + let keys: Vec = self + .views + .iter() + .filter(|(k, v)| (!chromium_only || v.is_chromium()) && self.profile_of(**k).is_some_and(|id| profiles.contains(&(k.private, id)))) + .map(|(k, _)| *k) + .collect(); + if !keys.is_empty() { + self.remake_views(keys, window, cx, |_| {}); + } + } + + /// Drops the views of `keys` (their pages reload when shown), runs `between`, then shows the + /// active tab and split again. + pub(super) fn remake_views(&mut self, keys: Vec, window: &mut Window, cx: &mut Context, between: impl FnOnce(&mut Self)) { + let active = self.model.active; + let split = self.shown_split().is_some_and(|s| s.panes().iter().any(|p| keys.contains(p))); + for key in keys { + self.hibernate(key, cx); + } + between(self); + if let Some(key) = active.filter(|_| split || self.model.active.is_none()) { + self.activate(key, window, cx); + } + cx.notify(); + } + + /// Tabs of the profile stop renaming visits that were just deleted. + pub(super) fn forget_visits(&mut self, private: bool, profile_id: Id) { + let keys: Vec = self.pages.keys().copied().filter(|k| k.private == private && self.profile_of(*k) == Some(profile_id)).collect(); + for key in keys { + if let Some(page) = self.pages.get_mut(&key) { + page.visit = None; + } + } + } + + pub fn clear_history(&mut self, private: bool, profile_id: Id, range: browser_core::library::HistoryRange, cx: &mut Context) { + browser_core::library::clear_history(self.store(private), profile_id, range, now()).ok(); + let all = range == browser_core::library::HistoryRange::All; + if all { + crate::zaps::apply(&self.core, private, profile_id); + } + let forget = move |b: &mut Self, cx: &mut Context| { + b.forget_history(private, profile_id); + if all { + b.reapply_site_zooms(private, profile_id, None); + b.set_site_muted(private, profile_id, None, false, false); + } + cx.notify(); + }; + forget(self, cx); + crate::shared::others(cx, |b, _, cx| forget(b, cx)); + } + + pub fn remove_history_url(&mut self, url: &str, cx: &mut Context) { + let Some((private, profile_id)) = self.model.profile() else { return }; + self.store(private).delete_history_url(profile_id, url).ok(); + let forget = move |b: &mut Self, cx: &mut Context| { + b.forget_visits(private, profile_id); + b.history_cache.clear(); + b.forget_text_matches(); + b.menu.history_cleared(); + cx.notify(); + }; + forget(self, cx); + crate::shared::others(cx, |b, _, cx| forget(b, cx)); + } + + /// Forgets what this window keeps in memory of a profile's history: visits, suggestions, + /// recently closed tabs and site icons. + pub(crate) fn forget_history(&mut self, private: bool, profile_id: Id) { + self.forget_visits(private, profile_id); + self.history_cache.clear(); + self.forget_text_matches(); + self.menu.history_cleared(); + self.model.closed_tabs.clear_profile(private, profile_id); + self.forget_favicons((private, profile_id)); + } + + /// The private profile is never written to disk. + pub fn export_profile(&mut self, private: bool, profile_id: Id, cx: &mut Context) { + let notice = match self.write_export(private, profile_id) { + Ok(path) => format!("Exported to {}.", path.display()), + Err(e) => format!("Export failed: {e}."), + }; + self.privacy_notice = Some(((private, profile_id), notice)); + cx.notify(); + } + + pub(super) fn write_export(&self, private: bool, profile_id: Id) -> Result { + use std::io::Write; + #[cfg(unix)] + use std::os::unix::fs::OpenOptionsExt; + if private { + return Err("private data is not saved".into()); + } + let store = self.store(private); + let name = store.profile(profile_id).map_err(|e| e.to_string())?.name; + let json = store.export_profile(profile_id).map_err(|e| e.to_string())?; + let dir = std::env::home_dir().ok_or("no home folder")?.join("Downloads"); + let file = browser_core::profile_data::export_name(&name); + let path = engine::downloads::free_path(&dir, &file, |_| false); + let mut options = std::fs::OpenOptions::new(); + #[cfg(unix)] + options.mode(0o600); + options.write(true).create_new(true).open(&path).and_then(|mut f| f.write_all(json.as_bytes())).map_err(|e| e.to_string())?; + Ok(path) + } + + /// Files already saved to Downloads stay; the profile row (name, Shield level) stays. + pub fn delete_profile_data(&mut self, private: bool, profile_id: Id, window: &mut Window, cx: &mut Context) { + let target = (private, profile_id); + self.forget_visits(private, profile_id); + let keys: Vec = self.views.keys().filter(|k| k.private == private && self.profile_of(**k) == Some(profile_id)).copied().collect(); + let folders: Vec = self + .model + .spaces + .iter() + .filter(|s| s.private == private && s.space.profile_id == profile_id) + .flat_map(|s| self.store(private).folders(s.space.id).unwrap_or_default()) + .map(|f| f.id) + .collect(); + let reset = match self.core.reset_profile_data(private, profile_id) { + Ok(reset) => reset, + Err(e) => { + self.privacy_notice = Some((target, format!("Deleting failed ({e})."))); + cx.notify(); + return; + } + }; + let space = reset.space; + Self::sync_other_windows(cx); + crate::shared::others(cx, |b, _, cx| { + b.forget_history(private, profile_id); + b.toast.forget(target); + b.forget_assistant(profile_id); + cx.notify(); + }); + self.forget_assistant(profile_id); + for key in keys { + self.hibernate(key, cx); + } + self.model.forget_folders(private, &folders); + self.toast.forget(target); + self.pending_external = None; + self.refocus |= std::mem::take(&mut self.find_open); + self.suggestions.clear(); + let store = self.core.store(private); + self.pages.retain(|k, _| k.private != private || store.tab(k.id).is_ok()); + self.history_cache.clear(); + self.forget_text_matches(); + self.model.closed_tabs.clear_profile(private, profile_id); + self.forget_favicons(target); + self.privacy_notice = Some((target, "Deleting website data…".into())); + let own_store = reset.own_store; + // WebKit's data removal leaves its tracking-prevention and site-security databases behind, + // so a profile with a store of its own moves to a new one and the old one goes as a whole. + if reset.fresh_store.is_some() { + #[cfg(feature = "chromium")] + self.wipe_chromium(&own_store, reset.fresh_store.as_deref().unwrap_or_default()); + #[cfg(windows)] + crate::shared::count_chromium_blocks(&self.core); + if let Some(old) = self.core.profiles.borrow_mut().remove(&(false, profile_id)) { + old.data.set_extensions(&[], &[], old.profile.shield_level); + if self.downloads_popover.active.get(&target).is_some_and(|n| *n > 0) { + self.core.retired_stores.borrow_mut().push(old.data); + } + } + self.core.extensions.borrow_mut().forget_running(false, profile_id); + DataStore::wipe_persistent(&own_store); + DataStore::wipe_extensions(&own_store); + crate::zaps::forget(&own_store); + self.retire_store(&own_store, cx); + self.runtime(false, profile_id); + self.core.sync_shield(); + self.privacy_notice = Some((target, "All data of this profile was deleted.".into())); + self.reload_spaces(); + let ix = self.model.spaces.iter().position(|s| !s.private && s.space.id == space.id).unwrap_or(0); + self.switch_space(ix, window, cx); + return; + } + #[cfg(feature = "chromium")] + if !private { + self.wipe_chromium(&own_store, &own_store); + } + let (core, app_cx) = (self.core.clone(), cx.to_async()); + let reached = match self.runtime(private, profile_id) { + Some(rt) => { + rt.overrides.borrow_mut().clear(); + rt.data.set_site_styles(&crate::themes::page_sheets(&core, private, profile_id)); + if !private { + crate::zaps::forget(&own_store); + rt.data.set_rule_lists("zaps", None, false); + #[cfg(windows)] + rt.data.set_hidden_elements(&[]); + } + rt.rules.clear(); + if !private && rt.profile.shield_level == ShieldLevel::Lockdown { + DataStore::wipe_persistent(&rt.profile.data_store_uuid); + DataStore::wipe_extensions(&own_store); + } + let this = cx.entity().downgrade(); + let mut async_cx = cx.to_async(); + rt.data.remove_extension_data(move || { + core.extensions.borrow_mut().forget_running(private, profile_id); + if core.apply_extensions(private, profile_id) { + core.sync_shield(); + app_cx.update(|cx| crate::shared::each(cx, |b, window, cx| b.restart_views_here(private, profile_id, None, false, window, cx))).ok(); + } + }); + rt.data.remove_all_data(move || { + this.update(&mut async_cx, |b, cx| { + b.privacy_notice = Some((target, "All data of this profile was deleted.".into())); + cx.notify(); + }) + .ok(); + }); + true + } + None => false, + }; + if !reached { + self.privacy_notice = Some((target, "Stored data was deleted; website data could not be reached.".into())); + } + self.core.sync_shield(); + self.reload_spaces(); + let ix = self.model.spaces.iter().position(|s| s.private == private && s.space.id == space.id).unwrap_or(0); + self.switch_space(ix, window, cx); + } + + pub(crate) fn forget_favicons(&mut self, profile: (bool, Id)) { + self.favicons.forget(&profile); + self.favicon_memo.take(); + #[cfg(feature = "translation")] + self.translation_offered.retain(|(p, id, _)| (*p, *id) != profile); + } + + /// The host's icon, else the nearest parent's within its site, so a subdomain never visited + /// still shows its site's icon. + /// Every tab row asks once per frame, so answers are kept until an icon arrives or goes. + pub fn favicon(&self, url: &str) -> Option> { + let space = self.model.current_space()?; + let profile = (space.private, space.space.profile_id); + let mut memo = self.favicon_memo.borrow_mut(); + // shortcut: a full memo starts over, so URLs a long session visited do not pile up. + if memo.as_ref().is_none_or(|(p, urls)| *p != profile || urls.len() >= 4096) { + *memo = Some((profile, HashMap::new())); + } + let urls = &mut memo.as_mut()?.1; + if let Some(found) = urls.get(url) { + return found.clone(); + } + let found = self.find_favicon(profile, url); + urls.insert(url.to_owned(), found.clone()); + found + } + + pub(super) fn find_favicon(&self, profile: (bool, Id), url: &str) -> Option> { + self.favicons.find(&profile, &tab_host(url)?).cloned() + } + + /// Lockdown pages get no extra requests. + pub(super) fn request_favicon(&mut self, key: TabKey, url: &Url) { + let lockdown = self.level_for_tab(key, url.as_str()) == ShieldLevel::Lockdown; + let (Some(profile_id), Some(host)) = (self.profile_of(key), favicon::icon_host(url, lockdown)) else { return }; + self.load_favicons(key.private, profile_id); + let Some(view) = self.views.get(&key) else { return }; + let profile = (key.private, profile_id); + let Some(ticket) = self.favicons.request(&profile, &host) else { return }; + let icon = (profile, host, ticket); + let (events, page) = (self.events.clone(), url.clone()); + view.icon_links(url, move |links| { + events.unbounded_send(Msg::IconLinks(key, icon.clone(), page.clone(), links)).ok(); + }); + } + + pub(super) fn fetch_favicon(&mut self, key: TabKey, icon: IconKey, page: &Url, links: &str) { + let urls = favicon::candidates(page, links); + let still_there = |v: &&Rc| v.url().is_some_and(|u| u.origin() == page.origin()); + let view = self.views.get(&key).filter(still_there).filter(|_| !urls.is_empty() && self.favicons.is_requested(&icon.0, &icon.1, icon.2)); + let Some(view) = view else { + self.favicons.withdraw(&icon.0, &icon.1, icon.2); + return; + }; + let events = self.events.clone(); + view.fetch_icon(page, &urls, favicon::MAX_BYTES, move |data| { + events.unbounded_send(Msg::IconData(icon.clone(), data)).ok(); + }); + } + + pub(super) fn store_favicon(&mut self, icon: IconKey, data: String, cx: &mut Context) { + cx.spawn(async move |this, cx| { + let png = cx.background_spawn(async move { favicon::normalize(&data) }).await; + this.update(cx, |b, cx| { + let (profile, host, ticket) = icon; + // A history clear while the icon was loading withdraws the request. + let wanted = b.favicons.is_requested(&profile, &host, ticket); + if let Some(png) = png.as_ref().filter(|_| wanted && b.core.keeps_records(profile.0, profile.1)) { + b.store(profile.0).set_favicon(profile.1, &host, png).ok(); + } + if b.favicons.accept(&profile, &host, ticket, png.map(|png| Arc::new(Image::from_bytes(ImageFormat::Png, png)))) { + b.favicon_memo.take(); + cx.notify(); + } + }) + .ok(); + }) + .detach(); + } + + /// The zoom is kept per host and profile and shared by its open tabs; Lockdown pages keep none. + pub fn zoom(&mut self, factor: Option, cx: &mut Context) { + if self.responsive_active() { + return self.show_toast("Zoom is off while Responsive Size is on", None, cx); + } + let (Some(key), Some(v)) = (self.model.active, self.active_view()) else { return }; + v.set_zoom(factor.map_or(1.0, |f| v.zoom() * f)); + self.show_toast(format!("Zoom {}%", (v.zoom() * 100.).round()), None, cx); + let (Some(profile_id), Some(url)) = (self.profile_of(key), v.url()) else { return }; + let Some(host) = url.host_str() else { return }; + let Some(zoom) = zoom_to_save(v.zoom(), self.level_for_tab(key, url.as_str()) == ShieldLevel::Lockdown) else { return }; + if self.store(key.private).set_site_zoom(profile_id, host, zoom).is_ok() { + self.reapply_site_zooms(key.private, profile_id, Some(host)); + } + cx.notify(); + } + + /// Sets the host's saved zoom; without one, `reset` returns the page to 100% and otherwise leaves it. + pub(super) fn apply_site_zoom(&mut self, key: TabKey, url: Option<&Url>, reset: bool) { + let Some(view) = self.views.get(&key).cloned() else { return }; + let saved = self.profile_of(key).zip(url.and_then(Url::host_str)).and_then(|(p, host)| self.store(key.private).site_zoom(p, host).ok().flatten()); + let Some(zoom) = saved.or(reset.then_some(1.0)) else { return }; + if self.responsive_active() { + self.zoom_before_responsive.insert(key, zoom); + } else { + view.set_zoom(zoom); + } + } + + /// Re-applies saved zooms to the profile's open pages on `host`, or on every host. + pub(super) fn reapply_site_zooms(&mut self, private: bool, profile_id: Id, host: Option<&str>) { + let views: Vec<(TabKey, Option)> = self + .views + .iter() + .filter(|(k, _)| k.private == private && self.profile_of(**k) == Some(profile_id)) + .map(|(k, v)| (*k, v.url())) + .filter(|(_, url)| host.is_none() || url.as_ref().and_then(Url::host_str) == host) + .collect(); + for (key, url) in views { + self.apply_site_zoom(key, url.as_ref(), true); + } + } + + pub(super) fn saved_mute(&self, key: TabKey, host: &str) -> bool { + self.profile_of(key).is_some_and(|p| self.store(key.private).muted_sites(p).unwrap_or_default().iter().any(|h| h == host)) + } + + /// A page starts muted on a muted host; like zoom, an unsaved Lockdown mute lasts until the tab leaves the host. + pub(super) fn apply_site_mute(&self, key: TabKey, url: &Url, left_host: bool) { + let saved = url.host_str().is_some_and(|host| self.saved_mute(key, host)); + if let Some(view) = self.views.get(&key).filter(|v| saved || left_host || v.is_muted()) { + view.set_muted(saved || !left_host); + } + } + + pub fn tab_muted(&self, key: TabKey) -> bool { + match self.views.get(&key) { + Some(view) => view.is_muted(), + None => self.tab_url(key).and_then(|u| tab_host(&u)).is_some_and(|host| self.saved_mute(key, &host)), + } + } + + /// Mutes or unmutes the tab's host in its profile, for its open tabs and later visits; Lockdown saves nothing. + pub fn toggle_site_muted(&mut self, key: TabKey, cx: &mut Context) { + let Some(url) = self.tab_url(key).and_then(|u| Url::parse(&u).ok()) else { return }; + let (Some(profile_id), Some(host)) = (self.profile_of(key), url.host_str()) else { return }; + let muted = !self.tab_muted(key); + let save = browser_core::site::saves_mute(muted, self.level_for_tab(key, url.as_str())); + self.set_site_muted(key.private, profile_id, Some(host), muted, save); + let host = crate::toolbar::host_tail(host.trim_start_matches("www."), 40); + self.show_toast(if muted { format!("Muted {host}") } else { format!("Unmuted {host}") }, None, cx); + } + + /// Applies a mute to the profile's open pages on `host`, or on every host, saving it when `save` is set. + pub fn set_site_muted(&mut self, private: bool, profile_id: Id, host: Option<&str>, muted: bool, save: bool) { + if let Some(host) = host.filter(|_| save) { + self.store(private).set_site_muted(profile_id, host, muted).ok(); + } + for (key, view) in &self.views { + let on_host = host.is_none() || view.url().as_ref().and_then(Url::host_str) == host; + if key.private == private && on_host && self.profile_of(*key) == Some(profile_id) { + view.set_muted(muted); + } + } + } + + pub fn muted_sites(&self) -> Vec { + let Some(space) = self.model.current_space() else { return Vec::new() }; + self.store(space.private).muted_sites(space.space.profile_id).unwrap_or_default() + } + + pub fn site_zooms(&self) -> Vec<(String, f64)> { + let Some(space) = self.model.current_space() else { return Vec::new() }; + self.store(space.private).site_zooms(space.space.profile_id).unwrap_or_default() + } + + pub fn remove_site_zoom(&mut self, private: bool, profile_id: Id, host: Option<&str>, cx: &mut Context) { + let store = self.store(private); + match host { + Some(host) => store.set_site_zoom(profile_id, host, None), + None => store.clear_site_zooms(profile_id), + } + .ok(); + self.reapply_site_zooms(private, profile_id, host); + cx.notify(); + } +} diff --git a/crates/app/src/browser/views.rs b/crates/app/src/browser/views.rs new file mode 100644 index 00000000..2011c4af --- /dev/null +++ b/crates/app/src/browser/views.rs @@ -0,0 +1,626 @@ +use super::*; + +impl Browser { + pub(crate) fn store(&self, private: bool) -> &Store { + self.core.store(private) + } + + pub fn page(&self, key: TabKey) -> PageState { + self.pages.get(&key).cloned().unwrap_or_default() + } + + pub fn loading(&self, key: TabKey) -> bool { + self.pages.get(&key).is_some_and(|p| p.loading) + } + + /// Books the redraw of the spinners' next step while a spinner of this space turns. + pub(crate) fn keep_spinning(&mut self, window: &mut Window, cx: &mut Context) { + let reloading = self.reload_spin.is_some_and(|(_, at)| at.elapsed() < crate::toolbar::SPIN); + if self.spinning || self.still() || !reloading && !self.model.tabs.iter().any(|t| self.loading(self.model.key(t))) { + return; + } + self.spinning = true; + spin_step(window, cx.entity().downgrade(), Instant::now()); + } + + /// Whether spinners stand still: motion is reduced or Tarn is in the background. + pub(crate) fn still(&self) -> bool { + !engine::app_active() || self.pref(crate::prefs::Pref::ReduceMotion) + } + + pub(crate) fn reload_spaces(&mut self) { + self.model.reload_spaces(&self.core); + } + + pub(crate) fn reload_space(&mut self) { + let old = self.model.reload_space(&self.core); + self.space_shown(&old); + } + + /// Catches the shell up with the current space's lists: its profile's site icons, the tabs + /// that fade in and its bookmarks. + pub(crate) fn space_shown(&mut self, old: &[Tab]) { + self.note_new_tabs(old); + let profile = self.model.profile(); + if let Some((private, profile_id)) = profile { + self.load_favicons(private, profile_id); + } + if profile != self.bookmarks_of { + self.bookmarks_of = profile; + self.set_bookmarks(profile.map(|(private, id)| self.store(private).bookmarks(id).unwrap_or_default()).unwrap_or_default()); + } + } + + /// A space's tabs, folders and groups as stored, with its profile's site icons loaded. + pub(crate) fn space_lists(&mut self, ix: usize) -> browser_core::tabs::Lists { + if let Some(space) = self.model.spaces.get(ix) { + self.load_favicons(space.private, space.space.profile_id); + } + self.model.space_lists(&self.core, ix) + } + + /// Stored icons are small 64 px PNGs, so a profile's set is read once and kept in memory. + pub(super) fn load_favicons(&mut self, private: bool, profile_id: Id) { + let store = self.core.store(private); + self.favicons.load(&(private, profile_id), || { + let icons = store.favicons(profile_id).unwrap_or_default(); + let icons = icons.into_iter().map(|(host, png)| (host, Arc::new(Image::from_bytes(ImageFormat::Png, png)))).collect(); + (icons, store.stale_favicons(profile_id, now() - favicon::MAX_AGE).unwrap_or_default()) + }); + self.favicon_memo.take(); + } + + pub(super) fn runtime(&mut self, private: bool, profile_id: Id) -> Option> { + let downloads = || -> Rc { + let events = self.core.downloads.clone(); + Rc::new(move |event| drop(events.unbounded_send((private, profile_id, event)))) + }; + if self.core.open_profile(private, profile_id, downloads)? { + let profiles = self.core.profiles.borrow(); + let data = &profiles[&(private, profile_id)].data; + self.core.apply_blocking_to(data); + data.set_sort_downloads(self.pref(crate::prefs::Pref::SortDownloads)); + drop(profiles); + self.core.apply_extensions(private, profile_id); + if !private { + crate::tarn_ext::opened(&self.core, profile_id); + } + self.apply_site_styles(private, profile_id); + crate::zaps::apply(&self.core, private, profile_id); + // Chromium refuses a profile's requests until its Shield choices arrive. + #[cfg(windows)] + self.core.sync_shield(); + } + self.loaded(private, profile_id) + } + + /// The runtime of a profile already opened; the borrow ends with the returned guard. + pub(crate) fn loaded(&self, private: bool, profile_id: Id) -> Option> { + Ref::filter_map(self.core.profiles.borrow(), |p| p.get(&(private, profile_id))).ok() + } + + pub fn set_filter_updates(&mut self, on: bool, cx: &mut Context) { + match self.core.disk.set_setting(filters::SETTING, if on { "on" } else { "off" }) { + Ok(()) => { + self.core.filters.borrow_mut().updates = on; + if self.warning.as_deref().is_some_and(|w| w.starts_with(FILTER_SETTING_WARNING)) { + self.warning = None; + } + } + Err(e) => self.warning = Some(format!("{FILTER_SETTING_WARNING} ({e}).")), + } + cx.notify(); + } + + pub(super) fn current_runtime(&mut self) -> Option> { + let space = self.model.current_space()?; + let (private, profile_id) = (space.private, space.space.profile_id); + self.runtime(private, profile_id) + } + + pub fn level_for(&self, url: &str) -> ShieldLevel { + let Some((private, profile_id)) = self.model.profile() else { return ShieldLevel::default() }; + self.core.level(private, profile_id, Url::parse(url).ok().as_ref()).unwrap_or_default() + } + + pub fn has_override(&self, host: &str) -> bool { + self.model.profile().is_some_and(|(private, profile_id)| self.core.has_override(private, profile_id, host)) + } + + /// Events are tagged with the view that sent them, so a replaced view's late events are dropped. + pub(crate) fn sink(&mut self, key: TabKey) -> Rc { + self.next_generation += 1; + let generation = self.next_generation; + self.view_generation.insert(key, generation); + let events = self.events.clone(); + Rc::new(move |event| { + events.unbounded_send(Msg::Tab(key, generation, event)).ok(); + }) + } + + /// Events of the link peek's view, tagged so a closed peek's late events are dropped. + pub(crate) fn peek_sink(&mut self) -> (u64, Rc) { + self.next_generation += 1; + let (generation, events) = (self.next_generation, self.events.clone()); + (generation, Rc::new(move |event| drop(events.unbounded_send(Msg::Peek(generation, event))))) + } + + #[cfg(feature = "chromium")] + pub(crate) fn web_engine_for(&mut self, key: TabKey, url: &str) -> WebEngine { + let tab = self.model.tab(key).and_then(|t| t.web_engine); + let Some((private, profile_id)) = self.model.profile() else { return WebEngine::WebKit }; + self.runtime(private, profile_id); + self.core.web_engine(private, profile_id, tab, Url::parse(url).ok().as_ref()).unwrap_or(WebEngine::WebKit) + } + + /// A web view of the profile's data store with the Shield rules for `url`. + pub(crate) fn web_view(&mut self, host: &Host, private: bool, profile_id: Id, url: &str, sink: Rc) -> Option { + let developer = self.developer; + let sets = self.core.sets.clone(); + let rt = self.runtime(private, profile_id)?; + let site_for = browser_core::site::site_for(rt.profile.clone(), rt.overrides.clone(), rt.rules.clone(), sets); + let site = Url::parse(url).map_or(nav_policy::Site::new(rt.profile.shield_level), |u| site_for(&u)); + let inspectable = (developer || rt.profile.is_dev) && site.level != ShieldLevel::Lockdown; + Some(WebView::new(host, &rt.data, site.level, site.filtered, inspectable, site_for, sink)) + } + + #[cfg_attr(not(feature = "chromium"), allow(unused_variables))] + pub(crate) fn create_view(&mut self, key: TabKey, url: &str, cx: &mut Context) -> Option> { + let host = self.host.clone()?; + let sink = self.sink(key); + let space = self.model.current_space()?; + let (private, profile_id) = (space.private, space.space.profile_id); + if self.core.awaits_extensions(private, profile_id) { + return None; + } + #[cfg(feature = "chromium")] + let wants_chromium = !private && self.web_engine_for(key, url) == WebEngine::Chromium; + #[cfg(feature = "chromium")] + if wants_chromium && !self.chromium_current(key, cx) { + return None; + } + #[cfg(feature = "chromium")] + let developer = self.developer; + #[cfg(feature = "chromium")] + let chromium = wants_chromium + .then(|| self.runtime(private, profile_id)) + .flatten() + .and_then(|rt| WebView::chromium(&host, &rt.data, &data_dir().join("Chromium"), &rt.own_store, developer || rt.profile.is_dev, sink.clone())); + #[cfg(not(feature = "chromium"))] + let chromium = None; + #[cfg(feature = "chromium")] + if chromium.is_some() { + if self.core.chromium_profile.get() != Some(profile_id) { + crate::shared::count_chromium_blocks(&self.core); + } + let owner_changed = self.core.chromium_profile.replace(Some(profile_id)) != Some(profile_id); + self.core.sync_shield(); + if owner_changed { + crate::tarn_ext::chromium_owner_changed(&self.core, profile_id); + } + let ageing = browser_core::staleness::Staleness::Ageing; + if self.core.chromium_staleness.get() == ageing && self.pages.get(&key).is_none_or(|p| p.notice.is_none()) { + self.notify_offer(key, ageing.message().to_owned(), None); + } + } + let view = Rc::new(match chromium { + Some(view) => view, + None => self.web_view(&host, private, profile_id, url, sink)?, + }); + view.set_corner_radius(page_corner()); + view.set_dark(!ui::theme::Theme::is_light()); + self.view_prefs(&view); + self.views.insert(key, view.clone()); + self.attach_tarn(key); + Some(view) + } + + /// Typed and incoming URLs are user-initiated, so stripping tracking parameters here keeps + /// the request's context; links from pages are left alone. + pub fn clean_user_url(&self, url: Url) -> Url { + self.core.clean_user_url(self.model.profile(), url) + } + + /// `clean_user_url` for a load the user starts now; removed parameters count on the current + /// profile's Shield card. + pub(super) fn clean_user_load(&mut self, url: Url, cx: &mut Context) -> Url { + let clean = self.clean_user_url(url.clone()); + if let Some((private, profile_id)) = self.model.current_space().map(|s| (s.private, s.space.profile_id)) { + self.count_shield(private, profile_id, Counter::TrackingParams, shield::url_clean::removed_params(&url, &clean), clean.host_str(), cx); + } + clean + } + + /// Counts one event for the site the tab shows, as the page that caused it. + pub(super) fn count_on_page(&mut self, key: TabKey, counter: Counter, cx: &mut Context) { + let host = self.tab_url(key).and_then(|u| Url::parse(&u).ok()).and_then(|u| page_host(&u)); + if let Some(profile_id) = self.profile_of(key) { + self.count_shield(key.private, profile_id, counter, 1, host.as_deref(), cx); + } + } + + /// Adds to a Shield card counter and repaints every window, so an open card follows. + pub(crate) fn count_shield(&mut self, private: bool, profile_id: Id, counter: Counter, n: i64, host: Option<&str>, cx: &mut Context) { + if n <= 0 || self.store(private).count(profile_id, counter, n, host).is_err() { + return; + } + crate::shield_card::touch(); + crate::shared::others(cx, |_, _, cx| cx.notify()); + cx.notify(); + } + + /// Shows how a download ended over the active tab: a passing toast in the window in front, or a + /// warning in every window, held until dismissed (S11) and, while the window shows another + /// profile's space, waiting for that profile's space. + pub(crate) fn notify_download( + &mut self, + private: bool, + profile_id: Id, + result: &Result<(std::path::PathBuf, bool), String>, + front: bool, + cx: &mut Context, + ) { + let here = self.model.current_space().is_some_and(|s| (s.private, s.space.profile_id) == (private, profile_id)); + let mark = if cfg!(windows) { "the mark of the web" } else { "macOS quarantine" }; + let (tone, text) = match result { + Ok((path, quarantined)) => { + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + browser_core::toast::download(&ui::text::bounded_title(&name), Ok((*quarantined, engine::downloads::is_dangerous(&name))), mark) + } + Err(message) => browser_core::toast::download("", Err(&ui::text::bounded_title(message)), mark), + }; + if tone == browser_core::toast::Tone::Warning { + self.hold_toast(text, self.model.active.filter(|_| here), (private, profile_id), cx); + } else if here && front { + let reveal = result.as_ref().ok().map(|(path, _)| crate::toast::Action::Reveal(path.clone())); + self.show_tab_toast(tone, text, reveal, (private, profile_id), cx); + } + } + + pub fn active_view(&self) -> Option> { + self.views.get(&self.model.active?).cloned() + } + + pub fn activate(&mut self, key: TabKey, window: &mut Window, cx: &mut Context) { + if self.model.tab(key).is_none() { + return; + } + let switched = self.model.active != Some(key); + let _span = switched.then(|| engine::startup::span(engine::startup::TAB_SWITCH)).flatten(); + if switched { + self.leave_page_fullscreen(window); + } + let mut fading = false; + if switched + && let Some((outgoing, _)) = self.page_fade.take() + && !self.views.get(&key).is_some_and(|v| Rc::ptr_eq(v, &outgoing)) + { + outgoing.set_visible(false); + } + let partners = self.split_partners(key, cx); + if let Some(prev) = self.model.active.filter(|p| *p != key && !partners.contains(p)).and_then(|p| self.views.get(&p)).cloned() { + fading = partners.is_empty() && !self.pref(crate::prefs::Pref::ReduceMotion) && !self.overlay_open() && self.active_json().is_none(); + if fading { + self.page_fade = Some((prev, Instant::now())); + } else { + prev.set_visible(false); + } + } + if let Some(prev) = self.model.active.filter(|p| *p != key) { + self.ask_media(prev, cx); + } + let left = Instant::now(); + self.seen.extend(self.model.active.into_iter().chain([key]).map(|k| (k, left))); + self.typed_in.remove(&key); + let evicted = self.model.lifecycle.activate_with(&partners, key); + for evicted in evicted { + if evicted == key || partners.contains(&evicted) || self.typed_in.contains(&evicted) { + // The split's panes, and tabs with typed input, stay awake above the live-tab limit. + self.model.lifecycle.keep(evicted); + } else { + self.sleep_unless_playing(evicted, cx); + } + } + let view = self.wake(key, cx); + self.model.active = Some(key); + if let Some(view) = view { + if fading { + view.raise(); + view.set_alpha(0.); + } else if switched { + view.set_alpha(1.); + } + view.set_visible(!self.overlay_open()); + if !self.overlay_open() { + view.focus(); + } + } + if !partners.is_empty() { + // A page still fading out would show between the panes. + if let Some((outgoing, _)) = self.page_fade.take() { + outgoing.set_visible(false); + } + for pane in &partners { + if let Some(view) = self.wake(*pane, cx) { + view.set_alpha(1.); + view.set_visible(!self.overlay_open()); + } + } + } + self.model.touch(&self.core, key, now()); + if !self.overlay_open() { + window.focus(&self.focus); + } + if switched { + self.layout_changed(); + if self.active_prompt().is_some() { + self.prepare_prompt(window, cx); + } + } + cx.notify(); + } + + /// The tab's view: this window's, else one taken over from another window, else a new one + /// that restores the tab's saved state or loads its page. + pub(super) fn wake(&mut self, key: TabKey, cx: &mut Context) -> Option> { + if let Some(view) = self.views.get(&key).cloned().or_else(|| self.adopt_view(key, cx)) { + return Some(view); + } + let tab = self.model.tab(key).cloned()?; + self.create_view(key, &tab.url, cx).inspect(|view| { + let restorable = self.level_for(&tab.url).policy().save_interaction_state; + let saved = self.store(key.private).interaction_state(key.id).ok().flatten(); + // Windows saves Tarn's own format; anything else loads the tab's page instead. + let ours = |state: &&[u8]| !cfg!(windows) || engine::view_policy::SavedHistory::from_bytes(state).is_some(); + let url = Url::parse(&tab.url).ok(); + // A restored history is never an Open File (S6), so an opened file loads afresh. + let opened = url.as_ref().is_some_and(|u| self.opened_file(key, u)); + match saved.as_deref().filter(|state| !opened && restorable && !view.is_chromium() && ours(state)) { + Some(state) => view.restore_interaction_state(state), + None => { + if let Some(url) = url { + self.load_tab_url(key, view, url); + } + } + } + }) + } + + pub(super) fn opened_file(&self, key: TabKey, url: &Url) -> bool { + self.pages.get(&key).and_then(|p| p.opened_file.as_ref()) == Some(url) + } + + pub(super) fn load_tab_url(&self, key: TabKey, view: &WebView, url: Url) { + match self.link_loads.get(&key) { + _ if self.opened_file(key, &url) => view.load_file(&url), + // Says why a file tab no Open File vouches for stays empty. + _ if url.scheme() == "file" => view.load(&url), + _ if nav_policy::decide(&url, Source::Sync) != Decision::Allow => {} + Some(from) => view.load_link(&url, from.as_ref()), + None => view.load(&url), + } + } + + pub(super) fn save_state(&self, key: TabKey) { + let Some(view) = self.views.get(&key) else { return }; + let url = view.url().map(String::from).unwrap_or_default(); + let state = self.level_for_tab(key, &url).policy().save_interaction_state.then(|| view.interaction_state()).flatten(); + self.store(key.private).set_interaction_state(key.id, state.as_deref()).ok(); + } + + /// Whether `key` still shows the view a request was sent to; tab ids are reused after a close. + pub(crate) fn same_view(&self, key: TabKey, asked: &std::rc::Weak) -> bool { + asked.upgrade().is_some_and(|v| self.views.get(&key).is_some_and(|live| Rc::ptr_eq(live, &v))) + } + + /// Drops this window's view of `key`, and the fade still showing it. + pub(super) fn take_view(&mut self, key: TabKey) -> Option> { + self.typed_in.remove(&key); + self.forget_media(key); + let view = self.views.remove(&key)?; + if self.page_fade.as_ref().is_some_and(|(fading, _)| Rc::ptr_eq(fading, &view)) { + self.page_fade = None; + } + Some(view) + } + + pub(crate) fn hibernate(&mut self, key: TabKey, cx: &mut Context) { + self.save_state(key); + self.take_view(key); + self.json_pages.remove(&key); + self.drop_reader(key); + self.view_generation.remove(&key); + self.drop_prompts(key, cx); + self.model.lifecycle.remove(key); + if let Some(page) = self.pages.get_mut(&key) { + page.loading = false; + page.retry = None; + } + if self.model.active == Some(key) { + self.model.active = None; + } + } + + pub(crate) fn save_all(&self) { + for key in self.views.keys() { + self.save_state(*key); + } + } + + pub fn new_tab(&mut self, url: &Url, window: &mut Window, cx: &mut Context) { + self.new_tab_in(url, None, Opened::Typed, window, cx); + } + + /// A new tab whose `tabs.web_engine` is `web_engine`, as for a copy or a pop-up of a tab, + /// placed as `opened` says. + pub(crate) fn new_tab_in(&mut self, url: &Url, web_engine: Option, opened: Opened, window: &mut Window, cx: &mut Context) { + if self.model.burner_shown() + && let Some(key) = self.model.tabs.first().map(|t| self.model.key(t)) + { + self.activate(key, window, cx); + return self.navigate(url, window, cx); + } + let Some(key) = self.model.open_tab(&self.core, url.as_str(), web_engine.or(self.saved.web_engine), opened) else { return }; + self.reload_space(); + self.activate(key, window, cx); + } + + pub fn navigate(&mut self, url: &Url, window: &mut Window, cx: &mut Context) { + if let Some(key) = self.model.active { + self.link_loads.remove(&key); + self.pages.entry(key).or_default().retry = Some(url.clone()); + } + match (self.active_view(), self.model.active) { + (Some(view), Some(key)) if view.is_chromium() && self.level_for(url.as_str()) == ShieldLevel::Lockdown => self.rebuild_view(key, url, cx), + (Some(view), _) => view.load(url), + (None, Some(key)) => { + self.store(key.private).update_tab_page(key.id, url.as_str(), "").ok(); + self.reload_space(); + self.activate(key, window, cx); + } + (None, None) => self.new_tab(url, window, cx), + } + } + + pub fn close_tab(&mut self, key: TabKey, window: &mut Window, cx: &mut Context) { + self.close_tabs(vec![key], window, cx); + } + + /// Unloads a pinned tab, or closes an unpinned one and returns what reopening it needs. The + /// caller reloads the space and picks the next active tab. + pub(super) fn close_one(&mut self, key: TabKey, cx: &mut Context) -> Option { + let tab = self.model.tab(key).cloned()?; + self.splits.leave(key); + if tab.kind != TabKind::Ephemeral { + self.hibernate(key, cx); + return None; + } + let closed = self.closed_tab(&tab, key); + self.tab_leaving(&tab, cx); + if !key.private { + self.core.tarn.borrow().send(crate::tarn_ext::Msg::TabClosed(key.id as u64)); + } + self.take_view(key); + self.link_loads.remove(&key); + self.json_pages.remove(&key); + self.drop_reader(key); + self.view_generation.remove(&key); + self.drop_prompts(key, cx); + self.model.lifecycle.remove(key); + self.pages.remove(&key); + self.store(key.private).delete_tab(key.id).ok(); + if self.model.active == Some(key) { + self.model.active = None; + } + Some(closed) + } + + pub(crate) fn pick_active(&mut self, window: &mut Window, cx: &mut Context) { + let adopting = self.adopting; + match self.model.pick(|k| Some(k) != adopting && crate::shared::live_elsewhere(k, cx)) { + Some(key) => self.activate(key, window, cx), + None => { + self.model.active = None; + cx.notify(); + } + } + } + + pub fn move_tab(&mut self, key: TabKey, kind: TabKind, folder: Option, index: usize, cx: &mut Context) { + if self.model.burner_shown() && kind != TabKind::Ephemeral { + return; + } + if self.store(key.private).move_tab(key.id, kind, folder, index).is_ok() { + self.reload_space(); + cx.notify(); + } + } + + /// The `n`th visible tab, counted from 1; 9 is the last, as in other browsers. + pub fn select_tab(&mut self, n: usize, window: &mut Window, cx: &mut Context) { + if let Some(key) = self.model.slot(n) { + self.switch_to(key, window, cx); + } + } + + pub fn cycle_tab(&mut self, forward: bool, window: &mut Window, cx: &mut Context) { + if let Some(key) = self.model.cycled(forward) { + self.switch_to(key, window, cx); + } + } + + /// A tab the user picks; an open address field or launcher closes so the tab shows. + pub fn switch_to(&mut self, key: TabKey, window: &mut Window, cx: &mut Context) { + if self.in_main(window, cx, move |b, window, cx| b.switch_to(key, window, cx)) { + return; + } + if self.command_mode.is_some() { + self.close_command(window, cx); + } + self.activate(key, window, cx); + } + + pub fn toggle_pin(&mut self, cx: &mut Context) { + if let Some(key) = self.model.active_tab().map(|t| self.model.key(t)) { + self.toggle_pin_tab(key, cx); + } + } + + pub fn new_folder(&mut self, parent: Option, window: &mut Window, cx: &mut Context) { + let Some(folder) = self.model.new_folder(&self.core, parent) else { return }; + self.reload_space(); + self.begin_rename(crate::groups::RenameTarget::Folder(folder.id), window, cx); + } + + pub fn move_folder(&mut self, id: Id, parent: Option, cx: &mut Context) { + if self.model.move_folder(&self.core, id, parent) { + self.reload_space(); + cx.notify(); + } + } + + pub fn toggle_folder(&mut self, id: Id, cx: &mut Context) { + self.model.toggle_folder(id); + cx.notify(); + } + + pub fn switch_space(&mut self, ix: usize, window: &mut Window, cx: &mut Context) { + if self.abandoned || ix >= self.model.spaces.len() || self.in_main(window, cx, move |b, window, cx| b.switch_space(ix, window, cx)) { + return; + } + let _span = (ix != self.model.space_ix).then(|| engine::startup::span(engine::startup::SPACE_SWITCH)).flatten(); + self.commit_rename(cx); + self.hide_hover_card(cx); + if self.command_mode.is_some() { + self.close_command(window, cx); + } + if let Some(view) = self.active_view() { + view.set_visible(false); + } + self.motion = Default::default(); + self.floating = Default::default(); + let burning = self.model.burner_shown(); + let Some((from, old)) = self.model.switch_space(&self.core, ix) else { return }; + self.motion.forget_pointer(); + if from != ix { + self.space_switched_at = Some(now()); + } + self.current_runtime(); + if self.responsive.is_some() && !self.devtools_on() { + self.set_responsive(None, cx); + } + self.space_shown(&[]); + self.slide_from(from, old); + self.pick_active(window, cx); + if burning && !self.model.burner_shown() { + self.burn(cx); + } + cx.notify(); + } + + pub fn open_private_space(&mut self, window: &mut Window, cx: &mut Context) { + if let Some(ix) = self.model.private_space(&self.core) { + self.switch_space(ix, window, cx); + } + } +} diff --git a/crates/app/src/content.rs b/crates/app/src/content.rs index 3cd2feb4..c2fd9033 100644 --- a/crates/app/src/content.rs +++ b/crates/app/src/content.rs @@ -145,7 +145,24 @@ pub fn render(b: &mut Browser, window: &mut Window, cx: &mut Context) - let error = page.error; let mut items: Vec<(Ghost, gpui::Div)> = Vec::new(); let mut push = |id: &'static str, text: String, color: Rgba, card: gpui::Div| items.push(((id, text.into(), color), card)); + warning_banners(b, cx, &mut push); + page_banners(b, page.notice, page.offer.as_ref(), error, cx, &mut push); + if !b.overlay_open() { + if let Some((title, card)) = prompt_card(b, window, cx) { + push("prompt-card", title, Theme::text(), card); + } + if b.find_open && b.active_json().is_none() { + push("find-bar", String::new(), Theme::text(), find_bar(b, window, cx)); + } + } + + let panel = floating_panel(b, items, reduce, window); + let body = page_body(b, window, page.blocked.as_ref(), reduce, cx); + panel.child(body).into_any_element() +} + +fn warning_banners(b: &Browser, cx: &mut Context, push: &mut impl FnMut(&'static str, String, Rgba, gpui::Div)) { let rules_warning = engine::builtin_rules_failed() .then(|| "Tarn's built-in protections failed to load: local-network blocking and HTTPS upgrades are off until Tarn restarts.".to_owned()); for (id, warning) in [("banner-storage", &b.core.storage_warning), ("banner-window", &b.warning), ("banner-rules", &rules_warning)] { @@ -169,9 +186,19 @@ pub fn render(b: &mut Browser, window: &mut Window, cx: &mut Context) - .child(secure_button("ext-cancel", "Cancel", false).on_click(cx.listener(|b, _, _, cx| b.resolve_external(false, cx)))), ); } - if let Some(message) = page.notice { +} + +fn page_banners( + b: &Browser, + notice: Option, + offer: Option<&crate::blocking::Offer>, + error: Option, + cx: &mut Context, + push: &mut impl FnMut(&'static str, String, Rgba, gpui::Div), +) { + if let Some(message) = notice { let text = ui::text::bounded_title(&message); - let offer = page.offer.as_ref().map(|o| match o { + let offer = offer.map(|o| match o { crate::blocking::Offer::Open(_) => "Open Anyway", crate::blocking::Offer::NewTab(_) => "Open Once", crate::blocking::Offer::WebKit(_) => "Open in WebKit", @@ -220,58 +247,48 @@ pub fn render(b: &mut Browser, window: &mut Window, cx: &mut Context) - .child(secure_button("err-dismiss", "Dismiss", false).on_click(cx.listener(|b, _, _, cx| b.dismiss_error(cx)))), ); } +} - if !b.overlay_open() { - if let Some((title, card)) = prompt_card(b, window, cx) { - push("prompt-card", title, Theme::text(), card); - } - if b.find_open && b.active_json().is_none() { - let focused = b.find_input.focus_handle(cx).is_focused(window); - push( - "find-bar", - String::new(), - Theme::text(), - surface(Theme::radius_panel()) - .mb_2() - .flex_none() - .shadow(Elevation::Floating.shadow()) - .when(focused, |d| d.border_color(Theme::accent())) - .text_size(px(TEXT)) - .h(px(40.)) - .pl_3() - .pr_1() - .flex() - .items_center() - .gap_2() - .child(icon(Icon::Search, 14., Theme::muted())) - .child(div().flex_1().min_w_0().overflow_hidden().child(b.find_input.clone())) - .child( - div() - .flex_none() - .text_size(px(TEXT_SMALL)) - .text_color(if matches!(b.find_count, Some((0, _))) { Theme::danger() } else { Theme::faint() }) - .child(browser_core::find::count_label(b.find_count.map(|c| c.0), b.find_count.and_then(|c| c.1))), - ) - .child(div().w(px(1.)).h(px(18.)).flex_none().bg(Theme::separator())) - .child( - icon_button("find-prev", Icon::ChevronUp, true) - .tooltip(crate::shortcuts::tip("Previous", &crate::FindPrevious)) - .on_click(cx.listener(|b, _, _, cx| b.find(true, cx))), - ) - .child( - icon_button("find-next", Icon::ChevronDown, true) - .tooltip(crate::shortcuts::tip("Next", &crate::FindNext)) - .on_click(cx.listener(|b, _, _, cx| b.find(false, cx))), - ) - .child( - icon_button("find-close", Icon::Close, true) - .tooltip(tooltip("Done", Some("Esc".into()))) - .on_click(cx.listener(|b, _, w, cx| b.close_find(w, cx))), - ), - ); - } - } +fn find_bar(b: &Browser, window: &mut Window, cx: &mut Context) -> gpui::Div { + let focused = b.find_input.focus_handle(cx).is_focused(window); + surface(Theme::radius_panel()) + .mb_2() + .flex_none() + .shadow(Elevation::Floating.shadow()) + .when(focused, |d| d.border_color(Theme::accent())) + .text_size(px(TEXT)) + .h(px(40.)) + .pl_3() + .pr_1() + .flex() + .items_center() + .gap_2() + .child(icon(Icon::Search, 14., Theme::muted())) + .child(div().flex_1().min_w_0().overflow_hidden().child(b.find_input.clone())) + .child( + div() + .flex_none() + .text_size(px(TEXT_SMALL)) + .text_color(if matches!(b.find_count, Some((0, _))) { Theme::danger() } else { Theme::faint() }) + .child(browser_core::find::count_label(b.find_count.map(|c| c.0), b.find_count.and_then(|c| c.1))), + ) + .child(div().w(px(1.)).h(px(18.)).flex_none().bg(Theme::separator())) + .child( + icon_button("find-prev", Icon::ChevronUp, true) + .tooltip(crate::shortcuts::tip("Previous", &crate::FindPrevious)) + .on_click(cx.listener(|b, _, _, cx| b.find(true, cx))), + ) + .child( + icon_button("find-next", Icon::ChevronDown, true) + .tooltip(crate::shortcuts::tip("Next", &crate::FindNext)) + .on_click(cx.listener(|b, _, _, cx| b.find(false, cx))), + ) + .child( + icon_button("find-close", Icon::Close, true).tooltip(tooltip("Done", Some("Esc".into()))).on_click(cx.listener(|b, _, w, cx| b.close_find(w, cx))), + ) +} +fn floating_panel(b: &mut Browser, items: Vec<(Ghost, gpui::Div)>, reduce: bool, window: &mut Window) -> gpui::Div { let present: Vec = items.iter().map(|(g, _)| g.clone()).collect(); if !present.iter().map(|g| g.0).eq(b.floating.shown.iter().map(|g| g.0)) { b.layout_changed(); @@ -288,15 +305,17 @@ pub fn render(b: &mut Browser, window: &mut Window, cx: &mut Context) - } let left = 8. - GUTTER_SHIFT * b.sidebar_shown(); let area = div().absolute().top_0().bottom(px(8.)).left(px(left)).right(px(8.)).child(crate::address::measure(b.address.content.clone())); - let panel = div().flex_1().min_h_0().relative().flex().flex_col().p(px(8.)).pt_0().pl(px(left)).text_color(Theme::text()).child(area).children(cards); + div().flex_1().min_h_0().relative().flex().flex_col().p(px(8.)).pt_0().pl(px(left)).text_color(Theme::text()).child(area).children(cards) +} +fn page_body(b: &mut Browser, window: &mut Window, blocked: Option<&crate::blocking::BlockedPage>, reduce: bool, cx: &mut Context) -> AnyElement { let exit = b.overlay_exit.map(|at| progress(at, EXIT)); let leaving = |body: AnyElement| match exit { Some(t) => pop_out(div().flex_1().flex().flex_col().child(body), t).into_any_element(), None => body, }; - let body: AnyElement = if let Some(editor) = crate::profiles::render_editor(b, window, cx) { + if let Some(editor) = crate::profiles::render_editor(b, window, cx) { leaving(editor) } else if b.shortcuts_open { leaving(pop_in(div().flex_1().min_h_0().flex().flex_col().child(crate::shortcuts::render(&b.shortcuts_scroll, cx)), "shortcuts", reduce)) @@ -306,7 +325,7 @@ pub fn render(b: &mut Browser, window: &mut Window, cx: &mut Context) - leaving(start(b, reduce, cx)) } else if let Some(split) = crate::split::render(b, window, cx) { split - } else if let Some(blocked) = &page.blocked { + } else if let Some(blocked) = blocked { if let Some(view) = b.active_view() { view.set_frame(0., 0., 0., 0.); } @@ -322,41 +341,43 @@ pub fn render(b: &mut Browser, window: &mut Window, cx: &mut Context) - } page_frame().relative().child(overlay).into_any_element() } else { - let view = b.active_view(); - let preset = b.responsive_preset(); - let slide = b.sidebar_slide().filter(|_| preset.is_none()); - let held = b.sidebar_held.clone(); - let alpha = b.page_fade.as_ref().map_or(1., |(_, at)| progress(*at, FADE)); - let link_rect = b.link_status.page.clone(); - let page = canvas( - move |bounds, window, _| { - let Some(view) = view else { return }; - view.set_alpha(alpha.into()); - let (x, y) = (f32::from(bounds.origin.x), f32::from(bounds.origin.y)); - let (w, h) = (f32::from(bounds.size.width), f32::from(bounds.size.height)); - let fit = preset.map(|preset| devkit::responsive::fit(&preset, w, h)); - let page = fit.as_ref().map_or((x, y, w, h), |fit| (x + fit.x, y + fit.y, fit.width, fit.height)); - let width = held_width(&held, &view, page.2, slide); - view.set_frame(page.0.into(), page.1.into(), width.into(), page.3.into()); - if let Some(fit) = fit { - // WebKit's page zoom stops at 0.3; below that the CSS viewport is narrower than the preset. - let scale = f64::from(fit.scale).max(engine::MIN_ZOOM); - if (view.zoom() - scale).abs() > 0.001 { - view.set_zoom(scale); - } - } - // A refresh during prepaint is dropped; the link bubble follows the page on the next frame. - if link_rect.replace(page) != page { - window.on_next_frame(|window, _| window.refresh()); - } - }, - |_, _, _, _| {}, - ) - .size_full(); - page_frame().child(page).into_any_element() - }; + page_view(b) + } +} - panel.child(body).into_any_element() +fn page_view(b: &Browser) -> AnyElement { + let view = b.active_view(); + let preset = b.responsive_preset(); + let slide = b.sidebar_slide().filter(|_| preset.is_none()); + let held = b.sidebar_held.clone(); + let alpha = b.page_fade.as_ref().map_or(1., |(_, at)| progress(*at, FADE)); + let link_rect = b.link_status.page.clone(); + let page = canvas( + move |bounds, window, _| { + let Some(view) = view else { return }; + view.set_alpha(alpha.into()); + let (x, y) = (f32::from(bounds.origin.x), f32::from(bounds.origin.y)); + let (w, h) = (f32::from(bounds.size.width), f32::from(bounds.size.height)); + let fit = preset.map(|preset| devkit::responsive::fit(&preset, w, h)); + let page = fit.as_ref().map_or((x, y, w, h), |fit| (x + fit.x, y + fit.y, fit.width, fit.height)); + let width = held_width(&held, &view, page.2, slide); + view.set_frame(page.0.into(), page.1.into(), width.into(), page.3.into()); + if let Some(fit) = fit { + // WebKit's page zoom stops at 0.3; below that the CSS viewport is narrower than the preset. + let scale = f64::from(fit.scale).max(engine::MIN_ZOOM); + if (view.zoom() - scale).abs() > 0.001 { + view.set_zoom(scale); + } + } + // A refresh during prepaint is dropped; the link bubble follows the page on the next frame. + if link_rect.replace(page) != page { + window.on_next_frame(|window, _| window.refresh()); + } + }, + |_, _, _, _| {}, + ) + .size_full(); + page_frame().child(page).into_any_element() } fn page_frame() -> gpui::Div { diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs index bec4b841..49a02c64 100644 --- a/crates/app/src/lib.rs +++ b/crates/app/src/lib.rs @@ -199,6 +199,12 @@ impl Render for Browser { } } +macro_rules! indexed_actions { + ($root:ident, $cx:ident, $method:ident: $($action:ident => $ix:expr),*) => { + $($root = $root.on_action($cx.listener(|b, _: &$action, w, cx| b.$method($ix, w, cx)));)* + }; +} + impl Browser { fn render_root(&mut self, window: &mut Window, cx: &mut Context) -> gpui::AnyElement { self.follow_theme(); @@ -215,9 +221,58 @@ impl Browser { if self.hidden_field_focused(window, cx) || (std::mem::take(&mut self.refocus) || stranded) && !self.overlay_open() && self.active_prompt().is_none() { window.focus(&self.focus_handle(cx)); } - let [back, forward, close_tab, bookmark, print, stop, reload, reload_fresh] = - [&Back as &dyn gpui::Action, &Forward, &CloseTab, &BookmarkTab, &Print, &StopLoading, &Reload, &ReloadFromOrigin].map(|a| !self.idle(a)); - let mut root = div() + let mut root = self.root_shell(cx); + root = self.root_tab_actions(root, cx); + root = self.root_listeners(root, cx); + root = self.root_late_actions(root, cx); + let shown = self.sidebar_shown(); + // A list taken away under the pointer sends no hover-out. + if shown < 1. { + self.motion.pointer = None; + } + let sidebar = (shown > 0.).then(|| { + div() + .flex_none() + .flex() + .justify_end() + .child(timed(engine::startup::SIDEBAR_FRAME, || sidebar::render(self, cx))) + .when(shown < 1., |d| d.w(px((self.sidebar_width + sidebar::SIDEBAR_MARGIN) * shown)).overflow_hidden().opacity(shown)) + }); + if self.page_fullscreen.is_on() && !self.page_fullscreen_holds() { + self.leave_page_fullscreen(window); + } + if let Some(view) = self.active_view().filter(|_| self.page_fullscreen.is_on()) { + let page = canvas( + move |bounds, _, _| { + view.set_frame( + f32::from(bounds.origin.x).into(), + f32::from(bounds.origin.y).into(), + f32::from(bounds.size.width).into(), + f32::from(bounds.size.height).into(), + ) + }, + |_, _, _, _| {}, + ); + return root.bg(gpui::black()).child(page.size_full()).into_any_element(); + } + root.children(sidebar) + .child( + div() + .flex_1() + .min_w_0() + .h_full() + .flex() + .flex_col() + .child(timed("toolbar", || toolbar::render(self, cx))) + .when(self.tab_placement == TabPlacement::Top, |d| d.child(tab_strip::render(self, cx))) + .child(timed("content", || content::render(self, window, cx))), + ) + .children(assistant::render(self, window, cx)) + .into_any_element() + } + + fn root_shell(&self, cx: &mut Context) -> gpui::Div { + div() .key_context("Browser") .track_focus(&self.focus_handle(cx)) .size_full() @@ -277,6 +332,12 @@ impl Browser { } }), ) + } + + fn root_tab_actions(&self, mut root: gpui::Div, cx: &mut Context) -> gpui::Div { + let [back, forward, close_tab, bookmark, print, stop, reload, reload_fresh] = + [&Back as &dyn gpui::Action, &Forward, &CloseTab, &BookmarkTab, &Print, &StopLoading, &Reload, &ReloadFromOrigin].map(|a| !self.idle(a)); + root = root .on_action(cx.listener(|b, _: &NewTab, w, cx| b.new_tab_page(w, cx))) .on_action(cx.listener(|b, _: &NewChromiumWindow, w, cx| b.new_chromium_window(w, cx))) .on_action(cx.listener(|b, _: &profiles::NewProfile, w, cx| b.open_profile_editor(None, w, cx))) @@ -331,13 +392,12 @@ impl Browser { .on_action(cx.listener(|b, _: &library::SaveSnapshot, w, cx| b.save_snapshot(w, cx))) .on_action(cx.listener(|b, _: &library::RestoreSnapshot, w, cx| b.open_library(library::Page::Snapshots, None, w, cx))) .on_action(cx.listener(|b, _: &ToggleAutoHideSidebar, _, cx| b.set_pref(prefs::Pref::AutoHideSidebar, !b.pref(prefs::Pref::AutoHideSidebar), cx))); - macro_rules! indexed_actions { - ($method:ident: $($action:ident => $ix:expr),*) => { - $(root = root.on_action(cx.listener(|b, _: &$action, w, cx| b.$method($ix, w, cx)));)* - }; - } - indexed_actions!(select_tab: Tab1 => 1, Tab2 => 2, Tab3 => 3, Tab4 => 4, Tab5 => 5, Tab6 => 6, Tab7 => 7, Tab8 => 8, LastTab => 9); - indexed_actions!(cycle_tab: NextTab => true, PreviousTab => false); + indexed_actions!(root, cx, select_tab: Tab1 => 1, Tab2 => 2, Tab3 => 3, Tab4 => 4, Tab5 => 5, Tab6 => 6, Tab7 => 7, Tab8 => 8, LastTab => 9); + indexed_actions!(root, cx, cycle_tab: NextTab => true, PreviousTab => false); + root + } + + fn root_listeners(&self, mut root: gpui::Div, cx: &mut Context) -> gpui::Div { root = assistant::listen(menubar::listen(root, self, cx), cx); root = tabs::listen(root, cx); let page = self.model.active.is_some(); @@ -354,7 +414,11 @@ impl Browser { .on_action(cx.listener(|b, _: &text_input::SelectAll, w, _| b.edit_page(E::SelectAll, w))); } root = root.on_action(cx.listener(|b, _: &text_input::Undo, w, cx| b.undo(w, cx))); - indexed_actions!(switch_space: Space1 => 0, Space2 => 1, Space3 => 2, Space4 => 3, Space5 => 4, Space6 => 5, Space7 => 6, Space8 => 7, Space9 => 8); + root + } + + fn root_late_actions(&self, mut root: gpui::Div, cx: &mut Context) -> gpui::Div { + indexed_actions!(root, cx, switch_space: Space1 => 0, Space2 => 1, Space3 => 2, Space4 => 3, Space5 => 4, Space6 => 5, Space7 => 6, Space8 => 7, Space9 => 8); root = root .when(!self.idle(&ReopenClosedTab), |d| d.on_action(cx.listener(|b, _: &ReopenClosedTab, w, cx| b.reopen_closed_tab(w, cx)))) .when(!self.idle(&CloseAllTabs), |d| d.on_action(cx.listener(|b, _: &CloseAllTabs, w, cx| b.close_all_tabs(w, cx)))) @@ -382,50 +446,7 @@ impl Browser { // The mouse's buttons never arrive here, `watch_navigation_buttons` takes them; GPUI reports swipe events as these. .on_mouse_down(MouseButton::Navigate(NavigationDirection::Back), cx.listener(|b, _, _, _| b.swipe_history(true))) .on_mouse_down(MouseButton::Navigate(NavigationDirection::Forward), cx.listener(|b, _, _, _| b.swipe_history(false))); - let shown = self.sidebar_shown(); - // A list taken away under the pointer sends no hover-out. - if shown < 1. { - self.motion.pointer = None; - } - let sidebar = (shown > 0.).then(|| { - div() - .flex_none() - .flex() - .justify_end() - .child(timed(engine::startup::SIDEBAR_FRAME, || sidebar::render(self, cx))) - .when(shown < 1., |d| d.w(px((self.sidebar_width + sidebar::SIDEBAR_MARGIN) * shown)).overflow_hidden().opacity(shown)) - }); - if self.page_fullscreen.is_on() && !self.page_fullscreen_holds() { - self.leave_page_fullscreen(window); - } - if let Some(view) = self.active_view().filter(|_| self.page_fullscreen.is_on()) { - let page = canvas( - move |bounds, _, _| { - view.set_frame( - f32::from(bounds.origin.x).into(), - f32::from(bounds.origin.y).into(), - f32::from(bounds.size.width).into(), - f32::from(bounds.size.height).into(), - ) - }, - |_, _, _, _| {}, - ); - return root.bg(gpui::black()).child(page.size_full()).into_any_element(); - } - root.children(sidebar) - .child( - div() - .flex_1() - .min_w_0() - .h_full() - .flex() - .flex_col() - .child(timed("toolbar", || toolbar::render(self, cx))) - .when(self.tab_placement == TabPlacement::Top, |d| d.child(tab_strip::render(self, cx))) - .child(timed("content", || content::render(self, window, cx))), - ) - .children(assistant::render(self, window, cx)) - .into_any_element() + root } } diff --git a/crates/app/src/library.rs b/crates/app/src/library.rs index 308f63ae..ddd2d246 100644 --- a/crates/app/src/library.rs +++ b/crates/app/src/library.rs @@ -46,6 +46,11 @@ const IMPORT_TIMEOUT: Duration = Duration::from_secs(120); const MEMORY_REFRESH: Duration = Duration::from_secs(2); const DELETE_KEY: &str = if cfg!(windows) { "Delete" } else { "⌘⌫" }; +mod actions; +mod browser_api; +mod entries; +use entries::*; + actions!(library, [SaveSnapshot, RestoreSnapshot]); pub(crate) use browser_core::shield_card::date; @@ -88,263 +93,6 @@ fn snapshot_error(e: LoadError) -> &'static str { } } -impl Browser { - pub(crate) fn reload_bookmarks(&mut self, cx: &mut Context) { - self.bookmarks_of = self.model.profile(); - if let Some(space) = self.model.current_space() { - self.set_bookmarks(self.store(space.private).bookmarks(space.space.profile_id).unwrap_or_default()); - } - cx.notify(); - } - - pub fn is_bookmarked(&self, url: &str) -> bool { - bookmarks::find(&self.bookmarks, url).is_some() - } - - fn bookmark_target(&self, key: Option) -> Option<(String, String)> { - let tab = key.or(self.model.active).and_then(|k| self.model.tab(k))?; - let url = self.tab_url(self.model.key(tab)).unwrap_or_else(|| tab.url.clone()); - (!url.is_empty()).then(|| (browser_core::text::stored_title_or_host(&tab.title, &url), url)) - } - - /// The top-level folder Save for Later files pages into, if it exists. - pub(crate) fn reading_list(&self) -> Option { - bookmarks::reading_list(&self.bookmarks) - } - - /// Files the active page into the Reading List bookmark folder, made on first use, so it is - /// kept, exported and deleted like any bookmark. - pub fn save_for_later(&mut self, cx: &mut Context) { - let (Some((title, url)), Some(space)) = (self.bookmark_target(None), self.model.current_space()) else { return }; - let (private, profile_id) = (space.private, space.space.profile_id); - self.reload_bookmarks(cx); - let saved = bookmarks::save_for_later(self.store(private), profile_id, &self.bookmarks, &url, &title, now()); - self.reload_bookmarks(cx); - let (tone, text) = browser_core::toast::reading_list(saved); - self.show_toast_as(tone, text, None, cx); - } - - /// Bookmarks the tab, or returns its bookmark when it already has one. - pub fn bookmark_tab(&mut self, key: Option, cx: &mut Context) -> Option { - let (title, url) = self.bookmark_target(key)?; - let space = self.model.current_space()?; - let id = bookmarks::bookmark(self.store(space.private), space.space.profile_id, &self.bookmarks, &url, &title, now())?; - self.reload_bookmarks(cx); - Some(id) - } - - pub fn unbookmark_tab(&mut self, key: Option, cx: &mut Context) { - let Some((_, url)) = self.bookmark_target(key) else { return }; - bookmarks::unbookmark(self.store(self.model.private()), &self.bookmarks, &url); - self.reload_bookmarks(cx); - } - - /// Saves every tab into a new dated folder and opens the library on its name field. - pub fn bookmark_all_tabs(&mut self, cx: &mut Context) { - let Some(space) = self.model.current_space().filter(|_| !self.model.tabs.is_empty()) else { return }; - let pages: Vec<(&str, String)> = self - .model - .tabs - .iter() - .filter(|t| !t.url.is_empty()) - .map(|t| (t.title.as_str(), self.tab_url(self.model.key(t)).unwrap_or_else(|| t.url.clone()))) - .collect(); - let Some(folder) = bookmarks::bookmark_all(self.store(space.private), space.space.profile_id, pages.iter().map(|(t, u)| (*t, u.as_str())), now()) - else { - return; - }; - self.reload_bookmarks(cx); - if let Some(main) = self.peek.main { - cx.defer(move |cx| { - main.update(cx, |b, window, cx| b.show_library(Some(folder), window, cx)).ok(); - }); - } - } - - pub fn new_bookmark_folder(&mut self, parent: Option, cx: &mut Context) -> Option { - let space = self.model.current_space()?; - let id = bookmarks::new_folder(self.store(space.private), space.space.profile_id, parent, now())?; - self.reload_bookmarks(cx); - Some(id) - } - - pub fn rename_bookmark(&mut self, id: Id, title: &str, cx: &mut Context) { - self.store(self.model.private()).rename_bookmark(id, title).ok(); - self.reload_bookmarks(cx); - } - - pub fn move_bookmark(&mut self, id: Id, parent: Option, cx: &mut Context) { - self.store(self.model.private()).move_bookmark(id, parent).ok(); - self.reload_bookmarks(cx); - } - - pub fn delete_bookmark(&mut self, id: Id, cx: &mut Context) { - self.store(self.model.private()).delete_bookmark(id).ok(); - self.reload_bookmarks(cx); - } - - /// Switches to a tab already showing `url`, otherwise opens it in a new one. - pub fn open_url(&mut self, url: &str, window: &mut Window, cx: &mut Context) { - if self.command_mode.is_some() { - self.close_command(window, cx); - } - if let Some(key) = self.model.tabs.iter().find(|t| t.url == url).map(|t| self.model.key(t)) { - return self.activate(key, window, cx); - } - if let Ok(url) = url::Url::parse(url) { - let before = self.model.active; - self.new_tab(&url, window, cx); - if self.model.active != before && self.is_bookmarked(url.as_str()) { - self.mark_typed(&url); - } - } - } - - /// Saves the current space's tabs as a snapshot named after it and opens the library on its name. - pub fn save_snapshot(&mut self, window: &mut Window, cx: &mut Context) { - let Some(space) = self.model.current_space() else { return }; - let name = format!("{} {}", space.space.name, date(now())); - if let Some(saved) = snapshot::save(self.store(space.private), space, &name, now()) { - self.open_library(Page::Snapshots, Some(Named::Snapshot(saved.id)), window, cx); - } - } - - /// The current profile's snapshots, newest first; a private space has none. - pub(crate) fn snapshots(&self) -> Vec { - self.model.current_space().filter(|s| !s.private).and_then(|s| self.store(false).snapshots(s.space.profile_id).ok()).unwrap_or_default() - } - - pub fn rename_snapshot(&mut self, saved: &Snapshot, name: &str) { - self.store(false).rename_snapshot(saved.profile_id, saved.id, name).ok(); - } - - pub fn delete_snapshot(&mut self, saved: &Snapshot) { - self.store(false).delete_snapshot(saved.profile_id, saved.id).ok(); - } - - /// Opens the snapshot's tabs in a new space of its profile, or at the end of the current space. - pub fn restore_snapshot(&mut self, saved: &Snapshot, new_space: bool, window: &mut Window, cx: &mut Context) -> Result<(), &'static str> { - let Some(current) = self.model.current_space().filter(|s| !s.private && s.space.profile_id == saved.profile_id).map(|s| s.space.id) else { - return Err("Switch to a space of this snapshot's profile to restore it."); - }; - let store = self.store(false); - let snapshot = SpaceSnapshot::load(store, saved.profile_id, saved.id).map_err(snapshot_error)?; - let target = if new_space { - let names = std::iter::once(saved.name.clone()).chain((2..50).map(|n| format!("{} {n}", saved.name))); - let name = names.filter_map(|n| crate::spaces::space_name(&n, &self.model.spaces, false, Some(saved.profile_id), None)).next(); - let space = store.create_space(saved.profile_id, name.as_deref().unwrap_or("Snapshot"), ""); - space.map_err(|_| "Tarn could not create a space for this snapshot.")?.id - } else { - current - }; - let last = snapshot.restore(store, target); - if new_space { - self.reload_spaces(); - if let Some(ix) = self.model.spaces.iter().position(|s| !s.private && s.space.id == target) { - self.switch_space(ix, window, cx); - } - } else { - self.reload_space(); - } - if let Some(id) = last { - self.activate(TabKey { private: false, id }, window, cx); - } - Self::sync_other_windows(cx); - cx.notify(); - Ok(()) - } - - pub(crate) fn downloads(&self) -> Vec { - self.model.current_space().and_then(|s| self.store(s.private).downloads(s.space.profile_id).ok()).unwrap_or_default() - } - - /// Removes one entry, or with `None` the whole list; the files stay. - pub fn remove_download(&mut self, id: Option) { - let Some(space) = self.model.current_space() else { return }; - let (store, profile_id) = (self.store(space.private), space.space.profile_id); - match id { - Some(id) => store.delete_download(profile_id, id), - None => store.clear_downloads(profile_id), - } - .ok(); - } - - pub(crate) fn close_library(&mut self, cx: &mut Context) { - if let Some(handle) = self.library.take() { - cx.defer(move |cx| drop(handle.update(cx, |library, window, cx| library.close(true, window, cx)))); - cx.notify(); - } - } - - pub fn toggle_library(&mut self, window: &mut Window, cx: &mut Context) { - match self.library { - Some(_) => self.close_library(cx), - // The click that took focus from the library already closed it; it must not reopen it. - None if self.library_closed.is_some_and(|t| t.elapsed() < ui::motion::REOPEN_GUARD) => {} - None => self.show_library(None, window, cx), - } - } - - /// Opens the library above the space row; with `edit`, on that bookmark with its name field open. - pub fn show_library(&mut self, edit: Option, window: &mut Window, cx: &mut Context) { - let page = match edit.and_then(|id| self.bookmarks.iter().find(|b| b.id == id)) { - Some(bm) => Page::Bookmarks(bm.parent_id), - None => Page::Home, - }; - self.open_library(page, edit.map(Named::Bookmark), window, cx); - } - - /// Opens the library on `page`; with `edit`, that row's name field is open. - pub(crate) fn open_library(&mut self, page: Page, edit: Option, window: &mut Window, cx: &mut Context) { - if let Some(handle) = self.library { - cx.defer(move |cx| drop(handle.update(cx, |library, window, cx| library.go(page, window, cx)))); - return; - } - let Some(main) = window.window_handle().downcast::().or(self.peek.main) else { return }; - let inset = SIDEBAR_MARGIN; - self.peek.owns[0] = self.peek.is_window(window); - if !self.peek.owns[0] { - self.close_peek(cx); - } - let anchor = self.main_bounds(window); - let room = f32::from(anchor.size.height) - 2. * inset - SPACE_ROW - TOOLBAR_HEIGHT - SEARCH_HEIGHT - 2.; - let max_list = room.max(ROW * 3.); - let downloads = self.downloads(); - let snapshots = self.snapshots(); - let sources = if page == Page::Import { detect_sources() } else { Vec::new() }; - let history = self.model.current_space().and_then(|s| self.store(s.private).history(s.space.profile_id, HISTORY_LOAD).ok()).unwrap_or_default(); - let rows: Vec<&HistoryEntry> = history.iter().collect(); - let listed = entries(self, page, "", &rows, &downloads, &snapshots, &sources); - let height = px(card_height(&listed, row_boundary(&listed, max_list))); - let (x, bottom, width) = (inset + 4., f32::from(anchor.size.height) - inset - SPACE_ROW, CARD_WIDTH.min(self.sidebar_width - 8.)); - let bounds = Bounds::new(point(anchor.origin.x + px(x), anchor.origin.y + px(bottom) - height), size(px(width), height)); - let display = window.display(cx).map(|d| d.id()); - let browser = cx.entity().downgrade(); - // The new window renders from the browser at once, so it must open after this update ends. - cx.defer(move |cx| { - let handle = cx.open_window(popup_options(bounds, display, true), |window, cx| { - if let Some(host) = engine::Host::from_window(window) { - host.hide_on_deactivate(); - host.round_corners(0., 0., 0., 0., f64::from(ui::theme::Theme::radius_panel())); - } - cx.new(|cx| LibraryWindow { - page, - fit: Some(Fit { x, bottom, width, max_list }), - sources: sources.clone(), - ..LibraryWindow::new(browser.clone(), main, history, downloads.clone(), edit, window, cx) - }) - }); - browser - .update(cx, |b, cx| { - b.library = handle.ok(); - cx.notify(); - }) - .ok(); - crate::peek::popovers_over_peek(&browser, cx); - }); - } -} - #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(crate) enum Page { Home, @@ -408,196 +156,6 @@ enum Entry { Row(Row), } -fn row(item: Item, title: String, bookmark: Option) -> Entry { - Entry::Row(Row { item, title, named: bookmark.map(Named::Bookmark), detail: None }) -} - -fn bookmark_row(bm: &Bookmark) -> Entry { - let item = match &bm.url { - Some(url) => Item::Url(url.clone()), - None => Item::Folder(bm.id), - }; - row(item, title_or_host(&bm.title, bm.url.as_deref().unwrap_or_default()), Some(bm.id)) -} - -fn entries(b: &Browser, page: Page, query: &str, history: &[&HistoryEntry], downloads: &[Download], snapshots: &[Snapshot], sources: &[Source]) -> Vec { - let matches = |title: &str, url: &str| library::matches(query, title, url); - let store = b.store(b.model.private()); - let bookmarks = &b.bookmarks; - let found = |limit| library::bookmarks(bookmarks, query).take(limit).map(bookmark_row); - let visits = history; - let history = |limit| visits.iter().take(limit).map(|h| row(Item::Url(h.url.clone()), title_or_host(&h.title, &h.url), None)); - let downloads = |limit| { - let now = now(); - library::downloads(downloads, query).take(limit).map(move |d| download_row(store, d, now)) - }; - let mut out = Vec::new(); - match page { - Page::Home => { - let tabs = library::open_tabs(&b.model.tabs, query); - if query.is_empty() || !tabs.is_empty() { - out.push(Entry::Header("Open Tabs", Some(tabs.len()))); - } - if query.is_empty() && tabs.is_empty() { - out.push(Entry::Empty("No open tabs".into())); - } - out.extend(tabs.into_iter().take(MAX_ROWS).map(|t| row(Item::Tab(b.model.key(t)), title_or_host(&t.title, &t.url), None))); - if !query.is_empty() { - let sections: [(&str, Vec); 3] = - [("Bookmarks", found(MAX_ROWS).collect()), ("History", history(MAX_ROWS).collect()), ("Downloads", downloads(MAX_ROWS).collect())]; - for (name, rows) in sections.into_iter().filter(|(_, rows)| !rows.is_empty()) { - out.push(Entry::Header(name, None)); - out.extend(rows); - } - if out.is_empty() { - out.push(Entry::Empty(empty_text(page, query))); - } - } - out.push(Entry::Header("Library", None)); - out.push(row(Item::Page(Page::History), "History".into(), None)); - out.push(row(Item::Page(Page::Bookmarks(None)), "Bookmarks".into(), None)); - if let Some(folder) = b.reading_list() { - out.push(row(Item::Page(Page::Bookmarks(Some(folder))), bookmarks::READING_LIST.into(), None)); - } - out.push(row(Item::Page(Page::Downloads), "Downloads".into(), None)); - if !b.model.private() { - out.push(row(Item::Page(Page::Snapshots), "Snapshots".into(), None)); - } - out.push(row(Item::Page(Page::Memory), "Memory".into(), None)); - if query.is_empty() && data::available() { - out.push(row(Item::Page(Page::Import), "Import Browser Data".into(), None)); - } - } - Page::History => { - out.push(Entry::Back("History".into())); - let now = now(); - let starts = library::day_starts(store, now); - let mut last = None; - for h in visits.iter().take(MAX_LIST) { - let day = library::history_day(h.visited_at, starts); - if last.replace(day) != Some(day) { - out.push(Entry::Header(day, None)); - } - out.push(visit_row(store, h, now)); - } - } - Page::Bookmarks(folder) => { - let name = folder.and_then(|id| bookmarks.iter().find(|bm| bm.id == id)).map_or("Bookmarks".into(), |bm| bounded_title(&bm.title)); - out.push(Entry::Back(name)); - if query.is_empty() { - out.extend(bookmarks.iter().filter(|bm| bm.parent_id == folder).map(bookmark_row)); - } else { - out.extend(found(MAX_LIST)); - } - } - Page::Downloads => { - out.push(Entry::Back("Downloads".into())); - out.extend(downloads(MAX_LIST)); - if out.len() > 1 && query.is_empty() { - out.push(Entry::Divider); - out.push(row(Item::ClearDownloads, "Clear List".into(), None)); - } - } - Page::Snapshots => { - out.push(Entry::Back("Snapshots".into())); - if snapshots.is_empty() { - out.push(Entry::Empty("Save a space with “Save Space as Snapshot”".into())); - } - let now = now(); - out.extend(snapshots.iter().filter(|s| matches(&s.name, "")).map(|s| { - let detail = Some(ago(store, s.created_at, now)); - Entry::Row(Row { item: Item::Snapshot(s.clone()), title: bounded_title(&s.name), named: Some(Named::Snapshot(s.id)), detail }) - })); - } - Page::Memory => { - out.push(Entry::Back("Memory".into())); - let costs = b.tab_costs(); - let mut tabs: Vec<(TabKey, &Tab)> = b.model.tabs.iter().filter(|t| matches(&t.title, &t.url)).map(|t| (b.model.key(t), t)).collect(); - tabs.sort_by_key(|(key, t)| (Reverse(costs.get(key).map_or(0, |c| c.footprint)), Reverse(t.last_active))); - out.extend(tabs.into_iter().map(|(key, t)| { - let detail = crate::memory::detail(costs.get(&key).copied(), b.sleeping(key)); - Entry::Row(Row { item: Item::Tab(key), title: title_or_host(&t.title, &t.url), named: None, detail: Some(detail) }) - })); - if out.len() > 1 && query.is_empty() { - out.push(Entry::Divider); - out.push(row(Item::SleepInactive, "Sleep All Inactive Tabs".into(), None)); - } - } - Page::Import => { - out.push(Entry::Back("Import Browser Data".into())); - if sources.is_empty() { - out.push(Entry::Empty("No supported browser found".into())); - } - out.extend( - sources.iter().enumerate().filter(|(_, s)| matches(s.browser.name(), &s.label)).map(|(ix, s)| { - Entry::Row(Row { item: Item::Source(ix), title: s.browser.name().into(), named: None, detail: Some(bounded_title(&s.label)) }) - }), - ); - } - } - if out.len() == 1 { - out.push(Entry::Empty(empty_text(page, query))); - } - out -} - -fn tally(n: usize) -> Option { - (n > 0).then(|| thousands(n as u64)) -} - -/// Rows listed on a page; on a page cut at `MAX_LIST` the cap reads "200+", never as the total. -fn listed_tally(n: usize, capped: bool) -> Option { - if capped && n >= MAX_LIST { Some(format!("{MAX_LIST}+")) } else { tally(n) } -} - -fn empty_text(page: Page, query: &str) -> String { - if !query.is_empty() { - return format!("No results for “{}”", bounded_title(query)); - } - match page { - Page::History => "No history yet", - Page::Bookmarks(None) => "No bookmarks yet", - Page::Bookmarks(Some(_)) => "This folder is empty", - Page::Downloads => "No downloads yet", - _ => "Nothing here", - } - .into() -} - -fn entry_height(entry: &Entry) -> f32 { - match entry { - Entry::Header(..) => HEADER_ROW, - Entry::Back(_) => BACK_ROW, - Entry::Empty(_) => EMPTY_ROW, - Entry::Divider => DIVIDER, - Entry::Row(r) if r.detail.is_some() => DETAIL_ROW, - Entry::Row(_) => ROW, - } -} - -/// The tallest list up to `max_list` that ends below a row, so a cut list never shows a heading or -/// divider without the row under it, or half a row; `max_list` when the whole list fits. -fn row_boundary(entries: &[Entry], max_list: f32) -> f32 { - let mut end = LIST_PAD; - let mut fit = None; - for (ix, entry) in entries.iter().enumerate() { - end += entry_height(entry) + if ix > 0 { 1. } else { 0. }; - if end > max_list { - return fit.unwrap_or(max_list); - } - if !matches!(entry, Entry::Header(..) | Entry::Divider) { - fit = Some(end); - } - } - max_list -} - -/// The card's height for `entries`, with the list capped at `max_list`. -fn card_height(entries: &[Entry], max_list: f32) -> f32 { - let list: f32 = entries.iter().map(entry_height).sum::() + entries.len().saturating_sub(1) as f32 + LIST_PAD; - SEARCH_HEIGHT + 2. + list.min(max_list) -} - pub struct LibraryWindow { browser: WeakEntity, main: WindowHandle, @@ -934,370 +492,92 @@ impl LibraryWindow { cx.notify(); } - fn begin_rename(&mut self, named: Named, window: &mut Window, cx: &mut Context) { - let title = match named { - Named::Bookmark(id) => self.browser.upgrade().and_then(|b| b.read(cx).bookmarks.iter().find(|bm| bm.id == id).map(|bm| bm.title.clone())), - Named::Snapshot(id) => self.snapshots.iter().find(|s| s.id == id).map(|s| s.name.clone()), - }; - let Some(title) = title else { return }; - let input = cx.new(|cx| { - let mut input = TextInput::new("Name", cx); - input.set_text(title, cx); - input.select_all_from_start(cx); - input - }); - let events = cx.subscribe_in(&input, window, |this, _, event, window, cx| match event { - TextInputEvent::Submit => this.end_rename(true, window, cx), - TextInputEvent::Cancel => this.end_rename(false, window, cx), - TextInputEvent::MenuClosed if !window.is_window_active() && !this.holding => this.close(false, window, cx), - _ => {} - }); - let focus = input.focus_handle(cx); - let blur = cx.on_blur(&focus, window, |this, window, cx| this.end_rename(true, window, cx)); - window.focus(&focus); - self.renaming = Some((named, input, [events, blur])); - cx.notify(); - } - - fn end_rename(&mut self, commit: bool, window: &mut Window, cx: &mut Context) { - let Some((named, input, _)) = self.renaming.take() else { return }; - let title = input.read(cx).text().trim().to_owned(); - if commit && !title.is_empty() { - match named { - Named::Bookmark(id) => drop(self.browser.update(cx, |b, cx| b.rename_bookmark(id, &title, cx))), - Named::Snapshot(id) => { - if let Some(saved) = self.snapshots.iter().find(|s| s.id == id).cloned() { - self.browser.update(cx, |b, _| b.rename_snapshot(&saved, &title)).ok(); - self.reload_snapshots(cx); - } - } - } - } - window.focus(&self.query.focus_handle(cx)); - cx.notify(); - } - - fn new_folder(&mut self, window: &mut Window, cx: &mut Context) { - let parent = match self.page { - Page::Bookmarks(folder) => folder, - _ => None, - }; - let Some(id) = self.browser.update(cx, |b, cx| b.new_bookmark_folder(parent, cx)).ok().flatten() else { return }; - self.go(Page::Bookmarks(parent), window, cx); - self.select(Named::Bookmark(id), cx); - self.begin_rename(Named::Bookmark(id), window, cx); - } - - fn delete(&mut self, named: Named, window: &mut Window, cx: &mut Context) { - let id = match named { - Named::Bookmark(id) => id, - Named::Snapshot(id) => { - let Some(saved) = self.snapshots.iter().find(|s| s.id == id).cloned() else { return }; - let message = format!("Delete the snapshot “{}”?", bounded_title(&saved.name)); - return self.confirm(&message, None, "Delete", window, cx, move |this, cx| { - this.browser.update(cx, |b, _| b.delete_snapshot(&saved)).ok(); - this.reload_snapshots(cx); - }); - } - }; - let Some(browser) = self.browser.upgrade() else { return }; - let b = browser.read(cx); - let Some(bm) = b.bookmarks.iter().find(|bm| bm.id == id) else { return }; - let message = if bookmarks::subtree(&b.bookmarks, id).len() == 1 { - format!("Delete the bookmark “{}”?", bounded_title(&bm.title)) - } else { - format!("Delete “{}” and everything in it?", bounded_title(&bm.title)) - }; - self.confirm(&message, None, "Delete", window, cx, move |this, cx| { - this.browser.update(cx, |b, cx| b.delete_bookmark(id, cx)).ok(); - }); - } - - fn remove_history(&mut self, url: String, cx: &mut Context) { - self.browser.update(cx, |b, cx| b.remove_history_url(&url, cx)).ok(); - self.history.retain(|h| h.url != url); - *self.history_hits.borrow_mut() = None; - self.shown = self.rows(cx); - cx.notify(); - } - - /// Delete, F2 and Shift+F10 act on the selected row; the delete keys only while the search - /// field is empty, so they still edit its text. - fn on_key(&mut self, event: &gpui::KeyDownEvent, window: &mut Window, cx: &mut Context) { - let key = &event.keystroke; - let Some((_, r)) = self.shown.get(self.selected).cloned() else { return }; - if self.renaming.is_some() || self.holding || event.is_held { - return; - } - match key.key.as_str() { - "f2" if !key.modifiers.modified() => match r.named { - Some(named) => self.begin_rename(named, window, cx), - None => return, - }, - "f10" if key.modifiers.shift => self.row_menu(r.item.clone(), r.named, window, cx), - _ => return, - } - cx.stop_propagation(); - } - - /// Deletes the selected row for Delete or ⌘⌫ while the search field is empty, before the - /// field, which holds the focus, takes the key. - fn delete_selected(&mut self, window: &mut Window, cx: &mut Context) { - let Some((_, r)) = self.shown.get(self.selected).cloned() else { return cx.propagate() }; - if self.renaming.is_some() || self.holding || !self.query.read(cx).text().is_empty() { - return cx.propagate(); - } - match (r.named, visit(&r)) { - (Some(named), _) => self.delete(named, window, cx), - (None, Some(url)) => self.remove_history(url.to_owned(), cx), - _ => return cx.propagate(), - } - cx.stop_propagation(); - } - - fn confirm( - &mut self, - message: &str, - detail: Option<&str>, - action: &str, - window: &mut Window, - cx: &mut Context, - then: impl FnOnce(&mut Self, &mut Context) + 'static, - ) { - let answer = self.ask(PromptLevel::Warning, message, detail, &[action, "Cancel"], window, cx); - cx.spawn_in(window, async move |this, cx| { - let yes = answer.await == Ok(0); - this.update_in(cx, |this, window, cx| { - this.answered(window, cx); - if yes { - then(this, cx); - } - window.focus(&this.query.focus_handle(cx)); - }) - .ok(); - }) - .detach(); - } - - /// A dialog draws inside the popover, so the popover takes its full height while one is up. - fn ask( - &mut self, - level: PromptLevel, - message: &str, - detail: Option<&str>, - answers: &[&str], - window: &mut Window, - cx: &mut Context, - ) -> oneshot::Receiver { - self.holding = true; - if let Some(fit) = &self.fit { - self.place(SEARCH_HEIGHT + 2. + fit.max_list, window, cx); - } - crate::dialog::ask(level, message, detail, answers, window, cx) - } - - fn answered(&mut self, window: &mut Window, cx: &mut Context) { - self.holding = false; - self.refit(window, cx); - } - - fn alert(&mut self, message: &str, detail: Option<&str>, window: &mut Window, cx: &mut Context) { - let answer = self.ask(PromptLevel::Info, message, detail, &["OK"], window, cx); - cx.spawn_in(window, async move |this, cx| { - answer.await.ok(); - this.update_in(cx, |this, window, cx| { - this.answered(window, cx); - window.focus(&this.query.focus_handle(cx)); + fn back_row(&self, title: String, tally: Option, on_bookmarks: bool, cx: &mut Context) -> AnyElement { + div() + .id("library-back") + .h(px(BACK_ROW)) + .px_1() + .flex() + .flex_none() + .items_center() + .gap_1() + .rounded(px(Theme::radius_row())) + .cursor_pointer() + .font_weight(FontWeight::SEMIBOLD) + .hover(|s| s.bg(Theme::hover())) + .child(icon(Icon::ChevronLeft, 14., Theme::muted())) + .child(div().flex_1().one_line(SharedString::from(title))) + .children(tally.map(|n| div().flex_none().px_1().text_size(px(TEXT_SMALL)).font_weight(FontWeight::NORMAL).text_color(Theme::muted()).child(n))) + .when(on_bookmarks, |d| { + d.child(icon_button("library-new-folder", Icon::FolderPlus, true).tooltip(tooltip("New Folder", None)).on_click(cx.listener( + |this, _, window, cx| { + cx.stop_propagation(); + this.new_folder(window, cx); + }, + ))) }) - .ok(); - }) - .detach(); + .on_click(cx.listener(|this, _, window, cx| this.back(window, cx))) + .into_any_element() } - /// Asks which data to bring from a source into the current space's profile, then reads it in - /// the background (where macOS may show its keychain prompt) and writes it. - fn start_import(&mut self, ix: usize, window: &mut Window, cx: &mut Context) { - let (Some(source), Some(browser)) = (self.sources.get(ix).cloned(), self.browser.upgrade()) else { return }; - let b = browser.read(cx); - let Some(space) = b.model.current_space() else { return }; - let (private, profile_id, core) = (space.private, space.space.profile_id, b.core.clone()); - if core.importing.get() { - return self.alert("An import is already running.", None, window, cx); - } - if core.import_target(private, profile_id).is_err() { - let detail = "Private and Lockdown profiles keep website data in memory only, so imported sign-ins would not last."; - return self.alert("Switch to a space of a normal profile to import into it.", Some(detail), window, cx); - } - let name = source.browser.name(); - let profile = core.disk.profile(profile_id).map(|p| p.name).unwrap_or_default(); - let data::Confirm { message, detail, cookies } = data::confirm(&source, &profile, ui::controls::THIS_DEVICE); - let sealed = !cookies; - let buttons: &[&str] = if sealed { &["Import", "Cancel"] } else { &["Import All", "History and Bookmarks Only", "Cancel"] }; - let answer = self.ask(PromptLevel::Info, &message, Some(&detail), buttons, window, cx); - let (weak_browser, main) = (self.browser.clone(), self.main); - cx.spawn_in(window, async move |this, cx| { - let cookies = match answer.await { - Ok(0) => !sealed, - Ok(1) if !sealed => false, - _ => return drop(this.update_in(cx, |this, window, cx| this.answered(window, cx))), - }; - if core.importing.replace(true) { - this.update_in(cx, |this, window, cx| { - this.answered(window, cx); - this.alert("An import is already running.", None, window, cx); - }) - .ok(); - return; - } - let kinds = Kinds { cookies, history: true, bookmarks: true }; - let browser_kind = source.browser; - let read = cx.background_executor().spawn(async move { data::read(&source, kinds) }).await; - let (tx, rx) = oneshot::channel(); - let summary = match core.import(profile_id, browser_kind, read, move |r| drop(tx.send(r))) { - // The engine answers each cookie write; a store closed meanwhile may never answer. - Ok(()) => match futures::future::select(rx, cx.background_executor().timer(IMPORT_TIMEOUT)).await { - futures::future::Either::Left((report, _)) => data::summary(name, report.ok().as_ref()), - futures::future::Either::Right(_) => data::summary(name, None), - }, - Err(_) => "Nothing was imported: this profile can no longer take imported data.".into(), - }; - core.importing.set(false); - let same_profile = weak_browser - .update(cx, |b, cx| { - b.reload_bookmarks(cx); - b.model.current_space().is_some_and(|s| !s.private && s.space.profile_id == profile_id) - }) - .unwrap_or(false); - this.update_in(cx, |this, window, cx| { - this.answered(window, cx); - if same_profile { - this.history = core.disk.history(profile_id, HISTORY_LOAD).unwrap_or_default(); - this.history_hits.take(); - } - if !window.is_window_active() { - this.close(false, window, cx); - } - }) - .ok(); - main.update(cx, |_, window, cx| drop(window.prompt(PromptLevel::Info, &format!("Import from {name}"), Some(&summary), &["OK"], cx))).ok(); - }) - .detach(); + fn search_box(&self, empty_query: bool, cx: &mut Context) -> gpui::Div { + div() + .m_1p5() + .h(px(SEARCH_HEIGHT - 12.)) + .px_2() + .flex() + .flex_none() + .items_center() + .gap_2() + .rounded(px(Theme::radius_row())) + .bg(Theme::raised()) + .child(icon(Icon::Search, 14., Theme::muted())) + .child(div().flex_1().min_w_0().child(self.query.clone())) + .when(empty_query, |d| d.child(key_hint(crate::shortcuts::shown(&crate::ToggleLibrary, cx)))) } - fn run(&mut self, cmd: Cmd, window: &mut Window, cx: &mut Context) { - match cmd { - Cmd::Open(item) => self.open(item, window, cx), - Cmd::OpenInNewTab(url) => { - if let Ok(url) = url::Url::parse(&url) { - self.main - .update(cx, |b, window, cx| { - let before = b.model.active; - b.new_tab(&url, window, cx); - if b.model.active != before && b.is_bookmarked(url.as_str()) { - b.mark_typed(&url); - } - }) - .ok(); - } - self.close(true, window, cx); - } - Cmd::Rename(named) => self.begin_rename(named, window, cx), - Cmd::Move(id, parent) => { - self.browser.update(cx, |b, cx| b.move_bookmark(id, parent, cx)).ok(); - } - Cmd::Delete(named) => self.delete(named, window, cx), - Cmd::Restore(saved, new_space) => self.restore(saved, new_space, window, cx), - Cmd::NewFolder => self.new_folder(window, cx), - Cmd::ToggleBookmark(key) => { - self.browser - .update(cx, |b, cx| match b.tab_url(key).is_some_and(|url| b.is_bookmarked(&url)) { - true => b.unbookmark_tab(Some(key), cx), - false => drop(b.bookmark_tab(Some(key), cx)), - }) - .ok(); - } - Cmd::CopyLink(url) => cx.write_to_clipboard(ClipboardItem::new_string(url)), - Cmd::RemoveDownload(id) => self.remove_download(Some(id), cx), - Cmd::RemoveHistory(url) => self.remove_history(url, cx), + fn row_title(&self, r: &Row, editing: Option>, detail: Option, cx: &mut Context) -> AnyElement { + match (editing, detail) { + (Some(input), _) => div() + .flex_1() + .min_w_0() + .px_1() + .rounded(px(Theme::radius_row())) + .bg(Theme::raised()) + .on_mouse_down_out(cx.listener(|this, _, window, cx| this.end_rename(true, window, cx))) + .child(input) + .into_any_element(), + (None, Some(detail)) => div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child(div().one_line(SharedString::from(r.title.clone()))) + .child(div().text_size(px(TEXT_SMALL)).text_color(Theme::muted()).one_line(SharedString::from(detail))) + .into_any_element(), + (None, None) => div().flex_1().one_line(SharedString::from(r.title.clone())).into_any_element(), } } - fn row_menu(&mut self, item: Item, named: Option, window: &mut Window, cx: &mut Context) { - cx.stop_propagation(); - let Some(browser) = self.browser.upgrade() else { return }; - let b = browser.read(cx); - let Some(host) = b.host.clone() else { return }; - let url = match &item { - Item::Url(url) => Some(url.clone()), - Item::Tab(key) => b.tab_url(*key), - _ => None, - }; - let item_key = item.clone(); - let history = match &item { - Item::Url(url) if named.is_none() => Some(url.clone()), + fn row_aside(&self, r: &Row, b: Option<&Browser>) -> (Option, Option) { + let inside = |folder: Option| b.map_or(0, |b| b.bookmarks.iter().filter(|bm| bm.parent_id == folder).count()); + // Shortened from the left like the toolbar's host (S5), so the registrable domain stays visible. + let host = + |url: Option| url.and_then(|url| tab_host(&url)).filter(|host| *host != r.title).map(|host| browser_core::command::host_tail(&host, 16)); + let aside = match &r.item { + Item::Url(url) => host(Some(url.clone())), + Item::Tab(key) if r.detail.is_none() => host(b.and_then(|b| b.tab_url(*key))), + Item::Page(Page::Bookmarks(None)) => tally(b.map_or(0, |b| b.bookmarks.iter().filter(|bm| bm.url.is_some()).count())), + Item::Page(Page::Bookmarks(Some(id))) | Item::Folder(id) => tally(inside(Some(*id))), + Item::Page(Page::Downloads) => tally(self.downloads.len()), + Item::Page(Page::Snapshots) => tally(self.snapshots.len()), _ => None, }; - let mut items = match &item { - Item::Download(d) => { - let mut items = vec![MenuItem::action(ui::controls::REVEAL, Cmd::Open(item.clone()))]; - items.extend((!d.url.is_empty()).then(|| MenuItem::action("Copy Download Link", Cmd::CopyLink(d.url.clone())))); - items.extend([MenuItem::Separator, MenuItem::action("Remove from List", Cmd::RemoveDownload(d.id))]); - items - } - Item::Snapshot(saved) => vec![ - MenuItem::action("Restore in New Space", Cmd::Restore(saved.clone(), true)), - MenuItem::action("Restore in This Space", Cmd::Restore(saved.clone(), false)), - MenuItem::Separator, - MenuItem::action("Rename", Cmd::Rename(Named::Snapshot(saved.id))), - MenuItem::action("Delete…", Cmd::Delete(Named::Snapshot(saved.id))), - ], - _ => vec![MenuItem::action("Open", Cmd::Open(item))], - }; - let bookmarked = url.as_deref().is_some_and(|url| b.is_bookmarked(url)); - if let Some(url) = url { - items.extend([MenuItem::action("Open in New Tab", Cmd::OpenInNewTab(url.clone())), MenuItem::action("Copy Link", Cmd::CopyLink(url))]); - } - if let Item::Tab(key) = item_key { - items.push(MenuItem::action(if bookmarked { "Remove Bookmark" } else { "Bookmark Tab" }, Cmd::ToggleBookmark(key))); - } - if let Some(url) = history { - items.extend([MenuItem::Separator, MenuItem::action("Remove from History", Cmd::RemoveHistory(url))]); - } - if let Some(Named::Bookmark(id)) = named { - let parent = b.bookmarks.iter().find(|bm| bm.id == id).and_then(|bm| bm.parent_id); - let mut folders = vec![MenuItem::action("Bookmarks", Cmd::Move(id, None)).checked(parent.is_none()).enabled(parent.is_some())]; - folders.extend( - bookmarks::move_targets(&b.bookmarks, id) - .into_iter() - .map(|f| MenuItem::action(bounded_title(&f.title), Cmd::Move(id, Some(f.id))).checked(parent == Some(f.id)).enabled(parent != Some(f.id))), - ); - items.extend([ - MenuItem::Separator, - MenuItem::action("Rename", Cmd::Rename(Named::Bookmark(id))), - MenuItem::Submenu("Move to Folder".into(), folders), - MenuItem::action("New Folder", Cmd::NewFolder), - MenuItem::Separator, - MenuItem::action("Delete", Cmd::Delete(Named::Bookmark(id))), - ]); + // A row with a detail line shows its host there, so the title keeps the row's width. + match (&r.detail, aside) { + (Some(detail), Some(host)) if matches!(r.item, Item::Url(_)) => (None, Some(format!("{detail} · {host}"))), + (detail, aside) => (aside, detail.clone()), } - self.holding = true; - cx.spawn_in(window, async move |this, cx| { - let (tx, rx) = oneshot::channel(); - menu::show(&host, crate::menu_glyphs::with_glyphs(items), None, move |cmd| { - tx.send(cmd).ok(); - }); - let cmd = rx.await.ok(); - this.update_in(cx, |this, window, cx| { - this.holding = false; - match cmd { - Some(cmd) => this.run(cmd, window, cx), - None if !window.is_window_active() => this.close(false, window, cx), - None => {} - } - }) - .ok(); - }) - .detach(); } fn render_row(&self, ix: usize, r: Row, leading: AnyElement, cx: &mut Context) -> AnyElement { @@ -1320,44 +600,8 @@ impl LibraryWindow { _ => None, }; let has_actions = r.named.is_some() || visited.is_some() || sleepable.is_some(); - let inside = |folder: Option| b.map_or(0, |b| b.bookmarks.iter().filter(|bm| bm.parent_id == folder).count()); - // Shortened from the left like the toolbar's host (S5), so the registrable domain stays visible. - let host = - |url: Option| url.and_then(|url| tab_host(&url)).filter(|host| *host != r.title).map(|host| browser_core::command::host_tail(&host, 16)); - let aside = match &r.item { - Item::Url(url) => host(Some(url.clone())), - Item::Tab(key) if r.detail.is_none() => host(b.and_then(|b| b.tab_url(*key))), - Item::Page(Page::Bookmarks(None)) => tally(b.map_or(0, |b| b.bookmarks.iter().filter(|bm| bm.url.is_some()).count())), - Item::Page(Page::Bookmarks(Some(id))) | Item::Folder(id) => tally(inside(Some(*id))), - Item::Page(Page::Downloads) => tally(self.downloads.len()), - Item::Page(Page::Snapshots) => tally(self.snapshots.len()), - _ => None, - }; - // A row with a detail line shows its host there, so the title keeps the row's width. - let (aside, detail) = match (&r.detail, aside) { - (Some(detail), Some(host)) if matches!(r.item, Item::Url(_)) => (None, Some(format!("{detail} · {host}"))), - (detail, aside) => (aside, detail.clone()), - }; - let title: AnyElement = match (editing, detail) { - (Some(input), _) => div() - .flex_1() - .min_w_0() - .px_1() - .rounded(px(Theme::radius_row())) - .bg(Theme::raised()) - .on_mouse_down_out(cx.listener(|this, _, window, cx| this.end_rename(true, window, cx))) - .child(input) - .into_any_element(), - (None, Some(detail)) => div() - .flex_1() - .min_w_0() - .flex() - .flex_col() - .child(div().one_line(SharedString::from(r.title.clone()))) - .child(div().text_size(px(TEXT_SMALL)).text_color(Theme::muted()).one_line(SharedString::from(detail))) - .into_any_element(), - (None, None) => div().flex_1().one_line(SharedString::from(r.title.clone())).into_any_element(), - }; + let (aside, detail) = self.row_aside(&r, b); + let title = self.row_title(&r, editing, detail, cx); div() .id(("library-row", ix)) .h(px(if r.detail.is_some() { DETAIL_ROW } else { ROW })) @@ -1434,6 +678,23 @@ impl LibraryWindow { } } +fn leading_icon(b: &Browser, item: &Item) -> AnyElement { + match item { + Item::Tab(key) => b.model.tab(*key).map_or_else(|| icon(Icon::Search, 16., Theme::muted()).into_any_element(), |t| site_icon(b, &t.url, 16.)), + Item::Url(url) => site_icon(b, url, 16.), + Item::Folder(_) => icon(Icon::Folder, 16., Theme::muted()).into_any_element(), + Item::Page(Page::History) => icon(Icon::History, 16., Theme::muted()).into_any_element(), + Item::Page(Page::Downloads) => icon(Icon::Download, 16., Theme::muted()).into_any_element(), + Item::Download(d) => site_icon(b, &d.url, 16.), + Item::Snapshot(_) | Item::Page(Page::Snapshots) => icon(Icon::Group, 16., Theme::muted()).into_any_element(), + Item::ClearDownloads => icon(Icon::Trash, 16., Theme::muted()).into_any_element(), + Item::Page(Page::Import) | Item::Source(_) => icon(Icon::AppWindow, 16., Theme::muted()).into_any_element(), + Item::Page(Page::Memory) => icon(Icon::Gauge, 16., Theme::muted()).into_any_element(), + Item::SleepInactive => div().size(px(16.)).flex_none().into_any_element(), + Item::Page(_) => icon(Icon::Bookmark, 16., Theme::muted()).into_any_element(), + } +} + impl Render for LibraryWindow { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { if self.scroll.offset() != self.hovered_at { @@ -1459,22 +720,7 @@ impl Render for LibraryWindow { .into_iter() .map(|e| { let leading = match &e { - Entry::Row(r) => Some(match &r.item { - Item::Tab(key) => { - b.model.tab(*key).map_or_else(|| icon(Icon::Search, 16., Theme::muted()).into_any_element(), |t| site_icon(b, &t.url, 16.)) - } - Item::Url(url) => site_icon(b, url, 16.), - Item::Folder(_) => icon(Icon::Folder, 16., Theme::muted()).into_any_element(), - Item::Page(Page::History) => icon(Icon::History, 16., Theme::muted()).into_any_element(), - Item::Page(Page::Downloads) => icon(Icon::Download, 16., Theme::muted()).into_any_element(), - Item::Download(d) => site_icon(b, &d.url, 16.), - Item::Snapshot(_) | Item::Page(Page::Snapshots) => icon(Icon::Group, 16., Theme::muted()).into_any_element(), - Item::ClearDownloads => icon(Icon::Trash, 16., Theme::muted()).into_any_element(), - Item::Page(Page::Import) | Item::Source(_) => icon(Icon::AppWindow, 16., Theme::muted()).into_any_element(), - Item::Page(Page::Memory) => icon(Icon::Gauge, 16., Theme::muted()).into_any_element(), - Item::SleepInactive => div().size(px(16.)).flex_none().into_any_element(), - Item::Page(_) => icon(Icon::Bookmark, 16., Theme::muted()).into_any_element(), - }), + Entry::Row(r) => Some(leading_icon(b, &r.item)), _ => None, }; (e, leading) @@ -1499,34 +745,7 @@ impl Render for LibraryWindow { .pb_1() .children(n.and_then(tally).map(|n| div().font_weight(FontWeight::NORMAL).text_color(Theme::faint()).child(n))) .into_any_element(), - Entry::Back(title) => div() - .id("library-back") - .h(px(BACK_ROW)) - .px_1() - .flex() - .flex_none() - .items_center() - .gap_1() - .rounded(px(Theme::radius_row())) - .cursor_pointer() - .font_weight(FontWeight::SEMIBOLD) - .hover(|s| s.bg(Theme::hover())) - .child(icon(Icon::ChevronLeft, 14., Theme::muted())) - .child(div().flex_1().one_line(SharedString::from(title))) - .children( - listed_tally(listed, capped) - .map(|n| div().flex_none().px_1().text_size(px(TEXT_SMALL)).font_weight(FontWeight::NORMAL).text_color(Theme::muted()).child(n)), - ) - .when(on_bookmarks, |d| { - d.child(icon_button("library-new-folder", Icon::FolderPlus, true).tooltip(tooltip("New Folder", None)).on_click(cx.listener( - |this, _, window, cx| { - cx.stop_propagation(); - this.new_folder(window, cx); - }, - ))) - }) - .on_click(cx.listener(|this, _, window, cx| this.back(window, cx))) - .into_any_element(), + Entry::Back(title) => self.back_row(title, listed_tally(listed, capped), on_bookmarks, cx), Entry::Divider => div().mx_2().my_1p5().h(px(1.)).flex_none().bg(Theme::hairline()).into_any_element(), Entry::Empty(text) => empty(text).h(px(EMPTY_ROW)).px_2().into_any_element(), Entry::Row(r) => { @@ -1536,19 +755,7 @@ impl Render for LibraryWindow { }); } let empty_query = self.query.read(cx).text().is_empty(); - let search = div() - .m_1p5() - .h(px(SEARCH_HEIGHT - 12.)) - .px_2() - .flex() - .flex_none() - .items_center() - .gap_2() - .rounded(px(Theme::radius_row())) - .bg(Theme::raised()) - .child(icon(Icon::Search, 14., Theme::muted())) - .child(div().flex_1().min_w_0().child(self.query.clone())) - .when(empty_query, |d| d.child(key_hint(crate::shortcuts::shown(&crate::ToggleLibrary, cx)))); + let search = self.search_box(empty_query, cx); let list = match (self.turn, self.backward) { (0, _) => list.into_any_element(), (turn, backward) => { diff --git a/crates/app/src/library/actions.rs b/crates/app/src/library/actions.rs new file mode 100644 index 00000000..882504a3 --- /dev/null +++ b/crates/app/src/library/actions.rs @@ -0,0 +1,369 @@ +use super::*; + +impl LibraryWindow { + pub(super) fn begin_rename(&mut self, named: Named, window: &mut Window, cx: &mut Context) { + let title = match named { + Named::Bookmark(id) => self.browser.upgrade().and_then(|b| b.read(cx).bookmarks.iter().find(|bm| bm.id == id).map(|bm| bm.title.clone())), + Named::Snapshot(id) => self.snapshots.iter().find(|s| s.id == id).map(|s| s.name.clone()), + }; + let Some(title) = title else { return }; + let input = cx.new(|cx| { + let mut input = TextInput::new("Name", cx); + input.set_text(title, cx); + input.select_all_from_start(cx); + input + }); + let events = cx.subscribe_in(&input, window, |this, _, event, window, cx| match event { + TextInputEvent::Submit => this.end_rename(true, window, cx), + TextInputEvent::Cancel => this.end_rename(false, window, cx), + TextInputEvent::MenuClosed if !window.is_window_active() && !this.holding => this.close(false, window, cx), + _ => {} + }); + let focus = input.focus_handle(cx); + let blur = cx.on_blur(&focus, window, |this, window, cx| this.end_rename(true, window, cx)); + window.focus(&focus); + self.renaming = Some((named, input, [events, blur])); + cx.notify(); + } + + pub(super) fn end_rename(&mut self, commit: bool, window: &mut Window, cx: &mut Context) { + let Some((named, input, _)) = self.renaming.take() else { return }; + let title = input.read(cx).text().trim().to_owned(); + if commit && !title.is_empty() { + match named { + Named::Bookmark(id) => drop(self.browser.update(cx, |b, cx| b.rename_bookmark(id, &title, cx))), + Named::Snapshot(id) => { + if let Some(saved) = self.snapshots.iter().find(|s| s.id == id).cloned() { + self.browser.update(cx, |b, _| b.rename_snapshot(&saved, &title)).ok(); + self.reload_snapshots(cx); + } + } + } + } + window.focus(&self.query.focus_handle(cx)); + cx.notify(); + } + + pub(super) fn new_folder(&mut self, window: &mut Window, cx: &mut Context) { + let parent = match self.page { + Page::Bookmarks(folder) => folder, + _ => None, + }; + let Some(id) = self.browser.update(cx, |b, cx| b.new_bookmark_folder(parent, cx)).ok().flatten() else { return }; + self.go(Page::Bookmarks(parent), window, cx); + self.select(Named::Bookmark(id), cx); + self.begin_rename(Named::Bookmark(id), window, cx); + } + + pub(super) fn delete(&mut self, named: Named, window: &mut Window, cx: &mut Context) { + let id = match named { + Named::Bookmark(id) => id, + Named::Snapshot(id) => { + let Some(saved) = self.snapshots.iter().find(|s| s.id == id).cloned() else { return }; + let message = format!("Delete the snapshot “{}”?", bounded_title(&saved.name)); + return self.confirm(&message, None, "Delete", window, cx, move |this, cx| { + this.browser.update(cx, |b, _| b.delete_snapshot(&saved)).ok(); + this.reload_snapshots(cx); + }); + } + }; + let Some(browser) = self.browser.upgrade() else { return }; + let b = browser.read(cx); + let Some(bm) = b.bookmarks.iter().find(|bm| bm.id == id) else { return }; + let message = if bookmarks::subtree(&b.bookmarks, id).len() == 1 { + format!("Delete the bookmark “{}”?", bounded_title(&bm.title)) + } else { + format!("Delete “{}” and everything in it?", bounded_title(&bm.title)) + }; + self.confirm(&message, None, "Delete", window, cx, move |this, cx| { + this.browser.update(cx, |b, cx| b.delete_bookmark(id, cx)).ok(); + }); + } + + pub(super) fn remove_history(&mut self, url: String, cx: &mut Context) { + self.browser.update(cx, |b, cx| b.remove_history_url(&url, cx)).ok(); + self.history.retain(|h| h.url != url); + *self.history_hits.borrow_mut() = None; + self.shown = self.rows(cx); + cx.notify(); + } + + /// Delete, F2 and Shift+F10 act on the selected row; the delete keys only while the search + /// field is empty, so they still edit its text. + pub(super) fn on_key(&mut self, event: &gpui::KeyDownEvent, window: &mut Window, cx: &mut Context) { + let key = &event.keystroke; + let Some((_, r)) = self.shown.get(self.selected).cloned() else { return }; + if self.renaming.is_some() || self.holding || event.is_held { + return; + } + match key.key.as_str() { + "f2" if !key.modifiers.modified() => match r.named { + Some(named) => self.begin_rename(named, window, cx), + None => return, + }, + "f10" if key.modifiers.shift => self.row_menu(r.item.clone(), r.named, window, cx), + _ => return, + } + cx.stop_propagation(); + } + + /// Deletes the selected row for Delete or ⌘⌫ while the search field is empty, before the + /// field, which holds the focus, takes the key. + pub(super) fn delete_selected(&mut self, window: &mut Window, cx: &mut Context) { + let Some((_, r)) = self.shown.get(self.selected).cloned() else { return cx.propagate() }; + if self.renaming.is_some() || self.holding || !self.query.read(cx).text().is_empty() { + return cx.propagate(); + } + match (r.named, visit(&r)) { + (Some(named), _) => self.delete(named, window, cx), + (None, Some(url)) => self.remove_history(url.to_owned(), cx), + _ => return cx.propagate(), + } + cx.stop_propagation(); + } + + pub(super) fn confirm( + &mut self, + message: &str, + detail: Option<&str>, + action: &str, + window: &mut Window, + cx: &mut Context, + then: impl FnOnce(&mut Self, &mut Context) + 'static, + ) { + let answer = self.ask(PromptLevel::Warning, message, detail, &[action, "Cancel"], window, cx); + cx.spawn_in(window, async move |this, cx| { + let yes = answer.await == Ok(0); + this.update_in(cx, |this, window, cx| { + this.answered(window, cx); + if yes { + then(this, cx); + } + window.focus(&this.query.focus_handle(cx)); + }) + .ok(); + }) + .detach(); + } + + /// A dialog draws inside the popover, so the popover takes its full height while one is up. + pub(super) fn ask( + &mut self, + level: PromptLevel, + message: &str, + detail: Option<&str>, + answers: &[&str], + window: &mut Window, + cx: &mut Context, + ) -> oneshot::Receiver { + self.holding = true; + if let Some(fit) = &self.fit { + self.place(SEARCH_HEIGHT + 2. + fit.max_list, window, cx); + } + crate::dialog::ask(level, message, detail, answers, window, cx) + } + + pub(super) fn answered(&mut self, window: &mut Window, cx: &mut Context) { + self.holding = false; + self.refit(window, cx); + } + + pub(super) fn alert(&mut self, message: &str, detail: Option<&str>, window: &mut Window, cx: &mut Context) { + let answer = self.ask(PromptLevel::Info, message, detail, &["OK"], window, cx); + cx.spawn_in(window, async move |this, cx| { + answer.await.ok(); + this.update_in(cx, |this, window, cx| { + this.answered(window, cx); + window.focus(&this.query.focus_handle(cx)); + }) + .ok(); + }) + .detach(); + } + + /// Asks which data to bring from a source into the current space's profile, then reads it in + /// the background (where macOS may show its keychain prompt) and writes it. + pub(super) fn start_import(&mut self, ix: usize, window: &mut Window, cx: &mut Context) { + let (Some(source), Some(browser)) = (self.sources.get(ix).cloned(), self.browser.upgrade()) else { return }; + let b = browser.read(cx); + let Some(space) = b.model.current_space() else { return }; + let (private, profile_id, core) = (space.private, space.space.profile_id, b.core.clone()); + if core.importing.get() { + return self.alert("An import is already running.", None, window, cx); + } + if core.import_target(private, profile_id).is_err() { + let detail = "Private and Lockdown profiles keep website data in memory only, so imported sign-ins would not last."; + return self.alert("Switch to a space of a normal profile to import into it.", Some(detail), window, cx); + } + let name = source.browser.name(); + let profile = core.disk.profile(profile_id).map(|p| p.name).unwrap_or_default(); + let data::Confirm { message, detail, cookies } = data::confirm(&source, &profile, ui::controls::THIS_DEVICE); + let sealed = !cookies; + let buttons: &[&str] = if sealed { &["Import", "Cancel"] } else { &["Import All", "History and Bookmarks Only", "Cancel"] }; + let answer = self.ask(PromptLevel::Info, &message, Some(&detail), buttons, window, cx); + let (weak_browser, main) = (self.browser.clone(), self.main); + cx.spawn_in(window, async move |this, cx| { + let cookies = match answer.await { + Ok(0) => !sealed, + Ok(1) if !sealed => false, + _ => return drop(this.update_in(cx, |this, window, cx| this.answered(window, cx))), + }; + if core.importing.replace(true) { + this.update_in(cx, |this, window, cx| { + this.answered(window, cx); + this.alert("An import is already running.", None, window, cx); + }) + .ok(); + return; + } + let kinds = Kinds { cookies, history: true, bookmarks: true }; + let browser_kind = source.browser; + let read = cx.background_executor().spawn(async move { data::read(&source, kinds) }).await; + let (tx, rx) = oneshot::channel(); + let summary = match core.import(profile_id, browser_kind, read, move |r| drop(tx.send(r))) { + // The engine answers each cookie write; a store closed meanwhile may never answer. + Ok(()) => match futures::future::select(rx, cx.background_executor().timer(IMPORT_TIMEOUT)).await { + futures::future::Either::Left((report, _)) => data::summary(name, report.ok().as_ref()), + futures::future::Either::Right(_) => data::summary(name, None), + }, + Err(_) => "Nothing was imported: this profile can no longer take imported data.".into(), + }; + core.importing.set(false); + let same_profile = weak_browser + .update(cx, |b, cx| { + b.reload_bookmarks(cx); + b.model.current_space().is_some_and(|s| !s.private && s.space.profile_id == profile_id) + }) + .unwrap_or(false); + this.update_in(cx, |this, window, cx| { + this.answered(window, cx); + if same_profile { + this.history = core.disk.history(profile_id, HISTORY_LOAD).unwrap_or_default(); + this.history_hits.take(); + } + if !window.is_window_active() { + this.close(false, window, cx); + } + }) + .ok(); + main.update(cx, |_, window, cx| drop(window.prompt(PromptLevel::Info, &format!("Import from {name}"), Some(&summary), &["OK"], cx))).ok(); + }) + .detach(); + } + + pub(super) fn run(&mut self, cmd: Cmd, window: &mut Window, cx: &mut Context) { + match cmd { + Cmd::Open(item) => self.open(item, window, cx), + Cmd::OpenInNewTab(url) => { + if let Ok(url) = url::Url::parse(&url) { + self.main + .update(cx, |b, window, cx| { + let before = b.model.active; + b.new_tab(&url, window, cx); + if b.model.active != before && b.is_bookmarked(url.as_str()) { + b.mark_typed(&url); + } + }) + .ok(); + } + self.close(true, window, cx); + } + Cmd::Rename(named) => self.begin_rename(named, window, cx), + Cmd::Move(id, parent) => { + self.browser.update(cx, |b, cx| b.move_bookmark(id, parent, cx)).ok(); + } + Cmd::Delete(named) => self.delete(named, window, cx), + Cmd::Restore(saved, new_space) => self.restore(saved, new_space, window, cx), + Cmd::NewFolder => self.new_folder(window, cx), + Cmd::ToggleBookmark(key) => { + self.browser + .update(cx, |b, cx| match b.tab_url(key).is_some_and(|url| b.is_bookmarked(&url)) { + true => b.unbookmark_tab(Some(key), cx), + false => drop(b.bookmark_tab(Some(key), cx)), + }) + .ok(); + } + Cmd::CopyLink(url) => cx.write_to_clipboard(ClipboardItem::new_string(url)), + Cmd::RemoveDownload(id) => self.remove_download(Some(id), cx), + Cmd::RemoveHistory(url) => self.remove_history(url, cx), + } + } + + pub(super) fn row_menu(&mut self, item: Item, named: Option, window: &mut Window, cx: &mut Context) { + cx.stop_propagation(); + let Some(browser) = self.browser.upgrade() else { return }; + let b = browser.read(cx); + let Some(host) = b.host.clone() else { return }; + let url = match &item { + Item::Url(url) => Some(url.clone()), + Item::Tab(key) => b.tab_url(*key), + _ => None, + }; + let item_key = item.clone(); + let history = match &item { + Item::Url(url) if named.is_none() => Some(url.clone()), + _ => None, + }; + let mut items = match &item { + Item::Download(d) => { + let mut items = vec![MenuItem::action(ui::controls::REVEAL, Cmd::Open(item.clone()))]; + items.extend((!d.url.is_empty()).then(|| MenuItem::action("Copy Download Link", Cmd::CopyLink(d.url.clone())))); + items.extend([MenuItem::Separator, MenuItem::action("Remove from List", Cmd::RemoveDownload(d.id))]); + items + } + Item::Snapshot(saved) => vec![ + MenuItem::action("Restore in New Space", Cmd::Restore(saved.clone(), true)), + MenuItem::action("Restore in This Space", Cmd::Restore(saved.clone(), false)), + MenuItem::Separator, + MenuItem::action("Rename", Cmd::Rename(Named::Snapshot(saved.id))), + MenuItem::action("Delete…", Cmd::Delete(Named::Snapshot(saved.id))), + ], + _ => vec![MenuItem::action("Open", Cmd::Open(item))], + }; + let bookmarked = url.as_deref().is_some_and(|url| b.is_bookmarked(url)); + if let Some(url) = url { + items.extend([MenuItem::action("Open in New Tab", Cmd::OpenInNewTab(url.clone())), MenuItem::action("Copy Link", Cmd::CopyLink(url))]); + } + if let Item::Tab(key) = item_key { + items.push(MenuItem::action(if bookmarked { "Remove Bookmark" } else { "Bookmark Tab" }, Cmd::ToggleBookmark(key))); + } + if let Some(url) = history { + items.extend([MenuItem::Separator, MenuItem::action("Remove from History", Cmd::RemoveHistory(url))]); + } + if let Some(Named::Bookmark(id)) = named { + let parent = b.bookmarks.iter().find(|bm| bm.id == id).and_then(|bm| bm.parent_id); + let mut folders = vec![MenuItem::action("Bookmarks", Cmd::Move(id, None)).checked(parent.is_none()).enabled(parent.is_some())]; + folders.extend( + bookmarks::move_targets(&b.bookmarks, id) + .into_iter() + .map(|f| MenuItem::action(bounded_title(&f.title), Cmd::Move(id, Some(f.id))).checked(parent == Some(f.id)).enabled(parent != Some(f.id))), + ); + items.extend([ + MenuItem::Separator, + MenuItem::action("Rename", Cmd::Rename(Named::Bookmark(id))), + MenuItem::Submenu("Move to Folder".into(), folders), + MenuItem::action("New Folder", Cmd::NewFolder), + MenuItem::Separator, + MenuItem::action("Delete", Cmd::Delete(Named::Bookmark(id))), + ]); + } + self.holding = true; + cx.spawn_in(window, async move |this, cx| { + let (tx, rx) = oneshot::channel(); + menu::show(&host, crate::menu_glyphs::with_glyphs(items), None, move |cmd| { + tx.send(cmd).ok(); + }); + let cmd = rx.await.ok(); + this.update_in(cx, |this, window, cx| { + this.holding = false; + match cmd { + Some(cmd) => this.run(cmd, window, cx), + None if !window.is_window_active() => this.close(false, window, cx), + None => {} + } + }) + .ok(); + }) + .detach(); + } +} diff --git a/crates/app/src/library/browser_api.rs b/crates/app/src/library/browser_api.rs new file mode 100644 index 00000000..78cb1e1b --- /dev/null +++ b/crates/app/src/library/browser_api.rs @@ -0,0 +1,258 @@ +use super::*; + +impl Browser { + pub(crate) fn reload_bookmarks(&mut self, cx: &mut Context) { + self.bookmarks_of = self.model.profile(); + if let Some(space) = self.model.current_space() { + self.set_bookmarks(self.store(space.private).bookmarks(space.space.profile_id).unwrap_or_default()); + } + cx.notify(); + } + + pub fn is_bookmarked(&self, url: &str) -> bool { + bookmarks::find(&self.bookmarks, url).is_some() + } + + fn bookmark_target(&self, key: Option) -> Option<(String, String)> { + let tab = key.or(self.model.active).and_then(|k| self.model.tab(k))?; + let url = self.tab_url(self.model.key(tab)).unwrap_or_else(|| tab.url.clone()); + (!url.is_empty()).then(|| (browser_core::text::stored_title_or_host(&tab.title, &url), url)) + } + + /// The top-level folder Save for Later files pages into, if it exists. + pub(crate) fn reading_list(&self) -> Option { + bookmarks::reading_list(&self.bookmarks) + } + + /// Files the active page into the Reading List bookmark folder, made on first use, so it is + /// kept, exported and deleted like any bookmark. + pub fn save_for_later(&mut self, cx: &mut Context) { + let (Some((title, url)), Some(space)) = (self.bookmark_target(None), self.model.current_space()) else { return }; + let (private, profile_id) = (space.private, space.space.profile_id); + self.reload_bookmarks(cx); + let saved = bookmarks::save_for_later(self.store(private), profile_id, &self.bookmarks, &url, &title, now()); + self.reload_bookmarks(cx); + let (tone, text) = browser_core::toast::reading_list(saved); + self.show_toast_as(tone, text, None, cx); + } + + /// Bookmarks the tab, or returns its bookmark when it already has one. + pub fn bookmark_tab(&mut self, key: Option, cx: &mut Context) -> Option { + let (title, url) = self.bookmark_target(key)?; + let space = self.model.current_space()?; + let id = bookmarks::bookmark(self.store(space.private), space.space.profile_id, &self.bookmarks, &url, &title, now())?; + self.reload_bookmarks(cx); + Some(id) + } + + pub fn unbookmark_tab(&mut self, key: Option, cx: &mut Context) { + let Some((_, url)) = self.bookmark_target(key) else { return }; + bookmarks::unbookmark(self.store(self.model.private()), &self.bookmarks, &url); + self.reload_bookmarks(cx); + } + + /// Saves every tab into a new dated folder and opens the library on its name field. + pub fn bookmark_all_tabs(&mut self, cx: &mut Context) { + let Some(space) = self.model.current_space().filter(|_| !self.model.tabs.is_empty()) else { return }; + let pages: Vec<(&str, String)> = self + .model + .tabs + .iter() + .filter(|t| !t.url.is_empty()) + .map(|t| (t.title.as_str(), self.tab_url(self.model.key(t)).unwrap_or_else(|| t.url.clone()))) + .collect(); + let Some(folder) = bookmarks::bookmark_all(self.store(space.private), space.space.profile_id, pages.iter().map(|(t, u)| (*t, u.as_str())), now()) + else { + return; + }; + self.reload_bookmarks(cx); + if let Some(main) = self.peek.main { + cx.defer(move |cx| { + main.update(cx, |b, window, cx| b.show_library(Some(folder), window, cx)).ok(); + }); + } + } + + pub fn new_bookmark_folder(&mut self, parent: Option, cx: &mut Context) -> Option { + let space = self.model.current_space()?; + let id = bookmarks::new_folder(self.store(space.private), space.space.profile_id, parent, now())?; + self.reload_bookmarks(cx); + Some(id) + } + + pub fn rename_bookmark(&mut self, id: Id, title: &str, cx: &mut Context) { + self.store(self.model.private()).rename_bookmark(id, title).ok(); + self.reload_bookmarks(cx); + } + + pub fn move_bookmark(&mut self, id: Id, parent: Option, cx: &mut Context) { + self.store(self.model.private()).move_bookmark(id, parent).ok(); + self.reload_bookmarks(cx); + } + + pub fn delete_bookmark(&mut self, id: Id, cx: &mut Context) { + self.store(self.model.private()).delete_bookmark(id).ok(); + self.reload_bookmarks(cx); + } + + /// Switches to a tab already showing `url`, otherwise opens it in a new one. + pub fn open_url(&mut self, url: &str, window: &mut Window, cx: &mut Context) { + if self.command_mode.is_some() { + self.close_command(window, cx); + } + if let Some(key) = self.model.tabs.iter().find(|t| t.url == url).map(|t| self.model.key(t)) { + return self.activate(key, window, cx); + } + if let Ok(url) = url::Url::parse(url) { + let before = self.model.active; + self.new_tab(&url, window, cx); + if self.model.active != before && self.is_bookmarked(url.as_str()) { + self.mark_typed(&url); + } + } + } + + /// Saves the current space's tabs as a snapshot named after it and opens the library on its name. + pub fn save_snapshot(&mut self, window: &mut Window, cx: &mut Context) { + let Some(space) = self.model.current_space() else { return }; + let name = format!("{} {}", space.space.name, date(now())); + if let Some(saved) = snapshot::save(self.store(space.private), space, &name, now()) { + self.open_library(Page::Snapshots, Some(Named::Snapshot(saved.id)), window, cx); + } + } + + /// The current profile's snapshots, newest first; a private space has none. + pub(crate) fn snapshots(&self) -> Vec { + self.model.current_space().filter(|s| !s.private).and_then(|s| self.store(false).snapshots(s.space.profile_id).ok()).unwrap_or_default() + } + + pub fn rename_snapshot(&mut self, saved: &Snapshot, name: &str) { + self.store(false).rename_snapshot(saved.profile_id, saved.id, name).ok(); + } + + pub fn delete_snapshot(&mut self, saved: &Snapshot) { + self.store(false).delete_snapshot(saved.profile_id, saved.id).ok(); + } + + /// Opens the snapshot's tabs in a new space of its profile, or at the end of the current space. + pub fn restore_snapshot(&mut self, saved: &Snapshot, new_space: bool, window: &mut Window, cx: &mut Context) -> Result<(), &'static str> { + let Some(current) = self.model.current_space().filter(|s| !s.private && s.space.profile_id == saved.profile_id).map(|s| s.space.id) else { + return Err("Switch to a space of this snapshot's profile to restore it."); + }; + let store = self.store(false); + let snapshot = SpaceSnapshot::load(store, saved.profile_id, saved.id).map_err(snapshot_error)?; + let target = if new_space { + let names = std::iter::once(saved.name.clone()).chain((2..50).map(|n| format!("{} {n}", saved.name))); + let name = names.filter_map(|n| crate::spaces::space_name(&n, &self.model.spaces, false, Some(saved.profile_id), None)).next(); + let space = store.create_space(saved.profile_id, name.as_deref().unwrap_or("Snapshot"), ""); + space.map_err(|_| "Tarn could not create a space for this snapshot.")?.id + } else { + current + }; + let last = snapshot.restore(store, target); + if new_space { + self.reload_spaces(); + if let Some(ix) = self.model.spaces.iter().position(|s| !s.private && s.space.id == target) { + self.switch_space(ix, window, cx); + } + } else { + self.reload_space(); + } + if let Some(id) = last { + self.activate(TabKey { private: false, id }, window, cx); + } + Self::sync_other_windows(cx); + cx.notify(); + Ok(()) + } + + pub(crate) fn downloads(&self) -> Vec { + self.model.current_space().and_then(|s| self.store(s.private).downloads(s.space.profile_id).ok()).unwrap_or_default() + } + + /// Removes one entry, or with `None` the whole list; the files stay. + pub fn remove_download(&mut self, id: Option) { + let Some(space) = self.model.current_space() else { return }; + let (store, profile_id) = (self.store(space.private), space.space.profile_id); + match id { + Some(id) => store.delete_download(profile_id, id), + None => store.clear_downloads(profile_id), + } + .ok(); + } + + pub(crate) fn close_library(&mut self, cx: &mut Context) { + if let Some(handle) = self.library.take() { + cx.defer(move |cx| drop(handle.update(cx, |library, window, cx| library.close(true, window, cx)))); + cx.notify(); + } + } + + pub fn toggle_library(&mut self, window: &mut Window, cx: &mut Context) { + match self.library { + Some(_) => self.close_library(cx), + // The click that took focus from the library already closed it; it must not reopen it. + None if self.library_closed.is_some_and(|t| t.elapsed() < ui::motion::REOPEN_GUARD) => {} + None => self.show_library(None, window, cx), + } + } + + /// Opens the library above the space row; with `edit`, on that bookmark with its name field open. + pub fn show_library(&mut self, edit: Option, window: &mut Window, cx: &mut Context) { + let page = match edit.and_then(|id| self.bookmarks.iter().find(|b| b.id == id)) { + Some(bm) => Page::Bookmarks(bm.parent_id), + None => Page::Home, + }; + self.open_library(page, edit.map(Named::Bookmark), window, cx); + } + + /// Opens the library on `page`; with `edit`, that row's name field is open. + pub(crate) fn open_library(&mut self, page: Page, edit: Option, window: &mut Window, cx: &mut Context) { + if let Some(handle) = self.library { + cx.defer(move |cx| drop(handle.update(cx, |library, window, cx| library.go(page, window, cx)))); + return; + } + let Some(main) = window.window_handle().downcast::().or(self.peek.main) else { return }; + let inset = SIDEBAR_MARGIN; + self.peek.owns[0] = self.peek.is_window(window); + if !self.peek.owns[0] { + self.close_peek(cx); + } + let anchor = self.main_bounds(window); + let room = f32::from(anchor.size.height) - 2. * inset - SPACE_ROW - TOOLBAR_HEIGHT - SEARCH_HEIGHT - 2.; + let max_list = room.max(ROW * 3.); + let downloads = self.downloads(); + let snapshots = self.snapshots(); + let sources = if page == Page::Import { detect_sources() } else { Vec::new() }; + let history = self.model.current_space().and_then(|s| self.store(s.private).history(s.space.profile_id, HISTORY_LOAD).ok()).unwrap_or_default(); + let rows: Vec<&HistoryEntry> = history.iter().collect(); + let listed = entries(self, page, "", &rows, &downloads, &snapshots, &sources); + let height = px(card_height(&listed, row_boundary(&listed, max_list))); + let (x, bottom, width) = (inset + 4., f32::from(anchor.size.height) - inset - SPACE_ROW, CARD_WIDTH.min(self.sidebar_width - 8.)); + let bounds = Bounds::new(point(anchor.origin.x + px(x), anchor.origin.y + px(bottom) - height), size(px(width), height)); + let display = window.display(cx).map(|d| d.id()); + let browser = cx.entity().downgrade(); + // The new window renders from the browser at once, so it must open after this update ends. + cx.defer(move |cx| { + let handle = cx.open_window(popup_options(bounds, display, true), |window, cx| { + if let Some(host) = engine::Host::from_window(window) { + host.hide_on_deactivate(); + host.round_corners(0., 0., 0., 0., f64::from(ui::theme::Theme::radius_panel())); + } + cx.new(|cx| LibraryWindow { + page, + fit: Some(Fit { x, bottom, width, max_list }), + sources: sources.clone(), + ..LibraryWindow::new(browser.clone(), main, history, downloads.clone(), edit, window, cx) + }) + }); + browser + .update(cx, |b, cx| { + b.library = handle.ok(); + cx.notify(); + }) + .ok(); + crate::peek::popovers_over_peek(&browser, cx); + }); + } +} diff --git a/crates/app/src/library/entries.rs b/crates/app/src/library/entries.rs new file mode 100644 index 00000000..c5a2fc6c --- /dev/null +++ b/crates/app/src/library/entries.rs @@ -0,0 +1,201 @@ +use super::*; + +pub(super) fn row(item: Item, title: String, bookmark: Option) -> Entry { + Entry::Row(Row { item, title, named: bookmark.map(Named::Bookmark), detail: None }) +} + +pub(super) fn bookmark_row(bm: &Bookmark) -> Entry { + let item = match &bm.url { + Some(url) => Item::Url(url.clone()), + None => Item::Folder(bm.id), + }; + row(item, title_or_host(&bm.title, bm.url.as_deref().unwrap_or_default()), Some(bm.id)) +} + +pub(super) fn entries( + b: &Browser, + page: Page, + query: &str, + history: &[&HistoryEntry], + downloads: &[Download], + snapshots: &[Snapshot], + sources: &[Source], +) -> Vec { + let matches = |title: &str, url: &str| library::matches(query, title, url); + let store = b.store(b.model.private()); + let bookmarks = &b.bookmarks; + let found = |limit| library::bookmarks(bookmarks, query).take(limit).map(bookmark_row); + let visits = history; + let history = |limit| visits.iter().take(limit).map(|h| row(Item::Url(h.url.clone()), title_or_host(&h.title, &h.url), None)); + let downloads = |limit| { + let now = now(); + library::downloads(downloads, query).take(limit).map(move |d| download_row(store, d, now)) + }; + let mut out = Vec::new(); + match page { + Page::Home => { + let tabs = library::open_tabs(&b.model.tabs, query); + if query.is_empty() || !tabs.is_empty() { + out.push(Entry::Header("Open Tabs", Some(tabs.len()))); + } + if query.is_empty() && tabs.is_empty() { + out.push(Entry::Empty("No open tabs".into())); + } + out.extend(tabs.into_iter().take(MAX_ROWS).map(|t| row(Item::Tab(b.model.key(t)), title_or_host(&t.title, &t.url), None))); + if !query.is_empty() { + let sections: [(&str, Vec); 3] = + [("Bookmarks", found(MAX_ROWS).collect()), ("History", history(MAX_ROWS).collect()), ("Downloads", downloads(MAX_ROWS).collect())]; + for (name, rows) in sections.into_iter().filter(|(_, rows)| !rows.is_empty()) { + out.push(Entry::Header(name, None)); + out.extend(rows); + } + if out.is_empty() { + out.push(Entry::Empty(empty_text(page, query))); + } + } + out.push(Entry::Header("Library", None)); + out.push(row(Item::Page(Page::History), "History".into(), None)); + out.push(row(Item::Page(Page::Bookmarks(None)), "Bookmarks".into(), None)); + if let Some(folder) = b.reading_list() { + out.push(row(Item::Page(Page::Bookmarks(Some(folder))), bookmarks::READING_LIST.into(), None)); + } + out.push(row(Item::Page(Page::Downloads), "Downloads".into(), None)); + if !b.model.private() { + out.push(row(Item::Page(Page::Snapshots), "Snapshots".into(), None)); + } + out.push(row(Item::Page(Page::Memory), "Memory".into(), None)); + if query.is_empty() && data::available() { + out.push(row(Item::Page(Page::Import), "Import Browser Data".into(), None)); + } + } + Page::History => { + out.push(Entry::Back("History".into())); + let now = now(); + let starts = library::day_starts(store, now); + let mut last = None; + for h in visits.iter().take(MAX_LIST) { + let day = library::history_day(h.visited_at, starts); + if last.replace(day) != Some(day) { + out.push(Entry::Header(day, None)); + } + out.push(visit_row(store, h, now)); + } + } + Page::Bookmarks(folder) => { + let name = folder.and_then(|id| bookmarks.iter().find(|bm| bm.id == id)).map_or("Bookmarks".into(), |bm| bounded_title(&bm.title)); + out.push(Entry::Back(name)); + if query.is_empty() { + out.extend(bookmarks.iter().filter(|bm| bm.parent_id == folder).map(bookmark_row)); + } else { + out.extend(found(MAX_LIST)); + } + } + Page::Downloads => { + out.push(Entry::Back("Downloads".into())); + out.extend(downloads(MAX_LIST)); + if out.len() > 1 && query.is_empty() { + out.push(Entry::Divider); + out.push(row(Item::ClearDownloads, "Clear List".into(), None)); + } + } + Page::Snapshots => { + out.push(Entry::Back("Snapshots".into())); + if snapshots.is_empty() { + out.push(Entry::Empty("Save a space with “Save Space as Snapshot”".into())); + } + let now = now(); + out.extend(snapshots.iter().filter(|s| matches(&s.name, "")).map(|s| { + let detail = Some(ago(store, s.created_at, now)); + Entry::Row(Row { item: Item::Snapshot(s.clone()), title: bounded_title(&s.name), named: Some(Named::Snapshot(s.id)), detail }) + })); + } + Page::Memory => memory_entries(b, query, &mut out), + Page::Import => { + out.push(Entry::Back("Import Browser Data".into())); + if sources.is_empty() { + out.push(Entry::Empty("No supported browser found".into())); + } + out.extend( + sources.iter().enumerate().filter(|(_, s)| matches(s.browser.name(), &s.label)).map(|(ix, s)| { + Entry::Row(Row { item: Item::Source(ix), title: s.browser.name().into(), named: None, detail: Some(bounded_title(&s.label)) }) + }), + ); + } + } + if out.len() == 1 { + out.push(Entry::Empty(empty_text(page, query))); + } + out +} + +fn memory_entries(b: &Browser, query: &str, out: &mut Vec) { + out.push(Entry::Back("Memory".into())); + let costs = b.tab_costs(); + let mut tabs: Vec<(TabKey, &Tab)> = b.model.tabs.iter().filter(|t| library::matches(query, &t.title, &t.url)).map(|t| (b.model.key(t), t)).collect(); + tabs.sort_by_key(|(key, t)| (Reverse(costs.get(key).map_or(0, |c| c.footprint)), Reverse(t.last_active))); + out.extend(tabs.into_iter().map(|(key, t)| { + let detail = crate::memory::detail(costs.get(&key).copied(), b.sleeping(key)); + Entry::Row(Row { item: Item::Tab(key), title: title_or_host(&t.title, &t.url), named: None, detail: Some(detail) }) + })); + if out.len() > 1 && query.is_empty() { + out.push(Entry::Divider); + out.push(row(Item::SleepInactive, "Sleep All Inactive Tabs".into(), None)); + } +} + +pub(super) fn tally(n: usize) -> Option { + (n > 0).then(|| thousands(n as u64)) +} + +/// Rows listed on a page; on a page cut at `MAX_LIST` the cap reads "200+", never as the total. +pub(super) fn listed_tally(n: usize, capped: bool) -> Option { + if capped && n >= MAX_LIST { Some(format!("{MAX_LIST}+")) } else { tally(n) } +} + +pub(super) fn empty_text(page: Page, query: &str) -> String { + if !query.is_empty() { + return format!("No results for “{}”", bounded_title(query)); + } + match page { + Page::History => "No history yet", + Page::Bookmarks(None) => "No bookmarks yet", + Page::Bookmarks(Some(_)) => "This folder is empty", + Page::Downloads => "No downloads yet", + _ => "Nothing here", + } + .into() +} + +pub(super) fn entry_height(entry: &Entry) -> f32 { + match entry { + Entry::Header(..) => HEADER_ROW, + Entry::Back(_) => BACK_ROW, + Entry::Empty(_) => EMPTY_ROW, + Entry::Divider => DIVIDER, + Entry::Row(r) if r.detail.is_some() => DETAIL_ROW, + Entry::Row(_) => ROW, + } +} + +/// The tallest list up to `max_list` that ends below a row, so a cut list never shows a heading or +/// divider without the row under it, or half a row; `max_list` when the whole list fits. +pub(super) fn row_boundary(entries: &[Entry], max_list: f32) -> f32 { + let mut end = LIST_PAD; + let mut fit = None; + for (ix, entry) in entries.iter().enumerate() { + end += entry_height(entry) + if ix > 0 { 1. } else { 0. }; + if end > max_list { + return fit.unwrap_or(max_list); + } + if !matches!(entry, Entry::Header(..) | Entry::Divider) { + fit = Some(end); + } + } + max_list +} + +/// The card's height for `entries`, with the list capped at `max_list`. +pub(super) fn card_height(entries: &[Entry], max_list: f32) -> f32 { + let list: f32 = entries.iter().map(entry_height).sum::() + entries.len().saturating_sub(1) as f32 + LIST_PAD; + SEARCH_HEIGHT + 2. + list.min(max_list) +} diff --git a/crates/app/src/settings.rs b/crates/app/src/settings.rs index a3882205..a4aea8e8 100644 --- a/crates/app/src/settings.rs +++ b/crates/app/src/settings.rs @@ -27,7 +27,11 @@ use crate::browser::Browser; mod ai; mod appearance; +mod extensions; mod notes; +mod privacy; +mod profile_card; +mod shortcuts; mod snippets; use crate::filters; use crate::prefs::{Choice, LIVE_TABS, Pref, Prefs}; @@ -524,131 +528,6 @@ impl SettingsWindow { } } - fn shortcuts(&mut self, cx: &mut Context) -> AnyElement { - let stored = crate::shortcuts::stored(&crate::shared::core(cx).disk); - let defaults = keymap::keymap(&crate::shortcuts::MAC, &Default::default()); - let changed: Vec = - keymap::keymap(&crate::shortcuts::MAC, &stored).into_iter().zip(&defaults).filter(|((k, _), (d, _))| k != d).map(|((_, a), _)| a).collect(); - let recording = self.recording.as_ref().map(|(a, _)| *a); - let mut n = 0usize; - let mut pane = div() - .child( - div() - .pt_3() - .flex() - .items_center() - .gap_3() - .child( - note(if cfg!(windows) { - "Click a shortcut and press the new keys, with Ctrl, or Alt with Shift or a digit; Esc cancels." - } else { - "Click a shortcut and press the new keys, with ⌘ or ⌃; Esc cancels." - }) - .flex_grow() - .flex_basis(px(0.)) - .pt_0(), - ) - .when(!changed.is_empty(), |d| { - d.child(button("shortcut-reset-all", "Reset All", false).on_click(cx.listener(|this, _, _, cx| this.reset_shortcuts(None, cx)))) - }), - ) - .children(self.shortcut_error.clone().map(|e| note(e).text_color(Theme::warning()))); - for (title, items) in crate::shortcuts::sections() { - let mut list = group(); - for (ix, (name, keys)) in items.iter().enumerate() { - let mut line = row(ix == 0).child(label(*name)); - line = match keys { - Fixed(keys) => line.child(value(ui::controls::keys(keys))), - Bound(action) => { - let action = *action; - n += 1; - let on = recording == Some(action); - let custom = changed.contains(&action); - let shown = match crate::shortcuts::gpui_action(action) { - _ if on => "Press keys…".to_owned(), - Some(gpui) => crate::shortcuts::shown(gpui, cx), - None => String::new(), - }; - line.child( - div() - .flex() - .items_center() - .gap_2() - .when(custom, |d| { - d.child( - button(("shortcut-reset", n), "Reset", false) - .on_click(cx.listener(move |this, _, _, cx| this.reset_shortcuts(Some(action), cx))), - ) - }) - .child(button(("shortcut", n), shown, on).on_click(cx.listener(move |this, _, window, cx| this.record(action, window, cx)))), - ) - } - }; - list = list.child(line); - } - pane = pane.child(section(title)).child(list); - } - pane.into_any_element() - } - - /// Catches the next keystroke in the Settings window as `action`'s new keys; a key in another - /// window stops recording and goes on as usual. - fn record(&mut self, action: Shortcut, window: &mut Window, cx: &mut Context) { - let me = cx.entity().downgrade(); - let settings = window.window_handle().window_id(); - let interceptor = cx.intercept_keystrokes(move |event, window, cx| { - if window.window_handle().window_id() != settings { - me.update(cx, |this, cx| { - if let Some((_, interceptor)) = this.recording.take() { - cx.defer(move |_| drop(interceptor)); - cx.notify(); - } - }) - .ok(); - return; - } - cx.stop_propagation(); - let keystroke = event.keystroke.clone(); - if me.update(cx, |this, cx| this.recorded(&keystroke, cx)).unwrap_or(false) { - cx.defer(crate::shortcuts::rebind); - } - }); - self.recording = Some((action, interceptor)); - self.shortcut_error = None; - cx.notify(); - } - - /// Saves `keystroke` for the recording action unless it is Esc, invalid or taken; true when saved. - fn recorded(&mut self, keystroke: &gpui::Keystroke, cx: &mut Context) -> bool { - let Some((action, interceptor)) = self.recording.take() else { return false }; - cx.defer(move |_| drop(interceptor)); - cx.notify(); - if keystroke.key == "escape" && keystroke.modifiers == gpui::Modifiers::none() { - return false; - } - if cfg!(windows) && keystroke.modifiers.platform { - self.shortcut_error = Some("The Windows key belongs to Windows; use Ctrl, or Alt with Shift or a digit.".to_owned()); - return false; - } - let disk = &crate::shared::core(cx).disk; - match keymap::save(&crate::shortcuts::MAC, disk, action, &crate::shortcuts::canonical(&keystroke.unparse())) { - Ok(()) => true, - Err(e) => { - self.shortcut_error = Some(e); - false - } - } - } - - /// Back to the default keys for `action`, unless another action took them meanwhile, or for - /// every action. - fn reset_shortcuts(&mut self, action: Option, cx: &mut Context) { - self.recording = None; - self.shortcut_error = keymap::reset(&crate::shortcuts::MAC, &crate::shared::core(cx).disk, action).err(); - cx.defer(crate::shortcuts::rebind); - cx.notify(); - } - /// Renders the card off the main thread and writes it to Downloads; nothing is uploaded. fn save_card(&mut self, card: Card, cx: &mut Context) { self.card_notice = Some("Saving…".into()); @@ -895,321 +774,7 @@ const SIDEBAR_WIDTH: f32 = 196.; const HEADER_HEIGHT: f32 = 52.; const CONTENT_WIDTH: f32 = 760.; -fn week_chart(card: &Card) -> Div { - const BARS: f32 = 92.; - let days = browser_core::shield_card::day_totals(&card.week); - if days.iter().all(|(_, n)| *n <= 0) { - return group().child(row(true).child(text_block("Last 7 days", "Nothing stopped yet. Each day Shield stops something shows here."))); - } - let busiest = days.iter().map(|(_, n)| *n).max().unwrap_or(0); - let bars = days.iter().map(|(day, n)| { - let fill = if *n == 0 { 2. } else { (BARS * *n as f32 / busiest.max(1) as f32).max(4.) }; - let top = *n == busiest && busiest > 0; - div() - .flex_1() - .flex() - .flex_col() - .items_center() - .justify_end() - .gap_1() - .text_size(px(TEXT_TINY)) - .text_color(Theme::muted()) - .child(if *n > 0 { thousands(*n as u64) } else { String::new() }) - .child(div().w(px(22.)).h(px(fill)).rounded(px(Theme::radius_small())).bg(if top { Theme::space_label() } else { Theme::accent() })) - .child(*day) - }); - let total: i64 = days.iter().map(|(_, n)| *n).sum(); - group() - .p_4() - .gap_3() - .child( - div() - .flex() - .justify_between() - .child(div().font_weight(FontWeight::SEMIBOLD).child("Last 7 days")) - .child(value(format!("{} protected", thousands(total.max(0) as u64))).text_size(px(TEXT_SMALL))), - ) - .child(div().h(px(BARS + 34.)).flex().items_end().gap_1().children(bars)) -} - -fn protected_sites(card: &Card) -> Div { - let most = card.sites.iter().map(|(_, n)| *n).max().unwrap_or(0).max(1); - let rows = card.sites.iter().map(|(host, n)| { - let host = crate::toolbar::host_tail(&bounded_title(host), 40); - let share = (*n).max(0) as f32 / most as f32; - div() - .h(px(28.)) - .flex() - .items_center() - .gap_2() - .child(ui::controls::favicon(&host, 16.)) - .child(div().flex_none().w(px(110.)).one_line(host)) - .child( - div() - .flex_1() - .h(px(4.)) - .rounded_full() - .bg(Theme::separator()) - .child(div().h_full().w(gpui::relative(share)).rounded_full().bg(Theme::accent())), - ) - .child(value(thousands((*n).max(0) as u64)).w(px(44.)).flex_none().text_right()) - }); - group().p_4().gap_1().child(div().pb_1().font_weight(FontWeight::SEMIBOLD).child("Most protected sites")).children(rows) -} - impl SettingsWindow { - /// The card's next frame: draws its faces off the main thread when the card changes, moves - /// the tilt, glow, flip and press a step towards their goals, and asks for another frame - /// until they arrive. - fn card_frame(&mut self, card: &Card, reduce: bool, window: &mut Window, cx: &mut Context) -> Option> { - const RATES: [f32; 5] = [12., 12., 8., 6.5, 25.]; - let m = &mut self.motion; - let key = (card.clone(), !Theme::is_light()); - if m.faces.as_ref().is_none_or(|(k, _)| *k != key) && m.drawing.as_ref() != Some(&key) { - m.drawing = Some(key.clone()); - let card = key; - cx.spawn(async move |this, cx| { - let made = cx.background_spawn({ - let (card, dark) = card.clone(); - async move { shield_card::faces(&card, dark) } - }); - let Some(faces) = made.await else { return }; - this.update(cx, |this, cx| { - if this.motion.drawing.as_ref() == Some(&card) { - this.motion.drawing = None; - this.motion.faces = Some((card, Arc::new(faces))); - cx.notify(); - } - }) - .ok(); - }) - .detach(); - } - let faces = m.faces.as_ref()?.1.clone(); - let flip = if m.flipped { 1. } else { 0. }; - let goal = if reduce || !m.hover { [0., 0., 0., flip, 0.] } else { [m.aim.0, m.aim.1, 1., flip, if m.pressed { 1. } else { 0. }] }; - let passed = m.stepped.replace(Instant::now()).map_or(0.05, |t| t.elapsed().as_secs_f32()).min(0.05); - for ((at, goal), rate) in m.at.iter_mut().zip(goal).zip(RATES) { - *at = if reduce || (goal - *at).abs() < 0.002 { goal } else { *at + (goal - *at) * (1. - (-passed * rate).exp()) }; - } - if m.at != goal { - window.request_animation_frame(); - } - if m.drawn.as_ref().is_none_or(|(at, from, _)| *at != m.at || !Arc::ptr_eq(from, &faces)) { - let [across, down, glow, flip, press] = m.at; - let image = - Arc::new(RenderImage::new([image::Frame::new(shield_card::frame(&faces, &ui::tilt::Pose { tilt: (across, down), glow, flip, press }))])); - if let Some((_, _, old)) = m.drawn.replace((m.at, faces, image)) { - cx.drop_image(old, Some(window)); - } - } - m.drawn.as_ref().map(|(_, _, image)| image.clone()) - } - - /// The first pane: the profile's Shield card, its week, and what Tarn does for it and talks to. - fn profile_tab(&mut self, s: &Snapshot, window: &mut Window, cx: &mut Context) -> AnyElement { - let Some(card) = s.card.clone() else { return note("No profile is open.").into_any_element() }; - let target = s.profile.as_ref().map(|p| (s.private, p.id)); - let frame = self.card_frame(&card, s.reduce, window, cx); - let [_, _, glow, flip, _] = self.motion.at; - let facing = (flip * std::f32::consts::PI).cos().abs(); - let (width, height, margin) = (shield_card::W as f32, shield_card::H as f32, shield_card::MARGIN as f32); - let bounds = self.motion.bounds.clone(); - let face = div() - .id("shield-card") - .relative() - .w(px(width)) - .h(px(height)) - .cursor_pointer() - .child( - div() - .absolute() - .top_0() - .h_full() - .left(px(width / 2. * (1. - facing))) - .w(px(width * facing)) - .rounded(px(18.)) - .shadow(Theme::elevation(5. + 5. * glow, 9. + 7. * glow)), - ) - .children(frame.map(|f| img(f).absolute().left(px(-margin)).top(px(-margin)).w(px(width + 2. * margin)).h(px(height + 2. * margin)))) - .child(canvas(move |at, _, _| bounds.set(at), |_, _, _, _| {}).absolute().size_full()) - .on_mouse_move(cx.listener(|this, moved: &MouseMoveEvent, _, cx| { - let card = this.motion.bounds.get(); - let from_centre = moved.position - card.center(); - this.motion.aim = ((from_centre.x / (card.size.width / 2.)).clamp(-1., 1.), (from_centre.y / (card.size.height / 2.)).clamp(-1., 1.)); - cx.notify(); - })) - .on_hover(cx.listener(|this, over: &bool, _, cx| { - this.motion.hover = *over; - this.motion.pressed &= *over; - cx.notify(); - })) - .on_mouse_down( - MouseButton::Left, - cx.listener(|this, _, _, cx| { - this.motion.pressed = true; - cx.notify(); - }), - ) - .on_click(cx.listener(|this, _, _, cx| { - this.motion.pressed = false; - this.motion.flipped ^= true; - cx.notify(); - })); - let hero = self.hero(&card, face, target, cx); - let mut page = div() - .child(hero) - .children(self.card_notice.clone().map(|n| note(n).pt_2())) - .child(div().pt_5().flex().gap_4().child(week_chart(&card).flex_1()).when(!card.sites.is_empty(), |d| d.child(protected_sites(&card).flex_1()))); - if s.default_browser == Some(false) { - page = page.child(section("Default browser")).child( - group().child( - row(true) - .child(text_block("Tarn isn't your default browser", "Links from other apps open in another browser.")) - .child(button("make-default", "Make Default", true).on_click(cx.listener(|this, _, _, cx| this.make_default(cx)))), - ), - ); - } - let levels = self.shield_levels(s, cx); - let to_privacy = - |id: &'static str, text: &'static str| button(id, text, false).on_click(cx.listener(|this, _, _, cx| this.set_pane(SettingsPane::Privacy, cx))); - let overrides = match s.overrides.len() { - 0 => "None".to_owned(), - 1 => "1 site".to_owned(), - n => format!("{n} sites"), - }; - page = page - .child(note({ - let kept = if s.private { "Counts stay in memory and are gone once the private space closes.".to_owned() } else { format!("Counted on {} only and never sent anywhere.", ui::controls::THIS_DEVICE) }; - if cfg!(windows) { - format!("{kept} Only what Tarn stops itself counts.") - } else { - format!("{kept} Only what Tarn stops itself counts: ad and tracker blocks in WebKit tabs are not counted, because WebKit does not report what its blocking rules stop.") - } - })) - .child(section("Shield level")) - .child(levels) - .child(note("Applies to this profile. Open pages reload with the new level.")) - .child(section("Shield")) - .child( - group() - .child(row(true).child(label("Site overrides")).child(value(overrides)).child(to_privacy("shield-change", "Change…"))) - .child(row(false).child(text_block("Filter lists", s.filters.summary()))), - ); - let filter_lists = match (filters::configured(), s.filters.updates) { - (false, _) => "Not set up", - (true, true) => "GitHub, once a day", - (true, false) => "Off", - }; - let updates = match (s.updater, s.update_checks) { - (false, _) => "Not set up", - (true, true) => "GitHub, once a day", - (true, false) => "Only when you ask", - }; - page.child(section("Connections Tarn makes")) - .child( - group() - .child(row(true).child(label("Filter-list updates")).child(value(filter_lists))) - .child(row(false).child(label("Extensions and themes")).child(value(if s.extension_downloads { - "GitHub, when you install" - } else { - "Off" - }))) - .child(row(false).child(label("Site icons")).child(value("The site you are on or its CDN"))) - .child(row(false).child(label("Update checks")).child(value(updates))) - .child( - row(false) - .child(text_block("Nothing else", "No accounts, no telemetry, no AI requests.")) - .child(to_privacy("connections-details", "Details…")), - ), - ) - .into_any_element() - } - - fn hero(&self, card: &Card, face: impl IntoElement, target: Option<(bool, Id)>, cx: &mut Context) -> Div { - let private = target.is_some_and(|(private, _)| private); - let since = match (card.days, &card.since) { - (Some(days), Some(since)) => browser_core::shield_card::protected_text(days, since), - _ if private => "Counts stay in memory until the private space closes.".to_owned(), - _ => "Counting starts with the first thing Shield stops.".to_owned(), - }; - let saved = card.clone(); - let shared = card.clone(); - let system = cfg!(target_os = "macos"); - let share = if system { "Share Card" } else { "Save as Image" }; - let action = |id: &'static str, glyph, text: &'static str| tab_stop(icon_text_button(id, glyph, text)).justify_center(); - let actions = div() - .grid() - .grid_cols(2) - .gap_2() - .child(action("flip-card", Icon::Reload, "Flip").on_click(cx.listener(|this, _, _, cx| { - this.motion.flipped ^= true; - cx.notify(); - }))) - .child(action("new-design", Icon::Palette, "Change Design").on_click(cx.listener(move |this, _, _, cx| { - let Some((private, id)) = target else { return }; - this.with_browser(cx, |b, _, cx| { - b.store(private).new_shield_design(id).ok(); - shield_card::touch(); - cx.notify(); - }); - }))) - .when(!private, |d| { - d.child(action("share-card", if system { Icon::Share } else { Icon::FileImage }, share).on_click(cx.listener(move |this, _, window, cx| { - if system { - this.share_card(shared.clone(), window, cx); - } else { - this.save_card(shared.clone(), cx); - } - }))) - }) - .when(system && !private, |d| { - d.child(action("save-card", Icon::FileImage, "Save as Image").on_click(cx.listener(move |this, _, _, cx| this.save_card(saved.clone(), cx)))) - }); - div().pt_4().flex().flex_wrap().items_start().gap_6().child(face).child( - div() - .flex_1() - .min_w(px(300.)) - .flex() - .flex_col() - .gap_3() - .child( - div() - .child(div().text_size(px(TEXT_HEADING)).font_weight(FontWeight::BOLD).one_line(card.name.clone())) - .child(value(since).text_size(px(TEXT_SMALL))), - ) - .child(actions), - ) - } - - fn share_card(&mut self, card: Card, window: &mut Window, cx: &mut Context) { - let Some(host) = engine::Host::from_window(window) else { return }; - let at = self.motion.bounds.get(); - cx.spawn(async move |this, cx| { - let name = engine::downloads::sanitize_filename(&format!("Tarn Shield {}.png", card.name)); - let dark = !Theme::is_light(); - let written = cx - .background_spawn(async move { - let png = shield_card::card_png(&card, dark)?; - let path = browser_core::shield_card::export_path(&name).ok()?; - std::fs::write(&path, png).ok()?; - url::Url::from_file_path(path).ok() - }) - .await; - let Some(url) = written else { - this.update(cx, |this, cx| { - this.card_notice = Some("Could not draw the image.".into()); - cx.notify(); - }) - .ok(); - return; - }; - let (x, y, w, h) = (f32::from(at.origin.x), f32::from(at.origin.y), f32::from(at.size.width), f32::from(at.size.height)); - host.share(url.as_str(), x.into(), y.into(), w.into(), h.into()); - }) - .detach(); - } - fn general(&self, s: &Snapshot, cx: &mut Context) -> AnyElement { div() .child(section("Updates")) @@ -1490,665 +1055,6 @@ impl SettingsWindow { } } -impl SettingsWindow { - fn permissions(&self, s: Snapshot, cx: &mut Context) -> AnyElement { - let body = if s.permissions.is_empty() { - note("No site has asked yet. When a site asks for the camera, microphone, location or pop-ups and you choose Remember, the answer shows here.") - } else { - let mut list = group(); - for (ix, p) in s.permissions.into_iter().enumerate() { - let set = |allow: Option, origin: String, kind: String| { - cx.listener(move |this: &mut Self, _, _, cx| { - let (origin, kind) = (origin.clone(), kind.clone()); - this.with_browser(cx, move |b, _, cx| b.set_profile_permission(&origin, &kind, allow, cx)); - }) - }; - list = list.child( - row(ix == 0) - .child(text_block(bounded_title(&p.site), p.label.clone())) - .child(button(("allow", ix), "Allow", p.allowed).on_click(set(Some(true), p.origin.clone(), p.kind.clone()))) - .child(button(("block", ix), "Block", !p.allowed).on_click(set(Some(false), p.origin.clone(), p.kind.clone()))) - .child(button(("forget", ix), "Forget", false).on_click(set(None, p.origin, p.kind))), - ); - } - list - }; - div() - .flex() - .flex_col() - .gap_2() - .child(note("This profile's answers to sites. A site you forget asks again next time; Lockdown sites never ask.")) - .child(body) - .into_any_element() - } - - fn shield_levels(&self, s: &Snapshot, cx: &mut Context) -> Div { - let level = s.profile.as_ref().map(|p| p.shield_level).unwrap_or_default(); - let name = s.profile.as_ref().map(|p| bounded_title(&p.name)).unwrap_or_default(); - ShieldLevel::ALL.into_iter().enumerate().fold(group(), |levels, (ix, l)| { - let name = name.clone(); - levels.child( - tab_stop(row(ix == 0).id(l.as_str())) - .cursor_pointer() - .hover(|s| s.bg(Theme::hover())) - .active(|s| s.bg(Theme::pressed())) - .child(radio(l == level)) - .child(text_block(shield_badge(l), level_description(l))) - .on_click(cx.listener(move |this, _, window, cx| { - if l != level { - this.set_level(l, &name, window, cx); - } - })), - ) - }) - } - - fn privacy(&self, s: Snapshot, cx: &mut Context) -> AnyElement { - let target = s.profile.as_ref().map(|p| (s.private, p.id)); - let profile_name = s.profile.as_ref().map(|p| bounded_title(&p.name)).unwrap_or_default(); - - let sites = if s.overrides.is_empty() { - note("No site overrides. Use the Shield button in the address bar to set one for a site.") - } else { - let mut list = group(); - for (ix, (host, l)) in s.overrides.into_iter().enumerate() { - list = list.child( - row(ix == 0).child(label(bounded_title(&host))).child(value(shield_badge(l))).child( - button(("remove-override", ix), "Remove", false) - .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, w, cx| b.remove_site_override(&host, w, cx)))), - ), - ); - } - list - }; - - let reset_zooms = (!s.zooms.is_empty()).then(|| { - button("reset-zooms", "Reset All…", false).on_click(cx.listener(move |this, _, window, cx| { - let Some((private, id)) = target else { return }; - this.ask("Reset every saved zoom level?", None, &["Reset All"], window, cx, move |this, _, cx| { - this.with_browser(cx, |b, _, cx| b.remove_site_zoom(private, id, None, cx)) - }); - })) - }); - let zooms = if s.zooms.is_empty() { - note(format!( - "No saved zoom levels. {} and {} remember the zoom for the site; {} forgets it.", - crate::shortcuts::shown(&crate::ZoomIn, cx), - crate::shortcuts::shown(&crate::ZoomOut, cx), - crate::shortcuts::shown(&crate::ZoomReset, cx) - )) - } else { - let mut list = group(); - for (ix, (host, zoom)) in s.zooms.into_iter().enumerate() { - list = list.child(row(ix == 0).child(label(bounded_title(&host))).child(value(format!("{:.0} %", zoom * 100.))).child( - button(("remove-zoom", ix), "Remove", false).on_click(cx.listener(move |this, _, _, cx| { - let Some((private, id)) = target else { return }; - this.with_browser(cx, |b, _, cx| b.remove_site_zoom(private, id, Some(&host), cx)); - })), - )); - } - list - }; - - let zapped = if s.private { - note("A private space keeps no hidden elements.") - } else if s.zapped.is_empty() { - note("No hidden elements. Zap Element in the command bar hides an element on a site in this profile.") - } else { - let mut list = group(); - for (ix, (host, selector)) in s.zapped.into_iter().enumerate() { - list = list.child(row(ix == 0).child(label(bounded_title(&format!("{host} — {selector}")))).child( - button(("unzap", ix), "Show Again", false).on_click(cx.listener(move |this, _, _, cx| { - let (host, selector) = (host.clone(), selector.clone()); - this.with_browser(cx, move |b, _, cx| b.unzap(&host, Some(&selector), cx)); - })), - )); - } - list - }; - - let muted = if s.muted.is_empty() { - note("No muted sites. Mute Site in the Tabs menu or a tab's menu silences a site in this profile.") - } else { - let mut list = group(); - for (ix, host) in s.muted.into_iter().enumerate() { - list = list.child(row(ix == 0).child(label(bounded_title(&host))).child(button(("unmute", ix), "Unmute", false).on_click(cx.listener( - move |this, _, _, cx| { - let Some((private, id)) = target else { return }; - this.with_browser(cx, |b, _, cx| { - b.set_site_muted(private, id, Some(&host), false, true); - cx.notify(); - }); - }, - )))); - } - list - }; - - let count = |category: &str, unit: &str| match s.filters.counts.get(category) { - Some(n) => format!(" {} {unit}.", thousands(*n)), - None if filters::configured() => " Lists not installed yet.".into(), - None => " Needs the filter lists, which this build does not download.".into(), - }; - let on = |pref| s.prefs.get(pref); - let blocking = group() - .child(self.pref_row(true, Pref::BlockAds, "Block ads", format!("EasyList, AdGuard Base and uBlock filters stop ad requests and hide ad placeholders.{}", count("ads", "rules")), on(Pref::BlockAds), cx)) - .child(self.pref_row(false, Pref::BlockTrackers, "Block trackers", format!("EasyPrivacy and uBlock Privacy stop tracking requests.{}", count("trackers", "rules")), on(Pref::BlockTrackers), cx)) - .child(self.pref_row(false, Pref::BlockAnnoyances, "Block cookie banners", format!("EasyList Cookie and uBlock Cookie Notices hide consent pop-ups and stop the scripts that show them. Nothing is accepted or refused for you.{}", count("annoyances", "rules")), on(Pref::BlockAnnoyances), cx)) - .child(self.pref_row(false, Pref::YouTubeAds, "Block YouTube ads", "Removes ads from YouTube's player data before the player sees them and hides ad slots. YouTube changes often; if videos stop playing, turn this off.", on(Pref::YouTubeAds), cx)) - .child(self.pref_row(false, Pref::BlockPopups, "Block pop-ups and ad redirects", format!("Pages open windows only when you click, never to known pop-up ad sites, and cannot send you to one.{}", count("popups", "domains")), on(Pref::BlockPopups), cx)) - .child(self.pref_row(false, Pref::BlockMalware, "Block dangerous sites", format!("Malware, phishing and scam lists{}.{}", if cfg!(windows) { "" } else { ", plus WebKit's fraudulent-website check, which asks Apple's Safe Browsing service about hashed addresses" }, count("malware", "domains")), on(Pref::BlockMalware), cx)) - .child(self.pref_row(false, Pref::BlockAdult, "Block adult content", format!("Pornographic and other adult websites, with no way past the warning page.{}", count("adult", "domains")), on(Pref::BlockAdult), cx)); - let paused = if s.paused.is_empty() { - note("Blocking runs on every site. Turn it off for one site with the Shield button in the address bar.") - } else { - let mut list = group(); - for (ix, host) in s.paused.into_iter().enumerate() { - list = list.child( - row(ix == 0).child(label(bounded_title(&host))).child( - button(("resume-blocking", ix), "Turn On", false) - .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, w, cx| b.set_site_paused(&host, false, w, cx)))), - ), - ); - } - list - }; - - let updates = s.filters.updates; - let filter_state = s.filters.summary(); - let connection = |first: bool, name: &'static str, detail: String| row(first).child(text_block(name, detail)); - let connections = group() - .child(if filters::configured() { - switch_row("filter-updates", true, text_block("Filter-list updates", format!("GitHub, once a day. {filter_state}")), updates) - .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, _, cx| b.set_filter_updates(!updates, cx)))) - .into_any_element() - } else { - connection(true, "Filter-list updates", format!("GitHub, once a day. {filter_state}")).into_any_element() - }) - .child({ - let on = s.extension_downloads; - switch_row( - "extension-downloads", - false, - text_block( - "Extension and theme downloads", - "GitHub, only when you click Install, Check for updates or Show official extensions in Extensions or Appearance settings. GitHub learns your address and the repository.", - ), - on, - ) - .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, _, cx| b.set_extension_downloads(!on, cx)))) - }) - .child(connection(false, "Site icons", "The site you are on, or a server it already loaded from such as its CDN (without cookies), through the tab's web engine with its Shield rules; never under Lockdown.".into())) - .child(connection(false, "Update checks", match (s.updater, s.update_checks) { - (false, _) => "Not set up in this build; Tarn does not check for updates.".into(), - (true, true) => "GitHub, once a day. Turn off in General.".into(), - (true, false) => "Off; only Check for Updates in the Tarn menu or Check Now in General asks GitHub.".into(), - })) - .when(cfg!(feature = "translation"), |d| { - d.child(connection(false, "Translation", "None. Pages are translated on this Mac with the language packs installed in System Settings; Tarn never downloads them.".into())) - }) - .child(connection(false, "AI requests", format!("Not built yet; no page content leaves {}.", ui::controls::THIS_DEVICE))); - - let mut data = group(); - if !s.private { - data = data.child(row(true).child(label("Export this profile's data to Downloads as JSON")).child( - button("export-profile", "Export", false).on_click(cx.listener(move |this, _, _, cx| { - let Some((private, id)) = target else { return }; - this.with_browser(cx, |b, _, cx| b.export_profile(private, id, cx)); - })), - )); - } - let clear_name = profile_name.clone(); - let delete_name = profile_name.clone(); - data = data - .child( - row(s.private) - .child(text_block( - "Clear browsing history", - "The last hour or today removes visited pages; everything also removes site icons, zoom levels, muted sites, protected sites and hidden elements.", - )) - .child(button("clear-history", "Clear…", false).on_click(cx.listener(move |this, _, window, cx| { - let Some((private, id)) = target else { return }; - let ranges = HistoryRange::ALL.map(HistoryRange::label); - let question = format!("Clear the browsing history of \u{201C}{clear_name}\u{201D}?"); - this.ask(&question, Some("Choose how far back to clear."), &ranges, window, cx, move |this, ix, cx| { - this.with_browser(cx, |b, _, cx| b.clear_history(private, id, HistoryRange::ALL[ix], cx)) - }); - }))), - ) - .child( - row(false).child(label(format!("Delete everything in the profile \u{201C}{profile_name}\u{201D}"))).child( - button("delete-profile", "Delete…", false).on_click(cx.listener(move |this, _, window, cx| { - let Some((private, id)) = target else { return }; - let question = format!("Delete everything in the profile \u{201C}{delete_name}\u{201D}?"); - let detail = "Its spaces, tabs, history, cookies, site data and site settings are deleted. This cannot be undone."; - this.ask(&question, Some(detail), &["Delete Everything"], window, cx, move |this, _, cx| { - this.with_browser(cx, |b, w, cx| b.delete_profile_data(private, id, w, cx)) - }); - })), - ), - ); - - div() - .child(section("Blocking")) - .child(blocking) - .child(note("Applies to every profile. Malware, phishing and adult lists stop whole sites with a warning page; ad, tracker and cookie-banner lists act inside pages.")) - .child(section("Sites without ad, tracker and cookie-banner blocking")) - .child(paused) - .when(!cfg!(windows), |d| { - d.child(section("Sign-in")) - .child(group().child(self.pref_row(true, Pref::Passkeys, "Passkeys and security keys", browser_core::settings::PASSKEYS_NOTE, on(Pref::Passkeys), cx))) - }) - .child(section("Links from other apps")) - .child(group().child(self.pref_row(true, Pref::LocalhostFromApps, "Open localhost links from other apps", format!("A link to {} (localhost, 127.0.0.1) from a terminal, editor or other app opens like a typed address, and the page it shows may lead elsewhere on your network as a typed one can. Off: Tarn refuses it, since a link in a mail could reach services running here; Open Anyway on the notice still opens it. Links to other addresses on your network are refused; Open Anyway on the notice opens them. Applies to every profile.", ui::controls::THIS_DEVICE), on(Pref::LocalhostFromApps), cx))) - .child(section("Site overrides")) - .child(sites) - .child(heading("Site zoom levels", div().children(reset_zooms))) - .child(zooms) - .child(section("Muted sites")) - .child(muted) - .child(section("Hidden elements")) - .child(zapped) - .child(section("Connections Tarn makes")) - .child(connections) - .child(note("Pages you open connect wherever they link to; this list covers Tarn itself. GitHub sees your IP address when Tarn checks for filter lists; turning updates off keeps the installed lists.")) - .child(section("Your data")) - .child(data) - .child(note(s.notice.clone().unwrap_or_else(|| { - let shared = if s.shared_data { " Cookies and site data are shared with another profile and are deleted there too." } else { "" }; - format!("Delete everything removes spaces, tabs, history, cookies, site data and site settings of this profile.{shared} Files you downloaded stay in Downloads.") - }))) - .into_any_element() - } -} - -impl SettingsWindow { - fn developer(&self, s: Snapshot, cx: &mut Context) -> AnyElement { - let on = s.developer; - let dev_profile = s.profiles.iter().find(|p| p.is_dev).map(|p| bounded_title(&p.name)); - let servers = match &s.local_servers { - None => note("Not checked yet."), - Some(ports) if ports.is_empty() => note("Nothing is listening on the common dev ports (3000, 5173, 8080 and others)."), - Some(ports) => { - let mut list = group(); - for (ix, port) in ports.iter().copied().enumerate() { - list = list.child( - row(ix == 0).child(label(format!("localhost:{port}"))).child( - button(("open-server", ix), "Open", false) - .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, w, cx| b.open_local_server(port, w, cx)))), - ), - ); - } - list - } - }; - div() - .child(section("Developer tools")) - .child(group().child( - switch_row("developer-tools", true, label("Web Inspector, JSON viewer, responsive sizes and local servers"), on) - .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, w, cx| b.set_developer(!on, w, cx)))), - )) - .child(note("Applies to every profile; open pages reload. Right-click a page and choose Inspect Element; the toolbar gains responsive sizes and Clear Site Data.")) - .child(section("Developer profile")) - .child(match dev_profile { - Some(name) => group().child(row(true).child(label(name)).child(value("Created"))), - None => group().child(row(true).child(label("A separate profile for development")).child( - button("create-dev-profile", "Create", false) - .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, w, cx| b.create_dev_profile(w, cx)))), - )), - }) - .child(note("Web Inspector and the developer tools are always on there; caches are cleared after every page load and Reload bypasses the cache.")) - .child(heading( - "Local servers", - button("refresh-servers", "Refresh", false).on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.refresh_local_servers(cx)))), - )) - .child(servers) - .into_any_element() - } -} - -impl SettingsWindow { - fn extensions(&self, s: Snapshot, window: &mut Window, cx: &mut Context) -> AnyElement { - if !s.extensions_allowed { - return div().child(section("Extensions")).child(note("Extensions are off in private and Lockdown profiles.")).into_any_element(); - } - let mut page = div(); - if cfg!(windows) { - page = page.child(note("Windows runs Tarn extensions only; Safari and Chrome extensions need their own engine and are not available here.")); - } - if s.all_sites_notice { - page = page.child( - group().child( - row(true) - .child(text_block( - "Extensions you had turned on keep access to every site they list", - "Their \u{201C}Allow on every site\u{201D} switch is on. Turn it off to be asked per site instead.", - )) - .child( - button("all-sites-notice", "OK", false) - .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.dismiss_all_sites_notice(cx)))), - ), - ), - ); - } - if !s.extension_notices.is_empty() { - let mut list = group(); - for (ix, n) in s.extension_notices.iter().enumerate() { - list = list.child(row(ix == 0).child(div().flex_1().text_color(Theme::warning()).child(n.clone()))); - } - page = page.child( - list.child( - row(false).child(div().flex_1()).child( - button("extension-notices", "Dismiss", false) - .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.dismiss_extension_notices(cx)))), - ), - ), - ); - } - if let Some((token, title, lines)) = s.store_sheet { - let card = group() - .child(row(true).child(text_block(title, "From Tarn's signed official catalog."))) - .children(lines.into_iter().map(|l| row(false).child(div().flex_1().child(l)))) - .child( - row(false) - .child(div().flex_1()) - .child( - button("store-cancel", "Cancel", true) - .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.cancel_store_offer(cx)))), - ) - .child(button("store-install", "Install", false).on_click(cx.listener(move |this, _, _, cx| { - let token = token.clone(); - this.with_browser(cx, move |b, _, cx| b.confirm_store_offer(&token, cx)) - }))), - ); - return page.child(section("Confirm")).child(card).into_any_element(); - } - if let Some(c) = s.consent { - let list = |title: &'static str, items: &[String]| { - (!items.is_empty()).then(|| text_block(title, items.iter().map(|i| crate::extensions::shown(i)).collect::>().join(", "))) - }; - let mut card = group() - .child(row(true).child(text_block(format!("Install {} {}?", c.name, c.version), format!("The extension's own words. Source: {}", c.badge)))) - .children(list("Permissions", &c.apis).map(|d| row(false).child(d))) - .children(list("Optional permissions", &c.optional_apis).map(|d| row(false).child(d))) - .children(list("Sites it asks for (you are asked per site)", &c.hosts).map(|d| row(false).child(d))) - .children(list("Optional sites", &c.optional_hosts).map(|d| row(false).child(d))) - .children(list("Changes", &c.changes).map(|d| row(false).child(d))); - if c.active_tab { - card = card.child(row(false).child(note("Clicking its toolbar button gives it the page you are on, in that tab."))); - } - if c.unreviewed { - card = card.child(row(false).child(div().flex_1().text_color(Theme::warning()).child(crate::extensions::UNREVIEWED))); - } - card = card.child( - row(false) - .child(div().flex_1()) - .child( - button("consent-cancel", "Cancel", true) - .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.cancel_extension_install(cx)))), - ) - .child( - button("consent-install", "Install", false) - .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.confirm_extension_install(cx)))), - ), - ); - return page.child(section("Confirm")).child(card).into_any_element(); - } - if !s.extension_choice.is_empty() { - let mut list = group().child(row(true).child(label("The release offers several packages. Pick the one for Chromium or Safari:"))); - for (ix, name) in s.extension_choice.iter().enumerate() { - list = list.child( - row(false).child(label(name.clone())).child( - button(("extension-asset", ix), "Install", false) - .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, move |b, _, cx| b.choose_extension_asset(ix, cx)))), - ), - ); - } - list = list.child( - row(false).child(div().flex_1()).child( - button("extension-asset-cancel", "Cancel", true) - .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.cancel_extension_install(cx)))), - ), - ); - page = page.child(list); - } - if let Some(busy) = s.extension_busy { - page = page.child( - group().child( - row(true).child(label(busy)).child( - button("install-cancel", "Cancel", false) - .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.cancel_extension_install(cx)))), - ), - ), - ); - } - let access = group() - .child(self.pref_row( - true, - Pref::ExtensionsEverySite, - "Allow extensions on every site", - "App and official extensions read and change every site they list without asking. Unverified extensions always ask per site.", - s.prefs.get(Pref::ExtensionsEverySite), - cx, - )) - .when(cfg!(target_os = "macos"), |g| { - g.child(self.pref_row( - false, - Pref::ExtensionsBitwarden, - "Bitwarden integration", - "Lets Bitwarden's app extension unlock with Touch ID through the Bitwarden app, use the clipboard and offer passkeys on sites. Off, it runs like any other app extension.", - s.prefs.get(Pref::ExtensionsBitwarden), - cx, - )) - }); - let installed = if s.extensions.is_empty() { - note("No extensions yet. Apps with a Safari web extension, such as Bitwarden from the Mac App Store, appear here.") - } else { - let mut list = group(); - for (ix, e) in s.extensions.into_iter().enumerate() { - let on = e.enabled; - let (install_id, app_path) = (e.install_id.clone(), e.app_path.clone()); - let mut actions = div().flex().flex_wrap().items_center().gap_2(); - if let (Some(all), Some(id)) = (e.all_sites, e.install_id.clone()) { - actions = actions.child( - tab_stop(div().id(("extension-all", ix))) - .flex() - .items_center() - .gap_1p5() - .cursor_pointer() - .text_size(px(TEXT_SMALL)) - .child(switch(all)) - .child("Every site") - .on_click(cx.listener(move |this, _, _, cx| { - let id = id.clone(); - this.with_browser(cx, move |b, w, cx| b.set_extension_all_sites(&id, !all, w, cx)) - })), - ); - } - if let Some(id) = e.install_id.clone() { - actions = actions.child(button(("extension-forget", ix), "Forget Site Answers", false).on_click(cx.listener(move |this, _, _, cx| { - let id = id.clone(); - this.with_browser(cx, move |b, w, cx| b.forget_extension_answers(&id, w, cx)) - }))); - } - if let Some(id) = e.install_id { - let question = format!("Remove the extension \u{201C}{}\u{201D}?", bounded_title(&e.name)); - actions = actions.child(button(("extension-remove", ix), "Remove\u{2026}", false).on_click(cx.listener(move |this, _, window, cx| { - let id = id.clone(); - this.ask(&question, Some("Its files and the data it stored are deleted."), &["Remove"], window, cx, move |this, _, cx| { - this.with_browser(cx, move |b, _, cx| b.remove_extension(&id, cx)) - }); - }))); - } - let r = row(ix == 0) - .child( - div() - .flex_1() - .min_w_0() - .flex() - .flex_col() - .gap_1p5() - .child(text_block(format!("{} \u{00B7} {}", e.name, e.badge), e.permissions).flex_initial()) - .child(actions), - ) - .child(tab_stop(div().id(("extension-switch", ix))).cursor_pointer().child(switch(on)).on_click(cx.listener(move |this, _, _, cx| { - let (install_id, app_path) = (install_id.clone(), app_path.clone()); - this.with_browser(cx, move |b, w, cx| match (install_id, app_path) { - (Some(id), _) => b.set_extension(&id, !on, w, cx), - (None, Some(path)) => b.enable_app_extension(path, w, cx), - _ => {} - }) - }))); - list = list.child(r); - } - list - }; - let downloads = s.extension_downloads; - const OFF: &str = "Extension downloads are off in Privacy settings."; - let input = self.repo_input.clone(); - let focused = input.focus_handle(cx).is_focused(window); - let add = group() - .child(row(true).child(field(focused).flex_1().py_0p5().child(input)).child(available( - button("install-github", "Install", false).when(downloads, |d| d.on_click(cx.listener(|this, _, _, cx| this.install_from_github(cx)))), - downloads, - OFF, - ))) - .child(row(false).child(label("A .zip or .crx file")).child(button("install-file", "Choose File\u{2026}", false).on_click(cx.listener( - |this, _, _, cx| { - let paths = cx.prompt_for_paths(gpui::PathPromptOptions { files: true, directories: false, multiple: false, prompt: None }); - let main = this.main; - cx.spawn(async move |_, cx| { - let Ok(Ok(Some(paths))) = paths.await else { return }; - let Some(path) = paths.into_iter().next() else { return }; - main.update(cx, |b, _, cx| { - if path.extension().is_some_and(|e| e.eq_ignore_ascii_case("zip") || e.eq_ignore_ascii_case("crx")) { - b.install_extension(crate::extensions::Install::File(path), None, cx); - } else { - b.core.extensions.borrow_mut().notices.push("Choose a .zip or .crx extension file.".to_owned()); - cx.notify(); - } - }) - .ok(); - }) - .detach(); - }, - )))) - .child( - row(false).child(label("Installed from GitHub or the catalog")).child(available( - button("extension-updates", "Check for Updates", false) - .when(downloads, |d| d.on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.check_extension_updates(cx))))), - downloads, - OFF, - )), - ); - page = page.child(section("Installed")).child(installed).child(section("Access")).child(access).child(section("Add")).child(add); - if !downloads { - page = page.child(note("Extension downloads are off in Privacy settings; installing from a file still works.")); - } - if crate::extensions::catalog_configured() { - let (rows, old) = s.catalog; - let mut official = group().child( - row(true).child(label("Reviewed and signed by Tarn")).child(available( - button("catalog", "Show Official Extensions", false) - .when(downloads, |d| d.on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.fetch_catalog(cx))))), - downloads, - OFF, - )), - ); - for (ix, e) in rows.into_iter().enumerate() { - let id = e.id.clone(); - official = official.child(row(false).child(text_block(format!("{} {}", e.name, e.version), e.description)).child(if e.installed { - value("Installed").into_any_element() - } else { - available( - button(("catalog-install", ix), "Install", false).when(downloads, |d| { - d.on_click(cx.listener(move |this, _, _, cx| { - let id = id.clone(); - this.with_browser(cx, move |b, _, cx| b.install_official(&id, cx)) - })) - }), - downloads, - OFF, - ) - .into_any_element() - })); - } - official = official.child(self.link_row( - "extension-store", - "Browse the store", - "Official extensions with screenshots and search; Install in Tarn asks here first.", - browser_core::extensions::STORE_URL, - cx, - )); - page = page.child(section("Official")).child(official); - if old { - page = page.child(note("This list is more than 30 days old. Show official extensions to get the current one.")); - } - } - page.child(note("Extensions run in WebKit tabs of this profile only, never in the private space or in Lockdown profiles, and never on sites set to Lockdown. An extension that may not use every site asks for each site when it first meets it. Open pages reload when an extension is turned on or off.")) - .into_any_element() - } - - fn profile_row(&self, s: &Snapshot, ix: usize, p: &Profile, deletable: bool, cx: &mut Context) -> gpui::Div { - let id = p.id; - let current = s.profile.as_ref().is_some_and(|c| c.id == id && c.is_private == p.is_private); - row(ix == 0) - .child(if p.is_private { icon(Icon::Person, 14., Theme::warning()).into_any_element() } else { profile_dot(&p.color, 12.).into_any_element() }) - .child(label(bounded_title(&p.name))) - .when(current, |d| d.child(value("This window"))) - .when(p.is_private, |d| d.child(value("Private, not saved"))) - .when(p.is_dev, |d| d.child(value("Developer"))) - .child(value(shield_badge(p.shield_level))) - .when(!p.is_private, |d| { - d.child( - button(("edit-profile", ix), "Edit…", false) - .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, w, cx| b.open_profile_editor(Some(id), w, cx)))), - ) - }) - .when(!p.is_private && deletable, |d| { - let question = format!("Delete the profile \u{201C}{}\u{201D}?", bounded_title(&p.name)); - d.child(button(("delete-profile", ix), "Delete…", false).on_click(cx.listener(move |this, _, window, cx| { - let detail = "Its spaces, tabs, history and website data are deleted. Website data another profile shares stays for that profile."; - this.ask(&question, Some(detail), &["Delete Profile"], window, cx, move |this, _, cx| { - this.with_browser(cx, |b, w, cx| b.delete_profile(id, w, cx)) - }); - }))) - }) - } - - fn profiles(&self, s: &Snapshot, cx: &mut Context) -> AnyElement { - let deletable = s.profiles.iter().filter(|p| !p.is_private).count() > 1; - let list = s.profiles.iter().enumerate().fold(group(), |list, (ix, p)| list.child(self.profile_row(s, ix, p, deletable, cx))); - let rules = if s.space_rules.is_empty() { - note("No rules. \u{201c}Always open in\u{201d} in a site's settings opens its new tabs in the space you pick.") - } else { - let mut list = group(); - for (ix, (id, pattern, space)) in s.space_rules.iter().cloned().enumerate() { - list = list.child( - row(ix == 0).child(label(bounded_title(&pattern))).child(value(space)).child( - button(("delete-space-rule", ix), "Remove", false) - .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, _, cx| b.delete_space_rule(id, cx)))), - ), - ); - } - list - }; - div() - .child(heading( - "Profiles", - button("new-profile", "New Profile…", true) - .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, w, cx| b.open_profile_editor(None, w, cx)))), - )) - .child(list) - .child(note( - "Delete removes a profile with its spaces, tabs, history and website data. Website data another profile shares stays for that profile.", - )) - .child(section("Space Rules")) - .child(rules) - .into_any_element() - } -} - /// Arms on the first call for `target`; returns true on a second call for the same target. pub(crate) fn confirm_twice(armed: &mut Option, target: T) -> bool { if armed.take().is_some_and(|a| a == target) { diff --git a/crates/app/src/settings/extensions.rs b/crates/app/src/settings/extensions.rs new file mode 100644 index 00000000..f1c7af4d --- /dev/null +++ b/crates/app/src/settings/extensions.rs @@ -0,0 +1,380 @@ +use super::*; + +const OFF: &str = "Extension downloads are off in Privacy settings."; + +impl SettingsWindow { + pub(super) fn extensions(&self, s: Snapshot, window: &mut Window, cx: &mut Context) -> AnyElement { + if !s.extensions_allowed { + return div().child(section("Extensions")).child(note("Extensions are off in private and Lockdown profiles.")).into_any_element(); + } + let mut page = div(); + if cfg!(windows) { + page = page.child(note("Windows runs Tarn extensions only; Safari and Chrome extensions need their own engine and are not available here.")); + } + page = self.extension_notices(page, &s, cx); + if let Some(sheet) = s.store_sheet { + return self.store_confirm(page, sheet, cx); + } + if let Some(c) = s.consent { + return self.consent_confirm(page, c, cx); + } + page = self.extension_progress(page, &s, cx); + let access = self.extension_access(&s, cx); + let installed = self.installed_extensions(s.extensions, cx); + let downloads = s.extension_downloads; + let add = self.add_extension(downloads, window, cx); + page = page.child(section("Installed")).child(installed).child(section("Access")).child(access).child(section("Add")).child(add); + if !downloads { + page = page.child(note("Extension downloads are off in Privacy settings; installing from a file still works.")); + } + if crate::extensions::catalog_configured() { + page = self.official_extensions(page, s.catalog, downloads, cx); + } + page.child(note("Extensions run in WebKit tabs of this profile only, never in the private space or in Lockdown profiles, and never on sites set to Lockdown. An extension that may not use every site asks for each site when it first meets it. Open pages reload when an extension is turned on or off.")) + .into_any_element() + } + + fn extension_notices(&self, mut page: Div, s: &Snapshot, cx: &mut Context) -> Div { + if s.all_sites_notice { + page = page.child( + group().child( + row(true) + .child(text_block( + "Extensions you had turned on keep access to every site they list", + "Their \u{201C}Allow on every site\u{201D} switch is on. Turn it off to be asked per site instead.", + )) + .child( + button("all-sites-notice", "OK", false) + .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.dismiss_all_sites_notice(cx)))), + ), + ), + ); + } + if !s.extension_notices.is_empty() { + let mut list = group(); + for (ix, n) in s.extension_notices.iter().enumerate() { + list = list.child(row(ix == 0).child(div().flex_1().text_color(Theme::warning()).child(n.clone()))); + } + page = page.child( + list.child( + row(false).child(div().flex_1()).child( + button("extension-notices", "Dismiss", false) + .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.dismiss_extension_notices(cx)))), + ), + ), + ); + } + page + } + + fn store_confirm(&self, page: Div, sheet: (crate::extensions::StoreToken, String, Vec), cx: &mut Context) -> AnyElement { + let (token, title, lines) = sheet; + let card = group() + .child(row(true).child(text_block(title, "From Tarn's signed official catalog."))) + .children(lines.into_iter().map(|l| row(false).child(div().flex_1().child(l)))) + .child( + row(false) + .child(div().flex_1()) + .child( + button("store-cancel", "Cancel", true) + .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.cancel_store_offer(cx)))), + ) + .child(button("store-install", "Install", false).on_click(cx.listener(move |this, _, _, cx| { + let token = token.clone(); + this.with_browser(cx, move |b, _, cx| b.confirm_store_offer(&token, cx)) + }))), + ); + page.child(section("Confirm")).child(card).into_any_element() + } + + fn consent_confirm(&self, page: Div, c: crate::extensions::Consent, cx: &mut Context) -> AnyElement { + let list = |title: &'static str, items: &[String]| { + (!items.is_empty()).then(|| text_block(title, items.iter().map(|i| crate::extensions::shown(i)).collect::>().join(", "))) + }; + let mut card = group() + .child(row(true).child(text_block(format!("Install {} {}?", c.name, c.version), format!("The extension's own words. Source: {}", c.badge)))) + .children(list("Permissions", &c.apis).map(|d| row(false).child(d))) + .children(list("Optional permissions", &c.optional_apis).map(|d| row(false).child(d))) + .children(list("Sites it asks for (you are asked per site)", &c.hosts).map(|d| row(false).child(d))) + .children(list("Optional sites", &c.optional_hosts).map(|d| row(false).child(d))) + .children(list("Changes", &c.changes).map(|d| row(false).child(d))); + if c.active_tab { + card = card.child(row(false).child(note("Clicking its toolbar button gives it the page you are on, in that tab."))); + } + if c.unreviewed { + card = card.child(row(false).child(div().flex_1().text_color(Theme::warning()).child(crate::extensions::UNREVIEWED))); + } + card = card.child( + row(false) + .child(div().flex_1()) + .child( + button("consent-cancel", "Cancel", true) + .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.cancel_extension_install(cx)))), + ) + .child( + button("consent-install", "Install", false) + .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.confirm_extension_install(cx)))), + ), + ); + page.child(section("Confirm")).child(card).into_any_element() + } + + fn extension_progress(&self, mut page: Div, s: &Snapshot, cx: &mut Context) -> Div { + if !s.extension_choice.is_empty() { + let mut list = group().child(row(true).child(label("The release offers several packages. Pick the one for Chromium or Safari:"))); + for (ix, name) in s.extension_choice.iter().enumerate() { + list = list.child( + row(false).child(label(name.clone())).child( + button(("extension-asset", ix), "Install", false) + .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, move |b, _, cx| b.choose_extension_asset(ix, cx)))), + ), + ); + } + list = list.child( + row(false).child(div().flex_1()).child( + button("extension-asset-cancel", "Cancel", true) + .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.cancel_extension_install(cx)))), + ), + ); + page = page.child(list); + } + if let Some(busy) = s.extension_busy.clone() { + page = page.child( + group().child( + row(true).child(label(busy)).child( + button("install-cancel", "Cancel", false) + .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.cancel_extension_install(cx)))), + ), + ), + ); + } + page + } + + fn extension_access(&self, s: &Snapshot, cx: &mut Context) -> Div { + group() + .child(self.pref_row( + true, + Pref::ExtensionsEverySite, + "Allow extensions on every site", + "App and official extensions read and change every site they list without asking. Unverified extensions always ask per site.", + s.prefs.get(Pref::ExtensionsEverySite), + cx, + )) + .when(cfg!(target_os = "macos"), |g| { + g.child(self.pref_row( + false, + Pref::ExtensionsBitwarden, + "Bitwarden integration", + "Lets Bitwarden's app extension unlock with Touch ID through the Bitwarden app, use the clipboard and offer passkeys on sites. Off, it runs like any other app extension.", + s.prefs.get(Pref::ExtensionsBitwarden), + cx, + )) + }) + } + + fn installed_extensions(&self, extensions: Vec, cx: &mut Context) -> Div { + if extensions.is_empty() { + note("No extensions yet. Apps with a Safari web extension, such as Bitwarden from the Mac App Store, appear here.") + } else { + let mut list = group(); + for (ix, e) in extensions.into_iter().enumerate() { + let on = e.enabled; + let (install_id, app_path) = (e.install_id.clone(), e.app_path.clone()); + let mut actions = div().flex().flex_wrap().items_center().gap_2(); + if let (Some(all), Some(id)) = (e.all_sites, e.install_id.clone()) { + actions = actions.child( + tab_stop(div().id(("extension-all", ix))) + .flex() + .items_center() + .gap_1p5() + .cursor_pointer() + .text_size(px(TEXT_SMALL)) + .child(switch(all)) + .child("Every site") + .on_click(cx.listener(move |this, _, _, cx| { + let id = id.clone(); + this.with_browser(cx, move |b, w, cx| b.set_extension_all_sites(&id, !all, w, cx)) + })), + ); + } + if let Some(id) = e.install_id.clone() { + actions = actions.child(button(("extension-forget", ix), "Forget Site Answers", false).on_click(cx.listener(move |this, _, _, cx| { + let id = id.clone(); + this.with_browser(cx, move |b, w, cx| b.forget_extension_answers(&id, w, cx)) + }))); + } + if let Some(id) = e.install_id { + let question = format!("Remove the extension \u{201C}{}\u{201D}?", bounded_title(&e.name)); + actions = actions.child(button(("extension-remove", ix), "Remove\u{2026}", false).on_click(cx.listener(move |this, _, window, cx| { + let id = id.clone(); + this.ask(&question, Some("Its files and the data it stored are deleted."), &["Remove"], window, cx, move |this, _, cx| { + this.with_browser(cx, move |b, _, cx| b.remove_extension(&id, cx)) + }); + }))); + } + let r = row(ix == 0) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap_1p5() + .child(text_block(format!("{} \u{00B7} {}", e.name, e.badge), e.permissions).flex_initial()) + .child(actions), + ) + .child(tab_stop(div().id(("extension-switch", ix))).cursor_pointer().child(switch(on)).on_click(cx.listener(move |this, _, _, cx| { + let (install_id, app_path) = (install_id.clone(), app_path.clone()); + this.with_browser(cx, move |b, w, cx| match (install_id, app_path) { + (Some(id), _) => b.set_extension(&id, !on, w, cx), + (None, Some(path)) => b.enable_app_extension(path, w, cx), + _ => {} + }) + }))); + list = list.child(r); + } + list + } + } + + fn add_extension(&self, downloads: bool, window: &mut Window, cx: &mut Context) -> Div { + let input = self.repo_input.clone(); + let focused = input.focus_handle(cx).is_focused(window); + group() + .child(row(true).child(field(focused).flex_1().py_0p5().child(input)).child(available( + button("install-github", "Install", false).when(downloads, |d| d.on_click(cx.listener(|this, _, _, cx| this.install_from_github(cx)))), + downloads, + OFF, + ))) + .child(row(false).child(label("A .zip or .crx file")).child(button("install-file", "Choose File\u{2026}", false).on_click(cx.listener( + |this, _, _, cx| { + let paths = cx.prompt_for_paths(gpui::PathPromptOptions { files: true, directories: false, multiple: false, prompt: None }); + let main = this.main; + cx.spawn(async move |_, cx| { + let Ok(Ok(Some(paths))) = paths.await else { return }; + let Some(path) = paths.into_iter().next() else { return }; + main.update(cx, |b, _, cx| { + if path.extension().is_some_and(|e| e.eq_ignore_ascii_case("zip") || e.eq_ignore_ascii_case("crx")) { + b.install_extension(crate::extensions::Install::File(path), None, cx); + } else { + b.core.extensions.borrow_mut().notices.push("Choose a .zip or .crx extension file.".to_owned()); + cx.notify(); + } + }) + .ok(); + }) + .detach(); + }, + )))) + .child( + row(false).child(label("Installed from GitHub or the catalog")).child(available( + button("extension-updates", "Check for Updates", false) + .when(downloads, |d| d.on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.check_extension_updates(cx))))), + downloads, + OFF, + )), + ) + } + + fn official_extensions(&self, mut page: Div, catalog: (Vec, bool), downloads: bool, cx: &mut Context) -> Div { + let (rows, old) = catalog; + let mut official = group().child( + row(true).child(label("Reviewed and signed by Tarn")).child(available( + button("catalog", "Show Official Extensions", false) + .when(downloads, |d| d.on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.fetch_catalog(cx))))), + downloads, + OFF, + )), + ); + for (ix, e) in rows.into_iter().enumerate() { + let id = e.id.clone(); + official = official.child(row(false).child(text_block(format!("{} {}", e.name, e.version), e.description)).child(if e.installed { + value("Installed").into_any_element() + } else { + available( + button(("catalog-install", ix), "Install", false).when(downloads, |d| { + d.on_click(cx.listener(move |this, _, _, cx| { + let id = id.clone(); + this.with_browser(cx, move |b, _, cx| b.install_official(&id, cx)) + })) + }), + downloads, + OFF, + ) + .into_any_element() + })); + } + official = official.child(self.link_row( + "extension-store", + "Browse the store", + "Official extensions with screenshots and search; Install in Tarn asks here first.", + browser_core::extensions::STORE_URL, + cx, + )); + page = page.child(section("Official")).child(official); + if old { + page = page.child(note("This list is more than 30 days old. Show official extensions to get the current one.")); + } + page + } + + fn profile_row(&self, s: &Snapshot, ix: usize, p: &Profile, deletable: bool, cx: &mut Context) -> gpui::Div { + let id = p.id; + let current = s.profile.as_ref().is_some_and(|c| c.id == id && c.is_private == p.is_private); + row(ix == 0) + .child(if p.is_private { icon(Icon::Person, 14., Theme::warning()).into_any_element() } else { profile_dot(&p.color, 12.).into_any_element() }) + .child(label(bounded_title(&p.name))) + .when(current, |d| d.child(value("This window"))) + .when(p.is_private, |d| d.child(value("Private, not saved"))) + .when(p.is_dev, |d| d.child(value("Developer"))) + .child(value(shield_badge(p.shield_level))) + .when(!p.is_private, |d| { + d.child( + button(("edit-profile", ix), "Edit…", false) + .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, w, cx| b.open_profile_editor(Some(id), w, cx)))), + ) + }) + .when(!p.is_private && deletable, |d| { + let question = format!("Delete the profile \u{201C}{}\u{201D}?", bounded_title(&p.name)); + d.child(button(("delete-profile", ix), "Delete…", false).on_click(cx.listener(move |this, _, window, cx| { + let detail = "Its spaces, tabs, history and website data are deleted. Website data another profile shares stays for that profile."; + this.ask(&question, Some(detail), &["Delete Profile"], window, cx, move |this, _, cx| { + this.with_browser(cx, |b, w, cx| b.delete_profile(id, w, cx)) + }); + }))) + }) + } + + pub(super) fn profiles(&self, s: &Snapshot, cx: &mut Context) -> AnyElement { + let deletable = s.profiles.iter().filter(|p| !p.is_private).count() > 1; + let list = s.profiles.iter().enumerate().fold(group(), |list, (ix, p)| list.child(self.profile_row(s, ix, p, deletable, cx))); + let rules = if s.space_rules.is_empty() { + note("No rules. \u{201c}Always open in\u{201d} in a site's settings opens its new tabs in the space you pick.") + } else { + let mut list = group(); + for (ix, (id, pattern, space)) in s.space_rules.iter().cloned().enumerate() { + list = list.child( + row(ix == 0).child(label(bounded_title(&pattern))).child(value(space)).child( + button(("delete-space-rule", ix), "Remove", false) + .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, _, cx| b.delete_space_rule(id, cx)))), + ), + ); + } + list + }; + div() + .child(heading( + "Profiles", + button("new-profile", "New Profile…", true) + .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, w, cx| b.open_profile_editor(None, w, cx)))), + )) + .child(list) + .child(note( + "Delete removes a profile with its spaces, tabs, history and website data. Website data another profile shares stays for that profile.", + )) + .child(section("Space Rules")) + .child(rules) + .into_any_element() + } +} diff --git a/crates/app/src/settings/privacy.rs b/crates/app/src/settings/privacy.rs new file mode 100644 index 00000000..9798fd16 --- /dev/null +++ b/crates/app/src/settings/privacy.rs @@ -0,0 +1,318 @@ +use super::*; + +impl SettingsWindow { + pub(super) fn permissions(&self, s: Snapshot, cx: &mut Context) -> AnyElement { + let body = if s.permissions.is_empty() { + note("No site has asked yet. When a site asks for the camera, microphone, location or pop-ups and you choose Remember, the answer shows here.") + } else { + let mut list = group(); + for (ix, p) in s.permissions.into_iter().enumerate() { + let set = |allow: Option, origin: String, kind: String| { + cx.listener(move |this: &mut Self, _, _, cx| { + let (origin, kind) = (origin.clone(), kind.clone()); + this.with_browser(cx, move |b, _, cx| b.set_profile_permission(&origin, &kind, allow, cx)); + }) + }; + list = list.child( + row(ix == 0) + .child(text_block(bounded_title(&p.site), p.label.clone())) + .child(button(("allow", ix), "Allow", p.allowed).on_click(set(Some(true), p.origin.clone(), p.kind.clone()))) + .child(button(("block", ix), "Block", !p.allowed).on_click(set(Some(false), p.origin.clone(), p.kind.clone()))) + .child(button(("forget", ix), "Forget", false).on_click(set(None, p.origin, p.kind))), + ); + } + list + }; + div() + .flex() + .flex_col() + .gap_2() + .child(note("This profile's answers to sites. A site you forget asks again next time; Lockdown sites never ask.")) + .child(body) + .into_any_element() + } + + pub(super) fn shield_levels(&self, s: &Snapshot, cx: &mut Context) -> Div { + let level = s.profile.as_ref().map(|p| p.shield_level).unwrap_or_default(); + let name = s.profile.as_ref().map(|p| bounded_title(&p.name)).unwrap_or_default(); + ShieldLevel::ALL.into_iter().enumerate().fold(group(), |levels, (ix, l)| { + let name = name.clone(); + levels.child( + tab_stop(row(ix == 0).id(l.as_str())) + .cursor_pointer() + .hover(|s| s.bg(Theme::hover())) + .active(|s| s.bg(Theme::pressed())) + .child(radio(l == level)) + .child(text_block(shield_badge(l), level_description(l))) + .on_click(cx.listener(move |this, _, window, cx| { + if l != level { + this.set_level(l, &name, window, cx); + } + })), + ) + }) + } + + pub(super) fn privacy(&self, s: Snapshot, cx: &mut Context) -> AnyElement { + let target = s.profile.as_ref().map(|p| (s.private, p.id)); + let profile_name = s.profile.as_ref().map(|p| bounded_title(&p.name)).unwrap_or_default(); + + let sites = if s.overrides.is_empty() { + note("No site overrides. Use the Shield button in the address bar to set one for a site.") + } else { + let mut list = group(); + for (ix, (host, l)) in s.overrides.into_iter().enumerate() { + list = list.child( + row(ix == 0).child(label(bounded_title(&host))).child(value(shield_badge(l))).child( + button(("remove-override", ix), "Remove", false) + .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, w, cx| b.remove_site_override(&host, w, cx)))), + ), + ); + } + list + }; + + let reset_zooms = (!s.zooms.is_empty()).then(|| { + button("reset-zooms", "Reset All…", false).on_click(cx.listener(move |this, _, window, cx| { + let Some((private, id)) = target else { return }; + this.ask("Reset every saved zoom level?", None, &["Reset All"], window, cx, move |this, _, cx| { + this.with_browser(cx, |b, _, cx| b.remove_site_zoom(private, id, None, cx)) + }); + })) + }); + let zooms = if s.zooms.is_empty() { + note(format!( + "No saved zoom levels. {} and {} remember the zoom for the site; {} forgets it.", + crate::shortcuts::shown(&crate::ZoomIn, cx), + crate::shortcuts::shown(&crate::ZoomOut, cx), + crate::shortcuts::shown(&crate::ZoomReset, cx) + )) + } else { + let mut list = group(); + for (ix, (host, zoom)) in s.zooms.into_iter().enumerate() { + list = list.child(row(ix == 0).child(label(bounded_title(&host))).child(value(format!("{:.0} %", zoom * 100.))).child( + button(("remove-zoom", ix), "Remove", false).on_click(cx.listener(move |this, _, _, cx| { + let Some((private, id)) = target else { return }; + this.with_browser(cx, |b, _, cx| b.remove_site_zoom(private, id, Some(&host), cx)); + })), + )); + } + list + }; + + let zapped = if s.private { + note("A private space keeps no hidden elements.") + } else if s.zapped.is_empty() { + note("No hidden elements. Zap Element in the command bar hides an element on a site in this profile.") + } else { + let mut list = group(); + for (ix, (host, selector)) in s.zapped.into_iter().enumerate() { + list = list.child(row(ix == 0).child(label(bounded_title(&format!("{host} — {selector}")))).child( + button(("unzap", ix), "Show Again", false).on_click(cx.listener(move |this, _, _, cx| { + let (host, selector) = (host.clone(), selector.clone()); + this.with_browser(cx, move |b, _, cx| b.unzap(&host, Some(&selector), cx)); + })), + )); + } + list + }; + + let muted = if s.muted.is_empty() { + note("No muted sites. Mute Site in the Tabs menu or a tab's menu silences a site in this profile.") + } else { + let mut list = group(); + for (ix, host) in s.muted.into_iter().enumerate() { + list = list.child(row(ix == 0).child(label(bounded_title(&host))).child(button(("unmute", ix), "Unmute", false).on_click(cx.listener( + move |this, _, _, cx| { + let Some((private, id)) = target else { return }; + this.with_browser(cx, |b, _, cx| { + b.set_site_muted(private, id, Some(&host), false, true); + cx.notify(); + }); + }, + )))); + } + list + }; + + let count = |category: &str, unit: &str| match s.filters.counts.get(category) { + Some(n) => format!(" {} {unit}.", thousands(*n)), + None if filters::configured() => " Lists not installed yet.".into(), + None => " Needs the filter lists, which this build does not download.".into(), + }; + let on = |pref| s.prefs.get(pref); + let blocking = group() + .child(self.pref_row(true, Pref::BlockAds, "Block ads", format!("EasyList, AdGuard Base and uBlock filters stop ad requests and hide ad placeholders.{}", count("ads", "rules")), on(Pref::BlockAds), cx)) + .child(self.pref_row(false, Pref::BlockTrackers, "Block trackers", format!("EasyPrivacy and uBlock Privacy stop tracking requests.{}", count("trackers", "rules")), on(Pref::BlockTrackers), cx)) + .child(self.pref_row(false, Pref::BlockAnnoyances, "Block cookie banners", format!("EasyList Cookie and uBlock Cookie Notices hide consent pop-ups and stop the scripts that show them. Nothing is accepted or refused for you.{}", count("annoyances", "rules")), on(Pref::BlockAnnoyances), cx)) + .child(self.pref_row(false, Pref::YouTubeAds, "Block YouTube ads", "Removes ads from YouTube's player data before the player sees them and hides ad slots. YouTube changes often; if videos stop playing, turn this off.", on(Pref::YouTubeAds), cx)) + .child(self.pref_row(false, Pref::BlockPopups, "Block pop-ups and ad redirects", format!("Pages open windows only when you click, never to known pop-up ad sites, and cannot send you to one.{}", count("popups", "domains")), on(Pref::BlockPopups), cx)) + .child(self.pref_row(false, Pref::BlockMalware, "Block dangerous sites", format!("Malware, phishing and scam lists{}.{}", if cfg!(windows) { "" } else { ", plus WebKit's fraudulent-website check, which asks Apple's Safe Browsing service about hashed addresses" }, count("malware", "domains")), on(Pref::BlockMalware), cx)) + .child(self.pref_row(false, Pref::BlockAdult, "Block adult content", format!("Pornographic and other adult websites, with no way past the warning page.{}", count("adult", "domains")), on(Pref::BlockAdult), cx)); + let paused = if s.paused.is_empty() { + note("Blocking runs on every site. Turn it off for one site with the Shield button in the address bar.") + } else { + let mut list = group(); + for (ix, host) in s.paused.into_iter().enumerate() { + list = list.child( + row(ix == 0).child(label(bounded_title(&host))).child( + button(("resume-blocking", ix), "Turn On", false) + .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, w, cx| b.set_site_paused(&host, false, w, cx)))), + ), + ); + } + list + }; + + let updates = s.filters.updates; + let filter_state = s.filters.summary(); + let connection = |first: bool, name: &'static str, detail: String| row(first).child(text_block(name, detail)); + let connections = group() + .child(if filters::configured() { + switch_row("filter-updates", true, text_block("Filter-list updates", format!("GitHub, once a day. {filter_state}")), updates) + .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, _, cx| b.set_filter_updates(!updates, cx)))) + .into_any_element() + } else { + connection(true, "Filter-list updates", format!("GitHub, once a day. {filter_state}")).into_any_element() + }) + .child({ + let on = s.extension_downloads; + switch_row( + "extension-downloads", + false, + text_block( + "Extension and theme downloads", + "GitHub, only when you click Install, Check for updates or Show official extensions in Extensions or Appearance settings. GitHub learns your address and the repository.", + ), + on, + ) + .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, _, cx| b.set_extension_downloads(!on, cx)))) + }) + .child(connection(false, "Site icons", "The site you are on, or a server it already loaded from such as its CDN (without cookies), through the tab's web engine with its Shield rules; never under Lockdown.".into())) + .child(connection(false, "Update checks", match (s.updater, s.update_checks) { + (false, _) => "Not set up in this build; Tarn does not check for updates.".into(), + (true, true) => "GitHub, once a day. Turn off in General.".into(), + (true, false) => "Off; only Check for Updates in the Tarn menu or Check Now in General asks GitHub.".into(), + })) + .when(cfg!(feature = "translation"), |d| { + d.child(connection(false, "Translation", "None. Pages are translated on this Mac with the language packs installed in System Settings; Tarn never downloads them.".into())) + }) + .child(connection(false, "AI requests", format!("Not built yet; no page content leaves {}.", ui::controls::THIS_DEVICE))); + + let mut data = group(); + if !s.private { + data = data.child(row(true).child(label("Export this profile's data to Downloads as JSON")).child( + button("export-profile", "Export", false).on_click(cx.listener(move |this, _, _, cx| { + let Some((private, id)) = target else { return }; + this.with_browser(cx, |b, _, cx| b.export_profile(private, id, cx)); + })), + )); + } + let clear_name = profile_name.clone(); + let delete_name = profile_name.clone(); + data = data + .child( + row(s.private) + .child(text_block( + "Clear browsing history", + "The last hour or today removes visited pages; everything also removes site icons, zoom levels, muted sites, protected sites and hidden elements.", + )) + .child(button("clear-history", "Clear…", false).on_click(cx.listener(move |this, _, window, cx| { + let Some((private, id)) = target else { return }; + let ranges = HistoryRange::ALL.map(HistoryRange::label); + let question = format!("Clear the browsing history of \u{201C}{clear_name}\u{201D}?"); + this.ask(&question, Some("Choose how far back to clear."), &ranges, window, cx, move |this, ix, cx| { + this.with_browser(cx, |b, _, cx| b.clear_history(private, id, HistoryRange::ALL[ix], cx)) + }); + }))), + ) + .child( + row(false).child(label(format!("Delete everything in the profile \u{201C}{profile_name}\u{201D}"))).child( + button("delete-profile", "Delete…", false).on_click(cx.listener(move |this, _, window, cx| { + let Some((private, id)) = target else { return }; + let question = format!("Delete everything in the profile \u{201C}{delete_name}\u{201D}?"); + let detail = "Its spaces, tabs, history, cookies, site data and site settings are deleted. This cannot be undone."; + this.ask(&question, Some(detail), &["Delete Everything"], window, cx, move |this, _, cx| { + this.with_browser(cx, |b, w, cx| b.delete_profile_data(private, id, w, cx)) + }); + })), + ), + ); + + div() + .child(section("Blocking")) + .child(blocking) + .child(note("Applies to every profile. Malware, phishing and adult lists stop whole sites with a warning page; ad, tracker and cookie-banner lists act inside pages.")) + .child(section("Sites without ad, tracker and cookie-banner blocking")) + .child(paused) + .when(!cfg!(windows), |d| { + d.child(section("Sign-in")) + .child(group().child(self.pref_row(true, Pref::Passkeys, "Passkeys and security keys", browser_core::settings::PASSKEYS_NOTE, on(Pref::Passkeys), cx))) + }) + .child(section("Links from other apps")) + .child(group().child(self.pref_row(true, Pref::LocalhostFromApps, "Open localhost links from other apps", format!("A link to {} (localhost, 127.0.0.1) from a terminal, editor or other app opens like a typed address, and the page it shows may lead elsewhere on your network as a typed one can. Off: Tarn refuses it, since a link in a mail could reach services running here; Open Anyway on the notice still opens it. Links to other addresses on your network are refused; Open Anyway on the notice opens them. Applies to every profile.", ui::controls::THIS_DEVICE), on(Pref::LocalhostFromApps), cx))) + .child(section("Site overrides")) + .child(sites) + .child(heading("Site zoom levels", div().children(reset_zooms))) + .child(zooms) + .child(section("Muted sites")) + .child(muted) + .child(section("Hidden elements")) + .child(zapped) + .child(section("Connections Tarn makes")) + .child(connections) + .child(note("Pages you open connect wherever they link to; this list covers Tarn itself. GitHub sees your IP address when Tarn checks for filter lists; turning updates off keeps the installed lists.")) + .child(section("Your data")) + .child(data) + .child(note(s.notice.clone().unwrap_or_else(|| { + let shared = if s.shared_data { " Cookies and site data are shared with another profile and are deleted there too." } else { "" }; + format!("Delete everything removes spaces, tabs, history, cookies, site data and site settings of this profile.{shared} Files you downloaded stay in Downloads.") + }))) + .into_any_element() + } +} + +impl SettingsWindow { + pub(super) fn developer(&self, s: Snapshot, cx: &mut Context) -> AnyElement { + let on = s.developer; + let dev_profile = s.profiles.iter().find(|p| p.is_dev).map(|p| bounded_title(&p.name)); + let servers = match &s.local_servers { + None => note("Not checked yet."), + Some(ports) if ports.is_empty() => note("Nothing is listening on the common dev ports (3000, 5173, 8080 and others)."), + Some(ports) => { + let mut list = group(); + for (ix, port) in ports.iter().copied().enumerate() { + list = list.child( + row(ix == 0).child(label(format!("localhost:{port}"))).child( + button(("open-server", ix), "Open", false) + .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, w, cx| b.open_local_server(port, w, cx)))), + ), + ); + } + list + } + }; + div() + .child(section("Developer tools")) + .child(group().child( + switch_row("developer-tools", true, label("Web Inspector, JSON viewer, responsive sizes and local servers"), on) + .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, w, cx| b.set_developer(!on, w, cx)))), + )) + .child(note("Applies to every profile; open pages reload. Right-click a page and choose Inspect Element; the toolbar gains responsive sizes and Clear Site Data.")) + .child(section("Developer profile")) + .child(match dev_profile { + Some(name) => group().child(row(true).child(label(name)).child(value("Created"))), + None => group().child(row(true).child(label("A separate profile for development")).child( + button("create-dev-profile", "Create", false) + .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, w, cx| b.create_dev_profile(w, cx)))), + )), + }) + .child(note("Web Inspector and the developer tools are always on there; caches are cleared after every page load and Reload bypasses the cache.")) + .child(heading( + "Local servers", + button("refresh-servers", "Refresh", false).on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.refresh_local_servers(cx)))), + )) + .child(servers) + .into_any_element() + } +} diff --git a/crates/app/src/settings/profile_card.rs b/crates/app/src/settings/profile_card.rs new file mode 100644 index 00000000..b74993fc --- /dev/null +++ b/crates/app/src/settings/profile_card.rs @@ -0,0 +1,313 @@ +use super::*; + +fn week_chart(card: &Card) -> Div { + const BARS: f32 = 92.; + let days = browser_core::shield_card::day_totals(&card.week); + if days.iter().all(|(_, n)| *n <= 0) { + return group().child(row(true).child(text_block("Last 7 days", "Nothing stopped yet. Each day Shield stops something shows here."))); + } + let busiest = days.iter().map(|(_, n)| *n).max().unwrap_or(0); + let bars = days.iter().map(|(day, n)| { + let fill = if *n == 0 { 2. } else { (BARS * *n as f32 / busiest.max(1) as f32).max(4.) }; + let top = *n == busiest && busiest > 0; + div() + .flex_1() + .flex() + .flex_col() + .items_center() + .justify_end() + .gap_1() + .text_size(px(TEXT_TINY)) + .text_color(Theme::muted()) + .child(if *n > 0 { thousands(*n as u64) } else { String::new() }) + .child(div().w(px(22.)).h(px(fill)).rounded(px(Theme::radius_small())).bg(if top { Theme::space_label() } else { Theme::accent() })) + .child(*day) + }); + let total: i64 = days.iter().map(|(_, n)| *n).sum(); + group() + .p_4() + .gap_3() + .child( + div() + .flex() + .justify_between() + .child(div().font_weight(FontWeight::SEMIBOLD).child("Last 7 days")) + .child(value(format!("{} protected", thousands(total.max(0) as u64))).text_size(px(TEXT_SMALL))), + ) + .child(div().h(px(BARS + 34.)).flex().items_end().gap_1().children(bars)) +} + +fn protected_sites(card: &Card) -> Div { + let most = card.sites.iter().map(|(_, n)| *n).max().unwrap_or(0).max(1); + let rows = card.sites.iter().map(|(host, n)| { + let host = crate::toolbar::host_tail(&bounded_title(host), 40); + let share = (*n).max(0) as f32 / most as f32; + div() + .h(px(28.)) + .flex() + .items_center() + .gap_2() + .child(ui::controls::favicon(&host, 16.)) + .child(div().flex_none().w(px(110.)).one_line(host)) + .child( + div() + .flex_1() + .h(px(4.)) + .rounded_full() + .bg(Theme::separator()) + .child(div().h_full().w(gpui::relative(share)).rounded_full().bg(Theme::accent())), + ) + .child(value(thousands((*n).max(0) as u64)).w(px(44.)).flex_none().text_right()) + }); + group().p_4().gap_1().child(div().pb_1().font_weight(FontWeight::SEMIBOLD).child("Most protected sites")).children(rows) +} + +impl SettingsWindow { + fn card_frame(&mut self, card: &Card, reduce: bool, window: &mut Window, cx: &mut Context) -> Option> { + const RATES: [f32; 5] = [12., 12., 8., 6.5, 25.]; + let m = &mut self.motion; + let key = (card.clone(), !Theme::is_light()); + if m.faces.as_ref().is_none_or(|(k, _)| *k != key) && m.drawing.as_ref() != Some(&key) { + m.drawing = Some(key.clone()); + let card = key; + cx.spawn(async move |this, cx| { + let made = cx.background_spawn({ + let (card, dark) = card.clone(); + async move { shield_card::faces(&card, dark) } + }); + let Some(faces) = made.await else { return }; + this.update(cx, |this, cx| { + if this.motion.drawing.as_ref() == Some(&card) { + this.motion.drawing = None; + this.motion.faces = Some((card, Arc::new(faces))); + cx.notify(); + } + }) + .ok(); + }) + .detach(); + } + let faces = m.faces.as_ref()?.1.clone(); + let flip = if m.flipped { 1. } else { 0. }; + let goal = if reduce || !m.hover { [0., 0., 0., flip, 0.] } else { [m.aim.0, m.aim.1, 1., flip, if m.pressed { 1. } else { 0. }] }; + let passed = m.stepped.replace(Instant::now()).map_or(0.05, |t| t.elapsed().as_secs_f32()).min(0.05); + for ((at, goal), rate) in m.at.iter_mut().zip(goal).zip(RATES) { + *at = if reduce || (goal - *at).abs() < 0.002 { goal } else { *at + (goal - *at) * (1. - (-passed * rate).exp()) }; + } + if m.at != goal { + window.request_animation_frame(); + } + if m.drawn.as_ref().is_none_or(|(at, from, _)| *at != m.at || !Arc::ptr_eq(from, &faces)) { + let [across, down, glow, flip, press] = m.at; + let image = + Arc::new(RenderImage::new([image::Frame::new(shield_card::frame(&faces, &ui::tilt::Pose { tilt: (across, down), glow, flip, press }))])); + if let Some((_, _, old)) = m.drawn.replace((m.at, faces, image)) { + cx.drop_image(old, Some(window)); + } + } + m.drawn.as_ref().map(|(_, _, image)| image.clone()) + } + + pub(super) fn profile_tab(&mut self, s: &Snapshot, window: &mut Window, cx: &mut Context) -> AnyElement { + let Some(card) = s.card.clone() else { return note("No profile is open.").into_any_element() }; + let target = s.profile.as_ref().map(|p| (s.private, p.id)); + let frame = self.card_frame(&card, s.reduce, window, cx); + let [_, _, glow, flip, _] = self.motion.at; + let facing = (flip * std::f32::consts::PI).cos().abs(); + let (width, height, margin) = (shield_card::W as f32, shield_card::H as f32, shield_card::MARGIN as f32); + let bounds = self.motion.bounds.clone(); + let face = div() + .id("shield-card") + .relative() + .w(px(width)) + .h(px(height)) + .cursor_pointer() + .child( + div() + .absolute() + .top_0() + .h_full() + .left(px(width / 2. * (1. - facing))) + .w(px(width * facing)) + .rounded(px(18.)) + .shadow(Theme::elevation(5. + 5. * glow, 9. + 7. * glow)), + ) + .children(frame.map(|f| img(f).absolute().left(px(-margin)).top(px(-margin)).w(px(width + 2. * margin)).h(px(height + 2. * margin)))) + .child(canvas(move |at, _, _| bounds.set(at), |_, _, _, _| {}).absolute().size_full()) + .on_mouse_move(cx.listener(|this, moved: &MouseMoveEvent, _, cx| { + let card = this.motion.bounds.get(); + let from_centre = moved.position - card.center(); + this.motion.aim = ((from_centre.x / (card.size.width / 2.)).clamp(-1., 1.), (from_centre.y / (card.size.height / 2.)).clamp(-1., 1.)); + cx.notify(); + })) + .on_hover(cx.listener(|this, over: &bool, _, cx| { + this.motion.hover = *over; + this.motion.pressed &= *over; + cx.notify(); + })) + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _, _, cx| { + this.motion.pressed = true; + cx.notify(); + }), + ) + .on_click(cx.listener(|this, _, _, cx| { + this.motion.pressed = false; + this.motion.flipped ^= true; + cx.notify(); + })); + let hero = self.hero(&card, face, target, cx); + let mut page = div() + .child(hero) + .children(self.card_notice.clone().map(|n| note(n).pt_2())) + .child(div().pt_5().flex().gap_4().child(week_chart(&card).flex_1()).when(!card.sites.is_empty(), |d| d.child(protected_sites(&card).flex_1()))); + if s.default_browser == Some(false) { + page = page.child(section("Default browser")).child( + group().child( + row(true) + .child(text_block("Tarn isn't your default browser", "Links from other apps open in another browser.")) + .child(button("make-default", "Make Default", true).on_click(cx.listener(|this, _, _, cx| this.make_default(cx)))), + ), + ); + } + let levels = self.shield_levels(s, cx); + let to_privacy = + |id: &'static str, text: &'static str| button(id, text, false).on_click(cx.listener(|this, _, _, cx| this.set_pane(SettingsPane::Privacy, cx))); + let overrides = match s.overrides.len() { + 0 => "None".to_owned(), + 1 => "1 site".to_owned(), + n => format!("{n} sites"), + }; + page = page + .child(note({ + let kept = if s.private { "Counts stay in memory and are gone once the private space closes.".to_owned() } else { format!("Counted on {} only and never sent anywhere.", ui::controls::THIS_DEVICE) }; + if cfg!(windows) { + format!("{kept} Only what Tarn stops itself counts.") + } else { + format!("{kept} Only what Tarn stops itself counts: ad and tracker blocks in WebKit tabs are not counted, because WebKit does not report what its blocking rules stop.") + } + })) + .child(section("Shield level")) + .child(levels) + .child(note("Applies to this profile. Open pages reload with the new level.")) + .child(section("Shield")) + .child( + group() + .child(row(true).child(label("Site overrides")).child(value(overrides)).child(to_privacy("shield-change", "Change…"))) + .child(row(false).child(text_block("Filter lists", s.filters.summary()))), + ); + let filter_lists = match (filters::configured(), s.filters.updates) { + (false, _) => "Not set up", + (true, true) => "GitHub, once a day", + (true, false) => "Off", + }; + let updates = match (s.updater, s.update_checks) { + (false, _) => "Not set up", + (true, true) => "GitHub, once a day", + (true, false) => "Only when you ask", + }; + page.child(section("Connections Tarn makes")) + .child( + group() + .child(row(true).child(label("Filter-list updates")).child(value(filter_lists))) + .child(row(false).child(label("Extensions and themes")).child(value(if s.extension_downloads { + "GitHub, when you install" + } else { + "Off" + }))) + .child(row(false).child(label("Site icons")).child(value("The site you are on or its CDN"))) + .child(row(false).child(label("Update checks")).child(value(updates))) + .child( + row(false) + .child(text_block("Nothing else", "No accounts, no telemetry, no AI requests.")) + .child(to_privacy("connections-details", "Details…")), + ), + ) + .into_any_element() + } + + fn hero(&self, card: &Card, face: impl IntoElement, target: Option<(bool, Id)>, cx: &mut Context) -> Div { + let private = target.is_some_and(|(private, _)| private); + let since = match (card.days, &card.since) { + (Some(days), Some(since)) => browser_core::shield_card::protected_text(days, since), + _ if private => "Counts stay in memory until the private space closes.".to_owned(), + _ => "Counting starts with the first thing Shield stops.".to_owned(), + }; + let saved = card.clone(); + let shared = card.clone(); + let system = cfg!(target_os = "macos"); + let share = if system { "Share Card" } else { "Save as Image" }; + let action = |id: &'static str, glyph, text: &'static str| tab_stop(icon_text_button(id, glyph, text)).justify_center(); + let actions = div() + .grid() + .grid_cols(2) + .gap_2() + .child(action("flip-card", Icon::Reload, "Flip").on_click(cx.listener(|this, _, _, cx| { + this.motion.flipped ^= true; + cx.notify(); + }))) + .child(action("new-design", Icon::Palette, "Change Design").on_click(cx.listener(move |this, _, _, cx| { + let Some((private, id)) = target else { return }; + this.with_browser(cx, |b, _, cx| { + b.store(private).new_shield_design(id).ok(); + shield_card::touch(); + cx.notify(); + }); + }))) + .when(!private, |d| { + d.child(action("share-card", if system { Icon::Share } else { Icon::FileImage }, share).on_click(cx.listener(move |this, _, window, cx| { + if system { + this.share_card(shared.clone(), window, cx); + } else { + this.save_card(shared.clone(), cx); + } + }))) + }) + .when(system && !private, |d| { + d.child(action("save-card", Icon::FileImage, "Save as Image").on_click(cx.listener(move |this, _, _, cx| this.save_card(saved.clone(), cx)))) + }); + div().pt_4().flex().flex_wrap().items_start().gap_6().child(face).child( + div() + .flex_1() + .min_w(px(300.)) + .flex() + .flex_col() + .gap_3() + .child( + div() + .child(div().text_size(px(TEXT_HEADING)).font_weight(FontWeight::BOLD).one_line(card.name.clone())) + .child(value(since).text_size(px(TEXT_SMALL))), + ) + .child(actions), + ) + } + + fn share_card(&mut self, card: Card, window: &mut Window, cx: &mut Context) { + let Some(host) = engine::Host::from_window(window) else { return }; + let at = self.motion.bounds.get(); + cx.spawn(async move |this, cx| { + let name = engine::downloads::sanitize_filename(&format!("Tarn Shield {}.png", card.name)); + let dark = !Theme::is_light(); + let written = cx + .background_spawn(async move { + let png = shield_card::card_png(&card, dark)?; + let path = browser_core::shield_card::export_path(&name).ok()?; + std::fs::write(&path, png).ok()?; + url::Url::from_file_path(path).ok() + }) + .await; + let Some(url) = written else { + this.update(cx, |this, cx| { + this.card_notice = Some("Could not draw the image.".into()); + cx.notify(); + }) + .ok(); + return; + }; + let (x, y, w, h) = (f32::from(at.origin.x), f32::from(at.origin.y), f32::from(at.size.width), f32::from(at.size.height)); + host.share(url.as_str(), x.into(), y.into(), w.into(), h.into()); + }) + .detach(); + } +} diff --git a/crates/app/src/settings/shortcuts.rs b/crates/app/src/settings/shortcuts.rs new file mode 100644 index 00000000..e821e07e --- /dev/null +++ b/crates/app/src/settings/shortcuts.rs @@ -0,0 +1,123 @@ +use super::*; + +impl SettingsWindow { + pub(super) fn shortcuts(&mut self, cx: &mut Context) -> AnyElement { + let stored = crate::shortcuts::stored(&crate::shared::core(cx).disk); + let defaults = keymap::keymap(&crate::shortcuts::MAC, &Default::default()); + let changed: Vec = + keymap::keymap(&crate::shortcuts::MAC, &stored).into_iter().zip(&defaults).filter(|((k, _), (d, _))| k != d).map(|((_, a), _)| a).collect(); + let recording = self.recording.as_ref().map(|(a, _)| *a); + let mut n = 0usize; + let mut pane = div() + .child( + div() + .pt_3() + .flex() + .items_center() + .gap_3() + .child( + note(if cfg!(windows) { + "Click a shortcut and press the new keys, with Ctrl, or Alt with Shift or a digit; Esc cancels." + } else { + "Click a shortcut and press the new keys, with ⌘ or ⌃; Esc cancels." + }) + .flex_grow() + .flex_basis(px(0.)) + .pt_0(), + ) + .when(!changed.is_empty(), |d| { + d.child(button("shortcut-reset-all", "Reset All", false).on_click(cx.listener(|this, _, _, cx| this.reset_shortcuts(None, cx)))) + }), + ) + .children(self.shortcut_error.clone().map(|e| note(e).text_color(Theme::warning()))); + for (title, items) in crate::shortcuts::sections() { + let mut list = group(); + for (ix, (name, keys)) in items.iter().enumerate() { + let mut line = row(ix == 0).child(label(*name)); + line = match keys { + Fixed(keys) => line.child(value(ui::controls::keys(keys))), + Bound(action) => { + let action = *action; + n += 1; + let on = recording == Some(action); + let custom = changed.contains(&action); + let shown = match crate::shortcuts::gpui_action(action) { + _ if on => "Press keys…".to_owned(), + Some(gpui) => crate::shortcuts::shown(gpui, cx), + None => String::new(), + }; + line.child( + div() + .flex() + .items_center() + .gap_2() + .when(custom, |d| { + d.child( + button(("shortcut-reset", n), "Reset", false) + .on_click(cx.listener(move |this, _, _, cx| this.reset_shortcuts(Some(action), cx))), + ) + }) + .child(button(("shortcut", n), shown, on).on_click(cx.listener(move |this, _, window, cx| this.record(action, window, cx)))), + ) + } + }; + list = list.child(line); + } + pane = pane.child(section(title)).child(list); + } + pane.into_any_element() + } + + fn record(&mut self, action: Shortcut, window: &mut Window, cx: &mut Context) { + let me = cx.entity().downgrade(); + let settings = window.window_handle().window_id(); + let interceptor = cx.intercept_keystrokes(move |event, window, cx| { + if window.window_handle().window_id() != settings { + me.update(cx, |this, cx| { + if let Some((_, interceptor)) = this.recording.take() { + cx.defer(move |_| drop(interceptor)); + cx.notify(); + } + }) + .ok(); + return; + } + cx.stop_propagation(); + let keystroke = event.keystroke.clone(); + if me.update(cx, |this, cx| this.recorded(&keystroke, cx)).unwrap_or(false) { + cx.defer(crate::shortcuts::rebind); + } + }); + self.recording = Some((action, interceptor)); + self.shortcut_error = None; + cx.notify(); + } + + fn recorded(&mut self, keystroke: &gpui::Keystroke, cx: &mut Context) -> bool { + let Some((action, interceptor)) = self.recording.take() else { return false }; + cx.defer(move |_| drop(interceptor)); + cx.notify(); + if keystroke.key == "escape" && keystroke.modifiers == gpui::Modifiers::none() { + return false; + } + if cfg!(windows) && keystroke.modifiers.platform { + self.shortcut_error = Some("The Windows key belongs to Windows; use Ctrl, or Alt with Shift or a digit.".to_owned()); + return false; + } + let disk = &crate::shared::core(cx).disk; + match keymap::save(&crate::shortcuts::MAC, disk, action, &crate::shortcuts::canonical(&keystroke.unparse())) { + Ok(()) => true, + Err(e) => { + self.shortcut_error = Some(e); + false + } + } + } + + fn reset_shortcuts(&mut self, action: Option, cx: &mut Context) { + self.recording = None; + self.shortcut_error = keymap::reset(&crate::shortcuts::MAC, &crate::shared::core(cx).disk, action).err(); + cx.defer(crate::shortcuts::rebind); + cx.notify(); + } +} diff --git a/crates/sync/src/file.rs b/crates/sync/src/file.rs index 47e16172..851dc541 100644 --- a/crates/sync/src/file.rs +++ b/crates/sync/src/file.rs @@ -3,7 +3,7 @@ use chacha20poly1305::aead::{Aead, KeyInit, Payload}; use chacha20poly1305::{XChaCha20Poly1305, XNonce}; use zeroize::Zeroizing; -use crate::{Snapshot, SyncError}; +use crate::model::{Snapshot, SyncError}; const MAGIC: &[u8; 8] = b"TARNSYNC"; const VERSION: u16 = 1; diff --git a/crates/sync/src/lib.rs b/crates/sync/src/lib.rs index f24a7b8e..f35249a2 100644 --- a/crates/sync/src/lib.rs +++ b/crates/sync/src/lib.rs @@ -2,16 +2,17 @@ #![forbid(unsafe_code)] mod file; +mod model; use std::collections::BTreeMap; use std::time::{SystemTime, UNIX_EPOCH}; use engine::nav_policy::{Decision, Source, decide}; -use serde::{Deserialize, Serialize}; use shield::ShieldLevel; use url::Url; pub use file::{KdfParams, MAX_FILE_LEN, SALT_LEN, SyncKey, header_kdf, open, open_with_key, seal, seal_with_key}; +pub use model::{Folder, Meta, Setting, Snapshot, Space, SyncError, SyncId, Tab, TabKind}; pub const MAX_SPACES: usize = 100; pub const MAX_FOLDERS: usize = 2_000; @@ -23,96 +24,6 @@ pub const MAX_URL_LEN: usize = 8_192; /// How far ahead of this device's clock a remote timestamp may be. pub const MAX_CLOCK_SKEW_MS: i64 = 24 * 60 * 60 * 1000; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum SyncError { - TooLarge, - Truncated, - BadMagic, - UnsupportedVersion, - WeakKdf, - CostlyKdf, - /// Wrong passphrase or tampered file; the two cannot be told apart. - Decrypt, - /// The file belongs to another sync set or passphrase (different salt or KDF parameters). - KeyMismatch, - Malformed, - TooMany, - TooLong, - BadId, - /// A timestamp is negative or too far in the future; it would win every later merge. - BadTime, - Rng, -} - -/// 32 lowercase hex characters (UUID v4, simple form). -pub type SyncId = String; - -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -pub struct Meta { - /// Milliseconds since the Unix epoch. - pub updated_at: i64, - pub device: SyncId, - pub deleted: bool, -} - -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -pub struct Space { - pub id: SyncId, - pub name: String, - pub icon: String, - pub position: i64, - pub meta: Meta, -} - -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -pub struct Folder { - pub id: SyncId, - pub space: SyncId, - pub parent: Option, - pub name: String, - pub position: i64, - pub meta: Meta, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum TabKind { - Tile, - Pinned, -} - -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -pub struct Tab { - pub id: SyncId, - pub space: SyncId, - pub folder: Option, - pub kind: TabKind, - pub url: String, - pub title: String, - pub position: i64, - pub meta: Meta, -} - -/// Keys: `shield_level`, `site_override:`; values: Shield level names. -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -pub struct Setting { - pub key: String, - pub value: String, - pub meta: Meta, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct Snapshot { - pub device: SyncId, - /// Incremented by the writing device on every write. Rejecting a lower value than last seen - /// from this device (rollback) and checking `device` against the file name is the caller's job. - pub seq: u64, - pub spaces: Vec, - pub folders: Vec, - pub tabs: Vec, - pub settings: Vec, -} - trait Item: Ord { fn key(&self) -> &str; fn meta(&self) -> &Meta; diff --git a/crates/sync/src/model.rs b/crates/sync/src/model.rs new file mode 100644 index 00000000..d00360a9 --- /dev/null +++ b/crates/sync/src/model.rs @@ -0,0 +1,91 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SyncError { + TooLarge, + Truncated, + BadMagic, + UnsupportedVersion, + WeakKdf, + CostlyKdf, + /// Wrong passphrase or tampered file; the two cannot be told apart. + Decrypt, + /// The file belongs to another sync set or passphrase (different salt or KDF parameters). + KeyMismatch, + Malformed, + TooMany, + TooLong, + BadId, + /// A timestamp is negative or too far in the future; it would win every later merge. + BadTime, + Rng, +} + +/// 32 lowercase hex characters (UUID v4, simple form). +pub type SyncId = String; + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct Meta { + /// Milliseconds since the Unix epoch. + pub updated_at: i64, + pub device: SyncId, + pub deleted: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct Space { + pub id: SyncId, + pub name: String, + pub icon: String, + pub position: i64, + pub meta: Meta, +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct Folder { + pub id: SyncId, + pub space: SyncId, + pub parent: Option, + pub name: String, + pub position: i64, + pub meta: Meta, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum TabKind { + Tile, + Pinned, +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct Tab { + pub id: SyncId, + pub space: SyncId, + pub folder: Option, + pub kind: TabKind, + pub url: String, + pub title: String, + pub position: i64, + pub meta: Meta, +} + +/// Keys: `shield_level`, `site_override:`; values: Shield level names. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct Setting { + pub key: String, + pub value: String, + pub meta: Meta, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Snapshot { + pub device: SyncId, + /// Incremented by the writing device on every write. Rejecting a lower value than last seen + /// from this device (rollback) and checking `device` against the file name is the caller's job. + pub seq: u64, + pub spaces: Vec, + pub folders: Vec, + pub tabs: Vec, + pub settings: Vec, +} diff --git a/docs/port-backlog.md b/docs/port-backlog.md index 105fa1c0..acee1afe 100644 --- a/docs/port-backlog.md +++ b/docs/port-backlog.md @@ -145,7 +145,7 @@ page instead of a banner that moves it, only while the tab that was in front is download's toast disappears after 5 seconds, a warning stays until dismissed and nothing replaces it. Toasts about downloads keep the security colours (S29). Shared API: `browser_core::toast::download`. -Reference: `crates/app/src/browser.rs` (`notify_download`), `crates/app/src/toast.rs` (`show_tab_toast`, +Reference: `crates/app/src/browser/views.rs` (`notify_download`), `crates/app/src/toast.rs` (`show_tab_toast`, `secure_card`). - [x] Windows — same code in `crates/app` @@ -159,7 +159,7 @@ Reference: `crates/app/src/browser.rs` (`notify_download`), `crates/app/src/toas What it does: Settings › Privacy › Passkeys and security keys (on by default) turns WebAuthn sign-in on or off for pages; off, `PublicKeyCredential` is gone from pages once they reload. Shared API: `browser_core::settings::{PASSKEYS, PASSKEYS_NOTE, passkeys}`; `engine::WebView::set_passkeys`. -Reference: `crates/app/src/browser/context.rs` (`view_prefs`), `crates/app/src/settings.rs` (Sign-in), +Reference: `crates/app/src/browser/context.rs` (`view_prefs`), `crates/app/src/settings/privacy.rs` (Sign-in), `crates/engine/src/webview.rs` (`set_passkeys`). - [ ] Windows and macOS Chromium tabs — CEF has no per-view WebAuthn switch; Chromium's @@ -179,7 +179,7 @@ script of Tarn's runs on the page. Shared API: `engine::page_scripts::{PAGE_KEEP, page_keep, PageKeep, scroll_script}`; `engine::WebView::{page_keep, scroll_to}`. Reference: `crates/app/src/tabs.rs` (`sleep_keeping_scroll`), `crates/app/src/browser.rs` -(`PageState::scroll_back`, `Event::Finished`). +(`PageState::scroll_back`), `crates/app/src/browser/events.rs` (`Event::Finished`). - [x] Windows — same code in `crates/app`, `crates/engine/src/view_windows.rs` - [ ] Linux — run `PAGE_KEEP` in the isolated world before `sleep_tab` / `unload` in @@ -206,7 +206,7 @@ responsive sizes, local servers) and the Developer profile; the Web Inspector ne pages. Shared API: `devkit::SETTING`, `Store::create_dev_profile`, `Profile::is_dev`; `tarn_nsh_shared::panes::Pane::Developer`. -macOS reference: `crates/app/src/settings.rs` (`developer`); Linux: `linux/src/browser/devtools.rs`, +macOS reference: `crates/app/src/settings/privacy.rs` (`developer`); Linux: `linux/src/browser/devtools.rs`, `linux/src/ui/settings.rs`. - [x] Windows — same code in `crates/app` @@ -236,7 +236,7 @@ What it does: the share menu saves the page as a PDF (listed in Downloads) and o dialog. Shared API: `browser_core::text::capture_name` (the PDF's file name); web view operations `pdf` and `print` (`docs/shared-core.md` §1). -macOS reference: `crates/app/src/share.rs`, `crates/app/src/capture.rs`, `crates/app/src/browser.rs` (`print`). +macOS reference: `crates/app/src/share.rs`, `crates/app/src/capture.rs`, `crates/app/src/browser/events.rs` (`print`). - [x] Windows - [x] Linux @@ -252,7 +252,7 @@ search, rename, move, delete and New Folder. Shared API: `browser_core::bookmarks::{bookmark, unbookmark, bookmark_all, new_folder, move_targets, subtree, recent, search, save_for_later, reading_list_pages, title_or_host}`; `store::Store::{rename_bookmark, move_bookmark, delete_bookmark}`. -macOS reference: `crates/app/src/library.rs` (`Page::Bookmarks`, `row_menu`), `crates/app/src/menubar.rs` (Bookmarks menu). +macOS reference: `crates/app/src/library.rs` (`Page::Bookmarks`), `crates/app/src/library/actions.rs` (`row_menu`), `crates/app/src/menubar.rs` (Bookmarks menu). - [x] Windows — same code in `crates/app` - [x] Linux — `linux/src/ui/library.rs` (`bookmarks_panel`), `linux/src/browser/bookmarks.rs` diff --git a/linux/src/webview/mod.rs b/linux/src/webview/mod.rs index d9ef880f..df388638 100644 --- a/linux/src/webview/mod.rs +++ b/linux/src/webview/mod.rs @@ -563,6 +563,93 @@ fn opener(state: &State, page: Option<&Url>) -> Site { Site { popups: if site.popups == PopupRule::Allow { PopupRule::Default } else { site.popups }, ..site } } +fn opens_popup(state: &Rc, action: &webkit6::NavigationAction, nav_type: NavigationType, uri: &str, gesture: bool, link: bool) -> bool { + let peek = gesture && is_peek(action); + if link && gesture && (peek || action.mouse_button() == 2 || action.modifiers() & CONTROL_MASK != 0) { + open_popup(state, uri, true, nav_type == NavigationType::LinkClicked, false, peek, false); + return true; + } + false +} + +fn gated(state: &Rc, uri: &str, blocked: Option, main_frame: bool, from_shell: bool) -> bool { + match nav_policy::gate(blocked, main_frame, from_shell, false) { + GateAction::Allow => false, + GateAction::Warn(category) | GateAction::Notice(category) => { + state.listed(uri, category); + true + } + GateAction::Cancel => true, + } +} + +fn store_install_intercepted(state: &Rc, url: &Url, store: engine::nav_policy::StoreNav) -> bool { + if engine::nav_policy::store_link_asks(store) + && let Some(id) = engine::tarn_ext::store_install(url) + { + state.emit(engine::tarn_ext::STORE_EVENT, json!({ "id": id })); + return true; + } + false +} + +fn allow_navigation(state: &Rc, web: &WebView, action: &webkit6::NavigationAction, url: &Url, javascript: bool, main_frame: bool) { + let nav_type = action.navigation_type(); + let form = matches!(nav_type, NavigationType::FormSubmitted | NavigationType::FormResubmitted); + let get = action.request().and_then(|r| r.http_method()).is_none_or(|m| m.eq_ignore_ascii_case("GET")); + if form && !get { + *state.posted.borrow_mut() = Some(url.clone()); + } + if !javascript && let Some(settings) = WebViewExt::settings(web) { + settings.set_enable_javascript(false); + } + if main_frame { + state.main_pending.set(true); + } +} + +fn upgrade_navigation(state: &Rc, web: &WebView, target: Url, nav: &Navigation) { + state.shielded("https_upgrade", target.as_str()); + *state.upgraded.borrow_mut() = Some((target.to_string(), nav.user_link, nav.from_shell || nav.user_step)); + if nav.from_shell { + *state.shell_url.borrow_mut() = Some(target.to_string()); + } + let web = web.clone(); + glib::idle_add_local_once(move || web.load_uri(target.as_str())); +} + +fn apply_verdict( + state: &Rc, + web: &WebView, + action: &webkit6::NavigationAction, + nav: &Navigation, + uri: &str, + main_frame: bool, + verdict: Verdict, +) -> bool { + match verdict { + Verdict::Allow { javascript } => { + allow_navigation(state, web, action, nav.url, javascript, main_frame); + return false; + } + Verdict::Blocked(reason) => { + if reason == "local_network" { + state.shielded("local_network", uri); + } + state.emit("blocked", json!({ "url": uri, "reason": reason })) + } + Verdict::Rebuild => state.emit("blocked", json!({ "url": uri, "reason": "rebuild" })), + Verdict::External => { + if nav.from_shell || state.admit_prompt() { + let origin = if nav.from_shell { String::new() } else { state.origin() }; + state.emit("external", json!({ "url": uri, "origin": origin })); + } + } + Verdict::Upgrade(target) => upgrade_navigation(state, web, target, nav), + } + true +} + fn decide_navigation(state: &Rc, web: &WebView, decision: &webkit6::PolicyDecision) -> bool { let Some((action, uri)) = navigation_uri(decision) else { decision.ignore(); @@ -573,9 +660,7 @@ fn decide_navigation(state: &Rc, web: &WebView, decision: &webkit6::Polic let nav_type = action.navigation_type(); let gesture = action.is_user_gesture(); let link = matches!(nav_type, NavigationType::LinkClicked | NavigationType::FormSubmitted); - let peek = gesture && is_peek(&action); - if link && gesture && (peek || action.mouse_button() == 2 || action.modifiers() & CONTROL_MASK != 0) { - open_popup(state, &uri, true, nav_type == NavigationType::LinkClicked, false, peek, false); + if opens_popup(state, &action, nav_type, &uri, gesture, link) { decision.ignore(); return true; } @@ -592,23 +677,8 @@ fn decide_navigation(state: &Rc, web: &WebView, decision: &webkit6::Polic let redirect = action.is_redirect(); let main_frame = from_shell || step || gesture || upgraded.is_some() || (redirect && state.main_pending.get()); let site = state.site(&url); - match nav_policy::gate(site.blocked, main_frame, from_shell, false) { - GateAction::Allow => {} - GateAction::Warn(category) | GateAction::Notice(category) => { - state.listed(&uri, category); - decision.ignore(); - return true; - } - GateAction::Cancel => { - decision.ignore(); - return true; - } - } let store = engine::nav_policy::StoreNav { redirect, shell_load: from_shell, page_link, clicked: nav_type == NavigationType::LinkClicked && gesture }; - if engine::nav_policy::store_link_asks(store) - && let Some(id) = engine::tarn_ext::store_install(&url) - { - state.emit(engine::tarn_ext::STORE_EVENT, json!({ "id": id })); + if gated(state, &uri, site.blocked, main_frame, from_shell) || store_install_intercepted(state, &url, store) { decision.ignore(); return true; } @@ -626,46 +696,11 @@ fn decide_navigation(state: &Rc, web: &WebView, decision: &webkit6::Polic file_open, }; let verdict = policy::navigation(&state.levels.borrow(), state.level.get(), &nav); - match verdict { - Verdict::Allow { javascript } => { - let form = matches!(nav_type, NavigationType::FormSubmitted | NavigationType::FormResubmitted); - let get = action.request().and_then(|r| r.http_method()).is_none_or(|m| m.eq_ignore_ascii_case("GET")); - if form && !get { - *state.posted.borrow_mut() = Some(url.clone()); - } - if !javascript && let Some(settings) = WebViewExt::settings(web) { - settings.set_enable_javascript(false); - } - if main_frame { - state.main_pending.set(true); - } - return false; - } - Verdict::Blocked(reason) => { - if reason == "local_network" { - state.shielded("local_network", &uri); - } - state.emit("blocked", json!({ "url": uri, "reason": reason })) - } - Verdict::Rebuild => state.emit("blocked", json!({ "url": uri, "reason": "rebuild" })), - Verdict::External => { - if from_shell || state.admit_prompt() { - let origin = if from_shell { String::new() } else { state.origin() }; - state.emit("external", json!({ "url": uri, "origin": origin })); - } - } - Verdict::Upgrade(target) => { - state.shielded("https_upgrade", target.as_str()); - *state.upgraded.borrow_mut() = Some((target.to_string(), nav.user_link, nav.from_shell || nav.user_step)); - if from_shell { - *state.shell_url.borrow_mut() = Some(target.to_string()); - } - let web = web.clone(); - glib::idle_add_local_once(move || web.load_uri(target.as_str())); - } + let ignore = apply_verdict(state, web, &action, &nav, &uri, main_frame, verdict); + if ignore { + decision.ignore(); } - decision.ignore(); - true + ignore } fn prompt(state: &Rc, pending: Pending, data: JsonValue) {