diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml
index 1dcdb236ea..b261233570 100644
--- a/.github/workflows/fuzz.yml
+++ b/.github/workflows/fuzz.yml
@@ -7,7 +7,7 @@ name: Fuzz
on:
pull_request:
- paths: [fuzz/**, crates/assuan/**, crates/ber/**, crates/dav/**, crates/charset/**, crates/engine/**, crates/ews/**, crates/html/**, crates/i18n/src/**, .github/workflows/fuzz.yml, crates/ical/**, crates/jmap/**, crates/link/**, crates/mime/**, crates/mime-model/**, crates/model/**, crates/proto/**, crates/oab/**, crates/openpgp/**, crates/pst/**, crates/smime/**, crates/spell/**, crates/tnef/**, crates/vcard/**]
+ paths: [fuzz/**, crates/assuan/**, crates/ber/**, crates/dav/**, crates/charset/**, crates/engine/**, crates/ews/**, crates/html/**, crates/i18n/src/**, .github/workflows/fuzz.yml, crates/ical/**, crates/jmap/**, crates/link/**, crates/mime/**, crates/mime-model/**, crates/model/**, crates/proto/**, crates/oab/**, crates/openpgp/**, crates/pst/**, crates/smime/**, crates/spell/**, crates/tnef/**, crates/ui-egui/src/reading/svg.rs, crates/vcard/**]
schedule:
- cron: '17 4 * * 1'
workflow_dispatch:
@@ -36,7 +36,7 @@ jobs:
PR: ${{ github.event.pull_request.number }}
REPO: ${{ github.repository }}
run: |
- all="assuan dav_xml dav_answers dav_apply dav_discovery dav_document mime html sheet ical vcard charset link imap smtp po jmap_address jmap_discovery jmap_response jmap_session ews ews_autodiscover ews_ntlm pst oab rtf mailbox_file header_block openpgp openpgp_decrypt smime smime_decrypt pkcs12 tnef spell"
+ all="assuan dav_xml dav_answers dav_apply dav_discovery dav_document mime html sheet ical vcard charset link imap smtp po jmap_address jmap_discovery jmap_response jmap_session ews ews_autodiscover ews_ntlm pst oab rtf mailbox_file header_block openpgp openpgp_decrypt smime smime_decrypt pkcs12 tnef spell svg"
paths_of() {
case "$1" in
assuan) echo crates/assuan/ ;;
@@ -60,6 +60,7 @@ jobs:
mime) echo crates/mime/ crates/mime-model/ ;;
openpgp|openpgp_decrypt) echo crates/openpgp/ crates/ber/ ;;
smime|smime_decrypt) echo crates/smime/ crates/model/ crates/ber/ ;;
+ svg) echo crates/ui-egui/src/reading/svg.rs crates/html/src/data.rs ;;
tnef) echo crates/tnef/ ;;
spell) echo crates/spell/ ;;
pkcs12) echo crates/smime/ crates/ber/ ;;
diff --git a/Cargo.lock b/Cargo.lock
index e6b053a0cf..869b1743dc 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2426,7 +2426,7 @@ dependencies = [
"hashbrown 0.17.1",
"log",
"peniko",
- "png",
+ "png 0.18.1",
"skrifa 0.44.0",
"smallvec",
"vello_common",
@@ -2701,7 +2701,7 @@ dependencies = [
"image-webp",
"moxcms",
"num-traits",
- "png",
+ "png 0.18.1",
"tiff",
"zune-core",
"zune-jpeg",
@@ -2717,6 +2717,12 @@ dependencies = [
"quick-error 2.0.1",
]
+[[package]]
+name = "imagesize"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285"
+
[[package]]
name = "imagesize"
version = "0.15.0"
@@ -2999,6 +3005,17 @@ dependencies = [
"zbus",
]
+[[package]]
+name = "kurbo"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c62026ae44756f8a599ba21140f350303d4f08dcdcc71b5ad9c9bb8128c13c62"
+dependencies = [
+ "arrayvec",
+ "euclid",
+ "smallvec",
+]
+
[[package]]
name = "kurbo"
version = "0.13.1"
@@ -3581,10 +3598,12 @@ dependencies = [
"mailcraft-pst",
"mailcraft-spell",
"mailcraft-time",
+ "resvg 0.45.1",
"serde",
"serde_json",
"sha2 0.11.1",
"skrifa 0.50.0",
+ "svgtypes 0.15.3",
"tempfile",
"toml",
"zeroize",
@@ -3726,7 +3745,7 @@ dependencies = [
"objc2-app-kit 0.3.2",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
- "png",
+ "png 0.18.1",
"thiserror 2.0.21",
"windows-sys 0.61.2",
]
@@ -4601,7 +4620,7 @@ checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6"
dependencies = [
"bytemuck",
"color",
- "kurbo",
+ "kurbo 0.13.1",
"linebender_resource_handle",
"smallvec",
]
@@ -4848,6 +4867,19 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
+[[package]]
+name = "png"
+version = "0.17.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"
+dependencies = [
+ "bitflags 1.3.2",
+ "crc32fast",
+ "fdeflate",
+ "flate2",
+ "miniz_oxide 0.8.9",
+]
+
[[package]]
name = "png"
version = "0.18.1"
@@ -5285,6 +5317,20 @@ version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51743d3e274e2b18df81c4dc6caf8a5b8e15dbe799e0dca05c7617380094e884"
+[[package]]
+name = "resvg"
+version = "0.45.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43"
+dependencies = [
+ "log",
+ "pico-args",
+ "rgb",
+ "svgtypes 0.15.3",
+ "tiny-skia 0.11.4",
+ "usvg 0.45.1",
+]
+
[[package]]
name = "resvg"
version = "0.50.0"
@@ -5295,9 +5341,9 @@ dependencies = [
"log",
"pico-args",
"rgb",
- "svgtypes",
+ "svgtypes 0.16.2",
"tiny-skia 0.12.0",
- "usvg",
+ "usvg 0.50.0",
]
[[package]]
@@ -5380,6 +5426,12 @@ dependencies = [
"digest 0.10.7",
]
+[[package]]
+name = "roxmltree"
+version = "0.20.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
+
[[package]]
name = "roxmltree"
version = "0.21.2"
@@ -6167,13 +6219,23 @@ version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+[[package]]
+name = "svgtypes"
+version = "0.15.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc"
+dependencies = [
+ "kurbo 0.11.3",
+ "siphasher",
+]
+
[[package]]
name = "svgtypes"
version = "0.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f12b12995e3638c70618c1facb1ce65302f6a6f706b675f07c58a5d7391120e"
dependencies = [
- "kurbo",
+ "kurbo 0.13.1",
"siphasher",
]
@@ -6367,6 +6429,7 @@ dependencies = [
"bytemuck",
"cfg-if",
"log",
+ "png 0.17.16",
"tiny-skia-path 0.11.4",
]
@@ -6381,7 +6444,7 @@ dependencies = [
"bytemuck",
"cfg-if",
"log",
- "png",
+ "png 0.18.1",
"tiny-skia-path 0.12.0",
]
@@ -6534,7 +6597,7 @@ dependencies = [
"objc2-core-graphics",
"objc2-foundation 0.3.2",
"once_cell",
- "png",
+ "png 0.18.1",
"thiserror 2.0.21",
"windows-sys 0.61.2",
]
@@ -6722,6 +6785,28 @@ version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
+[[package]]
+name = "usvg"
+version = "0.45.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef"
+dependencies = [
+ "base64 0.22.1",
+ "data-url",
+ "flate2",
+ "imagesize 0.13.0",
+ "kurbo 0.11.3",
+ "log",
+ "pico-args",
+ "roxmltree 0.20.0",
+ "simplecss",
+ "siphasher",
+ "strict-num",
+ "svgtypes 0.15.3",
+ "tiny-skia-path 0.11.4",
+ "xmlwriter",
+]
+
[[package]]
name = "usvg"
version = "0.50.0"
@@ -6729,15 +6814,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bdb896f04730b97805bbc3191fc57e4bf03face0f14577dd42e783c4d8c98802"
dependencies = [
"data-url",
- "imagesize",
- "kurbo",
+ "imagesize 0.15.0",
+ "kurbo 0.13.1",
"log",
"pico-args",
- "roxmltree",
+ "roxmltree 0.21.2",
"simplecss",
"siphasher",
"strict-num",
- "svgtypes",
+ "svgtypes 0.16.2",
"tiny-skia-path 0.12.0",
]
@@ -6763,7 +6848,7 @@ dependencies = [
"guillotiere",
"log",
"peniko",
- "png",
+ "png 0.18.1",
"smallvec",
"thiserror 2.0.21",
]
@@ -6777,7 +6862,7 @@ dependencies = [
"bytemuck",
"glifo",
"hashbrown 0.17.1",
- "png",
+ "png 0.18.1",
"vello_common",
]
@@ -7722,6 +7807,12 @@ version = "0.8.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
+[[package]]
+name = "xmlwriter"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
+
[[package]]
name = "xtask"
version = "0.16.0"
@@ -7729,7 +7820,7 @@ dependencies = [
"image",
"mailcraft-charset",
"mailcraft-i18n",
- "resvg",
+ "resvg 0.50.0",
"ring",
"serde_json",
]
diff --git a/Cargo.toml b/Cargo.toml
index f6d9ef1c29..d8b9bb6cc0 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -147,6 +147,12 @@ ed25519-dalek = { version = "2", default-features = false }
# (which brings BMP, the pictures inside one) for a sender's picture that is a web site's icon
# alone: everything else names the kinds it decodes (`reading::images::KINDS`).
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "ico"] }
+# SVG drawings: the pictures of mail that are SVG (#565, `reading::svg`) and the app icon
+# (`cargo xtask icon`). Pure Rust (usvg, tiny-skia). None of its features: no text, so no fonts are
+# looked for or read, and no decoders of the pictures a drawing may hold, which are never loaded.
+resvg = { version = "0.45", default-features = false }
+# The path and length syntax of SVG, which resvg reads with (already in the tree): a drawing is measured with it before resvg reads it (`reading::svg`).
+svgtypes = "0.15"
# ui
egui = "0.37"
diff --git a/apps/mailcraft/src/picture_cache.rs b/apps/mailcraft/src/picture_cache.rs
index 82256cb581..c271d921b0 100644
--- a/apps/mailcraft/src/picture_cache.rs
+++ b/apps/mailcraft/src/picture_cache.rs
@@ -20,8 +20,9 @@
//! Not the address (only its hash: the folder doesn't list what was read), not the message,
//! not who sent it, nothing a server said besides the bytes. The same picture at two addresses
//! is one file.
-//! - **Only pictures:** bytes are kept when they begin as a PNG, a JPEG, a GIF or a WebP does
-//! (or an ICO, a web site's icon, for a sender's picture: [`Cache::get_as`]) and are no
+//! - **Only pictures:** bytes are kept when they begin as a PNG, a JPEG, a GIF, a WebP or an SVG
+//! drawing does (#565; or an ICO, a web site's icon, for a sender's picture, which is never a
+//! drawing: [`Cache::get_as`]) and are no
//! larger than a download may be; the window, which decodes them, takes back what turns
//! out to be none ([`Cache::forget`]). Nothing here is ever run, opened by another program on
//! our say-so, or served to anyone: a file is read back as bytes, and only when it is a plain
@@ -123,8 +124,15 @@ fn clock() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |since| since.as_secs())
}
-/// Whether bytes begin the way a picture that is shown begins: PNG, JPEG, GIF or WebP.
+/// Whether bytes begin the way a picture of a message that is shown begins: PNG, JPEG, GIF, WebP
+/// or an SVG drawing (#565).
pub fn looks_like_a_picture(bytes: &[u8]) -> bool {
+ looks_like_a_raster(bytes) || mailcraft_ui_egui::looks_like_svg(bytes)
+}
+
+/// Whether bytes begin the way a PNG, JPEG, GIF or WebP does: a picture of pixels, as a sender's
+/// picture is ([`crate::sender_images`]).
+pub fn looks_like_a_raster(bytes: &[u8]) -> bool {
bytes.starts_with(b"\x89PNG\r\n\x1a\n")
|| bytes.starts_with(b"\xff\xd8\xff")
|| bytes.starts_with(b"GIF87a")
@@ -760,16 +768,24 @@ mod tests {
bytes.extend([7u8; 60]);
bytes
};
- for (name, bytes) in
- [("png", png(2, 64)), ("jpeg", b"\xff\xd8\xff\xe0\0\x10JFIF\0rest".to_vec()), ("gif", b"GIF89a\x01\0\x01\0rest".to_vec()), ("webp", webp)]
- {
+ for (name, bytes) in [
+ ("png", png(2, 64)),
+ ("jpeg", b"\xff\xd8\xff\xe0\0\x10JFIF\0rest".to_vec()),
+ ("gif", b"GIF89a\x01\0\x01\0rest".to_vec()),
+ ("webp", webp),
+ // A drawing (#565), which the window draws with what it says runs left out.
+ ("svg", b"\n ".to_vec()),
+ ] {
assert!(looks_like_a_picture(&bytes) && cache.put(&format!("https://img.example/{name}"), &bytes), "{name}");
+ assert_eq!(cache.get(&format!("https://img.example/{name}")).as_deref(), Some(&bytes[..]), "{name}");
}
+ // A drawing is no sender's picture.
+ assert!(!looks_like_a_raster(b" "));
let too_large = png(3, MAX_PICTURE + 1);
for (what, bytes) in [
("nothing", &b""[..]),
("a web page", b""),
- ("a drawing with a script", b" "),
+ ("a web page with a drawing in it", b" "),
("a program", b"MZ\x90\0\x03\0\0\0\x04\0\0\0\xff\xff\0\0"),
("a script", b"#!/bin/sh\nrm -rf ~\n"),
("a shortcut", b"[InternetShortcut]\r\nURL=file:///C:/Windows/System32/calc.exe\r\n"),
@@ -783,7 +799,7 @@ mod tests {
}
assert_eq!(cache.get("https://img.example/other"), None);
assert!(!cache.put("", &png(4, 64)) && !cache.put(&"a".repeat(MAX_ADDRESS + 1), &png(4, 64)));
- assert_eq!(cache.usage().0, 4);
+ assert_eq!(cache.usage().0, 5);
// Every file kept has a name of 64 hex digits and nothing after it: nothing to run.
for file in temp.files().iter().filter(|file| *file != "index") {
let name = file.rsplit('/').next().unwrap();
diff --git a/apps/mailcraft/src/sender_images.rs b/apps/mailcraft/src/sender_images.rs
index dff9245650..e9e92c05ed 100644
--- a/apps/mailcraft/src/sender_images.rs
+++ b/apps/mailcraft/src/sender_images.rs
@@ -63,11 +63,12 @@ fn site(domain: &str) -> &str {
if provider::is_public_suffix(last(2)) { last(3) } else { last(2) }
}
-/// Whether bytes begin as a sender's picture does: as a message's pictures do
-/// ([`picture_cache::looks_like_a_picture`]), or as an ICO holding a picture or more, a web
-/// site's icon, which only a sender's picture may be.
+/// Whether bytes begin as a sender's picture does: as a message's pictures of pixels do
+/// ([`picture_cache::looks_like_a_raster`]; never an SVG drawing, which a message's picture may
+/// be), or as an ICO holding a picture or more, a web site's icon, which only a sender's picture
+/// may be.
fn looks_like_a_picture(bytes: &[u8]) -> bool {
- picture_cache::looks_like_a_picture(bytes) || (bytes.starts_with(b"\0\0\x01\0") && bytes.get(4..6).is_some_and(|count| count != b"\0\0"))
+ picture_cache::looks_like_a_raster(bytes) || (bytes.starts_with(b"\0\0\x01\0") && bytes.get(4..6).is_some_and(|count| count != b"\0\0"))
}
/// The picture of `address`: from the first of [`addresses`] that has one, downloaded with
diff --git a/apps/mailcraft/src/sender_images_tests.rs b/apps/mailcraft/src/sender_images_tests.rs
index acfe2d8d20..97daad25e6 100644
--- a/apps/mailcraft/src/sender_images_tests.rs
+++ b/apps/mailcraft/src/sender_images_tests.rs
@@ -146,6 +146,20 @@ fn a_sites_icon_is_kept_for_a_sender_and_never_for_a_message() {
let _ = std::fs::remove_dir_all(dir);
}
+#[test]
+fn a_drawing_is_kept_for_a_message_and_never_for_a_sender() {
+ // #565: a message's pictures may be SVG drawings; a sender's picture never is.
+ let drawing = b" ".to_vec();
+ assert!(!looks_like_a_picture(&drawing));
+ let dir = std::env::temp_dir().join(format!("mailcraft-sender-svg-{}", std::process::id()));
+ let cache = Cache::at(dir.clone());
+ let icon = addresses("ada@example.org").remove(1);
+ assert!(!cache.put_as(&icon, &drawing, looks_like_a_picture));
+ assert!(cache.put(&icon, &drawing));
+ assert_eq!(cache.get_as(&icon, looks_like_a_picture), None);
+ let _ = std::fs::remove_dir_all(dir);
+}
+
#[test]
fn turning_it_off_stops_before_the_next_request() {
let dir = std::env::temp_dir().join(format!("mailcraft-sender-stop-{}", std::process::id()));
diff --git a/crates/html/src/blocks.rs b/crates/html/src/blocks.rs
index 48ece5b580..6aa596f292 100644
--- a/crates/html/src/blocks.rs
+++ b/crates/html/src/blocks.rs
@@ -1822,7 +1822,8 @@ impl Builder {
}
let (src, data) = data::picture(&picture.src, self.decode, &mut self.budget);
picture.src = src;
- picture.data = Some(data?);
+ // A drawing (#565) is shown as a picture of an ` ` only, not behind a box (#601).
+ picture.data = Some(data.filter(|p| !data::looks_like_svg(&p.0))?);
}
Some(picture)
}
diff --git a/crates/html/src/data.rs b/crates/html/src/data.rs
index f8f632df32..9e385ec214 100644
--- a/crates/html/src/data.rs
+++ b/crates/html/src/data.rs
@@ -4,11 +4,14 @@
//! `data:image/png;base64,…` (RFC 2397, base64 as in RFC 4648). They are part of the message, as
//! an attached (`cid:`) picture is: nothing is fetched for them and nobody is told anything.
//!
-//! Only a PNG, JPEG, GIF or WebP is taken, by its declared type and then by its own bytes; any
-//! other type (SVG, HTML, text) is not. The base64 is decoded within caps checked before
-//! anything is decoded: [`MAX_DATA_PICTURE_BYTES`] for one picture, [`MAX_DATA_PICTURES`] and
-//! [`MAX_DATA_PICTURES_BYTES`] for a message. What is refused is a placeholder for the picture.
-//! A `data:` address is never a link, nor anything else of a message's.
+//! Only a PNG, JPEG, GIF or WebP is taken, by its declared type and then by its own bytes, and
+//! an SVG drawing (#565), declared one and beginning as one ([`looks_like_svg`]); any other type
+//! (HTML, text) is not. The base64 (or, for a drawing, which is text, the `%xx` escapes) is
+//! decoded within caps checked before anything is decoded: [`MAX_DATA_PICTURE_BYTES`] for one
+//! picture, [`MAX_DATA_PICTURES`] and [`MAX_DATA_PICTURES_BYTES`] for a message. What is refused
+//! is a placeholder for the picture. A drawing is only bytes here: what it is drawn with, and
+//! the rule that nothing it refers to is ever loaded, are the reading pane's. A `data:` address
+//! is never a link, nor anything else of a message's.
use std::sync::Arc;
@@ -63,8 +66,8 @@ pub(crate) fn is_data(src: &str) -> bool {
}
/// The address kept of a picture written into the message (`data:` and its type when it is one
-/// of the four, never its content), and its bytes when it is shown: decoded within `budget`
-/// when `decode`, and a PNG, JPEG, GIF or WebP by its own bytes.
+/// of the five, never its content), and its bytes when it is shown: decoded within `budget`
+/// when `decode`, and a PNG, JPEG, GIF or WebP by its own bytes, or an SVG drawing said to be one.
pub(crate) fn picture(src: &str, decode: bool, budget: &mut Budget) -> (String, Option) {
let (kept, _, picture) = picture_taken(src, decode, budget);
(kept, picture)
@@ -75,8 +78,9 @@ pub(crate) fn picture(src: &str, decode: bool, budget: &mut Budget) -> (String,
/// and one that does agree on.
pub(crate) fn picture_taken(src: &str, decode: bool, budget: &mut Budget) -> (String, bool, Option) {
let (kept, taken) = admit(src, decode, budget);
- let Some((text, size)) = taken.filter(|_| decode) else { return (kept, taken.is_some(), None) };
- let data = base64(text, size).filter(|bytes| is_picture(bytes)).map(|bytes| Picture(Arc::new(bytes)));
+ let Some(admitted) = taken else { return (kept, false, None) };
+ let bytes = if admitted.base64ed { base64(admitted.text, admitted.size) } else { Some(percent_decode(admitted.text)) };
+ let data = bytes.filter(|bytes| if admitted.svg { looks_like_svg(bytes) } else { is_picture(bytes) }).map(|bytes| Picture(Arc::new(bytes)));
(kept, true, data)
}
@@ -86,9 +90,16 @@ pub(crate) fn counted(src: &str, budget: &mut Budget) -> (String, bool) {
(kept, taken.is_some())
}
-/// The address kept of a picture written into the message, and its base64 text and size when
+struct Admitted<'a> {
+ text: &'a str,
+ size: usize,
+ svg: bool,
+ base64ed: bool,
+}
+
+/// The address kept of a picture written into the message, and its encoded text and size when
/// `budget` takes it (and is spent by it); never when not `decode`.
-fn admit<'s>(src: &'s str, decode: bool, budget: &mut Budget) -> (String, Option<(&'s str, usize)>) {
+fn admit<'s>(src: &'s str, decode: bool, budget: &mut Budget) -> (String, Option>) {
let Some((head, text)) = src.trim_start().split_once(',') else { return ("data:".into(), None) };
let head: String = head.chars().filter(|c| !matches!(c, '\t' | '\n' | '\r')).collect();
let head = head.trim();
@@ -98,21 +109,102 @@ fn admit<'s>(src: &'s str, decode: bool, budget: &mut Budget) -> (String, Option
Some("image/jpeg" | "image/jpg" | "image/pjpeg") => "image/jpeg",
Some("image/gif") => "image/gif",
Some("image/webp") => "image/webp",
+ Some("image/svg+xml") => SVG,
_ => return ("data:".into(), None),
};
let kept = format!("data:{kind}");
- if !decode || !parts.any(|p| p.eq_ignore_ascii_case("base64")) || budget.pictures >= MAX_DATA_PICTURES || text.len() > MAX_PICTURE_TEXT {
+ let base64ed = parts.any(|p| p.eq_ignore_ascii_case("base64"));
+ // A drawing is text, and may be written as it is, its odd characters as `%xx`; a picture
+ // of the others is only ever base64.
+ if !decode || !(base64ed || kind == SVG) || budget.pictures >= MAX_DATA_PICTURES || text.len() > MAX_PICTURE_TEXT {
return (kept, None);
}
// What it would come to, from its length, before anything is decoded.
- let digits = text.bytes().filter(|b| !b.is_ascii_whitespace() && *b != b'=').count();
- let size = digits / 4 * 3 + (digits % 4).saturating_sub(1);
+ let size = if base64ed {
+ let digits = text.bytes().filter(|b| !b.is_ascii_whitespace() && *b != b'=').count();
+ digits / 4 * 3 + (digits % 4).saturating_sub(1)
+ } else {
+ text.len()
+ };
if size > MAX_DATA_PICTURE_BYTES || budget.bytes.saturating_add(size) > MAX_DATA_PICTURES_BYTES {
return (kept, None);
}
budget.pictures += 1;
budget.bytes = budget.bytes.saturating_add(size);
- (kept, Some((text, size)))
+ (kept, Some(Admitted { text, size, svg: kind == SVG, base64ed }))
+}
+
+/// The type an SVG drawing is written with.
+pub(crate) const SVG: &str = "image/svg+xml";
+
+/// `%xx` escapes decoded; anything else, a `%` that begins no escape among it, is kept as it is.
+fn percent_decode(text: &str) -> Vec {
+ let bytes = text.as_bytes();
+ let mut out = Vec::with_capacity(bytes.len());
+ let mut i = 0;
+ while let Some(&b) = bytes.get(i) {
+ let escape = (b == b'%').then(|| bytes.get(i + 1..i + 3)).flatten().and_then(|hex| std::str::from_utf8(hex).ok()).and_then(|hex| {
+ // `from_str_radix` would take a sign: only two hex digits are an escape.
+ hex.bytes().all(|h| h.is_ascii_hexdigit()).then(|| u8::from_str_radix(hex, 16).ok()).flatten()
+ });
+ match escape {
+ Some(byte) => {
+ out.push(byte);
+ i += 3;
+ }
+ None => {
+ out.push(b);
+ i += 1;
+ }
+ }
+ }
+ out
+}
+
+/// Whether bytes are an SVG drawing by how they begin: after a byte order mark, white space, an
+/// XML declaration or other processing instructions, comments and a document type of `svg`, the
+/// first element is ``. Lowercase, as XML is: `` is no SVG element. Never looks past
+/// what there is, and each byte at most a few times.
+pub fn looks_like_svg(bytes: &[u8]) -> bool {
+ let mut rest = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
+ loop {
+ rest = rest.trim_ascii_start();
+ let after = |rest: &[u8], start: usize, end: &[u8]| -> Option {
+ let from = rest.get(start..)?;
+ from.windows(end.len()).position(|w| w == end).map(|at| start + at + end.len())
+ };
+ let skip = if rest.starts_with(b"") {
+ after(rest, 2, b"?>")
+ } else if rest.starts_with(b"")
+ } else if rest.starts_with(b"` 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),
+ None => None,
+ }
+ } else {
+ return rest.starts_with(b"' | b'/'));
+ };
+ match skip.and_then(|at| rest.get(at..)) {
+ Some(next) => rest = next,
+ None => return false,
+ }
+ }
}
/// Base64 to bytes, the line breaks and spaces in it skipped and its padding optional; `None`
diff --git a/crates/html/src/data_svg_tests.rs b/crates/html/src/data_svg_tests.rs
new file mode 100644
index 0000000000..78ca2ddf93
--- /dev/null
+++ b/crates/html/src/data_svg_tests.rs
@@ -0,0 +1,123 @@
+// SPDX-FileCopyrightText: MailCraft contributors
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//! #565: SVG pictures written into a message (`data:image/svg+xml,…`): taken as the drawing's
+//! own bytes, base64 or percent-encoded, within the same caps as the others. Drawing it, with
+//! nothing it refers to ever loaded, is the reading pane's (`ui-egui/src/reading/svg.rs`).
+
+use crate::data_tests::{b64, img, pictures};
+use crate::{BlockKind, MAX_DATA_PICTURE_BYTES, MAX_DATA_PICTURES, images, is_embedded, looks_like_svg, parse};
+
+const SVG: &str = " ";
+
+/// `text` with every byte that isn't a letter or a digit written as `%xx`, as mail programs write
+/// an SVG into an address.
+fn percent(text: &str) -> String {
+ text.bytes().map(|b| if b.is_ascii_alphanumeric() { char::from(b).to_string() } else { format!("%{b:02X}") }).collect()
+}
+
+#[test]
+fn an_svg_written_into_the_message_is_shown() {
+ for src in [
+ format!("data:image/svg+xml;base64,{}", b64(SVG.as_bytes())),
+ format!("DATA:Image/SVG+XML;charset=utf-8;base64,{}", b64(SVG.as_bytes())),
+ // Percent-encoded, as most mail programs and web pages write one.
+ format!("data:image/svg+xml;charset=utf-8,{}", percent(SVG)),
+ format!("data:image/svg+xml,{}", percent(SVG)),
+ // As written, only its quotes changed for the attribute's sake.
+ format!("data:image/svg+xml;utf8,{}", SVG.replace('#', "%23")),
+ ] {
+ let shown = pictures(&img(&src));
+ assert_eq!(shown.len(), 1, "{src}");
+ let (kept, data) = &shown[0];
+ // The address kept says what it is, never its content.
+ assert_eq!(kept, "data:image/svg+xml", "{src}");
+ assert!(is_embedded(kept));
+ assert_eq!(data.as_deref(), Some(SVG.as_bytes()), "{src}");
+ }
+}
+
+#[test]
+fn what_is_said_to_be_an_svg_must_be_one_and_the_other_way_round() {
+ let png = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR";
+ for src in [
+ // A drawing's type on bytes that are no drawing.
+ format!("data:image/svg+xml;base64,{}", b64(png)),
+ format!("data:image/svg+xml,{}", percent(" ")),
+ format!("data:image/svg+xml,{}", percent("just some words")),
+ format!("data:image/svg+xml,{}", percent(" ")),
+ "data:image/svg+xml,".to_string(),
+ // Bad base64 or percent-encoding is no drawing either.
+ "data:image/svg+xml;base64,PHN2Zy*+".to_string(),
+ // A picture's type on a drawing.
+ format!("data:image/png;base64,{}", b64(SVG.as_bytes())),
+ format!("data:image/gif,{}", percent(SVG)),
+ // Anything else that is text.
+ format!("data:image/svg;base64,{}", b64(SVG.as_bytes())),
+ format!("data:text/xml;base64,{}", b64(SVG.as_bytes())),
+ ] {
+ let shown = pictures(&img(&src));
+ assert_eq!(shown.len(), 1, "{src}: a placeholder stands for it");
+ assert!(shown[0].1.is_none(), "{src}");
+ }
+}
+
+#[test]
+fn an_svg_is_known_by_its_first_element() {
+ for yes in [
+ SVG.to_string(),
+ format!("\u{feff}{SVG}"),
+ format!(" \r\n\t{SVG}"),
+ 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(),
+ ] {
+ assert!(looks_like_svg(yes.as_bytes()), "{yes:?}");
+ }
+ for no in [
+ "",
+ "svg",
+ "",
+ " ",
+ " ",
+ "",
+ "".repeat(10_000) + SVG;
+ assert!(looks_like_svg(comments.as_bytes()));
+}
+
+#[test]
+fn an_svg_takes_its_share_of_the_caps() {
+ // Over the cap for one picture, percent-encoded or not.
+ let big = format!("{} ", "x".repeat(MAX_DATA_PICTURE_BYTES));
+ assert!(pictures(&img(&format!("data:image/svg+xml,{big}")))[0].1.is_none());
+ assert!(pictures(&img(&format!("data:image/svg+xml;base64,{}", b64(big.as_bytes()))))[0].1.is_none());
+ // And one of the pictures a message may have.
+ let one = img(&format!("data:image/svg+xml,{}", percent(SVG)));
+ let shown = pictures(&one.repeat(MAX_DATA_PICTURES + 3));
+ assert_eq!(shown.len(), MAX_DATA_PICTURES + 3);
+ assert_eq!(shown.iter().filter(|(_, d)| d.is_some()).count(), MAX_DATA_PICTURES);
+}
+
+#[test]
+fn a_drawing_in_the_html_itself_is_still_not_drawn() {
+ // Only an ` ` of a drawing is a picture: an `` element in the message is not drawn
+ // (its words are read as they were before #565).
+ let blocks = parse(&format!("Before
{SVG}Drawn words After
"));
+ assert!(images(&blocks).is_empty());
+ assert!(blocks.iter().all(|b| !matches!(b.kind, BlockKind::Image { .. })));
+}
diff --git a/crates/html/src/data_tests.rs b/crates/html/src/data_tests.rs
index 71c77d6ba1..79cb17119f 100644
--- a/crates/html/src/data_tests.rs
+++ b/crates/html/src/data_tests.rs
@@ -32,7 +32,7 @@ pub(crate) fn b64(bytes: &[u8]) -> String {
}
/// The pictures of `html`: the address kept, and the bytes when it is shown.
-fn pictures(html: &str) -> Vec<(String, Option)> {
+pub(crate) fn pictures(html: &str) -> Vec<(String, Option)> {
images(&parse(html))
.into_iter()
.filter_map(|b| match &b.kind {
@@ -42,7 +42,7 @@ fn pictures(html: &str) -> Vec<(String, Option)> {
.collect()
}
-fn img(src: &str) -> String {
+pub(crate) fn img(src: &str) -> String {
format!("Before
After
")
}
@@ -105,8 +105,8 @@ fn what_is_not_a_picture_of_ours_is_a_placeholder() {
format!("data:image/png;base64,{}=AAAA", b64(&PNG)),
// Not base64 at all.
"data:image/png,%89PNG".to_string(),
- // A type that isn't a picture of ours, whatever the bytes.
- format!("data:image/svg+xml;base64,{}", b64(b" ")),
+ // A type that isn't a picture of ours, whatever the bytes (an SVG is one, by its own:
+ // `data_svg_tests.rs`, #565).
format!("data:text/html;base64,{}", b64(&PNG)),
format!("data:;base64,{}", b64(&PNG)),
format!("data:application/octet-stream;base64,{}", b64(&PNG)),
diff --git a/crates/html/src/lib.rs b/crates/html/src/lib.rs
index 51c2458585..e1788c11b8 100644
--- a/crates/html/src/lib.rs
+++ b/crates/html/src/lib.rs
@@ -49,7 +49,7 @@ use std::sync::Arc;
pub use bg::{BgOffset, BgPicture, BgRepeat, BgSize, MAX_BG_OFFSET_PX, MAX_BG_SIZE_PX};
pub use blocks::{MAX_HIDDEN_TEXT, Read, parse, parse_in, parse_text, parse_text_own, parse_text_with_tables};
-pub use data::{MAX_DATA_PICTURE_BYTES, MAX_DATA_PICTURES, MAX_DATA_PICTURES_BYTES, Picture};
+pub use data::{MAX_DATA_PICTURE_BYTES, MAX_DATA_PICTURES, MAX_DATA_PICTURES_BYTES, Picture, looks_like_svg};
pub use entities::{escape, unescape};
pub use grid::{Grid, Place, grid};
pub use media::{Env, MAX_ENVS as MAX_MEDIA_ENVS, envs as media_envs, verdicts as media_verdicts};
@@ -679,6 +679,8 @@ pub(crate) fn is_blank(c: char) -> bool {
#[cfg(test)]
mod bg_tests;
#[cfg(test)]
+mod data_svg_tests;
+#[cfg(test)]
mod data_tests;
#[cfg(test)]
mod float_tests;
diff --git a/crates/html/src/quote.rs b/crates/html/src/quote.rs
index f2c607bd50..de1c982ef9 100644
--- a/crates/html/src/quote.rs
+++ b/crates/html/src/quote.rs
@@ -221,7 +221,7 @@ pub fn quotable_in(html: &str, envs: &[Env]) -> String {
}
/// [`quotable`], with the pictures written into the message (`data:`) carried as parts of their
-/// own: each that the reading pane would show (a PNG, JPEG, GIF or WebP by its own bytes, within
+/// own: each that the reading pane would show (a PNG, JPEG, GIF or WebP by its own bytes, never an SVG drawing, within
/// [`MAX_DATA_PICTURES`](crate::MAX_DATA_PICTURES), [`MAX_DATA_PICTURE_BYTES`](crate::MAX_DATA_PICTURE_BYTES)
/// and [`MAX_DATA_PICTURES_BYTES`](crate::MAX_DATA_PICTURES_BYTES), and not hidden) is given to
/// `written`, and its ` ` refers to it by the Content-ID `written` answers (`cid:…`); the
@@ -458,6 +458,12 @@ impl Quoter<'_, '_> {
let bytes = drawn.picture.filter(|_| drawn.taken)?;
let (kept, _) = data::picture(&src, false, &mut Budget::default());
let mime = kept.strip_prefix("data:").unwrap_or_default();
+ // The reading pane draws an SVG drawing (#565), a reply does not hand one over: it is an
+ // active format, and the recipient's program is not ours. It counted against the caps as
+ // in the reading pane, and is left out like any picture that is not carried.
+ if mime == data::SVG {
+ return None;
+ }
let cid = written(mime, &bytes)?;
Some(format!("cid:{cid}"))
}
diff --git a/crates/html/src/quote/written_tests.rs b/crates/html/src/quote/written_tests.rs
index e3cb9c0cc1..6025b47296 100644
--- a/crates/html/src/quote/written_tests.rs
+++ b/crates/html/src/quote/written_tests.rs
@@ -163,3 +163,25 @@ proptest::proptest! {
proptest::prop_assert!(handed.len() <= MAX_DATA_PICTURES);
}
}
+
+#[test]
+fn an_svg_drawing_is_shown_in_the_reading_pane_but_never_handed_over() {
+ // #565: the reading pane draws a drawing written into the message, but a reply hands over
+ // only the four kinds of pixels, whichever way the drawing is written.
+ let drawing = b" ";
+ let escaped: String = drawing.iter().map(|b| format!("%{b:02X}")).collect();
+ for svg in [
+ format!("data:image/svg+xml;base64,{}", b64(drawing)),
+ format!("data:image/svg+xml;charset=utf-8;base64,{}", b64(drawing)),
+ format!("data:image/svg+xml,{escaped}"),
+ "data:image/svg+xml, ".to_string(),
+ ] {
+ let (out, handed) = quoted(&format!("Before
After
"));
+ assert_eq!(out, "Before
After
", "{svg}");
+ assert!(handed.is_empty(), "{svg}");
+ // Next to a PNG, only the PNG goes.
+ let (out, handed) = quoted(&format!(" ", png()));
+ assert_eq!(out, " ", "{svg}");
+ assert_eq!((handed.len(), handed[0].0.as_str()), (1, "image/png"), "{svg}");
+ }
+}
diff --git a/crates/i18n/po/cs.po b/crates/i18n/po/cs.po
index c4e804c8b0..0f793e5da4 100644
--- a/crates/i18n/po/cs.po
+++ b/crates/i18n/po/cs.po
@@ -24417,8 +24417,8 @@ msgstr "má dvě výjimky jednoho druhu, které hledají různé věci, a server
#. interface
#: crates/ui-egui/src/reading/images.rs
#, fuzzy
-msgid "it is a drawing of a kind that isn't shown (SVG)"
-msgstr "je to kresba druhu, který se nezobrazuje (SVG)"
+msgid "it is a drawing (SVG) that is damaged or can't be shown"
+msgstr "jde o poškozenou kresbu (SVG) nebo ji nelze zobrazit"
#. interface
#: crates/ui-egui/src/reading/images.rs
@@ -29553,6 +29553,9 @@ msgstr "−Řádky"
#~ msgstr "Správce vaší organizace musí jednou schválit čtení kalendářů sdílených poštovních schránek: Soubor › Informace"
#, fuzzy
+#~ msgid "it is a drawing of a kind that isn't shown (SVG)"
+#~ msgstr "je to kresba druhu, který se nezobrazuje (SVG)"
+
#~ msgid "Allow MailCraft to change your automatic replies on the page that opened in your browser…"
#~ msgstr "Povolte MailCraftu měnit vaše automatické odpovědi na stránce, která se otevřela v prohlížeči…"
diff --git a/crates/i18n/po/de.po b/crates/i18n/po/de.po
index a1a1e8e84d..015ef818a2 100644
--- a/crates/i18n/po/de.po
+++ b/crates/i18n/po/de.po
@@ -23001,8 +23001,8 @@ msgstr "sie hat zwei Ausnahmen derselben Art, die nach Verschiedenem suchen, und
#. interface
#: crates/ui-egui/src/reading/images.rs
#, fuzzy
-msgid "it is a drawing of a kind that isn't shown (SVG)"
-msgstr "es ist eine Zeichnung eines Typs, der nicht angezeigt wird (SVG)"
+msgid "it is a drawing (SVG) that is damaged or can't be shown"
+msgstr "es ist eine Zeichnung (SVG), die beschädigt ist oder nicht angezeigt werden kann"
#. interface
#: crates/ui-egui/src/reading/images.rs
@@ -27645,6 +27645,10 @@ msgstr "−Zeilen"
#~ msgstr[0] "{n} Nachricht gefunden"
#~ msgstr[1] "{n} Nachrichten gefunden"
+#, fuzzy
+#~ msgid "it is a drawing of a kind that isn't shown (SVG)"
+#~ msgstr "es ist eine Zeichnung eines Typs, der nicht angezeigt wird (SVG)"
+
#, fuzzy
#~ msgid "Capitalize the first word of sentences"
#~ msgstr "Erstes Wort eines Satzes großschreiben"
diff --git a/crates/i18n/po/es.po b/crates/i18n/po/es.po
index dd3dda1283..f03f15c2fe 100644
--- a/crates/i18n/po/es.po
+++ b/crates/i18n/po/es.po
@@ -24331,8 +24331,8 @@ msgstr "tiene dos excepciones del mismo tipo que buscan cosas distintas, y el se
#. interface
#: crates/ui-egui/src/reading/images.rs
#, fuzzy
-msgid "it is a drawing of a kind that isn't shown (SVG)"
-msgstr "es un dibujo de un tipo que no se muestra (SVG)"
+msgid "it is a drawing (SVG) that is damaged or can't be shown"
+msgstr "es un dibujo (SVG) dañado o que no se puede mostrar"
#. interface
#: crates/ui-egui/src/reading/images.rs
@@ -29638,6 +29638,9 @@ msgstr "−Líneas"
#~ msgstr[1] "{n} mensajes se eliminarán de forma definitiva."
#, fuzzy
+#~ msgid "it is a drawing of a kind that isn't shown (SVG)"
+#~ msgstr "es un dibujo de un tipo que no se muestra (SVG)"
+
#~ msgid "Double-click to open {name}; right-click to save it"
#~ msgstr "Haga doble clic para abrir {name}; clic con el botón derecho para guardarlo"
diff --git a/crates/i18n/po/fr.po b/crates/i18n/po/fr.po
index 7455059f2e..6e3f12a9be 100644
--- a/crates/i18n/po/fr.po
+++ b/crates/i18n/po/fr.po
@@ -24233,8 +24233,8 @@ msgstr "elle a deux exceptions du même type qui cherchent des choses différent
#. interface
#: crates/ui-egui/src/reading/images.rs
#, fuzzy
-msgid "it is a drawing of a kind that isn't shown (SVG)"
-msgstr "c'est un dessin d'un type qui n'est pas affiché (SVG)"
+msgid "it is a drawing (SVG) that is damaged or can't be shown"
+msgstr "c'est un dessin (SVG) endommagé ou qui ne peut pas être affiché"
#. interface
#: crates/ui-egui/src/reading/images.rs
@@ -29539,6 +29539,9 @@ msgstr "−Lignes"
#~ msgstr[1] "{n} messages seront définitivement supprimés."
#, fuzzy
+#~ msgid "it is a drawing of a kind that isn't shown (SVG)"
+#~ msgstr "c'est un dessin d'un type qui n'est pas affiché (SVG)"
+
#~ msgid "Double-click to open {name}; right-click to save it"
#~ msgstr "Double-cliquez pour ouvrir {name} ; clic droit pour l'enregistrer"
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/hu.po b/crates/i18n/po/hu.po
index a42237eea4..90d70cfba4 100644
--- a/crates/i18n/po/hu.po
+++ b/crates/i18n/po/hu.po
@@ -24326,8 +24326,8 @@ msgstr "két azonos fajtájú, de mást kereső kivétele van, a kiszolgáló pe
#. interface
#: crates/ui-egui/src/reading/images.rs
#, fuzzy
-msgid "it is a drawing of a kind that isn't shown (SVG)"
-msgstr "Ez egy olyan rajz, amely nem jelenik meg (SVG)"
+msgid "it is a drawing (SVG) that is damaged or can't be shown"
+msgstr "ez egy sérült vagy nem megjeleníthető rajz (SVG)"
#. interface
#: crates/ui-egui/src/reading/images.rs
@@ -29320,6 +29320,9 @@ msgstr "−Sorok"
#~ msgstr "A szervezet adminisztrátorának jóvá kell hagynia a megosztott postafiókok naptárainak olvasását egyszer: Fájl › Info"
#, fuzzy
+#~ msgid "it is a drawing of a kind that isn't shown (SVG)"
+#~ msgstr "Ez egy olyan rajz, amely nem jelenik meg (SVG)"
+
#~ msgid "Allow MailCraft to change your automatic replies on the page that opened in your browser…"
#~ msgstr "Engedje meg, hogy a MailCraft módosítsa az automatikus válaszokat az oldalon, amely megnyílt a böngésző…"
diff --git a/crates/i18n/po/it.po b/crates/i18n/po/it.po
index 2f3e626df9..072ee94eb0 100644
--- a/crates/i18n/po/it.po
+++ b/crates/i18n/po/it.po
@@ -24306,8 +24306,8 @@ msgstr "ha due eccezioni dello stesso tipo che cercano cose diverse, e il server
#. interface
#: crates/ui-egui/src/reading/images.rs
#, fuzzy
-msgid "it is a drawing of a kind that isn't shown (SVG)"
-msgstr "è un disegno di un tipo che non viene mostrato (SVG)"
+msgid "it is a drawing (SVG) that is damaged or can't be shown"
+msgstr "è un disegno (SVG) danneggiato o che non può essere mostrato"
#. interface
#: crates/ui-egui/src/reading/images.rs
@@ -29438,6 +29438,9 @@ msgstr "−Righe"
#~ msgstr "Sfoglia questo PC…"
#, fuzzy
+#~ msgid "it is a drawing of a kind that isn't shown (SVG)"
+#~ msgstr "è un disegno di un tipo che non viene mostrato (SVG)"
+
#~ msgid "{not_sending_yet}, and no other account here has a mail server to send this through."
#~ msgstr "{not_sending_yet}, e nessun altro account qui ha un server di posta tramite cui inviarlo."
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/ka.po b/crates/i18n/po/ka.po
index 8c12e73999..7ba2c984ac 100644
--- a/crates/i18n/po/ka.po
+++ b/crates/i18n/po/ka.po
@@ -24367,8 +24367,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 "ეს ნახატი (SVG) დაზიანებულია ან მისი ჩვენება შეუძლებელია"
#. interface
#: crates/ui-egui/src/reading/images.rs
@@ -29524,3 +29524,7 @@ msgstr "−სტრ."
#~ msgid "{not_sending_yet}: send this message from another account, or save it as a draft"
#~ msgstr "{not_sending_yet}: ეს წერილი სხვა ანგარიშიდან გაგზავნეთ ან მონახაზად შეინახეთ"
+#, fuzzy
+#~ msgid "it is a drawing of a kind that isn't shown (SVG)"
+#~ msgstr "ეს ისეთი სახის ნახატია, რომელიც არ ჩანს (SVG)"
+
diff --git a/crates/i18n/po/messages.pot b/crates/i18n/po/messages.pot
index 3fabee1bf9..2e0f3c20cb 100644
--- a/crates/i18n/po/messages.pot
+++ b/crates/i18n/po/messages.pot
@@ -20194,7 +20194,7 @@ msgstr ""
#. interface
#: crates/ui-egui/src/reading/images.rs
-msgid "it is a drawing of a kind that isn't shown (SVG)"
+msgid "it is a drawing (SVG) that is damaged or can't be shown"
msgstr ""
#. interface
diff --git a/crates/i18n/po/nl.po b/crates/i18n/po/nl.po
index 161ce1f27c..b163df4a98 100644
--- a/crates/i18n/po/nl.po
+++ b/crates/i18n/po/nl.po
@@ -23709,8 +23709,8 @@ msgstr "hij heeft twee uitzonderingen van dezelfde soort die naar iets anders zo
#. interface
#: crates/ui-egui/src/reading/images.rs
#, fuzzy
-msgid "it is a drawing of a kind that isn't shown (SVG)"
-msgstr "het is een tekening van een soort die niet wordt weergegeven (SVG)"
+msgid "it is a drawing (SVG) that is damaged or can't be shown"
+msgstr "het is een tekening (SVG) die beschadigd is of niet kan worden getoond"
#. interface
#: crates/ui-egui/src/reading/images.rs
@@ -29026,6 +29026,9 @@ msgstr "−Regels"
#~ msgstr "Planningassistent"
#, fuzzy
+#~ msgid "it is a drawing of a kind that isn't shown (SVG)"
+#~ msgstr "het is een tekening van een soort die niet wordt weergegeven (SVG)"
+
#~ msgid "Double-click to open {name}; right-click to save it"
#~ msgstr "Dubbelklik om {name} te openen; klik met de rechtermuisknop om het op te slaan"
diff --git a/crates/i18n/po/pl.po b/crates/i18n/po/pl.po
index 2897e0f308..ca9c791744 100644
--- a/crates/i18n/po/pl.po
+++ b/crates/i18n/po/pl.po
@@ -24419,8 +24419,8 @@ msgstr "ma dwa wyjątki jednego rodzaju, które szukają różnych rzeczy, a ser
#. interface
#: crates/ui-egui/src/reading/images.rs
#, fuzzy
-msgid "it is a drawing of a kind that isn't shown (SVG)"
-msgstr "to rysunek rodzaju, który nie jest wyświetlany (SVG)"
+msgid "it is a drawing (SVG) that is damaged or can't be shown"
+msgstr "to rysunek (SVG), który jest uszkodzony lub nie może zostać wyświetlony"
#. interface
#: crates/ui-egui/src/reading/images.rs
@@ -29551,6 +29551,9 @@ msgstr "−Wiersze"
#~ msgstr "Administrator Twojej organizacji musi raz zatwierdzić odczytywanie kalendarzy udostępnionych skrzynek pocztowych: Plik › Informacje"
#, fuzzy
+#~ msgid "it is a drawing of a kind that isn't shown (SVG)"
+#~ msgstr "to rysunek rodzaju, który nie jest wyświetlany (SVG)"
+
#~ msgid "Allow MailCraft to change your automatic replies on the page that opened in your browser…"
#~ msgstr "Zezwól programowi MailCraft na zmianę Twoich odpowiedzi automatycznych na stronie otwartej w przeglądarce…"
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/ro.po b/crates/i18n/po/ro.po
index 2b44804d88..ecf527763e 100644
--- a/crates/i18n/po/ro.po
+++ b/crates/i18n/po/ro.po
@@ -24412,8 +24412,8 @@ msgstr "are două excepții de același tip care caută lucruri diferite, iar se
#. interface
#: crates/ui-egui/src/reading/images.rs
#, fuzzy
-msgid "it is a drawing of a kind that isn't shown (SVG)"
-msgstr "este un desen de un tip care nu se afișează (SVG)"
+msgid "it is a drawing (SVG) that is damaged or can't be shown"
+msgstr "este un desen (SVG) deteriorat sau care nu poate fi afișat"
#. interface
#: crates/ui-egui/src/reading/images.rs
@@ -29707,6 +29707,9 @@ msgstr "−Linii"
#~ msgstr "Ciorna rămâne în Ciorne. {why}"
#, fuzzy
+#~ msgid "it is a drawing of a kind that isn't shown (SVG)"
+#~ msgstr "este un desen de un tip care nu se afișează (SVG)"
+
#~ msgid "Click to preview {name}; double-click to open it"
#~ msgstr "Clic pentru previzualizarea {name}; dublu clic pentru deschidere"
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/i18n/po/zh_CN.po b/crates/i18n/po/zh_CN.po
index 1588ffdbda..92b14ad08d 100644
--- a/crates/i18n/po/zh_CN.po
+++ b/crates/i18n/po/zh_CN.po
@@ -24304,8 +24304,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 "这是一个已损坏或无法显示的矢量图 (SVG)"
#. interface
#: crates/ui-egui/src/reading/images.rs
@@ -29323,6 +29323,9 @@ msgstr "−行"
#~ msgstr "草稿保留在“草稿”中。{why}"
#, fuzzy
+#~ msgid "it is a drawing of a kind that isn't shown (SVG)"
+#~ msgstr "这是无法显示的图像类型(SVG)"
+
#~ msgid "Click to preview {name}; double-click to open it"
#~ msgstr "单击可预览 {name};双击可打开"
diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml
index 9eaba9dccf..d19c26a1b2 100644
--- a/crates/ui-egui/Cargo.toml
+++ b/crates/ui-egui/Cargo.toml
@@ -31,6 +31,9 @@ mailcraft-names = { workspace = true }
mailcraft-spell = { workspace = true }
# Window screenshots for the control channel are saved as PNG.
image = { workspace = true }
+# A message's SVG pictures (#565, `reading/svg.rs`): drawn with nothing loaded from outside them.
+resvg = { workspace = true }
+svgtypes = { workspace = true }
# A font is opened as egui will open it before egui is given it (`theme::is_face`): a system's
# face, and the browser's Georgian face fetched from the server.
skrifa = { workspace = true }
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 810841034c..027d5c4e76 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -852,6 +852,10 @@ pub fn store_trouble_notice(trouble: StoreTrouble) -> String {
i18n::fmt(tl!("{why}, so sign-ins aren't remembered: MailCraft asks again each time it starts."), &[("why", why)])
}
+/// Whether bytes are an SVG drawing by how they begin, as the reading pane tells one that it
+/// draws (#565): for the host, whose picture cache keeps what the reading pane shows.
+pub use mailcraft_html::looks_like_svg;
+
/// The pictures from the web that the host keeps on disk between runs
/// ([`Services::picture_cache`]). The window calls these itself, so they are quick: saying how
/// much is kept reads nothing, and forgetting takes as long as removing the files takes.
diff --git a/crates/ui-egui/src/reading.rs b/crates/ui-egui/src/reading.rs
index b5385ee30b..2cd291425e 100644
--- a/crates/ui-egui/src/reading.rs
+++ b/crates/ui-egui/src/reading.rs
@@ -58,6 +58,11 @@ mod sharing_tests;
mod signature;
#[cfg(test)]
mod signature_tests;
+pub(crate) mod svg;
+#[cfg(test)]
+mod svg_tests;
+#[cfg(test)]
+mod svg_wide_stroke_tests;
#[cfg(test)]
mod tests;
pub(crate) mod unsubscribe;
diff --git a/crates/ui-egui/src/reading/attachment_pictures.rs b/crates/ui-egui/src/reading/attachment_pictures.rs
index 82a8062ab5..21f2151c9f 100644
--- a/crates/ui-egui/src/reading/attachment_pictures.rs
+++ b/crates/ui-egui/src/reading/attachment_pictures.rs
@@ -9,8 +9,8 @@
//! to fit; a double-click opens it and its `▾` menu is the chip's. Everything else stays a chip.
//!
//! The bytes are hostile, as every attachment's: whether a file is a picture is told by its
-//! bytes alone ([`images::probe`], within the reading pane's caps, never by its name or its
-//! declared type), and it is decoded by [`images::decode`] with the same caps, off the window's
+//! bytes alone ([`images::probe_raster`], within the reading pane's caps, never by its name or its
+//! declared type), and it is decoded by [`images::decode_raster`] with the same caps, off the window's
//! thread (one at a time), into a small texture. Mail in Junk E-mail is shown by names only. Only
//! the first [`MAX_PREVIEWS`] files of a message whose type or name says they may be pictures
//! are looked at, so that a message with a thousand attachments costs no more a frame than one
@@ -334,7 +334,7 @@ impl Thumbs {
// Everything kept is on screen now: this one is a chip.
drop(self.entries.swap_remove(oldest?));
}
- let size = images::probe(data);
+ let size = images::probe_raster(data);
self.entries.push(Thumb { data: Arc::downgrade(data), size, state: State::Waiting, used: frame });
self.entries.len() - 1
}
@@ -408,7 +408,7 @@ impl Thumbs {
}
// Here: in the browser, in a test, or when no thread could be started.
self.decoded_in = Some(frame);
- let image = images::decode(data, max_side, max_width);
+ let image = images::decode_raster(data, max_side, max_width);
let entry = self.entry(data, frame)?;
entry.state = match image {
Some(image) => State::Ready(ctx.load_texture("mailcraft-attachment-picture", image, egui::TextureOptions::LINEAR)),
@@ -442,7 +442,7 @@ impl Thumbs {
let bytes = data.clone();
let repaint = ctx.clone();
let job = std::thread::Builder::new().name("attachment-picture".into()).spawn(move || {
- let _ = send.send(images::decode(&bytes, max_side, max_width));
+ let _ = send.send(images::decode_raster(&bytes, max_side, max_width));
repaint.request_repaint();
});
match job {
diff --git a/crates/ui-egui/src/reading/images.rs b/crates/ui-egui/src/reading/images.rs
index c8dcb5ec41..b353bcddb8 100644
--- a/crates/ui-egui/src/reading/images.rs
+++ b/crates/ui-egui/src/reading/images.rs
@@ -9,11 +9,15 @@
//! Either way the bytes are hostile, so everything is capped: how large a file is looked at, how
//! large a picture is decoded, how much memory decoding may take, how large a texture is made,
//! how many are kept. A picture that is too large, damaged or of a kind that isn't decoded (PNG,
-//! JPEG, GIF and WebP are; one that moves shows its first frame) is a placeholder, not an error.
+//! JPEG, GIF and WebP are; one that moves shows its first frame; an SVG drawing is drawn, by
+//! [`super::svg`], with nothing it refers to loaded, on a thread of its own) is a placeholder,
+//! not an error.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
+use super::svg;
+
/// Largest attached picture that is looked at, in bytes.
pub const MAX_PICTURE_BYTES: usize = 24 * 1024 * 1024;
@@ -99,12 +103,30 @@ fn reader<'a>(data: &'a [u8], kinds: &[image::ImageFormat]) -> Option Option<[u32; 2]> {
+ if svg::is_svg(data) {
+ return svg::probe(data).map(|drawing| drawing.size);
+ }
+ probe_as(data, KINDS)
+}
+
+/// [`probe`] for raster pictures only: an SVG drawing is `None`. For a caller on the window's
+/// thread that has no thread of its own to read a drawing on (the pictures of attachments).
+pub fn probe_raster(data: &[u8]) -> Option<[u32; 2]> {
probe_as(data, KINDS)
}
+/// Whether bytes that came from the web may be a picture, as the window can tell without reading
+/// a drawing (that is done on a thread of its own, [`Pictures`]): a raster picture is probed, a
+/// drawing is one by how it begins and within [`svg::MAX_SVG_BYTES`].
+pub fn seems_a_picture(data: &[u8]) -> bool {
+ if svg::is_svg(data) { data.len() <= svg::MAX_SVG_BYTES } else { probe_as(data, KINDS).is_some() }
+}
+
/// [`probe`], for a sender's picture: a web site's icon (ICO) too.
pub fn probe_icon(data: &[u8]) -> Option<[u32; 2]> {
probe_as(data, ICON_KINDS)
@@ -127,8 +149,17 @@ fn kept_size(size: [u32; 2], max_side: u32, max_width: u32) -> [u32; 2] {
[(w * scale).round().max(1.0) as u32, (h * scale).round().max(1.0) as u32]
}
-/// Decode a picture, scaled down to fit a texture. `None` when it cannot be decoded.
+/// Decode a picture, scaled down to fit a texture (a drawing is drawn at the width it is shown,
+/// [`svg::kept_size`]). `None` when it cannot be decoded.
pub fn decode(data: &[u8], max_side: u32, max_width: u32) -> Option {
+ if svg::is_svg(data) {
+ return svg::decode(data, max_side, max_width);
+ }
+ decode_as(data, max_side, max_width, KINDS)
+}
+
+/// [`decode`] for raster pictures only: an SVG drawing is `None` (see [`probe_raster`]).
+pub fn decode_raster(data: &[u8], max_side: u32, max_width: u32) -> Option {
decode_as(data, max_side, max_width, KINDS)
}
@@ -153,6 +184,11 @@ struct Entry {
data: Arc>,
/// Its size in pixels; `None` when it is not a picture that can be shown.
size: Option<[u32; 2]>,
+ /// What it is as a drawing, when it is an SVG one: it is drawn at the size it is shown.
+ drawing: Option,
+ /// An SVG drawing that is not read yet (its read is done on a thread of its own, never on the
+ /// window's): it has no size until it is.
+ unread: bool,
texture: Option,
/// It was tried and could not be decoded.
failed: bool,
@@ -238,7 +274,7 @@ pub fn not_a_picture(data: &[u8]) -> &'static str {
tl!("it is a kind of picture that can't be shown here")
} else {
match text() {
- (_, true) => tl!("it is a drawing of a kind that isn't shown (SVG)"),
+ (_, true) => tl!("it is a drawing (SVG) that is damaged or can't be shown"),
(true, false) => tl!("the server sent a web page instead of a picture"),
_ => tl!("what the server sent is not a picture"),
}
@@ -253,13 +289,40 @@ pub struct Pictures {
decoded_in: Option,
/// The time (egui's, in seconds) at which a texture was last asked for.
asked_at: Option,
- /// How many pictures have been decoded.
+ /// How many pictures have been decoded, or drawings read.
#[cfg(test)]
decodes: usize,
/// Pictures from the web, by their address as the message wrote it.
remote: HashMap, RemoteEntry>,
+ /// The SVG drawing being read or drawn on a thread of its own, if any: one at a time, never
+ /// on the window's thread.
+ drawing: Option,
+ /// The thread of a drawing given up on after [`DRAWING_PATIENCE`] that has not finished yet:
+ /// no other drawing is begun until it has, so drawings that take long never run side by side.
+ given_up: Option>,
+ /// How many drawings have been read (so that a layout that waited for one is made again).
+ reads: u64,
+}
+
+/// What the thread of a drawing brings: the drawing as read (`None`, it is not one that is
+/// shown), or its picture (`None`, it can't be drawn).
+pub(crate) enum Done {
+ Read(Option),
+ Drawn(Option),
+}
+
+/// A drawing being read or drawn apart: whose bytes, and where what it comes to comes.
+struct Drawn {
+ data: Arc>,
+ answer: std::sync::mpsc::Receiver,
+ /// When it was begun (egui's time, in seconds).
+ since: f64,
}
+/// Seconds a drawing may take on its thread before it is given up as a broken picture (the thread
+/// finishes by itself, and what it brings is let go; the next drawing waits for that).
+const DRAWING_PATIENCE: f64 = 10.0;
+
impl Pictures {
/// The window's pictures.
pub fn of(ctx: &egui::Context) -> Arc> {
@@ -281,7 +344,11 @@ impl Pictures {
}
None => {
self.forget_unheld();
- self.entries.push(Entry { data: data.clone(), size: probe(data), texture: None, failed: false, used: frame });
+ // A drawing is read apart (`Pictures::begin_read`); what is decoded here is a raster
+ // picture's header.
+ let unread = svg::is_svg(data);
+ let size = if unread { None } else { probe(data) };
+ self.entries.push(Entry { data: data.clone(), size, drawing: None, unread, texture: None, failed: false, used: frame });
self.entries.len() - 1
}
},
@@ -298,6 +365,18 @@ impl Pictures {
size
}
+ /// Whether an attachment is an SVG drawing that is still being read, on a thread of its own: it
+ /// has no size yet, and is no broken picture.
+ pub fn is_reading(&mut self, data: &Arc>, frame: u64) -> bool {
+ self.entry(data, frame).is_some_and(|e| e.unread)
+ }
+
+ /// How many drawings have been read: a layout that had to do without one is made again when
+ /// it grows.
+ pub fn reads(&self) -> u64 {
+ self.reads
+ }
+
/// What became of the picture at `url`, when it was asked for; a message on screen is asking.
pub fn remote(&mut self, url: &str, frame: u64) -> Option {
let entry = self.remote.get_mut(url)?;
@@ -361,15 +440,24 @@ impl Pictures {
pub fn texture(&mut self, ctx: &egui::Context, data: &Arc>, shown: egui::Vec2) -> Picture {
let frame = frame(ctx);
self.asked_at = Some(ctx.input(|i| i.time));
+ self.settle(ctx);
let busy = self.decoded_in == Some(frame);
if self.entry(data, frame).is_none() {
return Picture::Failed;
}
+ // A drawing just met is begun to be read.
+ self.begin_read(ctx);
let Some(index) = self.entries.iter().position(|e| Arc::ptr_eq(&e.data, data)) else { return Picture::Failed };
- let (size, failed, have) = match self.entries.get(index) {
- Some(e) => (e.size, e.failed, e.texture.clone()),
+ let (size, drawing, failed, have, unread) = match self.entries.get(index) {
+ Some(e) => (e.size, e.drawing, e.failed, e.texture.clone(), e.unread),
None => return Picture::Failed,
};
+ if unread {
+ // A drawing being read apart (it was let go and is wanted again): looked at again in a
+ // while, whether it has come or not.
+ ctx.request_repaint_after(std::time::Duration::from_millis(100));
+ return have.map_or(Picture::Pending, Picture::Ready);
+ }
let ready = |have: Option| have.map_or(Picture::Failed, Picture::Ready);
let Some(size) = size.filter(|_| !failed) else { return ready(have) };
let max_side = u32::try_from(ctx.input(|i| i.max_texture_side)).unwrap_or(MAX_TEXTURE_SIDE);
@@ -381,7 +469,10 @@ impl Pictures {
let points = if points.is_finite() { points.clamp(1.0, super::MAX_BODY_WIDTH) } else { 1.0 };
let wanted = (points * ctx.pixels_per_point()).ceil().clamp(1.0, MAX_TEXTURE_SIDE as f32) as u32;
let wanted = wanted.div_ceil(WIDTH_STEP).saturating_mul(WIDTH_STEP).min(MAX_TEXTURE_SIDE);
- let [kw, kh] = kept_size(size, max_side, wanted);
+ let [kw, kh] = match &drawing {
+ Some(drawing) => svg::kept_size(drawing, max_side, wanted),
+ None => kept_size(size, max_side, wanted),
+ };
if have.as_ref().is_some_and(|t| t.size()[0] >= usize::try_from(kw).unwrap_or(usize::MAX)) {
return ready(have);
}
@@ -395,6 +486,9 @@ impl Pictures {
if bytes.saturating_add(cost) > CACHE_BYTES || (have.is_none() && textures >= CACHE_PICTURES) {
return ready(have);
}
+ if drawing.is_some() {
+ return self.draw_apart(ctx, index, max_side, wanted, have);
+ }
if busy {
return have.map_or(Picture::Pending, Picture::Ready);
}
@@ -419,12 +513,134 @@ impl Pictures {
picture
}
+ /// Draw the SVG drawing of entry `index` on a thread of its own, unless one is being read or
+ /// drawn already (this one or another: one at a time); meanwhile the picture is what it has, or
+ /// pending. A drawing is never read or drawn on the window's thread, so one that takes long
+ /// holds up the other drawings, never the window. Where there are no threads (the browser) it
+ /// can't be drawn.
+ fn draw_apart(&mut self, ctx: &egui::Context, index: usize, max_side: u32, wanted: u32, have: Option) -> Picture {
+ let waiting = have.map_or(Picture::Pending, Picture::Ready);
+ if self.drawing.is_some() || self.given_up.is_some() {
+ // Looked at again in a while, whether it comes or not.
+ ctx.request_repaint_after(std::time::Duration::from_millis(500));
+ return waiting;
+ }
+ let Some(entry) = self.entries.get_mut(index) else { return Picture::Failed };
+ let (sender, answer) = std::sync::mpsc::channel();
+ let (bytes, repaint) = (entry.data.clone(), ctx.clone());
+ let drawn = std::thread::Builder::new().name("mailcraft-svg".into()).stack_size(8 * 1024 * 1024).spawn(move || {
+ // The window may be gone, and nobody waiting: nothing to do about it.
+ let _ = sender.send(Done::Drawn(svg::decode(&bytes, max_side, wanted)));
+ repaint.request_repaint();
+ });
+ if drawn.is_err() {
+ entry.failed = true;
+ entry.texture = None;
+ return Picture::Failed;
+ }
+ self.drawing = Some(Drawn { data: entry.data.clone(), answer, since: ctx.input(|i| i.time) });
+ #[cfg(test)]
+ {
+ self.decodes += 1;
+ }
+ waiting
+ }
+
+ /// Take in the drawing read or drawn apart, once it is: what it is, or its texture, for its
+ /// entry (still there by those bytes, or the same bytes anew), or that it can't be shown; give
+ /// it up as one that can't once it has taken [`DRAWING_PATIENCE`]; and begin reading the next
+ /// drawing that is not read yet.
+ fn settle(&mut self, ctx: &egui::Context) {
+ self.settle_at(ctx, ctx.input(|i| i.time));
+ self.begin_read(ctx);
+ }
+
+ /// Begin reading the first drawing that is not read yet, on a thread of its own, unless one is
+ /// being read or drawn already. The read (the XML, usvg's tree and the stroking it does for
+ /// bounds) is the part that can take long on a hostile drawing, so it is never done on the
+ /// window's thread.
+ fn begin_read(&mut self, ctx: &egui::Context) {
+ if self.drawing.is_some() || self.given_up.is_some() {
+ return;
+ }
+ let Some(entry) = self.entries.iter_mut().find(|e| e.unread) else { return };
+ let (sender, answer) = std::sync::mpsc::channel();
+ let (bytes, repaint) = (entry.data.clone(), ctx.clone());
+ let read = std::thread::Builder::new().name("mailcraft-svg".into()).stack_size(8 * 1024 * 1024).spawn(move || {
+ // The window may be gone, and nobody waiting: nothing to do about it.
+ let _ = sender.send(Done::Read(svg::probe(&bytes)));
+ repaint.request_repaint();
+ });
+ if read.is_err() {
+ // No threads (or no more of them): it can't be read.
+ entry.unread = false;
+ entry.failed = true;
+ self.reads += 1;
+ return;
+ }
+ self.drawing = Some(Drawn { data: entry.data.clone(), answer, since: ctx.input(|i| i.time) });
+ #[cfg(test)]
+ {
+ self.decodes += 1;
+ }
+ }
+
+ /// [`Pictures::settle`] at the time `now` (egui's, in seconds).
+ fn settle_at(&mut self, ctx: &egui::Context, now: f64) {
+ // A thread given up on is waited for until it has finished: it has sent what it drew, or
+ // it is gone.
+ if self.given_up.as_ref().is_some_and(|answer| !matches!(answer.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty))) {
+ self.given_up = None;
+ }
+ let Some(drawn) = self.drawing.take() else { return };
+ let done = match drawn.answer.try_recv() {
+ Ok(done) => Some(done),
+ Err(std::sync::mpsc::TryRecvError::Empty) if now - drawn.since <= DRAWING_PATIENCE => {
+ self.drawing = Some(drawn);
+ return;
+ }
+ Err(std::sync::mpsc::TryRecvError::Empty) => {
+ // Given up on, its thread still running: it holds the next drawing back.
+ self.given_up = Some(drawn.answer);
+ None
+ }
+ Err(std::sync::mpsc::TryRecvError::Disconnected) => None,
+ };
+ let data = drawn.data;
+ let entry = match self.entries.iter().position(|e| Arc::ptr_eq(&e.data, &data)) {
+ Some(index) => self.entries.get_mut(index),
+ None => self.entries.iter_mut().find(|e| e.data.len() == data.len() && e.data == data),
+ };
+ let Some(entry) = entry else { return };
+ match done {
+ Some(Done::Read(read)) => {
+ // What it is, or that it is not shown.
+ entry.unread = false;
+ entry.size = read.map(|d| d.size);
+ entry.drawing = read;
+ entry.failed = read.is_none();
+ self.reads += 1;
+ }
+ Some(Done::Drawn(Some(image))) => entry.texture = Some(ctx.load_texture("mailcraft-inline-picture", image, egui::TextureOptions::LINEAR)),
+ // It can't be drawn, or its thread took too long or is gone (a drawing not read by
+ // then is not shown either).
+ Some(Done::Drawn(None)) | None => {
+ self.reads += u64::from(entry.unread);
+ entry.unread = false;
+ entry.failed = true;
+ entry.texture = None;
+ }
+ }
+ }
+
/// At the end of a frame: once no picture has been asked for for [`IDLE_SECONDS`] (no message
/// with pictures is shown), let go of every texture; they are made again when wanted. Until
/// then the cache is bounded by [`CACHE_BYTES`] and [`CACHE_PICTURES`] alone, so scrolling
/// away from a picture and back does not decode it again. Nothing repaints an idle window, so
/// one is asked for when the time is up.
pub fn release_unseen(&mut self, ctx: &egui::Context) {
+ // A drawing that has come is taken in (or let go) even when no picture is asked for.
+ self.settle(ctx);
let now = ctx.input(|i| i.time);
if self.release_at(now) {
ctx.request_repaint_after(std::time::Duration::from_secs_f64(IDLE_SECONDS + 1.0));
@@ -479,6 +695,23 @@ impl Pictures {
self.decodes
}
+ /// The drawing being drawn apart is answered through the sender this returns, as its thread
+ /// would answer, and not by its thread.
+ #[cfg(test)]
+ pub fn hold_drawing(&mut self) -> Option> {
+ let drawn = self.drawing.as_mut()?;
+ let (sender, answer) = std::sync::mpsc::channel();
+ drawn.answer = answer;
+ Some(sender)
+ }
+
+ /// [`Pictures::settle`] as of `seconds` after the drawing being drawn apart was begun.
+ #[cfg(test)]
+ pub fn settle_after(&mut self, ctx: &egui::Context, seconds: f64) {
+ let since = self.drawing.as_ref().map_or(0.0, |d| d.since);
+ self.settle_at(ctx, since + seconds);
+ }
+
/// [`Pictures::release_unseen`] as of `seconds` after the last picture was asked for.
#[cfg(test)]
pub fn release_after(&mut self, seconds: f64) {
@@ -555,8 +788,11 @@ mod tests {
assert_eq!(said(b""), "the server sent nothing");
assert_eq!(said(b"Not found"), "the server sent a web page instead of a picture");
assert_eq!(said(b"\r\n "), "the server sent a web page instead of a picture");
- assert_eq!(said(b" "), "it is a drawing of a kind that isn't shown (SVG)");
- assert_eq!(said(b" "), "it is a drawing of a kind that isn't shown (SVG)");
+ assert_eq!(
+ said(b" "),
+ "it is a drawing (SVG) that is damaged or can't be shown"
+ );
+ assert_eq!(said(b" "), "it is a drawing (SVG) that is damaged or can't be shown");
assert_eq!(said(b"\0\0\0\x1cftypavif\0\0\0\0avifmif1miaf"), "it is a kind of picture that can't be shown here (AVIF or HEIC)");
assert_eq!(said(b"BM\x46\0\0\0\0\0\0\0\x36\0\0\0"), "it is a kind of picture that can't be shown here");
assert_eq!(said(b"\0\0\x01\0\x01\0\x10\x10"), "it is a kind of picture that can't be shown here");
@@ -595,7 +831,9 @@ mod tests {
("nothing", &b""[..]),
("text", b"just some text, not a picture at all"),
("a signature and nothing else", b"\x89PNG\r\n\x1a\n"),
- ("svg", b" "),
+ // An SVG drawing is drawn, what it says runs left out (#565, `svg_tests.rs`); not one
+ // outside SVG's namespace.
+ ("svg of no drawing", b" "),
("html", b" "),
("bmp", b"BM\x46\0\0\0\0\0\0\0\x36\0\0\0\x28\0\0\0\x02\0\0\0\x02\0\0\0\x01\0\x18\0\0\0\0\0\x10\0\0\0"),
("avif", b"\0\0\0\x1cftypavif\0\0\0\0avifmif1miaf\0\0\0\xeameta"),
diff --git a/crates/ui-egui/src/reading/layout.rs b/crates/ui-egui/src/reading/layout.rs
index 33b9f0c9a0..0b2611693b 100644
--- a/crates/ui-egui/src/reading/layout.rs
+++ b/crates/ui-egui/src/reading/layout.rs
@@ -494,6 +494,8 @@ impl Cx<'_> {
}
let src = picture.src.trim();
let bytes = picture.data.as_ref().map(|p| p.0.clone()).or_else(|| self.parts.as_ref().and_then(|p| p.find(src)).map(|(_, a)| a.data.clone()));
+ // A drawing (#565) is shown as the picture of an ` ` only, not behind a box.
+ let bytes = bytes.filter(|data| !mailcraft_html::looks_like_svg(data));
let (data, size) = bytes.and_then(|data| self.pictures.size(&data, self.frame).map(|size| (data, size)))?;
self.stats.behind += 1;
Some(Behind { slot: self.slot(), data, size })
@@ -1065,6 +1067,8 @@ fn picture_tile<'a>(cx: &mut Cx<'_>, block: &'a Block, room: f32, padding: f32,
}
// (The pictures behind boxes count against the same cap: one message's pictures in all.)
let bytes = bytes.filter(|_| cx.stats.pictures.saturating_add(cx.stats.behind) < images::MAX_PICTURES_PER_MESSAGE);
+ // An SVG drawing is read on a thread of its own: until it is, it is on its way, not broken.
+ let reading = bytes.as_ref().is_some_and(|data| cx.pictures.is_reading(data, cx.frame));
let natural = bytes.and_then(|data| cx.pictures.size(&data, cx.frame).map(|size| (data, size)));
let asked = |v: &Option| v.map(f32::from).filter(|v| *v >= 1.0);
if let Some((data, [w, h])) = natural {
@@ -1098,7 +1102,7 @@ fn picture_tile<'a>(cx: &mut Cx<'_>, block: &'a Block, room: f32, padding: f32,
} else {
cx.ctx.fonts_mut(|f| f.layout_no_wrap(label.clone(), regular(CHIP_FONT), Color32::WHITE).size().x) + 10.0
};
- if shown {
+ if shown && !reading {
cx.stats.placeholders += 1;
if !mailcraft_html::is_embedded(src) {
cx.stats.remote += 1;
@@ -1106,7 +1110,7 @@ fn picture_tile<'a>(cx: &mut Cx<'_>, block: &'a Block, room: f32, padding: f32,
}
// One that was asked for and is on its way keeps the room it says it needs, so that the
// message does not jump when it comes.
- if let (true, Some(w), Some(h)) = (asked_for, asked(width), asked(height)) {
+ if let (true, Some(w), Some(h)) = (asked_for || reading, asked(width), asked(height)) {
let scale = (room / w).min(MAX_PICTURE_HEIGHT / h).min(1.0);
let size = vec2((w * scale).max(1.0), (h * scale).max(1.0));
return Tile { size, block, padding: None, data: None, label, described, wanted: w.min(super::MAX_BODY_WIDTH) };
diff --git a/crates/ui-egui/src/reading/remote.rs b/crates/ui-egui/src/reading/remote.rs
index 1aed865e56..61db17481a 100644
--- a/crates/ui-egui/src/reading/remote.rs
+++ b/crates/ui-egui/src/reading/remote.rs
@@ -334,7 +334,7 @@ pub fn tick(app: &mut MailApp, ctx: &egui::Context) {
// Whatever came is a stranger's bytes: a picture within the limits, or nothing.
let outcome = match answer {
Ok(bytes) if bytes.len() > MAX_BYTES => Err(Arc::from(tl!("it is too large to show"))),
- Ok(bytes) if images::probe(&bytes).is_some() => Ok(bytes),
+ Ok(bytes) if images::seems_a_picture(&bytes) => Ok(bytes),
Ok(bytes) => Err(Arc::from(images::not_a_picture(&bytes))),
Err(why) => Err(why),
};
diff --git a/crates/ui-egui/src/reading/svg.rs b/crates/ui-egui/src/reading/svg.rs
new file mode 100644
index 0000000000..eb0492e575
--- /dev/null
+++ b/crates/ui-egui/src/reading/svg.rs
@@ -0,0 +1,640 @@
+// SPDX-FileCopyrightText: MailCraft contributors
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//! A message's pictures that are SVG drawings (#565): an ` ` of one attached to the message
+//! (`cid:`), written into it (`data:`) or, when the owner asked for its pictures, on the web.
+//! An `` element in the message itself is not drawn.
+//!
+//! A drawing is a stranger's program for a renderer that was not made for strangers. So only the
+//! plainest drawings are shown, the kind flat logos and
+//! icons are, by an allowlist: what is not on it makes the drawing a broken picture, as a damaged
+//! PNG is.
+//!
+//! - **Nothing is loaded from outside it.** The resolvers usvg would load a picture or another
+//! drawing with answer nothing ([`options`]), no folder is given to look in, and the renderer is
+//! built without text, so no font is looked for. No element or attribute that refers to
+//! anything but a gradient is allowed.
+//! - **Before it is read:** at most [`MAX_SVG_BYTES`] of UTF-8 (`svgz` is not unpacked), nesting
+//! no deeper than [`MAX_SVG_DEPTH`] (by a scan with no stack, before the XML reader, which
+//! recurses, sees it), at most [`MAX_SVG_NODES`] nodes, no entity and no internal subset of the
+//! document type, an `` root in SVG's namespace.
+//! - **Only what is allowed ([`plain`]):** the elements of [`ELEMENTS`] in SVG's namespace or in
+//! none (and elements of other namespaces, which the renderer skips, but no `"),
+ format!(" "),
+ format!(" "),
+ format!(" "),
+ format!(" "),
+ "words ".to_string(),
+ ]
+ .iter()
+ .map(|body| drawing(40, 40, body))
+ .collect()
+}
+
+#[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 port = listener.local_addr().unwrap().port();
+ for address in [format!("http://127.0.0.1:{port}"), format!("https://127.0.0.1:{port}"), format!("//127.0.0.1:{port}")] {
+ let drawings = referring_to(&address);
+ // Drawn, with what it names on the web taken as no paint.
+ assert!(images::decode(&drawings[0], 2048, 40).is_some(), "{address}");
+ for data in &drawings[1..] {
+ assert!(refused(data), "{address}: {}", String::from_utf8_lossy(data));
+ }
+ }
+ // Nobody came: 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 usvg would load it on its own (it draws it in red: proved here, so that the rest of the
+ // test proves something).
+ let path = file.to_string_lossy().replace('\\', "/");
+ 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]), "usvg's own resolver reads files");
+ let red = b64(format!(" ").as_bytes());
+ let names = [path.clone(), file.to_string_lossy().into_owned(), format!("file:///{}", path.trim_start_matches('/')), "red.svg".into()];
+ for name in names.iter().map(String::as_str).chain([format!("data:image/svg+xml;base64,{red}").as_str()]) {
+ for body in [
+ format!(" "),
+ format!(" "),
+ format!(" "),
+ format!(" "),
+ ] {
+ // Refused, or drawn without it.
+ assert!(images::decode(&drawing(40, 40, &body), 2048, 40).is_none_or(|image| !any_red(&image)), "{body}");
+ }
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn words_scripts_and_animation_are_not_allowed() {
+ // No font is looked for, so a drawing with words would be shown without them: refused.
+ assert!(refused(&drawing(40, 20, "MMMM ")));
+ // Nothing runs, and a drawing that says something should is not shown.
+ assert!(refused(&drawing(20, 20, "")));
+ assert!(refused(&drawing(20, 20, " ")));
+ assert!(refused(&drawing(20, 20, " ")));
+}
+
+#[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; so is any internal subset.
+ assert!(refused(format!("]> ").as_bytes()));
+ assert!(refused(format!("]>&x; ").as_bytes()));
+ assert!(refused(format!("'>]> ").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, too many shapes.
+ assert!(refused(&drawing(8, 8, &" ".repeat(30_000))));
+ assert!(refused(&drawing(8, 8, &" ".repeat(MAX_SHAPES as usize + 1))));
+ // Too deep, however deep.
+ let deep = |n: usize| drawing(8, 8, &format!("{}{}", "".repeat(n), " ".repeat(n)));
+ assert!(refused(&deep(30_000)));
+ assert!(refused(&deep(MAX_SVG_DEPTH + 1)));
+ // A drawing of no size.
+ 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 only_a_plain_drawing_is_shown() {
+ // Every element that isn't a group, a shape or a gradient.
+ for name in [
+ "use",
+ "symbol",
+ "pattern",
+ "marker",
+ "mask",
+ "clipPath",
+ "style",
+ "filter",
+ "feGaussianBlur",
+ "feTurbulence",
+ "feMorphology",
+ "image",
+ "foreignObject",
+ "text",
+ "a",
+ "switch",
+ "svg",
+ "script",
+ "animate",
+ "set",
+ "view",
+ "cursor",
+ "font",
+ ] {
+ assert!(refused(&drawing(8, 8, &format!("<{name}/> "))), "{name}");
+ assert!(refused(&drawing(8, 8, &format!("<{name} id='x'/> "))), "{name}");
+ }
+ // Every attribute that refers to or draws what isn't allowed, written or in a style.
+ for attribute in [
+ "filter='url(#f)'",
+ "mask='url(#m)'",
+ "clip-path='url(#c)'",
+ "marker-mid='url(#m)'",
+ "stroke-dasharray='1 1'",
+ "href='#g'",
+ "xlink:href='#g'",
+ "xml:id='g'",
+ "style='filter: blur(4px)'",
+ "style='filter:drop-shadow(0 0 9px red)'",
+ "style='mix-blend-mode: multiply'",
+ "style='isolation: isolate'",
+ "style='clip-path: circle(4px)'",
+ "style='mask: url(#m)'",
+ "style='stroke-dasharray: 1'",
+ "style='fill: \"red\"'",
+ "style='fill: red /* x */'",
+ "style='fill: \\72 ed'",
+ "style='fill: red; } * { filter: blur(9px)'",
+ "fill='inherit' style='font-family: x'",
+ ] {
+ assert!(refused(&drawing(8, 8, &format!(" "))), "{attribute}");
+ }
+ // A group's opacity (a layer that holds others).
+ assert!(refused(&drawing(8, 8, " ")));
+ assert!(refused(&drawing(8, 8, " ")));
+}
+
+#[test]
+fn a_flat_logo_as_drawing_programs_write_it_is_drawn() {
+ let logo = format!(
+ "\n\n\
+ \
+ Lumen Works Logo \
+ \
+ \
+ \
+ \
+ \
+ \
+ "
+ );
+ 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 not allowed, whatever the path.
+#[test]
+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} "))));
+ 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. 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();
+ 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(400),
+ " ".repeat(depth)
+ );
+ 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
+/// ``, a clip, or what a group gives the shapes in it).
+#[test]
+fn review_4_copies_are_bounded_by_what_is_drawn() {
+ // 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. `` 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 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!(
+ "{} ",
+ k - 1,
+ " ".repeat(10)
+ );
+ }
+ assert!(refused(&drawing(8, 8, &format!("{patterns} "))));
+ let mask = format!("{} ", " ".repeat(2_000));
+ assert!(refused(&drawing(
+ 8,
+ 8,
+ &format!("{mask} {} ", " ".repeat(2_000))
+ )));
+}
+
+/// Review finding 5: the layers counted by the elements written. They are counted in the tree
+/// 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 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 / 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.
+ 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)
+ );
+ // 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.
+ 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);
+}
+
+/// Review finding 7: one path of very many segments counted as one shape. Its segments are
+/// counted, a stroke's (round ones most) weighing more, within a cap, and fewer pixels the more.
+#[test]
+fn review_7_the_segments_of_a_path_are_counted() {
+ let d = format!("M0 0{}", "h1v1".repeat(30_000));
+ // Filled: 60,000 segments are drawn, quickly, with fewer pixels than a plain drawing.
+ let few = svg::probe(&drawing(40, 40, "")).unwrap();
+ let start = Instant::now();
+ let filled = drawing(40, 40, &format!(" "));
+ let long = svg::probe(&filled).unwrap();
+ assert!(long.max_pixels < few.max_pixels, "{} {}", long.max_pixels, few.max_pixels);
+ assert!(images::decode(&filled, 2048, 2048).is_some());
+ assert!(start.elapsed() < Duration::from_secs(3), "took {:?}", start.elapsed());
+ // Stroked wide, with round joins and caps, or many times over: refused, at once.
+ assert!(refused(&drawing(40, 40, &format!(" "))));
+ assert!(refused(&drawing(40, 40, &format!(" "))));
+ let short = format!("M0 0{}", "h1v1".repeat(4_000));
+ assert!(refused(&drawing(40, 40, &format!(" ").repeat(14))));
+}
+
+/// Review finding 8: a curve counted as one segment, though it is drawn as up to 64 lines.
+#[test]
+fn review_8_a_curve_counts_as_the_lines_it_is_drawn_with() {
+ let cubics = |n: usize| format!("M0 0{}", "c1 2 3 4 5 6".repeat(n));
+ let quads = |n: usize| format!("M0 0{}", "q1 2 3 4".repeat(n));
+ // A thousand curves are a logo's; eleven thousand are refused, filled, and fifteen hundred,
+ // stroked.
+ assert!(images::probe(&drawing(40, 40, &format!(" ", cubics(1_000)))).is_some());
+ assert!(refused(&drawing(40, 40, &format!(" ", cubics(11_000)))));
+ assert!(refused(&drawing(40, 40, &format!(" ", quads(16_000)))));
+ assert!(refused(&drawing(40, 40, &format!(" ", cubics(1_500)))));
+ // An arc is made curves, and counts as them.
+ assert!(refused(&drawing(40, 40, &format!(" ", "a5 5 0 1 1 1 1".repeat(12_000)))));
+}
+
+/// The last review: XML's attributes, which usvg reads by their own names, dashes however they
+/// are given, strokes that usvg strokes as it reads the drawing, and editors' harmless attributes.
+#[test]
+fn review_9_xml_attributes_dashes_and_strokes_read() {
+ let svg = |body: &str| format!("{body} ").into_bytes();
+ // `xml:href`, an `href` to usvg: a ring of gradients it would follow for ever.
+ assert!(refused(&svg(
+ " "
+ )));
+ for attribute in ["xml:stroke-dasharray='1 1'", "xml:filter='blur(4px)'", "xml:stroke='#000'", "xml:transform='scale(9)'"] {
+ assert!(refused(&svg(&format!(" "))), "{attribute}");
+ }
+ assert!(images::probe(&svg(" ")).is_some());
+ // A stroked path so long that only stroking it for its bounds would take a while: refused
+ // before usvg reads it, at once.
+ let d = format!("M0 0{}", "h1v1".repeat(30_000));
+ let start = Instant::now();
+ assert!(refused(&svg(&format!(" "))));
+ assert!(refused(&svg(&format!(" "))));
+ assert!(start.elapsed() < Duration::from_secs(2), "took {:?}", start.elapsed());
+ // An icon drawn with round strokes, as icon sets draw theirs, and editors' harmless attributes.
+ let icon = " \
+ ";
+ let icon = format!("{icon} ");
+ assert!(images::decode(icon.as_bytes(), 2048, 48).is_some());
+}
+
+/// Review of #830: usvg takes a style sheet from a `", ""] {
+ assert!(refused(&svg(&format!("{style}{rect}"))), "{style}");
+ }
+ // Rules that match every element at every depth, under the size cap: refused at once, not
+ // matched for seconds on the window's thread.
+ let depth = 38;
+ let sheet: String = (0..3_000).map(|_| format!("{}*{{fill:red}}", "* ".repeat(30))).collect();
+ let nested = format!("{}{}{}", "".repeat(depth), " ".repeat(2_500), " ".repeat(depth));
+ for open in ["", "" };
+ let data = svg(&format!("{open}{sheet}{close}{nested}"));
+ assert!(data.len() <= MAX_SVG_BYTES, "{}", data.len());
+ assert!(refused(&data), "{open}");
+ }
+ // An element of no namespace that is not on the allowlist, as one of SVG's would be.
+ let red = b64(&drawing(4, 4, " "));
+ assert!(refused(&svg(&format!(" {rect}"))));
+ assert!(refused(&svg(&format!(" {rect}"))));
+ // One that is on it is let be (usvg skips it), as is an editor's element of its own namespace.
+ let image =
+ images::decode(&svg(&format!(" {rect}")), 512, 10)
+ .expect("drawn");
+ assert_eq!(pixel(&image, 5, 5), GREEN);
+}
+
+#[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'", "