Skip to content

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

fix(ui): keep the Type tool's path pointer in step with what a click does

PanPDX566a501bb8f9
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index e64665d10..62240d3d9 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -3898,10 +3898,12 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
draw_clone_preview(app, &painter, &xf, xf.to_doc(p), output);
}
// The Type tool over a path shows Photoshop's area-type or type-on-a-path pointer (#218).
- // Not while a type edit is open: a click then commits rather than starting new type.
+ // Not while a type edit is open (a click then commits rather than starting new type),
+ // nor over type a click would edit.
let type_path = if matches!(tool, Tool::Type | Tool::VerticalType) && app.ui.text_edit.is_none() {
let [x, y] = xf.to_doc(p);
- crate::type_tool::path_target(app, x, y)
+ let shift = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)).shift;
+ crate::type_tool::hover_path_target(app, x, y, shift)
} else {
None
};
diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs
index 684738e90..30d03d6aa 100644
--- a/crates/ui-egui/src/type_tool.rs
+++ b/crates/ui-egui/src/type_tool.rs
@@ -32,17 +32,18 @@ fn byte_of(text: &str, ci: usize) -> usize {
/// Layout of a type layer (cached per document revision) and its text → document transform.
pub fn layout(app: &mut PhotocraftApp, id: LayerId) -> Option<(Arc<TextLayout>, Affine, String)> {
+ let dragged = crate::type_transform::current_transform(app, id);
+ // Borrows the document in place (no clone): the canvas hover hit-tests type every frame.
let st = app.session.active()?;
- let (doc, rev) = (st.doc.clone(), st.revision);
- let t = text_layer(&doc, id)?;
- let transform = crate::type_transform::current_transform(app, id).unwrap_or(t.transform);
- let key = (doc.id.0, rev, id.0);
+ let t = text_layer(&st.doc, id)?;
+ let transform = dragged.unwrap_or(t.transform);
+ let key = (st.doc.id.0, st.revision, id.0);
if let Some((k, l)) = &app.type_layout
&& *k == key
{
return Some((l.clone(), transform, t.text.clone()));
}
- let l = Arc::new(photocraft_text::shared().lock().ok()?.layout(t, doc.resolution_dpi));
+ let l = Arc::new(photocraft_text::shared().lock().ok()?.layout(t, st.doc.resolution_dpi));
app.type_layout = Some((key, l.clone()));
Some((l, transform, t.text.clone()))
}
@@ -53,23 +54,25 @@ fn to_text(aff: &Affine, x: f64, y: f64) -> (f32, f32) {
}
/// Topmost shown type layer (it and every group around it visible, #4320) whose laid-out text
-/// contains the document point.
+/// contains the document point. The press and the canvas hover (`hover_path_target`) share it, so
+/// the pointer never promises a path click that the press would turn into editing this layer.
fn hit_layer(app: &mut PhotocraftApp, x: f64, y: f64) -> Option<LayerId> {
- let doc = app.session.active()?.doc.clone();
let slop = 6.0 / app.point_zoom().max(0.01);
// A Type Mask session's text is a hidden layer; it is still the text being edited.
let editing = app.ui.text_edit.as_ref().filter(|ed| ed.mask).map(|ed| LayerId(ed.layer));
- let mut ids: Vec<LayerId> = doc
- .walk()
- .into_iter()
- .filter(|(path, _, l)| matches!(l.content, LayerContent::Text(_)) && (editing == Some(l.id) || doc.shown_at(path)))
- .map(|(_, _, l)| l.id)
- .collect();
+ let mut ids: Vec<LayerId> = {
+ let doc = &app.session.active()?.doc;
+ doc.walk()
+ .into_iter()
+ .filter(|(path, _, l)| matches!(l.content, LayerContent::Text(_)) && (editing == Some(l.id) || doc.shown_at(path)))
+ .map(|(_, _, l)| l.id)
+ .collect()
+ };
ids.reverse(); // walk() is bottom-up; hit the topmost first
ids.into_iter().find(|id| {
// The pixels shown count too: a PSD's type keeps Photoshop's rendering until edited,
// which can sit off our layout when fonts are substituted (#123).
- let shown = text_layer(&doc, *id).and_then(|t| t.cache.as_ref()).map(|c| c.content_bounds()).is_some_and(|r| {
+ let shown = app.session.active().and_then(|st| text_layer(&st.doc, *id)).and_then(|t| t.cache.as_ref()).map(|c| c.content_bounds()).is_some_and(|r| {
let s = f64::from(slop);
!r.is_empty() && x >= f64::from(r.x0) - s && x <= f64::from(r.x1) + s && y >= f64::from(r.y0) - s && y <= f64::from(r.y1) + s
});
@@ -329,20 +332,40 @@ pub(crate) fn path_target(app: &PhotocraftApp, x: f64, y: f64) -> Option<PathCli
Some((id, p)) => (Some(id), p),
None => (None, app.session.active()?.doc.work_path.clone()?),
};
+ // The canvas hover runs this every frame and `hit` samples every segment, so a path with more
+ // anchors than this is not a click target (the click and the pointer agree: plain point
+ // text). 4096 anchors is far beyond hand-drawn paths and shapes yet keeps a frame cheap.
+ const MAX_TARGET_KNOTS: usize = 4096;
+ if path.subpaths.iter().map(|s| s.knots.len()).fold(0usize, usize::saturating_add) > MAX_TARGET_KNOTS {
+ return None;
+ }
let tol = 4.0 / app.point_zoom().max(0.01) as f64;
let on_path = |sp: usize, k: usize, t: f64| {
- let sub = path.subpaths.get(sp)?;
+ // Type on a path needs a segment to run along (`type.attachToPath` rejects one anchor).
+ let sub = path.subpaths.get(sp).filter(|s| s.knots.len() >= 2)?;
Some(PathClick::OnPath { shape, subpath: sp, start: arc_length_to(sub, k, t) })
};
- match hit(&path, Point::new(x, y), tol, &[]) {
- Some(Hit::Segment([sp, k], t)) => return on_path(sp, k, t),
- Some(Hit::Anchor([sp, k])) => return on_path(sp, k, 0.0),
- _ => {}
+ let outline = match hit(&path, Point::new(x, y), tol, &[]) {
+ Some(Hit::Segment([sp, k], t)) => on_path(sp, k, t),
+ Some(Hit::Anchor([sp, k])) => on_path(sp, k, 0.0),
+ _ => None,
+ };
+ if outline.is_some() {
+ return outline;
}
let area = photocraft_text::area::AreaShape::new(&path, false)?;
area.contains(x as f32, y as f32).then_some(PathClick::Area { shape })
}
+/// What the Type tool's pointer over document `(x, y)` shows (#218): the path click a press there
+/// would make, unless the press edits the type layer under it instead (`pointer_down`: an
+/// unshifted press on shown type), where Photoshop keeps the plain I-beam. The type hit is only
+/// tested over a path, so a hover elsewhere lays out nothing.
+pub(crate) fn hover_path_target(app: &mut PhotocraftApp, x: f64, y: f64, shift: bool) -> Option<PathClick> {
+ let target = path_target(app, x, y)?;
+ (shift || hit_layer(app, x, y).is_none()).then_some(target)
+}
+
/// Pointer up. `rect` is the dragged box (document px) when no edit session consumed the press.
pub fn pointer_up(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) {
if let Some(e) = app.ui.text_edit.as_mut() {
diff --git a/crates/ui-egui/src/type_tool_tests.rs b/crates/ui-egui/src/type_tool_tests.rs
index 98a100278..99c3a4864 100644
--- a/crates/ui-egui/src/type_tool_tests.rs
+++ b/crates/ui-egui/src/type_tool_tests.rs
@@ -2102,8 +2102,10 @@ fn clicking_on_a_path_outline_starts_type_on_the_path_where_clicked() {
let Some(PathClick::OnPath { start: right, .. }) = path_target(&app, 600.0, 350.0) else { panic!("on the outline") };
let d = (right - start).rem_euclid(1105.0);
assert!((d - 276.0).abs() < 15.0 || (d - 829.0).abs() < 15.0, "{start} → {right}");
+ let before = app.session.active().unwrap().history.entries().len();
click_at(&mut app, 400.0, 500.0);
let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer);
+ assert_eq!(app.session.active().unwrap().history.entries().len(), before + 1, "create + attach is one step");
assert!(
matches!(text_layer(&app.session.active().unwrap().doc, id).unwrap().shape, TextShape::Path { start: s, .. } if (f64::from(s) - start).abs() < 0.01)
);
@@ -2138,3 +2140,55 @@ fn type_mask_tools_ignore_paths() {
let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer);
assert_eq!(text_layer(&app.session.active().unwrap().doc, id).unwrap().shape, photocraft_doc::text::TextShape::Point);
}
+
+#[test]
+fn a_one_anchor_work_path_is_not_a_path_target() {
+ // `type.attachToPath` needs a segment, so the pointer must not promise type on this path.
+ let mut app = new_app();
+ std::sync::Arc::make_mut(&mut app.session.active_mut().unwrap().doc).work_path =
+ Some(photocraft_doc::Path::new(vec![photocraft_doc::Subpath::polyline(&[(500.0, 400.0)])]));
+ assert!(path_target(&app, 500.0, 400.0).is_none());
+ click_at(&mut app, 500.0, 400.0);
+ let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer);
+ assert_eq!(text_layer(&app.session.active().unwrap().doc, id).unwrap().shape, photocraft_doc::text::TextShape::Point);
+}
+
+#[test]
+fn over_existing_type_on_a_shape_the_pointer_is_the_plain_i_beam_and_a_click_edits_it() {
+ let mut app = new_app();
+ let text = app.run("type.create", json!({"text": "Hello", "x": 330, "y": 370, "size": 36})).unwrap()["layer"].as_u64().unwrap();
+ let shape = ellipse_layer(&mut app); // the shape layer is active, so its path is the target
+ let layers = app.session.active().unwrap().doc.walk().len();
+ let mut h = harness(1.0, app);
+ let on_text = glyph(&mut h, LayerId(text), 1, 0.5);
+ let [dx, dy] = xf(h.state()).to_doc(on_text);
+ assert!(matches!(path_target(h.state(), dx, dy), Some(PathClick::Area { shape: Some(s) }) if s == shape), "the text sits inside the shape");
+ h.hover_at(on_text);
+ h.run_steps(2);
+ assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Text, "a click here edits the type, so the plain I-beam");
+ // Inside the shape but away from the type: the area-type pointer (drawn, not the OS I-beam).
+ let inside = xf(h.state()).to_screen(400.0, 250.0);
+ h.hover_at(inside);
+ h.run_steps(2);
+ assert_ne!(h.output().platform_output.cursor_icon, egui::CursorIcon::Text, "area-type pointer inside the shape");
+ click(&mut h, on_text);
+ let app = h.state();
+ assert_eq!(app.ui.text_edit.as_ref().expect("editing").layer, text, "the click edits the existing layer");
+ assert_eq!(app.session.active().unwrap().doc.walk().len(), layers, "no new layer");
+ assert_eq!(text_layer(&app.session.active().unwrap().doc, LayerId(text)).unwrap().shape, photocraft_doc::text::TextShape::Point);
+}
+
+#[test]
+fn paths_with_too_many_anchors_are_not_hover_targets() {
+ // The hover hit-tests every segment each frame, so huge paths are skipped (click and pointer alike).
+ let ring = |n: usize| -> Vec<(f64, f64)> {
+ (0..n).map(|i| i as f64 / n as f64 * std::f64::consts::TAU).map(|a| (500.0 + 200.0 * a.cos(), 400.0 + 200.0 * a.sin())).collect()
+ };
+ let mut app = new_app();
+ std::sync::Arc::make_mut(&mut app.session.active_mut().unwrap().doc).work_path =
+ Some(photocraft_doc::Path::new(vec![photocraft_doc::Subpath::polygon(&ring(4000))]));
+ assert!(matches!(path_target(&app, 500.0, 400.0), Some(PathClick::Area { shape: None })));
+ std::sync::Arc::make_mut(&mut app.session.active_mut().unwrap().doc).work_path =
+ Some(photocraft_doc::Path::new(vec![photocraft_doc::Subpath::polygon(&ring(5000))]));
+ assert!(path_target(&app, 500.0, 400.0).is_none());
+}