compile fix 2 (shell): type errors after the L-171 codemod (swarm/cfix2); committed by the lead

This commit is contained in:
Dylan M. Taylor
2026-11-18 16:44:16 -05:00
parent ede367abd3
commit dca15f5029
44 changed files with 391 additions and 261 deletions
+13 -11
View File
@@ -441,7 +441,8 @@ impl PdfCraftApp {
replace_source: None,
#[cfg(not(target_arch = "wasm32"))]
document_fonts: None,
last_opened_url: None,
pending_urls: Vec::new(),
startup_superseded: false,
community_card_closed: false,
pending_link: None,
pending_window: None,
@@ -601,10 +602,7 @@ impl eframe::App for PdfCraftApp {
self.begin_logic();
#[cfg(not(target_arch = "wasm32"))]
self.update_logic(ctx);
self.guarded_frame(|app| app.logic_unguarded(ctx));
if self.frame_panicked {
self.close_after_panic(ctx);
}
self.guarded_frame(ctx, |app| app.logic_unguarded(ctx));
self.run_close_path(ctx);
}
@@ -616,7 +614,8 @@ impl eframe::App for PdfCraftApp {
if let Some(panels) = self.file_panels.as_mut() {
panels.pump_with(&mut self.dialogs, Some(&*frame));
}
self.guarded_frame(|app| app.ui_unguarded(ui));
let ctx = ui.ctx().clone();
self.guarded_frame(&ctx, |app| app.ui_unguarded(ui));
self.end_ui();
}
}
@@ -636,7 +635,7 @@ impl PdfCraftApp {
pdfcraft_engine::dates::use_form_date_language(self.session.date_language().unwrap_or(lang.code()));
#[cfg(not(target_arch = "wasm32"))]
{
self.poll_pending_opens();
self.poll_pending_opens(ctx);
self.poll_pending_destinations();
}
self.check_restored_recent();
@@ -656,7 +655,7 @@ impl PdfCraftApp {
self.autosave_tick(ctx, web_time::Instant::now());
// Reload documents whose files a build rewrote (#431).
#[cfg(not(target_arch = "wasm32"))]
self.watch_files();
self.watch_files(ctx);
if self.host_dirty.is_some() {
// An OCR review not yet accepted or rejected is work the page would lose, too.
let dirty = self.work_at_risk();
@@ -677,7 +676,7 @@ impl PdfCraftApp {
// Edit text and Add text's drags end while their input is blocked rather than wait, to
// land wherever the pointer is once it opens again.
if shut && matches!(self.quick_tool, QuickTool::EditText | QuickTool::AddText) {
view.cancel_edit_text_gestures();
view.cancel_pointer_gestures(ctx);
}
}
self.process_pending_edits();
@@ -777,7 +776,10 @@ impl PdfCraftApp {
dialogs::show(self, ui);
crate::notices::show(self, ui);
// Screenshots are issued only after a settled pass that really drew the window.
// PLAN: assumed PdfCraftApp::control_frame_end(&mut self, &egui::Context), the control channel's capture issue after the pass (pdf-shell-w11).
self.control_frame_end(&ctx);
self.control_ui_pass(&ctx);
// Addresses `open_url` queued: the runtime opens them in the browser.
for url in self.pending_urls.drain(..) {
ctx.open_url(egui::OpenUrl::new_tab(url));
}
}
}
+3 -3
View File
@@ -429,7 +429,7 @@ mod review_tests {
/// One frame's paste events offered, then Paste run as its command; the images on page 1.
fn paste(app: &mut PdfCraftApp, events: Vec<egui::Event>) -> usize {
app.offer_pasted(&egui::RawInput { events, ..Default::default() });
assert!(app.execute("edit.paste"));
assert!(app.execute(&egui::Context::default(), "edit.paste"));
app.session.get(app.views[0].id).unwrap().page_images(0).len()
}
@@ -467,7 +467,7 @@ mod review_tests {
fn review_failed_keyboard_cut_keeps_the_image_selection() {
let (mut app, _) = app_with_clipboard();
app.views[0].session.image_selection = Some(crate::edit_text_ui::ImageSelection::at(0, 0));
app.execute("edit.cut");
app.execute(&egui::Context::default(), "edit.cut");
assert!(app.views[0].session.image_selection.is_some());
}
@@ -487,7 +487,7 @@ mod review_tests {
app.views[0].session.texts.clear();
app.views[0].select_text(0, 0, 0);
assert!(app.views[0].selection_waits_for_text().is_some());
assert!(app.execute("edit.copy"));
assert!(app.execute(&egui::Context::default(), "edit.copy"));
assert_eq!(jobs.waiting(), 1, "the selection's copy started");
assert!(app.comment_clipboard.is_none(), "the comment was not copied");
assert!(writes.lock().unwrap().is_empty(), "no comment payload reached the clipboard");
+14 -11
View File
@@ -13,7 +13,7 @@ impl PdfCraftApp {
.flat_map(|g| g.sections.iter().flat_map(|s| s.items.iter()))
.any(|i| i.command == spec.id);
if self.active.is_none() && needs_document && is_tool && !self.command_enabled(spec) {
self.open_then_run(spec);
self.open_then_run(ctx, spec);
return;
}
self.execute(ctx, command);
@@ -35,12 +35,14 @@ impl PdfCraftApp {
/// Ask for a file to open, then run `spec` on it once it is open (or unlocked). Nothing runs
/// when the picker is cancelled or the file doesn't open.
fn open_then_run(&mut self, spec: &'static pdfcraft_engine::commands::CommandSpec) {
fn open_then_run(&mut self, ctx: &egui::Context, spec: &'static pdfcraft_engine::commands::CommandSpec) {
self.startup_superseded = true;
let request = craft::host::PickRequest::open("open").title(tl!(spec.label).trim_end_matches('…'));
let command = spec.id;
// PLAN: assumed `open_picked_then(&mut self, Picked, &'static str)` (pdf-shell-w13), which opens desktop paths and browser contents alike.
self.pick_file(request, None, move |app, picked| app.open_picked_then(picked, command));
// The continuation runs on the pass that takes the answer, which has no context of its
// own: it gets this one, a handle to the same window.
let ctx = ctx.clone();
self.pick_file(request, None, move |app, picked| app.open_picked_then(&ctx, picked, command));
}
pub(crate) fn reveal_tools(&mut self) {
@@ -156,7 +158,8 @@ impl PdfCraftApp {
self.enter_mode(mode);
}
if mode == Mode::Read && !was_read {
self.right_before_read = self.right.take();
self.right_before_read = self.right();
self.set_right(None);
// An editing tool is put down so its open paragraph is applied, as `select_mode` does.
if matches!(self.quick_tool, QuickTool::EditText | QuickTool::AddText) {
self.put_down_edit_text();
@@ -165,8 +168,8 @@ impl PdfCraftApp {
}
} else if mode != Mode::Read && was_read {
let before = self.right_before_read.take();
if self.right.is_none() {
self.right = before;
if self.right().is_none() {
self.set_right(before);
}
}
}
@@ -180,15 +183,15 @@ impl PdfCraftApp {
}
if panel == Some(RightPanel::Comments) {
self.comments_panel_closed = false;
} else if panel.is_none() && self.right == Some(RightPanel::Comments) {
} else if panel.is_none() && self.right() == Some(RightPanel::Comments) {
self.comments_panel_closed = true;
}
if panel.is_some() {
self.right_panel_closed = false;
} else if self.right.is_some() {
} else if self.right().is_some() {
self.right_panel_closed = true;
}
self.right = panel;
self.set_right(panel);
if let Some(panel) = panel {
self.last_right = panel;
}
@@ -196,6 +199,6 @@ impl PdfCraftApp {
/// F4: closes the side panel, or reopens the one open last.
pub(crate) fn toggle_side_panel(&mut self) {
self.choose_right_panel(if self.right.is_some() { None } else { Some(self.last_right) });
self.choose_right_panel(if self.right().is_some() { None } else { Some(self.last_right) });
}
}
+62 -28
View File
@@ -51,7 +51,7 @@ impl PdfCraftApp {
self.set_motion(motion);
}
("panel", _) => {
self.right = match value {
let panel = match value {
"comments" => Some(RightPanel::Comments),
"bookmarks" => Some(RightPanel::Bookmarks),
"pages" => Some(RightPanel::Pages),
@@ -65,7 +65,8 @@ impl PdfCraftApp {
"compare" => Some(RightPanel::Compare),
"none" => None,
other => return Err(format!("unknown panel {other}")),
}
};
self.set_right(panel);
}
("mode", _) => {
let mode = Mode::parse(value).unwrap_or(Mode::AllTools);
@@ -105,14 +106,18 @@ impl PdfCraftApp {
// The palette opens empty: typing reaches it through the runtime's input, as a user's.
("palette", _) => self.palette_open = true,
("page", Some(v)) => v.go_to_page(value.parse::<usize>().map_err(|e| e.to_string())?.saturating_sub(1)),
("zoom", Some(v)) => v.set_zoom(DocView::parse_zoom_percent(value).ok_or("zoom must be a percentage above 0")?),
("zoom", Some(v)) => {
let zoom = DocView::parse_zoom_percent(value).ok_or("zoom must be a percentage above 0")?;
v.view.zoom = f64::from(zoom);
v.view.fit = canvas::Fit::None;
}
("layout", Some(v)) => {
let (layout, continuous) = canvas::parse_display_token(value).ok_or("layout must be single, continuous, two-up or two-page")?;
v.set_display(layout, continuous);
let (display, continuous) = canvas::parse_display_token(value).ok_or("layout must be single, continuous, two-up or two-page")?;
(v.view.display, v.view.continuous) = (display, continuous);
}
("continuous", Some(v)) => match value {
"on" => v.set_continuous(true),
"off" => v.set_continuous(false),
"on" => v.view.continuous = true,
"off" => v.view.continuous = false,
_ => return Err("continuous must be on or off".into()),
},
("page-gaps", Some(_)) => {
@@ -124,7 +129,7 @@ impl PdfCraftApp {
self.set_active_page_gaps(show);
}
("default-page-gaps", _) => {
self.view_defaults.show_page_gaps = match value {
self.view_defaults.page_gaps = match value {
"on" => true,
"off" => false,
_ => return Err("default-page-gaps must be on or off".into()),
@@ -145,12 +150,12 @@ impl PdfCraftApp {
if on && !v.cover_applies() {
return Err("switch to two-page view first to show the cover page".into());
}
v.set_cover(on);
v.view.cover = on;
}
("default-layout", _) => {
let (layout, continuous) =
let (display, continuous) =
canvas::parse_display_token(value).ok_or("default-layout must be single, continuous, two-up or two-page")?;
(self.view_defaults.layout, self.view_defaults.continuous) = (layout, continuous);
(self.view_defaults.display, self.view_defaults.continuous) = (display, continuous);
}
("default-continuous", _) => {
self.view_defaults.continuous = match value {
@@ -191,8 +196,7 @@ impl PdfCraftApp {
if !percent.is_finite() || !craft::pages::ui::THUMBNAIL_ZOOM.range().contains(&(percent / 100.0)) {
return Err("thumbnail-zoom must be between 50 and 150".into());
}
// PLAN: assumed `set_thumbnail_zoom(f64)` (the canvas owner of `zoom.rs`, CV-C27).
v.set_thumbnail_zoom(percent / 100.0);
v.set_thumbnail_zoom((percent / 100.0) as f32);
}
// `--grid-zoom 150`: the size of the pages in the organize grid, in percent. The
// grid's size is one for every document, as it is remembered.
@@ -239,8 +243,14 @@ impl PdfCraftApp {
v.select_pages(&pages);
}
// `--select-text 2:10-40`: characters 10 to 40 of page 2 selected, as a drag would.
// PLAN: assumed `DocView::select_text_spec(&mut self, &str) -> Result<(), String>` (pdf-canvas-w8, canvas-02 CH-1).
("select-text", Some(v)) => v.select_text_spec(value)?,
("select-text", Some(v)) => {
const USAGE: &str = "select-text: PAGE:FROM-TO";
let (page, span) = value.split_once(':').ok_or(USAGE)?;
let (from, to) = span.split_once('-').ok_or(USAGE)?;
let number = |text: &str| text.trim().parse::<usize>().map_err(|_| USAGE);
let page = number(page)?.checked_sub(1).filter(|page| *page < v.page_count()).ok_or("select-text: no such page")?;
v.select_text(page, number(from)?, number(to)?);
}
// `--prepare-select NAME[:WIDGET]`: one form field selected in Prepare a form.
("prepare-select", Some(v)) => {
let (name, widget) = match value.rsplit_once(':') {
@@ -249,11 +259,36 @@ impl PdfCraftApp {
};
v.session.prepare.selected = Some((name.to_string(), widget));
}
// PLAN: assumed `CommentPrefs::set_recent_colours(&mut self, &str) -> Result<(), String>` (pdf-comments, H-18).
("recent-colours", _) => self.comment_prefs.set_recent_colours(value)?,
// `progress-hold 0.4` shows the card of a held fake job at that fraction, with Cancel;
// `null` takes it away.
("progress-hold", _) => {
// PLAN: assumed the field `progress_hold: bool` that keeps progress cards up (pdf-chrome-w19, chrome-03 :146).
self.progress_hold = value.parse::<bool>().map_err(|_| "progress-hold must be true or false")?;
use crate::notices::{ProgressKey, ProgressNotice, end_progress, set_progress};
if value == "null" {
end_progress(self, ProgressKey::Export);
} else {
let fraction = value.parse::<f32>().map_err(|_| "progress-hold must be a fraction or null")?;
set_progress(
self,
ProgressKey::Export,
ProgressNotice { label: tl!("Held for a capture").to_owned(), fraction, cancellable: true },
);
}
}
// `--recent-colours ff0000,00ff00`: the custom colours the pickers remember, as hex, the
// first ending up newest.
("recent-colours", _) => {
let hex = |text: &str| -> Result<[f64; 3], String> {
let digits = text.trim().trim_start_matches('#');
let channel = |at: usize| digits.get(at..at + 2).and_then(|pair| u8::from_str_radix(pair, 16).ok()).map(|v| f64::from(v) / 255.0);
match (digits.len(), channel(0), channel(2), channel(4)) {
(6, Some(r), Some(g), Some(b)) => Ok([r, g, b]),
_ => Err(format!("recent-colours: `{text}` is not a hex colour (rrggbb)")),
}
};
let colours = value.split(',').filter(|text| !text.trim().is_empty()).map(hex).collect::<Result<Vec<_>, _>>()?;
for colour in colours.into_iter().rev() {
self.recent_colours.remember(colour);
}
}
#[cfg(feature = "capture")]
// PLAN: assumed `Updates::set_source(&mut self, &str) -> Result<(), String>` (pdf-shell, shell-03 :119).
@@ -340,9 +375,9 @@ impl PdfCraftApp {
};
}
("system-title-bar", _) => {
self.system_title_bar = match value {
"true" => true,
"false" => false,
self.title_bar_choice = match value {
"true" => craft::window::policy::TitleBarPref::System,
"false" => craft::window::policy::TitleBarPref::Integrated,
_ => return Err("system-title-bar must be true or false".into()),
};
}
@@ -360,8 +395,7 @@ impl PdfCraftApp {
(p.trim().parse().map_err(|_| "comment: PAGE:INDEX")?, i.trim().parse().map_err(|_| "comment: PAGE:INDEX")?);
let thread = (p.saturating_sub(1), i.saturating_sub(1));
v.session.comments.select_only(thread);
// PLAN: assumed `CommentsPanel::reveal(&mut self, (usize, usize))` (pdf-comments-w12).
v.session.comments.panel.reveal(thread);
v.session.comments.reveal = true;
}
// `--combine-view list`: Combine files as thumbnails (grid) or as the table (list).
("combine-view", _) => {
@@ -428,7 +462,7 @@ impl PdfCraftApp {
"header-footer" => self.open_marks(ctx, MarkKind::HeaderFooter, false),
"watermark" => self.open_marks(ctx, MarkKind::Watermark, false),
"background" => self.open_marks(ctx, MarkKind::Background, false),
"printer-marks" => self.open_printer_marks(),
"printer-marks" => self.open_printer_marks(ctx),
"export-image" => export_ui::open(self, ctx, export_ui::ExportKind::Image),
"word-count" => self.open_word_count(),
"export-text" => export_ui::open(self, ctx, export_ui::ExportKind::Text),
@@ -453,8 +487,8 @@ impl PdfCraftApp {
let page = self.active.and_then(|i| self.views.get(i)).map_or(0, |v| v.current());
self.start_signing(page, None, None, (value == "certify").then_some(2));
}
"number-pages" => self.open_number_pages(),
"convert-colours" => self.open_convert_colours(),
"number-pages" => self.open_number_pages(ctx),
"convert-colours" => self.open_convert_colours(ctx),
// Through the command, so it is refused with no document or none that can be
// modified, as the menu is.
"fix-hairlines" => {
@@ -481,7 +515,7 @@ impl PdfCraftApp {
prepare::dialog::open(self, &name, widget, prepare::FieldTab::General);
}
"none" => {
self.cancel_dialogs();
self.cancel_dialogs(ctx);
self.redact_props = None;
self.redact_search_open = false;
self.hidden_draft = None;
+42 -43
View File
@@ -25,9 +25,8 @@ pub(crate) fn same_file(open: &str, path: &str) -> bool {
impl PdfCraftApp {
/// Shows `panel` as the right panel, or closes the one showing for `None`.
fn set_right(&mut self, panel: Option<RightPanel>) {
pub(crate) fn set_right(&mut self, panel: Option<RightPanel>) {
use crate::side_panels::{PanelId, set_panel_visible};
// PLAN: assumed `PanelId::from(RightPanel)` (pdf-chrome-w13)
match panel {
Some(panel) => set_panel_visible(self, PanelId::from(panel), true),
None => {
@@ -50,9 +49,7 @@ impl PdfCraftApp {
// (`/NonFullScreenPageMode`, Table 147), there when the prompt is declined or full
// screen is left.
let navigation = if v.full_screen { v.non_full_screen } else { v.navigation };
// PLAN: `right_panel_closed()` is a read-only view assumed from pdf-chrome-w13 (L-136); canvas-w11's
// `view.view` setters below land with that set.
if self.active == Some(index) && !self.right_panel_closed() {
if self.active == Some(index) && !self.right_panel_closed {
let panel = match navigation {
N::PageOnly => None,
N::Bookmarks => Some(RightPanel::Bookmarks),
@@ -83,11 +80,11 @@ impl PdfCraftApp {
match v.magnification {
// The view opened at the default zoom already.
M::Default => {}
M::ActualSize => view.set_zoom(1.0),
M::Percent(p) => view.set_zoom((p / 100.0) as f32),
M::FitPage | M::FitVisible => view.fit = canvas::Fit::Page,
M::FitWidth => view.fit = canvas::Fit::Width,
M::FitHeight => view.fit = canvas::Fit::Height,
M::ActualSize => (view.view.zoom, view.view.fit) = (1.0, canvas::Fit::None),
M::Percent(p) => (view.view.zoom, view.view.fit) = (f64::from(p) / 100.0, canvas::Fit::None),
M::FitPage | M::FitVisible => view.view.fit = canvas::Fit::Page,
M::FitWidth => view.view.fit = canvas::Fit::Width,
M::FitHeight => view.view.fit = canvas::Fit::Height,
}
}
// The opening destination (`/OpenAction`, named destinations resolved): its page, and
@@ -155,7 +152,7 @@ impl PdfCraftApp {
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn poll_pending_opens(&mut self) {
pub(crate) fn poll_pending_opens(&mut self, ctx: &egui::Context) {
// The queue delivers in the order jobs finish; each result goes to its entry, so the list
// keeps the order the files were asked for.
while let Some(finished) = self.opens.try_recv() {
@@ -195,7 +192,7 @@ impl PdfCraftApp {
if retry {
self.password_retry = None;
}
self.finish_pending_open(pending, kind);
self.finish_pending_open(ctx, pending, kind);
}
// A completion may schedule another open; preserve those requests as well as the
// earlier waiting replies, without consuming a blocked receiver's result.
@@ -205,7 +202,7 @@ impl PdfCraftApp {
}
#[cfg(not(target_arch = "wasm32"))]
fn finish_pending_open(&mut self, pending: PendingOpen, kind: open_worker::ResultKind) {
fn finish_pending_open(&mut self, ctx: &egui::Context, pending: PendingOpen, kind: open_worker::ResultKind) {
match kind {
open_worker::ResultKind::ReadFailed(reason) => {
self.notify_fmt("Couldn't read {name}: {e}", &[("name", &pending.name), ("e", &reason)]);
@@ -222,7 +219,7 @@ impl PdfCraftApp {
open_worker::ResultKind::Conversion(bytes) => match self.open_converted(&pending.name, &bytes) {
Some(Ok(())) => {
if let Some(command) = pending.then {
self.execute(command);
self.execute(ctx, command);
}
}
Some(Err(error)) => self.notify_fmt("Couldn't open {name}: {e}", &[("name", &pending.name), ("e", &error)]),
@@ -231,7 +228,7 @@ impl PdfCraftApp {
open_worker::ResultKind::Converted(created) => match self.open_converted_pdf(&pending.name, created) {
Ok(()) => {
if let Some(command) = pending.then {
self.execute(command);
self.execute(ctx, command);
}
}
Err(error) => self.notify_fmt("Couldn't open {name}: {e}", &[("name", &pending.name), ("e", &error)]),
@@ -248,14 +245,14 @@ impl PdfCraftApp {
if let Some((layout, continuous)) = pending.display_override
&& let Some(view) = self.views.iter_mut().find(|view| view.id == id)
{
view.set_display(layout, continuous);
(view.view.display, view.view.continuous) = (layout, continuous);
self.launch_display_target = Some(id);
}
if let Some(meta) = &pending.recovered {
self.finish_recovery(meta);
}
if let Some(command) = pending.then {
self.execute(command);
self.execute(ctx, command);
}
}
Err(error) => self.notify_fmt("Couldn't open {name}: {e}", &[("name", &pending.name), ("e", &error)]),
@@ -357,7 +354,7 @@ impl PdfCraftApp {
pdfcraft_render::AttachmentSource::Document { key } => Some(key.clone()),
pdfcraft_render::AttachmentSource::Annotation { .. } => None,
});
let opens_with = if activate && self.right().is_none() && !self.right_panel_closed() && opening_mode != Mode::Read {
let opens_with = if activate && self.right().is_none() && !self.right_panel_closed && opening_mode != Mode::Read {
if !doc.info.annotations.is_empty() {
Some(RightPanel::Comments)
// A full-screen document names its panel for outside full screen, and with
@@ -405,7 +402,7 @@ impl PdfCraftApp {
self.portfolio_initial = portfolio_initial.map(|key| (id, key));
}
if activate
&& self.left_open()
&& self.left_open
&& self.left == LeftPanel::Tool("organize")
&& let Some(view) = self.views.last_mut()
{
@@ -421,10 +418,10 @@ impl PdfCraftApp {
} else if activate && self.mode != self.default_mode {
// Switch workspace like the mode bar, but a left panel the user (or `--left closed`)
// closed stays closed, and an unchanged mode keeps the tool panel the user chose.
let (left, left_open) = (self.left, self.left_open());
let (left, left_open) = (self.left, self.left_open);
self.select_mode(self.default_mode);
if self.left_open() != left_open {
// PLAN: assumed `PanelId::from(LeftPanel)` (pdf-chrome-w13)
if self.left_open != left_open {
self.left_open = left_open;
crate::side_panels::set_panel_visible(self, crate::side_panels::PanelId::from(left), left_open);
}
}
@@ -660,20 +657,20 @@ impl PdfCraftApp {
(None, None) => return,
};
if unlock {
self.submit_unlock(password);
self.submit_unlock(ui.ctx(), password);
} else {
self.submit_password(password);
self.submit_password(ui.ctx(), password);
}
}
/// Answer the password prompt (`None` cancels).
pub fn submit_password(&mut self, password: Option<String>) {
pub fn submit_password(&mut self, ctx: &egui::Context, password: Option<String>) {
let Some(mut p) = self.password_prompt.take() else { return };
let Some(pw) = password.map(zeroize::Zeroizing::new) else {
// A cancelled recovery goes back on offer; its snapshot stays in the store and must
// not attach itself to whatever document is unlocked next (#813).
if let Some(meta) = p.recovered.take() {
self.recoverable.push(meta);
self.recovered.push(meta);
}
#[cfg(not(target_arch = "wasm32"))]
self.settle_launch_layout();
@@ -700,12 +697,12 @@ impl PdfCraftApp {
self.password_retry = Some(token);
}
#[cfg(target_arch = "wasm32")]
self.retry_inline(p, pw);
self.retry_inline(ctx, p, pw);
}
/// The web has no queue: the retry opens the held bytes at once.
#[cfg(target_arch = "wasm32")]
fn retry_inline(&mut self, mut p: PasswordPrompt, pw: zeroize::Zeroizing<String>) {
fn retry_inline(&mut self, ctx: &egui::Context, mut p: PasswordPrompt, pw: zeroize::Zeroizing<String>) {
let after_open = p.after_open.clone();
let opened = self.try_open(&p.name, p.path.take(), p.bytes.clone(), Some(&pw), p.activate);
drop(pw);
@@ -719,13 +716,13 @@ impl PdfCraftApp {
if let Some((layout, continuous)) = p.display_override
&& let Some(view) = self.views.last_mut()
{
view.set_display(layout, continuous);
(view.view.display, view.view.continuous) = (layout, continuous);
}
if let Some(meta) = &p.recovered {
self.finish_recovery(meta);
}
if let Some(command) = p.then {
self.execute(command);
self.execute(ctx, command);
}
}
// Wrong password: the new prompt is for the same bytes, so it keeps the snapshot
@@ -748,7 +745,7 @@ impl PdfCraftApp {
}
/// Answer the permissions password prompt (`None` cancels).
pub fn submit_unlock(&mut self, password: Option<String>) {
pub fn submit_unlock(&mut self, ctx: &egui::Context, password: Option<String>) {
let Some(mut p) = self.unlock_prompt.take() else { return };
let Some(mut pw) = password else { return };
let unlocked = self.session.unlock(p.doc, &pw);
@@ -757,7 +754,7 @@ impl PdfCraftApp {
// Carry on with what asked for the password, if its document is still the one shown.
Ok(()) => match p.then {
Some(command) if self.active_ids().is_some_and(|(_, id)| id == p.doc) => {
self.execute(command);
self.execute(ctx, command);
}
_ => self.notify_tr("Restrictions lifted"),
},
@@ -790,15 +787,20 @@ impl PdfCraftApp {
#[cfg(not(target_arch = "wasm32"))]
pub fn open_path(&mut self, path: &str) -> OpenOutcome {
self.open_path_then(path, None)
self.open_path_request(path, None, None)
}
/// Keep a chosen tool with its file until preparation and any password entry finish. The
/// return value is the programmatic open contract (#1620): callers that must know whether
/// the file opened, focused its tab, was handed to the background worker, or failed.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn open_path_then(&mut self, path: &str, then: Option<&'static str>) -> OpenOutcome {
self.open_path_request(path, then, None)
pub(crate) fn open_path_then(&mut self, ctx: &egui::Context, path: &str, then: Option<&'static str>) -> OpenOutcome {
let outcome = self.open_path_request(path, then, None);
// A file that was open already is focused at once, and the tool it was opened for runs on it.
if let (OpenOutcome::Focused, Some(command)) = (&outcome, then) {
self.execute(ctx, command);
}
outcome
}
#[cfg(not(target_arch = "wasm32"))]
@@ -829,15 +831,12 @@ impl PdfCraftApp {
if let Some((layout, continuous)) = display_override
&& let Some(view) = self.views.get_mut(i)
{
view.set_display(layout, continuous);
(view.view.display, view.view.continuous) = (layout, continuous);
self.launch_display_target = Some(view.id);
}
if let Some(destination) = after_open {
self.apply_destination_at(i, destination);
}
if let Some(command) = then {
self.execute(command);
}
return OpenOutcome::Focused;
}
if let Some(pending) = self.pending_opens.iter_mut().find(|p| p.path.as_deref().is_some_and(|p| same_file(p, path))) {
@@ -909,7 +908,7 @@ impl PdfCraftApp {
&& let Some(id) = self.launch_display_target
&& let Some(view) = self.views.iter_mut().find(|view| view.id == id)
{
view.set_display(layout, continuous);
(view.view.display, view.view.continuous) = (layout, continuous);
}
}
@@ -965,20 +964,20 @@ impl PdfCraftApp {
/// Opens what a picker answered and runs the command `then` on each opened document, as a tool
/// chosen from Home does once its file is ready.
pub fn open_picked_then(&mut self, picked: Picked, then: &'static str) {
pub fn open_picked_then(&mut self, ctx: &egui::Context, picked: Picked, then: &'static str) {
self.startup_superseded = true;
match picked {
#[cfg(not(target_arch = "wasm32"))]
Picked::Paths(paths) => {
for path in paths {
self.open_path_then(&path.to_string_lossy(), Some(then));
self.open_path_then(ctx, &path.to_string_lossy(), Some(then));
}
}
Picked::Contents(files) => {
for (name, bytes) in files {
match self.open_bytes(&name, None, bytes) {
Ok(()) => {
self.execute(then);
self.execute(ctx, then);
}
Err(error) => self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &error)]),
}
+2
View File
@@ -11,6 +11,8 @@ impl PdfCraftApp {
/// a second pass of the same frame runs on what this call set and fires nothing twice.
pub(super) fn prepare_raw_input(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.offer_pasted(raw);
self.set_title_bar_choice(ctx, self.title_bar_choice);
self.control_before_input(ctx);
embed::before_input(ctx, |output| {
for fired in &output.fired {
self.run_fired(ctx, fired);
+2 -2
View File
@@ -24,7 +24,7 @@ impl PdfCraftApp {
{
view.find = None;
} else if self.full_screen() && self.combine_tab.preview.is_none() {
self.set_full_screen(ctx, false);
self.set_full_screen(false);
}
}
}
@@ -38,7 +38,7 @@ impl PdfCraftApp {
return;
}
let pages_owns_keyboard =
self.right == Some(RightPanel::Pages) && self.views[i].pages_focus_id.is_some_and(|id| ctx.memory(|m| m.has_focus(id)));
self.right() == Some(RightPanel::Pages) && self.views[i].pages_focus_id.is_some_and(|id| ctx.memory(|m| m.has_focus(id)));
let view = &self.views[i];
// A paragraph or text box open for typing keeps ⌘A for its own text.
let edit_objects = self.quick_tool == QuickTool::EditText && view.session.line_editor.is_none() && view.session.content.draft.is_none();
+1
View File
@@ -50,6 +50,7 @@ impl PdfCraftApp {
after_open: Some(destination),
recovered: None,
then: None,
priority: craft::host::queue::Priority::NEAR,
});
}
+34 -17
View File
@@ -47,6 +47,24 @@ impl PdfCraftApp {
self.theme_preference = preference;
}
/// Sets Preferences ▸ Animation effects; the next frame's [`Self::root_env`] carries it and
/// the next [`Self::save_settings`] keeps it.
pub fn set_motion(&mut self, motion: craft::theme::MotionChoice) {
self.animation_effects = motion;
}
/// Hands the preferences to the settings store and writes them if they changed. A write that
/// fails is logged: the preferences stay in the app and the next save tries again.
pub(crate) fn save_settings(&mut self) {
let snapshot = self.settings_snapshot();
if let Some(store) = self.settings.as_mut() {
store.set(snapshot);
if let Err(e) = store.flush() {
log::warn!("the preferences could not be written: {e}");
}
}
}
/// The app-wide reading-colours preference: sets it and applies it to every open document,
/// not just the active one (Preferences ▸ Reading colours, Acrobat's Replace Document
/// Colors). A document the change actually touches re-renders.
@@ -75,7 +93,7 @@ impl PdfCraftApp {
reopen_last_session: Some(self.reopen_last_session),
restore_last_view: Some(self.restore_last_view),
last_views: json_text(&self.last_views_to_save()),
system_title_bar: Some(self.system_title_bar),
system_title_bar: Some(self.title_bar_choice == TitleBarPref::System),
reload_changed_files: Some(self.reload_changed_files),
update_check_at_start: Some(self.update_check_at_start),
show_secured_notice: Some(self.show_secured_notice),
@@ -163,9 +181,13 @@ impl PdfCraftApp {
self.comment_prefs.font_sizes().map(|(t, size)| serde_json::json!({ "tool": t.command(), "font_size": size })).collect();
let comment = settings::Comment { comment_styles: json_text(&styles), comment_font_sizes: json_text(&font_sizes) };
let signature = settings::Signature {
// PLAN: assumed app fields `saved_signatures: Vec<SavedSignature>` and `sign_graphic: Option<SignatureImage>` (forms-w5)
signatures: Some(self.saved_signatures.clone()),
sign_graphic: self.sign_graphic.clone(),
signatures: Some({
let mut slots = craft::review::ui::signature::SignatureSettings::default();
slots.signature = self.signature.clone();
slots.initials = self.initials.clone();
slots
}),
sign_graphic: Some(self.sign_graphic.clone()),
// macOS Keychain and Windows store identities are read from their OS key stores each time.
digital_ids: Some(
self.digital_ids.iter().filter(|e| !e.path.starts_with("keychain:") && !e.path.starts_with("windows:")).cloned().collect(),
@@ -183,8 +205,7 @@ impl PdfCraftApp {
recent_view: name_of(&self.recent_view),
recent_sort: name_of(&self.recent_sort),
};
// PLAN: assumed app field `hotbar_tools: Vec<String>` (chrome-w18)
let hotbar = settings::Hotbar { tools: Some(self.hotbar_tools.clone()) };
let hotbar = settings::Hotbar { tools: Some(self.hotbar.tools.clone()) };
// Kept only while the preference is on.
let session = settings::Session { last_session: self.reopen_last_session.then(|| json_text(&self.session_to_save())).flatten() };
PdfCraftSettings { layout, print, behavior, view, comment, signature, dock, recent, hotbar, session }
@@ -207,7 +228,7 @@ impl PdfCraftApp {
fn apply_hotbar(&mut self, s: &settings::Hotbar) {
if let Some(tools) = &s.tools {
self.hotbar_tools = tools.clone();
self.hotbar.tools = tools.clone();
}
}
@@ -266,12 +287,8 @@ impl PdfCraftApp {
}
self.restore_last_views(&parsed(&s.last_views).unwrap_or(serde_json::Value::Null));
if let Some(on) = s.system_title_bar {
let changed = on != self.system_title_bar;
self.system_title_bar = on;
if changed && let Some(ctx) = self.ctx.clone() {
let pref = if on { TitleBarPref::System } else { TitleBarPref::Integrated };
self.set_title_bar_choice(&ctx, pref);
}
// The window follows in the next frame (`prepare_raw_input`).
self.title_bar_choice = if on { TitleBarPref::System } else { TitleBarPref::Integrated };
}
if let Some(on) = s.reload_changed_files {
self.reload_changed_files = on;
@@ -542,12 +559,12 @@ impl PdfCraftApp {
/// Saved signatures, stamps, actions and trusted certificates.
fn apply_signature(&mut self, s: &settings::Signature) {
if let Some(signatures) = &s.signatures {
// PLAN: assumed app field `saved_signatures: Vec<SavedSignature>` (forms-w5)
self.saved_signatures = signatures.clone();
if let Some(slots) = &s.signatures {
self.signature = slots.signature.clone();
self.initials = slots.initials.clone();
}
// An unreadable choice (a damaged image) falls back to the name.
self.sign_graphic = s.sign_graphic.clone();
self.sign_graphic = s.sign_graphic.clone().unwrap_or_default();
if let Some(ids) = &s.digital_ids {
self.digital_ids = ids.clone();
}
+13 -13
View File
@@ -34,9 +34,9 @@ impl PdfCraftApp {
/// it found. Nothing here reads the frame's input: the reload request and the changes are
/// taken once from where they wait, so a second pass in a frame finds only what arrived since
/// the first.
pub(crate) fn watch_files(&mut self) {
pub(crate) fn watch_files(&mut self, ctx: &egui::Context) {
if let Some(id) = self.reload_request.take() {
self.reload_from_disk(id);
self.reload_from_disk(ctx, id);
}
// Every open document with a file, while the preference is on. Turning it off stops the
// watching; the versions recorded stay, so a save still asks about a file changed on disk.
@@ -60,7 +60,7 @@ impl PdfCraftApp {
return;
}
for change in self.watch.take_changes() {
self.file_changed(change);
self.file_changed(ctx, change);
}
}
@@ -69,12 +69,12 @@ impl PdfCraftApp {
/// holds until the save has taken its answer, since replacing the document first would save
/// another version than the one the user was asked about.
fn holds_reload(&self) -> bool {
self.modal_open() || self.pending_full_screen.is_some() || self.pending_save.as_ref().is_some_and(|p| p.asking())
self.modal_open() || self.pending_save.as_ref().is_some_and(|p| p.asking())
}
/// A watched file has a new version: reload its document, or say so when it has unsaved
/// changes. Stale versions never reach here: [`FileWatch::take_changes`] drops them.
fn file_changed(&mut self, change: Changed<DocId>) {
fn file_changed(&mut self, ctx: &egui::Context, change: Changed<DocId>) {
let Some(i) = self.views.iter().position(|v| v.id == change.key) else { return };
// LaunchServices recovery (and Finder metadata edits) changes ctime. The watch already
// read the stable file: identical saved bytes are not a document change.
@@ -91,16 +91,16 @@ impl PdfCraftApp {
return;
}
match change.bytes {
Some(bytes) => self.reload_view(i, bytes),
Some(bytes) => self.reload_view(ctx, i, bytes),
// The watch reads every change whole (`document_watch`); one reported by its stamp
// alone is read here.
None => self.reload_from_disk(change.key),
None => self.reload_from_disk(ctx, change.key),
}
}
/// The notice bar's Reload: read the file now and replace the document, unsaved changes and
/// all.
fn reload_from_disk(&mut self, doc: DocId) {
fn reload_from_disk(&mut self, ctx: &egui::Context, doc: DocId) {
let Some(i) = self.views.iter().position(|v| v.id == doc) else { return };
let Some(path) = self.session.get(doc).and_then(|d| d.path.clone()) else { return };
let path = Path::new(&path);
@@ -109,7 +109,7 @@ impl PdfCraftApp {
match std::fs::read(path) {
Ok(bytes) => {
self.watch.known_as(doc, path, stamp);
self.reload_view(i, Arc::new(bytes));
self.reload_view(ctx, i, Arc::new(bytes));
}
Err(e) => {
let name = self.session.get(doc).map(|d| d.name.clone()).unwrap_or_default();
@@ -121,7 +121,7 @@ impl PdfCraftApp {
/// Open `bytes` in place of tab `i`'s document, keeping the tab and the reader's place. A
/// version that can't be opened leaves the document as it was, and says so. The one place a
/// reload resets what the view holds about the old version.
fn reload_view(&mut self, i: usize, bytes: Arc<Vec<u8>>) {
fn reload_view(&mut self, ctx: &egui::Context, i: usize, bytes: Arc<Vec<u8>>) {
let Some(id) = self.views.get(i).map(|v| v.id) else { return };
match self.session.reload(id, bytes) {
Ok(()) => {
@@ -130,7 +130,7 @@ impl PdfCraftApp {
self.forget_recovery(id);
self.placed_signatures.remove(&id);
if let (Some(view), Some(doc)) = (self.views.get_mut(i), self.session.get(id)) {
view.document_replaced(&doc.info);
view.document_replaced(ctx, &doc.info);
}
// What the form's scripts said while it opened, as on opening.
let out = self.session.take_js_output(id);
@@ -223,9 +223,9 @@ mod tests {
// PLAN: assumed `AppServices::new(wake, clipboard, recovery_dir, update_source, intake, watch)` (L-207, pdf-hub-w1)
let services = crate::AppServices::new(Wake::none(), clipboard, None, None, intake, document_watch(Wake::none()).inline());
let path = path.to_owned();
let h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
let h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |cc| {
let mut app = PdfCraftApp::with_host(host, services);
app.set_option("language", "en").unwrap();
app.set_option(&cc.egui_ctx, "language", "en").unwrap();
app.open_path(&path);
app
});
+16 -6
View File
@@ -6,7 +6,6 @@
//! `config.toml` and a hostile legacy file reach the same code.
use super::*;
use craft::review::{SavedSignature, SignatureImage};
use craft::settings::{LegacyFile, SectionError, Settings};
use craft::theme::{ModeChoice, MotionChoice};
use craft::ui::contract::ColumnLayout;
@@ -146,8 +145,8 @@ impl Comment {
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Signature {
pub signatures: Option<Vec<SavedSignature>>,
pub sign_graphic: Option<SignatureImage>,
pub signatures: Option<craft::review::ui::signature::SignatureSettings>,
pub sign_graphic: Option<crate::sign_ui::SignGraphic>,
pub digital_ids: Option<Vec<crate::DigitalIdEntry>>,
/// PEM text of each trusted certificate.
pub trusted: Option<Vec<String>>,
@@ -461,6 +460,16 @@ impl<'a> Reader<'a> {
}
}
/// The last release's visible-signature choice: a unit name or `{"Image": "<base64 png>"}`.
fn legacy_sign_graphic(v: &Value) -> Option<crate::sign_ui::SignGraphic> {
use crate::sign_ui::SignGraphic;
match v.as_str() {
Some("Name") => Some(SignGraphic::Name),
Some("FillSign") => Some(SignGraphic::FillSign),
_ => v.get("Image").and_then(crate::fill_sign::legacy_image).map(SignGraphic::Image),
}
}
/// The last release's settings JSON as typed settings. Values that fail to read stay at their
/// default and are listed; the text itself failing to parse gives the defaults and one entry.
pub fn import_json(text: &str) -> (PdfCraftSettings, Vec<SectionError>) {
@@ -581,9 +590,10 @@ pub fn import_json(text: &str) -> (PdfCraftSettings, Vec<SectionError>) {
let signature = {
let mut r = Reader::new(&root, Signature::KEY, &mut errors);
// PLAN: assumed `fill_sign::legacy_signatures(&Value) -> Vec<SavedSignature>` and `fill_sign::legacy_image(&Value) -> Option<SignatureImage>` (forms-w5)
let signatures = r.value("signatures").map(crate::fill_sign::legacy_signatures);
let sign_graphic = r.value("sign_graphic").and_then(crate::fill_sign::legacy_image);
// The last release kept the two slots under four top-level keys.
let has_slots = ["signature", "signature_text", "signature_image", "initials"].iter().any(|key| root.contains_key(*key));
let signatures = has_slots.then(|| crate::fill_sign::legacy_signatures(&Value::Object(root.clone())));
let sign_graphic = r.value("sign_graphic").and_then(legacy_sign_graphic);
Signature {
signatures,
sign_graphic,
+5 -1
View File
@@ -165,7 +165,11 @@ impl DocView {
let config = session.render_config(self.id).unwrap_or_default();
let ranked = visible.iter().map(|p| (*p, Priority::VISIBLE)).chain(rest.iter().map(|p| (*p, Priority::BACKGROUND)));
for (page, priority) in ranked {
if page >= self.page_count || self.session.texts.contains_key(&page) || self.session.text_failed.contains(&page) || self.session.text_queue.contains(&page) {
if page >= self.page_count
|| self.session.texts.contains_key(&page)
|| self.session.text_failed.contains(&page)
|| self.session.text_queue.contains(&page)
{
continue;
}
let (bytes, config) = (doc.display.clone(), config.clone());
+2 -1
View File
@@ -322,7 +322,8 @@ fn rows(ui: &mut egui::Ui, view: &mut DocView, cx: &PageMenuCx<'_>, menu_for: Op
return;
}
// The comment the press went to, when it is the one selected, or connected lines being drawn.
let on_selected_comment = matches!(view.session.menu_for, Some((page, Owner::Comment { index, .. })) if view.session.comments.selected == Some((page, index)));
let on_selected_comment =
matches!(view.session.menu_for, Some((page, Owner::Comment { index, .. })) if view.session.comments.selected == Some((page, index)));
let drawing_points = matches!(cx.tool, QuickTool::Comment(t) if t.clicks_points()) && !view.session.comments.tool.drawing().is_empty();
if on_selected_comment || drawing_points {
let tool = if let QuickTool::Comment(t) = cx.tool { Some(t) } else { None };
+1 -1
View File
@@ -13,8 +13,8 @@ use craft::ui::shell::{AppShell, Slot, Title, TitleBar};
use crate::panes::Place;
use crate::{PdfCraftApp, side_panels};
mod mode_bar;
pub(crate) mod doc_tabs;
mod mode_bar;
pub(crate) mod view_rail;
/// Compose the window: title bar, mode bar, view rail and the dock, whose document panel holds the
+1 -1
View File
@@ -49,7 +49,7 @@ use std::sync::atomic::{AtomicU64, Ordering};
use craft::automation::dialogs::dialog_method;
use craft::automation::screenshot::{DocumentId, ScreenshotParams, settle_ms};
use craft::automation::synthetic::input_method;
use craft::automation::{access, ControlRequest, Reply};
use craft::automation::{ControlRequest, Reply, access};
use craft::ui::runtime::motion;
use craft::ui::runtime::windows::WindowHost;
use egui::ViewportId;
+1 -1
View File
@@ -163,7 +163,7 @@ impl crate::PdfCraftApp {
"left_panel": if self.left_open { json!(format!("{:?}", self.left)) } else { Value::Null },
"tools_side": dock["tools_side"].clone(),
"rail_side": dock["rail_side"].clone(),
"right_panel": self.right.map(|r| format!("{r:?}")),
"right_panel": self.right().map(|r| format!("{r:?}")),
"hidden_interface": self.hidden_interface().to_json(),
// The top host dialog's key, else the inline window that is open.
"dialog": self
+2 -1
View File
@@ -463,7 +463,8 @@ impl PdfCraftApp {
let Some((i, id)) = self.active_ids() else { return };
let Some(doc) = self.session.get(id) else { return };
let Some(p) = doc.comment_props(page, index) else { return };
let selection = self.views.get(i).map(|v| &v.session.comments).filter(|c| c.is_selected((page, index))).map(|c| c.selection()).unwrap_or_default();
let selection =
self.views.get(i).map(|v| &v.session.comments).filter(|c| c.is_selected((page, index))).map(|c| c.selection()).unwrap_or_default();
let others: Vec<(usize, usize, CommentProps)> =
selection.into_iter().filter(|k| *k != (page, index)).filter_map(|(pg, ix)| doc.comment_props(pg, ix).map(|c| (pg, ix, c))).collect();
let me = doc.info.annotations.iter().find(|a| a.page == page && a.index == index && !a.is_reply());
+17 -10
View File
@@ -278,7 +278,9 @@ impl PdfCraftApp {
self.notify(match &n {
pdfcraft_engine::EditNotice::Undrawn(t) => crate::content_ui::undrawn_message(t),
pdfcraft_engine::EditNotice::BackdropsLeftOff { pages } => crate::marks_ui::backdrops_left_off_message(pages),
pdfcraft_engine::EditNotice::RedactionElsewhere(e) => crate::redact_ui::still_holding_note(e).unwrap_or_else(|| n.to_string()),
pdfcraft_engine::EditNotice::RedactionElsewhere(e) => {
crate::redact_ui::still_holding_note(e).unwrap_or_else(|| n.to_string())
}
pdfcraft_engine::EditNotice::RedactionIdentification(id) => {
crate::redact_ui::identification_note(id).unwrap_or_else(|| n.to_string())
}
@@ -462,9 +464,9 @@ impl PdfCraftApp {
/// text.
// PLAN: callers still pass a ctx (`commands.rs:880`, `:882`, owner pdf-hub-w3): drop the argument there
pub(crate) fn page_box_focused(&self) -> bool {
self.active.and_then(|i| self.views.get(i)).is_some_and(|v| {
v.session.line_editor.as_ref().is_some_and(|ed| ed.focus) || v.session.content.draft.as_ref().is_some_and(|d| d.focus)
})
self.active
.and_then(|i| self.views.get(i))
.is_some_and(|v| v.session.line_editor.as_ref().is_some_and(|ed| ed.focus) || v.session.content.draft.as_ref().is_some_and(|d| d.focus))
}
/// Whether the focused box on the page has typing its own Redo would put back: after Undo in
@@ -492,7 +494,8 @@ impl PdfCraftApp {
/// have yet: Undo and Redo keys take it back in the box first.
pub(crate) fn page_typing_unapplied(&self) -> bool {
self.active.and_then(|i| self.views.get(i)).is_some_and(|v| {
v.session.line_editor.as_ref().is_some_and(|ed| ed.has_unsaved_text()) || v.session.content.draft.as_ref().is_some_and(|d| d.has_unapplied_typing())
v.session.line_editor.as_ref().is_some_and(|ed| ed.has_unsaved_text())
|| v.session.content.draft.as_ref().is_some_and(|d| d.has_unapplied_typing())
})
}
@@ -1264,7 +1267,7 @@ impl PdfCraftApp {
self.apply_edit(Edit::AddBookmark { parent: vec![], index: n, title: "Untitled".into(), page, left, top });
// Like Acrobat: the new bookmark starts in rename mode.
self.bookmark_rename = Some((vec![n], "Untitled".into()));
self.right = Some(crate::RightPanel::Bookmarks);
self.set_right(Some(crate::RightPanel::Bookmarks));
return;
}
A::StartRename(path) => {
@@ -1314,7 +1317,7 @@ impl PdfCraftApp {
return;
}
A::FromStructure => {
self.right = Some(crate::RightPanel::Bookmarks);
self.set_right(Some(crate::RightPanel::Bookmarks));
Edit::BookmarksFromStructure
}
// A dialog chooses the styles; it makes the edit.
@@ -1391,7 +1394,6 @@ fn step_typing(
stepped
}
#[cfg(test)]
mod tests;
@@ -1601,7 +1603,8 @@ mod revert_draft_tests {
};
assert_eq!(hint(&app), "Type here");
// As the editor opens on it: its text and value.
app.views[0].session.forms.focus = Some(Focus { name: "hint".into(), text: "Type here".into(), picked: vec!["Type here".into()], ..focus("") });
app.views[0].session.forms.focus =
Some(Focus { name: "hint".into(), text: "Type here".into(), picked: vec!["Type here".into()], ..focus("") });
assert!(app.commit_form_typing());
assert_eq!(hint(&app), "", "hint's enter ran before the document is read");
assert_eq!(app.views[0].session.forms.focus.as_ref().map(|f| f.text.as_str()), Some(""), "and its editor shows it");
@@ -1668,7 +1671,11 @@ mod revert_draft_tests {
assert!(!reverted.dirty);
assert_eq!(reverted.edit_generation(), source_generation + 1);
assert!(reverted.form.iter().find(|field| field.name == "name").unwrap().value.is_empty());
assert!(app.views[0].session.forms.focus.is_none() && app.views[0].session.forms.committed.is_none() && app.views[0].session.pending_edit.is_none());
assert!(
app.views[0].session.forms.focus.is_none()
&& app.views[0].session.forms.committed.is_none()
&& app.views[0].session.pending_edit.is_none()
);
assert!(!app.has_unsaved_work(0));
assert_eq!(app.views[1].session.forms.focus.as_ref().unwrap().text, "Other focused draft");
assert_eq!(app.views[1].session.forms.committed.as_ref().unwrap().text, "Other queued draft");
+7 -2
View File
@@ -133,8 +133,13 @@ impl PdfCraftApp {
failed(self);
return false;
}
self.pending_save =
Some(PendingSave { key: id, after: Some(Box::new(after)), failed: Some(Box::new(failed)), redactions: (redacted, unredacted), prompt: None });
self.pending_save = Some(PendingSave {
key: id,
after: Some(Box::new(after)),
failed: Some(Box::new(failed)),
redactions: (redacted, unredacted),
prompt: None,
});
self.run_save_step(step)
}
+18 -15
View File
@@ -34,15 +34,15 @@ impl PdfCraftApp {
}
/// Run one part of the frame (`logic` or `ui`) under the guard.
pub(crate) fn guarded_frame(&mut self, part: impl FnOnce(&mut PdfCraftApp)) {
pub(crate) fn guarded_frame(&mut self, ctx: &egui::Context, part: impl FnOnce(&mut PdfCraftApp)) {
if let Err(message) = pdfcraft_engine::guard(|| part(self)) {
self.after_frame_panic(&message);
self.after_frame_panic(ctx, &message);
}
}
/// After a frame panicked: keep the work, drop what the frame was showing on top (a dialog,
/// the command palette), keep `active` pointing at a tab, and say so.
fn after_frame_panic(&mut self, message: &str) {
fn after_frame_panic(&mut self, ctx: &egui::Context, message: &str) {
log::error!("a frame panicked and was caught: {message}");
if !self.frame_panicked {
self.frame_panicked = true;
@@ -60,13 +60,15 @@ impl PdfCraftApp {
self.palette_open = false;
self.keep_active_valid();
self.notify_fmt("That didn't work: an internal error stopped it ({m}).", &[("m", message)]);
if let Some(ctx) = &self.ctx {
// Top first, so a child dialog is cancelled before the parent it was opened from.
// PLAN: assumed `PdfCraftApp.dialogs: DialogHost` (pdf-hub-w1)
for open in self.dialogs.open_dialogs().into_iter().rev() {
self.dialogs.cancel_by_id(ctx, open.id);
}
ctx.request_repaint();
self.cancel_dialogs(ctx);
ctx.request_repaint();
}
/// Cancels every dialog the dialog host has open, the top one first so a child dialog is
/// cancelled before the parent it was opened from.
pub(crate) fn cancel_dialogs(&mut self, ctx: &egui::Context) {
for open in self.dialogs.open_dialogs().into_iter().rev() {
self.dialogs.cancel_by_id(ctx, open.id);
}
}
@@ -142,7 +144,6 @@ mod tests {
}
/// An app built through `with_host`, with recovery in `dir` when given.
// PLAN: assumed `AppServices::new(wake, clipboard, recovery_dir, update_source, intake, watch)` and `PdfCraftApp::with_host(Arc<Host>, AppServices)` (pdf-hub-w1, L-207)
fn app(dir: Option<&std::path::Path>) -> PdfCraftApp {
let wake = craft::host::Wake::none();
let (intake, _) = craft::platform::open::FileIntake::new(wake.clone());
@@ -156,9 +157,9 @@ mod tests {
/// Two tabs, the second with an unsaved edit, and the About dialog open when `about`.
fn harness(store: &Store, about: bool) -> Harness<'static, PdfCraftApp> {
let dir = store.0.clone();
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |_cc| {
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |cc| {
let mut app = app(Some(&dir));
app.set_option("language", "en").unwrap();
app.set_option(&cc.egui_ctx, "language", "en").unwrap();
app.enable_recovery();
app.open_bytes("a.pdf", None, pdf("First")).unwrap();
app.open_bytes("b.pdf", None, pdf("Second")).unwrap();
@@ -167,7 +168,8 @@ mod tests {
h.run_steps(4);
assert!(h.state_mut().apply_edit(Edit::RotatePages { pages: vec![0], degrees: 90 }));
if about {
h.state_mut().set_option("dialog", "about").unwrap();
let ctx = h.ctx.clone();
h.state_mut().set_option(&ctx, "dialog", "about").unwrap();
}
h.run_steps(1);
h
@@ -186,7 +188,8 @@ mod tests {
h.get_by_label_contains("injected Logic panic");
assert_eq!(snapshots(&store), 1);
h.state_mut().set_option("dialog", "about").unwrap();
let ctx = h.ctx.clone();
h.state_mut().set_option(&ctx, "dialog", "about").unwrap();
h.run_steps(1);
assert!(!h.state().dialogs.open_dialogs().is_empty(), "the dialog is showing");
h.state_mut().panic_next = Some(FramePart::Ui);
+6 -6
View File
@@ -3,8 +3,10 @@
use std::cell::RefCell;
use craft::behavior::IconId;
use craft::behavior::{DisplayOrder, ItemSource, SizeHint};
use craft::keymap::CommandRef;
use craft::theme::variant::Tone;
use craft::ui::buttons::{Button, IconButton};
use craft::ui::contract::{CollectionEvent, Props as _, Show as _, ShowCollection as _};
use craft::ui::display::{PictureSize, Text};
@@ -14,8 +16,6 @@ use craft::ui::runtime::env::Env;
use craft::ui::shell::{RecentFile, StartAction, StartLink, StartPlace, StartScreen};
use craft::ui::style::DataColor;
use craft::ui::tile_grid::{Tile, TileGrid, TilePartEvent};
use craft::behavior::IconId;
use craft::theme::variant::Tone;
use pdfcraft_engine::catalog::{self, ToolGroup};
use crate::{PdfCraftApp, brand, panels::human_size};
@@ -107,8 +107,7 @@ pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
let pinned_folders = app.pinned_folders(&Env::of(ui));
let pinned_tools: Vec<&'static ToolGroup> = app.pinned_tools.iter().filter_map(|id| catalog::group(id)).collect();
let recommended: Vec<&'static ToolGroup> =
RECOMMENDED.iter().filter(|id| !app.is_tool_pinned(id)).filter_map(|id| catalog::group(id)).collect();
let recommended: Vec<&'static ToolGroup> = RECOMMENDED.iter().filter(|id| !app.is_tool_pinned(id)).filter_map(|id| catalog::group(id)).collect();
let community_card = !app.community_card_closed;
let asked = RefCell::new(Vec::new());
@@ -146,8 +145,9 @@ pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
})
.section(StartPlace::AfterSections, |ui, _| {
let _ = Text::new(tl!("Privacy").to_string()).show(ui);
let _ = Text::new(tl!("PdfCraft works offline. No telemetry, no account, and no cloud processing unless you add a provider.").to_string())
.show(ui);
let _ =
Text::new(tl!("PdfCraft works offline. No telemetry, no account, and no cloud processing unless you add a provider.").to_string())
.show(ui);
});
#[cfg(not(target_arch = "wasm32"))]
{
+1 -5
View File
@@ -231,7 +231,6 @@ impl PdfCraftApp {
/// File ▸ Pin folder to Home…: choose a folder whose newest PDFs Home lists.
pub fn pin_folder_dialog(&mut self) {
#[cfg(not(target_arch = "wasm32"))]
self.pick_first(PickRequest::folder("pin-folder").title(tl!("Pin a folder to Home").to_string()), None, |app, dir| {
app.pin_folder(&dir.to_string_lossy());
});
@@ -301,10 +300,7 @@ impl PdfCraftApp {
let listing = match self.pinned.listing(folder) {
None => ShellListing::Pending,
Some(l) if l.unavailable => ShellListing::Unavailable,
Some(l) => ShellListing::Listed {
files: l.files.iter().take(MAX_LISTED).map(|f| pinned_file(f, env)).collect(),
total: l.total,
},
Some(l) => ShellListing::Listed { files: l.files.iter().take(MAX_LISTED).map(|f| pinned_file(f, env)).collect(), total: l.total },
};
PinnedFolder::new(folder.as_str(), name)
.listing(listing)
+5 -6
View File
@@ -142,14 +142,13 @@ mod tests {
#[test]
fn every_icon_the_app_names_resolves() {
register();
let missing: Vec<String> = engine_icons()
.into_iter()
.filter(|(_, name)| !has_icon(&IconId::new(name)))
.map(|(owner, name)| format!("{owner}: {name}"))
.collect();
let missing: Vec<String> =
engine_icons().into_iter().filter(|(_, name)| !has_icon(&IconId::new(name))).map(|(owner, name)| format!("{owner}: {name}")).collect();
assert!(missing.is_empty(), "icons nobody has: {missing:?}");
// The eight documents the comment tools name stay served.
for name in ["message-square-plus", "type", "highlighter", "move-right", "message-square-quote", "message-square-text", "replace", "paperclip"] {
for name in
["message-square-plus", "type", "highlighter", "move-right", "message-square-quote", "message-square-text", "replace", "paperclip"]
{
assert!(has_icon(&IconId::new(name)), "comment tool icon {name}");
}
}
+16 -11
View File
@@ -87,8 +87,14 @@ pub use workflows::js_dialogs::JsDialog;
pub use workflows::ocr_verify::{OcrVerify, Phase};
mod app;
pub(crate) mod brand;
pub(crate) mod colour_picker;
pub(crate) mod credits_data;
pub mod fonts;
mod frame_guard;
mod hooks;
pub(crate) mod icons;
pub(crate) mod notices;
mod persist;
mod platform;
#[cfg(not(target_arch = "wasm32"))]
@@ -96,15 +102,9 @@ mod script_dialog;
mod state;
mod tools;
mod workflows;
pub(crate) mod brand;
pub(crate) mod colour_picker;
pub(crate) mod credits_data;
pub mod fonts;
pub(crate) mod icons;
pub(crate) mod notices;
pub use app::settings;
pub(crate) use app::same_file;
pub use app::settings;
pub(crate) use app::{MAX_AUTHOR_CHARS, copy_refused, date_text_for_pdf, print_refused};
use canvas::crop;
use canvas::image_pick;
@@ -204,7 +204,7 @@ struct PendingOpen {
after_open: Option<pdfcraft_render::RemoteDestination>,
recovered: Option<craft::platform::autosave::RecoveryEntry>,
then: Option<&'static str>,
display_override: Option<craft::pages::PageDisplay>,
display_override: Option<(craft::pages::PageDisplay, bool)>,
/// An answer taken from the queue and kept back for later (a password prompt waiting for an
/// earlier file's password retry).
ready: Option<open_worker::ResultKind>,
@@ -435,7 +435,7 @@ pub struct PdfCraftApp {
next_open_token: u64,
/// Explicit CLI layout waits for flagged launch opens, never targeting restored tabs.
#[cfg(not(target_arch = "wasm32"))]
launch_layout: Option<craft::pages::PageDisplay>,
launch_layout: Option<(craft::pages::PageDisplay, bool)>,
#[cfg(not(target_arch = "wasm32"))]
launch_display_target: Option<DocId>,
/// The file picks asked of the host's file service, by ticket, with what each is for.
@@ -678,8 +678,13 @@ pub struct PdfCraftApp {
pub(crate) document_fonts: Option<files::InstalledFonts>,
/// The installed fonts being listed off the UI thread.
pub(crate) font_scan: Queue<(), Vec<pdfcraft_engine::text_fonts::FontFile>>,
/// The last web link the app asked the system to open (tests and automation).
pub last_opened_url: Option<String>,
/// Web links the app asked the system to open, waiting for the pass that hands them to the
/// runtime.
pub(crate) pending_urls: Vec<String>,
/// A file the user opened, or a dialog or document that came up, since the app started: the
/// browser's startup `?file=` download then opens in the background instead of in front
/// (#171).
pub(crate) startup_superseded: bool,
/// The home screen's community card was closed; it comes back next launch (not remembered).
pub community_card_closed: bool,
/// A document asked to open this address; the user hasn't answered yet (#90, #91).
+1 -1
View File
@@ -8,10 +8,10 @@
//! (`commands::catalog`), fired once per click, whichever bar it came from.
use craft::keymap::{Key, Mods};
use craft::ui::runtime::commands::{FireSource, fire, resolve};
use craft::menu::{
Chord, CommandRef, Document, Gate, Item, ItemRole, ItemState, Labeled, Layout, LayoutOptions, Menu, MenuBar, MenuRole, Node, Target,
};
use craft::ui::runtime::commands::{FireSource, fire, resolve};
use pdfcraft_engine::catalog::{Availability, TOOL_GROUPS};
use pdfcraft_engine::commands::{self, Shortcut};
+2 -1
View File
@@ -42,7 +42,8 @@ pub(super) fn edit_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui, g: &'static T
commands.push(HeaderCommand::new(IconId::new("settings"), "app.preferences"));
let shown = Panel::new(title).titled().commands(commands).actions([HeaderAction::Close]).show(ui, |ui, _| {
// Several objects selected: how many, and how to move them. Acrobat's panel has no idle hint.
let count = app.active_ids().filter(|_| app.quick_tool == crate::QuickTool::EditText).map_or(0, |(i, _)| app.views[i].session.objects.count());
let count =
app.active_ids().filter(|_| app.quick_tool == crate::QuickTool::EditText).map_or(0, |(i, _)| app.views[i].session.objects.count());
if count > 0 {
Text::new(crate::i18n::trn(crate::i18n::current(), count as u64, "{n} object selected", "{n} objects selected")).show(ui);
Text::new(tl!("Drag the selection to move it. Esc clears the selection.").to_string()).show(ui);
+3 -1
View File
@@ -440,7 +440,9 @@ pub(crate) fn page_area(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
let views = SplitViews::new(tl!("Pages").to_string(), layout, Bind::bound(&mut at))
.count(1)
.active(active)
.takes_tabs::<StripTab>(|documents, _| !documents.is_empty() && documents.iter().all(|d| matches!(d, StripTab::View(key) if open.contains(key))))
.takes_tabs::<StripTab>(|documents, _| {
!documents.is_empty() && documents.iter().all(|d| matches!(d, StripTab::View(key) if open.contains(key)))
})
.show(ui, |ui, body| {
let rects = shown.placed(layout, count, body.rect, body.env.direction().is_rtl());
for (pane, rect) in rects.iter().enumerate() {
-1
View File
@@ -159,6 +159,5 @@ mod tests {
}
assert_eq!(zoom_text(canvas::Fit::None, 1.1), "110%");
assert_eq!(zoom_text(canvas::Fit::None, 0.625), "62.5%");
}
}
-1
View File
@@ -57,7 +57,6 @@ pub fn percent(factor: f32) -> u32 {
(factor * 100.0).round().clamp(0.0, 1000.0) as u32
}
#[cfg(test)]
mod tests {
use super::*;
+1 -3
View File
@@ -176,9 +176,7 @@ impl ScriptPromptDialog {
/// The dialog for `prompt` of document `run`, or `None` for a message box, which the standard prompt answers.
fn for_prompt(run: DocId, document: String, prompt: ScriptPrompt) -> Option<Self> {
let body = match prompt {
ScriptPrompt::Text { title, question, password, label, default, .. } => {
Body::Text { title, question, label, password, text: default }
}
ScriptPrompt::Text { title, question, password, label, default, .. } => Body::Text { title, question, label, password, text: default },
ScriptPrompt::Menu(items) => {
let mut nodes = Vec::new();
flatten(&items, 0, &mut nodes);
+1 -1
View File
@@ -235,7 +235,7 @@ pub struct PasswordPrompt {
/// A link destination to apply after the linked PDF is unlocked.
pub(crate) after_open: Option<pdfcraft_render::RemoteDestination>,
/// A launch-time display override, applied only after this PDF is unlocked.
pub(crate) display_override: Option<craft::pages::PageDisplay>,
pub(crate) display_override: Option<(craft::pages::PageDisplay, bool)>,
}
#[cfg(not(target_arch = "wasm32"))]
+4 -6
View File
@@ -14,13 +14,15 @@ use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use craft::behavior::item_source::keyed;
use craft::behavior::kurbo::{CubicBez, ParamCurve as _, Point};
use craft::behavior::selection::Selection;
use craft::behavior::{EditEvent, IconId, Input, Metrics, ReorderKeys, SelectionChange};
use craft::theme::variant::Tone as Status;
use craft::ui::buttons::IconButton;
use craft::ui::choice::Checkbox;
use craft::ui::contract::{
Access, Bind, CollectionEvent, Common, Component, Cx, MeasureCx, Outcome as _, PaintUi, Props as _, ReorderRule, Role, SelectMode, Show as _, ShowCollection as _, ShowContainer as _,
Access, Bind, CollectionEvent, Common, Component, Cx, MeasureCx, Outcome as _, PaintUi, Props as _, ReorderRule, Role, SelectMode, Show as _,
ShowCollection as _, ShowContainer as _,
};
use craft::ui::display::{Badge, Shade, Text};
use craft::ui::layout_components::Stack;
@@ -29,7 +31,6 @@ use craft::ui::notices::{Notice, NoticeAction};
use craft::ui::primitives::{HAlign, IconSpec, PaintShape, StrokeWidth, TextRun};
use craft::ui::runtime::env::Label;
use craft::ui::style::{ComponentStyle, StyleColor, StyleCx};
use craft::behavior::kurbo::{CubicBez, ParamCurve as _, Point};
use egui::{CornerRadius, Pos2, Rect, Response, Vec2, pos2, vec2};
use pdfcraft_cos::ObjRef;
use pdfcraft_engine::form_scripts::{CalcOp, Calculate, format_value};
@@ -674,10 +675,7 @@ pub(crate) fn panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
}
}
Text::new(String::new()).show(ui);
Checkbox::new(Bind::bound(&mut links_on))
.label(tl!("Links on page"))
.tooltip(tl!("Show on the page which fields each field reads"))
.show(ui);
Checkbox::new(Bind::bound(&mut links_on)).label(tl!("Links on page")).tooltip(tl!("Show on the page which fields each field reads")).show(ui);
if editable {
let (up, down) = if cfg!(target_os = "macos") { ("⌥↑", "⌥↓") } else { ("Alt+↑", "Alt+↓") };
let hint = crate::i18n::fmt(tl!("Drag a field to move it, or select it and press {up} or {down}."), &[("up", up), ("down", down)]);
+11 -4
View File
@@ -493,7 +493,8 @@ fn an_unnamed_shift_clears_state_for_the_old_index() {
let mut view = DocView::new(pdfcraft_engine::DocId(1), &info, crate::canvas::ViewDefaults::default());
view.session.comments.select_only((0, 1));
view.session.comments.panel.editing = Some((ThreadId(bridge::id_of(0, 1).0), 0, "the first note".into()));
view.session.comments.composer = Some(Composer { page: 0, at: [10.0, 10.0], kind: ComposerKind::Edit(1), text: "the first note".into(), focus: false });
view.session.comments.composer =
Some(Composer { page: 0, at: [10.0, 10.0], kind: ComposerKind::Edit(1), text: "the first note".into(), focus: false });
let xf = PageXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(300.0, 400.0)), rot: 0, pw: 300.0, ph: 400.0 };
let placed = [placed_page(&xf, 1.0)];
let map = page_map(&placed, &info, 0);
@@ -561,7 +562,8 @@ fn the_hover_outline_goes_round_what_a_press_would_take() {
assert_eq!(pick_at(&annotations, over, tolerance, side, &markers), Some(bridge::id_of(0, 0)), "the highlight a press there selects");
// PLAN: the outline shape itself is the overlay's `HoverOutline` (pdf-comments-w8); a request to w8 for an `overlay` helper
// the test can compare against the part's annotation. The part registered at the pointer is asserted here.
let parts = |view: &DocView, pointer| bridge::parts(&info, &map, &prefs, QuickTool::Select, pointer, &view.session.comments.tool, tolerance, side);
let parts =
|view: &DocView, pointer| bridge::parts(&info, &map, &prefs, QuickTool::Select, pointer, &view.session.comments.tool, tolerance, side);
assert_eq!(parts(&view, Some(over)).len(), 1, "one part for the comment under the pointer");
assert!(parts(&view, None).is_empty(), "no pointer, no part");
assert!(parts(&view, Some(Point::new(5.0, 5.0))).is_empty(), "nor where nothing would take the press");
@@ -594,8 +596,13 @@ fn an_annotation_round_trips_through_the_page_map_on_turned_and_zoomed_pages() {
}
let mut view = DocView::new(pdfcraft_engine::DocId(1), &info, crate::canvas::ViewDefaults::default());
let delta = Vec2::new(1.0, 0.0);
let moved =
bridge::edit(AnnotationEdit::Move { ids: vec![bridge::id_of(0, 0)], delta }, &map, &mut view.session.comments, &info, &CommentPrefs::default());
let moved = bridge::edit(
AnnotationEdit::Move { ids: vec![bridge::id_of(0, 0)], delta },
&map,
&mut view.session.comments,
&info,
&CommentPrefs::default(),
);
let Some(Edit::MoveAnnotation { dx, dy, .. }) = moved else { panic!("{case}: a move is one MoveAnnotation, got {moved:?}") };
let origin = map.to_doc(0, [50.0, 80.0]);
let (from, to) = (map.to_user(0, origin), map.to_user(0, origin + delta));
+2 -1
View File
@@ -986,7 +986,8 @@ fn draft_session(ui: &mut egui::Ui, body: &PageBody<'_>, view: &mut DocView, doc
let zoom = placed.scale as f32;
let page_width = f64::from(doc.info.pages.get(page)?.width);
let editor_id = egui::Id::new(("added-text-editor", view.view_key()));
let background_ready = view.session.content.draft.as_ref().and_then(|d| d.index).is_some_and(|index| view.session.text_background.ready_added(page, index));
let background_ready =
view.session.content.draft.as_ref().and_then(|d| d.index).is_some_and(|index| view.session.text_background.ready_added(page, index));
let cv = &mut view.session.content;
let draft = cv.draft.as_mut().filter(|d| d.page == page)?;
let font = crate::edit_text_ui::editor_font(&draft.style, (draft.style.size as f32 * zoom).clamp(1.0, 300.0));
+5 -6
View File
@@ -229,10 +229,7 @@ pub(crate) fn pass(app: &mut PdfCraftApp, ctx: &Context) {
// The window belongs to one page of one document, while that document is being prepared.
let belongs = app.active_ids().map(|(_, id)| id) == Some(doc)
&& app.is_preparing()
&& app
.session
.get(doc)
.is_some_and(|d| d.edit_generation() == generation && page < d.info.pages.len() && d.allows_modification());
&& app.session.get(doc).is_some_and(|d| d.edit_generation() == generation && page < d.info.pages.len() && d.allows_modification());
if !belongs {
app.dialogs.cancel::<FieldTableDialog>(ctx);
return;
@@ -336,8 +333,10 @@ fn widths(ui: &mut Ui, d: &mut FieldTableDraft) {
fn names(ui: &mut Ui, d: &mut FieldTableDraft, info: &PageInfo, form: &[FormField]) {
Text::new(tl!("Field names").to_owned()).show(ui);
// How the names are worked out. Its tokens are the same in every language.
Text::new(tl!("N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last.").to_owned())
.show(ui);
Text::new(
tl!("N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last.").to_owned(),
)
.show(ui);
// The widths shown don't depend on the names being typed below.
let layout = d.laid(info, form);
let total: f64 = d.table.columns.iter().map(|c| c.width).sum();
+34 -6
View File
@@ -392,7 +392,15 @@ fn press_offset(ctx: &egui::Context, view: &DocView, doc: &pdfcraft_engine::Docu
/// the press, its caret where it landed, and a drag moves the caret, so press-and-drag selects text in a field that
/// was not focused (#2213). The rest act on the click, which counts when the button comes up over the widget its press
/// began on, as a button's does.
pub(crate) fn field_press(ctx: &egui::Context, view: &mut DocView, doc: &pdfcraft_engine::Document, info: &DocInfo, allowed: bool, press: &PagePress, mods: Mods) {
pub(crate) fn field_press(
ctx: &egui::Context,
view: &mut DocView,
doc: &pdfcraft_engine::Document,
info: &DocInfo,
allowed: bool,
press: &PagePress,
mods: Mods,
) {
let Owner::Field { field, widget: wi } = press.owner else { return };
let form = doc.form.as_slice();
let Some((f, w)) = form.get(field).and_then(|f| f.widgets.get(wi).map(|w| (f, w))) else { return };
@@ -517,8 +525,14 @@ fn clicked(
picked
} else if multi
&& shift
&& let Some(anchor) =
view.session.forms.list_anchor.as_ref().filter(|(name, _)| *name == f.name).map(|(_, row)| *row).or_else(|| in_order.last().copied())
&& let Some(anchor) = view
.session
.forms
.list_anchor
.as_ref()
.filter(|(name, _)| *name == f.name)
.map(|(_, row)| *row)
.or_else(|| in_order.last().copied())
{
let (min, max) = (anchor.min(opt_idx), anchor.max(opt_idx));
(min..=max).collect()
@@ -726,7 +740,14 @@ pub fn field_screen_font(painter: &egui::Painter, f: &FormField, w: &FormWidget,
if font.is_nan() { 3.0 } else { font.clamp(3.0, MAX_SCREEN_FONT) }
}
fn paint_unbaked_widget(draw: &Draw<'_>, painter: &egui::Painter, xf: &PageXform, frame: TextFrame, (f, wi, w): (&FormField, usize, &FormWidget), r: Rect) {
fn paint_unbaked_widget(
draw: &Draw<'_>,
painter: &egui::Painter,
xf: &PageXform,
frame: TextFrame,
(f, wi, w): (&FormField, usize, &FormWidget),
r: Rect,
) {
// PLAN: framework gap: `Draw` gives no `state.selected` colour, so the selected row still reads the visuals.
let selected_row = painter.ctx().global_style().visuals.selection.bg_fill;
match f.kind {
@@ -774,7 +795,13 @@ fn paint_unbaked_widget(draw: &Draw<'_>, painter: &egui::Painter, xf: &PageXform
if f.selected.contains(&i) {
p.rect_filled(row_rect, CornerRadius::ZERO, selected_row);
}
p.text(egui::pos2(r.min.x + 3.0, y + font_size * 0.15), egui::Align2::LEFT_TOP, display, egui::FontId::proportional(font_size), Color32::BLACK);
p.text(
egui::pos2(r.min.x + 3.0, y + font_size * 0.15),
egui::Align2::LEFT_TOP,
display,
egui::FontId::proportional(font_size),
Color32::BLACK,
);
y += row_h;
}
}
@@ -784,7 +811,8 @@ fn paint_unbaked_widget(draw: &Draw<'_>, painter: &egui::Painter, xf: &PageXform
if checked {
let sz = (r.height() * 0.75).clamp(8.0, 32.0);
let c = r.center();
let tick = vec![egui::pos2(c.x - sz * 0.3, c.y), egui::pos2(c.x - sz * 0.1, c.y + sz * 0.25), egui::pos2(c.x + sz * 0.3, c.y - sz * 0.25)];
let tick =
vec![egui::pos2(c.x - sz * 0.3, c.y), egui::pos2(c.x - sz * 0.1, c.y + sz * 0.25), egui::pos2(c.x + sz * 0.3, c.y - sz * 0.25)];
draw.stroke(&PaintShape::Path(tick), StrokeWidth::Medium, DataColor::new(Color32::BLACK));
}
}
@@ -52,15 +52,13 @@ pub(super) fn choice_list(ui: &mut egui::Ui, field: &FormField, rect: Rect, zoom
};
let names: Vec<&str> = field.options.iter().map(|(_, shown)| shown.as_str()).collect();
let source = Names(&names);
let shown = PopupList::new(tl!("Options"), Bind::bound(&mut *open)).overlay(|overlay| overlay.opener_anchor(Anchor::Rect(rect))).show(
ui,
|ui, _| {
let shown =
PopupList::new(tl!("Options"), Bind::bound(&mut *open)).overlay(|overlay| overlay.opener_anchor(Anchor::Rect(rect))).show(ui, |ui, _| {
List::<usize>::options(field.name.as_str())
.document_rows(DocumentRows::new(FontRef::proportional(), size, align))
.show_items(ui, &source, &mut |key, _| ListRow::new(names.get(*key).copied().unwrap_or("")).option())
.events
},
);
});
let mut picked = None;
for event in shown.inner.into_iter().flatten() {
if let CollectionEvent::Activate(key) = event {
+3 -2
View File
@@ -15,8 +15,8 @@ use egui::{Pos2, Rect, Ui, Vec2};
use pdfcraft_engine::{Document, Edit, EditableObject, MAX_MOVE_OBJECTS, ObjectKind, ObjectTarget};
use pdfcraft_render::DocInfo;
use crate::canvas::{DocView, PageXform};
use crate::canvas::page_parts::{Owner, PageLayer, PagePart, PagePress};
use crate::canvas::{DocView, PageXform};
#[derive(Default)]
pub(crate) struct ObjectSelection {
@@ -412,7 +412,8 @@ pub(crate) fn objects_press(view: &mut DocView, doc: &Document, info: &DocInfo,
PressPhase::Down { .. } => {
if let Owner::Frame { block } = press.owner {
let object = view
.session.objects
.session
.objects
.inventory(doc, page)
.ok()
.and_then(|objects| objects.into_iter().find(|o| o.target == ObjectTarget { kind: ObjectKind::Text, index: block }));
+1 -1
View File
@@ -15,11 +15,11 @@ use pdfcraft_render::DocInfo;
use crate::canvas::{DocView, PageBoxDrag, PageXform};
pub(crate) mod dialog;
mod draft;
mod properties;
mod tabs;
pub(crate) mod tool;
pub(crate) mod dialog;
pub use dialog::FieldPropsDialog;
pub use draft::{ACTION_KINDS, ActionDraft, FieldDraft, FieldTab};
@@ -139,9 +139,10 @@ pub(super) fn body(ui: &mut egui::Ui, d: &mut FieldDraft, shared: Shared<'_>) ->
let tabs = d.tabs();
let keys: Vec<FieldTab> = tabs.iter().map(|(tab, _)| *tab).collect();
let source = keyed(&keys, |key: &FieldTab| *key);
let strip = TabStrip::new(tl!("Field properties")).kind(TabKind::Panel).shown(d.tab).show_items(ui, &source, &mut |key, _| {
Tab::new(tabs.iter().find(|(tab, _)| tab == key).map_or("", |(_, label)| tl!(label)))
});
let strip = TabStrip::new(tl!("Field properties"))
.kind(TabKind::Panel)
.shown(d.tab)
.show_items(ui, &source, &mut |key, _| Tab::new(tabs.iter().find(|(tab, _)| tab == key).map_or("", |(_, label)| tl!(label))));
for event in strip.response.events {
if let CollectionEvent::Selection(SelectionChange::Set(picked)) = event
&& let Some(tab) = picked.last()
@@ -231,7 +232,8 @@ fn appearance_tab(ui: &mut egui::Ui, d: &mut FieldDraft, recent: &RecentColours,
}
fn position_tab(ui: &mut egui::Ui, d: &mut FieldDraft) {
for (i, (salt, label)) in [("left", tl!("Left:")), ("bottom", tl!("Bottom:")), ("width", tl!("Width:")), ("height", tl!("Height:"))].into_iter().enumerate()
for (i, (salt, label)) in
[("left", tl!("Left:")), ("bottom", tl!("Bottom:")), ("width", tl!("Width:")), ("height", tl!("Height:"))].into_iter().enumerate()
{
let range = if i < 2 { -14_400.0..=14_400.0 } else { 4.0..=14_400.0 };
number_row(ui, salt, label, &mut d.position[i], range, Some(tl!("pt")), true);
+8 -3
View File
@@ -264,8 +264,11 @@ pub(super) fn actions_tab(ui: &mut egui::Ui, d: &mut FieldDraft) {
format!("{}, {then}", act.describe())
};
let delete = Label::from(crate::i18n::fmt(tl!("Delete {o}"), &[("o", tl!(tr.label()))]));
let mut item = ListRow::new(format!("{}: {summary}", tl!(tr.label())))
.trailing_part(DELETE, TrailingFace::Icon(IconSpec::svg(IconId::new("trash"))), delete);
let mut item = ListRow::new(format!("{}: {summary}", tl!(tr.label()))).trailing_part(
DELETE,
TrailingFace::Icon(IconSpec::svg(IconId::new("trash"))),
delete,
);
if !editing && matches!(act, pdfcraft_engine::FieldAction::JavaScript(_)) {
item = item.trailing_part(EDIT, TrailingFace::Icon(IconSpec::svg(IconId::new("pencil"))), tl!("Edit"));
}
@@ -403,6 +406,8 @@ fn custom_script(ui: &mut egui::Ui, js: &mut String, refused: &mut bool) {
}
}
if *refused {
Notice::new(Tone::Bad, tl!("A script edited here can be at most 256 KiB long; that change wasn't made.")).layout(NoticeLayout::Inline).show(ui);
Notice::new(Tone::Bad, tl!("A script edited here can be at most 256 KiB long; that change wasn't made."))
.layout(NoticeLayout::Inline)
.show(ui);
}
}
+7 -2
View File
@@ -177,7 +177,8 @@ impl CanvasTool for PrepareTool<'_> {
// A drag that began on a field part moves the field the part's press selected.
let on_selected = self
.view
.session.prepare
.session
.prepare
.selected
.clone()
.filter(|key| widget_rect(self.view, self.form, key).is_some_and(|(page, r)| page == placed.page && r.contains(pointer.pos)));
@@ -188,7 +189,11 @@ impl CanvasTool for PrepareTool<'_> {
return ToolAction::Claimed;
}
let extend = pointer.mods.shift || pointer.mods.cmd;
let base = if extend { self.view.session.prepare.selected.iter().chain(self.view.session.prepare.also.iter()).cloned().collect() } else { Vec::new() };
let base = if extend {
self.view.session.prepare.selected.iter().chain(self.view.session.prepare.also.iter()).cloned().collect()
} else {
Vec::new()
};
self.view.session.prepare.gesture = Gesture::Marquee(MarqueeSelect::begin(pointer.pos, pointer.mods, base));
ToolAction::Claimed
}
+11 -15
View File
@@ -7,6 +7,7 @@ use std::sync::Arc;
use craft::behavior::{CancelReason, Cursor, CursorIcon, DisplayOrder, ItemSource, Selection, SelectionChange};
use craft::host::{PickRequest, Picked};
use craft::pages::ui::PlacedPage;
use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPointer};
use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
use craft::ui::dialog::{DialogId, DialogResult};
@@ -17,7 +18,6 @@ use craft::ui::pickers::ComboBox;
use craft::ui::primitives::Draw;
use craft::ui::sections::Section;
use craft::ui::text::TextField;
use craft::pages::ui::PlacedPage;
use egui::Pos2;
use pdfcraft_engine::{Edit, MarkFile, NewAnnotation, Shape, StampGroup, StampKind, Style};
use pdfcraft_render::DocInfo;
@@ -301,13 +301,14 @@ pub(crate) fn palette_section(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
};
let (mut choose, mut remove) = (None, None);
Section::fixed(tl!("Custom")).id_salt("custom-stamps").show(ui, |ui, _| {
let out = List::new(tl!("Custom stamps"))
.select(SelectMode::Single)
.selection(Bind::bound(&mut selection))
.show_items(ui, &rows, &mut |key, item| match key {
let out = List::new(tl!("Custom stamps")).select(SelectMode::Single).selection(Bind::bound(&mut selection)).show_items(
ui,
&rows,
&mut |key, item| match key {
PaletteKey::Heading(_) => ListRow::new(rows.text(item.at).unwrap_or_default().into_owned()).section_heading().state(item.row.clone()),
PaletteKey::Stamp(_) => ListRow::new(rows.text(item.at).unwrap_or_default().into_owned()).state(item.row.clone()),
});
},
);
for event in out.events {
match event {
CollectionEvent::Selection(SelectionChange::Set(keys)) => {
@@ -346,10 +347,9 @@ impl PdfCraftApp {
/// Create ▸ choose a PDF or an image for a new custom stamp.
pub(crate) fn pick_stamp_file(&mut self, ctx: &egui::Context) {
let ctx = ctx.clone();
let request = PickRequest::open("stamp").title(tl!("Select a file for the stamp")).filter(
tl!("PDF or image"),
&["pdf", "png", "jpg", "jpeg", "tif", "tiff", "gif", "bmp", "jp2", "j2k", "jpx"],
);
let request = PickRequest::open("stamp")
.title(tl!("Select a file for the stamp"))
.filter(tl!("PDF or image"), &["pdf", "png", "jpg", "jpeg", "tif", "tiff", "gif", "bmp", "jp2", "j2k", "jpx"]);
self.pick_file(request, None, |app, picked| match picked {
Picked::Paths(paths) => {
let Some(path) = paths.into_iter().next() else { return };
@@ -380,11 +380,7 @@ impl PdfCraftApp {
let name = file.rsplit_once('.').map_or(file.as_str(), |(s, _)| s).to_string();
let category = self.custom_stamps.last().map(|s| s.category.clone()).unwrap_or_else(|| "My stamps".into());
let existing = categories(&self.custom_stamps);
let fields = DialogFields::from_pairs([
(CATEGORY, category),
(NAME, name),
(LINE, DEFAULT_LINE.to_owned()),
]);
let fields = DialogFields::from_pairs([(CATEGORY, category), (NAME, name), (LINE, DEFAULT_LINE.to_owned())]);
let shown_file = file.clone();
let dialog = HostedParamDialog::new(ctx, DIALOG_KEY, fields, move |fields| {
ParamDialog::new(DIALOG_KEY, tl!("Create Custom Stamp"), create_params(&shown_file, &existing)).ok_enabled(fields_ok(fields))
+4 -2
View File
@@ -224,7 +224,8 @@ pub(crate) fn panel(
let dirty = state.selected.and_then(|r| tags.iter().find(|t| t.object == r)).is_some_and(|tag| state.draft.edit(tag).is_some());
Text::new(crate::i18n::fmt(tl!("{n} tags"), &[("n", &matching.len().to_string())])).shade(Shade::Muted).show(ui);
let mut page = None;
let source = TagRows { rows: &matching, parents: &parents, collapsed: &state.collapsed, searching: !query.is_empty(), selected: state.selected, dirty };
let source =
TagRows { rows: &matching, parents: &parents, collapsed: &state.collapsed, searching: !query.is_empty(), selected: state.selected, dirty };
let mut picked = match state.selected {
Some(object) => Selection::single(object),
None => Selection::new(Vec::new(), None, None),
@@ -289,7 +290,8 @@ pub(crate) fn panel(
let position = siblings.iter().position(|sibling| sibling.object == tag.object);
let before = position.and_then(|position| position.checked_sub(1)).and_then(|position| siblings.get(position).copied());
let after = position.and_then(|position| siblings.get(position + 1)).copied();
let save = Button::new(tl!("Save tag properties")).enabled(can_edit && !state.draft.kind.is_empty() && edit.is_some()).show(ui).response().clicked();
let save =
Button::new(tl!("Save tag properties")).enabled(can_edit && !state.draft.kind.is_empty() && edit.is_some()).show(ui).response().clicked();
if Button::new(tl!("Revert changes")).enabled(dirty).show(ui).response().clicked() {
state.draft = Draft::from_tag(tag);
}