diff --git a/Cargo.lock b/Cargo.lock index a7f3c7adb..4c4c470e6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -824,6 +824,7 @@ dependencies = [ "cadcraft-io", "cadcraft-render", "chrono", + "craft-image-codecs", "craft-ui", "craft-update", "craft-window", diff --git a/crates/io/src/raster.rs b/crates/io/src/raster.rs index 92afeb4f6..0d7e19b2d 100644 --- a/crates/io/src/raster.rs +++ b/crates/io/src/raster.rs @@ -4,7 +4,7 @@ use crate::{IoError, Result}; use cadcraft_doc::Raster; -use craft_image_codecs::{ChannelLayout, DecodeOptions, DecodeWarning, EncodeOptions, Format, Image, Limits, PngRows, SampleType}; +use craft_image_codecs::{ChannelLayout, DecodeOptions, DecodeWarning, Format, Limits, SampleType}; /// Largest image file read (bytes). pub const MAX_IMAGE_BYTES: usize = 256 << 20; @@ -61,17 +61,7 @@ pub fn decode(bytes: &[u8]) -> Result { /// `raster` as a PNG file, encoded in rows to avoid a full extra image copy. pub fn encode_png(raster: &Raster) -> Result> { - let stride = usize::try_from(raster.width()).ok().and_then(|w| w.checked_mul(4)).filter(|s| *s > 0).ok_or_else(|| bad("invalid image width"))?; - let mut chunks = raster.rgba().chunks_exact(stride); - let first = chunks.next().ok_or_else(|| bad("the image is empty"))?; - let row = |data: &[u8]| Image::from_u8(raster.width(), 1, ChannelLayout::Rgba, data.to_vec()).map_err(bad); - let first = row(first)?; let mut out = Vec::new(); - let mut writer = PngRows::new(&mut out, &first, raster.height(), &EncodeOptions::default()).map_err(bad)?; - writer.push(&first).map_err(bad)?; - for chunk in chunks { - writer.push(&row(chunk)?).map_err(bad)?; - } - writer.finish().map_err(bad)?; + cadcraft_render::raster::write_rgba_png(&mut out, raster.width(), raster.height(), raster.rgba()).ok_or_else(|| bad("PNG encoding failed"))?; Ok(out) } diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 9149d6f02..fb734cb34 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -354,6 +354,25 @@ fn premultiplied(r: &cadcraft_doc::Raster) -> Option { Pixmap::from_vec(data, tiny_skia::IntSize::from_wh(r.width(), r.height())?) } +/// Write straight-alpha RGBA8 pixels as PNG a row at a time. +pub fn write_rgba_png(mut output: impl std::io::Write, width: u32, height: u32, pixels: &[u8]) -> Option<()> { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, PngRows}; + let stride = usize::try_from(width).ok()?.checked_mul(4).filter(|n| *n > 0)?; + let expected = stride.checked_mul(usize::try_from(height).ok()?)?; + if height == 0 || pixels.len() != expected { + return None; + } + let mut rows = pixels.chunks_exact(stride); + let row = |data: &[u8]| Image::from_u8(width, 1, ChannelLayout::Rgba, data.to_vec()).ok(); + let first = row(rows.next()?)?; + let mut encoder = PngRows::new(&mut output, &first, height, &EncodeOptions::default()).ok()?; + encoder.push(&first).ok()?; + for data in rows { + encoder.push(&row(data)?).ok()?; + } + encoder.finish().ok() +} + /// Encode a premultiplied pixmap as PNG without a second full-frame copy. pub fn encode_png(pixmap: &Pixmap) -> Option> { use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, PngRows}; diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 034bb1d4d..b9d16801c 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -16,6 +16,8 @@ cadcraft-color = { workspace = true } cadcraft-doc = { workspace = true } cadcraft-render = { workspace = true } cadcraft-engine = { workspace = true } +cadcraft-io = { workspace = true } +craft-image-codecs = { workspace = true } cadcraft-fonts = { workspace = true } craft-window = { workspace = true } egui = { workspace = true } @@ -40,8 +42,6 @@ craft-ui = { workspace = true, features = ["native-windows"] } egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] } # Validates the canvas WGSL and its GLSL ES 3.0 (WebGL2) translation in tests (same naga wgpu uses). naga = { version = "30", features = ["wgsl-in", "glsl-out"] } -# Reads the synthetic dynamic-block fixture of the io tests for the dynamic grips tests. -cadcraft-io = { workspace = true } [build-dependencies] serde_json = { workspace = true } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 55e2da3f6..be605c876 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -691,6 +691,29 @@ impl Drop for PathlessShots { } } +fn write_screenshot_png(img: &image::RgbaImage, output: impl std::io::Write) -> std::io::Result<()> { + cadcraft_render::raster::write_rgba_png(output, img.width(), img.height(), img.as_raw()) + .ok_or_else(|| std::io::Error::other("PNG encoding failed")) +} + +fn save_explicit_screenshot(img: &image::RgbaImage, path: &str) -> std::io::Result<()> { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image}; + let format = match image::ImageFormat::from_path(path).map_err(std::io::Error::other)? { + image::ImageFormat::Png => Format::Png, + image::ImageFormat::Jpeg => Format::Jpeg, + image::ImageFormat::Bmp => Format::Bmp, + image::ImageFormat::Tiff => Format::Tiff, + _ => return Err(std::io::Error::other("unsupported screenshot format")), + }; + if format == Format::Png { + return write_screenshot_png(img, std::fs::File::create(path)?); + } + let pixels = Image::from_u8(img.width(), img.height(), ChannelLayout::Rgba, img.as_raw().clone()).map_err(std::io::Error::other)?; + let opts = EncodeOptions { jpeg_quality: 75, jpeg_chroma_subsampling: false, ..EncodeOptions::default() }; + let bytes = craft_image_codecs::encode(&pixels, format, &opts).map_err(std::io::Error::other)?; + std::fs::write(path, bytes) +} + /// Save a pathless screenshot into the private per-process directory: re-validate or recreate it as an owner-only real directory (0700 on Unix; plain create elsewhere), then create up to 64 exclusive files (0600 on Unix) and write a PNG. fn save_pathless_screenshot(img: &image::RgbaImage, token: u64) -> std::io::Result { use std::io::Write as _; @@ -713,7 +736,7 @@ fn save_pathless_screenshot(img: &image::RgbaImage, token: u64) -> std::io::Resu let path = dir.join(format!("cadcraft-shot-{token}-{}.png", next_pathless_nonce())); match create_private_file(&path) { Ok(mut file) => { - let written = img.write_to(&mut file, image::ImageFormat::Png).map_err(std::io::Error::other).and_then(|()| file.flush()); + let written = write_screenshot_png(img, &mut file).and_then(|()| file.flush()); if let Err(e) = written { // The reply carries no path on failure, so nobody else could remove the partial file. drop(file); @@ -752,7 +775,7 @@ pub fn save_screenshot(image: &egui::ColorImage, path: Option<&str>, token: u64) return inline_screenshot(&img, token); } let saved = match path { - Some(path) => img.save(path).map(|()| path.to_string()).map_err(std::io::Error::other), + Some(path) => save_explicit_screenshot(&img, path).map(|()| path.to_string()), None => save_pathless_screenshot(&img, token).map(|path| path.to_string_lossy().into_owned()), }; match saved { @@ -766,7 +789,7 @@ pub fn save_screenshot(image: &egui::ColorImage, path: Option<&str>, token: u64) fn inline_screenshot(img: &image::RgbaImage, token: u64) -> Value { let (w, h) = img.dimensions(); let mut png = Vec::new(); - if let Err(e) = img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) { + if let Err(e) = write_screenshot_png(img, &mut png) { return json!({"ok": false, "error": e.to_string(), "request": token}); } json!({"ok": true, "request": token, "result": {"pngBase64": cadcraft_engine::cmd::file::base64_encode(&png), "width": w, "height": h, "bytes": png.len()}}) @@ -776,6 +799,25 @@ fn inline_screenshot(img: &image::RgbaImage, token: u64) -> Value { mod tests { use super::*; + #[test] + fn explicit_screenshot_retains_supported_file_formats() { + let img = image::RgbaImage::from_pixel(3, 2, image::Rgba([10, 20, 30, 128])); + for ext in ["png", "bmp", "tiff", "jpg"] { + let path = std::env::temp_dir().join(format!("cadcraft-format-{}-{}.{}", std::process::id(), next_pathless_nonce(), ext)); + let name = path.to_string_lossy().to_string(); + save_explicit_screenshot(&img, &name).unwrap(); + let decoded = image::open(&path).unwrap().to_rgba8(); + assert_eq!(decoded.dimensions(), img.dimensions(), "{ext}"); + if ext != "jpg" { + let mut original = std::io::Cursor::new(Vec::new()); + img.write_to(&mut original, image::ImageFormat::from_path(&path).unwrap()).unwrap(); + let original = image::load_from_memory(&original.into_inner()).unwrap().to_rgba8(); + assert_eq!(decoded.as_raw(), original.as_raw(), "{ext}"); + } + std::fs::remove_file(path).unwrap(); + } + } + #[test] fn an_inline_screenshot_carries_the_png_and_its_size() { let img = image::RgbaImage::from_pixel(3, 2, image::Rgba([10, 20, 30, 255])); diff --git a/crates/ui-egui/src/exchange.rs b/crates/ui-egui/src/exchange.rs index b7a0246c6..153bbf925 100644 --- a/crates/ui-egui/src/exchange.rs +++ b/crates/ui-egui/src/exchange.rs @@ -70,16 +70,12 @@ fn render(app: &mut CadApp, ctx: &egui::Context) -> Result<(TextureHandle, Strin if let Some(f) = ctx.data(|d| d.get_temp::(egui::Id::unique(FROM_PLOT))) { let r = app.session.execute("plot", &f.params).map_err(|e| e.to_string())?; let png = r["data"].as_str().and_then(cadcraft_engine::cmd::file::base64_decode).ok_or("the preview has no image")?; - let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).map_err(|e| e.to_string())?.to_rgba8(); - let size = [img.width() as usize, img.height() as usize]; - let tex = ctx.load_texture("plot-preview", egui::ColorImage::from_rgba_unmultiplied(size, img.as_raw()), egui::TextureOptions::LINEAR); + let tex = preview_texture(ctx, &png)?; return Ok((tex, f.info)); } let r = app.session.execute("preview", &json!({ "width": 1600 })).map_err(|e| e.to_string())?; let png = r["data"].as_str().and_then(cadcraft_engine::cmd::file::base64_decode).ok_or("the preview has no image")?; - let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).map_err(|e| e.to_string())?.to_rgba8(); - let size = [img.width() as usize, img.height() as usize]; - let tex = ctx.load_texture("plot-preview", egui::ColorImage::from_rgba_unmultiplied(size, img.as_raw()), egui::TextureOptions::LINEAR); + let tex = preview_texture(ctx, &png)?; let mut info = format!("{} · {}", r["layout"].as_str().unwrap_or(""), r["paper"].as_str().unwrap_or("")); if r["landscape"].as_bool() == Some(true) { info.push_str(" · landscape"); @@ -87,6 +83,15 @@ fn render(app: &mut CadApp, ctx: &egui::Context) -> Result<(TextureHandle, Strin Ok((tex, info)) } +fn preview_texture(ctx: &egui::Context, png: &[u8]) -> Result { + if !png.starts_with(b"\x89PNG\r\n\x1a\n") { + return Err("the preview is not a PNG".into()); + } + let img = cadcraft_io::raster::decode(png).map_err(|e| e.to_string())?; + let size = [img.width() as usize, img.height() as usize]; + Ok(ctx.load_texture("plot-preview", egui::ColorImage::from_rgba_unmultiplied(size, img.rgba()), egui::TextureOptions::LINEAR)) +} + /// The Plot Preview window: the sheet as it plots, with Print and Close. pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { let id = egui::Id::unique("cc_plot_preview"); @@ -169,6 +174,16 @@ mod tests { (CadApp::new(Session::new(), services), asked) } + #[test] + fn plot_preview_reads_shared_png_and_rejects_other_bytes() { + let ctx = egui::Context::default(); + let mut png = Vec::new(); + cadcraft_render::raster::write_rgba_png(&mut png, 1, 1, &[10, 20, 30, 255]).unwrap(); + let texture = super::preview_texture(&ctx, &png).unwrap(); + assert_eq!(texture.size(), [1, 1]); + assert!(super::preview_texture(&ctx, b"not a PNG").is_err()); + } + #[test] fn typed_and_menu_commands_ask_json_calls_never_do() { let (mut app, asked) = app();