Embed raster images in the SVG preview

The SVG preview painted every DisplayItem::Image as a grey rectangle. Encode
the raw RGB image as a PNG (zlib via flate2, CRC32, base64) and emit an SVG
<image> data URI; keep the grey fallback for images above four megapixels.

The article preview now contains the real 480x240 plot and the framed rule
figure is visible while editing. Test count stays 1074.
This commit is contained in:
gloamxun committed 2026-10-27 23:50:48 +08:00
1 parent fc328a56c6
commit 2ef5e29329
4 files changed
+107 -11

No files matched your search

+99 -4
View File
@@ -346,15 +346,24 @@ impl DisplayList {
y,
width,
height,
..
index,
} => {
let x = *x as f64 / 65_536.0;
let y = *y as f64 / 65_536.0;
let width = *width as f64 / 65_536.0;
let height = *height as f64 / 65_536.0;
out.push_str(&format!(
"<rect x=\"{x:.3}\" y=\"{y:.3}\" width=\"{width:.3}\" height=\"{height:.3}\" fill=\"#cccccc\"/>\n"
));
if let Some(image) = self.images.get(*index)
&& image.width as u64 * image.height as u64 <= 4_000_000
{
let uri = png_data_uri(image);
out.push_str(&format!(
"<image x=\"{x:.3}\" y=\"{y:.3}\" width=\"{width:.3}\" height=\"{height:.3}\" href=\"{uri}\"/>\n"
));
} else {
out.push_str(&format!(
"<rect x=\"{x:.3}\" y=\"{y:.3}\" width=\"{width:.3}\" height=\"{height:.3}\" fill=\"#cccccc\"/>\n"
));
}
}
}
}
@@ -363,6 +372,92 @@ impl DisplayList {
}
}
fn png_data_uri(image: &PdfImage) -> String {
let png = encode_png(image.width, image.height, &image.rgb);
format!("data:image/png;base64,{}", base64(&png))
}
fn encode_png(width: u32, height: u32, rgb: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(b"\x89PNG\r\n\x1a\n");
let mut ihdr = Vec::with_capacity(13);
ihdr.extend_from_slice(&width.to_be_bytes());
ihdr.extend_from_slice(&height.to_be_bytes());
ihdr.extend_from_slice(&[8, 2, 0, 0, 0]);
png_chunk(&mut out, b"IHDR", &ihdr);
let stride = width as usize * 3;
let mut raw = Vec::with_capacity((stride + 1) * height as usize);
for row in 0..height as usize {
raw.push(0);
let start = row * stride;
let end = start + stride;
if end <= rgb.len() {
raw.extend_from_slice(&rgb[start..end]);
} else {
raw.extend(std::iter::repeat_n(
255u8,
stride.saturating_sub(rgb.len().saturating_sub(start)),
));
}
}
let mut encoder = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
use std::io::Write as _;
encoder.write_all(&raw).expect("compress preview image");
let compressed = encoder.finish().expect("finish preview image");
png_chunk(&mut out, b"IDAT", &compressed);
png_chunk(&mut out, b"IEND", &[]);
out
}
fn png_chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
out.extend_from_slice(kind);
out.extend_from_slice(data);
let mut crc_data = Vec::with_capacity(4 + data.len());
crc_data.extend_from_slice(kind);
crc_data.extend_from_slice(data);
out.extend_from_slice(&crc32(&crc_data).to_be_bytes());
}
fn crc32(data: &[u8]) -> u32 {
let mut crc = 0xffff_ffffu32;
for byte in data {
crc ^= u32::from(*byte);
for _ in 0..8 {
crc = if crc & 1 != 0 {
(crc >> 1) ^ 0xedb8_8320
} else {
crc >> 1
};
}
}
!crc
}
fn base64(data: &[u8]) -> String {
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let a = chunk[0];
let b = chunk.get(1).copied().unwrap_or(0);
let c = chunk.get(2).copied().unwrap_or(0);
out.push(TABLE[(a >> 2) as usize] as char);
out.push(TABLE[(((a & 3) << 4) | (b >> 4)) as usize] as char);
out.push(if chunk.len() > 1 {
TABLE[(((b & 15) << 2) | (c >> 6)) as usize] as char
} else {
'='
});
out.push(if chunk.len() > 2 {
TABLE[(c & 63) as usize] as char
} else {
'='
});
}
out
}
fn escape(text: &str) -> String {
text.replace('&', "&amp;")
.replace('<', "&lt;")
+4 -3
View File
@@ -49,9 +49,10 @@ execution is not a goal.
numeric, and the full natbib option surface is not implemented;
- display math is approximate;
- PNG/JPEG/BMP floats now reserve their image height, embed the raster with
its real pixel dimensions, and centre the image within the float; table
floats are centred with their booktabs rules. The fbox frame and vector/PDF
images are still missing, and float order/placement differs.
its real pixel dimensions, centre the image within the float, and emit it
into the SVG preview as a PNG data URI. Table floats are centred with their
booktabs rules. Vector/PDF images are still missing, and float
order/placement differs.
- Incremental foundation exists:
- `Engine::edit` + page hashes;
- project-scoped sessions and changed-page reporting;
+1 -1
View File
@@ -49,7 +49,7 @@ now means route-D.
| Article/report basics: title, sections, lists, TOC, page numbers | Supported | corpus and 1074-test suite |
| Inline/display math, equations, tags, cleveref | Supported | math tests, oracle fixtures |
| Floats, captions, tables, booktabs | Supported | table/math tests, corpus |
| PNG/JPEG/BMP `\includegraphics` | Supported | project image tests; PDF XObjects now use pixel dimensions and embed the raster |
| PNG/JPEG/BMP `\includegraphics` | Supported | project image tests; PDF XObjects use pixel dimensions and the SVG preview embeds a PNG data URI |
| PDF/SVG/EPS figures | **Not supported** | undecodable images become placeholder rules |
| Inline `thebibliography` + `\cite` | Supported | numeric or custom labels; citation tests |
| `.bib` + BibTeX data | Partial | simple `@article`/`@inproceedings` fields are inlined as labeled `thebibliography`; project citations use author-year labels (`Kour and Saabne, 2014a`) |
+3 -3
View File
@@ -2322,7 +2322,7 @@ fn project_preview_and_pdf_embed_images() {
);
assert_eq!(preview.status, 200, "{}", preview.text());
let svg = preview.text();
assert!(svg.contains(r##"fill=\"#cccccc\""##), "preview: {svg}");
assert!(svg.contains("data:image/png;base64"), "preview: {svg}");
assert!(svg.contains(">P</text>"), "preview: {svg}");
let pdf = server.request(
@@ -2416,7 +2416,7 @@ fn project_images_degrade_to_placeholders() {
);
assert_eq!(preview.status, 200, "{}", preview.text());
assert!(
preview.text().contains(r##"fill=\"#cccccc\""##),
preview.text().contains("data:image/png;base64"),
"{}",
preview.text()
);
@@ -2450,7 +2450,7 @@ fn project_images_resolve_through_graphicspath() {
);
assert_eq!(preview.status, 200, "{}", preview.text());
let svg = preview.text();
assert!(svg.contains(r##"fill=\"#cccccc\""##), "preview: {svg}");
assert!(svg.contains("data:image/png;base64"), "preview: {svg}");
assert!(svg.contains(">P</text>"), "preview: {svg}");
assert!(!svg.contains("graphicspath"), "preview: {svg}");