App red round 7 g1: fixes and wiring from the g1 fixer

This commit is contained in:
Dylan M. Taylor
2026-11-19 12:26:11 -05:00
parent f11f16c571
commit 124f0e0420
4 changed files with 89 additions and 96 deletions
+13 -4
View File
@@ -266,13 +266,22 @@ impl PdfCraftApp {
}
fn execute_unguarded(&mut self, ctx: &egui::Context, id: &str) -> bool {
// In Organize the clipboard commands are the picked pages' (the catalog enables them as
// `page.copy`, `page.cut` and `page.paste`).
let organize = self.active.and_then(|i| self.views.get(i)).is_some_and(|v| v.organize);
let page_command = match id {
"edit.copy" => Some("page.copy"),
crate::menus::CUT => Some("page.cut"),
crate::menus::PASTE => Some("page.paste"),
_ => None,
};
if organize && let Some(page_command) = page_command {
return self.execute_unguarded(ctx, page_command);
}
// Paste is the framework's clipboard command, not a registered one: the pages take what
// the clipboard holds (pages in Organize, else objects, a picture or comment text).
// the clipboard holds (objects, a picture or comment text).
if id == crate::menus::PASTE {
let Some(i) = self.active.filter(|&i| i < self.views.len()) else { return false };
if self.views[i].organize {
return self.execute_unguarded(ctx, "page.paste");
}
if self.views[i].session.forms.focus.is_some() {
return false;
}
+20 -60
View File
@@ -20,6 +20,7 @@ use craft::text::ui::editor::{CaretLine, EditKind, EditorEnd, HostLine, HostRun,
use craft::ui::canvas_controls::SelectionOutline;
use craft::ui::contract::{Bind, Props as _, Show as _};
use craft::ui::fonts::FontRef;
use craft::ui::runtime::focus::FocusRequest;
use egui::epaint::text::CharIndex;
use egui::{Pos2, Rect, Vec2, pos2, vec2};
use pdfcraft_engine::{Edit, ObjectKind, ObjectTarget};
@@ -600,59 +601,15 @@ fn look_of_line(l: &pdfcraft_engine::TextLine) -> pdfcraft_engine::AddedText {
source_look(&l.base_font, l.size, l.color, l.bold, l.italic)
}
/// What a drag on a paragraph box's edge takes hold of, for the shape rule ([`grab_at`]).
#[derive(Clone, Copy, Debug, PartialEq)]
enum Grip {
Move,
/// An edge (screen left or right), dragged to rewrap the paragraph.
Left,
Right,
}
/// How far an edge grip reaches either side of a box's edge (screen pixels). Wide enough to
/// catch without aiming for the hairline (#2203); a narrow box still keeps its middle for moving.
/// How far a closed paragraph's edge grabs either side of its line (screen pixels), along its whole
/// height: wide enough to catch without aiming for the hairline (#2203). The width frame's edge band
/// (`BoxRules::with_edge_band`) and the paragraph part's reach are both this wide, so the hover that
/// shows the frame covers the band its press lands on.
const EDGE_REACH: f32 = 8.0;
/// How far outside an open paragraph's frame the pointer still means the frame (screen pixels):
/// the frame's Move cursor shows, and a press there takes hold of the box (`object_ui`).
pub(crate) const FRAME_REACH: f32 = 8.0;
/// The edge of `b` that `p` grabs: anywhere along its height, within reach of the line. A narrow
/// box keeps its middle for moving.
fn edge_at(b: Rect, p: Pos2) -> Option<Grip> {
if p.y < b.top() - EDGE_REACH || p.y > b.bottom() + EDGE_REACH {
return None;
}
let inside = EDGE_REACH.min(b.width() / 4.0);
let (dl, dr) = (p.x - b.left(), b.right() - p.x);
match (dl >= -EDGE_REACH && dl <= inside, dr >= -EDGE_REACH && dr <= inside) {
(true, true) if dl <= dr => Some(Grip::Left),
(_, true) => Some(Grip::Right),
(true, false) => Some(Grip::Left),
_ => None,
}
}
/// The box under `p` and what it grabs there; edges only on an upright page. An edge reaches a
/// little above and below its box, so where that reach overlaps another box the one `p` is level
/// with wins: a press beside one paragraph's edge doesn't rewrap the paragraph just under it.
/// Among boxes equally near, the topmost.
fn grab_at(boxes: &[Rect], p: Pos2, upright: bool) -> Option<(usize, Grip)> {
let mut best: Option<(f32, usize, Grip)> = None;
for (i, b) in boxes.iter().enumerate().rev() {
let grip = match upright.then(|| edge_at(*b, p)).flatten() {
Some(g) => g,
None if b.contains(p) => Grip::Move,
None => continue,
};
// How far above or below the box `p` is: 0 within its height.
let off = (b.top() - p.y).max(p.y - b.bottom()).max(0.0);
if best.is_none_or(|(o, ..)| off < o) {
best = Some((off, i, grip));
}
}
best.map(|(_, i, g)| (i, g))
}
/// A paragraph's box on screen: its text rect (user space), with a little room around it.
fn paragraph_box(xf: &PageXform, info: &DocInfo, page: usize, rect: [f64; 4]) -> Rect {
xf.user_rect(info, page, rect.map(|v| v as f32)).expand(2.0)
@@ -687,9 +644,9 @@ fn page_blocks(session: &mut PageSession, doc: &pdfcraft_engine::Document, page:
}
/// Where a press at the closed paragraph `i` of `boxes` reaches: its box and, on an upright page, the
/// reach of its edges ([`edge_at`]). Where that reach runs toward a box above or below, it ends
/// halfway between them: of two boxes the pointer is level with the nearer one ([`grab_at`]), and the
/// arena's own tie rule (the nearest centre) would not say that.
/// reach of its edges ([`EDGE_REACH`]). Where that reach runs toward a box above or below, it ends
/// halfway between them: of two boxes the pointer is level with the nearer one, and the arena's own
/// tie rule (the nearest centre) would not say that.
fn reach_of(boxes: &[Rect], i: usize, upright: bool) -> Rect {
let Some(b) = boxes.get(i).copied() else { return Rect::NOTHING };
if !upright {
@@ -940,7 +897,8 @@ fn open_waiting(
&& gate
&& !open_here
&& let Some(xf) = session.page_xform(page, geo)
&& let Some((block, _)) = grab_at(boxes, user_to_screen(&xf, &doc.info, page, x, y), false)
&& let at = user_to_screen(&xf, &doc.info, page, x, y)
&& let Some(block) = boxes.iter().rposition(|b| b.contains(at))
{
open_editor(session, doc, page, block, geo);
}
@@ -996,13 +954,15 @@ fn width_frame(
let (block, l, b) = framed?;
let start = doc_rect(&body.view, b);
let state = BoxState::from_rect(start);
// `TransformBox::text_frame`'s rules, showing the left and right handles only.
// `TransformBox::text_frame`'s rules, showing the left and right handles only, each side grabbed
// anywhere along the paragraph's height.
let rules = BoxRules::default()
.with_scale(ScaleRule::Free)
.with_aspect_linked(false)
.with_allow(BoxAllow::new(false, false, false).with_warp(false))
.with_min_side(4.0)
.with_handles(BoxHandles::Sides);
.with_handles(BoxHandles::Sides)
.with_edge_band(EDGE_REACH);
let output = TransformBox::text_frame(tl!("Width").to_string(), Bind::given(state), start).rules(rules).show_at(ui, body.rect);
let after = output.edit.events.iter().find_map(|event| match event {
EditEvent::Commit { after, .. } | EditEvent::Set { after, .. } => Some(*after),
@@ -1250,22 +1210,22 @@ fn editor_session(
let len = ed.text.chars().count();
let mut selection = ed.selection.map_or_else(|| TextSelection::caret_at(len), |s| TextSelection::new(s.anchor.min(len), s.caret.min(len)));
let origin = ed.rect.min;
// An editor opened in this pass takes the keys at once. The press that opened it may lie in the
// paragraph's reach outside the editor, where the editor sees a click away: it doesn't apply it.
let fresh = std::mem::replace(&mut ed.focus, false);
let (output, galley) = {
let mut host = ParagraphHost { ctx: &ctx, ed: &mut *ed, faces: &faces, view: body.view, scale, width, origin, galley: None };
// Escape cancels and selects the paragraph's box (Acrobat); ⌘Enter and a press on the page
// background apply.
let output =
TextEditor::new(tl!("Text editing line").to_string(), &mut host, Bind::bound(&mut selection)).esc_commits(false).show_at(ui, live);
let editor = TextEditor::new(tl!("Text editing line").to_string(), &mut host, Bind::bound(&mut selection)).esc_commits(false);
let output = if fresh { editor.request_focus(FocusRequest::Take) } else { editor }.show_at(ui, live);
(output, host.galley())
};
ed.selection = Some(selection);
// PLAN: framework gap F-6: `TextEditor` has no focus-request prop, so an editor opened by a click
// on the paragraph's part takes the keys only with a press on it.
ed.focus = false;
if ed.has_changes() {
ParagraphText::new(origin, Arc::clone(&galley), text_color).show_at(ui, page_clip);
}
let ended = output.ended;
let ended = output.ended.filter(|end| !(fresh && *end == EditorEnd::Commit));
session.text_background.remember(&xf, page, block, galley, origin, text_color);
match ended {
None => None,
+17 -11
View File
@@ -78,17 +78,22 @@ pub(crate) fn editor_fill(text: Color32) -> Color32 {
/// never asked for.
///
/// The key carries the program's length: resource names such as `F1` repeat across documents.
// PLAN: framework gap F-8: the framework registers each face as a family of its own, so the old
// chain of a face's sibling subsets (Word splits one face over several) is gone, and characters a
// subset lacks fall back to the interface family. A chain option on `document_face` is the
// framework's.
/// Word-created PDFs often split one face into several subsets: each face chains the page's other
/// subsets of the same face, so a character one subset lacks takes a sibling's glyph before the
/// interface family's.
pub(crate) fn source_faces(cx: &impl FacesCx, doc: &pdfcraft_engine::Document, page: usize) -> BTreeMap<String, FontRef> {
let programs: Vec<_> = doc.text_editor_fonts(page).into_iter().filter(|font| !font.choice_only).collect();
// Each program's face key, its resource and its document-face key.
let keys: Vec<(String, &str, String)> = programs
.iter()
.map(|p| (pdfcraft_fonts::embedding::face_key(&p.face), p.resource.as_str(), format!("pdf-source-{}-{}", p.resource, p.bytes.len())))
.collect();
let mut faces = BTreeMap::new();
for program in doc.text_editor_fonts(page).into_iter().filter(|font| !font.choice_only) {
let key = format!("pdf-source-{}-{}", program.resource, program.bytes.len());
let state = cx.document_face(&key, || Some(FaceBytes::new(Arc::from(program.bytes.as_slice()), 0)));
for (program, (face, resource, key)) in programs.iter().zip(&keys) {
let siblings: Vec<String> = keys.iter().filter(|(f, r, _)| f == face && r != resource).map(|(.., k)| k.clone()).collect();
let state = cx.document_face(key, || Some(FaceBytes::new(Arc::from(program.bytes.as_slice()), 0).chain(siblings)));
if let FaceState::Ready(face) = state {
faces.insert(program.resource, face);
faces.insert(program.resource.clone(), face);
}
}
faces
@@ -145,13 +150,14 @@ pub(super) fn editor_job(
if ed.look.size != ed.look0.size {
look.size = ed.look.size;
}
let font = editor_font(&look, (look.size as f32 * scale).clamp(1.0, 300.0));
let mut font = editor_font(&look, (look.size as f32 * scale).clamp(1.0, 300.0));
let original_face =
ed.look.family == ed.look0.family && !ed.family_chosen && ed.look.bold == ed.look0.bold && ed.look.italic == ed.look0.italic;
let source_face = faces.get(&line.font).filter(|_| original_face);
let embedded = source_face.is_some();
// PLAN: framework gap F-7: a ready `FontRef` has no public layout family, so a run cannot
// take its source face yet and is laid out in the interface family.
if let Some(face) = source_face {
font.family = face.family();
}
let native_width = ctx.fonts_mut(|f| f.layout_no_wrap(line.text.clone(), font.clone(), Color32::BLACK).size().x);
let target_width = ((line.rect[2] - line.rect[0]) * look.size / base.max(0.01)) as f32 * scale;
let spacing = if original_face { (target_width - native_width) / line.text.chars().count().saturating_sub(1).max(1) as f32 } else { 0.0 };
+39 -21
View File
@@ -654,8 +654,8 @@ fn the_save_prompt_starts_on_save_every_time_it_opens() {
h.key_press(Key::Enter);
h.run_steps(3);
assert!(h.state().views.is_empty(), "Enter saved and closed");
assert!(out.exists(), "the second prompt opened on Save");
let _ = std::fs::remove_file(out);
// Saves go through the file service, which keeps them in memory.
assert!(FILES.with(|f| f.file(&out)).is_some(), "the second prompt opened on Save");
}
#[test]
@@ -686,12 +686,13 @@ fn keys_leave_the_document_under_a_dialog_alone() {
assert!(h.query_by_label(dont_save()).is_none(), "{m:?}+{key:?} asked to close the file");
assert!(app.session.get(app.views[0].id).unwrap().can_undo().is_some(), "{m:?}+{key:?} undid the rotation");
assert!(app.views[0].find.is_none(), "{m:?}+{key:?} opened Find");
assert!(h.query_by_label("Preferences").is_some(), "{m:?}+{key:?} replaced Preferences");
// The dialog's heading carries its name too: the dialog is the node with its role.
assert!(h.query_by_role_and_label(Role::Dialog, "Preferences").is_some(), "{m:?}+{key:?} replaced Preferences");
}
assert_eq!(page_texts(h.state()), ["Page 1", "Page 2", "Page 3"], "a page was deleted under the dialog");
h.key_press(Key::Escape);
h.run_steps(3);
assert!(h.query_by_label("Preferences").is_none(), "Escape closes Preferences");
assert!(h.query_by_role_and_label(Role::Dialog, "Preferences").is_none(), "Escape closes Preferences");
assert_eq!(h.state().views[0].target_pages(), [1], "Escape went to the dialog, not the page selection");
h.key_press_modifiers(Modifiers::COMMAND, Key::W);
h.run_steps(3);
@@ -878,11 +879,11 @@ fn opening_the_same_path_again_focuses_its_tab() {
let pdfs = TempPdfs::new("dedup-open");
let a = pdfs.file("a.pdf", 1);
let b = pdfs.file("b.pdf", 1);
// Inline opens: this pins the synchronous open contract (open vs focus). A live app
// schedules the background worker instead and answers `Pending` until it completes.
// Every open goes through the open queue and answers `Pending`; its tab appears when the queue is polled. A file
// already in a tab is focused at once.
let mut h = inline_session_harness();
assert_eq!(h.state_mut().open_path(&a), OpenOutcome::Opened);
assert_eq!(h.state_mut().open_path(&b), OpenOutcome::Opened);
assert_eq!(h.state_mut().open_path(&a), OpenOutcome::Pending);
assert_eq!(h.state_mut().open_path(&b), OpenOutcome::Pending);
h.run_steps(2);
assert_eq!(h.state().views.len(), 2, "two different files open two tabs");
assert_eq!(h.state_mut().open_path(&a), OpenOutcome::Focused, "opening an open file focuses, it doesn't reopen");
@@ -896,8 +897,9 @@ fn opening_the_same_path_again_focuses_its_tab() {
fn opening_a_missing_file_fails_and_tells_the_user() {
let mut h = session_harness(|_| {});
let missing = std::env::temp_dir().join(format!("pdfcraft-no-such-file-{}.pdf", std::process::id()));
assert!(matches!(h.state_mut().open_path(&missing.to_string_lossy()), OpenOutcome::Failed(_)));
h.run_steps(2);
// The open is queued; its failure is reported once the read fails.
assert_eq!(h.state_mut().open_path(&missing.to_string_lossy()), OpenOutcome::Pending);
h.run_steps(4);
assert!(h.state().views.is_empty());
assert!(support::shown_notice(&mut h).is_some(), "the failure is still reported to the user");
}
@@ -943,7 +945,8 @@ fn opening_an_encrypted_document_twice_keeps_one_prompt_and_one_tab() {
h.state_mut().open_path(&s);
h.run_steps(2);
assert!(h.state().views.is_empty(), "still locked");
let field = h.get_by_role(Role::PasswordInput);
// One prompt: a second would add a second field.
let field = password_field(&h);
field.focus();
field.type_text("pw");
h.run_steps(2);
@@ -1817,8 +1820,21 @@ fn files_that_cannot_be_read_are_listed_and_left_out_once_the_user_agrees() {
assert_eq!(texts_of(h.state(), 1), ["Page 1", "Page 2", "Page 1"]);
}
/// The password dialog's field. Its text widget's own node is hidden in the field's, so the role alone finds two.
fn password_field<'h>(h: &'h Harness<'static, PdfCraftApp>) -> egui_kittest::Node<'h> {
h.get_by_role_and_label(Role::PasswordInput, "Password")
}
/// The password dialog is open and asks for the permissions password (its OK is Unlock), or for the one that opens
/// the file (Open).
fn password_dialog_asks(h: &Harness<'static, PdfCraftApp>, permissions: bool) {
h.get_by_role(Role::Dialog);
let _ = password_field(h);
h.get_by_role_and_label(Role::Button, if permissions { "Unlock" } else { "Open" });
}
fn type_password(h: &mut Harness<'static, PdfCraftApp>, password: &str) {
let field = h.get_by_role(Role::PasswordInput);
let field = password_field(h);
field.focus();
field.type_text(password);
h.run_steps(1);
@@ -1837,12 +1853,12 @@ fn a_password_protected_file_is_unlocked_with_its_password_and_combined() {
// The row's link (the toolbar's Unlock… comes first).
h.get_all_by_label("Unlock…").last().unwrap().click();
h.run_steps(3);
h.get_by_label("Unlock secret.pdf");
password_dialog_asks(&h, false);
type_password(&mut h, "nope");
h.get_by_label("Wrong password");
assert!(h.state().combine_draft[1].lock.is_some());
// The box stays open for another try.
let field = h.get_by_role(Role::PasswordInput);
let field = password_field(&h);
field.focus();
h.key_press_modifiers(Modifiers::COMMAND, Key::A);
h.run_steps(1);
@@ -1876,7 +1892,9 @@ fn one_password_unlocks_several_selected_files_and_undo_locks_them_again() {
h.run_steps(1);
h.get_all_by_label("Unlock…").next().unwrap().click(); // the toolbar's (the rows' links come after it)
h.run_steps(3);
h.get_by_label("Unlock 3 files");
// One dialog asks for the three files' password.
password_dialog_asks(&h, false);
assert!(h.query_all_by_label_contains("3 files").next().is_some(), "the dialog names the three files");
type_password(&mut h, "same");
let locked: Vec<bool> = h.state().combine_draft.iter().map(|f| f.lock.is_some()).collect();
assert_eq!(locked, [false, false, false, true]);
@@ -1900,7 +1918,7 @@ fn a_file_that_opens_but_forbids_combining_takes_the_permissions_password() {
let _ = h.get_all_by_label_contains("Enter the permissions password");
h.get_all_by_label("Unlock…").last().unwrap().click();
h.run_steps(3);
h.get_by_label("Enter the permissions password to allow combining");
password_dialog_asks(&h, true);
type_password(&mut h, "owner");
assert!(h.state().combine_draft[1].lock.is_none());
assert!(!h.get_by_role_and_label(Role::Button, "Combine").accesskit_node().is_disabled());
@@ -2694,7 +2712,7 @@ fn password_prompt_opens_and_security_tab_reports_the_details() {
});
h.run_steps(4);
h.get_by_label_contains("is protected");
let field = h.get_by_role(Role::PasswordInput);
let field = password_field(&h);
field.focus();
field.type_text("pw");
h.run_steps(2);
@@ -4973,7 +4991,7 @@ fn the_format_panel_restyles_the_paragraph_being_edited() {
h.run_steps(3);
assert!(h.state().views[0].session.line_editor.is_some());
// The Format text panel shows the paragraph's look; making it bold applies at once.
h.get_by_label("FORMAT TEXT");
assert!(h.query_all_by_label("Format text").next().is_some(), "the Format text section shows");
h.get_by_label("Bold").click();
h.run_steps(4);
let s = h.state();
@@ -5012,7 +5030,7 @@ fn the_format_panel_toggles_superscript_and_subscript_on_selection() {
h.run_steps(1);
// Click Superscript: "1" becomes "¹"
h.get_by_label("FORMAT TEXT");
assert!(h.query_all_by_label("Format text").next().is_some(), "the Format text section shows");
let btn = h.get_by_label("Superscript");
btn.click();
h.run_steps(4);
@@ -5125,7 +5143,7 @@ fn typed_small_coloured_text_size_survives_save_and_reopen() {
h.drop_at(at);
h.run_steps(3);
assert!(h.state().views[0].session.line_editor.is_some());
h.get_by_label("Font size:").click();
h.get_by_label("Font size").click();
h.run_steps(1);
h.key_press_modifiers(Modifiers::COMMAND, Key::A);
h.event(egui::Event::Text("6.5".into()));
@@ -10281,7 +10299,7 @@ fn format_panel_shows_selection_size_and_updates_after_font_applied() {
h.run_steps(1);
}
use egui::accesskit::Role;
let size_node = h.get_by_role_and_label(Role::TextInput, "Font size:");
let size_node = h.get_by_role_and_label(Role::TextInput, "Font size");
assert_eq!(size_node.value().as_deref(), Some("12"), "size text input value is 12");
let font_node = h.get_by_role_and_label(Role::ComboBox, "Font");