DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
T: Composition highlights — keep and H&J violations, custom tracking/kerning
Brandon Thomas98d8edf76421
diff --git a/ROADMAP.md b/ROADMAP.mdindex 761a164ee..543d0ba1e 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -41,6 +41,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope- Attributes panel (`object.attributes`: Overprint Fill/Stroke/Gap, Nonprinting), with Overprint Gap in Overprint Preview and IDML.- Page Numbering View (Preferences: section or absolute): page labels everywhere follow it; Go to Page takes section names, numbers or `+n`.- Preferences › Advanced Type (document `advancedType`: superscript/subscript size and position; IDML TextPreference); subscripts now drop 33.3% like InDesign.+- Preferences › Composition › Highlight: keep violations, H&J violations (three shades), custom tracking/kerning, substituted fonts.- Drag and drop text editing: drag selected text to move it (Alt copies) with its formatting (`text.release`).- Image Import Options: place any page of a multi-page PDF (`file.place {pdfPage}`; the app asks which page), shown on screen and embedded as that page in PDF export.- Define Lists: named numbered lists that continue across stories in page order (`list.define`, paragraph `listName` / `startAt`), round-tripped through IDML; `null` in `type.para` / `type.char` now removes an override.diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rsindex ae0f3e755..a95e83cc8 100644--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@ -54,6 +54,8 @@ pub struct RunStyle {pub size: f64,/// The run's font isn't installed (shown in a substitute; highlighted on screen).pub missing_font: bool,+ /// Tracking or manual kerning (Highlight Custom Tracking/Kerning).+ pub custom_tracking: bool,}/// An underline or strikethrough bar: its top edge `offset` below the baseline (negative =@@ -115,6 +117,11 @@ pub struct Line {pub end_x: f64,/// Word-space ratio actually used vs desired (H&J violation highlighting), 1.0 = desired.pub spacing: f64,+ /// H&J violation: 0 = within the paragraph's minimum/maximum word spacing, 1–3 = how far out+ /// (Preferences › Composition › Highlight H&J Violations shades).+ pub hj: u8,+ /// The paragraph's Keep Options couldn't be honoured here (Highlight Keep Violations).+ pub keep_violation: bool,}/// A paragraph rule or shading rectangle in frame inner space.@@ -681,6 +688,8 @@ pub fn compose(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &Compolast_in_para: last,end_x,spacing: ratio,+ hj: hj_severity(ratio, pp.word_space_min, pp.word_space_max),+ keep_violation: false,});for k in line_notes {notes.place(doc, k, cur.fi, cur.col, col_w, f, opts);@@ -828,9 +837,55 @@ pub fn compose(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &Compo}}out.styles = styles_tab;+ mark_keep_violations(doc, story, &mut out);out}+/// Flag the lines of paragraphs whose Keep Options the layout couldn't honour: lines kept+/// together that split, too few lines at the bottom (orphans) or top (widows) of a column, or a+/// keep-with-next paragraph separated from the next one.+fn mark_keep_violations(doc: &Document, story: &Story, out: &mut ComposedStory) {+ // Per paragraph, the columns its lines sit in: ((frame, column), line count) in order.+ let mut cols: HashMap<usize, Vec<((usize, u32), usize)>> = HashMap::new();+ for (fi, ft) in out.frames.iter().enumerate() {+ for l in &ft.lines {+ let v = cols.entry(l.para).or_default();+ match v.last_mut() {+ Some((c, n)) if *c == (fi, l.column) => *n += 1,+ _ => v.push(((fi, l.column), 1)),+ }+ }+ }+ let mut bad: Vec<usize> = Vec::new();+ for (&pi, v) in &cols {+ let Some(pf) = story.paras.get(pi) else { continue };+ let (pp, _) = doc.styles.resolve_para(pf);+ if pp.keep_lines_together && v.len() > 1 {+ let (first, last) = (v[0].1, v[v.len() - 1].1);+ if pp.keep_all_lines || first < pp.keep_first.max(1) as usize || last < pp.keep_last.max(1) as usize {+ bad.push(pi);+ continue;+ }+ }+ if pp.keep_with_next > 0+ && let (Some(end), Some(next)) = (v.last(), cols.get(&(pi + 1)))+ && next.first().is_some_and(|(c, n)| *c != end.0 || (*n < pp.keep_with_next as usize && next.len() > 1))+ {+ bad.push(pi);+ }+ }+ if bad.is_empty() {+ return;+ }+ for ft in &mut out.frames {+ for l in &mut ft.lines {+ if bad.contains(&l.para) {+ l.keep_violation = true;+ }+ }+ }+}+/// Breaker parameters from the paragraph's settings.fn spacing_for(pp: &ParaProps, base_size: f64) -> Spacing {Spacing {@@ -1143,6 +1198,25 @@ fn estimate_slots(f: &FrameSpec, col: Rect, first: f64, lead: f64, size: f64, glv}+/// How far a line's word spacing falls outside `[min, max]` (ratios of the space width): 0 inside,+/// then 1–3 for up to 10%, 25% and beyond.+pub fn hj_severity(ratio: f64, min: f64, max: f64) -> u8 {+ let r = if ratio > max + 1e-6 {+ ratio / max.max(1e-6)+ } else if ratio < min - 1e-6 {+ min / ratio.max(1e-6)+ } else {+ return 0;+ };+ if r < 1.1 {+ 1+ } else if r < 1.25 {+ 2+ } else {+ 3+ }+}+/// Position glyphs `s..e` within `[x0, x1]`; returns (glyphs, end x, word-space ratio).////// Justified lines distribute the difference to the measure in priority order: word spaces up todiff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rsindex c23f55ad0..c60bab8c7 100644--- a/crates/compose/src/shape.rs+++ b/crates/compose/src/shape.rs@@ -125,6 +125,7 @@ impl StyleTable<'_> {.missing.entry(p.font_family.clone()).or_insert_with(|| !p.font_family.is_empty() && !designcraft_fonts::FontDb::global().has_family(&p.font_family)),+ custom_tracking: p.tracking.abs() > 1e-9 || matches!(p.kerning, designcraft_doc::Kerning::Manual(_)),};if let Some(i) = self.styles.iter().rposition(|s| *s == rs) {return i as u32;diff --git a/crates/compose/src/table.rs b/crates/compose/src/table.rsindex 408045f36..656488a23 100644--- a/crates/compose/src/table.rs+++ b/crates/compose/src/table.rs@@ -404,6 +404,8 @@ fn emit(last_in_para: last,end_x: right,spacing: 1.0,+ hj: 0,+ keep_violation: false,});ft.tables.push(TableFrag {table: table.id,diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rsindex f8f8318bc..ec91dc258 100644--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@ -787,3 +787,13 @@ fn footnote_line_at_column_top_still_sets() {assert!(!cs.frames[0].lines.is_empty());assert_eq!(cs.frames[0].notes.len(), 1);}++#[test]+fn hj_severity_shades() {+ use crate::hj_severity;+ assert_eq!(hj_severity(1.0, 0.8, 1.33), 0);+ assert_eq!(hj_severity(1.4, 0.8, 1.33), 1);+ assert_eq!(hj_severity(1.6, 0.8, 1.33), 2);+ assert_eq!(hj_severity(2.5, 0.8, 1.33), 3);+ assert_eq!(hj_severity(0.6, 0.8, 1.33), 3);+}diff --git a/crates/engine/src/cmd/prefs.rs b/crates/engine/src/cmd/prefs.rsindex 0297b82ee..d41c57585 100644--- a/crates/engine/src/cmd/prefs.rs+++ b/crates/engine/src/cmd/prefs.rs@@ -28,7 +28,7 @@ pub fn specs() -> Vec<CommandSpec> {"Preferences",[],None,- "{showHiddenCharacters?, typographersQuotes?, polygonSides?, starInset?, scaleStrokes?, dimensionsIncludeStroke?, transformationsAreTotals?, absolutePageNumbers?} → all application preferences",+ "{showHiddenCharacters?, typographersQuotes?, polygonSides?, starInset?, scaleStrokes?, dimensionsIncludeStroke?, transformationsAreTotals?, absolutePageNumbers?, highlightHj?, highlightKeeps?, highlightCustomTracking?, highlightSubstitutedFonts?} → all application preferences",super::always,|s, p| {let cur = serde_json::to_value(&s.prefs).map_err(|e| bad("prefs.set", e.to_string()))?;@@ -164,3 +164,66 @@ mod advanced_type_idml_tests {assert_eq!(back.settings.advanced_type.superscript_size, 58.3);}}++#[cfg(test)]+mod highlight_tests {+ use serde_json::json;++ use crate::Session;++ #[test]+ fn hj_violations_and_custom_tracking_are_highlighted_on_screen() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ // A narrow justified column of long words: loose lines.+ let r = s+ .execute("frame.create", &json!({"rect": [72, 72, 172, 400], "content": "text", "text": "Incomprehensibilities notwithstanding characteristically uncharacteristically a b"}))+ .unwrap();+ s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 3})).unwrap();+ s.execute("type.para", &json!({"align": "fullyJustified"})).unwrap();+ s.execute("type.char", &json!({"tracking": 50})).unwrap();+ let sid = designcraft_doc::StoryId(r["story"].as_u64().unwrap());+ let d = s.doc().unwrap().doc.clone();+ let cs = s.cache.get(&d, sid, None);+ assert!(cs.frames[0].lines.iter().any(|l| l.hj > 0), "some line breaks the word-spacing limits");+ assert!(cs.styles.iter().any(|st| st.custom_tracking));+ let render = |hj: bool, tr: bool| {+ let mut r = designcraft_render::Renderer::new();+ r.threads = 0;+ let o = designcraft_render::RenderOptions { highlight_hj: hj, highlight_custom_tracking: tr, ..Default::default() };+ r.render_page(&d, &s.cache, 0, 1.0, false, &o).unwrap()+ };+ let plain = render(false, false);+ let lit = render(true, true);+ let count = |img: &designcraft_render::Rendered, pred: &dyn Fn([u8; 4]) -> bool| {+ (72..172).flat_map(|x| (72..400).map(move |y| (x, y))).filter(|&(x, y)| pred(img.pixel(x, y))).count()+ };+ let yellow = |p: [u8; 4]| p[0] > 240 && p[1] > 200 && p[2] < 190;+ let green = |p: [u8; 4]| p[1] > 220 && p[0] < 200 && p[2] < 200;+ assert_eq!(count(&plain, &yellow), 0);+ assert!(count(&lit, &yellow) > 50, "H&J shading");+ assert!(count(&lit, &green) > 10, "custom tracking shading");+ }+}++#[cfg(test)]+mod keep_highlight_tests {+ use serde_json::json;++ use crate::Session;++ #[test]+ fn unkeepable_paragraph_is_flagged() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let text = "word ".repeat(120);+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 160], "content": "text", "text": text, "caret": false})).unwrap();+ s.execute("object.textFrameOptions", &json!({"ids": [r["id"]], "columns": 2})).unwrap();+ let sid = designcraft_doc::StoryId(r["story"].as_u64().unwrap());+ let flagged = |s: &Session| s.cache.get(&s.doc().unwrap().doc, sid, None).frames[0].lines.iter().any(|l| l.keep_violation);+ assert!(!flagged(&s), "no keep options, no violation");+ s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();+ s.execute("type.para", &json!({"keepLinesTogether": true, "keepAllLines": true})).unwrap();+ assert!(flagged(&s), "too long to keep together in one column");+ }+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex dc36f1832..e561a4860 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -138,6 +138,12 @@ pub struct Prefs {/// Preferences › General › Page Numbering View: Absolute (1, 2, 3… from the first page) instead/// of section numbering (the page names, e.g. "iv", "A-3").pub absolute_page_numbers: bool,+ /// Preferences › Composition › Highlight: H&J violations, custom tracking/kerning, substituted+ /// fonts (screen only).+ pub highlight_hj: bool,+ pub highlight_keeps: bool,+ pub highlight_custom_tracking: bool,+ pub highlight_substituted_fonts: bool,/// Preferences › Type › Smart Text Reflow: pages follow the primary text frame's story/// (added while it oversets, empty ones at the end removed).pub smart_text_reflow: bool,@@ -154,6 +160,10 @@ impl Default for Prefs {dimensions_include_stroke: true,transformations_are_totals: true,absolute_page_numbers: false,+ highlight_hj: false,+ highlight_keeps: false,+ highlight_custom_tracking: false,+ highlight_substituted_fonts: true,smart_text_reflow: true,}}diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rsindex f191a332e..225a258b2 100644--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@ -100,6 +100,11 @@ pub struct RenderOptions {pub page_shadow: bool,/// Pink highlight behind text set in fonts that aren't installed (screen view).pub highlight_missing_fonts: bool,+ /// Preferences › Composition: yellow behind lines whose word spacing breaks the paragraph's+ /// limits (darker = worse), green behind text with custom tracking or kerning (screen view).+ pub highlight_hj: bool,+ pub highlight_keeps: bool,+ pub highlight_custom_tracking: bool,/// View › Display Performance.pub quality: DisplayQuality,/// Preferences › Appearance of Black: show 100% K as rich (pure) black instead of the@@ -132,6 +137,9 @@ impl Default for RenderOptions {greek_below_px: 0.0,page_shadow: false,highlight_missing_fonts: false,+ highlight_hj: false,+ highlight_keeps: false,+ highlight_custom_tracking: false,quality: DisplayQuality::High,rich_black: false,overprint_preview: false,diff --git a/crates/render/src/text.rs b/crates/render/src/text.rsindex ade4201a4..b03d241c5 100644--- a/crates/render/src/text.rs+++ b/crates/render/src/text.rs@@ -205,6 +205,30 @@ impl Renderer {}}}+ if f.opts.highlight_keeps && ft.lines.iter().any(|l| l.keep_violation) {+ ctx.set_transform(m);+ ctx.set_paint(peniko::Color::from_rgb8(255, 236, 120));+ for l in ft.lines.iter().filter(|l| l.keep_violation) {+ ctx.fill_rect(&kurbo::Rect::new(l.x0, l.baseline - l.ascent, l.x1, l.baseline + l.descent));+ }+ }+ if f.opts.highlight_hj && ft.lines.iter().any(|l| l.hj > 0) {+ ctx.set_transform(m);+ for l in ft.lines.iter().filter(|l| l.hj > 0) {+ let shade = [0u8, 0xF6, 0xEA, 0xD8][l.hj.min(3) as usize];+ ctx.set_paint(peniko::Color::from_rgb8(255, shade, [0u8, 0xB0, 0x70, 0x30][l.hj.min(3) as usize]));+ ctx.fill_rect(&kurbo::Rect::new(l.x0, l.baseline - l.ascent, l.end_x.max(l.x0 + 1.0), l.baseline + l.descent));+ }+ }+ if f.opts.highlight_custom_tracking && cs.styles.iter().any(|s| s.custom_tracking) {+ ctx.set_transform(m);+ ctx.set_paint(peniko::Color::from_rgb8(176, 236, 176));+ for l in &ft.lines {+ for g in l.glyphs.iter().filter(|g| g.adv > 0.0 && cs.styles.get(g.style as usize).is_some_and(|s| s.custom_tracking)) {+ ctx.fill_rect(&kurbo::Rect::new(g.x, l.baseline - l.ascent, g.x + g.adv, l.baseline + l.descent));+ }+ }+ }let scale = m.determinant().abs().sqrt();let greek_px = f.opts.greek_below_px;let mut greek = BezPath::new();diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex b38f01153..be5f38d59 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -310,7 +310,10 @@ fn render_texture(app: &mut DesignApp, ctx: &egui::Context, rect: Rect, xf: &Xf,let opts = designcraft_render::RenderOptions {printing_only: preview,greek_below_px: 3.0 * ppp,- highlight_missing_fonts: !preview,+ highlight_missing_fonts: !preview && app.session.prefs.highlight_substituted_fonts,+ highlight_hj: !preview && app.session.prefs.highlight_hj,+ highlight_keeps: !preview && app.session.prefs.highlight_keeps,+ highlight_custom_tracking: !preview && app.session.prefs.highlight_custom_tracking,quality: app.ui.display_quality,rich_black: app.ui.rich_black,overprint_preview: app.ui.overprint_preview,@@ -415,7 +418,10 @@ fn patch_texture(app: &mut DesignApp, layout: &CanvasLayout, ppp: f64, doc_key:let opts = designcraft_render::RenderOptions {printing_only: preview,greek_below_px: 3.0 * ppp,- highlight_missing_fonts: !preview,+ highlight_missing_fonts: !preview && app.session.prefs.highlight_substituted_fonts,+ highlight_hj: !preview && app.session.prefs.highlight_hj,+ highlight_keeps: !preview && app.session.prefs.highlight_keeps,+ highlight_custom_tracking: !preview && app.session.prefs.highlight_custom_tracking,quality: app.ui.display_quality,rich_black: app.ui.rich_black,overprint_preview: app.ui.overprint_preview,diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 47a30a213..322d4c623 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -340,6 +340,7 @@ fn preferences(ui: &mut egui::Ui, d: &mut Dialog) {("interface", "Interface"),("type", "Type"),("advancedType", "Advanced Type"),+ ("composition", "Composition"),("units", "Units & Increments"),("grids", "Grids"),("guides", "Guides & Pasteboard"),@@ -347,7 +348,7 @@ fn preferences(ui: &mut egui::Ui, d: &mut Dialog) {("black", "Appearance of Black"),]} else {- &[("general", "General"), ("interface", "Interface"), ("type", "Type"), ("display", "Display Performance")]+ &[("general", "General"), ("interface", "Interface"), ("type", "Type"), ("composition", "Composition"), ("display", "Display Performance")]};let cur = d.s("section");ui.horizontal_top(|ui| {@@ -373,6 +374,13 @@ fn preferences(ui: &mut egui::Ui, d: &mut Dialog) {ui.label(egui::RichText::new("Smart Text Reflow").font(semibold(12.0)));check(ui, d, "smartTextReflow", "Add and remove pages as the primary text frame's story grows and shrinks");}+ "composition" => {+ ui.label(egui::RichText::new("Highlight").font(semibold(12.0)));+ check(ui, d, "highlightKeeps", "Keep Violations");+ check(ui, d, "highlightHj", "H&J Violations");+ check(ui, d, "highlightCustomTracking", "Custom Tracking/Kerning");+ check(ui, d, "highlightSubstitutedFonts", "Substituted Fonts");+ }"advancedType" => {ui.label(egui::RichText::new("Character Settings").font(semibold(12.0)));egui::Grid::new("pref_adv").num_columns(3).spacing([8.0, 6.0]).show(ui, |ui| {@@ -916,8 +924,10 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {"preferences" => {app.run("prefs.set",- json!({"scaleStrokes": d.b("scaleStrokes"), "dimensionsIncludeStroke": d.b("dimensionsIncludeStroke"), "transformationsAreTotals": d.b("transformationsAreTotals"), "absolutePageNumbers": d.b("absolutePageNumbers"), "typographersQuotes": d.b("typographersQuotes"), "smartTextReflow": d.b("smartTextReflow")}),+ json!({"scaleStrokes": d.b("scaleStrokes"), "dimensionsIncludeStroke": d.b("dimensionsIncludeStroke"), "transformationsAreTotals": d.b("transformationsAreTotals"), "absolutePageNumbers": d.b("absolutePageNumbers"), "highlightHj": d.b("highlightHj"), "highlightKeeps": d.b("highlightKeeps"), "highlightCustomTracking": d.b("highlightCustomTracking"), "highlightSubstitutedFonts": d.b("highlightSubstitutedFonts"), "typographersQuotes": d.b("typographersQuotes"), "smartTextReflow": d.b("smartTextReflow")}),)?;+ // Highlight options change the screen view only.+ app.canvas.shown = None;let view = match d.s("displayQuality").as_str() {"fast" => "view.fastDisplay","typical" => "view.typicalDisplay",diff --git a/docs/parity.md b/docs/parity.mdindex 96c0b40dc..15408e71f 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -10,7 +10,7 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia| Priority | Features | Done | Partial | Missing | Parity ||---|---|---|---|---|---|| P0 | 102 | 99 | 3 | 0 | 99% |-| P1 | 97 | 73 | 22 | 2 | 87% |+| P1 | 97 | 74 | 21 | 2 | 87% || P2 | 76 | 12 | 13 | 51 | 24% || Area | Parity |@@ -24,7 +24,7 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia| Effects & transparency | 62% || Placing & links | 82% || Type & text frames | 88% |-| Typography | 87% |+| Typography | 88% || Styles | 92% || Tables | 88% || Long documents | 79% |@@ -229,7 +229,7 @@ Open P0 items: Preferences, Vector/page formats (PDF/AI/SVG/EPS place), Export t| Typography | Balance ragged lines | P1 | D || Typography | Optical margin alignment | P1 | D || Typography | Baseline grid | P0 | D |-| Typography | Highlight H&J / keep violations | P1 | P |+| Typography | Highlight H&J / keep violations | P1 | D || Typography | Glyph scaling, letter/word spacing | P0 | D || Typography | Auto leading | P0 | D || Typography | Text wrap | P0 | D |