mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-22 02:11:20 +01:00
Merge cfix2/forms (forms files: the forms group's versions)
This commit is contained in:
18 files changed
+312
-269
No files matched your search
@@ -342,14 +342,13 @@ impl PdfCraftApp {
|
||||
/// answer, or a cancellation.
|
||||
fn take_prompt_result(&mut self, id: DialogId, asked: Asked) -> Option<DialogResult<Option<String>>> {
|
||||
match asked {
|
||||
Asked::Alert { proceed, .. } => self.dialogs.take_by_id::<StandardPrompt>(id).map(|result| match result {
|
||||
DialogResult::Ok(answer) => match answer.choice {
|
||||
PromptChoice::Proceed => DialogResult::Ok(Some(proceed.to_owned())),
|
||||
PromptChoice::Alternate => DialogResult::Ok(Some("3".to_owned())),
|
||||
Asked::Alert { proceed, .. } => {
|
||||
self.dialogs.take_by_id::<StandardPrompt>(id).map(|result| match result.ok().map(|answer| answer.choice) {
|
||||
Some(PromptChoice::Proceed) => DialogResult::Ok(Some(proceed.to_owned())),
|
||||
Some(PromptChoice::Alternate) => DialogResult::Ok(Some("3".to_owned())),
|
||||
_ => DialogResult::Cancel,
|
||||
},
|
||||
DialogResult::Cancel => DialogResult::Cancel,
|
||||
}),
|
||||
})
|
||||
}
|
||||
Asked::Dialog => self.dialogs.take_by_id::<ScriptPromptDialog>(id),
|
||||
}
|
||||
}
|
||||
@@ -427,7 +426,7 @@ impl PdfCraftApp {
|
||||
if let Some(i) = self.views.iter().position(|v| v.id == id)
|
||||
&& let Some(info) = self.session.get(id).map(|d| d.info.clone())
|
||||
{
|
||||
self.views[i].document_changed(&info);
|
||||
self.views[i].document_changed(ctx, &info);
|
||||
}
|
||||
self.handle_js(
|
||||
id,
|
||||
@@ -496,15 +495,30 @@ mod review_tests {
|
||||
#[cfg(test)]
|
||||
mod review13_ui_tests {
|
||||
use super::*;
|
||||
/// Create a native app with a visible synthetic blank document and no renderer.
|
||||
fn app() -> (PdfCraftApp, DocId) {
|
||||
let mut app = PdfCraftApp::for_unit_tests();
|
||||
app.set_option("language", "en").unwrap();
|
||||
use craft::host::{AppInfo, Host, Picked, ScriptedFiles, Wake};
|
||||
use craft::platform::clipboard::{Clipboard, EventClipboard};
|
||||
use craft::platform::open::FileIntake;
|
||||
use craft::platform::watch::FileWatch;
|
||||
use craft::ui::notices::PostedNotice;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Create a native app over `files` with a visible synthetic blank document and no renderer.
|
||||
fn app_over(files: Arc<ScriptedFiles>) -> (PdfCraftApp, DocId) {
|
||||
let host = Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).files(files).build();
|
||||
let (intake, _) = FileIntake::new(Wake::none());
|
||||
let clipboard = Clipboard::new(EventClipboard::new(|| 0, |_| Ok(0)));
|
||||
let services = crate::AppServices::new(Wake::none(), clipboard, None, None, intake, FileWatch::new(Wake::none()).inline());
|
||||
let mut app = PdfCraftApp::with_host(Arc::new(host), services);
|
||||
app.set_option(&egui::Context::default(), "language", "en").unwrap();
|
||||
let bytes = app.session.create_blank(200.0, 300.0, 2).unwrap();
|
||||
app.open_bytes("synthetic.pdf", None, bytes.to_vec()).unwrap();
|
||||
let id = app.active_ids().unwrap().1;
|
||||
(app, id)
|
||||
}
|
||||
fn app() -> (PdfCraftApp, DocId) {
|
||||
app_over(Arc::new(ScriptedFiles::new()))
|
||||
}
|
||||
/// Refused clicks and execution/prompt timeouts are visible, while stale runs stay silent.
|
||||
#[test]
|
||||
fn busy_and_timeout_notices_do_not_claim_worker_termination() {
|
||||
@@ -513,8 +527,8 @@ mod review13_ui_tests {
|
||||
let (mut app, id) = app();
|
||||
app.start_ui_script(id, "app.response({cQuestion:'Wait'});", None, None);
|
||||
app.start_ui_script(id, "var shouldNotRun=1;", None, None);
|
||||
assert!(app.toast.as_ref().unwrap().0.contains("not run"));
|
||||
app.toast = None;
|
||||
assert!(app.posted_notices.contains(&PostedNotice::new("Another form script is active; this click was not run")));
|
||||
app.posted_notices.clear();
|
||||
if prompt {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while app.script_pending.as_ref().unwrap().dialog.is_none() && Instant::now() < deadline {
|
||||
@@ -531,9 +545,9 @@ mod review13_ui_tests {
|
||||
app.poll_script_dialog(&ctx);
|
||||
assert!(app.script_pending.is_none());
|
||||
if timeout {
|
||||
assert_eq!(app.toast.as_ref().unwrap().0, "The form script timed out; its result was discarded");
|
||||
assert_eq!(app.posted_notices, [PostedNotice::new("The form script timed out; its result was discarded")]);
|
||||
} else {
|
||||
assert!(app.toast.is_none());
|
||||
assert!(app.posted_notices.is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -541,7 +555,9 @@ mod review13_ui_tests {
|
||||
#[test]
|
||||
fn non_active_comparison_document_completes_native_script() {
|
||||
for request in ["", "app.execMenuItem('SaveAs');", "print();"] {
|
||||
let (mut app, old) = app();
|
||||
let saved = PathBuf::from("/scripted/source.pdf");
|
||||
let files = Arc::new(ScriptedFiles::answering([Picked::Paths(vec![saved.clone()])]));
|
||||
let (mut app, old) = app_over(files.clone());
|
||||
app.views.iter_mut().find(|v| v.id == old).unwrap().view.current = 1;
|
||||
let bytes = app.session.create_blank(200.0, 300.0, 1).unwrap();
|
||||
app.open_bytes("new.pdf", None, bytes.to_vec()).unwrap();
|
||||
@@ -551,14 +567,6 @@ mod review13_ui_tests {
|
||||
app.compare_old = Some(old);
|
||||
app.run_compare();
|
||||
assert!(app.compare.as_ref().unwrap().side_by_side);
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"pdfcraft-comparison-request-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
|
||||
));
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let saved = dir.join("source.pdf");
|
||||
app.save_override = Some(saved.to_string_lossy().into_owned());
|
||||
app.printer_source = Some(std::sync::Arc::new(Vec::new));
|
||||
app.start_ui_script(old, &format!("var comparisonKept=42;{request}"), None, None);
|
||||
let ctx = egui::Context::default();
|
||||
@@ -568,6 +576,8 @@ mod review13_ui_tests {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
assert!(app.script_pending.is_none());
|
||||
// The Save As the script asked for takes the queued answer on this pass.
|
||||
app.save_flow_pass(&ctx);
|
||||
assert_eq!(app.session.run_javascript(old, "comparisonKept", None).unwrap().result.as_deref(), Some("42"));
|
||||
assert_eq!(app.session.save_bytes(new).unwrap(), new_before);
|
||||
assert!(app.session.get(new).unwrap().path.is_none());
|
||||
@@ -575,22 +585,17 @@ mod review13_ui_tests {
|
||||
assert_eq!(app.active_ids().unwrap().1, new, "Save As need not change the comparison tab");
|
||||
assert_eq!(app.session.get(old).unwrap().path.as_deref(), saved.to_str());
|
||||
let mut reopened = pdfcraft_engine::Session::new();
|
||||
let id = reopened.open("saved.pdf", None, std::sync::Arc::new(std::fs::read(&saved).unwrap()), None).unwrap();
|
||||
let id = reopened.open("saved.pdf", None, std::sync::Arc::new(files.file(&saved).unwrap()), None).unwrap();
|
||||
assert_eq!(reopened.get(id).unwrap().info.pages.len(), 2, "the saved file is the two-page source, not the one-page active file");
|
||||
} else if request == "print();" {
|
||||
assert_eq!(app.active_ids().unwrap().1, old, "Print must retain its source as the active document");
|
||||
assert!(app.dialogs.is_open::<craft::print::ui::HostedPrint>());
|
||||
assert_eq!(app.print_draft.current_page, 1);
|
||||
assert!(!saved.exists());
|
||||
assert!(files.file(&saved).is_none());
|
||||
} else {
|
||||
assert_eq!(app.active_ids().unwrap().1, new);
|
||||
assert!(!saved.exists());
|
||||
assert!(files.file(&saved).is_none());
|
||||
}
|
||||
drop(app);
|
||||
if saved.exists() {
|
||||
std::fs::remove_file(saved).unwrap();
|
||||
}
|
||||
std::fs::remove_dir(dir).unwrap();
|
||||
}
|
||||
}
|
||||
/// Script focus reveals the requested field page before opening its editor.
|
||||
|
||||
@@ -424,7 +424,7 @@ fn apply(app: &mut PdfCraftApp, draft: &Draft) -> Result<(), Label> {
|
||||
/// One property: a group box whose check box is `apply`, enclosing the control, which binds the value as a `Mixed`.
|
||||
/// An edit makes a mixed value concrete. `unknown` shows the control as mixed while the row is not applied, for a value the
|
||||
/// control cannot show.
|
||||
fn row<T: Value>(ui: &mut Ui, label: &str, c: &mut Change<T>, unknown: bool, control: impl FnOnce(&mut Ui, &mut Mixed<T>)) {
|
||||
fn row<T: Value>(ui: &mut Ui, label: &str, c: &mut Change<T>, unknown: bool, mut control: impl FnMut(&mut Ui, &mut Mixed<T>)) {
|
||||
let Change { value, mixed, apply } = c;
|
||||
let hidden = unknown && !*apply;
|
||||
GroupBox::apply(tl!(label).to_owned(), Bind::bound(apply)).show(ui, |ui, _| {
|
||||
@@ -494,20 +494,25 @@ fn text_colour(ui: &mut Ui, label: &str, c: &mut Change<[f64; 3]>, recent: &Rece
|
||||
});
|
||||
}
|
||||
|
||||
/// A colour that may be none: `choice` is the row's border or fill chooser.
|
||||
/// A colour that may be none: `choice` is the row's border or fill chooser. Its Other… request is parked in `request`.
|
||||
fn optional_colour(
|
||||
ui: &mut Ui,
|
||||
label: &str,
|
||||
c: &mut Change<Option<[f64; 3]>>,
|
||||
choice: impl FnOnce(&mut Ui, &str, Option<[f64; 3]>) -> Option<Option<[f64; 3]>>,
|
||||
request: &mut Option<ColorRequest>,
|
||||
mut choice: impl FnMut(&mut Ui, Option<[f64; 3]>) -> colours::ColourChoice,
|
||||
) {
|
||||
let Change { value, mixed, apply } = c;
|
||||
GroupBox::apply(tl!(label).to_owned(), Bind::bound(apply)).show(ui, |ui, _| {
|
||||
let current = if *mixed { None } else { *value };
|
||||
if let Some(chosen) = choice(ui, tl!(label), current) {
|
||||
let picked = choice(ui, current);
|
||||
if let Some(chosen) = picked.choice {
|
||||
*value = chosen;
|
||||
*mixed = false;
|
||||
}
|
||||
if picked.request.is_some() {
|
||||
*request = picked.request;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -574,14 +579,12 @@ fn appearance(ui: &mut Ui, d: &mut Draft, recent: &RecentColours, request: &mut
|
||||
let shown_label = d.font.value.label() != d.font_label;
|
||||
let (font, placeholder) = (&mut d.font, d.font_label.clone());
|
||||
row(ui, "Font:", font, shown_label, |ui, shown| {
|
||||
Select::new(tl!("Font:").to_owned(), Bind::bound_mixed(shown), &fonts).placeholder(placeholder).show(ui);
|
||||
Select::new(tl!("Font:").to_owned(), Bind::bound_mixed(shown), &fonts).placeholder(placeholder.clone()).show(ui);
|
||||
});
|
||||
text_colour(ui, "Text Color:", &mut d.text, recent, request);
|
||||
}
|
||||
// PLAN: `border_choice` and `fill_choice` return only the choice (`Option<Option<Rgb>>`), so their "Other colour..."
|
||||
// cannot ask for the picker; the owner (pdf-comments-w10) adds the request, then these rows park it as `text_colour` does.
|
||||
optional_colour(ui, "Border Color:", &mut d.border, |ui, label, current| colours::border_choice(ui, label, current, BORDER_KEY, recent));
|
||||
optional_colour(ui, "Fill Color:", &mut d.fill, |ui, label, current| colours::fill_choice(ui, label, current, FILL_KEY, recent));
|
||||
optional_colour(ui, "Border Color:", &mut d.border, request, |ui, current| colours::border_choice(ui, current, BORDER_KEY, recent));
|
||||
optional_colour(ui, "Fill Color:", &mut d.fill, request, |ui, current| colours::fill_choice(ui, current, FILL_KEY, recent));
|
||||
number(ui, "Line Thickness:", &mut d.width, 0.0..=12.0, Some("pt"), |v| *v, |v| v);
|
||||
let styles: Vec<Entry<BorderStyle>> = BorderStyle::ALL.into_iter().map(|style| Entry::new(style, tl!(style.label()).to_owned())).collect();
|
||||
choose(ui, "Line Style:", &mut d.style, &styles);
|
||||
|
||||
@@ -689,7 +689,7 @@ pub(crate) fn panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
|
||||
app.apply_edit(Edit::SetCalculationOrder { names });
|
||||
}
|
||||
Some(Act::Undo) => {
|
||||
app.execute("edit.undo");
|
||||
app.execute(ui.ctx(), "edit.undo");
|
||||
}
|
||||
Some(Act::EditFormula(name)) => {
|
||||
if let Some(view) = app.views.get_mut(index) {
|
||||
|
||||
@@ -268,5 +268,7 @@ pub(crate) fn show(ui: &mut egui::Ui, body: &PageBody<'_>, session: &mut PageSes
|
||||
typed_with(tb.page, tb.at, &tb.text, tb.size, crate::comments::page_rotation(info, tb.page), author, look)
|
||||
})
|
||||
}
|
||||
// `EditorEnd` is non-exhaustive: an end this code does not know leaves the box open.
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -384,8 +384,7 @@ pub(crate) fn field_parts(view: &DocView, info: &DocInfo, doc: &pdfcraft_engine:
|
||||
/// The char offset in widget `wi` of field `fi`'s draft that the screen point `at` on `page` is over: the one mapping
|
||||
/// from a point to an offset is the editor's, which takes the screen point.
|
||||
fn press_offset(ctx: &egui::Context, view: &DocView, doc: &pdfcraft_engine::Document, info: &DocInfo, fi: usize, wi: usize, at: Pos2) -> usize {
|
||||
// PLAN: `editor` is pdf-forms-w8's module; the lead declares `mod editor;` at combine.
|
||||
editor::offset_at(ctx, view, &doc.form, info, fi, wi, at)
|
||||
editor::offset_at(ctx, view, doc, &doc.form, info, fi, wi, at)
|
||||
}
|
||||
|
||||
/// A press on a form widget part. `allowed`: whether the document lets its fields be filled. A text field opens on
|
||||
|
||||
@@ -54,7 +54,7 @@ pub(super) fn choice_list(ui: &mut egui::Ui, field: &FormField, rect: Rect, zoom
|
||||
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, _| {
|
||||
List::<usize>::options(field.name.as_str())
|
||||
List::<usize>::options(field.name.clone())
|
||||
.document_rows(DocumentRows::new(FontRef::proportional(), size, align))
|
||||
.show_items(ui, &source, &mut |key, _| ListRow::new(names.get(*key).copied().unwrap_or("")).option())
|
||||
.events
|
||||
|
||||
@@ -13,8 +13,8 @@ use craft::behavior::CanvasView;
|
||||
use craft::behavior::kurbo::Point;
|
||||
use craft::pages::ui::view::PageBody;
|
||||
use craft::text::ui::editor::{CaretLine, EditKind, EditorEnd, EditorMode, HostLine, HostRun, TextEditor, TextEditorHost};
|
||||
use craft::ui::contract::Bind;
|
||||
use egui::text::{CCursor, LayoutJob};
|
||||
use craft::ui::contract::{Bind, Show as _};
|
||||
use egui::text::{CCursor, CharIndex, LayoutJob};
|
||||
use egui::{Align, Color32, CornerRadius, FontId, Pos2, Rect, pos2, vec2};
|
||||
use pdfcraft_engine::{Document, FormField, FormFieldKind, FormWidget, field_flags, form_appearance};
|
||||
use pdfcraft_render::DocInfo;
|
||||
@@ -87,7 +87,7 @@ impl FieldLayout {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let mut rows: Vec<Row> = Vec::new();
|
||||
for i in 0..=count {
|
||||
let top = galley.pos_from_cursor(CCursor { index: i, prefer_next_row: true }).min.y;
|
||||
let top = galley.pos_from_cursor(CCursor { index: CharIndex(i), prefer_next_row: true }).min.y;
|
||||
match rows.last_mut() {
|
||||
Some(last) if (top - last.top).abs() < 0.5 => last.chars.end = i,
|
||||
_ => rows.push(Row { chars: i..i, top }),
|
||||
@@ -133,7 +133,7 @@ impl FieldLayout {
|
||||
let x = self.origin.x + offset as f32 * cell;
|
||||
return [pos2(x, self.origin.y), pos2(x, self.origin.y + self.row_height.max(self.font))];
|
||||
}
|
||||
let at = self.galley.pos_from_cursor(CCursor { index: offset, prefer_next_row: row == self.row_of(offset) });
|
||||
let at = self.galley.pos_from_cursor(CCursor { index: CharIndex(offset), prefer_next_row: row == self.row_of(offset) });
|
||||
let bottom = at.max.y.max(at.min.y + self.font);
|
||||
let x = self.origin.x + at.min.x;
|
||||
[pos2(x, self.origin.y + at.min.y), pos2(x, self.origin.y + bottom)]
|
||||
@@ -153,7 +153,7 @@ impl FieldLayout {
|
||||
let at = (v.x / cell).round().max(0.0) as usize;
|
||||
return (at.min(line.chars.end), row);
|
||||
}
|
||||
let at = self.galley.cursor_from_pos(vec2(v.x, line.top + self.row_height / 2.0)).index;
|
||||
let at = self.galley.cursor_from_pos(vec2(v.x, line.top + self.row_height / 2.0)).index.0;
|
||||
(at.clamp(line.chars.start, line.chars.end), row)
|
||||
}
|
||||
|
||||
@@ -382,19 +382,21 @@ pub(crate) fn show(ui: &mut egui::Ui, body: &PageBody<'_>, view: &mut DocView, d
|
||||
Some(EditorEnd::Next) => view.session.pending_edit = super::tab_to_next_field(view, info, form, f, widget, true, None),
|
||||
Some(EditorEnd::Previous) => view.session.pending_edit = super::tab_to_next_field(view, info, form, f, widget, false, None),
|
||||
Some(EditorEnd::Cancel) => view.session.forms.focus = None,
|
||||
None => {}
|
||||
// `EditorEnd` is non-exhaustive: an end this code does not know leaves the session open.
|
||||
Some(_) | None => {}
|
||||
}
|
||||
let Some(focus) = view.session.forms.focus.as_mut() else { return };
|
||||
// A list box is picked from in place on the page, so only a combo box has a drop-down list.
|
||||
let picked = if combo { super::choice_list(ui, f, w, rect, zoom, &mut focus.list_open) } else { None };
|
||||
let picked = if combo { super::choice_list(ui, f, rect, zoom, &mut focus.list_open) } else { None };
|
||||
let date = match &f.actions.format {
|
||||
pdfcraft_engine::form_scripts::Format::Date(fmt) if types => super::calendar(ui, rect, &mut focus.text, fmt, &mut focus.calendar_open),
|
||||
_ => false,
|
||||
pdfcraft_engine::form_scripts::Format::Date(fmt) if types => super::calendar(ui, rect, &focus.text, fmt, &mut focus.calendar_open),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(i) = picked {
|
||||
view.session.pending_edit = Some(list_pick_edit(form, f, vec![i]));
|
||||
view.session.forms.focus = None;
|
||||
} else if date {
|
||||
} else if let Some(text) = date {
|
||||
focus.text = text;
|
||||
commit(view, form);
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ use pdfcraft_engine::form_scripts::{CalcOp, Calculate, DATE_PRESETS, Format, TIM
|
||||
use pdfcraft_engine::{BorderStyle, Document, Edit, FieldFont, FieldLook, FieldProps, FormField, FormFieldKind, NewField};
|
||||
use pdfcraft_render::DocInfo;
|
||||
|
||||
use crate::canvas::{DocView, PageBoxDrag, PageXform};
|
||||
use crate::canvas::{DocView, PageBoxDrag, PageSession, PageXform};
|
||||
|
||||
pub(crate) mod dialog;
|
||||
mod draft;
|
||||
@@ -269,10 +269,10 @@ fn place_tab_badge(widget: Rect, page: Rect, size: egui::Vec2, placed: &[Rect])
|
||||
/// A right-click on widget `widget` of field `field` (the top hit there): the field is selected,
|
||||
/// so the menu acts on it. Part of a selection of several, it becomes the anchor the others line
|
||||
/// up with. Not while a gesture runs: the release acts on the selection the gesture began with.
|
||||
pub(crate) fn context(form: &[FormField], field: usize, widget: usize, view: &mut DocView) {
|
||||
pub(crate) fn context(form: &[FormField], field: usize, widget: usize, session: &mut PageSession) {
|
||||
let Some(f) = form.get(field) else { return };
|
||||
let key = (f.name.clone(), widget);
|
||||
let prep = &mut view.session.prepare;
|
||||
let prep = &mut session.prepare;
|
||||
if !matches!(prep.gesture, Gesture::Idle) {
|
||||
return;
|
||||
}
|
||||
@@ -386,10 +386,10 @@ pub fn arrange(form: &[FormField], anchor: &(String, usize), others: &[(String,
|
||||
/// clear the selection. Each selection is one widget, so selecting one radio button of a group,
|
||||
/// or one copy of a duplicated field, deletes only that one, as in Acrobat (#4609); a field's
|
||||
/// last widget takes the field with it.
|
||||
pub(crate) fn delete_selected(view: &mut DocView) -> Option<Edit> {
|
||||
let first = view.session.prepare.selected.take()?;
|
||||
pub(crate) fn delete_selected(session: &mut PageSession) -> Option<Edit> {
|
||||
let first = session.prepare.selected.take()?;
|
||||
let mut picked = vec![first];
|
||||
for w in std::mem::take(&mut view.session.prepare.also) {
|
||||
for w in std::mem::take(&mut session.prepare.also) {
|
||||
if !picked.contains(&w) {
|
||||
picked.push(w);
|
||||
}
|
||||
@@ -406,30 +406,30 @@ pub(crate) fn delete_selected(view: &mut DocView) -> Option<Edit> {
|
||||
/// Select every widget on the current page.
|
||||
pub(crate) fn select_all(view: &mut DocView, form: &[FormField]) {
|
||||
let mut selected =
|
||||
form.iter().flat_map(|f| f.widgets.iter().enumerate().filter(|(_, w)| w.page == Some(view.current)).map(|(wi, _)| (f.name.clone(), wi)));
|
||||
form.iter().flat_map(|f| f.widgets.iter().enumerate().filter(|(_, w)| w.page == Some(view.current())).map(|(wi, _)| (f.name.clone(), wi)));
|
||||
view.session.prepare.selected = selected.next();
|
||||
view.session.prepare.also = selected.collect();
|
||||
}
|
||||
|
||||
/// After an Add field edit: select the new field (the form's last).
|
||||
pub(crate) fn after_refresh(view: &mut DocView, form: &[FormField]) {
|
||||
view.session.prepare.also.retain(|(name, wi)| form.iter().any(|f| &f.name == name && *wi < f.widgets.len()));
|
||||
if let Some(n) = view.session.prepare.select_added.take() {
|
||||
pub(crate) fn after_refresh(session: &mut PageSession, form: &[FormField]) {
|
||||
session.prepare.also.retain(|(name, wi)| form.iter().any(|f| &f.name == name && *wi < f.widgets.len()));
|
||||
if let Some(n) = session.prepare.select_added.take() {
|
||||
if form.len() > n
|
||||
&& let Some(f) = form.last()
|
||||
{
|
||||
view.session.prepare.selected = Some((f.name.clone(), 0));
|
||||
} else if let Some((name, _)) = &view.session.prepare.selected
|
||||
session.prepare.selected = Some((f.name.clone(), 0));
|
||||
} else if let Some((name, _)) = &session.prepare.selected
|
||||
&& let Some(f) = form.iter().find(|f| &f.name == name)
|
||||
{
|
||||
// A radio button joined the selected group: select the new button.
|
||||
view.session.prepare.selected = Some((f.name.clone(), f.widgets.len().saturating_sub(1)));
|
||||
session.prepare.selected = Some((f.name.clone(), f.widgets.len().saturating_sub(1)));
|
||||
}
|
||||
}
|
||||
if let Some((name, wi)) = &view.session.prepare.selected
|
||||
if let Some((name, wi)) = &session.prepare.selected
|
||||
&& !form.iter().any(|f| &f.name == name && *wi < f.widgets.len())
|
||||
{
|
||||
view.session.prepare.selected = None;
|
||||
session.prepare.selected = None;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -102,7 +102,7 @@ pub(crate) fn finish(app: &mut PdfCraftApp) {
|
||||
let (field, widget, typed) = (dialog.draft.field.clone(), dialog.draft.widget, dialog.draft.name.trim().to_string());
|
||||
if let Some(request) = request {
|
||||
let key = request.key.clone();
|
||||
app.open_colour_picker(&mut app.dialogs, request, move |app, colour: Srgba| {
|
||||
app.open_colour_picker(crate::colour_picker::PickerHost::App, request, move |app, colour: Srgba| {
|
||||
if let Some(dialog) = app.dialogs.get_mut::<FieldPropsDialog>() {
|
||||
dialog.set_colour(&key, crate::comments::colours::to_rgb(colour));
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ impl FlagBit {
|
||||
|
||||
/// A check box; whether the user changed it.
|
||||
pub(super) fn check(ui: &mut egui::Ui, label: &str, value: &mut bool, enabled: bool) -> bool {
|
||||
Checkbox::new(Bind::bound(&mut *value)).label(label).enabled(enabled).show(ui).events.committed().is_some()
|
||||
Checkbox::new(Bind::bound(&mut *value)).label(label.to_owned()).enabled(enabled).show(ui).events.committed().is_some()
|
||||
}
|
||||
|
||||
/// A check box for a `/Ff` bit.
|
||||
@@ -75,21 +75,21 @@ fn flag_box(ui: &mut egui::Ui, d: &mut FieldDraft, bit: u32, inverted: bool, lab
|
||||
/// A labelled one-line text field.
|
||||
pub(super) fn text_row(ui: &mut egui::Ui, salt: &'static str, label: &str, value: &mut String) {
|
||||
Field::new(label).id_salt(salt).show(ui, |ui, _| {
|
||||
TextField::new(label, Bind::bound(&mut *value)).show(ui);
|
||||
TextField::new(label.to_owned(), Bind::bound(&mut *value)).show(ui);
|
||||
});
|
||||
}
|
||||
|
||||
/// A labelled multi-line field for script text: monospaced, and Tab types a tab.
|
||||
pub(super) fn code_row(ui: &mut egui::Ui, salt: &'static str, label: &str, value: &mut String, lines: usize) {
|
||||
Field::new(label).id_salt(salt).show(ui, |ui, _| {
|
||||
TextField::new(label, Bind::bound(&mut *value)).lines(lines).mono().tab_inserts(true).show(ui);
|
||||
TextField::new(label.to_owned(), Bind::bound(&mut *value)).lines(lines).mono().tab_inserts(true).show(ui);
|
||||
});
|
||||
}
|
||||
|
||||
/// A labelled choice among `entries`.
|
||||
pub(super) fn select_row<T: Value>(ui: &mut egui::Ui, salt: &'static str, label: &str, value: &mut T, entries: &[Entry<T>]) {
|
||||
Field::new(label).id_salt(salt).show(ui, |ui, _| {
|
||||
Select::new(label, Bind::bound(&mut *value), entries).show(ui);
|
||||
Select::new(label.to_owned(), Bind::bound(&mut *value), entries).show(ui);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -105,9 +105,9 @@ pub(super) fn number_row(
|
||||
) {
|
||||
let mut shown = Some(*value);
|
||||
Field::new(label).id_salt(salt).show(ui, |ui, _| {
|
||||
let mut field = NumberField::new(label, Bind::bound(&mut shown)).range(range);
|
||||
let mut field = NumberField::new(label.to_owned(), Bind::bound(&mut shown)).range(range.clone());
|
||||
if let Some(unit) = unit {
|
||||
field = field.unit(unit);
|
||||
field = field.unit(unit.to_owned());
|
||||
}
|
||||
field.enabled(enabled).show(ui);
|
||||
});
|
||||
|
||||
@@ -56,11 +56,11 @@ const EDIT: TrailingPart = TrailingPart::new(1);
|
||||
/// value they belong to; the group's value is written back when another is chosen.
|
||||
fn radios<T: Value + Copy>(ui: &mut egui::Ui, name: &str, value: &mut T, options: &[(T, &str)], mut after: impl FnMut(&mut egui::Ui, T)) {
|
||||
let shown = *value;
|
||||
RadioGroup::new(name, Bind::bound(value)).show(ui, |ui, _| {
|
||||
RadioGroup::new(name.to_owned(), Bind::bound(value)).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, cx| {
|
||||
for (at, (option, label)) in options.iter().enumerate() {
|
||||
let side = SideLabel::new().layout(FieldLayout::After);
|
||||
cx.labelled(ui, at, Label::from(*label), side, Radio::new(*option));
|
||||
cx.labelled(ui, at, Label::from((*label).to_owned()), side, Radio::new(*option));
|
||||
if *option == shown {
|
||||
after(ui, *option);
|
||||
}
|
||||
@@ -71,7 +71,7 @@ fn radios<T: Value + Copy>(ui: &mut egui::Ui, name: &str, value: &mut T, options
|
||||
|
||||
/// A choice among the `names`, numbered from 0, over `value`.
|
||||
fn index_row<T: Value + Copy + TryFrom<usize> + Into<usize>>(ui: &mut egui::Ui, salt: &'static str, label: &str, value: &mut T, names: &[&str]) {
|
||||
let entries: Vec<Entry<usize>> = names.iter().enumerate().map(|(i, name)| Entry::new(i, *name)).collect();
|
||||
let entries: Vec<Entry<usize>> = names.iter().enumerate().map(|(i, name)| Entry::new(i, (*name).to_owned())).collect();
|
||||
let mut shown: usize = (*value).into();
|
||||
select_row(ui, salt, label, &mut shown, &entries);
|
||||
if let Ok(v) = T::try_from(shown) {
|
||||
@@ -236,7 +236,7 @@ pub(super) fn actions_tab(ui: &mut egui::Ui, d: &mut FieldDraft) {
|
||||
d.new_action.text.clear();
|
||||
d.editing = None;
|
||||
}
|
||||
Err(e) => note(ui, tl!(&e)),
|
||||
Err(e) => note(ui, tl!(&e).to_owned()),
|
||||
}
|
||||
}
|
||||
if discard {
|
||||
@@ -387,7 +387,7 @@ fn custom_script(ui: &mut egui::Ui, js: &mut String, refused: &mut bool) {
|
||||
let start = js.get(..js.floor_char_boundary(MAX_EDITED_SCRIPT)).unwrap_or_default().to_string();
|
||||
Field::new(label).id_salt("calc-script").show(ui, |ui, _| {
|
||||
// A given value takes no edit: what is typed is not kept.
|
||||
TextField::new(label, Bind::given(start)).lines(6).mono().show(ui);
|
||||
TextField::new(label, Bind::given(start.clone())).lines(6).mono().show(ui);
|
||||
});
|
||||
note(ui, note_text);
|
||||
return;
|
||||
|
||||
@@ -8,71 +8,85 @@ use craft::behavior::kurbo::{Point, Rect as KRect};
|
||||
use craft::behavior::press::{PointerButton, PressPhase};
|
||||
use craft::behavior::{CancelReason, Cursor, CursorIcon, EditEvent, Input, Metrics};
|
||||
use craft::draw::ui::transform::TransformBox;
|
||||
use craft::pages::ui::PlacedPage;
|
||||
use craft::ui::canvas::{CanvasTool, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer};
|
||||
use craft::ui::contract::{Bind, Common, Component, Cx, MeasureCx, PaintUi, Props, Role};
|
||||
use craft::ui::contract::{Bind, Common, Component, Cx, MeasureCx, PaintUi, Props, Role, Show as _};
|
||||
use craft::ui::primitives::{Draw, PaintShape, StrokeWidth, TextRun};
|
||||
use craft::ui::style::{ComponentStyle, StyleColor, StyleCx, TypeRole};
|
||||
use egui::{CornerRadius, Pos2, Rect, Response, Ui, Vec2, vec2};
|
||||
use pdfcraft_engine::{Edit, FieldProps, FormField};
|
||||
use pdfcraft_render::DocInfo;
|
||||
|
||||
use super::{FieldTool, Gesture, PrepareView, delete_selected, place_tab_badge, screen_rect, table_rect, to_user, user_rect};
|
||||
use crate::canvas::page_parts::{Owner, PageLayer, PagePart, PagePress};
|
||||
use crate::canvas::{DocView, PageBoxDrag, PageXform};
|
||||
use crate::canvas::{PageBoxDrag, PageSession, PageXform};
|
||||
|
||||
/// A drag under this many screen pixels either way is a click, which places the default size.
|
||||
const CLICK_SIZE: f32 = 4.0;
|
||||
|
||||
/// The page position, transform and the page's info for `page`, or `None` while it is not laid out.
|
||||
// PLAN: assumed `DocView::info(&self) -> &DocInfo` and `DocView::page_xform(page)` (pdf-canvas-w8); canvas-w8's
|
||||
// written body has neither (it passes `info`, `pages` and `rotation` from its pass and calls
|
||||
// `page_parts(out, session, form, info, pages, rotation)`, `field_press(session, form, press)`): the lead pins one shape.
|
||||
fn geometry(view: &DocView, page: usize) -> Option<PageXform> {
|
||||
view.page_xform(page)
|
||||
/// The transforms of the pages placed this pass, with the view's `rotation` and the page sizes of `info`.
|
||||
fn transforms(pages: &[PlacedPage], info: &DocInfo, rotation: u16) -> Vec<(usize, PageXform)> {
|
||||
pages
|
||||
.iter()
|
||||
.map(|placed| {
|
||||
let size = info.pages.get(placed.page).map_or((1.0, 1.0), |p| (p.width, p.height));
|
||||
(placed.page, PageXform::of(placed, rotation, size))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One part per widget on `page`, for the pages' router: a press on a field selects it, a drag of it
|
||||
/// The transform of `page` among `xforms`.
|
||||
fn transform_of(xforms: &[(usize, PageXform)], page: usize) -> Option<PageXform> {
|
||||
xforms.iter().find(|(p, _)| *p == page).map(|(_, xf)| *xf)
|
||||
}
|
||||
|
||||
/// One part per widget on the placed `pages`, for the pages' router: a press on a field selects it, a drag of it
|
||||
/// moves it. The caller asks only while preparing with no field tool armed, because a field tool draws
|
||||
/// anywhere and fields are then not pressable.
|
||||
pub(crate) fn page_parts(form: &[FormField], page: usize, view: &DocView) -> Vec<PagePart> {
|
||||
let Some(xf) = geometry(view, page) else { return Vec::new() };
|
||||
let info = view.info();
|
||||
let mut parts = Vec::new();
|
||||
for (field, f) in form.iter().enumerate() {
|
||||
for (widget, w) in f.widgets.iter().enumerate().filter(|(_, w)| w.page == Some(page)) {
|
||||
let rect = screen_rect(&xf, info, page, w.rect);
|
||||
parts.push(PagePart::new(Owner::PrepareField { field, widget }, page, rect, PageLayer::Placed).cursor(CursorIcon::Move).passes_drag());
|
||||
// The parts read nothing from the session; the page body hands it over so every owner's `page_parts` has one shape.
|
||||
pub(crate) fn page_parts(out: &mut Vec<PagePart>, _session: &PageSession, form: &[FormField], info: &DocInfo, pages: &[PlacedPage], rotation: u16) {
|
||||
for (page, xf) in transforms(pages, info, rotation) {
|
||||
for (field, f) in form.iter().enumerate() {
|
||||
for (widget, w) in f.widgets.iter().enumerate().filter(|(_, w)| w.page == Some(page)) {
|
||||
let rect = screen_rect(&xf, info, page, w.rect);
|
||||
out.push(PagePart::new(Owner::PrepareField { field, widget }, page, rect, PageLayer::Placed).cursor(CursorIcon::Move).passes_drag());
|
||||
}
|
||||
}
|
||||
}
|
||||
parts
|
||||
}
|
||||
|
||||
/// A press on a field part: a click selects it (Shift or ⌘ toggles it in the selection), a double
|
||||
/// click opens Field Properties, a secondary press selects it for the field menu. A drag that follows
|
||||
/// goes to [`PrepareTool`].
|
||||
pub(crate) fn field_press(press: &PagePress, view: &mut DocView, form: &[FormField]) {
|
||||
pub(crate) fn field_press(session: &mut PageSession, form: &[FormField], press: &PagePress) {
|
||||
let Owner::PrepareField { field, widget } = press.owner else { return };
|
||||
let PressPhase::Down { start, .. } = press.phase else { return };
|
||||
let Some(f) = form.get(field) else { return };
|
||||
match start.button {
|
||||
PointerButton::Secondary => super::context(form, field, widget, view),
|
||||
PointerButton::Secondary => super::context(form, field, widget, session),
|
||||
PointerButton::Primary => {
|
||||
let extend = press.mods.shift || press.mods.cmd;
|
||||
view.session.prepare.select((f.name.clone(), widget), extend);
|
||||
session.prepare.select((f.name.clone(), widget), extend);
|
||||
// The `Down` of a second primary press: the one double press, as `PressState::double_pressed` reads it.
|
||||
if start.clicks >= 2 && !extend {
|
||||
view.session.prepare.outcome.properties = true;
|
||||
session.prepare.outcome.properties = true;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The screen rect of widget `key` and its page.
|
||||
fn widget_rect(view: &DocView, form: &[FormField], key: &(String, usize)) -> Option<(usize, Rect)> {
|
||||
/// The widget `key` names, and the page it is on.
|
||||
fn widget_of<'f>(form: &'f [FormField], key: &(String, usize)) -> Option<(usize, &'f pdfcraft_engine::FormWidget)> {
|
||||
let w = form.iter().find(|f| f.name == key.0)?.widgets.get(key.1)?;
|
||||
let page = w.page?;
|
||||
let xf = geometry(view, page)?;
|
||||
Some((page, screen_rect(&xf, view.info(), page, w.rect)))
|
||||
Some((w.page?, w))
|
||||
}
|
||||
|
||||
/// The screen rect of widget `key` and its page.
|
||||
fn widget_rect(xforms: &[(usize, PageXform)], info: &DocInfo, form: &[FormField], key: &(String, usize)) -> Option<(usize, Rect)> {
|
||||
let (page, w) = widget_of(form, key)?;
|
||||
let xf = transform_of(xforms, page)?;
|
||||
Some((page, screen_rect(&xf, info, page, w.rect)))
|
||||
}
|
||||
|
||||
fn kurbo_rect(r: Rect) -> KRect {
|
||||
@@ -90,24 +104,33 @@ pub(crate) struct PrepareTool<'a> {
|
||||
tool: Option<FieldTool>,
|
||||
allowed: bool,
|
||||
form: &'a [FormField],
|
||||
view: &'a mut DocView,
|
||||
session: &'a mut PageSession,
|
||||
info: &'a DocInfo,
|
||||
/// The transforms of the pages placed this pass.
|
||||
xforms: &'a [(usize, PageXform)],
|
||||
}
|
||||
|
||||
impl<'a> PrepareTool<'a> {
|
||||
/// The tool for this pass. `allowed` is false while a table window is open (nothing is drawn or
|
||||
/// moved then).
|
||||
pub(crate) fn new(tool: Option<FieldTool>, allowed: bool, form: &'a [FormField], view: &'a mut DocView) -> Self {
|
||||
Self { tool, allowed, form, view }
|
||||
pub(crate) fn new(
|
||||
tool: Option<FieldTool>,
|
||||
allowed: bool,
|
||||
form: &'a [FormField],
|
||||
session: &'a mut PageSession,
|
||||
info: &'a DocInfo,
|
||||
xforms: &'a [(usize, PageXform)],
|
||||
) -> Self {
|
||||
Self { tool, allowed, form, session, info, xforms }
|
||||
}
|
||||
|
||||
/// Every widget key and screen rect on every shown page.
|
||||
fn all_widgets(&self) -> Vec<((String, usize), Rect)> {
|
||||
let mut out = Vec::new();
|
||||
for placed in &self.view.placed {
|
||||
let Some(xf) = geometry(self.view, placed.page) else { continue };
|
||||
for (page, xf) in self.xforms {
|
||||
for f in self.form {
|
||||
for (wi, w) in f.widgets.iter().enumerate().filter(|(_, w)| w.page == Some(placed.page)) {
|
||||
out.push(((f.name.clone(), wi), screen_rect(&xf, self.view.info(), placed.page, w.rect)));
|
||||
for (wi, w) in f.widgets.iter().enumerate().filter(|(_, w)| w.page == Some(*page)) {
|
||||
out.push(((f.name.clone(), wi), screen_rect(xf, self.info, *page, w.rect)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -118,27 +141,27 @@ impl<'a> PrepareTool<'a> {
|
||||
let Some(tool) = self.tool else { return };
|
||||
// PLAN: assumed `PageBoxDrag::release(min: f32) -> Option<(usize, Rect)>` (pdf-canvas-w18 note 7)
|
||||
let Some((page, rect)) = drag.release(CLICK_SIZE) else { return };
|
||||
let Some(xf) = geometry(self.view, page) else { return };
|
||||
let Some(xf) = transform_of(self.xforms, page) else { return };
|
||||
let click = rect.width() < CLICK_SIZE || rect.height() < CLICK_SIZE;
|
||||
if tool == FieldTool::TextTable {
|
||||
let area = if click { Rect::from_min_size(origin, Vec2::ZERO) } else { rect };
|
||||
self.view.prepare.outcome.table = Some((page, table_rect(&xf, area)));
|
||||
self.view.prepare.outcome.placed = true;
|
||||
self.session.prepare.outcome.table = Some((page, table_rect(&xf, area)));
|
||||
self.session.prepare.outcome.placed = true;
|
||||
return;
|
||||
}
|
||||
let user = if click {
|
||||
// A click: the default size, top-left at the pointer.
|
||||
let at = to_user(&xf, self.view.info(), page, origin);
|
||||
let at = to_user(&xf, self.info, page, origin);
|
||||
let (w, h) = tool.default_size();
|
||||
[at[0], at[1] - h, at[0] + w, at[1]]
|
||||
} else {
|
||||
user_rect(&xf, self.view.info(), page, rect)
|
||||
user_rect(&xf, self.info, page, rect)
|
||||
};
|
||||
let join = self.view.prepare.selected.as_ref().and_then(|(n, _)| self.form.iter().find(|f| &f.name == n));
|
||||
let join = self.session.prepare.selected.as_ref().and_then(|(n, _)| self.form.iter().find(|f| &f.name == n));
|
||||
let kind = tool.new_field(join);
|
||||
self.view.prepare.select_added = Some(self.form.len());
|
||||
self.view.pending_edit = Some(Edit::AddField { page, rect: user, kind, name: None });
|
||||
self.view.prepare.outcome.placed = true;
|
||||
self.session.prepare.select_added = Some(self.form.len());
|
||||
self.session.pending_edit = Some(Edit::AddField { page, rect: user, kind, name: None });
|
||||
self.session.prepare.outcome.placed = true;
|
||||
}
|
||||
|
||||
fn finish_move(&mut self, page: usize, offset: craft::behavior::kurbo::Vec2, widget: (String, usize)) {
|
||||
@@ -146,19 +169,19 @@ impl<'a> PrepareTool<'a> {
|
||||
if offset.hypot() < 1.0 {
|
||||
return;
|
||||
}
|
||||
let Some((_, rect)) = widget_rect(self.view, self.form, &widget) else { return };
|
||||
let Some(xf) = geometry(self.view, page) else { return };
|
||||
let Some((_, rect)) = widget_rect(self.xforms, self.info, self.form, &widget) else { return };
|
||||
let Some(xf) = transform_of(self.xforms, page) else { return };
|
||||
let moved = rect.translate(vec2(offset.x as f32, offset.y as f32));
|
||||
let user = user_rect(&xf, self.view.info(), page, moved);
|
||||
let user = user_rect(&xf, self.info, page, moved);
|
||||
let (name, wi) = widget;
|
||||
self.view.pending_edit = Some(Edit::SetFieldProps { name, props: Box::new(FieldProps { rect: Some((wi, user)), ..Default::default() }) });
|
||||
self.session.pending_edit = Some(Edit::SetFieldProps { name, props: Box::new(FieldProps { rect: Some((wi, user)), ..Default::default() }) });
|
||||
}
|
||||
|
||||
fn finish_marquee(&mut self, marquee: MarqueeSelect<(String, usize)>) {
|
||||
let hits = self.all_widgets().into_iter().filter(|(_, r)| r.intersects(marquee.rect())).collect::<Vec<_>>();
|
||||
let mut items = marquee.selection(hits).into_iter();
|
||||
self.view.prepare.selected = items.next();
|
||||
self.view.prepare.also = items.collect();
|
||||
self.session.prepare.selected = items.next();
|
||||
self.session.prepare.also = items.collect();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,39 +190,31 @@ impl CanvasTool for PrepareTool<'_> {
|
||||
if !self.allowed || pointer.button != PointerButton::Primary {
|
||||
return ToolAction::Ignored;
|
||||
}
|
||||
let Some(placed) = self.view.session.placed.iter().find(|p| p.rect.contains(pointer.pos)).cloned() else { return ToolAction::Ignored };
|
||||
let Some(placed) = self.session.placed.iter().find(|p| p.rect.contains(pointer.pos)).cloned() else { return ToolAction::Ignored };
|
||||
if self.tool.is_some() {
|
||||
let mut drag = PageBoxDrag::default();
|
||||
drag.press(&placed, pointer.pos);
|
||||
self.view.session.prepare.gesture = Gesture::Draw { drag, origin: pointer.pos };
|
||||
self.session.prepare.gesture = Gesture::Draw { drag, origin: pointer.pos };
|
||||
return ToolAction::Claimed;
|
||||
}
|
||||
// A drag that began on a field part moves the field the part's press selected.
|
||||
let on_selected = self
|
||||
.view
|
||||
.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)));
|
||||
let on_selected = self.session.prepare.selected.clone().filter(|key| {
|
||||
widget_rect(self.xforms, self.info, self.form, key).is_some_and(|(page, r)| page == placed.page && r.contains(pointer.pos))
|
||||
});
|
||||
if let Some(widget) = on_selected {
|
||||
let slop = f64::from(cx.slop);
|
||||
let gesture = MoveGesture::press(&ConstrainStyle::new(slop, slop), point(pointer.pos), pointer.mods, Directions::Four);
|
||||
self.view.session.prepare.gesture = Gesture::Move { page: placed.page, gesture, widget };
|
||||
self.session.prepare.gesture = Gesture::Move { page: placed.page, gesture, widget };
|
||||
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()
|
||||
};
|
||||
self.view.session.prepare.gesture = Gesture::Marquee(MarqueeSelect::begin(pointer.pos, pointer.mods, base));
|
||||
let base = if extend { self.session.prepare.selected.iter().chain(self.session.prepare.also.iter()).cloned().collect() } else { Vec::new() };
|
||||
self.session.prepare.gesture = Gesture::Marquee(MarqueeSelect::begin(pointer.pos, pointer.mods, base));
|
||||
ToolAction::Claimed
|
||||
}
|
||||
|
||||
fn drag(&mut self, pointer: &ToolPointer, _cx: &mut ToolContext<'_>) {
|
||||
match &mut self.view.session.prepare.gesture {
|
||||
match &mut self.session.prepare.gesture {
|
||||
Gesture::Draw { drag, .. } => drag.drag(pointer.pos),
|
||||
Gesture::Marquee(marquee) => marquee.update(pointer.pos),
|
||||
Gesture::Move { gesture, .. } => {
|
||||
@@ -210,7 +225,7 @@ impl CanvasTool for PrepareTool<'_> {
|
||||
}
|
||||
|
||||
fn release(&mut self, pointer: &ToolPointer, _cx: &mut ToolContext<'_>) {
|
||||
match std::mem::take(&mut self.view.session.prepare.gesture) {
|
||||
match std::mem::take(&mut self.session.prepare.gesture) {
|
||||
Gesture::Idle => {}
|
||||
Gesture::Draw { mut drag, origin } => {
|
||||
drag.drag(pointer.pos);
|
||||
@@ -228,26 +243,26 @@ impl CanvasTool for PrepareTool<'_> {
|
||||
}
|
||||
|
||||
fn cancel(&mut self, _reason: CancelReason, _cx: &mut ToolContext<'_>) {
|
||||
if let Gesture::Marquee(marquee) = std::mem::take(&mut self.view.session.prepare.gesture) {
|
||||
if let Gesture::Marquee(marquee) = std::mem::take(&mut self.session.prepare.gesture) {
|
||||
let mut before = marquee.cancel().into_iter();
|
||||
self.view.session.prepare.selected = before.next();
|
||||
self.view.session.prepare.also = before.collect();
|
||||
self.session.prepare.selected = before.next();
|
||||
self.session.prepare.also = before.collect();
|
||||
}
|
||||
}
|
||||
|
||||
fn claims(&self) -> ToolClaims {
|
||||
if self.view.session.prepare.selected.is_some() { ToolClaims::NONE.deletes() } else { ToolClaims::NONE }
|
||||
if self.session.prepare.selected.is_some() { ToolClaims::NONE.deletes() } else { ToolClaims::NONE }
|
||||
}
|
||||
|
||||
fn key(&mut self, key: &ToolKey, _cx: &mut ToolContext<'_>) -> bool {
|
||||
match key {
|
||||
ToolKey::Delete { .. } if self.view.session.prepare.selected.is_some() => {
|
||||
self.view.session.pending_edit = delete_selected(self.view);
|
||||
ToolKey::Delete { .. } if self.session.prepare.selected.is_some() => {
|
||||
self.session.pending_edit = delete_selected(self.session);
|
||||
true
|
||||
}
|
||||
ToolKey::Cancel if self.view.session.prepare.selected.is_some() => {
|
||||
self.view.session.prepare.selected = None;
|
||||
self.view.session.prepare.also.clear();
|
||||
ToolKey::Cancel if self.session.prepare.selected.is_some() => {
|
||||
self.session.prepare.selected = None;
|
||||
self.session.prepare.also.clear();
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
@@ -255,7 +270,7 @@ impl CanvasTool for PrepareTool<'_> {
|
||||
}
|
||||
|
||||
fn paint(&self, _draw: &Draw<'_>, cx: &ToolContext<'_>) {
|
||||
match &self.view.session.prepare.gesture {
|
||||
match &self.session.prepare.gesture {
|
||||
Gesture::Draw { drag, .. } => drag.paint(cx),
|
||||
Gesture::Marquee(marquee) => {
|
||||
let r = marquee.rect();
|
||||
@@ -277,15 +292,14 @@ impl CanvasTool for PrepareTool<'_> {
|
||||
/// The corner handles of the anchor field, as a Free Transform box that only resizes: no rotating,
|
||||
/// skewing or distorting, and a press inside is the field part's. A corner drag's `Commit` and an
|
||||
/// arrow nudge's `Set` each become one field edit; Escape with no drag clears the selection.
|
||||
// PLAN: the box's state is in the canvas's document space; assumed that is screen space on the page body
|
||||
// (pdf-canvas-w8), as the sheet's `selection_box(ui, view, form, page)` gives no view.
|
||||
pub(crate) fn selection_box(ui: &mut Ui, view: &mut DocView, form: &[FormField], page: usize) {
|
||||
let Some(key) = view.session.prepare.selected.clone() else { return };
|
||||
let Some((widget_page, rect)) = widget_rect(view, form, &key) else { return };
|
||||
// PLAN: the box's state is in the canvas's document space; assumed that is screen space on the page body (pdf-canvas-w8).
|
||||
pub(crate) fn selection_box(ui: &mut Ui, session: &mut PageSession, form: &[FormField], info: &DocInfo, xforms: &[(usize, PageXform)], page: usize) {
|
||||
let Some(key) = session.prepare.selected.clone() else { return };
|
||||
let Some((widget_page, rect)) = widget_rect(xforms, info, form, &key) else { return };
|
||||
if widget_page != page {
|
||||
return;
|
||||
}
|
||||
let Some(xf) = geometry(view, page) else { return };
|
||||
let Some(xf) = transform_of(xforms, page) else { return };
|
||||
let rules = BoxRules::default()
|
||||
.with_scale(ScaleRule::Free)
|
||||
.with_allow(BoxAllow::new(false, false, false).with_warp(false))
|
||||
@@ -309,14 +323,14 @@ pub(crate) fn selection_box(ui: &mut Ui, view: &mut DocView, form: &[FormField],
|
||||
hi = Point::new(hi.x.max(p.x), hi.y.max(p.y));
|
||||
}
|
||||
let screen = Rect::from_min_max(Pos2::new(lo.x as f32, lo.y as f32), Pos2::new(hi.x as f32, hi.y as f32));
|
||||
edit = Some(user_rect(&xf, view.info(), page, screen));
|
||||
edit = Some(user_rect(&xf, info, page, screen));
|
||||
}
|
||||
if let Some(user) = edit {
|
||||
let (name, wi) = key;
|
||||
view.session.pending_edit = Some(Edit::SetFieldProps { name, props: Box::new(FieldProps { rect: Some((wi, user)), ..Default::default() }) });
|
||||
session.pending_edit = Some(Edit::SetFieldProps { name, props: Box::new(FieldProps { rect: Some((wi, user)), ..Default::default() }) });
|
||||
} else if shown.discard {
|
||||
view.session.prepare.selected = None;
|
||||
view.session.prepare.also.clear();
|
||||
session.prepare.selected = None;
|
||||
session.prepare.also.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,11 +354,17 @@ pub(crate) struct PrepareOverlay {
|
||||
}
|
||||
|
||||
impl PrepareOverlay {
|
||||
/// The overlay of `page`, from the form, the tab order and the view's selection and gesture.
|
||||
pub(crate) fn new(form: &[FormField], tab_order: &[(usize, usize)], view: &DocView, page: usize) -> Option<Self> {
|
||||
let xf = geometry(view, page)?;
|
||||
let info = view.info();
|
||||
let prep: &PrepareView = &view.session.prepare;
|
||||
/// The overlay of `page`, from the form, the tab order and the session's selection and gesture.
|
||||
pub(crate) fn new(
|
||||
form: &[FormField],
|
||||
tab_order: &[(usize, usize)],
|
||||
session: &PageSession,
|
||||
info: &DocInfo,
|
||||
xforms: &[(usize, PageXform)],
|
||||
page: usize,
|
||||
) -> Option<Self> {
|
||||
let xf = transform_of(xforms, page)?;
|
||||
let prep: &PrepareView = &session.prepare;
|
||||
let moving = match &prep.gesture {
|
||||
Gesture::Move { page: p, gesture, widget } if *p == page => {
|
||||
let d = gesture.value().delta;
|
||||
|
||||
@@ -178,15 +178,14 @@ pub(crate) fn show_props(app: &mut PdfCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
|
||||
/// Opens Mark Page Range over the current page.
|
||||
pub(crate) fn open_pages(app: &mut PdfCraftApp) {
|
||||
pub(crate) fn open_pages(app: &mut PdfCraftApp, ctx: &egui::Context) {
|
||||
let Some((i, id)) = app.active_ids() else { return };
|
||||
let Some(doc) = app.session.get(id) else { return };
|
||||
let count = doc.info.pages.len();
|
||||
let current = app.views.get(i).map_or(0, |v| v.current);
|
||||
let current = app.views.get(i).map_or(0, |v| v.current());
|
||||
let range = PageRange { scope: PageScope::Current, ..PageRange::default() };
|
||||
let fields = DialogFields::from_pairs([("pages", PageRangeOptions::field_value(&range))]);
|
||||
let Some(ctx) = app.ctx.clone() else { return };
|
||||
let dialog = HostedParamDialog::new(&ctx, "redact.pages", fields, move |fields| {
|
||||
let dialog = HostedParamDialog::new(ctx, "redact.pages", fields, move |fields| {
|
||||
let rows = vec![PageRangeOptions::param("pages", "", count, current, PageRangeChoices::Current)];
|
||||
ParamDialog::new("redact.pages", tl!("Mark Page Range"), rows).values(Bind::bound(fields))
|
||||
});
|
||||
@@ -200,7 +199,7 @@ pub(crate) fn finish_pages(app: &mut PdfCraftApp, fields: &DialogFields) {
|
||||
let Some((i, id)) = app.active_ids() else { return };
|
||||
let Some(doc) = app.session.get(id) else { return };
|
||||
let count = doc.info.pages.len();
|
||||
let current = app.views.get(i).map_or(0, |v| v.current);
|
||||
let current = app.views.get(i).map_or(0, |v| v.current());
|
||||
let pages = range.pages(count, current, &[]);
|
||||
app.redact_pages(&pages);
|
||||
}
|
||||
|
||||
@@ -39,6 +39,8 @@ pub(crate) struct RedactTool<'a> {
|
||||
select: PageSelectTool<'a>,
|
||||
drag: PageBoxDrag,
|
||||
placed: &'a [PlacedPage],
|
||||
/// The view's rotation, in degrees clockwise.
|
||||
rotation: u16,
|
||||
info: &'a DocInfo,
|
||||
over_text: Box<dyn Fn(Pos2) -> bool + 'a>,
|
||||
gesture: Gesture,
|
||||
@@ -49,11 +51,18 @@ pub(crate) struct RedactTool<'a> {
|
||||
impl<'a> RedactTool<'a> {
|
||||
/// The tool over the placed pages, with the select tool that runs text selections and the
|
||||
/// test of whether a screen point is over text (the same one the I-beam uses).
|
||||
pub(crate) fn new(select: PageSelectTool<'a>, placed: &'a [PlacedPage], info: &'a DocInfo, over_text: impl Fn(Pos2) -> bool + 'a) -> Self {
|
||||
pub(crate) fn new(
|
||||
select: PageSelectTool<'a>,
|
||||
placed: &'a [PlacedPage],
|
||||
rotation: u16,
|
||||
info: &'a DocInfo,
|
||||
over_text: impl Fn(Pos2) -> bool + 'a,
|
||||
) -> Self {
|
||||
Self {
|
||||
select,
|
||||
drag: PageBoxDrag::default(),
|
||||
placed,
|
||||
rotation,
|
||||
info,
|
||||
over_text: Box::new(over_text),
|
||||
gesture: Gesture::Idle,
|
||||
@@ -89,9 +98,10 @@ impl<'a> RedactTool<'a> {
|
||||
|
||||
/// A screen point of `placed` in the page's user space.
|
||||
fn to_user(&self, placed: &PlacedPage, p: Pos2) -> Option<[f64; 2]> {
|
||||
let xf = PageXform::of(placed, self.info);
|
||||
let page = self.info.pages.get(placed.page)?;
|
||||
let xf = PageXform::of(placed, self.rotation, (page.width, page.height));
|
||||
let (vx, vy) = xf.screen_to_view(p);
|
||||
let u = self.info.pages.get(placed.page)?.view_to_user(vx, vy);
|
||||
let u = page.view_to_user(vx, vy);
|
||||
Some([u[0] as f64, u[1] as f64])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,7 +272,7 @@ impl PdfCraftApp {
|
||||
|
||||
/// Start signing: the rectangle (or field) is known; show Sign with a Digital ID, after a
|
||||
/// dynamic form's preSign scripts for the field.
|
||||
pub fn start_signing(&mut self, page: usize, rect: Option<[f64; 4]>, field: Option<String>, certify: Option<u8>) {
|
||||
pub fn start_signing(&mut self, ctx: &egui::Context, page: usize, rect: Option<[f64; 4]>, field: Option<String>, certify: Option<u8>) {
|
||||
self.refresh_os_key_store_ids();
|
||||
let mut draft = SignDraft::new(page, rect, field.clone(), certify, &self.digital_ids);
|
||||
draft.graphic = match &self.sign_graphic {
|
||||
@@ -289,16 +289,16 @@ impl PdfCraftApp {
|
||||
if let Some(f) = &field
|
||||
&& let Some((_, doc)) = self.active_ids()
|
||||
{
|
||||
self.run_presign(doc, f);
|
||||
self.run_presign(ctx, doc, f);
|
||||
}
|
||||
}
|
||||
|
||||
/// Run signature field `field`'s preSign scripts in document `doc` and keep the step pending.
|
||||
fn run_presign(&mut self, doc: pdfcraft_engine::DocId, field: &str) {
|
||||
fn run_presign(&mut self, ctx: &egui::Context, doc: pdfcraft_engine::DocId, field: &str) {
|
||||
match self.session.run_sign_event(doc, field, pdfcraft_engine::js::SignEvent::Before) {
|
||||
Ok(true) => {
|
||||
self.presign = self.session.get(doc).map(|d| (doc, d.undo_depth()));
|
||||
self.refresh_view_of(doc);
|
||||
self.refresh_view_of(ctx, doc);
|
||||
let out = self.session.take_js_output(doc);
|
||||
self.handle_js(doc, out);
|
||||
}
|
||||
@@ -310,7 +310,7 @@ impl PdfCraftApp {
|
||||
/// Take back a pending preSign step once signing has ended without a signature: the Sign
|
||||
/// dialog closed and no save picker is open for it. Only a step still the last one is taken
|
||||
/// back. Called every frame.
|
||||
pub(crate) fn settle_presign(&mut self) {
|
||||
pub(crate) fn settle_presign(&mut self, ctx: &egui::Context) {
|
||||
let Some((doc, depth)) = self.presign else { return };
|
||||
if self.picks_pending() {
|
||||
return;
|
||||
@@ -320,16 +320,16 @@ impl PdfCraftApp {
|
||||
}
|
||||
self.presign = None;
|
||||
if self.session.get(doc).is_some_and(|d| d.undo_depth() == depth) && self.session.undo(doc).is_ok() {
|
||||
self.refresh_view_of(doc);
|
||||
self.refresh_view_of(ctx, doc);
|
||||
}
|
||||
}
|
||||
|
||||
/// Show document `doc`'s changed form in its view.
|
||||
fn refresh_view_of(&mut self, doc: pdfcraft_engine::DocId) {
|
||||
fn refresh_view_of(&mut self, ctx: &egui::Context, doc: pdfcraft_engine::DocId) {
|
||||
if let Some(i) = self.views.iter().position(|v| v.id == doc)
|
||||
&& let Some(info) = self.session.get(doc).map(|d| d.info.clone())
|
||||
{
|
||||
self.views[i].document_changed(&info);
|
||||
self.views[i].document_changed(ctx, &info);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -402,9 +402,14 @@ impl PdfCraftApp {
|
||||
true
|
||||
}
|
||||
|
||||
/// Configure New Digital ID ▸ Create: a self-signed ID saved as a .p12 next to the app data
|
||||
/// (or in `export_dir_override`). Returns its list index.
|
||||
/// Configure New Digital ID ▸ Create: a self-signed ID saved as a .p12 next to the app data.
|
||||
/// Returns its list index.
|
||||
fn create_digital_id(&mut self) -> Result<usize, String> {
|
||||
self.create_digital_id_in(id_dir())
|
||||
}
|
||||
|
||||
/// [`Self::create_digital_id`], saving into `dir` (`None`: there is no folder to save in).
|
||||
fn create_digital_id_in(&mut self, dir: Option<PathBuf>) -> Result<usize, String> {
|
||||
let (path, cert) = {
|
||||
let Some(d) = self.sign_draft.as_ref().map(|d| &d.new_id) else { return Err("nothing to create".into()) };
|
||||
if d.name.trim().is_empty() {
|
||||
@@ -431,11 +436,7 @@ impl PdfCraftApp {
|
||||
let cert = Certificate::self_signed(&dn, &key, sign::Time::from_unix(now), 5, &serial).map_err(|e| e.to_string())?;
|
||||
let id = DigitalId { key, certificate: cert.clone(), chain: Vec::new(), friendly_name: Some(d.name.trim().to_string()) };
|
||||
let p12 = sign::pkcs12::write(&id, &d.password).map_err(|e| e.to_string())?;
|
||||
let dir = match &self.export_dir_override {
|
||||
Some(p) => Some(PathBuf::from(p)),
|
||||
None => id_dir(),
|
||||
}
|
||||
.ok_or("There is no folder to save the digital ID in.")?;
|
||||
let dir = dir.ok_or("There is no folder to save the digital ID in.")?;
|
||||
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
||||
let stem: String = d.name.trim().chars().map(|c| if c.is_alphanumeric() || c == ' ' || c == '-' { c } else { '_' }).collect();
|
||||
let path = save_new_id_file(&dir, &stem, &p12).map_err(|e| e.to_string())?;
|
||||
@@ -542,7 +543,7 @@ impl PdfCraftApp {
|
||||
if let Some(view) = app.views.iter_mut().find(|v| v.id == doc_id) {
|
||||
view.invalidate_content();
|
||||
}
|
||||
app.right = Some(crate::RightPanel::Signatures);
|
||||
app.set_right(Some(crate::RightPanel::Signatures));
|
||||
app.notify_fmt("Signed and saved to {path}", &[("path", &path.display().to_string())]);
|
||||
app.handle_js(doc_id, said);
|
||||
if let Some(e) = after {
|
||||
@@ -550,27 +551,22 @@ impl PdfCraftApp {
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
match self.save_override.clone() {
|
||||
Some(p) => sign_and_save(self, PathBuf::from(p)),
|
||||
None => {
|
||||
// The signature's page, rectangle and field refer to the document as it is now:
|
||||
// the pick is dropped (with a notice) if it is edited or switched away from
|
||||
// meanwhile. An error after the pick arrives as a notice.
|
||||
let mut request = PickRequest::save(FilePurpose::SignedCopy.key()).file_name(format!("{stem}_signed.pdf")).filter("PDF", &["pdf"]);
|
||||
if let Some(parent) = folder.as_deref().and_then(|p| std::path::Path::new(p).parent()) {
|
||||
request = request.default_directory(parent);
|
||||
}
|
||||
// PLAN: assumed `pick_file(PickRequest, Option<target of doc_id>, FnOnce(&mut Self, PathBuf))` (pdf-shell-w14); the target is the document id.
|
||||
self.pick_file(request, Some(doc_id), move |app: &mut Self, path: PathBuf| {
|
||||
if let Err(e) = sign_and_save(app, path)
|
||||
&& !e.is_empty()
|
||||
{
|
||||
app.notify(e);
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
// The signature's page, rectangle and field refer to the document as it is now:
|
||||
// the pick is dropped (with a notice) if it is edited or switched away from
|
||||
// meanwhile. An error after the pick arrives as a notice.
|
||||
let mut request = PickRequest::save(FilePurpose::SignedCopy.key()).file_name(format!("{stem}_signed.pdf")).filter("PDF", &["pdf"]);
|
||||
if let Some(parent) = folder.as_deref().and_then(|p| std::path::Path::new(p).parent()) {
|
||||
request = request.default_directory(parent);
|
||||
}
|
||||
let target = self.pick_target(Some(doc_id));
|
||||
self.pick_first(request, target, move |app: &mut Self, path: PathBuf| {
|
||||
if let Err(e) = sign_and_save(app, path)
|
||||
&& !e.is_empty()
|
||||
{
|
||||
app.notify(e);
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The saved signature or image `g` stands for (`None`: the name).
|
||||
@@ -678,8 +674,8 @@ impl PdfCraftApp {
|
||||
// The reading-colours preference is app-wide: the newly opened revision starts with it.
|
||||
self.session.set_reading_colors(new, self.reading_colors);
|
||||
let Some(doc) = self.session.get(new) else { return };
|
||||
let mut view = DocView::new(new, &doc.info, self.view_defaults);
|
||||
if self.full_screen {
|
||||
let mut view = DocView::new(new, &doc.info, self.view_defaults, self.highlight_fields);
|
||||
if self.full_screen() {
|
||||
view.enter_presentation();
|
||||
}
|
||||
view.snapshot = Some(Snapshot { kind: SnapshotKind::Revision, revision: n, from });
|
||||
@@ -730,8 +726,8 @@ impl PdfCraftApp {
|
||||
// The reading-colours preference is app-wide: the newly opened copy starts with it.
|
||||
self.session.set_reading_colors(new, self.reading_colors);
|
||||
let Some(doc) = self.session.get(new) else { return };
|
||||
let mut view = DocView::new(new, &doc.info, self.view_defaults);
|
||||
if self.full_screen {
|
||||
let mut view = DocView::new(new, &doc.info, self.view_defaults, self.highlight_fields);
|
||||
if self.full_screen() {
|
||||
view.enter_presentation();
|
||||
}
|
||||
view.snapshot = Some(Snapshot { kind: SnapshotKind::SignedVersion, revision, from });
|
||||
@@ -761,7 +757,6 @@ mod tests {
|
||||
/// does. Returns where it was saved.
|
||||
fn create_in(dir: &std::path::Path) -> Result<PathBuf, String> {
|
||||
let mut app = PdfCraftApp::for_unit_tests();
|
||||
app.export_dir_override = Some(dir.to_string_lossy().into_owned());
|
||||
let mut draft = SignDraft::new(0, None, None, None, &[]);
|
||||
// P-256 keeps the test fast.
|
||||
let key = KEY_ALGORITHMS.iter().position(|k| k.1 == "p256").unwrap();
|
||||
@@ -770,25 +765,31 @@ mod tests {
|
||||
draft.new_id.password = "secret12".into();
|
||||
draft.new_id.confirm = "secret12".into();
|
||||
app.sign_draft = Some(draft);
|
||||
let i = app.create_digital_id()?;
|
||||
let i = app.create_digital_id_in(Some(dir.to_path_buf()))?;
|
||||
Ok(PathBuf::from(&app.digital_ids[i].path))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exported_certificate_is_written_inside_the_chosen_folder() {
|
||||
let dir = scratch();
|
||||
let out = dir.join("out");
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
use craft::host::{AppInfo, Host, Picked, ScriptedFiles, Wake};
|
||||
use craft::platform::clipboard::{Clipboard, EventClipboard};
|
||||
use craft::platform::open::FileIntake;
|
||||
use craft::platform::watch::FileWatch;
|
||||
use std::sync::Arc;
|
||||
|
||||
let out = PathBuf::from("/scripted/out");
|
||||
let files = Arc::new(ScriptedFiles::answering([Picked::Paths(vec![out.clone()])]));
|
||||
let host = Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).files(files.clone()).build();
|
||||
let (intake, _) = FileIntake::new(Wake::none());
|
||||
let clipboard = Clipboard::new(EventClipboard::new(|| 0, |_| Ok(0)));
|
||||
let services = crate::AppServices::new(Wake::none(), clipboard, None, None, intake, FileWatch::new(Wake::none()).inline());
|
||||
let mut app = PdfCraftApp::with_host(Arc::new(host), services);
|
||||
let key = PrivateKey::generate_p256().unwrap();
|
||||
let cert = Certificate::self_signed(&Name::build("../x", "", "", "", ""), &key, sign::Time::from_unix(0), 1, &[1]).unwrap();
|
||||
let mut app = PdfCraftApp::for_unit_tests();
|
||||
app.export_dir_override = Some(out.to_string_lossy().into_owned());
|
||||
app.export_certificate(&cert);
|
||||
let written: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name()).collect();
|
||||
assert_eq!(written, vec![std::ffi::OsString::from("out")]);
|
||||
let pem = std::fs::read_to_string(out.join(".._x.cer")).unwrap();
|
||||
app.process_picks();
|
||||
let pem = String::from_utf8(files.file(&out.join(".._x.cer")).unwrap()).unwrap();
|
||||
assert!(pem.starts_with("-----BEGIN CERTIFICATE-----"), "{pem}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -913,7 +914,7 @@ mod tests {
|
||||
assert!(app.remove_digital_id(1));
|
||||
assert_eq!(app.sign_draft.as_ref().unwrap().selected, Some(0));
|
||||
let mut fresh = PdfCraftApp::for_unit_tests();
|
||||
fresh.restore(&app.persist());
|
||||
fresh.apply_settings(&app.settings_snapshot());
|
||||
assert!(fresh.digital_ids.is_empty(), "the removal survives a restart: {:?}", fresh.digital_ids);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -1020,9 +1021,9 @@ mod tests {
|
||||
fn dismissing_or_stepping_back_in_the_sign_dialog_clears_passwords() {
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(|_| {
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(|cc| {
|
||||
let mut app = PdfCraftApp::for_unit_tests();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.set_option(&cc.egui_ctx, "language", "en").unwrap();
|
||||
app.digital_ids = vec![listed("/ids/grace.p12", "Grace Hopper")];
|
||||
let mut draft = SignDraft::new(0, None, None, None, &app.digital_ids);
|
||||
draft.step = SignStep::SignAs;
|
||||
@@ -1063,7 +1064,14 @@ mod tests {
|
||||
// Importing a digital ID file and signing work by borrowing the draft in place.
|
||||
let dir = scratch();
|
||||
let saved = create_in(&dir).unwrap();
|
||||
let mut import_app = PdfCraftApp::for_unit_tests();
|
||||
let out_pdf = dir.join("signed.pdf");
|
||||
let files = std::sync::Arc::new(craft::host::ScriptedFiles::answering([craft::host::Picked::Paths(vec![out_pdf.clone()])]));
|
||||
let host = craft::host::Host::builder(craft::host::AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).files(files).build();
|
||||
let (intake, _) = craft::platform::open::FileIntake::new(craft::host::Wake::none());
|
||||
let clipboard = craft::platform::clipboard::Clipboard::new(craft::platform::clipboard::EventClipboard::new(|| 0, |_| Ok(0)));
|
||||
let watch = craft::platform::watch::FileWatch::new(craft::host::Wake::none()).inline();
|
||||
let services = crate::AppServices::new(craft::host::Wake::none(), clipboard, None, None, intake, watch);
|
||||
let mut import_app = PdfCraftApp::with_host(std::sync::Arc::new(host), services);
|
||||
let mut import_draft = SignDraft::new(0, None, None, None, &[]);
|
||||
import_draft.new_id.create = false;
|
||||
import_draft.new_id.file = saved.to_string_lossy().into_owned();
|
||||
@@ -1074,13 +1082,12 @@ mod tests {
|
||||
|
||||
let bytes = pdfcraft_engine::Session::new().create_blank(200.0, 200.0, 1).unwrap();
|
||||
import_app.open_bytes("unsigned.pdf", None, bytes.as_ref().clone()).unwrap();
|
||||
let out_pdf = dir.join("signed.pdf");
|
||||
import_app.save_override = Some(out_pdf.to_string_lossy().into_owned());
|
||||
let mut sign_draft = SignDraft::new(0, None, None, None, &import_app.digital_ids);
|
||||
sign_draft.step = SignStep::SignAs;
|
||||
sign_draft.password = "secret12".into();
|
||||
import_app.sign_draft = Some(sign_draft);
|
||||
assert_eq!(import_app.finish_signing(), Ok(()));
|
||||
import_app.process_picks();
|
||||
assert!(out_pdf.exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ use craft::review::ui::signature::paint_signature;
|
||||
use craft::theme::variant::Tone;
|
||||
use craft::ui::buttons::Button;
|
||||
use craft::ui::choice::{Checkbox, Radio, RadioGroup};
|
||||
use craft::ui::contract::{Bind, CollectionEvent, Entry, SelectMode, Show, ShowCollection as _, ShowContainer as _};
|
||||
use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, SelectMode, Show, ShowCollection as _, ShowContainer as _};
|
||||
use craft::ui::display::{Picture, PictureSize, Text};
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
@@ -222,7 +222,7 @@ fn run(app: &mut PdfCraftApp, step: SignStep, picked: Option<usize>, asked: Aske
|
||||
/// The error line of the draft.
|
||||
fn error(ui: &mut egui::Ui, error: &Option<String>) {
|
||||
if let Some(e) = error.as_ref().filter(|e| !e.is_empty()) {
|
||||
Notice::new(Tone::Bad, tl!(e)).show(ui);
|
||||
Notice::new(Tone::Bad, tl!(e).to_owned()).show(ui);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,12 +14,13 @@ const LEAST_SIDE: f32 = 8.0;
|
||||
|
||||
/// Drags a signature rectangle on one page. The rectangle of a finished drag is taken with
|
||||
/// [`SignAreaTool::finished`], in user space of its page.
|
||||
// PLAN: pdf-canvas-w9 (`canvas/page_tools.rs:322`) calls `SignAreaTool::new(certify)`; it passes `cx.pages` and `cx.info` as well.
|
||||
pub(crate) struct SignAreaTool<'a> {
|
||||
drag: PageBoxDrag,
|
||||
/// Certify (DocMDP) rather than sign: names the command that takes the same numbers.
|
||||
certify: bool,
|
||||
placed: &'a [PlacedPage],
|
||||
/// The view's rotation, in degrees clockwise.
|
||||
rotation: u16,
|
||||
info: &'a DocInfo,
|
||||
drawn: Option<(usize, [f64; 4])>,
|
||||
}
|
||||
@@ -27,8 +28,8 @@ pub(crate) struct SignAreaTool<'a> {
|
||||
impl<'a> SignAreaTool<'a> {
|
||||
/// A tool over the placed pages that draws the area for a certification when `certify`, for a
|
||||
/// signature otherwise.
|
||||
pub(crate) fn new(certify: bool, placed: &'a [PlacedPage], info: &'a DocInfo) -> Self {
|
||||
Self { drag: PageBoxDrag::default(), certify, placed, info, drawn: None }
|
||||
pub(crate) fn new(certify: bool, placed: &'a [PlacedPage], rotation: u16, info: &'a DocInfo) -> Self {
|
||||
Self { drag: PageBoxDrag::default(), certify, placed, rotation, info, drawn: None }
|
||||
}
|
||||
|
||||
/// The (page, user-space rectangle) a drag finished with since the last call, once.
|
||||
@@ -42,8 +43,9 @@ impl<'a> SignAreaTool<'a> {
|
||||
|
||||
/// A screen point of `placed` in the page's user space.
|
||||
fn to_user(&self, placed: &PlacedPage, p: Pos2) -> Option<[f64; 2]> {
|
||||
let (vx, vy) = PageXform::of(placed, self.info).screen_to_view(p);
|
||||
let u = self.info.pages.get(placed.page)?.view_to_user(vx, vy);
|
||||
let page = self.info.pages.get(placed.page)?;
|
||||
let (vx, vy) = PageXform::of(placed, self.rotation, (page.width, page.height)).screen_to_view(p);
|
||||
let u = page.view_to_user(vx, vy);
|
||||
Some([f64::from(u[0]), f64::from(u[1])])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,7 +116,7 @@ impl PdfCraftApp {
|
||||
Panel::Layers => crate::RightPanel::Layers,
|
||||
};
|
||||
// Show/Hide: a panel already showing closes.
|
||||
self.right = (self.right != Some(panel)).then_some(panel);
|
||||
self.set_right((self.right() != Some(panel)).then_some(panel));
|
||||
}
|
||||
Request::Zoom(z) => {
|
||||
if let Some(i) = view {
|
||||
@@ -149,19 +149,13 @@ impl PdfCraftApp {
|
||||
}
|
||||
|
||||
/// Show form script messages `messages` in order, each as a notice with its title and tone.
|
||||
/// The first is posted at once when no script notice is on screen; otherwise it waits, like the
|
||||
/// rest, for the one shown to end ([`Self::script_notice_ended`]). With no window context yet,
|
||||
/// [`Self::script_tick`] posts it on the first pass.
|
||||
/// The first is posted on the next pass ([`Self::script_tick`]) when no script notice is on
|
||||
/// screen; otherwise it waits, like the rest, for the one shown to end ([`Self::script_notice_ended`]).
|
||||
pub fn show_script_messages(&mut self, messages: Vec<Message>) {
|
||||
let room = MAX_WAITING_MESSAGES.saturating_sub(self.script_messages.len());
|
||||
let left_out = u64::try_from(messages.len().saturating_sub(room)).unwrap_or(u64::MAX);
|
||||
self.script_messages_dropped = self.script_messages_dropped.saturating_add(left_out);
|
||||
self.script_messages.extend(messages.into_iter().take(room));
|
||||
if self.script_shown.is_none()
|
||||
&& let Some(ctx) = self.ctx.clone()
|
||||
{
|
||||
self.next_script_message(&ctx);
|
||||
}
|
||||
}
|
||||
|
||||
/// A form button's `exportDataObject`: the attached file `name` (its key in the document's
|
||||
@@ -187,7 +181,7 @@ impl PdfCraftApp {
|
||||
if let Some(v) = self.views.iter_mut().find(|v| v.id == id) {
|
||||
v.session.highlight_fields = on;
|
||||
}
|
||||
self.view_defaults.highlight_fields = on;
|
||||
self.highlight_fields = on;
|
||||
self.session.set_field_highlight(on);
|
||||
}
|
||||
|
||||
@@ -275,7 +269,7 @@ impl PdfCraftApp {
|
||||
}
|
||||
if run.edited {
|
||||
if let Some(info) = self.session.get(id).map(|d| d.info.clone()) {
|
||||
self.views[i].document_changed(&info);
|
||||
self.views[i].document_changed(ctx, &info);
|
||||
}
|
||||
if let Some(before) = &before
|
||||
&& let Some(draft) = self.views[i].session.forms.focus.as_mut()
|
||||
@@ -302,14 +296,14 @@ impl PdfCraftApp {
|
||||
/// Run document `id`'s catalog JavaScript for `event` (Will Save before a save, Will Print
|
||||
/// before printing) and show what it said. What it changed is part of what is saved or
|
||||
/// printed. A failing script is reported and the save or print still goes ahead.
|
||||
pub(crate) fn run_document_actions(&mut self, id: DocId, event: pdfcraft_engine::js::DocumentScriptEvent) {
|
||||
pub(crate) fn run_document_actions(&mut self, ctx: &egui::Context, id: DocId, event: pdfcraft_engine::js::DocumentScriptEvent) {
|
||||
let before = self.session.get(id).map(|d| d.edit_generation());
|
||||
let out = self.session.run_document_actions(id, event);
|
||||
if self.session.get(id).map(|d| d.edit_generation()) != before
|
||||
&& let Some(i) = self.views.iter().position(|v| v.id == id)
|
||||
&& let Some(info) = self.session.get(id).map(|d| d.info.clone())
|
||||
{
|
||||
self.views[i].document_changed(&info);
|
||||
self.views[i].document_changed(ctx, &info);
|
||||
}
|
||||
if !out.is_empty() {
|
||||
self.handle_js(id, out);
|
||||
@@ -317,11 +311,11 @@ impl PdfCraftApp {
|
||||
}
|
||||
|
||||
/// Run a push button's JavaScript (its Mouse Up action).
|
||||
pub fn run_button_script(&mut self, id: DocId, field: &str, script: &str) {
|
||||
self.run_button_script_target(id, field, None, script);
|
||||
pub fn run_button_script(&mut self, ctx: &egui::Context, id: DocId, field: &str, script: &str) {
|
||||
self.run_button_script_target(ctx, id, field, None, script);
|
||||
}
|
||||
/// Run the action of the exact clicked button, preserving legacy name-only entry points.
|
||||
pub fn run_button_script_target(&mut self, id: DocId, field: &str, identity: Option<u64>, script: &str) {
|
||||
pub fn run_button_script_target(&mut self, ctx: &egui::Context, id: DocId, field: &str, identity: Option<u64>, script: &str) {
|
||||
// A script reads the fields: include what's still being typed in one (#166).
|
||||
if !self.commit_form_typing() {
|
||||
return;
|
||||
@@ -336,7 +330,7 @@ impl PdfCraftApp {
|
||||
if let Some(i) = self.views.iter().position(|v| v.id == id)
|
||||
&& let Some(info) = self.session.get(id).map(|d| d.info.clone())
|
||||
{
|
||||
self.views[i].document_changed(&info);
|
||||
self.views[i].document_changed(ctx, &info);
|
||||
}
|
||||
let out = JsOutput {
|
||||
alerts: o.alerts,
|
||||
@@ -397,7 +391,7 @@ impl PdfCraftApp {
|
||||
if let Some(i) = self.views.iter().position(|v| v.id == id)
|
||||
&& let Some(info) = self.session.get(id).map(|d| d.info.clone())
|
||||
{
|
||||
self.views[i].document_changed(&info);
|
||||
self.views[i].document_changed(ctx, &info);
|
||||
}
|
||||
let out = JsOutput {
|
||||
alerts: o.alerts,
|
||||
@@ -413,13 +407,13 @@ impl PdfCraftApp {
|
||||
}
|
||||
|
||||
/// Prepare a form ▸ detect fields from the page's blanks, lines and boxes.
|
||||
pub fn detect_fields(&mut self) {
|
||||
pub fn detect_fields(&mut self, ctx: &egui::Context) {
|
||||
let Some((i, id)) = self.active_ids() else { return };
|
||||
match self.session.auto_detect_fields(id, &[]) {
|
||||
Ok(names) if names.is_empty() => self.notify_tr("No form fields were detected"),
|
||||
Ok(names) => {
|
||||
if let Some(info) = self.session.get(id).map(|d| d.info.clone()) {
|
||||
self.views[i].document_changed(&info);
|
||||
self.views[i].document_changed(ctx, &info);
|
||||
}
|
||||
if names.len() == 1 {
|
||||
self.notify_tr("Detected 1 form field");
|
||||
@@ -432,7 +426,7 @@ impl PdfCraftApp {
|
||||
}
|
||||
|
||||
/// The console's Run: evaluate the input in the active document.
|
||||
pub fn run_console(&mut self) {
|
||||
pub fn run_console(&mut self, ctx: &egui::Context) {
|
||||
let Some((i, id)) = self.active_ids() else { return };
|
||||
let script = self.js_console.input.clone();
|
||||
if script.trim().is_empty() {
|
||||
@@ -442,7 +436,7 @@ impl PdfCraftApp {
|
||||
match self.session.run_javascript(id, &script, None) {
|
||||
Ok(o) => {
|
||||
if let Some(info) = self.session.get(id).map(|d| d.info.clone()) {
|
||||
self.views[i].document_changed(&info);
|
||||
self.views[i].document_changed(ctx, &info);
|
||||
}
|
||||
let (error, result) = (o.error.clone(), o.result.clone());
|
||||
let out = JsOutput { alerts: o.alerts, console: o.console, requests: o.requests, errors: Vec::new(), doc_errors: Vec::new() };
|
||||
|
||||
Reference in new issue
Block a user