PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge main into feat/align-selected-lines
RiceDeea33a8bba3810
diff --cc crates/automation/src/tools.rsindex 2b9e1f0ec,4b4ac8873..196808130--- a/crates/automation/src/tools.rs+++ b/crates/automation/src/tools.rs@@@ -626,10 -625,9 +626,10 @@@ pub fn tools() -> Vec<ToolDef>"font": { "type": "string", "enum": ["helvetica", "times", "courier"] }, "size": { "type": "number", "minimum": 1, "maximum": 500 },"bold": { "type": "boolean" }, "italic": { "type": "boolean" }, "color": { "type": "string" },"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },+ "aligns": { "type": "array", "maxItems": 4096, "items": { "enum": ["left", "center", "right", "justify", null] }, "description": "Each paragraph's (line's) own alignment, by index; null follows align." },"char_spacing": { "type": "number", "minimum": -500, "maximum": 500, "description": "Points after each character." },"rotate": { "type": "integer" }, "flip_h": { "type": "boolean" }, "flip_v": { "type": "boolean" },- "crop": { "type": "array", "items": { "type": "number", "minimum": 0, "maximum": 0.49 }, "minItems": 4, "maxItems": 4 },+ "crop": { "type": "array", "items": { "type": "number", "minimum": 0, "maximum": 0.95 }, "minItems": 4, "maxItems": 4, "description": "Fractions trimmed: left, bottom, right, top. Left and right together, and bottom and top together, trim at most 0.95." },"image": { "type": "string", "description": "Replace the picture with this file." },}),&["doc", "page", "index"],diff --cc crates/ui-egui/src/content_ui.rsindex d6ac839f0,0da3b235c..8fbec3079--- a/crates/ui-egui/src/content_ui.rs+++ b/crates/ui-egui/src/content_ui.rs@@@ -618,46 -605,39 +644,51 @@@ pub(crate) fn editor(ctx: &egui::Contex// The box is white in every theme, so the caret must not follow the theme (pale in dark mode) (#655).ui.visuals_mut().text_cursor.stroke.color = crate::edit_text_ui::caret_color_on(Color32::WHITE);let [cr, cg, cb] = t.style.color.map(|v| (v.clamp(0.0, 1.0) * 255.0) as u8);- // Laid out as the page draws it, so opening the box doesn't show it realigned.- // shortcut: justified text is shown left-aligned here (TextEdit can't justify), until the editor gets its own layouter.- let halign = match t.style.align {- pdfcraft_engine::TextAlign::Center => egui::Align::Center,- pdfcraft_engine::TextAlign::Right => egui::Align::Max,- pdfcraft_engine::TextAlign::Left | pdfcraft_engine::TextAlign::Justify => egui::Align::Min,- };+ let color = Color32::from_rgb(cr, cg, cb);// Character spacing shows as the page will draw it, scaled like the font.let letter_spacing = (t.style.char_spacing * f64::from(zoom)) as f32;- let mut spaced = |ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap_width: f32| {- let job = spaced_job(text.as_str(), &font, Color32::from_rgb(cr, cg, cb), letter_spacing, wrap_width, halign);- ui.fonts_mut(|f| f.layout_job(job))+ // Laid out as the page draws it, each paragraph with its own alignment, so opening the+ // box doesn't show it realigned.+ let style = t.style.clone();+ let line_font = font.clone();+ let mut layouter = |ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap: f32| {+ aligned_galley(ui, text.as_str(), &style, &line_font, color, letter_spacing, wrap)};+ let before = t.text.clone();+ let input = input_id();+ t.claim_typing(ui.ctx(), doc_id);ui.horizontal_top(|ui| {ui.spacing_mut().item_spacing.x = 4.0;- let mut edit = egui::TextEdit::multiline(&mut t.text)- .font(font.clone())+ let output = egui::TextEdit::multiline(&mut t.text)+ .font(font).desired_width(width).desired_rows(1)- .align(egui::Align2::new(halign, egui::Align::TOP))+ .layouter(&mut layouter)+ // Keep the page editor's original inset; the theme's larger button padding+ // otherwise shifts narrow right-aligned boxes away from their text edge.+ .margin(egui::Margin::symmetric(4, 2)).background_color(if background_ready { Color32::TRANSPARENT } else { Color32::WHITE })- .text_color(Color32::from_rgb(cr, cg, cb))+ .text_color(color).hint_text(tl!("Type text"))- .id_salt("added-text-edit");- if letter_spacing != 0.0 {- edit = edit.layouter(&mut spaced);+ .id(input)+ .show(ui);+ let resp = output.response;+ if let Some(cursor) = output.cursor_range {+ let chars = cursor.as_sorted_char_range();+ let byte = |index: usize| t.text.char_indices().nth(index).map_or(t.text.len(), |(at, _)| at);+ t.selection = Some(byte(chars.start.into())..byte(chars.end.into()));+ }+ // Each paragraph keeps its own alignment through the typing.+ if t.text != before {+ crate::edit_text_ui::follow_typing(ui.ctx(), input, &before, &t.text, &mut [&mut t.style.aligns]);}- let resp = ui.add(edit).accessible_name(tl!("Added text"));++ // The editor has no visible label; name it for assistive tech.++ resp.response.clone().accessible_name(tl!("Added text"));if t.focus {resp.request_focus();+ if let Some(range) = &t.selection {+ crate::edit_text_ui::reselect(ui.ctx(), input, &t.text, range);+ }t.focus = false;}let buttons = egui::Frame::NONE@@@ -727,63 -697,6 +758,63 @@@ fn finish(cv: &mut ContentView, d: Text}}+/// The added-text box's text field.+pub(crate) fn input_id() -> egui::Id {- egui::Id::new("added-text-input")++ egui::Id::unique("added-text-input")+}++/// `text` laid out as added text with `style` is drawn: each paragraph (line typed with Enter) wrapped+/// to `wrap` and placed by its own alignment, a justified one with every row but its last+/// stretched.+fn aligned_galley(+ ui: &egui::Ui,+ text: &str,+ style: &AddedText,+ font: &egui::FontId,+ color: Color32,+ letter_spacing: f32,+ wrap: f32,+) -> std::sync::Arc<egui::Galley> {+ use pdfcraft_engine::TextAlign;+ let job = |text: &str, align: TextAlign| {+ let mut job = spaced_job(text, font, color, letter_spacing, wrap, egui::Align::Min);+ job.justify = align == TextAlign::Justify;+ job+ };+ let uniform = text.split('\n').enumerate().all(|(i, _)| style.paragraph_align(i) == style.align);+ if uniform && style.align != TextAlign::Center && style.align != TextAlign::Right {+ return ui.fonts_mut(|f| f.layout_job(job(text, style.align)));+ }+ // Each paragraph on its own (egui aligns a whole job one way), its rows moved within the+ // box's width, then joined in order: the caret and selection see one text.+ let mut galleys = Vec::new();+ let mut start = 0;+ for (i, paragraph) in text.split('\n').enumerate() {+ let end = start + paragraph.len();+ // The last paragraph keeps a trailing break, as egui's own split does.+ let last = end + 1 == text.len();+ let piece = if last { text.get(start..).unwrap_or_default() } else { paragraph };+ let mut galley = ui.fonts_mut(|f| f.layout_job(job(piece, style.paragraph_align(i))));+ let g = std::sync::Arc::make_mut(&mut galley);+ for placed in &mut g.rows {+ let free = (wrap - placed.row.size.x).max(0.0);+ placed.pos.x = match style.paragraph_align(i) {+ TextAlign::Center => free / 2.0,+ TextAlign::Right => free,+ TextAlign::Left | TextAlign::Justify => 0.0,+ };+ }+ g.rect = Rect::from_min_max(Pos2::ZERO, Pos2::new(g.rect.width().max(wrap), g.rect.height()));+ galleys.push(galley);+ if last {+ break;+ }+ start = end + 1;+ }+ let whole = std::sync::Arc::new(spaced_job(text, font, color, letter_spacing, wrap, egui::Align::Min));+ std::sync::Arc::new(egui::Galley::concat(whole, &galleys, ui.ctx().pixels_per_point()))+}+/// How to use the tools, under the Add content list.pub(crate) fn hint(ui: &mut egui::Ui, t: &Tokens) {ui.label(diff --cc crates/ui-egui/src/edit_text_ui.rsindex 69b08e49e,4f5630c0b..793383b99--- a/crates/ui-egui/src/edit_text_ui.rs+++ b/crates/ui-egui/src/edit_text_ui.rs@@@ -260,118 -260,6 +260,118 @@@ pub struct LineEditor/// horizontal scale (%), and what they were.pub extras: Extras,extras0: Extras,+ /// The text the box's own Undo history starts from; see [`forget_typing_before`].+ typing_from: Option<String>,+}++/// The paragraph editor's text box.+pub(crate) fn input_id() -> egui::Id {- egui::Id::new("edit-text-line-input")++ egui::Id::unique("edit-text-line-input")+}++/// The page text box `id` keeps its own Undo history, across every paragraph or box it has shown+/// in every tab (they share the id). Once the page has `text` (the box opened on it, or formatting+/// applied it), that history is cleared: Undo in the box takes back only what was typed since, and+/// then reaches the document. Kept, it put back text from another paragraph, or the whole paragraph+/// as it was before a format change, into a box showing the page as it is now. `from` is the box's+/// own record of that; which document `doc` last used the history is kept beside it, since a box+/// in another tab on the same text would otherwise take that document's typing with its Redo.+/// When another document's box takes the text box, the box it leaves keeps its history (and+/// caret) aside, and gets it back on its return, so its typing can still be undone there. Each+/// box claims the text box when it is drawn, and Undo and Redo from the menu claim it first too,+/// since they can run before the box is drawn again after a tab switch.+pub(crate) fn forget_typing_before(ctx: &egui::Context, id: egui::Id, doc: pdfcraft_engine::DocId, from: &mut Option<String>, text: &str) {+ let owner = id.with("typing-doc");+ let last = ctx.data(|d| d.get_temp::<pdfcraft_engine::DocId>(owner));+ if from.as_deref() == Some(text) && last == Some(doc) {+ return;+ }+ let aside = |doc: pdfcraft_engine::DocId| id.with(("typing-aside", doc));+ let aligns = id.with(ALIGN_HISTORY);+ if let Some(left) = last.filter(|l| *l != doc)+ && let Some(state) = egui::TextEdit::load_state(ctx, id)+ {+ // A copy of its own: a state's history is shared between its clones, and the next box+ // clears it in place. The rows' alignments by text go with it.+ let mut kept = egui::text_edit::TextEditState::default();+ kept.cursor = state.cursor;+ kept.set_undoer(state.undoer());+ ctx.data_mut(|d| {+ let rows = d.get_temp::<AlignHistory>(aligns).unwrap_or_default();+ d.insert_temp(aside(left), (kept, rows));+ });+ }+ // Only the same box, still on the text it opened on, takes its history back.+ let back =+ ctx.data_mut(|d| d.remove_temp::<(egui::text_edit::TextEditState, AlignHistory)>(aside(doc))).filter(|_| from.as_deref() == Some(text));+ // A box new to the text box starts with nothing of the last one's: no history, caret,+ // selection or rows' alignments by text.+ let (state, rows) = back.unwrap_or_default();+ egui::TextEdit::store_state(ctx, id, state);+ ctx.data_mut(|d| {+ d.insert_temp(owner, doc);+ d.insert_temp(aligns, rows);+ });+ *from = Some(text.to_owned());+}++/// Each text a page box has shown through its own typing, with its rows' alignments then, oldest+/// last: egui's history keeps only the text and the caret.+type AlignHistory = Vec<(String, Vec<Vec<Option<pdfcraft_engine::TextAlign>>>)>;+const ALIGN_HISTORY: &str = "aligns-by-text";+/// As many texts as egui's own history keeps.+const ALIGN_HISTORY_LEN: usize = 100;++/// The page text box `id` went from `before` to `after` through its own typing (typing, Undo or+/// Redo), and each list of row alignments in `aligns` follows. A text the box showed before gets+/// back the alignments it had then, so Undo bringing back a deleted row brings back its+/// alignment; a new text follows the edit ([`pdfcraft_engine::paragraph_align::remap`]). An+/// alignment picked since makes the older texts' alignments stale, and they are dropped.+pub(crate) fn follow_typing(+ ctx: &egui::Context,+ id: egui::Id,+ before: &str,+ after: &str,+ aligns: &mut [&mut Vec<Option<pdfcraft_engine::TextAlign>>],+) {+ let now: Vec<Vec<_>> = aligns.iter().map(|a| a.to_vec()).collect();+ let next = ctx.data_mut(|d| {+ let seen = d.get_temp_mut_or_default::<AlignHistory>(id.with(ALIGN_HISTORY));+ if seen.iter().any(|(text, was)| text == before && *was != now) {+ seen.clear();+ }+ remember(seen, before, now.clone());+ let next = match seen.iter().rev().find(|(text, _)| text == after) {+ Some((_, was)) if was.len() == now.len() => was.clone(),+ _ => now.iter().map(|a| pdfcraft_engine::paragraph_align::remap(before, after, a)).collect(),+ };+ remember(seen, after, next.clone());+ next+ });+ for (slot, a) in aligns.iter_mut().zip(next) {+ **slot = a;+ }+}++fn remember(seen: &mut AlignHistory, text: &str, aligns: Vec<Vec<Option<pdfcraft_engine::TextAlign>>>) {+ seen.retain(|(t, _)| t != text);+ seen.push((text.to_owned(), aligns));+ if seen.len() > ALIGN_HISTORY_LEN {+ seen.remove(0);+ }+}++/// Select `range` (bytes of `text`) in the page text box `id` again. egui keeps a box's selection+/// only while it has the focus, so a click on Format text drops it; given back as formatting+/// returns the focus, it stays shown, and a second choice reaches the same text.+pub(crate) fn reselect(ctx: &egui::Context, id: egui::Id, text: &str, range: &std::ops::Range<usize>) {+ let chars = |at: usize| text.get(..at).map(|s| s.chars().count());+ let (Some(start), Some(end)) = (chars(range.start), chars(range.end)) else { return };+ if start < end {+ let mut state = egui::TextEdit::load_state(ctx, id).unwrap_or_default();+ state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(start), egui::text::CCursor::new(end))));+ egui::TextEdit::store_state(ctx, id, state);+ }}#[derive(Clone, Copy, Debug, PartialEq)]@@@ -1938,109 -1783,6 +1953,109 @@@ pub(crate) fn caret_color_on(fill: Colomod tests {use super::*;+ /// Formatting applied restarts the rows' alignments by text with the box's history: a Redo+ /// past the format can't bring back an alignment from before it (FredApps on bfc6f8b1).+ #[test]+ fn formatting_applied_restarts_the_alignments_by_text() {+ use pdfcraft_engine::{DocId, TextAlign::Right};- let (ctx, id) = (egui::Context::default(), egui::Id::new("box"));++ let (ctx, id) = (egui::Context::default(), egui::Id::unique("box"));+ let mut from = None;+ forget_typing_before(&ctx, id, DocId(1), &mut from, "A\nB");+ let mut aligns = vec![None, Some(Right)];+ follow_typing(&ctx, id, "A\nB", "A", &mut [&mut aligns]);+ // Formatting applied: the page now has "A", and the box's record of its text is reset.+ from = None;+ forget_typing_before(&ctx, id, DocId(1), &mut from, "A");+ follow_typing(&ctx, id, "A", "A\nB", &mut [&mut aligns]);+ assert_eq!(aligns, pdfcraft_engine::paragraph_align::remap("A", "A\nB", &[None]), "the row before the format doesn't come back aligned");+ }++ /// The rows' alignments by text go aside with the box's history when another tab's box takes+ /// the text box, and come back with it: Undo after the trip still restores a deleted row's+ /// alignment, while the other tab's box starts with none.+ #[test]+ fn alignments_by_text_survive_a_trip_to_another_tab() {+ use pdfcraft_engine::{DocId, TextAlign::Right};- let (ctx, id) = (egui::Context::default(), egui::Id::new("box"));++ let (ctx, id) = (egui::Context::default(), egui::Id::unique("box"));+ let (mut a_from, mut b_from) = (None, None);+ forget_typing_before(&ctx, id, DocId(1), &mut a_from, "A\nB");+ let mut aligns = vec![None, Some(Right)];+ follow_typing(&ctx, id, "A\nB", "A", &mut [&mut aligns]);+ forget_typing_before(&ctx, id, DocId(2), &mut b_from, "A\nB");+ let mut other = vec![None, None];+ follow_typing(&ctx, id, "A\nB", "A", &mut [&mut other]);+ follow_typing(&ctx, id, "A", "A\nB", &mut [&mut other]);+ assert_eq!(other, [None, None], "tab B's box gets back its own alignments, not tab A's");+ forget_typing_before(&ctx, id, DocId(1), &mut a_from, "A\nB");+ follow_typing(&ctx, id, "A", "A\nB", &mut [&mut aligns]);+ assert_eq!(aligns, [None, Some(Right)], "back in tab A, Undo brings the row back right-aligned");+ }++ /// Undo back to a text the box showed brings its rows' alignments back, unless an alignment+ /// was picked since: then the older alignments are stale, and the edit is followed instead, so+ /// Undo never takes back the pick.+ #[test]+ fn typing_history_restores_alignments_unless_one_was_picked_since() {+ use pdfcraft_engine::TextAlign::{Center, Right};- let (ctx, id) = (egui::Context::default(), egui::Id::new("box"));++ let (ctx, id) = (egui::Context::default(), egui::Id::unique("box"));+ let mut aligns = vec![None, Some(Center), Some(Right)];+ follow_typing(+ &ctx,+ id,+ "A+B+C",+ "A+C",+ &mut [&mut aligns],+ );+ assert_eq!(aligns, [None, Some(Right)], "the deleted row's entry goes");+ follow_typing(+ &ctx,+ id,+ "A+C",+ "A+B+C",+ &mut [&mut aligns],+ );+ assert_eq!(aligns, [None, Some(Center), Some(Right)], "Undo brings it back");+ follow_typing(+ &ctx,+ id,+ "A+B+C",+ "A+C",+ &mut [&mut aligns],+ );+ // An alignment picked for the first row, with no typing.+ aligns = vec![Some(Right), Some(Right)];+ let picked = aligns.clone();+ follow_typing(+ &ctx,+ id,+ "A+C",+ "A+B+C",+ &mut [&mut aligns],+ );+ assert_eq!(+ aligns,+ pdfcraft_engine::paragraph_align::remap(+ "A+C", "A+B+C", &picked+ ),+ "the pick stays"+ );+ }+#[test]fn the_rotate_knob_moves_below_when_there_is_no_room_above() {let view = Rect::from_min_max(Pos2::new(0.0, 100.0), Pos2::new(500.0, 500.0));