From 13d30d48488a1d63e9d7b808b3638c05eade7db2 Mon Sep 17 00:00:00 2001 From: vangel76 <271991477+vangel76@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:53:16 +0100 Subject: [PATCH 01/23] #565: SVG pictures are drawn, with nothing they refer to loaded An of an SVG drawing, attached (cid:), written into the message (data:image/svg+xml, base64 or percent-encoded) or on the web once the owner asks, is drawn with resvg (already in the tree for the app icon, no features) at the size it is shown. Nothing it names is loaded: the image resolvers answer nothing, no folder is given, no text or fonts. Before usvg sees it the drawing is read within caps (2 MB, no svgz, a stackless nesting scan, 20,000 nodes, no entity declared) and weighed: every use, pattern, clip, mask, marker and filter reference counted with what it brings (100,000 elements, 40 deep), filters of unbounded cost refused, and many layers drawn with fewer pixels. An element in a message is still not drawn; sender images stay pictures of pixels. Human-reviewed, AI-assisted, nobody's mailbox harmed. --- AGENTS.md | 2 +- Cargo.lock | 1 + Cargo.toml | 4 + ROADMAP.md | 2 +- apps/mailcraft/src/picture_cache.rs | 32 +- apps/mailcraft/src/sender_images.rs | 9 +- apps/mailcraft/src/sender_images_tests.rs | 14 + crates/html/src/data.rs | 96 +++- crates/html/src/data_svg_tests.rs | 119 +++++ crates/html/src/data_tests.rs | 10 +- crates/html/src/lib.rs | 4 +- crates/i18n/po/de.po | 9 +- crates/i18n/po/es.po | 9 +- crates/i18n/po/fr.po | 9 +- crates/i18n/po/it.po | 9 +- crates/i18n/po/messages.pot | 2 +- crates/i18n/po/nl.po | 9 +- crates/ui-egui/Cargo.toml | 2 + crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/src/reading.rs | 3 + crates/ui-egui/src/reading/images.rs | 51 +- crates/ui-egui/src/reading/svg.rs | 458 ++++++++++++++++++ crates/ui-egui/src/reading/svg_tests.rs | 455 +++++++++++++++++ crates/ui-egui/src/reading/tests.rs | 10 +- crates/ui-egui/src/reading/tests/web_svg.rs | 34 ++ .../src/reading/tests/written_pictures.rs | 3 +- docs/log.d/ROADMAP/progress/565.md | 1 + docs/log.d/ROADMAP/revisions/565.md | 1 + packaging/release-notes.d/new/565.md | 1 + xtask/Cargo.toml | 8 +- 30 files changed, 1303 insertions(+), 68 deletions(-) create mode 100644 crates/html/src/data_svg_tests.rs create mode 100644 crates/ui-egui/src/reading/svg.rs create mode 100644 crates/ui-egui/src/reading/svg_tests.rs create mode 100644 crates/ui-egui/src/reading/tests/web_svg.rs create mode 100644 docs/log.d/ROADMAP/progress/565.md create mode 100644 docs/log.d/ROADMAP/revisions/565.md create mode 100644 packaging/release-notes.d/new/565.md diff --git a/AGENTS.md b/AGENTS.md index 6146e0ea32..c7895c5fa2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,7 +17,7 @@ People trust MailCraft with years of correspondence; a crash loses their work an - Production crate roots carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`; new crates start with it. Tests may `unwrap` (`clippy.toml`). ## Mail is private and mail is hostile -- **Nothing in a message runs, and nothing in a message is fetched unless the owner asks for its pictures; the one other thing fetched for mail is a sender's picture, once the owner turns sender images on.** HTML mail becomes display blocks through `crates/html`; there is no script engine, no CSS engine, and no tracking pixel that fires by itself. Don't add a web view. The only presentation read from a message is a short whitelist (text and background colour, bold, italic, underline, strike, alignment, a clamped font size, whether a block has a margin or a border on a side, table spans and widths (a `width` in a table's or cell's style too, and a `max-width`, both clamped), where a cell sits in its row and the gaps between cells (`valign`, `vertical-align`, `cellspacing`, `border-spacing` up to 16 pixels), centring by automatic margins (`margin: 0 auto`), `display: inline-block` and no other value, which lays out an element that has a width, padding, a frame or a background as a box on a line (at most 256 a message) only when everything else in the element that holds it is white space, a comment or hidden (`crates/html/src/look.rs` reads the holder to its end, within bounds; anything else leaves the element in its line as it was), padding and margins with their real sizes (`px`, `pt`, `em`, `%`; 0 to 64 pixels a side), the line round a box (a width of 1 to 4 pixels, solid, dashed or dotted, and a colour, per side), rounded corners (the first length of `border-radius`, up to 24 pixels), a line height (1 to 2.5 times the font size), Outlook's list markers, hiding what the sender hid, and the first font family's name, which only a paste into the composer keeps), from inline attributes and from the message's own style sheets (its `` addresses: no backgrounds, style sheets, fonts or frames, and nothing declared 2 px or smaller. `mailcraft_net::pictures::fetch` is the only way out, and it tells the server nothing but the address: no cookies, no referrer, no credentials; public hosts only (never loopback, private or link-local addresses, checked on every redirect and against the addresses actually connected to); at most five redirects, and one more try when the server says "not now"; size and time capped; and what arrives must be a PNG, JPEG, GIF or WebP by its own bytes. A downloaded picture is kept on this computer so it is not asked for again (`apps/mailcraft/src/picture_cache.rs`: beside the mailbox, named by hashes with the address itself never written, at most 4,000 pictures, 256 MB and 30 days, read back through the same checks as a download, cleared from File › Options); nothing else that is fetched is written to disk. Sender images (File › Options, off by default) are the one thing asked for without a message being opened: a picture for a sender the owner knows (a contact, or somebody mail in Sent Items went to) or whose mail's pictures the owner lets come (all mail, that sender or domain, that message; never for mail in Junk E-mail), the sender's only for mail the server vouches for as theirs (DMARC, `reading::remote::vouched`; who the owner's own mail went to needs no such word), while a row of theirs is on screen, from Gravatar (told the SHA-256 of the address, `d=404`) or else favicon.im (told the domain of the sender's site alone, `nutrient.io` for `mail.nutrient.io`, never a mail provider's or a name on a hosting platform: `provider::is_mail_provider`, `provider::is_public_suffix`, `provider::on_hosting_platform`), or else Google's favicon service (the same domain, which it passes on to its `gstatic.com`; its 404 globe is never shown), through the same `pictures::fetch` and picture cache, where a site's icon may also be an ICO, on that path alone (`apps/mailcraft/src/sender_images.rs`, `crates/ui-egui/src/sender_images.rs`). The switch says in plain words who is asked and what each is told; turning it off stops a look-up in flight before its next request (one already on its way finishes, and what it brings is not kept), and Clear in File › Options removes the senders' pictures with the others (#363). Links are shown with their real destination and only `http`, `https`, `mailto`, `tel` and `cid` are followed. +- **Nothing in a message runs, and nothing in a message is fetched unless the owner asks for its pictures; the one other thing fetched for mail is a sender's picture, once the owner turns sender images on.** HTML mail becomes display blocks through `crates/html`; there is no script engine, no CSS engine, and no tracking pixel that fires by itself. Don't add a web view. The only presentation read from a message is a short whitelist (text and background colour, bold, italic, underline, strike, alignment, a clamped font size, whether a block has a margin or a border on a side, table spans and widths (a `width` in a table's or cell's style too, and a `max-width`, both clamped), where a cell sits in its row and the gaps between cells (`valign`, `vertical-align`, `cellspacing`, `border-spacing` up to 16 pixels), centring by automatic margins (`margin: 0 auto`), `display: inline-block` and no other value, which lays out an element that has a width, padding, a frame or a background as a box on a line (at most 256 a message) only when everything else in the element that holds it is white space, a comment or hidden (`crates/html/src/look.rs` reads the holder to its end, within bounds; anything else leaves the element in its line as it was), padding and margins with their real sizes (`px`, `pt`, `em`, `%`; 0 to 64 pixels a side), the line round a box (a width of 1 to 4 pixels, solid, dashed or dotted, and a colour, per side), rounded corners (the first length of `border-radius`, up to 24 pixels), a line height (1 to 2.5 times the font size), Outlook's list markers, hiding what the sender hid, and the first font family's name, which only a paste into the composer keeps), from inline attributes and from the message's own style sheets (its `\ + \ + \ + \ + \ + \ + \ + words" + ), + ) +} + +#[test] +fn nothing_an_svg_refers_to_on_the_web_is_fetched() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let address = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port()); + for address in [address.clone(), address.replace("http:", "https:"), format!("//127.0.0.1:{}", listener.local_addr().unwrap().port())] { + let data = referring_to(&address); + let image = images::decode(&data, 2048, 40).unwrap(); + assert_eq!(pixel(&image, 20, 20), GREEN, "{address}"); + } + // Nobody came: the drawing is drawn and done, and nothing was asked of the server. + match listener.accept() { + Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::WouldBlock), + Ok((_, from)) => panic!("an SVG made a connection from {from}"), + } +} + +#[test] +fn no_file_an_svg_refers_to_is_read() { + // A red drawing on this computer, named every way a drawing could name it. + let dir = std::env::temp_dir().join(format!("mailcraft-svg-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("red.svg"); + std::fs::write(&file, format!("")).unwrap(); + // As a drawing would load it (the default way would draw it in red: proved here, so that the + // test below proves something). + let path = file.to_string_lossy().replace('\\', "/"); + let names = [path.clone(), file.to_string_lossy().into_owned(), format!("file:///{}", path.trim_start_matches('/')), "red.svg".into()]; + let mut loads = resvg::usvg::Options { resources_dir: Some(dir.clone()), ..Default::default() }; + loads.image_href_resolver = resvg::usvg::ImageHrefResolver::default(); + let tree = resvg::usvg::Tree::from_data(&drawing(40, 40, &format!("")), &loads).unwrap(); + let mut pixmap = resvg::tiny_skia::Pixmap::new(40, 40).unwrap(); + resvg::render(&tree, resvg::tiny_skia::Transform::default(), &mut pixmap.as_mut()); + assert_eq!(pixmap.pixel(20, 20).map(|p| [p.red(), p.green(), p.blue()]), Some([255, 0, 0]), "the default resolver reads files"); + for name in names { + for body in [ + format!(""), + format!(""), + format!(""), + ] { + let image = images::decode(&drawing(40, 40, &body), 2048, 40).unwrap(); + assert!(!any_red(&image), "{body}"); + } + } + // Nor one written into it: a drawing never holds another, nor a picture. + let red = b64(format!("").as_bytes()); + let image = + images::decode(&drawing(40, 40, &format!("")), 2048, 40).unwrap(); + assert!(!any_red(&image)); + let _ = std::fs::remove_dir_all(&dir); +} + +fn b64(bytes: &[u8]) -> String { + const ABC: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + bytes + .chunks(3) + .flat_map(|group| { + let n = group.iter().enumerate().fold(0u32, |n, (i, b)| n | u32::from(*b) << (16 - 8 * i)); + (0..4).map(move |i| if i <= group.len() { char::from(ABC[(n >> (18 - 6 * i) & 63) as usize]) } else { '=' }) + }) + .collect() +} + +#[test] +fn words_in_an_svg_are_left_out_and_the_rest_drawn() { + // No font is looked for: the words are not drawn, the shapes are. + let data = drawing(40, 20, "MMMM"); + let image = images::decode(&data, 2048, 40).unwrap(); + assert!(!any_red(&image)); + assert_eq!(pixel(&image, 20, 10), GREEN); +} + +#[test] +fn what_an_svg_says_runs_never_does() { + let data = drawing( + 20, + 20, + "\ + \ +
x
", + ); + let image = images::decode(&data, 2048, 20).unwrap(); + assert_eq!(pixel(&image, 10, 10), GREEN); + assert!(!any_red(&image)); +} + +#[test] +fn entities_are_refused_and_a_plain_document_type_is_not() { + let laughs = format!( + "{}]>&j;", + (b'b'..=b'j').map(|c| format!("", char::from(c), format!("&{};", char::from(c - 1)).repeat(10))).collect::() + ); + assert!(refused(laughs.as_bytes())); + // One entity, however harmless, is refused: none is ever expanded. + assert!(refused(format!("]>").as_bytes())); + assert!(refused(format!("]>&x;").as_bytes())); + // What drawing programs write before a drawing is fine. + let plain = format!( + "\n\n\n{}", + String::from_utf8(drawing(8, 8, "")).unwrap() + ); + assert_eq!(images::probe(plain.as_bytes()), Some([8, 8])); +} + +#[test] +fn a_packed_svg_is_not_unpacked() { + // svgz: what would be unpacked could be any size. Not an SVG by its bytes, and not read as one. + let packed = b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\xb3\x29\x2e\x4b\x57\x00\x00"; + assert!(!svg::is_svg(packed)); + assert!(refused(packed)); +} + +#[test] +fn an_svg_over_the_caps_is_refused() { + // Too many bytes. + let big = drawing(8, 8, &format!("{}", "x".repeat(MAX_SVG_BYTES))); + assert!(refused(&big)); + // Too many elements. + assert!(refused(&drawing(8, 8, &"".repeat(30_000)))); + // Too deep, by nesting and by references in a chain. + let deep = |n: usize| drawing(8, 8, &format!("{}{}", "".repeat(n), "".repeat(n))); + assert!(refused(&deep(10_000))); + assert!(refused(&deep(MAX_SVG_DEPTH + 1))); + let chain: String = (0..MAX_SVG_DEPTH + 2).map(|i| format!("", i + 1)).collect(); + assert!(refused(&drawing(8, 8, &format!("{chain}")))); + // A drawing of no size, or not one at all. + assert!(refused(format!("").as_bytes())); + assert!(refused(format!("").as_bytes())); +} + +#[test] +fn an_svg_at_the_deepest_allowed_is_drawn_on_a_small_stack() { + // The window's thread has the system's stack, a megabyte on Windows: the deepest drawing + // allowed is drawn on one, in a build without optimisations at that. + let depth = MAX_SVG_DEPTH - 2; + let data = drawing(8, 8, &format!("{}{}", "".repeat(depth), "".repeat(depth))); + let drawn = std::thread::Builder::new().stack_size(1024 * 1024).spawn(move || images::decode(&data, 64, 8).map(|i| i.size)).unwrap().join(); + assert_eq!(drawn.ok().flatten(), Some([8, 8])); +} + +#[test] +fn references_that_multiply_are_refused() { + // Ten deep, each ten times the one before: 10^10 copies. + let mut uses = String::from(""); + for level in 1..=10 { + uses += &format!("{}", format!("", level - 1).repeat(10)); + } + assert!(refused(&drawing(8, 8, &format!("{uses}")))); + assert!(refused(&drawing(8, 8, &format!("{}", uses.replace("href=", "xlink:href="))))); + // Patterns that fill with patterns, through a style sheet and through attributes. + let mut patterns = String::from(""); + for level in 1..=10 { + patterns += &format!( + "{}", + format!("", level - 1).repeat(10) + ); + } + let sheet: String = (0..=10).map(|i| format!(".c{i} {{ fill: url(#p{i}) }}")).collect(); + assert!(refused(&drawing(8, 8, &format!("{patterns}")))); + let attributes = patterns.replace(" class='c", " fill='url(#p").replace("'/>", ")'/>"); + assert!(refused(&drawing(8, 8, &format!("{attributes}")))); + // Clips and masks the same way, a selector that matches everything, and a marker at each + // of very many points. + let mut masks = String::from(""); + for level in 1..=10 { + masks += &format!( + "{}", + "".replace('X', &(level - 1).to_string()).repeat(10) + ); + } + assert!(refused(&drawing(8, 8, &format!("{masks}")))); + assert!(refused(&drawing(8, 8, &format!("")))); + let points: String = (0..20_000).map(|i| format!(" {} {}", i % 8, i % 7)).collect(); + let marker = format!("{}", "".repeat(100)); + assert!(refused(&drawing(8, 8, &format!("{marker}")))); + // A reference to itself. + assert!(refused(&drawing(8, 8, ""))); +} + +#[test] +fn what_drawing_programs_write_is_not_mistaken_for_a_bomb() { + // Gradients and clips from a style sheet, as drawing programs export them, many of each. + let mut body = String::from(""; + for i in 0..60 { + body += &format!( + "\ + " + ); + } + body += ""; + for i in 0..60 { + body += &format!(""); + } + body += ""; + // A drop shadow. + body += "\ + "; + let image = images::decode(&drawing(40, 40, &body), 2048, 40).unwrap(); + assert_eq!(pixel(&image, 30, 30), GREEN); +} + +#[test] +fn filters_that_cost_without_bound_are_refused() { + for filter in [ + "", + "", + "", + ] { + let data = drawing(8, 8, &format!("{filter}")); + assert!(refused(&data), "{filter}"); + } + // Within bounds they are drawn. + let data = + drawing(8, 8, ""); + assert!(images::decode(&data, 64, 8).is_some()); +} + +#[test] +fn a_drawing_of_many_layers_is_drawn_with_fewer_pixels() { + let many: String = (0..800).map(|i| format!("", i % 40)).collect(); + let few = svg::probe(&drawing(40, 40, "")).unwrap(); + let layered = svg::probe(&drawing(40, 40, &many)).unwrap(); + assert!(layered.max_pixels < few.max_pixels, "{} {}", layered.max_pixels, few.max_pixels); + let image = images::decode(&drawing(40, 40, &many), 8192, 8192).unwrap(); + assert!((image.size[0] * image.size[1]) as u64 <= layered.max_pixels, "{:?}", image.size); +} + +#[test] +fn a_damaged_svg_is_a_broken_picture() { + for data in [ + format!("").into_bytes(), + format!("").into_bytes(), + b"".to_vec(), + b"".to_vec(), + [&b""[..], &[0xff, 0xfe, 0xc0], b""].concat(), + b""), "it is a drawing (SVG) that is damaged or can't be shown"); +} + +/// A small generator of the same numbers every run (xorshift). +struct Junk(u64); + +impl Junk { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, n: usize) -> usize { + (self.next() % n.max(1) as u64) as usize + } +} + +#[test] +fn arbitrary_and_damaged_svgs_never_panic() { + let mut junk = Junk(0x5851_f42d_4c95_7f2d); + let good = drawing( + 16, + 16, + "\ + \ + \ + ", + ); + let pieces = ["<", ">", "/", "'", "=", " ", "", "", "url(#", "#g", "href='#c'", "\n".repeat(30_000)))); - // Too deep, by nesting and by references in a chain. + // Too deep, however deep. let deep = |n: usize| drawing(8, 8, &format!("{}{}", "".repeat(n), "".repeat(n))); - assert!(refused(&deep(10_000))); + assert!(refused(&deep(30_000))); assert!(refused(&deep(MAX_SVG_DEPTH + 1))); - let chain: String = (0..MAX_SVG_DEPTH + 2).map(|i| format!("", i + 1)).collect(); - assert!(refused(&drawing(8, 8, &format!("{chain}")))); - // A drawing of no size, or not one at all. + // A drawing of no size. assert!(refused(format!("").as_bytes())); assert!(refused(format!("").as_bytes())); } @@ -239,209 +236,146 @@ fn an_svg_at_the_deepest_allowed_is_drawn_on_a_small_stack() { } #[test] -fn references_inherited_from_a_group_are_counted_for_each_shape() { - // Patterns whose content takes its fill from a group: each shape copies the pattern below. - let mut patterns = String::from(""); - for k in 1..=10 { - patterns += &format!( - "{}", - k - 1, - "".repeat(10) - ); +fn only_a_plain_drawing_is_shown() { + // Each element whose content is copied, a style sheet, filters, pictures and foreign content. + for name in REFUSED.iter().chain(&["feGaussianBlur", "feOffset", "feTurbulence", "feMorphology"]) { + assert!(refused(&drawing(8, 8, &format!("<{name} id='x'/>"))), "{name}"); + assert!(refused(&drawing(8, 8, &format!("<{name}/>"))), "{name}"); } - assert!(refused(&drawing(8, 8, &format!("{patterns}")))); - // A marker given to a group, drawn at every point of the shapes in it. - let points: String = (0..10_000).map(|i| format!(" {},{}", i % 8, i % 7)).collect(); - let marker = format!("{}", "".repeat(500)); - assert!(refused(&drawing(8, 8, &format!("{marker}")))); - // A mask a shape takes from its group with `inherit`. - let mask = format!("{}", "".repeat(5_000)); - let shapes = "".repeat(5_000); - assert!(refused(&drawing(8, 8, &format!("{mask}{shapes}")))); - let shapes = "".repeat(5_000); - let clip = mask.replace("mask", "clipPath"); - assert!(refused(&drawing(8, 8, &format!("{clip}{shapes}")))); -} - -#[test] -fn a_target_named_any_way_the_renderer_finds_it_is_counted() { - // An id in the XML or the SVG namespace is an id to the renderer: clips in clips, ten deep. - let mut clips = String::from(""); - for k in 1..=10 { - clips += &format!("{}", format!("", k - 1).repeat(10)); + // `inherit` anywhere, a comment or an escape in a style, a clip inside a clip. + assert!(refused(&drawing(8, 8, ""))); + assert!(refused(&drawing(8, 8, ""))); + assert!(refused(&drawing(8, 8, ""))); + assert!(refused(&drawing(8, 8, ""))); + assert!(refused(&drawing( + 8, + 8, + "" + ))); + assert!(refused(&drawing( + 8, + 8, + "" + ))); + // What drawing programs write for logos and icons is drawn: gradients and clips by + // attribute, opacity, nested drawings, links. + let mut body = String::from(""); + for i in 0..60 { + body += &format!( + "\ + " + ); } - assert!(refused(&drawing(8, 8, &format!("{clips}")))); - let svg_ns = clips.replace("xml:id=", "svg:id="); - assert!(refused( - format!( - "{svg_ns}" - ) - .as_bytes() - )); - // `url()` with spaces and quotes, as the renderer reads it. - let spaced = clips.replace("xml:id=", "id=").replace("url(#", "url( \"#").replace(")'/>", " \" )'/>"); - assert!(refused(&drawing(8, 8, &format!("{spaced}")))); - // A style sheet's reference to anything but a gradient, however its rules are written (a - // quoted brace or semicolon would hide a rule from a careless reader). - let mut quoted = String::from(""); - let mut sheet = String::new(); - for k in 1..=10 { - quoted += &format!("{}", format!("", k - 1).repeat(10)); - sheet += &format!(".c{} {{ font-family: \"}};{{\"; clip-path: url(#q{}) }} ", k - 1, k - 1); + body += ""; + for i in 0..60 { + body += &format!( + "" + ); } - assert!(refused(&drawing(8, 8, &format!("{quoted}")))); - // A style that escapes what it says is not read for what it might mean: it is refused. - assert!(refused(&drawing(8, 8, ""))); - assert!(refused(&drawing(8, 8, ""))); - // An internal subset of the document type, which nothing needs. - assert!(refused(format!("'>]>").as_bytes())); + body += ""; + let image = images::decode(&drawing(40, 40, &body), 2048, 40).unwrap(); + assert!(pixel(&image, 30, 30)[1].abs_diff(GREEN[1]) <= 2, "{:?}", pixel(&image, 30, 30)); } +/// Review finding 1: a marker drawn at each point of a path whose numbers are packed so that a +/// count of them comes short. Markers are refused, whatever the path. #[test] -fn the_points_of_a_shape_are_never_counted_short() { - // Numbers run together as the path grammar allows, and commands with no number at all. +fn review_1_markers_at_packed_points_are_refused() { let marker = format!("{}", "".repeat(100)); for d in [ format!("M0 0L{}", "1.2.3.4.5.6.7.8.9".repeat(1_500)), format!("M0 0L{}", "-1-2-3-4-5-6-7-8".repeat(1_500)), format!("M0 0{}", "z".repeat(20_000)), ] { - assert!(refused(&drawing(8, 8, &format!("{marker}"))), "{}", &d[..20]); + assert!(refused(&drawing(8, 8, &format!("{marker}")))); + assert!(refused(&drawing(8, 8, &format!("{marker}")))); } } +/// Review findings 2 and 3: rules of a style sheet matched against many elements of many classes, +/// nested deep (quadratic, and work done before it was counted). A style sheet is refused before +/// anything is matched, at once. #[test] -fn a_style_sheet_of_many_rules_and_classes_is_weighed_quickly() { - // Many rules, and many elements nested deep, each of many classes: the sheet is never matched - // against the elements, so it is drawn at once. +fn review_2_and_3_a_style_sheet_is_refused_at_once() { let sheet: String = (0..1_500).map(|i| format!(".c{i}{{opacity:0.5;fill:url(#g)}}")).collect(); let classes: String = (0..60).map(|i| format!("c{i} ")).collect(); let depth = MAX_SVG_DEPTH - 4; let nested = format!( "{}{}{}", format!("").repeat(depth), - format!("").repeat(2_000), + format!("").repeat(400), "".repeat(depth) ); - let gradient = ""; - let start = Instant::now(); - assert!(images::decode(&drawing(8, 8, &format!("{gradient}{nested}")), 64, 8).is_some()); - assert!(start.elapsed() < Duration::from_secs(3), "took {:?}", start.elapsed()); + assert!(refused(&drawing(8, 8, &format!("{nested}")))); + // Without the sheet, the same elements are a plain drawing. + assert!(images::probe(&drawing(8, 8, &nested)).is_some()); } +/// Review finding 4: copies counted by the elements written, not the elements drawn (through +/// `` and through what a group gives the shapes in it). #[test] -fn what_is_copied_depending_on_where_it_is_drawn_is_refused() { - // A pattern or a marker, wherever it is, and a style sheet referring to anything but a - // gradient: what they come to depends on what inherits them or what the sheet matches. - assert!(refused(&drawing(8, 8, ""))); - assert!(refused(&drawing(8, 8, ""))); - assert!(refused(&drawing( - 8, - 8, - "" - ))); - assert!(refused(&drawing(8, 8, ""))); - // `inherit` anywhere in a style, or for a clip, a mask or a filter in an attribute. - assert!(refused(&drawing(8, 8, ""))); - assert!(refused(&drawing(8, 8, ""))); - // A comment in a style. - assert!(refused(&drawing(8, 8, ""))); - // Gradients from a style sheet are drawn, as drawing programs export them. - let gradient = "\ - "; - assert_eq!(pixel(&images::decode(&drawing(8, 8, gradient), 64, 8).unwrap(), 4, 4), GREEN); -} - -#[test] -fn references_that_multiply_are_refused() { - // Ten deep, each ten times the one before: 10^10 copies. - let mut uses = String::from(""); - for level in 1..=10 { - uses += &format!("{}", format!("", level - 1).repeat(10)); +fn review_4_copies_are_bounded_by_what_is_drawn() { + // ``, which copies what it names, ten times ten times over. + let mut uses = String::from("".to_string() + &"".repeat(50) + ""); + for level in 1..=6 { + uses += &format!("{}", format!("", level - 1).repeat(10)); } - assert!(refused(&drawing(8, 8, &format!("{uses}")))); - assert!(refused(&drawing(8, 8, &format!("{}", uses.replace("href=", "xlink:href="))))); - // Patterns that fill with patterns, through a style sheet and through attributes. + assert!(refused(&drawing(8, 8, &format!("{uses}")))); + // Under every bound counted by the elements written: a group of 600 shapes painted with a + // gradient of 500 stops, drawn 60 times, is 18 million stops copied. + let gradient = format!("{}", "".repeat(500)); + let group = format!("{}", "".repeat(600)); + assert!(refused(&drawing(8, 8, &format!("{gradient}{group}{}", "".repeat(60))))); + // A gradient of many stops given by a group to many shapes: each shape copies the stops. + let gradient = format!("{}", "".repeat(3_000)); + assert!(refused(&drawing(8, 8, &format!("{gradient}{}", "".repeat(1_000))))); + // A clip of many shapes given to many elements: each copies the clip's content. + let clip = format!("{}", "".repeat(500)); + assert!(refused(&drawing(8, 8, &format!("{clip}{}", "".repeat(500))))); + // Clips in clips through ids in any namespace, ten deep: no clip may be clipped. + let mut clips = String::from(""); + for k in 1..=10 { + clips += &format!("{}", format!("", k - 1).repeat(10)); + } + assert!(refused(&drawing(8, 8, &format!("{clips}")))); + // Patterns, masks and markers that copy themselves for what inherits them. let mut patterns = String::from(""); - for level in 1..=10 { + for k in 1..=10 { patterns += &format!( - "{}", - format!("", level - 1).repeat(10) - ); - } - let sheet: String = (0..=10).map(|i| format!(".c{i} {{ fill: url(#p{i}) }}")).collect(); - assert!(refused(&drawing(8, 8, &format!("{patterns}")))); - let attributes = patterns.replace(" class='c", " fill='url(#p").replace("'/>", ")'/>"); - assert!(refused(&drawing(8, 8, &format!("{attributes}")))); - // Clips and masks the same way, a selector that matches everything, and a marker at each - // of very many points. - let mut masks = String::from(""); - for level in 1..=10 { - masks += &format!( - "{}", - "".replace('X', &(level - 1).to_string()).repeat(10) + "{}", + k - 1, + "".repeat(10) ); } - assert!(refused(&drawing(8, 8, &format!("{masks}")))); - assert!(refused(&drawing(8, 8, ""))); - let points: String = (0..20_000).map(|i| format!(" {} {}", i % 8, i % 7)).collect(); - let marker = format!("{}", "".repeat(100)); - assert!(refused(&drawing(8, 8, &format!("{marker}")))); + assert!(refused(&drawing(8, 8, &format!("{patterns}")))); + let mask = format!("{}", "".repeat(2_000)); + assert!(refused(&drawing( + 8, + 8, + &format!("{mask}{}", "".repeat(2_000)) + ))); // A reference to itself. assert!(refused(&drawing(8, 8, ""))); } +/// Review finding 5: the layers counted by the elements written. They are counted in the tree +/// the renderer made, where each element a clip is given to is a layer of its own. #[test] -fn what_drawing_programs_write_is_not_mistaken_for_a_bomb() { - // Gradients from a style sheet and clips by attribute, as drawing programs export them, many - // of each. - let mut body = String::from(""; - for i in 0..60 { - body += &format!( - "\ - " - ); - } - body += ""; - for i in 0..60 { - body += &format!(""); - } - body += ""; - // A drop shadow. - body += "\ - "; - let image = images::decode(&drawing(40, 40, &body), 2048, 40).unwrap(); - assert_eq!(pixel(&image, 30, 30), GREEN); -} - -#[test] -fn filters_that_cost_without_bound_are_refused() { - for filter in [ - "", - "", - "", - ] { - let data = drawing(8, 8, &format!("{filter}")); - assert!(refused(&data), "{filter}"); - } - // Within bounds they are drawn. - let data = - drawing(8, 8, ""); - assert!(images::decode(&data, 64, 8).is_some()); -} - -#[test] -fn a_drawing_of_many_layers_is_drawn_with_fewer_pixels() { - let many: String = (0..800).map(|i| format!("", i % 40)).collect(); +fn review_5_layers_are_counted_in_the_tree_that_is_drawn() { let few = svg::probe(&drawing(40, 40, "")).unwrap(); - let layered = svg::probe(&drawing(40, 40, &many)).unwrap(); + let clip = ""; + let clipped = + svg::probe(&drawing(40, 40, &format!("{clip}{}", "".repeat(150)))).unwrap(); + assert!(clipped.max_pixels < few.max_pixels / 2, "{} {}", clipped.max_pixels, few.max_pixels); + let opaque: String = (0..800).map(|i| format!("", i % 40)).collect(); + let layered = svg::probe(&drawing(40, 40, &opaque)).unwrap(); assert!(layered.max_pixels < few.max_pixels, "{} {}", layered.max_pixels, few.max_pixels); - let image = images::decode(&drawing(40, 40, &many), 8192, 8192).unwrap(); + let image = images::decode(&drawing(40, 40, &opaque), 8192, 8192).unwrap(); assert!((image.size[0] * image.size[1]) as u64 <= layered.max_pixels, "{:?}", image.size); + // A style sheet's opacity on a group drawn many times over (layers counted by the elements + // written would be few): refused, as any style sheet and any `` is. + let group = format!("{}", "".repeat(900)); + assert!(refused(&drawing(40, 40, &format!("{group}{}", "".repeat(60))))); } #[test] @@ -482,10 +416,10 @@ fn arbitrary_and_damaged_svgs_never_panic() { let good = drawing( 16, 16, - "\ - \ - \ - ", + "\ + \ + \ + ", ); let pieces = ["<", ">", "/", "'", "=", " ", "", "", "url(#", "#g", "href='#c'", "\n\ + \ + Lumen WorksLogo\ + \ + \ + \ + \ + \ + \ + " + ); + let image = images::decode(logo.as_bytes(), 2048, 40).unwrap(); + assert_eq!(pixel(&image, 35, 35), GREEN); } /// Review finding 1: a marker drawn at each point of a path whose numbers are packed so that a -/// count of them comes short. Markers are refused, whatever the path. +/// count of them comes short. Markers are not allowed, whatever the path. #[test] fn review_1_markers_at_packed_points_are_refused() { let marker = format!("{}", "".repeat(100)); @@ -293,8 +328,7 @@ fn review_1_markers_at_packed_points_are_refused() { } /// Review findings 2 and 3: rules of a style sheet matched against many elements of many classes, -/// nested deep (quadratic, and work done before it was counted). A style sheet is refused before -/// anything is matched, at once. +/// nested deep. A style sheet is not allowed: refused before anything is matched, at once. #[test] fn review_2_and_3_a_style_sheet_is_refused_at_once() { let sheet: String = (0..1_500).map(|i| format!(".c{i}{{opacity:0.5;fill:url(#g)}}")).collect(); @@ -312,33 +346,21 @@ fn review_2_and_3_a_style_sheet_is_refused_at_once() { } /// Review finding 4: copies counted by the elements written, not the elements drawn (through -/// `` and through what a group gives the shapes in it). +/// ``, a clip, or what a group gives the shapes in it). #[test] fn review_4_copies_are_bounded_by_what_is_drawn() { - // ``, which copies what it names, ten times ten times over. - let mut uses = String::from("".to_string() + &"".repeat(50) + ""); - for level in 1..=6 { - uses += &format!("{}", format!("", level - 1).repeat(10)); - } - assert!(refused(&drawing(8, 8, &format!("{uses}")))); // Under every bound counted by the elements written: a group of 600 shapes painted with a - // gradient of 500 stops, drawn 60 times, is 18 million stops copied. + // gradient of 500 stops, drawn 60 times, is 18 million stops copied. `` is not allowed. let gradient = format!("{}", "".repeat(500)); let group = format!("{}", "".repeat(600)); assert!(refused(&drawing(8, 8, &format!("{gradient}{group}{}", "".repeat(60))))); // A gradient of many stops given by a group to many shapes: each shape copies the stops. let gradient = format!("{}", "".repeat(3_000)); assert!(refused(&drawing(8, 8, &format!("{gradient}{}", "".repeat(1_000))))); - // A clip of many shapes given to many elements: each copies the clip's content. - let clip = format!("{}", "".repeat(500)); - assert!(refused(&drawing(8, 8, &format!("{clip}{}", "".repeat(500))))); - // Clips in clips through ids in any namespace, ten deep: no clip may be clipped. - let mut clips = String::from(""); - for k in 1..=10 { - clips += &format!("{}", format!("", k - 1).repeat(10)); - } - assert!(refused(&drawing(8, 8, &format!("{clips}")))); - // Patterns, masks and markers that copy themselves for what inherits them. + // A clip of a path of many segments given to many elements. Clips are not allowed. + let clip = format!("", "h1".repeat(20_000)); + assert!(refused(&drawing(8, 8, &format!("{clip}{}", "".repeat(1_000))))); + // Patterns and masks that copy themselves for what inherits them. let mut patterns = String::from(""); for k in 1..=10 { patterns += &format!( @@ -354,30 +376,66 @@ fn review_4_copies_are_bounded_by_what_is_drawn() { 8, &format!("{mask}{}", "".repeat(2_000)) ))); - // A reference to itself. - assert!(refused(&drawing(8, 8, ""))); } /// Review finding 5: the layers counted by the elements written. They are counted in the tree -/// the renderer made, where each element a clip is given to is a layer of its own. +/// the renderer made; a layer inside a layer is refused, and more shapes and layers mean fewer +/// pixels. #[test] fn review_5_layers_are_counted_in_the_tree_that_is_drawn() { let few = svg::probe(&drawing(40, 40, "")).unwrap(); - let clip = ""; - let clipped = - svg::probe(&drawing(40, 40, &format!("{clip}{}", "".repeat(150)))).unwrap(); - assert!(clipped.max_pixels < few.max_pixels / 2, "{} {}", clipped.max_pixels, few.max_pixels); let opaque: String = (0..800).map(|i| format!("", i % 40)).collect(); let layered = svg::probe(&drawing(40, 40, &opaque)).unwrap(); - assert!(layered.max_pixels < few.max_pixels, "{} {}", layered.max_pixels, few.max_pixels); + assert!(layered.max_pixels < few.max_pixels / 4, "{} {}", layered.max_pixels, few.max_pixels); let image = images::decode(&drawing(40, 40, &opaque), 8192, 8192).unwrap(); assert!((image.size[0] * image.size[1]) as u64 <= layered.max_pixels, "{:?}", image.size); - // A style sheet's opacity on a group drawn many times over (layers counted by the elements - // written would be few): refused, as any style sheet and any `` is. + // A style sheet's opacity on a group drawn many times over. let group = format!("{}", "".repeat(900)); assert!(refused(&drawing(40, 40, &format!("{group}{}", "".repeat(60))))); } +/// The second review of the plain-drawing rules: each of its drawings, as it wrote them. +#[test] +fn review_6_what_got_past_the_first_plain_rules_is_refused() { + let svg = |body: String| format!("{body}").into_bytes(); + // Gradients that refer to each other in a ring: usvg follows them for ever. + assert!(refused(&svg( + "".into() + ))); + // A `>` in a quoted literal of the document type, which a careless scan would take as its end + // and so miss a thousand levels of nesting behind a comment it never closed. + let n = 1_000; + for (open, close) in [("", ""), ("", "")] { + let data = format!( + "", + open.repeat(n), + close.repeat(n) + ); + assert!(refused(data.as_bytes())); + } + // Dashes, many to a path and many paths. + assert!(refused(&svg("".repeat(20)))); + // A clip of a long path given to many elements. + assert!(refused(&svg(format!( + "{}", + "h1".repeat(20_000), + "".repeat(1_000) + )))); + // Layers, nested and side by side, each larger than the drawing. + let huge = ""; + assert!(refused(&svg(format!("{}{huge}{}", "".repeat(30), "".repeat(30))))); + assert!(refused(&svg(format!("{huge}").repeat(30)))); + // Drawings in drawings, with their opacities and blend modes. + assert!(refused(&svg(format!( + "{}{}", + "".repeat(30), + "".repeat(30) + )))); + // Shapes larger than the drawing, side by side, are drawn with fewer pixels the more there are. + let many = svg::probe(&svg("".repeat(3_500))).unwrap(); + assert!(many.max_pixels <= MAX_SVG_PIXELS / 16, "{}", many.max_pixels); +} + #[test] fn a_damaged_svg_is_a_broken_picture() { for data in [ @@ -416,10 +474,10 @@ fn arbitrary_and_damaged_svgs_never_panic() { let good = drawing( 16, 16, - "\ - \ - \ - ", + "\ + \ + \ + ", ); let pieces = ["<", ">", "/", "'", "=", " ", "", "", "url(#", "#g", "href='#c'", "") } else if rest.starts_with(b"' || b == b'['); + // Its internal subset, if any, in brackets, then the end of it: a `>` or `[` inside + // a quoted literal (`SYSTEM "urn:a>b"`) is no end of it. + let mut quote = None; + let close = rest.iter().position(|&b| match quote { + Some(q) => { + quote = (b != q).then_some(q); + false + } + None if b == b'"' || b == b'\'' => { + quote = Some(b); + false + } + None => b == b'>' || b == b'[', + }); match close.and_then(|at| rest.get(at).map(|b| (at, *b))) { Some((at, b'[')) => after(rest, at, b"]").and_then(|end| after(rest, end, b">")), Some((at, _)) => Some(at + 1), diff --git a/crates/html/src/data_svg_tests.rs b/crates/html/src/data_svg_tests.rs index 3b21f5d776..78ca2ddf93 100644 --- a/crates/html/src/data_svg_tests.rs +++ b/crates/html/src/data_svg_tests.rs @@ -70,6 +70,9 @@ fn an_svg_is_known_by_its_first_element() { format!("\n\n{SVG}"), format!("{SVG}"), format!(" ]>{SVG}"), + // A `>` or a `[` in a quoted literal of the document type is no end of it. + format!("b\">{SVG}"), + format!("y\">{SVG}"), "".to_string(), "".to_string(), "".to_string(), @@ -87,6 +90,7 @@ fn an_svg_is_known_by_its_first_element() { "", "", "", + "b>", "\u{89}PNG", ] { assert!(!looks_like_svg(no.as_bytes()), "{no:?}"); diff --git a/crates/i18n/po/he.po b/crates/i18n/po/he.po index cb188fa9c8..a935553d7b 100644 --- a/crates/i18n/po/he.po +++ b/crates/i18n/po/he.po @@ -24365,9 +24365,8 @@ msgstr "יש לו שתי חריגות מסוג אחד שמחפשות דברים #. interface #: crates/ui-egui/src/reading/images.rs -#, fuzzy -msgid "it is a drawing of a kind that isn't shown (SVG)" -msgstr "מדובר באיור מסוג שאינו מוצג (SVG)" +msgid "it is a drawing (SVG) that is damaged or can't be shown" +msgstr "" #. interface #: crates/ui-egui/src/reading/images.rs @@ -29189,6 +29188,10 @@ msgstr "−בינארי" msgid "−Lines" msgstr "−שורות" +#, fuzzy +#~ msgid "it is a drawing of a kind that isn't shown (SVG)" +#~ msgstr "מדובר באיור מסוג שאינו מוצג (SVG)" + #, fuzzy #~ msgid "It is held in memory until MailCraft closes, and never saved. Send Again sends the message that waits for it." #~ msgstr "הוא נשמר בזיכרון עד לסגירת MailCraft, ולעולם אינו נשמר בדיסק. 'שליחה חוזרת' שולחת את ההודעה שממתינה לו." diff --git a/crates/i18n/po/ja.po b/crates/i18n/po/ja.po index 96ac372565..41c76addb2 100644 --- a/crates/i18n/po/ja.po +++ b/crates/i18n/po/ja.po @@ -24308,9 +24308,8 @@ msgstr "異なる内容を探す同じ種類の例外が 2 つあり、サーバ #. interface #: crates/ui-egui/src/reading/images.rs -#, fuzzy -msgid "it is a drawing of a kind that isn't shown (SVG)" -msgstr "表示されない種類の図 (SVG) です" +msgid "it is a drawing (SVG) that is damaged or can't be shown" +msgstr "" #. interface #: crates/ui-egui/src/reading/images.rs @@ -28997,6 +28996,10 @@ msgstr "−バイナリ" msgid "−Lines" msgstr "−行" +#, fuzzy +#~ msgid "it is a drawing of a kind that isn't shown (SVG)" +#~ msgstr "表示されない種類の図 (SVG) です" + #, fuzzy #~ msgid "It is held in memory until MailCraft closes, and never saved. Send Again sends the message that waits for it." #~ msgstr "MailCraft を閉じるまでメモリに保持され、保存されることはありません。再送信で、これを待っているメッセージが送信されます。" diff --git a/crates/i18n/po/pt_BR.po b/crates/i18n/po/pt_BR.po index 89d874686a..c9e6080fcf 100644 --- a/crates/i18n/po/pt_BR.po +++ b/crates/i18n/po/pt_BR.po @@ -24362,9 +24362,8 @@ msgstr "tem duas exceções do mesmo tipo que procuram coisas diferentes, e o se #. interface #: crates/ui-egui/src/reading/images.rs -#, fuzzy -msgid "it is a drawing of a kind that isn't shown (SVG)" -msgstr "é um desenho de um tipo que não é mostrado (SVG)" +msgid "it is a drawing (SVG) that is damaged or can't be shown" +msgstr "" #. interface #: crates/ui-egui/src/reading/images.rs @@ -29186,6 +29185,10 @@ msgstr "−Bin" msgid "−Lines" msgstr "−Linhas" +#, fuzzy +#~ msgid "it is a drawing of a kind that isn't shown (SVG)" +#~ msgstr "é um desenho de um tipo que não é mostrado (SVG)" + #, fuzzy #~ msgid "It is held in memory until MailCraft closes, and never saved. Send Again sends the message that waits for it." #~ msgstr "Fica na memória até o MailCraft fechar e nunca é salva. Enviar Novamente envia a mensagem que espera por ela." diff --git a/crates/i18n/po/pt_PT.po b/crates/i18n/po/pt_PT.po index c5481b2ae9..ae581774c6 100644 --- a/crates/i18n/po/pt_PT.po +++ b/crates/i18n/po/pt_PT.po @@ -24362,9 +24362,8 @@ msgstr "tem duas exceções do mesmo tipo que procuram coisas diferentes, e o se #. interface #: crates/ui-egui/src/reading/images.rs -#, fuzzy -msgid "it is a drawing of a kind that isn't shown (SVG)" -msgstr "é um desenho de um tipo que não é mostrado (SVG)" +msgid "it is a drawing (SVG) that is damaged or can't be shown" +msgstr "" #. interface #: crates/ui-egui/src/reading/images.rs @@ -29186,6 +29185,10 @@ msgstr "−Bin" msgid "−Lines" msgstr "−Linhas" +#, fuzzy +#~ msgid "it is a drawing of a kind that isn't shown (SVG)" +#~ msgstr "é um desenho de um tipo que não é mostrado (SVG)" + #, fuzzy #~ msgid "It is held in memory until MailCraft closes, and never saved. Send Again sends the message that waits for it." #~ msgstr "Fica na memória até o MailCraft fechar e nunca é guardado. Enviar de Novo envia a mensagem que está à espera." diff --git a/crates/i18n/po/sl.po b/crates/i18n/po/sl.po index 8ead122860..0b255508a1 100644 --- a/crates/i18n/po/sl.po +++ b/crates/i18n/po/sl.po @@ -24470,9 +24470,8 @@ msgstr "ima dve izjemi iste vrste, ki iščeta različne stvari, strežnik pa vz #. interface #: crates/ui-egui/src/reading/images.rs -#, fuzzy -msgid "it is a drawing of a kind that isn't shown (SVG)" -msgstr "je risba vrste, ki se ne prikaže (SVG)" +msgid "it is a drawing (SVG) that is damaged or can't be shown" +msgstr "" #. interface #: crates/ui-egui/src/reading/images.rs @@ -29564,6 +29563,10 @@ msgstr "−Bin" msgid "−Lines" msgstr "−Vrstice" +#, fuzzy +#~ msgid "it is a drawing of a kind that isn't shown (SVG)" +#~ msgstr "je risba vrste, ki se ne prikaže (SVG)" + #, fuzzy #~ msgid "It is held in memory until MailCraft closes, and never saved. Send Again sends the message that waits for it." #~ msgstr "V pomnilniku je do zaprtja programa MailCraft in se nikoli ne shrani. Pošlji znova pošlje sporočilo, ki čaka nanj." diff --git a/crates/ui-egui/src/reading/svg.rs b/crates/ui-egui/src/reading/svg.rs index 04aa2f4ee1..eb0492e575 100644 --- a/crates/ui-egui/src/reading/svg.rs +++ b/crates/ui-egui/src/reading/svg.rs @@ -356,7 +356,7 @@ fn plain(document: &roxmltree::Document) -> Option { shapes += u64::from(shape); stops += u64::from(matches!(name, "stop" | "linearGradient" | "radialGradient")); } - // usvg strokes every stroked path as it reads it, on the window's thread, for its bounds: a + // usvg strokes every stroked path as it reads it, for its bounds: a // stroked drawing's segments (a shape that isn't a path is a few), each weighted for what the // stroker makes of it, are bounded before usvg sees it. let segments = path_text.saturating_add(shapes.saturating_mul(8)); @@ -371,12 +371,13 @@ fn plain(document: &roxmltree::Document) -> Option { return None; } let steps = 1 + (ratio / STROKE_RATIO_STEP) as u64; - let weight = if round { + // Nothing stroked, nothing to stroke, whatever a `style` or a join says of rounds. + let weight = if !stroked { + 0 + } else if round { 1 + READ_ROUND_WEIGHT - } else if stroked { - 1 + READ_STROKE_WEIGHT } else { - 0 + 1 + READ_STROKE_WEIGHT } .saturating_mul(steps); let strokes_fit = segments.saturating_mul(weight) <= MAX_READ_STROKES; @@ -458,7 +459,8 @@ fn finest_of(node: roxmltree::Node, name: &str, whole: f64, dust: f64) -> (f64, let number = |name: &str| node.attribute(name).and_then(|v| user_length(v, whole)).unwrap_or(0.0); let point = |name: &str| node.attribute(name).and_then(|v| v.trim().parse::().ok()).unwrap_or(0.0); match name { - "rect" => [number("width"), number("height")].into_iter().for_each(&mut piece), + // Its corners too: `rx` and `ry` (when given) are drawn as four arcs of that size. + "rect" => [number("width"), number("height"), number("rx"), number("ry")].into_iter().for_each(&mut piece), "circle" => piece(number("r")), "ellipse" => [number("rx"), number("ry")].into_iter().for_each(&mut piece), "line" => [point("x2") - point("x1"), point("y2") - point("y1")].into_iter().for_each(&mut piece), @@ -511,8 +513,8 @@ fn text_lines(text: &str) -> u64 { /// What stroking a segment takes, for its bounds as usvg reads the drawing: a few curves for its /// sides (8), and with round joins or caps up to three conics of 16 curves each (48 more), at -/// most [`MAX_READ_STROKES`] for a drawing, so that reading one is a bounded amount of work on -/// the window's thread. +/// most [`MAX_READ_STROKES`] for a drawing, so that reading one is a bounded amount of work for +/// the thread that reads it. const READ_STROKE_WEIGHT: u64 = 8; const READ_ROUND_WEIGHT: u64 = 48; const MAX_READ_STROKES: u64 = 2_000_000; diff --git a/crates/ui-egui/src/reading/svg_tests.rs b/crates/ui-egui/src/reading/svg_tests.rs index 8b21dfcbf3..293af89ccf 100644 --- a/crates/ui-egui/src/reading/svg_tests.rs +++ b/crates/ui-egui/src/reading/svg_tests.rs @@ -411,6 +411,8 @@ fn review_6_what_got_past_the_first_plain_rules_is_refused() { open.repeat(n), close.repeat(n) ); + // It is known for a drawing (the `>` is in a literal), so it is the nesting that refuses it. + assert!(mailcraft_html::looks_like_svg(data.as_bytes())); assert!(refused(data.as_bytes())); } // Dashes, many to a path and many paths. diff --git a/crates/ui-egui/src/reading/svg_wide_stroke_tests.rs b/crates/ui-egui/src/reading/svg_wide_stroke_tests.rs index 8af17a327e..84e30bf3ff 100644 --- a/crates/ui-egui/src/reading/svg_wide_stroke_tests.rs +++ b/crates/ui-egui/src/reading/svg_wide_stroke_tests.rs @@ -207,3 +207,42 @@ fn review_12_important_is_read_in_any_case() { let _ = read(&styled(2, &format!("stroke=\"black\" style=\"stroke-width:{width}\""))); } } + +/// Review of #830, round two: a rounded rect is drawn as four corner arcs, and usvg strokes them +/// all as it builds the tree, so `rx` and `ry` are pieces of the stroke's bound like the sides. +#[test] +fn review_13_a_stroked_rect_with_dust_corners_is_refused() { + let rect = |corners: &str| format!(""); + // 17 rects: one more than the most pieces of dust a stroked drawing may have (`MAX_DUST`, 16). + for corners in ["rx=\"1e-7\" ry=\"1e-7\"", "rx=\"1e-7\""] { + let (took, probed) = read(&drawn(&rect(corners).repeat(17))); + assert!(took < Duration::from_secs(1) && probed.is_none(), "{corners}: {took:?} {probed:?}"); + } + // Corners of a size that is one, and none at all, are drawn; so are dust corners that are + // not stroked. + for corners in ["rx=\"10\" ry=\"10\"", "rx=\"0.5\"", ""] { + let (took, probed) = read(&drawn(&rect(corners).repeat(17))); + assert!(took < DRAWN && probed == Some([100, 100]), "{corners}: {took:?} {probed:?}"); + } + let filled = "".repeat(17); + assert_eq!(read(&drawn(&filled)).1, Some([100, 100])); +} + +/// Review of #830, round two: the weight of round joins and caps is for what is stroked: a +/// flat logo that only fills, and says "round" in the name of a gradient or in a join it never +/// strokes with, is no heavier for it. +#[test] +fn review_13_a_drawing_that_strokes_nothing_is_not_weighed_as_round_stroked() { + // About 42,000 segments: under the cap as a plain stroke (x9), over it with round ones (x49). + let path = |attributes: &str| format!("", " l1 1".repeat(14_000)); + let gradient = ""; + for attributes in ["style=\"fill:url(#rounded)\"", "fill=\"none\" stroke=\"none\" stroke-linejoin=\"round\"", "stroke-linecap=\"round\""] { + let (took, probed) = read(&drawn(&format!("{gradient}{}", path(attributes)))); + assert!(took < DRAWN && probed == Some([100, 100]), "{attributes}: {took:?} {probed:?}"); + } + // Stroked with round joins it is that heavy. + let (took, probed) = read(&drawn(&path("fill=\"none\" stroke=\"black\" stroke-linejoin=\"round\""))); + assert!(took < Duration::from_secs(1) && probed.is_none(), "{took:?} {probed:?}"); + // And stroked with plain ones it fits. + assert_eq!(read(&drawn(&path("fill=\"none\" stroke=\"black\""))).1, Some([100, 100])); +} diff --git a/crates/ui-egui/src/reading/tests.rs b/crates/ui-egui/src/reading/tests.rs index a9feb55304..f28c55cc4e 100644 --- a/crates/ui-egui/src/reading/tests.rs +++ b/crates/ui-egui/src/reading/tests.rs @@ -1334,8 +1334,8 @@ fn the_reading_pane_names_nothing_that_could_fetch() { checked += 1; } assert_eq!( - checked, 31, - "reading.rs, attachment pictures (and its tests), backdrop (and its tests), colors (and its tests), encrypted (and its tests), the font faces test, header tests, images (and its tests), invitation, layout, remote, react (and its tests), scroll keys tests, select, sharing (and its tests), signature (and its tests), svg, unsubscribe (and its tests), view (and its zoom tests) and warnings (and its tests)" + checked, 32, + "reading.rs, attachment pictures (and its tests), backdrop (and its tests), colors (and its tests), encrypted (and its tests), the font faces test, header tests, images (and its tests), invitation, layout, remote, react (and its tests), scroll keys tests, select, sharing (and its tests), signature (and its tests), svg (and its tests), unsubscribe (and its tests), view (and its zoom tests) and warnings (and its tests)" ); } diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 661fe3b532..90ee543264 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -2,7 +2,7 @@ > Generated by `cargo xtask parity` from `crates/engine/src/catalog.rs` and the command registry. Do not edit by hand. -**258 of 319 in-scope catalog features have a command (80.9%); 0 are Complete (0%).** 17 more rows are out of scope and left out of both. The registry holds 396 commands. +**259 of 319 in-scope catalog features have a command (81.2%); 0 are Complete (0%).** 17 more rows are out of scope and left out of both. The registry holds 402 commands. **Has a command** means the behaviour is reachable by id (ribbon, shortcut, CLI, control channel, MCP); it says nothing of how closely it behaves as the incumbent's does. **Complete** means the behaviour matches the incumbent's as far as MailCraft's rules allow, a test shows it, and `docs/gaps.md` has no open row for it. How far the rest falls short is tracked in `docs/gaps.md` and the per-area parity checklists. @@ -19,7 +19,7 @@ | Message | 32 | 0 | 32 | | Insert | 7 | 0 | 13 | | Picture Format | 1 | 0 | 1 | -| Options | 5 | 0 | 12 | +| Options | 6 | 0 | 12 | | Format Text | 5 | 0 | 8 | | Review | 2 | 0 | 6 | | Attachments | 4 | 0 | 7 | @@ -69,7 +69,6 @@ | Options | Themes | Themes | `options.theme` | | Options | Themes | Page Color | `options.pageColor` | | Options | Encrypt | Encrypt | `compose.encrypt` | -| Options | Encrypt | Sign | `compose.sign` | | Options | Tracking | Use Voting Buttons | `compose.voting` | | Options | Tracking | Request a Delivery Receipt | `compose.deliveryReceipt` | | Options | More Options | Save Sent Item To | `compose.saveSentTo` |