//! Clearwake: a quieter browser. //! //! One Rust program for Mac, Windows, Linux, Android and the web. Pages are //! read by `clearwake-core` into clean text, links and pictures. Scripts //! never run, ads and trackers are never loaded, and there is no switch to //! turn that off. mod net; mod ui; use clearwake_core::bookmarks::Bookmarks; use clearwake_core::history::History; use clearwake_core::html::{self, Document}; use clearwake_core::{Filter, Url}; use egui::TextureHandle; use net::{Body, Done, Inbox, Job, Kind, Loader}; use std::collections::HashMap; use std::sync::{Arc, Mutex}; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); pub enum Page { Home, Loading { url: String }, Doc(Document), Picture { url: String }, Text { url: String, text: String }, Error { url: String, message: String }, } pub enum Picture { Loading, Ready(TextureHandle), Failed, } pub struct Clearwake { filter: Arc, loader: Loader, inbox: Inbox, generation: u64, page: Page, history: History, bookmarks: Bookmarks, pictures: HashMap, address: String, address_focus: bool, forms: HashMap, home_search: String, hover: Option, blocked_total: u64, text_scale: f32, dark: Option, show_bookmarks: bool, scroll_to_top: bool, #[cfg(target_os = "android")] keyboard_shown: bool, } impl Clearwake { pub fn new(cc: &eframe::CreationContext<'_>, start: Option) -> Clearwake { let filter = Arc::new(Filter::new()); let inbox: Inbox = Arc::new(Mutex::new(Vec::new())); let loader = Loader::new(inbox.clone(), cc.egui_ctx.clone(), filter.clone()); let mut app = Clearwake { filter, loader, inbox, generation: 0, page: Page::Home, history: History::default(), bookmarks: Bookmarks::default(), pictures: HashMap::new(), address: String::new(), address_focus: true, forms: HashMap::new(), home_search: String::new(), hover: None, blocked_total: 0, text_scale: 1.0, dark: None, show_bookmarks: false, scroll_to_top: false, #[cfg(target_os = "android")] keyboard_shown: false, }; if let Some(storage) = cc.storage { if let Some(t) = storage.get_string("bookmarks") { app.bookmarks = Bookmarks::from_text(&t); } if let Some(s) = storage.get_string("text_scale").and_then(|s| s.parse::().ok()) { app.text_scale = s.clamp(0.7, 2.0); } app.dark = match storage.get_string("look").as_deref() { Some("dark") => Some(true), Some("light") => Some(false), _ => None, }; if let Some(n) = storage.get_string("blocked_total").and_then(|s| s.parse().ok()) { app.blocked_total = n; } } ui::install_style(&cc.egui_ctx, app.dark); app.history.visit(String::from("about:home")); if let Some(s) = start { app.address_focus = false; app.open_input(&s); } app } /// Open what the person typed in the address bar or the home search. pub fn open_input(&mut self, input: &str) { if let Some(u) = clearwake_core::resolve_input(input) { self.open(u.to_string(), true); } } /// Open an address. `record` adds it to back/forward history. pub fn open(&mut self, url: String, record: bool) { self.generation += 1; self.forms.clear(); self.pictures.clear(); self.hover = None; self.show_bookmarks = false; self.scroll_to_top = true; if record { self.history.visit(url.clone()); } self.address = if url == "about:home" { String::new() } else { url.clone() }; if url == "about:home" { self.page = Page::Home; return; } match Url::parse(&url) { Some(u) if self.filter.blocks(&u) => { self.blocked_total += 1; self.page = Page::Error { url, message: String::from("Clearwake blocked this address because it serves ads or tracking.") }; } Some(_) => { self.page = Page::Loading { url: url.clone() }; self.loader.load(Job { generation: self.generation, kind: Kind::Page, url }); } None => { self.page = Page::Error { url, message: String::from("Clearwake only opens web addresses (http and https).") }; } } } pub fn back(&mut self) { if let Some(u) = self.history.back() { self.open(u, false); } } pub fn forward(&mut self) { if let Some(u) = self.history.forward() { self.open(u, false); } } pub fn reload(&mut self) { if let Some(u) = self.history.current().map(|s| s.to_string()) { self.open(u, false); } } pub fn current_url(&self) -> Option { match &self.page { Page::Home => None, Page::Loading { url } | Page::Picture { url } | Page::Text { url, .. } | Page::Error { url, .. } => Some(url.clone()), Page::Doc(d) => Some(d.url.to_string()), } } pub fn current_title(&self) -> String { match &self.page { Page::Doc(d) if !d.title.is_empty() => d.title.clone(), _ => self.current_url().unwrap_or_default(), } } fn receive(&mut self, ctx: &egui::Context) { let done: Vec = std::mem::take(&mut *self.inbox.lock().unwrap()); for d in done { if d.job.generation != self.generation { continue; } match d.job.kind { Kind::Page => self.page_arrived(ctx, d.job.url, d.result), Kind::Image => { let pic = match d.result { Ok(Body::Image { width, height, rgba }) => { let img = egui::ColorImage::from_rgba_unmultiplied([width, height], &rgba); Picture::Ready(ctx.load_texture(d.job.url.clone(), img, egui::TextureOptions::LINEAR)) } Err(e) if e.contains("blocked") => { self.blocked_total += 1; Picture::Failed } _ => Picture::Failed, }; self.pictures.insert(d.job.url, pic); } } } } fn page_arrived(&mut self, ctx: &egui::Context, asked: String, result: Result) { match result { Err(message) => { if message.contains("blocked") { self.blocked_total += 1; } self.page = Page::Error { url: asked, message }; } Ok(Body::Image { .. }) => {} Ok(Body::Page { url, content_type, bytes }) => { if url != asked { self.history.replace(url.clone()); } self.address = url.clone(); let ct = content_type.to_ascii_lowercase(); let sniff_html = { let head = String::from_utf8_lossy(&bytes[..bytes.len().min(512)]).to_ascii_lowercase(); head.contains(" { let img = egui::ColorImage::from_rgba_unmultiplied([width, height], &rgba); self.pictures.insert(url.clone(), Picture::Ready(ctx.load_texture(url, img, egui::TextureOptions::LINEAR))); } _ => { self.pictures.insert(url, Picture::Failed); } } } else if ct.contains("html") || ct.contains("xml") || (ct.is_empty() && sniff_html) || sniff_html { let text = html::decode_bytes(&bytes, &content_type); let base = Url::parse(&url).unwrap_or_else(|| Url::parse("about:blank").unwrap()); let doc = html::parse(&text, &base, &self.filter); self.blocked_total += doc.stats.blocked as u64; for (i, src) in doc.image_urls().into_iter().enumerate() { if i >= 80 { break; } self.pictures.insert(src.clone(), Picture::Loading); self.loader.load(Job { generation: self.generation, kind: Kind::Image, url: src }); } self.page = Page::Doc(doc); } else if ct.starts_with("text/") || ct.contains("json") || ct.is_empty() { self.page = Page::Text { url, text: String::from_utf8_lossy(&bytes).into_owned() }; } else { self.page = Page::Error { url, message: String::from("This is a file, not a page. Clearwake doesn't download files."), }; } } } } } impl eframe::App for Clearwake { fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { let ctx = ui.ctx().clone(); self.receive(&ctx); ui::shortcuts(self, &ctx); ui::toolbar(self, ui); ui::status_bar(self, ui); ui::content(self, ui); let title = match &self.page { Page::Home => String::from("Clearwake"), _ => { let t = self.current_title(); if t.is_empty() { String::from("Clearwake") } else { format!("{t} — Clearwake") } } }; ctx.send_viewport_cmd(egui::ViewportCommand::Title(title)); #[cfg(target_os = "android")] android_keyboard(&ctx, &mut self.keyboard_shown); } fn save(&mut self, storage: &mut dyn eframe::Storage) { storage.set_string("bookmarks", self.bookmarks.to_text()); storage.set_string("text_scale", self.text_scale.to_string()); storage.set_string( "look", match self.dark { Some(true) => "dark", Some(false) => "light", None => "system", } .to_string(), ); storage.set_string("blocked_total", self.blocked_total.to_string()); } } /// Window options shared by the computer and phone builds. #[cfg(not(target_arch = "wasm32"))] pub fn native_options() -> eframe::NativeOptions { let icon = ui::app_icon(); eframe::NativeOptions { viewport: egui::ViewportBuilder::default() .with_title("Clearwake") .with_app_id("ai.clearwake.Clearwake") .with_inner_size([1180.0, 820.0]) .with_min_inner_size([360.0, 420.0]) .with_icon(icon), ..Default::default() } } #[cfg(target_os = "android")] static ANDROID: std::sync::OnceLock = std::sync::OnceLock::new(); /// Show the phone's keyboard while a text field is being typed in. #[cfg(target_os = "android")] fn android_keyboard(ctx: &egui::Context, shown: &mut bool) { let want = ctx.egui_wants_keyboard_input(); if want != *shown { if let Some(app) = ANDROID.get() { if want { app.show_soft_input(true); } else { app.hide_soft_input(true); } } *shown = want; } } #[cfg(target_os = "android")] #[unsafe(no_mangle)] fn android_main(app: winit::platform::android::activity::AndroidApp) { let _ = ANDROID.set(app.clone()); let mut options = native_options(); options.android_app = Some(app); let _ = eframe::run_native("Clearwake", options, Box::new(|cc| Ok(Box::new(Clearwake::new(cc, None))))); } #[cfg(target_arch = "wasm32")] mod web_start { use super::*; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; #[wasm_bindgen(start)] pub fn start() { let window = web_sys::window().expect("window"); let document = window.document().expect("document"); let canvas = document .get_element_by_id("clearwake") .expect("canvas") .dyn_into::() .expect("canvas element"); let start = window.location().hash().ok().and_then(|h| { let h = h.trim_start_matches('#'); if h.is_empty() { None } else { Some(clearwake_core::url::decode_component(h)) } }); wasm_bindgen_futures::spawn_local(async move { let runner = eframe::WebRunner::new(); let _ = runner .start(canvas, eframe::WebOptions::default(), Box::new(move |cc| Ok(Box::new(Clearwake::new(cc, start))))) .await; if let Some(el) = web_sys::window().and_then(|w| w.document()).and_then(|d| d.get_element_by_id("loading")) { el.remove(); } }); } }