Merge branch 'main' into patch-20

This commit is contained in:
Mex authored and GitHub committed 2026-11-14 22:52:42 +01:00
commit e4a23c2b2e
14 files changed
+198 -21

No files matched your search

+4
View File
@@ -46,6 +46,10 @@ jobs:
# A missing oracle fails the job instead of printing a skip notice that reads as a pass.
linux-env: PDFCRAFT_ORACLES_REQUIRED=1
windows-env: PDFCRAFT_REQUIRE_WINRES=1
# Preserve the packaging regression check removed from git-sources in #7042.
command: |
pwsh -NoProfile -File packaging/windows/test-font-notices.ps1
cargo xtask ci
# Windows checks what differs by platform: the build (with resources) and the tests.
windows-command: |
cargo clippy --workspace --all-targets --locked -- -D warnings
+1 -1
View File
@@ -1 +1 @@
575cfdef63227b14daf173b8cc87928bfdfa325e
e56d26244bbac099bfd42e23fb12f78a4be418a7
+18 -8
View File
@@ -145,13 +145,23 @@ fn decoded(doc: &Document, s: &Stream, budget: &mut ImageBudget) -> Result<Vec<u
/// alpha, JPEG images included, so cut-out images keep their transparent background.
fn image(doc: &Document, s: &Stream, budget: &mut ImageBudget) -> Result<(&'static str, Vec<u8>), String> {
let f = filters(s);
let jpeg = matches!(f.last().map(Vec::as_slice), Some(b"DCTDecode" | b"DCT")) && f.len() == 1;
match f.last().map(Vec::as_slice) {
Some(b"JPXDecode") => return Err("JPEG 2000 images can't be exported yet".into()),
Some(b"DCTDecode" | b"DCT") if !jpeg => return Err("JPEG images inside other filters can't be exported yet".into()),
_ => {}
let jpeg = matches!(f.last().map(Vec::as_slice), Some(b"DCTDecode" | b"DCT"));
if matches!(f.last().map(Vec::as_slice), Some(b"JPXDecode")) {
return Err("JPEG 2000 images can't be exported yet".into());
}
let as_is = || Ok(("jpg", s.raw.to_vec()));
// Decode only the stages before DCT, within the same work budget as other image filters.
// The JPEG decoder and as-is export below both need the unwrapped JPEG bytes.
let jpeg_data = if jpeg && f.len() > 1 {
let direct = doc.with_direct_parms(s);
let chain = direct.filters();
let Some(((pdfcraft_filters::Filter::Dct, _), prefix)) = chain.split_last() else {
return Err("invalid JPEG filter chain".into());
};
std::borrow::Cow::Owned(budget.decode_chain(prefix, &s.raw, MAX_DECODED).map_err(|e| e.to_string())?)
} else {
std::borrow::Cow::Borrowed(s.raw.as_ref())
};
let as_is = || Ok(("jpg", jpeg_data.to_vec()));
let (w, h) = (s.dict.int(b"Width").unwrap_or(0), s.dict.int(b"Height").unwrap_or(0));
let Some((w, h)) = size(w, h) else {
return match () {
@@ -195,12 +205,12 @@ fn image(doc: &Document, s: &Stream, budget: &mut ImageBudget) -> Result<(&'stat
None => space(doc, s.dict.get(b"ColorSpace"), budget)?,
};
let (samples, bpc) = if jpeg {
if !budget.pay_jpeg((w as u64).saturating_mul(h as u64).saturating_mul(space.components() as u64), &s.raw) {
if !budget.pay_jpeg((w as u64).saturating_mul(h as u64).saturating_mul(space.components() as u64), &jpeg_data) {
return Err(FilterError::Spent.to_string());
}
// Grey, RGB or CMYK samples (YCCK is converted); a JPEG that doesn't decode, or an
// indexed one (not valid), is written as is, without its transparency.
let Some((samples, decoded)) = jpeg_samples(&s.raw, &space, w, h) else { return as_is() };
let Some((samples, decoded)) = jpeg_samples(&jpeg_data, &space, w, h) else { return as_is() };
space = decoded;
(samples, 8)
} else {
+46
View File
@@ -3073,3 +3073,49 @@ fn office_documents_are_their_own_kind() {
assert_eq!(source_kind("Report.docx", b"%PDF-1.7\n"), Some(SourceKind::Pdf));
assert_eq!(source_kind("photos.zip", b"PK\x03\x04\x14\x00"), None);
}
#[test]
fn flate_wrapped_jpeg_exports_with_and_without_a_soft_mask() {
for masked in [false, true] {
let jpeg = real_jpeg();
let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();
with_image(&mut doc, |doc| {
let mut d = image_dict(4, 2, "DeviceGray", 8);
d.set(b"Filter".to_vec(), Object::Array(vec![Object::name("FlateDecode"), Object::name("DCTDecode")]));
if masked {
let mask = Stream::from_raw(image_dict(4, 2, "DeviceGray", 8), vec![0, 255, 0, 255, 255, 0, 255, 0]);
d.set(b"SMask".to_vec(), Object::Ref(doc.add(Object::Stream(mask))));
}
Stream::from_raw(d, pdfcraft_filters::encode_flate(&jpeg))
});
let doc = reopen(&doc);
let out = crate::extract::extract_images(&doc, &[0], 0);
assert!(out.skipped.is_empty(), "{:?}", out.skipped);
assert_eq!(out.images.len(), 1);
if masked {
assert_eq!(out.images[0].extension, "png");
assert_eq!(alphas(&exported_png_pixels(&out.images[0].data)), vec![0, 255, 0, 255, 255, 0, 255, 0]);
} else {
assert_eq!(out.images[0].extension, "jpg");
assert_eq!(out.images[0].data, jpeg);
}
}
}
#[test]
fn flate_wrapped_jpeg_rejects_corruption_and_spent_budget() {
for corrupt in [false, true] {
let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();
with_image(&mut doc, |_| {
let mut d = image_dict(4, 2, "DeviceGray", 8);
d.set(b"Filter".to_vec(), Object::Array(vec![Object::name("FlateDecode"), Object::name("DCTDecode")]));
let bytes = if corrupt { vec![1, 2, 3] } else { pdfcraft_filters::encode_flate(&real_jpeg()) };
Stream::from_raw(d, bytes)
});
let doc = reopen(&doc);
let mut budget = pdfcraft_cos::ImageBudget::with_work(if corrupt { u64::MAX } else { 0 });
let out = crate::extract::extract_images_within(&doc, &[0], 0, &mut budget, usize::MAX);
assert!(out.images.is_empty());
assert_eq!(out.skipped.len(), 1, "{:?}", out.skipped);
}
}
+1 -1
View File
@@ -293,7 +293,7 @@ pub const COMMANDS: &[CommandSpec] = &[
c("comment.polyline", "Draw connected lines", None, None, Annotate, "spline"),
c("comment.cloud", "Draw a cloud", None, None, Annotate, "cloud"),
c("comment.callout", "Add a callout", None, None, Annotate, "message-square-quote"),
c("comment.caret", "Insert text", None, None, Annotate, "text-cursor-input"),
c("comment.caret", "Insert text", None, None, Annotate, "message-square-text"),
c("comment.replace", "Replace text", None, None, Annotate, "replace"),
c("comment.attach", "Attach a file", None, None, Annotate, "paperclip"),
c("comment.eraser", "Erase drawings", None, None, Annotate, "eraser"),
+1 -1
View File
@@ -211,7 +211,7 @@ impl CommentTool {
Self::PolyLine => "spline",
Self::Cloud => "cloud",
Self::Callout => "message-square-quote",
Self::Caret => "text-cursor-input",
Self::Caret => "message-square-text",
Self::ReplaceText => "replace",
Self::Attach => "paperclip",
Self::Eraser => "eraser",
+20 -2
View File
@@ -788,7 +788,7 @@ pub(crate) fn delete_selected(cv: &mut CommentView, info: &DocInfo) -> Option<Ed
}
}
/// The arrow keys move the selected comment a screen pixel; with ⌘/Ctrl or Shift, ten. Up is up
/// The arrow keys move selected comments a screen pixel; with ⌘/Ctrl or Shift, ten. Up is up
/// on screen whatever the zoom, the page's rotation and the view's; the keys are taken before
/// the view scrolls or turns the page with them. Each press is one undo step. Text markup stays
/// with its text, and a locked comment where it is.
@@ -838,7 +838,25 @@ pub(crate) fn nudge_keys(ctx: &egui::Context, keys: PageKeys, view: &mut DocView
let (a, b) = (user(xf.rect.center()), user(xf.rect.center() + step));
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
if dx.is_finite() && dy.is_finite() && (dx != 0.0 || dy != 0.0) {
view.pending_edit = Some(Edit::MoveAnnotation { page, index, dx, dy });
// Match a pointer drag: move the eligible selection on this page as one undo step.
// Text markup and locked comments cannot be moved and would reject a batch.
let mut indices = vec![index];
for &(other_page, other_index) in &view.comments.also {
if other_page == page
&& !indices.contains(&other_index)
&& info.annotations.iter().any(|a| a.page == page && a.index == other_index && !a.is_reply() && !on_text(a) && !a.locked)
{
indices.push(other_index);
}
}
view.pending_edit = Some(if indices.len() == 1 {
Edit::MoveAnnotation { page, index, dx, dy }
} else {
Edit::Batch {
label: tl!("Move comments").to_owned(),
edits: indices.into_iter().map(|index| Edit::MoveAnnotation { page, index, dx, dy }).collect(),
}
});
}
}
@@ -898,3 +898,13 @@ fn comment_marker_wins_over_an_overlapping_body_for_pick_and_hover() {
super::input::describe(&hidden, &mut view);
assert!(view.cursor.resolve(&ctx, QuickTool::Select).is_none());
}
#[test]
fn insert_text_icon_is_distinct_from_edit_text_and_matches_its_command() {
let insert = CommentTool::Caret.icon();
let edit = pdfcraft_engine::commands::command("edit.edit_text").unwrap().icon;
let command = pdfcraft_engine::commands::command("comment.caret").unwrap().icon;
assert_ne!(insert, edit, "adjacent tools need distinct icons");
assert_eq!(insert, command, "the annotation toolbar and command use the same icon");
assert!(crate::widgets::icons::exists(insert));
}
+84 -3
View File
@@ -1127,6 +1127,58 @@ fn arrow_keys_nudge_the_selected_comment() {
assert_eq!(h.state().views[0].current, 1, "and the view goes to the next page");
}
#[test]
fn arrow_keys_nudge_all_selected_comments_as_one_undo_step() {
use egui::Key;
let mut h = harness(|app| app.set_option("quick", "square").unwrap());
drag_pt(&mut h, (30.0, 110.0), (80.0, 70.0));
drag_pt(&mut h, (130.0, 110.0), (180.0, 70.0));
h.state_mut().set_option("quick", "select").unwrap();
let before: Vec<_> = comments(&h).iter().map(|a| a.rect).collect();
assert_eq!(before.len(), 2);
h.state_mut().views[0].comments.selected = Some((0, 0));
h.state_mut().views[0].comments.also = vec![(0, 1)];
h.key_press(Key::ArrowRight);
h.run_steps(3);
let moved: Vec<_> = comments(&h).iter().map(|a| a.rect).collect();
for (old, new) in before.iter().zip(&moved) {
assert!(new[0] > old[0], "each selected comment moves: {before:?} -> {moved:?}");
}
h.state_mut().undo();
h.run_steps(2);
let undone: Vec<_> = comments(&h).iter().map(|a| a.rect).collect();
assert_eq!(undone, before, "one undo restores the whole selection");
}
#[test]
fn arrow_nudge_skips_locked_comments_and_duplicate_selection_entries() {
let mut h = harness(|app| app.set_option("quick", "square").unwrap());
for (a, b) in [((20.0, 20.0), (60.0, 60.0)), ((100.0, 20.0), (140.0, 60.0)), ((180.0, 20.0), (220.0, 60.0))] {
drag_pt(&mut h, a, b);
}
h.state_mut().set_option("quick", "select").unwrap();
assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::LockAnnotation { page: 0, index: 1, locked: true }));
h.run_steps(2);
let before = comments(&h);
h.state_mut().views[0].comments.selected = Some((0, 0));
h.state_mut().views[0].comments.also = vec![(0, 1), (0, 2), (0, 2), (0, 0)];
h.key_press(egui::Key::ArrowRight);
h.run_steps(3);
let after = comments(&h);
let left = |list: &[Annotation], i: usize| list.iter().find(|a| a.index == i).expect("comment still exists").rect[0];
let primary_delta = left(&after, 0) - left(&before, 0);
let secondary_delta = left(&after, 2) - left(&before, 2);
assert!(primary_delta > 0.0, "primary comment moves");
assert!((secondary_delta - primary_delta).abs() < 0.01, "duplicate entries must not move the second comment twice");
assert_eq!(left(&after, 1), left(&before, 1), "locked comment stays in place");
h.state_mut().undo();
h.run_steps(2);
let undone = comments(&h);
for i in 0..3 {
assert_eq!(left(&undone, i), left(&before, i), "one undo restores comment {i}");
}
}
/// #3632: with a comment selected, Alt+← / Alt+→ still go back and forward through the view
/// history instead of nudging it (egui's key patterns let an extra Alt through).
#[test]
@@ -4641,14 +4693,18 @@ fn hotbar_picker_searches_translated_tool_labels() {
if crate::support::skip_without_catalogs("hotbar_picker_searches_translated_tool_labels") {
return;
}
use pdfcraft_ui_egui::i18n::{Lang, tr};
let french = Lang::from_code("fr").unwrap();
let mut h = harness(|app| {
app.set_option("language", "fr").unwrap();
});
h.get_by_label("Hotbar settings").click();
// The button and the search field are in French too, in the catalog's words.
h.get_by_label(tr(french, "Hotbar settings")).click();
h.run_steps(3);
field(&h, "Search all tools…").click();
let search = tr(french, "Search all tools…");
field(&h, search).click();
h.run_steps(2);
field(&h, "Search all tools…").type_text("Dessiner");
field(&h, search).type_text("Dessiner");
h.run_steps(3);
h.get_by_role_and_label(Role::CheckBox, "Dessiner à main levée").click();
h.run_steps(3);
@@ -5848,3 +5904,28 @@ fn properties_dialog_makes_the_text_box_font_size_default() {
assert_eq!(font_size_of_last(&fresh).font_size, Some(size), "{quick}: the default font size persisted");
}
}
#[test]
fn ctrl_selected_lines_nudge_together_and_undo() {
let mut h = harness(|app| app.set_option("quick", "line").unwrap());
for y in [40.0, 80.0, 120.0] {
drag_pt(&mut h, (40.0, y), (160.0, y));
}
assert_eq!(comments(&h).len(), 3);
h.state_mut().set_option("quick", "select").unwrap();
h.run_steps(2);
click_pt(&mut h, (100.0, 40.0));
click_pt_with(&mut h, (100.0, 80.0), egui::Modifiers::COMMAND);
click_pt_with(&mut h, (100.0, 120.0), egui::Modifiers::COMMAND);
assert_eq!(h.state().views[0].comments.selection().len(), 3);
let before: Vec<_> = comments(&h).iter().map(|a| a.rect).collect();
h.key_press(egui::Key::ArrowRight);
h.run_steps(3);
let moved: Vec<_> = comments(&h).iter().map(|a| a.rect).collect();
for (old, new) in before.iter().zip(&moved) {
assert!(new[0] > old[0], "each selected line moves: {before:?} -> {moved:?}");
}
h.state_mut().undo();
h.run_steps(2);
assert_eq!(comments(&h).iter().map(|a| a.rect).collect::<Vec<_>>(), before);
}
+6 -2
View File
@@ -424,8 +424,12 @@ fn primary_ui_fonts_cover_latin_and_cyrillic_catalogs() {
"áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽãõçâêôàÃÕÇÂÊÔÀñÑüÜäÄöÖőűßæøåÆØÅ„“¿¡«»…ґҐєЄіІїЇәғқңөұүһӘҒҚҢӨҰҮҺđĐạảấầẩẫậắằẳẵặếềểễệọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹ",
);
for line in catalog.lines().filter(|l| !l.starts_with('#')) {
if let Some(translation) = line.split('\t').nth(2) {
text.extend(translation.chars().filter(|c| !c.is_whitespace()));
let mut columns = line.split('\t').skip(1);
if let (Some(source), Some(translation)) = (columns.next(), columns.next()) {
// Every letter is checked. A symbol the row's English text has too (the menu path
// arrow `▸`, say) is drawn however English draws it, so it is not this catalog's
// to cover.
text.extend(translation.chars().filter(|c| !c.is_whitespace() && (c.is_alphanumeric() || !source.contains(*c))));
}
}
for name in ["Inter", "Inter-Medium", "Inter-SemiBold", "JetBrainsMono"] {
+4 -1
View File
@@ -332,7 +332,10 @@ fn native_script_prompt_uses_the_german_catalog_when_available() {
h.state_mut().run_button_script(id, "hello", "app.response({cQuestion:'Test',bPassword:true});");
wait_for(&mut h, heading);
assert!(h.query_by_label("Dokument: form.pdf").is_some());
assert!(h.query_by_label("Diese Aufforderung stammt aus dem Dokument und wird von dessen Skript angezeigt. Gib ein Passwort nur ein, wenn du diesem Dokument vertraust.").is_some());
// The warning in the catalog's words, which translators may reword, and never the English.
let warning = "This request comes from the document, not PdfCraft. Only enter a password if you trust this document.";
assert_ne!(tr(german, warning), warning, "the German catalog translates the password warning");
assert!(h.query_by_label(tr(german, warning)).is_some());
}
#[test]
+1
View File
@@ -19,6 +19,7 @@ allow = [
"Unicode-3.0",
"BSL-1.0",
"CC0-1.0",
"IJG",
]
[licenses.private]
@@ -126,5 +126,5 @@ modules:
path: stage
- type: git
url: https://github.com/storytold/craft-i18n
commit: 575cfdef63227b14daf173b8cc87928bfdfa325e
commit: e56d26244bbac099bfd42e23fb12f78a4be418a7
dest: craft-i18n
@@ -132,6 +132,6 @@ modules:
# The interface translations at the commit in craft-i18n.rev (a test keeps the two equal).
- type: git
url: https://github.com/storytold/craft-i18n
commit: 575cfdef63227b14daf173b8cc87928bfdfa325e
commit: e56d26244bbac099bfd42e23fb12f78a4be418a7
dest: craft-i18n
- cargo-sources.json