From daeec2b5a7a953e6916d4139d8a6e16462d36eba Mon Sep 17 00:00:00 2001 From: PawelKra <15887575+PawelKra@users.noreply.github.com> Date: Thu, 5 Nov 2026 09:47:20 +0100 Subject: [PATCH 1/9] feat(ui): links in the identify pop-up, and pictures from the asset server or on click A value that is an http:// or https:// address (strictly: a host name or IP address, no spaces, quotes or user name before the host, at most 2048 bytes) is drawn as a hyperlink that opens in the browser, in a new tab on the web so the map stays open, with Copy Link in its context menu. Other text, javascript:, file: and data: values included, is shown as before. Without a picture kept in a value (a data:image/... thumbnail, which still wins), the pop-up can show a picture from the web: the https:// address in a field named image, image_url, photo, photo_url, picture, picture_url, thumbnail or thumbnail_url (any case, with or without _, - or spaces), else the first address whose path ends in .jpg, .jpeg, .png or .webp. Fetching a picture named by the data tells its server who opened the file, so only https://assets.rustgis.app/ is fetched as the pop-up opens: exactly that host, compared without regard to case, with no port, user name, subdomain or trailing dot. A picture on any other server shows a Show Picture button naming the server, and nothing is fetched until it is clicked. Plain http:// pictures and addresses on this computer or the local network are never fetched, and the pop-up says so. Pictures go through the tile cache's downloads (worker threads natively, the browser's fetch on the web) with a 4 MB budget the fetchers enforce while reading. Natively they use the public-only agent through a new cache::download_public_limited, so a public-looking name or a redirect that resolves to this computer or the local network is refused where it resolves, past what the address check can tell; the header is checked against 2048 x 2048 pixels before anything is decoded, and the decoded picture is kept at most 1024 pixels a side. Each address's picture, or why there is none, is kept for the session (16 addresses, the least recently shown dropped first), so it isn't fetched again when the pop-up reopens, nor a failure every frame. A failure says why in the pop-up ("Picture unavailable: ..." with the server's answer, the network or CORS error, too many bytes or pixels, not a picture) and the address stays a link. The image crate's WebP decoder, already built for map tiles, is named in the UI crate's features so .webp pictures decode there too. docs: the pop-up's links and pictures in the user guide; privacy.md says which pictures are fetched by themselves, which wait for a click, and which are never fetched. --- crates/tiles/src/cache.rs | 53 +- crates/ui-egui/Cargo.toml | 2 +- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/mapview.rs | 116 +++- crates/ui-egui/src/popupmedia.rs | 638 +++++++++++++++++++ crates/ui-egui/tests/popup_links_pictures.rs | 348 ++++++++++ docs/privacy.md | 12 + docs/user-guide/editing.md | 20 + 8 files changed, 1174 insertions(+), 16 deletions(-) create mode 100644 crates/ui-egui/src/popupmedia.rs create mode 100644 crates/ui-egui/tests/popup_links_pictures.rs diff --git a/crates/tiles/src/cache.rs b/crates/tiles/src/cache.rs index 07ecdf8ac7..cd4b96f7cc 100644 --- a/crates/tiles/src/cache.rs +++ b/crates/tiles/src/cache.rs @@ -781,9 +781,32 @@ pub fn download_detailed(url: &str, max: usize, done: DoneDetailed) { download_detailed_within(url, max, DOWNLOAD_TIMEOUT, &[], done); } +/// Like [`download_limited`], connecting natively only to internet addresses (as +/// [`download_public_within`], off the frame): a name, or a redirect to one, that resolves to this +/// computer or the local network is refused when it is resolved. For an address that comes from +/// data rather than the user (a picture named in a feature's values), which mustn't be able to +/// reach local services. An installed fetcher (the browser's) fetches as it always does. +pub fn download_public_limited(url: &str, max: usize, done: Done) { + download_reaching(url, max, DOWNLOAD_TIMEOUT, &[], Reaching::Public, Box::new(move |r| done(r.map_err(|f| f.message)))); +} + +/// Which addresses a native download may connect to. +#[derive(Clone, Copy)] +enum Reaching { + /// Wherever the address's name resolves (the user named it). + Any, + /// Only internet addresses, judged where names resolve and redirects lead. + Public, +} + /// Like [`download_detailed`], giving up after `timeout` natively; a status in `omit` isn't /// recorded as a failure. fn download_detailed_within(url: &str, max: usize, timeout: std::time::Duration, omit: &'static [u16], done: DoneDetailed) { + download_reaching(url, max, timeout, omit, Reaching::Any, done); +} + +/// [`download_detailed_within`], natively connecting only where `reaching` allows. +fn download_reaching(url: &str, max: usize, timeout: std::time::Duration, omit: &'static [u16], reaching: Reaching, done: DoneDetailed) { if let Err(e) = crate::address::check(url, None) { done(Err(Failure::new(url, e))); return; @@ -800,7 +823,10 @@ fn download_detailed_within(url: &str, max: usize, timeout: std::time::Duration, let f = fetcher().lock().unwrap_or_else(|e| e.into_inner()).clone(); match f { Some(f) => f(marked.clone(), Box::new(move |r| done(r.map_err(|e| Failure::new(&marked, e)))), omit), - None => native::download_within(marked, timeout, omit, done), + None => match reaching { + Reaching::Any => native::download_within(marked, timeout, omit, done), + Reaching::Public => native::download_public_within(marked, timeout, done), + }, } } @@ -1496,6 +1522,15 @@ mod native { }); } + /// Like [`download_within`], connecting only to internet addresses ([`public_agent`]). + pub(super) fn download_public_within(url: String, timeout: std::time::Duration, done: DoneDetailed) { + let capture = Capture::current(); + std::thread::spawn(move || { + let _scope = capture.enter(); + done(get_detailed_omitting(&public_agent(timeout), &url, &[])); + }); + } + fn work() { let agent = shared_agent(); let q = queue(); @@ -1813,6 +1848,10 @@ mod native { done(Err(crate::failure::Failure::new(&url, message))); } + pub(super) fn download_public_within(url: String, timeout: std::time::Duration, done: DoneDetailed) { + download_within(url, timeout, &[], done); + } + pub(super) fn post(url: String, _body: String, done: Done) { done(Err(format!("{url}: this build has no way to send requests"))); } @@ -2179,6 +2218,18 @@ mod tests { assert!(err.contains("resolves to this computer or the local network"), "{err}"); } + /// The same off the frame ([`download_public_limited`] without a fetcher installed, called + /// directly: other tests here install theirs): one that resolves locally is refused there. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn public_downloads_off_the_frame_refuse_names_that_resolve_locally() { + let (tx, rx) = std::sync::mpsc::channel(); + let url = download_address("http://localhost:9/picture.png", 1024); + native::download_public_within(url, std::time::Duration::from_secs(5), Box::new(move |r| drop(tx.send(r)))); + let err = rx.recv_timeout(std::time::Duration::from_secs(30)).unwrap().unwrap_err().message; + assert!(err.contains("resolves to this computer or the local network"), "{err}"); + } + #[test] fn announced_tiff_header_lengths() { assert_eq!(tiff_header_length(" 16384 "), Some(16384)); diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 05394b366e..942d37deb0 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -29,7 +29,7 @@ unicode-normalization = "0.1" sys-locale = { version = "0.3", features = ["js"] } # Pictures kept with features (photo thumbnails), shown in the identify popup. -image = { workspace = true, features = ["jpeg"] } +image = { workspace = true, features = ["jpeg", "webp"] } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] rfd = { workspace = true } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6b11cfc67f..65aeaad1f2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -64,6 +64,7 @@ mod panes; mod pluginpanel; mod pluginstart; mod pluginsui; +mod popupmedia; mod portalsui; #[cfg(not(target_arch = "wasm32"))] mod relayshot; diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 9e81ace485..28e3c42571 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -322,6 +322,8 @@ pub struct MapView { /// The picture an identified feature carries (a photo's thumbnail, a `data:image/…` value): /// a hash of the value, and its texture (or why it couldn't be read). picture: Option<(u64, Result)>, + /// Pictures fetched from web addresses in features' values, by address, for the session. + pictures: crate::popupmedia::Pictures, /// The tile layers' credits, from the last render. attribution: Vec, /// Tile layer errors already reported. @@ -413,6 +415,7 @@ impl Default for MapView { snap: None, split: None, picture: None, + pictures: Default::default(), attribution: Vec::new(), tile_errors: std::collections::HashSet::new(), last_render: -10.0, @@ -3499,6 +3502,22 @@ fn popup(app: &mut RustGisApp, ui: &mut Ui, rect: Rect) { // A picture value (a photo's thumbnail) shows as the picture, not as its text. let picture_key = attrs.iter().find(|(_, v)| v.as_str().is_some_and(is_picture)).map(|(k, _)| k.clone()); let picture = picture_key.and_then(|k| attrs.remove(&k)).and_then(|v| v.as_str().map(|s| picture_texture(app, ui.ctx(), s))); + let picture_is_data = picture.is_some(); + // Without one, a picture from a web address in the values (`image_url`, a `.jpg` address…): + // fetched as the pop-up opens only from RustGIS's own asset server, from anywhere else only + // once the user asks; kept for the session. Its address stays in the rows as a link. + let web_picture = if picture.is_none() { + crate::popupmedia::picture_link(attrs.iter().filter_map(|(k, v)| Some((k.as_str(), v.as_str()?)))).map(str::to_string) + } else { + None + }; + let picture = match (picture, &web_picture) { + (Some(Ok(tex)), _) => Some(crate::popupmedia::Shown::Ready(tex)), + (Some(Err(e)), _) => Some(crate::popupmedia::Shown::Failed(crate::popupmedia::Failure::Fetch(e))), + (None, Some(url)) => Some(app.map.pictures.show(ui.ctx(), url, crate::popupmedia::fetch)), + (None, None) => None, + }; + let mut load_picture = false; let title = if waiting { tl!("Asking the map service…").to_string() } else if info["raster"].as_bool() == Some(true) { @@ -3581,17 +3600,62 @@ fn popup(app: &mut RustGisApp, ui: &mut Ui, rect: Rect) { }); }); }); + let mut picture_h = 0.0; if let Some(picture) = &picture { - egui::Frame::NONE.inner_margin(egui::Margin { left: 12, right: 12, top: 8, bottom: 0 }).show(ui, |ui| match picture { - Ok(tex) => { - let size = tex.size_vec2(); - let scale = (ui.available_width() / size.x.max(1.0)).min(1.5); - ui.add(egui::Image::new((tex.id(), size * scale)).corner_radius(CornerRadius::same(6))); - } - Err(e) => { - ui.label(egui::RichText::new(e.as_str()).size(11.0).color(t.text_dim)); - } - }); + let shown = + egui::Frame::NONE.inner_margin(egui::Margin { left: 12, right: 12, top: 8, bottom: 0 }).show( + ui, + |ui| match picture { + crate::popupmedia::Shown::Ready(tex) => { + // As wide as the pop-up, up to half again its own size, and no taller + // than a thumbnail shown that way; one from the web leaves room for + // a few rows under it. + let size = tex.size_vec2(); + let tallest = if picture_is_data { 240.0 } else { 180.0 }; + let scale = (ui.available_width() / size.x.max(1.0)).min(tallest / size.y.max(1.0)).min(1.5); + ui.add( + egui::Image::new((tex.id(), size * scale)) + .corner_radius(CornerRadius::same(6)) + .alt_text(tl!("Picture")), + ); + } + // From another server: fetched only when asked, naming who + // would be asked. + crate::popupmedia::Shown::Offered => { + let host = web_picture.as_deref().and_then(crate::popupmedia::authority).unwrap_or_default(); + ui.horizontal_wrapped(|ui| { + let ask = ui.add(egui::Button::new(egui::RichText::new(tl!("Show Picture")).size(11.5))); + let tip = crate::i18n::fmt( + "Fetches the picture from {host}, which learns your IP address and that it was viewed", + &[("host", host)], + ); + if ask.on_hover_text(tip).clicked() { + load_picture = true; + } + ui.label( + egui::RichText::new(crate::i18n::fmt("from {host}", &[("host", host)])) + .size(11.0) + .color(t.text_dim), + ); + }); + } + crate::popupmedia::Shown::Loading => { + ui.horizontal(|ui| { + ui.spinner(); + ui.label(egui::RichText::new(tl!("Loading picture…")).size(11.0).color(t.text_dim)); + }); + } + // A picture kept in a value says why it can't be shown, as it always has. + crate::popupmedia::Shown::Failed(crate::popupmedia::Failure::Fetch(e)) if picture_is_data => { + ui.label(egui::RichText::new(e.as_str()).size(11.0).color(t.text_dim)); + } + crate::popupmedia::Shown::Failed(f) => { + ui.add(egui::Label::new(egui::RichText::new(f.line()).size(11.0).color(t.text_dim)).wrap()); + } + }, + ); + // The rows below take what the picture leaves of the height limit. + picture_h = shown.response.rect.height(); } // A solid scroll bar in its own gutter, shown when the rows are taller than the // limit (a floating one is invisible until hovered). @@ -3601,7 +3665,7 @@ fn popup(app: &mut RustGisApp, ui: &mut Ui, rect: Rect) { egui::ScrollArea::vertical() .id_salt(("popup_rows", key)) .auto_shrink([false, true]) - .max_height((limit.y - header.response.rect.height()).max(40.0)) + .max_height((limit.y - header.response.rect.height() - picture_h).max(40.0)) .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::VisibleWhenNeeded) .show(ui, |ui| { egui::Frame::NONE.inner_margin(egui::Margin { left: 12, right: 14, top: 6, bottom: 12 }).show(ui, |ui| { @@ -3619,7 +3683,24 @@ fn popup(app: &mut RustGisApp, ui: &mut Ui, rect: Rect) { // A fixed column: long values wrap, and the stripes span it. ui.set_min_width(value_w); ui.set_max_width(value_w); - ui.add(egui::Label::new(egui::RichText::new(v.as_str().unwrap_or("")).size(11.5)).wrap()); + let text = v.as_str().unwrap_or(""); + // A web address is a link that opens in the browser (a new + // tab on the web, so the map stays open). + if let Some(url) = crate::popupmedia::web_link(text) { + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap); + ui.add( + egui::Hyperlink::from_label_and_url(egui::RichText::new(url).size(11.5), url) + .open_in_new_tab(true), + ) + .context_menu(|ui| { + if ui.button(tl!("Copy Link")).clicked() { + ui.ctx().copy_text(url.to_string()); + ui.close(); + } + }); + } else { + ui.add(egui::Label::new(egui::RichText::new(text).size(11.5)).wrap()); + } }); ui.end_row(); } @@ -3645,6 +3726,10 @@ fn popup(app: &mut RustGisApp, ui: &mut Ui, rect: Rect) { if let Some(l) = new_limit { ui.ctx().data_mut(|d| d.insert_temp(limit_id, l)); } + if let (true, Some(url)) = (load_picture, &web_picture) { + app.map.pictures.accept(url, crate::popupmedia::fetch); + ui.ctx().request_repaint(); + } // Zooms to the feature shown, found by its id, as Zoom To Selection does: the selection and // the undo history are left as they are. if let (true, Some((id, fid))) = (zoom, shown) { @@ -3720,14 +3805,17 @@ fn picture_texture(app: &mut RustGisApp, ctx: &egui::Context, value: &str) -> Re decoded } +/// The largest picture the identify popup decodes, pixels a side. +pub(crate) const MAX_PICTURE_SIDE: u32 = 2048; + /// A picture kept with a feature, decoded for the identify popup. A project's value is hostile: /// its size is checked before anything is decoded, so a small compressed picture can't unpack /// into a huge one. pub(crate) fn decode_picture(bytes: &[u8]) -> Result { let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| e.to_string())?; let mut limits = image::Limits::default(); - limits.max_image_width = Some(2048); - limits.max_image_height = Some(2048); + limits.max_image_width = Some(MAX_PICTURE_SIDE); + limits.max_image_height = Some(MAX_PICTURE_SIDE); limits.max_alloc = Some(64 << 20); reader.limits(limits); Ok(reader.decode().map_err(|_| "the picture is too large to show, or isn't one".to_string())?.to_rgba8()) diff --git a/crates/ui-egui/src/popupmedia.rs b/crates/ui-egui/src/popupmedia.rs new file mode 100644 index 0000000000..4f966689b1 --- /dev/null +++ b/crates/ui-egui/src/popupmedia.rs @@ -0,0 +1,638 @@ +//! The identify pop-up's web addresses: values that are links, and a picture fetched from one. +//! +//! A value that is an `http://` or `https://` address is a link. The pop-up shows a picture from +//! the `https://` address in a field named as one (`image`, `image_url`, `photo`, `photo_url`, +//! `picture`, `picture_url`, `thumbnail` or `thumbnail_url`, in any case, with or without the +//! `_`, `-` or space), or else from the first address whose path ends in `.jpg`, `.jpeg`, `.png` +//! or `.webp`. +//! +//! Fetching a picture named by the data tells its server who opened the file and when, so only +//! RustGIS's own asset server ([`AUTO_HOST`], exactly, over `https://`: [`loads_by_itself`]) is +//! fetched as the pop-up opens. A picture anywhere else shows a **Show Picture** button and +//! nothing is fetched until it is clicked. A plain `http://` picture, or one on this computer or +//! the local network, is never fetched; the pop-up says so. +//! +//! A picture is fetched through the tile cache's downloads (worker threads natively, the +//! browser's fetch on the web, where the browser's own HTTP cache applies), at most +//! [`MAX_PICTURE_BYTES`], and decoded with the limits of [`crate::mapview::decode_picture`], +//! its size checked before decoding. Each address's picture, or why there is none, is kept for +//! the session ([`MAX_PICTURES`] of them, the least recently shown dropped first), so it isn't +//! fetched again when the pop-up opens again, nor a failure every frame. + +use rustgis_engine::render::rustgis_tiles::{address, cache}; + +use crate::Slot; + +/// The longest value shown as a link, in bytes. +pub(crate) const MAX_LINK: usize = 2048; +/// The most bytes a picture fetched for the pop-up may have (as a picture kept in a value). +pub(crate) const MAX_PICTURE_BYTES: usize = 4 << 20; +/// The most pictures (or failures) kept, by address. +pub(crate) const MAX_PICTURES: usize = 16; +/// The longest side a fetched picture is kept at, in pixels: the pop-up shows it smaller. +const MAX_SIDE: u32 = 1024; + +/// Field names (lowercase, without `_`, `-` and spaces) whose web address is a picture. +const PICTURE_FIELDS: [&str; 8] = ["image", "imageurl", "photo", "photourl", "picture", "pictureurl", "thumbnail", "thumbnailurl"]; +/// Address path endings that are a picture, whatever the field is named. +const PICTURE_ENDINGS: [&str; 4] = [".jpg", ".jpeg", ".png", ".webp"]; + +/// `s` without `prefix`, matched in any case. +fn strip_prefix_ignore_case<'a>(s: &'a str, prefix: &str) -> Option<&'a str> { + let head = s.get(..prefix.len())?; + if head.eq_ignore_ascii_case(prefix) { s.get(prefix.len()..) } else { None } +} + +/// The scheme-less rest of an `http://` or `https://` address. +fn after_scheme(v: &str) -> Option<&str> { + strip_prefix_ignore_case(v, "https://").or_else(|| strip_prefix_ignore_case(v, "http://")) +} + +/// Whether an address's authority is a host name or an IP address (letters, digits, dots and +/// hyphens, or an IPv6 address in brackets), with a port of digits if any. +fn valid_authority(authority: &str) -> bool { + let (host_ok, port) = match authority.strip_prefix('[') { + Some(v6) => match v6.split_once(']') { + Some((h, rest)) => (!h.is_empty() && h.chars().all(|c| c.is_ascii_hexdigit() || c == ':' || c == '.'), rest), + None => return false, + }, + None => { + let (h, rest) = authority.find(':').map_or((authority, ""), |i| authority.split_at(i)); + let ok = !h.is_empty() && !h.starts_with(['.', '-']) && h.chars().all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-'); + (ok, rest) + } + }; + let port_ok = match port.strip_prefix(':') { + Some(p) => (1..=5).contains(&p.len()) && p.chars().all(|c| c.is_ascii_digit()), + None => port.is_empty(), + }; + host_ok && port_ok +} + +/// `v` as a web address the pop-up links to: `http://` or `https://` (in any case), a host +/// name or IP address, and nothing that can't be in an address (spaces, control characters, +/// quotes, angle brackets, backslashes), at most [`MAX_LINK`] bytes. A user name before the host +/// (`https://bank.example@other.example/`) passes for another site, so it is text too. +pub(crate) fn web_link(v: &str) -> Option<&str> { + if v.len() > MAX_LINK { + return None; + } + let rest = after_scheme(v)?; + if v.chars().any(|c| c.is_whitespace() || c.is_control() || matches!(c, '"' | '<' | '>' | '\\' | '`' | '{' | '}' | '^')) { + return None; + } + let authority = rest.split(['/', '?', '#']).next().unwrap_or_default(); + (!authority.contains('@') && valid_authority(authority)).then_some(v) +} + +/// Whether a field is named as a picture's address (`image_url`, `Photo`, `thumbnail`…); not +/// `image_page_url` or `image_credit`. +pub(crate) fn picture_field(name: &str) -> bool { + if name.len() > 64 { + return false; + } + let plain: String = name.chars().filter(|c| !matches!(c, '_' | '-' | ' ')).flat_map(char::to_lowercase).collect(); + PICTURE_FIELDS.contains(&plain.as_str()) +} + +/// Whether a web address's path (not its host, query or fragment) ends as a picture file does. +pub(crate) fn picture_path(url: &str) -> bool { + let Some(rest) = after_scheme(url) else { return false }; + let Some((_, path)) = rest.split_once('/') else { return false }; + let path = path.split(['?', '#']).next().unwrap_or_default(); + PICTURE_ENDINGS + .iter() + .any(|end| path.len() > end.len() && path.get(path.len() - end.len()..).is_some_and(|t| t.eq_ignore_ascii_case(end))) +} + +/// The web address the pop-up shows a picture from, among a feature's text values (name, +/// value): a link in a picture field first, else the first link whose path is a picture file's. +pub(crate) fn picture_link<'a>(attrs: impl Iterator + Clone) -> Option<&'a str> { + let mut links = attrs.filter_map(|(k, v)| Some((k, web_link(v)?))); + let named = links.clone().find(|(k, _)| picture_field(k)); + named.or_else(|| links.find(|(_, v)| picture_path(v))).map(|(_, v)| v) +} + +/// The one host whose pictures the pop-up fetches without being asked: RustGIS's own asset +/// server, which the project runs and which serves the sample data's pictures. +pub(crate) const AUTO_HOST: &str = "assets.rustgis.app"; + +/// The authority (host and port) of a web address the pop-up links to, as written. +pub(crate) fn authority(url: &str) -> Option<&str> { + let rest = after_scheme(web_link(url)?)?; + rest.split(['/', '?', '#']).next() +} + +/// Whether the pop-up fetches the picture at `url` as soon as it shows it: an `https://` address +/// (the scheme in any case) whose authority is exactly [`AUTO_HOST`], compared without regard to +/// case as host names are. Nothing else passes: no port (not even `:443`), no user name (which +/// [`web_link`] refuses), no subdomain or longer name (`assets.rustgis.app.example.com`), no +/// trailing dot, no percent-encoded or non-ASCII host (neither is a link at all), no `http://`. +pub(crate) fn loads_by_itself(url: &str) -> bool { + strip_prefix_ignore_case(url, "https://").is_some() && authority(url).is_some_and(|a| a.eq_ignore_ascii_case(AUTO_HOST)) +} + +/// The largest picture decoded, pixels a side (as [`crate::mapview::decode_picture`] takes). +const MAX_DECODED_SIDE: u32 = crate::mapview::MAX_PICTURE_SIDE; + +/// Why there is no picture to show. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Failure { + /// The fetch failed: the network, the server's answer, the browser's CORS check, its size + /// in bytes (the fetcher stops reading past [`MAX_PICTURE_BYTES`]). + Fetch(String), + /// What came back isn't a picture that decodes. + NotPicture, + /// A picture of more pixels than are decoded (width, height), refused before decoding. + TooLarge(u32, u32), + /// Only `https://` pictures are fetched. + NotHttps, + /// Addresses on this computer or the local network aren't fetched for a value. + Local, +} + +impl Failure { + /// The line the pop-up shows: "Picture unavailable: …". + pub(crate) fn line(&self) -> String { + match self { + Failure::Fetch(e) => { + let reason: String = e.chars().take(200).collect(); + crate::i18n::fmt("Picture unavailable: {reason}", &[("reason", &reason)]) + } + Failure::NotPicture => crate::i18n::fmt("Picture unavailable: not a picture", &[]), + Failure::TooLarge(w, h) => crate::i18n::fmt( + "Picture unavailable: {w} × {h} pixels is larger than {max} × {max}", + &[("w", &w.to_string()), ("h", &h.to_string()), ("max", &MAX_DECODED_SIDE.to_string())], + ), + Failure::NotHttps => crate::i18n::fmt("Picture unavailable: only https:// pictures are fetched", &[]), + Failure::Local => crate::i18n::fmt("Picture unavailable: pictures aren't fetched from this computer or the local network", &[]), + } + } +} + +/// Why the picture at a web address won't be fetched at all, even when asked, if it won't. +fn refusal(url: &str) -> Option { + if strip_prefix_ignore_case(url, "https://").is_none() { + Some(Failure::NotHttps) + } else if address::reach(url) != address::Reach::Public { + Some(Failure::Local) + } else { + None + } +} + +/// Where a fetched picture lands, decoded off the frame (natively). +pub(crate) type Landing = Slot>; + +/// A picture by address: being fetched, shown, or not to be had. +enum Entry { + Loading(Landing), + Ready(egui::TextureHandle), + Failed(Failure), +} + +/// What the pop-up shows for a picture address. +#[derive(Clone)] +pub(crate) enum Shown { + /// Not fetched: a picture from another server, fetched only when the user asks. + Offered, + Loading, + Ready(egui::TextureHandle), + Failed(Failure), +} + +/// The pictures fetched for the pop-up this session, the least recently shown first. +#[derive(Default)] +pub(crate) struct Pictures { + entries: Vec<(String, Entry)>, +} + +impl Pictures { + /// The picture at `url`. The first time it is asked for (or after it was dropped to make + /// room), one from [`AUTO_HOST`] is started with `fetch`; any other is [`Shown::Offered`], + /// not fetched, until [`Self::accept`]. A refused or failed one is kept like a picture, so + /// it isn't fetched again. + pub(crate) fn show(&mut self, ctx: &egui::Context, url: &str, fetch: impl FnOnce(&str, Landing)) -> Shown { + let (url, mut entry) = match self.entries.iter().position(|(u, _)| u == url) { + Some(i) => self.entries.remove(i), + None => match refusal(url) { + Some(f) => self.make_room(url, Entry::Failed(f)), + None if loads_by_itself(url) => self.make_room(url, start(url, fetch)), + None => return Shown::Offered, + }, + }; + let landed = match &entry { + Entry::Loading(landing) => landing.lock().unwrap_or_else(|e| e.into_inner()).take(), + _ => None, + }; + if let Some(r) = landed { + entry = match r { + Ok(img) => { + let size = [img.width() as usize, img.height() as usize]; + let color = egui::ColorImage::from_rgba_unmultiplied(size, img.as_raw()); + Entry::Ready(ctx.load_texture(format!("identify_picture:{url}"), color, egui::TextureOptions::LINEAR)) + } + Err(f) => Entry::Failed(f), + }; + } + let shown = match &entry { + Entry::Loading(_) => { + ctx.request_repaint_after(std::time::Duration::from_millis(150)); + Shown::Loading + } + Entry::Ready(t) => Shown::Ready(t.clone()), + Entry::Failed(f) => Shown::Failed(f.clone()), + }; + self.entries.push((url, entry)); + shown + } + + /// The user asked to see the picture at `url`: it is started with `fetch` unless it is + /// already kept (fetched, being fetched or failed) or is never fetched ([`refusal`]). + pub(crate) fn accept(&mut self, url: &str, fetch: impl FnOnce(&str, Landing)) { + if self.entries.iter().any(|(u, _)| u == url) { + return; + } + let entry = match refusal(url) { + Some(f) => Entry::Failed(f), + None => start(url, fetch), + }; + let kept = self.make_room(url, entry); + self.entries.push(kept); + } + + /// Room for one more address, the least recently shown dropped; the new one, to push. + fn make_room(&mut self, url: &str, entry: Entry) -> (String, Entry) { + if self.entries.len() >= MAX_PICTURES { + self.entries.remove(0); + } + (url.to_string(), entry) + } + + /// How many addresses are kept. + #[cfg(test)] + pub(crate) fn len(&self) -> usize { + self.entries.len() + } +} + +/// Starts fetching the picture at `url` with `fetch`. +fn start(url: &str, fetch: impl FnOnce(&str, Landing)) -> Entry { + let landing = Landing::default(); + fetch(url, landing.clone()); + Entry::Loading(landing) +} + +/// Decodes a fetched picture for the pop-up: refused when it isn't one, or when its header says +/// it is larger than [`crate::mapview::decode_picture`] takes (before anything is decoded, so a +/// small file can't unpack into a huge picture), and kept at most [`MAX_SIDE`] pixels a side. +pub(crate) fn decode(bytes: &[u8]) -> Result { + let header = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|_| Failure::NotPicture)?; + if header.format().is_none() { + return Err(Failure::NotPicture); + } + let (w, h) = header.into_dimensions().map_err(|_| Failure::NotPicture)?; + if w > MAX_DECODED_SIDE || h > MAX_DECODED_SIDE { + return Err(Failure::TooLarge(w, h)); + } + let img = crate::mapview::decode_picture(bytes).map_err(|_| Failure::NotPicture)?; + let (w, h) = (img.width().max(1), img.height().max(1)); + if w.max(h) <= MAX_SIDE { + return Ok(img); + } + let k = MAX_SIDE as f32 / w.max(h) as f32; + let (tw, th) = (((w as f32 * k) as u32).clamp(1, MAX_SIDE), ((h as f32 * k) as u32).clamp(1, MAX_SIDE)); + Ok(image::imageops::thumbnail(&img, tw, th)) +} + +/// Fetches a picture for the pop-up through the tile cache's downloads (the browser's fetch on +/// the web), at most [`MAX_PICTURE_BYTES`], decoding it where it lands (off the frame natively). +/// Natively it connects only to internet addresses: a public-looking name, or a redirect, that +/// resolves to this computer or the local network is refused where it resolves, past what +/// [`refusal`] can tell from the address. +pub(crate) fn fetch(url: &str, landing: Landing) { + cache::download_public_limited( + url, + MAX_PICTURE_BYTES, + Box::new(move |r| { + let r = r.map_err(Failure::Fetch).and_then(|bytes| decode(&bytes)); + *landing.lock().unwrap_or_else(|e| e.into_inner()) = Some(r); + }), + ); +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + #[test] + fn links_are_http_and_https_addresses_only() { + for good in [ + "https://example.org", + "https://example.org/", + "http://example.org/a/b?c=d&e=f#g", + "HTTPS://EXAMPLE.ORG/PATH", + "HtTp://example.org", + "https://example.org:8443/x", + "https://[2001:db8::1]:443/x", + "https://192.0.2.1/x", + "https://de.wikipedia.org/wiki/Zürich", + ] { + assert_eq!(web_link(good), Some(good), "{good}"); + } + for bad in [ + "", + "example.org", + "www.example.org/page", + "javascript:alert(1)", + "JavaScript://example.org/%0aalert(1)", + "data:text/html,hi", + "data:image/png;base64,iVBORw0KGgo=", + "file:///etc/passwd", + "ftp://example.org/x", + "mailto:someone@example.org", + "https://", + "https:///path", + "https://exa mple.org", + "https://example.org/a b", + " https://example.org", + "https://example.org ", + "https://example.org/\n", + "https://example.org/\u{0}", + "https://example.org/\"onmouseover=\"x", + "https://example.org/