DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
refactor: split complex functions in psd, table, parabox, index, trace, pdf export, render (Sonar S3776) (#1724)
Dylan M. Taylorcb763c258339
diff --git a/crates/compose/src/parabox.rs b/crates/compose/src/parabox.rsindex b8b58cb44..f6b90e127 100644--- a/crates/compose/src/parabox.rs+++ b/crates/compose/src/parabox.rs@@ -122,6 +122,45 @@ pub(crate) fn draw(out: &mut ComposedStory, boxes: &[Option<ParaBox>], frames: &}}+/// The shading box for one part of a paragraph run, if it has any area.+fn shading_deco(s: &Shading, part: &Part<'_>, frames: &[FrameSpec], first_part: bool, last_part: bool) -> Option<Deco> {+ let r = inner_rect(&part.lines, s.width, s.top, s.bottom)?;+ let [t, l, bo, rr] = s.offsets;+ let mut rect = Rect::new(r.x0 - l, r.y0 - t, r.x1 + rr, r.y1 + bo);+ if s.clip+ && let Some(f) = frames.get(part.fi)+ {+ rect = rect.intersect(frame_rect(f));+ }+ if rect.width() > 0.0 && rect.height() > 0.0 {+ // Corners stay square where the box is cut by a split.+ let corners = cut_corners(s.corners, !first_part, !last_part);+ let path = (!corners.iter().all(Corner::is_none)).then(|| box_outline(rect, &corners, [true; 4]));+ return Some(Deco { rect, color: s.color.clone(), tint: s.tint, path, nonprinting: s.nonprinting });+ }+ None+}++/// The border strokes (and plain edges) for one part of a paragraph run, pushed onto `decos`.+fn border_decos(bd: &Border, part: &Part<'_>, first_part: bool, last_part: bool, decos: &mut Vec<(usize, bool, Deco)>) {+ let Some(r) = inner_rect(&part.lines, bd.width, bd.top, bd.bottom) else { return };+ let [t, l, bo, rr] = bd.offsets;+ let o = Rect::new(r.x0 - l, r.y0 - t, r.x1 + rr, r.y1 + bo);+ let open_top = !first_part && !bd.display_if_splits;+ let open_bottom = !last_part && !bd.display_if_splits;+ for (path, gap) in border_paths(bd, o, open_top, open_bottom) {+ let (color, tint) = if gap { (bd.gap_color.clone(), bd.gap_tint) } else { (bd.color.clone(), bd.tint) };+ decos.push((part.fi, false, Deco { rect: path.bounding_box(), color, tint, path: Some(path), nonprinting: false }));+ }+ if is_plain(bd, open_top, open_bottom) {+ decos.extend(+ plain_edges(bd, o, open_top, open_bottom)+ .into_iter()+ .map(|rect| (part.fi, false, Deco { rect, color: bd.color.clone(), tint: bd.tint, path: None, nonprinting: false })),+ );+ }+}+/// The decorations of paragraphs `paras` sharing box `b`: (frame, drawn under the rest, deco).fn group_decos(out: &ComposedStory, paras: std::ops::RangeInclusive<usize>, b: &ParaBox, frames: &[FrameSpec]) -> Vec<(usize, bool, Deco)> {let mut parts: Vec<Part<'_>> = Vec::new();@@ -136,40 +175,12 @@ fn group_decos(out: &ComposedStory, paras: std::ops::RangeInclusive<usize>, b: &for (k, part) in parts.iter().enumerate() {let (first_part, last_part) = (k == 0, k + 1 == n);if let Some(s) = &b.shading- && let Some(r) = inner_rect(&part.lines, s.width, s.top, s.bottom)+ && let Some(deco) = shading_deco(s, part, frames, first_part, last_part){- let [t, l, bo, rr] = s.offsets;- let mut rect = Rect::new(r.x0 - l, r.y0 - t, r.x1 + rr, r.y1 + bo);- if s.clip- && let Some(f) = frames.get(part.fi)- {- rect = rect.intersect(frame_rect(f));- }- if rect.width() > 0.0 && rect.height() > 0.0 {- // Corners stay square where the box is cut by a split.- let corners = cut_corners(s.corners, !first_part, !last_part);- let path = (!corners.iter().all(Corner::is_none)).then(|| box_outline(rect, &corners, [true; 4]));- decos.push((part.fi, true, Deco { rect, color: s.color.clone(), tint: s.tint, path, nonprinting: s.nonprinting }));- }+ decos.push((part.fi, true, deco));}- if let Some(bd) = &b.border- && let Some(r) = inner_rect(&part.lines, bd.width, bd.top, bd.bottom)- {- let [t, l, bo, rr] = bd.offsets;- let o = Rect::new(r.x0 - l, r.y0 - t, r.x1 + rr, r.y1 + bo);- let open_top = !first_part && !bd.display_if_splits;- let open_bottom = !last_part && !bd.display_if_splits;- for (path, gap) in border_paths(bd, o, open_top, open_bottom) {- let (color, tint) = if gap { (bd.gap_color.clone(), bd.gap_tint) } else { (bd.color.clone(), bd.tint) };- decos.push((part.fi, false, Deco { rect: path.bounding_box(), color, tint, path: Some(path), nonprinting: false }));- }- if is_plain(bd, open_top, open_bottom) {- decos.extend(- plain_edges(bd, o, open_top, open_bottom)- .into_iter()- .map(|rect| (part.fi, false, Deco { rect, color: bd.color.clone(), tint: bd.tint, path: None, nonprinting: false })),- );- }+ if let Some(bd) = &b.border {+ border_decos(bd, part, first_part, last_part, &mut decos);}}decosdiff --git a/crates/compose/src/table.rs b/crates/compose/src/table.rsindex 39219e43b..9a41a546e 100644--- a/crates/compose/src/table.rs+++ b/crates/compose/src/table.rs@@ -343,6 +343,26 @@ pub(crate) fn place_table(true}+/// A cell's text cut to the lines that fit `clip_height`, with where the overset text begins.+/// Uses the same baseline/bounds test as auto-growth, and retains a prefix: overset text cannot+/// reappear after a line that did not fit.+fn clip_overset(lay: &CellLayout, clip_height: f64) -> Arc<ComposedStory> {+ let Some(f) = lay.text.frames.first() else { return lay.text.clone() };+ let keep = lay.line_heights.iter().take_while(|h| **h <= clip_height + 0.01).count();+ let overset_at = f.lines.get(keep).map(|l| l.range.start);+ let mut t = (*lay.text).clone();+ if let Some(frame) = t.frames.first_mut() {+ frame.lines.truncate(keep);+ frame.objects.retain(|o| o.line < keep);+ frame.tables.retain(|table| table.line < keep);+ frame.range.end = frame.lines.last().map_or(frame.range.start, |l| l.range.end);+ }+ if let Some(at) = overset_at {+ t.overset_at = Some(at);+ }+ Arc::new(t)+}+/// Build one fragment from its rows and push it (with its glyph-less line) to the current frame.#[allow(clippy::too_many_arguments)]fn emit(@@ -407,24 +427,7 @@ fn emit(_ => 0.0,};let overset = space < -0.01 || lay.text.is_overset();- let mut text = lay.text.clone();- if overset && let Some(f) = text.frames.first() {- // Use the same baseline/bounds test as auto-growth, and retain a prefix:- // overset text cannot reappear after a line that did not fit.- let keep = lay.line_heights.iter().take_while(|h| **h <= clip.height() + 0.01).count();- let overset_at = f.lines.get(keep).map(|l| l.range.start);- let mut t = (*text).clone();- if let Some(frame) = t.frames.first_mut() {- frame.lines.truncate(keep);- frame.objects.retain(|o| o.line < keep);- frame.tables.retain(|table| table.line < keep);- frame.range.end = frame.lines.last().map_or(frame.range.start, |l| l.range.end);- }- if let Some(at) = overset_at {- t.overset_at = Some(at);- }- text = Arc::new(t);- }+ let text = if overset { clip_overset(lay, clip.height()) } else { lay.text.clone() };cells.push(PlacedCell {row: r,col: c,diff --git a/crates/doc/src/index.rs b/crates/doc/src/index.rsindex 9f56c42ea..826464329 100644--- a/crates/doc/src/index.rs+++ b/crates/doc/src/index.rs@@ -100,6 +100,25 @@ fn sort_key(s: &str) -> String {if k.is_empty() { s.to_lowercase() } else { k }}+/// Record one reference's see-target or page on its topic node.+fn record_ref(n: &mut Node, res: &Resolved) {+ match &res.r.range {+ IndexRange::See(t) => n.see.push(t.clone()),+ IndexRange::SeeAlso(t) => {+ n.see_also.push(t.clone());+ if let Some(p) = res.pages {+ n.pages.push(p);+ }+ }+ IndexRange::SuppressPageRange => {}+ _ => {+ if let Some(p) = res.pages {+ n.pages.push(p);+ }+ }+ }+}+/// The index as paragraphs `(style, text)`; `page_name` formats an absolute page.pub fn build(spec: &IndexSpec, refs: &[Resolved], page_name: &dyn Fn(usize) -> String) -> Vec<(String, String)> {let mut root: BTreeMap<String, Node> = BTreeMap::new();@@ -114,21 +133,7 @@ pub fn build(spec: &IndexSpec, refs: &[Resolved], page_name: &dyn Fn(usize) -> S.map(|(i, t)| (format!("{}\u{0}{}", sort_key(res.r.sort.get(i).filter(|s| !s.is_empty()).unwrap_or(t)), t.trim()), t.trim().to_string())).collect();let n = descend(&mut root, &keys);- match &res.r.range {- IndexRange::See(t) => n.see.push(t.clone()),- IndexRange::SeeAlso(t) => {- n.see_also.push(t.clone());- if let Some(p) = res.pages {- n.pages.push(p);- }- }- IndexRange::SuppressPageRange => {}- _ => {- if let Some(p) = res.pages {- n.pages.push(p);- }- }- }+ record_ref(n, res);}let mut out = Vec::new();if !spec.title.is_empty() {diff --git a/crates/doc/src/table.rs b/crates/doc/src/table.rsindex e96aac4b7..d80b1d475 100644--- a/crates/doc/src/table.rs+++ b/crates/doc/src/table.rs@@ -1040,6 +1040,15 @@ impl Table {if self.rows[h..self.nrows() - f].iter().any(|r| r.kind != RowKind::Body) {return Err(format!("table {}: header/footer rows out of order", self.id));}+ self.check_spans()?;+ for cell in &self.cells {+ cell.text.check()?;+ }+ Ok(())+ }++ /// Every merged cell stays inside the grid and no two merged cells overlap.+ fn check_spans(&self) -> Result<(), String> {let mut seen = vec![false; self.cells.len()];for r in 0..self.nrows() {for c in 0..self.ncols() {@@ -1064,9 +1073,6 @@ impl Table {}}}- for cell in &self.cells {- cell.text.check()?;- }Ok(())}}diff --git a/crates/geom/src/trace.rs b/crates/geom/src/trace.rsindex 54809fbb5..292f82e87 100644--- a/crates/geom/src/trace.rs+++ b/crates/geom/src/trace.rs@@ -5,12 +5,9 @@ use std::collections::HashMap;use crate::Point;-/// Closed outlines around the `true` cells of a `w`×`h` mask (row-major), simplified to within-/// `tol` pixels; outlines enclosing less than `min_area` pixels are dropped. Holes come out-/// with the opposite winding.-pub fn trace(mask: &[bool], w: usize, h: usize, tol: f64, min_area: f64) -> Vec<Vec<Point>> {+/// Pixel-border edges of the mask with the inside on the right (clockwise, y down), by start point.+fn border_edges(mask: &[bool], w: usize, h: usize) -> HashMap<(isize, isize), Vec<(isize, isize)>> {let inside = |x: isize, y: isize| x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h && mask[y as usize * w + x as usize];- // Pixel-border edges with the inside on the right (clockwise, y down).let mut next: HashMap<(isize, isize), Vec<(isize, isize)>> = HashMap::new();let mut add = |a: (isize, isize), b: (isize, isize)| next.entry(a).or_default().push(b);for y in 0..h as isize {@@ -32,6 +29,14 @@ pub fn trace(mask: &[bool], w: usize, h: usize, tol: f64, min_area: f64) -> Vec<}}}+ next+}++/// Closed outlines around the `true` cells of a `w`×`h` mask (row-major), simplified to within+/// `tol` pixels; outlines enclosing less than `min_area` pixels are dropped. Holes come out+/// with the opposite winding.+pub fn trace(mask: &[bool], w: usize, h: usize, tol: f64, min_area: f64) -> Vec<Vec<Point>> {+ let mut next = border_edges(mask, w, h);let mut out = Vec::new();let mut starts: Vec<(isize, isize)> = next.keys().copied().collect();starts.sort();diff --git a/crates/images/src/psd.rs b/crates/images/src/psd.rsindex 980f802c5..4006e0e30 100644--- a/crates/images/src/psd.rs+++ b/crates/images/src/psd.rs@@ -81,6 +81,16 @@ impl Mode {/// The merged composite as straight RGBA8, `None` when the file is damaged or unsupported (32-bit,/// Multichannel, ZIP-compressed composite).+/// Whether the header's depth, channel count and size are all within what the decoder supports.+fn header_in_range(mode: Mode, depth: u16, channels: usize, (w, h): (u32, u32), max_side: u32) -> bool {+ let depth_ok = match mode {+ Mode::Bitmap => depth == 1,+ Mode::Indexed => depth == 8,+ _ => depth == 8 || depth == 16,+ };+ (1..=56).contains(&channels) && channels >= mode.colour_channels() && (1..=max_side).contains(&w) && (1..=max_side).contains(&h) && depth_ok+}+pub(crate) fn decode(bytes: &[u8]) -> Option<image::RgbaImage> {let mut r = Reader { b: bytes };if r.take(4)? != b"8BPS" {@@ -97,13 +107,8 @@ pub(crate) fn decode(bytes: &[u8]) -> Option<image::RgbaImage> {let depth = r.u16()?;let mode = Mode::parse(r.u16()?)?;let max_side = if psb { 300_000 } else { 30_000 };- let depth_ok = match mode {- Mode::Bitmap => depth == 1,- Mode::Indexed => depth == 8,- _ => depth == 8 || depth == 16,- };let colours = mode.colour_channels();- if !(1..=56).contains(&channels) || channels < colours || !(1..=max_side).contains(&w) || !(1..=max_side).contains(&h) || !depth_ok {+ if !header_in_range(mode, depth, channels, (w, h), max_side) {return None;}let (wu, hu) = (usize::try_from(w).ok()?, usize::try_from(h).ok()?);diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rsindex 34934b911..5d3ad0644 100644--- a/crates/pdf/src/export.rs+++ b/crates/pdf/src/export.rs@@ -134,6 +134,25 @@ pub fn export_pdf_with_report(doc: &Document, cache: &Cache, opts: &PdfOptions)write::guard(|| export_pdf_with_report_inner(doc, cache, opts))}+/// Form fields (Buttons and Forms) and, for interactive PDF, video and sound; not in PDF/X+/// or PDF/A: this update comes after krilla's validator ran, and its NeedAppearances fields and+/// Screen annotations aren't allowed in PDF/A.+fn add_form_fields(bytes: &mut Vec<u8>, warnings: &mut Vec<String>, doc: &Document, sheets: &[Sheet], opts: &PdfOptions) {+ let fields = crate::forms::collect(doc, sheets);+ let media = if opts.media { crate::forms::collect_media(doc, sheets) } else { Vec::new() };+ if fields.is_empty() && media.is_empty() {+ return;+ }+ match opts.standard {+ Standard::PdfX4 => warnings.push("PDF/X-4: form fields and media were left out".into()),+ Standard::PdfA2b => warnings.push("PDF/A-2b: form fields and media were left out".into()),+ _ => match crate::forms::add_fields(&*bytes, &fields, &media) {+ Some(b) => *bytes = b,+ None => warnings.push("form fields and media couldn't be added to this PDF".into()),+ },+ }+}+fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions) -> Result<ExportReport> {let sheets = sheets(doc, opts)?;let warnings = Vec::new();@@ -235,23 +254,7 @@ fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions// group that got past it, with its page.crate::pdfx::cmyk_group_spaces(&mut bytes);}- // Form fields (Buttons and Forms) and, for interactive PDF, video and sound; not in PDF/X- // or PDF/A: this update comes after krilla's validator ran, and its NeedAppearances fields and- // Screen annotations aren't allowed in PDF/A.- let fields = crate::forms::collect(doc, &sheets);- let media = if opts.media { crate::forms::collect_media(doc, &sheets) } else { Vec::new() };- if !fields.is_empty() || !media.is_empty() {- if opts.standard == Standard::PdfX4 {- warnings.push("PDF/X-4: form fields and media were left out".into());- } else if opts.standard == Standard::PdfA2b {- warnings.push("PDF/A-2b: form fields and media were left out".into());- } else {- match crate::forms::add_fields(&bytes, &fields, &media) {- Some(b) => bytes = b,- None => warnings.push("form fields and media couldn't be added to this PDF".into()),- }- }- }+ add_form_fields(&mut bytes, &mut warnings, doc, &sheets, opts);if opts.standard == Standard::PdfX4 {// Output intent and PDF/X identification, then check the result.match crate::pdfx::make_pdfx4(&bytes, &title, created) {@@ -654,6 +657,27 @@ impl Exporter<'_> {self.doc.resolve_color(name, tint).map(|c| device(&c, self.rgb_only))}+ /// The parent pages' items on `layer` shown on page `pi` of spread `si`: the parent's bases+ /// first, then the parent.+ fn parent_items(&mut self, s: &mut Surface, si: usize, pi: usize, page: &designcraft_doc::Page, layer: &designcraft_doc::Layer, first: usize) {+ let doc = self.doc;+ for (ppi, ppage) in doc.shown_parent_pages(SpreadRef::Doc(si), pi) {+ let Some(parent) = doc.parents.get(ppi) else { continue };+ let Some(ppg) = parent.pages.get(ppage) else { continue };+ let dx = page.x - ppg.x;+ for it in &parent.items {+ if it.layer != layer.id || page.overridden.contains(&it.id) {+ continue;+ }+ // Parent items belong to the parent page they sit on.+ if parent.page_at_x(it.bounds().center().x) != Some(ppage) && parent.pages.len() > 1 {+ continue;+ }+ self.top_item(s, it, Affine::translate((dx, 0.0)), Some(first + pi), true);+ }+ }+ }+fn spread(&mut self, s: &mut Surface, si: usize) {let doc = self.doc;let Some(sp) = doc.spreads.get(si) else { return };@@ -663,24 +687,8 @@ impl Exporter<'_> {continue;}for (pi, page) in sp.pages.iter().enumerate() {- if !page.show_parent_items {- continue;- }- // The parent's bases first, then the parent.- for (ppi, ppage) in doc.shown_parent_pages(SpreadRef::Doc(si), pi) {- let Some(parent) = doc.parents.get(ppi) else { continue };- let Some(ppg) = parent.pages.get(ppage) else { continue };- let dx = page.x - ppg.x;- for it in &parent.items {- if it.layer != layer.id || page.overridden.contains(&it.id) {- continue;- }- // Parent items belong to the parent page they sit on.- if parent.page_at_x(it.bounds().center().x) != Some(ppage) && parent.pages.len() > 1 {- continue;- }- self.top_item(s, it, Affine::translate((dx, 0.0)), Some(first + pi), true);- }+ if page.show_parent_items {+ self.parent_items(s, si, pi, page, layer, first);}}for it in &sp.items {diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rsindex b239df164..522e245cb 100644--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@ -277,6 +277,26 @@ pub fn default_threads() -> u16 {}}+/// An item's fill under its content; an overprinting fill multiplies into what is beneath.+fn draw_body_fill(ctx: &mut RenderContext, f: &Frame, it: &Item, bp: &BezPath, xf: Affine) {+ if it.fill.is_none() {+ return;+ }+ let doc = f.doc;+ ctx.set_transform(f.view * xf);+ let op = overprints(f, &it.fill.swatch, it.fill.tint, it.fill.overprint);+ if op {+ ctx.push_layer(None, Some(BlendMode::new(Mix::Multiply, Compose::SrcOver)), None, None, None);+ }+ if set_fill_paint(ctx, doc, &it.fill, bp.bounding_box()) {+ ctx.fill_path(bp);+ }+ ctx.reset_paint_transform();+ if op {+ ctx.pop_layer();+ }+}+impl Renderer {pub fn new() -> Self {Self {@@ -627,22 +647,7 @@ impl Renderer {/// Fill, content and stroke of a leaf item (no opacity, blend or effects).pub(crate) fn draw_body(&mut self, ctx: &mut RenderContext, f: &Frame, it: &Item, bp: &BezPath, xf: Affine, page: ShownOn) {- let doc = f.doc;- // Fill.- if !it.fill.is_none() {- ctx.set_transform(f.view * xf);- let op = overprints(f, &it.fill.swatch, it.fill.tint, it.fill.overprint);- if op {- ctx.push_layer(None, Some(BlendMode::new(Mix::Multiply, Compose::SrcOver)), None, None, None);- }- if set_fill_paint(ctx, doc, &it.fill, bp.bounding_box()) {- ctx.fill_path(bp);- }- ctx.reset_paint_transform();- if op {- ctx.pop_layer();- }- }+ draw_body_fill(ctx, f, it, bp, xf);// Content.match &it.content {Content::Graphic(g) => {