Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Add Photoshop-style guide layout dialog and live preview (#2930)

Skyfullerec28fdd03d94
diff --git a/contributors/people.toml b/contributors/people.toml
index 25d60599e..b7107559a 100644
--- a/contributors/people.toml
+++ b/contributors/people.toml
@@ -17,6 +17,10 @@
# To remove your names, delete your entry (or set fields empty) in a PR. The next
# contributors.py run, and the next build, drop them.
+[people.Skyfuller1303]
+display_name = "Skyfuller"
+sync_github_name = true
+
[people.AlanRockefeller]
sync_github_name = true
@@ -97,5 +101,3 @@ sync_github_name = true
[people.TheTeslak]
sync_github_name = true
-[people.Skyfuller1303]
-sync_github_name = true
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index 0ccf1d10e..a6096ac96 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -1267,77 +1267,8 @@ fn push_unique(v: &mut Vec<f32>, x: f64) {
}
}
-/// Guide positions for `count` columns (or rows) across `[start, end]`, Photoshop-style: both
-/// edges of every column; a fixed `width` packs columns from `start` (or centres them).
-fn layout_lines(start: f64, end: f64, count: u32, width: Option<f64>, gutter: f64, center: bool, out: &mut Vec<f32>) {
- let avail = (end - start).max(0.0);
- if count == 0 {
- return;
- }
- let n = count as f64;
- let w = width.unwrap_or(((avail - (n - 1.0) * gutter) / n).max(0.0));
- let total = n * w + (n - 1.0) * gutter;
- let x0 = if center && width.is_some() { start + (avail - total) / 2.0 } else { start };
- for i in 0..count {
- let a = x0 + i as f64 * (w + gutter);
- push_unique(out, a);
- push_unique(out, a + w);
- }
-}
-
fn new_guide_layout(s: &mut Session, p: &Value) -> Result<Value> {
- let d = s.active().ok_or(EngineError::NoDocument)?;
- let (cw, ch) = (d.doc.size.width as f64, d.doc.size.height as f64);
- let m = match p.get("margin") {
- Some(Value::Array(a)) if a.len() == 4 => [0, 1, 2, 3].map(|i| a[i].as_f64().unwrap_or(0.0)),
- Some(v) if v.is_number() => [v.as_f64().unwrap_or(0.0); 4],
- _ => [0.0; 4],
- };
- let [top, left, bottom, right] = m;
- let cols = p.get("columns").and_then(Value::as_u64).unwrap_or(0);
- let rows = p.get("rows").and_then(Value::as_u64).unwrap_or(0);
- // Each column/row costs a loop iteration plus a duplicate scan, so an
- // absurd count from the caller would block the app for minutes (#704).
- // Photoshop's own dialog caps at 32; 1000 is a generous ceiling that
- // still finishes instantly.
- const MAX_GUIDE_LINES: u64 = 1000;
- for (n, what) in [(cols, "columns"), (rows, "rows")] {
- if n > MAX_GUIDE_LINES {
- return Err(EngineError::BadParams { cmd: "view.newGuideLayout".into(), msg: format!("{what} must be {MAX_GUIDE_LINES} or fewer (got {n})") });
- }
- }
- let (cols, rows) = (cols as u32, rows as u32);
- let mut v: Vec<f32> = Vec::new();
- let mut h: Vec<f32> = Vec::new();
- let has_margin = m.iter().any(|x| *x != 0.0);
- if has_margin {
- push_unique(&mut v, left);
- push_unique(&mut v, cw - right);
- push_unique(&mut h, top);
- push_unique(&mut h, ch - bottom);
- }
- let center = p.get("centerColumns").and_then(Value::as_bool).unwrap_or(false);
- layout_lines(left, cw - right, cols, size_param(p, "width"), f64_param(p, "gutter").unwrap_or(0.0), center, &mut v);
- layout_lines(top, ch - bottom, rows, size_param(p, "height"), f64_param(p, "rowGutter").or_else(|| f64_param(p, "gutter")).unwrap_or(0.0), center, &mut h);
- if v.is_empty() && h.is_empty() {
- return Err(EngineError::BadParams { cmd: "view.newGuideLayout".into(), msg: "give \"columns\", \"rows\" or a \"margin\"".into() });
- }
- let clear = p.get("clearExisting").and_then(Value::as_bool).unwrap_or(false);
- let (nv, nh) = (v.len(), h.len());
- s.edit("New Guide Layout", |doc, _| {
- if clear {
- doc.guides.vertical.clear();
- doc.guides.horizontal.clear();
- }
- for x in v {
- push_unique(&mut doc.guides.vertical, x as f64);
- }
- for y in h {
- push_unique(&mut doc.guides.horizontal, y as f64);
- }
- Ok(())
- })?;
- Ok(json!({"vertical": nv, "horizontal": nh}))
+ crate::guide_layout::apply(s, p)
}
fn guides_from_shape(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1538,7 +1469,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Guide Layout…",
&["View"],
None,
- r##"{"columns":n=0,"width":px?,"gutter":px=0,"rows":n=0,"height":px?,"rowGutter":px=gutter,"margin":px|[top,left,bottom,right]=0,"centerColumns":bool=false,"clearExisting":bool=false}"##,
+ r##"{"columns":n=0,"width":px?,"gutter":px=0,"rows":n=0,"height":px?,"rowGutter":px=gutter,"margin":px|[top,left,bottom,right]=0,"centerColumns":bool=false,"clearExisting":bool=false,"target":"document|selectedArtboards"="document"}"##,
has_doc,
new_guide_layout
),
diff --git a/crates/engine/src/guide_layout.rs b/crates/engine/src/guide_layout.rs
new file mode 100644
index 000000000..770843047
--- /dev/null
+++ b/crates/engine/src/guide_layout.rs
@@ -0,0 +1,184 @@
+//! Pure guide-layout calculation shared by the command and its non-destructive UI preview.
+
+use photocraft_doc::Guides;
+use photocraft_geom::Rect;
+use serde_json::Value;
+
+use crate::{EngineError, Result, Session};
+
+const COMMAND: &str = "view.newGuideLayout";
+const MAX_COUNT: u64 = 1000;
+const MAX_EDGES: u64 = 16_000;
+
+fn bad(message: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: COMMAND.into(), msg: message.into() }
+}
+
+fn number(p: &Value, key: &str, default: f64) -> Result<f64> {
+ match p.get(key) {
+ None | Some(Value::Null) => Ok(default),
+ Some(v) => v.as_f64().filter(|n| n.is_finite() && *n >= 0.0).ok_or_else(|| bad(format!("{key} must be a finite non-negative number"))),
+ }
+}
+
+fn count(p: &Value, key: &str) -> Result<u64> {
+ let n = match p.get(key) {
+ None => 0,
+ Some(v) => v.as_u64().ok_or_else(|| bad(format!("{key} must be a whole number")))?,
+ };
+ // Each column/row costs a loop iteration plus a duplicate scan, so an
+ // absurd count from the caller would block the app for minutes (#704).
+ // Photoshop's own dialog caps at 32; 1000 is a generous ceiling that
+ // still finishes instantly.
+ if n > MAX_COUNT {
+ return Err(bad(format!("{key} must be {MAX_COUNT} or fewer (got {n})")));
+ }
+ Ok(n)
+}
+
+fn flag(p: &Value, key: &str) -> Result<bool> {
+ match p.get(key) {
+ None => Ok(false),
+ Some(v) => v.as_bool().ok_or_else(|| bad(format!("{key} must be a boolean"))),
+ }
+}
+
+/// Document coordinates of every selected artboard, including boards containing selected layers.
+pub fn selected_artboards(s: &Session) -> Vec<Rect> {
+ let Some(st) = s.active() else { return Vec::new() };
+ let selected = st.selected_layers();
+ let ids: std::collections::HashSet<_> = selected.iter().filter_map(|id| st.doc.artboard_of(*id)).collect();
+ st.doc.artboards().into_iter().filter(|(id, _, _)| ids.contains(id)).map(|(_, _, board)| board.rect).collect()
+}
+
+fn targets(s: &Session, p: &Value) -> Result<Vec<Rect>> {
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let target = match p.get("target") {
+ None => "document",
+ Some(v) => v.as_str().ok_or_else(|| bad("target must be a string"))?,
+ };
+ match target {
+ "document" => Ok(vec![st.doc.bounds()]),
+ "selectedArtboards" => {
+ let boards = selected_artboards(s);
+ if boards.is_empty() { Err(bad("select an artboard or a layer inside one")) } else { Ok(boards) }
+ }
+ _ => Err(bad("target must be document or selectedArtboards")),
+ }
+}
+
+fn push_unique(out: &mut Vec<f32>, value: f64) -> Result<()> {
+ let value = value as f32;
+ if !value.is_finite() {
+ return Err(bad("guide coordinates exceed the supported range"));
+ }
+ if !out.iter().any(|x| (*x - value).abs() < 0.01) {
+ out.push(value);
+ }
+ Ok(())
+}
+
+/// Guide positions for `count` columns (or rows) across `[start, end]`, Photoshop-style: both
+/// edges of every column; a fixed `width` packs columns from `start` (or centres them).
+fn axis(start: f64, end: f64, count: u64, fixed: f64, gap: f64, center: bool, out: &mut Vec<f32>) -> Result<()> {
+ if count == 0 {
+ return Ok(());
+ }
+ let available = end - start;
+ let n = count as f64;
+ let width = if fixed > 0.0 { fixed } else { (available - (n - 1.0) * gap) / n };
+ let total = n * width + (n - 1.0) * gap;
+ if width <= 0.0 || !total.is_finite() || total > available + 0.001 {
+ return Err(bad("count, size and gutter must fit inside the target margins"));
+ }
+ let origin = if center && fixed > 0.0 { start + (available - total) / 2.0 } else { start };
+ for i in 0..count {
+ let a = origin + i as f64 * (width + gap);
+ push_unique(out, a)?;
+ push_unique(out, a + width)?;
+ }
+ Ok(())
+}
+
+/// New lines and the exact guide set that OK will commit. This never edits the session.
+#[derive(Clone, Debug)]
+pub struct Layout {
+ pub added: Guides,
+ pub guides: Guides,
+}
+
+pub fn calculate(s: &Session, p: &Value) -> Result<Layout> {
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let cols = count(p, "columns")?;
+ let rows = count(p, "rows")?;
+ let width = number(p, "width", 0.0)?;
+ let height = number(p, "height", 0.0)?;
+ let gap = number(p, "gutter", 0.0)?;
+ let row_gap = number(p, "rowGutter", gap)?;
+ let center = flag(p, "centerColumns")?;
+ let clear = flag(p, "clearExisting")?;
+ let margins = match p.get("margin") {
+ Some(Value::Array(a)) => {
+ if a.len() != 4 {
+ return Err(bad("margin must contain top, left, bottom and right"));
+ }
+ let mut m = [0.0; 4];
+ for (out, value) in m.iter_mut().zip(a) {
+ *out = value.as_f64().filter(|v| v.is_finite() && *v >= 0.0).ok_or_else(|| bad("margins must be finite non-negative numbers"))?;
+ }
+ m
+ }
+ _ => [number(p, "margin", 0.0)?; 4],
+ };
+ let [top, left, bottom, right] = margins;
+ let bounds = targets(s, p)?;
+ // Bound the aggregate work as well as each count, including multi-artboard requests.
+ if (cols + rows + 4).saturating_mul(2).saturating_mul(bounds.len() as u64) > MAX_EDGES {
+ return Err(bad("the selected targets would create too many guide lines"));
+ }
+ let mut added = Guides::default();
+ for rect in &bounds {
+ let (x0, y0, x1, y1) = (f64::from(rect.x0) + left, f64::from(rect.y0) + top, f64::from(rect.x1) - right, f64::from(rect.y1) - bottom);
+ if x0 >= x1 || y0 >= y1 {
+ return Err(bad("margins must leave space inside the target"));
+ }
+ if margins.iter().any(|x| *x != 0.0) {
+ push_unique(&mut added.vertical, x0)?;
+ push_unique(&mut added.vertical, x1)?;
+ push_unique(&mut added.horizontal, y0)?;
+ push_unique(&mut added.horizontal, y1)?;
+ }
+ axis(x0, x1, cols, width, gap, center, &mut added.vertical)?;
+ axis(y0, y1, rows, height, row_gap, center, &mut added.horizontal)?;
+ }
+ if added.vertical.is_empty() && added.horizontal.is_empty() {
+ return Err(bad("give \"columns\", \"rows\" or a \"margin\""));
+ }
+ let mut guides = st.doc.guides.clone();
+ if clear {
+ if p.get("target").and_then(Value::as_str) == Some("selectedArtboards") {
+ // Guides are stored as document-wide axes, matching Clear Selected Artboard Guides.
+ guides.vertical.retain(|v| !bounds.iter().any(|r| f64::from(*v) >= f64::from(r.x0) && f64::from(*v) <= f64::from(r.x1)));
+ guides.horizontal.retain(|v| !bounds.iter().any(|r| f64::from(*v) >= f64::from(r.y0) && f64::from(*v) <= f64::from(r.y1)));
+ } else {
+ guides = Guides::default();
+ }
+ }
+ for x in &added.vertical {
+ push_unique(&mut guides.vertical, f64::from(*x))?;
+ }
+ for y in &added.horizontal {
+ push_unique(&mut guides.horizontal, f64::from(*y))?;
+ }
+ Ok(Layout { added, guides })
+}
+
+pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
+ let layout = calculate(s, p)?;
+ let result = serde_json::json!({"vertical":layout.added.vertical.len(),"horizontal":layout.added.horizontal.len()});
+ s.edit("New Guide Layout", |doc, _| {
+ doc.guides = layout.guides;
+ Ok(())
+ })?;
+ Ok(result)
+}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index a20d02bf8..749c04475 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -48,6 +48,7 @@ pub mod fx_visibility_cmds;
pub mod gallery_cmds;
pub mod gradient_fill_cmds;
pub mod group_view_cmds;
+pub mod guide_layout;
pub mod hidden_target;
pub mod history_cmds;
pub mod image_cmds;
diff --git a/crates/engine/tests/guide_layout_preview.rs b/crates/engine/tests/guide_layout_preview.rs
new file mode 100644
index 000000000..c49aa2a60
--- /dev/null
+++ b/crates/engine/tests/guide_layout_preview.rs
@@ -0,0 +1,73 @@
+use photocraft_engine::{Session, guide_layout};
+use serde_json::json;
+
+fn session() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width":100,"height":60})).unwrap();
+ s
+}
+
+#[test]
+fn pure_preview_matches_commit_and_one_undo_restores_existing_guides() {
+ let mut s = session();
+ s.execute("view.newGuideLayout", json!({"columns":2})).unwrap();
+ let before = s.active().unwrap().doc.guides.clone();
+ let revision = s.active().unwrap().revision;
+ let p = json!({"columns":3,"rows":2,"gutter":4,"rowGutter":6,"margin":[3,7,5,11],"clearExisting":true});
+ let preview = guide_layout::calculate(&s, &p).unwrap();
+ assert_eq!(s.active().unwrap().revision, revision);
+ assert_eq!(s.active().unwrap().doc.guides, before);
+ s.execute("view.newGuideLayout", p).unwrap();
+ assert_eq!(s.active().unwrap().doc.guides, preview.guides);
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(s.active().unwrap().doc.guides, before);
+ s.execute("edit.redo", json!({})).unwrap();
+ assert_eq!(s.active().unwrap().doc.guides, preview.guides);
+}
+
+#[test]
+fn fixed_sizes_center_and_keep_existing_lines() {
+ let mut s = session();
+ s.execute("view.newGuideLayout", json!({"margin":5})).unwrap();
+ let before = s.active().unwrap().doc.guides.clone();
+ let p = json!({"columns":2,"width":20,"gutter":10,"rows":2,"height":10,"rowGutter":4,"centerColumns":true});
+ let result = guide_layout::calculate(&s, &p).unwrap();
+ assert_eq!(result.added.vertical, vec![25.0, 45.0, 55.0, 75.0]);
+ assert_eq!(result.added.horizontal, vec![18.0, 28.0, 32.0, 42.0]);
+ assert!(before.vertical.iter().all(|g| result.guides.vertical.contains(g)));
+ assert!(before.horizontal.iter().all(|g| result.guides.horizontal.contains(g)));
+}
+
+#[test]
+fn invalid_geometry_is_atomic() {
+ let mut s = session();
+ let revision = s.active().unwrap().revision;
+ for params in [
+ json!({"columns":-1}),
+ json!({"rows":1.5}),
+ json!({"columns":2,"width":60}),
+ json!({"columns":3,"gutter":50}),
+ json!({"margin":[1,2,3]}),
+ json!({"margin":[0,100,0,0]}),
+ json!({"columns":2,"gutter":"bad"}),
+ json!({"columns":2,"clearExisting":1}),
+ json!({"columns":1,"target":"selectedArtboards"}),
+ ] {
+ assert!(s.execute("view.newGuideLayout", params.clone()).is_err(), "accepted {params}");
+ assert_eq!(s.active().unwrap().revision, revision);
+ }
+}
+
+#[test]
+fn selected_artboards_use_offsets_and_clear_only_the_target_ranges() {
+ let mut s = session();
+ s.execute("view.newGuideLayout", json!({"margin":5})).unwrap();
+ s.execute("layer.new.artboard", json!({"rect":[200,100,100,60]})).unwrap();
+ let p = json!({"columns":2,"margin":[5,10,5,10],"target":"selectedArtboards","clearExisting":true});
+ let preview = guide_layout::calculate(&s, &p).unwrap();
+ assert_eq!(preview.added.vertical, vec![210.0, 290.0, 250.0]);
+ assert_eq!(preview.added.horizontal, vec![105.0, 155.0]);
+ assert!(preview.guides.vertical.contains(&5.0));
+ s.execute("view.newGuideLayout", p).unwrap();
+ assert_eq!(s.active().unwrap().doc.guides, preview.guides);
+}
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index b99b8780e..a2bb654c3 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -3113,7 +3113,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
if app.ui.extras.grid && app.ui.view.extras {
crate::rulers::draw_grid(app, &painter, &xf, &doc);
}
- if app.ui.view.shows(app.ui.view.show.canvas_guides) {
+ if app.ui.view.shows(app.ui.view.show.canvas_guides) || crate::guide_layout_ui::preview(app, &doc).is_some() {
crate::rulers::draw_guides(app, &painter, &xf, &doc);
}
// The pending crop frame shows on its own document only, not on the other tiles (#1918).
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index c14b9fc48..c3994e591 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -210,6 +210,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
ui.add_space(8.0);
about_tab_body(app, ui, chosen);
}
+ DialogKind::Command if crate::guide_layout_ui::owns(&fields) => outcome = crate::guide_layout_ui::body(app, ui, &mut fields, interactive),
DialogKind::Command if crate::fill_ui::owns(&fields) => crate::fill_ui::body(app, ui, &mut fields),
DialogKind::Command if crate::stroke_ui::owns(&fields) => crate::stroke_ui::body(ui, &mut fields),
DialogKind::Command if crate::shape_dialog::owns(&fields) => crate::shape_dialog::body(app, ui, &mut fields),
@@ -249,7 +250,9 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
}
}
crate::field_tab::end(ui.ctx(), tab);
- if crate::color_picker_ui::owns(&fields) {
+ if crate::guide_layout_ui::owns(&fields) {
+ // This dialog owns its right-side actions and validates Enter itself.
+ } else if crate::color_picker_ui::owns(&fields) {
if interactive && outcome.is_none() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
outcome = Some(true);
}
@@ -417,6 +420,12 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
if crate::layer_style::color_picker::has_child(app, id) {
return Err("confirm or cancel the Layer Style color picker first".into());
}
+ if let Some(d) = app.ui.dialogs.iter().find(|d| d.id == id).filter(|d| crate::guide_layout_ui::owns(&d.fields)) {
+ if app.ui.dialogs.iter().any(|child| crate::color_picker_ui::owns(&child.fields) && child.fields.get("__dialog").and_then(Value::as_u64) == Some(id)) {
+ return Err("confirm or cancel the guide color picker first".into());
+ }
+ crate::guide_layout_ui::validate(app, &d.fields)?;
+ }
let d = app.ui.close_dialog(id).ok_or_else(|| format!("no dialog {id}"))?;
match d.kind {
DialogKind::NewDocument => {
@@ -429,6 +438,7 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
}
r
}
+ DialogKind::Command if crate::guide_layout_ui::owns(&d.fields) => crate::guide_layout_ui::confirm(app, &d.fields),
DialogKind::Command if crate::fill_ui::owns(&d.fields) => crate::fill_ui::confirm(app, &d.fields),
DialogKind::Command if crate::stroke_ui::owns(&d.fields) => crate::stroke_ui::confirm(app, &d.fields),
DialogKind::Command if crate::shape_dialog::owns(&d.fields) => crate::shape_dialog::confirm(app, &d.fields),
@@ -474,7 +484,10 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
/// Cancel a dialog and its dependent Layer Style picker, without applying edits.
pub fn cancel(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
- app.ui.close_dialog(id).ok_or_else(|| format!("no dialog {id}"))?;
+ let closed = app.ui.close_dialog(id).ok_or_else(|| format!("no dialog {id}"))?;
+ if crate::guide_layout_ui::owns(&closed.fields) {
+ app.ui.dialogs.retain(|child| child.fields.get("__dialog").and_then(Value::as_u64) != Some(id));
+ }
app.ui.dialogs.retain(|d| !crate::layer_style::color_picker::child_of(&d.fields, id));
app.filter_preview = None;
app.color_range = None;
@@ -486,6 +499,9 @@ pub fn cancel(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
/// schema dialog for filters, the Color Range dialog for `select.colorRange`, otherwise a bare
/// confirm dialog.
pub fn open_command_dialog(app: &mut PhotocraftApp, command: &str, label: &str) -> u64 {
+ if command == "view.newGuideLayout" {
+ return crate::guide_layout_ui::open(app);
+ }
if command == crate::stroke_ui::COMMAND {
return crate::stroke_ui::open(app);
}
diff --git a/crates/ui-egui/src/guide_layout_ui.rs b/crates/ui-egui/src/guide_layout_ui.rs
new file mode 100644
index 000000000..d85daf305
--- /dev/null
+++ b/crates/ui-egui/src/guide_layout_ui.rs
@@ -0,0 +1,359 @@
+//! Photoshop-style guide layout dialog. Its preview is a pure guide overlay, never an edit.
+
+use egui::{Color32, Stroke};
+use photocraft_doc::{Document, Guides};
+use serde_json::{Map, Value, json};
+
+use crate::{PhotocraftApp, theme::Tokens, widgets};
+
+const COMMAND: &str = "view.newGuideLayout";
+const MARK: &str = "__guideLayout";
+const COLORS: [(&str, &str); 5] = [("#4affff", "Cyan"), ("#ff00ff", "Magenta"), ("#378ef0", "Blue"), ("#00a86b", "Green"), ("#ffcc00", "Yellow")];
+
+pub fn owns(f: &Map<String, Value>) -> bool {
+ f.contains_key(MARK)
+}
+
+fn on(f: &Map<String, Value>, key: &str, fallback: bool) -> bool {
+ f.get(key).and_then(Value::as_bool).unwrap_or(fallback)
+}
+fn positive(f: &Map<String, Value>, key: &str) -> bool {
+ f.get(key).and_then(Value::as_f64).is_some_and(|n| n > 0.0)
+}
+
+pub fn open(app: &mut PhotocraftApp) -> u64 {
+ let mut f = app.ui.view.guide_layout.as_object().cloned().unwrap_or_default();
+ f.insert(MARK.into(), json!(true));
+ f.insert("__command".into(), json!(COMMAND));
+ f.insert("__label".into(), json!("New Guide Layout…"));
+ f.insert("__document".into(), app.session.active().map(|s| json!(s.doc.id)).unwrap_or(Value::Null));
+ f.insert("__preview".into(), json!(true));
+ f.insert("color".into(), json!(app.session.prefs().guides_grid_and_slices.guide_color));
+ f.entry("target").or_insert_with(|| json!("document"));
+ if f.get("target").and_then(Value::as_str) == Some("selectedArtboards") && photocraft_engine::guide_layout::selected_artboards(&app.session).is_empty() {
+ f.insert("target".into(), json!("document"));
+ }
+ f.entry("__preset").or_insert_with(|| json!("custom"));
+ f.entry("width").or_insert(Value::Null);
+ f.entry("height").or_insert(Value::Null);
+ let margin = f.get("margin").cloned().unwrap_or(json!(0));
+ if !margin.is_array() {
+ f.insert("margin".into(), json!([margin.clone(), margin.clone(), margin.clone(), margin]));
+ }
+ for key in ["__previewGuides", "__previewParams", "__previewSource"] {
+ f.remove(key);
+ }
+ app.ui.open_dialog(crate::state::DialogKind::Command, f)
+}
+
+/// Preserve legacy command parameter names for automation and remembered defaults.
+pub fn params(f: &Map<String, Value>) -> Value {
+ let mut p: Map<String, Value> = ["columns", "rows", "width", "height", "gutter", "rowGutter", "margin", "centerColumns", "clearExisting", "target"]
+ .into_iter()
+ .filter_map(|k| f.get(k).cloned().map(|v| (k.to_string(), v)))
+ .collect();
+ for (toggle, key) in [("__columnsEnabled", "columns"), ("__rowsEnabled", "rows")] {
+ if !on(f, toggle, positive(f, key)) {
+ p.insert(key.into(), json!(0));
+ }
+ }
+ if !on(f, "__marginEnabled", true) {
+ p.insert("margin".into(), json!(0));
+ }
+ for key in ["width", "height"] {
+ if let Some(Value::String(s)) = p.get(key) {
+ let value = if s.trim().is_empty() {
+ Value::Null
+ } else {
+ widgets::parse_num(s).and_then(serde_json::Number::from_f64).map(Value::Number).unwrap_or_else(|| json!(s))
+ };
+ p.insert(key.into(), value);
+ }
+ }
+ // A disabled axis must not be rejected for a stale width or gap typed before disabling it.
+ for (key, size, gap) in [("columns", "width", "gutter"), ("rows", "height", "rowGutter")] {
+ if p.get(key).and_then(Value::as_u64) == Some(0) {
+ p.insert(size.into(), Value::Null);
+ p.insert(gap.into(), json!(0));
+ }
+ }
+ Value::Object(p)
+}
+
+fn source(app: &PhotocraftApp) -> Value {
+ app.session.active().map(|st| json!([st.doc.id, st.revision, st.active_layer, st.selected_layers])).unwrap_or(Value::Null)
+}
+
+fn calculate(app: &PhotocraftApp, f: &Map<String, Value>) -> Result<Guides, String> {
+ let st = app.session.active().ok_or("no document")?;
+ if f.get("__document") != Some(&json!(st.doc.id)) {
+ return Err("the guide layout belongs to another document".into());
+ }
+ let params = params(f);
+ // Painting an unchanged dialog must not repeat the duplicate scans every frame.
+ if f.get("__previewParams") == Some(&params)
+ && f.get("__previewSource") == Some(&source(app))
+ && let Some(guides) = f.get("__previewGuides").and_then(|v| serde_json::from_value(v.clone()).ok())
+ {
+ return Ok(guides);
+ }
+ photocraft_engine::guide_layout::calculate(&app.session, &params).map(|l| l.guides).map_err(|e| e.to_string())
+}
+
+pub fn validate(app: &PhotocraftApp, f: &Map<String, Value>) -> Result<(), String> {
+ let color = f.get("color").and_then(Value::as_str).unwrap_or("#4affff");
+ crate::rulers::parse_guide_color(color).ok_or("invalid guide color")?;
+ calculate(app, f).map(|_| ())
+}
+
+pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {
+ validate(app, f)?;
+ let color = f.get("color").and_then(Value::as_str).unwrap_or("#4affff");
+ // Colour is the existing global guide display preference, not document data.
+ let color = crate::rulers::parse_guide_color(color).ok_or("invalid guide color")?;
+ let hex = format!("#{:02x}{:02x}{:02x}", color.r(), color.g(), color.b());
+ let result = app.run(COMMAND, params(f))?;
+ app.session.prefs.edit(|prefs| prefs.guides_grid_and_slices.guide_color = hex);
+ let mut remembered = f.clone();
+ for key in [MARK, "__command", "__label", "__document", "__previewGuides", "__previewParams", "__previewSource"] {
+ remembered.remove(key);
+ }
+ app.ui.view.guide_layout = Value::Object(remembered);
+ Ok(result)
+}
+
+/// Full replacement guide set for the dialog's own document. Cancel/removal drops it immediately.
+pub fn preview(app: &PhotocraftApp, doc: &Document) -> Option<(Guides, Color32)> {
+ let dialog = app.ui.dialogs.iter().rev().find(|d| owns(&d.fields))?;
+ let f = &dialog.fields;
+ if !on(f, "__preview", true) || f.get("__document") != Some(&json!(doc.id)) {
+ return None;
+ }
+ let guides = calculate(app, f).ok().or_else(|| f.get("__previewGuides").and_then(|v| serde_json::from_value(v.clone()).ok()))?;
+ let color = f.get("color").and_then(Value::as_str).and_then(crate::rulers::parse_guide_color).unwrap_or(Color32::from_rgb(74, 255, 255));
+ Some((guides, color))
+}
+
+fn check(ui: &mut egui::Ui, f: &mut Map<String, Value>, key: &str, label: &str, fallback: bool) -> bool {
+ let mut value = on(f, key, fallback);
+ if widgets::checkbox(ui, &mut value, label).changed() {
+ f.insert(key.into(), json!(value));
+ }
+ value
+}
+
+fn number(ui: &mut egui::Ui, f: &mut Map<String, Value>, key: &str, count: bool) {
+ let mut value = f.get(key).and_then(Value::as_f64).unwrap_or(0.0) as f32;
+ if widgets::value_field(ui, &mut value, (if count { 1.0 } else { 0.0 })..=if count { 1000.0 } else { 300_000.0 }, if count { "" } else { "px" }, 68.0)
+ .changed()
+ {
+ f.insert(key.into(), if count { json!(value.round() as u64) } else { json!(value) });
+ }
+}
+
+fn optional(ui: &mut egui::Ui, f: &mut Map<String, Value>, key: &str) {
+ let mut value = match f.get(key) {
+ Some(Value::String(s)) => s.clone(),
+ Some(v) if v.is_number() => v.to_string(),
+ _ => String::new(),
+ };
+ let t = Tokens::get(ui.ctx());
+ let response = ui.add(egui::TextEdit::singleline(&mut value).id_salt(key).desired_width(60.0).font(crate::theme::mono(12.0)).background_color(t.field));
+ if ui.is_enabled() {
+ crate::field_tab::register(ui.ctx(), response.id);
+ }
+ if response.gained_focus() {
+ crate::field_tab::select_all(ui.ctx(), response.id, &value);
+ }
+ if response.changed() {
+ f.insert(key.into(), json!(value));
+ }
+ response.on_hover_text(tl!("Leave empty for automatic size"));
+}
+
+fn group<R>(ui: &mut egui::Ui, content: impl FnOnce(&mut egui::Ui) -> R) -> R {
+ let t = Tokens::get(ui.ctx());
+ egui::Frame::new().stroke(Stroke::new(1.0, t.field_border)).inner_margin(8).show(ui, |ui| ui.vertical(content).inner).inner
+}
+
+fn axis(ui: &mut egui::Ui, f: &mut Map<String, Value>, rows: bool) {
+ let (toggle, count, size, gap, title, size_label) = if rows {
+ ("__rowsEnabled", "rows", "height", "rowGutter", tl!("Rows"), tl!("Height"))
+ } else {
+ ("__columnsEnabled", "columns", "width", "gutter", tl!("Columns"), tl!("Width"))
+ };
+ group(ui, |ui| {
+ let enabled = check(ui, f, toggle, title, positive(f, count));
+ if enabled && f.get(count).and_then(Value::as_f64) == Some(0.0) {
+ f.insert(count.into(), json!(1));
+ }
+ ui.add_space(6.0);
+ ui.add_enabled_ui(enabled, |ui| {
+ egui::Grid::new(count).spacing([8.0, 6.0]).show(ui, |ui| {
+ ui.label(tl!("Number"));
+ number(ui, f, count, true);
+ ui.end_row();
+ ui.label(size_label);
+ optional(ui, f, size);
+ ui.end_row();
+ ui.label(tl!("Spacing"));
+ number(ui, f, gap, false);
+ ui.end_row();
+ });
+ });
+ });
+}
+
+fn main_fields(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+ let before: Map<String, Value> = f.iter().filter(|(key, _)| !key.starts_with("__preview")).map(|(k, v)| (k.clone(), v.clone())).collect();
+ egui::Grid::new("guide-header").spacing([8.0, 6.0]).show(ui, |ui| {
+ ui.label(tl!("Preset:"));
+ let mut preset = f.get("__preset").and_then(Value::as_str).unwrap_or("custom").to_string();
+ if widgets::dropdown(
+ ui,
+ "guide-preset",
+ &mut preset,
+ &[("custom".into(), "Custom"), ("five".into(), "5 Columns, 3 Rows"), ("eight".into(), "8 Columns"), ("twelve".into(), "12 Columns")],
+ 222.0,
+ ) {
+ f.insert("__preset".into(), json!(preset));
+ match preset.as_str() {
+ "five" | "eight" | "twelve" => {
+ let (cols, rows, gap) = match preset.as_str() {
+ "five" => (5, 3, 0),
+ "eight" => (8, 0, 20),
+ _ => (12, 0, 24),
+ };
+ for (k, v) in [
+ ("columns", json!(cols)),
+ ("rows", json!(rows)),
+ ("gutter", json!(gap)),
+ ("rowGutter", json!(0)),
+ ("width", Value::Null),
+ ("height", Value::Null),
+ ("margin", json!([0, 0, 0, 0])),
+ ("__columnsEnabled", json!(true)),
+ ("__rowsEnabled", json!(rows > 0)),
+ ("__marginEnabled", json!(true)),
+ ("centerColumns", json!(false)),
+ ] {
+ f.insert(k.into(), v);
+ }
+ }
+ _ => {}
+ }
+ }
+ ui.end_row();
+ ui.label(tl!("Target:"));
+ let mut target = f.get("target").and_then(Value::as_str).unwrap_or("document").to_string();
+ let mut options = vec![("document".to_string(), "Document")];
+ if !photocraft_engine::guide_layout::selected_artboards(&app.session).is_empty() {
+ options.push(("selectedArtboards".into(), "Selected Artboards"));
+ }
+ if widgets::dropdown(ui, "guide-target", &mut target, &options, 222.0) {
+ f.insert("target".into(), json!(target));
+ }
+ ui.end_row();
+ });
+ ui.add_space(10.0);
+ group(ui, |ui| {
+ ui.label(tl!("Color"));
+ ui.horizontal(|ui| {
+ ui.label(tl!("Color:"));
+ let mut color = f.get("color").and_then(Value::as_str).unwrap_or("#4affff").to_string();
+ let mut colors: Vec<(String, &str)> = COLORS.iter().map(|(v, l)| (v.to_string(), *l)).collect();
+ if !COLORS.iter().any(|(v, _)| *v == color) {
+ colors.push((color.clone(), "Custom"));
+ }
+ if widgets::dropdown(ui, "guide-color", &mut color, &colors, 174.0) {
+ f.insert("color".into(), json!(color));
+ }
+ let shown = crate::rulers::parse_guide_color(&color).unwrap_or(Tokens::get(ui.ctx()).accent);
+ if widgets::color_swatch_button(ui, shown, tl!("Guide color")).clicked() {
+ crate::color_picker_ui::request(f, tl!("Guide color"));
+ }
+ });
+ });
+ ui.add_space(10.0);
+ ui.horizontal_top(|ui| {
+ axis(ui, f, false);
+ ui.add_space(4.0);
+ axis(ui, f, true);
+ });
+ ui.add_space(10.0);
+ group(ui, |ui| {
+ let enabled = check(ui, f, "__marginEnabled", tl!("Margin"), true);
+ let mut margins = f.get("margin").and_then(Value::as_array).cloned().unwrap_or_else(|| vec![json!(0); 4]);
+ ui.add_space(5.0);
+ ui.add_enabled_ui(enabled, |ui| {
+ ui.horizontal(|ui| {
+ for (value, label) in margins.iter_mut().zip([tl!("Top:"), tl!("Left:"), tl!("Bottom:"), tl!("Right:")]) {
+ ui.vertical(|ui| {
+ ui.label(label);
+ let mut n = value.as_f64().unwrap_or(0.0) as f32;
+ if widgets::value_field(ui, &mut n, 0.0..=300_000.0, "px", 64.0).changed() {
+ *value = json!(n);
+ }
+ });
+ }
+ });
+ });
+ f.insert("margin".into(), Value::Array(margins));
+ });
+ ui.add_space(8.0);
+ check(ui, f, "centerColumns", tl!("Center Columns"), false);
+ check(ui, f, "clearExisting", tl!("Clear Existing Guides"), false);
+ // A typed edit makes a named preset custom; changing target/colour/preview does not.
+ if ["columns", "rows", "width", "height", "gutter", "rowGutter", "margin", "centerColumns", "__columnsEnabled", "__rowsEnabled", "__marginEnabled"]
+ .iter()
+ .any(|k| before.get(*k) != f.get(*k))
+ && before.get("__preset") == f.get("__preset")
+ {
+ f.insert("__preset".into(), json!("custom"));
+ }
+}
+
+/// Own the action rail as well as the body, so OK/Cancel/Preview follow Photoshop's arrangement.
+pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>, interactive: bool) -> Option<bool> {
+ let before = (params(f), on(f, "__preview", true), f.get("color").cloned());
+ let mut outcome = None;
+ ui.horizontal_top(|ui| {
+ ui.vertical(|ui| {
+ main_fields(app, ui, f);
+ });
+ ui.add_space(12.0);
+ ui.vertical(|ui| {
+ let valid = validate(app, f).is_ok();
+ if ui.add_enabled_ui(valid, |ui| widgets::primary_button(ui, tl!("OK"), 96.0)).inner.clicked() {
+ outcome = Some(true);
+ }
+ ui.add_space(4.0);
+ if widgets::secondary_button(ui, tl!("Cancel"), 96.0).clicked() {
+ outcome = Some(false);
+ }
+ ui.add_space(6.0);
+ check(ui, f, "__preview", tl!("Preview"), true);
+ });
+ });
+ match calculate(app, f) {
+ Ok(guides) => {
+ f.insert("__previewGuides".into(), json!(guides));
+ f.insert("__previewParams".into(), params(f));
+ f.insert("__previewSource".into(), source(app));
+ }
+ Err(error) => {
+ ui.colored_label(Tokens::get(ui.ctx()).text_dim, tl!("Invalid guide layout")).on_hover_text(error);
+ }
+ }
+ if outcome.is_none() && interactive && validate(app, f).is_ok() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
+ outcome = Some(true);
+ }
+ // The canvas paints before the dialog. Schedule the frame that displays this draft edit.
+ if before != (params(f), on(f, "__preview", true), f.get("color").cloned()) {
+ ui.ctx().request_repaint();
+ }
+ outcome
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/ui-egui/src/guide_layout_ui/tests.rs b/crates/ui-egui/src/guide_layout_ui/tests.rs
new file mode 100644
index 000000000..914a4a74b
--- /dev/null
+++ b/crates/ui-egui/src/guide_layout_ui/tests.rs
@@ -0,0 +1,222 @@
+use super::*;
+
+#[test]
+fn tab_includes_optional_sizes_and_shift_tab_selects_their_text() {
+ let mut app = app();
+ let id = open(&mut app);
+ let f = &mut app.ui.dialog_mut(id).unwrap().fields;
+ f.insert("columns".into(), json!(5));
+ f.insert("rows".into(), json!(3));
+ f.insert("width".into(), json!(100));
+ f.insert("height".into(), json!(80));
+ let mut h = harness(app);
+ h.run_steps(3);
+ let original = h.state().session.active().unwrap().doc.guides.clone();
+ for text in ["4", "120", "12", "2", "90"] {
+ h.key_press(egui::Key::Tab);
+ h.run_steps(2);
+ h.event(egui::Event::Text(text.into()));
+ h.run_steps(2);
+ }
+ let f = &h.state().ui.dialogs.first().unwrap().fields;
+ assert_eq!((f["columns"].as_u64(), f["rows"].as_u64()), (Some(4), Some(2)));
+ assert_eq!(params(f)["width"], 120.0);
+ assert_eq!(params(f)["height"], 90.0);
+ assert_eq!(f["gutter"], 12.0);
+ h.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::Tab);
+ h.run_steps(2);
+ h.event(egui::Event::Text("3".into()));
+ h.run_steps(2);
+ assert_eq!(h.state().ui.dialogs.first().unwrap().fields["rows"], 3);
+ assert_eq!(h.state().session.active().unwrap().doc.guides, original);
+}
+
+#[test]
+fn tab_skips_disabled_rows_and_margins() {
+ let mut app = app();
+ let id = open(&mut app);
+ let f = &mut app.ui.dialog_mut(id).unwrap().fields;
+ f.insert("columns".into(), json!(2));
+ f.insert("__rowsEnabled".into(), json!(false));
+ f.insert("__marginEnabled".into(), json!(false));
+ let mut h = harness(app);
+ h.run_steps(3);
+ for text in ["5", "100", "4", "6"] {
+ h.key_press(egui::Key::Tab);
+ h.run_steps(2);
+ h.event(egui::Event::Text(text.into()));
+ h.run_steps(2);
+ }
+ let f = &h.state().ui.dialogs.first().unwrap().fields;
+ assert_eq!(f["columns"], 6, "Tab wraps after column spacing, skipping disabled row and margin fields");
+ assert_eq!(params(f)["width"], 100.0);
+ assert_eq!(f["gutter"], 4.0);
+}
+
+fn harness(app: PhotocraftApp) -> egui_kittest::Harness<'static, PhotocraftApp> {
+ let mut initialized = false;
+ egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(
+ move |ui, app| {
+ if initialized {
+ crate::dialogs::show(app, ui.ctx());
+ } else {
+ PhotocraftApp::setup_context(ui.ctx(), Default::default());
+ initialized = true;
+ }
+ },
+ app,
+ )
+}
+
+fn app() -> PhotocraftApp {
+ let mut session = photocraft_engine::Session::new();
+ session.execute("file.new", json!({"width":1200,"height":800})).unwrap();
+ PhotocraftApp::new(session, crate::Services::default())
+}
+
+fn draw(app: &mut PhotocraftApp, id: u64) {
+ let mut f = app.ui.dialog_mut(id).unwrap().fields.clone();
+ let ctx = egui::Context::default();
+ PhotocraftApp::setup_context(&ctx, Default::default());
+ ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), ..Default::default() }, |ui| {
+ body(app, ui, &mut f, false);
+ })
+ .textures_delta
+ .clear();
+ app.ui.dialog_mut(id).unwrap().fields = f;
+}
+
+#[test]
+fn typing_previews_without_editing_and_cancel_restores_preferences_and_lines() {
+ let mut app = app();
+ app.run(COMMAND, json!({"margin":50})).unwrap();
+ let original = app.session.active().unwrap().doc.guides.clone();
+ let revision = app.session.active().unwrap().revision;
+ let color = app.session.prefs().guides_grid_and_slices.guide_color.clone();
+ let id = open(&mut app);
+ for (k, v) in [
+ ("columns", json!(5)),
+ ("rows", json!(3)),
+ ("gutter", json!(24)),
+ ("margin", json!([20, 40, 60, 80])),
+ ("color", json!("#ff00ff")),
+ ("clearExisting", json!(true)),
+ ] {
+ app.ui.dialog_mut(id).unwrap().fields.insert(k.into(), v);
+ }
+ let (pending, shown_color) = preview(&app, &app.session.active().unwrap().doc).unwrap();
+ assert_ne!(pending, original);
+ assert_eq!(shown_color, Color32::from_rgb(255, 0, 255));
+ assert_eq!(app.session.active().unwrap().revision, revision);
+ assert_eq!(app.session.prefs().guides_grid_and_slices.guide_color, color);
+ crate::dialogs::cancel(&mut app, id).unwrap();
+ assert!(preview(&app, &app.session.active().unwrap().doc).is_none());
+ assert_eq!(app.session.active().unwrap().doc.guides, original);
+ assert_eq!(app.session.prefs().guides_grid_and_slices.guide_color, color);
+}
+
+#[test]
+fn ok_matches_preview_and_is_one_undo_step() {
+ let mut app = app();
+ app.run(COMMAND, json!({"columns":2})).unwrap();
+ let original = app.session.active().unwrap().doc.guides.clone();
+ let id = open(&mut app);
+ for (k, v) in [
+ ("columns", json!(3)),
+ ("rows", json!(2)),
+ ("width", json!("100*2")),
+ ("height", json!(150)),
+ ("centerColumns", json!(true)),
+ ("clearExisting", json!(true)),
+ ("color", json!("#ff00ff")),
+ ] {
+ app.ui.dialog_mut(id).unwrap().fields.insert(k.into(), v);
+ }
+ let expected = preview(&app, &app.session.active().unwrap().doc).unwrap().0;
+ crate::dialogs::confirm(&mut app, id).unwrap();
+ assert_eq!(app.session.active().unwrap().doc.guides, expected);
+ assert_eq!(app.session.prefs().guides_grid_and_slices.guide_color, "#ff00ff");
+ assert!(preview(&app, &app.session.active().unwrap().doc).is_none());
+ app.run("edit.undo", json!({})).unwrap();
+ assert_eq!(app.session.active().unwrap().doc.guides, original);
+}
+
+#[test]
+fn preview_off_and_foreign_document_never_replace_guides() {
+ let mut app = app();
+ let id = open(&mut app);
+ app.ui.dialog_mut(id).unwrap().fields.insert("__preview".into(), json!(false));
+ assert!(preview(&app, &app.session.active().unwrap().doc).is_none());
+ app.ui.dialog_mut(id).unwrap().fields.insert("__preview".into(), json!(true));
+ app.run("file.new", json!({"width":50,"height":50})).unwrap();
+ assert!(preview(&app, &app.session.active().unwrap().doc).is_none());
+ assert!(crate::dialogs::confirm(&mut app, id).is_err());
+ assert!(app.ui.dialog_mut(id).is_some());
+}
+
+#[test]
+fn invalid_fields_keep_last_valid_preview_and_dialog_open() {
+ let mut app = app();
+ let id = open(&mut app);
+ draw(&mut app, id);
+ let expected = preview(&app, &app.session.active().unwrap().doc).unwrap().0;
+ app.ui.dialog_mut(id).unwrap().fields.insert("gutter".into(), json!(1000));
+ assert!(crate::dialogs::confirm(&mut app, id).is_err());
+ assert!(app.ui.dialog_mut(id).is_some());
+ assert_eq!(preview(&app, &app.session.active().unwrap().doc).unwrap().0, expected);
+ app.ui.dialog_mut(id).unwrap().fields.insert("gutter".into(), json!(20));
+ app.ui.dialog_mut(id).unwrap().fields.insert("color".into(), json!("invalid"));
+ assert!(crate::dialogs::confirm(&mut app, id).is_err());
+ assert!(app.ui.dialog_mut(id).is_some());
+}
+
+#[test]
+fn disabled_axes_preserve_values_and_do_not_validate_stale_inputs() {
+ let mut app = app();
+ let id = open(&mut app);
+ let f = &mut app.ui.dialog_mut(id).unwrap().fields;
+ for (k, v) in [("columns", json!(8)), ("width", json!("invalid")), ("gutter", json!(2000)), ("__columnsEnabled", json!(false)), ("rows", json!(3))] {
+ f.insert(k.into(), v);
+ }
+ let p = params(f);
+ assert_eq!(p["columns"], 0);
+ assert_eq!(p["width"], Value::Null);
+ assert_eq!(f["columns"], 8);
+ crate::dialogs::confirm(&mut app, id).unwrap();
+ assert!(app.session.active().unwrap().doc.guides.vertical.is_empty());
+ let reopened = open(&mut app);
+ let f = &app.ui.dialog_mut(reopened).unwrap().fields;
+ assert_eq!(f["columns"], 8);
+ assert_eq!(f["__columnsEnabled"], false);
+}
+
+#[test]
+fn parent_cancel_also_closes_guide_color_picker() {
+ let mut app = app();
+ let id = open(&mut app);
+ let child = crate::color_picker_ui::open_for_field(&mut app, "Color Picker", [0.0, 1.0, 1.0], id, "color");
+ assert!(crate::dialogs::confirm(&mut app, id).is_err());
+ crate::dialogs::cancel(&mut app, id).unwrap();
+ assert!(app.ui.dialog_mut(child).is_none());
+ assert!(app.ui.dialog_mut(id).is_none());
+}
+
+#[test]
+fn automation_opens_the_same_guide_layout_dialog() {
+ let mut app = app();
+ app.ui.view.guide_layout["target"] = json!("selectedArtboards");
+ let id = crate::dialogs::open_command_dialog(&mut app, COMMAND, "New Guide Layout");
+ assert!(owns(&app.ui.dialog_mut(id).unwrap().fields));
+ assert_eq!(app.ui.dialog_mut(id).unwrap().fields["target"], "document");
+ assert!(preview(&app, &app.session.active().unwrap().doc).is_some());
+}
+
+#[test]
+fn preview_cache_tracks_document_revision() {
+ let mut app = app();
+ let id = open(&mut app);
+ draw(&mut app, id);
+ assert!(!preview(&app, &app.session.active().unwrap().doc).unwrap().0.vertical.contains(&23.0));
+ app.run(COMMAND, json!({"margin":23})).unwrap();
+ assert!(preview(&app, &app.session.active().unwrap().doc).unwrap().0.vertical.contains(&23.0));
+}
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index 02e36d68a..f04b62e06 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -19,6 +19,25 @@
# (PhotoCraft, ArtCraft, OpenType, CMYK, Lab ...) stay in Latin letters; the trailing "…" of
# dialog commands is kept.
+# Guide layout dialog
+ Columns Sloupce
+ Rows Řádky
+ Number Počet
+ Margin Okraj
+ Top: Nahoře:
+ Left: Vlevo:
+ Bottom: Dole:
+ Right: Vpravo:
+ Target: Cíl:
+ Selected Artboards Vybraná kreslicí plátna
+ Center Columns Vystředit sloupce
+ Clear Existing Guides Odstranit stávající vodítka
+ Invalid guide layout Neplatné rozvržení vodítek
+ Leave empty for automatic size Pro automatickou velikost ponechte prázdné
+ 5 Columns, 3 Rows 5 sloupců, 3 řádky
+ 8 Columns 8 sloupců
+ 12 Columns 12 sloupců
+
File Soubor
Edit Úpravy
Image Obraz
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index d5fe68f51..e5180a8b3 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -15,6 +15,25 @@
# way. Product and technology names (PhotoCraft, ArtCraft, OpenType, CMYK, Lab ...) stay in Latin
# letters; the trailing "…" of dialog commands is kept. Plural rule: one|other (n != 1 -> other).
+# Guide layout dialog
+ Columns Spalten
+ Rows Zeilen
+ Number Anzahl
+ Margin Rand
+ Top: Oben:
+ Left: Links:
+ Bottom: Unten:
+ Right: Rechts:
+ Target: Ziel:
+ Selected Artboards Ausgewählte Zeichenflächen
+ Center Columns Spalten zentrieren
+ Clear Existing Guides Vorhandene Hilfslinien löschen
+ Invalid guide layout Ungültiges Hilfslinien-Layout
+ Leave empty for automatic size Für automatische Größe leer lassen
+ 5 Columns, 3 Rows 5 Spalten, 3 Zeilen
+ 8 Columns 8 Spalten
+ 12 Columns 12 Spalten
+
File Datei
Edit Bearbeiten
Image Bild
diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv
index 3b0c12a11..607740e67 100644
--- a/crates/ui-egui/src/i18n/el.tsv
+++ b/crates/ui-egui/src/i18n/el.tsv
@@ -2,6 +2,24 @@
# Columns separated by TAB: context, English source, Greek translation.
# Original translations based on general Greek graphics/computing terminology.
# Covers every source label the i18n coverage check lists.
+
+# Guide layout dialog
+ Rows Γραμμές
+ Number Πλήθος
+ Top: Επάνω:
+ Left: Αριστερά:
+ Bottom: Κάτω:
+ Right: Δεξιά:
+ Target: Στόχος:
+ Selected Artboards Επιλεγμένοι πίνακες γραφικών
+ Center Columns Κεντράρισμα στηλών
+ Clear Existing Guides Διαγραφή υπαρχόντων οδηγών
+ Invalid guide layout Μη έγκυρη διάταξη οδηγών
+ Leave empty for automatic size Αφήστε κενό για αυτόματο μέγεθος
+ 5 Columns, 3 Rows 5 στήλες, 3 γραμμές
+ 8 Columns 8 στήλες
+ 12 Columns 12 στήλες
+
File Αρχείο
Edit Επεξεργασία
Image Εικόνα
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index df6dfd2aa..4e0480bca 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -11,6 +11,26 @@
# resource, string table or product UI was consulted or copied; add entries the same way.
# Product and technology names (PhotoCraft, ArtCraft, OpenType, CMYK, Lab ...) stay in Latin
# letters; the trailing "…" of dialog commands is kept.
+
+# Guide layout dialog
+ Columns Columnas
+ Rows Filas
+ Number Número
+ Margin Margen
+ Top: Superior:
+ Left: Izquierda:
+ Bottom: Inferior:
+ Right: Derecha:
+ Target: Destino:
+ Selected Artboards Mesas de trabajo seleccionadas
+ Center Columns Centrar columnas
+ Clear Existing Guides Eliminar guías existentes
+ Invalid guide layout Disposición de guías no válida
+ Leave empty for automatic size Dejar vacío para el tamaño automático
+ 5 Columns, 3 Rows 5 columnas, 3 filas
+ 8 Columns 8 columnas
+ 12 Columns 12 columnas
+
File Archivo
Edit Edición
Image Imagen
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index 3dbc15e6c..e07163142 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -18,6 +18,25 @@
# « : ; ? ! » and "%", and inside guillemets « … ». Product and technology names (PhotoCraft,
# ArtCraft, OpenType, Lab ...) stay as they are; RGB/CMYK read RVB/CMJN; the trailing "…" of
# dialog commands is kept.
+
+# Guide layout dialog
+ Rows Lignes
+ Number Nombre
+ Margin Marge
+ Top: Haut :
+ Left: Gauche :
+ Bottom: Bas :
+ Right: Droite :
+ Target: Cible :
+ Selected Artboards Plans de travail sélectionnés
+ Center Columns Centrer les colonnes
+ Clear Existing Guides Effacer les repères existants
+ Invalid guide layout Disposition des repères non valide
+ Leave empty for automatic size Laisser vide pour une taille automatique
+ 5 Columns, 3 Rows 5 colonnes, 3 lignes
+ 8 Columns 8 colonnes
+ 12 Columns 12 colonnes
+
File Fichier
Edit Édition
Image Image
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index 6083c94dc..73c038e93 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -11,6 +11,25 @@
# resource, string table or product UI was consulted or copied; add entries the same way.
# Product and technology names (PhotoCraft, ArtCraft, OpenType, CMYK, Lab ...) stay in Latin
# letters; the trailing "…" of dialog commands is kept.
+
+# Guide layout dialog
+ Rows Baris
+ Number Jumlah
+ Margin Margin
+ Top: Atas:
+ Left: Kiri:
+ Bottom: Bawah:
+ Right: Kanan:
+ Target: Target:
+ Selected Artboards Artboard yang dipilih
+ Center Columns Pusatkan kolom
+ Clear Existing Guides Hapus panduan yang ada
+ Invalid guide layout Tata letak panduan tidak valid
+ Leave empty for automatic size Kosongkan untuk ukuran otomatis
+ 5 Columns, 3 Rows 5 kolom, 3 baris
+ 8 Columns 8 kolom
+ 12 Columns 12 kolom
+
File Berkas
Edit Edit
Image Gambar
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 4eeda8a3e..e1180f8cd 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -11,6 +11,26 @@
# resource, string table or product UI was consulted or copied; add entries the same way.
# Product and technology names (PhotoCraft, ArtCraft, OpenType, CMYK, Lab ...) stay in Latin
# letters; the trailing … of dialog commands is kept.
+
+# Guide layout dialog
+ Columns Colonne
+ Rows Righe
+ Number Numero
+ Margin Margine
+ Top: Alto:
+ Left: Sinistra:
+ Bottom: Basso:
+ Right: Destra:
+ Target: Destinazione:
+ Selected Artboards Tavole da disegno selezionate
+ Center Columns Centra colonne
+ Clear Existing Guides Elimina guide esistenti
+ Invalid guide layout Layout delle guide non valido
+ Leave empty for automatic size Lasciare vuoto per la dimensione automatica
+ 5 Columns, 3 Rows 5 colonne, 3 righe
+ 8 Columns 8 colonne
+ 12 Columns 12 colonne
+
File File
Edit Modifica
Image Immagine
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index c7777e64a..1cb135875 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -15,6 +15,23 @@
# Product and technology names (PhotoCraft, ArtCraft, OpenType, CMYK, Lab ...) stay in Latin
# letters; the trailing "…" of dialog commands is kept.
+# Guide layout dialog
+ Rows 行
+ Number 数
+ Top: 上:
+ Left: 左:
+ Bottom: 下:
+ Right: 右:
+ Target: 対象:
+ Selected Artboards 選択したアートボード
+ Center Columns 列を中央に配置
+ Clear Existing Guides 既存のガイドを削除
+ Invalid guide layout ガイドレイアウトが無効です
+ Leave empty for automatic size 自動サイズにするには空欄にします
+ 5 Columns, 3 Rows 5列、3行
+ 8 Columns 8列
+ 12 Columns 12列
+
File ファイル
Edit 編集
Image 画像
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index f6b1bee14..2f6347d6c 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -7,6 +7,24 @@
# Licensed MIT OR Apache-2.0. See LICENSE-translations.txt and ATTRIBUTION.md.
# Product names and technology names retain their spelling.
+# Guide layout dialog
+ Columns 열
+ Rows 행
+ Number 개수
+ Top: 위:
+ Left: 왼쪽:
+ Bottom: 아래:
+ Right: 오른쪽:
+ Target: 대상:
+ Selected Artboards 선택한 아트보드
+ Center Columns 열 가운데 정렬
+ Clear Existing Guides 기존 안내선 지우기
+ Invalid guide layout 잘못된 안내선 레이아웃
+ Leave empty for automatic size 자동 크기를 사용하려면 비워 두세요
+ 5 Columns, 3 Rows 5열, 3행
+ 8 Columns 8열
+ 12 Columns 12열
+
File 파일
Edit 편집
Image 이미지
diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv
index 8d1e1f6c6..713f935b4 100644
--- a/crates/ui-egui/src/i18n/nl.tsv
+++ b/crates/ui-egui/src/i18n/nl.tsv
@@ -8,6 +8,23 @@
# stay as they are; the trailing "…" of dialog commands is kept. UI text addresses the user
# informally ("je") and uses sentence case.
+# Guide layout dialog
+ Rows Rijen
+ Number Aantal
+ Top: Boven:
+ Left: Links:
+ Bottom: Onder:
+ Right: Rechts:
+ Target: Doel:
+ Selected Artboards Geselecteerde tekengebieden
+ Center Columns Kolommen centreren
+ Clear Existing Guides Bestaande hulplijnen wissen
+ Invalid guide layout Ongeldige hulplijnindeling
+ Leave empty for automatic size Leeg laten voor automatische grootte
+ 5 Columns, 3 Rows 5 kolommen, 3 rijen
+ 8 Columns 8 kolommen
+ 12 Columns 12 kolommen
+
File Bestand
Edit Bewerken
Image Afbeelding
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index 4e87d5b53..335b8d069 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -18,6 +18,23 @@
# Conventions: menus are nouns (Plik, Edycja, Obraz ...), commands are infinitives (Otwórz…,
# Zapisz jako…), sentence case as in the English source. Quotes: „…”.
+# Guide layout dialog
+ Rows Wiersze
+ Number Liczba
+ Top: Góra:
+ Left: Lewo:
+ Bottom: Dół:
+ Right: Prawo:
+ Target: Cel:
+ Selected Artboards Wybrane obszary kompozycji
+ Center Columns Wyśrodkuj kolumny
+ Clear Existing Guides Usuń istniejące linie pomocnicze
+ Invalid guide layout Nieprawidłowy układ linii pomocniczych
+ Leave empty for automatic size Pozostaw puste dla rozmiaru automatycznego
+ 5 Columns, 3 Rows 5 kolumn, 3 wiersze
+ 8 Columns 8 kolumn
+ 12 Columns 12 kolumn
+
File Plik
Edit Edycja
Image Obraz
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index 587069bd5..beea57d3c 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -15,6 +15,24 @@
# entries the same way. Product and technology names (PhotoCraft, ArtCraft, OpenType, CMYK, Lab ...)
# stay as they are; the trailing "…" of dialog commands is kept.
+# Guide layout dialog
+ Rows Linhas
+ Number Número
+ Margin Margem
+ Top: Superior:
+ Left: Esquerda:
+ Bottom: Inferior:
+ Right: Direita:
+ Target: Destino:
+ Selected Artboards Pranchetas selecionadas
+ Center Columns Centralizar colunas
+ Clear Existing Guides Limpar guias existentes
+ Invalid guide layout Layout de guias inválido
+ Leave empty for automatic size Deixe vazio para tamanho automático
+ 5 Columns, 3 Rows 5 colunas, 3 linhas
+ 8 Columns 8 colunas
+ 12 Columns 12 colunas
+
File Arquivo
Edit Editar
Image Imagem
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 0b950a69d..3ec3ce023 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -18,6 +18,25 @@
# the Russian typographic equivalent, with the space the source carries.
# Menus
+
+# Guide layout dialog
+ Rows Строки
+ Number Количество
+ Margin Поля
+ Top: Сверху:
+ Left: Слева:
+ Bottom: Снизу:
+ Right: Справа:
+ Target: Цель:
+ Selected Artboards Выбранные монтажные области
+ Center Columns Центрировать столбцы
+ Clear Existing Guides Удалить существующие направляющие
+ Invalid guide layout Недопустимый макет направляющих
+ Leave empty for automatic size Оставьте пустым для автоматического размера
+ 5 Columns, 3 Rows 5 столбцов, 3 строки
+ 8 Columns 8 столбцов
+ 12 Columns 12 столбцов
+
File Файл
Edit Редактирование
Image Изображение
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index 66ea4366c..e15aee93a 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -9,6 +9,24 @@
# Licensed MIT OR Apache-2.0. See LICENSE-translations.txt and ATTRIBUTION.md.
# Menus
+
+# Guide layout dialog
+ Rows Рядки
+ Number Кількість
+ Top: Зверху:
+ Left: Ліворуч:
+ Bottom: Знизу:
+ Right: Праворуч:
+ Target: Ціль:
+ Selected Artboards Вибрані монтажні області
+ Center Columns Центрувати стовпці
+ Clear Existing Guides Видалити наявні напрямні
+ Invalid guide layout Неприпустимий макет напрямних
+ Leave empty for automatic size Залиште порожнім для автоматичного розміру
+ 5 Columns, 3 Rows 5 стовпців, 3 рядки
+ 8 Columns 8 стовпців
+ 12 Columns 12 стовпців
+
File Файл
Edit Редагування
Image Зображення
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 1c36a77ac..362c3c9d8 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -11,6 +11,25 @@
# Licensed MIT OR Apache-2.0, as the code.
# Product and technology names retain their spelling. See docs/localization-zh-hans.md.
+# Guide layout dialog
+ Columns 列
+ Rows 行
+ Number 数量
+ Margin 边距
+ Top: 上:
+ Left: 左:
+ Bottom: 下:
+ Right: 右:
+ Target: 目标:
+ Selected Artboards 所选画板
+ Center Columns 列居中
+ Clear Existing Guides 清除现有参考线
+ Invalid guide layout 参考线布局无效
+ Leave empty for automatic size 留空以自动设置大小
+ 5 Columns, 3 Rows 5列,3行
+ 8 Columns 8列
+ 12 Columns 12列
+
File 文件
Edit 编辑
Image 图像
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index cba84fda3..e278e4550 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -19,6 +19,25 @@
# kept. Full-width punctuation (,。:) inside sentences; half-width parentheses and the " · "
# separators as in the English.
+# Guide layout dialog
+ Columns 欄
+ Rows 列
+ Number 數量
+ Margin 邊界
+ Top: 上:
+ Left: 左:
+ Bottom: 下:
+ Right: 右:
+ Target: 目標:
+ Selected Artboards 選取的工作區域
+ Center Columns 欄置中
+ Clear Existing Guides 清除現有參考線
+ Invalid guide layout 參考線版面配置無效
+ Leave empty for automatic size 留白以自動設定大小
+ 5 Columns, 3 Rows 5欄,3列
+ 8 Columns 8欄
+ 12 Columns 12欄
+
File 檔案
Edit 編輯
Image 影像
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 406b9b122..d60e774f7 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -81,6 +81,7 @@ pub mod gallery_ui;
pub mod gpu_canvas;
pub mod gpu_status;
pub mod gradient_ui;
+pub mod guide_layout_ui;
pub mod hold_keys;
pub mod i18n;
mod icon_data;
diff --git a/crates/ui-egui/src/rulers.rs b/crates/ui-egui/src/rulers.rs
index dde9c09ab..eb36839d6 100644
--- a/crates/ui-egui/src/rulers.rs
+++ b/crates/ui-egui/src/rulers.rs
@@ -143,11 +143,25 @@ pub fn draw_grid(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, d
}
}
+pub(crate) fn parse_guide_color(value: &str) -> Option<Color32> {
+ let value = value.strip_prefix('#')?;
+ if value.len() != 6 {
+ return None;
+ }
+ let r = u8::from_str_radix(value.get(0..2)?, 16).ok()?;
+ let g = u8::from_str_radix(value.get(2..4)?, 16).ok()?;
+ let b = u8::from_str_radix(value.get(4..6)?, 16).ok()?;
+ Some(Color32::from_rgb(r, g, b))
+}
+
pub fn draw_guides(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, doc: &Document) {
let clip = painter.clip_rect();
let drag = app.guide_drag;
let g = &app.session.prefs().guides_grid_and_slices;
- let (guide, style) = (pref_color(&g.guide_color, Color32::from_rgb(74, 255, 255)), g.guide_style);
+ let preview = crate::guide_layout_ui::preview(app, doc);
+ let guides = preview.as_ref().map(|(guides, _)| guides).unwrap_or(&doc.guides);
+ let (guide, style) =
+ (preview.as_ref().map(|(_, color)| *color).unwrap_or_else(|| pref_color(&g.guide_color, Color32::from_rgb(74, 255, 255))), g.guide_style);
let line = |vertical: bool, pos: f64, color: Color32| {
if vertical {
let x = xf.to_screen(pos as f32, 0.0).x;
@@ -157,8 +171,8 @@ pub fn draw_guides(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform,
styled_line(painter, pos2(clip.left(), y), pos2(clip.right(), y), Stroke::new(1.0, color), style);
}
};
- if app.ui.extras.guides {
- for (vertical, list) in [(true, &doc.guides.vertical), (false, &doc.guides.horizontal)] {
+ if app.ui.extras.guides || preview.is_some() {
+ for (vertical, list) in [(true, &guides.vertical), (false, &guides.horizontal)] {
for (i, p) in list.iter().enumerate() {
if drag.is_some_and(|d| d.vertical == vertical && d.index == Some(i)) {
continue;
diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rs
index 48500e145..435df87ec 100644
--- a/crates/ui-egui/src/view_cmds.rs
+++ b/crates/ui-egui/src/view_cmds.rs
@@ -1003,10 +1003,7 @@ fn front(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<Val
json!({"from": "any", "to": "rgb"}),
json!({"from": ["any", "rgb", "grayscale", "cmyk", "lab", "indexed", "bitmap", "duotone", "multichannel"], "to": ["rgb", "grayscale", "cmyk", "lab"]}),
),
- "view.newGuideLayout" => {
- let fields = app.ui.view.guide_layout.clone();
- dialog(app, fields, json!({}))
- }
+ "view.newGuideLayout" => Some(Ok(json!({"dialog": crate::guide_layout_ui::open(app)}))),
"type.warpText" => Some(Ok(json!({"dialog": crate::dialogs::open_command_dialog(app, id, label)}))),
"file.export.layersToFiles" => {
let (_, _, name) = doc?;
diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs
index 500ff3526..ccd7877e1 100644
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@ -479,7 +479,9 @@ fn number_edit(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive<f32
ui.memory_mut(|m| m.request_focus(id));
}
// Tab in a dialog goes from one of these to the next (field_tab.rs).
- crate::field_tab::register(&ctx, id);
+ if ui.is_enabled() {
+ crate::field_tab::register(&ctx, id);
+ }
let held = id.with("arithmetic");
let math = ui.memory(|m| m.has_focus(id)) && ui.data(|d| d.get_temp(held)).unwrap_or(false);
ui.data_mut(|d| d.insert_temp(held, math));