Text wrap: Alpha Channel contour traced from the image, holes with Include Inside Edges, open gaps kept

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
moppeeerandClaude Opus 5.5 committed 2026-10-16 09:53:40 +02:00
1 parent c708b08033
commit afa015f113
25 files changed
+584 -49

No files matched your search

+1
View File
@@ -347,6 +347,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m
Newest first.
- 2026-10-16: Text Wrap › Contour › Alpha Channel follows a placed image's transparency, as InDesign's: the outline is traced from the image and follows it when it moves or is refitted; text keeps the open gaps between its parts, and enters enclosed holes with Include Inside Edges.
- **2026-10-14** · The Type tool draws a new text frame over a locked empty frame, as InDesign does, instead of turning the locked frame into a text frame. No readiness percentage change.
- **2026-10-14** · 100% black shows as pure black on screen by default, as InDesign's Appearance of Black does out of the box (Display All Blacks as Rich Black); Preferences › Appearance of Black › Display All Blacks Accurately still shows it as the dark grey it prints, and a saved choice is kept. No readiness percentage change.
- **2026-10-14** · Pathfinder keeps the frontmost object, as InDesign does: a photo placed over shapes and intersected with them shows through the shapes (it was dropped, and the shapes kept their black fill); Add, Exclude Overlap and Minus Back take the front object's fill too, Subtract still keeps the back one. No readiness percentage change.
+148 -36
View File
@@ -369,6 +369,96 @@ impl Contour {
}
(lo <= hi).then_some((lo - self.offset, hi + self.offset))
}
/// Occupied intervals across the whole line band, preserving gaps between parts of a
/// concave or compound outline. Project boundary edges and the filled middle slice: any
/// area that starts or ends inside the band is bounded by those projected edges.
fn band_spans(&self, y0: f64, y1: f64) -> Vec<(f64, f64)> {
let (low, high) = (y0 - self.offset, y1 + self.offset);
if !low.is_finite() || !high.is_finite() || high < low {
return self.band_extent(y0, y1).into_iter().collect();
}
let mut spans = rings_band_spans(&self.rings, low, high);
// Extremely fragmented imported paths use the conservative outer extent, bounding the
// work of subtracting intervals from every line. A traced 128-column mask stays below it.
if spans.len() > 128 {
return self.band_extent(y0, y1).into_iter().collect();
}
if !self.clip.is_empty() {
let clip = rings_band_spans(&self.clip, low, high);
let mut cut = Vec::new();
let (mut i, mut j) = (0, 0);
while let (Some(&(a, b)), Some(&(c, d))) = (spans.get(i), clip.get(j)) {
if a.max(c) < b.min(d) {
cut.push((a.max(c), b.min(d)));
}
if b < d {
i += 1;
} else {
j += 1;
}
}
spans = cut;
}
merge_spans(spans.into_iter().map(|(a, b)| (a - self.offset, b + self.offset)).collect())
}
}
fn merge_spans(mut spans: Vec<(f64, f64)>) -> Vec<(f64, f64)> {
spans.retain(|(a, b)| a.is_finite() && b.is_finite() && b - a > 1e-9);
spans.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut out: Vec<(f64, f64)> = Vec::new();
for (a, b) in spans {
if let Some(last) = out.last_mut().filter(|last| a <= last.1 + 1e-9) {
last.1 = last.1.max(b);
} else {
out.push((a, b));
}
}
out
}
fn rings_band_spans(rings: &[Vec<Point>], y0: f64, y1: f64) -> Vec<(f64, f64)> {
let mut spans = Vec::new();
let mut crossings = Vec::new();
let middle = y0 * 0.5 + y1 * 0.5;
for ring in rings {
let Some(&last) = ring.last() else { continue };
let mut a = last;
for &b in ring {
let dy = b.y - a.y;
if a.y.max(b.y) >= y0 && a.y.min(b.y) <= y1 {
let (t0, t1) = if dy.abs() < 1e-12 {
(0.0, 1.0)
} else {
let (u, v) = ((y0 - a.y) / dy, (y1 - a.y) / dy);
(u.min(v).clamp(0.0, 1.0), u.max(v).clamp(0.0, 1.0))
};
let (x0, x1) = (a.x + t0 * (b.x - a.x), a.x + t1 * (b.x - a.x));
spans.push((x0.min(x1), x0.max(x1)));
}
if (a.y <= middle && middle < b.y) || (b.y <= middle && middle < a.y) {
let x = a.x + (middle - a.y) / dy * (b.x - a.x);
if x.is_finite() {
crossings.push((x, if dy > 0.0 { 1i32 } else { -1 }));
}
}
a = b;
}
}
crossings.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut winding = 0i32;
let mut previous = None;
for (x, delta) in crossings {
if winding != 0
&& let Some(start) = previous
{
spans.push((start, x));
}
winding += delta;
previous = Some(x);
}
merge_spans(spans)
}
/// The closed polylines of `path` (after `to_inner`), flattened; None if it is empty or too detailed.
@@ -431,7 +521,13 @@ fn rings_band_extent(rings: &[Vec<Point>], y0: f64, y1: f64) -> Option<(f64, f64
/// The wrap exclusion of `other` (an item whose inner space maps to the spread by `xf`) for a
/// frame whose inner space is reached from the spread by `inv`. `left_page` places the object on
/// a left page (for the spine sides).
pub fn exclusion(other: &designcraft_doc::Item, xf: designcraft_geom::Affine, inv: designcraft_geom::Affine, left_page: bool) -> Exclusion {
pub fn exclusion(
doc: &Document,
other: &designcraft_doc::Item,
xf: designcraft_geom::Affine,
inv: designcraft_geom::Affine,
left_page: bool,
) -> Exclusion {
let o = other.wrap.offsets;
let b = if other.shape == designcraft_doc::Shape::Group {
(xf * other.xf.inverse()).transform_rect_bbox(other.bounds())
@@ -452,7 +548,7 @@ pub fn exclusion(other: &designcraft_doc::Item, xf: designcraft_geom::Affine, in
let contour = matches!(other.wrap.mode, WrapMode::BoundingBox | WrapMode::Contour).then_some(custom);
return Exclusion { rect, mode: other.wrap.mode, side, contour };
}
let contour = (other.wrap.mode == WrapMode::Contour && other.shape != designcraft_doc::Shape::Group).then(|| contour_path(other)).and_then(
let contour = (other.wrap.mode == WrapMode::Contour && other.shape != designcraft_doc::Shape::Group).then(|| contour_path(doc, other)).and_then(
|(path, frame)| {
let c = Contour::of(&path, inv * xf, other.wrap.offsets[0])?;
Some(match frame {
@@ -466,11 +562,26 @@ pub fn exclusion(other: &designcraft_doc::Item, xf: designcraft_geom::Affine, in
}
/// The outline a contour wrap follows, in the item's inner space, and for an outline taken from
/// the placed graphic, the frame path that clips it. Graphic frames follow their contour type;
/// detected edges, alpha channels and image paths need the image, so they follow the frame's path
/// (as other frames do).
fn contour_path(it: &designcraft_doc::Item) -> (designcraft_geom::BezPath, Option<designcraft_geom::BezPath>) {
/// the placed graphic, the frame path that clips it. Graphic frames follow their contour type. An
/// alpha channel follows the image's traced outline, placed where the graphic is now (so it
/// follows the image when it moves or is refitted); its transparent holes count only with Include
/// Inside Edges. Detected edges and image paths, and an alpha channel not traced (yet), follow the
/// frame's path (as other frames do).
fn contour_path(doc: &Document, it: &designcraft_doc::Item) -> (designcraft_geom::BezPath, Option<designcraft_geom::BezPath>) {
let frame = designcraft_geom::corners::apply(&it.path, &it.corners);
if it.wrap.contour == designcraft_doc::ContourType::AlphaChannel
&& let Some(g) = it.graphic()
&& let Some(o) = doc.alpha_outline(g.asset, it.wrap.alpha_threshold)
&& o.width > 0
&& o.height > 0
{
let to_graphic = designcraft_geom::Affine::scale_non_uniform(g.size.0 / f64::from(o.width), g.size.1 / f64::from(o.height));
let mut path = o.outer.to_bezpath();
if it.wrap.inside_edges {
path.extend(o.holes.to_bezpath().iter());
}
return (g.xf * to_graphic * path, Some(frame));
}
if it.wrap.contour == designcraft_doc::ContourType::BoundingBox
&& let Some(g) = it.graphic()
&& let Some(fb) = it.path.bounds()
@@ -573,7 +684,7 @@ pub fn frame_specs(doc: &Document, sid: StoryId) -> Vec<FrameSpec> {
.page_at_x(other.bounds().center().x)
.and_then(|pi| sp.pages.get(pi))
.is_some_and(|p| p.side == designcraft_doc::PageSide::Left);
let ex = exclusion(other, other.xf, inv, left);
let ex = exclusion(doc, other, other.xf, inv, left);
let reach = ex.rect.intersect(item.inner_bounds());
if reach.width() > 0.0 && reach.height() > 0.0 {
exclusions.push(ex);
@@ -2592,39 +2703,40 @@ fn free_slots(f: &FrameSpec, col: Rect, y0: f64, y1: f64, size: f64, rtl: bool)
let blocked = match ex.mode {
WrapMode::JumpToNextColumn if y1 > r.y0 && r.x0 < col.x1 && r.x1 > col.x0 => return vec![],
WrapMode::BoundingBox | WrapMode::Contour if overlaps_band => match &ex.contour {
Some(c) => c.band_extent(y0, y1),
None => Some((r.x0, r.x1)),
Some(c) => c.band_spans(y0, y1),
None => vec![(r.x0, r.x1)],
},
_ => None,
_ => Vec::new(),
};
let Some((a, b)) = blocked.filter(|&(a, b)| a < col.x1 && b > col.x0) else { continue };
cut = true;
// One-sided wraps also block the column on the other side of the object.
let text_left = match ex.side {
WrapSide::LeftSide => Some(true),
WrapSide::RightSide => Some(false),
WrapSide::LargestArea => Some(r.x0 - col.x0 >= col.x1 - r.x1),
WrapSide::BothSides | WrapSide::TowardsSpine | WrapSide::AwayFromSpine => None,
};
let (a, b) = match text_left {
Some(true) => (a, b.max(col.x1)),
Some(false) => (a.min(col.x0), b),
None => (a, b),
};
let mut next = Vec::with_capacity(free.len() + 1);
for (fa, fb) in free {
if b <= fa || a >= fb {
next.push((fa, fb));
continue;
}
if a > fa {
next.push((fa, a));
}
if b < fb {
next.push((b, fb));
for (a, b) in blocked.into_iter().filter(|&(a, b)| a < col.x1 && b > col.x0) {
cut = true;
// One-sided wraps also block the column on the other side of the object.
let text_left = match ex.side {
WrapSide::LeftSide => Some(true),
WrapSide::RightSide => Some(false),
WrapSide::LargestArea => Some(r.x0 - col.x0 >= col.x1 - r.x1),
WrapSide::BothSides | WrapSide::TowardsSpine | WrapSide::AwayFromSpine => None,
};
let (a, b) = match text_left {
Some(true) => (a, b.max(col.x1)),
Some(false) => (a.min(col.x0), b),
None => (a, b),
};
let mut next = Vec::with_capacity(free.len() + 1);
for (fa, fb) in free {
if b <= fa || a >= fb {
next.push((fa, fb));
continue;
}
if a > fa {
next.push((fa, a));
}
if b < fb {
next.push((b, fb));
}
}
free = next;
}
free = next;
}
if !cut {
return vec![(col.x0, col.x1)];
+27
View File
@@ -4,6 +4,33 @@ use designcraft_geom::Rect;
use super::*;
#[test]
fn contour_intervals_preserve_the_gap_between_legs() {
let mut path = designcraft_geom::BezPath::new();
path.move_to((0.0, 0.0));
for p in [(40.0, 0.0), (40.0, 100.0), (30.0, 100.0), (30.0, 20.0), (10.0, 20.0), (10.0, 100.0), (0.0, 100.0)] {
path.line_to(p);
}
path.close_path();
let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 3.0).unwrap();
assert_eq!(c.band_spans(50.0, 60.0), vec![(-3.0, 13.0), (27.0, 43.0)]);
assert_eq!(c.band_spans(5.0, 15.0), vec![(-3.0, 43.0)]);
let frame = designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 35.0, 100.0)).to_bezpath();
assert_eq!(c.within(&frame, designcraft_geom::Affine::IDENTITY).band_spans(50.0, 60.0), vec![(-3.0, 13.0), (27.0, 38.0)]);
}
#[test]
fn contour_intervals_cover_the_whole_slanted_line_band() {
let mut path = designcraft_geom::BezPath::new();
path.move_to((0.0, 0.0));
for p in [(2.0, 0.0), (12.0, 10.0), (10.0, 10.0)] {
path.line_to(p);
}
path.close_path();
let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 0.0).unwrap();
assert_eq!(c.band_spans(0.0, 10.0), vec![(0.0, 12.0)]);
}
const LOREM: &str = "Typography is the art and technique of arranging type to make written language legible, readable and appealing when displayed. \
The arrangement of type involves selecting typefaces, point sizes, line lengths, line spacing, and letter spacing, and adjusting the space between pairs of letters.";
+1
View File
@@ -160,6 +160,7 @@ impl Document {
modified: 0,
next_id: 0,
font_scope: 0,
alpha_outlines: Vec::new(),
};
let lid = LayerId(d.alloc());
d.layers.push(Layer {
+25 -1
View File
@@ -501,7 +501,7 @@ pub enum ContourType {
}
/// Text Wrap panel settings.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct TextWrap {
pub mode: WrapMode,
@@ -515,6 +515,30 @@ pub struct TextWrap {
/// item transforms it with the path; other path edits keep it as it is.
#[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<PathData>,
/// Contour Options › Include Inside Edges: an Alpha Channel contour also lets text into the
/// transparent holes it encloses (off: holes are blocked with the shape around them).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub inside_edges: bool,
/// Alpha Channel contour: pixels more opaque than this (0..254) count as the image.
pub alpha_threshold: u8,
}
/// InDesign's default alpha threshold for contour wraps.
pub const DEFAULT_ALPHA_THRESHOLD: u8 = 25;
impl Default for TextWrap {
fn default() -> Self {
TextWrap {
mode: WrapMode::default(),
offsets: [0.0; 4],
invert: false,
side: WrapSide::default(),
contour: ContourType::default(),
path: None,
inside_edges: false,
alpha_threshold: DEFAULT_ALPHA_THRESHOLD,
}
}
}
/// Frame fitting options (Object → Fitting → Frame Fitting Options).
+23
View File
@@ -448,6 +448,21 @@ pub struct Asset {
pub page: u32,
}
/// The outline of a raster image's visible pixels (Text Wrap › Contour › Alpha Channel), in the
/// image's pixel space (0..width, 0..height). Derived from the image, so not saved: the engine
/// traces it again when a document opens.
#[derive(Clone, Debug, PartialEq)]
pub struct AlphaOutline {
pub asset: AssetId,
pub threshold: u8,
pub width: u32,
pub height: u32,
/// The outer boundaries of the visible areas.
pub outer: designcraft_geom::PathData,
/// The boundaries of transparent holes those areas enclose (wound the other way).
pub holes: designcraft_geom::PathData,
}
impl Asset {
/// A raster image (PNG, JPEG, GIF, WebP, TIFF, BMP, PSD), as opposed to a PDF, EPS or SVG.
pub fn is_raster(&self) -> bool {
@@ -501,6 +516,9 @@ pub struct Document {
pub sections: Vec<Section>,
#[serde(default)]
pub assets: BTreeMap<AssetId, Arc<Asset>>,
/// Alpha Channel contour outlines of placed images (see [`AlphaOutline`]). Not saved.
#[serde(skip)]
pub alpha_outlines: Vec<Arc<AlphaOutline>>,
/// Hyperlinks (Window → Interactive → Hyperlinks).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub hyperlinks: Vec<Hyperlink>,
@@ -695,6 +713,11 @@ impl Document {
if sec.include_prefix { format!("{}{}", sec.prefix, num) } else { num }
}
/// The Alpha Channel outline of `asset` at `threshold`, once the engine has traced it.
pub fn alpha_outline(&self, asset: AssetId, threshold: u8) -> Option<&AlphaOutline> {
self.alpha_outlines.iter().map(|o| &**o).find(|o| o.asset == asset && o.threshold == threshold)
}
pub fn layer(&self, id: LayerId) -> Option<&Layer> {
self.layers.iter().find(|l| l.id == id)
}
+285
View File
@@ -0,0 +1,285 @@
//! Text Wrap › Contour › Alpha Channel: the outline of a placed raster's visible pixels.
//!
//! The outline is traced once per image and threshold, in the image's pixel space, and kept on
//! the document ([`designcraft_doc::AlphaOutline`]). Composition maps it through the graphic's
//! current transform, so it follows the image when it is moved, scaled or refitted.
use std::sync::Arc;
use designcraft_doc::{AlphaOutline, AssetId, ContourType, Document, WrapMode};
use designcraft_geom::{BezPath, PathData, Point};
/// Images larger than this many pixels aren't traced (their contour follows the frame).
const MAX_PIXELS: u64 = 40_000_000;
/// The finest grid an outline is traced on; coarser grids when the outline would be too long.
const MAX_GRID: u32 = 256;
/// Boundary edges an outline may have.
const MAX_EDGES: usize = 1 << 16;
/// Trace the outlines new Alpha Channel contours need and drop the ones nothing uses. Cheap when
/// nothing changed: tracing happens only for an image and threshold not seen before.
pub(crate) fn sync(doc: &mut Document) {
let mut wanted: Vec<(AssetId, u8)> = Vec::new();
for sp in doc.spreads.iter().chain(doc.parents.iter()) {
for it in &sp.items {
if it.wrap.mode == WrapMode::Contour
&& it.wrap.contour == ContourType::AlphaChannel
&& let Some(g) = it.graphic()
&& !wanted.contains(&(g.asset, it.wrap.alpha_threshold))
{
wanted.push((g.asset, it.wrap.alpha_threshold));
}
}
}
if wanted.is_empty() && doc.alpha_outlines.is_empty() {
return;
}
doc.alpha_outlines.retain(|o| wanted.contains(&(o.asset, o.threshold)) && doc.assets.contains_key(&o.asset));
for (asset, threshold) in wanted {
if doc.alpha_outline(asset, threshold).is_some() {
continue;
}
let Some(a) = doc.assets.get(&asset).filter(|a| a.is_raster()) else { continue };
if let Some(o) = trace(&a.data, asset, threshold) {
doc.alpha_outlines.push(Arc::new(o));
}
}
}
/// The outline of the pixels of `data` more opaque than `threshold`. None for an image that
/// can't be read, is too large, or has no transparency (its contour is its rectangle).
pub(crate) fn trace(data: &[u8], asset: AssetId, threshold: u8) -> Option<AlphaOutline> {
let (w, h) = designcraft_images::pixel_size(data)?;
if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS {
return None;
}
let img = designcraft_images::decode_rgba(data)?;
if img.width() != w || img.height() != h {
return None;
}
let mut grid = MAX_GRID;
while grid >= 16 {
let (cols, rows) = (w.min(grid), h.min(grid));
let (mask, transparent) = occupancy(img.as_raw(), w, h, cols, rows, threshold);
if !transparent {
return None;
}
if let Some((outer, holes)) = rings(&mask, cols as usize, rows as usize) {
let (sx, sy) = (f64::from(w) / f64::from(cols), f64::from(h) / f64::from(rows));
let path = |rings: &[Vec<(i32, i32)>]| {
let mut p = BezPath::new();
for ring in rings {
let mut pts = ring.iter().map(|&(x, y)| Point::new(f64::from(x) * sx, f64::from(y) * sy));
let Some(first) = pts.next() else { continue };
p.move_to(first);
for q in pts {
p.line_to(q);
}
p.close_path();
}
PathData::from_bezpath(&p)
};
return Some(AlphaOutline { asset, threshold, width: w, height: h, outer: path(&outer), holes: path(&holes) });
}
grid /= 2;
}
None
}
/// Which cells of a `cols` × `rows` grid hold a pixel of the `w` × `h` RGBA image `rgba` more
/// opaque than `threshold` (a cell is visible when any of its pixels is), and whether the image
/// has any transparency.
fn occupancy(rgba: &[u8], w: u32, h: u32, cols: u32, rows: u32, threshold: u8) -> (Vec<bool>, bool) {
let mut mask = vec![false; (cols as usize) * (rows as usize)];
let mut transparent = false;
for (i, px) in rgba.chunks_exact(4).enumerate() {
let alpha = px[3];
transparent |= alpha < 255;
if alpha > threshold {
let (x, y) = ((i as u64) % u64::from(w), (i as u64) / u64::from(w));
let (gx, gy) = (x * u64::from(cols) / u64::from(w), y * u64::from(rows) / u64::from(h));
if let Some(c) = mask.get_mut((gy * u64::from(cols) + gx) as usize) {
*c = true;
}
}
}
(mask, transparent)
}
/// The closed boundaries of the visible cells, split into outer boundaries and the boundaries of
/// holes (by winding: each boundary keeps the visible cells on the same side). None when the
/// outline would have more than [`MAX_EDGES`] edges.
#[allow(clippy::type_complexity)]
fn rings(mask: &[bool], cols: usize, rows: usize) -> Option<(Vec<Vec<(i32, i32)>>, Vec<Vec<(i32, i32)>>)> {
use std::collections::BTreeMap;
let visible = |x: i32, y: i32| {
x >= 0 && y >= 0 && (x as usize) < cols && (y as usize) < rows && mask.get(y as usize * cols + x as usize).copied().unwrap_or(false)
};
let mut edges: BTreeMap<(i32, i32), Vec<(i32, i32)>> = BTreeMap::new();
let mut count = 0usize;
for y in 0..rows as i32 {
for x in 0..cols as i32 {
if !visible(x, y) {
continue;
}
for (open, a, b) in [
(!visible(x, y - 1), (x, y), (x + 1, y)),
(!visible(x + 1, y), (x + 1, y), (x + 1, y + 1)),
(!visible(x, y + 1), (x + 1, y + 1), (x, y + 1)),
(!visible(x - 1, y), (x, y + 1), (x, y)),
] {
if open {
count += 1;
if count > MAX_EDGES {
return None;
}
edges.entry(a).or_default().push(b);
}
}
}
}
let (mut outer, mut holes) = (Vec::new(), Vec::new());
while let Some((&start, _)) = edges.first_key_value() {
let mut ring = vec![start];
let mut at = start;
for _ in 0..=MAX_EDGES {
let next = edges.get_mut(&at).and_then(Vec::pop)?;
if edges.get(&at).is_some_and(Vec::is_empty) {
edges.remove(&at);
}
// Drop the middle of straight runs.
if let [.., a, b] = ring[..]
&& (b.0 - a.0) * (next.1 - b.1) == (b.1 - a.1) * (next.0 - b.0)
{
ring.pop();
}
if next == start {
break;
}
ring.push(next);
at = next;
}
// Shoelace in y-down space: positive for outer boundaries, negative for holes.
let area: i64 = ring
.iter()
.zip(ring.iter().cycle().skip(1))
.map(|(&(x0, y0), &(x1, y1))| i64::from(x0) * i64::from(y1) - i64::from(x1) * i64::from(y0))
.sum();
if ring.len() >= 3 {
if area > 0 { outer.push(ring) } else { holes.push(ring) }
}
}
Some((outer, holes))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use crate::Session;
/// A 64 × 64 PNG: visible where `on(x, y)`.
fn png(on: impl Fn(usize, usize) -> bool) -> Vec<u8> {
let mut pixels = vec![0; 64 * 64 * 4];
for y in 0..64 {
for x in 0..64 {
let i = (y * 64 + x) * 4;
pixels[i] = 120;
pixels[i + 3] = if on(x, y) { 255 } else { 0 };
}
}
designcraft_render::Rendered { width: 64, height: 64, pixels }.to_png()
}
#[test]
fn traces_outer_boundaries_and_holes_apart() {
// A ring: a square with a square hole.
let data = png(|x, y| (8..56).contains(&x) && (8..56).contains(&y) && !((24..40).contains(&x) && (24..40).contains(&y)));
let o = trace(&data, AssetId(1), 25).unwrap();
assert_eq!((o.width, o.height), (64, 64));
assert_eq!((o.outer.subpaths.len(), o.holes.subpaths.len()), (1, 1));
let (a, b) = (o.outer.bounds().unwrap(), o.holes.bounds().unwrap());
assert_eq!((a.x0, a.y0, a.x1, a.y1), (8.0, 8.0, 56.0, 56.0));
assert_eq!((b.x0, b.y0, b.x1, b.y1), (24.0, 24.0, 40.0, 40.0));
// An opaque image has no alpha outline.
assert!(trace(&png(|_, _| true), AssetId(1), 25).is_none());
}
#[test]
fn an_alpha_channel_contour_is_traced_when_set_and_kept_out_of_the_saved_file() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let data = png(|x, _| (16..48).contains(&x));
let id = s
.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128}))
.unwrap()["id"]
.clone();
assert!(s.doc().unwrap().doc.alpha_outlines.is_empty());
s.execute("object.textWrap", &json!({"ids": [id], "mode": "contour", "contour": "alphaChannel"})).unwrap();
let d = &s.doc().unwrap().doc;
assert_eq!(d.alpha_outlines.len(), 1);
// Saved and opened again: traced again on open.
let bytes = crate::cmd::file::to_bytes(d);
let back = crate::cmd::file::from_bytes(&bytes).unwrap();
assert!(back.alpha_outlines.is_empty(), "not saved");
let st = crate::DocState::new(back, None);
assert_eq!(st.doc.alpha_outlines.len(), 1, "traced on open");
// Wrap off: the outline goes.
s.execute("object.textWrap", &json!({"ids": [id], "mode": "none"})).unwrap();
assert!(s.doc().unwrap().doc.alpha_outlines.is_empty());
}
/// An image placed 128 pt wide at (100, 100) (2 pt per pixel), its wrap a contour with no
/// offset, and a caption frame at `caption` with 8 pt "Hi".
fn page(data: &[u8], caption: [f64; 4]) -> (Session, Value, u64) {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let image = s
.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(data), "name": "cut.png", "x": 100, "y": 100, "width": 128}))
.unwrap()["id"]
.clone();
let c = s.execute("frame.create", &json!({"rect": caption, "content": "text", "text": "Hi"})).unwrap();
s.execute("selection.set", &json!({"ids": [c["id"]]})).unwrap();
s.execute("type.char", &json!({"size": 8})).unwrap();
s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "offset": 0})).unwrap();
(s, image, c["story"].as_u64().unwrap())
}
fn overset(s: &Session, story: u64) -> bool {
s.cache.get(&s.doc().unwrap().doc, designcraft_doc::StoryId(story), None).is_overset()
}
use serde_json::Value;
/// A caption fits between two legs of a cutout, and the contour follows the image when it's
/// moved within its frame (it isn't a boundary stored where it was traced).
#[test]
fn an_alpha_channel_contour_keeps_gaps_open_and_follows_the_image() {
// Legs at pixels 8..20 and 44..56: 116..140 and 188..212 on the page.
let (mut s, image, story) = page(&png(|x, _| (8..20).contains(&x) || (44..56).contains(&x)), [150.0, 120.0, 178.0, 170.0]);
assert!(overset(&s, story), "the frame's contour covers the gap");
s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap();
assert!(!overset(&s, story), "the gap between the legs stays open");
// The graphic moved 30 pt right within its frame: its left leg now covers the caption.
s.execute("selection.set", &json!({"ids": [image], "content": true})).unwrap();
s.execute("transform.move", &json!({"dx": 30, "dy": 0})).unwrap();
assert!(overset(&s, story), "the contour moved with the image");
s.execute("edit.undo", &json!({})).unwrap();
assert!(!overset(&s, story));
}
/// A hole enclosed by the image stays blocked unless Include Inside Edges is on.
#[test]
fn holes_are_blocked_unless_inside_edges_are_included() {
// A ring: outer 116..212, hole 148..180 on the page.
let ring = png(|x, y| (8..56).contains(&x) && (8..56).contains(&y) && !((24..40).contains(&x) && (24..40).contains(&y)));
let (mut s, image, story) = page(&ring, [152.0, 152.0, 176.0, 176.0]);
s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap();
assert!(overset(&s, story), "the hole is blocked with the ring around it");
s.execute("object.textWrap", &json!({"ids": [image], "insideEdges": true})).unwrap();
assert!(!overset(&s, story), "Include Inside Edges lets text into the hole");
for bad in [json!({"ids": [image], "threshold": 255}), json!({"ids": [image], "insideEdges": 1})] {
assert!(s.execute("object.textWrap", &bad).is_err());
}
}
}
+1
View File
@@ -1,5 +1,6 @@
//! The command registry. Ids follow InDesign's menu structure.
pub(crate) mod alpha_wrap;
mod anchored;
pub mod anchors;
mod articles;
+19 -5
View File
@@ -584,7 +584,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Text Wrap",
["Window"],
Some("Cmd+Alt+W"),
"{mode?: none|boundingBox|contour|jumpObject|jumpToNextColumn (boundingBox when absent, unless side or contour is given: then unchanged), offset?: number|[t,l,b,r], invert?: bool, side?: bothSides|leftSide|rightSide|towardsSpine|awayFromSpine|largestArea, contour?: boundingBox|graphicFrame|sameAsClipping, ids?}; offset or contour drops an imported custom wrap boundary",
"{mode?: none|boundingBox|contour|jumpObject|jumpToNextColumn (boundingBox when absent, unless side, contour, insideEdges or threshold is given: then unchanged), offset?: number|[t,l,b,r], invert?: bool, side?: bothSides|leftSide|rightSide|towardsSpine|awayFromSpine|largestArea, contour?: boundingBox|graphicFrame|sameAsClipping|alphaChannel, insideEdges?: bool (alphaChannel: text may enter transparent holes), threshold?: 0..254 (alphaChannel: pixels more opaque count; default 25), ids?}; offset or contour drops an imported custom wrap boundary",
has_selection,
text_wrap
),
@@ -1523,16 +1523,24 @@ fn text_wrap(s: &mut Session, p: &Value) -> Result<Value> {
Some(v) => Some(serde_json::from_value(v.clone()).map_err(|_| bad("object.textWrap", "unknown side"))?),
None => None,
};
// Detected edges, alpha channels and image paths need the image's pixels or paths, which
// composition doesn't read; those types aren't offered.
// Detected edges and image paths need the image's own analysis or paths, which aren't read;
// those types aren't offered. An alpha channel is traced from the image's pixels.
let contour = match p.get("contour").map(|v| serde_json::from_value::<ContourType>(v.clone())) {
Some(Ok(c @ (ContourType::BoundingBox | ContourType::GraphicFrame | ContourType::SameAsClipping))) => Some(c),
Some(Ok(c @ (ContourType::BoundingBox | ContourType::GraphicFrame | ContourType::SameAsClipping | ContourType::AlphaChannel))) => Some(c),
Some(_) => return Err(bad("object.textWrap", "unsupported contour type")),
None => None,
};
let inside_edges = match p.get("insideEdges") {
None => None,
Some(v) => Some(v.as_bool().ok_or_else(|| bad("object.textWrap", "`insideEdges` is true or false"))?),
};
let threshold = match p.get("threshold") {
None => None,
Some(v) => Some(v.as_u64().filter(|t| *t <= 254).ok_or_else(|| bad("object.textWrap", "`threshold` is 0..254"))? as u8),
};
let mode: Option<WrapMode> = match p.get("mode") {
Some(v) => Some(serde_json::from_value(v.clone()).map_err(|_| bad("object.textWrap", "unknown mode"))?),
None if side.is_some() || contour.is_some() => None,
None if side.is_some() || contour.is_some() || inside_edges.is_some() || threshold.is_some() => None,
None => Some(WrapMode::BoundingBox),
};
let off = match p.get("offset") {
@@ -1560,6 +1568,12 @@ fn text_wrap(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(c) = contour {
i.wrap.contour = c;
}
if let Some(v) = inside_edges {
i.wrap.inside_edges = v;
}
if let Some(t) = threshold {
i.wrap.alpha_threshold = t;
}
// A custom boundary has the offsets built in and replaces the contour, so setting
// either one rebuilds the wrap from the frame.
if off.is_some() || contour.is_some() {
+4 -1
View File
@@ -131,7 +131,9 @@ impl Drop for FontScope {
static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
impl DocState {
pub fn new(doc: Document, path: Option<String>) -> Self {
pub fn new(mut doc: Document, path: Option<String>) -> Self {
// Alpha Channel contour outlines aren't saved: trace them for the document as opened.
crate::cmd::alpha_wrap::sync(&mut doc);
let active_layer = doc.default_layer();
let doc = Arc::new(doc);
DocState {
@@ -589,6 +591,7 @@ impl Session {
let r = f(&mut doc, &mut sel)?;
crate::cmd::sync_placeholders(&mut doc);
crate::cmd::flex::sync(&mut doc);
crate::cmd::alpha_wrap::sync(&mut doc);
doc.sync_endnote_story();
st.doc = Arc::new(doc);
st.selection = sel;
-1
View File
@@ -1156,7 +1156,6 @@ fn a_line_fits_when_its_baseline_does() {
assert!(overset(&mut s, 50.0), "a baseline below the frame still oversets the line");
}
/// Beside an object with text on both sides, every line stays within its segment, however many
/// lines the paragraph needs (the breaker's segment estimate can run out on narrow segments; a
/// line it set for the whole column ran across the object).
+5 -1
View File
@@ -1852,7 +1852,11 @@ impl<'a> Ex<'a> {
.attr("Right", num(w.offsets[3]))])
.collect(),
)
.child(El::new("ContourOption").attr("ContourType", names::contour_type_out(w.contour)).attr("IncludeInsideEdges", "false")),
.child(
El::new("ContourOption")
.attr("ContourType", names::contour_type_out(w.contour))
.attr("IncludeInsideEdges", if w.inside_edges { "true" } else { "false" }),
),
);
match &it.content {
Content::Group { items } => {
+2
View File
@@ -2429,6 +2429,7 @@ impl<'r> Importer<'r> {
invert: w.get("Inverse") == Some("true"),
side: names::wrap_side_in(w.get("TextWrapSide").unwrap_or("BothSides")),
contour: names::contour_type_in(w.find("ContourOption").and_then(|c| c.get("ContourType")).unwrap_or("SameAsClipping")),
inside_edges: w.find("ContourOption").and_then(|c| c.get("IncludeInsideEdges")) == Some("true"),
..TextWrap::default()
};
if let Some(o) = w.prop_el("TextWrapOffset") {
@@ -2739,6 +2740,7 @@ impl<'r> Importer<'r> {
modified: 0,
next_id: self.next_id,
font_scope: 0,
alpha_outlines: Vec::new(),
};
Ok(d)
}
+7
View File
@@ -2627,6 +2627,13 @@ fn imports_and_round_trips_text_wrap_side_and_contour_type() {
let back = import_idml(&export_idml(&d)).unwrap();
let w = back.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap().wrap.clone();
assert_eq!((w.side, w.contour), (designcraft_doc::WrapSide::AwayFromSpine, designcraft_doc::ContourType::DetectEdges));
assert!(!w.inside_edges);
// An Alpha Channel contour with Include Inside Edges.
d.item_mut(id).unwrap().wrap.contour = designcraft_doc::ContourType::AlphaChannel;
d.item_mut(id).unwrap().wrap.inside_edges = true;
let back = import_idml(&export_idml(&d)).unwrap();
let w = back.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap().wrap.clone();
assert_eq!((w.contour, w.inside_edges), (designcraft_doc::ContourType::AlphaChannel, true));
}
/// One single-column text frame at (0, 0)-(300, 200) on page 1, beside a 100 pt wide rectangle
+3
View File
@@ -113,6 +113,7 @@ fn same_document(old: &Document, new: &Document) -> bool {
modified,
next_id,
font_scope,
alpha_outlines,
} = new;
let same_spreads = |a: &[std::sync::Arc<designcraft_doc::Spread>], b: &[std::sync::Arc<designcraft_doc::Spread>]| {
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| std::sync::Arc::ptr_eq(a, b))
@@ -124,6 +125,8 @@ fn same_document(old: &Document, new: &Document) -> bool {
&& old.stories.iter().zip(stories).all(|((a, x), (b, y))| a == b && std::sync::Arc::ptr_eq(x, y))
&& old.assets.len() == assets.len()
&& old.assets.iter().zip(assets).all(|((a, x), (b, y))| a == b && std::sync::Arc::ptr_eq(x, y))
&& old.alpha_outlines.len() == alpha_outlines.len()
&& old.alpha_outlines.iter().zip(alpha_outlines).all(|(a, b)| std::sync::Arc::ptr_eq(a, b))
&& old.title == *title
&& old.settings == *settings
&& old.layers == *layers
+5
View File
@@ -58,6 +58,11 @@ const TABLE: &[(&str, [&str; 5])] = &[
("Cut", ["Ausschneiden", "Couper", "Cortar", "カット", "剪切"]),
("Copy", ["Kopieren", "Copier", "Copiar", "コピー", "复制"]),
("Paste", ["Einfügen", "Coller", "Pegar", "ペースト", "粘贴"]),
(
"Include Inside Edges",
["Innenkanten einschließen", "Inclure les bords intérieurs", "Incluir bordes interiores", "内側エッジを含める", "包含内边缘"],
),
("Alpha Channel", ["Alphakanal", "Couche alpha", "Canal alfa", "アルファチャンネル", "Alpha 通道"]),
(
"Bulleted & Numbered Lists",
[
+1
View File
@@ -30,6 +30,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Cut", "قص"),
("Copy", "نسخ"),
("Paste", "لصق"),
("Include Inside Edges", "تضمين الحواف الداخلية"),
("Bulleted & Numbered Lists", "القوائم ذات التعداد النقطي والرقمي"),
("Current Page Number", "رقم الصفحة الحالية"),
("Apply Color (,)", "تطبيق اللون (,)"),
+1
View File
@@ -30,6 +30,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Cut", "Ausschneiden"),
("Copy", "Kopieren"),
("Paste", "Einfügen"),
("Include Inside Edges", "Innenkanten einschließen"),
("Clear", "Löschen"),
("Duplicate", "Duplizieren"),
("Select All", "Alles auswählen"),
+2
View File
@@ -28,6 +28,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Cut", "Taglia"),
("Copy", "Copia"),
("Paste", "Incolla"),
("Include Inside Edges", "Includi bordi interni"),
("Alpha Channel", "Canale alfa"),
("Bulleted & Numbered Lists", "Elenchi puntati e numerati"),
("Current Page Number", "Numero di pagina corrente"),
("Apply Color (,)", "Applica colore (,)"),
+1
View File
@@ -30,6 +30,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Cut", "カット"),
("Copy", "コピー"),
("Paste", "ペースト"),
("Include Inside Edges", "内側エッジを含める"),
("Bulleted & Numbered Lists", "箇条書き"),
("Apply Color (,)", "カラーを適用 (,)"),
("Apply Gradient (.)", "グラデーションを適用 (.)"),
+1
View File
@@ -31,6 +31,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Cut", "ამოჭრა"),
("Copy", "კოპირება"),
("Paste", "ჩასმა"),
("Include Inside Edges", "შიდა კიდეების ჩართვა"),
("Reverse Path", "ტრაექტორიის შებრუნება"),
("Set Anchor", "საყრდენი წერტილის დაყენება"),
("Clear", "გასუფთავება"),
+2
View File
@@ -31,6 +31,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Cut", "Recortar"),
("Copy", "Copiar"),
("Paste", "Colar"),
("Include Inside Edges", "Incluir bordas internas"),
("Alpha Channel", "Canal alfa"),
("Bulleted & Numbered Lists", "Listas com marcadores e numeradas"),
("Show Hidden Characters", "Mostrar caracteres ocultos"),
("Current Page Number", "Número da página atual"),
+2
View File
@@ -31,6 +31,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Cut", "Вирізати"),
("Copy", "Копіювати"),
("Paste", "Вставити"),
("Include Inside Edges", "Включити внутрішні краї"),
("Alpha Channel", "Альфа-канал"),
("Bulleted & Numbered Lists", "Марковані й нумеровані списки"),
("Current Page Number", "Номер поточної сторінки"),
("Apply Color (,)", "Застосувати колір (,)"),
+3
View File
@@ -51,6 +51,8 @@ pub struct SelInfo {
pub wrap_offsets: [f64; 4],
pub wrap_side: String,
pub wrap_contour: String,
/// Contour Options › Include Inside Edges (an Alpha Channel contour).
pub wrap_inside_edges: bool,
pub locked: bool,
}
@@ -161,6 +163,7 @@ pub fn sel_info(app: &DesignApp) -> Option<SelInfo> {
wrap_offsets: first.wrap.offsets,
wrap_side: serde_json::to_value(first.wrap.side).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(),
wrap_contour: serde_json::to_value(first.wrap.contour).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(),
wrap_inside_edges: first.wrap.inside_edges,
locked: first.locked,
})
}
+15 -4
View File
@@ -1903,11 +1903,22 @@ pub fn wrap_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
];
wrap_combo(app, ui, "wrap_side", "Wrap To", &sides, &[], &i.wrap_side, "side");
if i.wrap == "contour" && i.is_graphic {
// Detected edges, alpha channels and image paths aren't offered: composition doesn't read
// the image. An imported one shows by name and wraps around the frame.
let types = [("boundingBox", "Bounding Box"), ("graphicFrame", "Graphic Frame"), ("sameAsClipping", "Same as Clipping")];
let shown_only = [("detectEdges", "Detect Edges"), ("alphaChannel", "Alpha Channel"), ("photoshopPath", "Photoshop Path")];
// Detected edges and image paths aren't offered: they need the image's own analysis or
// paths. An imported one shows by name and wraps around the frame.
let types = [
("boundingBox", "Bounding Box"),
("alphaChannel", "Alpha Channel"),
("graphicFrame", "Graphic Frame"),
("sameAsClipping", "Same as Clipping"),
];
let shown_only = [("detectEdges", "Detect Edges"), ("photoshopPath", "Photoshop Path")];
wrap_combo(app, ui, "wrap_contour", "Contour Type", &types, &shown_only, &i.wrap_contour, "contour");
if i.wrap_contour == "alphaChannel" {
let mut inside = i.wrap_inside_edges;
if widgets::checkbox(ui, &mut inside, crate::i18n::tr(&app.ui.language, "Include Inside Edges")).changed() {
let _ = app.run("object.textWrap", json!({"insideEdges": inside}));
}
}
}
}