From 29c5c19d6735b8f3fb8eec00eb96f615c4327fad Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 3 Dec 2026 17:17:58 -0800 Subject: [PATCH] Keep floating objects at the drop position above pushed text --- crates/engine/src/cmd/draw.rs | 7 ++++ crates/engine/src/cmd/objects.rs | 2 +- crates/engine/src/cmd/objects/arrange.rs | 31 ++++++++++++++- crates/engine/src/tests.rs | 50 ++++++++++++++++++++++++ crates/layout/src/boxes.rs | 4 +- crates/layout/src/floats.rs | 45 +++++++++++++++------ crates/layout/src/flow.rs | 6 +-- crates/layout/src/tests.rs | 4 ++ 8 files changed, 129 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/draw.rs b/crates/engine/src/cmd/draw.rs index f762cb30b2..490bdc31a9 100644 --- a/crates/engine/src/cmd/draw.rs +++ b/crates/engine/src/cmd/draw.rs @@ -521,6 +521,13 @@ fn place(s: &mut Session, layout: &DocLayout, obj: InlineObject, page: usize, (x float.y = y - origin.y; } para.touch(); + if !on_page && let Some(offset) = super::objects::shifted_float_offset(s, &at, page, y, origin.y) { + super::objects::edit_obj(s, &at, |o| { + if let Some(float) = o.float_mut() { + float.y = offset; + } + })?; + } Ok(at) } diff --git a/crates/engine/src/cmd/objects.rs b/crates/engine/src/cmd/objects.rs index 8b5c2e7989..e417e99ae0 100644 --- a/crates/engine/src/cmd/objects.rs +++ b/crates/engine/src/cmd/objects.rs @@ -21,7 +21,7 @@ mod shape; mod specs; pub use arrange::moves_with_text; -pub(crate) use arrange::{anchor_paragraph, nearest_line}; +pub(crate) use arrange::{anchor_paragraph, nearest_line, shifted_float_offset}; #[cfg(test)] use group::ungroup; pub use picture::{OriginalSize, PictureLook, cropped_original_size, fit_size, original_size}; diff --git a/crates/engine/src/cmd/objects/arrange.rs b/crates/engine/src/cmd/objects/arrange.rs index 4453975168..c772a53492 100644 --- a/crates/engine/src/cmd/objects/arrange.rs +++ b/crates/engine/src/cmd/objects/arrange.rs @@ -212,9 +212,29 @@ fn move_object_once(s: &mut Session, pos: &Pos, page: usize, x: f32, y: f32, (w, f.x = (x - origin.x).clamp(-MAX_OFFSET, MAX_OFFSET); f.y = (y - origin.y).clamp(-MAX_OFFSET, MAX_OFFSET); })?; + if let Some(offset) = shifted_float_offset(s, &at, page, y, origin.y) { + edit_float(s, &at, |f| f.y = offset.clamp(-MAX_OFFSET, MAX_OFFSET))?; + } Ok(at) } +/// A page-to-paragraph conversion can make a float move from the unpushed paragraph top to +/// the pushed first line. Once layout has resolved that choice, offset from the origin it used. +/// Leave other layout effects, such as wrapping settlement or a change of page, to the caller. +pub(crate) fn shifted_float_offset(s: &mut Session, at: &Pos, page: usize, y: f32, old_origin: f32) -> Option { + let offset = y - old_origin; + if offset >= 0.0 + || at.story != StoryRef::Body + || at.path.depth() != 0 + || (!s.view.read_mode && !matches!(s.view.mode, wordcraft_layout::ViewMode::Print | wordcraft_layout::ViewMode::Read)) + { + return None; + } + s.touch(); + let hit = s.layout().object(at, page)?; + (hit.page == page && hit.origin.y > old_origin + 0.01 && (hit.rect.y - hit.origin.y - offset).abs() < 0.01).then_some(y - hit.origin.y) +} + /// Turn the selected floating object's alignment (left, centred, …) into an offset from its /// column / paragraph that keeps it where it is, so it can be moved by an offset. pub(super) fn unalign(s: &mut Session) -> Result<(), CmdError> { @@ -245,6 +265,12 @@ pub(super) fn unalign(s: &mut Session) -> Result<(), CmdError> { f.y = oy.clamp(-MAX_OFFSET, MAX_OFFSET); } })?; + if float.v_align.is_some() + && float.v_rel != Anchor::Page + && let Some(offset) = shifted_float_offset(s, &pos, hit.page, hit.rect.y, hit.origin.y) + { + edit_float(s, &pos, |f| f.y = offset.clamp(-MAX_OFFSET, MAX_OFFSET))?; + } Ok(()) } @@ -268,11 +294,14 @@ pub(super) fn move_with_text(s: &mut Session, with_text: bool) -> CmdResult { let hit = s.layout().object(&pos, s.page_hint).ok_or_else(|| CmdError::Failed("the object isn't laid out".into()))?; // Paragraph offsets start at the paragraph's top (the hit's origin), page offsets at the page's. let y = if with_text { hit.rect.y - hit.origin.y } else { hit.rect.y }; - let o = edit_float(s, &pos, |f| { + let mut o = edit_float(s, &pos, |f| { f.v_rel = if with_text { Anchor::Paragraph } else { Anchor::Page }; f.v_align = None; f.y = y.clamp(-MAX_OFFSET, MAX_OFFSET); })?; + if with_text && let Some(offset) = shifted_float_offset(s, &pos, hit.page, hit.rect.y, hit.origin.y) { + o = edit_float(s, &pos, |f| f.y = offset.clamp(-MAX_OFFSET, MAX_OFFSET))?; + } Ok(json!({"object": serde_json::to_value(o).unwrap_or(Value::Null)})) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b7bada31e8..fc4c147ce9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7169,6 +7169,56 @@ fn select_box(s: &mut Session) { run(s, "select.range", json!({"anchor": o.pos(), "focus": end})); } +#[test] +fn dragging_above_a_pushed_first_line_keeps_the_drop_position() { + use wordcraft_doc::para::{Anchor, Float, InlineObject, OBJ, ShapeKind, Wrap}; + let shape = |w, h, float| InlineObject::Shape { + kind: ShapeKind::Rectangle, + w, + h, + fill: None, + stroke: None, + stroke_width: 1.0, + float, + story: None, + freeform: None, + effects: Default::default(), + extra: Default::default(), + }; + for frame_wrap in [Wrap::TopAndBottom, Wrap::BehindText] { + // Original synthetic version of #6587's first-line push. Only the frame wraps text. + let mut doc = wordcraft_doc::Document::from_text("A line under a frame."); + let old_top = doc.last_section.margin_top; + let (x, y) = (120.0, old_top - 22.0); + let object = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Page, v_rel: Anchor::Page, x, y: old_top + 12.0, ..Default::default() }; + let frame = Float { wrap: frame_wrap, v_rel: Anchor::Paragraph, y: -20.0, ..Default::default() }; + let at = Pos::body(0, 0); + let end = Pos::body(0, OBJ.len_utf8()); + doc.insert_object(&at, shape(40.0, 18.0, object), &Default::default()).unwrap(); + doc.insert_object(&end, shape(300.0, 250.0, frame), &Default::default()).unwrap(); + let mut s = Session::new(doc); + run(&mut s, "select.range", json!({"anchor": at, "focus": end})); + run(&mut s, "arrange.bounds", json!({"page": 0, "x": x, "y": y})); + let hit = s.layout().object(&at, 0).unwrap(); + assert!((hit.rect.y - y).abs() < 0.01 && (hit.rect.x - x).abs() < 0.01, "{frame_wrap:?}: {hit:?}"); + assert_eq!(hit.origin.y > old_top + 1.0, frame_wrap == Wrap::TopAndBottom); + + for (with_text, anchor) in [(false, Anchor::Page), (true, Anchor::Paragraph)] { + run(&mut s, "arrange.moveWithText", json!({"value": with_text})); + let hit = s.layout().object(&at, 0).unwrap(); + let (_, _, float) = s.doc.para_at(&at).unwrap().object_at(at.off).unwrap().frame().unwrap(); + assert_eq!(float.v_rel, anchor); + assert!((hit.rect.y - y).abs() < 0.01, "{frame_wrap:?}, {anchor:?}: {hit:?}"); + let origin = if with_text { hit.origin.y } else { 0.0 }; + assert!((hit.rect.y - origin - float.y).abs() < 0.01, "{frame_wrap:?}, {anchor:?}: {hit:?}"); + } + + run(&mut s, "draw.stroke", json!({"page": 0, "points": [[x, y], [x + 10.0, y]], "width": 2.0})); + let ink = s.layout().object(&at, 0).unwrap(); + assert!((ink.rect.y - (y - 1.0)).abs() < 0.01, "{frame_wrap:?}: {ink:?}"); + } +} + #[test] fn arrange_bounds_resizes_and_moves_objects() { use wordcraft_doc::para::{Anchor, Wrap}; diff --git a/crates/layout/src/boxes.rs b/crates/layout/src/boxes.rs index 7ed67e801b..ebb6c0b0b8 100644 --- a/crates/layout/src/boxes.rs +++ b/crates/layout/src/boxes.rs @@ -1,6 +1,6 @@ use super::ctx::{Ctx, Joining, page_anchored}; use super::floats::{ - ObjFrame, ObjectPlacement, WrapArea, align_in, float_rect, floating, left_out_objects, place_objects, rel_exclusions, wrap_area, + AnchoredFloat, ObjFrame, ObjectPlacement, WrapArea, align_in, float_rect, floating, left_out_objects, place_objects, rel_exclusions, wrap_area, }; use super::flow::again; use super::page::PageFrame; @@ -361,7 +361,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout { let outline = ctx.wrap_outline(o); excl.extend(wrap_area(r, float, outline.as_deref().map(Vec::as_slice))); } - floats.insert(oi, r); + floats.insert(oi, AnchoredFloat::new(r)); } let rel = rel_exclusions(&excl, 0.0, y, applied); if !rel.is_empty() { diff --git a/crates/layout/src/floats.rs b/crates/layout/src/floats.rs index ae97ddb0e5..96be1f0df5 100644 --- a/crates/layout/src/floats.rs +++ b/crates/layout/src/floats.rs @@ -349,7 +349,7 @@ pub(crate) fn anchor_floats( pb: &mut PageBuilder, anchor: FloatAnchor, force: &[usize], -) -> (HashMap, Arc, Vec, Vec) { +) -> (HashMap, Arc, Vec, Vec) { let FloatAnchor { p, block, y0, place, .. } = anchor; ctx.fields.page = pb.number; // Each layout of it here counts its automatic equation numbers from the same place. @@ -471,13 +471,26 @@ pub(crate) fn anchor_lines(p: &Paragraph, pl: &ParaLayout) -> Vec> out } +/// A float placed before its paragraph's objects are drawn. +pub(crate) struct AnchoredFloat { + rect: Rect, + /// The origin used when the float was placed again from the pushed first line. + pushed_origin: Option, +} + +impl AnchoredFloat { + pub(crate) fn new(rect: Rect) -> Self { + Self { rect, pushed_origin: None } + } +} + /// [`anchor_floats`], leaving out the floats in `late` (in order). fn anchor_floats_but( ctx: &mut Ctx, pb: &mut PageBuilder, anchor: FloatAnchor, late: &[usize], -) -> (HashMap, Arc, Vec) { +) -> (HashMap, Arc, Vec) { let FloatAnchor { p, block, y0, before, excl_mark, label, place } = anchor; ctx.fields.page = pb.number; ctx.fields.page_format = pb.page_format; @@ -515,7 +528,7 @@ fn anchor_floats_but( let seed = early.and_then(|v| v.iter().find(|(b, k, _)| (*b, *k) == (block, oi))).map(|(_, _, a)| a); (r, area) = settle_early(r, area, seed, top, |r| wrap_area(r, float, outline)); } - rects.insert(oi, r); + rects.insert(oi, AnchoredFloat::new(r)); // Above the paragraph, beside text laid out before it: the page is laid out again // with it known from the start (#2048). let above = area.as_ref().filter(|a| text_before && a.0.y < top - 0.5).map(|a| (page, a.clone())); @@ -553,7 +566,8 @@ fn anchor_floats_but( for (oi, o) in p.objects.iter().enumerate() { let Some((_, _, float)) = floating(o) else { continue }; let Some(&area) = areas.get(&oi) else { continue }; - let Some(&r) = rects.get(&oi) else { continue }; + let Some(placed) = rects.get_mut(&oi) else { continue }; + let r = placed.rect; if float.y < 0.0 && area.map_or(r.bottom(), |(_, b)| b) < y0 + lead - 0.5 { // Only down: across it stays where it was placed (`settle_early` may have moved it). let moved = Rect { y: float_rect(Some(frame), (col_x, width), top + lead, r.w, r.h, float).y, ..r }; @@ -561,7 +575,11 @@ fn anchor_floats_but( if area.is_some_and(|(_, b)| b + (moved.y - r.y) > y0 + lead - 0.5) { continue; } - rects.insert(oi, moved); + placed.rect = moved; + placed.pushed_origin = match float.v_rel { + Anchor::Page | Anchor::Margin | Anchor::TopMargin | Anchor::BottomMargin | Anchor::InsideMargin | Anchor::OutsideMargin => None, + _ => Some(top + lead), + }; if let Some((k, _)) = area && let Some(slot) = pb.excl.get_mut(k) { @@ -738,7 +756,7 @@ pub(crate) struct ObjectPlacement<'a> { pub lines: (usize, usize), pub origin: (f32, f32), pub at: &'a ObjFrame<'a>, - pub floats: &'a HashMap, + pub floats: &'a HashMap, pub depth: usize, } @@ -798,22 +816,23 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec *r, + Some(placed) => (placed.rect, placed.pushed_origin.unwrap_or(at.para_y)), None => { let h = ctx.float_height(obj, w, h); - float_rect(at.page, at.col, at.para_y, w, h, float) + (float_rect(at.page, at.col, at.para_y, w, h, float), at.para_y) } } } else { let cx = x + line.cl_left(k).unwrap_or(0.0); let modern = ctx.doc.settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT; - display::inline_rect(Some(obj), cx, y + (line.baseline - fl.top), c.adv, (c.obj_h, c.obj_d), pl.rule_room(line, k), modern) + let r = display::inline_rect(Some(obj), cx, y + (line.baseline - fl.top), c.adv, (c.obj_h, c.obj_d), pl.rule_room(line, k), modern); + (r, at.para_y) }; let (mut behind, mut front) = (Vec::new(), Vec::new()); let layer = if float.wrap == Wrap::BehindText { &mut behind } else { &mut front }; @@ -860,7 +879,7 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec { excl_mark: usize, /// Where its automatic equation numbers start: each layout of it again counts from here. eq_start: u32, - float_rects: HashMap, + float_rects: HashMap, pl: Arc, rel: Vec, /// The page its fields were laid out for, and the width. diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index b8b164b02e..45b233bdb5 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -19209,6 +19209,10 @@ fn negative_offset_floats_in_a_paragraph_pushed_down_by_a_wrapping_float_stay_on assert!((title_rect.y - (line_top - 652.55)).abs() < 0.5, "title measured from displaced line {line_top}: {title_rect:?}"); assert!((row_rect.y - (line_top - 460.75)).abs() < 0.5, "row measured from displaced line {line_top}: {row_rect:?}"); assert!(title_rect.y > frame_rect.y && row_rect.bottom() < frame_rect.bottom(), "{placed:?}"); + let frame = l.object(&Pos::body(0, 2 * wordcraft_doc::para::OBJ.len_utf8()), 0).unwrap(); + let title = l.object(&Pos::body(0, 0), 0).unwrap(); + assert!((title.origin.y - line_top).abs() < 0.5, "moved float's offset starts at the pushed line: {title:?}"); + assert!((frame.rect.y - frame.origin.y + 43.11).abs() < 0.5, "unmoved wrapping float keeps its origin: {frame:?}"); } /// #6567 review: a wrapping float above its paragraph that would land on the first line when