mirror of
https://github.com/storytold/designcraft.git
synced 2026-11-15 23:02:32 +00:00
Merge #1084 (Alpha Channel text wrap) into main
This commit is contained in:
commit
1fbb7e86b0
21 files changed
+699
-58
No files matched your search
+153
-39
@@ -431,6 +431,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.
|
||||
@@ -493,19 +583,19 @@ 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: &Item, xf: Affine, inv: Affine, left_page: bool) -> Exclusion {
|
||||
pub fn exclusion(doc: &Document, other: &Item, xf: Affine, inv: Affine, left_page: bool) -> Exclusion {
|
||||
let group = other.shape == designcraft_doc::Shape::Group;
|
||||
let b =
|
||||
if group { (xf * other.xf.inverse()).transform_rect_bbox(other.bounds()) } else { other.path.transformed(xf).bounds().unwrap_or(Rect::ZERO) };
|
||||
wrap_exclusion(&other.wrap, b, || (!group).then(|| contour_path(other, other.wrap.contour)), xf, inv, left_page)
|
||||
wrap_exclusion(&other.wrap, b, || (!group).then(|| contour_path(doc, other, &other.wrap)), xf, inv, left_page)
|
||||
}
|
||||
|
||||
/// The wrap exclusion of the graphic placed in frame `it` (arguments as for [`exclusion`]): around
|
||||
/// the part of the graphic the frame shows. None if there is no graphic or it is not shown.
|
||||
pub fn graphic_exclusion(it: &Item, xf: Affine, inv: Affine, left_page: bool) -> Option<Exclusion> {
|
||||
pub fn graphic_exclusion(doc: &Document, it: &Item, xf: Affine, inv: Affine, left_page: bool) -> Option<Exclusion> {
|
||||
let g = it.graphic()?;
|
||||
let shown = g.shown_bounds(it.inner_bounds())?;
|
||||
Some(wrap_exclusion(&g.wrap, xf.transform_rect_bbox(shown), || Some(contour_path(it, g.wrap.contour)), xf, inv, left_page))
|
||||
Some(wrap_exclusion(&g.wrap, xf.transform_rect_bbox(shown), || Some(contour_path(doc, it, &g.wrap)), xf, inv, left_page))
|
||||
}
|
||||
|
||||
/// The exclusion of `wrap` around an object with spread-space bounds `b`; `outline` gives its
|
||||
@@ -549,8 +639,22 @@ fn wrap_exclusion(
|
||||
/// follows the part of the placed graphic the frame shows; Same As Clipping follows the graphic's
|
||||
/// clipping path when it has one; 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: &Item, kind: designcraft_doc::ContourType) -> (designcraft_geom::BezPath, Option<designcraft_geom::BezPath>) {
|
||||
fn contour_path(doc: &Document, it: &Item, wrap: &designcraft_doc::TextWrap) -> (designcraft_geom::BezPath, Option<designcraft_geom::BezPath>) {
|
||||
let frame = designcraft_geom::corners::apply(&it.path, &it.corners);
|
||||
let kind = wrap.contour;
|
||||
if kind == designcraft_doc::ContourType::AlphaChannel
|
||||
&& let Some(g) = it.graphic()
|
||||
&& let Some(o) = doc.alpha_outline(g.asset, wrap.alpha_threshold)
|
||||
&& o.width > 0
|
||||
&& o.height > 0
|
||||
{
|
||||
let to_graphic = 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 wrap.inside_edges {
|
||||
path.extend(o.holes.to_bezpath().iter());
|
||||
}
|
||||
return (g.xf * to_graphic * path, Some(frame));
|
||||
}
|
||||
if kind == designcraft_doc::ContourType::SameAsClipping
|
||||
&& let Some((path, _)) = it.graphic().and_then(|g| g.clip_region())
|
||||
{
|
||||
@@ -646,20 +750,29 @@ const MAX_WRAP_DEPTH: usize = 64;
|
||||
/// the spread; `skip` is the text frame being wrapped; `left_page` tells whether a spread x is on
|
||||
/// a left page.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn wrap_obstacles(it: &Item, parent: Affine, inv: Affine, skip: ItemId, left_page: &dyn Fn(f64) -> bool, depth: usize, out: &mut Vec<Exclusion>) {
|
||||
fn wrap_obstacles(
|
||||
doc: &Document,
|
||||
it: &Item,
|
||||
parent: Affine,
|
||||
inv: Affine,
|
||||
skip: ItemId,
|
||||
left_page: &dyn Fn(f64) -> bool,
|
||||
depth: usize,
|
||||
out: &mut Vec<Exclusion>,
|
||||
) {
|
||||
if it.id == skip || it.hidden || depth > MAX_WRAP_DEPTH {
|
||||
return;
|
||||
}
|
||||
let xf = parent * it.xf;
|
||||
let left = || left_page(parent.transform_rect_bbox(it.bounds()).center().x);
|
||||
if it.wrap.mode != WrapMode::None {
|
||||
out.push(exclusion(it, xf, inv, left()));
|
||||
out.push(exclusion(doc, it, xf, inv, left()));
|
||||
}
|
||||
match &it.content {
|
||||
Content::Graphic(g) if g.wrap.mode != WrapMode::None => out.extend(graphic_exclusion(it, xf, inv, left())),
|
||||
Content::Graphic(g) if g.wrap.mode != WrapMode::None => out.extend(graphic_exclusion(doc, it, xf, inv, left())),
|
||||
Content::Group { .. } => {
|
||||
for c in it.shown_children() {
|
||||
wrap_obstacles(c, xf, inv, skip, left_page, depth + 1, out);
|
||||
wrap_obstacles(doc, c, xf, inv, skip, left_page, depth + 1, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -676,7 +789,7 @@ fn frame_wrap_exclusions(doc: &Document, sp: &designcraft_doc::Spread, item: &It
|
||||
if doc.layer(other.layer).is_some_and(|l| !l.visible) {
|
||||
continue;
|
||||
}
|
||||
wrap_obstacles(other, Affine::IDENTITY, inv, item.id, &left, 0, exclusions);
|
||||
wrap_obstacles(doc, other, Affine::IDENTITY, inv, item.id, &left, 0, exclusions);
|
||||
}
|
||||
let a = item.text_area();
|
||||
exclusions.retain(|e| {
|
||||
@@ -4323,39 +4436,40 @@ fn free_slots(f: &FrameSpec, col: Rect, y0: f64, y1: f64, desc: f64, size: f64,
|
||||
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 {
|
||||
free.retain(|(a, b)| b - a >= size * 1.5);
|
||||
|
||||
@@ -8437,6 +8437,33 @@ fn an_object_wraps_the_frame_its_anchor_lands_in_after_an_earlier_object_pushed_
|
||||
assert_eq!(line_layout(&compose_story(&d, sid, &ComposeOptions::default())), line_layout(&cs));
|
||||
}
|
||||
|
||||
#[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)]);
|
||||
}
|
||||
|
||||
/// Rule Above's offset runs from the first line's baseline up to the rule's bottom edge, as in
|
||||
/// InDesign: a rule set clear of the cap height sits between the rows, not across the row above
|
||||
/// (an INDD project list whose rules crossed the previous paragraph's text).
|
||||
|
||||
@@ -152,7 +152,7 @@ pub(crate) fn exclusions(doc: &Document, specs: &[FrameSpec], obs: &[Obstacle])
|
||||
let a = spec.area;
|
||||
for ob in obs.iter().filter(|o| o.spread == loc.spread) {
|
||||
let mut found = Vec::new();
|
||||
crate::wrap_obstacles(ob.item, ob.xf, inv, spec.id, &left, 0, &mut found);
|
||||
crate::wrap_obstacles(doc, ob.item, ob.xf, inv, spec.id, &left, 0, &mut found);
|
||||
for mut e in found {
|
||||
let r = e.rect;
|
||||
if r.is_finite() && r.x0 < a.x1 && r.x1 > a.x0 && r.y0 < a.y1 && r.y1 > a.y0 {
|
||||
|
||||
@@ -165,6 +165,7 @@ impl Document {
|
||||
modified: 0,
|
||||
next_id: 0,
|
||||
font_scope: 0,
|
||||
alpha_outlines: Vec::new(),
|
||||
};
|
||||
let lid = LayerId(d.alloc());
|
||||
d.layers.push(Layer {
|
||||
|
||||
@@ -29,8 +29,8 @@ pub use paint::{
|
||||
path_length_bound,
|
||||
};
|
||||
pub use text_frame::{
|
||||
AutoSize, ColumnsKind, ContourType, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame, TextFrameOptions,
|
||||
TextWrap, VerticalJustification, WrapMode, WrapSide, vertical_text_xf,
|
||||
AutoSize, ColumnsKind, ContourType, DEFAULT_ALPHA_THRESHOLD, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame,
|
||||
TextFrameOptions, TextWrap, VerticalJustification, WrapMode, WrapSide, vertical_text_xf,
|
||||
};
|
||||
|
||||
fn is_zero_usize(v: &usize) -> bool {
|
||||
|
||||
@@ -284,7 +284,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,
|
||||
@@ -298,6 +298,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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TextWrap {
|
||||
|
||||
@@ -657,6 +657,41 @@ impl PdfCrop {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)]
|
||||
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,
|
||||
/// The image data it was traced from: a relink or link update replaces the asset's data
|
||||
/// under the same id, and the outline is traced again. (Weak, so it doesn't keep old image
|
||||
/// data alive, and its address can't be reused by new data while it's held.)
|
||||
pub source: std::sync::Weak<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl AlphaOutline {
|
||||
/// Traced from `data`, the asset's current image data.
|
||||
pub fn traced_from(&self, data: &Arc<Vec<u8>>) -> bool {
|
||||
std::ptr::eq(self.source.as_ptr(), Arc::as_ptr(data))
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for AlphaOutline {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
(self.asset, self.threshold, self.width, self.height) == (other.asset, other.threshold, other.width, other.height)
|
||||
&& self.outer == other.outer
|
||||
&& self.holes == other.holes
|
||||
&& self.source.ptr_eq(&other.source)
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -713,6 +748,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>,
|
||||
@@ -1023,6 +1061,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)
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
//! 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()) {
|
||||
// Every frame, in groups and Paste Into containers too, with the wrap set on the frame or
|
||||
// on its placed graphic (Direct Selection sets the graphic's).
|
||||
for top in &sp.items {
|
||||
top.walk(&mut |it| {
|
||||
let Some(g) = it.graphic() else { return };
|
||||
for w in [&it.wrap, &g.wrap] {
|
||||
if w.mode == WrapMode::Contour && w.contour == ContourType::AlphaChannel && !wanted.contains(&(g.asset, w.alpha_threshold)) {
|
||||
wanted.push((g.asset, w.alpha_threshold));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
if wanted.is_empty() && doc.alpha_outlines.is_empty() {
|
||||
return;
|
||||
}
|
||||
// An outline traced from data the asset no longer has (relinked or updated) is traced again.
|
||||
let assets = &doc.assets;
|
||||
doc.alpha_outlines.retain(|o| wanted.contains(&(o.asset, o.threshold)) && assets.get(&o.asset).is_some_and(|a| o.traced_from(&a.data)));
|
||||
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 };
|
||||
// An image with no outline (opaque, unreadable, too large) is remembered as an empty
|
||||
// one, so later edits don't decode it again; the contour is then the frame's.
|
||||
let o = trace(&a.data, asset, threshold).unwrap_or_else(|| no_outline(&a.data, asset, threshold));
|
||||
doc.alpha_outlines.push(Arc::new(o));
|
||||
}
|
||||
}
|
||||
|
||||
/// The empty outline standing for an image `trace` found none in: zero-size, which composition
|
||||
/// takes as no outline, and dropped like a traced one when the asset's data changes.
|
||||
fn no_outline(data: &Arc<Vec<u8>>, asset: AssetId, threshold: u8) -> AlphaOutline {
|
||||
AlphaOutline { asset, threshold, width: 0, height: 0, outer: Default::default(), holes: Default::default(), source: Arc::downgrade(data) }
|
||||
}
|
||||
|
||||
/// 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: &Arc<Vec<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)
|
||||
};
|
||||
let source = Arc::downgrade(data);
|
||||
return Some(AlphaOutline { asset, threshold, width: w, height: h, outer: path(&outer), holes: path(&holes), source });
|
||||
}
|
||||
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.as_chunks::<4>().0.iter().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(&Arc::new(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(&Arc::new(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).unwrap();
|
||||
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 with no outline (here opaque) is remembered as an empty one: later edits don't
|
||||
/// trace it again, and the contour is the frame's.
|
||||
#[test]
|
||||
fn an_image_with_no_outline_is_not_traced_on_every_edit() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let data = png(|_, _| true);
|
||||
let id = s
|
||||
.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "solid.png", "x": 100, "y": 100, "width": 128}))
|
||||
.unwrap()["id"]
|
||||
.clone();
|
||||
s.execute("object.textWrap", &json!({"ids": [id], "mode": "contour", "contour": "alphaChannel"})).unwrap();
|
||||
let first = s.doc().unwrap().doc.alpha_outlines.clone();
|
||||
assert_eq!(first.len(), 1, "remembered");
|
||||
assert_eq!((first[0].width, first[0].height), (0, 0), "as no outline");
|
||||
s.execute("frame.create", &json!({"rect": [300, 300, 350, 350]})).unwrap();
|
||||
let after = &s.doc().unwrap().doc.alpha_outlines;
|
||||
assert!(Arc::ptr_eq(&first[0], &after[0]), "kept, not traced again");
|
||||
}
|
||||
|
||||
/// Outlines are traced for a wrap set on the placed graphic and for frames inside groups, and
|
||||
/// traced again when the image's data changes under the same asset (relink, link update).
|
||||
#[test]
|
||||
fn graphic_wraps_nested_frames_and_relinked_images_get_outlines() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let place = |s: &mut Session, x: u64| {
|
||||
let data = png(|x, _| (16..48).contains(&x));
|
||||
s.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": x, "y": 100, "width": 128}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap()
|
||||
};
|
||||
let image = place(&mut s, 100);
|
||||
// The wrap on the graphic (Direct Selection), not the frame.
|
||||
s.execute("object.textWrap", &json!({"ids": [image], "content": true, "mode": "contour", "contour": "alphaChannel"})).unwrap();
|
||||
let frame_wrap = s.doc().unwrap().doc.item(designcraft_doc::ItemId(image)).unwrap().wrap.mode;
|
||||
assert_eq!(frame_wrap, WrapMode::None, "the frame has no wrap of its own");
|
||||
assert_eq!(s.doc().unwrap().doc.alpha_outlines.len(), 1, "traced for the graphic's wrap");
|
||||
// In a group with another frame: still traced.
|
||||
let other = s.execute("frame.create", &json!({"rect": [300, 100, 350, 150]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.group", &json!({"ids": [image, other]})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.find(designcraft_doc::ItemId(image)).unwrap().path.len() > 1, "the frame is nested");
|
||||
assert_eq!(d.alpha_outlines.len(), 1, "a nested frame keeps its outline");
|
||||
// A frame placed and grouped before its wrap is set: traced too.
|
||||
let second = place(&mut s, 400);
|
||||
let other2 = s.execute("frame.create", &json!({"rect": [600, 100, 650, 150]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.group", &json!({"ids": [second, other2]})).unwrap();
|
||||
s.execute("object.textWrap", &json!({"ids": [second], "mode": "contour", "contour": "alphaChannel", "threshold": 200})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.alpha_outlines.len(), 2);
|
||||
// The image data replaced under the same asset, as a relink does: traced again.
|
||||
let Some(designcraft_doc::Content::Graphic(g)) = s.doc().unwrap().doc.item(designcraft_doc::ItemId(image)).map(|it| it.content.clone())
|
||||
else {
|
||||
panic!("a graphic")
|
||||
};
|
||||
let narrower = Arc::new(png(|x, _| (24..40).contains(&x)));
|
||||
s.edit(|d, _| {
|
||||
let a = d.assets.get(&g.asset).unwrap();
|
||||
let mut a = (**a).clone();
|
||||
a.data = narrower.clone();
|
||||
d.assets.insert(g.asset, Arc::new(a));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let o = d.alpha_outline(g.asset, designcraft_doc::DEFAULT_ALPHA_THRESHOLD).unwrap();
|
||||
assert!(o.traced_from(&narrower));
|
||||
let b = o.outer.bounds().unwrap();
|
||||
assert_eq!((b.x0, b.x1), (24.0, 40.0), "the new image's outline");
|
||||
}
|
||||
|
||||
/// 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -628,7 +628,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; null or those: each object's own, unchanged), offset?: number|[t,l,b,r] (a null side keeps each object's own), invert?: bool, side?: bothSides|leftSide|rightSide|towardsSpine|awayFromSpine|largestArea, contour?: boundingBox|graphicFrame|sameAsClipping, content?: bool (the placed graphic instead of its frame; default: whether the selection is the frame's content), 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; null or those: each object's own, unchanged), offset?: number|[t,l,b,r] (a null side keeps each object's own), invert?: bool, side?: bothSides|leftSide|rightSide|towardsSpine|awayFromSpine|largestArea, contour?: boundingBox|graphicFrame|sameAsClipping|alphaChannel, insideEdges?: bool (alphaChannel: text may enter transparent holes), content?: bool (the placed graphic instead of its frame; default: whether the selection is the frame's content), threshold?: 0..254 (alphaChannel: pixels more opaque count; default 25), ids?}; offset or contour drops an imported custom wrap boundary",
|
||||
has_selection,
|
||||
text_wrap
|
||||
),
|
||||
@@ -2152,18 +2152,23 @@ 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.
|
||||
// Alpha contours use the document's traced image mask; other unsupported contour types are rejected.
|
||||
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 =
|
||||
p.get("insideEdges").map(|v| v.as_bool().ok_or_else(|| bad("object.textWrap", "insideEdges must be a boolean"))).transpose()?;
|
||||
let threshold = match p.get("threshold") {
|
||||
Some(v) => Some(v.as_u64().filter(|n| *n <= 254).ok_or_else(|| bad("object.textWrap", "threshold must be 0..254"))? as u8),
|
||||
None => None,
|
||||
};
|
||||
let mode: Option<WrapMode> = match p.get("mode") {
|
||||
// Null keeps each object's own mode (an edit of the offsets or Invert alone).
|
||||
Some(Value::Null) => None,
|
||||
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),
|
||||
};
|
||||
// Per side [top, left, bottom, right]; a null side keeps each object's own offset there, so
|
||||
@@ -2206,6 +2211,12 @@ fn text_wrap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(c) = contour {
|
||||
w.contour = c;
|
||||
}
|
||||
if let Some(v) = inside_edges {
|
||||
w.inside_edges = v;
|
||||
}
|
||||
if let Some(v) = threshold {
|
||||
w.alpha_threshold = v;
|
||||
}
|
||||
// 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() {
|
||||
|
||||
@@ -146,7 +146,9 @@ fn next_revision() -> u64 {
|
||||
|
||||
impl DocState {
|
||||
/// Initialize saved/live document identity, revision, epoch, active default layer, empty history with limit 1,000 and the initial path.
|
||||
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.working_layer();
|
||||
let doc = Arc::new(doc);
|
||||
let revision = next_revision();
|
||||
@@ -830,6 +832,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);
|
||||
// The generated endnote story first: it replaces its text, anchored frames pasted into it
|
||||
// included.
|
||||
doc.sync_endnote_story();
|
||||
|
||||
@@ -2010,6 +2010,30 @@ fn direct_selection_on_a_selected_frame_deletes_only_its_image() {
|
||||
assert!(st.selection.content && st.selection.items == [designcraft_doc::ItemId(holder)], "the pasted-in items are selected: {:?}", st.selection);
|
||||
}
|
||||
|
||||
/// 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).
|
||||
#[test]
|
||||
fn every_line_beside_a_wrap_stays_within_its_segment() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"facingPages": false})).unwrap();
|
||||
// Placeholder text: paragraphs of a few sentences, some of them starting beside the object.
|
||||
let t = s.execute("frame.create", &json!({"rect": [36, 36, 576, 756], "content": "text", "text": ""})).unwrap();
|
||||
s.execute("type.fillWithPlaceholder", &json!({})).unwrap();
|
||||
s.execute("selection.set", &json!({"ids": []})).unwrap();
|
||||
s.execute("frame.create", &json!({"rect": [196, 160, 416, 490]})).unwrap();
|
||||
s.execute("object.textWrap", &json!({"mode": "boundingBox", "offset": 6})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let c = s.cache.get(d, designcraft_doc::StoryId(t["story"].as_u64().unwrap()), None);
|
||||
let mut beside = 0;
|
||||
for l in c.frames.iter().flat_map(|f| &f.lines) {
|
||||
let end = l.glyphs.iter().filter(|g| g.visible).map(|g| g.x + g.adv).fold(l.x0, f64::max);
|
||||
assert!(end <= l.x1 + 0.5, "line at {} runs to {end}, past its segment {}..{}", l.baseline, l.x0, l.x1);
|
||||
beside += usize::from(l.x1 < 400.0 || l.x0 > 400.0);
|
||||
}
|
||||
assert!(beside > 20, "lines on both sides of the object: {beside}");
|
||||
}
|
||||
|
||||
/// Issue #1637: with several objects selected, a click on one of them (no drag) makes it the key
|
||||
/// object, and Align to Key Object leaves it in place. A second click on it drops the key.
|
||||
#[test]
|
||||
|
||||
@@ -387,7 +387,7 @@ fn text_wrap_pref(w: &designcraft_doc::TextWrap) -> El {
|
||||
.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", bool_s(w.inside_edges)))
|
||||
}
|
||||
|
||||
pub(super) fn text_frame_pref(o: &TextFrameOptions, rule_color: &str) -> El {
|
||||
|
||||
@@ -806,6 +806,7 @@ impl<'r> Importer<'r> {
|
||||
modified: self.modified.unwrap_or(0),
|
||||
next_id: self.next_id,
|
||||
font_scope: 0,
|
||||
alpha_outlines: Vec::new(),
|
||||
};
|
||||
// A link from a frame anchored in text is kept -- it is in the document and goes back out
|
||||
// to IDML -- but PDF export finds a link's frame among the spreads' items, where an
|
||||
|
||||
@@ -9,6 +9,7 @@ pub(super) fn text_wrap(w: &El) -> TextWrap {
|
||||
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") {
|
||||
|
||||
@@ -117,6 +117,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))
|
||||
@@ -128,6 +129,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.file_info == *file_info
|
||||
&& old.settings == *settings
|
||||
|
||||
@@ -13,7 +13,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[
|
||||
("Align To", "Aligner sur"),
|
||||
("Alignment", "Alignement"),
|
||||
("All Documents", "Tous les documents"),
|
||||
("Alpha Channel", "Couche alpha"),
|
||||
("Alternate layout", "Variante de mise en page"),
|
||||
("Anchored Object Options", "Options d'objet ancré"),
|
||||
("Apply Numbering & Section Options", "Appliquer les options de numérotation et de section"),
|
||||
|
||||
@@ -389,6 +389,11 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[
|
||||
),
|
||||
("Add CMYK Swatch", ["CMYK-Farbfeld hinzufügen", "Ajouter une nuance CMJN", "Añadir muestra CMYK", "CMYK スウォッチを追加", "添加 CMYK 色板"]),
|
||||
("Added swatch", ["Farbfeld hinzugefügt", "Nuance ajoutée", "Muestra añadida", "スウォッチを追加しました", "已添加色板"]),
|
||||
(
|
||||
"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",
|
||||
[
|
||||
|
||||
@@ -550,6 +550,7 @@ fn interface_strings() -> HashSet<&'static str> {
|
||||
"Equal fixed heights for the selected rows; cell text may become overset.",
|
||||
"Found",
|
||||
"Grab bag",
|
||||
"Include Inside Edges",
|
||||
"Key Object",
|
||||
"Load Styles",
|
||||
"layer",
|
||||
|
||||
@@ -56,11 +56,12 @@ pub struct SelInfo {
|
||||
/// Uniform corner (shape, size) — the first corner.
|
||||
pub corner: (designcraft_geom::corners::CornerShape, f64),
|
||||
pub wrap_invert: bool,
|
||||
/// Text wrap side and contour type ids (`bothSides`, `sameAsClipping`, …).
|
||||
pub wrap_side: String,
|
||||
pub wrap_contour: String,
|
||||
/// Text wrap offsets: top, left, bottom, right.
|
||||
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,
|
||||
}
|
||||
|
||||
@@ -261,6 +262,7 @@ pub fn sel_info(app: &DesignApp) -> Option<SelInfo> {
|
||||
wrap_side: serde_json::to_value(tw.side).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(),
|
||||
wrap_contour: serde_json::to_value(tw.contour).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(),
|
||||
wrap_offsets: tw.offsets,
|
||||
wrap_inside_edges: tw.inside_edges,
|
||||
locked: first.locked,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -286,11 +286,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}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user