Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

merge: reconcile upstream/main with local changes

Combiler01b31e6b49db44
diff --cc crates/automation/src/lib.rs
index acda47104,ad18f7112..859f96b49
--- a/crates/automation/src/lib.rs
+++ b/crates/automation/src/lib.rs
@@@ -469,19 -504,6 +504,11 @@@ impl Automation
"flip_horizontal" => ImageEdit::Flip { horizontal: true },
"flip_vertical" => ImageEdit::Flip { horizontal: false },
"delete" => ImageEdit::Delete,
+ "bring_to_front" => ImageEdit::Arrange(pdfcraft_engine::ArrangeOrder::BringToFront),
+ "send_to_back" => ImageEdit::Arrange(pdfcraft_engine::ArrangeOrder::SendToBack),
+ "bring_forward" => ImageEdit::Arrange(pdfcraft_engine::ArrangeOrder::BringForward),
+ "send_backward" => ImageEdit::Arrange(pdfcraft_engine::ArrangeOrder::SendBackward),
+ "remove_crop" => ImageEdit::RemoveCrop,
- "crop" => {
- let r: Vec<f64> =
- a.get("rect").and_then(Value::as_array).map(|x| x.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
- let r = <[f64; 4]>::try_from(r).map_err(|_| ToolError::InvalidArgs("crop needs rect: 4 numbers".into()))?;
- let info = &self.doc(&a)?.info.pages[page];
- let (u0, u1) = (info.view_to_user(r[0] as f32, r[1] as f32), info.view_to_user(r[2] as f32, r[3] as f32));
- ImageEdit::Crop([u0[0].min(u1[0]) as f64, u0[1].min(u1[1]) as f64, u0[0].max(u1[0]) as f64, u0[1].max(u1[1]) as f64])
- }
"replace" => {
let path = self.resolve(a.str("path")?, false)?;
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
diff --cc crates/automation/src/tools.rs
index 137cba344,5e89aef78..9c9389f00
--- a/crates/automation/src/tools.rs
+++ b/crates/automation/src/tools.rs
@@@ -1171,7 -1248,7 +1248,7 @@@ pub fn tools() -> Vec<ToolDef>
"doc": doc(),
"page": { "type": "integer", "minimum": 1 },
"image": { "type": "integer", "minimum": 1 },
- "action": { "type": "string", "enum": ["move", "rotate", "flip_horizontal", "flip_vertical", "replace", "delete", "bring_to_front", "send_to_back", "bring_forward", "send_backward", "remove_crop", "crop"] },
- "action": { "type": "string", "enum": ["move", "crop", "rotate", "flip_horizontal", "flip_vertical", "replace", "delete"] },
++ "action": { "type": "string", "enum": ["move", "crop", "rotate", "flip_horizontal", "flip_vertical", "replace", "delete", "bring_to_front", "send_to_back", "bring_forward", "send_backward", "remove_crop"] },
"rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 },
"quarters": { "type": "integer" },
"path": { "type": "string" },
diff --cc crates/automation/tests/automation.rs
index 28ce3e9b7,f45aec3f5..4d9134eb9
--- a/crates/automation/tests/automation.rs
+++ b/crates/automation/tests/automation.rs
@@@ -530,11 -717,11 +717,12 @@@ fn an_in_place_save_reports_a_required_
#[test]
fn a_save_that_does_not_reopen_leaves_the_file_as_it_was() {
let dir = workdir("save-verify-before-write");
-- let objs: [&[u8]; 4] = [
++ let objs: [&[u8]; 5] = [
b"<< /Type /Catalog /Pages 3 0 R >>",
b"<< /Type /Page /MediaBox [0 0 200 300] /Contents 4 0 R >>",
b"[ 0 ]",
b"<< /Length 18 >>\nstream\n0 0 m 100 100 l S\nendstream",
++ b"<< /Type /Page /MediaBox [0 0 200 200] >>",
];
let mut original = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
@@@ -545,11 -732,11 +733,11 @@@
original.extend_from_slice(b"\nendobj\n");
}
let xref = original.len();
-- original.extend_from_slice(b"xref\n0 5\n0000000000 65535 f \n");
++ original.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
for o in offsets {
original.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
-- original.extend_from_slice(format!("trailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n").as_bytes());
++ original.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
std::fs::write(dir.join("damaged.pdf"), &original).unwrap();
let mut a = auto(&dir);
@@@ -2262,18 -2535,14 +2536,24 @@@ fn editing_page_images_through_tools()
assert_eq!(r["undo"], "Move image");
let moved = ok(&mut a, "page_images", json!({ "doc": made, "page": 1 }))["images"][0]["rect"].clone();
assert_eq!(moved, json!([5.0, 5.0, 25.0, 35.0]));
+ // Crop keeps part of it in place: the placement stays, visible_rect says what shows.
+ let r = ok(&mut a, "image_edit", json!({ "doc": made, "page": 1, "image": 1, "action": "crop", "rect": [10, 10, 25, 30] }));
+ assert_eq!(r["undo"], "Crop image");
+ let cropped = ok(&mut a, "page_images", json!({ "doc": made, "page": 1 }))["images"][0].clone();
+ assert_eq!(cropped["rect"], json!([5.0, 5.0, 25.0, 35.0]));
+ assert_eq!(cropped["visible_rect"], json!([10.0, 10.0, 25.0, 30.0]));
ok(&mut a, "image_edit", json!({ "doc": made, "page": 1, "image": 1, "action": "rotate" }));
ok(&mut a, "image_edit", json!({ "doc": made, "page": 1, "image": 1, "action": "flip_horizontal" }));
+ let r = ok(&mut a, "image_edit", json!({ "doc": made, "page": 1, "image": 1, "action": "bring_to_front" }));
+ assert_eq!(r["undo"], "Bring to front");
+ let r = ok(&mut a, "image_edit", json!({ "doc": made, "page": 1, "image": 1, "action": "send_to_back" }));
+ assert_eq!(r["undo"], "Send to back");
+ let r = ok(&mut a, "image_edit", json!({ "doc": made, "page": 1, "image": 1, "action": "bring_forward" }));
+ assert_eq!(r["undo"], "Bring forward");
+ let r = ok(&mut a, "image_edit", json!({ "doc": made, "page": 1, "image": 1, "action": "send_backward" }));
+ assert_eq!(r["undo"], "Send backward");
+ let r = ok(&mut a, "image_edit", json!({ "doc": made, "page": 1, "image": 1, "action": "remove_crop" }));
+ assert_eq!(r["undo"], "Remove crop");
let saved = ok(&mut a, "image_save", json!({ "doc": made, "page": 1, "image": 1, "path": "out/picture" }));
assert_eq!(saved["format"], "png");
assert!(std::fs::read(dir.join("out/picture.png")).unwrap().starts_with(b"\x89PNG"));
@@@ -4095,6 -4502,89 +4513,89 @@@ fn digital_ids_signing_and_validation_t
assert_eq!(ok(&mut a, "sign_list", json!({ "doc": doc }))["signatures"][0]["status"], "unknown");
}
+ /// The decoded text of every visible signature appearance (Helvetica forms) in a signed file.
+ fn signature_appearances(path: &Path) -> String {
+ use pdfcraft_cos::{Document, ObjRef, Object};
+ let doc = Document::open(std::sync::Arc::new(std::fs::read(path).unwrap())).unwrap();
+ let mut text = String::new();
+ for num in doc.object_numbers() {
+ if let Object::Stream(s) = &*doc.get(ObjRef { num, generation: 0 })
+ && s.dict.name(b"Subtype") == Some(b"Form")
+ {
+ let content = String::from_utf8_lossy(&s.decoded().unwrap()).into_owned();
+ if content.contains("/Helv") {
+ text.push_str(&content);
+ }
+ }
+ }
+ text
+ }
+
+ /// `sign_document` takes the words of a visible signature's labels (say, in German) and which
+ /// items it shows, as the interface does. A label the signature's font can't draw is refused,
+ /// naming the label, the character and what is allowed, before anything is written.
+ #[test]
+ fn signing_with_translated_labels_through_tools() {
+ let dir = workdir("signing-labels");
+ let mut a = auto(&dir);
- ok(&mut a, "sign_id_create", json!({ "name": "Ada Lovelace", "key": "p256", "password": "secret1", "path": "ada.p12" }));
++ ok(&mut a, "sign_id_create", json!({ "name": "Ada Lovelace", "key": "p256", "password": "secret12", "path": "ada.p12" }));
+ let open = |a: &mut Automation| ok(a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
+ let doc = open(&mut a);
+ let args = |doc: u64, extra: Value, out: &str| {
- let mut args = json!({ "doc": doc, "id": "ada.p12", "password": "secret1", "page": 1, "rect": [10, 150, 190, 290], "reason": "Genehmigt", "location": "Berlin", "out": out });
++ let mut args = json!({ "doc": doc, "id": "ada.p12", "password": "secret12", "page": 1, "rect": [10, 150, 190, 290], "reason": "Genehmigt", "location": "Berlin", "out": out });
+ for (k, v) in extra.as_object().unwrap() {
+ args[k] = v.clone();
+ }
+ args
+ };
+ for (extra, why, says) in [
+ (
+ json!({ "labels": { "signed_by": "数字签名者" } }),
+ "a label Helvetica can't draw",
+ "labels.signed_by: the standard fonts can't draw \"数\" (U+6570)",
+ ),
+ (json!({ "labels": { "reason": "Причина: " } }), "even one this signature doesn't show", "labels.reason"),
+ (json!({ "labels": { "signer": "Von" } }), "an unknown label", "unknown label \"signer\""),
+ (json!({ "labels": { "date": 1 } }), "not a string", "labels.date must be a string"),
+ (json!({ "labels": "Datum" }), "not an object", "labels must be an object"),
+ (json!({ "labels": { "date": "x".repeat(201) } }), "too long", "longer than 200"),
+ (json!({ "appearance": { "reason": "yes" } }), "not true or false", "appearance.reason must be true or false"),
+ (json!({ "appearance": { "logo": true } }), "an unknown item", "unknown appearance item"),
+ (json!({ "rect": null, "labels": { "date": "Datum: " } }), "labels for an invisible signature", "needs a visible signature"),
+ (json!({ "rect": null, "appearance": { "reason": true } }), "an appearance for an invisible one", "needs a visible signature"),
+ ] {
+ let r = a.call("sign_document", &args(doc, extra, "bad.pdf"));
+ assert!(matches!(&r, Err(ToolError::InvalidArgs(m)) if m.contains(says)), "{why}: {r:?}");
+ }
+ let r = a.call("sign_document", &args(doc, json!({ "labels": { "signed_by": "数字签名者" } }), "bad.pdf"));
+ assert!(matches!(&r, Err(ToolError::InvalidArgs(m)) if m.contains("signed_by label") && m.contains("Western European")), "{r:?}");
+ assert!(!dir.join("bad.pdf").exists(), "nothing is written for a refused call");
+
+ // German labels, with the reason and the location shown: stamped as given.
+ let german = json!({
+ "labels": { "signed_by": "Digital signiert von", "reason": "Grund: ", "location": "Ort: ", "date": "Datum: " },
+ "appearance": { "reason": true, "location": true },
+ });
+ let r = ok(&mut a, "sign_document", args(doc, german, "de.pdf"));
+ assert_eq!(r["signature"]["reason"], "Genehmigt");
+ let stamped = signature_appearances(&dir.join("de.pdf"));
+ // Each line starts with its label (a long one wraps after it).
+ for word in ["(Digital", "(Grund:", "Genehmigt", "(Ort:", "Berlin", "(Datum:"] {
+ assert!(stamped.contains(word), "{word}: {stamped}");
+ }
+ assert!(!stamped.contains("Reason") && !stamped.contains("Date:"), "{stamped}");
+
+ // Labels omitted keep the English; the labels turned off show the values alone.
+ let doc = open(&mut a);
+ ok(&mut a, "sign_document", args(doc, json!({ "labels": { "date": "Datum: " }, "appearance": { "reason": true } }), "mixed.pdf"));
+ let stamped = signature_appearances(&dir.join("mixed.pdf"));
+ assert!(stamped.contains("(Reason:") && stamped.contains("(Datum:") && !stamped.contains("Berlin"), "{stamped}");
+ let doc = open(&mut a);
+ ok(&mut a, "sign_document", args(doc, json!({ "appearance": { "reason": true, "labels": false } }), "bare.pdf"));
+ let stamped = signature_appearances(&dir.join("bare.pdf"));
+ assert!(stamped.contains("(Genehmigt)") && !stamped.contains("Reason") && !stamped.contains("Date"), "{stamped}");
+ }
+
#[test]
fn optimizing_through_tools() {
let dir = workdir("optimize");
diff --cc crates/edit/src/images.rs
index 725900e2b,fb6212588..cd4dbade4
--- a/crates/edit/src/images.rs
+++ b/crates/edit/src/images.rs
@@@ -413,12 -379,6 +417,10 @@@ pub enum ImageChange
/// Draw this image XObject instead, in the same place.
Replace(ObjRef),
Delete,
+ /// Change the stacking order.
+ Arrange(ArrangeOrder),
+ /// Remove any private crop on the image.
+ RemoveCrop,
- /// Crop to a user-space box [x0, y0, x1, y1].
- Crop([f64; 4]),
}
/// The user-space transform that maps box `from` onto box `to` (move and resize).
@@@ -471,784 -444,6 +486,741 @@@ fn clip_matrix(draw: Matrix, cm: Matrix
Some(outer.then(&t).then(&outer.invert()?))
}
+fn is_entire_page_wrapped(ops: &[Op]) -> bool {
+ if ops.len() < 2 || !ops.first().is_some_and(|o| o.is("q")) || !ops.last().is_some_and(|o| o.is("Q")) {
+ return false;
+ }
+ let mut depth: usize = 0;
+ for (i, op) in ops.iter().enumerate() {
+ if op.is("q") {
+ depth = depth.saturating_add(1);
+ } else if op.is("Q") {
+ depth = depth.saturating_sub(1);
+ if depth == 0 && i < ops.len().saturating_sub(1) {
+ return false;
+ }
+ }
+ }
+ depth == 0
+}
+
+fn content_units(ops: &[Op], scan_start: usize, scan_end: usize) -> Vec<std::ops::Range<usize>> {
+ let mut units = Vec::new();
+ let mut i = scan_start;
+ while i < scan_end {
+ let op = match ops.get(i) {
+ Some(o) => o,
+ None => break,
+ };
+ if op.is("q") {
+ let mut depth: usize = 1;
+ let mut j = i.saturating_add(1);
+ while j < scan_end {
+ if let Some(next) = ops.get(j) {
+ if next.is("q") {
+ depth = depth.saturating_add(1);
+ } else if next.is("Q") {
+ depth = depth.saturating_sub(1);
+ if depth == 0 {
+ j = j.saturating_add(1);
+ break;
+ }
+ }
+ }
+ j = j.saturating_add(1);
+ }
+ units.push(i..j);
+ i = j;
+ } else if op.is("BT") {
+ let mut j = i.saturating_add(1);
+ while j < scan_end {
+ if ops.get(j).is_some_and(|o| o.is("ET")) {
+ j = j.saturating_add(1);
+ break;
+ }
+ j = j.saturating_add(1);
+ }
+ units.push(i..j);
+ i = j;
+ } else if op.is("BI") {
+ let mut j = i.saturating_add(1);
+ while j < scan_end {
+ if ops.get(j).is_some_and(|o| o.is("EI")) {
+ j = j.saturating_add(1);
+ break;
+ }
+ j = j.saturating_add(1);
+ }
+ units.push(i..j);
+ i = j;
+ } else if op.is("Do") || op.is("sh") {
+ units.push(i..i.saturating_add(1));
+ i = i.saturating_add(1);
+ } else {
+ let mut j = i;
+ let mut found_end = false;
+ while j < scan_end {
+ let next = match ops.get(j) {
+ Some(o) => o,
+ None => break,
+ };
+ if matches!(next.op.as_slice(), b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" | b"n") {
+ j = j.saturating_add(1);
+ found_end = true;
+ break;
+ } else if j > i && matches!(next.op.as_slice(), b"q" | b"BT" | b"BI" | b"Do" | b"sh") {
+ found_end = true;
+ break;
+ }
+ j = j.saturating_add(1);
+ }
+ let u_end = if found_end { j } else { scan_end };
+ units.push(i..u_end);
+ i = u_end;
+ }
+ }
++ units.retain(|u| {
++ ops.get(u.clone()).is_some_and(|slice| {
++ slice.iter().any(|op| {
++ matches!(
++ op.op.as_slice(),
++ b"Do" | b"sh" | b"BI" | b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" | b"Tj" | b"TJ" | b"'" | b"\""
++ )
++ })
++ })
++ });
+ units
+}
+
+struct ExtractedScopeState {
+ clip_ops: Vec<Op>,
+ state_ops: Vec<Op>,
+}
+
+#[derive(Clone, Debug, Default, PartialEq)]
+struct EffectiveGState {
+ ca: Option<f64>,
+ ca_stroke: Option<f64>,
+ bm: Option<Vec<u8>>,
+ smask: Option<MaskIdentity>,
+}
+
+impl EffectiveGState {
+ fn effective_ca(&self) -> f64 {
+ self.ca.unwrap_or(1.0)
+ }
+
+ fn effective_ca_stroke(&self) -> f64 {
+ self.ca_stroke.unwrap_or(1.0)
+ }
+
+ fn effective_bm(&self) -> &[u8] {
+ self.bm.as_deref().unwrap_or(b"Normal")
+ }
+
+ fn effective_smask(&self) -> Option<&MaskIdentity> {
+ self.smask.as_ref()
+ }
+
+ fn visually_differs(&self, other: &EffectiveGState) -> bool {
+ (self.effective_ca() - other.effective_ca()).abs() > 1e-4
+ || (self.effective_ca_stroke() - other.effective_ca_stroke()).abs() > 1e-4
+ || self.effective_bm() != other.effective_bm()
+ || self.effective_smask() != other.effective_smask()
+ }
+
+ fn merge_dict(&mut self, dict: &Dict, doc: &Document, gs_name: Option<&[u8]>) {
+ if let Some(val) = dict.get(b"ca").map(|v| doc.resolve(v)).and_then(|v| v.as_f64()) {
+ self.ca = Some(val);
+ }
+ if let Some(val) = dict.get(b"CA").map(|v| doc.resolve(v)).and_then(|v| v.as_f64()) {
+ self.ca_stroke = Some(val);
+ }
+ if let Some(bm_obj) = dict.get(b"BM").map(|v| doc.resolve(v)) {
+ if let Some(name) = bm_obj.as_name() {
+ self.bm = Some(name.to_vec());
+ } else if let Some(arr) = bm_obj.as_array()
+ && let Some(first_name) = arr.first().map(|v| doc.resolve(v)).and_then(|v| v.as_name().map(|n| n.to_vec()))
+ {
+ self.bm = Some(first_name);
+ }
+ }
+ if let Some(raw_smask) = dict.get(b"SMask") {
+ let resolved = doc.resolve(raw_smask);
+ if let Some(name) = resolved.as_name() {
+ if name == b"None" {
+ self.smask = None;
+ } else {
+ self.smask = Some(MaskIdentity::Named(name.to_vec()));
+ }
+ } else if let Some(mask_dict) = resolved.as_dict() {
+ if let Some(gr) = mask_dict.get(b"G").and_then(|g| g.as_ref()) {
+ self.smask = Some(MaskIdentity::Group(gr.num, gr.generation));
+ } else if let Some(r) = raw_smask.as_ref() {
+ self.smask = Some(MaskIdentity::Ref(r.num, r.generation));
+ } else if let Some(name) = mask_dict.get(b"Name").map(|n| doc.resolve(n)).and_then(|n| n.as_name().map(|s| s.to_vec())) {
+ self.smask = Some(MaskIdentity::Named(name));
+ } else if let Some(name) = gs_name {
+ self.smask = Some(MaskIdentity::Named(name.to_vec()));
+ } else {
+ self.smask = Some(MaskIdentity::Named(b"CustomMask".to_vec()));
+ }
+ } else if let Some(r) = raw_smask.as_ref() {
+ self.smask = Some(MaskIdentity::Ref(r.num, r.generation));
+ }
+ }
+ }
+}
+
+#[derive(Clone, Default)]
+struct ExtendedGStateTracker {
+ stack: Vec<(EffectiveGState, Vec<(Op, Matrix)>)>,
+ current_state: EffectiveGState,
+ active_gs_ops: Vec<(Op, Matrix)>,
+}
+
+impl ExtendedGStateTracker {
+ fn step(&mut self, op: &Op, ext_gstates: &Dict, doc: &Document, ctm: Matrix) -> Result<(), EditError> {
+ match op.op.as_slice() {
+ b"q" => {
+ if self.stack.len() >= 4096 {
+ return Err(EditError::Invalid("the image graphics state is too deeply nested".into()));
+ }
+ self.stack.push((self.current_state.clone(), self.active_gs_ops.clone()));
+ }
+ b"Q" => {
+ if let Some((prev_state, prev_ops)) = self.stack.pop() {
+ self.current_state = prev_state;
+ self.active_gs_ops = prev_ops;
+ }
+ }
+ b"gs" => {
+ if let Some(name) = op.name(0) {
+ if let Some(dict) = ext_gstates.get(name).map(|v| doc.resolve(v)).and_then(|v| v.as_dict().cloned()) {
+ self.current_state.merge_dict(&dict, doc, Some(name));
+ } else if self.current_state.ca.is_none() {
+ self.current_state.ca = Some(0.5);
+ }
+ self.active_gs_ops.retain(|(o, _)| o.name(0) != Some(name));
+ self.active_gs_ops.push((op.clone(), ctm));
+ }
+ }
+ _ => {}
+ }
+ Ok(())
+ }
+}
+
- fn extract_scope_state(ops: &[Op], start: usize, target: usize) -> Result<Option<ExtractedScopeState>, EditError> {
++fn extract_scope_state(ops: &[Op], start: usize, target: usize, initial_ctm: Matrix) -> Result<Option<ExtractedScopeState>, EditError> {
+ if target >= ops.len() || start > target {
+ return Ok(None);
+ }
+ if start == target {
+ return Ok(Some(ExtractedScopeState { clip_ops: Vec::new(), state_ops: Vec::new() }));
+ }
+ let mut clip_ops = Vec::new();
+ let mut state_ops = Vec::new();
+ let mut pending_path: Vec<Op> = Vec::new();
+ let mut pending_clip = false;
+ let mut active_path = false;
+ let mut depth: usize = 0;
- let mut matrix = Matrix::IDENTITY;
++ let mut matrix = initial_ctm;
+ let mut matrix_at_clip = None;
+
+ let scan_start = if ops.get(start).is_some_and(|o| o.is("q")) { start.saturating_add(1) } else { start };
+
+ for i in scan_start..target {
+ let Some(op) = ops.get(i) else {
+ return Ok(None);
+ };
+ match op.op.as_slice() {
+ b"q" => {
+ if depth >= 4096 {
+ return Err(EditError::Invalid("the image graphics state is too deeply nested".into()));
+ }
+ depth = depth.saturating_add(1);
+ }
+ b"Q" => {
+ if depth == 0 {
+ return Ok(None);
+ }
+ depth = depth.saturating_sub(1);
+ }
+ _ if depth > 0 => {}
+ b"cm" => {
+ if active_path {
+ return Ok(None);
+ }
+ if let Some(m) = op.nums::<6>() {
+ matrix = Matrix(m).then(&matrix);
+ }
+ }
+ b"m" | b"l" | b"c" | b"v" | b"y" | b"re" | b"h" => {
+ active_path = true;
+ pending_path.push(op.clone());
+ }
+ b"W" | b"W*" => {
+ if !active_path {
+ return Ok(None);
+ }
+ pending_clip = true;
+ pending_path.push(op.clone());
+ }
+ b"n" => {
+ if pending_clip {
+ if matrix_at_clip.is_none() {
+ matrix_at_clip = Some(matrix);
+ } else if matrix_at_clip != Some(matrix) {
+ return Ok(None);
+ }
+ clip_ops.extend(std::mem::take(&mut pending_path));
+ clip_ops.push(op.clone());
+ pending_clip = false;
+ active_path = false;
+ } else {
+ pending_path.clear();
+ active_path = false;
+ }
+ }
+ b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" => {
+ if pending_clip {
+ return Ok(None);
+ }
+ pending_path.clear();
+ active_path = false;
+ }
+ b"gs" | b"CS" | b"cs" | b"SC" | b"sc" | b"SCN" | b"scn" | b"G" | b"g" | b"RG" | b"rg" | b"K" | b"k" | b"ri" | b"i" => {
+ state_ops.push(op.clone());
+ }
+ b"BT" => {
+ return Ok(None);
+ }
+ _ => {}
+ }
+ }
+
+ if depth != 0 || active_path || pending_clip {
+ return Ok(None);
+ }
+
+ if !clip_ops.is_empty() && matrix_at_clip != Some(Matrix::IDENTITY) {
+ return Ok(None);
+ }
+
+ Ok(Some(ExtractedScopeState { clip_ops, state_ops }))
+}
+
+/// Change the stacking order of image `index` on `page`.
+pub fn arrange_image(doc: &mut Document, page: usize, index: usize, order: ArrangeOrder) -> Result<(), EditError> {
+ let images = page_images(doc, page)?;
+ let img = images.get(index).cloned().ok_or_else(|| EditError::Invalid(format!("page {} has no image {}", page + 1, index + 1)))?;
+ let p = page_of(doc, page)?;
+ let all = streams(doc, &p.dict);
+ let mut offset = 0_usize;
+ for (_, data) in all.iter().take(img.stream) {
+ offset = offset
+ .checked_add(data.len())
+ .and_then(|n| n.checked_add(1))
+ .ok_or_else(|| EditError::Invalid("the image content is too large".into()))?;
+ }
+ let data = all.get(img.stream).ok_or_else(|| EditError::Invalid("the image stream is missing".into()))?;
+ let op = parse(&data.1).ops.get(img.op).cloned().ok_or_else(|| EditError::Invalid("the image operation is missing".into()))?;
+ let span = offset.checked_add(op.span.start).ok_or_else(|| EditError::Invalid("the image content is too large".into()))?;
+ let pieces = pdfcraft_content::Pieces::join(&all.iter().map(|(_, data)| data.as_slice()).collect::<Vec<_>>());
+ let ops = pieces.parse().ops;
+ let target = ops
+ .iter()
+ .position(|op| op.span.start == span && op.is("Do"))
+ .ok_or_else(|| EditError::Invalid("the image operation could not be located".into()))?;
+
+ let is_wrapped = is_entire_page_wrapped(&ops);
+ let (scan_start, scan_end) = if is_wrapped { (1, ops.len().saturating_sub(1)) } else { (0, ops.len()) };
+ let units = content_units(&ops, scan_start, scan_end);
+ let Some(target_idx) = units.iter().position(|u| u.start <= target && target < u.end) else {
+ return Ok(());
+ };
+ if units.len() <= 1 {
+ return Ok(());
+ }
+
+ let (dest_unit, insert_after) = match order {
+ ArrangeOrder::BringToFront => {
+ if target_idx == units.len().saturating_sub(1) {
+ return Ok(());
+ }
+ let Some(u) = units.last() else { return Ok(()) };
+ (u, true)
+ }
+ ArrangeOrder::SendToBack => {
+ if target_idx == 0 {
+ return Ok(());
+ }
+ let Some(u) = units.first() else { return Ok(()) };
+ (u, false)
+ }
+ ArrangeOrder::BringForward => {
+ if target_idx == units.len().saturating_sub(1) {
+ return Ok(());
+ }
+ let Some(u) = units.get(target_idx.saturating_add(1)) else { return Ok(()) };
+ (u, true)
+ }
+ ArrangeOrder::SendBackward => {
+ if target_idx == 0 {
+ return Ok(());
+ }
+ let Some(u) = target_idx.checked_sub(1).and_then(|i| units.get(i)) else { return Ok(()) };
+ (u, false)
+ }
+ };
+
+ let Some(target_unit) = units.get(target_idx) else { return Ok(()) };
+ let has_other_paint = ops.iter().enumerate().any(|(i, op)| {
+ i >= target_unit.start
+ && i < target_unit.end
+ && i != target
+ && matches!(
+ op.op.as_slice(),
+ b"Do" | b"Tj" | b"TJ" | b"'" | b"\"" | b"sh" | b"BI" | b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*"
+ )
+ });
+
++ let (target_span, scope_start) = if let Ok(Some((sub_start, sub_end, _))) = image_exclusive_scope(&ops, target)
++ && sub_start >= target_unit.start
++ && sub_end < target_unit.end
++ {
++ let start_op = ops.get(sub_start).unwrap_or(&ops[target]);
++ let end_op = ops.get(sub_end).unwrap_or(&ops[target]);
++ (start_op.span.start..end_op.span.end, sub_start)
++ } else if has_other_paint {
++ let target_op = &ops[target];
++ (target_op.span.start..target_op.span.end, target_unit.start)
++ } else {
++ let Some(first_op) = ops.get(target_unit.start) else { return Ok(()) };
++ let Some(last_op) = target_unit.end.checked_sub(1).and_then(|i| ops.get(i)) else { return Ok(()) };
++ (first_op.span.start..last_op.span.end, target_unit.start)
++ };
++
+ let (dest_pos, scan_target) = if insert_after {
+ let Some(op) = dest_unit.end.checked_sub(1).and_then(|i| ops.get(i)) else { return Ok(()) };
+ (op.span.end, dest_unit.end)
+ } else {
+ let Some(op) = ops.get(dest_unit.start) else { return Ok(()) };
+ (op.span.start, dest_unit.start)
+ };
+
+ let res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
+ let ext_gstates = res.get(b"ExtGState").map(|g| doc.resolve(g)).and_then(|g| g.as_dict().cloned()).unwrap_or_default();
+
+ let mut state = ImageState::new(Matrix::IDENTITY, p.crop(doc), Vec::new());
+ let mut tracker = ExtendedGStateTracker::default();
+ let mut source_effective_state = EffectiveGState::default();
+ let mut source_gs_ops = Vec::new();
+ let mut dest_effective_state = EffectiveGState::default();
+ let mut dest_ctm = Matrix::IDENTITY;
++ let mut scope_start_ctm = Matrix::IDENTITY;
+
- let max_scan = scan_target.max(target.saturating_add(1));
++ let max_scan = scan_target.max(target.saturating_add(1)).max(scope_start.saturating_add(1));
+ for (i, op) in ops.iter().enumerate() {
++ if i == scope_start {
++ scope_start_ctm = state.placement.matrix;
++ }
+ if i == target {
+ source_effective_state = tracker.current_state.clone();
+ source_gs_ops = tracker.active_gs_ops.clone();
+ }
+ if i == scan_target {
+ dest_effective_state = tracker.current_state.clone();
+ dest_ctm = state.placement.matrix;
+ }
+ if i >= max_scan {
+ break;
+ }
+ state.apply(op)?;
+ tracker.step(op, &ext_gstates, doc, state.placement.matrix)?;
+ }
+ if scan_target >= ops.len() {
+ dest_effective_state = tracker.current_state.clone();
+ dest_ctm = state.placement.matrix;
+ }
+ if dest_ctm.invert().is_none() {
+ return Err(EditError::Invalid("unsupported graphics state: non-invertible CTM".into()));
+ }
+
- let (target_span, scope_start) = if let Ok(Some((sub_start, sub_end, _))) = image_exclusive_scope(&ops, target)
- && sub_start >= target_unit.start
- && sub_end < target_unit.end
- {
- let start_op = ops.get(sub_start).unwrap_or(&ops[target]);
- let end_op = ops.get(sub_end).unwrap_or(&ops[target]);
- (start_op.span.start..end_op.span.end, sub_start)
- } else if has_other_paint {
- let target_op = &ops[target];
- (target_op.span.start..target_op.span.end, target_unit.start)
- } else {
- let Some(first_op) = ops.get(target_unit.start) else { return Ok(()) };
- let Some(last_op) = target_unit.end.checked_sub(1).and_then(|i| ops.get(i)) else { return Ok(()) };
- (first_op.span.start..last_op.span.end, target_unit.start)
- };
-
+ let is_clipped = (img.visible_rect.is_some() && img.visible_rect != Some(img.rect)) || !img.clips.is_empty();
+
- let extracted = extract_scope_state(&ops, scope_start, target)?;
++ let extracted = extract_scope_state(&ops, scope_start, target, scope_start_ctm)?;
+ let Some(extracted) = extracted else {
+ return Err(EditError::Invalid("unsupported graphics state: unable to cleanly extract image scope state".into()));
+ };
+
+ if is_clipped && extracted.clip_ops.is_empty() {
+ return Err(EditError::Invalid("unsupported graphics state: inherited clipping path cannot be cleanly preserved".into()));
+ }
+
+ let non_gs_ops: Vec<Op> = extracted.state_ops.into_iter().filter(|o| !o.is("gs")).collect();
+
+ let mut reconstructed_state = dest_effective_state.clone();
+ for (op, _) in &source_gs_ops {
+ if let Some(name) = op.name(0) {
+ if let Some(dict) = ext_gstates.get(name).map(|v| doc.resolve(v)).and_then(|v| v.as_dict().cloned()) {
+ reconstructed_state.merge_dict(&dict, doc, Some(name));
+ } else if reconstructed_state.ca.is_none() {
+ reconstructed_state.ca = Some(0.5);
+ }
+ }
+ }
+
+ if reconstructed_state.visually_differs(&source_effective_state) {
+ return Err(EditError::Invalid(
+ "unsupported graphics state: moving the image would alter effective opacity, blend mode, or soft mask".into(),
+ ));
+ }
+
+ let mut unit_ops = Vec::new();
+ unit_ops.push(Op::new("q", vec![]));
+ let mut current_ctm = dest_ctm;
+
+ for (gs_op, target_ctm) in &source_gs_ops {
+ if *target_ctm != current_ctm {
+ let Some(current_inv) = current_ctm.invert() else {
+ return Err(EditError::Invalid("unsupported graphics state: non-invertible CTM".into()));
+ };
+ let delta = target_ctm.then(&current_inv);
+ if !delta.0.iter().all(|v| v.is_finite()) {
+ return Err(EditError::Invalid("unsupported graphics state: invalid transform coordinates".into()));
+ }
+ if delta != Matrix::IDENTITY {
+ unit_ops.push(Op::new("cm", delta.0.map(pdfcraft_content::num).to_vec()));
+ current_ctm = *target_ctm;
+ }
+ }
+ unit_ops.push(gs_op.clone());
+ }
+
+ unit_ops.extend(non_gs_ops);
+
+ if !extracted.clip_ops.is_empty() {
+ if current_ctm != Matrix::IDENTITY {
+ let Some(current_inv) = current_ctm.invert() else {
+ return Err(EditError::Invalid("unsupported graphics state: non-invertible CTM".into()));
+ };
+ unit_ops.push(Op::new("cm", current_inv.0.map(pdfcraft_content::num).to_vec()));
+ }
+ unit_ops.extend(extracted.clip_ops);
+ if Matrix(img.draw_matrix) != Matrix::IDENTITY {
+ unit_ops.push(Op::new("cm", img.draw_matrix.map(pdfcraft_content::num).to_vec()));
+ }
+ } else {
+ if Matrix(img.draw_matrix) != current_ctm {
+ let Some(current_inv) = current_ctm.invert() else {
+ return Err(EditError::Invalid("unsupported graphics state: non-invertible CTM".into()));
+ };
+ let delta = Matrix(img.draw_matrix).then(&current_inv);
+ if !delta.0.iter().all(|v| v.is_finite()) {
+ return Err(EditError::Invalid("unsupported graphics state: invalid transform coordinates".into()));
+ }
+ if delta != Matrix::IDENTITY {
+ unit_ops.push(Op::new("cm", delta.0.map(pdfcraft_content::num).to_vec()));
+ }
+ }
+ }
+ unit_ops.push(ops.get(target).cloned().unwrap_or_else(|| Op::new("Do", vec![Object::name(&img.name)])));
+ unit_ops.push(Op::new("Q", vec![]));
+
+ let mut serialized = Vec::new();
+ serialized.push(b'\n');
+ serialized.extend_from_slice(&serialize_ops(&unit_ops));
+ serialized.push(b'\n');
+
+ let mut edits = Vec::new();
+ if dest_pos >= target_span.end {
+ edits.push((target_span, Vec::new()));
+ edits.push((dest_pos..dest_pos, serialized));
+ } else if dest_pos <= target_span.start {
+ edits.push((dest_pos..dest_pos, serialized));
+ edits.push((target_span, Vec::new()));
+ } else {
+ return Ok(());
+ }
+
+ let changed = pieces.splice(edits);
+ let contents = crate::text::rewritten_contents(doc, &all, changed);
+ doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), contents))?;
+ Ok(())
+}
+
+/// Locate the innermost graphics state scope enclosing only `target` (with no other painting operations).
+/// Returns `Some((start, end, scope_matrix))` where `start` is the index of `q`, `end` is the index of `Q`,
+/// and `scope_matrix` is the CTM in effect immediately before entering that `q`.
+fn image_exclusive_scope(ops: &[Op], target: usize) -> Result<Option<(usize, usize, Matrix)>, EditError> {
+ struct Scope {
+ start: usize,
+ matrix: Matrix,
+ inherited_clip: bool,
+ inherited_path: bool,
+ selected: bool,
+ other_paint: bool,
+ }
+ let mut stack: Vec<Scope> = Vec::new();
+ let mut matrix = Matrix::IDENTITY;
+ let mut clipped = false;
+ let mut path = false;
+ let mut pending_clip = false;
+ let mut text = false;
+ let mut at_image = None;
+ let mut isolated = None;
+ for (index, op) in ops.iter().enumerate() {
+ match op.op.as_slice() {
+ b"q" => {
+ if stack.len() >= 256 {
+ return Err(EditError::Invalid("the image graphics state is too deeply nested".into()));
+ }
+ stack.push(Scope { start: index, matrix, inherited_clip: clipped, inherited_path: path, selected: false, other_paint: false });
+ }
+ b"Q" => {
+ if let Some(scope) = stack.pop() {
+ if scope.selected && !scope.other_paint && !scope.inherited_clip && !scope.inherited_path {
+ isolated.get_or_insert((scope.start, index, scope.matrix));
+ }
+ matrix = scope.matrix;
+ clipped = scope.inherited_clip;
+ }
+ }
+ b"cm" => {
+ if let Some(m) = op.nums::<6>() {
+ matrix = Matrix(m).then(&matrix);
+ }
+ }
+ b"BT" => text = true,
+ b"ET" => text = false,
+ b"m" | b"l" | b"c" | b"v" | b"y" | b"re" => path = true,
+ b"W" | b"W*" => pending_clip = true,
+ _ => {}
+ }
+ if index == target {
+ if text {
+ return Err(EditError::Invalid("an image inside a text object cannot be cropped".into()));
+ }
+ at_image = Some(matrix);
+ for scope in &mut stack {
+ scope.selected = true;
+ }
+ } else if matches!(
+ op.op.as_slice(),
+ b"Do" | b"Tj" | b"TJ" | b"'" | b"\"" | b"sh" | b"BI" | b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*"
+ ) {
+ for scope in &mut stack {
+ scope.other_paint = true;
+ }
+ }
+ if matches!(op.op.as_slice(), b"n" | b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*") {
+ clipped |= pending_clip;
+ pending_clip = false;
+ path = false;
+ }
+ }
+ if at_image.is_none() {
+ return Err(EditError::Invalid("the image operation is missing".into()));
+ }
+ Ok(isolated)
+}
+
+fn extract_image_drawing_ops(ops: &[Op], start: usize, end: usize, scope_matrix: Matrix) -> Vec<Op> {
+ let mut drawing = Vec::new();
+ let mut i = start.saturating_add(1);
+ while i < end {
+ let op = match ops.get(i) {
+ Some(o) => o,
+ None => break,
+ };
+ if op.is("cm")
+ && scope_matrix != Matrix::IDENTITY
+ && let (Some(m), Some(inv)) = (op.nums::<6>(), scope_matrix.invert())
+ && Matrix(m) == inv
- && ops.get(i + 1).is_some_and(|next| next.is("re"))
+ {
- i = i.saturating_add(1);
- continue;
- }
- if op.is("re") {
- i = i.saturating_add(1);
- if ops.get(i).is_some_and(|next| next.is("W") || next.is("W*")) {
- i = i.saturating_add(1);
++ let mut k = i.saturating_add(1);
++ while ops.get(k).is_some_and(|o| matches!(o.op.as_slice(), b"m" | b"l" | b"c" | b"v" | b"y" | b"h" | b"re")) {
++ k = k.saturating_add(1);
+ }
- if ops.get(i).is_some_and(|next| next.is("n")) {
++ if k > i.saturating_add(1)
++ && ops.get(k).is_some_and(|o| matches!(o.op.as_slice(), b"W" | b"W*"))
++ && ops.get(k.saturating_add(1)).is_some_and(|o| o.is("n"))
++ {
+ i = i.saturating_add(1);
++ continue;
+ }
- if scope_matrix != Matrix::IDENTITY
- && ops.get(i).is_some_and(|next| next.is("cm"))
- && let Some(m) = ops.get(i).and_then(|next| next.nums::<6>())
- && Matrix(m) == scope_matrix
++ }
++ if matches!(op.op.as_slice(), b"m" | b"l" | b"c" | b"v" | b"y" | b"h" | b"re") {
++ let mut k = i;
++ while ops.get(k).is_some_and(|o| matches!(o.op.as_slice(), b"m" | b"l" | b"c" | b"v" | b"y" | b"h" | b"re")) {
++ k = k.saturating_add(1);
++ }
++ if k > i
++ && ops.get(k).is_some_and(|o| matches!(o.op.as_slice(), b"W" | b"W*"))
++ && ops.get(k.saturating_add(1)).is_some_and(|o| o.is("n"))
+ {
- i = i.saturating_add(1);
++ i = k.saturating_add(2);
++ if scope_matrix != Matrix::IDENTITY
++ && ops.get(i).is_some_and(|next| next.is("cm"))
++ && let Some(m) = ops.get(i).and_then(|next| next.nums::<6>())
++ && Matrix(m) == scope_matrix
++ {
++ i = i.saturating_add(1);
++ }
++ continue;
+ }
- continue;
+ }
+ drawing.push(op.clone());
+ i = i.saturating_add(1);
+ }
+ drawing
+}
+
+/// Remove any private clipping path / crop on image `index` on `page`.
+pub fn remove_image_crop(doc: &mut Document, page: usize, index: usize) -> Result<(), EditError> {
+ let images = page_images(doc, page)?;
+ let img = images.get(index).cloned().ok_or_else(|| EditError::Invalid(format!("page {} has no image {}", page + 1, index + 1)))?;
+ let p = page_of(doc, page)?;
+ let all = streams(doc, &p.dict);
+ let mut offset = 0_usize;
+ for (_, data) in all.iter().take(img.stream) {
+ offset = offset
+ .checked_add(data.len())
+ .and_then(|n| n.checked_add(1))
+ .ok_or_else(|| EditError::Invalid("the image content is too large".into()))?;
+ }
+ let data = all.get(img.stream).ok_or_else(|| EditError::Invalid("the image stream is missing".into()))?;
+ let op = parse(&data.1).ops.get(img.op).cloned().ok_or_else(|| EditError::Invalid("the image operation is missing".into()))?;
+ let span = offset.checked_add(op.span.start).ok_or_else(|| EditError::Invalid("the image content is too large".into()))?;
+ let pieces = pdfcraft_content::Pieces::join(&all.iter().map(|(_, data)| data.as_slice()).collect::<Vec<_>>());
+ let ops = pieces.parse().ops;
+ let target = ops
+ .iter()
+ .position(|op| op.span.start == span && op.is("Do"))
+ .ok_or_else(|| EditError::Invalid("the image operation could not be located".into()))?;
+ if let Some((start, end, scope_matrix)) = image_exclusive_scope(&ops, target)? {
+ let drawing_ops = extract_image_drawing_ops(&ops, start, end, scope_matrix);
+ let start_op = ops.get(start).ok_or_else(|| EditError::Invalid("the image operation is missing".into()))?;
+ let end_op = ops.get(end).ok_or_else(|| EditError::Invalid("the image operation is missing".into()))?;
+ let range = start_op.span.start..end_op.span.end;
+ let mut unit_ops = Vec::new();
+ unit_ops.push(Op::new("q", vec![]));
+ unit_ops.extend(drawing_ops);
+ unit_ops.push(Op::new("Q", vec![]));
+ let serialized = serialize_ops(&unit_ops);
+ let changed = pieces.splice([(range, serialized)]);
+ let contents = crate::text::rewritten_contents(doc, &all, changed);
+ doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), contents))?;
+ }
+ Ok(())
+}
+
+/// Crop image `index` on `page` to `crop_rect` in user space `[x0, y0, x1, y1]`.
+pub fn crop_image(doc: &mut Document, page: usize, index: usize, crop_rect: [f64; 4]) -> Result<(), EditError> {
- if !crop_rect.iter().all(|v| v.is_finite() && v.abs() <= 1e12) {
- return Err(EditError::Invalid("the crop rectangle coordinates must be finite".into()));
- }
- let (x0, y0) = (crop_rect[0].min(crop_rect[2]), crop_rect[1].min(crop_rect[3]));
- let (w, h) = ((crop_rect[2] - crop_rect[0]).abs(), (crop_rect[3] - crop_rect[1]).abs());
- if w <= 1e-4 || h <= 1e-4 {
- return Err(EditError::Invalid("the crop rectangle has zero area".into()));
- }
- let images = page_images(doc, page)?;
- let img = images.get(index).cloned().ok_or_else(|| EditError::Invalid(format!("page {} has no image {}", page + 1, index + 1)))?;
- let p = page_of(doc, page)?;
- let all = streams(doc, &p.dict);
- let mut offset = 0_usize;
- for (_, data) in all.iter().take(img.stream) {
- offset = offset
- .checked_add(data.len())
- .and_then(|n| n.checked_add(1))
- .ok_or_else(|| EditError::Invalid("the image content is too large".into()))?;
- }
- let data = all.get(img.stream).ok_or_else(|| EditError::Invalid("the image stream is missing".into()))?;
- let op = parse(&data.1).ops.get(img.op).cloned().ok_or_else(|| EditError::Invalid("the image operation is missing".into()))?;
- let span = offset.checked_add(op.span.start).ok_or_else(|| EditError::Invalid("the image content is too large".into()))?;
- let pieces = pdfcraft_content::Pieces::join(&all.iter().map(|(_, data)| data.as_slice()).collect::<Vec<_>>());
- let ops = pieces.parse().ops;
- let target = ops
- .iter()
- .position(|op| op.span.start == span && op.is("Do"))
- .ok_or_else(|| EditError::Invalid("the image operation could not be located".into()))?;
-
- let (start, end, drawing_ops, scope_matrix) = if let Some((start, end, scope_matrix)) = image_exclusive_scope(&ops, target)? {
- let drawing_ops = extract_image_drawing_ops(&ops, start, end, scope_matrix);
- (start, end, drawing_ops, scope_matrix)
- } else {
- let mut state = ImageState::new(Matrix::IDENTITY, p.crop(doc), Vec::new());
- for (i, o) in ops.iter().enumerate() {
- if i == target {
- break;
- }
- state.apply(o)?;
- }
- let scope_matrix = state.placement.matrix;
- let drawing_ops = vec![ops.get(target).cloned().unwrap_or_else(|| Op::new("Do", vec![Object::name(&img.name)]))];
- (target, target, drawing_ops, scope_matrix)
- };
-
- let mut unit_ops = Vec::new();
- unit_ops.push(Op::new("q", vec![]));
- if scope_matrix != Matrix::IDENTITY
- && let Some(inv) = scope_matrix.invert()
- {
- unit_ops.push(Op::new("cm", inv.0.map(pdfcraft_content::num).to_vec()));
- }
- unit_ops.push(Op::new("re", vec![pdfcraft_content::num(x0), pdfcraft_content::num(y0), pdfcraft_content::num(w), pdfcraft_content::num(h)]));
- unit_ops.push(Op::new("W", vec![]));
- unit_ops.push(Op::new("n", vec![]));
- if scope_matrix != Matrix::IDENTITY {
- unit_ops.push(Op::new("cm", scope_matrix.0.map(pdfcraft_content::num).to_vec()));
- }
- unit_ops.extend(drawing_ops);
- unit_ops.push(Op::new("Q", vec![]));
-
- let start_op = ops.get(start).ok_or_else(|| EditError::Invalid("the image operation is missing".into()))?;
- let end_op = ops.get(end).ok_or_else(|| EditError::Invalid("the image operation is missing".into()))?;
- let range = start_op.span.start..end_op.span.end;
- let serialized = serialize_ops(&unit_ops);
- let changed = pieces.splice([(range, serialized)]);
- let contents = crate::text::rewritten_contents(doc, &all, changed);
- doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), contents))?;
- Ok(())
++ change_image(doc, page, index, &ImageChange::Crop(crop_rect))
+}
+
/// Change image `index` (from [`page_images`]) on `page`.
pub fn change_image(doc: &mut Document, page: usize, index: usize, change: &ImageChange) -> Result<(), EditError> {
let images = page_images(doc, page)?;
@@@ -1266,14 -461,8 +1238,14 @@@
ImageChange::Transform(t) => {
return transform_image(doc, &p, &all, &img, *t);
}
+ ImageChange::Arrange(order) => {
+ return arrange_image(doc, page, index, *order);
+ }
+ ImageChange::RemoveCrop => {
+ return remove_image_crop(doc, page, index);
+ }
- ImageChange::Crop(rect) => {
- return crop_image(doc, page, index, *rect);
+ ImageChange::Crop(keep) => {
- return crop_image(doc, &p, &all, &img, *keep);
++ return crop_image_impl(doc, &p, &all, &img, *keep);
}
ImageChange::Replace(r) => {
if img.is_form {
@@@ -1456,6 -659,86 +1442,86 @@@ fn transform_image
Ok(())
}
+ /// Crop: clip the image's drawing to `keep` (user space). The clip goes just inside the scope
+ /// that holds the image and its private crop (or a new `q … Q` around the `Do`), written in
+ /// that scope's coordinates as the box's four corners, so a turned image crops to an upright
+ /// box too and a later transform of the scope moves the crop with the pixels.
-fn crop_image(
++fn crop_image_impl(
+ doc: &mut Document,
+ page: &pdfcraft_model::Page,
+ streams: &[(Object, Vec<u8>)],
+ image: &PageImage,
+ keep: [f64; 4],
+ ) -> Result<(), EditError> {
+ if !keep.iter().all(|v| v.is_finite() && v.abs() <= 1e12) {
+ return Err(EditError::Invalid("the crop box must be finite and no larger than 1e12".into()));
+ }
+ let [x0, y0, x1, y1] = [keep[0].min(keep[2]), keep[1].min(keep[3]), keep[0].max(keep[2]), keep[1].max(keep[3])];
+ if x1 - x0 < 1e-6 || y1 - y0 < 1e-6 {
+ return Err(EditError::Invalid("the crop box has no area".into()));
+ }
+ let mut offset = 0_usize;
+ for (_, data) in streams.iter().take(image.stream) {
+ offset = offset
+ .checked_add(data.len())
+ .and_then(|n| n.checked_add(1))
+ .ok_or_else(|| EditError::Invalid("the image content is too large".into()))?;
+ }
+ let data = streams.get(image.stream).ok_or_else(|| EditError::Invalid("the image stream is missing".into()))?;
+ let op = parse(&data.1).ops.get(image.op).cloned().ok_or_else(|| EditError::Invalid("the image operation is missing".into()))?;
+ let span = offset.checked_add(op.span.start).ok_or_else(|| EditError::Invalid("the image content is too large".into()))?;
+ let pieces = pdfcraft_content::Pieces::join(&streams.iter().map(|(_, data)| data.as_slice()).collect::<Vec<_>>());
+ let ops = pieces.parse().ops;
+ let target = ops
+ .iter()
+ .position(|op| op.span.start == span && op.is("Do"))
+ .ok_or_else(|| EditError::Invalid("the image operation could not be located".into()))?;
+ let (start, end, placement) = image_transform_scope(&ops, target)?.unwrap_or((target, target, Matrix(image.draw_matrix)));
+ let inverse = placement.invert().ok_or_else(|| EditError::Invalid("the image has no area".into()))?;
+ let corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)].map(|(x, y)| inverse.apply(x, y));
+ if !corners.iter().all(|(x, y)| x.is_finite() && y.is_finite() && x.abs() <= 1e12 && y.abs() <= 1e12) {
+ return Err(EditError::Invalid("the crop box is too large for the image's placement".into()));
+ }
+ let clip: Vec<Op> = corners
+ .iter()
+ .enumerate()
+ .map(|(i, (x, y))| Op::new(if i == 0 { "m" } else { "l" }, vec![Object::Real(*x), Object::Real(*y)]))
+ .chain([Op::new("h", vec![]), Op::new("W", vec![]), Op::new("n", vec![])])
+ .collect();
+ // The image's own earlier crop (a clipping path right after the scope's `q`) gives way to
+ // the new one, so a crop can grow again as well as shrink.
+ let old_clip: Option<std::ops::Range<usize>> = (start != end)
+ .then(|| {
+ let mut k = start + 1;
+ while ops.get(k).is_some_and(|o| matches!(o.op.as_slice(), b"m" | b"l" | b"c" | b"v" | b"y" | b"h" | b"re")) {
+ k += 1;
+ }
+ (k > start + 1 && ops.get(k).is_some_and(|o| matches!(o.op.as_slice(), b"W" | b"W*")) && ops.get(k + 1).is_some_and(|o| o.is("n")))
+ .then_some(start + 1..k + 2)
+ })
+ .flatten();
+ let changed = crate::text::splice(&pieces, &ops, |index| {
+ if start == end && index == target {
+ // No scope of its own yet: one around the drawing, with the crop inside.
+ let mut out = vec![Op::new("q", vec![])];
+ out.extend(clip.iter().cloned());
+ out.extend(ops.get(index).cloned());
+ out.push(Op::new("Q", vec![]));
+ (out, false)
+ } else if start != end && index == start + 1 {
+ // Inside the scope's `q`, before whatever it draws (in place of its old crop).
+ (clip.clone(), old_clip.is_none())
+ } else if old_clip.as_ref().is_some_and(|r| r.contains(&index)) {
+ (Vec::new(), false)
+ } else {
+ (Vec::new(), true)
+ }
+ });
+ let contents = crate::text::rewritten_contents(doc, streams, changed);
+ doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), contents))?;
+ Ok(())
+ }
+
/// Plan all transforms before changing a stream; indexes refer to the original inventory.
/// Splice only the chosen Do operators and preserve all other bytes and stream dictionaries.
pub(crate) fn translate_images(doc: &mut Document, page: usize, indexes: &[usize], offset: [f64; 2]) -> Result<(), EditError> {
diff --cc crates/edit/src/lib.rs
index 822a62666,515f17d8d..6e75bc236
--- a/crates/edit/src/lib.rs
+++ b/crates/edit/src/lib.rs
@@@ -623,12 -650,10 +650,13 @@@ pub use objects::{EditableObject, MAX_M
mod flatten;
pub use flatten::{flatten, flatten_fill_sign};
pub mod images;
-pub use images::{ImageChange, PageImage, change_image, page_images, reading_images, rect_to_rect, turn_about_centre};
+pub use images::{
+ ArrangeOrder, ImageChange, MaskIdentity, PageImage, arrange_image, change_image, crop_image, page_images, reading_images, rect_to_rect,
+ remove_image_crop, turn_about_centre,
+};
pub mod bidi;
pub mod indic;
+ mod linebreak;
pub mod text;
pub use text::{
BlockStyle, LineEdit, RangeStyle, TextBlock, TextLine, clear_block, reading_blocks, replace_block, replace_line, rewrite_block, text_blocks,
diff --cc crates/engine/src/lib.rs
index 7a679d4e7,01f162ae7..3df0a908d
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@@ -81,14 -87,8 +87,12 @@@ pub enum ImageEdit
bytes: Arc<Vec<u8>>,
},
Delete,
+ /// Change the stacking order.
+ Arrange(ArrangeOrder),
+ /// Remove any private crop on the image.
+ RemoveCrop,
- /// Crop to this box (user space).
- Crop([f64; 4]),
}
- pub use pdfcraft_fonts::{MAX_SIGNATURE_CHARS, ScriptOutline, script_missing, script_outline};
+ pub use pdfcraft_fonts::{MAX_SIGNATURE_CHARS, ScriptOutline, script_missing, script_outline, undrawable_message};
/// Fill & Sign: `text` in the script font as a typed signature, its left edge at `at` (user
/// space, vertically centred) and `height` points tall. `None` for text with no outlines.
@@@ -1847,12 -1998,6 +2008,11 @@@ impl Edit
ImageEdit::Flip { .. } => "Flip image",
ImageEdit::Replace { .. } => "Replace image",
ImageEdit::Delete => "Delete image",
+ ImageEdit::Arrange(ArrangeOrder::BringToFront) => "Bring to front",
+ ImageEdit::Arrange(ArrangeOrder::SendToBack) => "Send to back",
+ ImageEdit::Arrange(ArrangeOrder::BringForward) => "Bring forward",
+ ImageEdit::Arrange(ArrangeOrder::SendBackward) => "Send backward",
+ ImageEdit::RemoveCrop => "Remove crop",
- ImageEdit::Crop(_) => "Crop image",
}),
Edit::AddHeaderFooter { replace: false, .. } => Label::of("Add header & footer"),
Edit::AddHeaderFooter { .. } => Label::of("Update header & footer"),
@@@ -2349,10 -2510,8 +2525,10 @@@ fn run_edit(doc: &mut pdfcraft_cos::Doc
}
pdfcraft_edit::ImageChange::Replace(embed_image(doc, name, bytes)?.0)
}
+ ImageEdit::Crop(keep) => pdfcraft_edit::ImageChange::Crop(*keep),
ImageEdit::Delete => pdfcraft_edit::ImageChange::Delete,
+ ImageEdit::Arrange(order) => pdfcraft_edit::ImageChange::Arrange(*order),
+ ImageEdit::RemoveCrop => pdfcraft_edit::ImageChange::RemoveCrop,
- ImageEdit::Crop(rect) => pdfcraft_edit::ImageChange::Crop(*rect),
};
pdfcraft_edit::change_image(doc, *page, *index, &c)?;
}
diff --cc crates/ui-egui/src/canvas.rs
index 7623913f4,8bc3a5c7a..0f924cb5a
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@@ -1884,8 -1905,7 +2026,8 @@@ impl DocView
/// The hover popup for an annotation. Replies and Fill & Sign marks (typed text, checks, signatures)
/// show none: they are page content being edited, not comments.
+/// If `display_author_no_comment` is false, highlighted text markup with no comment body shows no popup.
- fn annotation_hover_text(a: &pdfcraft_render::Annotation, display_author_no_comment: bool) -> Option<String> {
+ fn annotation_hover_text(a: &pdfcraft_render::Annotation) -> Option<String> {
if a.in_reply_to.is_some() || a.fill_sign {
return None;
}
@@@ -3242,15 -3407,14 +3531,17 @@@ pub fn document_area(app: &mut PdfCraft
}
return;
}
- if view.comments.selected.is_none() {
- let selected = view.selected_text().is_some_and(|t| !t.is_empty());
- let key = crate::commands::shortcut_label(ui.ctx(), crate::commands::COPY);
- if ui.add_enabled(can_copy && selected, egui::Button::new(tl!("Copy")).shortcut_text(key)).clicked() {
- copy_selected = true;
- ui.close();
- }
- ui.separator();
+ if tool == QuickTool::EditText
++ && ui.ctx().data(|d| d.get_temp::<bool>(resp.id.with("image-menu"))).unwrap_or(false)
+ && let Some(sel) = view.image_selection.clone()
+ {
- crate::edit_text_ui::image_context_menu(ui, view, doc, sel.page, sel.index, can_paste_image, &mut image_action);
++ let images = doc.page_images(sel.page);
++ crate::edit_text_ui::image_context_menu(ui, view, &images, sel.page, sel.index, can_paste_image, &mut image_action);
+ return;
+ }
+ if view.comments.selected.is_some() {
+ canvas_action = comments::context_menu(ui, view, info, prefs, allowed);
+ return;
}
// Over a picture (and no comment): Copy Image, as in Acrobat's page menu.
let mut copy_image = None;
@@@ -3278,14 -3444,7 +3569,14 @@@
ui.separator();
}
}
- canvas_action = comments::context_menu(ui, view, info, prefs, allowed).or(copy_image);
+ let has_copy_image = copy_image.is_some();
+ if copy_image.is_some() {
+ canvas_action = copy_image;
+ }
+ let (page, at) = view.comments.context_at.unwrap_or((view.current, [0.0, 0.0]));
- let can_copy = view.image_selection.is_some() || view.selected_text().is_some() || has_copy_image;
++ let can_copy_items = can_copy && (view.image_selection.is_some() || view.selected_text().is_some() || has_copy_image);
+ let can_paste = can_paste_image;
- default_page_context_menu(ui, page, at, can_copy, can_paste, &mut page_action);
++ default_page_context_menu(ui, page, at, can_copy_items, can_paste, &mut page_action);
});
(wanted, visible_now)
});
@@@ -3547,137 -3726,19 +3861,123 @@@
});
}
match image_action {
- Some(crate::edit_text_ui::ImageAction::Replace(page, i)) => app.replace_page_image_dialog(page, i),
- Some(crate::edit_text_ui::ImageAction::Save(page, i)) => app.save_page_image(page, i),
- Some(crate::edit_text_ui::ImageAction::Copy(page, i)) => app.copy_page_image(page, i),
- Some(crate::edit_text_ui::ImageAction::CopyFile(page, i)) => app.copy_page_image_file(page, i),
- Some(crate::edit_text_ui::ImageAction::Cut(page, i)) => {
- app.cut_page_image(index, page, i);
+ Some(crate::edit_text_ui::ImageAction::Replace(page, index)) => app.replace_page_image_dialog(page, index),
+ Some(crate::edit_text_ui::ImageAction::Save(page, index)) => app.save_page_image(page, index),
+ Some(crate::edit_text_ui::ImageAction::Copy(page, index)) => {
+ app.copy_page_image(page, index);
+ }
+ Some(crate::edit_text_ui::ImageAction::CopyFile(page, index)) => app.copy_page_image_file(page, index),
+ Some(crate::edit_text_ui::ImageAction::Cut(page, image)) => {
+ app.views[index].image_selection = None;
+ app.cut_page_image(page, image);
}
+ Some(crate::edit_text_ui::ImageAction::Paste(page, rect)) => {
+ let offset_rect = [rect[0] + 20.0, rect[1] - 20.0, rect[2] + 20.0, rect[3] - 20.0];
+ app.paste_image(page, Some(offset_rect));
+ }
+ Some(crate::edit_text_ui::ImageAction::DrawFreehand) => {
+ app.quick_tool = crate::QuickTool::Comment(crate::comments::CommentTool::Ink);
+ }
- Some(crate::edit_text_ui::ImageAction::Redact(page, i)) => {
- if let Some(d) = app.session.get(app.views[index].id) {
- let images = d.page_images(page);
- if let Some(img) = images.get(i) {
- let r = img.visible_rect.unwrap_or(img.rect);
- let quad = [r[0], r[1], r[2], r[1], r[2], r[3], r[0], r[3]];
- let author = app.comment_prefs.author.clone();
- app.views[index].pending_edit = Some(app.redact_prefs.mark(page, vec![quad], &author));
- }
- }
- }
- Some(crate::edit_text_ui::ImageAction::CreateLink(page, i)) => {
- if let Some(d) = app.session.get(app.views[index].id) {
- let images = d.page_images(page);
- if let Some(img) = images.get(i) {
- let r = img.visible_rect.unwrap_or(img.rect);
- app.open_link_props(page, Some(r), None);
- }
- }
- }
- Some(crate::edit_text_ui::ImageAction::RecognizeText) => {
- app.dialog = Some(crate::Dialog::RecognizeText);
- }
+ Some(crate::edit_text_ui::ImageAction::Redact(page, index)) => app.redact_page_image(page, index),
+ Some(crate::edit_text_ui::ImageAction::Link(page, index)) => app.link_page_image(page, index),
+ Some(crate::edit_text_ui::ImageAction::Recognize(page)) => app.recognize_text_on_page(page),
+ Some(crate::edit_text_ui::ImageAction::AddComment(page, i)) => {
+ if let Some(d) = app.session.get(app.views[index].id) {
+ let images = d.page_images(page);
+ if let Some(img) = images.get(i) {
+ let r = img.visible_rect.unwrap_or(img.rect);
+ let center = [(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0];
+ app.views[index].comments.context_at = Some((page, center));
+ app.views[index].comments.composer = Some(crate::comments::Composer {
+ page,
+ at: center,
+ kind: crate::comments::ComposerKind::Note,
+ text: String::new(),
+ focus: true,
+ });
+ }
+ }
+ }
+ Some(crate::edit_text_ui::ImageAction::Crop) => {
++ let doc_id = app.views[index].id;
+ if let Some(s) = app.views[index].image_selection.as_mut() {
- s.crop_mode = true;
- s.crop_rect = None;
++ if let Some(d) = app.session.get(doc_id) {
++ let images = d.page_images(s.page);
++ if let Some(im) = images.get(s.index) {
++ s.crop = Some(crate::edit_text_ui::CropMode::new(im.visible_rect.unwrap_or(im.rect)));
++ s.crop_mode = true;
++ s.crop_rect = None;
++ }
++ }
+ }
+ }
+ None => {}
+ }
+ match page_action {
+ Some(PageMenuAction::Copy) => {
+ if let Some(sel) = app.views[index].image_selection.clone() {
+ app.copy_page_image(sel.page, sel.index);
- } else if let Some(text) = app.views[index].selected_text() {
- if let Some(id) = app.views.get(index).map(|v| v.id)
- && app.may_copy(id)
- {
- ui.ctx().copy_text(text);
- }
++ } else if app.views[index].selected_text().is_some() {
++ app.execute("edit.copy");
+ } else if let Some((page, at)) = app.views[index].comments.context_at
+ && let Some(doc) = app.session.get(app.views[index].id)
+ && let Some(image) = doc.page_image_at(page, at)
+ {
+ app.copy_page_image(page, image);
+ }
+ }
+ Some(PageMenuAction::Paste(page, at)) => {
+ app.paste_image_at(page, at);
+ }
+ Some(PageMenuAction::RotateCCW(page)) => {
+ app.views[index].pending_edit = Some(pdfcraft_engine::Edit::RotatePages { pages: vec![page], degrees: -90 });
+ }
+ Some(PageMenuAction::RotateCW(page)) => {
+ app.views[index].pending_edit = Some(pdfcraft_engine::Edit::RotatePages { pages: vec![page], degrees: 90 });
+ }
+ Some(PageMenuAction::Print) => {
+ app.open_print();
+ }
+ Some(PageMenuAction::SelectTool) => {
+ app.quick_tool = QuickTool::Select;
+ }
+ Some(PageMenuAction::HandTool) => {
+ app.quick_tool = QuickTool::Hand;
+ }
+ Some(PageMenuAction::MarqueeZoom) => {
+ app.quick_tool = QuickTool::MarqueeZoom;
+ }
+ Some(PageMenuAction::AddComment(page, at)) => {
+ app.views[index].comments.composer =
+ Some(crate::comments::Composer { page, at, kind: crate::comments::ComposerKind::Note, text: String::new(), focus: true });
+ }
+ Some(PageMenuAction::AddBookmark(_page)) => {
+ app.bookmark_action(crate::panels::BmAction::New);
+ }
+ Some(PageMenuAction::TakeSnapshot) => {
+ app.quick_tool = QuickTool::Snapshot;
+ }
+ Some(PageMenuAction::EditPdf) => {
+ app.quick_tool = QuickTool::EditText;
+ }
+ Some(PageMenuAction::AddText) => {
+ app.quick_tool = QuickTool::AddText;
+ }
+ Some(PageMenuAction::AddImage) => {
+ app.add_image_dialog();
+ }
+ Some(PageMenuAction::DeletePage(page)) => {
+ app.views[index].pending_edit = Some(pdfcraft_engine::Edit::DeletePages { pages: vec![page] });
+ }
+ Some(PageMenuAction::ExportPdf) => {
+ app.dialog = Some(crate::Dialog::Export(crate::export_ui::ExportKind::Image));
+ }
+ Some(PageMenuAction::Find) => {
+ app.views[index].open_find();
+ }
+ Some(PageMenuAction::DocProperties) => {
+ app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Description));
+ }
None => {}
}
if let Some(why) = refused {
@@@ -3731,32 -3803,26 +4042,32 @@@ fn selection_actions
}
let rect = xf.view_rect(last);
if !viewport.intersects(rect) {
- return;
+ return false;
}
- let x = rect.left().clamp(viewport.left() + 8.0, (viewport.right() - 520.0).max(viewport.left() + 8.0));
+ let menu_width = 184.0;
+ let ideal_x = rect.right() - 24.0;
+ let max_x = (viewport.right() - menu_width - 8.0).max(viewport.left() + 8.0);
+ let x = ideal_x.clamp(viewport.left() + 8.0, max_x);
let y = if rect.bottom() + 48.0 < viewport.bottom() { rect.bottom() + 6.0 } else { (rect.top() - 44.0).max(viewport.top() + 6.0) };
let mut chosen = None;
egui::Area::new(egui::Id::new(("text-selection-actions", view.id.0))).order(egui::Order::Foreground).fixed_pos(pos2(x, y)).show(ui.ctx(), |ui| {
- egui::Frame::popup(ui.style()).show(ui, |ui| {
+ egui::Frame::popup(ui.style()).corner_radius(CornerRadius::same(12)).show(ui, |ui| {
+ ui.spacing_mut().item_spacing.x = 2.0;
ui.horizontal(|ui| {
- for (label, action) in [
- (tl!("Add comment"), SelectionAction::Note),
- (tl!("Highlight"), SelectionAction::Markup(comments::CommentTool::Highlight)),
- (tl!("Underline"), SelectionAction::Markup(comments::CommentTool::Underline)),
- (tl!("Strikethrough"), SelectionAction::Markup(comments::CommentTool::StrikeOut)),
- (tl!("Replace text"), SelectionAction::Replace),
- ] {
- if ui.add_enabled(can_comment, egui::Button::new(label)).clicked() {
- chosen = Some(action);
+ ui.add_enabled_ui(can_comment, |ui| {
+ for (icon, tooltip, action) in [
+ ("message-square-plus", tl!("Add comment"), SelectionAction::Note),
+ ("highlighter", tl!("Highlight"), SelectionAction::Markup(comments::CommentTool::Highlight)),
+ ("underline", tl!("Underline"), SelectionAction::Markup(comments::CommentTool::Underline)),
+ ("strikethrough", tl!("Strikethrough"), SelectionAction::Markup(comments::CommentTool::StrikeOut)),
+ ("replace", tl!("Replace text"), SelectionAction::Replace),
+ ] {
+ if icons::button(ui, icon, 26.0, false, tooltip).clicked() {
+ chosen = Some(action);
+ }
}
- }
- if ui.add_enabled(can_copy, egui::Button::new(tl!("Copy"))).clicked() {
+ });
- if icons::button(ui, "copy", 26.0, false, tl!("Copy")).clicked() {
++ if ui.add_enabled_ui(can_copy, |ui| icons::button(ui, "copy", 26.0, false, tl!("Copy"))).inner.clicked() {
chosen = Some(SelectionAction::Copy);
}
});
diff --cc crates/ui-egui/src/content_ui.rs
index c9d020641,5f5ef32f7..c3388912b
--- a/crates/ui-egui/src/content_ui.rs
+++ b/crates/ui-egui/src/content_ui.rs
@@@ -715,21 -730,12 +773,21 @@@ impl crate::PdfCraftApp
}
/// Copy Image: image `index` on `page`, at its own resolution, to the clipboard.
- pub(crate) fn copy_page_image(&mut self, page: usize, index: usize) {
- let Some((_, id)) = self.active_ids() else { return };
+ pub(crate) fn copy_page_image(&mut self, page: usize, index: usize) -> bool {
+ let Some((_, id)) = self.active_ids() else { return false };
if !self.may_copy(id) {
- return;
+ return false;
}
- let Some(pixels) = self.session.get(id).map(|d| d.page_image_rgba(page, index)) else { return false };
+ let img_rect = self.session.get(id).and_then(|d| d.page_images(page).into_iter().nth(index).map(|im| im.rect));
+ self.last_copied_image_rect = img_rect;
+ if let Some(doc) = self.session.get(id)
+ && let Ok((ext, bytes)) = doc.page_image_copy_file(page, index)
+ {
+ let stem = crate::image_pick::safe_name(doc.name.rsplit_once('.').map_or(doc.name.as_str(), |(s, _)| s));
+ let name = format!("{stem} p{} img{}.{ext}", page.saturating_add(1), index.saturating_add(1));
+ self.last_copied_file = Some((name, bytes));
+ }
- let Some(pixels) = self.session.get(id).map(|d| d.page_image_rgba(page, index)) else { return };
++ let Some(pixels) = self.session.get(id).map(|d| d.page_image_rgba(page, index)) else { return false; };
let copied = pixels.and_then(|(w, h, rgba)| {
#[cfg(not(target_arch = "wasm32"))]
if self.system_clipboard {
@@@ -749,132 -761,46 +813,168 @@@
}
}
- /// Cut Image: copy image `index` on `page` to the clipboard, then delete it.
- pub(crate) fn cut_page_image(&mut self, view_idx: usize, page: usize, index: usize) {
- self.copy_page_image(page, index);
- if let Some(view) = self.views.get_mut(view_idx) {
- view.pending_edit = Some(pdfcraft_engine::Edit::EditPageImage { page, index, change: pdfcraft_engine::ImageEdit::Delete });
- view.image_selection = None;
- /// The picture's visible box on its page, in user space.
++/// The picture's visible box on its page, in user space.
+ fn page_image_box(&self, page: usize, index: usize) -> Option<[f64; 4]> {
+ let (_, id) = self.active_ids()?;
+ let image = self.session.get(id)?.page_images(page).into_iter().nth(index)?;
+ Some(image.visible_rect.unwrap_or(image.rect))
+ }
+
+ /// Cut: copy the picture, and only when that worked take it off the page (one undo step).
+ pub(crate) fn cut_page_image(&mut self, page: usize, index: usize) {
+ if self.copy_page_image(page, index) {
+ self.apply_edit(Edit::EditPageImage { page, index, change: pdfcraft_engine::ImageEdit::Delete });
++ for v in &mut self.views {
++ if let Some(sel) = &v.image_selection && sel.page == page && sel.index == index {
++ v.image_selection = None;
++ }
++ }
+ }
+ }
+
+ /// Redact image: a redaction mark over the whole picture. It is applied, like any mark, from
+ /// Redact a PDF.
+ pub(crate) fn redact_page_image(&mut self, page: usize, index: usize) {
+ let Some(rect) = self.page_image_box(page, index) else { return };
+ let author = self.comment_prefs.author.clone();
+ let mark = self.redact_prefs.mark(page, vec![pdfcraft_engine::rect_quad(rect)], &author);
+ if self.apply_edit(mark) {
+ self.notify_tr("The image is marked for redaction. Apply it with Redact a PDF");
}
}
+ /// Create link: the link properties for a new link over the picture.
+ pub(crate) fn link_page_image(&mut self, page: usize, index: usize) {
+ if let Some(rect) = self.page_image_box(page, index) {
+ self.open_link_props(page, Some(rect), None);
+ }
+ }
+
+ /// Recognize text: the Recognize Text dialog, set to this page.
+ pub fn recognize_text_on_page(&mut self, page: usize) {
+ self.ocr_draft.pages = crate::ocr_ui::OcrPages::Range;
+ self.ocr_draft.from = page + 1;
+ self.ocr_draft.to = page + 1;
+ self.dialog = Some(crate::Dialog::RecognizeText);
+ }
+
+ /// Whether there is an image in the in-memory clipboard or system clipboard ready to paste.
+ pub fn can_paste_image(&self) -> bool {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ if self.system_clipboard
+ && let Ok(mut cb) = arboard::Clipboard::new()
+ {
+ return cb.get_image().is_ok();
+ }
+ }
+ self.last_copied_image.is_some() || self.last_copied_file.is_some()
+ }
+
+ /// Paste an image from the clipboard onto `page`.
+ pub fn paste_image(&mut self, page: usize, rect: Option<[f64; 4]>) -> bool {
+ let Some((i, id)) = self.active_ids() else {
+ return false;
+ };
+ if let Some(doc) = self.session.get(id)
+ && !doc.allows_modification()
+ {
+ self.notify_error(tl!("The document's security settings don't allow changes"));
+ return false;
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ let (has_system_cb, os_image) = if self.system_clipboard {
+ if let Ok(mut cb) = arboard::Clipboard::new() {
+ let img_opt = cb.get_image().ok().map(|img| (img.width, img.height, img.bytes.to_vec()));
+ (true, img_opt)
+ } else {
+ (false, None)
+ }
+ } else {
+ (false, None)
+ };
+ #[cfg(target_arch = "wasm32")]
+ let (has_system_cb, os_image): (bool, Option<(usize, usize, Vec<u8>)>) = (false, None);
+
+ let image_data: Option<(String, Vec<u8>)> = if has_system_cb {
+ match os_image {
+ Some((width, height, bytes)) => {
+ let matches_internal = self
+ .last_copied_image
+ .as_ref()
+ .is_some_and(|(w, h, rgba)| *w as usize == width && *h as usize == height && rgba.as_slice() == bytes.as_slice());
+ if matches_internal && let Some((name, file_bytes)) = self.last_copied_file.clone() {
+ Some((name, file_bytes))
+ } else if let Ok(png_bytes) = crate::create_ui::png_from_rgba(width, height, &bytes) {
+ self.last_copied_image = Some((width as u32, height as u32, bytes));
+ self.last_copied_file = Some(("clipboard_image.png".to_string(), png_bytes.clone()));
+ self.last_copied_image_rect = None;
+ Some(("clipboard_image.png".to_string(), png_bytes))
+ } else {
+ None
+ }
+ }
+ // When system clipboard is active and accessible but contains text or non-image data:
+ // Do NOT fall back to stale in-memory cached image!
+ None => None,
+ }
+ } else if let Some((name, bytes)) = self.last_copied_file.clone() {
+ Some((name, bytes))
+ } else if let Some((w, h, rgba)) = self.last_copied_image.clone() {
+ crate::create_ui::png_from_rgba(w as usize, h as usize, &rgba).ok().map(|b| ("pasted_image.png".to_string(), b))
+ } else {
+ None
+ };
+
+ let Some((name, bytes)) = image_data else {
+ self.notify_tr("No image on clipboard to paste");
+ return false;
+ };
+
+ let target_rect = match rect {
+ Some(r) => Some(r),
+ None => {
+ if let Some(src_rect) = self.last_copied_image_rect {
+ let w = src_rect[2] - src_rect[0];
+ let h = src_rect[3] - src_rect[1];
+ let offset_x = 20.0;
+ let offset_y = -20.0;
+ let new_r = [src_rect[0] + offset_x, src_rect[1] + offset_y, src_rect[0] + offset_x + w, src_rect[1] + offset_y + h];
+ self.last_copied_image_rect = Some(new_r);
+ Some(new_r)
+ } else {
+ None
+ }
+ }
+ };
+
+ let before = self.session.get(id).map_or(0, |d| d.page_images(page).len());
+ if self.apply_edit(pdfcraft_engine::Edit::AddImage { page, rect: target_rect, name, bytes: std::sync::Arc::new(bytes) }) {
+ if let Some(v) = self.views.get_mut(i) {
+ v.current = page;
- v.image_selection = Some(crate::edit_text_ui::ImageSelection { page, index: before, crop_mode: false, crop_rect: None, drag: None });
++ v.image_selection = Some(crate::edit_text_ui::ImageSelection { page, index: before, crop_mode: false, crop_rect: None, drag: None, crop: None });
+ }
+ self.quick_tool = crate::QuickTool::EditText;
+ self.notify_tr("Image pasted");
+ true
+ } else {
+ false
+ }
+ }
+
+ /// Paste an image centered at context menu point `at: [f64; 2]` on `page`.
+ pub fn paste_image_at(&mut self, page: usize, at: [f64; 2]) -> bool {
+ let rect = if let Some(src_r) = self.last_copied_image_rect {
+ let w = src_r[2] - src_r[0];
+ let h = src_r[3] - src_r[1];
+ Some([at[0] - w * 0.5, at[1] - h * 0.5, at[0] + w * 0.5, at[1] + h * 0.5])
+ } else {
+ None
+ };
+ self.paste_image(page, rect)
+ }
+
/// Click an image field: pick a picture for it.
pub fn choose_field_image(&mut self, name: &str) {
#[cfg(not(target_arch = "wasm32"))]
diff --cc crates/ui-egui/src/edit_text_ui.rs
index b2563fb24,d8881ba47..7b16bbab8
--- a/crates/ui-egui/src/edit_text_ui.rs
+++ b/crates/ui-egui/src/edit_text_ui.rs
@@@ -97,414 -136,54 +136,415 @@@ impl TextBackground
/// hit-testing still covers every image, so nothing becomes unselectable.
const MAX_OUTLINES: usize = 250;
- /// A paragraph being edited.
- #[derive(Clone, Debug, PartialEq)]
- pub struct LineEditor {
- pub selection: Option<std::ops::Range<usize>>,
- pub font_resource: Option<String>,
- pub page: usize,
- pub block: usize,
- pub text: String,
- original: String,
- rect: Rect,
- /// The original PDF rectangle, in user space. It is converted again each frame so the editor
- /// stays attached while the page is zoomed, scrolled, or rotated.
- source_rect: [f32; 4],
- multiline: bool,
- source: Option<(pdfcraft_engine::TextBlock, Vec<pdfcraft_engine::TextLine>)>,
- pub(crate) fonts: BTreeMap<String, String>,
- /// The draft extends outside the source container; its frame follows the live draft bounds.
- pub overflow: bool,
- /// The initial source container width in screen pixels.
- max_width: f32,
- /// Current screen-space size. Recomputed from the current page transform before painting.
- size: f32,
- focus: bool,
- /// The Format text panel's values, and what the paragraph had (to send only changes).
- pub look: pdfcraft_engine::AddedText,
- look0: pdfcraft_engine::AddedText,
- /// Underline, line spacing (× size; 0 = the paragraph's own), character spacing (pt) and
- /// horizontal scale (%), and what they were.
- pub extras: Extras,
- extras0: Extras,
- }
-
- #[derive(Clone, Copy, Debug, PartialEq)]
- pub struct Extras {
- pub underline: bool,
- pub line_spacing: f64,
- pub paragraph_spacing: f64,
- pub char_spacing: f64,
- pub scale: f64,
- }
-
- impl Default for Extras {
- fn default() -> Self {
- Extras { underline: false, line_spacing: 0.0, paragraph_spacing: 0.0, char_spacing: 0.0, scale: 100.0 }
- }
- }
-
+pub fn is_bulleted(text: &str) -> bool {
+ let mut lines = text.lines();
+ let Some(first) = lines.next() else { return false };
+ first.trim_start().starts_with("• ") || first.trim_start().starts_with("- ")
+}
+
+pub fn is_numbered(text: &str) -> bool {
+ let mut lines = text.lines();
+ let Some(first) = lines.next() else { return false };
+ let t = first.trim_start();
+ let num_end = t.find('.').unwrap_or(0);
+ num_end > 0 && t[..num_end].chars().all(|c| c.is_ascii_digit()) && t[num_end..].starts_with(". ")
+}
+
+pub fn toggle_bullet_list(text: &mut String) -> bool {
+ let lines: Vec<&str> = text.lines().collect();
+ if lines.is_empty() {
+ return false;
+ }
+ let all_bulleted = lines.iter().all(|l| {
+ let t = l.trim_start();
+ t.is_empty() || t.starts_with("• ") || t.starts_with("- ")
+ });
+ let mut new_text = String::with_capacity(text.len() + 16);
+ for (i, line) in lines.iter().enumerate() {
+ if i > 0 {
+ new_text.push('\n');
+ }
+ let trimmed = line.trim_start();
+ if all_bulleted {
+ if let Some(rest) = trimmed.strip_prefix("• ").or_else(|| trimmed.strip_prefix("- ")) {
+ new_text.push_str(rest);
+ } else {
+ new_text.push_str(line);
+ }
+ } else if trimmed.is_empty() || trimmed.starts_with("• ") {
+ new_text.push_str(line);
+ } else {
+ new_text.push_str("• ");
+ new_text.push_str(line);
+ }
+ }
+ if new_text != *text {
+ *text = new_text;
+ true
+ } else {
+ false
+ }
+}
+
+pub fn toggle_numbered_list(text: &mut String) -> bool {
+ let lines: Vec<&str> = text.lines().collect();
+ if lines.is_empty() {
+ return false;
+ }
+ let is_num_line = |l: &str| {
+ let t = l.trim_start();
+ if t.is_empty() {
+ return true;
+ }
+ let dot_idx = t.find('.').unwrap_or(0);
+ dot_idx > 0 && t[..dot_idx].chars().all(|c| c.is_ascii_digit()) && t[dot_idx..].starts_with(". ")
+ };
+ let all_numbered = lines.iter().all(|l| is_num_line(l));
+ let mut new_text = String::with_capacity(text.len() + 16);
+ let mut num = 1;
+ for (i, line) in lines.iter().enumerate() {
+ if i > 0 {
+ new_text.push('\n');
+ }
+ let t = line.trim_start();
+ if all_numbered {
+ if let Some(dot_idx) = t.find('.')
+ && dot_idx > 0
+ && t[..dot_idx].chars().all(|c| c.is_ascii_digit())
+ && t[dot_idx..].starts_with(". ")
+ {
+ new_text.push_str(&t[dot_idx + 2..]);
+ continue;
+ }
+ new_text.push_str(line);
+ } else if t.is_empty() {
+ new_text.push_str(line);
+ } else {
+ use std::fmt::Write as _;
+ let _ = write!(new_text, "{num}. ");
+ new_text.push_str(t);
+ num += 1;
+ }
+ }
+ if new_text != *text {
+ *text = new_text;
+ true
+ } else {
+ false
+ }
+}
+
+pub fn char_to_superscript(c: char) -> char {
+ match c {
+ '0' => '⁰',
+ '1' => '¹',
+ '2' => '²',
+ '3' => '³',
+ '4' => '⁴',
+ '5' => '⁵',
+ '6' => '⁶',
+ '7' => '⁷',
+ '8' => '⁸',
+ '9' => '⁹',
+ '+' => '⁺',
+ '-' | '−' => '⁻',
+ '=' => '⁼',
+ '(' => '⁽',
+ ')' => '⁾',
+ 'a' => 'ᵃ',
+ 'b' => 'ᵇ',
+ 'c' => 'ᶜ',
+ 'd' => 'ᵈ',
+ 'e' => 'ᵉ',
+ 'f' => 'ᶠ',
+ 'g' => 'ᵍ',
+ 'h' => 'ʰ',
+ 'i' => 'ⁱ',
+ 'j' => 'ʲ',
+ 'k' => 'ᵏ',
+ 'l' => 'ˡ',
+ 'm' => 'ᵐ',
+ 'n' => 'ⁿ',
+ 'o' => 'ᵒ',
+ 'p' => 'ᵖ',
+ 'r' => 'ʳ',
+ 's' => 'ˢ',
+ 't' => 'ᵗ',
+ 'u' => 'ᵘ',
+ 'v' => 'ᵛ',
+ 'w' => 'ʷ',
+ 'x' => 'ˣ',
+ 'y' => 'ʸ',
+ 'z' => 'ᶻ',
+ 'A' => 'ᴬ',
+ 'B' => 'ᴮ',
+ 'D' => 'ᴰ',
+ 'E' => 'ᴱ',
+ 'G' => 'ᴳ',
+ 'H' => 'ᴴ',
+ 'I' => 'ᴵ',
+ 'J' => 'ᴶ',
+ 'K' => 'ᴷ',
+ 'L' => 'ᴸ',
+ 'M' => 'ᴹ',
+ 'N' => 'ᴺ',
+ 'O' => 'ᴼ',
+ 'P' => 'ᴾ',
+ 'R' => 'ᴿ',
+ 'T' => 'ᵀ',
+ 'U' => 'ᵁ',
+ 'V' => 'ⱽ',
+ 'W' => 'ᵂ',
+ other => other,
+ }
+}
+
+pub fn char_from_superscript(c: char) -> char {
+ match c {
+ '⁰' => '0',
+ '¹' => '1',
+ '²' => '2',
+ '³' => '3',
+ '⁴' => '4',
+ '⁵' => '5',
+ '⁶' => '6',
+ '⁷' => '7',
+ '⁸' => '8',
+ '⁹' => '9',
+ '⁺' => '+',
+ '⁻' => '-',
+ '⁼' => '=',
+ '⁽' => '(',
+ '⁾' => ')',
+ 'ᵃ' => 'a',
+ 'ᵇ' => 'b',
+ 'ᶜ' => 'c',
+ 'ᵈ' => 'd',
+ 'ᵉ' => 'e',
+ 'ᶠ' => 'f',
+ 'ᵍ' => 'g',
+ 'ʰ' => 'h',
+ 'ⁱ' => 'i',
+ 'ʲ' => 'j',
+ 'ᵏ' => 'k',
+ 'ˡ' => 'l',
+ 'ᵐ' => 'm',
+ 'ⁿ' => 'n',
+ 'ᵒ' => 'o',
+ 'ᵖ' => 'p',
+ 'ʳ' => 'r',
+ 'ˢ' => 's',
+ 'ᵗ' => 't',
+ 'ᵘ' => 'u',
+ 'ᵛ' => 'v',
+ 'ʷ' => 'w',
+ 'ˣ' => 'x',
+ 'ʸ' => 'y',
+ 'ᶻ' => 'z',
+ 'ᴬ' => 'A',
+ 'ᴮ' => 'B',
+ 'ᴰ' => 'D',
+ 'ᴱ' => 'E',
+ 'ᴳ' => 'G',
+ 'ᴴ' => 'H',
+ 'ᴵ' => 'I',
+ 'ᴶ' => 'J',
+ 'ᴷ' => 'K',
+ 'ᴸ' => 'L',
+ 'ᴹ' => 'M',
+ 'ᴺ' => 'N',
+ 'ᴼ' => 'O',
+ 'ᴾ' => 'P',
+ 'ᴿ' => 'R',
+ 'ᵀ' => 'T',
+ 'ᵁ' => 'U',
+ 'ⱽ' => 'V',
+ 'ᵂ' => 'W',
+ other => other,
+ }
+}
+
+pub fn char_to_subscript(c: char) -> char {
+ match c {
+ '0' => '₀',
+ '1' => '₁',
+ '2' => '₂',
+ '3' => '₃',
+ '4' => '₄',
+ '5' => '₅',
+ '6' => '₆',
+ '7' => '₇',
+ '8' => '₈',
+ '9' => '₉',
+ '+' => '₊',
+ '-' | '−' => '₋',
+ '=' => '₌',
+ '(' => '₍',
+ ')' => '₎',
+ 'a' => 'ₐ',
+ 'e' => 'ₑ',
+ 'h' => 'ₕ',
+ 'i' => 'ᵢ',
+ 'j' => 'ⱼ',
+ 'k' => 'ₖ',
+ 'l' => 'ₗ',
+ 'm' => 'ₘ',
+ 'n' => 'ₙ',
+ 'o' => 'ₒ',
+ 'p' => 'ₚ',
+ 'r' => 'ᵣ',
+ 's' => 'ₛ',
+ 't' => 'ₜ',
+ 'u' => 'ᵤ',
+ 'v' => 'ᵥ',
+ 'x' => 'ₓ',
+ other => other,
+ }
+}
+
+pub fn char_from_subscript(c: char) -> char {
+ match c {
+ '₀' => '0',
+ '₁' => '1',
+ '₂' => '2',
+ '₃' => '3',
+ '₄' => '4',
+ '₅' => '5',
+ '₆' => '6',
+ '₇' => '7',
+ '₈' => '8',
+ '₉' => '9',
+ '₊' => '+',
+ '₋' => '-',
+ '₌' => '=',
+ '₍' => '(',
+ '₎' => ')',
+ 'ₐ' => 'a',
+ 'ₑ' => 'e',
+ 'ₕ' => 'h',
+ 'ᵢ' => 'i',
+ 'ⱼ' => 'j',
+ 'ₖ' => 'k',
+ 'ₗ' => 'l',
+ 'ₘ' => 'm',
+ 'ₙ' => 'n',
+ 'ₒ' => 'o',
+ 'ₚ' => 'p',
+ 'ᵣ' => 'r',
+ 'ₛ' => 's',
+ 'ₜ' => 't',
+ 'ᵤ' => 'u',
+ 'ᵥ' => 'v',
+ 'ₓ' => 'x',
+ other => other,
+ }
+}
+
+fn snap_char_boundaries(s: &str, start: usize, end: usize) -> (usize, usize) {
+ let mut s_idx = start.min(s.len());
+ while s_idx > 0 && !s.is_char_boundary(s_idx) {
+ s_idx -= 1;
+ }
+ let mut e_idx = end.min(s.len());
+ while e_idx < s.len() && !s.is_char_boundary(e_idx) {
+ e_idx += 1;
+ }
+ (s_idx, e_idx)
+}
+
+pub fn toggle_superscript(ed: &mut LineEditor) -> bool {
+ let (s_pos, e_pos) = if let Some(r) = &ed.selection { (r.start.min(ed.text.len()), r.end.min(ed.text.len())) } else { (0, ed.text.len()) };
+ let (start, end) = snap_char_boundaries(&ed.text, s_pos, e_pos);
+ if start >= end {
+ return false;
+ }
+ let target = &ed.text[start..end];
+ let all_sup = target.chars().all(|c| char_from_superscript(c) != c);
+ let converted: String =
+ if all_sup { target.chars().map(char_from_superscript).collect() } else { target.chars().map(char_to_superscript).collect() };
+ if converted != target {
+ let conv_len = converted.len();
+ ed.text.replace_range(start..end, &converted);
+ if ed.selection.is_some() {
+ ed.selection = Some(start..start + conv_len);
+ }
+ true
+ } else {
+ false
+ }
+}
+
+pub fn toggle_subscript(ed: &mut LineEditor) -> bool {
+ let (s_pos, e_pos) = if let Some(r) = &ed.selection { (r.start.min(ed.text.len()), r.end.min(ed.text.len())) } else { (0, ed.text.len()) };
+ let (start, end) = snap_char_boundaries(&ed.text, s_pos, e_pos);
+ if start >= end {
+ return false;
+ }
+ let target = &ed.text[start..end];
+ let all_sub = target.chars().all(|c| char_from_subscript(c) != c);
+ let converted: String = if all_sub { target.chars().map(char_from_subscript).collect() } else { target.chars().map(char_to_subscript).collect() };
+ if converted != target {
+ let conv_len = converted.len();
+ ed.text.replace_range(start..end, &converted);
+ if ed.selection.is_some() {
+ ed.selection = Some(start..start + conv_len);
+ }
+ true
+ } else {
+ false
+ }
+}
+
+/// Underline, value-based line spacing, paragraph spacing, character spacing and horizontal
- /// scale for the paragraph being edited. Returns `true` when something changed.
++
+ /// A paragraph being edited.
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct LineEditor {
+ pub selection: Option<std::ops::Range<usize>>,
+ pub font_resource: Option<String>,
+ pub page: usize,
+ pub block: usize,
+ pub text: String,
+ original: String,
+ rect: Rect,
+ /// The original PDF rectangle, in user space. It is converted again each frame so the editor
+ /// stays attached while the page is zoomed, scrolled, or rotated.
+ source_rect: [f32; 4],
+ multiline: bool,
+ source: Option<(pdfcraft_engine::TextBlock, Vec<pdfcraft_engine::TextLine>)>,
+ pub(crate) fonts: BTreeMap<String, String>,
+ /// The draft extends outside the source container; its frame follows the live draft bounds.
+ pub overflow: bool,
+ /// The initial source container width in screen pixels.
+ max_width: f32,
+ /// Current screen-space size. Recomputed from the current page transform before painting.
+ size: f32,
+ focus: bool,
+ /// The Format text panel's values, and what the paragraph had (to send only changes).
+ pub look: pdfcraft_engine::AddedText,
+ look0: pdfcraft_engine::AddedText,
+ /// Underline, line spacing (× size; 0 = the paragraph's own), character spacing (pt) and
+ /// horizontal scale (%), and what they were.
+ pub extras: Extras,
+ extras0: Extras,
+ }
+
+ #[derive(Clone, Copy, Debug, PartialEq)]
+ pub struct Extras {
+ pub underline: bool,
+ pub line_spacing: f64,
+ pub char_spacing: f64,
+ pub scale: f64,
+ }
+
+ impl Default for Extras {
+ fn default() -> Self {
+ Extras { underline: false, line_spacing: 0.0, char_spacing: 0.0, scale: 100.0 }
+ }
+ }
+
+ /// Underline, line spacing, character spacing and horizontal scale for the paragraph being
+ /// edited (under Format text). Returns `true` when something changed.
pub(crate) fn extras_panel(ui: &mut egui::Ui, e: &mut Extras) -> bool {
let before = *e;
ui.horizontal(|ui| {
@@@ -730,9 -354,177 +742,189 @@@ pub struct ImageDrag
pub struct ImageSelection {
pub page: usize,
pub index: usize,
+ /// Dragging: the start point and, for a corner, the opposite corner (screen).
- drag: Option<(Pos2, Option<Pos2>)>,
++ pub drag: Option<(Pos2, Option<Pos2>)>,
+ /// Crop mode (Acrobat's crop handles): the box kept so far.
+ pub crop: Option<CropMode>,
+ pub crop_mode: bool,
+ pub crop_rect: Option<Rect>,
- pub drag: Option<ImageDrag>,
+ }
+
+ /// Cropping a page image: the handles trim instead of resizing, the part that will go is
+ /// dimmed, Enter or Done applies and Esc or Cancel leaves it.
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct CropMode {
+ /// The box to keep (user space).
+ pub keep: [f64; 4],
+ /// A drag in progress: the grip (0–3 corners, 4–7 edges, 8 the inside), where it started
+ /// and the box then.
+ drag: Option<(usize, Pos2, [f64; 4])>,
+ }
+
+ impl CropMode {
+ pub fn new(keep: [f64; 4]) -> Self {
+ Self { keep, drag: None }
+ }
+ }
+
+ /// The screen boxes of the crop's eight handles: corners, then the top, right, bottom and left
+ /// edge midpoints.
+ fn crop_handles(k: Rect) -> [Pos2; 8] {
+ [k.left_top(), k.right_top(), k.left_bottom(), k.right_bottom(), k.center_top(), k.right_center(), k.center_bottom(), k.left_center()]
+ }
+
+ /// Crop mode for the selected image `i` whose visible frame is `b` (screen). Returns `true`
+ /// (the pointer and keys are the crop's while it lasts).
+ #[allow(clippy::too_many_arguments)]
+ fn crop_input(
+ ui: &egui::Ui,
+ resp: &egui::Response,
+ xf: &PageXform,
+ page: usize,
+ info: &DocInfo,
+ view: &mut DocView,
+ i: usize,
+ b: Rect,
+ allow_interaction: bool,
+ ) -> bool {
+ let painter = ui.painter();
- let Some(mode) = view.image_selection.as_mut().and_then(|s| s.crop.as_mut()) else { return false };
++ let Some(sel) = view.image_selection.as_mut() else { return false };
++ if let Some(rect) = sel.crop_rect
++ && let Some(mode) = sel.crop.as_mut()
++ {
++ mode.keep = user_box(xf, info, page, rect);
++ }
++ let Some(mode) = sel.crop.as_mut() else { return false };
+ let hover_pos = ui.input(|inp| inp.pointer.hover_pos());
+ let keep_screen = |keep: [f64; 4]| xf.user_rect(info, page, keep.map(|v| v as f32)).intersect(b);
+ // A drag in progress moves a grip; the box stays inside the picture and at least 6 px.
+ if allow_interaction
+ && resp.drag_started()
+ && let Some(o) = ui.input(|inp| inp.pointer.press_origin())
+ {
+ let k = keep_screen(mode.keep);
+ let grip = crop_handles(k).iter().position(|h| h.distance(o) < 8.0).or_else(|| k.contains(o).then_some(8));
+ if let Some(g) = grip {
+ mode.drag = Some((g, o, mode.keep));
+ }
+ }
+ if let Some((grip, start, at_start)) = mode.drag
+ && let Some(p) = hover_pos
+ {
+ let d = p - start;
+ let k0 = keep_screen(at_start);
+ let (mut min, mut max) = (k0.min, k0.max);
+ match grip {
+ 0 => {
+ min.x += d.x;
+ min.y += d.y;
+ }
+ 1 => {
+ max.x += d.x;
+ min.y += d.y;
+ }
+ 2 => {
+ min.x += d.x;
+ max.y += d.y;
+ }
+ 3 => {
+ max.x += d.x;
+ max.y += d.y;
+ }
+ 4 => min.y += d.y,
+ 5 => max.x += d.x,
+ 6 => max.y += d.y,
+ 7 => min.x += d.x,
+ _ => {
+ let shift = egui::vec2(d.x.clamp(b.min.x - k0.min.x, b.max.x - k0.max.x), d.y.clamp(b.min.y - k0.min.y, b.max.y - k0.max.y));
+ min += shift;
+ max += shift;
+ }
+ }
+ let (min_w, min_h) = (6.0_f32.min(b.width()), 6.0_f32.min(b.height()));
+ min.x = min.x.clamp(b.min.x, b.max.x - min_w);
+ min.y = min.y.clamp(b.min.y, b.max.y - min_h);
+ max.x = max.x.clamp(min.x + min_w, b.max.x);
+ max.y = max.y.clamp(min.y + min_h, b.max.y);
+ mode.keep = user_box(xf, info, page, Rect::from_min_max(min, max));
+ if resp.drag_stopped() || !ui.input(|inp| inp.pointer.primary_down()) {
+ mode.drag = None;
+ }
+ }
+ let k = keep_screen(mode.keep);
+ // What goes is dimmed; what stays keeps its frame and handles.
+ let dim = Color32::from_black_alpha(96);
+ for r in [
+ Rect::from_min_max(b.min, Pos2::new(b.max.x, k.min.y)),
+ Rect::from_min_max(Pos2::new(b.min.x, k.max.y), b.max),
+ Rect::from_min_max(Pos2::new(b.min.x, k.min.y), Pos2::new(k.min.x, k.max.y)),
+ Rect::from_min_max(Pos2::new(k.max.x, k.min.y), Pos2::new(b.max.x, k.max.y)),
+ ] {
+ if r.is_positive() {
+ painter.rect_filled(r.intersect(xf.rect), CornerRadius::ZERO, dim);
+ }
+ }
+ painter.rect_stroke(k, CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);
+ for h in crop_handles(k) {
+ painter.rect(
+ Rect::from_center_size(h, egui::vec2(8.0, 8.0)),
+ CornerRadius::ZERO,
+ Color32::WHITE,
+ Stroke::new(1.0, ACCENT),
+ egui::StrokeKind::Middle,
+ );
+ }
+ // Done and Cancel, painted under the box (above it near the bottom of the view).
+ let font = egui::FontId::proportional(12.5);
+ let pill = |label: &str, right: f32, y: f32| -> Rect {
+ let w = painter.layout_no_wrap(label.to_string(), font.clone(), Color32::WHITE).size().x + 20.0;
+ Rect::from_min_size(Pos2::new(right - w, y), egui::vec2(w, 22.0))
+ };
+ let y = if k.max.y + 30.0 < xf.rect.max.y { k.max.y + 6.0 } else { k.min.y - 28.0 };
+ let done = pill(tl!("Done"), k.max.x, y);
+ let cancel = pill(tl!("Cancel"), done.min.x - 6.0, y);
+ let t = crate::theme::Tokens::get(ui.ctx());
+ painter.rect_filled(done, CornerRadius::same(11), ACCENT);
+ painter.text(done.center(), egui::Align2::CENTER_CENTER, tl!("Done"), font.clone(), Color32::WHITE);
+ painter.rect(cancel, CornerRadius::same(11), t.panel, Stroke::new(1.0, t.border), egui::StrokeKind::Inside);
+ painter.text(cancel.center(), egui::Align2::CENTER_CENTER, tl!("Cancel"), font, t.text);
+ if let Some(p) = hover_pos {
+ let icon = if let Some(g) = crop_handles(k).iter().position(|h| h.distance(p) < 8.0) {
+ match g {
+ 0 | 3 => egui::CursorIcon::ResizeNwSe,
+ 1 | 2 => egui::CursorIcon::ResizeNeSw,
+ 4 | 6 => egui::CursorIcon::ResizeVertical,
+ _ => egui::CursorIcon::ResizeHorizontal,
+ }
+ } else if done.contains(p) || cancel.contains(p) {
+ egui::CursorIcon::PointingHand
+ } else if k.contains(p) {
+ egui::CursorIcon::Move
+ } else {
+ egui::CursorIcon::Default
+ };
+ ui.ctx().set_cursor_icon(icon);
+ }
+ let clicked = |r: Rect| allow_interaction && resp.clicked() && hover_pos.is_some_and(|p| r.contains(p));
+ let keys = |key: egui::Key| allow_interaction && ui.input(|inp| inp.key_pressed(key)) && !ui.ctx().egui_wants_keyboard_input();
+ if clicked(done) || keys(egui::Key::Enter) {
+ let keep = mode.keep;
+ if let Some(s) = view.image_selection.as_mut() {
+ s.crop = None;
++ s.crop_mode = false;
++ s.crop_rect = None;
+ }
+ if keep_screen(keep) != b {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Crop(keep) });
+ }
+ } else if (clicked(cancel) || keys(egui::Key::Escape))
+ && let Some(s) = view.image_selection.as_mut()
+ {
+ s.crop = None;
++ s.crop_mode = false;
++ s.crop_rect = None;
+ }
+ true
}
impl ImageSelection {
@@@ -826,14 -610,14 +1010,18 @@@ pub(crate) enum ImageAction
Save(usize, usize),
Copy(usize, usize),
CopyFile(usize, usize),
+ /// Copy the picture, then remove it from the page.
Cut(usize, usize),
+ /// Mark the picture for redaction (applied later from Redact a PDF).
+ Redact(usize, usize),
+ /// Create a link over the picture.
+ Link(usize, usize),
+ /// Open Recognize Text for the picture's page.
+ Recognize(usize),
+ Paste(usize, [f64; 4]),
+ DrawFreehand,
- Redact(usize, usize),
- CreateLink(usize, usize),
- RecognizeText,
+ AddComment(usize, usize),
+ Crop,
}
fn user_box(xf: &PageXform, info: &DocInfo, page: usize, r: Rect) -> [f64; 4] {
@@@ -895,132 -679,20 +1083,24 @@@ pub(crate) fn image_input
painter.rect_stroke(b, CornerRadius::ZERO, Stroke::new(1.5, ACCENT.gamma_multiply(0.7)), egui::StrokeKind::Outside);
}
}
- // The selected image: frame, 8 handles (or crop mode), dragging.
+ // The selected image: frame, corner handles, dragging.
if let Some(i) = selected.filter(|i| boxes.get(*i).is_some_and(|b| b.is_positive())) {
let b = boxes[i];
- let is_crop = view.image_selection.as_ref().is_some_and(|s| s.crop_mode);
-
- let handle_pos = |rect: Rect, h: ImageHandle| match h {
- ImageHandle::TopLeft => rect.left_top(),
- ImageHandle::TopCenter => Pos2::new(rect.center().x, rect.top()),
- ImageHandle::TopRight => rect.right_top(),
- ImageHandle::RightCenter => Pos2::new(rect.right(), rect.center().y),
- ImageHandle::BottomRight => rect.right_bottom(),
- ImageHandle::BottomCenter => Pos2::new(rect.center().x, rect.bottom()),
- ImageHandle::BottomLeft => rect.left_bottom(),
- ImageHandle::LeftCenter => Pos2::new(rect.left(), rect.center().y),
- };
- let all_handles = [
- ImageHandle::TopLeft,
- ImageHandle::TopCenter,
- ImageHandle::TopRight,
- ImageHandle::RightCenter,
- ImageHandle::BottomRight,
- ImageHandle::BottomCenter,
- ImageHandle::BottomLeft,
- ImageHandle::LeftCenter,
- ];
- let cursor_for = |h: ImageHandle| match h {
- ImageHandle::TopLeft | ImageHandle::BottomRight => egui::CursorIcon::ResizeNwSe,
- ImageHandle::TopRight | ImageHandle::BottomLeft => egui::CursorIcon::ResizeNeSw,
- ImageHandle::TopCenter | ImageHandle::BottomCenter => egui::CursorIcon::ResizeVertical,
- ImageHandle::LeftCenter | ImageHandle::RightCenter => egui::CursorIcon::ResizeHorizontal,
- };
- let draw_handles = |rect: Rect| {
- for &h in &all_handles {
- let c = handle_pos(rect, h);
- match h {
- ImageHandle::TopLeft | ImageHandle::TopRight | ImageHandle::BottomLeft | ImageHandle::BottomRight => {
- painter.rect(
- Rect::from_center_size(c, egui::vec2(8.0, 8.0)),
- CornerRadius::ZERO,
- Color32::WHITE,
- Stroke::new(1.0, ACCENT),
- egui::StrokeKind::Middle,
- );
- }
- ImageHandle::TopCenter | ImageHandle::BottomCenter => {
- painter.rect(
- Rect::from_center_size(c, egui::vec2(12.0, 6.0)),
- CornerRadius::same(1),
- Color32::WHITE,
- Stroke::new(1.0, ACCENT),
- egui::StrokeKind::Middle,
- );
- }
- ImageHandle::LeftCenter | ImageHandle::RightCenter => {
- painter.rect(
- Rect::from_center_size(c, egui::vec2(6.0, 12.0)),
- CornerRadius::same(1),
- Color32::WHITE,
- Stroke::new(1.0, ACCENT),
- egui::StrokeKind::Middle,
- );
- }
- }
- }
- };
-
- if is_crop {
- let active_crop = view.image_selection.as_ref().and_then(|s| s.crop_rect).unwrap_or(b);
- let shade_color = Color32::from_rgba_unmultiplied(15, 35, 70, 150);
- if active_crop.top() > b.top() {
- painter.rect_filled(Rect::from_min_max(b.min, Pos2::new(b.right(), active_crop.top())), CornerRadius::ZERO, shade_color);
- }
- if active_crop.bottom() < b.bottom() {
- painter.rect_filled(Rect::from_min_max(Pos2::new(b.left(), active_crop.bottom()), b.max), CornerRadius::ZERO, shade_color);
- }
- if active_crop.left() > b.left() {
- painter.rect_filled(
- Rect::from_min_max(Pos2::new(b.left(), active_crop.top()), Pos2::new(active_crop.left(), active_crop.bottom())),
- CornerRadius::ZERO,
- shade_color,
- );
- }
- if active_crop.right() < b.right() {
- painter.rect_filled(
- Rect::from_min_max(Pos2::new(active_crop.right(), active_crop.top()), Pos2::new(b.right(), active_crop.bottom())),
- CornerRadius::ZERO,
- shade_color,
- );
- if view.image_selection.as_ref().is_some_and(|s| s.crop.is_some()) {
++ if view.image_selection.as_ref().is_some_and(|s| s.crop.is_some() || s.crop_mode) {
++ if let Some(s) = view.image_selection.as_mut() && s.crop.is_none() {
++ let rect = images.get(i).and_then(|im| im.visible_rect).unwrap_or(images.get(i).map_or([0.0; 4], |im| im.rect));
++ s.crop = Some(CropMode::new(rect));
+ }
-
- painter.rect_stroke(active_crop, CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);
- let x1 = active_crop.left() + active_crop.width() / 3.0;
- let x2 = active_crop.left() + active_crop.width() * 2.0 / 3.0;
- let y1 = active_crop.top() + active_crop.height() / 3.0;
- let y2 = active_crop.top() + active_crop.height() * 2.0 / 3.0;
- painter
- .line_segment([Pos2::new(x1, active_crop.top()), Pos2::new(x1, active_crop.bottom())], Stroke::new(0.75, ACCENT.gamma_multiply(0.5)));
- painter
- .line_segment([Pos2::new(x2, active_crop.top()), Pos2::new(x2, active_crop.bottom())], Stroke::new(0.75, ACCENT.gamma_multiply(0.5)));
- painter
- .line_segment([Pos2::new(active_crop.left(), y1), Pos2::new(active_crop.right(), y1)], Stroke::new(0.75, ACCENT.gamma_multiply(0.5)));
- painter
- .line_segment([Pos2::new(active_crop.left(), y2), Pos2::new(active_crop.right(), y2)], Stroke::new(0.75, ACCENT.gamma_multiply(0.5)));
-
- let crop_handles = [
- ImageHandle::TopLeft,
- ImageHandle::TopCenter,
- ImageHandle::TopRight,
- ImageHandle::RightCenter,
- ImageHandle::BottomRight,
- ImageHandle::BottomCenter,
- ImageHandle::BottomLeft,
- ImageHandle::LeftCenter,
- ];
- for &h in &crop_handles {
- let c = handle_pos(active_crop, h);
- let sz = match h {
- ImageHandle::TopCenter | ImageHandle::BottomCenter => egui::vec2(16.0, 6.0),
- ImageHandle::LeftCenter | ImageHandle::RightCenter => egui::vec2(6.0, 16.0),
- _ => egui::vec2(10.0, 10.0),
- };
+ return crop_input(ui, resp, xf, page, info, view, i, b, allow_interaction);
+ }
+ let corners = [b.left_top(), b.right_top(), b.left_bottom(), b.right_bottom()];
+ let handles = |rect: Rect| {
+ for c in [rect.left_top(), rect.right_top(), rect.left_bottom(), rect.right_bottom()] {
painter.rect(
- Rect::from_center_size(c, sz),
- CornerRadius::same(1),
+ Rect::from_center_size(c, egui::vec2(8.0, 8.0)),
+ CornerRadius::ZERO,
Color32::WHITE,
- Stroke::new(1.5, ACCENT),
+ Stroke::new(1.0, ACCENT),
egui::StrokeKind::Middle,
);
}
@@@ -1306,26 -802,24 +1210,21 @@@
if !allow_interaction {
return false;
}
+ // An open menu stays drawn wherever the pointer is: most of its items lie outside the picture
+ // (a logo is smaller than its menu), and a menu that is not drawn for a frame cannot be clicked.
+ // Only a menu opened by a right-click on the picture: one opened over text or empty page while
+ // a picture stays selected is the page's own menu.
+ let menu_key = resp.id.with("image-menu");
+ if resp.secondary_clicked() {
+ ui.ctx().data_mut(|d| d.insert_temp(menu_key, false));
+ }
- let mut menu_drawn = false;
- if let Some(sel) = selected
- && resp.context_menu_opened()
- && ui.ctx().data(|d| d.get_temp::<bool>(menu_key)).unwrap_or(false)
- {
- resp.context_menu(|ui| image_menu(ui, page, sel, images, view, action));
- menu_drawn = true;
- }
let Some(p) = hover_pos.filter(|p| xf.rect.contains(*p)) else { return false };
- let Some(hit) = boxes.iter().enumerate().rposition(|(i, b)| b.contains(p) && image_contains(i, p)) else { return false };
+ let Some(hit) = boxes.iter().enumerate().rposition(|(i, b)| b.contains(p) && image_contains(i, p)) else {
- let over_popup = egui::Popup::is_any_open(ui.ctx())
- || resp.context_menu_opened()
- || ui.ctx().is_pointer_over_egui()
- || ui.ctx().egui_wants_pointer_input();
- if (resp.secondary_clicked() || resp.clicked()) && !over_popup {
- if let Some(s) = view.image_selection.as_mut()
- && s.crop_mode
- {
- let img_box = boxes.get(s.index).copied();
- if let Some(crop) = s.crop_rect.filter(|c| img_box.is_some_and(|b| *c != b)) {
- view.pending_edit =
- Some(Edit::EditPageImage { page, index: s.index, change: pdfcraft_engine::ImageEdit::Crop(user_box(xf, info, page, crop)) });
- }
- }
++ if resp.secondary_clicked() || resp.clicked() {
+ view.image_selection = None;
+ }
+ return false;
+ };
if selected != Some(hit) {
painter.rect_stroke(boxes[hit], CornerRadius::ZERO, Stroke::new(1.5, ACCENT.gamma_multiply(0.7)), egui::StrokeKind::Outside);
}
@@@ -1338,153 -832,93 +1237,164 @@@
_ => egui::CursorIcon::PointingHand,
});
if resp.clicked() || resp.secondary_clicked() {
- view.image_selection = Some(ImageSelection { page, index: hit, crop_mode: false, crop_rect: None, drag: None });
- view.image_selection = Some(ImageSelection { page, index: hit, drag: None, crop: None });
++ view.image_selection = Some(ImageSelection { page, index: hit, drag: None, crop: None, crop_mode: false, crop_rect: None });
+ }
+ if resp.secondary_clicked() {
+ ui.ctx().data_mut(|d| d.insert_temp(menu_key, true));
}
- if selected == Some(hit) && !menu_drawn {
- resp.context_menu(|ui| image_menu(ui, page, hit, images, view, action));
- }
true
}
-/// The right-click menu of the picture `hit` (its rotate, flip, replace, copy, cut, redact, link,
-/// recognize and delete items).
-fn image_menu(
+/// The right-click context menu for a selected image matching Adobe Acrobat.
+pub(crate) fn image_context_menu(
ui: &mut egui::Ui,
+ view: &mut DocView,
- doc: &pdfcraft_engine::Document,
++ images: &[pdfcraft_engine::PageImage],
page: usize,
hit: usize,
- images: &[pdfcraft_engine::PageImage],
- view: &mut DocView,
+ can_paste: bool,
action: &mut Option<ImageAction>,
) {
- let images = doc.page_images(page);
+ let Some(img) = images.get(hit) else { return };
use pdfcraft_engine::ImageEdit as E;
- let items: [(&str, Option<E>); 4] = [
- (tl!("Rotate Clockwise"), Some(E::Rotate(1))),
- (tl!("Rotate Counterclockwise"), Some(E::Rotate(3))),
- (tl!("Flip Horizontal"), Some(E::Flip { horizontal: true })),
- (tl!("Flip Vertical"), Some(E::Flip { horizontal: false })),
- ];
- for (label, change) in items {
- if ui.button(label).clicked() {
- view.pending_edit = change.map(|c| Edit::EditPageImage { page, index: hit, change: c });
+
- // Top horizontal icon bar: Comment, Crop, Rotate CCW, Rotate CW, Delete
++ // Top horizontal icon bar: Comment, Crop, Rotate CCW, Rotate CW
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ if crate::icons::button(ui, "message-square", 24.0, false, tl!("Add a sticky note here")).clicked() {
+ *action = Some(ImageAction::AddComment(page, hit));
ui.close();
}
- }
- // Crop: the handles trim instead of resizing until Done.
- if ui.button(tl!("Crop Image")).clicked() {
- if let (Some(s), Some(im)) = (view.image_selection.as_mut(), images.get(hit)) {
- s.crop = Some(CropMode::new(im.visible_rect.unwrap_or(im.rect)));
+ if crate::icons::button(ui, "crop", 24.0, false, tl!("Crop")).clicked() {
+ *action = Some(ImageAction::Crop);
+ if let Some(s) = view.image_selection.as_mut() {
++ let rect = img.visible_rect.unwrap_or(img.rect);
++ s.crop = Some(CropMode::new(rect));
+ s.crop_mode = true;
+ s.crop_rect = None;
+ }
+ ui.close();
+ }
+ if crate::icons::button(ui, "rotate-ccw", 24.0, false, tl!("Rotate Counterclockwise")).clicked() {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Rotate(3) });
+ ui.close();
+ }
+ if crate::icons::button(ui, "rotate-cw", 24.0, false, tl!("Rotate Clockwise")).clicked() {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Rotate(1) });
+ ui.close();
}
- if crate::icons::button(ui, "trash-2", 24.0, false, tl!("Delete")).clicked() {
- view.image_selection = None;
- view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Delete });
- ui.close();
- }
+ });
+
+ ui.separator();
+
+ let raster = !img.is_form;
- if ui.add(egui::Button::new(tl!("Cut")).shortcut_text("Ctrl+X")).clicked() {
++ if ui.button(tl!("Cut Image")).clicked() {
+ *action = Some(ImageAction::Cut(page, hit));
ui.close();
}
- if ui.add(egui::Button::new(tl!("Copy")).shortcut_text("Ctrl+C")).clicked() {
- let cropped = images.get(hit).is_some_and(|im| im.visible_rect.is_some_and(|v| v.iter().zip(im.rect.iter()).any(|(a, b)| (a - b).abs() > 0.01)));
- if ui.add_enabled(cropped, egui::Button::new(tl!("Remove Crop"))).clicked() {
- if let Some(im) = images.get(hit) {
- view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Crop(im.rect) });
- }
++ if ui.button(tl!("Copy Image")).clicked() {
+ *action = Some(ImageAction::Copy(page, hit));
ui.close();
}
- if ui.add_enabled(can_paste, egui::Button::new(tl!("Paste")).shortcut_text("Ctrl+V")).clicked() {
- let raster = images.get(hit).is_some_and(|image| !image.is_form);
- if ui.add_enabled(raster, egui::Button::new(tl!("Replace Image…"))).clicked() {
- *action = Some(ImageAction::Replace(page, hit));
++ if ui.add_enabled(can_paste, egui::Button::new(tl!("Paste"))).clicked() {
+ *action = Some(ImageAction::Paste(page, img.rect));
ui.close();
}
- if ui.add_enabled(raster, egui::Button::new(tl!("Save Image As…"))).clicked() {
- *action = Some(ImageAction::Save(page, hit));
+
+ ui.separator();
+
+ let is_cropped = img.visible_rect.is_some() && img.visible_rect != Some(img.rect);
+ if ui.add_enabled(is_cropped, egui::Button::new(tl!("Remove crop"))).clicked() {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::RemoveCrop });
ui.close();
}
- // Cutting and copying also find the picture inside grouped Form artwork.
- if ui.button(tl!("Cut Image")).clicked() {
- *action = Some(ImageAction::Cut(page, hit));
+
+ if ui.button(tl!("Flip horizontal")).clicked() {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Flip { horizontal: true } });
ui.close();
}
- if ui.button(tl!("Copy Image")).clicked() {
- *action = Some(ImageAction::Copy(page, hit));
+ if ui.button(tl!("Flip vertical")).clicked() {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Flip { horizontal: false } });
ui.close();
}
- if ui.button(tl!("Copy Image in Original Format")).clicked() {
- *action = Some(ImageAction::CopyFile(page, hit));
+
+ ui.menu_button(tl!("Arrange image"), |ui| {
+ let total = images.len();
+ if ui.button(tl!("Bring to front")).clicked() {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Arrange(pdfcraft_engine::ArrangeOrder::BringToFront) });
+ if let Some(s) = view.image_selection.as_mut() {
+ s.index = total.saturating_sub(1);
+ }
+ ui.close();
+ }
+ if ui.button(tl!("Send to back")).clicked() {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Arrange(pdfcraft_engine::ArrangeOrder::SendToBack) });
+ if let Some(s) = view.image_selection.as_mut() {
+ s.index = 0;
+ }
+ ui.close();
+ }
+ if ui.button(tl!("Bring forward")).clicked() {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Arrange(pdfcraft_engine::ArrangeOrder::BringForward) });
+ if let Some(s) = view.image_selection.as_mut() {
+ s.index = (hit + 1).min(total.saturating_sub(1));
+ }
+ ui.close();
+ }
+ if ui.button(tl!("Send backward")).clicked() {
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Arrange(pdfcraft_engine::ArrangeOrder::SendBackward) });
+ if let Some(s) = view.image_selection.as_mut() {
+ s.index = hit.saturating_sub(1);
+ }
+ ui.close();
+ }
+ });
+
+ if ui.add_enabled(raster, egui::Button::new(tl!("Replace image"))).clicked() {
+ *action = Some(ImageAction::Replace(page, hit));
ui.close();
}
++ if ui.add_enabled(raster, egui::Button::new(tl!("Save Image As…"))).clicked() {
++ *action = Some(ImageAction::Save(page, hit));
++ ui.close();
++ }
+
ui.separator();
+
+ if ui.button(tl!("Draw freehand")).clicked() {
+ *action = Some(ImageAction::DrawFreehand);
+ ui.close();
+ }
- if ui.button(tl!("Redact image")).clicked() {
+ if ui.button(tl!("Redact Image")).clicked() {
*action = Some(ImageAction::Redact(page, hit));
ui.close();
}
+ if ui.add_enabled(raster, egui::Button::new(tl!("Export image"))).clicked() {
+ *action = Some(ImageAction::Save(page, hit));
+ ui.close();
+ }
+
+ ui.separator();
+
- if ui.button(tl!("Create link")).clicked() {
- *action = Some(ImageAction::CreateLink(page, hit));
+ if ui.button(tl!("Create Link…")).clicked() {
+ *action = Some(ImageAction::Link(page, hit));
ui.close();
}
+
+ ui.menu_button(tl!("Edit image using"), |ui| {
+ ui.add_enabled(false, egui::Button::new(tl!("Default image editor")));
+ });
+
- if ui.button(tl!("Recognize text")).clicked() {
- *action = Some(ImageAction::RecognizeText);
+ if ui.button(tl!("Recognize Text…")).clicked() {
+ *action = Some(ImageAction::Recognize(page));
+ ui.close();
+ }
++
+ ui.separator();
++
+ if ui.button(tl!("Delete")).clicked() {
+ view.image_selection = None;
+ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Delete });
ui.close();
}
}
@@@ -2016,99 -1546,4 +2022,99 @@@ mod tests
assert_eq!(caret_color_on(Color32::BLACK), Color32::WHITE);
assert_eq!(caret_color_on(DARK_EDITOR_FILL), Color32::WHITE);
}
+
- #[test]
++#[test]
+ fn bullet_list_toggles_and_preserves_content() {
+ let mut text = "First line\nSecond line\n\nThird line".to_string();
+ assert!(!is_bulleted(&text));
+ assert!(toggle_bullet_list(&mut text));
+ assert!(is_bulleted(&text));
+ assert_eq!(text, "• First line\n• Second line\n\n• Third line");
+
+ // Toggling again removes bullets
+ assert!(toggle_bullet_list(&mut text));
+ assert!(!is_bulleted(&text));
+ assert_eq!(text, "First line\nSecond line\n\nThird line");
+ }
+
+ #[test]
+ fn numbered_list_toggles_and_preserves_content() {
+ let mut text = "Item A\nItem B\n\nItem C".to_string();
+ assert!(!is_numbered(&text));
+ assert!(toggle_numbered_list(&mut text));
+ assert!(is_numbered(&text));
+ assert_eq!(text, "1. Item A\n2. Item B\n\n3. Item C");
+
+ // Toggling again removes numbering
+ assert!(toggle_numbered_list(&mut text));
+ assert!(!is_numbered(&text));
+ assert_eq!(text, "Item A\nItem B\n\nItem C");
+ }
+
+ #[test]
+ fn superscript_and_subscript_conversion() {
+ let mut ed = LineEditor {
+ page: 0,
+ block: 0,
+ text: "E = mc2".to_string(),
+ original: "E = mc2".to_string(),
+ rect: egui::Rect::ZERO,
+ source_rect: [0.0; 4],
+ max_width: 100.0,
+ overflow: false,
+ selection: Some(6..7), // selecting '2'
+ font_resource: None,
+ fonts: std::collections::BTreeMap::new(),
+ source: None,
+ multiline: false,
+ size: 12.0,
+ focus: true,
+ look: pdfcraft_engine::AddedText::default(),
+ look0: pdfcraft_engine::AddedText::default(),
+ extras: Extras::default(),
+ extras0: Extras::default(),
+ };
+
+ assert!(toggle_superscript(&mut ed));
+ assert_eq!(ed.text, "E = mc²");
+ // Toggling superscript again returns to normal '2'
+ assert!(toggle_superscript(&mut ed));
+ assert_eq!(ed.text, "E = mc2");
+
+ // Test subscript on H2O
+ ed.text = "H2O".to_string();
+ ed.selection = Some(1..2); // selecting '2'
+ assert!(toggle_subscript(&mut ed));
+ assert_eq!(ed.text, "H₂O");
+ assert!(toggle_subscript(&mut ed));
+ assert_eq!(ed.text, "H2O");
+ }
+
+ #[test]
+ fn value_based_line_spacing_in_style() {
+ let ed = LineEditor {
+ page: 0,
+ block: 0,
+ text: "Paragraph text".to_string(),
+ original: "Paragraph text".to_string(),
+ rect: egui::Rect::ZERO,
+ source_rect: [0.0; 4],
+ max_width: 100.0,
+ overflow: false,
+ selection: None,
+ font_resource: None,
+ fonts: std::collections::BTreeMap::new(),
+ source: None,
+ multiline: false,
+ size: 12.0,
+ focus: true,
+ look: pdfcraft_engine::AddedText::default(),
+ look0: pdfcraft_engine::AddedText::default(),
+ extras: Extras { line_spacing: 1.33, underline: true, ..Default::default() },
+ extras0: Extras::default(),
+ };
+ let style = ed.style();
+ assert_eq!(style.line_spacing, Some(1.33));
+ assert_eq!(style.underline, Some(true));
+ }
}
diff --cc crates/ui-egui/src/lib.rs
index 2535adae8,d101d812e..1050dbda3
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@@ -6,8 -6,13 +6,14 @@@
//! `pdfcraft-engine`.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
+#![recursion_limit = "256"]
+ /// Whether `a` and `b` name the same file: equal, or equal once made absolute against the
+ /// current directory (links are not resolved, as in `last_session`).
+ pub(crate) fn same_file(a: &str, b: &str) -> bool {
+ a == b || matches!((std::path::absolute(a), std::path::absolute(b)), (Ok(x), Ok(y)) if x == y)
+ }
+
/// Translate an English UI string into the current language (see [`i18n`]).
macro_rules! tl {
($s:expr) => {
@@@ -73,8 -78,8 +79,8 @@@ mod autoscroll
mod bidi;
pub mod bulk_fields;
mod dialogs;
-mod edit_text_ui;
-pub use edit_text_ui::CropMode;
+pub mod edit_text_ui;
- pub use edit_text_ui::{DragTarget, ImageDrag, ImageHandle, ImageSelection};
++pub use edit_text_ui::{CropMode, DragTarget, ImageDrag, ImageHandle, ImageSelection};
mod editing;
#[cfg(not(target_arch = "wasm32"))]
pub mod file_watch;
@@@ -2318,8 -2380,8 +2443,10 @@@ impl PdfCraftApp
if let Some(author) = v["author"].as_str().map(str::trim).filter(|a| !a.is_empty()) {
self.comment_prefs.author = author.chars().take(MAX_AUTHOR_CHARS).collect();
}
- if let Some(display) = v["display_author_hover_no_comment"].as_bool() {
- self.comment_prefs.display_author_hover_no_comment = display;
+ if let Some(hide) = v["hide_empty_highlight_hover"].as_bool() {
+ self.comment_prefs.hide_empty_highlight_hover = hide;
++ } else if let Some(display) = v["display_author_hover_no_comment"].as_bool() {
++ self.comment_prefs.hide_empty_highlight_hover = !display;
}
// Per-tool comment styles (#340): each field goes through its clamping setter, so a
// malformed or hostile entry is clamped or ignored rather than trusted.
@@@ -2623,13 -2692,13 +2757,20 @@@
};
}
("author", _) => self.comment_prefs.author = value.to_string(),
- ("display-author-hover-no-comment", _) => {
- self.comment_prefs.display_author_hover_no_comment = match value {
+ ("hide-empty-highlight-hover", _) => {
+ self.comment_prefs.hide_empty_highlight_hover = match value {
"true" => true,
"false" => false,
+ _ => return Err("hide-empty-highlight-hover must be true or false".into()),
+ };
+ }
++ ("display-author-hover-no-comment", _) => {
++ self.comment_prefs.hide_empty_highlight_hover = match value {
++ "true" => false,
++ "false" => true,
+ _ => return Err("display-author-hover-no-comment must be true or false".into()),
+ };
+ }
("ui-scale", _) => self.ui_scale = ui_scale::parse(value)?,
("system-title-bar", _) => {
self.system_title_bar = match value {
@@@ -2744,8 -2813,8 +2885,8 @@@
{
object_ui::nudge_keys(ctx, &mut self.views[i], doc);
}
- canvas::shortcuts(&mut self.views[i], ctx);
+ canvas::shortcuts(&mut self.views[i], ctx, self.scroll_speed);
- self.copy_key(i, ctx);
+ self.clipboard_keys(i, ctx);
self.image_pick_keys(i, ctx);
}
}
@@@ -2769,45 -2838,28 +2910,56 @@@ impl PdfCraftApp
false
}
- /// ⌘C copies the selected text, unless a text field has the keyboard (it copies its own).
- fn copy_key(&mut self, i: usize, ctx: &egui::Context) {
- // ⌘C arrives as a Copy event on most platforms.
- let copy = ctx.input(|input| input.events.iter().any(|e| matches!(e, egui::Event::Copy)));
- if !copy || ctx.egui_wants_keyboard_input() {
+ /// ⌘C / ⌘X / ⌘V copy, cut and paste text or images on canvas (unless a text field has focus).
+ fn clipboard_keys(&mut self, i: usize, ctx: &egui::Context) {
+ use egui::{Key, KeyboardShortcut, Modifiers};
+ if ctx.egui_wants_keyboard_input() || self.views.get(i).is_some_and(|v| v.forms.focus.is_some() || v.organize) {
return;
}
- self.copy_selected_text(i, ctx);
+ let copy = ctx.input(|input| input.events.iter().any(|e| matches!(e, egui::Event::Copy)))
+ || ctx.input_mut(|input| input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::C)));
+ let cut = ctx.input(|input| input.events.iter().any(|e| matches!(e, egui::Event::Cut)))
+ || ctx.input_mut(|input| input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::X)));
+ let paste = ctx.input(|input| input.events.iter().any(|e| matches!(e, egui::Event::Paste(_))))
+ || ctx.input_mut(|input| input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::V)));
+
+ if copy {
- if let Some(text) = self.views.get(i).and_then(|v| v.selected_text())
- && let Some(id) = self.views.get(i).map(|v| v.id)
- && self.may_copy(id)
- {
- ctx.copy_text(text);
- } else if let Some(sel) = self.views.get(i).and_then(|v| v.image_selection.clone())
++ if !self.copy_selected_text(i, ctx)
++ && let Some(sel) = self.views.get(i).and_then(|v| v.image_selection.clone())
+ && let Some(id) = self.views.get(i).map(|v| v.id)
+ && self.may_copy(id)
+ {
+ self.copy_page_image(sel.page, sel.index);
+ }
+ }
+ if cut
+ && let Some(sel) = self.views.get(i).and_then(|v| v.image_selection.clone())
+ && let Some(id) = self.views.get(i).map(|v| v.id)
+ && self.may_copy(id)
+ {
- self.cut_page_image(i, sel.page, sel.index);
++ if let Some(v) = self.views.get_mut(i) {
++ v.image_selection = None;
++ }
++ self.cut_page_image(sel.page, sel.index);
+ }
+ if paste {
+ let page = self.views.get(i).map_or(0, |v| v.current);
+ self.paste_image(page, None);
+ }
}
+ /// Shared permission gate for copying selected page text from menus and keyboard events.
+ pub(crate) fn copy_selected_text(&mut self, i: usize, ctx: &egui::Context) -> bool {
+ let Some((id, text)) = self.views.get(i).and_then(|v| Some((v.id, v.selected_text()?))).filter(|(_, text)| !text.is_empty()) else {
+ return false;
+ };
+ if !self.may_copy(id) {
+ return false;
+ }
+ ctx.copy_text(text);
+ true
+ }
+
/// The quick tools' keys, as in Acrobat: V selects, H pans, and holding Space pans until it
/// is released. Plain letters, so not while a text field, a form field, a dialog or the
/// palette has the keyboard.
diff --cc crates/ui-egui/src/panels.rs
index 71e6e14e0,92071c249..23871e68e
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@@ -383,161 -381,41 +414,157 @@@ fn format_section(app: &mut PdfCraftApp
let mut ed = ed;
let mut changed = false;
let font_choices = app.session.get(app.views[i].id).map(|d| d.text_editor_fonts(ed.page)).unwrap_or_default();
- egui::ComboBox::from_id_salt("document-font-resource")
- .selected_text(
- ed.font_resource
- .as_ref()
- .and_then(|r| font_choices.iter().find(|f| &f.resource == r))
- .map_or(tl!("Keep source fonts"), |f| f.face.as_str()),
- )
- .show_ui(ui, |ui| {
- changed |= ui.selectable_value(&mut ed.font_resource, None, tl!("Keep source fonts")).changed();
- for font in font_choices.iter().filter(|f| !f.resource.starts_with("PCApproved")) {
- changed |= ui.selectable_value(&mut ed.font_resource, Some(font.resource.clone()), &font.face).changed();
+ let current_font_label = if let Some(r) = ed.font_resource.as_ref() {
+ font_choices.iter().find(|f| &f.resource == r).map_or_else(|| r.clone(), |f| f.face.clone())
+ } else if ed.look.family != pdfcraft_engine::FontFamily::Helvetica {
+ ed.look.family.label().to_string()
+ } else {
+ tl!("Keep source fonts").to_string()
+ };
+
+ crate::widgets::section_title(ui, tl!("FORMAT TEXT"));
+ egui::ComboBox::from_id_salt("text-font-dropdown").selected_text(current_font_label).width(ui.available_width().max(180.0)).show_ui(
+ ui,
+ |ui| {
+ if ui.selectable_label(ed.font_resource.is_none(), tl!("Keep source fonts")).clicked() {
+ ed.font_resource = None;
+ changed = true;
}
- });
- if ui.button(tl!("Load font…")).clicked() {
- app.pick_files(crate::files::FilePurpose::TextFont { page: ed.page }, false);
- }
- #[cfg(not(target_arch = "wasm32"))]
- egui::ComboBox::from_id_salt("installed-document-font").selected_text(tl!("Installed fonts…")).show_ui(ui, |ui| {
- if let Some(fonts) = crate::files::installed_font_files(ui.ctx()) {
- if fonts.is_empty() {
- ui.label(tl!("No openly licensed document fonts found. Load a font file."));
+ if !font_choices.is_empty() {
+ ui.separator();
+ ui.label(egui::RichText::new(tl!("Document fonts")).weak().small());
+ for font in font_choices.iter().filter(|f| !f.resource.starts_with("PCApproved")) {
+ let is_current = ed.font_resource.as_ref() == Some(&font.resource);
+ if ui.selectable_label(is_current, &font.face).clicked() {
+ ed.font_resource = Some(font.resource.clone());
+ changed = true;
+ }
+ }
}
- for font in fonts {
- if ui.selectable_label(false, &font.face).clicked() {
- app.use_paths(crate::files::FilePurpose::TextFont { page: ed.page }, &[font.path]);
+ ui.separator();
+ ui.label(egui::RichText::new(tl!("Standard fonts")).weak().small());
+ for f in [pdfcraft_engine::FontFamily::Helvetica, pdfcraft_engine::FontFamily::Times, pdfcraft_engine::FontFamily::Courier] {
+ let is_current = ed.font_resource.is_none() && ed.look.family == f;
+ if ui.selectable_label(is_current, f.label()).clicked() {
+ ed.font_resource = None;
+ ed.look.family = f;
+ changed = true;
}
}
- } else {
- ui.label(tl!("Finding document fonts…"));
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ ui.separator();
+ ui.label(egui::RichText::new(tl!("Installed fonts")).weak().small());
+ if let Some(installed) = crate::files::installed_font_files(ui.ctx()) {
+ if installed.is_empty() {
+ ui.label(egui::RichText::new(tl!("No installed fonts found.")).weak().small());
+ } else {
+ for font in &installed {
+ let is_current =
+ ed.font_resource.as_ref().is_some_and(|r| font_choices.iter().any(|f| &f.resource == r && f.face == font.face));
+ if ui.selectable_label(is_current, &font.face).clicked()
+ && let Ok(bytes) = std::fs::read(&font.path)
+ {
+ let edit = pdfcraft_engine::Edit::RegisterTextFont { page: ed.page, bytes: std::sync::Arc::new(bytes.clone()) };
+ if app.apply_edit(edit)
+ && let Some(doc) = app.session.get(app.views[i].id)
+ {
+ if let Some(f) = doc.text_editor_fonts(ed.page).into_iter().find(|f| f.bytes == bytes) {
+ ed.font_resource = Some(f.resource);
+ changed = true;
+ }
+ ed.fonts = crate::edit_text_ui::install_source_fonts(ui.ctx(), doc, ed.page);
+ }
+ }
+ }
+ }
+ } else {
+ ui.label(egui::RichText::new(tl!("Finding installed fonts…")).weak().small());
+ }
+ }
+ ui.separator();
+ if ui.button(tl!("Load font from file…")).clicked() {
+ app.pick_files(crate::files::FilePurpose::TextFont { page: ed.page }, false);
+ }
+ },
+ );
+
+ ui.horizontal(|ui| {
+ // Font size ComboBox
+ egui::ComboBox::from_id_salt("font-size").selected_text(format!("{:.1}", ed.look.size)).width(55.0).show_ui(ui, |ui| {
+ for size in [6.0, 8.0, 9.0, 10.0, 10.5, 11.0, 12.0, 14.0, 16.0, 18.0, 20.0, 24.0, 28.0, 36.0, 48.0, 72.0] {
+ changed |= ui.selectable_value(&mut ed.look.size, size, format!("{size}")).changed();
+ }
+ });
+ // Color swatch square
+ let (color_rect, color_resp) = ui.allocate_exact_size(egui::vec2(20.0, 20.0), egui::Sense::click());
+ let color_val = crate::comments::color32(ed.look.color);
+ ui.painter().rect_filled(color_rect, t.radius, color_val);
+ ui.painter().rect_stroke(color_rect, t.radius, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside);
+ let show_palette_id = ui.id().with("show-palette");
+ let mut show_palette = ui.data(|d| d.get_temp::<bool>(show_palette_id)).unwrap_or(false);
+ if color_resp.on_hover_text(tl!("Text color")).clicked() {
+ show_palette = !show_palette;
+ ui.data_mut(|d| d.insert_temp(show_palette_id, show_palette));
+ }
+ ui.add_space(2.0);
+ // Bullet list button
+ let is_bullet = crate::edit_text_ui::is_bulleted(&ed.text);
+ if crate::icons::button(ui, "list", 24.0, is_bullet, tl!("Bullet list")).clicked() {
+ changed |= crate::edit_text_ui::toggle_bullet_list(&mut ed.text);
+ }
+ // Numbered list button
+ let is_num = crate::edit_text_ui::is_numbered(&ed.text);
+ if crate::icons::button(ui, "list-ordered", 24.0, is_num, tl!("Numbered list")).clicked() {
+ changed |= crate::edit_text_ui::toggle_numbered_list(&mut ed.text);
+ }
+ ui.add_space(2.0);
+ // Alignment buttons
+ for (a, icon, tip) in [
+ (pdfcraft_engine::TextAlign::Left, "align-left", tl!("Align left")),
+ (pdfcraft_engine::TextAlign::Center, "align-center", tl!("Centre")),
+ (pdfcraft_engine::TextAlign::Right, "align-right", tl!("Align right")),
+ (pdfcraft_engine::TextAlign::Justify, "align-justify", tl!("Justify")),
+ ] {
+ if crate::icons::button(ui, icon, 24.0, ed.look.align == a, tip).clicked() {
+ ed.look.align = a;
+ changed = true;
+ }
}
});
- if let Some(look) = crate::content_ui::format_panel(ui, t, &ed.look) {
- ed.look = look;
+
+ // Color Swatch Grid (when toggled or open)
+ let show_palette_id = ui.id().with("show-palette");
+ if ui.data(|d| d.get_temp::<bool>(show_palette_id)).unwrap_or(false)
+ && let Some(picked) = crate::comments::swatch_grid(ui, Some(ed.look.color))
+ {
+ ed.look.color = picked;
changed = true;
}
+
+ // Formatting Buttons: Bold, Italic, Underline, Superscript, Subscript
+ ui.horizontal(|ui| {
+ let b_resp = ui.selectable_label(ed.look.bold, egui::RichText::new("B").strong()).on_hover_text(tl!("Bold"));
+ if b_resp.clicked() {
+ ed.look.bold = !ed.look.bold;
+ changed = true;
+ }
+ let i_resp = ui.selectable_label(ed.look.italic, egui::RichText::new("I").italics()).on_hover_text(tl!("Italic"));
+ if i_resp.clicked() {
+ ed.look.italic = !ed.look.italic;
+ changed = true;
+ }
- if crate::icons::button(ui, "underline", 24.0, ed.extras.underline, tl!("Underline")).clicked() {
- ed.extras.underline = !ed.extras.underline;
- changed = true;
- }
+ let sup_resp = ui.selectable_label(false, egui::RichText::new("T¹").size(13.0)).on_hover_text(tl!("Superscript"));
+ if sup_resp.clicked() {
+ changed |= crate::edit_text_ui::toggle_superscript(&mut ed);
+ }
+ let sub_resp = ui.selectable_label(false, egui::RichText::new("T₁").size(13.0)).on_hover_text(tl!("Subscript"));
+ if sub_resp.clicked() {
+ changed |= crate::edit_text_ui::toggle_subscript(&mut ed);
+ }
+ });
+
+ // Spacing: Value-based line spacing, paragraph spacing, horizontal scale, character spacing
changed |= crate::edit_text_ui::extras_panel(ui, &mut ed.extras);
if changed {
let edit = pdfcraft_engine::Edit::EditTextBlock { page: ed.page, block: ed.block, text: ed.text.clone(), style: ed.style() };
diff --cc crates/ui-egui/tests/editing.rs
index 05357891e,65b90dad5..b48adf301
--- a/crates/ui-egui/tests/editing.rs
+++ b/crates/ui-egui/tests/editing.rs
@@@ -1686,6 -1740,48 +1740,48 @@@ fn files_dropped_outside_the_page_grid_
assert_eq!(doc.bytes.as_slice(), fixture(1).as_slice());
}
+ /// The Pages panel's thumbnail of page `label` (the panel is right of the page view).
+ fn panel_thumb_rect(h: &Harness<'static, PdfCraftApp>, label: &str) -> egui::Rect {
+ h.get_all_by_label(label).map(|n| n.rect()).max_by(|a, b| a.left().total_cmp(&b.left())).unwrap()
+ }
+
+ #[test]
+ fn files_dropped_on_the_pages_panel_are_inserted_there() {
+ let mut h = harness(3, |app| app.right = Some(pdfcraft_ui_egui::RightPanel::Pages));
+ // The top half of page 2's thumbnail: between pages 1 and 2.
+ let thumb = panel_thumb_rect(&h, "Page 2");
+ h.hover_at(thumb.center() - egui::vec2(0.0, thumb.height() * 0.25));
+ h.run_steps(2);
+ assert_eq!(h.state().views[0].panel_gap, Some(1));
+ drop_files(&mut h, vec![Dropped("extra.pdf", fixture(2)), Dropped("note.txt", b"a note".to_vec())]);
+ h.run_steps(4);
+ assert_eq!(h.state().views.len(), 1, "dropped files are not opened as documents");
+ assert_eq!(texts_of(h.state(), 0), ["Page 1", "Page 1", "Page 2", "a note", "Page 2", "Page 3"]);
+ assert_eq!(picked(&h), [1, 2, 3], "the inserted pages are selected");
+ // The bottom half of the last thumbnail: the end.
+ let mut h = harness(2, |app| app.right = Some(pdfcraft_ui_egui::RightPanel::Pages));
+ let last = panel_thumb_rect(&h, "Page 2");
+ h.hover_at(last.center() + egui::vec2(0.0, last.height() * 0.25));
+ h.run_steps(2);
+ drop_files(&mut h, vec![Dropped("note.txt", b"a note".to_vec())]);
+ h.run_steps(4);
+ assert_eq!(h.state().views.len(), 1);
+ assert_eq!(texts_of(h.state(), 0), ["Page 1", "Page 2", "a note"]);
+ }
+
+ #[test]
+ fn files_dropped_beside_the_pages_panel_still_open_as_documents() {
+ let mut h = harness(2, |app| app.right = Some(pdfcraft_ui_egui::RightPanel::Pages));
+ // Over the page view, not the panel.
+ let thumb = panel_thumb_rect(&h, "Page 1");
+ h.hover_at(egui::pos2(thumb.left() - 300.0, thumb.center().y));
+ h.run_steps(2);
+ drop_files(&mut h, vec![Dropped("other.pdf", fixture(1))]);
- h.run_steps(3);
++ support::wait_until(&mut h, "dropped document", |app| app.views.len() == 2 && app.password_prompt.is_none());
+ assert_eq!(h.state().views.len(), 2);
+ assert_eq!(texts_of(h.state(), 0), ["Page 1", "Page 2"]);
+ }
+
fn grid_zoom(h: &Harness<'static, PdfCraftApp>) -> f32 {
h.state().views[0].grid_zoom()
}
@@@ -2548,251 -2841,6 +2841,240 @@@ fn check_existing_artwork(name: &'stati
assert!(h.state().session.get(id).unwrap().page_images(0).is_empty());
}
+#[test]
+fn image_right_click_context_menu_items_and_actions() {
+ let mut png = Vec::new();
+ image::RgbImage::from_pixel(80, 40, image::Rgb([200, 40, 40])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
+ let mut app = PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ app.open_bytes("picture.png", None, png.clone()).expect("opens");
+ app
+ });
+ h.run_steps(4);
+ assert!(h.state_mut().execute("edit.edit_text"));
+ h.run_steps(2);
+ let r = h.state().views[0].page_screen_rect(0).expect("on screen");
+ let c = r.center();
+ // Select image
+ h.hover_at(c);
+ h.run_steps(1);
+ h.drag_at(c);
+ h.run_steps(1);
+ h.drop_at(c);
+ h.run_steps(2);
+ assert!(h.state().views[0].image_selection.is_some(), "selected");
+
+ // Right-click image
+ h.hover_at(c);
+ h.run_steps(1);
+ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });
+ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });
+ h.run_steps(2);
+ assert!(h.state().views[0].image_selection.is_some());
+
+ for item in [
+ "Cut",
+ "Copy",
+ "Paste",
+ "Flip horizontal",
+ "Flip vertical",
+ "Arrange image",
+ "Replace image",
+ "Draw freehand",
- "Redact image",
++ "Redact Image",
+ "Export image",
- "Create link",
++ "Create Link",
+ "Edit image using",
- "Recognize text",
++ "Recognize Text",
+ ] {
+ h.get_by_label_contains(item);
+ }
+
+ // Top horizontal icon buttons
+ h.get_by_label("Rotate Counterclockwise");
+ h.get_by_label("Rotate Clockwise");
+ h.get_by_label("Delete");
+
+ // Flip horizontal via context menu item
+ h.get_by_label("Flip horizontal").click();
+ h.run_steps(3);
+ let id = h.state().views[0].id;
+ let doc = h.state().session.get(id).unwrap();
+ assert_eq!(doc.can_undo(), Some("Flip image"));
+
+ // Undo flip
+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z);
+ h.run_steps(3);
+ let doc = h.state().session.get(id).unwrap();
+ assert_eq!(doc.can_undo(), None);
+}
+
+#[test]
+fn default_page_context_menu_when_not_in_edit_mode() {
+ let mut h = harness(1, |_| {});
+ h.run_steps(4);
+ assert_eq!(h.state().quick_tool, pdfcraft_ui_egui::QuickTool::Select);
+
+ let r = h.state().views[0].page_screen_rect(0).expect("on screen");
+ let c = r.center();
+ // Right click on page in Select mode
+ h.hover_at(c);
+ h.run_steps(1);
+ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });
+ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });
+ h.run_steps(2);
+
+ // Verify Acrobat page context menu items (Screenshot 3)
+ h.get_by_label("Rotate Counterclockwise");
+ h.get_by_label("Print");
+ h.get_by_label("Select Tool");
+ h.get_by_label("Hand Tool");
+ h.get_by_label("Marquee Zoom");
+
+ for item in ["Add bookmark", "Take a snapshot", "Edit this PDF", "Delete page", "Export this PDF", "Find text or tools", "Document properties…"]
+ {
+ h.get_by_label_contains(item);
+ }
+ h.get_by_label("Rotate view clockwise");
+ assert!(h.query_all_by_label("Add comment").next().is_some());
+ assert!(h.query_all_by_label("Add text").next().is_some());
+ assert!(h.query_all_by_label("Add image").next().is_some());
+ assert!(h.query_all_by_label_contains("Copy").next().is_some());
+ assert!(h.query_all_by_label_contains("Paste").next().is_some());
+
+ // Clicking "Edit this PDF" enters edit mode
+ h.get_by_label("Edit this PDF").click();
+ h.run_steps(2);
+ assert_eq!(h.state().quick_tool, pdfcraft_ui_egui::QuickTool::EditText);
+}
+
+#[test]
+fn image_edge_handle_stretch_and_crop_mode() {
+ let mut png = Vec::new();
+ image::RgbImage::from_pixel(100, 100, image::Rgb([100, 150, 200]))
+ .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
+ .unwrap();
+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
+ let mut app = PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ app.open_bytes("square.png", None, png.clone()).expect("opens");
+ app
+ });
+ h.run_steps(4);
+ assert!(h.state_mut().execute("edit.edit_text"));
+ h.run_steps(2);
+
+ let r = h.state().views[0].page_screen_rect(0).expect("on screen");
+ let c = r.center();
+ // Select image
+ h.hover_at(c);
+ h.run_steps(1);
+ h.drag_at(c);
+ h.run_steps(1);
+ h.drop_at(c);
+ h.run_steps(2);
+ assert!(h.state().views[0].image_selection.is_some());
+
+ // Enter crop mode via context menu
+ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });
+ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });
+ h.run_steps(2);
+ h.get_by_label("Crop").click();
+ h.run_steps(2);
+ assert!(h.state().views[0].image_selection.as_ref().is_some_and(|s| s.crop_mode));
+
+ // Set smaller crop rect
+ let smaller = egui::Rect::from_center_size(c, egui::vec2(50.0, 50.0));
+ h.state_mut().views[0].image_selection.as_mut().unwrap().crop_rect = Some(smaller);
+
+ // Confirm crop with Enter key
+ h.key_press(egui::Key::Enter);
+ h.run_steps(4);
+ assert!(!h.state().views[0].image_selection.as_ref().is_some_and(|s| s.crop_mode));
+ let doc_id = h.state().views[0].id;
+ let images = h.state().session.get(doc_id).unwrap().page_images(0);
+ assert_eq!(images.len(), 1, "image still exists: {images:?}");
+ assert!(images[0].visible_rect.is_some(), "cropped image is visible");
+ assert_ne!(images[0].visible_rect, Some(images[0].rect), "image is cropped");
+
+ // Remove crop via context menu
+ h.hover_at(c);
+ h.run_steps(1);
+ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });
+ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });
+ h.run_steps(2);
+ h.get_by_label("Remove crop").click();
+ h.run_steps(4);
+ let images = h.state().session.get(doc_id).unwrap().page_images(0);
+ assert_eq!(images[0].visible_rect, Some(images[0].rect), "crop is removed");
+}
+
+#[test]
+fn tiny_image_crop_handle_drag_does_not_panic() {
+ let mut png = Vec::new();
+ image::RgbImage::from_pixel(5, 5, image::Rgb([100, 150, 200])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
+ let mut h = Harness::builder().with_size(egui::vec2(800.0, 600.0)).build_eframe(move |_cc| {
+ let mut app = PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ app.open_bytes("tiny.png", None, png.clone()).expect("opens");
+ app
+ });
+ h.run_steps(4);
+ assert!(h.state_mut().execute("edit.edit_text"));
+ h.run_steps(2);
+
- // Enter crop mode on image 0
- let view = &mut h.state_mut().views[0];
- view.image_selection = Some(pdfcraft_ui_egui::ImageSelection { page: 0, index: 0, drag: None, crop_mode: true, crop_rect: None });
++ // Enter crop mode on image 0 with small dimensions (5.0 x 5.0)
++ h.state_mut().views[0].image_selection = Some(pdfcraft_ui_egui::ImageSelection {
++ page: 0,
++ index: 0,
++ drag: None,
++ crop: Some(pdfcraft_ui_egui::CropMode::new([100.0, 100.0, 105.0, 105.0])),
++ crop_mode: true,
++ crop_rect: None,
++ });
+ h.run_steps(1);
+
- // Simulate drag on TopLeft crop handle with an initial_rect of 5.0 x 5.0
- let initial = egui::Rect::from_min_size(egui::pos2(100.0, 100.0), egui::vec2(5.0, 5.0));
- let view = &mut h.state_mut().views[0];
- if let Some(s) = view.image_selection.as_mut() {
- s.drag = Some(pdfcraft_ui_egui::ImageDrag {
- start: egui::pos2(100.0, 100.0),
- target: pdfcraft_ui_egui::DragTarget::CropHandle(pdfcraft_ui_egui::ImageHandle::TopLeft),
- initial_rect: initial,
- });
- }
-
- // Hover/drag to a new position, triggering the clamp calculation
++ // Hover and drag a handle across a 5.0 x 5.0 image to ensure clamp bounds do not panic
++ h.hover_at(egui::pos2(100.0, 100.0));
++ h.run_steps(1);
++ h.drag_at(egui::pos2(100.0, 100.0));
++ h.run_steps(1);
+ h.hover_at(egui::pos2(105.0, 105.0));
+ h.run_steps(2);
-
- // Also test BottomRight handle
- let view = &mut h.state_mut().views[0];
- if let Some(s) = view.image_selection.as_mut() {
- s.drag = Some(pdfcraft_ui_egui::ImageDrag {
- start: egui::pos2(105.0, 105.0),
- target: pdfcraft_ui_egui::DragTarget::CropHandle(pdfcraft_ui_egui::ImageHandle::BottomRight),
- initial_rect: initial,
- });
- }
- h.hover_at(egui::pos2(95.0, 95.0));
++ h.drop_at(egui::pos2(105.0, 105.0));
+ h.run_steps(2);
+}
+
+#[test]
+fn text_selection_action_icons() {
+ let mut h = harness(1, |_| {});
+ h.run_steps(4);
+ let r = h.state().views[0].page_screen_rect(0).expect("on screen");
+ let p0 = egui::pos2(r.left() + 40.0 / 200.0 * r.width(), r.top() + (300.0 - 158.0) / 300.0 * r.height());
+ let p1 = egui::pos2(r.left() + 100.0 / 200.0 * r.width(), r.top() + (300.0 - 158.0) / 300.0 * r.height());
+
+ // Drag to select text
+ h.hover_at(p0);
+ h.run_steps(1);
+ h.drag_at(p0);
+ h.run_steps(1);
+ h.hover_at(p1);
+ h.run_steps(1);
+ h.drop_at(p1);
+ h.run_steps(2);
+
+ assert!(h.state().views[0].selected_text().is_some());
+
+ // Verify all 6 minimalist action icons are present in the floating menu
+ assert!(h.query_all_by_label("Add comment").next().is_some());
+ assert!(h.query_all_by_label("Highlight").next().is_some());
+ assert!(h.query_all_by_label("Underline").next().is_some());
+ assert!(h.query_all_by_label("Strikethrough").next().is_some());
+ assert!(h.query_all_by_label("Replace text").next().is_some());
+ assert!(h.query_all_by_label("Copy").next().is_some());
+}
+
#[test]
fn the_format_panel_restyles_the_paragraph_being_edited() {
let mut h = harness(1, |_| {});
@@@ -4406,86 -4522,151 +4756,236 @@@ fn private_new_chinese_keyboard_input_p
println!("verified Chinese keyboard insertion/deletion and save/reopen rendering on {pages} pages");
}
+ /// Moving text shows the four-way arrow wherever a drag would move it (#1520 follow-up): over a
+ /// closed paragraph, on the frame of an open one, and while dragging. Inside the open one the
+ /// pointer reads as text; on a closed one's edge, as the rewrap handle.
+ #[test]
+ fn moving_text_offers_the_four_way_arrow() {
+ let mut h = harness(2, |_| {});
+ assert!(h.state_mut().execute("edit.edit_text"));
+ h.run_steps(2);
+ let id = h.state().views[0].id;
+ let block = h.state().session.get(id).unwrap().text_blocks(0)[0].clone();
+ let r = h.state().views[0].page_screen_rect(0).expect("on screen");
+ let k = r.width() / 200.0;
+ let screen = |x: f64, y: f64| egui::pos2(r.left() + x as f32 * k, r.top() + (300.0 - y as f32) * k);
+ let centre = screen((block.rect[0] + block.rect[2]) / 2.0, (block.rect[1] + block.rect[3]) / 2.0);
+ let cursor_at = |h: &mut Harness<'static, PdfCraftApp>, at: egui::Pos2| {
+ h.hover_at(at);
+ h.run_steps(2);
+ h.output().platform_output.cursor_icon
+ };
+ // A closed paragraph: a drag moves it; its left edge rewraps it.
+ assert_eq!(cursor_at(&mut h, centre), egui::CursorIcon::Move);
+ assert_eq!(cursor_at(&mut h, screen(block.rect[0], (block.rect[1] + block.rect[3]) / 2.0)), egui::CursorIcon::ResizeHorizontal);
+ // While it is being dragged.
+ h.hover_at(centre);
+ h.run_steps(1);
+ h.drag_at(centre);
+ h.run_steps(1);
+ let mid = centre + egui::vec2(20.0 * k, 10.0 * k);
+ h.hover_at(mid);
+ h.run_steps(2);
+ assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Move);
+ h.drop_at(mid);
+ h.run_steps(4);
+ let moved = h.state().session.get(id).unwrap().text_blocks(0)[0].clone();
+ assert!((moved.rect[0] - block.rect[0] - 20.0).abs() < 1.5, "{:?} → {:?}", block.rect, moved.rect);
+ // Open: text inside, the frame moves it.
+ let centre = screen((moved.rect[0] + moved.rect[2]) / 2.0, (moved.rect[1] + moved.rect[3]) / 2.0);
+ click_at(&mut h, centre);
+ assert!(h.state().views[0].line_editor.is_some());
+ assert_eq!(cursor_at(&mut h, centre), egui::CursorIcon::Text);
+ let frame = screen((moved.rect[0] + moved.rect[2]) / 2.0, moved.rect[3]) - egui::vec2(0.0, 4.0);
+ assert_eq!(cursor_at(&mut h, frame), egui::CursorIcon::Move);
+ }
+
+ /// Cropping a picture on the page (Acrobat's crop handles): in crop mode the
+ /// handles trim, Enter applies what is kept, Esc leaves the picture as it was.
+ #[test]
+ fn cropping_a_picture_with_its_handles() {
+ let mut png = Vec::new();
+ image::RgbImage::from_pixel(80, 40, image::Rgb([200, 40, 40])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
+ let mut app = PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ app.open_bytes("picture.png", None, png.clone()).expect("opens");
+ app
+ });
+ h.run_steps(4);
+ let id = h.state().views[0].id;
+ let before = h.state().session.get(id).unwrap().page_images(0)[0].visible_rect.unwrap();
+ assert!(h.state_mut().execute("edit.edit_text"));
+ h.run_steps(2);
+ let r = h.state().views[0].page_screen_rect(0).expect("on screen");
+ let c = r.center();
+ h.hover_at(c);
+ h.run_steps(1);
+ h.drag_at(c);
+ h.run_steps(1);
+ h.drop_at(c);
+ h.run_steps(2);
+ assert!(h.state().views[0].image_selection.is_some(), "selected");
+ // Crop mode (as the context menu's Crop Image starts it): drag the right-bottom handle a
+ // quarter of the picture inward, then Enter.
+ h.state_mut().views[0].image_selection.as_mut().unwrap().crop = Some(pdfcraft_ui_egui::CropMode::new(before));
+ h.run_steps(2);
+ let corner = r.right_bottom();
+ let to = corner - egui::vec2(r.width() / 4.0, r.height() / 4.0);
+ h.hover_at(corner);
+ h.run_steps(1);
+ h.drag_at(corner);
+ h.run_steps(1);
+ for k in 1..=4 {
+ h.hover_at(corner + (to - corner) * (k as f32 / 4.0));
+ h.run_steps(1);
+ }
+ h.drop_at(to);
+ h.run_steps(2);
+ let keep = h.state().views[0].image_selection.as_ref().unwrap().crop.as_ref().unwrap().keep;
+ assert!(keep[2] < before[2] - 1.0 && keep[1] > before[1] + 1.0, "trimmed on the right and the bottom: {keep:?} of {before:?}");
+ h.key_press(egui::Key::Enter);
+ h.run_steps(4);
+ let doc = h.state().session.get(id).unwrap();
+ assert_eq!(doc.can_undo(), Some("Crop image"));
+ let im = &doc.page_images(0)[0];
+ assert_eq!(im.rect, [0.0, 0.0, 80.0, 40.0], "the placement is not scaled");
+ let v = im.visible_rect.unwrap();
+ assert!((v[2] - 60.0).abs() < 1.5 && (v[1] - 10.0).abs() < 1.5, "kept {v:?}");
+ assert!(h.state().views[0].image_selection.as_ref().is_some_and(|s| s.crop.is_none()), "crop mode ends");
+ // Esc leaves it.
+ h.state_mut().views[0].image_selection.as_mut().unwrap().crop = Some(pdfcraft_ui_egui::CropMode::new([10.0, 10.0, 20.0, 20.0]));
+ h.run_steps(2);
+ h.key_press(egui::Key::Escape);
+ h.run_steps(3);
+ let doc = h.state().session.get(id).unwrap();
+ assert_eq!(doc.page_images(0)[0].visible_rect.unwrap(), v);
+ assert!(h.state().views[0].image_selection.as_ref().is_none_or(|s| s.crop.is_none()));
+ }
+
+ /// Organize pages has Acrobat's panel whenever the grid shows, however it was opened, and the
+ /// panel's Close ends Organize: the grid closes and All tools comes back.
+ #[test]
+ fn organize_panel_comes_with_the_grid_and_closes_it() {
+ let mut h = organize(3);
+ h.get_by_label("Insert");
+ h.get_by_label("Bates numbering");
+ h.get_by_label("Page properties");
+ h.get_by_label("Close panel").click();
+ h.run_steps(3);
+ assert!(!h.state().views[0].organize, "Close ends Organize");
+ assert_eq!(h.state().left, pdfcraft_ui_egui::LeftPanel::AllTools);
+ assert!(h.query_by_label("Page properties").is_none(), "the panel is gone");
+ }
+
+ /// Leaving Organize (a page opened from the grid, or the grid's Close) goes back to the
+ /// workspace's panel: under the Edit tab, the Edit panel, not All tools.
+ #[test]
+ fn leaving_organize_goes_back_to_the_workspace_panel() {
+ use pdfcraft_ui_egui::{LeftPanel, Mode};
+ let mut h = harness(3, |_| {});
+ h.state_mut().mode = Mode::Edit;
+ h.state_mut().left = LeftPanel::Tool("edit");
+ h.run_steps(2);
+ h.state_mut().left = LeftPanel::Tool("organize");
+ h.state_mut().views[0].organize = true;
+ h.run_steps(3);
+ h.get_by_label("Pages selected".to_uppercase().as_str());
+ // What opening a page from the grid does.
+ h.state_mut().views[0].organize = false;
+ h.run_steps(3);
+ assert_eq!(h.state().left, LeftPanel::Tool("edit"), "back to the Edit panel");
+ // The same from All tools goes back to All tools.
+ h.state_mut().mode = Mode::AllTools;
+ h.state_mut().left = LeftPanel::Tool("organize");
+ h.state_mut().views[0].organize = true;
+ h.run_steps(3);
+ h.state_mut().views[0].organize = false;
+ h.run_steps(3);
+ assert_eq!(h.state().left, LeftPanel::AllTools);
+ }
++
+#[test]
+fn image_copy_cut_paste_keyboard_and_context_menu() {
+ let mut png = Vec::new();
+ image::RgbImage::from_pixel(60, 40, image::Rgb([180, 50, 50])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
+ let mut app = PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ app.system_clipboard = false;
+ app.open_bytes("picture.png", None, png.clone()).expect("opens");
+ app
+ });
+ h.run_steps(4);
+ assert!(h.state_mut().execute("edit.edit_text"));
+ h.run_steps(2);
+
+ let id = h.state().views[0].id;
+ let initial_count = h.state().session.get(id).unwrap().page_images(0).len();
+ assert_eq!(initial_count, 1, "starts with 1 image");
+
+ let r = h.state().views[0].page_screen_rect(0).expect("on screen");
+ let c = r.center();
+
+ // 1. Select the image
+ h.hover_at(c);
+ h.run_steps(1);
+ h.drag_at(c);
+ h.run_steps(1);
+ h.drop_at(c);
+ h.run_steps(2);
+ assert!(h.state().views[0].image_selection.is_some(), "image selected");
+
+ // 2. Copy via keyboard shortcut (COMMAND+C / Event::Copy)
+ h.event(egui::Event::Copy);
+ h.run_steps(2);
+ assert!(h.state().last_copied_image.is_some(), "image copied to clipboard buffer");
+
+ // 3. Paste via keyboard shortcut (COMMAND+V / Event::Paste)
+ h.event(egui::Event::Paste("".into()));
+ h.run_steps(3);
+ let after_paste = h.state().session.get(id).unwrap().page_images(0).len();
+ assert_eq!(after_paste, 2, "now has 2 images");
+ assert_eq!(h.state().views[0].image_selection.as_ref().map(|s| s.index), Some(1), "new image is selected");
+
+ // 4. Cut via keyboard shortcut (COMMAND+X / Event::Cut)
+ h.event(egui::Event::Cut);
+ h.run_steps(3);
+ let after_cut = h.state().session.get(id).unwrap().page_images(0).len();
+ assert_eq!(after_cut, 1, "cut deleted the pasted image");
+ assert!(h.state().views[0].image_selection.is_none(), "selection cleared after cut");
+
+ // 5. Paste again via context menu on the page
+ h.hover_at(c);
+ h.run_steps(1);
+ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });
+ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });
+ h.run_steps(2);
+ h.get_by_label_contains("Paste").click();
+ h.run_steps(3);
+ let after_paste2 = h.state().session.get(id).unwrap().page_images(0).len();
+ assert_eq!(after_paste2, 2, "pasted via context menu");
+}
+
+#[test]
+fn stale_clipboard_plain_text_does_not_paste_image() {
+ let mut h = harness(1, |_| {});
+ h.run_steps(4);
+ // Put an image into internal cache
+ h.state_mut().last_copied_image = Some((10, 10, vec![0; 400]));
+ h.state_mut().last_copied_file = Some(("cached.png".to_string(), vec![1, 2, 3]));
+ h.state_mut().system_clipboard = true;
+
+ // Set actual system clipboard to plain text
+ #[cfg(not(target_arch = "wasm32"))]
+ if let Ok(mut cb) = arboard::Clipboard::new() {
+ cb.set_text("just plain text").ok();
+ }
+
+ // can_paste_image should now be false because the system clipboard has text, not an image!
+ assert!(!h.state().can_paste_image(), "cannot paste image when system clipboard has text");
+
+ // paste_image should fail and return false without pasting
+ assert!(!h.state_mut().paste_image(0, None), "must not paste stale cached image");
+}
++