Clearwake / app / crates / clearwake-app / src / lib.rs
| 1 | //! Clearwake: a quieter browser. |
| 2 | //! |
| 3 | //! One Rust program for Mac, Windows, Linux, Android and the web. Pages are |
| 4 | //! read by `clearwake-core` into clean text, links and pictures. Scripts |
| 5 | //! never run, ads and trackers are never loaded, and there is no switch to |
| 6 | //! turn that off. |
| 7 | |
| 8 | mod net; |
| 9 | mod ui; |
| 10 | |
| 11 | use clearwake_core::bookmarks::Bookmarks; |
| 12 | use clearwake_core::history::History; |
| 13 | use clearwake_core::html::{self, Document}; |
| 14 | use clearwake_core::{Filter, Url}; |
| 15 | use egui::TextureHandle; |
| 16 | use net::{Body, Done, Inbox, Job, Kind, Loader}; |
| 17 | use std::collections::HashMap; |
| 18 | use std::sync::{Arc, Mutex}; |
| 19 | |
| 20 | pub const VERSION: &str = env!("CARGO_PKG_VERSION"); |
| 21 | |
| 22 | pub enum Page { |
| 23 | Home, |
| 24 | Loading { url: String }, |
| 25 | Doc(Document), |
| 26 | Picture { url: String }, |
| 27 | Text { url: String, text: String }, |
| 28 | Error { url: String, message: String }, |
| 29 | } |
| 30 | |
| 31 | pub enum Picture { |
| 32 | Loading, |
| 33 | Ready(TextureHandle), |
| 34 | Failed, |
| 35 | } |
| 36 | |
| 37 | pub struct Clearwake { |
| 38 | filter: Arc<Filter>, |
| 39 | loader: Loader, |
| 40 | inbox: Inbox, |
| 41 | generation: u64, |
| 42 | page: Page, |
| 43 | history: History, |
| 44 | bookmarks: Bookmarks, |
| 45 | pictures: HashMap<String, Picture>, |
| 46 | address: String, |
| 47 | address_focus: bool, |
| 48 | forms: HashMap<usize, String>, |
| 49 | home_search: String, |
| 50 | hover: Option<String>, |
| 51 | blocked_total: u64, |
| 52 | text_scale: f32, |
| 53 | dark: Option<bool>, |
| 54 | show_bookmarks: bool, |
| 55 | scroll_to_top: bool, |
| 56 | #[cfg(target_os = "android")] |
| 57 | keyboard_shown: bool, |
| 58 | } |
| 59 | |
| 60 | impl Clearwake { |
| 61 | pub fn new(cc: &eframe::CreationContext<'_>, start: Option<String>) -> Clearwake { |
| 62 | let filter = Arc::new(Filter::new()); |
| 63 | let inbox: Inbox = Arc::new(Mutex::new(Vec::new())); |
| 64 | let loader = Loader::new(inbox.clone(), cc.egui_ctx.clone(), filter.clone()); |
| 65 | let mut app = Clearwake { |
| 66 | filter, |
| 67 | loader, |
| 68 | inbox, |
| 69 | generation: 0, |
| 70 | page: Page::Home, |
| 71 | history: History::default(), |
| 72 | bookmarks: Bookmarks::default(), |
| 73 | pictures: HashMap::new(), |
| 74 | address: String::new(), |
| 75 | address_focus: true, |
| 76 | forms: HashMap::new(), |
| 77 | home_search: String::new(), |
| 78 | hover: None, |
| 79 | blocked_total: 0, |
| 80 | text_scale: 1.0, |
| 81 | dark: None, |
| 82 | show_bookmarks: false, |
| 83 | scroll_to_top: false, |
| 84 | #[cfg(target_os = "android")] |
| 85 | keyboard_shown: false, |
| 86 | }; |
| 87 | if let Some(storage) = cc.storage { |
| 88 | if let Some(t) = storage.get_string("bookmarks") { |
| 89 | app.bookmarks = Bookmarks::from_text(&t); |
| 90 | } |
| 91 | if let Some(s) = storage.get_string("text_scale").and_then(|s| s.parse::<f32>().ok()) { |
| 92 | app.text_scale = s.clamp(0.7, 2.0); |
| 93 | } |
| 94 | app.dark = match storage.get_string("look").as_deref() { |
| 95 | Some("dark") => Some(true), |
| 96 | Some("light") => Some(false), |
| 97 | _ => None, |
| 98 | }; |
| 99 | if let Some(n) = storage.get_string("blocked_total").and_then(|s| s.parse().ok()) { |
| 100 | app.blocked_total = n; |
| 101 | } |
| 102 | } |
| 103 | ui::install_style(&cc.egui_ctx, app.dark); |
| 104 | app.history.visit(String::from("about:home")); |
| 105 | if let Some(s) = start { |
| 106 | app.address_focus = false; |
| 107 | app.open_input(&s); |
| 108 | } |
| 109 | app |
| 110 | } |
| 111 | |
| 112 | /// Open what the person typed in the address bar or the home search. |
| 113 | pub fn open_input(&mut self, input: &str) { |
| 114 | if let Some(u) = clearwake_core::resolve_input(input) { |
| 115 | self.open(u.to_string(), true); |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | /// Open an address. `record` adds it to back/forward history. |
| 120 | pub fn open(&mut self, url: String, record: bool) { |
| 121 | self.generation += 1; |
| 122 | self.forms.clear(); |
| 123 | self.pictures.clear(); |
| 124 | self.hover = None; |
| 125 | self.show_bookmarks = false; |
| 126 | self.scroll_to_top = true; |
| 127 | if record { |
| 128 | self.history.visit(url.clone()); |
| 129 | } |
| 130 | self.address = if url == "about:home" { String::new() } else { url.clone() }; |
| 131 | if url == "about:home" { |
| 132 | self.page = Page::Home; |
| 133 | return; |
| 134 | } |
| 135 | match Url::parse(&url) { |
| 136 | Some(u) if self.filter.blocks(&u) => { |
| 137 | self.blocked_total += 1; |
| 138 | self.page = Page::Error { url, message: String::from("Clearwake blocked this address because it serves ads or tracking.") }; |
| 139 | } |
| 140 | Some(_) => { |
| 141 | self.page = Page::Loading { url: url.clone() }; |
| 142 | self.loader.load(Job { generation: self.generation, kind: Kind::Page, url }); |
| 143 | } |
| 144 | None => { |
| 145 | self.page = Page::Error { url, message: String::from("Clearwake only opens web addresses (http and https).") }; |
| 146 | } |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | pub fn back(&mut self) { |
| 151 | if let Some(u) = self.history.back() { |
| 152 | self.open(u, false); |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | pub fn forward(&mut self) { |
| 157 | if let Some(u) = self.history.forward() { |
| 158 | self.open(u, false); |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | pub fn reload(&mut self) { |
| 163 | if let Some(u) = self.history.current().map(|s| s.to_string()) { |
| 164 | self.open(u, false); |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | pub fn current_url(&self) -> Option<String> { |
| 169 | match &self.page { |
| 170 | Page::Home => None, |
| 171 | Page::Loading { url } | Page::Picture { url } | Page::Text { url, .. } | Page::Error { url, .. } => Some(url.clone()), |
| 172 | Page::Doc(d) => Some(d.url.to_string()), |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | pub fn current_title(&self) -> String { |
| 177 | match &self.page { |
| 178 | Page::Doc(d) if !d.title.is_empty() => d.title.clone(), |
| 179 | _ => self.current_url().unwrap_or_default(), |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | fn receive(&mut self, ctx: &egui::Context) { |
| 184 | let done: Vec<Done> = std::mem::take(&mut *self.inbox.lock().unwrap()); |
| 185 | for d in done { |
| 186 | if d.job.generation != self.generation { |
| 187 | continue; |
| 188 | } |
| 189 | match d.job.kind { |
| 190 | Kind::Page => self.page_arrived(ctx, d.job.url, d.result), |
| 191 | Kind::Image => { |
| 192 | let pic = match d.result { |
| 193 | Ok(Body::Image { width, height, rgba }) => { |
| 194 | let img = egui::ColorImage::from_rgba_unmultiplied([width, height], &rgba); |
| 195 | Picture::Ready(ctx.load_texture(d.job.url.clone(), img, egui::TextureOptions::LINEAR)) |
| 196 | } |
| 197 | Err(e) if e.contains("blocked") => { |
| 198 | self.blocked_total += 1; |
| 199 | Picture::Failed |
| 200 | } |
| 201 | _ => Picture::Failed, |
| 202 | }; |
| 203 | self.pictures.insert(d.job.url, pic); |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | fn page_arrived(&mut self, ctx: &egui::Context, asked: String, result: Result<Body, String>) { |
| 210 | match result { |
| 211 | Err(message) => { |
| 212 | if message.contains("blocked") { |
| 213 | self.blocked_total += 1; |
| 214 | } |
| 215 | self.page = Page::Error { url: asked, message }; |
| 216 | } |
| 217 | Ok(Body::Image { .. }) => {} |
| 218 | Ok(Body::Page { url, content_type, bytes }) => { |
| 219 | if url != asked { |
| 220 | self.history.replace(url.clone()); |
| 221 | } |
| 222 | self.address = url.clone(); |
| 223 | let ct = content_type.to_ascii_lowercase(); |
| 224 | let sniff_html = { |
| 225 | let head = String::from_utf8_lossy(&bytes[..bytes.len().min(512)]).to_ascii_lowercase(); |
| 226 | head.contains("<html") || head.contains("<!doctype html") || head.contains("<head") || head.contains("<body") |
| 227 | }; |
| 228 | if ct.starts_with("image/") { |
| 229 | self.page = Page::Picture { url: url.clone() }; |
| 230 | match net::decode_image(&bytes, 4096) { |
| 231 | Ok(Body::Image { width, height, rgba }) => { |
| 232 | let img = egui::ColorImage::from_rgba_unmultiplied([width, height], &rgba); |
| 233 | self.pictures.insert(url.clone(), Picture::Ready(ctx.load_texture(url, img, egui::TextureOptions::LINEAR))); |
| 234 | } |
| 235 | _ => { |
| 236 | self.pictures.insert(url, Picture::Failed); |
| 237 | } |
| 238 | } |
| 239 | } else if ct.contains("html") || ct.contains("xml") || (ct.is_empty() && sniff_html) || sniff_html { |
| 240 | let text = html::decode_bytes(&bytes, &content_type); |
| 241 | let base = Url::parse(&url).unwrap_or_else(|| Url::parse("about:blank").unwrap()); |
| 242 | let doc = html::parse(&text, &base, &self.filter); |
| 243 | self.blocked_total += doc.stats.blocked as u64; |
| 244 | for (i, src) in doc.image_urls().into_iter().enumerate() { |
| 245 | if i >= 80 { |
| 246 | break; |
| 247 | } |
| 248 | self.pictures.insert(src.clone(), Picture::Loading); |
| 249 | self.loader.load(Job { generation: self.generation, kind: Kind::Image, url: src }); |
| 250 | } |
| 251 | self.page = Page::Doc(doc); |
| 252 | } else if ct.starts_with("text/") || ct.contains("json") || ct.is_empty() { |
| 253 | self.page = Page::Text { url, text: String::from_utf8_lossy(&bytes).into_owned() }; |
| 254 | } else { |
| 255 | self.page = Page::Error { |
| 256 | url, |
| 257 | message: String::from("This is a file, not a page. Clearwake doesn't download files."), |
| 258 | }; |
| 259 | } |
| 260 | } |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | impl eframe::App for Clearwake { |
| 266 | fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { |
| 267 | let ctx = ui.ctx().clone(); |
| 268 | self.receive(&ctx); |
| 269 | ui::shortcuts(self, &ctx); |
| 270 | ui::toolbar(self, ui); |
| 271 | ui::status_bar(self, ui); |
| 272 | ui::content(self, ui); |
| 273 | let title = match &self.page { |
| 274 | Page::Home => String::from("Clearwake"), |
| 275 | _ => { |
| 276 | let t = self.current_title(); |
| 277 | if t.is_empty() { String::from("Clearwake") } else { format!("{t} — Clearwake") } |
| 278 | } |
| 279 | }; |
| 280 | ctx.send_viewport_cmd(egui::ViewportCommand::Title(title)); |
| 281 | #[cfg(target_os = "android")] |
| 282 | android_keyboard(&ctx, &mut self.keyboard_shown); |
| 283 | } |
| 284 | |
| 285 | fn save(&mut self, storage: &mut dyn eframe::Storage) { |
| 286 | storage.set_string("bookmarks", self.bookmarks.to_text()); |
| 287 | storage.set_string("text_scale", self.text_scale.to_string()); |
| 288 | storage.set_string( |
| 289 | "look", |
| 290 | match self.dark { |
| 291 | Some(true) => "dark", |
| 292 | Some(false) => "light", |
| 293 | None => "system", |
| 294 | } |
| 295 | .to_string(), |
| 296 | ); |
| 297 | storage.set_string("blocked_total", self.blocked_total.to_string()); |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | /// Window options shared by the computer and phone builds. |
| 302 | #[cfg(not(target_arch = "wasm32"))] |
| 303 | pub fn native_options() -> eframe::NativeOptions { |
| 304 | let icon = ui::app_icon(); |
| 305 | eframe::NativeOptions { |
| 306 | viewport: egui::ViewportBuilder::default() |
| 307 | .with_title("Clearwake") |
| 308 | .with_app_id("ai.clearwake.Clearwake") |
| 309 | .with_inner_size([1180.0, 820.0]) |
| 310 | .with_min_inner_size([360.0, 420.0]) |
| 311 | .with_icon(icon), |
| 312 | ..Default::default() |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | #[cfg(target_os = "android")] |
| 317 | static ANDROID: std::sync::OnceLock<winit::platform::android::activity::AndroidApp> = std::sync::OnceLock::new(); |
| 318 | |
| 319 | /// Show the phone's keyboard while a text field is being typed in. |
| 320 | #[cfg(target_os = "android")] |
| 321 | fn android_keyboard(ctx: &egui::Context, shown: &mut bool) { |
| 322 | let want = ctx.egui_wants_keyboard_input(); |
| 323 | if want != *shown { |
| 324 | if let Some(app) = ANDROID.get() { |
| 325 | if want { |
| 326 | app.show_soft_input(true); |
| 327 | } else { |
| 328 | app.hide_soft_input(true); |
| 329 | } |
| 330 | } |
| 331 | *shown = want; |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | #[cfg(target_os = "android")] |
| 336 | #[unsafe(no_mangle)] |
| 337 | fn android_main(app: winit::platform::android::activity::AndroidApp) { |
| 338 | let _ = ANDROID.set(app.clone()); |
| 339 | let mut options = native_options(); |
| 340 | options.android_app = Some(app); |
| 341 | let _ = eframe::run_native("Clearwake", options, Box::new(|cc| Ok(Box::new(Clearwake::new(cc, None))))); |
| 342 | } |
| 343 | |
| 344 | #[cfg(target_arch = "wasm32")] |
| 345 | mod web_start { |
| 346 | use super::*; |
| 347 | use wasm_bindgen::prelude::*; |
| 348 | use wasm_bindgen::JsCast; |
| 349 | |
| 350 | #[wasm_bindgen(start)] |
| 351 | pub fn start() { |
| 352 | let window = web_sys::window().expect("window"); |
| 353 | let document = window.document().expect("document"); |
| 354 | let canvas = document |
| 355 | .get_element_by_id("clearwake") |
| 356 | .expect("canvas") |
| 357 | .dyn_into::<web_sys::HtmlCanvasElement>() |
| 358 | .expect("canvas element"); |
| 359 | let start = window.location().hash().ok().and_then(|h| { |
| 360 | let h = h.trim_start_matches('#'); |
| 361 | if h.is_empty() { None } else { Some(clearwake_core::url::decode_component(h)) } |
| 362 | }); |
| 363 | wasm_bindgen_futures::spawn_local(async move { |
| 364 | let runner = eframe::WebRunner::new(); |
| 365 | let _ = runner |
| 366 | .start(canvas, eframe::WebOptions::default(), Box::new(move |cc| Ok(Box::new(Clearwake::new(cc, start))))) |
| 367 | .await; |
| 368 | if let Some(el) = web_sys::window().and_then(|w| w.document()).and_then(|d| d.get_element_by_id("loading")) { |
| 369 | el.remove(); |
| 370 | } |
| 371 | }); |
| 372 | } |
| 373 | } |