DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge upstream main 736acff into next
aionggaadd54a92685
diff --cc ROADMAP.mdindex 18d3bfb99,eb05508d1..a25e7fdf9--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -24,10 -5,7 +24,10 @@@- AR1.1: Kashida justification tests verify space fallback without Tatweel fonts using an isolated font database, while retaining elongation assertions when fonts support it.- AR1: Arabic IDML controls now retain character direction, kashida switches, diacritic offsets/forms, paragraph policy values and independent story/table directions. Shaping preserves joining context and script/language selection; paragraph-level bidi, contextual digit conversion, mark-safe elongation, RTL columns/tables and physical column insertion have regression coverage. Vendor-specific justification and diacritic presets remain explicit preflight warnings; see docs/arabic-typography.md.+- FONT3: opening documents with unavailable font families or styles automatically offers Find/Replace Font. The dialog supports repeated replacements, refreshed inventory and visible validation errors; native builds without craft-fonts use system CJK fonts for readable names.+- FONT2: font replacements validate available targets and resolve inherited formatting in nested text and empty paragraphs, with undo and composite component preservation.+- FONT1: composite-font references resolve by resource identity, retain literal display names, and export as object references. Font inventory and preflight share the character-selected component fonts, including nested notes and cells.- - CJK1: IDML composite fonts now retain character mappings and metrics; explicit aki, tsume, jidori, em alignment/leading, named/custom kinsoku boundaries, hanging punctuation, tate-chu-yoko offsets and kenten symbols flow through composition and IDML export. Automatic kerning no longer imports inactive numeric values as enormous manual spacing. Composite definitions are editable through commands with undo/cache invalidation. Mojikumi definitions are retained and unsupported spacing-table / push-in-push-out policies are reported by preflight. Full InDesign CJK composition parity, frame-grid layout and detailed ruby/warichu remain unfinished.+ - CJK1: IDML composite fonts now retain character mappings and metrics; explicit aki, tsume, jidori, em alignment/leading, named/custom kinsoku boundaries, hanging punctuation, tate-chu-yoko offsets and kenten symbols flow through composition and IDML export. Automatic kerning no longer imports inactive numeric values as enormous manual spacing. Composite definitions are editable through commands with undo/cache invalidation. Mojikumi definitions are retained and unsupported spacing-table / push-in-push-out policies are reported by preflight. Full InDesign CJK composition parity, frame-grid layout and detailed ruby remain unfinished. Warichu sets the selected run in smaller lines inside the line after the line is broken.DesignCraft aims at full Adobe InDesign parity — and to be better: faster, open (documented JSON format + IDML), scriptable by agents (MCP), and available on the web.@@@ -61,9 -37,9 +61,10 @@@- Missing glyphs, as in InDesign: a character the applied font lacks is drawn as that font's missing-glyph box (its .notdef; a drawn box when the font's is empty), on screen and in PDF (as a path, so PDF/A and PDF/UA exports take it), and Preflight lists the characters by font. Preferences › Composition › Draw Missing Glyphs from Fallback Fonts (`document.preferences {glyphFallback}`, stored with the document) draws them from other fonts instead; it is off in new documents and IDML imports, on in documents saved before it existed. A missing font's substitute always uses fallback fonts.- Damage-region repaint: after an edit the canvas re-renders only the frames whose composed text (or the items that) changed and patches its texture — pixel-identical to a full render; typing in a frame repaints in under a millisecond instead of a full-viewport render (22 ms measured on the sample).- Crash recovery: unsaved documents are written to the recovery folder every 30 s and reopened (unsaved, remembering their files) after a crash; File › Revert and Save a Copy…; `file.recovery.*`, `file.revert`, `file.saveACopy`.+ - Graphics backend chosen before the window exists (DirectX 12 on Windows, Vulkan on Linux, Metal on macOS, OpenGL as the fallback; `WGPU_BACKEND` overrides) with a start-up fallback: a backend whose start never showed a frame is skipped at the next start and the status bar says so (`gpu.json`). Found on an AMD hybrid-graphics laptop whose Vulkan driver faulted at the first present.- Edit › Paste Into (copied objects become a frame's content, clipped by it; rendered, PDF and IDML both ways — verified in InDesign 2026); Polygon Settings (sides, star inset; double-click the Polygon tool).- Color panel (fill/stroke proxy, CMYK/RGB/Lab sliders with channel ramps, tint slider for swatches, spectrum ramp, Add to Swatches) and Color Picker (double-click the proxy); mixed colours are unnamed (not listed in Swatches until added); `object.color`, `swatch.addToSwatches`, `swatch.addUnnamed`.+- Threading: click a selected text frame's in or out port (overset or not) to load the text cursor, then click a frame to thread it (stories merge), click empty space for a column-wide frame down to the bottom margin, or drag a frame; Shift-click autoflows, Alt-click stays loaded; click the linked frame or double-click a port to break the thread; Esc unloads. Link and unthread cursors show where a click threads or unthreads. `text.thread`, `text.unthread`, `text.removeFromThread`.- Place text files: Word (.docx: styles by name with their attributes, bold/italic/underline/size/font, footnotes, tables, tabs, breaks), RTF and plain text, into the insertion point, the selected frame or a new frame; autoflow adds pages and threaded frames until the text fits; Remove Styles option (`designcraft-textimport`).- Gradient Feather (⇧G tool, `object.gradientFeather`): objects fade along a linear or radial opacity gradient, on screen and as a soft mask in PDF.- Script Label (`object.label`, `object.findByLabel`), alt text (`object.altText`), Isolate Blending / Knockout Group (`object.transparencyGroup`; on screen, PDF isolates), Table ▸ Sort (`table.sortRows`, numeric-aware, header/footer fixed).diff --cc crates/compose/src/lib.rsindex 8571e5bd6,09e295250..e7f1fe206--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -827,25 -762,12 +839,27 @@@ fn compose_with_db(doc: &Document, stor// the next column.let spanning = matches!(pp.span_columns, SpanColumns::Span(n) if n != 1);span_paras[pi] = spanning;- let next_column = |cur: &mut Cursor| if spanning { cur.next_frame() } else { cur.next_column(&cols) };+ // Consecutive paragraphs with the same Split Columns settings share a split block; within+ // it, a paragraph moves on to the next sub-column.+ let split_cfg = SplitCfg::of(&pp);+ split_paras[pi] = split_cfg.is_some();+ if cur.split.is_some_and(|s| Some(s.cfg) != split_cfg) {+ cur.split = None;+ }+ let next_column = |cur: &mut Cursor| {+ if spanning {+ cur.next_frame()+ } else if cur.can_next_sub() {+ cur.next_sub()+ } else {+ cur.next_column(&cols)+ }+ };+ // A paragraph start or a break character; Next Column while a paragraph spans columns is+ // the next frame, as above.- let begin_at = |cur: &mut Cursor, start: StartParagraph| match start {+ let go = |cur: &mut Cursor, start| match start {StartParagraph::NextColumn => next_column(cur),- other => cur.start(other, &cols, frames, doc),+ start => cur.start(start, &cols, frames, doc),};// Paragraph start options.if let Some(start) = after_break@@@ -1132,27 -978,8 +1146,30 @@@let forced_mid = brk == Some(story::FORCED_LINE_BREAK) && !last;let (mut placed, end_x, ratio) =layout_line(&glyphs, s, e, b.hyphen, lx0, lx1, col.x0, &pp, &spacing, ends_para, forced_mid, f.left_page, &bidi_info);- // Warichu runs before ruby so a reading is placed over the stacked note.++ // Warichu runs before ruby so a reading is placed over the stacked note, and before++ // the trimmed spaces and the drop cap join the line, so neither is stacked.+ let end_x = end_x + warichu::place(&styles_tab, &mut placed);+ // The spaces the break trimmed off the end follow the line undrawn, so the caret+ // and the selection reach them; alignment and justification ignore them.+ if pp.direction != designcraft_doc::TextDirection::RightToLeft && !placed.iter().any(|g| g.rtl) {+ let mut x = end_x;+ for g in glyphs.get(e..(g0 + b.next).min(glyphs.len())).unwrap_or(&[]).iter().filter(|g| g.is_space()) {+ placed.push(PlacedGlyph { visible: false, ..place(g, x) });+ x += g.adv;+ }+ }+ let mut drop_box = None;+ if line_no == 0+ && let Some(dc) = &drop_cap+ {+ let at = if rtl { x1 - pp.right_indent - dc.width } else { x0 + pp.left_indent - dc.lsb };+ placed.splice(0..0, place_drop_cap(dc, at, rtl));+ drop_box = Some(DropCapBox {+ end: dc.end,+ baseline: baseline + dc.drop,+ rect: Rect::new(at, baseline - asc, at + dc.width, baseline + dc.drop + desc),+ });+ }ruby::annotate(db, &styles_tab, &mut placed, doc.settings.glyph_fallback);let range_end = if last { prange.end } else { glyphs.get(g0 + b.next).map(|g| g.byte).unwrap_or(prange.end) };let range_start = glyphs.get(s).map(|g| g.byte).unwrap_or(prange.start).min(range_end);@@@ -3207,16 -2585,132 +3224,138 @@@ fn vertical_justify(ft: &mut FrameText// ---------- caret and hit testing (Type tool) ----------+ /// Two stacked glyphs this far apart in `y` sit on different rows (warichu).+ const ROW_Y: f64 = 0.25;++ /// (ascent, descent) of `g` in points, both positive.+ fn glyph_extents(g: &PlacedGlyph) -> (f64, f64) {+ let (asc, desc) = g.face.vertical_metrics();+ let sy = g.sy.abs();+ (asc * sy, desc * sy)+ }++ fn x_span(g: &PlacedGlyph) -> (f64, f64) {+ (g.x.min(g.x + g.adv), g.x.max(g.x + g.adv))+ }++ fn x_ranges_overlap(a: &PlacedGlyph, b: &PlacedGlyph) -> bool {+ let (a0, a1) = x_span(a);+ let (b0, b1) = x_span(b);+ a0 < b1 - 0.2 && b0 < a1 - 0.2+ }++ fn line_glyphs(l: &Line) -> Vec<&PlacedGlyph> {+ l.glyphs.iter().filter(|g| g.len > 0).collect()+ }++ /// `g` shares its x with another glyph on a different baseline (a stacked warichu row).+ fn on_stacked_row(glyphs: &[&PlacedGlyph], g: &PlacedGlyph) -> bool {+ glyphs.iter().any(|o| (o.y - g.y).abs() > ROW_Y && x_ranges_overlap(o, g))+ }++ fn line_has_stacked_rows(l: &Line) -> bool {+ let glyphs = line_glyphs(l);+ glyphs.iter().any(|g| on_stacked_row(&glyphs, g))+ }++ /// The glyph `caret_x` anchors `pos` to, if the caret is not the line end.+ fn caret_anchor(l: &Line, pos: usize) -> Option<&PlacedGlyph> {+ for g in l.glyphs.iter().filter(|g| g.len > 0) {+ if pos >= g.byte && pos < g.byte + g.len {+ return Some(g);+ }+ if g.byte >= pos {+ return Some(g);+ }+ }+ None+ }++ /// Baseline an underline or strikethrough uses. Warichu follows the small line; everything else+ /// stays on the parent baseline (a baseline shift does not move the rule).+ pub fn rule_baseline(style: &RunStyle, line: &Line, g: &PlacedGlyph) -> f64 {+ if style.warichu { line.baseline + g.y } else { line.baseline }+ }++ fn band_quad(x0: f64, x1: f64, top: f64, bot: f64) -> [Point; 4] {+ [Point::new(x0, top), Point::new(x1, top), Point::new(x1, bot), Point::new(x0, bot)]+ }++ /// Highlight rectangles for bytes `s..e` on `l`. `past_end` extends the line-end caret when the+ /// selection continues onto the next line. Stacked rows (warichu) each get their own band.+ pub fn highlight_quads(l: &Line, s: usize, e: usize, past_end: bool) -> Vec<[Point; 4]> {+ let selected: Vec<&PlacedGlyph> = l.glyphs.iter().filter(|g| g.len > 0 && g.byte >= s && g.byte < e).collect();+ let stacked = selected.iter().any(|g| on_stacked_row(&selected, g));+ if stacked {+ let mut items: Vec<(f64, f64, f64, f64, f64)> = selected+ .iter()+ .map(|g| {+ let (asc, desc) = glyph_extents(g);+ let (x0, x1) = x_span(g);+ let y = l.baseline + g.y;+ (g.y, x0, x1, y - asc, y + desc)+ })+ .collect();+ items.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1)));+ let mut quads = Vec::new();+ let mut cur: Option<(f64, f64, f64, f64, f64)> = None;+ for (y, x0, x1, top, bot) in items {+ match cur {+ Some(c) if (c.0 - y).abs() <= ROW_Y && x0 <= c.2 + 0.5 => {+ cur = Some((c.0, c.1, c.2.max(x1), c.3.min(top), c.4.max(bot)));+ }+ Some(c) => {+ quads.push(band_quad(c.1, c.2, c.3, c.4));+ cur = Some((y, x0, x1, top, bot));+ }+ None => cur = Some((y, x0, x1, top, bot)),+ }+ }+ if let Some(c) = cur {+ quads.push(band_quad(c.1, c.2, c.3, c.4));+ }+ if past_end {+ quads.push(band_quad(l.end_x, l.end_x + 3.0, l.baseline - l.ascent, l.baseline + l.descent));+ }+ return quads;+ }+ let top = l.baseline - l.ascent;+ let bot = l.baseline + l.descent;+ if l.glyphs.iter().any(|g| g.rtl) {+ let mut spans: Vec<(f64, f64)> = selected.iter().map(|g| (g.x, g.x + g.adv)).collect();+ spans.sort_by(|a, b| a.0.total_cmp(&b.0));+ let mut merged: Vec<(f64, f64)> = Vec::new();+ for (a, b) in spans {+ match merged.last_mut() {+ Some(m) if a <= m.1 + 0.5 => m.1 = m.1.max(b),+ _ => merged.push((a, b)),+ }+ }+ return merged.into_iter().map(|(a, b)| band_quad(a, b, top, bot)).collect();+ }+ let x0 = caret_x(l, s);+ let x1 = if past_end { l.end_x.max(x0 + 3.0) } else { caret_x(l, e) };+ vec![band_quad(x0, x1, top, bot)]+ }+/// Caret geometry for story byte `pos`: (frame index, x, baseline, ascent, descent).+ /// A stacked warichu row reports that row's baseline and em, not the parent line's.pub fn caret(cs: &ComposedStory, pos: usize) -> Option<(usize, f64, f64, f64, f64)> {let (fi, l) = caret_line(cs, pos)?;+ // In the drop cap the caret is as tall as it.+ if let Some(dc) = l.drop_cap+ && pos < dc.end+ {+ return Some((fi, caret_x(l, pos), dc.baseline, dc.baseline - dc.rect.y0, l.descent));+ }- Some((fi, caret_x(l, pos), l.baseline, l.ascent, l.descent))+ let x = caret_x(l, pos);+ let glyphs = line_glyphs(l);+ let metrics = caret_anchor(l, pos).filter(|g| on_stacked_row(&glyphs, g)).map(|g| {+ let (asc, desc) = glyph_extents(g);+ (l.baseline + g.y, asc, desc)+ });+ let (bl, asc, desc) = metrics.unwrap_or((l.baseline, l.ascent, l.descent));+ Some((fi, x, bl, asc, desc))}/// The line the caret at `pos` is drawn on (and its frame index).diff --cc crates/engine/src/cmd/text.rsindex abf549460,4950d82b9..0611742f0--- a/crates/engine/src/cmd/text.rs+++ b/crates/engine/src/cmd/text.rs@@@ -870,23 -782,43 +888,60 @@@ pub(crate) fn format_targets(s: &Sessiov}+/// Character formatting chosen at a bare caret in text: applied to what is typed there next.+#[derive(Clone, Debug)]+pub(crate) struct TypingFormat {+ doc: u64,+ at: TextSel,+ attrs: CharAttrs,+ /// Overrides removed (`null` in `type.char`).+ cleared: Vec<String>,+}++/// The typing format for the active document's caret, if it was chosen at this caret.+fn typing_format(s: &Session) -> Option<&TypingFormat> {+ let st = s.active()?;+ let t = st.selection.text?;+ s.typing_format.as_ref().filter(|f| f.doc == st.uid && f.at.story == t.story && f.at.cell == t.cell && f.at.range() == t.range())+}++ fn warichu_cmd(s: &mut Session, p: &Value) -> Result<Value> {+ let has_opts = ["lines", "size", "lineSpacing", "align", "charsBeforeBreak", "charsAfterBreak"].iter().any(|k| p.get(k).is_some());+ let on = match p.get("on").and_then(Value::as_bool) {+ Some(v) => v,+ None if has_opts => true,+ None => !format_targets(s).first().is_some_and(|t| {+ s.doc()+ .ok()+ .and_then(|d| d.doc.text_story(t.story, t.cell))+ .is_some_and(|st| st.char_format_at(if t.range.is_empty() { t.range.start } else { t.range.start + 1 }).over.warichu == Some(true))+ }),+ };+ let mut body = serde_json::Map::new();+ body.insert("warichu".into(), json!(on));+ if on {+ if let Some(v) = p.get("lines").and_then(Value::as_u64) {+ body.insert("warichuLines".into(), json!(v.clamp(2, 16)));+ }+ if let Some(v) = p.get("size").and_then(Value::as_f64).filter(|v| v.is_finite()) {+ body.insert("warichuSize".into(), json!(v.clamp(1.0, 1000.0)));+ }+ if let Some(v) = p.get("lineSpacing").and_then(Value::as_f64).filter(|v| v.is_finite()) {+ body.insert("warichuLineSpacing".into(), json!(v.clamp(-10_000.0, 10_000.0)));+ }+ if let Some(v) = p.get("align").and_then(Value::as_str) {+ body.insert("warichuAlignment".into(), json!(v));+ }+ if let Some(v) = p.get("charsBeforeBreak").and_then(Value::as_u64) {+ body.insert("warichuCharsBeforeBreak".into(), json!(v.min(100)));+ }+ if let Some(v) = p.get("charsAfterBreak").and_then(Value::as_u64) {+ body.insert("warichuCharsAfterBreak".into(), json!(v.min(100)));+ }+ }+ format_chars(s, &Value::Object(body))+ }+pub(crate) fn format_chars(s: &mut Session, attrs: &Value) -> Result<Value> {let mut a = CharAttrs::default();if let Some(o) = attrs.as_object() {diff --cc crates/pdf/src/export.rsindex b1db98540,d92fc242b..97569aab6--- a/crates/pdf/src/export.rs+++ b/crates/pdf/src/export.rs@@@ -410,8 -442,12 +442,13 @@@ pub(crate) struct Exporter<'a>/// Current sheet's visible area (spread space) for culling.pub clip: Rect,pub warnings: Vec<String>,+ drawing_items: Vec<designcraft_doc::ItemId>,images: HashMap<AssetId, Option<Image>>,+ // Immutable export options (including rgb_only) make bytes the complete conversion key.+ // PDF-page/SVG/media routing precedes this path. Failures remain per AssetId.+ images_by_content: ImageContentCache,+ #[cfg(test)]+ image_conversions: usize,/// Placed PDFs (embedded as vector pages).pdfs: HashMap<AssetId, Option<krilla::pdf::PdfDocument>>,/// The PDF version written; placed PDFs must not be newer.@@@ -1213,8 -1228,21 +1250,20 @@@ impl Exporter<'_>}let asset = self.doc.assets.get(&id)?.clone();let data = asset.data.clone();+ if let Some(converted) = self.images_by_content.get(&data).cloned() {+ if let Some(warning) = converted.warning {+ self.warn(format!("{}: {warning}", asset.name));+ }+ self.images.insert(id, Some(converted.image.clone()));+ return Some(converted.image);+ }let fmt = image::guess_format(&data).ok();+ #[cfg(test)]+ {+ self.image_conversions += 1;+ }+ let mut warning = None;- let mut mode = RasterMode::for_standard(self.opts.standard);- mode.interpolate &= self.interpolate;+ let mode = RasterMode::for_standard(self.opts.standard);let img = match fmt {Some(image::ImageFormat::Jpeg) => jpeg(data.clone().into(), || embedded_icc(&data), mode),// A CMYK TIFF keeps its ink values (`image` decodes it to RGB, and 100% K would print@@@ -1506,3 -1537,218 +1558,218 @@@ fn recompress(data: &[u8], mode: Rasterimage::ImageEncoder::write_image(enc, rgb.as_raw(), rgb.width(), rgb.height(), image::ExtendedColorType::Rgb8).ok()?;jpeg(buf.into(), || embedded_icc(data).filter(|p| is_rgb_icc(p)), mode)}++ #[cfg(test)]+ mod image_content_cache_tests {+ use super::*;+ use designcraft_doc::Asset;++ fn png(w: u32, h: u32, color: [u8; 4]) -> Vec<u8> {+ let image = image::RgbaImage::from_pixel(w, h, image::Rgba(color));+ let mut bytes = Vec::new();+ image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();+ bytes+ }+ fn asset(doc: &mut Document, bytes: Vec<u8>, name: &str) -> AssetId {+ let id = AssetId(doc.alloc());+ doc.assets.insert(+ id,+ Arc::new(Asset { id, name: name.into(), mime: "image/png".into(), link: None, data: Arc::new(bytes), pixels: None, page: 0 }),+ );+ id+ }+ fn exporter<'a>(doc: &'a Document, cache: &'a Cache, opts: &'a PdfOptions) -> Exporter<'a> {+ Exporter {++ drawing_items: Vec::new(),+ doc,+ cache,+ opts,+ clip: Rect::ZERO,+ warnings: Vec::new(),+ images: HashMap::new(),+ images_by_content: ImageContentCache::default(),+ image_conversions: 0,+ pdfs: HashMap::new(),+ version: PdfVersion::Pdf17,+ too_new: Vec::new(),+ svgs: HashMap::new(),+ fonts: HashMap::new(),+ reverse_cmaps: HashMap::new(),+ rgb_only: false,- interpolate: true,+ tags: Vec::new(),+ story_tags: HashMap::new(),+ tag_story: None,+ para_tags: HashMap::new(),+ }+ }+ #[test]+ fn exact_bytes_reuse_conversion_under_real_hash_collisions() {+ use std::hash::{BuildHasher, Hasher};+ let mut d = Document::new(&Default::default());+ let red = png(2, 1, [255, 0, 0, 255]);+ let blue = png(1, 2, [0, 0, 255, 128]);+ let a1 = asset(&mut d, red.clone(), "a1");+ let b1 = asset(&mut d, blue.clone(), "b1");+ let a2 = asset(&mut d, red, "a2");+ let b2 = asset(&mut d, blue, "b2");+ assert!(!Arc::ptr_eq(&d.assets[&a1].data, &d.assets[&a2].data));+ let cache = Cache::new();+ let opts = PdfOptions::default();+ let mut ex = exporter(&d, &cache, &opts);+ let mut h1 = ex.images_by_content.hasher().build_hasher();+ h1.write(&d.assets[&a1].data);+ let mut h2 = ex.images_by_content.hasher().build_hasher();+ h2.write(&d.assets[&b1].data);+ assert_eq!(h1.finish(), h2.finish());+ assert_ne!(d.assets[&a1].data, d.assets[&b1].data);+ for (id, count, size) in [(a1, 1, (2, 1)), (b1, 2, (1, 2)), (a2, 2, (2, 1)), (a1, 2, (2, 1)), (b2, 2, (1, 2))] {+ assert_eq!(ex.load_image(id).unwrap().size(), size);+ assert_eq!(ex.image_conversions, count, "count actual converter executions, not krilla resource equality");+ }+ assert_eq!(ex.images.len(), 4);+ assert_eq!(ex.images_by_content.len(), 2);+ let first_key = ex.images_by_content.keys().find(|key| key.as_slice() == d.assets[&a1].data.as_slice()).unwrap();+ assert!(Arc::ptr_eq(first_key, &d.assets[&a1].data), "cache keys share the original encoded payload");+ ex.images_by_content.clear();+ assert_eq!(ex.load_image(a1).unwrap().size(), (2, 1));+ assert_eq!(ex.image_conversions, 2, "the AssetId cache remains the first lookup");+ assert!(ex.images_by_content.is_empty());+ }+ #[test]+ fn successful_content_cache_does_not_suppress_failure_names() {+ let mut d = Document::new(&Default::default());+ let a = asset(&mut d, vec![0, 1, 2, 3], "broken-a.png");+ let b = asset(&mut d, vec![0, 1, 2, 3], "broken-b.png");+ let cache = Cache::new();+ let opts = PdfOptions::default();+ let mut ex = exporter(&d, &cache, &opts);+ assert!(ex.load_image(a).is_none());+ assert!(ex.load_image(b).is_none());+ assert!(ex.load_image(a).is_none());+ assert_eq!(ex.image_conversions, 2);+ assert!(ex.images_by_content.is_empty());+ assert_eq!(ex.warnings.len(), 2);+ assert!(ex.warnings[0].contains("broken-a.png"));+ assert!(ex.warnings[1].contains("broken-b.png"));+ }+ #[test]+ fn content_cache_is_scoped_to_each_immutable_options_context() {+ let mut d = Document::new(&Default::default());+ let data = png(2, 2, [240, 20, 30, 255]);+ let a = asset(&mut d, data.clone(), "a");+ let b = asset(&mut d, data, "b");+ let cache = Cache::new();+ for compress_images in [false, true, false] {+ let opts = PdfOptions { compress_images, ..Default::default() };+ let mut ex = exporter(&d, &cache, &opts);+ assert!(ex.load_image(a).is_some());+ assert!(ex.load_image(b).is_some());+ assert_eq!(ex.image_conversions, 1);+ assert_eq!(ex.images_by_content.len(), 1);+ }+ }++ #[test]+ fn successful_cmyk_fallback_replays_each_asset_name_once_and_converts_once() {+ let bytes = crate::image_fixtures::cmyk_tiff(None, true);+ assert!(designcraft_images::is_cmyk_tiff(&bytes));+ assert!(designcraft_images::decode_cmyk_tiff(&bytes).is_none());+ assert!(designcraft_images::decode_rgba(&bytes).is_some());+ let mut d = Document::new(&Default::default());+ let a = asset(&mut d, bytes.clone(), "ink-a.tif");+ let b = asset(&mut d, bytes, "ink-b.tif");+ let cache = Cache::new();+ for compress_images in [false, true] {+ let opts = PdfOptions { compress_images, ..Default::default() };+ let mut ex = exporter(&d, &cache, &opts);+ for id in [a, b, a, b] {+ assert_eq!(ex.load_image(id).unwrap().size(), (2, 1));+ }+ assert_eq!(ex.image_conversions, 1);+ assert_eq!(ex.images_by_content.len(), 1);+ assert_eq!(ex.warnings, [format!("ink-a.tif: {CMYK_FALLBACK_WARNING}"), format!("ink-b.tif: {CMYK_FALLBACK_WARNING}")]);+ }+ }++ #[test]+ fn cmyk_alpha_and_rgb_only_context_keep_conversion_counts_and_failures() {+ let cache = Cache::new();+ for alpha in [None, Some(2), Some(1)] {+ let mut d = Document::new(&Default::default());+ let bytes = crate::image_fixtures::cmyk_tiff(alpha, false);+ let a = asset(&mut d, bytes.clone(), "a.tif");+ let b = asset(&mut d, bytes, "b.tif");+ for standard in [Standard::None, Standard::PdfA2b, Standard::PdfX4, Standard::PdfA2b, Standard::None] {+ let opts = PdfOptions { standard, ..Default::default() };+ let mut ex = exporter(&d, &cache, &opts);+ ex.rgb_only = standard == Standard::PdfA2b;+ // The pinned image decoder does not support CMYKA as RGB. Associated alpha+ // is also rejected by the ink-preserving path: retain both failure names.+ let succeeds = alpha.is_none() || (alpha == Some(2) && !ex.rgb_only);+ let first = ex.load_image(a);+ assert_eq!(first.is_some(), succeeds, "{alpha:?} {standard:?}");+ if alpha.is_none() {+ let (space, samples) = image_color_samples(first.unwrap());+ assert_eq!(space, if ex.rgb_only { "DeviceRGB" } else { "DeviceCMYK" });+ assert_eq!(samples, if ex.rgb_only { vec![0, 0, 0, 255, 0, 0] } else { crate::image_fixtures::INKS.to_vec() });+ }+ assert_eq!(ex.load_image(b).is_some(), succeeds, "{alpha:?} {standard:?}");+ assert_eq!(ex.load_image(a).is_some(), succeeds);+ assert_eq!(ex.image_conversions, if succeeds { 1 } else { 2 });+ assert_eq!(ex.images_by_content.len(), usize::from(succeeds));+ if succeeds {+ assert!(ex.warnings.is_empty());+ } else {+ for name in ["a.tif", "b.tif"] {+ assert!(ex.warnings.contains(&format!("image `{name}` could not be decoded and was skipped")));+ assert_eq!(ex.warnings.contains(&format!("{name}: {CMYK_FALLBACK_WARNING}")), !ex.rgb_only);+ }+ }+ }+ }+ }++ // Serialize the converted raster without an archival validator so the RGB-only pixel+ // contract stays independent of main's existing PDF/A interpolation validation failure.+ fn image_color_samples(image: Image) -> (String, Vec<u8>) {+ use hayro_syntax::object::Name;+ let mut pdf = krilla::Document::new();+ let size = Size::from_wh(20.0, 20.0).unwrap();+ let mut page = pdf.start_page_with(PageSettings::new(size));+ let mut surface = page.surface();+ surface.draw_image(image, size);+ surface.finish();+ page.finish();+ let bytes = pdf.finish().unwrap();+ let pdf = hayro_syntax::Pdf::new(bytes).unwrap();+ let stream = pdf+ .objects()+ .into_iter()+ .filter_map(|o| o.into_stream())+ .find(|s| s.dict().get::<Name>("Subtype").is_some_and(|n| n.as_str() == "Image"))+ .unwrap();+ (stream.dict().get::<Name>("ColorSpace").unwrap().as_str().to_owned(), stream.decoded().unwrap().into_owned())+ }++ #[test]+ fn content_cache_owns_only_existing_payloads_and_drops_with_exporter() {+ let mut d = Document::new(&Default::default());+ let bytes = png(2, 1, [20, 30, 40, 255]);+ let a = asset(&mut d, bytes.clone(), "a.png");+ let b = asset(&mut d, bytes, "b.png");+ let payload = Arc::downgrade(&d.assets[&a].data);+ let duplicate = Arc::downgrade(&d.assets[&b].data);+ let cache = Cache::new();+ let opts = PdfOptions::default();+ let mut ex = exporter(&d, &cache, &opts);+ assert!(ex.load_image(a).is_some());+ assert!(ex.load_image(b).is_some());+ assert_eq!(duplicate.strong_count(), 1, "a content hit must not retain the second encoded allocation");+ let key = ex.images_by_content.keys().next().unwrap();+ assert!(Arc::ptr_eq(key, &d.assets[&a].data));+ drop(ex);+ drop(d);+ assert!(payload.upgrade().is_none(), "no converted image or encoded key outlives this exporter");+ assert!(duplicate.upgrade().is_none());+ }+ }diff --cc crates/ui-egui/src/canvas.rsindex 08a753a87,34dd61442..246061a5f--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@@ -1014,41 -986,8 +1014,17 @@@ fn draw_text_selectionif s > e || (s == e && !(l.range.end < range.end && e == l.range.end)) {continue;}- let quad = |x0: f64, x1: f64| {- [- Point::new(x0, l.baseline - l.ascent),- Point::new(x1, l.baseline - l.ascent),- Point::new(x1, l.baseline + l.descent),- Point::new(x0, l.baseline + l.descent),- ]- };- if l.glyphs.iter().any(|g| g.rtl) {- // Mixed directions: the selected glyphs' boxes, joined where they touch.- let mut spans: Vec<(f64, f64)> =- l.glyphs.iter().filter(|g| g.len > 0 && g.byte >= s && g.byte < e).map(|g| (g.x, g.x + g.adv)).collect();- spans.sort_by(|a, b| a.0.total_cmp(&b.0));- let mut merged: Vec<(f64, f64)> = Vec::new();- for (a, b) in spans {- match merged.last_mut() {- Some(m) if a <= m.1 + 0.5 => m.1 = m.1.max(b),- _ => merged.push((a, b)),- }- }- quads.extend(merged.into_iter().map(|(a, b)| quad(a, b)));- } else {- let x0 = compose::caret_x(l, s);- let x1 = if e == l.range.end && range.end > l.range.end { l.end_x.max(x0 + 3.0) } else { compose::caret_x(l, e) };- quads.push(quad(x0, x1));- }+ let past = e == l.range.end && range.end > l.range.end;+ quads.extend(compose::highlight_quads(l, s, e, past));+ // A selected drop cap is highlighted down to its baseline.+ if let Some(dc) = l.drop_cap {+ let sel = l.glyphs.iter().filter(|g| g.len > 0 && g.byte < dc.end && g.byte >= s && g.byte < e);+ let (a, b) = sel.fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), g| (a.min(g.x), b.max(g.x + g.adv)));+ if a < b {+ let r = dc.rect;+ quads.push([Point::new(a, r.y0), Point::new(b, r.y0), Point::new(b, r.y1), Point::new(a, r.y1)]);+ }+ }for (gi, g) in l.glyphs.iter().enumerate() {if g.visible && g.len > 0 && g.byte >= s && g.byte < e {glyphs.push((li, gi));