PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Fill colour for rectangle, oval and polygon comments (#686) (#793)
DWAA166086dd8d828367
diff --git a/ATTRIBUTION.toml b/ATTRIBUTION.tomlindex fdb2c4aa9..0905e395e 100644--- a/ATTRIBUTION.toml+++ b/ATTRIBUTION.toml@@ -19,7 +19,7 @@ licence = "MIT OR Apache-2.0"licence_file = "LICENSE-MIT"kind = "translation"usage = "Simplified Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"-sha256 = "d79b409519f49bc8d257eda7abb3381a0fc62fec31c88712c95c53c95d756162"+sha256 = "9a105c2a7177f076f7d4188e75c86fab682ee604db9a8cc54828c26fbf0c3999"[[asset]]path = "crates/ui-egui/src/i18n/zh-hant.tsv"@@ -30,7 +30,7 @@ licence = "MIT OR Apache-2.0"licence_file = "LICENSE-MIT"kind = "translation"usage = "Traditional Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"-sha256 = "cefe9cffb13e9babbbfbcc881bf3f24ee65b7ed013d94405b04bcf57349b3371"+sha256 = "4bdc334589eb97d5ea94906cbeaa0980ee24245b189d32631dfc0ca01b138e58"[[asset]]path = "crates/ui-egui/src/i18n/cs.tsv"@@ -52,7 +52,7 @@ licence = "MIT OR Apache-2.0"licence_file = "LICENSE-MIT"kind = "translation"usage = "Brazilian Portuguese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"-sha256 = "3de8647fc74dc4a11979836ec0bcaeb2299965ce6779c118d0df3fbbb9e1fb05"+sha256 = "687a5b9aef8126950e3d2a144bef253d7affb8d640468d55e984180540c6d81a"[[asset]]path = "crates/ui-egui/src/i18n/es.tsv"@@ -63,7 +63,7 @@ licence = "MIT OR Apache-2.0"licence_file = "LICENSE-MIT"kind = "translation"usage = "Spanish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"-sha256 = "83d2a772ac1d08d506b4e6e19c2ebc07860614710a058d69923d5bff7e1355c5"+sha256 = "582f286b990248de822c50a003302666b70c2317b26026cc547261b294b8fdb3"[[asset]]path = "crates/ui-egui/src/i18n/fr.tsv"@@ -74,7 +74,7 @@ licence = "MIT OR Apache-2.0"licence_file = "LICENSE-MIT"kind = "translation"usage = "French UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"-sha256 = "32a092a72ebc03f4bc9f849091421ba306a0ee06531249c104471f51420450e9"+sha256 = "26652013f0aea0bd7b8d85ee404bd6c0abdd3df4c2ce4328436c836c5fe17dd2"[[asset]]path = "crates/ui-egui/src/i18n/de.tsv"@@ -85,7 +85,7 @@ licence = "MIT OR Apache-2.0"licence_file = "LICENSE-MIT"kind = "translation"usage = "German UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"-sha256 = "b598b6564cb9851cd97ccadc064071f02c3061d4f5a297baacdf3c7ef41dfd89"+sha256 = "e7949815a7498728f503093276377fe28dd9721474e74be86d7c6b08e04356aa"[[asset]]path = "crates/ui-egui/src/i18n/te.tsv"@@ -107,7 +107,7 @@ licence = "MIT OR Apache-2.0"licence_file = "LICENSE-MIT"kind = "translation"usage = "Italian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"-sha256 = "48ecc081b27cfa6be06af619785123cba7a786a1290d6aeb794f693c902d8246"+sha256 = "3859cb26f3f904c1cc5942aa3d80c2c0c6514f59cbf3579f761fe6f3d5cc370f"[[asset]]path = "crates/ui-egui/src/i18n/ru.tsv"@@ -118,7 +118,7 @@ licence = "MIT OR Apache-2.0"licence_file = "LICENSE-MIT"kind = "translation"usage = "Russian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"-sha256 = "1b7bc6dc28b20c10840af092f5a52e45f8fbb3740ddd907185b89a91b5d8a5ab"+sha256 = "ec7ead4385453163bb7391deb54703158d7dc41ab029755d46306071adbabfb3"[[asset]]path = "crates/ui-egui/src/i18n/hu.tsv"@@ -129,7 +129,7 @@ licence = "MIT OR Apache-2.0"licence_file = "LICENSE-MIT"kind = "translation"usage = "Hungarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"-sha256 = "b6800b09844ec71ad26cc38670a8fb94873690f3dc9585a47352f334f7993906"+sha256 = "5924e38d2482b4d33a9cd73e96c116769a52a3fbe1f98e401dd1c6e8a1a3c904"[[asset]]path = "crates/ui-egui/src/i18n/bg.tsv"@@ -140,7 +140,7 @@ licence = "MIT OR Apache-2.0"licence_file = "LICENSE-MIT"kind = "translation"usage = "Bulgarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"-sha256 = "e15e166aafc0c0e0a939b578c25a7a4f3808932aeed8eddbfe9bcc06e0362f3b"+sha256 = "514beb169b6916b0f6a0d9295b5016959c42c4a89e7308847a4fe309f8139f3b"[[asset]]path = "crates/ui-egui/src/i18n/ja.tsv"@@ -151,7 +151,7 @@ licence = "MIT OR Apache-2.0"licence_file = "LICENSE-MIT"kind = "translation"usage = "Japanese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"-sha256 = "519d505722abc4e778a7ca3ff0aacc808321771d4e0b5629c7bf0b39e2dd8759"+sha256 = "4a530d0e3d7f380194d439ee2269b1c0c4c1dbfedc6cdd0b4e45e986d6fb5a2f"[[asset]]path = "crates/ui-egui/src/i18n/uk.tsv"@@ -162,7 +162,7 @@ licence = "MIT OR Apache-2.0"licence_file = "LICENSE-MIT"kind = "translation"usage = "Ukrainian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"-sha256 = "5a7a4592c205347621e002d6eaffbd8b021db54252c9cba2759d79763901af5c"+sha256 = "4c0c4ebf6a1c9a0c91e9a07842c8332e07be0710dfc992886bdf774a4a1cc5b4"[[asset]]path = "crates/ui-egui/src/i18n/ar.tsv"@@ -173,7 +173,7 @@ licence = "MIT OR Apache-2.0"licence_file = "LICENSE-MIT"kind = "translation"usage = "Arabic UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"-sha256 = "e593813504da5443bd89d764c383872c997910ba63581b8bca7dc3879fe7b0fc"+sha256 = "647234c45a66dd736e5bf833047a10b3d2a6860a066e7c2e9d6cef98fb499eca"[[asset]]path = "assets/icons/accessibility.svg"diff --git a/ROADMAP.md b/ROADMAP.mdindex 2c40b42d2..9076f6da6 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -216,6 +216,7 @@ M0 → M1 → M2 → M3 → M4 must happen in order. After M4, M5–M12 can run## LogNewest first: the date, what moved, and the new overall estimate.+- **2026-10-10 (M5, shape fill colour, #686):** Rectangles, ovals, polygons and clouds can be filled. The comment quick bar has a Fill colour control for those tools ("No fill" or a swatch; it persists with the other per-tool styles), Comment Properties ▸ Appearance has a Fill colour row (one undo step with the other changes, carried over by Make Current Properties Default), and `comment_edit` takes `fill` (`"none"` removes it). `pdfcraft-annot::set_fill` writes or removes `/IC` and redraws the appearance; lines, ink and locked comments refuse it. Still missing: a custom colour picker (only the comment palette), and a separate fill for line endings.- **2026-10-10 (M10, #645):** Export all images and Save image as keep transparency. A JPEG with a soft mask (the usual cut-out photo) was written as the bare JPEG, and soft masks of another size than the image, JPEG-compressed soft masks, stencil `/Mask` images and colour-key `/Mask` arrays were dropped, so cut-outs came out on solid white or black. These images are now PNG with the mask as alpha (soft masks scaled to the image, `/Matte` un-blended); JPEGs without transparency are still written byte for byte. A negative image size no longer overflows in Save image as. JPX/JBIG2/CCITT masks are still left out. Overall estimate unchanged (about 30–35%).- **2026-10-10 (M12, XFA rows and areas):** Dynamic XFA forms lay out a repeating subform inside a top-to-bottom container in positioned content (a table in an area) with all its instances, drawn and measured, instead of one; and areas no longer appear in data paths (`pdfcraft_xfa::data_path`), since they are not data scopes. Before, a form whose fields sit in an area read none of the values Adobe's viewers saved, wrote what was filled here under a new element named after the area, which Adobe's viewers would most likely not read, and a FormCalc total looping over the table's rows failed on the rows that were missing. Layout, the script tree, reading and writing the data and the engine's value and row operations share the one path rule. Synthetic tests cover the layout, the path rule and the whole round trip (rows, Adobe-written values, a FormCalc total over all rows, the written data, reopening). Still open for such forms: XFA script objects (`<variables><script>`), which aren't supported. Overall estimate unchanged (about 30–35%).diff --git a/crates/annot/src/lib.rs b/crates/annot/src/lib.rsindex 121076791..8a0253e70 100644--- a/crates/annot/src/lib.rs+++ b/crates/annot/src/lib.rs@@ -1728,6 +1728,41 @@ pub fn set_style(set_appearance(doc, r)}+/// Whether a comment of this subtype has an interior that can be filled (`/IC`: rectangles,+/// ovals, polygons and clouds, §12.5.6.8–9).+pub fn fillable(subtype: &str) -> bool {+ matches!(subtype, "Square" | "Circle" | "Polygon")+}++/// Fill a rectangle, oval or polygon comment with `fill`, or remove its fill (`None`), and+/// redraw its appearance (Acrobat: Properties ▸ Fill Color).+pub fn set_fill(doc: &mut Document, page: usize, index: usize, fill: Option<Rgb>, meta: &Meta) -> Result<(), AnnotError> {+ let (_, r) = annot_ref(doc, page, index)?;+ unlocked(doc, r)?;+ let d = annot_dict(doc, r);+ let subtype = String::from_utf8_lossy(d.name(b"Subtype").unwrap_or_default()).into_owned();+ if !fillable(&subtype) {+ return Err(AnnotError::Invalid("only rectangles, ovals and polygons can be filled".into()));+ }+ // Check before changing anything: a stale appearance would contradict the new fill.+ if appearance::build(&d).is_none() {+ return Err(AnnotError::Unsupported(subtype));+ }+ if fill.is_some_and(|c| !finite(&c)) {+ return Err(AnnotError::Invalid("invalid fill colour".into()));+ }+ doc.update_dict(r, |d| {+ match fill {+ Some(c) => d.set(b"IC".to_vec(), rgb(c)),+ None => {+ d.remove(b"IC");+ }+ }+ touch(d, meta);+ })?;+ set_appearance(doc, r)+}+/// Grow a line or polyline's rectangle so a non-`None` ending is not clipped. Idempotent.fn ensure_ending_room(d: &mut Dict) {let subtype = d.name(b"Subtype").unwrap_or_default();@@ -1919,6 +1954,10 @@ pub struct Props {pub locked: bool,/// `/LE`: two names for a line or polyline (`None` when unset), one for a callout.pub endings: Option<Vec<LineEnding>>,+ /// Rectangles, ovals and polygons: their interior can be filled (see [`fillable`]).+ pub fillable: bool,+ /// `/IC`, the interior colour (`None`: no fill).+ pub fill: Option<Rgb>,}/// The current properties of the comment at `(page, index)`.@@ -1942,11 +1981,25 @@ pub fn props(doc: &Document, page: usize, index: usize) -> Option<Props> {modified: text_value(doc, d, b"M"),restylable: appearance::build(d).is_some(),locked: annotation_flags(doc, d) & FLAG_LOCKED != 0,+ fillable: fillable(&subtype),+ fill: fill_of(d),subtype,endings: line_endings_of(d),})}+/// `/IC` as an RGB colour. An empty array means no fill; grey and CMYK fills are converted.+fn fill_of(d: &Dict) -> Option<Rgb> {+ let c: Vec<f64> = d.get(b"IC")?.as_array()?.iter().filter_map(|x| x.as_f64()).collect();+ let rgb = match c.as_slice() {+ [g] => [*g; 3],+ [r, g, b] => [*r, *g, *b],+ [c, m, y, k] => [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)],+ _ => return None,+ };+ finite(&rgb).then(|| rgb.map(|x| x.clamp(0.0, 1.0)))+}+/// `/LE` for a line, polyline or callout. Unknown names yield `None` so the control stays hidden.fn line_endings_of(d: &Dict) -> Option<Vec<LineEnding>> {let parse = |name: &[u8]| std::str::from_utf8(name).ok().and_then(LineEnding::parse);diff --git a/crates/annot/src/tests.rs b/crates/annot/src/tests.rsindex 2e42d1f5c..48eeb8c61 100644--- a/crates/annot/src/tests.rs+++ b/crates/annot/src/tests.rs@@ -283,6 +283,50 @@ fn restyle_and_resize_redraw_the_appearance() {assert!(matches!(set_rect(&mut doc, 0, l, [0.0, 0.0, 5.0, 5.0], &meta("")), Err(AnnotError::Invalid(_))));}+#[test]+fn shapes_can_be_filled_and_unfilled() {+ let mut doc = fixture();+ let r = add_annotation(&mut doc, &new(0, Shape::Rectangle { rect: [10.0, 10.0, 110.0, 60.0] }), &meta("r")).unwrap();+ let p = props(&doc, 0, r).unwrap();+ assert!(p.fillable);+ assert_eq!(p.fill, None);+ set_fill(&mut doc, 0, r, Some([0.0, 0.5, 1.0]), &meta("")).unwrap();+ let doc2 = reopen(&doc);+ let d = &list(&doc2, 0)[r];+ let ap = ap_content(&doc2, d);+ assert!(ap.contains("0 0.5 1 rg") && ap.contains("\nB\n"), "filled and stroked: {ap}");+ assert_eq!(props(&doc2, 0, r).unwrap().fill, Some([0.0, 0.5, 1.0]));+ // No fill again: /IC goes and the appearance only strokes.+ set_fill(&mut doc, 0, r, None, &meta("")).unwrap();+ let doc2 = reopen(&doc);+ let d = &list(&doc2, 0)[r];+ assert!(d.get(b"IC").is_none());+ let ap = ap_content(&doc2, d);+ assert!(!ap.contains(" rg") && ap.contains("\nS\n"), "stroked only: {ap}");+ assert_eq!(props(&doc2, 0, r).unwrap().fill, None);+ // Ovals and polygons fill too.+ let o = add_annotation(&mut doc, &new(0, Shape::Oval { rect: [10.0, 10.0, 60.0, 60.0] }), &meta("o")).unwrap();+ set_fill(&mut doc, 0, o, Some([1.0, 1.0, 0.0]), &meta("")).unwrap();+ assert!(ap_content(&doc, &list(&doc, 0)[o]).contains("1 1 0 rg"));+ let vertices = vec![[0.0, 0.0], [50.0, 0.0], [25.0, 40.0]];+ let g = add_annotation(&mut doc, &new(0, Shape::Polygon { vertices, cloud: false }), &meta("g")).unwrap();+ set_fill(&mut doc, 0, g, Some([1.0, 0.0, 0.0]), &meta("")).unwrap();+ assert!(ap_content(&doc, &list(&doc, 0)[g]).contains("1 0 0 rg"));+ // Lines have no interior, and bad colours change nothing.+ let l = add_annotation(+ &mut doc,+ &new(0, Shape::Line { from: [0.0, 0.0], to: [10.0, 10.0], start: LineEnding::None, end: LineEnding::None }),+ &meta("l"),+ )+ .unwrap();+ assert!(!props(&doc, 0, l).unwrap().fillable);+ assert!(matches!(set_fill(&mut doc, 0, l, Some([1.0; 3]), &meta("")), Err(AnnotError::Invalid(_))));+ let before = list(&doc, 0)[r].clone();+ assert!(matches!(set_fill(&mut doc, 0, r, Some([f64::NAN, 0.0, 0.0]), &meta("")), Err(AnnotError::Invalid(_))));+ assert_eq!(list(&doc, 0)[r], before);+ assert!(set_fill(&mut doc, 0, 99, None, &meta("")).is_err());+}+#[test]fn text_box_text_and_colour_changes_are_drawn() {let mut doc = fixture();diff --git a/crates/automation/src/comments.rs b/crates/automation/src/comments.rsindex c6e722d2c..4aac6ac55 100644--- a/crates/automation/src/comments.rs+++ b/crates/automation/src/comments.rs@@ -578,6 +578,10 @@ impl Automation {if color.is_some() || opacity.is_some() || width.is_some() {edits.push(Edit::StyleAnnotation { page, index, color, opacity, width, endings: None });}+ if let Some(f) = a.opt_str("fill")? {+ let fill = if f.eq_ignore_ascii_case("none") { None } else { Some(parse_color(f)?) };+ edits.push(Edit::FillAnnotation { page, index, fill });+ }if let Some(r) = a.nums::<4>("rect")? {edits.push(Edit::ResizeAnnotation { page, index, rect: rect_to_user(&info, r) });}diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rsindex 9c0489a8e..88fd8b7ab 100644--- a/crates/automation/src/tools.rs+++ b/crates/automation/src/tools.rs@@ -656,12 +656,13 @@ pub fn tools() -> Vec<ToolDef> {json!({ "doc": doc(), "sort": { "type": "string", "enum": ["page", "author", "date", "type"] }, "out": save_out, "open": open }),&["doc"],)),- t("comment_edit", "Edit a comment", "Change a comment's text, colour, opacity, line width, rectangle (rectangle/oval/text box/stamp) or position (`move` [dx, dy] in points). Stamps keep their original appearance when resized. One undo step.").with(schema(+ t("comment_edit", "Edit a comment", "Change a comment's text, colour, opacity, line width, fill (rectangle/oval/polygon; \"none\" removes it), rectangle (rectangle/oval/text box/stamp) or position (`move` [dx, dy] in points). Stamps keep their original appearance when resized. One undo step.").with(schema(comment_ref(json!({"contents": { "type": "string" },"color": color(),"opacity": { "type": "number", "minimum": 0, "maximum": 1 },"width": { "type": "number", "minimum": 0 },+ "fill": { "type": "string", "description": "Interior colour of a rectangle, oval or polygon: #RRGGBB, a colour name, or \"none\" for no fill." },"rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 },"move": point(),})),diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rsindex 2e89cc19b..fae13b60a 100644--- a/crates/automation/tests/automation.rs+++ b/crates/automation/tests/automation.rs@@ -989,6 +989,15 @@ fn comments_through_tools() {let undo = ok(&mut a, "edit_undo", json!({ "doc": doc }));assert_eq!(undo["undone"], "Edit comment");ok(&mut a, "edit_redo", json!({ "doc": doc }));+ // Rectangles, ovals and polygons take a fill (#686); "none" removes it. Lines have none.+ ok(&mut a, "comment_edit", json!({ "doc": doc, "page": page, "index": index, "fill": "yellow" }));+ ok(&mut a, "comment_edit", json!({ "doc": doc, "page": page, "index": index, "fill": "none" }));+ assert!(matches!(a.call("comment_edit", &json!({ "doc": doc, "page": page, "index": index, "fill": "mauve" })), Err(ToolError::InvalidArgs(_))));+ let arrow = ok(&mut a, "comment_list", json!({ "doc": doc, "page": 3 }))["comments"][0].clone();+ assert!(matches!(+ a.call("comment_edit", &json!({ "doc": doc, "page": arrow["page"], "index": arrow["index"], "fill": "red" })),+ Err(ToolError::Failed(_))+ ));// Editing a text box re-fits its rectangle to the new text: the wrap width and top edge// stay, the height follows the wrapped lines.diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex d1738a2f5..cb1494e1e 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -184,6 +184,7 @@ fn scope_of(edit: &Edit) -> Scope {| Edit::MoveAnnotation { .. }| Edit::ResizeAnnotation { .. }| Edit::StyleAnnotation { .. }+ | Edit::FillAnnotation { .. }| Edit::SetAnnotationInfo { .. } => Scope::Comments,Edit::SetFieldValue { .. } | Edit::ResetForm { .. } | Edit::SetFieldImage { .. } | Edit::ApplyScriptChanges { .. } => Scope::Form,Edit::Batch { edits, .. } => {@@ -879,6 +880,12 @@ pub enum Edit {/// Line or polyline: two endings. Callout: one. `None` leaves `/LE` unchanged.endings: Option<Vec<pdfcraft_annot::LineEnding>>,},+ /// Fill a rectangle, oval or polygon comment, or remove its fill (`None`).+ FillAnnotation {+ page: usize,+ index: usize,+ fill: Option<Rgb>,+ },/// Comment properties ▸ General / note icon.SetAnnotationInfo {page: usize,@@ -1156,7 +1163,7 @@ impl Edit {Edit::LockAnnotation { .. } => "Unlock comment".into(),Edit::MoveAnnotation { .. } => "Move comment".into(),Edit::ResizeAnnotation { .. } => "Resize comment".into(),- Edit::StyleAnnotation { .. } | Edit::SetAnnotationInfo { .. } => "Change comment properties".into(),+ Edit::StyleAnnotation { .. } | Edit::FillAnnotation { .. } | Edit::SetAnnotationInfo { .. } => "Change comment properties".into(),Edit::SetFieldValue { name, .. } => format!("Fill in {name}"),Edit::SetFieldImage { name, .. } => format!("Set the image of {name}"),Edit::ResetForm { .. } => "Clear form".into(),@@ -1295,6 +1302,7 @@ fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Result<(), Ed| Edit::MoveAnnotation { .. }| Edit::ResizeAnnotation { .. }| Edit::StyleAnnotation { .. }+ | Edit::FillAnnotation { .. }| Edit::SetAnnotationInfo { .. }| Edit::SetMeasurementScale { .. } => {if p.annotate() {@@ -1537,6 +1545,7 @@ fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) ->Edit::StyleAnnotation { page, index, color, opacity, width, endings } => {pdfcraft_annot::set_style(doc, *page, *index, *color, *opacity, *width, endings.as_deref(), &cx.meta())?;}+ Edit::FillAnnotation { page, index, fill } => pdfcraft_annot::set_fill(doc, *page, *index, *fill, &cx.meta())?,Edit::SetAnnotationInfo { page, index, author, subject, icon } => {pdfcraft_annot::set_info(doc, *page, *index, author.as_deref(), subject.as_deref(), *icon, &cx.meta())?;}diff --git a/crates/ui-egui/src/comment_props.rs b/crates/ui-egui/src/comment_props.rsindex 023f5b7e8..11776bcaf 100644--- a/crates/ui-egui/src/comment_props.rs+++ b/crates/ui-egui/src/comment_props.rs@@ -1,5 +1,5 @@//! Comment Properties (Acrobat: right-click a comment ▸ Properties…; audit "Comment-//! properties"): Appearance (colour, opacity, line thickness, note icon), General (author,+//! properties"): Appearance (colour, fill, opacity, line thickness, note icon), General (author,//! subject, modified) and Review History (status changes), with Acrobat's Locked box.use egui::{Align, Layout};@@ -100,6 +100,9 @@ impl PdfCraftApp {if let Some(w) = p.width {style.width = w;}+ if p.fillable && tool.has_fill() {+ style.fill = p.fill;+ }self.comment_prefs.set_style(tool, style);self.notify_fmt("New {tool} comments will look like this one", &[("tool", &crate::i18n::in_sentence(tl!(tool.label())))]);}@@ -128,6 +131,9 @@ pub fn edits(d: &PropsDraft) -> Vec<Edit> {if e.restylable && (color.is_some() || opacity.is_some() || width.is_some() || endings.is_some()) {out.push(Edit::StyleAnnotation { page: d.page, index: d.index, color, opacity, width, endings });}+ if e.restylable && e.fillable && e.fill != o.fill {+ out.push(Edit::FillAnnotation { page: d.page, index: d.index, fill: e.fill });+ }let author = (e.author != o.author).then(|| e.author.clone());let subject = (e.subject != o.subject).then(|| e.subject.clone());let icon = (e.icon != o.icon).then_some(e.icon).flatten();@@ -194,6 +200,13 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> (booe.color = Some(c);}ui.end_row();+ if e.fillable {+ ui.label(tl!("Fill colour"));+ if let Some(f) = crate::comments::fill_picker(ui, e.fill) {+ e.fill = f;+ }+ ui.end_row();+ }ui.label(tl!("Opacity"));let mut pct = e.opacity * 100.0;if ui.add(egui::Slider::new(&mut pct, 0.0..=100.0).suffix("%")).changed() {diff --git a/crates/ui-egui/src/comments.rs b/crates/ui-egui/src/comments.rsindex 4de1e2c0a..4f1a8b3fb 100644--- a/crates/ui-egui/src/comments.rs+++ b/crates/ui-egui/src/comments.rs@@ -191,6 +191,11 @@ impl CommentTool {self.draws() || self.clicks_points()}+ /// Whether the fill-colour control applies: shapes with an interior (#686).+ pub fn has_fill(self) -> bool {+ matches!(self, Self::Rectangle | Self::Oval | Self::Polygon | Self::Cloud)+ }+/// A placeholder shape of this kind (for per-tool default styles).fn sample(self) -> Shape {match self {@@ -287,6 +292,13 @@ impl CommentPrefs {}}+ /// The tool's fill (`None`: no fill). Only shapes with an interior keep one.+ pub fn set_fill(&mut self, tool: CommentTool, fill: Option<Rgb>) {+ if let Some((_, s)) = self.styles.iter_mut().find(|(t, _)| *t == tool) {+ s.fill = if tool.has_fill() { fill.filter(|c| c.iter().all(|x| x.is_finite())).map(|c| c.map(|x| x.clamp(0.0, 1.0))) } else { None };+ }+ }+pub fn set_style(&mut self, tool: CommentTool, style: Style) {if let Some((_, s)) = self.styles.iter_mut().find(|(t, _)| *t == tool) {*s = style;@@ -1359,7 +1371,23 @@ pub fn swatch_grid(ui: &mut egui::Ui, current: Option<Rgb>) -> Option<Rgb> {picked}-/// The comment tools' extra quick-bar controls: pin, colour, opacity and thickness.+/// "No fill" and the colour swatches; returns the choice clicked (`Some(None)`: no fill).+pub fn fill_picker(ui: &mut egui::Ui, current: Option<Rgb>) -> Option<Option<Rgb>> {+ let mut picked = None;+ ui.push_id("fill-picker", |ui| {+ ui.vertical(|ui| {+ if ui.selectable_label(current.is_none(), tl!("No fill")).clicked() {+ picked = Some(None);+ }+ if let Some(c) = swatch_grid(ui, current) {+ picked = Some(Some(c));+ }+ });+ });+ picked+}++/// The comment tools' extra quick-bar controls: pin, colour, fill, opacity and thickness.pub(crate) fn quick_bar_controls(ui: &mut egui::Ui, tool: CommentTool, prefs: &mut CommentPrefs) {let style = prefs.style(tool);if icons::button(ui, "pin", 32.0, prefs.pinned, if prefs.pinned { tl!("Keep tool selected: on") } else { tl!("Keep tool selected") }).clicked() {@@ -1375,6 +1403,16 @@ pub(crate) fn quick_bar_controls(ui: &mut egui::Ui, tool: CommentTool, prefs: &mui.close();}});+ if tool.has_fill() {+ let resp = fill_button(ui, style.fill);+ egui::Popup::menu(&resp).align(egui::RectAlign::RIGHT_START).show(|ui| {+ ui.label(egui::RichText::new(tl!("Fill colour")).font(theme::semibold(12.0)));+ if let Some(f) = fill_picker(ui, style.fill) {+ prefs.set_fill(tool, f);+ ui.close();+ }+ });+ }let resp = icons::button(ui, "blend", 32.0, false, tl!("Opacity"));egui::Popup::menu(&resp).align(egui::RectAlign::RIGHT_START).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {ui.set_min_width(180.0);@@ -1397,6 +1435,32 @@ pub(crate) fn quick_bar_controls(ui: &mut egui::Ui, tool: CommentTool, prefs: &m}}+/// The quick bar's fill button: a filled square in the fill colour, or a crossed-out outline+/// for no fill.+fn fill_button(ui: &mut egui::Ui, fill: Option<Rgb>) -> egui::Response {+ let (r, resp) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::click());+ let sq = Rect::from_center_size(r.center(), vec2(16.0, 16.0));+ let edge = Stroke::new(1.0, Color32::from_black_alpha(90));+ match fill {+ Some(c) => {+ ui.painter().rect_filled(sq, 2.0, color32(c));+ }+ None => {+ ui.painter().line_segment([sq.left_bottom(), sq.right_top()], Stroke::new(1.5, Color32::from_rgb(0xD3, 0x2F, 0x2F)));+ }+ }+ ui.painter().rect_stroke(sq, 2.0, edge, egui::StrokeKind::Inside);+ if resp.hovered() {+ ui.painter().rect_stroke(r.shrink(2.0), 6.0, Stroke::new(1.0, Color32::from_black_alpha(40)), egui::StrokeKind::Inside);+ }+ let label = match fill {+ Some(_) => tl!("Fill colour"),+ None => tl!("Fill colour: none"),+ };+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label));+ resp.on_hover_text(label)+}+/// Status badge icon and label for a review state name.pub fn status_badge(state: &str) -> Option<(&'static str, &'static str, Color32)> {match state {diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rsindex a250167ed..77ada1781 100644--- a/crates/ui-egui/src/editing.rs+++ b/crates/ui-egui/src/editing.rs@@ -639,6 +639,7 @@ fn comment_page(edit: &Edit) -> Option<usize> {| Edit::MoveAnnotation { page, .. }| Edit::ResizeAnnotation { page, .. }| Edit::StyleAnnotation { page, .. }+ | Edit::FillAnnotation { page, .. }| Edit::SetAnnotationInfo { page, .. } => Some(*page),_ => None,}diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsvindex acb60a847..0e85571ba 100644--- a/crates/ui-egui/src/i18n/ar.tsv+++ b/crates/ui-egui/src/i18n/ar.tsv@@ -2165,3 +2165,6 @@ certificate Subject صاحب الشهادةA selected field has no widget on any page, so the fields can't be edited together. أحد الحقول المحددة ليس له عنصر واجهة في أي صفحة، لذا لا يمكن تحرير الحقول معًا.Text recognition isn't installed: its models are missing (run `cargo xtask models`, or set PDFCRAFT_MODELS). التعرف على النص غير مثبت: نماذجه مفقودة (شغّل `cargo xtask models`، أو اضبط PDFCRAFT_MODELS).({n} at {dpi} dpi, the largest size they can be drawn at) ({n} بدقة {dpi} dpi، وهي أكبر دقة يمكن رسمها بها)+ Fill colour لون التعبئة+ No fill بلا تعبئة+ Fill colour: none لون التعبئة: بلاdiff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsvindex 5e98978d3..77454e13e 100644--- a/crates/ui-egui/src/i18n/bg.tsv+++ b/crates/ui-egui/src/i18n/bg.tsv@@ -2105,3 +2105,6 @@ action wizard Start СтартThe field {name} no longer exists. Полето {name} вече не съществува.A selected field has no widget on any page, so the fields can't be edited together. Едно от избраните полета няма елемент на нито една страница, затова полетата не могат да се редактират заедно.({n} at {dpi} dpi, the largest size they can be drawn at) ({n} с {dpi} dpi, най-голямата резолюция, с която могат да бъдат изобразени)+ Fill colour Цвят на запълване+ No fill Без запълване+ Fill colour: none Цвят на запълване: нямаdiff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex 2830d3f41..fb5205be0 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -2143,3 +2143,6 @@ action wizard Start StartenThe field {name} no longer exists. Das Feld {name} existiert nicht mehr.A selected field has no widget on any page, so the fields can't be edited together. Ein ausgewähltes Feld hat auf keiner Seite ein Widget, daher können die Felder nicht gemeinsam bearbeitet werden.({n} at {dpi} dpi, the largest size they can be drawn at) ({n} mit {dpi} dpi, der größten Auflösung, in der sie gezeichnet werden können)+ Fill colour Füllfarbe+ No fill Keine Füllung+ Fill colour: none Füllfarbe: keinediff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex 1d8ffcd26..6867503a0 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -2059,3 +2059,6 @@The field {name} no longer exists. El campo {name} ya no existe.A selected field has no widget on any page, so the fields can't be edited together. Un campo seleccionado no tiene ningún widget en ninguna página, así que los campos no se pueden editar juntos.({n} at {dpi} dpi, the largest size they can be drawn at) ({n} a {dpi} ppp, el mayor tamaño al que se pueden dibujar)+ Fill colour Color de relleno+ No fill Sin relleno+ Fill colour: none Color de relleno: ningunodiff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex ab1241076..e931cb518 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -2143,3 +2143,6 @@ signature pad Type SaisirThe field {name} no longer exists. Le champ {name} n'existe plus.A selected field has no widget on any page, so the fields can't be edited together. Un champ sélectionné n'a de widget sur aucune page : les champs ne peuvent pas être modifiés ensemble.({n} at {dpi} dpi, the largest size they can be drawn at) ({n} à {dpi} ppp, la plus grande taille possible pour les dessiner)+ Fill colour Couleur de fond+ No fill Sans fond+ Fill colour: none Couleur de fond : aucunediff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsvindex 813aa27d5..2965a4056 100644--- a/crates/ui-egui/src/i18n/hu.tsv+++ b/crates/ui-egui/src/i18n/hu.tsv@@ -2141,3 +2141,6 @@ action wizard Start IndításThe field {name} no longer exists. A(z) {name} mező már nem létezik.A selected field has no widget on any page, so the fields can't be edited together. Az egyik kijelölt mezőnek egyik oldalon sincs widgetje, ezért a mezők nem szerkeszthetők együtt.({n} at {dpi} dpi, the largest size they can be drawn at) ({n} {dpi} dpi felbontással, a legnagyobb méretben, amelyben megjeleníthetők)+ Fill colour Kitöltőszín+ No fill Nincs kitöltés+ Fill colour: none Kitöltőszín: nincsdiff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex 38c929395..21bd12f0c 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -2152,3 +2152,6 @@ signature pad Type DigitaThe field {name} no longer exists. Il campo {name} non esiste più.A selected field has no widget on any page, so the fields can't be edited together. Un campo selezionato non ha widget in nessuna pagina, quindi i campi non possono essere modificati insieme.({n} at {dpi} dpi, the largest size they can be drawn at) ({n} a {dpi} dpi, la dimensione massima a cui si possono disegnare)+ Fill colour Colore riempimento+ No fill Nessun riempimento+ Fill colour: none Colore riempimento: nessunodiff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex b44cbc77b..3def1d951 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -2143,3 +2143,6 @@ signature pad Type 入力The field {name} no longer exists. フィールド {name} はもう存在しません。A selected field has no widget on any page, so the fields can't be edited together. 選択したフィールドの一つがどのページにもウィジェットを持たないため、まとめて編集できません。({n} at {dpi} dpi, the largest size they can be drawn at) ({n} 件は描画できる最大サイズの {dpi} dpi で書き出しました)+ Fill colour 塗りつぶし色+ No fill 塗りつぶしなし+ Fill colour: none 塗りつぶし色: なしdiff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex 62527bb11..bdc1cc0cd 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -2144,3 +2144,6 @@ comment menu Edit EditarThe field {name} no longer exists. O campo {name} não existe mais.A selected field has no widget on any page, so the fields can't be edited together. Um campo selecionado não tem widget em nenhuma página, então os campos não podem ser editados juntos.({n} at {dpi} dpi, the largest size they can be drawn at) ({n} a {dpi} dpi, o maior tamanho em que podem ser desenhadas)+ Fill colour Cor de preenchimento+ No fill Sem preenchimento+ Fill colour: none Cor de preenchimento: nenhumadiff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex 631be2ce0..cd04f07f3 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -2056,3 +2056,6 @@The field {name} no longer exists. Поле {name} больше не существует.A selected field has no widget on any page, so the fields can't be edited together. У одного из выбранных полей нет виджета ни на одной странице, поэтому поля нельзя изменить вместе.({n} at {dpi} dpi, the largest size they can be drawn at) ({n} — с разрешением {dpi} dpi, максимальным, с каким их можно отрисовать)+ Fill colour Цвет заливки+ No fill Без заливки+ Fill colour: none Цвет заливки: нетdiff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex ae1349cd3..a35e000de 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -2166,3 +2166,6 @@ certificate Subject Власник сертифікатаThe field {name} no longer exists. Поле {name} більше не існує.A selected field has no widget on any page, so the fields can't be edited together. Одне з вибраних полів не має віджета на жодній сторінці, тому поля не можна редагувати разом.({n} at {dpi} dpi, the largest size they can be drawn at) ({n} — з роздільністю {dpi} dpi, найбільшою, з якою їх можна відобразити)+ Fill colour Колір заливки+ No fill Без заливки+ Fill colour: none Колір заливки: немаєdiff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex 0aca6798e..57a690fdf 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2107,3 +2107,6 @@The field {name} no longer exists. 字段 {name} 已不存在。A selected field has no widget on any page, so the fields can't be edited together. 某个所选字段在任何页面上都没有控件,因此无法一起编辑这些字段。({n} at {dpi} dpi, the largest size they can be drawn at) ({n} 张以可绘制的最大尺寸 {dpi} dpi 导出)+ Fill colour 填充颜色+ No fill 无填充+ Fill colour: none 填充颜色:无diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex ae7132dd4..db96639cc 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2029,3 +2029,6 @@The field {name} no longer exists. 欄位 {name} 已不存在。A selected field has no widget on any page, so the fields can't be edited together. 某個所選欄位在任何頁面上都沒有控制項,因此無法一起編輯這些欄位。({n} at {dpi} dpi, the largest size they can be drawn at) ({n} 張以可繪製的最大尺寸 {dpi} dpi 匯出)+ Fill colour 填充顏色+ No fill 無填充+ Fill colour: none 填充顏色:無diff --git a/crates/ui-egui/tests/comments.rs b/crates/ui-egui/tests/comments.rsindex ae5eb1c76..b4059276f 100644--- a/crates/ui-egui/tests/comments.rs+++ b/crates/ui-egui/tests/comments.rs@@ -360,6 +360,64 @@ fn comment_properties_change_appearance_and_author() {assert_eq!(doc.can_undo(), Some("Change comment properties"), "one undo step");}+/// #686: rectangles, ovals, polygons and clouds can be filled, from the quick bar for new ones+/// and from Properties for existing ones; "No fill" takes it away again.+#[test]+fn shapes_take_a_fill_colour_from_the_quick_bar_and_properties() {+ use pdfcraft_ui_egui::comments::CommentTool;+ let mut h = harness(|app| app.set_option("quick", "square").unwrap());+ h.run_steps(2);+ // No fill by default; the quick bar says so.+ h.get_by_label("Fill colour: none");+ h.state_mut().comment_prefs.set_fill(CommentTool::Rectangle, Some([1.0, 0.5, 0.0]));+ // Tools without an interior keep no fill.+ h.state_mut().comment_prefs.set_fill(CommentTool::Line, Some([1.0, 0.5, 0.0]));+ assert_eq!(h.state().comment_prefs.style(CommentTool::Line).fill, None);+ h.run_steps(2);+ drag_pt(&mut h, (40.0, 100.0), (140.0, 40.0));+ let fill_of = |h: &Harness<'static, PdfCraftApp>, index: usize| {+ let s = h.state();+ let doc = s.session.get(s.views[0].id).unwrap();+ let p = doc.comment_props(0, index).unwrap();+ assert!(p.fillable);+ p.fill+ };+ assert_eq!(fill_of(&h, 0), Some([1.0, 0.5, 0.0]), "the new rectangle is filled");+ // Quick bar ▸ Fill colour ▸ No fill: the next rectangle has none.+ h.state_mut().set_option("quick", "square").unwrap();+ h.run_steps(2);+ h.get_by_label("Fill colour").click();+ h.run_steps(2);+ h.get_by_label("No fill").click();+ h.run_steps(2);+ assert_eq!(h.state().comment_prefs.style(CommentTool::Rectangle).fill, None);+ drag_pt(&mut h, (160.0, 100.0), (260.0, 40.0));+ assert_eq!(fill_of(&h, 1), None);++ // Properties ▸ Fill colour changes an existing one, as one undo step.+ h.state_mut().open_comment_props(0, 0);+ h.run_steps(2);+ h.get_by_label("Rectangle Properties");+ h.get_by_label("Fill colour");+ assert_eq!(h.state().comment_props.as_ref().unwrap().original.fill, Some([1.0, 0.5, 0.0]));+ h.get_by_label("No fill").click();+ h.run_steps(2);+ h.get_by_label("OK").click();+ h.run_steps(3);+ assert_eq!(fill_of(&h, 0), None);+ let undo = h.state().session.get(h.state().views[0].id).unwrap().can_undo().map(str::to_owned);+ assert_eq!(undo.as_deref(), Some("Change comment properties"));+ h.state_mut().open_comment_props(0, 1);+ h.run_steps(2);+ h.state_mut().comment_props.as_mut().expect("open").edited.fill = Some([0.0, 0.0, 1.0]);+ h.get_by_label("OK").click();+ h.run_steps(3);+ assert_eq!(fill_of(&h, 1), Some([0.0, 0.0, 1.0]));+ // Make Current Properties Default carries the fill into the tool.+ h.state_mut().make_comment_default(0, 1);+ assert_eq!(h.state().comment_prefs.style(CommentTool::Rectangle).fill, Some([0.0, 0.0, 1.0]));+}+#[test]fn the_panel_filters_and_sorts() {let mut h = harness(|app| {diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.tomlindex 098bffc19..40f9c89aa 100644--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@ -3662,8 +3662,8 @@ milestone = "M5"status = "shipped"commands = ["comment.square"]tools = ["comment_add", "comment_edit"]-evidence = ["crates/ui-egui/tests/comments.rs::shapes_and_ink_are_drawn_by_dragging", "crates/annot/src/tests.rs::restyle_and_resize_redraw_the_appearance"]-notes = "resize with the 8 handles"+evidence = ["crates/ui-egui/tests/comments.rs::shapes_and_ink_are_drawn_by_dragging", "crates/annot/src/tests.rs::restyle_and_resize_redraw_the_appearance", "crates/annot/src/tests.rs::shapes_can_be_filled_and_unfilled", "crates/ui-egui/tests/comments.rs::shapes_take_a_fill_colour_from_the_quick_bar_and_properties"]+notes = "resize with the 8 handles; fill colour or no fill (#686) from the quick bar, Properties and comment_edit `fill`; fill swatches are the comment palette only (no custom colour picker yet)"[[feature]]id = "comment.oval"@@ -3782,8 +3782,8 @@ milestone = "M5"status = "shipped"commands = ["comment.list"]tools = ["comment_edit"]-evidence = ["crates/ui-egui/tests/comments.rs::comment_properties_change_appearance_and_author", "crates/annot/src/tests.rs::author_subject_and_note_icon_change"]-notes = "Appearance (colour, opacity, thickness, note icon), General (author, subject), Review History"+evidence = ["crates/ui-egui/tests/comments.rs::comment_properties_change_appearance_and_author", "crates/annot/src/tests.rs::author_subject_and_note_icon_change", "crates/ui-egui/tests/comments.rs::shapes_take_a_fill_colour_from_the_quick_bar_and_properties"]+notes = "Appearance (colour, fill colour for rectangles/ovals/polygons, opacity, thickness, note icon), General (author, subject), Review History"[[feature]]id = "comment.properties-bar"@@ -3795,7 +3795,7 @@ status = "shipped"commands = ["comment.note"]tools = ["comment_edit"]evidence = ["crates/annot/src/tests.rs::restyle_and_resize_redraw_the_appearance", "crates/ui-egui/tests/comments.rs::the_opacity_set_for_a_tool_goes_into_its_new_comments"]-notes = "quick-bar colour swatches, opacity (10–100 %) and line thickness per tool; colour from the context menu"+notes = "quick-bar colour swatches, fill colour (rectangle, oval, polygon, cloud), opacity (10–100 %) and line thickness per tool; colour from the context menu"[[feature]]id = "comment.lock-comment"