From 3074db1cbb76ade27b18013028dccac435ca134f Mon Sep 17 00:00:00 2001 From: Barzabel Date: Wed, 14 Oct 2026 18:45:15 +0300 Subject: [PATCH 1/6] M1: drop shadows under a background blur (#255) A layer with a background blur (or glass) drew its blurred backdrop into its own pixels before casting its drop shadows from them, so a translucent fill cast a shadow as dark as an opaque one, and with "show behind transparent areas" the shadow was cast from the backdrop's pixels. The backdrop was also read before the shadows were drawn, so a shadow showing behind was never seen through the blur. When a layer has both, it now casts its shadows from what it paints (with the layer blur, noise and texture it will get), draws them, and only then reads the backdrop, which goes under its content; the content still sees the first backdrop under it while it's drawn. Layers without both draw as before. --- crates/render/src/backdrop_shadow_tests.rs | 79 ++++++++++++++++++++ crates/render/src/draw.rs | 86 +++++++++++++++------- crates/render/src/lib.rs | 2 + 3 files changed, 142 insertions(+), 25 deletions(-) create mode 100644 crates/render/src/backdrop_shadow_tests.rs diff --git a/crates/render/src/backdrop_shadow_tests.rs b/crates/render/src/backdrop_shadow_tests.rs new file mode 100644 index 00000000..9c5fb562 --- /dev/null +++ b/crates/render/src/backdrop_shadow_tests.rs @@ -0,0 +1,79 @@ +//! A drop shadow under a layer with a background blur (#255): the shadow is cast by what the layer +//! paints (a translucent fill casts a faint one), not by the blurred backdrop drawn through its +//! shape, and the blur reads what lies under the layer with its own shadow there, so a shadow +//! that shows behind transparent areas is seen, blurred, through the layer. + +use figcraft_color::{Color, Paint}; +use figcraft_doc::{Blur, Document, Effect, EffectKind, NodeId, NodeKind, Shadow}; + +use super::*; + +/// A white 240 × 200 frame with blue and green stripes and, on top, a pane at (60, 40) 120 × 80 +/// filled 20% black, with a hard black drop shadow 40 down (below it and under its lower half) +/// and, when `blur`, a background blur. +fn scene(show_behind: bool, blur: bool) -> (Document, NodeId) { + let mut d = Document::new("shadow behind blur"); + let p = d.first_page().unwrap(); + let f = d.create(p, NodeKind::Frame, "Frame", 0.0, 0.0, 240.0, 200.0).unwrap(); + d.get_mut(f).unwrap().fills = vec![Paint::solid(Color::from_hex("FFFFFF").unwrap())]; + for (i, x) in [20.0, 80.0, 140.0, 200.0].into_iter().enumerate() { + let s = d.create(f, NodeKind::Rectangle, "Stripe", x, 0.0, 20.0, 200.0).unwrap(); + d.get_mut(s).unwrap().fills = vec![Paint::solid(Color::from_hex(if i % 2 == 0 { "2040E0" } else { "20C060" }).unwrap())]; + } + let pane = d.create(f, NodeKind::Rectangle, "Pane", 60.0, 40.0, 120.0, 80.0).unwrap(); + let n = d.get_mut(pane).unwrap(); + n.fills = vec![Paint::solid(Color::new(0.0, 0.0, 0.0, 0.2))]; + let shadow = Shadow { color: Color::new(0.0, 0.0, 0.0, 1.0), offset: (0.0, 40.0), radius: 0.0, show_behind, ..Shadow::default() }; + n.effects = vec![Effect { kind: EffectKind::DropShadow(shadow), visible: true }]; + if blur { + n.effects.push(Effect { kind: EffectKind::BackgroundBlur(Blur::uniform(8.0)), visible: true }); + } + (d, f) +} + +fn px(p: &Pixmap, x: u32, y: u32) -> [u8; 4] { + let i = ((y * p.width() + x) * 4) as usize; + [p.data()[i], p.data()[i + 1], p.data()[i + 2], p.data()[i + 3]] +} + +/// The largest channel difference between `a` and `b` over the shadow below the pane +/// (60..180 × 122..160). +fn max_diff_below_pane(a: &Pixmap, b: &Pixmap) -> u8 { + let mut worst = 0; + for y in 122..160 { + for x in 60..180 { + worst = worst.max(px(a, x, y).iter().zip(px(b, x, y)).map(|(c, d)| c.abs_diff(d)).max().unwrap()); + } + } + worst +} + +#[test] +fn a_background_blur_doesnt_change_the_shadow_its_layer_casts() { + for show_behind in [false, true] { + let (with_blur, f) = scene(show_behind, true); + let (without, _) = scene(show_behind, false); + let got = render_node(&with_blur, f, 1.0).unwrap(); + let want = render_node(&without, f, 1.0).unwrap(); + let diff = max_diff_below_pane(&got, &want); + assert!(diff <= 2, "show behind {show_behind}: the shadow below the pane differs by {diff}"); + // A 20% fill casts a faint shadow: the white between the stripes stays light. + let light = px(&got, 120, 140); + assert!(light[0] > 180, "show behind {show_behind}: {light:?}"); + } +} + +#[test] +fn a_shadow_showing_behind_is_seen_through_the_background_blur() { + let (d, f) = scene(true, true); + let got = render_node(&d, f, 1.0).unwrap(); + // Between the stripes, the pane's top (no shadow under it) and its lower half (its own shadow + // under it, from y = 80). + let (top, low) = (px(&got, 120, 50), px(&got, 120, 110)); + assert!(top[0] > low[0] + 20, "the shadow under the pane doesn't show through: top {top:?}, lower half {low:?}"); + // Hidden behind the layer, it doesn't. + let (d, f) = scene(false, true); + let got = render_node(&d, f, 1.0).unwrap(); + let (top, low) = (px(&got, 120, 50), px(&got, 120, 110)); + assert!(top[0].abs_diff(low[0]) <= 2, "a hidden shadow shows: top {top:?}, lower half {low:?}"); +} diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index be839b27..af73aeeb 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -423,16 +423,15 @@ pub fn draw_node(ctx: &Ctx, pix: &mut Pixmap, id: NodeId, parent_xf: Affine, dep let shape = node_outline(ctx.doc, n); // Background blur and glass: the whole backdrop under the layer (every surface below this // one, composited), through the shape, under the content. - if backdrop::has_effects(n) - && let Some(sh) = &backdrop::outline(ctx.doc, n) - { - let pad = backdrop::pad(n, ctx.scale); - let p = i32::try_from(pad).unwrap_or(0); - if let Some(back) = backdrop::backdrop(pix, ctx.under, lx.saturating_sub(p), ly.saturating_sub(p), lw + pad * 2, lh + pad * 2) - && let Some(b) = backdrop::effects(n, sh, &back, pad, lw, lh, lxf, ctx.scale) - { - layer.draw_pixmap(0, 0, b.as_ref(), &PixmapPaint::default(), Transform::identity(), None); - } + let back_shape = if backdrop::has_effects(n) { backdrop::outline(ctx.doc, n) } else { None }; + let read_backdrop = |pix: &Pixmap| back_shape.as_ref().and_then(|sh| backdrop_layer(ctx, pix, n, sh, (lx, ly), (lw, lh), lxf)); + // With drop shadows too, the layer casts them from what it paints, not from the backdrop, and + // the backdrop is read again once they lie under it (a shadow showing behind is seen through + // it). Until then, the layer's content sees the backdrop read first under it (#255). + let casts = back_shape.is_some() && n.effects.iter().any(|e| e.visible && matches!(e.kind, EffectKind::DropShadow(_))); + let first_back = read_backdrop(pix); + if !casts && let Some(b) = &first_back { + layer.draw_pixmap(0, 0, b.as_ref(), &PixmapPaint::default(), Transform::identity(), None); } let op = n.opacity.clamp(0.0, 1.0); { @@ -448,9 +447,12 @@ pub fn draw_node(ctx: &Ctx, pix: &mut Pixmap, id: NodeId, parent_xf: Affine, dep } }; let has_inner = shape.is_some() && n.effects.iter().any(|e| e.visible && matches!(e.kind, EffectKind::InnerShadow(_))); - // Backdrops further down see this layer composited onto `pix`. + // Backdrops further down see this layer composited onto `pix` (over its backdrop, when + // that is kept apart for now). let under = Under { opacity: op, blend: n.blend, ..Under::new(pix, (lx, ly), ctx.under) }; - draw_content(&Ctx { under: Some(&under), ..*ctx }, &mut layer, n, lxf, depth, has_inner.then_some(&inner as &dyn Fn(&mut Pixmap))); + let over_back = first_back.as_ref().filter(|_| casts).map(|b| Under::new(b, (0, 0), Some(&under))); + let content_under = over_back.as_ref().unwrap_or(&under); + draw_content(&Ctx { under: Some(content_under), ..*ctx }, &mut layer, n, lxf, depth, has_inner.then_some(&inner as &dyn Fn(&mut Pixmap))); } // A group is no outline of its own: its inner shadows are cast from around what its layers // draw together, over them. @@ -465,24 +467,58 @@ pub fn draw_node(ctx: &Ctx, pix: &mut Pixmap, id: NodeId, parent_xf: Affine, dep } } // Layer blur, noise and texture, in list order, over everything else. + if !casts { + layer_effects(ctx, &mut layer, n, id, lxf); + } + // Drop shadows go under the layer, in effect-list order. + { + // Kept apart, the backdrop isn't in the layer yet: the shadows are cast from the content + // with the layer effects it will get. + let content = casts.then(|| { + let mut c = layer.clone(); + layer_effects(ctx, &mut c, n, id, lxf); + c + }); + let caster = shadow::Caster::new(ctx.doc, n, content.as_ref().unwrap_or(&layer), lxf, ctx.scale); + for e in n.effects.iter().filter(|e| e.visible) { + if let EffectKind::DropShadow(s) = &e.kind + && let Some(sh) = shadow::drop_shadow(&caster, s) + { + composite(pix, (lx, ly), &sh, op, s.blend); + } + } + } + if casts { + // The backdrop with the shadows under it, the content over it, then the layer effects. + if let Some(mut b) = read_backdrop(pix) { + b.draw_pixmap(0, 0, layer.as_ref(), &PixmapPaint::default(), Transform::identity(), None); + layer = b; + } + layer_effects(ctx, &mut layer, n, id, lxf); + } + composite(pix, (lx, ly), &layer, op, n.blend); +} + +/// Node `n`'s backdrop effects through its backdrop outline `sh`, for its `size` layer at `at` on +/// `pix` (local → layer pixels through `lxf`): what `pix` holds there now, over what lies under it. +fn backdrop_layer(ctx: &Ctx, pix: &Pixmap, n: &Node, sh: &shadow::Outline, at: (i32, i32), size: (u32, u32), lxf: Affine) -> Option { + let ((lx, ly), (lw, lh)) = (at, size); + let pad = backdrop::pad(n, ctx.scale); + let p = i32::try_from(pad).unwrap_or(0); + let back = backdrop::backdrop(pix, ctx.under, lx.saturating_sub(p), ly.saturating_sub(p), lw + pad * 2, lh + pad * 2)?; + backdrop::effects(n, sh, &back, pad, lw, lh, lxf, ctx.scale) +} + +/// Node `n`'s layer blur, noise and texture on its `layer`, in list order. +fn layer_effects(ctx: &Ctx, layer: &mut Pixmap, n: &Node, id: NodeId, lxf: Affine) { for e in n.effects.iter().filter(|e| e.visible) { match &e.kind { - EffectKind::LayerBlur(b) => blur::apply(&mut layer, b, (n.width, n.height), lxf, ctx.scale), - EffectKind::Noise(nz) => grain::noise(&mut layer, nz, lxf, id.0 as u32), - EffectKind::Texture(t) => grain::texture(&mut layer, t, lxf, ctx.scale, id.0 as u32), + EffectKind::LayerBlur(b) => blur::apply(layer, b, (n.width, n.height), lxf, ctx.scale), + EffectKind::Noise(nz) => grain::noise(layer, nz, lxf, id.0 as u32), + EffectKind::Texture(t) => grain::texture(layer, t, lxf, ctx.scale, id.0 as u32), _ => {} } } - // Drop shadows go under the layer, in effect-list order. - let caster = shadow::Caster::new(ctx.doc, n, &layer, lxf, ctx.scale); - for e in n.effects.iter().filter(|e| e.visible) { - if let EffectKind::DropShadow(s) = &e.kind - && let Some(sh) = shadow::drop_shadow(&caster, s) - { - composite(pix, (lx, ly), &sh, op, s.blend); - } - } - composite(pix, (lx, ly), &layer, op, n.blend); } fn draw_outline(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, depth: usize) { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index c2bf9dda..1025d507 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -425,6 +425,8 @@ pub fn png_insert_chunk(png: Vec, kind: &[u8; 4], data: &[u8]) -> Vec { out } +#[cfg(test)] +mod backdrop_shadow_tests; #[cfg(test)] mod backdrop_tests; #[cfg(test)] From f4d53a659b68d03f7bc03e0c438e6197980560f3 Mon Sep 17 00:00:00 2001 From: Barzabel Date: Wed, 14 Oct 2026 20:36:47 +0300 Subject: [PATCH 2/6] M1: memory budgets for decoded images and a file's images (#203, #189) --- crates/format/src/image_budget_tests.rs | 93 ++++++++++++++++++++ crates/format/src/lib.rs | 64 +++++++++++--- crates/render/src/image_budget_tests.rs | 111 ++++++++++++++++++++++++ crates/render/src/images.rs | 95 +++++++++++++++----- crates/render/src/lib.rs | 2 + 5 files changed, 331 insertions(+), 34 deletions(-) create mode 100644 crates/format/src/image_budget_tests.rs create mode 100644 crates/render/src/image_budget_tests.rs diff --git a/crates/format/src/image_budget_tests.rs b/crates/format/src/image_budget_tests.rs new file mode 100644 index 00000000..58bb4da1 --- /dev/null +++ b/crates/format/src/image_budget_tests.rs @@ -0,0 +1,93 @@ +//! The images of a native file within a budget (#189): however many members each within the +//! per-member limit a file holds, the images read from it together stay within a byte and a count +//! budget. The document's own images are read first, and the ones past the budget are reported. + +use std::io::Write; + +use figcraft_doc::Document; + +use super::*; + +fn png(k: u8) -> Vec { + let img = image::RgbaImage::from_pixel(2, 2, image::Rgba([k, 7, 0, 255])); + let mut out = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +/// A saved document with `n` images, and their hashes and total size. +fn file_with_images(n: u8) -> (Vec, Vec, u64) { + let mut d = Document::new("File"); + let mut hashes = Vec::new(); + let mut total = 0; + for k in 0..n { + let bytes = png(k); + total += bytes.len() as u64; + hashes.push(add_image(&mut d, bytes).unwrap().0); + } + (save_bytes(&d, None).unwrap(), hashes, total) +} + +/// `bytes` with one more member, `name` holding `data`. +fn with_member(bytes: &[u8], name: &str, data: &[u8]) -> Vec { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let names: Vec = z.file_names().map(str::to_string).collect(); + let mut buf = std::io::Cursor::new(Vec::new()); + let mut w = zip::ZipWriter::new(&mut buf); + let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + for n in names { + let member = read_member(&mut z, &n, u64::MAX).unwrap(); + w.start_file(n, stored).unwrap(); + w.write_all(&member).unwrap(); + } + w.start_file(name, stored).unwrap(); + w.write_all(data).unwrap(); + w.finish().unwrap(); + buf.into_inner() +} + +#[test] +fn images_exactly_within_the_budget_all_load() { + let (bytes, hashes, total) = file_with_images(3); + let loaded = load_within(&bytes, ImageBudget { images: 3, bytes: total }).unwrap(); + assert!(loaded.issues.is_empty(), "{:?}", loaded.issues); + assert!(hashes.iter().all(|h| loaded.doc.images.contains_key(h))); +} + +#[test] +fn images_past_the_byte_budget_are_left_out_and_reported() { + let (bytes, hashes, total) = file_with_images(3); + let loaded = load_within(&bytes, ImageBudget { images: 100, bytes: total - 1 }).unwrap(); + let held: u64 = loaded.doc.images.values().map(|i| i.bytes.len() as u64).sum(); + assert!(held < total, "{held} bytes held"); + assert_eq!(loaded.doc.images.len(), 2); + let lost: Vec<&String> = hashes.iter().filter(|h| !loaded.doc.images.contains_key(*h)).collect(); + assert_eq!(lost.len(), 1); + assert!(loaded.issues.iter().any(|i| i.contains(lost[0].as_str()) && i.contains("together")), "{:?}", loaded.issues); +} + +#[test] +fn images_past_the_count_budget_are_left_out_and_reported() { + let (bytes, _, _) = file_with_images(4); + let loaded = load_within(&bytes, ImageBudget { images: 3, bytes: u64::MAX }).unwrap(); + assert_eq!(loaded.doc.images.len(), 3); + assert!(loaded.issues.iter().any(|i| i.contains("more than 3 images")), "{:?}", loaded.issues); +} + +#[test] +fn the_documents_own_images_are_read_before_others() { + let (bytes, hashes, total) = file_with_images(2); + // An image the document doesn't list, named to come first in the archive's order. + let extra = with_member(&bytes, "images/0000", &png(99)); + let loaded = load_within(&extra, ImageBudget { images: 2, bytes: total }).unwrap(); + assert!(hashes.iter().all(|h| loaded.doc.images.contains_key(h)), "{:?}", loaded.issues); + assert!(!loaded.issues.iter().any(|i| hashes.iter().any(|h| i.contains(h.as_str()))), "{:?}", loaded.issues); +} + +#[test] +fn a_file_within_the_shipped_budget_loads_as_before() { + let (bytes, hashes, _) = file_with_images(3); + let loaded = load_bytes_with_versions(&bytes).unwrap(); + assert!(loaded.issues.is_empty(), "{:?}", loaded.issues); + assert!(hashes.iter().all(|h| loaded.doc.images.contains_key(h))); +} diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 56798d14..f88416e2 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -47,6 +47,8 @@ pub const MAX_VERSION_DESCRIPTION: usize = 2000; /// Largest version index and total size of the version snapshots read from one file. const MAX_VERSION_INDEX: u64 = 16 * 1024 * 1024; const MAX_VERSION_BYTES: u64 = 1024 * 1024 * 1024; +/// Most images, and image bytes together, read from one file (members past it are left out). +const IMAGE_BUDGET: ImageBudget = ImageBudget { images: 20_000, bytes: 4 * 1024 * 1024 * 1024 }; const BRANCH_INDEX: &str = "branches/index.json"; /// Most branches a file keeps: making more is refused, extra entries in a file are skipped. pub const MAX_BRANCHES: usize = 100; @@ -453,8 +455,20 @@ pub(crate) fn read_member(z: &mut zip::ZipArchive, name: &str Ok(data) } +/// How many images, and how many bytes of them together, one file may give. +#[derive(Clone, Copy, Debug)] +pub(crate) struct ImageBudget { + pub images: usize, + pub bytes: u64, +} + /// Read a `.figcraft` archive (or bare JSON) with its version history. pub fn load_bytes_with_versions(bytes: &[u8]) -> Result { + load_within(bytes, IMAGE_BUDGET) +} + +/// [`load_bytes_with_versions`] reading at most `budget` of images. +pub(crate) fn load_within(bytes: &[u8], budget: ImageBudget) -> Result { let trimmed = bytes.iter().position(|b| !b.is_ascii_whitespace()).and_then(|i| bytes.get(i)); if trimmed == Some(&b'{') { let text = std::str::from_utf8(bytes).map_err(|e| FormatError::Corrupt(e.to_string()))?; @@ -464,18 +478,7 @@ pub fn load_bytes_with_versions(bytes: &[u8]) -> Result { let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| FormatError::Corrupt(e.to_string()))?; let text = String::from_utf8(read_member(&mut z, "document.json", MAX_MEMBER)?).map_err(|e| FormatError::Corrupt(e.to_string()))?; let (mut doc, mut issues, own_images) = parse_json(&text)?; - let names: Vec = z.file_names().filter(|n| n.starts_with("images/")).map(str::to_string).collect(); - let mut images = BTreeMap::new(); - let mut unread = Vec::new(); - for name in names { - let hash = name.trim_start_matches("images/").to_string(); - match read_member(&mut z, &name, MAX_MEMBER) { - Ok(data) => { - images.insert(hash, image_data(data)); - } - Err(e) => unread.push((hash, e)), - } - } + let (images, unread) = read_images(&mut z, own_images.as_ref(), budget); report_lost_images(&mut issues, &unread, own_images.as_ref(), &images); match library::read(&mut z, &images, u64::MAX) { Ok(lib) => doc.published = lib.map(Arc::new), @@ -497,6 +500,41 @@ pub fn load_bytes_with_versions(bytes: &[u8]) -> Result { Ok(Loaded { doc, issues, versions, branches }) } +/// The archive's `images/` members by hash, within `budget`, and the ones that couldn't be read +/// with why. The document's own images (`own`) are read first, so a file past the budget loses +/// the images only its history uses before its own. +fn read_images( + z: &mut zip::ZipArchive, + own: Option<&BTreeSet>, + budget: ImageBudget, +) -> (BTreeMap, Vec<(String, FormatError)>) { + let mut hashes: Vec = z.file_names().filter_map(|n| n.strip_prefix("images/")).map(str::to_string).collect(); + hashes.sort_by_key(|h| !own.is_some_and(|o| o.contains(h))); + let mut images = BTreeMap::new(); + let mut unread = Vec::new(); + let mut left = budget.bytes; + for (i, hash) in hashes.into_iter().enumerate() { + let name = format!("images/{hash}"); + if i >= budget.images { + unread.push((hash, FormatError::Corrupt(format!("the file has more than {} images", budget.images)))); + continue; + } + if z.by_name(&name).is_ok_and(|f| f.size() > left) { + let mb = budget.bytes / (1024 * 1024); + unread.push((hash, FormatError::Corrupt(format!("the file's images together pass {mb} MB")))); + continue; + } + match read_member(z, &name, left.min(MAX_MEMBER)) { + Ok(data) => { + left = left.saturating_sub(data.len() as u64); + images.insert(hash, image_data(data)); + } + Err(e) => unread.push((hash, e)), + } + } + (images, unread) +} + /// Most lost images reported one by one (the rest as a count). const MAX_IMAGE_ISSUES: usize = 20; @@ -712,6 +750,8 @@ pub fn load_file(path: &std::path::Path) -> Result<(Document, Vec), Form #[cfg(test)] mod branch_tests; #[cfg(test)] +mod image_budget_tests; +#[cfg(test)] mod image_tests; #[cfg(test)] mod large_tests; diff --git a/crates/render/src/image_budget_tests.rs b/crates/render/src/image_budget_tests.rs new file mode 100644 index 00000000..ae654e09 --- /dev/null +++ b/crates/render/src/image_budget_tests.rs @@ -0,0 +1,111 @@ +//! Decoded images within a memory budget (#203): an image too large is refused from its header, +//! before its pixels are decoded, and the decoded-image caches hold a bounded number of bytes +//! however many images, filters and colour profiles a document uses. + +use std::sync::Arc; + +use figcraft_color::ColorProfile; +use tiny_skia::Pixmap; + +use super::*; + +fn png(w: u32, h: u32) -> Vec { + let img = image::RgbaImage::from_pixel(w, h, image::Rgba([200, 40, 40, 255])); + let mut out = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +/// A PNG whose header claims `w` × `h` but which holds no pixel data at all. +fn png_header_only(w: u32, h: u32) -> Vec { + let mut ihdr = Vec::new(); + ihdr.extend_from_slice(&w.to_be_bytes()); + ihdr.extend_from_slice(&h.to_be_bytes()); + ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); + let mut out = b"\x89PNG\r\n\x1a\n".to_vec(); + out.extend_from_slice(&13u32.to_be_bytes()); + let chunk: Vec = b"IHDR".iter().copied().chain(ihdr).collect(); + out.extend_from_slice(&chunk); + out.extend_from_slice(&crc32(&chunk).to_be_bytes()); + out +} + +fn crc32(data: &[u8]) -> u32 { + let mut crc = !0u32; + for b in data { + crc ^= u32::from(*b); + for _ in 0..8 { + crc = if crc & 1 == 1 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 }; + } + } + !crc +} + +#[test] +fn an_image_within_the_limits_decodes() { + let (p, _) = images::decode_within(&png(30, 20), ColorProfile::Srgb, 30, 30 * 20 * 4).unwrap(); + assert_eq!((p.width(), p.height()), (30, 20)); +} + +#[test] +fn an_image_wider_or_taller_than_the_limit_is_refused() { + assert!(images::decode_within(&png(30, 20), ColorProfile::Srgb, 29, u64::MAX).is_none()); + assert!(images::decode_within(&png(20, 30), ColorProfile::Srgb, 29, u64::MAX).is_none()); +} + +#[test] +fn an_image_whose_pixels_pass_the_byte_budget_is_refused() { + assert!(images::decode_within(&png(30, 20), ColorProfile::Srgb, 1000, 30 * 20 * 4 - 1).is_none()); +} + +#[test] +fn a_huge_image_is_refused_from_its_header_alone() { + // 16 000 × 16 000 is within the side limit; its pixels (1 GB) aren't within a 1 MB budget, and + // the file has none to decode: only the header is read. + assert!(images::decode_within(&png_header_only(16_000, 16_000), ColorProfile::Srgb, 16_384, 1 << 20).is_none()); + // Past the side limit, the shipped decode refuses it the same way. + assert!(images::decode(&png_header_only(20_000, 10)).is_none()); +} + +fn key(name: &str) -> images::Key { + (name.to_string(), [0; 7], ColorProfile::Srgb) +} + +fn pixmap(side: u32) -> Arc { + Arc::new(Pixmap::new(side, side).unwrap()) +} + +#[test] +fn the_image_cache_keeps_within_its_byte_budget() { + // 10 × 10 pixmaps are 400 bytes; 1000 bytes hold two. + let mut c = images::PixmapCache::default(); + for name in ["a", "b", "c", "d", "e"] { + c.insert(key(name), pixmap(10), 1000); + assert!(c.bytes() <= 1000, "{} bytes held", c.bytes()); + assert!(c.get(&key(name)).is_some(), "{name} was just added"); + } +} + +#[test] +fn an_image_larger_than_the_budget_is_held_alone() { + let mut c = images::PixmapCache::default(); + c.insert(key("small"), pixmap(10), 1000); + c.insert(key("big"), pixmap(20), 1000); + assert!(c.get(&key("big")).is_some()); + assert!(c.get(&key("small")).is_none()); + assert_eq!(c.bytes(), 20 * 20 * 4); + // The next image takes its place. + c.insert(key("next"), pixmap(10), 1000); + assert_eq!(c.bytes(), 400); +} + +#[test] +fn filter_and_profile_variants_count_against_one_budget() { + let mut c = images::PixmapCache::default(); + for (i, profile) in [ColorProfile::Srgb, ColorProfile::DisplayP3].into_iter().enumerate() { + for f in 0..4 { + c.insert(("img".to_string(), [f, 0, 0, 0, 0, 0, i as i32], profile), pixmap(10), 1000); + assert!(c.bytes() <= 1000, "{} bytes held", c.bytes()); + } + } +} diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index abdb9e1f..4892e508 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -13,11 +13,54 @@ use figcraft_color::{ColorProfile, ImageFilters, PaintKind}; use figcraft_doc::{Document, ImageData, NodeId}; use tiny_skia::Pixmap; -type Key = (String, [i32; 7], ColorProfile); +pub(crate) type Key = (String, [i32; 7], ColorProfile); -fn cache() -> &'static Mutex>> { - static C: OnceLock>>> = OnceLock::new(); - C.get_or_init(|| Mutex::new(HashMap::new())) +/// The largest image side decoded. +const MAX_SIDE: u32 = 16_384; +/// The most bytes one image's decoded pixels take (a 16k × 16k 8-bit RGBA image). +const MAX_DECODED_BYTES: u64 = 1 << 30; +/// The most bytes of pixels each decoded-image cache holds (one image larger than this is held +/// alone). +const MAX_CACHED_BYTES: u64 = 512 << 20; +/// The most entries each decoded-image cache holds. +const MAX_CACHED_IMAGES: usize = 256; + +/// Decoded pixmaps by image, filters and profile, holding at most a byte budget of pixels: adding +/// one past the budget (or past [`MAX_CACHED_IMAGES`]) empties the cache first. +#[derive(Default)] +pub(crate) struct PixmapCache { + map: HashMap>, + bytes: u64, +} + +impl PixmapCache { + pub(crate) fn get(&self, key: &Key) -> Option> { + self.map.get(key).cloned() + } + + /// Add `p` under `key`, keeping the cache within `max_bytes` (or holding `p` alone). + pub(crate) fn insert(&mut self, key: Key, p: Arc, max_bytes: u64) { + let size = p.data().len() as u64; + if self.bytes.saturating_add(size) > max_bytes || self.map.len() >= MAX_CACHED_IMAGES { + self.map.clear(); + self.bytes = 0; + } + if let Some(old) = self.map.insert(key, p) { + self.bytes = self.bytes.saturating_sub(old.data().len() as u64); + } + self.bytes = self.bytes.saturating_add(size); + } + + /// The bytes of pixels held. + #[cfg(test)] + pub(crate) fn bytes(&self) -> u64 { + self.bytes + } +} + +fn cache() -> &'static Mutex { + static C: OnceLock> = OnceLock::new(); + C.get_or_init(|| Mutex::new(PixmapCache::default())) } fn fkey(f: &ImageFilters) -> [i32; 7] { @@ -34,7 +77,23 @@ pub fn decode(bytes: &[u8]) -> Option { /// image's own profile into `target` (`false`), or as sRGB when it has none (`true`: the sRGB → /// `target` conversion is still to do). fn decode_in(bytes: &[u8], target: ColorProfile) -> Option<(Pixmap, bool)> { - let mut dec = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?; + decode_within(bytes, target, MAX_SIDE, MAX_DECODED_BYTES) +} + +/// [`decode_in`] for images at most `max_side` wide and tall whose decoded pixels take at most +/// `max_bytes`; larger ones are refused from their header, before any pixels are decoded. +pub(crate) fn decode_within(bytes: &[u8], target: ColorProfile, max_side: u32, max_bytes: u64) -> Option<(Pixmap, bool)> { + use image::ImageDecoder; + let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?; + let mut limits = image::Limits::default(); + limits.max_image_width = Some(max_side); + limits.max_image_height = Some(max_side); + limits.max_alloc = Some(max_bytes); + reader.limits(limits); + let mut dec = reader.into_decoder().ok()?; + if dec.total_bytes() > max_bytes { + return None; + } let source = crate::image_profile::Source::read(bytes, &mut dec); let img = image::DynamicImage::from_decoder(dec).ok()?; match source.convert(&img, target) { @@ -66,7 +125,7 @@ pub fn profile_name(hash: &str, data: Option<&ImageData>) -> Option { /// Straight RGBA → a premultiplied pixmap (max 16k per side). fn premultiplied(rgba: &image::RgbaImage) -> Option { let (w, h) = rgba.dimensions(); - if w == 0 || h == 0 || w > 16_384 || h > 16_384 { + if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE { return None; } let mut p = Pixmap::new(w, h)?; @@ -87,17 +146,13 @@ fn premultiplied(rgba: &image::RgbaImage) -> Option { pub fn get(hash: &str, data: Option<&ImageData>, filters: &ImageFilters, profile: ColorProfile) -> Option> { let key = (hash.to_string(), fkey(filters), profile); if let Some(p) = cache().lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&key) { - return Some(p.clone()); + return Some(p); } let (mut p, srgb) = decode_in(&data?.bytes, profile)?; // Images with their own profile are in `profile` already (sRGB → sRGB is the identity). finish(&mut p, filters, if srgb { profile } else { ColorProfile::Srgb }); let p = Arc::new(p); - let mut c = cache().lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if c.len() > 256 { - c.clear(); - } - c.insert(key, p.clone()); + cache().lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(key, p.clone(), MAX_CACHED_BYTES); Some(p) } @@ -166,7 +221,7 @@ pub fn decode_frames(bytes: &[u8]) -> Option> { let dec = image::codecs::gif::GifDecoder::new(std::io::Cursor::new(bytes)).ok()?; let (w, h) = dec.dimensions(); let frame_bytes = u64::from(w) * u64::from(h) * 4; - if frame_bytes == 0 || w > 16_384 || h > 16_384 { + if frame_bytes == 0 || w > MAX_SIDE || h > MAX_SIDE { return None; } let most = (MAX_ANIMATION_BYTES / frame_bytes).min(MAX_FRAMES as u64) as usize; @@ -304,22 +359,18 @@ pub fn pad(pm: &Pixmap) -> Option { Some(out) } -fn padded_cache() -> &'static Mutex>> { - static C: OnceLock>>> = OnceLock::new(); - C.get_or_init(|| Mutex::new(HashMap::new())) +fn padded_cache() -> &'static Mutex { + static C: OnceLock> = OnceLock::new(); + C.get_or_init(|| Mutex::new(PixmapCache::default())) } /// `pm` with a transparent 1-pixel border (cached). pub fn padded(hash: &str, filters: &ImageFilters, profile: ColorProfile, pm: &Pixmap) -> Option> { let key = (hash.to_string(), fkey(filters), profile); if let Some(p) = padded_cache().lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&key) { - return Some(p.clone()); + return Some(p); } let out = Arc::new(pad(pm)?); - let mut c = padded_cache().lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if c.len() > 256 { - c.clear(); - } - c.insert(key, out.clone()); + padded_cache().lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(key, out.clone(), MAX_CACHED_BYTES); Some(out) } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index c2bf9dda..904e6dce 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -442,6 +442,8 @@ mod grain_tests; #[cfg(test)] mod group_effects_tests; #[cfg(test)] +mod image_budget_tests; +#[cfg(test)] mod image_profile_tests; #[cfg(test)] mod lod_tests; From a7bcc6d6ffc252bbf0296b5c35aff6065d618a9b Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 15 Oct 2026 19:25:05 +0700 Subject: [PATCH 3/6] #317: compute the backdrop once under a casting layer With drop shadows the backdrop was read twice: before the content and again after the shadows. The first read is only what backdrop effects inside the content see, so it now runs only when the layer has such descendants, and the content is copied for the shadow caster only when it gets a layer blur, noise or texture. The output is unchanged. --- crates/render/src/draw.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index af73aeeb..45b48500 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -429,7 +429,10 @@ pub fn draw_node(ctx: &Ctx, pix: &mut Pixmap, id: NodeId, parent_xf: Affine, dep // the backdrop is read again once they lie under it (a shadow showing behind is seen through // it). Until then, the layer's content sees the backdrop read first under it (#255). let casts = back_shape.is_some() && n.effects.iter().any(|e| e.visible && matches!(e.kind, EffectKind::DropShadow(_))); - let first_back = read_backdrop(pix); + // Kept apart, the first read is only what backdrop effects inside the content see: without + // any, the backdrop (blur or glass, the costly part) is computed once, after the shadows. + let nested = || ctx.doc.subtree(id).iter().skip(1).any(|c| ctx.doc.node(*c).is_some_and(backdrop::has_effects)); + let first_back = if !casts || nested() { read_backdrop(pix) } else { None }; if !casts && let Some(b) = &first_back { layer.draw_pixmap(0, 0, b.as_ref(), &PixmapPaint::default(), Transform::identity(), None); } @@ -473,8 +476,10 @@ pub fn draw_node(ctx: &Ctx, pix: &mut Pixmap, id: NodeId, parent_xf: Affine, dep // Drop shadows go under the layer, in effect-list order. { // Kept apart, the backdrop isn't in the layer yet: the shadows are cast from the content - // with the layer effects it will get. - let content = casts.then(|| { + // with the layer effects it will get (a copy only when it gets some). + let layer_fx = + n.effects.iter().any(|e| e.visible && matches!(e.kind, EffectKind::LayerBlur(_) | EffectKind::Noise(_) | EffectKind::Texture(_))); + let content = (casts && layer_fx).then(|| { let mut c = layer.clone(); layer_effects(ctx, &mut c, n, id, lxf); c From 4a2d19f0db5565260ce08f0b77ed2d5e2b417d76 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 15 Oct 2026 18:50:55 +0700 Subject: [PATCH 4/6] #326: decode at most the image crate's default 512 MiB per image; a full image cache drops its least recently used images, not all of them --- crates/render/src/image_budget_tests.rs | 14 +++++++++ crates/render/src/images.rs | 39 +++++++++++++++++-------- 2 files changed, 41 insertions(+), 12 deletions(-) diff --git a/crates/render/src/image_budget_tests.rs b/crates/render/src/image_budget_tests.rs index ae654e09..6228efc5 100644 --- a/crates/render/src/image_budget_tests.rs +++ b/crates/render/src/image_budget_tests.rs @@ -86,6 +86,20 @@ fn the_image_cache_keeps_within_its_byte_budget() { } } +#[test] +fn a_full_image_cache_drops_the_least_recently_used_image_only() { + // 1000 bytes hold two 400-byte pixmaps: the third drops the one used longest ago. + let mut c = images::PixmapCache::default(); + c.insert(key("a"), pixmap(10), 1000); + c.insert(key("b"), pixmap(10), 1000); + assert!(c.get(&key("a")).is_some()); + c.insert(key("c"), pixmap(10), 1000); + assert!(c.get(&key("a")).is_some(), "used since b: kept"); + assert!(c.get(&key("b")).is_none(), "used longest ago: dropped"); + assert!(c.get(&key("c")).is_some()); + assert_eq!(c.bytes(), 800); +} + #[test] fn an_image_larger_than_the_budget_is_held_alone() { let mut c = images::PixmapCache::default(); diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 4892e508..f4f9c5d9 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -17,8 +17,9 @@ pub(crate) type Key = (String, [i32; 7], ColorProfile); /// The largest image side decoded. const MAX_SIDE: u32 = 16_384; -/// The most bytes one image's decoded pixels take (a 16k × 16k 8-bit RGBA image). -const MAX_DECODED_BYTES: u64 = 1 << 30; +/// The most bytes one image's decoding may allocate: the image crate's own default limit (a +/// larger image is refused from its header). +const MAX_DECODED_BYTES: u64 = 512 << 20; /// The most bytes of pixels each decoded-image cache holds (one image larger than this is held /// alone). const MAX_CACHED_BYTES: u64 = 512 << 20; @@ -26,31 +27,45 @@ const MAX_CACHED_BYTES: u64 = 512 << 20; const MAX_CACHED_IMAGES: usize = 256; /// Decoded pixmaps by image, filters and profile, holding at most a byte budget of pixels: adding -/// one past the budget (or past [`MAX_CACHED_IMAGES`]) empties the cache first. +/// one past the budget (or past [`MAX_CACHED_IMAGES`]) drops the least recently used first, so +/// the images on screen stay while they fit. #[derive(Default)] pub(crate) struct PixmapCache { - map: HashMap>, + /// Each pixmap and when it was last used. + map: HashMap, u64)>, bytes: u64, + tick: u64, } impl PixmapCache { - pub(crate) fn get(&self, key: &Key) -> Option> { - self.map.get(key).cloned() + pub(crate) fn get(&mut self, key: &Key) -> Option> { + self.tick += 1; + let tick = self.tick; + self.map.get_mut(key).map(|(p, used)| { + *used = tick; + p.clone() + }) } /// Add `p` under `key`, keeping the cache within `max_bytes` (or holding `p` alone). pub(crate) fn insert(&mut self, key: Key, p: Arc, max_bytes: u64) { let size = p.data().len() as u64; - if self.bytes.saturating_add(size) > max_bytes || self.map.len() >= MAX_CACHED_IMAGES { - self.map.clear(); - self.bytes = 0; - } - if let Some(old) = self.map.insert(key, p) { - self.bytes = self.bytes.saturating_sub(old.data().len() as u64); + self.remove(&key); + while self.bytes.saturating_add(size) > max_bytes || self.map.len() >= MAX_CACHED_IMAGES { + let Some(oldest) = self.map.iter().min_by_key(|(_, (_, used))| *used).map(|(k, _)| k.clone()) else { break }; + self.remove(&oldest); } + self.tick += 1; + self.map.insert(key, (p, self.tick)); self.bytes = self.bytes.saturating_add(size); } + fn remove(&mut self, key: &Key) { + if let Some((p, _)) = self.map.remove(key) { + self.bytes = self.bytes.saturating_sub(p.data().len() as u64); + } + } + /// The bytes of pixels held. #[cfg(test)] pub(crate) fn bytes(&self) -> u64 { From 97f9c2fc5de430730c24b954736901f2a85a9f69 Mon Sep 17 00:00:00 2001 From: Barzabel Date: Wed, 14 Oct 2026 17:37:59 +0300 Subject: [PATCH 5/6] M1: say why when the window can't open (#261) Release builds on Windows have no console, so an eframe::run_native error (no usable graphics adapter, a device the driver refuses) went to an unseen standard error and the app quit silently. The error is now logged and shown in a message box with a hint: unset WGPU_BACKEND when it is set, otherwise update the driver or try another graphics API (OpenGL on Windows), and where to report it. With --control the box is skipped so agents aren't blocked. --- apps/figcraft/src/main.rs | 12 ++++++-- apps/figcraft/src/startup.rs | 44 ++++++++++++++++++++++++++++++ apps/figcraft/src/startup_tests.rs | 35 ++++++++++++++++++++++++ 3 files changed, 89 insertions(+), 2 deletions(-) create mode 100644 apps/figcraft/src/startup.rs create mode 100644 apps/figcraft/src/startup_tests.rs diff --git a/apps/figcraft/src/main.rs b/apps/figcraft/src/main.rs index 7b14d8e2..1babfd5b 100644 --- a/apps/figcraft/src/main.rs +++ b/apps/figcraft/src/main.rs @@ -17,6 +17,7 @@ mod gamepad; mod graphics; mod recovery; mod services; +mod startup; #[cfg(all(test, target_os = "macos"))] mod apple_events_tests; @@ -30,6 +31,8 @@ mod recovery_online_tests; mod recovery_tests; #[cfg(test)] mod services_tests; +#[cfg(test)] +mod startup_tests; use std::sync::{Arc, Mutex}; @@ -203,7 +206,7 @@ fn main() -> eframe::Result { let apple_events = apple_events::AppleEvents::install(); #[cfg(target_os = "macos")] let apple_events = &apple_events; - eframe::run_native( + let result = eframe::run_native( "FigCraft", options, Box::new(move |_cc| { @@ -216,5 +219,10 @@ fn main() -> eframe::Result { apple_events: apple_events.connect(&_cc.egui_ctx), })) }), - ) + ); + // Say why instead of quitting silently: release builds on Windows have no console. + if let Err(e) = &result { + startup::failed(e, port.is_some()); + } + result } diff --git a/apps/figcraft/src/startup.rs b/apps/figcraft/src/startup.rs new file mode 100644 index 00000000..8a50d7a5 --- /dev/null +++ b/apps/figcraft/src/startup.rs @@ -0,0 +1,44 @@ +//! When the window can't open. +//! +//! Release builds on Windows have no console, so an error from `eframe::run_native` (no usable +//! graphics adapter, a surface or device the driver refuses) went to a standard error nobody sees +//! and the app quit without a word (#261). Now it is logged and shown in a message box. + +/// Where a report goes. +const ISSUES: &str = "https://github.com/storytold/figcraft/issues"; + +/// The text shown when the window couldn't open with `error`. `backend_set`: `WGPU_BACKEND` named +/// the graphics API, so the hint is to unset it rather than to try another one. +pub fn message(error: &str, backend_set: bool) -> String { + let hint = if backend_set { + "WGPU_BACKEND is set and names the graphics API to use; unsetting it lets FigCraft choose." + } else if cfg!(windows) { + // Direct3D 12 and OpenGL are both offered (`graphics.rs`), but wgpu keeps the Direct3D 12 + // adapter it picked even when its device then fails, so naming OpenGL alone can still help. + "Updating the graphics driver often helps. To use OpenGL only, start FigCraft from a Command Prompt with:\n\nset WGPU_BACKEND=gl\nfigcraft.exe" + } else { + "Updating the graphics driver often helps. WGPU_BACKEND (vulkan, gl, metal) names another graphics API to try." + }; + format!("FigCraft couldn't open its window: {error}\n\n{hint}\n\nIf it keeps happening, please report it at {ISSUES} with this message.") +} + +/// Log the failure and, unless `quiet` (started for an agent with `--control`: a modal box would +/// keep the caller waiting, and it reads standard error), show it in a message box. +pub fn failed(error: &eframe::Error, quiet: bool) { + let text = message(&error.to_string(), std::env::var_os("WGPU_BACKEND").is_some()); + // Standard error even when RUST_LOG turned errors off. + if log::log_enabled!(log::Level::Error) { + log::error!("{text}"); + } else { + eprintln!("figcraft: {text}"); + } + if quiet { + return; + } + let _ = rfd::MessageDialog::new() + .set_level(rfd::MessageLevel::Error) + .set_title("FigCraft") + .set_description(text) + .set_buttons(rfd::MessageButtons::Ok) + .show(); +} diff --git a/apps/figcraft/src/startup_tests.rs b/apps/figcraft/src/startup_tests.rs new file mode 100644 index 00000000..6818ae77 --- /dev/null +++ b/apps/figcraft/src/startup_tests.rs @@ -0,0 +1,35 @@ +//! The message shown when the window can't open: it carries the error, a next step and where to +//! report it, instead of the app quitting silently (#261). + +use crate::startup::message; + +const ERROR: &str = "WGPU error: Failed to create surface for any enabled backend: {}"; + +#[test] +fn the_message_carries_the_error_and_where_to_report_it() { + let text = message(ERROR, false); + assert!(text.contains(ERROR), "the error itself: {text}"); + assert!(text.contains("https://github.com/storytold/figcraft/issues"), "where to report it: {text}"); +} + +#[test] +fn without_wgpu_backend_it_suggests_the_driver_and_another_graphics_api() { + let text = message(ERROR, false); + assert!(text.contains("graphics driver"), "{text}"); + assert!(text.contains("WGPU_BACKEND"), "another graphics API to try: {text}"); + assert!(!text.contains("unsetting"), "{text}"); +} + +#[cfg(windows)] +#[test] +fn on_windows_it_shows_how_to_start_with_opengl() { + let text = message(ERROR, false); + assert!(text.contains("set WGPU_BACKEND=gl"), "a release build has no console to look this up from: {text}"); +} + +#[test] +fn with_wgpu_backend_set_it_suggests_unsetting_it() { + let text = message(ERROR, true); + assert!(text.contains("unsetting"), "{text}"); + assert!(!text.contains("graphics driver"), "the chosen backend is the likelier cause: {text}"); +} From 916ee3276c931000fe2b956a8e499bd2a8775b45 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 15 Oct 2026 19:36:00 +0700 Subject: [PATCH 6/6] #306: say why the window can't open in the interface language The message now comes from the UI crate (dialogs::window_failed) through tr() and trf(), with entries in every catalog, and the app picks the language from the preferences before the event loop starts, so the box reads in it even though no frame was ever drawn. The commands to type stay as written. --- apps/figcraft/src/main.rs | 3 +++ apps/figcraft/src/startup.rs | 21 ++---------------- apps/figcraft/src/startup_tests.rs | 2 +- crates/ui-egui/locales/de.toml | 5 +++++ crates/ui-egui/locales/en.toml | 5 +++++ crates/ui-egui/locales/es.toml | 5 +++++ crates/ui-egui/locales/fr.toml | 5 +++++ crates/ui-egui/locales/ja.toml | 5 +++++ crates/ui-egui/locales/ko.toml | 5 +++++ crates/ui-egui/locales/pt-BR.toml | 5 +++++ crates/ui-egui/locales/zh-Hans.toml | 5 +++++ crates/ui-egui/src/dialogs.rs | 33 +++++++++++++++++++++++++++++ 12 files changed, 79 insertions(+), 20 deletions(-) diff --git a/apps/figcraft/src/main.rs b/apps/figcraft/src/main.rs index 1babfd5b..5debb538 100644 --- a/apps/figcraft/src/main.rs +++ b/apps/figcraft/src/main.rs @@ -169,6 +169,9 @@ fn main() -> eframe::Result { if session.docs.is_empty() && !first_run { let _ = session.execute("file.new", &json!({})); } + // The interface language from the first frame on, and for the message when the window can't + // open (no frame then). + figcraft_ui_egui::i18n::set(&session.prefs.language, figcraft_ui_egui::Services::system_language(&svc).as_deref()); let mut fig = FigApp::new(session, Box::new(svc)); fig.ui.home = false; fig.note_recovered(recovered.copies); diff --git a/apps/figcraft/src/startup.rs b/apps/figcraft/src/startup.rs index 8a50d7a5..a25821f3 100644 --- a/apps/figcraft/src/startup.rs +++ b/apps/figcraft/src/startup.rs @@ -4,28 +4,11 @@ //! graphics adapter, a surface or device the driver refuses) went to a standard error nobody sees //! and the app quit without a word (#261). Now it is logged and shown in a message box. -/// Where a report goes. -const ISSUES: &str = "https://github.com/storytold/figcraft/issues"; - -/// The text shown when the window couldn't open with `error`. `backend_set`: `WGPU_BACKEND` named -/// the graphics API, so the hint is to unset it rather than to try another one. -pub fn message(error: &str, backend_set: bool) -> String { - let hint = if backend_set { - "WGPU_BACKEND is set and names the graphics API to use; unsetting it lets FigCraft choose." - } else if cfg!(windows) { - // Direct3D 12 and OpenGL are both offered (`graphics.rs`), but wgpu keeps the Direct3D 12 - // adapter it picked even when its device then fails, so naming OpenGL alone can still help. - "Updating the graphics driver often helps. To use OpenGL only, start FigCraft from a Command Prompt with:\n\nset WGPU_BACKEND=gl\nfigcraft.exe" - } else { - "Updating the graphics driver often helps. WGPU_BACKEND (vulkan, gl, metal) names another graphics API to try." - }; - format!("FigCraft couldn't open its window: {error}\n\n{hint}\n\nIf it keeps happening, please report it at {ISSUES} with this message.") -} - /// Log the failure and, unless `quiet` (started for an agent with `--control`: a modal box would /// keep the caller waiting, and it reads standard error), show it in a message box. pub fn failed(error: &eframe::Error, quiet: bool) { - let text = message(&error.to_string(), std::env::var_os("WGPU_BACKEND").is_some()); + // In the interface language: the text and its catalog entries are the UI crate's. + let text = figcraft_ui_egui::dialogs::window_failed(&error.to_string(), std::env::var_os("WGPU_BACKEND").is_some()); // Standard error even when RUST_LOG turned errors off. if log::log_enabled!(log::Level::Error) { log::error!("{text}"); diff --git a/apps/figcraft/src/startup_tests.rs b/apps/figcraft/src/startup_tests.rs index 6818ae77..0c92bd19 100644 --- a/apps/figcraft/src/startup_tests.rs +++ b/apps/figcraft/src/startup_tests.rs @@ -1,7 +1,7 @@ //! The message shown when the window can't open: it carries the error, a next step and where to //! report it, instead of the app quitting silently (#261). -use crate::startup::message; +use figcraft_ui_egui::dialogs::window_failed as message; const ERROR: &str = "WGPU error: Failed to create surface for any enabled backend: {}"; diff --git a/crates/ui-egui/locales/de.toml b/crates/ui-egui/locales/de.toml index affda97d..5987ec70 100644 --- a/crates/ui-egui/locales/de.toml +++ b/crates/ui-egui/locales/de.toml @@ -457,6 +457,7 @@ status = "draft — needs native review" "Fade" = "Verblassen" "False" = "Falsch" "Fetching from the server…" = "Wird vom Server abgerufen…" +"FigCraft couldn't open its window: {error}" = "FigCraft konnte sein Fenster nicht öffnen: {error}" "File" = "Datei" "File name" = "Dateiname" "File published" = "Datei veröffentlicht" @@ -568,6 +569,7 @@ status = "draft — needs native review" "Hue" = "Farbton" "Hug" = "Umschließen" "Hug contents" = "Inhalt umschließen" +"If it keeps happening, please report it at {link} with this message." = "Wenn es weiterhin passiert, melden Sie es bitte mit dieser Meldung unter {link}." "If" = "Wenn" "If {condition}" = "Wenn {condition}" "Ignore auto layout (absolute position)" = "Auto-Layout ignorieren (absolute Position)" @@ -1323,6 +1325,8 @@ status = "draft — needs native review" "Update plugin" = "Plugin aktualisieren" "Updated {components} and {styles}" = "{components} und {styles} aktualisiert" "Updated {name}" = "{name} aktualisiert" +"Updating the graphics driver often helps. To use OpenGL only, start FigCraft from a Command Prompt with:" = "Oft hilft es, den Grafiktreiber zu aktualisieren. Um nur OpenGL zu verwenden, starten Sie FigCraft in der Eingabeaufforderung mit:" +"Updating the graphics driver often helps. WGPU_BACKEND (vulkan, gl, metal) names another graphics API to try." = "Oft hilft es, den Grafiktreiber zu aktualisieren. Mit WGPU_BACKEND (vulkan, gl, metal) lässt sich eine andere Grafik-API ausprobieren." "Uploads this file to a FigCraft server and keeps this tab in sync with it. You get a link to edit and a link to view." = "Lädt diese Datei auf einen FigCraft-Server hoch und hält diesen Tab mit ihm synchron. Sie erhalten einen Link zum Bearbeiten und einen zum Ansehen." "Uppercase" = "Großbuchstaben" "Use a fixed value" = "Festen Wert verwenden" @@ -1364,6 +1368,7 @@ status = "draft — needs native review" "Visibility" = "Sichtbarkeit" "Visible" = "Sichtbar" "Vivid" = "Lebhaft" +"WGPU_BACKEND is set and names the graphics API to use; unsetting it lets FigCraft choose." = "WGPU_BACKEND ist gesetzt und legt die Grafik-API fest; ohne diese Variable wählt FigCraft selbst." "Warm" = "Warm" "Watch" = "Smartwatch" "Wavy" = "Gewellt" diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 08ac64ba..21df8bfe 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -475,6 +475,7 @@ name = "English" "False" = "False" "Feb" = "Feb" "Fetching from the server…" = "Fetching from the server…" +"FigCraft couldn't open its window: {error}" = "FigCraft couldn't open its window: {error}" "File" = "File" "File name" = "File name" "File not found" = "File not found" @@ -594,6 +595,7 @@ name = "English" "Hug contents" = "Hug contents" "Icon components on a 24 px grid with keylines and a size preview" = "Icon components on a 24 px grid with keylines and a size preview" "Icon set starter" = "Icon set starter" +"If it keeps happening, please report it at {link} with this message." = "If it keeps happening, please report it at {link} with this message." "If" = "If" "If {condition}" = "If {condition}" "Ignore auto layout (absolute position)" = "Ignore auto layout (absolute position)" @@ -1389,6 +1391,8 @@ name = "English" "Update from selection" = "Update from selection" "Updated {components} and {styles}" = "Updated {components} and {styles}" "Updated {name}" = "Updated {name}" +"Updating the graphics driver often helps. To use OpenGL only, start FigCraft from a Command Prompt with:" = "Updating the graphics driver often helps. To use OpenGL only, start FigCraft from a Command Prompt with:" +"Updating the graphics driver often helps. WGPU_BACKEND (vulkan, gl, metal) names another graphics API to try." = "Updating the graphics driver often helps. WGPU_BACKEND (vulkan, gl, metal) names another graphics API to try." "Uploads this file to a FigCraft server and keeps this tab in sync with it. You get a link to edit and a link to view." = "Uploads this file to a FigCraft server and keeps this tab in sync with it. You get a link to edit and a link to view." "Uppercase" = "Uppercase" "Use a fixed value" = "Use a fixed value" @@ -1431,6 +1435,7 @@ name = "English" "Visibility" = "Visibility" "Visible" = "Visible" "Vivid" = "Vivid" +"WGPU_BACKEND is set and names the graphics API to use; unsetting it lets FigCraft choose." = "WGPU_BACKEND is set and names the graphics API to use; unsetting it lets FigCraft choose." "Warm" = "Warm" "Watch" = "Watch" "Wavy" = "Wavy" diff --git a/crates/ui-egui/locales/es.toml b/crates/ui-egui/locales/es.toml index 3200e891..af5c6a15 100644 --- a/crates/ui-egui/locales/es.toml +++ b/crates/ui-egui/locales/es.toml @@ -476,6 +476,7 @@ status = "draft — needs native review" "False" = "Falso" "Feb" = "feb" "Fetching from the server…" = "Obteniendo del servidor…" +"FigCraft couldn't open its window: {error}" = "FigCraft no pudo abrir su ventana: {error}" "File" = "Archivo" "File name" = "Nombre del archivo" "File not found" = "No se encuentra el archivo" @@ -595,6 +596,7 @@ status = "draft — needs native review" "Hug contents" = "Ajustar al contenido" "Icon components on a 24 px grid with keylines and a size preview" = "Componentes de icono en una cuadrícula de 24 px con líneas guía y una vista de tamaños" "Icon set starter" = "Base de conjunto de iconos" +"If it keeps happening, please report it at {link} with this message." = "Si sigue pasando, infórmalo en {link} con este mensaje." "If" = "Si" "If {condition}" = "Si {condition}" "Ignore auto layout (absolute position)" = "Ignorar diseño automático (posición absoluta)" @@ -1390,6 +1392,8 @@ status = "draft — needs native review" "Update from selection" = "Actualizar desde la selección" "Updated {components} and {styles}" = "Actualizados {components} y {styles}" "Updated {name}" = "{name} actualizado" +"Updating the graphics driver often helps. To use OpenGL only, start FigCraft from a Command Prompt with:" = "Actualizar el controlador gráfico suele ayudar. Para usar solo OpenGL, inicia FigCraft desde el Símbolo del sistema con:" +"Updating the graphics driver often helps. WGPU_BACKEND (vulkan, gl, metal) names another graphics API to try." = "Actualizar el controlador gráfico suele ayudar. WGPU_BACKEND (vulkan, gl, metal) indica otra API gráfica que probar." "Uploads this file to a FigCraft server and keeps this tab in sync with it. You get a link to edit and a link to view." = "Sube este archivo a un servidor FigCraft y mantiene esta pestaña sincronizada con él. Obtienes un enlace para editar y otro para ver." "Uppercase" = "Mayúsculas" "Use a fixed value" = "Usar un valor fijo" @@ -1432,6 +1436,7 @@ status = "draft — needs native review" "Visibility" = "Visibilidad" "Visible" = "Visible" "Vivid" = "Vívido" +"WGPU_BACKEND is set and names the graphics API to use; unsetting it lets FigCraft choose." = "WGPU_BACKEND está definida e indica la API gráfica que se usa; si la quitas, FigCraft elige por sí mismo." "Warm" = "Cálido" "Watch" = "Reloj" "Wavy" = "Ondulado" diff --git a/crates/ui-egui/locales/fr.toml b/crates/ui-egui/locales/fr.toml index 69798340..1f5544c2 100644 --- a/crates/ui-egui/locales/fr.toml +++ b/crates/ui-egui/locales/fr.toml @@ -457,6 +457,7 @@ status = "draft — needs native review" "Fade" = "Fondu" "False" = "Faux" "Fetching from the server…" = "Récupération depuis le serveur…" +"FigCraft couldn't open its window: {error}" = "FigCraft n’a pas pu ouvrir sa fenêtre : {error}" "File" = "Fichier" "File name" = "Nom du fichier" "File published" = "Fichier publié" @@ -568,6 +569,7 @@ status = "draft — needs native review" "Hue" = "Teinte" "Hug" = "Ajuster" "Hug contents" = "Ajuster au contenu" +"If it keeps happening, please report it at {link} with this message." = "Si cela se reproduit, signalez-le sur {link} avec ce message." "If" = "Si" "If {condition}" = "Si {condition}" "Ignore auto layout (absolute position)" = "Ignorer la mise en page auto (position absolue)" @@ -1323,6 +1325,8 @@ status = "draft — needs native review" "Update plugin" = "Mettre à jour le plugin" "Updated {components} and {styles}" = "{components} et {styles} mis à jour" "Updated {name}" = "{name} mis à jour" +"Updating the graphics driver often helps. To use OpenGL only, start FigCraft from a Command Prompt with:" = "Mettre à jour le pilote graphique aide souvent. Pour n’utiliser qu’OpenGL, lancez FigCraft depuis l’invite de commandes avec :" +"Updating the graphics driver often helps. WGPU_BACKEND (vulkan, gl, metal) names another graphics API to try." = "Mettre à jour le pilote graphique aide souvent. WGPU_BACKEND (vulkan, gl, metal) désigne une autre API graphique à essayer." "Uploads this file to a FigCraft server and keeps this tab in sync with it. You get a link to edit and a link to view." = "Envoie ce fichier sur un serveur FigCraft et garde cet onglet synchronisé avec lui. Vous obtenez un lien de modification et un lien de consultation." "Uppercase" = "Majuscules" "Use a fixed value" = "Utiliser une valeur fixe" @@ -1364,6 +1368,7 @@ status = "draft — needs native review" "Visibility" = "Visibilité" "Visible" = "Visible" "Vivid" = "Vif" +"WGPU_BACKEND is set and names the graphics API to use; unsetting it lets FigCraft choose." = "WGPU_BACKEND est définie et impose l’API graphique ; sans elle, FigCraft choisit lui-même." "Warm" = "Chaud" "Watch" = "Montre" "Wavy" = "Ondulé" diff --git a/crates/ui-egui/locales/ja.toml b/crates/ui-egui/locales/ja.toml index fb81b042..9174a65a 100644 --- a/crates/ui-egui/locales/ja.toml +++ b/crates/ui-egui/locales/ja.toml @@ -478,6 +478,7 @@ status = "draft — needs native review" "False" = "false" "Feb" = "2月" "Fetching from the server…" = "サーバーから取得中…" +"FigCraft couldn't open its window: {error}" = "FigCraft のウィンドウを開けなかった:{error}" "File" = "ファイル" "File name" = "ファイル名" "File not found" = "ファイルが見つからない" @@ -597,6 +598,7 @@ status = "draft — needs native review" "Hug contents" = "内容に合わせる" "Icon components on a 24 px grid with keylines and a size preview" = "24 px グリッドのアイコンコンポーネント、キーライン、サイズのプレビュー" "Icon set starter" = "アイコンセットの雛形" +"If it keeps happening, please report it at {link} with this message." = "繰り返し起きる場合は、このメッセージを添えて {link} に報告。" "If" = "条件" "If {condition}" = "条件:{condition}" "Ignore auto layout (absolute position)" = "オートレイアウトを無視(絶対位置)" @@ -1392,6 +1394,8 @@ status = "draft — needs native review" "Update plugin" = "プラグインを更新" "Updated {components} and {styles}" = "{components}と{styles}を更新済み" "Updated {name}" = "{name} を更新済み" +"Updating the graphics driver often helps. To use OpenGL only, start FigCraft from a Command Prompt with:" = "グラフィックスドライバーの更新で解決することが多い。OpenGL だけを使うには、コマンドプロンプトから次のように FigCraft を起動:" +"Updating the graphics driver often helps. WGPU_BACKEND (vulkan, gl, metal) names another graphics API to try." = "グラフィックスドライバーの更新で解決することが多い。WGPU_BACKEND(vulkan、gl、metal)で別のグラフィックス API を試せる。" "Uploads this file to a FigCraft server and keeps this tab in sync with it. You get a link to edit and a link to view." = "このファイルを FigCraft サーバーにアップロードし、このタブを同期した状態に保つ。編集用リンクと閲覧用リンクが発行される。" "Uppercase" = "大文字" "Use a fixed value" = "固定値を使用" @@ -1434,6 +1438,7 @@ status = "draft — needs native review" "Visibility" = "表示" "Visible" = "表示" "Vivid" = "ビビッド" +"WGPU_BACKEND is set and names the graphics API to use; unsetting it lets FigCraft choose." = "WGPU_BACKEND が設定されていて、使うグラフィックス API を指定している。解除すると FigCraft が選ぶ。" "Warm" = "ウォーム" "Watch" = "ウォッチ" "Wavy" = "波線" diff --git a/crates/ui-egui/locales/ko.toml b/crates/ui-egui/locales/ko.toml index aed3529a..e672efe7 100644 --- a/crates/ui-egui/locales/ko.toml +++ b/crates/ui-egui/locales/ko.toml @@ -458,6 +458,7 @@ status = "draft — needs native review" "Fade" = "페이드" "False" = "거짓" "Fetching from the server…" = "서버에서 가져오는 중…" +"FigCraft couldn't open its window: {error}" = "FigCraft 창을 열 수 없음: {error}" "File" = "파일" "File name" = "파일 이름" "File published" = "파일 게시됨" @@ -569,6 +570,7 @@ status = "draft — needs native review" "Hue" = "색조" "Hug" = "맞춤" "Hug contents" = "내용에 맞춤" +"If it keeps happening, please report it at {link} with this message." = "계속 발생하면 이 메시지와 함께 {link}에 알려 주세요." "If" = "조건" "If {condition}" = "조건: {condition}" "Ignore auto layout (absolute position)" = "자동 레이아웃 무시(절대 위치)" @@ -1324,6 +1326,8 @@ status = "draft — needs native review" "Update plugin" = "플러그인 업데이트" "Updated {components} and {styles}" = "{components} 및 {styles} 업데이트됨" "Updated {name}" = "{name} 업데이트됨" +"Updating the graphics driver often helps. To use OpenGL only, start FigCraft from a Command Prompt with:" = "그래픽 드라이버를 업데이트하면 해결되는 경우가 많습니다. OpenGL만 사용하려면 명령 프롬프트에서 다음과 같이 FigCraft를 시작하세요:" +"Updating the graphics driver often helps. WGPU_BACKEND (vulkan, gl, metal) names another graphics API to try." = "그래픽 드라이버를 업데이트하면 해결되는 경우가 많습니다. WGPU_BACKEND(vulkan, gl, metal)로 다른 그래픽 API를 시도할 수 있습니다." "Uploads this file to a FigCraft server and keeps this tab in sync with it. You get a link to edit and a link to view." = "이 파일을 FigCraft 서버에 업로드하고 이 탭을 동기화된 상태로 유지함. 편집 링크와 보기 링크가 생성됨." "Uppercase" = "대문자" "Use a fixed value" = "고정 값 사용" @@ -1365,6 +1369,7 @@ status = "draft — needs native review" "Visibility" = "표시 여부" "Visible" = "표시됨" "Vivid" = "선명하게" +"WGPU_BACKEND is set and names the graphics API to use; unsetting it lets FigCraft choose." = "WGPU_BACKEND가 설정되어 사용할 그래픽 API를 지정하고 있습니다. 설정을 해제하면 FigCraft가 선택합니다." "Warm" = "따뜻하게" "Watch" = "시계" "Wavy" = "물결선" diff --git a/crates/ui-egui/locales/pt-BR.toml b/crates/ui-egui/locales/pt-BR.toml index 97500236..f49beb30 100644 --- a/crates/ui-egui/locales/pt-BR.toml +++ b/crates/ui-egui/locales/pt-BR.toml @@ -456,6 +456,7 @@ status = "draft — needs native review" "Fade" = "Esmaecer" "False" = "Falso" "Fetching from the server…" = "Buscando no servidor…" +"FigCraft couldn't open its window: {error}" = "O FigCraft não conseguiu abrir a janela: {error}" "File" = "Arquivo" "File name" = "Nome do arquivo" "File published" = "Arquivo publicado" @@ -567,6 +568,7 @@ status = "draft — needs native review" "Hue" = "Matiz" "Hug" = "Ajustar" "Hug contents" = "Ajustar ao conteúdo" +"If it keeps happening, please report it at {link} with this message." = "Se continuar acontecendo, informe em {link} com esta mensagem." "If" = "Se" "If {condition}" = "Se {condition}" "Ignore auto layout (absolute position)" = "Ignorar layout automático (posição absoluta)" @@ -1322,6 +1324,8 @@ status = "draft — needs native review" "Update plugin" = "Atualizar plugin" "Updated {components} and {styles}" = "{components} e {styles} atualizados" "Updated {name}" = "{name} atualizado" +"Updating the graphics driver often helps. To use OpenGL only, start FigCraft from a Command Prompt with:" = "Atualizar o driver de vídeo costuma ajudar. Para usar só o OpenGL, abra o FigCraft pelo Prompt de Comando com:" +"Updating the graphics driver often helps. WGPU_BACKEND (vulkan, gl, metal) names another graphics API to try." = "Atualizar o driver de vídeo costuma ajudar. WGPU_BACKEND (vulkan, gl, metal) indica outra API gráfica para tentar." "Uploads this file to a FigCraft server and keeps this tab in sync with it. You get a link to edit and a link to view." = "Envia este arquivo para um servidor FigCraft e mantém esta aba sincronizada com ele. Você recebe um link para editar e outro para visualizar." "Uppercase" = "Maiúsculas" "Use a fixed value" = "Usar um valor fixo" @@ -1363,6 +1367,7 @@ status = "draft — needs native review" "Visibility" = "Visibilidade" "Visible" = "Visível" "Vivid" = "Vívido" +"WGPU_BACKEND is set and names the graphics API to use; unsetting it lets FigCraft choose." = "WGPU_BACKEND está definida e indica a API gráfica a usar; sem ela, o FigCraft escolhe sozinho." "Warm" = "Quente" "Watch" = "Relógio" "Wavy" = "Ondulado" diff --git a/crates/ui-egui/locales/zh-Hans.toml b/crates/ui-egui/locales/zh-Hans.toml index d1887735..70a05c5f 100644 --- a/crates/ui-egui/locales/zh-Hans.toml +++ b/crates/ui-egui/locales/zh-Hans.toml @@ -459,6 +459,7 @@ status = "draft — needs native review" "Fade" = "褪色" "False" = "假" "Fetching from the server…" = "正在从服务器获取…" +"FigCraft couldn't open its window: {error}" = "FigCraft 无法打开窗口:{error}" "File" = "文件" "File name" = "文件名" "File published" = "文件已发布" @@ -570,6 +571,7 @@ status = "draft — needs native review" "Hue" = "色相" "Hug" = "适应" "Hug contents" = "适应内容" +"If it keeps happening, please report it at {link} with this message." = "如果问题持续出现,请附上此消息到 {link} 报告。" "If" = "如果" "If {condition}" = "如果 {condition}" "Ignore auto layout (absolute position)" = "忽略自动布局(绝对定位)" @@ -1325,6 +1327,8 @@ status = "draft — needs native review" "Update plugin" = "更新插件" "Updated {components} and {styles}" = "已更新 {components} 和 {styles}" "Updated {name}" = "已更新 {name}" +"Updating the graphics driver often helps. To use OpenGL only, start FigCraft from a Command Prompt with:" = "更新显卡驱动通常会有帮助。若只想使用 OpenGL,请在命令提示符中这样启动 FigCraft:" +"Updating the graphics driver often helps. WGPU_BACKEND (vulkan, gl, metal) names another graphics API to try." = "更新显卡驱动通常会有帮助。可用 WGPU_BACKEND(vulkan、gl、metal)指定另一个图形 API 来尝试。" "Uploads this file to a FigCraft server and keeps this tab in sync with it. You get a link to edit and a link to view." = "将此文件上传到 FigCraft 服务器,并使此标签页与之保持同步。你会获得一个编辑链接和一个查看链接。" "Uppercase" = "大写" "Use a fixed value" = "使用固定值" @@ -1366,6 +1370,7 @@ status = "draft — needs native review" "Visibility" = "可见性" "Visible" = "可见" "Vivid" = "鲜艳" +"WGPU_BACKEND is set and names the graphics API to use; unsetting it lets FigCraft choose." = "已设置 WGPU_BACKEND,它指定了要使用的图形 API;取消设置后由 FigCraft 自行选择。" "Warm" = "暖调" "Watch" = "手表" "Wavy" = "波浪线" diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 221ee636..5f51a610 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -15,6 +15,39 @@ use crate::theme::{ACCENT, Tokens, regular, semibold}; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); +/// Where a report goes. +const ISSUES: &str = "https://github.com/storytold/figcraft/issues"; + +/// What the desktop app says when its window couldn't open with `error` (no frame was drawn: the +/// language is the one [`i18n::set`] picked from the preferences). `backend_set`: `WGPU_BACKEND` +/// named the graphics API, so the hint is to unset it rather than to try another one. +pub fn window_failed(error: &str, backend_set: bool) -> String { + let hint = if backend_set { + tr("WGPU_BACKEND is set and names the graphics API to use; unsetting it lets FigCraft choose.").to_string() + } else if cfg!(windows) { + // Direct3D 12 and OpenGL are both offered, but wgpu keeps the Direct3D 12 adapter it picked + // even when its device then fails, so naming OpenGL alone can still help. + format!( + "{} + +set WGPU_BACKEND=gl +figcraft.exe", + tr("Updating the graphics driver often helps. To use OpenGL only, start FigCraft from a Command Prompt with:") + ) + } else { + tr("Updating the graphics driver often helps. WGPU_BACKEND (vulkan, gl, metal) names another graphics API to try.").to_string() + }; + format!( + "{} + +{hint} + +{}", + trf("FigCraft couldn't open its window: {error}", &[("error", &error)]), + trf("If it keeps happening, please report it at {link} with this message.", &[("link", &ISSUES)]) + ) +} + /// A dialog window, centred. pub(crate) fn window<'a>(title: &'a str, ctx: &Context) -> egui::Window<'a> { floating(title, ctx).anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0))