mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-16 15:53:54 +00:00
Merge branch 'main' into fix/7175-update-download-test
This commit is contained in:
29 files changed
+224
-92
No files matched your search
@@ -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
@@ -1 +1 @@
|
||||
575cfdef63227b14daf173b8cc87928bfdfa325e
|
||||
e56d26244bbac099bfd42e23fb12f78a4be418a7
|
||||
@@ -947,7 +947,7 @@ fn open_inspect_render_and_find() {
|
||||
let Content::Png { data, width, height } = &png[0] else { panic!("expected an image") };
|
||||
assert_eq!((*width, *height), (200, 300));
|
||||
assert_eq!(&data[..8], b"\x89PNG\r\n\x1a\n");
|
||||
let decoded = craft_image_codecs::decode(&data).unwrap();
|
||||
let decoded = craft_image_codecs::decode(data).unwrap();
|
||||
assert_eq!(decoded.dimensions(), (200, 300));
|
||||
}
|
||||
|
||||
@@ -7790,7 +7790,7 @@ fn typed_signatures_stay_upright_on_rotated_pages() {
|
||||
let Content::Png { data, .. } = &output[0] else { panic!() };
|
||||
let (width, height, pixels) = decode_rgba(data);
|
||||
assert_eq!((width, height), if page % 2 == 1 { (200, 300) } else { (300, 200) }, "page {page}");
|
||||
let dark: Vec<bool> = pixels.chunks_exact(4).map(|p| p[..3].iter().all(|v| *v < 128)).collect();
|
||||
let dark: Vec<bool> = pixels.as_chunks::<4>().0.iter().map(|p| p[..3].iter().all(|v| *v < 128)).collect();
|
||||
for y in [60, 140] {
|
||||
let mut b = [u32::MAX, u32::MAX, 0, 0];
|
||||
for py in 0..height {
|
||||
@@ -7847,7 +7847,7 @@ fn fill_sign_marks_stay_upright_on_rotated_pages() {
|
||||
let output = a.call("page_render", &json!({ "doc": doc, "page": page, "dpi": 144 })).unwrap();
|
||||
let Content::Png { data, .. } = &output[0] else { panic!() };
|
||||
let (width, height, pixels) = decode_rgba(data);
|
||||
let dark: Vec<bool> = pixels.chunks_exact(4).map(|p| p[..3].iter().all(|v| *v < 128)).collect();
|
||||
let dark: Vec<bool> = pixels.as_chunks::<4>().0.iter().map(|p| p[..3].iter().all(|v| *v < 128)).collect();
|
||||
// The line, 36 × 4 pt displayed, runs across.
|
||||
let mut b = [u32::MAX, u32::MAX, 0, 0];
|
||||
for y in 0..height {
|
||||
@@ -8389,7 +8389,7 @@ fn named_layer_verdicts_are_reported_and_rendered_through_tools() {
|
||||
let rendered = a.call("page_render", &json!({"doc": doc, "page": 1, "dpi": 72})).unwrap();
|
||||
let Content::Png { data, .. } = &rendered[0] else { panic!("expected a PNG") };
|
||||
let (_, _, pixels) = decode_rgba(data);
|
||||
let red = pixels.chunks_exact(4).filter(|p| p[..3].iter().zip([0xD7u8, 0x37, 0x3F]).all(|(a, b)| a.abs_diff(b) < 30)).count();
|
||||
let red = pixels.as_chunks::<4>().0.iter().filter(|p| p[..3].iter().zip([0xD7u8, 0x37, 0x3F]).all(|(a, b)| a.abs_diff(b) < 30)).count();
|
||||
assert!(red > 100, "the invalid state is drawn: {red} red pixels");
|
||||
ok(&mut a, "doc_save", json!({"doc": doc, "path": "saved.pdf", "full": false}));
|
||||
assert_eq!(std::fs::read(dir.join("saved.pdf")).unwrap(), original, "the drawn state never enters saves");
|
||||
@@ -8923,7 +8923,7 @@ fn a_one_bit_scan_stays_one_bit_and_exports() {
|
||||
assert_eq!(files.len(), 1, "{r}");
|
||||
let exported = std::fs::read(files[0]["path"].as_str().unwrap()).unwrap();
|
||||
let (_, _, rgba) = decode_rgba(&exported);
|
||||
let white: Vec<bool> = rgba.chunks_exact(4).map(|p| p[..3] == [255, 255, 255]).collect();
|
||||
let white: Vec<bool> = rgba.as_chunks::<4>().0.iter().map(|p| p[..3] == [255, 255, 255]).collect();
|
||||
let expected: Vec<bool> =
|
||||
(0..h as usize).flat_map(|y| (0..w as usize).map(move |x| (y, x))).map(|(y, x)| bits[y * stride + x / 8] & (0x80 >> (x % 8)) != 0).collect();
|
||||
assert_eq!(white, expected);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -431,7 +431,6 @@ fn png_image(name: &str, bytes: &[u8]) -> Result<Embedded, CreateError> {
|
||||
let opts = craft_image_codecs::DecodeOptions {
|
||||
keep_orientation: true,
|
||||
limits: craft_image_codecs::Limits { max_alloc: MAX_DECODED_BYTES as u64, ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Png, bytes, &opts).map_err(|e| match e {
|
||||
craft_image_codecs::CodecError::LimitExceeded(m) => bad(format!("image too large: {m}")),
|
||||
@@ -695,7 +694,6 @@ fn tiff_pages_within(name: &str, bytes: &[u8], wanted: usize, budget: usize) ->
|
||||
let opts = craft_image_codecs::DecodeOptions {
|
||||
keep_orientation: true,
|
||||
limits: craft_image_codecs::Limits { max_alloc: MAX_DECODED_BYTES as u64, ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
let mut kept = 0usize;
|
||||
|
||||
@@ -1687,7 +1687,7 @@ fn png_of(w: u32, h: u32, color: TestPngColor, depth: TestPngDepth, data: &[u8],
|
||||
(TestPngColor::Grayscale | TestPngColor::Indexed, TestPngDepth::One) => (w as usize).div_ceil(8),
|
||||
(TestPngColor::Grayscale | TestPngColor::Indexed, TestPngDepth::Eight) => w as usize,
|
||||
(TestPngColor::Rgb, TestPngDepth::Eight) => w as usize * 3,
|
||||
(TestPngColor::Rgb, TestPngDepth::One) => unreachable!(),
|
||||
(TestPngColor::Rgb, TestPngDepth::One) => return Vec::new(),
|
||||
};
|
||||
let mut raw = Vec::with_capacity((1 + row_bytes) * h as usize);
|
||||
for row in data.chunks_exact(row_bytes) {
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -81,7 +81,6 @@ fn turned(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
let opts = craft_image_codecs::DecodeOptions {
|
||||
keep_orientation: false,
|
||||
limits: craft_image_codecs::Limits { max_pixels: MAX_PIXELS, ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
let mut img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Jpeg, bytes, &opts).ok()?;
|
||||
if let Some((mut dx, mut dy)) = jfif_density_dpi(bytes) {
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -143,7 +143,6 @@ pub(crate) fn decode_source(bytes: &[u8]) -> Result<DynamicImage, SignatureImage
|
||||
max_pixels: MAX_SOURCE_PIXELS,
|
||||
max_alloc: MAX_SOURCE_PIXELS * 4,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let decoded = craft_image_codecs::decode_as_with(format, bytes, &opts).map_err(|e| match e {
|
||||
craft_image_codecs::CodecError::LimitExceeded(_) => SignatureImageError::Size,
|
||||
@@ -218,7 +217,7 @@ impl SignatureImage {
|
||||
let mut raw = self.rgba.as_ref().clone();
|
||||
let high = f32::from(cutoff);
|
||||
let span = f32::from(feather.max(1));
|
||||
for px in raw.chunks_exact_mut(4) {
|
||||
for px in raw.as_chunks_mut::<4>().0 {
|
||||
let whiteness = f32::from(px[0].min(px[1]).min(px[2]));
|
||||
let keep = ((high - whiteness) / span).clamp(0.0, 1.0);
|
||||
px[3] = (f32::from(px[3]) * keep).round() as u8;
|
||||
|
||||
@@ -387,7 +387,7 @@ xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawin
|
||||
target: format!("media/{name}"),
|
||||
external: false,
|
||||
});
|
||||
pkg.binary(&format!("word/media/{name}"), image_mime(&im.ext), im.bytes.to_vec());
|
||||
pkg.binary(&format!("word/media/{name}"), image_mime(im.ext), im.bytes.to_vec());
|
||||
}
|
||||
if page_colour.is_some() {
|
||||
doc_rels.items.push(RelOut { id: "rIdSettings".into(), ty: format!("{RT_BASE}settings"), target: "settings.xml".into(), external: false });
|
||||
|
||||
@@ -368,7 +368,7 @@ xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" type=\"blank\"
|
||||
pkg.rels(&path, s_rels);
|
||||
}
|
||||
for (name, im) in &global_media {
|
||||
pkg.binary(&format!("ppt/media/{name}"), image_mime(&im.ext), im.bytes.to_vec());
|
||||
pkg.binary(&format!("ppt/media/{name}"), image_mime(im.ext), im.bytes.to_vec());
|
||||
}
|
||||
pkg.finish().unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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"] {
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -192,7 +192,7 @@ pub fn parse_data_file(text: &str, expect_root: Option<&str>) -> Result<Vec<Impo
|
||||
if crate::xml_nesting_depth(text) > MAX_IMPORT_DEPTH {
|
||||
return Err(XfaError::TooLarge(format!("the data file nests more than {MAX_IMPORT_DEPTH} levels deep")));
|
||||
}
|
||||
let opts = crate::xml::ParsingOptions { allow_dtd: false, nodes_limit: MAX_NODES, ..Default::default() };
|
||||
let opts = crate::xml::ParsingOptions { allow_dtd: false, nodes_limit: MAX_NODES };
|
||||
let parsed = crate::xml::Document::parse_with_options(text, opts).map_err(|e| XfaError::Malformed(format!("the data file is not XML: {e}")))?;
|
||||
let root = parsed.root_element();
|
||||
let local = root.tag_name().name();
|
||||
@@ -304,7 +304,7 @@ pub fn export_data(doc: &Document, xdp: bool, pdf_name: &str) -> Result<String,
|
||||
/// data element), each with the namespaces it uses declared on it. `Ok(None)`: no datasets
|
||||
/// element; `Err`: the text can't be read.
|
||||
fn datasets_markup(text: &str) -> Result<Option<(String, String)>, ()> {
|
||||
let opts = || crate::xml::ParsingOptions { allow_dtd: false, nodes_limit: MAX_NODES, ..Default::default() };
|
||||
let opts = || crate::xml::ParsingOptions { allow_dtd: false, nodes_limit: MAX_NODES };
|
||||
if crate::xml_nesting_depth(text) > crate::MAX_XML_DEPTH {
|
||||
return Err(());
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ fn merge(text: &str, within: Within, op: Op, warnings: &mut Vec<String>) -> Merg
|
||||
warnings.push("The XFA data nests XML elements deeper than the reader accepts; the field values were not written to it".into());
|
||||
return Merged::Failed;
|
||||
}
|
||||
let opts = || crate::xml::ParsingOptions { allow_dtd: false, nodes_limit: MAX_NODES, ..Default::default() };
|
||||
let opts = || crate::xml::ParsingOptions { allow_dtd: false, nodes_limit: MAX_NODES };
|
||||
// A packet of an array may use the prefixes the XDP envelope declares: read it inside
|
||||
// an element declaring the usual ones.
|
||||
let wrapped;
|
||||
@@ -465,7 +465,7 @@ pub(super) fn readable(text: &str, within: Within, warnings: &mut Vec<String>) -
|
||||
warnings.push(format!("The XFA data would be larger than {} MB; it was not written", MAX_PACKET_WRITE >> 20));
|
||||
return false;
|
||||
}
|
||||
let opts = || crate::xml::ParsingOptions { allow_dtd: false, nodes_limit: MAX_NODES, ..Default::default() };
|
||||
let opts = || crate::xml::ParsingOptions { allow_dtd: false, nodes_limit: MAX_NODES };
|
||||
let ok = crate::xml::Document::parse_with_options(text, opts()).is_ok()
|
||||
|| (within == Within::Packet && crate::xml::Document::parse_with_options(&format!("{WRAP_OPEN}{text}{WRAP_CLOSE}"), opts()).is_ok());
|
||||
if !ok {
|
||||
|
||||
@@ -17,7 +17,7 @@ pub fn parse_datasets(xdp: &str) -> Option<DataNode> {
|
||||
if crate::xml_nesting_depth(xdp) > crate::MAX_XML_DEPTH {
|
||||
return None;
|
||||
}
|
||||
let opts = crate::xml::ParsingOptions { allow_dtd: false, nodes_limit: MAX_NODES, ..Default::default() };
|
||||
let opts = crate::xml::ParsingOptions { allow_dtd: false, nodes_limit: MAX_NODES };
|
||||
let doc = crate::xml::Document::parse_with_options(xdp, opts).ok()?;
|
||||
let datasets = doc.descendants().find(|n| n.is_element() && n.tag_name().name() == "datasets")?;
|
||||
let data = datasets.children().find(|n| n.is_element() && n.tag_name().name() == "data")?;
|
||||
@@ -33,7 +33,7 @@ pub(super) fn parse_datasets_packet(text: &str) -> Option<DataNode> {
|
||||
if crate::xml_nesting_depth(text) > crate::MAX_XML_DEPTH {
|
||||
return None;
|
||||
}
|
||||
let opts = || crate::xml::ParsingOptions { allow_dtd: false, nodes_limit: MAX_NODES, ..Default::default() };
|
||||
let opts = || crate::xml::ParsingOptions { allow_dtd: false, nodes_limit: MAX_NODES };
|
||||
let wrapped;
|
||||
let doc = match crate::xml::Document::parse_with_options(text, opts()) {
|
||||
Ok(d) => d,
|
||||
|
||||
@@ -169,7 +169,7 @@ pub fn decode(data: &[u8]) -> Result<Decoded, String> {
|
||||
}
|
||||
match kind(data) {
|
||||
Some(Kind::Png) => {
|
||||
let opts = craft_image_codecs::DecodeOptions { keep_orientation: true, limits: decode_limits(), ..Default::default() };
|
||||
let opts = craft_image_codecs::DecodeOptions { keep_orientation: true, limits: decode_limits() };
|
||||
let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Png, data, &opts).map_err(|e| match e {
|
||||
craft_image_codecs::CodecError::LimitExceeded(_) => too_big(),
|
||||
other => bad(other.to_string()),
|
||||
@@ -212,7 +212,7 @@ pub fn decode(data: &[u8]) -> Result<Decoded, String> {
|
||||
_ => craft_image_codecs::Format::Tiff,
|
||||
};
|
||||
let data = if k == Kind::Bmp { bmp_with_pixel_offset(data) } else { std::borrow::Cow::Borrowed(data) };
|
||||
let opts = craft_image_codecs::DecodeOptions { keep_orientation: false, limits: decode_limits(), ..Default::default() };
|
||||
let opts = craft_image_codecs::DecodeOptions { keep_orientation: false, limits: decode_limits() };
|
||||
let img = craft_image_codecs::decode_as_with(format, &data, &opts).map_err(|e| match e {
|
||||
craft_image_codecs::CodecError::LimitExceeded(_) => too_big(),
|
||||
other => bad(other.to_string()),
|
||||
|
||||
@@ -1266,7 +1266,7 @@ pub fn parse(xml: &str) -> Result<(Template, Vec<String>), XfaError> {
|
||||
crate::MAX_XML_DEPTH
|
||||
)));
|
||||
}
|
||||
let opts = || crate::xml::ParsingOptions { allow_dtd: false, nodes_limit: MAX_NODES, ..Default::default() };
|
||||
let opts = || crate::xml::ParsingOptions { allow_dtd: false, nodes_limit: MAX_NODES };
|
||||
let doc = crate::xml::Document::parse_with_options(xml, opts()).map_err(|e| XfaError::Malformed(format!("template XML: {e}")))?;
|
||||
let root = doc.root_element();
|
||||
// The XDP's config packet has a <template> element too: the one we want is in the
|
||||
|
||||
@@ -151,7 +151,7 @@ pub fn strip(doc: &mut Document) -> Result<Stripped, XfaError> {
|
||||
}
|
||||
// One XDP: the packets it holds are the envelope's children.
|
||||
let text = s.decoded_within(64 << 20).ok().and_then(|b| crate::packets::decode(&b)).map(|(t, _)| t).unwrap_or_default();
|
||||
let opts = crate::xml::ParsingOptions { allow_dtd: false, nodes_limit: 1_000_000, ..Default::default() };
|
||||
let opts = crate::xml::ParsingOptions { allow_dtd: false, nodes_limit: 1_000_000 };
|
||||
if crate::xml_nesting_depth(&text) <= crate::MAX_XML_DEPTH
|
||||
&& let Ok(parsed) = crate::xml::Document::parse_with_options(&text, opts)
|
||||
{
|
||||
|
||||
@@ -165,9 +165,11 @@ impl Document {
|
||||
}
|
||||
|
||||
pub(crate) fn parse_with_options(text: &str, options: ParsingOptions) -> Result<Self, String> {
|
||||
let mut opts = craft_xml::Options::default();
|
||||
opts.strict = true;
|
||||
opts.doctype = if options.allow_dtd { craft_xml::Doctype::Ignore } else { craft_xml::Doctype::Reject };
|
||||
let mut opts = craft_xml::Options {
|
||||
strict: true,
|
||||
doctype: if options.allow_dtd { craft_xml::Doctype::Ignore } else { craft_xml::Doctype::Reject },
|
||||
..Default::default()
|
||||
};
|
||||
opts.limits.max_nodes = options.nodes_limit as usize;
|
||||
opts.limits.max_depth = crate::MAX_XML_DEPTH;
|
||||
|
||||
|
||||
@@ -86,9 +86,7 @@ pub(crate) fn check_form_xml_depth(text: &str) -> Result<(), DataError> {
|
||||
}
|
||||
|
||||
pub(crate) fn parse_form_xml(text: &str) -> Result<craft_xml::El, craft_xml::Error> {
|
||||
let mut opts = craft_xml::Options::default();
|
||||
opts.strict = true;
|
||||
opts.doctype = craft_xml::Doctype::Reject;
|
||||
let mut opts = craft_xml::Options { strict: true, doctype: craft_xml::Doctype::Reject, ..Default::default() };
|
||||
opts.limits.max_nodes = MAX_NODES as usize;
|
||||
opts.limits.max_depth = MAX_XML_DEPTH.max(1024);
|
||||
opts.parse(text.as_bytes())
|
||||
|
||||
+1
-42
@@ -316,9 +316,7 @@ fn walk_rich_plain(node: &craft_xml::El, out: &mut String) {
|
||||
for n in &node.children {
|
||||
match n {
|
||||
craft_xml::Node::El(el) => {
|
||||
if el.local() == "br" {
|
||||
out.push('\r');
|
||||
} else if matches!(el.local(), "p" | "div" | "li") && !out.is_empty() && !out.ends_with('\r') {
|
||||
if el.local() == "br" || (matches!(el.local(), "p" | "div" | "li") && !out.is_empty() && !out.ends_with('\r')) {
|
||||
out.push('\r');
|
||||
}
|
||||
walk_rich_plain(el, out);
|
||||
@@ -1023,45 +1021,6 @@ fn read_rich_text(rich: &craft_xml::El, ns: &[(String, String)], has_contents: b
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether start tag `tag` (from `<` up to its closing `>`) declares attribute `name` (white
|
||||
/// space may come before the `=`). Attribute values are skipped: `title=" xmlns:b='x'"` declares
|
||||
/// nothing.
|
||||
fn declares(tag: &str, name: &str) -> bool {
|
||||
let mut quote = None;
|
||||
let mut after_space = false;
|
||||
for (i, c) in tag.char_indices() {
|
||||
if let Some(q) = quote {
|
||||
if c == q {
|
||||
quote = None;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if c == '"' || c == '\'' {
|
||||
quote = Some(c);
|
||||
} else if after_space && tag.get(i..).and_then(|rest| rest.strip_prefix(name)).is_some_and(|a| a.trim_start().starts_with('=')) {
|
||||
return true;
|
||||
}
|
||||
after_space = c.is_whitespace();
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Where the start tag at the beginning of `markup` ends: its first `>` outside an attribute
|
||||
/// value (the end of `markup` when there is none).
|
||||
fn start_tag_end(markup: &str) -> usize {
|
||||
let mut quote = None;
|
||||
for (i, c) in markup.char_indices() {
|
||||
match quote {
|
||||
Some(q) if c == q => quote = None,
|
||||
Some(_) => {}
|
||||
None if c == '"' || c == '\'' => quote = Some(c),
|
||||
None if c == '>' => return i,
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
markup.len()
|
||||
}
|
||||
|
||||
/// The one element `markup` (cut out of `rich`, a `<contents-richtext>`) as an XML
|
||||
/// document of its own: the namespaces it inherits from the XFDF around it are declared on it,
|
||||
/// the default one (XHTML declared on `<contents-richtext>`, say; not XFDF's own, which a
|
||||
|
||||
@@ -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
|
||||
Reference in new issue
Block a user