PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Merge remote-tracking branch 'origin/main' into integration-batch-7
David Mann8c04b175ecd3
diff --cc Cargo.lockindex 8f3ef03ec,c925c8f29..df709e58d--- a/Cargo.lock+++ b/Cargo.lock@@@ -4784,10 -4783,9 +4784,10 @@@ dependencies =[[package]]name = "photocraft-compose"- version = "0.15.0"+ version = "0.15.1"dependencies = ["criterion",+ "photocraft-cms","photocraft-color","photocraft-doc","photocraft-geom",diff --cc crates/automation/src/rpc.rsindex 0b388ff76,7d52291f4..5fea45027--- a/crates/automation/src/rpc.rs+++ b/crates/automation/src/rpc.rs@@@ -734,76 -724,59 +734,129 @@@ mod testsstd::fs::remove_dir_all(base).unwrap();}+ #[test]+ fn doc_replace_smart_object_reads_through_the_read_root_and_never_outside_it() {+ let base = std::env::temp_dir().join(format!("pc-doc-replace-so-{}", std::process::id()));+ let root = base.join("workspace");+ let outside = base.join("outside");+ for dir in [&root, &outside] {+ std::fs::create_dir_all(dir).unwrap();+ }+ let png = |w: u32, h: u32, v: u8| {+ let img = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, vec![v; (w * h * 3) as usize]).unwrap();+ photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()+ };+ std::fs::write(root.join("logo.png"), png(8, 6, 42)).unwrap();+ std::fs::write(root.join("red.png"), png(8, 6, 200)).unwrap();+ std::fs::write(outside.join("red.png"), png(8, 6, 200)).unwrap();+ let absolute = outside.join("red.png").to_string_lossy().into_owned();++ let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap());+ h.handle("doc.new", json!({"width": 40, "height": 30})).unwrap();+ let layer = h.handle("doc.place", json!({"path": "logo.png"})).unwrap()["layer"].clone();+ // The smart object's file name and the composite at its centre: what Replace Contents changes.+ let contents = |h: &mut Headless| {+ let inspected = h.handle("doc.inspect", json!({})).unwrap();+ let layers = inspected["layers"].as_array().unwrap();+ let so = layers.iter().find(|l| l["id"] == layer).unwrap_or_else(|| panic!("{inspected}"));+ let name = so["smartSource"]["fileName"].as_str().unwrap_or_default().to_owned();+ let rendered = h.handle("doc.render", json!({"maxSide": 0})).unwrap();+ let png = base64::engine::general_purpose::STANDARD.decode(rendered["base64"].as_str().unwrap()).unwrap();+ let img = photocraft_codecs::decode(&png).unwrap();+ let (w, ht) = img.dimensions();+ let data = img.as_u8().unwrap();+ let channels = data.len() / (w * ht) as usize;+ (name, data[((ht / 2 * w + w / 2) as usize) * channels])+ };+ assert_eq!(contents(&mut h), ("logo.png".to_owned(), 42), "the placed contents");+ let replaced = h.handle("doc.replaceSmartObject", json!({"path": "red.png", "layer": layer})).unwrap();+ assert_eq!(replaced["layer"], layer, "{replaced}");+ assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "the contents were replaced");+ h.handle("engine.execute", json!({"command": "edit.undo"})).unwrap();+ assert_eq!(contents(&mut h), ("logo.png".to_owned(), 42), "one undo step restores the old contents");+ h.handle("engine.execute", json!({"command": "edit.redo"})).unwrap();+ assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "redo replaces them again");+ // Outside the read root, a bad layer, a missing path or a file that is no image: refused, nothing changed.+ for (params, reason) in [+ (json!({"path": "../outside/red.png"}), "parent traversal"),+ (json!({"path": absolute}), "must be inside the automation root"),+ (json!({"path": "logo.png", "layer": 999_999}), "no such layer"),+ (json!({}), "needs `path`"),+ ] {+ let refused = h.handle("doc.replaceSmartObject", params).unwrap_err().to_string();+ assert!(refused.contains(reason), "{refused}");+ assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "nothing changed: {refused}");+ }+ std::fs::write(root.join("junk.png"), b"not an image").unwrap();+ assert!(h.handle("doc.replaceSmartObject", json!({"path": "junk.png", "layer": layer})).is_err());+ assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "a file that is no image changes nothing");+ // The ambient command keeps its refusal.+ let ambient = h.handle("engine.execute", json!({"command": "layer.smartObjects.replaceContents", "params": {"path": "red.png"}}));+ assert!(ambient.unwrap_err().to_string().contains("ambient filesystem paths"));+ // Trusted local keeps the ambient command.+ let mut t = Headless::trusted_local();+ t.handle("doc.new", json!({"width": 40, "height": 30})).unwrap();+ let tl = t.handle("doc.place", json!({"path": root.join("logo.png").to_string_lossy()})).unwrap()["layer"].clone();+ let trusted = t.handle("doc.replaceSmartObject", json!({"path": root.join("red.png").to_string_lossy(), "layer": tl})).unwrap();+ assert_eq!(trusted["layer"], tl, "{trusted}");+ drop(t);+ drop(h);+ std::fs::remove_dir_all(base).unwrap();+ }++ #[test]+ fn doc_export_layers_reports_skips_in_workspace_and_trusted_sessions() {+ for trusted in [false, true] {+ let base = std::env::temp_dir().join(format!("pc-export-skips-{}-{trusted}", std::process::id()));+ let _ = std::fs::remove_dir_all(&base);+ std::fs::create_dir_all(&base).unwrap();+ let mut h =+ if trusted { Headless::trusted_local() } else { Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&base), Some(&base)).unwrap()) };+ h.handle("doc.new", json!({"width": 4, "height": 4, "background": "white", "name": "card"})).unwrap();+ let adjustment = h.handle("engine.execute", json!({"command": "layer.newAdjustmentLayer.levels"})).unwrap()["layer"].clone();+ h.handle("engine.execute", json!({"command": "layer.setProps", "params": {"name": "Levels"}})).unwrap();+ let hidden = h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {"name": "Hidden"}})).unwrap()["layer"].clone();+ h.handle("engine.execute", json!({"command": "layer.setProps", "params": {"visible": false}})).unwrap();+ // Exercise the actual JSON-lines serve envelope, not only direct dispatch.+ let h = Mutex::new(h);+ let out_dir = base.join("out").to_string_lossy().into_owned();+ let request = json!({"id": 8491, "method": "doc.exportLayers", "params": {"dir": out_dir}}).to_string() + "\n";+ let mut output = Vec::new();+ serve_lines(&h, request.as_bytes(), &mut output).unwrap();+ let reply: Value = serde_json::from_slice(&output).unwrap();+ assert_eq!(reply["id"], 8491);+ assert_eq!(reply["ok"], true, "{reply}");+ assert_eq!(reply["result"]["files"], json!([format!("{out_dir}/card_0001_Background.png")]));+ if !trusted {+ assert_eq!(reply["result"]["count"], 1);+ }+ assert_eq!(+ reply["result"]["skipped"],+ json!([+ {"layer": hidden, "name": "Hidden", "reason": "hidden by visibleOnly"},+ {"layer": adjustment, "name": "Levels", "reason": "adjustment layer has no pixels of its own"}+ ])+ );+ assert_eq!(std::fs::read_dir(base.join("out")).unwrap().count(), 1);+ let mut h = h.into_inner().unwrap();+ let all_dir = base.join("all").to_string_lossy().into_owned();+ let all = h.export_layers(None, &all_dir, &json!({"visibleOnly": false})).unwrap();+ assert_eq!(all["files"].as_array().unwrap().len(), 2);+ assert_eq!(all["skipped"].as_array().unwrap().len(), 1);+ // Workspace no-overwrite errors still fail and remove only newly created files.+ if !trusted {+ let collision = base.join("collision");+ std::fs::create_dir_all(&collision).unwrap();+ std::fs::write(collision.join("card_0002_Background.png"), b"keep").unwrap();+ assert!(h.export_layers(None, &collision.to_string_lossy(), &json!({"visibleOnly": false})).is_err());+ assert_eq!(std::fs::read_dir(&collision).unwrap().count(), 1);+ assert_eq!(std::fs::read(collision.join("card_0002_Background.png")).unwrap(), b"keep");+ }+ drop(h);+ std::fs::remove_dir_all(base).unwrap();+ }+ }+#[test]fn doc_export_layers_writes_only_beneath_the_write_root() {let base = std::env::temp_dir().join(format!("pc-doc-export-layers-{}", std::process::id()));diff --cc crates/automation/src/server.rsindex 04a849f33,1174c5f84..f5ccef00c--- a/crates/automation/src/server.rs+++ b/crates/automation/src/server.rs@@@ -651,34 -644,8 +659,34 @@@ impl PhotocraftMcpself.run_command("file.placeEmbedded".into(), bridge_params, true).await}+ #[tool(+ description = "Replace a Smart Object's contents with the file at `path` beneath the read root, keeping its transform and filters (the capability-scoped Replace Contents). `layer` is the Smart Object's id or name (default: the active layer)."+ )]+ async fn doc_replace_smart_object(&self, Parameters(p): Parameters<ReplaceSmartObjectParams>) -> Result<CallToolResult, McpError> {+ let mut opts = serde_json::Map::new();+ if let Some(v) = p.layer {+ opts.insert("layer".into(), v);+ }+ let opts = Value::Object(opts);+ // Bridge mode runs the app on this machine, which reads the path itself like any command.+ let mut bridge_params = opts.clone();+ if let Some(o) = bridge_params.as_object_mut() {+ o.insert("path".into(), Value::String(p.path.clone()));+ }+ let (path, index) = (p.path, p.index);+ if let Some(r) = self.headless_op(move |h| h.replace_smart_object(index, &path, &opts)).await {+ return to_result(r);+ }+ // The app's command runs on its active document: an `index` it cannot honour is refused+ // rather than dropped, or another document's contents would be replaced.+ if index.is_some() {+ return Ok(fail("`index` is only supported in headless mode; in bridge mode select the document in the app first"));+ }+ self.run_command("layer.smartObjects.replaceContents".into(), bridge_params, true).await+ }+#[tool(- description = "Export each exported layer of the document as its own file beneath the write root (the capability-scoped Layers to Files). A file that already exists is an error, not an overwrite."+ description = "Export top-level layers as files (groups merged). Returns files and skipped: [{layer, name, reason}] for hidden layers (visible_only) and adjustments with no pixels of their own. Workspace exports resolve beneath the write root, also return count of written files, and reject existing files instead of overwriting them. Trusted-local/bridge exports use the engine command's file access policy.")]async fn doc_export_layers(&self, Parameters(p): Parameters<ExportLayersParams>) -> Result<CallToolResult, McpError> {let mut opts = serde_json::Map::new();diff --cc crates/gpu/src/health.rsindex 0216b7c41,948ef2804..18e255feb--- a/crates/gpu/src/health.rs+++ b/crates/gpu/src/health.rs@@@ -99,36 -110,22 +110,45 @@@ impl DeviceHealthself.0.errors.fetch_add(1, Ordering::Relaxed);let text = e.to_string();log::error!("uncaptured wgpu error: {text}");- self.mark(fault_of(&text));- // Errors about invalid or lost objects follow a device loss whose callback may not have- // run yet (it fires on the next poll).- let lower = text.to_ascii_lowercase();- let fault = if matches!(e, wgpu::Error::OutOfMemory { .. }) {- Fault::Error(OUT_OF_MEMORY.into())- } else if lower.contains("lost") || lower.contains("destroyed") {- Fault::Lost(first_line(&text))- } else {- Fault::Error(first_line(&text))- };- self.mark(fault);++ self.mark(fault_of(e));+ }++ /// Record an error an error scope caught.+ ///+ /// [`DeviceHealth::watch`]'s uncaptured-error handler never sees a scoped error, so without+ /// this a watched device would keep being handed to a GPU that has already failed. Polls+ /// first: a lost device is a [`Fault::Lost`], and its callback may not have run yet (it fires+ /// on a poll, and `Device::poll` panics on a lost device).+ ///+ /// The poll is a single non-blocking check, never a fence wait. This runs on the UI thread+ /// immediately after a failed frame, so `PollType::Wait` with no timeout would stall the app+ /// until every in-flight submission drained (or forever, if the device is wedged). A+ /// non-blocking poll loses nothing here: wgpu still reads the fence and fires the+ /// device-lost callback for a lost device, it just never blocks waiting for one.++ ///++ /// A device that only recorded an error is still polled and marked, so a loss or an++ /// out-of-memory error can upgrade that fault as [`DeviceHealth::mark`] allows (#6564).+ pub fn caught(&self, device: &wgpu::Device, error: &wgpu::Error) {- if !self.is_ok() {++ if self.lost() {+ return;+ }+ #[cfg(not(target_arch = "wasm32"))]+ self.poll(device);+ #[cfg(target_arch = "wasm32")]+ let _ = device;- if !self.is_ok() {++ if self.lost() {+ return;+ }- self.mark(fault_of(&error.to_string()));++ self.mark(fault_of(error));++ }++++ fn lost(&self) -> bool {++ self.fault().is_some_and(|f| f.is_lost())}- /// Mark the device unusable. The first fault is kept; a later device loss upgrades an error.+ /// Mark the device unusable. The first fault is kept; a later device loss upgrades an error,+ /// and a later out-of-memory error upgrades another one, so the canvas can still recover by+ /// itself when memory ran out after a validation error in the same frame (#6564).pub fn mark(&self, fault: Fault) {let mut slot = self.0.fault.lock().unwrap_or_else(PoisonError::into_inner);let replace = match slot.as_ref() {@@@ -214,14 -211,6 +234,21 @@@}}- /// The fault a wgpu error message stands for. Errors about invalid or lost objects follow a- /// device loss whose callback may not have run yet (it fires on the next poll), so they count as- /// a loss rather than as an error.- fn fault_of(text: &str) -> Fault {++/// The fault a wgpu error stands for. Errors about invalid or lost objects follow a device loss++/// whose callback may not have run yet (it fires on the next poll), so they count as a loss++/// rather than as an error. Only wgpu's own out-of-memory error is [`OUT_OF_MEMORY`].++fn fault_of(e: &wgpu::Error) -> Fault {++ let text = e.to_string();+ let lower = text.to_ascii_lowercase();- if lower.contains("lost") || lower.contains("destroyed") { Fault::Lost(first_line(text)) } else { Fault::Error(first_line(text)) }++ if matches!(e, wgpu::Error::OutOfMemory { .. }) {++ Fault::Error(OUT_OF_MEMORY.into())++ } else if lower.contains("lost") || lower.contains("destroyed") {++ Fault::Lost(first_line(&text))++ } else {++ Fault::Error(first_line(&text))++ }+}+fn first_line(s: &str) -> String {let line = s.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("");let mut out: String = line.chars().take(200).collect();diff --cc crates/text/src/tests.rsindex e4bbe1bc4,6c0f1fedb..4fe970994--- a/crates/text/src/tests.rs+++ b/crates/text/src/tests.rs@@@ -2745,288 -2699,51 +2777,337 @@@ fn a_word_wider_than_the_paragraph_box_assert_eq!(l.lines[1].range.start, 3, "{:?}", l.lines);}+/// Closed polygon in text space.+fn area_poly(pts: &[(f64, f64)]) -> photocraft_doc::vector::Path {+ photocraft_doc::vector::Path::new(vec![photocraft_doc::vector::Subpath::polygon(pts)])+}++/// An ellipse from four kappa curves inside `[x, y, w, h]`.+fn area_ellipse(x: f64, y: f64, w: f64, h: f64) -> photocraft_doc::vector::Path {+ use photocraft_doc::vector::{Knot, Subpath};+ use photocraft_geom::Point;+ let (rx, ry, cx, cy) = (w / 2.0, h / 2.0, x + w / 2.0, y + h / 2.0);+ let (kx, ky) = (0.552_284_75 * rx, 0.552_284_75 * ry);+ let p = Point::new;+ let knots = vec![+ Knot::smooth(p(cx, y), p(cx - kx, y), p(cx + kx, y)),+ Knot::smooth(p(x + w, cy), p(x + w, cy - ky), p(x + w, cy + ky)),+ Knot::smooth(p(cx, y + h), p(cx + kx, y + h), p(cx - kx, y + h)),+ Knot::smooth(p(x, cy), p(x, cy + ky), p(x, cy - ky)),+ ];+ photocraft_doc::vector::Path::new(vec![Subpath { closed: true, knots, op: Default::default() }])+}++const BUBBLE_TEXT: &str = "Well, that went better than expected. Now where did the cat hide the keys this time?";++/// Every laid-out line sits inside a span of the shape across its band.+fn assert_lines_inside(l: &crate::TextLayout, path: &photocraft_doc::vector::Path) {+ let a = crate::area::AreaShape::new(path, false).unwrap();+ for line in &l.lines {+ let spans = a.spans(line.baseline - line.ascent, line.baseline + line.descent, 0.0);+ assert!(spans.iter().any(|&(s0, s1)| line.x0 >= s0 - 0.5 && line.x1 <= s1 + 0.5), "{line:?} not inside {spans:?}");+ }+}++#[test]+fn area_text_stays_inside_an_ellipse() {+ let mut e = TextEngine::new();+ let mut t = point(BUBBLE_TEXT, 18.0);+ let path = area_ellipse(0.0, 0.0, 260.0, 160.0);+ t.shape = TextShape::Area { path: path.clone() };+ let l = e.layout(&t, 72.0);+ assert!(l.lines.len() >= 4, "{}", l.lines.len());+ assert_lines_inside(&l, &path);+ // The top of an ellipse is too narrow for a line at its very edge: the first line starts lower.+ assert!(l.lines[0].baseline - l.lines[0].ascent > 1.0, "{:?}", l.lines[0]);+ // Lines go down the shape in text order.+ for w in l.lines.windows(2) {+ assert!(w[1].baseline >= w[0].baseline && w[1].range.start >= w[0].range.end, "{w:?}");+ }+ // Middle lines are wider than the first (the ellipse is widest in the middle).+ let width = |i: usize| l.lines[i].x1 - l.lines[i].x0;+ assert!(width(l.lines.len() / 2) > width(0), "{l:?}");+}++#[test]+fn area_overflow_is_hidden() {+ let mut e = TextEngine::new();+ let mut t = point(&BUBBLE_TEXT.repeat(10), 14.0);+ let path = area_ellipse(0.0, 0.0, 200.0, 80.0);+ t.shape = TextShape::Area { path: path.clone() };+ let l = e.layout(&t, 72.0);+ assert!(!l.lines.is_empty());+ assert!(l.lines.last().unwrap().range.end < t.text.len(), "the rest is hidden");+ assert_lines_inside(&l, &path);+}++/// A long word that reaches the narrow bottom of a full bubble is hidden with the rest, not+/// drawn past the outline: the wide middle rows would hold it, so the shape just ran out.+#[test]+fn area_overflow_at_the_narrow_bottom_is_hidden() {+ let mut e = TextEngine::new();+ let words = "Unfortunately the misunderstanding between representatives continued indefinitely. ";+ for (w, h, size) in [(260.0, 160.0, 12.0), (180.0, 140.0, 14.0), (150.0, 220.0, 12.0)] {+ let mut t = point(&words.repeat(8), size);+ let path = area_ellipse(0.0, 0.0, w, h);+ t.shape = TextShape::Area { path: path.clone() };+ let l = e.layout(&t, 72.0);+ assert!(!l.lines.is_empty());+ assert!(l.lines.last().unwrap().range.end < t.text.len(), "the rest is hidden");+ assert_lines_inside(&l, &path);+ }+}++/// The same in a later paragraph: its own rows start below the wide top of the shape, but the+/// shape would still hold the word there, so it is hidden rather than drawn past the outline.+#[test]+fn area_overflow_in_a_later_paragraph_is_hidden() {+ let mut e = TextEngine::new();+ // A funnel: 300 px wide at the top, a point at the bottom.+ let path = area_poly(&[(0.0, 0.0), (300.0, 0.0), (150.0, 300.0)]);+ for n in (10..120).step_by(5) {+ let text = format!("{}\nmisunderstanding and more", "cat ".repeat(n));+ let mut t = point(&text, 12.0);+ t.shape = TextShape::Area { path: path.clone() };+ let l = e.layout(&t, 72.0);+ assert_lines_inside(&l, &path);+ }+}++#[test]+fn area_lines_center_in_their_span() {+ let mut e = TextEngine::new();+ let mut t = point(BUBBLE_TEXT, 12.0);+ t.paragraphs = vec![ParagraphRun { len: t.text.len(), style: ParagraphStyle { align: TextAlign::Center, ..Default::default() } }];+ // A diamond: every row's span is centred on x = 100.+ t.shape = TextShape::Area { path: area_poly(&[(100.0, 0.0), (200.0, 100.0), (100.0, 200.0), (0.0, 100.0)]) };+ let l = e.layout(&t, 72.0);+ assert!(l.lines.len() >= 3);+ for line in &l.lines {+ assert!(((line.x0 + line.x1) / 2.0 - 100.0).abs() < 1.5, "{line:?}");+ }+}++/// Horizontal scale applies after shaping, so area lines break at the span width divided by it:+/// widened text stays inside the shape and centred lines stay centred (#5565).+#[test]+fn horizontally_scaled_area_text_stays_inside_its_spans() {+ let mut e = TextEngine::new();+ let style = CharStyle { font_family: "Inter".into(), size_pt: 12.0, horizontal_scale: 1.5, ..Default::default() };+ let mut t = styled(BUBBLE_TEXT, style);+ let path = area_ellipse(0.0, 0.0, 240.0, 200.0);+ t.shape = TextShape::Area { path: path.clone() };+ let l = e.layout(&t, 72.0);+ assert!(l.lines.len() >= 3, "{:?}", l.lines);+ assert_lines_inside(&l, &path);+ t.paragraphs = vec![ParagraphRun { len: t.text.len(), style: ParagraphStyle { align: TextAlign::Center, ..Default::default() } }];+ t.shape = TextShape::Area { path: area_poly(&[(100.0, 0.0), (200.0, 100.0), (100.0, 200.0), (0.0, 100.0)]) };+ let l = e.layout(&t, 72.0);+ assert!(l.lines.len() >= 2, "{:?}", l.lines);+ for line in &l.lines {+ assert!(((line.x0 + line.x1) / 2.0 - 100.0).abs() < 1.5, "{line:?}");+ }+}++#[test]+fn area_rows_split_around_a_hole() {+ use photocraft_doc::vector::{PathOp, Subpath};+ let mut e = TextEngine::new();+ let mut t = point(&BUBBLE_TEXT.repeat(6), 12.0);+ let path = photocraft_doc::vector::Path::new(vec![+ Subpath::polygon(&[(0.0, 0.0), (300.0, 0.0), (300.0, 300.0), (0.0, 300.0)]),+ Subpath::polygon(&[(120.0, 100.0), (180.0, 100.0), (180.0, 200.0), (120.0, 200.0)]).with_op(PathOp::Subtract),+ ]);+ t.shape = TextShape::Area { path: path.clone() };+ let l = e.layout(&t, 72.0);+ assert_lines_inside(&l, &path);+ // Some baseline carries two lines: one left of the hole, one right of it, left first.+ let w = l.lines.windows(2).find(|w| (w[0].baseline - w[1].baseline).abs() < 1e-3).expect("a row split around the hole");+ let (left, right) = (&w[0], &w[1]);+ assert!(left.x1 <= 120.5 && right.x0 >= 179.5, "{left:?} {right:?}");+}++#[test]+fn vertical_area_text_stays_inside() {+ use photocraft_doc::text::Orientation;+ let mut e = TextEngine::new();+ let mut t = point(BUBBLE_TEXT, 12.0);+ t.orientation = Orientation::Vertical;+ t.shape = TextShape::Area { path: area_poly(&[(0.0, 0.0), (120.0, 0.0), (120.0, 200.0), (0.0, 200.0)]) };+ let l = e.layout(&t, 72.0);+ assert!(l.lines.len() >= 2, "several columns");+ for g in &l.glyphs {+ assert!(g.x > -1.0 && g.x < 121.0 && g.y > -1.0 && g.y < 201.0, "{g:?}");+ }+}++#[test]+fn area_without_room_lays_out_nothing_and_a_bad_path_lays_out_as_point_text() {+ let mut e = TextEngine::new();+ let mut t = point("Hello", 40.0);+ // 10 px tall: no 40 pt line fits.+ t.shape = TextShape::Area { path: area_poly(&[(0.0, 0.0), (300.0, 0.0), (300.0, 10.0), (0.0, 10.0)]) };+ assert!(e.layout(&t, 72.0).lines.is_empty());+ // An open path encloses nothing (only reachable from a hostile file): point text, no panic.+ t.shape = TextShape::Area { path: photocraft_doc::vector::Path::new(vec![photocraft_doc::vector::Subpath::polyline(&[(0.0, 0.0), (9.0, 9.0)])]) };+ let point_layout = e.layout(&point("Hello", 40.0), 72.0);+ assert_eq!(e.layout(&t, 72.0).lines.len(), point_layout.lines.len());+}++#[test]+fn area_word_wider_than_every_span_overflows_instead_of_hiding_the_text() {+ use photocraft_doc::vector::Subpath;+ let mut e = TextEngine::new();+ // Two 40 px columns 120 px apart: their bounding box is 200 px wide, but no span is wider+ // than 40 px, so no row can ever hold the long word.+ let mut t = point("Wonderfulness is a long word", 12.0);+ let path = photocraft_doc::vector::Path::new(vec![+ Subpath::polygon(&[(0.0, 0.0), (40.0, 0.0), (40.0, 200.0), (0.0, 200.0)]),+ Subpath::polygon(&[(160.0, 0.0), (200.0, 0.0), (200.0, 200.0), (160.0, 200.0)]),+ ]);+ t.shape = TextShape::Area { path };+ let l = e.layout(&t, 72.0);+ let first = l.lines.first().expect("the text is shown");+ // The word overflows its 40 px span on the first row (box text would break it, #6694).+ assert!(first.x1 - first.x0 > 40.0 && first.x1 - first.x0 < 200.0, "{first:?}");+ assert!(first.x0 >= -0.5, "{first:?}");+ // Nothing is hidden.+ assert_eq!(l.lines.last().map(|line| line.range.end), Some(t.text.len()), "{:?}", l.lines);+}++#[test]+fn single_size_area_paragraph_breaks_in_one_pass() {+ let mut e = TextEngine::new();+ let mut t = point(BUBBLE_TEXT, 12.0);+ t.shape = TextShape::Area { path: area_poly(&[(0.0, 0.0), (300.0, 0.0), (300.0, 300.0), (0.0, 300.0)]) };+ crate::layout::AREA_PASSES.with(|c| c.set(0));+ let l = e.layout(&t, 72.0);+ assert!(l.lines.len() >= 2);+ // Rows are planned with the paragraph's real metrics: no re-plan and no skipped spans.+ assert_eq!(crate::layout::AREA_PASSES.with(|c| c.get()), 1);+}++#[test]+fn area_word_skips_a_narrow_span_for_a_wider_one_on_the_same_row() {+ let mut e = TextEngine::new();+ let mut t = point("Wonderful things happen in speech bubbles every single day.", 12.0);+ // A U: a 24 px left arm and a wide right arm above y = 150, joined below it.+ let path = area_poly(&[(0.0, 0.0), (24.0, 0.0), (24.0, 150.0), (80.0, 150.0), (80.0, 0.0), (300.0, 0.0), (300.0, 200.0), (0.0, 200.0)]);+ t.shape = TextShape::Area { path: path.clone() };+ let l = e.layout(&t, 72.0);+ assert_lines_inside(&l, &path);+ let first = l.lines.first().expect("the text is shown");+ // "Wonderful" is wider than the left arm: it starts the text in the right arm, on the first+ // row, and nothing is put in the left arm's span on that row.+ assert_eq!(first.range.start, 0);+ assert!(first.x0 >= 79.5, "{first:?}");+ assert!(first.baseline < 30.0, "first row: {first:?}");+ assert_eq!(l.lines.iter().filter(|line| (line.baseline - first.baseline).abs() < 1e-3).count(), 1, "{:?}", l.lines);+ assert_eq!(l.lines.last().map(|line| line.range.end), Some(t.text.len()), "nothing hidden");+}++#[test]+fn area_stacks_paragraphs_with_leading_and_space_before() {+ let mut e = TextEngine::new();+ let text = "First paragraph of the bubble text.\nSecond paragraph goes right after it.";+ let mut t = point(text, 12.0);+ let style = ParagraphStyle { space_before_pt: 6.0, ..Default::default() };+ let leading = style.auto_leading * 12.0;+ t.paragraphs = vec![ParagraphRun { len: text.len(), style }];+ let path = area_poly(&[(0.0, 0.0), (120.0, 0.0), (120.0, 300.0), (0.0, 300.0)]);+ t.shape = TextShape::Area { path: path.clone() };+ let l = e.layout(&t, 72.0);+ assert_lines_inside(&l, &path);+ let (p0, p1): (Vec<_>, Vec<_>) = l.lines.iter().partition(|line| line.paragraph == 0);+ assert!(p0.len() >= 2 && p1.len() >= 2, "both paragraphs wrap: {:?}", l.lines);+ assert!(p1.iter().all(|line| line.paragraph == 1));+ // The second paragraph starts right after the break, one leading plus space before lower.+ let second = text.find('\n').unwrap() + 1;+ assert_eq!(p1[0].range.start, second);+ let gap = p1[0].baseline - p0.last().unwrap().baseline;+ assert!((gap - (leading + 6.0)).abs() < 1.0, "gap {gap}, want {}", leading + 6.0);+ // Lines within a paragraph are one leading apart.+ for w in p0.windows(2) {+ assert!((w[1].baseline - w[0].baseline - leading).abs() < 1.0, "{w:?}");+ }+ assert_eq!(l.lines.last().map(|line| line.range.end), Some(text.len()));+}++#[test]+fn area_justify_fills_each_span_but_the_last_line() {+ let mut e = TextEngine::new();+ let mut t = point(&BUBBLE_TEXT.repeat(2), 12.0);+ t.paragraphs = vec![ParagraphRun { len: t.text.len(), style: ParagraphStyle { align: TextAlign::JustifyLeft, ..Default::default() } }];+ let path = area_ellipse(0.0, 0.0, 260.0, 160.0);+ t.shape = TextShape::Area { path: path.clone() };+ let l = e.layout(&t, 72.0);+ assert!(l.lines.len() >= 4, "{}", l.lines.len());+ assert_lines_inside(&l, &path);+ let a = crate::area::AreaShape::new(&path, false).unwrap();+ let span_of = |line: &crate::LineInfo| {+ a.spans(line.baseline - line.ascent, line.baseline + line.descent, 0.0)+ .into_iter()+ .find(|&(s0, s1)| line.x0 >= s0 - 0.5 && line.x1 <= s1 + 0.5)+ .unwrap()+ };+ let (last, rest) = l.lines.split_last().unwrap();+ for line in rest {+ // Justified: the glyphs run from one edge of the line's span to the other.+ let (s0, s1) = span_of(line);+ let ink = l.glyphs.iter().filter(|g| (g.y - line.baseline).abs() < 1e-3).map(|g| g.x).fold(f32::MIN, f32::max);+ assert!((line.x0 - s0).abs() < 1.0, "{line:?} in {s0}..{s1}");+ assert!(ink > s1 - 12.0, "last glyph at {ink}, span ends {s1}: {line:?}");+ }+ // The last line is set flush left, not stretched.+ let (s0, s1) = span_of(last);+ assert!((last.x0 - s0).abs() < 1.0 && last.x1 < s1 - 12.0, "{last:?} in {s0}..{s1}");+}+++ /// #8602: each colour is rasterised only over its own glyphs instead of the whole text, and the+ /// pixels match a full-size pass per colour (plain, faux bold, underlined, rotated and warped+ /// text; RGB and CMYK), up to float rounding in the coverage sums.+ #[test]+ fn per_colour_passes_match_full_size_passes() {+ use photocraft_doc::text::TextWarp;+ let mut e = TextEngine::new();+ let text = "Many coloured runs of text, one colour a letter, across two lines\nof a point text layer";+ let colours = [Color::rgb(0.9, 0.1, 0.1), Color::rgb(0.1, 0.7, 0.2), Color::rgb(0.1, 0.2, 0.9), Color::rgb(0.6, 0.6, 0.1)];+ let runs = |bold: bool| {+ text.char_indices()+ .map(|(i, ch)| {+ let colour = colours[i % colours.len()];+ let style = CharStyle { size_pt: 28.0, color: colour, faux_bold: bold && i % 3 == 0, underline: i % 5 == 0, ..Default::default() };+ TextRun { len: ch.len_utf8(), style }+ })+ .collect::<Vec<_>>()+ };+ let cases = [+ TextLayer { text: text.into(), runs: runs(false), transform: Affine::translate(10.0, 40.0), ..Default::default() },+ TextLayer { text: text.into(), runs: runs(true), transform: Affine::rotate(0.3).then(&Affine::translate(30.0, 90.0)), ..Default::default() },+ TextLayer {+ text: text.into(),+ runs: runs(true),+ transform: Affine::translate(10.0, 60.0),+ warp: Some(TextWarp { style: "warpArc".into(), value: 40.0, horizontal_distortion: 0.0, vertical_distortion: 0.0, horizontal: true }),+ ..Default::default()+ },+ ];+ for (k, t) in cases.iter().enumerate() {+ let l = e.layout(t, 72.0);+ let warp = crate::render::layout_deform(&l, t);+ for format in [PixelFormat::RGBA8, PixelFormat::CMYKA8] {+ let fast = crate::render::rasterize_passes(&l, &t.transform, format, t.antialias, warp.as_ref(), true);+ let full = crate::render::rasterize_passes(&l, &t.transform, format, t.antialias, warp.as_ref(), false);+ assert_eq!(fast.rect, full.rect, "case {k}");+ let (a, b) = (fast.surface.read_region(fast.rect), full.surface.read_region(full.rect));+ assert!(!a.is_empty());+ // Compare what shows: colour weighted by alpha (a fully transparent pixel's colour is moot).+ let ch = format.channels();+ let shown = |px: &[f32]| {+ px.chunks_exact(ch).flat_map(|p| p[..ch - 1].iter().map(|c| c * p[ch - 1]).chain([p[ch - 1]]).collect::<Vec<_>>()).collect::<Vec<_>>()+ };+ let worst = shown(&a).iter().zip(&shown(&b)).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max);+ assert!(worst <= 1.0 / 255.0, "case {k} {format:?}: largest difference {worst}");+ }+ }+ }diff --cc crates/ui-egui/src/i18n/zh-hans.tsvindex 61778561c,c4fd417cc..d08bb7acd--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@@ -3062,22 -3038,13 +3062,30 @@@ curves Smooth 平�Left-to-right paragraph direction 从左到右的段落方向Right-to-left paragraph direction 从右到左的段落方向Not rendered: this adjustment ({key}) is kept as imported. 未渲染:此调整({key})按导入时的原样保留。-# Print preview image (#8236)- Print preview image Print preview image+ Print preview image 打印预览图像++# Color panel menu: modes, copy commands and colour ramps (#6000)+ Hue Cube 色相立方体+ Brightness Cube 亮度立方体+ Color Wheel 色轮+ Grayscale Slider 灰度滑块+ RGB Sliders RGB 滑块+ HSB Sliders HSB 滑块+ CMYK Sliders CMYK 滑块+ Lab Sliders Lab 滑块+ Web Color Sliders Web 颜色滑块+ Copy Color as HTML 将颜色复制为 HTML+ Copy Color's Hex Code 复制颜色的十六进制代码+ RGB Spectrum RGB 色谱+ CMYK Spectrum CMYK 色谱+ Grayscale Ramp 灰度色带+ Current Colors 当前颜色+ Make Ramp Web Safe 使色带成为 Web 安全色+++ # File opening, export status and graphics driver information+ Couldn't open {name}: {error} 无法打开 {name}:{error}+ Exported {path} ({size}) 已导出 {path}({size})+ Exported {path} 已导出 {path}+ Exported {n} files 已导出 {n} 个文件+ Driver: {driver} 驱动程序:{driver}diff --cc crates/ui-egui/src/panels.rsindex e6b90e76b,04b6f1ac5..2d8dc5a8c--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@@ -975,572 -975,631 +975,572 @@@ pub fn options_bar(app: &mut Photocraft.show(ui, |ui| {ui.style_mut().spacing.scroll = egui::style::ScrollStyle { bar_width: 4.0, ..egui::style::ScrollStyle::floating() };egui::ScrollArea::horizontal().id_salt("tool-options").auto_shrink([false, false]).show(ui, |ui| {- // Font ink can extend beyond its advance width at fractional positions.- // Include its gutter in the container layout, including right-aligned actions.- egui::Frame::NONE.inner_margin(egui::Margin { right: 2, ..Default::default() }).show(ui, |ui| {- crate::direction::horizontal_centered(ui, |ui| {- if t.pro {- crate::chrome_ui::home_button(app, ui);- widgets::vline(ui, 22.0);- }- let tool_icon = icons::button(ui, icons::tool_icon(app.ui.tool), if t.pro { 26.0 } else { 28.0 }, !t.pro, tl!(app.ui.tool.label()));- // Photoshop: right-click the tool icon for Reset Tool / Reset All Tools (#2825).- let mut reset = None;- tool_icon.context_menu(|ui| {- if ui.button(tl!("Reset Tool")).clicked() {- reset = Some("tool.reset");- ui.close();- }- if ui.button(tl!("Reset All Tools")).clicked() {- reset = Some("tool.resetAll");- ui.close();- }- });- if let Some(id) = reset- && let Err(e) = crate::menus::invoke(app, ui.ctx(), id, json!({}))- {- app.ui.status = e;- }- if t.pro {- let (r, _) = ui.allocate_exact_size(vec2(10.0, 20.0), Sense::hover());- icons::paint(ui, r, "chevron-down", 10.0, t.text_faint);- }- widgets::vline(ui, 22.0);- if app.ui.transform.is_some() {- crate::transform_tool::options_bar(app, ui);- return;- }- if crate::symmetry_ui::options_bar(app, ui) || crate::distort_ui::options_bar(app, ui) {- return;- }- let tool = app.ui.tool;- // The options bar shows the active tool's brush: switch it in before drawing the- // chip, so a tool change swaps the brush with it (Photoshop keeps one per tool).- crate::paint_mouse::sync_tool_brush(app);- // Brush edits here go through `tools.setBrush`, one journal entry per gesture (Rule 1).- if (tool.is_brushlike() && !matches!(tool, Tool::Brush | Tool::Pencil | Tool::MixerBrush | Tool::Eraser)) || tool == Tool::QuickSelection {- brush_preset_chip(ui, &app.session.tools.brush, &mut app.ui);- crate::brush_picker::settings_toggle(app, ui);- widgets::vline(ui, 22.0);- }- if tool == Tool::CloneStamp {- let before = app.session.tools.brush.clone();- let mut brush = before.clone();- let width = if t.pro { 62.0 } else { 66.0 };- percent_field(ui, tl!("Opacity"), &mut brush.opacity, 1.0..=100.0, width);- percent_field(ui, tl!("Flow"), &mut brush.flow, 1.0..=100.0, width);- crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &brush);- widgets::vline(ui, 22.0);- }- if crate::eraser_ui::options_bar(app, ui, tool)- || crate::retouch_ui::options_bar(app, ui, tool)- || crate::vector_ui::options_bar(app, ui, tool)- || crate::analysis_ui::options_bar(app, ui, tool)- || crate::slice_ui::options_bar(app, ui, tool)- || crate::frame_tool::options_bar(app, ui, tool)- || crate::artboard_tool::options_bar(app, ui, tool)- {- return;- }- let brush_before = app.session.tools.brush.clone();- let mut brush = brush_before.clone();- let b = &mut brush;- match app.ui.tool {- Tool::Brush | Tool::Eraser if t.pro => {- // A Block-mode Eraser has a fixed size, opacity and flow (Photoshop, #2770).- let block = crate::eraser_ui::block_mode(app, app.ui.tool);- ui.add_enabled_ui(!block, |ui| {- brush_preset_chip(ui, b, &mut app.ui);- crate::brush_picker::settings_toggle(app, ui);- });- widgets::vline(ui, 22.0);- // The Eraser has no blend mode: its Mode is Brush, Pencil or Block (#2662).- if app.ui.tool == Tool::Eraser {- crate::eraser_ui::mode_dropdown(ui, &mut app.ui.tool_options.eraser_mode);- } else {- opt_label(ui, tl!("Mode"));- let held = app.held_erase;- paint_mode_dropdown(ui, "brush-mode", b, &mut app.ui.tool_options.brush_clear, held);+ // Font ink can extend beyond its advance width at fractional positions.+ // Include its gutter in the container layout, including right-aligned actions.+ egui::Frame::NONE.inner_margin(egui::Margin { right: 2, ..Default::default() }).show(ui, |ui| {+ crate::direction::horizontal_centered(ui, |ui| {+ if t.pro {+ crate::chrome_ui::home_button(app, ui);+ widgets::vline(ui, 22.0);}- ui.add_enabled_ui(!block, |ui| {- percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, 62.0);- if icons::button(ui, "circle-dot", 24.0, b.pressure_opacity, tl!("Always use pressure for opacity")).clicked() {- b.pressure_opacity = !b.pressure_opacity;+ let tool_icon = icons::button(ui, icons::tool_icon(app.ui.tool), if t.pro { 26.0 } else { 28.0 }, !t.pro, tl!(app.ui.tool.label()));+ // Photoshop: right-click the tool icon for Reset Tool / Reset All Tools (#2825).+ let mut reset = None;+ tool_icon.context_menu(|ui| {+ if ui.button(tl!("Reset Tool")).clicked() {+ reset = Some("tool.reset");+ ui.close();}- });- // A Pencil- or Block-mode Eraser is always full flow, without build-up (Photoshop).- ui.add_enabled_ui(!block && !crate::eraser_ui::pencil_mode(app, app.ui.tool), |ui| {- percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 62.0);- let airbrush = icons::button(ui, "sparkles", 24.0, b.build_up, tl!("Enable airbrush-style build-up effects"));- if crate::brush_picker::named(airbrush, "Enable airbrush-style build-up effects").clicked() {- b.build_up = !b.build_up;+ if ui.button(tl!("Reset All Tools")).clicked() {+ reset = Some("tool.resetAll");+ ui.close();}});- opt_label(ui, tl!("Smoothing"));- smoothing_field(ui, b, 58.0);- smoothing_options(ui, b);- widgets::vline(ui, 22.0);- if icons::button(ui, "circle-dot", 24.0, b.pressure_size, tl!("Always use pressure for size")).clicked() {- b.pressure_size = !b.pressure_size;- }- }- // Pencil: Photoshop's options (no hardness or flow: the pencil is always hard).- Tool::Pencil => {- brush_preset_chip(ui, b, &mut app.ui);- crate::brush_picker::settings_toggle(app, ui);- widgets::vline(ui, 22.0);- if !t.pro {- opt_label(ui, tl!("Size"));- widgets::value_field(ui, &mut b.size, 1.0..=photocraft_engine::paint::MAX_BRUSH_SIZE, "px", 76.0);- widgets::vline(ui, 22.0);+ if let Some(id) = reset+ && let Err(e) = crate::menus::invoke(app, ui.ctx(), id, json!({}))+ {+ app.ui.status = e;}- opt_label(ui, tl!("Mode"));- let held = app.held_erase;- paint_mode_dropdown(ui, "pencil-mode", b, &mut app.ui.tool_options.pencil_clear, held);- percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, if t.pro { 62.0 } else { 66.0 });- opt_label(ui, tl!("Smoothing"));- smoothing_field(ui, b, if t.pro { 58.0 } else { 66.0 });- widgets::vline(ui, 22.0);- widgets::checkbox(ui, &mut app.ui.tool_options.pencil_auto_erase, tl!("Auto Erase"));- }- Tool::Brush | Tool::Eraser => {- brush_preset_chip(ui, b, &mut app.ui);- crate::brush_picker::settings_toggle(app, ui);- widgets::vline(ui, 22.0);- // A Block-mode Eraser has a fixed size, opacity and flow (Photoshop, #2770).- let block = crate::eraser_ui::block_mode(app, app.ui.tool);- ui.add_enabled_ui(!block, |ui| {- opt_label(ui, tl!("Size"));- widgets::value_field(ui, &mut b.size, 1.0..=photocraft_engine::paint::MAX_BRUSH_SIZE, "px", 76.0);- });- widgets::vline(ui, 22.0);- if app.ui.tool == Tool::Eraser {- crate::eraser_ui::mode_dropdown(ui, &mut app.ui.tool_options.eraser_mode);- } else {- opt_label(ui, tl!("Mode"));- let held = app.held_erase;- paint_mode_dropdown(ui, "brush-mode", b, &mut app.ui.tool_options.brush_clear, held);+ if t.pro {+ let (r, _) = ui.allocate_exact_size(vec2(10.0, 20.0), Sense::hover());+ icons::paint(ui, r, "chevron-down", 10.0, t.text_faint);}- // A Pencil-mode Eraser is always hard and at full flow (Photoshop).- let fixed = block || crate::eraser_ui::pencil_mode(app, app.ui.tool);- ui.add_enabled_ui(!fixed, |ui| percent_field(ui, tl!("Hardness"), &mut b.hardness, 0.0..=100.0, 66.0));- ui.add_enabled_ui(!block, |ui| percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, 66.0));- ui.add_enabled_ui(!fixed, |ui| percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 66.0));- opt_label(ui, tl!("Smoothing"));- smoothing_field(ui, b, 66.0);widgets::vline(ui, 22.0);- widgets::toggle(ui, &mut b.pressure_size, tl!("Pressure for Size"));- widgets::toggle(ui, &mut b.pressure_opacity, tl!("Pressure for Opacity"));- }- Tool::MixerBrush => {- brush_preset_chip(ui, b, &mut app.ui);- crate::brush_picker::settings_toggle(app, ui);- widgets::vline(ui, 22.0);- mixer_load_swatch(app, ui);- let m = &mut b.mixer;- for (icon, on, tip) in [- ("brush", &mut m.load_after_stroke, tl!("Load the brush after each stroke")),- ("brush-cleaning", &mut m.clean_after_stroke, tl!("Clean the brush after each stroke")),- ] {- if icons::button(ui, icon, 24.0, *on, tip).clicked() {- *on = !*on;- }+ if app.ui.transform.is_some() {+ crate::transform_tool::options_bar(app, ui);+ return;}- widgets::vline(ui, 22.0);- for (label, value) in [- (tl!("Wet"), &mut b.mixer.wet),- (tl!("Load"), &mut b.mixer.load),- (tl!("Mix"), &mut b.mixer.mix),- (tl!("Flow"), &mut b.mixer.flow),- ] {- percent_field(ui, label, value, 0.0..=100.0, 62.0);+ if crate::symmetry_ui::options_bar(app, ui) || crate::distort_ui::options_bar(app, ui) {+ return;}- widgets::vline(ui, 22.0);- widgets::checkbox(ui, &mut b.mixer.sample_all_layers, tl!("Sample All Layers"));- }- Tool::RectMarquee | Tool::EllipseMarquee | Tool::SingleRowMarquee | Tool::SingleColumnMarquee if t.pro => {- ui.spacing_mut().item_spacing.x = 2.0;- for (i, (icon, tip)) in [- ("square", tl!("New selection").to_string()),- ("plus", crate::i18n::fmt(tl!("Add to selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift"))])),- ("minus", crate::i18n::fmt(tl!("Subtract from selection ({key})"), &[("key", &crate::shortcuts::pretty("Alt"))])),- (- "squares-subtract",- crate::i18n::fmt(tl!("Intersect with selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift+Alt"))]),- ),- ]- .iter()- .enumerate()+ let tool = app.ui.tool;+ // The options bar shows the active tool's brush: switch it in before drawing the+ // chip, so a tool change swaps the brush with it (Photoshop keeps one per tool).+ crate::paint_mouse::sync_tool_brush(app);+ // Brush edits here go through `tools.setBrush`, one journal entry per gesture (Rule 1).+ if (tool.is_brushlike() && !matches!(tool, Tool::Brush | Tool::Pencil | Tool::MixerBrush | Tool::Eraser))+ || tool == Tool::QuickSelection{- if icons::button(ui, icon, 24.0, app.ui.selection_mode == i as u8, tip).clicked() {- app.ui.selection_mode = i as u8;- }+ brush_preset_chip(ui, &app.session.tools.brush, &mut app.ui);+ crate::brush_picker::settings_toggle(app, ui);+ widgets::vline(ui, 22.0);}- ui.spacing_mut().item_spacing.x = 8.0;- widgets::vline(ui, 22.0);- let (units, size) = fixed_size_units(app);- let o = &mut app.ui.tool_options;- opt_label(ui, tl!("Feather"));- widgets::value_field(ui, &mut o.feather, 0.0..=1000.0, "px", 62.0);- // Photoshop greys Anti-alias for the Rectangular Marquee (its edges are always hard).- ui.add_enabled_ui(app.ui.tool == Tool::EllipseMarquee, |ui| widgets::checkbox(ui, &mut o.anti_alias, tl!("Anti-alias")));- widgets::vline(ui, 22.0);- // A single row or column has no style or size: Photoshop greys them.- let sized = matches!(app.ui.tool, Tool::RectMarquee | Tool::EllipseMarquee);- ui.add_enabled_ui(sized, |ui| opt_label(ui, tl!("Style")));- let styles = [- ("normal".to_string(), tl!("Normal")),- ("fixedRatio".to_string(), tl!("Fixed Ratio")),- ("fixedSize".to_string(), tl!("Fixed Size")),- ];- if ui.add_enabled_ui(sized, |ui| widgets::dropdown(ui, "marquee-style", &mut o.marquee_style, &styles, 96.0)).inner {- (o.marquee_width, o.marquee_height) = if o.marquee_style == "fixedSize" { (64.0, 64.0) } else { (1.0, 1.0) };+ if tool == Tool::CloneStamp {+ let before = app.session.tools.brush.clone();+ let mut brush = before.clone();+ let width = if t.pro { 62.0 } else { 66.0 };+ percent_field(ui, tl!("Opacity"), &mut brush.opacity, 1.0..=100.0, width);+ percent_field(ui, tl!("Flow"), &mut brush.flow, 1.0..=100.0, width);+ crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &brush);+ widgets::vline(ui, 22.0);}- let fixed = sized && o.marquee_style != "normal";- let fixed_size = o.marquee_style == "fixedSize";- // Fixed Size shows its pixels in the unit picked by right-clicking Width or Height (#7910).- let units = widgets::FieldUnits { unit: photocraft_engine::prefs::Unit::parse(&o.marquee_unit).unwrap_or_default(), ..units };- ui.add_enabled_ui(fixed, |ui| {- let mut picked = None;- opt_label(ui, tl!("Width"));- if fixed_size {- picked = fixed_size_field(ui, &mut o.marquee_width, units, size[0]);- } else {- widgets::value_field(ui, &mut o.marquee_width, crate::tool_memory::style_range(&o.marquee_style), "", 62.0);- }- if icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked() {- std::mem::swap(&mut o.marquee_width, &mut o.marquee_height);- }- opt_label(ui, tl!("Height"));- if fixed_size {- picked = fixed_size_field(ui, &mut o.marquee_height, units, size[1]).or(picked);- } else {- widgets::value_field(ui, &mut o.marquee_height, crate::tool_memory::style_range(&o.marquee_style), "", 62.0);+ if crate::eraser_ui::options_bar(app, ui, tool)+ || crate::retouch_ui::options_bar(app, ui, tool)+ || crate::vector_ui::options_bar(app, ui, tool)+ || crate::analysis_ui::options_bar(app, ui, tool)+ || crate::slice_ui::options_bar(app, ui, tool)+ || crate::frame_tool::options_bar(app, ui, tool)+ || crate::artboard_tool::options_bar(app, ui, tool)+ {+ return;+ }+ let brush_before = app.session.tools.brush.clone();+ let mut brush = brush_before.clone();+ let b = &mut brush;+ match app.ui.tool {+ Tool::Brush | Tool::Eraser if t.pro => {+ // A Block-mode Eraser has a fixed size, opacity and flow (Photoshop, #2770).+ let block = crate::eraser_ui::block_mode(app, app.ui.tool);+ ui.add_enabled_ui(!block, |ui| {+ brush_preset_chip(ui, b, &mut app.ui);+ crate::brush_picker::settings_toggle(app, ui);+ });+ widgets::vline(ui, 22.0);+ // The Eraser has no blend mode: its Mode is Brush, Pencil or Block (#2662).+ if app.ui.tool == Tool::Eraser {+ crate::eraser_ui::mode_dropdown(ui, &mut app.ui.tool_options.eraser_mode);+ } else {+ opt_label(ui, tl!("Mode"));+ let held = app.held_erase;+ paint_mode_dropdown(ui, "brush-mode", b, &mut app.ui.tool_options.brush_clear, held);+ }+ ui.add_enabled_ui(!block, |ui| {+ percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, 62.0);+ if icons::button(ui, "circle-dot", 24.0, b.pressure_opacity, tl!("Always use pressure for opacity")).clicked() {+ b.pressure_opacity = !b.pressure_opacity;+ }+ });+ // A Pencil- or Block-mode Eraser is always full flow, without build-up (Photoshop).+ ui.add_enabled_ui(!block && !crate::eraser_ui::pencil_mode(app, app.ui.tool), |ui| {+ percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 62.0);+ let airbrush = icons::button(ui, "sparkles", 24.0, b.build_up, tl!("Enable airbrush-style build-up effects"));+ if crate::brush_picker::named(airbrush, "Enable airbrush-style build-up effects").clicked() {+ b.build_up = !b.build_up;+ }+ });+ opt_label(ui, tl!("Smoothing"));+ smoothing_field(ui, b, 58.0);+ smoothing_options(ui, b);+ widgets::vline(ui, 22.0);+ if icons::button(ui, "circle-dot", 24.0, b.pressure_size, tl!("Always use pressure for size")).clicked() {+ b.pressure_size = !b.pressure_size;+ }}- if let Some(name) = picked {- o.marquee_unit = name.into();+ // Pencil: Photoshop's options (no hardness or flow: the pencil is always hard).+ Tool::Pencil => {+ brush_preset_chip(ui, b, &mut app.ui);+ crate::brush_picker::settings_toggle(app, ui);+ widgets::vline(ui, 22.0);+ if !t.pro {+ opt_label(ui, tl!("Size"));+ widgets::value_field(ui, &mut b.size, 1.0..=photocraft_engine::paint::MAX_BRUSH_SIZE, "px", 76.0);+ widgets::vline(ui, 22.0);+ }+ opt_label(ui, tl!("Mode"));+ let held = app.held_erase;+ paint_mode_dropdown(ui, "pencil-mode", b, &mut app.ui.tool_options.pencil_clear, held);+ percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, if t.pro { 62.0 } else { 66.0 });+ opt_label(ui, tl!("Smoothing"));+ smoothing_field(ui, b, if t.pro { 58.0 } else { 66.0 });+ widgets::vline(ui, 22.0);+ widgets::checkbox(ui, &mut app.ui.tool_options.pencil_auto_erase, tl!("Auto Erase"));}- });- widgets::vline(ui, 22.0);- select_and_mask_button(app, ui);- }- Tool::Lasso | Tool::PolygonLasso | Tool::MagneticLasso if t.pro => {- selection_mode_buttons(app, ui);- widgets::vline(ui, 22.0);- opt_label(ui, tl!("Feather"));- widgets::value_field(ui, &mut app.ui.tool_options.feather, 0.0..=1000.0, "px", 62.0);- widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias"));- widgets::vline(ui, 22.0);- if app.ui.tool == Tool::MagneticLasso {- let o = &mut app.ui.tool_options;- opt_label(ui, tl!("Width"));- widgets::value_field(ui, &mut o.magnetic_width, 1.0..=256.0, "px", 58.0)- .on_hover_text(tl!("Follows only edges this close to the pointer ([ and ] change it)"));- opt_label(ui, tl!("Contrast"));- widgets::value_field(ui, &mut o.magnetic_contrast, 1.0..=100.0, "%", 58.0)- .on_hover_text(tl!("Higher values follow only edges that contrast sharply with their surroundings"));- opt_label(ui, tl!("Frequency"));- widgets::value_field(ui, &mut o.magnetic_frequency, 0.0..=100.0, "", 50.0)- .on_hover_text(tl!("How often fastening points are placed by themselves"));- if icons::button(ui, "circle-dot", 24.0, o.magnetic_pressure, tl!("Use tablet pressure to change pen width")).clicked() {- o.magnetic_pressure = !o.magnetic_pressure;+ Tool::Brush | Tool::Eraser => {+ brush_preset_chip(ui, b, &mut app.ui);+ crate::brush_picker::settings_toggle(app, ui);+ widgets::vline(ui, 22.0);+ // A Block-mode Eraser has a fixed size, opacity and flow (Photoshop, #2770).+ let block = crate::eraser_ui::block_mode(app, app.ui.tool);+ ui.add_enabled_ui(!block, |ui| {+ opt_label(ui, tl!("Size"));+ widgets::value_field(ui, &mut b.size, 1.0..=photocraft_engine::paint::MAX_BRUSH_SIZE, "px", 76.0);+ });+ widgets::vline(ui, 22.0);+ if app.ui.tool == Tool::Eraser {+ crate::eraser_ui::mode_dropdown(ui, &mut app.ui.tool_options.eraser_mode);+ } else {+ opt_label(ui, tl!("Mode"));+ let held = app.held_erase;+ paint_mode_dropdown(ui, "brush-mode", b, &mut app.ui.tool_options.brush_clear, held);+ }+ // A Pencil-mode Eraser is always hard and at full flow (Photoshop).+ let fixed = block || crate::eraser_ui::pencil_mode(app, app.ui.tool);+ ui.add_enabled_ui(!fixed, |ui| percent_field(ui, tl!("Hardness"), &mut b.hardness, 0.0..=100.0, 66.0));+ ui.add_enabled_ui(!block, |ui| percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, 66.0));+ ui.add_enabled_ui(!fixed, |ui| percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 66.0));+ opt_label(ui, tl!("Smoothing"));+ smoothing_field(ui, b, 66.0);+ widgets::vline(ui, 22.0);+ widgets::toggle(ui, &mut b.pressure_size, tl!("Pressure for Size"));+ widgets::toggle(ui, &mut b.pressure_opacity, tl!("Pressure for Opacity"));}- widgets::vline(ui, 22.0);- }- select_and_mask_button(app, ui);- if crate::lasso_ui::active(app) || (app.ui.tool == Tool::PolygonLasso && !app.ui.polygon.is_empty()) {- hint(- ui,- &crate::i18n::fmt(- tl!("Click the first point or press {key} to close · Esc cancels"),- &[("key", &crate::shortcuts::pretty("Enter"))],- ),- );- } else if app.ui.tool == Tool::Lasso {- hint(ui, tl!("Hold Alt while drawing for straight segments"));- }- if app.ui.tool == Tool::MagneticLasso && app.ui.magnetic.active() {- hint(- ui,- &crate::i18n::fmt(- tl!("Click the first point or press {key} to close · {del} removes a point · Esc cancels"),- &[("key", &crate::shortcuts::pretty("Enter")), ("del", &crate::shortcuts::pretty("Backspace"))],- ),- );- }- }- Tool::MagicWand => {- selection_mode_buttons(app, ui);- widgets::vline(ui, 22.0);- opt_label(ui, tl!("Tolerance"));- widgets::value_field(ui, &mut app.ui.tool_options.tolerance, 0.0..=255.0, "", 58.0);- widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias"));- widgets::checkbox(ui, &mut app.ui.tool_options.contiguous, tl!("Contiguous"));- widgets::checkbox(ui, &mut app.ui.tool_options.sample_all.magic_wand, tl!("Sample All Layers"));- widgets::vline(ui, 22.0);- if widgets::secondary_button(ui, tl!("Select Subject"), 0.0).clicked() {- let r = app.run("select.subject", json!({}));- crate::retouch_ui::report_smart_result(app, r, tl!("No subject found — try Object Selection or the Lasso"));- }- select_and_mask_button(app, ui);- }- Tool::PaintBucket if t.pro => {- opt_label(ui, tl!("Fill"));- let mut src = u8::from(app.ui.tool_options.bucket_fill_pattern);- if widgets::dropdown(ui, "bucket-src", &mut src, &[(0u8, tl!("Foreground")), (1, tl!("Pattern"))], 100.0) {- app.ui.tool_options.bucket_fill_pattern = src == 1;- }- opt_label(ui, tl!("Opacity"));- widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0);- opt_label(ui, tl!("Tolerance"));- widgets::value_field(ui, &mut app.ui.tool_options.tolerance, 0.0..=255.0, "", 58.0);- widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias"));- widgets::checkbox(ui, &mut app.ui.tool_options.contiguous, tl!("Contiguous"));- widgets::checkbox(ui, &mut app.ui.tool_options.sample_all.paint_bucket, tl!("All Layers"));- }- Tool::Gradient => {- // Live "Gradient" (a Gradient Fill layer) or "Classic gradient" (pixels).- let mut classic = app.ui.tool_options.gradient_classic;- if widgets::dropdown(ui, "gradient-mode", &mut classic, &[(false, "Gradient"), (true, "Classic gradient")], 118.0) {- app.ui.tool_options.gradient_classic = classic;- }- // Live "Gradient" (a Gradient Fill layer) or "Classic gradient" (pixels):- // both paint with the same engine-owned preset (#1651), and either swatch- // click opens the Gradient Editor window, as in Photoshop.- if crate::gradient_ui::preset_swatch(app, ui) {- app.ui.panels.gradient_editor = true;- }- widgets::vline(ui, 22.0);- ui.spacing_mut().item_spacing.x = 2.0;- let before = app.ui.tool_options.clone();- for (style, icon, tip) in [- ("linear", "gradient", tl!("Linear Gradient")),- ("radial", "circle", tl!("Radial Gradient")),- ("angle", "rotate-cw", tl!("Angle Gradient")),- ("reflected", "arrow-left-right", tl!("Reflected Gradient")),- ("diamond", "diamond", tl!("Diamond Gradient")),- ] {- if icons::button(ui, icon, 24.0, app.ui.tool_options.gradient_style == style, tip).clicked() {- app.ui.tool_options.gradient_style = style.into();+ Tool::MixerBrush => {+ brush_preset_chip(ui, b, &mut app.ui);+ crate::brush_picker::settings_toggle(app, ui);+ widgets::vline(ui, 22.0);+ mixer_load_swatch(app, ui);+ let m = &mut b.mixer;+ for (icon, on, tip) in [+ ("brush", &mut m.load_after_stroke, tl!("Load the brush after each stroke")),+ ("brush-cleaning", &mut m.clean_after_stroke, tl!("Clean the brush after each stroke")),+ ] {+ if icons::button(ui, icon, 24.0, *on, tip).clicked() {+ *on = !*on;+ }+ }+ widgets::vline(ui, 22.0);+ for (label, value) in [+ (tl!("Wet"), &mut b.mixer.wet),+ (tl!("Load"), &mut b.mixer.load),+ (tl!("Mix"), &mut b.mixer.mix),+ (tl!("Flow"), &mut b.mixer.flow),+ ] {+ percent_field(ui, label, value, 0.0..=100.0, 62.0);+ }+ widgets::vline(ui, 22.0);+ widgets::checkbox(ui, &mut b.mixer.sample_all_layers, tl!("Sample All Layers"));}- }- ui.spacing_mut().item_spacing.x = 8.0;- widgets::vline(ui, 22.0);- opt_label(ui, tl!("Mode"));- let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect();- // The wheel over it steps the mode, as over the Layers panel's (#2061).- widgets::dropdown_wheel_hovered(ui, "gradient-blend-mode", &mut app.ui.tool_options.gradient_blend_mode, &opts, 96.0);- opt_label(ui, tl!("Opacity"));- let r = widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0);- // Live while scrubbed, one undo step per scrub (#5012).- let drag_key = r.id.with("gradient-opacity-drag");- if r.drag_started() {- let n = ui.ctx().cumulative_pass_nr();- ui.data_mut(|d| d.insert_temp(drag_key, n));- }- if r.changed() {- let drag = if r.dragged() { ui.data(|d| d.get_temp::<u64>(drag_key)) } else { None };- crate::gradient_ui::opacity_changed(app, drag);- }- widgets::checkbox(ui, &mut app.ui.tool_options.gradient_reverse, tl!("Reverse"));- widgets::checkbox(ui, &mut app.ui.tool_options.gradient_dither, tl!("Dither"));- // Live mode: the options also change a selected gradient fill layer.- crate::gradient_ui::options_changed(app, &before);- }- Tool::PerspectiveCrop if t.pro => crate::perspective_crop_ui::options_bar(app, ui),- Tool::Crop if t.pro => {- let before_ratio = crate::crop_ui::preset_ratio(app);- let doc_size = app.session.active().map_or((0.0, 0.0), |s| (f64::from(s.doc.size.width), f64::from(s.doc.size.height)));- // Ratios, sizes, saved presets, New / Delete Crop Preset… (#2443, #1919).- crate::crop_presets::dropdown(app, ui);- let o = &mut app.ui.tool_options;- let mut ratio_base = None;- if o.crop_ratio == crate::crop_size::WHR {- crate::crop_size::fields(o, ui);- } else {- // Keep partial edits in ToolOptions so the first side survives a frame;- // Original Ratio shows the document's numbers, as Photoshop does.- let (mut rw, mut rh) = crate::crop_size::custom_ratio_fields(o, doc_size);- let decimals = crate::crop_size::RATIO_DECIMALS;- let fw = widgets::value_field_prec(ui, &mut rw, 0.0..=99_999.0, "", 54.0, decimals);- let swap = icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked();- let fh = widgets::value_field_prec(ui, &mut rh, 0.0..=99_999.0, "", 54.0, decimals);- let (cw, ch) = (fw.changed(), fh.changed());- if swap {- std::mem::swap(&mut rw, &mut rh);+ Tool::RectMarquee | Tool::EllipseMarquee | Tool::SingleRowMarquee | Tool::SingleColumnMarquee => {+ ui.spacing_mut().item_spacing.x = 2.0;+ for (i, (icon, tip)) in [+ ("square", tl!("New selection").to_string()),+ ("plus", crate::i18n::fmt(tl!("Add to selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift"))])),+ ("minus", crate::i18n::fmt(tl!("Subtract from selection ({key})"), &[("key", &crate::shortcuts::pretty("Alt"))])),+ (+ "squares-subtract",+ crate::i18n::fmt(tl!("Intersect with selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift+Alt"))]),+ ),+ ]+ .iter()+ .enumerate()+ {+ if icons::button(ui, icon, 24.0, app.ui.selection_mode == i as u8, tip).clicked() {+ app.ui.selection_mode = i as u8;+ }+ }+ ui.spacing_mut().item_spacing.x = 8.0;+ widgets::vline(ui, 22.0);+ let (units, size) = fixed_size_units(app);+ let o = &mut app.ui.tool_options;+ opt_label(ui, tl!("Feather"));+ widgets::value_field(ui, &mut o.feather, 0.0..=1000.0, "px", 62.0);+ // Photoshop greys Anti-alias for the Rectangular Marquee (its edges are always hard).+ ui.add_enabled_ui(app.ui.tool == Tool::EllipseMarquee, |ui| widgets::checkbox(ui, &mut o.anti_alias, tl!("Anti-alias")));+ widgets::vline(ui, 22.0);+ // A single row or column has no style or size: Photoshop greys them.+ let sized = matches!(app.ui.tool, Tool::RectMarquee | Tool::EllipseMarquee);+ ui.add_enabled_ui(sized, |ui| opt_label(ui, tl!("Style")));+ let styles = [+ ("normal".to_string(), tl!("Normal")),+ ("fixedRatio".to_string(), tl!("Fixed Ratio")),+ ("fixedSize".to_string(), tl!("Fixed Size")),+ ];+ if ui.add_enabled_ui(sized, |ui| widgets::dropdown(ui, "marquee-style", &mut o.marquee_style, &styles, 96.0)).inner {+ (o.marquee_width, o.marquee_height) = if o.marquee_style == "fixedSize" { (64.0, 64.0) } else { (1.0, 1.0) };+ }+ let fixed = sized && o.marquee_style != "normal";+ let fixed_size = o.marquee_style == "fixedSize";+ // Fixed Size shows its pixels in the unit picked by right-clicking Width or Height (#7910).+ let units = widgets::FieldUnits { unit: photocraft_engine::prefs::Unit::parse(&o.marquee_unit).unwrap_or_default(), ..units };+ ui.add_enabled_ui(fixed, |ui| {+ let mut picked = None;+ opt_label(ui, tl!("Width"));+ if fixed_size {+ picked = fixed_size_field(ui, &mut o.marquee_width, units, size[0]);+ } else {- widgets::value_field(ui, &mut o.marquee_width, 0.001..=999.0, "", 62.0);++ widgets::value_field(ui, &mut o.marquee_width, crate::tool_memory::style_range(&o.marquee_style), "", 62.0);+ }+ if icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked() {+ std::mem::swap(&mut o.marquee_width, &mut o.marquee_height);+ }+ opt_label(ui, tl!("Height"));+ if fixed_size {+ picked = fixed_size_field(ui, &mut o.marquee_height, units, size[1]).or(picked);+ } else {- widgets::value_field(ui, &mut o.marquee_height, 0.001..=999.0, "", 62.0);++ widgets::value_field(ui, &mut o.marquee_height, crate::tool_memory::style_range(&o.marquee_style), "", 62.0);+ }+ if let Some(name) = picked {+ o.marquee_unit = name.into();+ }+ });+ widgets::vline(ui, 22.0);+ select_and_mask_button(app, ui);}- if cw || ch || swap {- crate::crop_size::set_custom_ratio_fields(o, rw, rh);+ Tool::Lasso | Tool::PolygonLasso | Tool::MagneticLasso => {+ selection_mode_buttons(app, ui);+ widgets::vline(ui, 22.0);+ opt_label(ui, tl!("Feather"));+ widgets::value_field(ui, &mut app.ui.tool_options.feather, 0.0..=1000.0, "px", 62.0);+ widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias"));+ widgets::vline(ui, 22.0);+ if app.ui.tool == Tool::MagneticLasso {+ let o = &mut app.ui.tool_options;+ opt_label(ui, tl!("Width"));+ widgets::value_field(ui, &mut o.magnetic_width, 1.0..=256.0, "px", 58.0)+ .on_hover_text(tl!("Follows only edges this close to the pointer ([ and ] change it)"));+ opt_label(ui, tl!("Contrast"));+ widgets::value_field(ui, &mut o.magnetic_contrast, 1.0..=100.0, "%", 58.0)+ .on_hover_text(tl!("Higher values follow only edges that contrast sharply with their surroundings"));+ opt_label(ui, tl!("Frequency"));+ widgets::value_field(ui, &mut o.magnetic_frequency, 0.0..=100.0, "", 50.0)+ .on_hover_text(tl!("How often fastening points are placed by themselves"));+ if icons::button(ui, "circle-dot", 24.0, o.magnetic_pressure, tl!("Use tablet pressure to change pen width")).clicked() {+ o.magnetic_pressure = !o.magnetic_pressure;+ }+ widgets::vline(ui, 22.0);+ }+ select_and_mask_button(app, ui);+ if crate::lasso_ui::active(app) || (app.ui.tool == Tool::PolygonLasso && !app.ui.polygon.is_empty()) {+ hint(+ ui,+ &crate::i18n::fmt(+ tl!("Click the first point or press {key} to close · Esc cancels"),+ &[("key", &crate::shortcuts::pretty("Enter"))],+ ),+ );+ } else if app.ui.tool == Tool::Lasso {+ hint(ui, tl!("Hold Alt while drawing for straight segments"));+ }+ if app.ui.tool == Tool::MagneticLasso && app.ui.magnetic.active() {+ hint(+ ui,+ &crate::i18n::fmt(+ tl!("Click the first point or press {key} to close · {del} removes a point · Esc cancels"),+ &[("key", &crate::shortcuts::pretty("Enter")), ("del", &crate::shortcuts::pretty("Backspace"))],+ ),+ );+ }}- // Every ratio typed or scrubbed in one edit fits from the frame the edit- // started with: 1:3 on the way to 16:3 mustn't shrink it first (#7752).- let base_id = egui::Id::new("crop-ratio-edit-base");- if cw || ch {- ratio_base = ui.data(|d| d.get_temp::<[f64; 4]>(base_id)).or(app.ui.crop_rect);+ Tool::MagicWand => {+ selection_mode_buttons(app, ui);+ widgets::vline(ui, 22.0);+ opt_label(ui, tl!("Tolerance"));+ widgets::value_field(ui, &mut app.ui.tool_options.tolerance, 0.0..=255.0, "", 58.0);+ widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias"));+ widgets::checkbox(ui, &mut app.ui.tool_options.contiguous, tl!("Contiguous"));+ widgets::checkbox(ui, &mut app.ui.tool_options.sample_all.magic_wand, tl!("Sample All Layers"));+ widgets::vline(ui, 22.0);+ if widgets::secondary_button(ui, tl!("Select Subject"), 0.0).clicked() {+ let r = app.run("select.subject", json!({}));+ crate::retouch_ui::report_smart_result(app, r, tl!("No subject found — try Object Selection or the Lasso"));+ }+ select_and_mask_button(app, ui);}- if ![&fw, &fh].iter().any(|f| f.has_focus() || f.dragged()) {- ui.data_mut(|d| d.remove::<[f64; 4]>(base_id));- } else if let Some(base) = ratio_base {- ui.data_mut(|d| d.insert_temp(base_id, base));+ Tool::PaintBucket => {+ opt_label(ui, tl!("Fill"));+ let mut src = u8::from(app.ui.tool_options.bucket_fill_pattern);+ if widgets::dropdown(ui, "bucket-src", &mut src, &[(0u8, tl!("Foreground")), (1, tl!("Pattern"))], 100.0) {+ app.ui.tool_options.bucket_fill_pattern = src == 1;+ }+ opt_label(ui, tl!("Opacity"));+ widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0);+ opt_label(ui, tl!("Tolerance"));+ widgets::value_field(ui, &mut app.ui.tool_options.tolerance, 0.0..=255.0, "", 58.0);+ widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias"));+ widgets::checkbox(ui, &mut app.ui.tool_options.contiguous, tl!("Contiguous"));+ widgets::checkbox(ui, &mut app.ui.tool_options.sample_all.paint_bucket, tl!("All Layers"));}- }- widgets::vline(ui, 22.0);- if widgets::secondary_button(ui, tl!("Clear"), 0.0).clicked() {- if o.crop_ratio == crate::crop_size::WHR {- crate::crop_size::clear(o);- } else {- o.crop_ratio.clear();+ Tool::Gradient => {+ // Live "Gradient" (a Gradient Fill layer) or "Classic gradient" (pixels).+ let mut classic = app.ui.tool_options.gradient_classic;+ if widgets::dropdown(ui, "gradient-mode", &mut classic, &[(false, "Gradient"), (true, "Classic gradient")], 118.0) {+ app.ui.tool_options.gradient_classic = classic;+ }+ // Live "Gradient" (a Gradient Fill layer) or "Classic gradient" (pixels):+ // both paint with the same engine-owned preset (#1651), and either swatch+ // click opens the Gradient Editor window, as in Photoshop.+ if crate::gradient_ui::preset_swatch(app, ui) {+ app.ui.panels.gradient_editor = true;+ }+ widgets::vline(ui, 22.0);+ ui.spacing_mut().item_spacing.x = 2.0;+ let before = app.ui.tool_options.clone();+ for (style, icon, tip) in [+ ("linear", "gradient", tl!("Linear Gradient")),+ ("radial", "circle", tl!("Radial Gradient")),+ ("angle", "rotate-cw", tl!("Angle Gradient")),+ ("reflected", "arrow-left-right", tl!("Reflected Gradient")),+ ("diamond", "diamond", tl!("Diamond Gradient")),+ ] {+ if icons::button(ui, icon, 24.0, app.ui.tool_options.gradient_style == style, tip).clicked() {+ app.ui.tool_options.gradient_style = style.into();+ }+ }+ ui.spacing_mut().item_spacing.x = 8.0;+ widgets::vline(ui, 22.0);+ opt_label(ui, tl!("Mode"));+ let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect();+ // The wheel over it steps the mode, as over the Layers panel's (#2061).+ widgets::dropdown_wheel_hovered(ui, "gradient-blend-mode", &mut app.ui.tool_options.gradient_blend_mode, &opts, 96.0);+ opt_label(ui, tl!("Opacity"));+ let r = widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0);+ // Live while scrubbed, one undo step per scrub (#5012).+ let drag_key = r.id.with("gradient-opacity-drag");+ if r.drag_started() {+ let n = ui.ctx().cumulative_pass_nr();+ ui.data_mut(|d| d.insert_temp(drag_key, n));+ }+ if r.changed() {+ let drag = if r.dragged() { ui.data(|d| d.get_temp::<u64>(drag_key)) } else { None };+ crate::gradient_ui::opacity_changed(app, drag);+ }+ widgets::checkbox(ui, &mut app.ui.tool_options.gradient_reverse, tl!("Reverse"));+ widgets::checkbox(ui, &mut app.ui.tool_options.gradient_dither, tl!("Dither"));+ // Live mode: the options also change a selected gradient fill layer.+ crate::gradient_ui::options_changed(app, &before);}- }- crate::crop_straighten::options_button(&mut app.crop.straighten, ui);- crate::crop_overlay::options_button(o, ui);- let pick_shield_color = crate::crop_shield::options_button(&mut o.crop_shield, ui);- widgets::checkbox(ui, &mut o.crop_delete, tl!("Delete Cropped Pixels"));- // Fill: what a turned or extending crop puts where the image doesn't reach- // (#3823). Generative Expand is not offered.- ui.label(tl!("Fill:"));- widgets::dropdown(- ui,- "crop-fill",- &mut o.crop_content_aware,- &[(false, tl!("Background (Default)")), (true, tl!("Content-Aware Fill"))],- 150.0,- );- if crate::crop_ui::preset_ratio(app) != before_ratio {- match ratio_base {- Some(base) => crate::crop_ui::apply_ratio_from(app, base),- None => crate::crop_ui::apply_ratio(app),+ Tool::PerspectiveCrop => crate::perspective_crop_ui::options_bar(app, ui),+ Tool::Crop => {+ let before_ratio = crate::crop_ui::preset_ratio(app);+ let doc_size = app.session.active().map_or((0.0, 0.0), |s| (f64::from(s.doc.size.width), f64::from(s.doc.size.height)));+ // Ratios, sizes, saved presets, New / Delete Crop Preset… (#2443, #1919).+ crate::crop_presets::dropdown(app, ui);+ let o = &mut app.ui.tool_options;+ let mut ratio_base = None;+ if o.crop_ratio == crate::crop_size::WHR {+ crate::crop_size::fields(o, ui);+ } else {+ // Keep partial edits in ToolOptions so the first side survives a frame;+ // Original Ratio shows the document's numbers, as Photoshop does.+ let (mut rw, mut rh) = crate::crop_size::custom_ratio_fields(o, doc_size);+ let decimals = crate::crop_size::RATIO_DECIMALS;+ let fw = widgets::value_field_prec(ui, &mut rw, 0.0..=99_999.0, "", 54.0, decimals);+ let swap = icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked();+ let fh = widgets::value_field_prec(ui, &mut rh, 0.0..=99_999.0, "", 54.0, decimals);+ let (cw, ch) = (fw.changed(), fh.changed());+ if swap {+ std::mem::swap(&mut rw, &mut rh);+ }+ if cw || ch || swap {+ crate::crop_size::set_custom_ratio_fields(o, rw, rh);+ }+ // Every ratio typed or scrubbed in one edit fits from the frame the edit+ // started with: 1:3 on the way to 16:3 mustn't shrink it first (#7752).+ let base_id = egui::Id::new("crop-ratio-edit-base");+ if cw || ch {+ ratio_base = ui.data(|d| d.get_temp::<[f64; 4]>(base_id)).or(app.ui.crop_rect);+ }+ if ![&fw, &fh].iter().any(|f| f.has_focus() || f.dragged()) {+ ui.data_mut(|d| d.remove::<[f64; 4]>(base_id));+ } else if let Some(base) = ratio_base {+ ui.data_mut(|d| d.insert_temp(base_id, base));+ }+ }+ widgets::vline(ui, 22.0);+ if widgets::secondary_button(ui, tl!("Clear"), 0.0).clicked() {+ if o.crop_ratio == crate::crop_size::WHR {+ crate::crop_size::clear(o);+ } else {+ o.crop_ratio.clear();+ }+ }+ crate::crop_straighten::options_button(&mut app.crop.straighten, ui);+ crate::crop_overlay::options_button(o, ui);+ let pick_shield_color = crate::crop_shield::options_button(&mut o.crop_shield, ui);+ widgets::checkbox(ui, &mut o.crop_delete, tl!("Delete Cropped Pixels"));+ // Fill: what a turned or extending crop puts where the image doesn't reach+ // (#3823). Generative Expand is not offered.+ ui.label(tl!("Fill:"));+ widgets::dropdown(+ ui,+ "crop-fill",+ &mut o.crop_content_aware,+ &[(false, tl!("Background (Default)")), (true, tl!("Content-Aware Fill"))],+ 150.0,+ );+ if crate::crop_ui::preset_ratio(app) != before_ratio {+ match ratio_base {+ Some(base) => crate::crop_ui::apply_ratio_from(app, base),+ None => crate::crop_ui::apply_ratio(app),+ }+ }+ if pick_shield_color {+ crate::crop_shield::pick_custom_color(app);+ }+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ if icons::button(+ ui,+ "check",+ 26.0,+ false,+ &crate::i18n::fmt(tl!("Commit current crop operation ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]),+ )+ .clicked()+ {+ crate::canvas::commit_crop(app);+ }+ if icons::button(ui, "ban", 26.0, false, tl!("Cancel current crop operation (Esc)")).clicked() {+ crate::crop_ui::cancel(app);+ }+ });}- }- if pick_shield_color {- crate::crop_shield::pick_custom_color(app);- }- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {- if icons::button(- ui,- "check",- 26.0,- false,- &crate::i18n::fmt(tl!("Commit current crop operation ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]),- )- .clicked()- {- crate::canvas::commit_crop(app);+ // Every theme gets the font, style and size controls (#1387), as with Auto-Select (#1275).+ Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => crate::type_tool::options_bar(app, ui),+ Tool::Move => {+ let o = &mut app.ui.tool_options;+ widgets::checkbox(ui, &mut o.move_auto_select, tl!("Auto-Select:"));+ widgets::dropdown(+ ui,+ "move-target",+ &mut o.move_target,+ &[("layer".to_string(), tl!("Layer")), ("group".to_string(), tl!("Group"))],+ 76.0,+ );+ widgets::vline(ui, 22.0);+ widgets::checkbox(ui, &mut o.move_show_transform, tl!("Show Transform Controls"));+ widgets::vline(ui, 22.0);+ crate::align_bar::options(app, ui);}- if icons::button(ui, "ban", 26.0, false, tl!("Cancel current crop operation (Esc)")).clicked() {- crate::crop_ui::cancel(app);+ Tool::Eyedropper => crate::eyedropper_ui::options(app, ui),+ Tool::Zoom => {+ // Resize Windows to Fit is Preferences › Zoom Resizes Windows itself, as in+ // Photoshop: one setting, shown in both places (zoom_window_fit.rs).+ let mut fit = app.session.prefs().general.zoom_resizes_windows;+ if widgets::checkbox(ui, &mut fit, tl!("Resize Windows to Fit")).changed() {+ app.session.prefs.edit(|p| p.general.zoom_resizes_windows = fit);+ }+ widgets::checkbox(ui, &mut app.ui.tool_options.zoom_scrubby, tl!("Scrubby Zoom"));+ hint(+ ui,+ &crate::i18n::fmt(+ tl!("Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out"),+ &[("key", &crate::shortcuts::pretty("Alt"))],+ ),+ );+ if widgets::secondary_button(ui, tl!("Fit Screen"), 0.0).clicked()+ && let Some(i) = app.session.active_index()+ {+ app.ui.views[i].fit_pending = true;+ app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom);+ app.ui.views[i].zoom_anchor = None;+ }+ if widgets::secondary_button(ui, "100%", 0.0).clicked()+ && let Some(i) = app.session.active_index()+ {+ app.ui.views[i].zoom = 1.0;+ app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom);+ app.ui.views[i].zoom_anchor = None;+ app.ui.views[i].fit_pending = false;+ app.ui.views[i].fill_pending = false;+ }}- });- }- // Every theme gets the font, style and size controls (#1387), as with Auto-Select (#1275).- Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => crate::type_tool::options_bar(app, ui),- Tool::Move if t.pro => {- let o = &mut app.ui.tool_options;- widgets::checkbox(ui, &mut o.move_auto_select, tl!("Auto-Select:"));- widgets::dropdown(- ui,- "move-target",- &mut o.move_target,- &[("layer".to_string(), tl!("Layer")), ("group".to_string(), tl!("Group"))],- 76.0,- );- widgets::vline(ui, 22.0);- widgets::checkbox(ui, &mut o.move_show_transform, tl!("Show Transform Controls"));- widgets::vline(ui, 22.0);- crate::align_bar::options(app, ui);- }- Tool::RectMarquee | Tool::EllipseMarquee => hint(- ui,- &format!(- "Drag to select · {} add · {} subtract · {} intersect · click to deselect",- crate::shortcuts::pretty("Shift"),- crate::shortcuts::pretty("Alt"),- crate::shortcuts::pretty("Shift+Alt")- ),- ),- Tool::SingleRowMarquee | Tool::SingleColumnMarquee => hint(- ui,- &format!(- "Click to select a one-pixel line · {} add · {} subtract · {} intersect",- crate::shortcuts::pretty("Shift"),- crate::shortcuts::pretty("Alt"),- crate::shortcuts::pretty("Shift+Alt")- ),- ),- Tool::Move => {- // The Studio themes keep Photoshop's Auto-Select toggle too (#1275).- widgets::checkbox(ui, &mut app.ui.tool_options.move_auto_select, tl!("Auto-Select:"));- // And Show Transform Controls (#5740): without it the box could not be- // turned on outside the Pro themes.- widgets::checkbox(ui, &mut app.ui.tool_options.move_show_transform, tl!("Show Transform Controls"));- hint(ui, tl!("Drag to move the active layer"));- widgets::vline(ui, 22.0);- crate::align_bar::options(app, ui);- }- Tool::Eyedropper => crate::eyedropper_ui::options(app, ui),- Tool::Zoom => {- // Resize Windows to Fit is Preferences › Zoom Resizes Windows itself, as in- // Photoshop: one setting, shown in both places (zoom_window_fit.rs).- let mut fit = app.session.prefs().general.zoom_resizes_windows;- if widgets::checkbox(ui, &mut fit, tl!("Resize Windows to Fit")).changed() {- app.session.prefs.edit(|p| p.general.zoom_resizes_windows = fit);- }- widgets::checkbox(ui, &mut app.ui.tool_options.zoom_scrubby, tl!("Scrubby Zoom"));- hint(- ui,- &crate::i18n::fmt(- tl!("Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out"),- &[("key", &crate::shortcuts::pretty("Alt"))],- ),- );- if widgets::secondary_button(ui, tl!("Fit Screen"), 0.0).clicked()- && let Some(i) = app.session.active_index()- {- app.ui.views[i].fit_pending = true;- app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom);- app.ui.views[i].zoom_anchor = None;- }- if widgets::secondary_button(ui, "100%", 0.0).clicked()- && let Some(i) = app.session.active_index()- {- app.ui.views[i].zoom = 1.0;- app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom);- app.ui.views[i].zoom_anchor = None;- app.ui.views[i].fit_pending = false;- app.ui.views[i].fill_pending = false;- }- }- Tool::RotateView => {- hint(ui, tl!("Drag around the centre to rotate the view · Shift constrains to 15°"));- if let Some(i) = app.session.active_index() {- ui.label(tl!("Angle"));- let mut angle = app.ui.views.get(i).map(|v| v.rotation).unwrap_or(0.0);- if widgets::value_field(ui, &mut angle, -180.0..=180.0, "°", 56.0).changed()- && let Some(v) = app.ui.views.get_mut(i)- {- v.rotation = crate::rotate_view::wrap_deg(angle);+ Tool::RotateView => {+ hint(ui, tl!("Drag around the centre to rotate the view · Shift constrains to 15°"));+ if let Some(i) = app.session.active_index() {+ ui.label(tl!("Angle"));+ let mut angle = app.ui.views.get(i).map(|v| v.rotation).unwrap_or(0.0);+ if widgets::value_field(ui, &mut angle, -180.0..=180.0, "°", 56.0).changed()+ && let Some(v) = app.ui.views.get_mut(i)+ {+ v.rotation = crate::rotate_view::wrap_deg(angle);+ }+ if widgets::secondary_button(ui, tl!("Reset View"), 0.0).clicked()+ && let Some(v) = app.ui.views.get_mut(i)+ {+ v.rotation = 0.0;+ }+ }}- if widgets::secondary_button(ui, tl!("Reset View"), 0.0).clicked()- && let Some(v) = app.ui.views.get_mut(i)- {- v.rotation = 0.0;+ Tool::Hand => {+ hint(ui, tl!("Drag to pan · hold Space with any tool"));+ if widgets::secondary_button(ui, "100%", 0.0).clicked()+ && let Some(i) = app.session.active_index()+ {+ app.ui.views[i].zoom = 1.0;+ app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom);+ app.ui.views[i].zoom_anchor = None;+ app.ui.views[i].fit_pending = false;+ app.ui.views[i].fill_pending = false;+ }+ if widgets::secondary_button(ui, tl!("Fit Screen"), 0.0).clicked()+ && let Some(i) = app.session.active_index()+ {+ app.ui.views[i].fit_pending = true;+ app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom);+ app.ui.views[i].zoom_anchor = None;+ app.ui.views[i].fill_pending = false;+ }+ if widgets::secondary_button(ui, tl!("Fill Screen"), 0.0).clicked()+ && let Some(i) = app.session.active_index()+ {+ app.ui.views[i].fill_pending = true;+ app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom);+ app.ui.views[i].zoom_anchor = None;+ app.ui.views[i].fit_pending = false;+ }}+ // Retouching and smart-selection tools draw their bar in `retouch_ui::options_bar`.+ _ => {}}- }- Tool::Hand => {- hint(ui, tl!("Drag to pan · hold Space with any tool"));- if widgets::secondary_button(ui, "100%", 0.0).clicked()- && let Some(i) = app.session.active_index()- {- app.ui.views[i].zoom = 1.0;- app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom);- app.ui.views[i].zoom_anchor = None;- app.ui.views[i].fit_pending = false;- app.ui.views[i].fill_pending = false;- }- if widgets::secondary_button(ui, tl!("Fit Screen"), 0.0).clicked()- && let Some(i) = app.session.active_index()- {- app.ui.views[i].fit_pending = true;- app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom);- app.ui.views[i].zoom_anchor = None;- app.ui.views[i].fill_pending = false;- }- if widgets::secondary_button(ui, tl!("Fill Screen"), 0.0).clicked()- && let Some(i) = app.session.active_index()- {- app.ui.views[i].fill_pending = true;- app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom);- app.ui.views[i].zoom_anchor = None;- app.ui.views[i].fit_pending = false;+ // Painting symmetry is independent of visual theme. Keep the options-bar+ // action available for Brush, Pencil and Eraser in every palette (#2659).+ if matches!(tool, Tool::Brush | Tool::Pencil | Tool::Eraser) {+ crate::symmetry_ui::menu(app, ui);}- }- Tool::Lasso | Tool::PolygonLasso => hint(- ui,- &crate::i18n::fmt(- tl!("Drag or click polygon points · hold Alt during lasso for straight segments · {add} add · {sub} before drawing subtracts"),- &[("add", &crate::shortcuts::pretty("Shift")), ("sub", &crate::shortcuts::pretty("Alt"))],- ),- ),- Tool::MagneticLasso => hint(- ui,- &crate::i18n::fmt(- tl!("Click, then move along an edge · click to fasten a point · {alt}-click for a straight segment · double-click to close"),- &[("alt", &crate::shortcuts::pretty("Alt"))],- ),- ),- Tool::Crop => hint(- ui,- &crate::i18n::fmt(- tl!("Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels"),- &[- ("ratio", &crate::shortcuts::pretty("Shift")),- ("centre", &crate::shortcuts::pretty("Alt")),- ("commit", &crate::shortcuts::pretty("Enter")),- ],- ),- ),- Tool::PerspectiveCrop => hint(- ui,- &crate::i18n::fmt(- tl!("Drag a box or click four corners · drag the corners onto the edges of a skewed shape · {commit} commits · Esc cancels"),- &[("commit", &crate::shortcuts::pretty("Enter"))],- ),- ),- Tool::PaintBucket => hint(ui, tl!("Click to fill similar colours")),- // Retouching and smart-selection tools draw their bar in `retouch_ui::options_bar`.- _ => {}- }- // Painting symmetry is independent of visual theme. Keep the options-bar- // action available for Brush, Pencil and Eraser in every palette (#2659).- if matches!(tool, Tool::Brush | Tool::Pencil | Tool::Eraser) {- crate::symmetry_ui::menu(app, ui);- }- crate::brush_panel::commit_gesture(app, ui.ctx(), &brush_before, &brush);- });- reveal_focused_control(ui);- });+ crate::brush_panel::commit_gesture(app, ui.ctx(), &brush_before, &brush);+ });+ reveal_focused_control(ui);+ });});});}diff --cc docs/control-protocol.mdindex 747350c11,07d3a0918..6d8b00a80--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@@ -393,8 -378,7 +393,8 @@@ no MCP framing, no app start-up per com| `session.list` | open documents and the active index || `doc.open` / `doc.new` | `{path}` / `file.new` params || `doc.place` | `{path, scale? (percent), fit? (true), center? ([x, y]), index?}`: places a file as a Smart Object layer above the active one and returns `{layer, scale, bounds}`. `path` resolves beneath the read root, so this is the capability-scoped `file.placeEmbedded` — that command itself still refuses an ambient path |+| `doc.replaceSmartObject` | `{path, layer? (id or name; default the active layer), index?}` → the command's `{layer, instances}`: replaces a Smart Object's contents (one history step, transform and filters kept). `path` resolves beneath the read root, so this is the capability-scoped `layer.smartObjects.replaceContents`, which itself still refuses an ambient path (#8061) |- | `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, count}`: one file per exported layer, named like `file.export.layersToFiles` names them. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file |+ | `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, skipped}` (plus `count` for workspace exports): one file per exported top-level layer, named like `file.export.layersToFiles` names them. `count` is present only for workspace exports and counts written files only. `skipped` is always an array (empty when nothing is omitted), in top-to-bottom order, of `{layer, name, reason}`: the session layer id, original unsanitized name, and `"hidden by visibleOnly"` or `"adjustment layer has no pixels of its own"`. Visibility takes precedence for hidden adjustments; `visibleOnly:false` exports hidden non-adjustment layers. Groups export merged; their children are not separate exports or skips. Existing filenames/numbering are unchanged. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file. Encode/write failures are errors, not skips || `doc.exportDataSets` | `{dir, format? (png), dataSets? (all), naming? ("{name}\|{index}\|{document}"), index?}` → `{files, count}`: the capability-scoped `file.export.dataSetsAsFiles`. The batch is planned first and colliding names are refused before any file is written, as in the command || `doc.importDataSets` | `{path, delimiter? (,), index?}` → `{imported}`: the capability-scoped `file.import.variableDataSets`; the CSV is read beneath the read root || `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tgaBits?, ddsCompression?, ddsMipmaps?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tgaBits` 24 or 32 sets a TGA's bits per pixel, and `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, as `app.save` does). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty |diff --cc docs/ui-parity.mdindex f725984b9,f1ed065ce..d778ba34f--- a/docs/ui-parity.md+++ b/docs/ui-parity.md@@@ -1,6 -1,6 +1,6 @@@# UI parity: tools, handles, modifiers and feel- > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests) · **Target:** Adobe Photoshop 2026-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests) · **Target:** Adobe Photoshop 2026++> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests) · **Target:** Adobe Photoshop 2026How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, thehandles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation,@@@ -242,7 -241,7 +243,8 @@@ Paragraph; the rest open as in-app floa| Date | Change | Summary ||---|---|---|+ | 2026-10-22 | minor | Crop default mode: a drag inside an upright box snaps the frame's edges and centre to the document, layers, guides and grid, as a Classic Mode frame's move does (#8580); no percentage changed |+| 2026-10-21 | minor | Adjustment clipping moved above Properties editors to remain visible in compact docks (#5231); scope, undo/redo and 8/16/32-bit pixel regressions; readiness estimate unchanged || 2026-10-19 | minor | A guide being moved or dragged out of a ruler shows an `X:` / `Y:` position readout beside the pointer, from the zero point in the ruler unit (#7680) || 2026-10-17 | minor | The wheel steps value fields: a focused field takes it wherever the pointer is (the canvas and panels don't scroll), an unfocused one only a gesture that starts over it (#5473, #4061); no percentage changed || 2026-10-17 | minor | Object Finder foreground/background discrimination (#6548) |