pdf-chrome-w15: net change of 3 commits

- pdf-chrome-w15: written from its sheet
- pdf-chrome-w15: repair 1
- pdf-chrome-w15: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor
2026-11-18 16:15:25 -05:00
parent d01c739ae3
commit ecc1353ca6
9 changed files with 949 additions and 224 deletions
@@ -6,11 +6,19 @@
use pdfcraft_engine::text_style_bookmarks::{TextStyle, TextStyleUse};
use pdfcraft_engine::{DocId, Edit};
use crate::theme::{self, Tokens};
use crate::{PdfCraftApp, widgets};
use craft::ui::dialog::{Alert, DialogResult, HostedAlert, dialog_id};
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind};
use craft::ui::runtime::env::Label;
use crate::PdfCraftApp;
use crate::side_panels::{PanelId, set_panel_visible};
/// The levels offered: deeper outlines are rare, and each level needs a style of its own.
const LEVELS: usize = 4;
/// The dialog's key: its result is found by it.
const KEY: &str = "bookmarks-from-text-styles";
/// The id of the "no style" entry of a level's select.
const NONE: &str = "none";
/// What the dialog shows and what has been chosen in it.
#[derive(Debug, Default)]
@@ -31,11 +39,16 @@ impl TextStyleDraft {
}
}
/// The key of level `n`'s select.
fn level_key(n: usize) -> String {
format!("level{n}")
}
impl PdfCraftApp {
/// Open New bookmarks from text styles for document `id`: its styles are read now, and the
/// largest is offered for level 1 when there is more than one (headings are larger than the
/// text around them; a single style has no headings to tell apart).
pub fn open_text_style_bookmarks(&mut self, id: DocId) {
pub fn open_text_style_bookmarks(&mut self, ctx: &egui::Context, id: DocId) {
// The style list includes samples copied from the document's text. Enforce the PDF's
// copy permission before extracting any of that text, not only when creating bookmarks.
let can_copy = self.session.get(id).is_some_and(|d| d.permissions().is_none_or(|p| p.copy()));
@@ -46,7 +59,51 @@ impl PdfCraftApp {
let styles = self.session.get(id).map(|d| d.text_styles()).unwrap_or_default();
let first = (styles.len() > 1).then_some(0);
self.text_style_draft = TextStyleDraft { doc: Some(id), styles, levels: [first, None, None, None] };
self.dialog = Some(crate::Dialog::BookmarksFromTextStyles);
let draft = &self.text_style_draft;
if draft.styles.is_empty() {
// A form dialog always has two buttons; a notice with only Close is an alert.
let alert = Alert::new(tl!("New bookmarks from text styles"), tl!("This document has no text to make bookmarks from.")).ok_label(tl!("Close"));
self.dialogs.open(HostedAlert::new(alert));
return;
}
let mut options: Vec<(String, Label)> = vec![(NONE.to_string(), tl!("None").into())];
options.extend(draft.styles.iter().enumerate().map(|(i, u)| (i.to_string(), Label::from(style_label(u)))));
let style_ids: Vec<String> = (0..draft.styles.len()).map(|i| i.to_string()).collect();
let params: Vec<Param> = (0..LEVELS)
.map(|level| {
let name = crate::i18n::fmt(tl!("Level {n}"), &[("n", &(level + 1).to_string())]);
let default = Some(draft.levels.get(level).copied().flatten().map_or_else(|| NONE.to_string(), |i| i.to_string()));
let param = Param::new(level_key(level), name, ParamKind::choice(options.clone(), default));
// A level takes a style only once the one above it has one.
if level == 0 { param } else { param.enabled_when_in(level_key(level - 1), style_ids.clone()) }
})
.collect();
let dialog = HostedParamDialog::new(ctx, KEY, DialogFields::new(), move |_| {
ParamDialog::new(KEY, tl!("New bookmarks from text styles"), params.clone()).ok_label(tl!("Create"))
});
self.dialogs.open(dialog);
}
/// One pass over the dialog: Create makes the bookmarks and shows them in the Bookmarks panel.
pub(crate) fn bookmarks_from_styles_pass(&mut self, _ctx: &egui::Context) {
let Some(result) = self.dialogs.take_by_id::<HostedParamDialog>(dialog_id(KEY)) else { return };
let mut draft = std::mem::take(&mut self.text_style_draft);
let DialogResult::Ok(result) = result else { return };
for (n, slot) in draft.levels.iter_mut().enumerate() {
*slot = result.fields.text(&level_key(n)).and_then(|id| id.parse::<usize>().ok());
}
// A level left without a style ends the list: `chosen` stops at the first gap.
let levels = draft.chosen();
if levels.is_empty() {
return;
}
// The document the styles came from, even if another tab is active by now.
if let Some(i) = draft.doc.and_then(|id| self.views.iter().position(|v| v.id == id)) {
self.active = Some(i);
if self.apply_edit(Edit::BookmarksFromTextStyles { levels }) {
set_panel_visible(self, PanelId::Bookmarks, true);
}
}
}
}
@@ -66,69 +123,3 @@ fn style_label(u: &TextStyleUse) -> String {
let more = if sample.chars().count() < u.sample.chars().count() { "…" } else { "" };
format!("{s} · “{sample}{more}” ({lines})")
}
/// The dialog's contents and its buttons. Returns whether it closes; Create makes the
/// bookmarks and shows them in the Bookmarks panel.
pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> bool {
ui.label(egui::RichText::new(tl!("New bookmarks from text styles")).font(theme::semibold(18.0)));
ui.add_space(6.0);
let d = &mut app.text_style_draft;
let id = d.doc;
if d.styles.is_empty() {
ui.label(tl!("This document has no text to make bookmarks from."));
ui.add_space(12.0);
return widgets::pill_button(ui, tl!("Close"), true).clicked();
}
ui.label(
egui::RichText::new(tl!("Every line set in the style chosen for a level becomes a bookmark of that level, under a new first bookmark."))
.color(t.text_muted),
);
ui.add_space(8.0);
let none = tl!("None");
egui::Grid::new("text_style_levels").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| {
for level in 0..LEVELS {
// A level takes a style only once the one above it has one.
let open = level == 0 || d.levels.get(level - 1).copied().flatten().is_some();
let label = ui.label(crate::i18n::fmt(tl!("Level {n}"), &[("n", &(level + 1).to_string())]));
ui.add_enabled_ui(open, |ui| {
let Some(slot) = d.levels.get_mut(level) else { return };
let shown = slot.and_then(|i| d.styles.get(i)).map_or_else(|| none.to_string(), style_label);
craft_ui::ComboBox::from_id_salt(("text_style_level", level))
.selected_text(shown)
.width(460.0)
.show_ui(ui, |ui| {
ui.selectable_value(slot, None, none);
for (i, u) in d.styles.iter().enumerate() {
ui.selectable_value(slot, Some(i), style_label(u));
}
})
.response
.labelled_by(label.id);
});
ui.end_row();
}
});
// A level left without a style ends the list: the ones below it don't count.
if let Some(gap) = d.levels.iter().position(Option::is_none) {
d.levels.iter_mut().skip(gap).for_each(|l| *l = None);
}
let levels = d.chosen();
ui.add_space(16.0);
let mut close = false;
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.add_enabled_ui(!levels.is_empty(), |ui| widgets::pill_button(ui, tl!("Create"), true)).inner.clicked() {
close = true;
// The document the styles came from, even if another tab is active by now.
if let Some(i) = id.and_then(|id| app.views.iter().position(|v| v.id == id)) {
app.active = Some(i);
if app.apply_edit(Edit::BookmarksFromTextStyles { levels }) {
app.right = Some(crate::RightPanel::Bookmarks);
}
}
}
if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {
close = true;
}
});
close
}
+64
View File
@@ -0,0 +1,64 @@
//! Page Properties ▸ Tab Order for the pages the dialog opened on: Use Row Order, Use Column Order, Use Document
//! Structure and Unspecified, as a hosted dialog with one radio row.
use craft::ui::dialog::{DialogResult, dialog_id};
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind};
use pdfcraft_engine::{Edit, TabOrder};
use crate::{PagePropsDraft, PdfCraftApp};
/// The dialog's key: its remembered values and its result are found by it.
const KEY: &str = "page-props";
/// The radio row's key.
const ORDER: &str = "tab_order";
/// The id the radio row stores for `order`.
fn order_id(order: TabOrder) -> &'static str {
match order {
TabOrder::Row => "row",
TabOrder::Column => "column",
TabOrder::Structure => "structure",
TabOrder::Annotations => "annotations",
}
}
/// The order a stored radio id names.
fn order_of(id: &str) -> Option<TabOrder> {
[TabOrder::Row, TabOrder::Column, TabOrder::Structure, TabOrder::Annotations].into_iter().find(|o| order_id(*o) == id)
}
impl PdfCraftApp {
/// Opens Page Properties for the pages and document `draft` names; a newer open replaces the old.
pub(crate) fn open_page_props(&mut self, ctx: &egui::Context, draft: PagePropsDraft) {
let options = vec![
(order_id(TabOrder::Row).to_string(), tl!("Use Row Order").into()),
(order_id(TabOrder::Column).to_string(), tl!("Use Column Order").into()),
(order_id(TabOrder::Structure).to_string(), tl!("Use Document Structure").into()),
(order_id(TabOrder::Annotations).to_string(), tl!("Unspecified").into()),
];
let default = draft.tab_order.map(|o| order_id(o).to_string());
let params = vec![Param::new(ORDER, tl!("Tab Order"), ParamKind::radio(options, default))];
let dialog = HostedParamDialog::new(ctx, KEY, DialogFields::new(), move |_| ParamDialog::new(KEY, tl!("Page Properties"), params.clone()));
self.dialogs.open(dialog);
self.page_props_draft = Some(draft);
}
/// One pass over the dialog: applies the chosen order when it differs from what every page has and the document
/// is as the dialog opened it.
pub(crate) fn page_props_pass(&mut self, _ctx: &egui::Context) {
let Some(result) = self.dialogs.take_by_id::<HostedParamDialog>(dialog_id(KEY)) else { return };
let Some(draft) = self.page_props_draft.take() else { return };
let DialogResult::Ok(result) = result else { return };
let Some(order) = result.fields.text(ORDER).and_then(order_of) else { return };
// An order every page already has adds no undo step.
if draft.before == Some(order) {
return;
}
let current = self.session.get(draft.doc).is_some_and(|d| d.edit_generation() == draft.generation);
let Some(index) = self.views.iter().position(|v| v.id == draft.doc) else { return };
if current {
self.active = Some(index);
self.apply_edit(Edit::SetTabOrder { pages: draft.pages, order });
}
}
}
+15 -5
View File
@@ -6,15 +6,17 @@ use pdfcraft_engine::catalog::{self, Availability, TOOL_GROUPS, ToolGroup, ToolI
use pdfcraft_render::{DocInfo, FieldKind, OutlineItem};
use crate::theme::{self, Tokens};
use crate::{LeftPanel, PdfCraftApp, RightPanel, icons, widgets};
use crate::{LeftPanel, PdfCraftApp, RightPanel, icons};
pub(super) mod all_tools_ui;
mod attachments;
mod bookmarks;
pub(super) mod comments_panel;
mod edit;
mod fields;
pub(super) mod format_text_ui;
mod layers;
pub(super) mod organize_panel;
pub(super) mod page_selection_ui;
mod pages;
mod right;
pub(super) mod search_ui;
@@ -22,10 +24,8 @@ pub mod side_panels;
mod tools;
pub use bookmarks::BmAction;
pub(crate) use bookmarks::ellipsized_prefix;
pub use right::right_panel;
pub use right::panel_body;
pub use tools::left_panel;
pub(crate) use tools::panel_header;
// ───────────────────────────────────────────────────────────────────────────── right panels
@@ -38,6 +38,16 @@ pub(crate) enum Nav {
Flash(usize, [f32; 4]),
}
/// A panel's empty state: a centred notice with the panel's icon and `text`. Every empty-panel message
/// goes through here.
pub(crate) fn empty_state(ui: &mut egui::Ui, icon: &'static str, text: &str) {
use craft::ui::contract::Show as _;
craft::ui::notices::Notice::new(craft::theme::variant::Tone::Neutral, text.to_string())
.layout(craft::ui::notices::NoticeLayout::Centred)
.icon(craft::ui::notices::NoticeIcon::Custom(craft::ui::primitives::IconSpec::svg(craft::behavior::IconId::new(icon))))
.show(ui);
}
pub fn human_size(n: usize) -> String {
match n {
// A size that rounds to "1024.0 KB" reads as the next unit.
+164
View File
@@ -0,0 +1,164 @@
//! The Attachments panel: the document's embedded files and file-attachment annotations, with Save,
//! Open and Delete on each row and the row's menu.
// PLAN: assumed `super::right::PanelResult` and a `BodyCx` passed to `show` (pdf-chrome-w13 calls `show(app, ui)` today).
use craft::behavior::{DisplayOrder, IconId, ItemSource};
use craft::ui::buttons::Button;
use craft::ui::contract::{BodyCx, CollectionEvent, Entry, SelectMode, Show as _, ShowCollection as _};
use craft::ui::list::{List, ListRow, RowEvent, TrailingFace, TrailingPart};
use craft::ui::menu::Menu;
use craft::ui::primitives::IconSpec;
use super::right::PanelResult;
use super::{empty_state, human_size};
use crate::PdfCraftApp;
const SAVE: TrailingPart = TrailingPart::new(0);
const OPEN: TrailingPart = TrailingPart::new(1);
const DELETE: TrailingPart = TrailingPart::new(2);
/// What the row menu's entries do.
const MENU_OPEN: u8 = 0;
const MENU_SAVE: u8 = 1;
const MENU_DESCRIBE: u8 = 2;
const MENU_DELETE: u8 = 3;
/// The attachments, keyed by position.
struct Attached(usize);
impl DisplayOrder<usize> for Attached {
fn len(&self) -> usize {
self.0
}
fn key(&self, at: usize) -> usize {
at
}
fn index_of(&self, key: &usize) -> Option<usize> {
(*key < self.0).then_some(*key)
}
}
impl ItemSource<usize> for Attached {}
/// Whether an attachment is a PDF by its name; whether its bytes are is decided where it opens.
fn is_pdf(a: &pdfcraft_render::Attachment) -> bool {
a.name.to_lowercase().ends_with(".pdf")
}
/// Show the Attachments panel for the active document.
pub(crate) fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui, cx: &mut BodyCx<'_>) -> PanelResult {
let mut result = PanelResult::default();
let Some((_, id)) = app.active_ids() else { return result };
let Some(doc) = app.session.get(id) else { return result };
let info = &doc.info;
let attachable = doc.allows_modification() && doc.read_only_reason.is_none();
if attachable && Button::new(tl!("Attach a file…").to_string()).show(ui).clicked() {
result.command = Some("edit.attach");
}
if info.attachments.is_empty() {
empty_state(ui, "paperclip", tl!("This document has no attachments."));
return result;
}
// Only an attachment of the document itself can be deleted here.
let deletable = |a: &pdfcraft_render::Attachment| match &a.source {
pdfcraft_render::AttachmentSource::Document { key } if attachable => Some(key.clone()),
_ => None,
};
let detail = |a: &pdfcraft_render::Attachment| {
let mut parts = vec![a.size.map(human_size).unwrap_or_default()];
if let pdfcraft_render::AttachmentSource::Annotation { page, .. } = a.source {
parts.push(crate::i18n::fmt(tl!("on page {label}"), &[("label", info.pages.get(page).map(|p| p.label.as_str()).unwrap_or("?"))]));
}
if let Some(d) = &a.description {
parts.push(d.clone());
}
parts.join(" · ")
};
let out = List::<usize>::new(tl!("Attachments").to_string()).select(SelectMode::Single).natural_height(true).show_items(
ui,
&Attached(info.attachments.len()),
&mut |key, _| {
let Some(a) = info.attachments.get(*key) else { return ListRow::new("") };
let mut row = ListRow::new(a.name.clone()).icon(IconSpec::svg(IconId::new("paperclip"))).detail(detail(a)).trailing_part(
SAVE,
TrailingFace::Icon(IconSpec::svg(IconId::new("file-down"))),
tl!("Save attachment…").to_string(),
);
if is_pdf(a) {
row = row.trailing_part(OPEN, TrailingFace::Icon(IconSpec::svg(IconId::new("file-input"))), tl!("Open in a new tab").to_string());
}
if deletable(a).is_some() {
row = row.trailing_part(DELETE, TrailingFace::Icon(IconSpec::svg(IconId::new("trash-2"))), tl!("Delete attachment").to_string());
}
row
},
);
// A double click opens a PDF in a new tab, as Acrobat opens an attachment; any other file is saved,
// since PdfCraft opens only PDFs.
// The row the open context menu belongs to lives in the panel body's memory, not in egui's temp data.
let menu_slot = cx.id.with("attachment-menu-row");
for event in &out.events {
match event {
CollectionEvent::Activate(ai) => {
if let Some(a) = info.attachments.get(*ai) {
result.attachment = Some((*ai, is_pdf(a)));
}
}
CollectionEvent::Item(ai, RowEvent::Trailing { part, .. }) => {
let Some(a) = info.attachments.get(*ai) else { continue };
if *part == SAVE {
result.attachment = Some((*ai, false));
} else if *part == OPEN {
result.attachment = Some((*ai, true));
} else if *part == DELETE
&& let Some(key) = deletable(a)
{
result.edit = Some(pdfcraft_engine::Edit::DeleteAttachment { key });
}
}
CollectionEvent::ContextMenu(request) => {
*cx.memory.shown::<Option<usize>>(menu_slot) = Some(request.key);
}
_ => {}
}
}
let row: Option<usize> = *cx.memory.shown::<Option<usize>>(menu_slot);
let mut describe = None;
if let Some(ai) = row
&& let Some(a) = info.attachments.get(ai)
{
let key = deletable(a);
let mut entries = Vec::new();
if is_pdf(a) {
entries.push(Entry::new(MENU_OPEN, tl!("Open in a new tab").to_string()));
}
entries.push(Entry::new(MENU_SAVE, tl!("Save attachment…").to_string()));
if key.is_some() {
entries.push(Entry::new(MENU_DESCRIBE, tl!("Edit description").to_string()));
entries.push(Entry::new(MENU_DELETE, tl!("Delete attachment").to_string()));
}
match Menu::context(tl!("Attachment").to_string(), &out.response).pick(ui, &entries).picked {
Some(MENU_OPEN) => result.attachment = Some((ai, true)),
Some(MENU_SAVE) => result.attachment = Some((ai, false)),
Some(MENU_DESCRIBE) => {
if let Some(key) = key {
describe = Some((doc.edit_generation(), key, a.name.clone(), a.description.clone().unwrap_or_default(), a.has_description));
}
}
Some(MENU_DELETE) => {
if let Some(key) = key {
result.edit = Some(pdfcraft_engine::Edit::DeleteAttachment { key });
}
}
_ => {}
}
}
// Opened once the panel's borrows of the document end: the dialog is the app's.
if let Some((generation, key, name, description, has_description)) = describe {
let ctx = ui.ctx().clone();
app.open_attachment_description(&ctx, id, generation, key, name, description, has_description);
}
result
}
+347
View File
@@ -0,0 +1,347 @@
//! The Fields panel: the document's form fields by page, each page's in tab order. While preparing
//! a form a field can move earlier or later in its page's tab order (Acrobat: Order Tabs Manually).
// PLAN: assumed `super::right::PanelResult` (pdf-chrome-w13).
use std::collections::HashMap;
use craft::behavior::{DisplayOrder, IconId, ItemSource, Selection, SelectionChange};
use craft::ui::buttons::Button;
use craft::ui::contract::{Bind, CollectionEvent, LeadSource, Props as _, SelectMode, Show as _, ShowCollection as _};
use craft::ui::display::Text;
use craft::ui::list::{List, ListRow, RowEvent, TrailingFace, TrailingPart};
use craft::ui::primitives::IconSpec;
use pdfcraft_render::{DocInfo, Field, FieldKind};
use super::right::PanelResult;
use super::{Nav, empty_state};
use crate::PdfCraftApp;
/// The part that moves a field earlier in its page's tab order.
const EARLIER: TrailingPart = TrailingPart::new(0);
/// The part that moves a field later in its page's tab order.
const LATER: TrailingPart = TrailingPart::new(1);
/// A row of the Fields list. A field's identity is its name and page, not its position: the form can
/// change under a selection. `dup` tells apart fields that share both.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum FieldRow {
/// A page's heading; `None` is "Unplaced".
Page(Option<usize>),
/// A field on a page.
Field { name: String, page: Option<usize>, dup: usize },
}
/// One row with what it stands for.
struct Row<'a> {
key: FieldRow,
/// The field; `None` for a heading.
field: Option<&'a Field>,
/// The form field and widget a selection of this row names; `None` when the form has no widget of it
/// on its page.
select: Option<(String, usize)>,
}
/// The rows in display order, with each key's position.
struct Rows<'a> {
rows: Vec<Row<'a>>,
at: HashMap<FieldRow, usize>,
}
impl<'a> Rows<'a> {
fn new(fields: &'a [Field], form: &[pdfcraft_engine::FormField]) -> Self {
let mut rows = Vec::new();
for (page, page_rows) in field_rows(fields, form) {
rows.push(Row { key: FieldRow::Page(page), field: None, select: None });
let mut seen: HashMap<&str, usize> = HashMap::new();
for (field, select) in page_rows {
let dup = seen.entry(field.name.as_str()).or_insert(0);
let key = FieldRow::Field { name: field.name.clone(), page, dup: *dup };
*dup += 1;
rows.push(Row { key, field: Some(field), select });
}
}
let at = rows.iter().enumerate().map(|(i, r)| (r.key.clone(), i)).collect();
Rows { rows, at }
}
fn get(&self, key: &FieldRow) -> Option<&Row<'a>> {
self.at.get(key).and_then(|&i| self.rows.get(i))
}
}
impl DisplayOrder<FieldRow> for Rows<'_> {
fn len(&self) -> usize {
self.rows.len()
}
fn key(&self, at: usize) -> FieldRow {
self.rows.get(at).map(|r| r.key.clone()).unwrap_or(FieldRow::Page(None))
}
fn index_of(&self, key: &FieldRow) -> Option<usize> {
self.at.get(key).copied()
}
fn text(&self, at: usize) -> Option<std::borrow::Cow<'_, str>> {
self.rows.get(at).and_then(|r| r.field).map(|f| std::borrow::Cow::Borrowed(f.name.as_str()))
}
}
impl ItemSource<FieldRow> for Rows<'_> {}
/// A heading's text: "Page {label}", or "Unplaced" for no page or one the document doesn't have (#1307).
fn heading(info: &DocInfo, page: Option<usize>) -> String {
page.and_then(|p| info.pages.get(p))
.map(|page| crate::i18n::fmt(tl!("Page {label}"), &[("label", &page.label)]))
.unwrap_or_else(|| tl!("Unplaced").to_string())
}
/// The icon a field kind shows.
fn kind_icon(kind: &FieldKind) -> &'static str {
match kind {
FieldKind::Text => "text-cursor-input",
FieldKind::CheckBox => "check-circle-2",
FieldKind::Radio => "circle",
FieldKind::PushButton | FieldKind::Unknown => "square",
FieldKind::Combo => "chevron-down",
FieldKind::List => "list",
FieldKind::Signature => "signature",
}
}
/// The rows a selection change leaves selected: `current` with `change` applied.
fn changed(current: Vec<FieldRow>, change: &SelectionChange<FieldRow>) -> Vec<FieldRow> {
match change {
SelectionChange::Set(keys) => keys.clone(),
SelectionChange::Toggle(key) => {
let mut keys = current;
match keys.iter().position(|k| k == key) {
Some(i) => {
keys.remove(i);
}
None => keys.push(key.clone()),
}
keys
}
SelectionChange::Clear => Vec::new(),
_ => current,
}
}
/// Show the Fields panel for the active document.
pub(crate) fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) -> PanelResult {
let mut result = PanelResult::default();
let preparing = app.is_preparing();
let Some((index, id)) = app.active_ids() else { return result };
let Some(doc) = app.session.get(id) else { return result };
let Some(view) = app.views.get_mut(index) else { return result };
let info = &doc.info;
if info.fields.is_empty() {
empty_state(ui, "text-cursor-input", tl!("This document has no form fields."));
return result;
}
let selection = &mut view.prepare;
if preparing {
Text::new(tl!("Tab order: move a field with its arrows.").to_string()).show(ui);
Text::new(tl!("Shift- or Ctrl/Command-click to select several fields.").to_string()).show(ui);
let names = selection.names();
Text::new(crate::i18n::fmt(tl!("{n} selected"), &[("n", &names.len().to_string())])).show(ui);
if Button::new(tl!("Properties…").to_string()).enabled(!names.is_empty()).show(ui).clicked() {
result.field_properties = selection.selected.clone();
}
}
let rows = Rows::new(&info.fields, doc.form.as_slice());
let is_selected = |row: &Row<'_>| {
row.select.as_ref().is_some_and(|key| selection.selected.as_ref() == Some(key) || selection.also.contains(key))
};
let shown = Selection::new(
rows.rows.iter().filter(|r| is_selected(r)).map(|r| r.key.clone()).collect(),
rows.rows.iter().find(|r| r.select.is_some() && r.select.as_ref() == selection.selected.as_ref()).map(|r| r.key.clone()),
None,
);
let mode = if preparing { SelectMode::Multi } else { SelectMode::None };
let out = List::<FieldRow>::new(tl!("Fields").to_string()).select(mode).selection(Bind::given(shown)).natural_height(true).show_items(
ui,
&rows,
&mut |key, _| {
let Some(row) = rows.get(key) else { return ListRow::new("") };
let Some(field) = row.field else {
let page = if let FieldRow::Page(p) = &row.key { *p } else { None };
return ListRow::new(heading(info, page)).section_heading();
};
let mut list_row =
ListRow::new(field.name.clone()).icon(IconSpec::svg(IconId::new(kind_icon(&field.kind)))).tooltip(field_tip(field));
if let Some(value) = &field.value {
list_row = list_row.optional(value.clone());
}
if preparing && field.page.is_some() {
list_row = list_row
.trailing_part(EARLIER, TrailingFace::Icon(IconSpec::svg(IconId::new("chevron-up"))), tl!("Earlier in tab order").to_string())
.trailing_part(LATER, TrailingFace::Icon(IconSpec::svg(IconId::new("chevron-down"))), tl!("Later in tab order").to_string());
}
list_row
},
);
let mut flashed = false;
let mut flash = |key: &FieldRow, result: &mut PanelResult| {
if let Some(Row { field: Some(f), .. }) = rows.get(key)
&& let (Some(p), Some(r)) = (f.page, f.rect)
&& !flashed
{
result.nav = Some(Nav::Flash(p, r));
flashed = true;
}
};
for event in &out.events {
match event {
CollectionEvent::Selection(change) => {
if preparing {
let current = rows.rows.iter().filter(|r| is_selected(r)).map(|r| r.key.clone()).collect();
let keys: Vec<(String, usize)> =
changed(current, change).iter().filter_map(|k| rows.get(k).and_then(|r| r.select.clone())).collect();
if let Some((last, rest)) = keys.split_last() {
selection.selected = Some(last.clone());
selection.also = rest.to_vec();
} else {
selection.selected = None;
selection.also.clear();
}
}
if let SelectionChange::Set(keys) = change
&& let Some(key) = keys.last()
{
flash(key, &mut result);
}
}
CollectionEvent::LeadMoved { key, by: LeadSource::Pointer } => flash(key, &mut result),
CollectionEvent::Activate(key) if preparing => {
if let Some(select) = rows.get(key).and_then(|r| r.select.clone()) {
if !is_selected(rows.get(key).unwrap_or(&rows.rows[0])) {
selection.selected = Some(select.clone());
selection.also.clear();
}
result.field_properties = Some(select);
}
}
CollectionEvent::Item(key, RowEvent::Trailing { part, .. }) => {
if let Some(Row { field: Some(f), .. }) = rows.get(key) {
let earlier = *part == EARLIER;
if earlier || *part == LATER {
result.edit = Some(pdfcraft_engine::Edit::MoveInTabOrder { name: f.name.clone(), earlier });
}
}
}
_ => {}
}
}
result
}
/// A Fields panel row's tooltip: the field's kind, its own tooltip and whether it has scripts.
fn field_tip(f: &Field) -> String {
let kind = format!("{:?}", f.kind);
let mut tip = crate::i18n::fmt(tl!("{kind} field"), &[("kind", tl!(&kind))]);
if let Some(tt) = &f.tooltip {
tip.push_str(&format!(" — {tt}"));
}
if f.has_actions {
tip.push_str(&format!("\n{}", tl!("Has JavaScript actions (run in M6)")));
}
tip
}
/// One page's rows of the Fields panel: each field, with the form field and widget a click on
/// it selects (`None` when the form has no widget of it on that page).
type FieldRows<'a> = Vec<(&'a Field, Option<(String, usize)>)>;
/// The Fields panel's rows: by page ("Unplaced" first), each page's in tab order. A row is paired
/// with the first form field of its name, as the engine pairs them: one map, built once a frame.
/// Searching the form for each row, and again inside the sort, was O(fields²) every frame.
fn field_rows<'a>(fields: &'a [Field], form: &[pdfcraft_engine::FormField]) -> Vec<(Option<usize>, FieldRows<'a>)> {
let mut by_name: HashMap<&str, &pdfcraft_engine::FormField> = HashMap::with_capacity(form.len());
for field in form {
by_name.entry(field.name.as_str()).or_insert(field);
}
let rank = |name: &str| by_name.get(name).and_then(|f| f.widgets.iter().map(|w| w.tab).min()).unwrap_or(usize::MAX);
let mut ordered: Vec<&Field> = fields.iter().collect();
ordered.sort_by_cached_key(|f| (f.page, rank(&f.name)));
let mut rows: Vec<(Option<usize>, FieldRows<'a>)> = Vec::new();
for f in ordered {
let key =
by_name.get(f.name.as_str()).and_then(|field| field.widgets.iter().position(|w| w.page == f.page).map(|wi| (field.name.clone(), wi)));
match rows.last_mut() {
Some((page, page_rows)) if *page == f.page => page_rows.push((f, key)),
_ => rows.push((f.page, vec![(f, key)])),
}
}
rows
}
#[cfg(test)]
mod field_rows_tests {
use super::field_rows;
use std::sync::Arc;
/// A PDF of `objects` (numbered from 1; object 1 the catalog) with a valid xref table.
fn pdf(objects: &[String]) -> Vec<u8> {
let mut out = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, o) in objects.iter().enumerate() {
offsets.push(out.len());
out.extend(format!("{} 0 obj\n{o}\nendobj\n", i + 1).bytes());
}
let xref = out.len();
out.extend(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).bytes());
for o in offsets {
out.extend(format!("{o:010} 00000 n \n").bytes());
}
out.extend(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).bytes());
out
}
/// The fields the engine reads from `bytes`: the inspector's list and the form.
fn open(bytes: Vec<u8>) -> (Vec<pdfcraft_render::Field>, Arc<Vec<pdfcraft_engine::FormField>>) {
let mut session = pdfcraft_engine::Session::new();
let id = session.open("form.pdf", None, Arc::new(bytes), None).expect("opens");
let doc = session.get(id).expect("open");
(doc.info.fields.clone(), doc.form.clone())
}
/// Rows go by page, the unplaced first, each page's in tab order (here its annotation order,
/// not the `/Fields` order), and a row selects the first form field of its name.
#[test]
fn rows_follow_pages_and_tab_order() {
let widget = |name: &str, page: Option<usize>| match page {
Some(p) => format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /Rect [10 10 90 30] /P {} 0 R >>", 3 + p),
None => format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /Rect [10 10 90 30] >>"),
};
let bytes = pdf(&[
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 7 0 R 8 0 R 9 0 R 10 0 R 6 0 R] >> >>".into(),
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>".into(),
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [6 0 R 5 0 R] >>".into(),
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [7 0 R 8 0 R 9 0 R] >>".into(),
widget("a1", Some(0)),
widget("a2", Some(0)),
widget("b", Some(1)),
widget("twin", Some(1)),
widget("twin", Some(1)),
widget("loose", None),
]);
let (fields, form) = open(bytes);
// A page's rows as (field name, the form field and widget a click selects).
type Named<'a> = Vec<(&'a str, Option<(String, usize)>)>;
let rows: Vec<(Option<usize>, Named)> = field_rows(&fields, &form)
.into_iter()
.map(|(page, rows)| (page, rows.into_iter().map(|(f, key)| (f.name.as_str(), key)).collect()))
.collect();
let key = |name: &str| Some((name.to_string(), 0));
assert_eq!(
rows,
[
(None, vec![("loose", key("loose"))]),
(Some(0), vec![("a2", key("a2")), ("a1", key("a1"))]),
(Some(1), vec![("b", key("b")), ("twin", key("twin")), ("twin", key("twin"))]),
]
);
}
}
+140
View File
@@ -0,0 +1,140 @@
//! The Layers panel: the default configuration's `/Order` tree with an eye column, and the panel
//! menu's rows.
// PLAN: assumed `super::right::PanelResult` (pdf-chrome-w13).
use craft::behavior::{ColumnKey, ColumnWidth, DisplayOrder, IconId, ItemSource, SelectionChange};
use craft::keymap::CommandRef;
use craft::ui::contract::{CollectionEvent, ColumnSpec, SelectMode, ShowCollection as _};
use craft::ui::list::{List, ListRow, RowInk, ToggleCell};
use craft::ui::menu::PanelRow;
use craft::ui::runtime::env::Label;
use pdfcraft_render::{DocInfo, LayerItem};
use super::empty_state;
use super::right::PanelResult;
use crate::PdfCraftApp;
/// The eye column.
const EYE: ColumnKey = ColumnKey::new("eye");
/// The label column.
const NAME: ColumnKey = ColumnKey::new("name");
/// The deepest level of `/Order` shown indented; deeper rows stay at it.
const MAX_DEPTH: usize = 8;
/// The `/Order` rows, keyed by their position in `info.layer_order`.
struct Order<'a>(&'a DocInfo);
impl Order<'_> {
/// The layer (an index into `info.layers`) row `at` shows; `None` for a label.
fn layer(&self, at: usize) -> Option<usize> {
match self.0.layer_order.get(at).map(|r| &r.item) {
Some(LayerItem::Layer(li)) => Some(*li),
_ => None,
}
}
fn visible(&self, at: usize) -> bool {
self.layer(at).and_then(|li| self.0.layers.get(li)).is_some_and(|l| l.visible)
}
}
impl DisplayOrder<usize> for Order<'_> {
fn len(&self) -> usize {
self.0.layer_order.len()
}
fn key(&self, at: usize) -> usize {
at
}
fn index_of(&self, key: &usize) -> Option<usize> {
(*key < self.0.layer_order.len()).then_some(*key)
}
fn text(&self, at: usize) -> Option<std::borrow::Cow<'_, str>> {
match self.0.layer_order.get(at).map(|r| &r.item)? {
LayerItem::Layer(li) => self.0.layers.get(*li).map(|l| std::borrow::Cow::Borrowed(l.name.as_str())),
LayerItem::Label(label) => Some(std::borrow::Cow::Borrowed(label.as_str())),
}
}
}
impl ItemSource<usize> for Order<'_> {
fn toggled(&self, at: usize, column: &ColumnKey) -> bool {
*column == EYE && self.visible(at)
}
}
/// Show the Layers panel for the active document. A layer's eye, or a click on its row, turns it on
/// or off; a label of `/Order` heads the rows under it and does nothing.
pub(crate) fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) -> PanelResult {
let mut result = PanelResult::default();
let Some((_, id)) = app.active_ids() else { return result };
let Some(doc) = app.session.get(id) else { return result };
let info = &doc.info;
if info.layers.is_empty() {
empty_state(ui, "layers", tl!("This document has no layers."));
return result;
}
if info.layer_order.is_empty() {
// ISO 32000-2 Table 99: only the groups /Order lists are presented.
empty_state(ui, "layers", tl!("This document lists no layers to show."));
return result;
}
let order = Order(info);
let columns = vec![
ColumnSpec::toggle(EYE, Label::Empty, craft::ui::contract::ToggleColumn::sweepable()).icon(IconId::new("eye")),
ColumnSpec::new(NAME, Label::Empty, ColumnWidth::fill(1.0)),
];
let out = List::<usize>::new(tl!("Layers").to_string())
.header(false)
.tree(true)
.natural_height(true)
.select(SelectMode::Single)
.columns(columns)
.show_items(ui, &order, &mut |key, icx| {
let Some(row) = info.layer_order.get(*key) else { return ListRow::new("") };
let depth = row.depth.min(MAX_DEPTH);
match &row.item {
LayerItem::Label(label) => ListRow::new(label.clone()).section_heading().depth(depth).cells(icx.cells()).state(icx.row.clone()),
LayerItem::Layer(li) => {
let Some(layer) = info.layers.get(*li) else { return ListRow::new("") };
let list_row = ListRow::new(layer.name.clone())
.layer(true)
.depth(depth)
.cells(icx.cells())
.state(icx.row.clone())
.toggle(ToggleCell::eye(EYE, layer.visible).row_press());
if layer.visible { list_row } else { list_row.ink(RowInk::Dimmed) }
}
}
});
// The eye reports a toggle. A click on the row's own area is a selection: it flips what the eye shows.
let mut toggled = false;
for event in &out.events {
if let CollectionEvent::Toggle(edit) = event
&& let Some(cell) = edit.landed()
&& let Some(layer) = order.layer(cell.key)
{
result.layer = Some((layer, cell.on));
toggled = true;
}
}
if !toggled {
for event in &out.events {
if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event
&& let Some(key) = keys.last()
&& let Some(layer) = order.layer(*key)
{
result.layer = Some((layer, !order.visible(*key)));
}
}
}
result
}
/// The rows of the Layers panel's menu: Reset to Initial Visibility while the document has layers.
pub(crate) fn menu_rows(app: &PdfCraftApp) -> Vec<PanelRow> {
let has_layers = app.active_ids().and_then(|(_, id)| app.session.get(id)).is_some_and(|d| !d.info.layers.is_empty());
if has_layers { vec![PanelRow::Command(CommandRef::new("layers.reset_visibility"))] } else { Vec::new() }
}
+117 -63
View File
@@ -1,50 +1,89 @@
//! Edit ▸ Advanced Search (⇧⌘F): the search in a side panel that lists every match with its
//! context, page by page; click a result to go to it. It shares the find bar's search.
// PLAN: assumed `super::right::PanelResult` (pdf-chrome-w13).
use egui::text::LayoutJob;
use egui::{Color32, FontId, TextFormat};
use std::collections::HashMap;
use crate::canvas::DocView;
use crate::theme::{self, Tokens};
use crate::widgets;
use craft::behavior::{DisplayOrder, ItemSource, Selection, SelectionChange};
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _};
use craft::ui::display::Text;
use craft::ui::list::{List, ListRow};
use craft::ui::runtime::env::Label;
use craft::ui::runtime::focus::{self, FocusTarget};
use craft::ui::style::Span;
use craft::ui::text::TextField;
use super::right::PanelResult;
use crate::PdfCraftApp;
/// Glyphs of context shown on each side of a match.
const CONTEXT: usize = 36;
/// The most results listed.
const MAX_RESULTS: usize = 2000;
/// A row of the results: a page's heading or a match by its index in the search's matches.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum Hit {
Page(usize),
Match(usize),
}
/// The results in display order.
struct Results {
rows: Vec<Hit>,
at: HashMap<Hit, usize>,
}
impl DisplayOrder<Hit> for Results {
fn len(&self) -> usize {
self.rows.len()
}
fn key(&self, at: usize) -> Hit {
self.rows.get(at).cloned().unwrap_or(Hit::Page(0))
}
fn index_of(&self, key: &Hit) -> Option<usize> {
self.at.get(key).copied()
}
}
impl ItemSource<Hit> for Results {}
/// Draw the Search panel with its query, options, progress and clickable result excerpts.
pub(crate) fn panel(ui: &mut egui::Ui, t: &Tokens, view: &mut DocView, pages: usize) {
crate::widgets::begin_dialog(ui);
pub(crate) fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) -> PanelResult {
let result = PanelResult::default();
let Some((index, id)) = app.active_ids() else { return result };
let pages = app.session.get(id).map_or(0, |d| d.info.pages.len());
let Some(view) = app.views.get_mut(index) else { return result };
let searched = view.texts.len() + view.text_failed.len();
let Some(find) = view.find.as_mut() else { return };
let Some(find) = view.find.as_mut() else { return result };
find.in_panel = true;
let l = ui.label(egui::RichText::new(tl!("What word or phrase would you like to search for?")).color(t.text_muted));
let r = ui
.add(crate::widgets::line(&mut find.query).id(egui::Id::unique("search-panel-input")).hint_text(tl!("Search")).desired_width(f32::INFINITY))
.accessible_name(tl!("Search"))
.labelled_by(l.id);
widgets::focus_selecting_all(ui, &r, &find.query, &mut find.focus);
ui.horizontal(|ui| {
// Outlined boxes (the panel and the check-box fill are alike), as in dialogs.
let w = &mut ui.visuals_mut().widgets;
w.inactive.bg_stroke = egui::Stroke::new(1.0, t.border);
w.inactive.bg_fill = t.hover;
let a = ui.add(widgets::checkbox(&mut find.whole_words, tl!("Whole words only"))).changed();
let b = ui.add(widgets::checkbox(&mut find.case_sensitive, tl!("Case-sensitive"))).changed();
if a || b {
find.case_query.clear();
}
});
let field = TextField::search(tl!("What word or phrase would you like to search for?").to_string(), Bind::bound(&mut find.query))
.select_on_focus()
.show(ui);
// The bar was asked for (⇧⌘F, also with the panel open): the field takes the focus once.
if find.bar.taken() {
focus::request(ui.ctx(), FocusTarget::Id(field.response.id));
}
let before = (find.options.whole_word, find.options.match_case);
Checkbox::new(Bind::bound(&mut find.options.whole_word)).label(tl!("Whole words only").to_string()).show(ui);
Checkbox::new(Bind::bound(&mut find.options.match_case)).label(tl!("Case-sensitive").to_string()).show(ui);
if before != (find.options.whole_word, find.options.match_case) {
find.case_query.clear();
}
if find.query != find.case_query {
view.rerun_find();
}
let Some(find) = view.find.as_ref() else { return };
ui.add_space(6.0);
let Some(find) = view.find.as_ref() else { return result };
let matches = find.matches.matches();
let status = if find.query.trim().is_empty() {
String::new()
} else if find.matches.is_empty() && searched < pages {
} else if matches.is_empty() && searched < pages {
crate::i18n::fmt(tl!("Searching… {s} of {p} pages"), &[("s", &searched.to_string()), ("p", &pages.to_string())])
} else {
let n = find.matches.len();
let n = matches.len();
let more = if searched < pages {
crate::i18n::fmt(tl!(" (searching… {s} of {p} pages)"), &[("s", &searched.to_string()), ("p", &pages.to_string())])
} else {
@@ -54,45 +93,60 @@ pub(crate) fn panel(ui: &mut egui::Ui, t: &Tokens, view: &mut DocView, pages: us
let count = if n == 1 { crate::i18n::fmt(tl!("1 instance"), &[]) } else { crate::i18n::fmt(tl!("{n} instances"), &[("n", &n.to_string())]) };
format!("{count}{more}")
};
ui.label(egui::RichText::new(status).font(theme::semibold(12.5)));
ui.add_space(4.0);
let mut go = None;
if !status.is_empty() {
Text::new(status).show(ui);
}
let mut rows = Vec::new();
let mut last_page = None;
for (i, (p, range)) in find.matches.iter().enumerate().take(2000) {
if last_page != Some(*p) {
ui.add_space(4.0);
ui.label(egui::RichText::new(crate::i18n::fmt(tl!("Page {label}"), &[("label", &(p + 1).to_string())])).small().color(t.text_faint));
last_page = Some(*p);
for (i, m) in matches.iter().enumerate().take(MAX_RESULTS) {
if !view.texts.contains_key(&m.page) {
continue;
}
let Some(text) = view.texts.get(p) else { continue };
let n = text.glyphs.len();
let before = text.text_of(range.start.saturating_sub(CONTEXT)..range.start.min(n));
let hit = text.text_of(range.start.min(n)..range.end.min(n));
let after = text.text_of(range.end.min(n)..(range.end + CONTEXT).min(n));
let flat = |s: String| s.split_whitespace().collect::<Vec<_>>().join(" ");
let mut job = LayoutJob::default();
let font = FontId::new(12.5, egui::FontFamily::Proportional);
let plain = TextFormat { font_id: font.clone(), color: t.text_muted, ..Default::default() };
job.append(&format!("…{} ", flat(before)), 0.0, plain.clone());
job.append(
&flat(hit),
0.0,
TextFormat {
font_id: theme::semibold(12.5),
color: t.text,
background: Color32::from_rgba_unmultiplied(255, 214, 0, 90),
..Default::default()
},
);
job.append(&format!(" {}…", flat(after)), 0.0, plain);
job.wrap.max_width = ui.available_width();
let selected = find.current == Some(i);
let resp = ui.add(egui::Button::selectable(selected, job).wrap()).on_hover_text(tl!("Go to this result"));
if resp.clicked() {
go = Some(i);
if last_page != Some(m.page) {
rows.push(Hit::Page(m.page));
last_page = Some(m.page);
}
rows.push(Hit::Match(i));
}
let at = rows.iter().cloned().enumerate().map(|(i, h)| (h, i)).collect();
let results = Results { rows, at };
let current = find.matches.current().map(|i| Selection::single(Hit::Match(i))).unwrap_or_default();
let flat = |s: String| s.split_whitespace().collect::<Vec<_>>().join(" ");
let out = List::<Hit>::new(tl!("Search results").to_string())
.select(SelectMode::Single)
.selection(Bind::given(current))
.natural_height(true)
.show_items(ui, &results, &mut |key, _| match key {
Hit::Page(p) => ListRow::new(crate::i18n::fmt(tl!("Page {label}"), &[("label", &(p + 1).to_string())])).section_heading(),
Hit::Match(i) => {
let Some(m) = matches.get(*i) else { return ListRow::new(Label::Empty) };
let Some(text) = view.texts.get(&m.page) else { return ListRow::new(Label::Empty) };
let n = text.glyphs.len();
let range = &m.range;
let before = flat(text.text_of(range.start.saturating_sub(CONTEXT)..range.start.min(n)));
let hit = flat(text.text_of(range.start.min(n)..range.end.min(n)));
let after = flat(text.text_of(range.end.min(n)..range.end.saturating_add(CONTEXT).min(n)));
let name = format!("…{before} {hit} {after}…");
ListRow::new(Label::Empty)
.lines(vec![Span::new(format!("…{before} ")).muted(), Span::new(hit).highlight().strong(), Span::new(format!(" {after}…")).muted()])
.accessible_name(name)
.tooltip(tl!("Go to this result").to_string())
}
});
let mut go = None;
for event in &out.events {
match event {
CollectionEvent::Selection(SelectionChange::Set(keys)) => {
if let Some(Hit::Match(i)) = keys.last() {
go = Some(*i);
}
}
CollectionEvent::Activate(Hit::Match(i)) => go = Some(*i),
_ => {}
}
}
if let Some(i) = go {
view.go_to_match(i);
}
result
}
+33 -84
View File
@@ -1,6 +1,10 @@
//! An attachment's row in the Attachments panel answers a double-click and a right-click, as
//! in Acrobat (#3466), while its buttons keep taking their own clicks.
use std::path::Path;
use std::sync::Arc;
use craft::host::{AppInfo, Host, Picked, ScriptedFiles};
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use pdfcraft_ui_egui::PdfCraftApp;
@@ -48,8 +52,16 @@ fn harness() -> Harness<'static, PdfCraftApp> {
}
fn harness_with_pdf(pdf: Vec<u8>) -> Harness<'static, PdfCraftApp> {
harness_answering(pdf, Arc::new(ScriptedFiles::new()))
}
/// [`harness_with_pdf`] whose file picks `files` answers.
// PLAN: assumed `crate::support::test_app(Arc<Host>) -> PdfCraftApp`, the shared harness that builds the app over a host
// with its test services (pdf-chrome-w9, w9-1).
fn harness_answering(pdf: Vec<u8>, files: Arc<ScriptedFiles>) -> Harness<'static, PdfCraftApp> {
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_eframe(move |_cc| {
let mut app = PdfCraftApp::new();
let host = Arc::new(Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).files(files).build());
let mut app = crate::support::test_app(host);
app.set_option("language", "en").unwrap();
app.open_bytes("doc.pdf", None, pdf).unwrap();
app.set_option("panel", "attachments").unwrap();
@@ -93,24 +105,6 @@ fn submitting_blank_leaves_an_absent_description_untouched() {
assert_eq!(doc.can_undo(), None);
}
/// A folder of its own for one test's saved file, removed afterwards.
struct Dir(std::path::PathBuf);
impl Dir {
fn new(test: &str) -> Self {
let path = std::env::temp_dir().join(format!("pdfcraft-attachment-row-{test}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
}
impl Drop for Dir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// Two pointer clicks a frame apart on `label` (an accessibility click is never a double-click).
fn double_click(h: &mut Harness<'static, PdfCraftApp>, label: &str) {
let at = row_name(h, label);
@@ -133,53 +127,40 @@ fn right_click(h: &mut Harness<'static, PdfCraftApp>, label: &str) {
h.run_steps(2);
}
/// A row event of the Attachments list becomes an attachment action: a double click saves a file that
/// is not a PDF and opens one that is; the row menu offers Open only for the PDF, and its Save, Open and
/// Delete act on the row it was opened on.
#[test]
fn double_clicking_a_pdf_attachment_opens_it_in_a_new_tab() {
let mut h = harness();
fn attachment_rows_turn_their_events_into_attachment_actions() {
let saved = Path::new("out/saved notes.txt");
let from_menu = Path::new("out/from menu.pdf");
let files = Arc::new(ScriptedFiles::answering([Picked::file(saved), Picked::file(from_menu)]));
let mut h = harness_answering(attachments_pdf(), files.clone());
assert_eq!(h.state().views.len(), 1);
double_click(&mut h, "notes.txt");
assert_eq!(files.file(saved).as_deref(), Some(&b"hello notes"[..]), "PdfCraft opens only PDFs, so it saves the rest");
assert_eq!(h.state().views.len(), 1, "nothing opens");
double_click(&mut h, "inner.pdf");
assert_eq!(h.state().views.len(), 2, "the attached PDF opens in a tab of its own");
}
#[test]
fn double_clicking_another_attachment_saves_it() {
let dir = Dir::new("double");
let target = dir.0.join("saved notes.txt");
let mut h = harness();
h.state_mut().pick_override = Some(vec![target.to_string_lossy().into_owned()]);
double_click(&mut h, "notes.txt");
assert_eq!(std::fs::read(&target).unwrap(), b"hello notes", "PdfCraft opens only PDFs, so it saves the rest");
assert_eq!(h.state().views.len(), 1, "nothing opens");
}
#[test]
fn the_right_click_menu_opens_saves_and_deletes() {
let dir = Dir::new("menu");
let target = dir.0.join("from menu.pdf");
let mut h = harness();
let count = |h: &Harness<'static, PdfCraftApp>, label: &str| h.query_all_by_label(label).count();
// The rows have Save and Delete buttons each, and the PDF's row an Open button.
assert_eq!((count(&h, "Save attachment…"), count(&h, "Open in a new tab"), count(&h, "Delete attachment")), (2, 1, 2));
// A text file's menu has Save and Delete, no Open.
h.get_all_by_label("doc.pdf").next().expect("the first tab").click();
h.run_steps(3);
// The menu of a text file has no Open; the PDF's has.
right_click(&mut h, "notes.txt");
assert_eq!((count(&h, "Save attachment…"), count(&h, "Open in a new tab"), count(&h, "Delete attachment")), (3, 1, 3));
assert!(h.get_by_role(egui::accesskit::Role::Menu).query_by_label("Open in a new tab").is_none(), "no Open for notes.txt");
h.key_press(egui::Key::Escape);
h.run_steps(3);
// Scope actions to the menu: egui nests it under its row in the accessibility tree.
// Save writes the PDF, not the text file whose row comes last.
right_click(&mut h, "inner.pdf");
assert_eq!(count(&h, "Open in a new tab"), 2, "the PDF's menu offers Open");
h.state_mut().pick_override = Some(vec![target.to_string_lossy().into_owned()]);
h.get_by_role(egui::accesskit::Role::Menu).get_by_label("Open in a new tab");
h.get_by_role(egui::accesskit::Role::Menu).get_by_label("Save attachment…").click();
h.run_steps(3);
assert_eq!(std::fs::read(&target).unwrap(), INNER, "Save from inner.pdf's menu");
assert_eq!(files.file(from_menu).as_deref(), Some(INNER), "Save from inner.pdf's menu");
right_click(&mut h, "inner.pdf");
h.get_by_role(egui::accesskit::Role::Menu).get_by_label("Open in a new tab").click();
h.run_steps(3);
assert_eq!(h.state().views.len(), 2, "Open from the menu");
h.state_mut().active = Some(0);
assert_eq!(h.state().views.len(), 3, "Open from the menu");
h.get_all_by_label("doc.pdf").next().expect("the first tab").click();
h.run_steps(3);
// Delete from inner.pdf's menu leaves notes.txt, whose row's button would delete itself.
// Delete from inner.pdf's menu leaves notes.txt.
right_click(&mut h, "inner.pdf");
h.get_by_role(egui::accesskit::Role::Menu).get_by_label("Delete attachment").click();
h.run_steps(3);
@@ -241,38 +222,6 @@ fn editing_the_document_while_description_dialog_is_open_discards_its_stale_draf
assert_eq!(doc.can_undo(), Some("Edit attachment description"));
}
#[test]
fn the_row_buttons_still_take_their_own_clicks() {
let dir = Dir::new("buttons");
let target = dir.0.join("from button.txt");
let mut h = harness();
h.state_mut().pick_override = Some(vec![target.to_string_lossy().into_owned()]);
// The rows list inner.pdf first, then notes.txt: the second Save button is notes.txt's.
h.get_all_by_label("Save attachment…").nth(1).unwrap().click();
h.run_steps(3);
assert_eq!(std::fs::read(&target).unwrap(), b"hello notes", "the Save button under the row's click area");
h.get_by_label("Open in a new tab").click();
h.run_steps(3);
assert_eq!(h.state().views.len(), 2, "the Open button");
}
/// CodeRabbit on #4513: a right-click on one of a row's buttons opens that row's menu too, as a
/// right-click anywhere on the row does.
#[test]
fn a_right_click_on_a_row_button_opens_the_row_menu() {
let mut h = harness();
let count = |h: &Harness<'static, PdfCraftApp>, label: &str| h.query_all_by_label(label).count();
// inner.pdf's row comes first: its Save button is the first one.
let at = h.get_all_by_label("Save attachment…").next().expect("inner.pdf's Save button").rect().center();
h.hover_at(at);
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });
h.run_steps(2);
assert_eq!(count(&h, "Open in a new tab"), 2, "inner.pdf's menu, with Open, is open");
assert_eq!(count(&h, "Save attachment…"), 3);
}
/// Where the attachment named `label` shows in the panel: the lowest text with that name, below
/// a tab of the same name once the attachment is open.
fn row_name(h: &Harness<'static, PdfCraftApp>, label: &str) -> egui::Pos2 {
+8 -2
View File
@@ -1,6 +1,8 @@
//! Set-layer-visibility actions (`SetOCGState`) on links and push buttons show and hide layers,
//! as the Layers panel does.
use std::sync::Arc;
use egui::Pos2;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
@@ -46,7 +48,9 @@ fn harness(setup: impl FnOnce(&mut PdfCraftApp) + 'static) -> Harness<'static, P
fn harness_with(pdf: Vec<u8>, setup: impl FnOnce(&mut PdfCraftApp) + 'static) -> Harness<'static, PdfCraftApp> {
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
let mut app = PdfCraftApp::new();
// PLAN: assumed `crate::support::test_app(Arc<Host>) -> PdfCraftApp`, the shared harness (pdf-chrome-w9, w9-1).
let host = Arc::new(craft::host::Host::builder(craft::host::AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).build());
let mut app = crate::support::test_app(host);
app.set_option("language", "en").unwrap();
app.open_bytes("layers.pdf", None, pdf).unwrap();
app.set_option("zoom", "150").unwrap();
@@ -123,7 +127,9 @@ fn layer_options_reset_to_initial_visibility() {
app.set_option("panel", "layers").unwrap();
});
assert_eq!(shown(&h), layers(false, true));
h.get_by_label("Layer options").click();
// The Layers panel's menu holds the catalog command (`layers.reset_visibility`, L-87).
// PLAN: `DockWords::default()` is assumed to give the framework's English words (`panel_menu`).
h.get_by_label(craft::ui::docking::DockWords::default().panel_menu.as_str()).click();
h.run_steps(2);
h.get_by_label("Reset to Initial Visibility").click();
h.run_steps(3);