Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Merge r2 track t02: edit-content

aiongg7bf122eea884
diff --cc ROADMAP.md
index 40fabb8f3,3643bb048..f19c158c4
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -176,9 -176,8 +177,10 @@@ Ranked; detail and the full milestone t
- **2026-10-20 (M6, calculation order page):** Prepare a form ▸ Calculation order, a page of its own, lists the calculated fields in the order they calculate with their formulas and values, moved with Up/Down arrows (as Acrobat's Set Field Calculation Order), Alt+↑/↓ or by dragging. A card says what is wrong with the order and holds Fix order; a loop has a card of its own that opens one of its formulas. On the page, each calculated field shows its step, and arrows show what the field in focus reads and what reads it. Estimates unchanged.
- **2026-10-20 (M6, calculation order):** The order a form's fields calculate in (`/CO`) is read, checked, fixed and set headlessly with `form_calculation_order`: it says which fields read one calculated later (they show stale values), which read each other in a loop, and which the PDF's order leaves out; Fix order moves only what must move, in one undo step, and the form recalculates. Editing a formula no longer moves its field to the end of the order, and a field the order lists twice calculates once. Estimates unchanged.
- **2026-10-19 (M6, renames keep formulas):** Renaming a field renames it in every calculation that reads it, in the same undo step: `AFSimple_Calculate` field lists, simplified field notation (the comment and the JavaScript after it) and `getField` calls naming it in one string literal; the rest of each script is kept as written. A sum used to drop the renamed field, notation read it as 0 and a script kept a stale value. Field Properties says how many formulas changed and `form_set_props` lists them as `formulas_updated`. Names built at run time and other events' scripts are not rewritten. Estimates unchanged.
+ - **2026-10-19 (M7, #3591):** A background added to a page that already has one is painted over the old one instead of going under it and staying hidden. Behind the content, backgrounds come first, in the order added, and then behind-content watermarks, so a watermark added after a background no longer disappears. Synthetic regressions in `crates/edit` check the order. Estimates unchanged.
+- **2026-10-16 (M7, #2516):** A paragraph number from `text_paragraphs` keeps naming the paragraph it listed after edits regroup the page: `text_edit`, `text_edit_layout` and `page_render`'s `hide_text_block` find it again by its text and box, and refuse one that was merged into a neighbour (the edited paragraph included) instead of rewriting the paragraph that took its number (`stale_paragraphs` lists the numbers gone). The inline editor's switch-paragraph click holds the same key. No stable identity across save and reopen yet (#2508).
+
- **2026-10-19 (M14, #3373):** The main menu and its long submenus scroll in short windows, keeping their commands reachable. Estimates unchanged.
- **2026-10-19 (M3, #3387):** Save-prompt shortcuts yield to later consent and utility dialogs; a synthetic UI regression checks that an edited document stays open. Estimates unchanged.
diff --cc crates/edit/src/tests.rs
index e9b743c5c,ed1e35dee..1333a3057
--- a/crates/edit/src/tests.rs
+++ b/crates/edit/src/tests.rs
@@@ -5420,286 -5424,39 +5625,323 @@@ fn a_clipping_copy_on_the_same_baseline
assert_eq!(text::text_lines(&doc, 0).unwrap().len(), 2, "refused means untouched");
}
+/// #2512: a session's drafts are laid out from the document as it was opened, never from each
+/// other, and its commit writes what a one-shot rewrite writes, whatever was laid out before.
+#[test]
+fn a_text_session_commits_what_a_rewrite_writes_whatever_it_laid_out_before() {
+ let page = "BT /F1 12 Tf 14 TL 72 700 Td (The first row of a paragraph) Tj T* (and its second row here.) Tj ET";
+ let bold = BlockStyle { bold: Some(true), ..Default::default() };
+ let drafts: [(&str, &BlockStyle); 4] = [
+ ("The first row of a paragraph\nand its second row here, with more words to wrap it onto a third row", &BlockStyle::default()),
+ ("Short", &bold),
+ ("The first row\nsecond", &BlockStyle::default()),
+ ("The first row of a paragraph\nand its second row here.", &bold),
+ ];
+ let doc = text_page(page);
+ let session = text::TextSession::open(&doc, 0, 0).unwrap();
+ assert_eq!(session.source().editor_text, "The first row of a paragraph\nand its second row here.");
+ for (text, style) in drafts {
+ let fresh = text::text_edit_layout(&text_page(page), 0, 0, text, style).unwrap();
+ assert_eq!(session.layout(text, style).unwrap(), fresh, "{text:?} is laid out from the opened page");
+ }
+ let (text, style) = drafts[0];
+ let mut by_session = doc.clone();
+ session.commit(&mut by_session, Some(text), style).unwrap();
+ let mut by_rewrite = text_page(page);
+ text::rewrite_block(&mut by_rewrite, 0, 0, Some(text), style).unwrap();
+ assert_eq!(
+ pdfcraft_cos::write_full(&by_session, &SaveOptions::default()).unwrap(),
+ pdfcraft_cos::write_full(&by_rewrite, &SaveOptions::default()).unwrap(),
+ "the commit writes what a rewrite writes"
+ );
+ // A document changed since the session opened isn't written to.
+ let before = pdfcraft_cos::write_full(&by_session, &SaveOptions::default()).unwrap();
+ let refused = session.commit(&mut by_session, Some("Again"), &BlockStyle::default());
+ assert!(matches!(&refused, Err(EditError::Invalid(m)) if m.contains("changed while it was being edited")), "{refused:?}");
+ assert_eq!(pdfcraft_cos::write_full(&by_session, &SaveOptions::default()).unwrap(), before);
+ assert!(session.is_current(&doc) && !session.is_current(&by_session));
+}
+
+/// A one-page document whose resources have `/GS0` (30 % opacity) and `/L1`, a layer that is OFF.
+fn row_state_page(content: &str) -> Document {
+ let objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [5 0 R] /D << /OFF [5 0 R] /Order [5 0 R] >> >> >>".into(),
+ "<< /Type /Pages /Kids [6 0 R] /Count 1 >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
+ "<< /Type /ExtGState /ca 0.3 /CA 0.3 >>".into(),
+ "<< /Type /OCG /Name (Hidden layer) >>".into(),
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 7 0 R /Resources << /Font << /F1 3 0 R >> /ExtGState << /GS0 4 0 R /GS1 << /Type /ExtGState /ca 0.3 /CA 0.3 /BM /Normal >> /GS2 << /Type /ExtGState /ca 1 /CA 1 >> >> /Properties << /L1 5 0 R >> >> >>".into(),
+ format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),
+ ];
+ let mut out = b"%PDF-1.7\n".to_vec();
+ let mut offs = Vec::new();
+ for (i, o) in objs.iter().enumerate() {
+ offs.push(out.len());
+ out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
+ }
+ let x = out.len();
+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
+ for o in offs {
+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
+ }
+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{x}\n%%EOF\n", objs.len() + 1).as_bytes());
+ Document::open(Arc::new(out)).unwrap()
+}
+
+/// Each shown string on page 0 with the state it is drawn in: inside a `/OC` marked-content
+/// sequence, after `/GS0 gs`, and its horizontal scale (percent).
+fn shown_states(doc: &Document) -> Vec<(String, bool, bool, f64)> {
+ let joined = streams(doc, 0).join("\n");
+ let (mut oc, mut marks) = (0usize, Vec::new());
+ let (mut gs, mut tz, mut stack) = (false, 100.0, Vec::new());
+ let mut out = Vec::new();
+ for op in pdfcraft_content::parse(joined.as_bytes()).ops {
+ match op.op.as_slice() {
+ b"BDC" | b"BMC" => {
+ let layer = op.name(0) == Some(b"OC".as_slice());
+ oc += usize::from(layer);
+ marks.push(layer);
+ }
+ b"EMC" => oc -= usize::from(marks.pop().unwrap()),
+ b"q" => stack.push((gs, tz)),
+ b"Q" => (gs, tz) = stack.pop().unwrap(),
+ b"gs" => gs |= op.name(0) == Some(b"GS0".as_slice()),
+ b"Tz" => tz = op.num(0).unwrap(),
+ b"Tj" | b"'" => {
+ let Some(Object::String(s)) = op.operands.last() else { continue };
+ if !s.bytes.is_empty() {
+ out.push((String::from_utf8_lossy(&s.bytes).into_owned(), oc > 0, gs, tz));
+ }
+ }
+ _ => {}
+ }
+ }
+ out
+}
+
+/// #3115: a row drawn in a hidden layer, at 30 % opacity or at 80 % horizontal scale keeps that
+/// state when another row of the same paragraph is edited; the edited row doesn't take it on.
+#[test]
+fn editing_a_row_keeps_the_layer_opacity_and_scale_of_the_rows_around_it() {
+ let row1 = "BT /F1 12 Tf 72 700 Td (Hello world, this is the first line) Tj ET\n";
+ let row2 = "BT /F1 12 Tf 72 686 Td (and the second) Tj ET";
+ let pages = [
+ (format!("{row1}/OC /L1 BDC {row2} EMC"), (true, false, 100.0)),
+ (format!("{row1}q /GS0 gs {row2} Q"), (false, true, 100.0)),
+ ("BT /F1 12 Tf 72 700 Td (Hello world, this is the first line) Tj 80 Tz 0 -14 Td (and the second) Tj ET".to_string(), (false, false, 80.0)),
+ (format!("{row1}{row2}"), (false, false, 100.0)),
+ ];
+ for (n, (content, (oc, gs, tz))) in pages.iter().enumerate() {
+ let mut doc = row_state_page(content);
+ let blocks = text::text_blocks(&doc, 0).unwrap();
+ let block = blocks.iter().position(|b| b.text.starts_with("Hello")).unwrap();
+ let text = blocks[block].text.replacen("Hello", "Jello", 1);
+ text::replace_block(&mut doc, 0, block, &text).unwrap();
+ let shown = shown_states(&reopen(&doc));
+ let find = |needle: &str| shown.iter().filter(|s| s.0.contains(needle)).cloned().collect::<Vec<_>>();
+ let first = find("Jello");
+ assert_eq!(first.len(), 1, "page {}: {shown:?}", n + 1);
+ assert_eq!((first[0].1, first[0].2, first[0].3), (false, false, 100.0), "page {}: the edited row keeps its own state: {shown:?}", n + 1);
+ let second = find("and the second");
+ assert_eq!(second.len(), 1, "page {}: {shown:?}", n + 1);
+ assert_eq!((second[0].1, second[0].2, second[0].3), (*oc, *gs, *tz), "page {}: the other row keeps its state: {shown:?}", n + 1);
+ }
+ // The control: rows in the same state are still one paragraph.
+ let blocks = text::text_blocks(&row_state_page(&pages[3].0), 0).unwrap();
+ assert_eq!(blocks.len(), 1);
+ assert_eq!(blocks[0].text, "Hello world, this is the first line and the second");
+}
+
+/// What keeps rows apart is the graphics state they are drawn in, not the `gs` operators
+/// before them: a repeated `gs` without q/Q, or another name with the same settings, is still one
+/// paragraph, and a `gs` that changes the opacity or puts it back is not.
+#[test]
+fn rows_under_repeated_or_equal_gs_states_stay_one_paragraph() {
+ let row1 = "BT /F1 12 Tf 72 700 Td (Hello world, this is the first line) Tj ET\n";
+ let row2 = "BT /F1 12 Tf 72 686 Td (and the second) Tj ET";
+ let paragraphs = |content: String| text::text_blocks(&row_state_page(&content), 0).unwrap().len();
+ assert_eq!(paragraphs(format!("/GS0 gs {row1}/GS0 gs {row2}")), 1, "the same name twice");
+ assert_eq!(paragraphs(format!("/GS0 gs {row1}/GS0 gs /GS0 gs {row2}")), 1, "the same name three times");
+ assert_eq!(paragraphs(format!("/GS0 gs {row1}/GS1 gs {row2}")), 1, "two names, the same settings");
+ assert_eq!(paragraphs(format!("/GS2 gs {row1}{row2}")), 1, "settings that are the defaults");
+ assert_eq!(paragraphs(format!("{row1}/GS0 gs {row2}")), 2, "another opacity");
+ assert_eq!(paragraphs(format!("/GS0 gs {row1}/GS2 gs {row2}")), 2, "the opacity put back");
+}
+
+/// A page of three vertical (`Identity-V`) columns at 20 pt: `ABCDEF` at x = 500, the same
+/// text 30 pt to its left, and `ABCD` far away. Synthetic font: no font program is needed.
+fn vertical_columns_page() -> Document {
+ vertical_page(
+ "BT /V1 20 Tf 500 720 Td <004100420043004400450046> Tj ET\nBT /V1 20 Tf 470 720 Td <004100420043004400450046> Tj ET\nBT /V1 20 Tf 300 720 Td <0041004200430044> Tj ET",
+ )
+}
+
+/// A page drawing `content` with the vertical font `/V1` (as in [`vertical_columns_page`]) and
+/// Helvetica `/F1`.
+fn vertical_page(content: &str) -> Document {
+ let mut doc = text_page(content);
+ let mut font = Dict::from_iter([
+ (b"Type".to_vec(), Object::name("Font")),
+ (b"Subtype".to_vec(), Object::name("Type0")),
+ (b"BaseFont".to_vec(), Object::name("SyntheticCID")),
+ (b"Encoding".to_vec(), Object::name("Identity-V")),
+ ]);
+ let unicode = doc.add(Object::Stream(Stream::flate(
+ Dict::new(),
+ b"1 begincodespacerange <0000> <ffff> endcodespacerange 6 beginbfchar <0041> <0041> <0042> <0042> <0043> <0043> <0044> <0044> <0045> <0045> <0046> <0046> endbfchar",
+ )));
+ font.set(b"ToUnicode".to_vec(), Object::Ref(unicode));
+ font.set(
+ b"DescendantFonts".to_vec(),
+ Object::Array(vec![Object::Dict(Dict::from_iter([
+ (b"Subtype".to_vec(), Object::name("CIDFontType2")),
+ (b"DW".to_vec(), Object::Int(1000)),
+ ]))]),
+ );
+ let p = pdfcraft_model::pages(&doc)[0].obj;
+ let helvetica = Dict::from_iter([
+ (b"Type".to_vec(), Object::name("Font")),
+ (b"Subtype".to_vec(), Object::name("Type1")),
+ (b"BaseFont".to_vec(), Object::name("Helvetica")),
+ (b"Encoding".to_vec(), Object::name("WinAnsiEncoding")),
+ ]);
+ let fonts = Dict::from_iter([(b"V1".to_vec(), Object::Dict(font)), (b"F1".to_vec(), Object::Dict(helvetica))]);
+ let resources = Dict::from_iter([(b"Font".to_vec(), Object::Dict(fonts))]);
+ doc.update_dict(p, |d| d.set(b"Resources".to_vec(), Object::Dict(resources))).unwrap();
+ doc
+}
+
+#[test]
+fn vertical_text_lines_are_columns_and_editing_one_keeps_its_neighbour() {
+ let doc = vertical_columns_page();
+ let lines = text::text_lines(&doc, 0).unwrap();
+ let first = lines.iter().find(|l| l.baseline()[0] == 500.0).unwrap();
+ let r = first.rect;
+ // Six glyphs, each 20 pt wide and advancing 20 pt down, centred on x = 500.
+ assert!((r[0] - 490.0).abs() < 0.5 && (r[2] - 510.0).abs() < 0.5, "{r:?}");
+ assert!((r[1] - 600.0).abs() < 0.5 && (r[3] - 720.0).abs() < 0.5, "{r:?}");
+ for edit in [0, 1] {
+ let mut doc = vertical_columns_page();
+ let lines = text::text_lines(&doc, 0).unwrap();
+ if edit == 0 {
+ let line = lines.iter().position(|l| l.baseline()[0] == 500.0).unwrap();
+ text::replace_line(&mut doc, 0, line, "ABCDEA").unwrap();
+ } else {
+ let blocks = text::text_blocks(&doc, 0).unwrap();
+ let block = blocks.iter().position(|b| b.lines.iter().any(|&i| lines[i].baseline()[0] == 500.0)).unwrap();
+ assert_eq!(blocks[block].lines.len(), 1, "{blocks:?}");
+ text::replace_block(&mut doc, 0, block, "ABCDEA").unwrap();
+ }
+ let after = text::text_lines(&doc, 0).unwrap();
+ let texts: Vec<(f64, &str)> = after.iter().map(|l| (l.baseline()[0], l.text.as_str())).collect();
+ assert!(texts.contains(&(500.0, "ABCDEA")), "{texts:?}");
+ assert!(texts.contains(&(470.0, "ABCDEF")), "{texts:?}");
+ assert!(texts.contains(&(300.0, "ABCD")), "{texts:?}");
+ }
+}
+
+/// Gives `/V1` an embedded CMap that uses itself: which way its glyphs advance can't be known.
+fn make_cmap_cyclic(doc: &mut Document) {
+ let cmap = doc.add(Object::Null);
+ doc.set(
+ cmap,
+ Object::Stream(Stream::flate(
+ Dict::from_iter([(b"UseCMap".to_vec(), Object::Ref(cmap))]),
+ b"1 begincodespacerange <0000> <ffff> endcodespacerange",
+ )),
+ );
+ let p = pdfcraft_model::pages(doc)[0].obj;
+ doc.update_dict(p, |d| {
+ if let Some(Object::Dict(res)) = d.get_mut(b"Resources")
+ && let Some(Object::Dict(fonts)) = res.get_mut(b"Font")
+ && let Some(Object::Dict(font)) = fonts.get_mut(b"V1")
+ {
+ font.set(b"Encoding".to_vec(), Object::Ref(cmap));
+ }
+ })
+ .unwrap();
+}
+
+#[test]
+fn text_whose_cmap_writing_mode_cannot_be_read_is_not_edited() {
+ let mut doc = vertical_columns_page();
+ make_cmap_cyclic(&mut doc);
+ let error = text::replace_line(&mut doc, 0, 0, "ABCDEA").unwrap_err();
+ assert!(error.to_string().contains("cyclic"), "{error}");
+}
+
+#[test]
+fn a_cyclic_cmap_falls_back_to_horizontal_and_only_refuses_its_own_lines() {
+ let mut doc = vertical_page("BT /V1 20 Tf 100 700 Td <00410042> Tj ET\nBT /F1 12 Tf 100 600 Td (Plain) Tj ET");
+ make_cmap_cyclic(&mut doc);
+ // The page is still listed: the broken font's text as horizontal, the rest untouched.
+ let lines = text::text_lines(&doc, 0).unwrap();
+ let texts: Vec<&str> = lines.iter().map(|l| l.text.as_str()).collect();
+ assert_eq!(texts, ["AB", "Plain"], "{texts:?}");
+ assert!(lines[0].rect[2] - lines[0].rect[0] > 30.0 && lines[0].rect[3] - lines[0].rect[1] < 30.0, "{:?}", lines[0].rect);
+ assert_eq!(text::reading_blocks(&doc, 0).unwrap().len(), 2);
+ assert_eq!(text::text_blocks(&doc, 0).unwrap().len(), 2);
+ // Only the line in the broken font is refused.
+ let error = text::replace_line(&mut doc.clone(), 0, 0, "BA").unwrap_err();
+ assert!(error.to_string().contains("cyclic"), "{error}");
+ let block = text::text_blocks(&doc, 0).unwrap().iter().position(|b| b.text == "AB").unwrap();
+ let error = text::replace_block(&mut doc.clone(), 0, block, "BA").unwrap_err();
+ assert!(error.to_string().contains("cyclic"), "{error}");
+ text::replace_line(&mut doc, 0, 1, "Changed").unwrap();
+ let texts: Vec<String> = text::text_lines(&doc, 0).unwrap().into_iter().map(|l| l.text).collect();
+ assert_eq!(texts, ["AB", "Changed"]);
+}
+
+#[test]
+fn vertical_text_drawn_one_glyph_per_tj_is_one_line() {
+ // One text object, a `Tj` per glyph; and a column with a text object per glyph.
+ let doc = vertical_page(
+ "BT /V1 20 Tf 500 720 Td <0041> Tj <0042> Tj <0043> Tj ET\n\
+ BT /V1 20 Tf 1 0 0 1 470 720 Tm <0041> Tj ET\nBT /V1 20 Tf 1 0 0 1 470 700 Tm <0042> Tj ET\nBT /V1 20 Tf 1 0 0 1 470 680 Tm <0043> Tj ET",
+ );
+ let lines = text::text_lines(&doc, 0).unwrap();
+ let columns: Vec<(f64, &str)> = lines.iter().map(|l| (l.baseline()[0], l.text.as_str())).collect();
+ assert_eq!(columns, [(500.0, "ABC"), (470.0, "ABC")], "{columns:?}");
+ for line in &lines {
+ let r = line.rect;
+ assert!((r[1] - 660.0).abs() < 0.5 && (r[3] - 720.0).abs() < 0.5, "{r:?}");
+ }
+ assert_eq!(text::text_blocks(&doc, 0).unwrap().len(), 2);
+}
++
+ /// Two genuinely stacked rows of ordinary body text must not join into one row just because the
+ /// first is narrow enough to put the second's start within the #3252 tolerance band: here the
+ /// second row starts 1.4pt to the left of where the first ends (so the two overlap a little,
+ /// as compressed text or a tight column can) and 5pt below its baseline — inside the widened 50%
+ /// tolerance but outside the original 20% one. They stay two rows (and two paragraphs).
+ #[test]
+ fn stacked_rows_that_merely_overlap_do_not_join_into_one_row() {
+ let doc = text_page("BT /F1 12 Tf 72 700 Td (A compressed line of body text here) Tj 190 -5 Td (Second stacked line of body text) Tj ET");
+ let lines = text::text_lines(&doc, 0).unwrap();
+ assert_eq!(lines.len(), 2);
+ let gap = lines[1].rect[0] - lines[0].rect[2];
+ assert!((-2.4..0.0).contains(&gap), "the rows overlap a little, within the old tolerance band: {gap}");
+ let baseline_shift = lines[0].rect[3] - lines[1].rect[3];
+ assert!((2.4..6.0).contains(&baseline_shift), "between the old and new vertical tolerance: {baseline_shift}");
+ let blocks = text::text_blocks(&doc, 0).unwrap();
+ assert_eq!(blocks.len(), 2, "two separate rows stay two paragraphs, not one: {blocks:?}");
+ }
+
+ /// Two equal-size rows with no horizontal overlap must not join into one row either (#3252):
+ /// the wider tolerance is for a run distinctly smaller or larger than its neighbour (a
+ /// super/subscript), not for two ordinary body-text rows that happen to sit close enough
+ /// vertically — here a 5pt baseline shift, inside the widened 50% tolerance but outside the
+ /// original 20% one, with the second row starting just past where the first ends.
+ #[test]
+ fn equal_size_rows_need_the_tighter_tolerance_even_without_overlap() {
+ let doc = text_page("BT /F1 12 Tf 72 700 Td (Short line one) Tj 75 -5 Td (Second line two here) Tj ET");
+ let lines = text::text_lines(&doc, 0).unwrap();
+ assert_eq!(lines.len(), 2);
+ assert_eq!(lines[0].size, lines[1].size, "same size: no super/subscript here");
+ let gap = lines[1].rect[0] - lines[0].rect[2];
+ assert!(gap >= 0.0, "no horizontal overlap: {gap}");
+ let baseline_shift = lines[0].rect[3] - lines[1].rect[3];
+ assert!((2.4..6.0).contains(&baseline_shift), "between the old and new vertical tolerance: {baseline_shift}");
+ let blocks = text::text_blocks(&doc, 0).unwrap();
+ assert_eq!(blocks.len(), 2, "two separate rows stay two paragraphs, not one: {blocks:?}");
+ }
diff --cc crates/edit/src/text.rs
index 13b828db6,8530680f9..eea1ef3dd
--- a/crates/edit/src/text.rs
+++ b/crates/edit/src/text.rs
@@@ -22,10 -22,7 +22,10 @@@ use crate::EditError
#[path = "text_regions.rs"]
mod regions;
+#[path = "text_session.rs"]
+mod session;
- use regions::{group_blocks, rewrite_styled_block};
+ use regions::{group_blocks, is_centred, rewrite_styled_block};
+pub use session::TextSession;
/// One line of existing text.
#[derive(Clone, Debug, PartialEq)]
diff --cc crates/ui-egui/src/edit_text_ui.rs
index b9b675cc3,c139a040c..5e0e401dc
--- a/crates/ui-egui/src/edit_text_ui.rs
+++ b/crates/ui-egui/src/edit_text_ui.rs
@@@ -460,8 -369,9 +460,11 @@@ pub struct ImageSelection
drag: Option<(Pos2, Option<Pos2>)>,
/// Crop mode (Acrobat's crop handles): the box kept so far.
pub crop: Option<CropMode>,
+ /// The drag is turning the picture by its rotate handle (the `drag` start is then unused).
+ turning: bool,
+ /// A move or resize applied on release: the frame it had and the one it got, in the page's
+ /// 0..1 coordinates, while the page raster still has the picture where it was.
+ settled: Option<(Rect, Rect)>,
}
/// Cropping a page image: the handles trim instead of resizing, the part that will go is
@@@ -637,7 -547,29 +640,29 @@@ impl ImageSelection
}
}
+ /// The page raster's picture of the box `from`, stretched into `to`, over blanks at `blank` (where
+ /// the screen may still show the picture).
+ fn stretched_picture(painter: &egui::Painter, xf: &PageXform, tex: egui::TextureId, blank: &[Rect], from: Rect, to: Rect) {
+ let clipped = painter.with_clip_rect(painter.clip_rect().intersect(xf.rect));
+ for r in blank {
+ clipped.rect_filled(*r, CornerRadius::ZERO, Color32::WHITE);
+ }
+ let mut mesh = egui::Mesh::with_texture(tex);
+ for (a, b) in [
+ (from.left_top(), to.left_top()),
+ (from.right_top(), to.right_top()),
+ (from.right_bottom(), to.right_bottom()),
+ (from.left_bottom(), to.left_bottom()),
+ ] {
+ let (u, v) = xf.screen_to_norm(a);
+ mesh.vertices.push(egui::epaint::Vertex { pos: b, uv: Pos2::new(u, v), color: Color32::WHITE });
+ }
+ mesh.add_triangle(0, 1, 2);
+ mesh.add_triangle(0, 2, 3);
+ clipped.add(egui::Shape::mesh(mesh));
+ }
+
-/// Once a selected corner is grabbed, text under it cannot take over the gesture. The same
+/// Once a selected corner or the rotate knob is grabbed, text under it cannot take over the gesture. The same
/// applies after the pointer leaves the image/page while dragging.
pub(crate) fn image_owns_pointer(ui: &egui::Ui, xf: &PageXform, page: usize, info: &DocInfo, view: &DocView) -> bool {
let Some(selection) = view.image_selection.as_ref().filter(|s| s.page == page) else { return false };
@@@ -1021,7 -885,7 +1063,7 @@@ pub(crate) fn image_input
_ => egui::CursorIcon::PointingHand,
});
if resp.clicked() || resp.secondary_clicked() {
- view.image_selection = Some(ImageSelection { page, index: hit, drag: None, crop: None, turning: false });
- view.image_selection = Some(ImageSelection { page, index: hit, drag: None, crop: None, settled: None });
++ view.image_selection = Some(ImageSelection { page, index: hit, drag: None, crop: None, turning: false, settled: None });
}
if resp.secondary_clicked() {
ui.ctx().data_mut(|d| d.insert_temp(menu_key, true));