PhotoCraft: An open-source, photo editor written by scratch in pure Rust
feat(ui): Type tool click inside or on a path starts area or path type
PanPDX94c48b63b700
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 391ad464f..e64665d10 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -3897,6 +3897,14 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:if !resizing && !alt && !app.ui.shell.sticky_alt {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.+ 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)+ } else {+ None+ };let icon = match tool {// Resizing the brush: the circle stays where the drag began (`brush_resize`).t if resizing && crate::brush_resize::applies(t) => egui::CursorIcon::None,@@ -4022,6 +4030,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:Tool::Hand => crate::tool_cursor::hand(ui.ctx(), false),Tool::RotateView => crate::rotate_view::cursor(response.dragged()),Tool::Zoom => crate::tool_cursor::zoom(ui.ctx(), zoom_out(alt)),+ Tool::Type | Tool::VerticalType if type_path.is_some() => match type_path {+ Some(crate::type_tool::PathClick::Area { .. }) => crate::tool_cursor::area_type(&painter, p),+ _ => crate::tool_cursor::path_type(&painter, p),+ },Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => egui::CursorIcon::Text,Tool::MagneticLasso => crate::magnetic_lasso_ui::cursor(app, &painter, p, xf.zoom),Tool::RedEye => {diff --git a/crates/ui-egui/src/tool_cursor.rs b/crates/ui-egui/src/tool_cursor.rsindex 8b67b96d6..f53d5b755 100644--- a/crates/ui-egui/src/tool_cursor.rs+++ b/crates/ui-egui/src/tool_cursor.rs@@ -92,6 +92,43 @@ fn close_ring() -> Vec<Vec2> {(0..16).map(|i| (i as f32 / 16.0 * std::f32::consts::TAU, vec2(9.0, 9.0))).map(|(a, c)| c + vec2(a.cos(), a.sin()) * 3.5).collect()}+/// Closed outline of an I-beam, centred on the hotspot.+fn i_beam() -> Vec<Vec2> {+ [(-3.0, -8.0), (3.0, -8.0), (3.0, -7.0), (0.5, -7.0), (0.5, 7.0), (3.0, 7.0), (3.0, 8.0), (-3.0, 8.0), (-3.0, 7.0), (-0.5, 7.0), (-0.5, -7.0), (-3.0, -7.0)]+ .into_iter()+ .map(|(x, y)| vec2(x, y))+ .collect()+}++/// A dot (a tiny closed square) at `c`.+fn dot(c: Vec2) -> Vec<Vec2> {+ vec![c + vec2(-0.75, -0.75), c + vec2(0.75, -0.75), c + vec2(0.75, 0.75), c + vec2(-0.75, 0.75)]+}++/// Photoshop's area-type pointer (#218): the I-beam inside a dotted ellipse.+pub(crate) fn area_type_rings() -> Vec<Vec<Vec2>> {+ let mut rings = vec![i_beam()];+ rings.extend((0..12).map(|i| i as f32 / 12.0 * std::f32::consts::TAU).map(|a| dot(vec2(a.cos() * 8.0, a.sin() * 10.5))));+ rings+}++/// Photoshop's type-on-a-path pointer (#218): the I-beam crossed by a dotted wave.+pub(crate) fn path_type_rings() -> Vec<Vec<Vec2>> {+ let mut rings = vec![i_beam()];+ rings.extend((0..9).map(|i| -10.0 + i as f32 * 2.5).map(|x| dot(vec2(x, 4.0 + (x * 0.4).sin() * 2.0))));+ rings+}++/// The Type tool over the inside of a closed path: a click starts area type there.+pub(crate) fn area_type(painter: &Painter, at: Pos2) -> CursorIcon {+ outline(painter, at, area_type_rings(), false)+}++/// The Type tool over a path's outline: a click starts type on the path there.+pub(crate) fn path_type(painter: &Painter, at: Pos2) -> CursorIcon {+ outline(painter, at, path_type_rings(), false)+}+/// Can this pass show an OS cursor bitmap? eframe's immediate viewports and its web integration/// don't upload cursor images; every desktop root viewport does (winit custom cursors). Wayland at/// any scale but 1 doesn't either: winit sizes the bitmap there with a `wp_viewport` destinationdiff --git a/crates/ui-egui/src/tool_cursor/tests.rs b/crates/ui-egui/src/tool_cursor/tests.rsindex d68be241f..b15774147 100644--- a/crates/ui-egui/src/tool_cursor/tests.rs+++ b/crates/ui-egui/src/tool_cursor/tests.rs@@ -515,3 +515,13 @@ fn resize_follows_the_view() {assert_eq!(got, want, "view turned {rotation}°, flip {flip}");}}++#[test]+fn type_path_cursors_are_small_and_centred() {+ for rings in [super::area_type_rings(), super::path_type_rings()] {+ assert!(rings.len() > 3);+ for v in rings.iter().flatten() {+ assert!(v.x.abs() <= 12.0 && v.y.abs() <= 12.0, "{v:?}");+ }+ }+}diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rsindex d73bb2e2c..684738e90 100644--- a/crates/ui-egui/src/type_tool.rs+++ b/crates/ui-egui/src/type_tool.rs@@ -296,6 +296,53 @@ pub fn pointer_move(app: &mut PhotocraftApp, x: f64, y: f64) {}}+/// What a Type tool click on a path does, like Photoshop: inside a closed path, area type;+/// on a path's outline, type on the path from that point.+#[derive(Clone, Debug, PartialEq)]+pub(crate) enum PathClick {+ Area { shape: Option<u64> },+ OnPath { shape: Option<u64>, subpath: usize, start: f64 },+}++/// Arc length (px) along `sub` from its first anchor to segment `seg` at curve parameter `t`.+fn arc_length_to(sub: &photocraft_doc::Subpath, seg: usize, t: f64) -> f64 {+ const PIECES: usize = 32;+ let eval = photocraft_vector::edit::eval;+ let length = |s: &[Point; 4], upto: f64| {+ (1..=PIECES)+ .fold((0.0, eval(s, 0.0)), |(len, prev), j| {+ let q = eval(s, upto * j as f64 / PIECES as f64);+ (len + (q.x - prev.x).hypot(q.y - prev.y), q)+ })+ .0+ };+ let segs = sub.segments();+ let whole: f64 = segs.iter().take(seg).map(|s| length(s, 1.0)).sum();+ whole + segs.get(seg).map_or(0.0, |s| length(s, t.clamp(0.0, 1.0)))+}++/// The path a Type tool click at document `(x, y)` would use: the active shape layer's path,+/// else the work path (the path Photoshop shows), within 4 screen px of its outline or inside it.+pub(crate) fn path_target(app: &PhotocraftApp, x: f64, y: f64) -> Option<PathClick> {+ use photocraft_vector::edit::{Hit, hit};+ let (shape, path) = match crate::vector_ui::active_shape_path(app) {+ Some((id, p)) => (Some(id), p),+ None => (None, app.session.active()?.doc.work_path.clone()?),+ };+ 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)?;+ 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 area = photocraft_text::area::AreaShape::new(&path, false)?;+ area.contains(x as f32, y as f32).then_some(PathClick::Area { shape })+}+/// 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() {@@ -307,6 +354,9 @@ pub fn pointer_up(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) {let min = 4.0 / app.point_zoom().max(0.01) as f64;let o = app.ui.tool_options.clone();let mask = app.ui.tool.is_type_mask();+ // A click (not a drag) with the Type tool on a path: area type inside a closed path, type+ // on the path on its outline. The Type Mask tools ignore paths.+ let target = if !mask && !(w >= min && h >= min) { path_target(app, start[0], start[1]) } else { None };// Preferences ▸ Type: "Fill new type layers with placeholder text" (on by default). The Type// Mask tools start empty, as Photoshop's do.let text = if !mask && app.session.prefs().type_.fill_new_type_layers_with_placeholder { PLACEHOLDER } else { "" };@@ -330,6 +380,15 @@ pub fn pointer_up(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) {if let Ok(v) = app.run("type.create", p)&& let Some(id) = v.get("layer").and_then(serde_json::Value::as_u64){+ match &target {+ Some(PathClick::Area { shape }) => {+ let _ = app.run("type.fillPath", json!({"layer": id, "shape": shape, "coalesce": key}));+ }+ Some(PathClick::OnPath { shape, subpath, start }) => {+ let _ = app.run("type.attachToPath", json!({"layer": id, "shape": shape, "subpath": subpath, "start": start, "coalesce": key}));+ }+ None => {}+ }if o.type_aa != "sharp" {let _ = app.run("type.edit", json!({"layer": id, "antialias": o.type_aa, "coalesce": key}));}@@ -1043,6 +1102,17 @@ pub fn draw_overlay(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewX}}}+ // Area type: the outline of the shape it wraps inside.+ Some(photocraft_doc::text::TextShape::Area { path }) => {+ if !has_transform {+ for poly in photocraft_vector::flatten::flatten_path(&path, 0.5) {+ let pts: Vec<Pos2> = poly.pts.iter().map(|&(x, y)| scr_t(x as f32, y as f32)).collect();+ if pts.len() >= 2 {+ painter.add(egui::Shape::closed_line(pts, frame));+ }+ }+ }+ }_ => {for ln in &l.lines {// Horizontal: just under the baseline; vertical: the column's centre line.diff --git a/crates/ui-egui/src/type_tool_tests.rs b/crates/ui-egui/src/type_tool_tests.rsindex f56829c6d..98a100278 100644--- a/crates/ui-egui/src/type_tool_tests.rs+++ b/crates/ui-egui/src/type_tool_tests.rs@@ -10,7 +10,7 @@ use photocraft_doc::{LayerContent, LayerId, TextLayer};use photocraft_geom::{Affine, Point};use serde_json::json;-use super::{layout, text_layer};+use super::{PathClick, layout, path_target, text_layer};use crate::PhotocraftApp;use crate::canvas::ViewXform;@@ -2062,3 +2062,79 @@ fn type_mask_shift_adds_and_alt_subtracts_without_a_layer_row() {assert!(at(&app, stem.0, stem.1) < 0.01, "⌥ subtracts the glyphs");assert!(at(&app, 1050, 150) > 0.99, "and keeps the rest");}++fn ellipse_layer(app: &mut PhotocraftApp) -> u64 {+ app.run("shape.create", json!({"kind": "ellipse", "rect": [200, 200, 400, 300], "fill": "#dddddd"})).unwrap()["layer"].as_u64().unwrap()+}++fn click_at(app: &mut PhotocraftApp, x: f64, y: f64) {+ use crate::canvas::{ToolEvent, tool_event};+ tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, Modifiers::NONE);+ tool_event(app, ToolEvent::Up { x, y }, Modifiers::NONE);+}++#[test]+fn clicking_inside_a_shape_starts_area_type_in_one_step() {+ use photocraft_doc::text::TextShape;+ let mut app = new_app();+ let shape = ellipse_layer(&mut app);+ assert!(matches!(path_target(&app, 400.0, 350.0), Some(PathClick::Area { shape: Some(s) }) if s == shape));+ let before = app.session.active().unwrap().history.entries().len();+ click_at(&mut app, 400.0, 350.0);+ let id = LayerId(app.ui.text_edit.as_ref().expect("editing").layer);+ let st = app.session.active().unwrap();+ assert!(matches!(text_layer(&st.doc, id).unwrap().shape, TextShape::Area { .. }));+ assert_eq!(st.history.entries().len(), before + 1, "create + fill is one step");+ super::commit(&mut app);+ app.run("edit.undo", json!({})).unwrap();+ assert!(app.session.active().unwrap().doc.layer(id).is_none());+}++#[test]+fn clicking_on_a_path_outline_starts_type_on_the_path_where_clicked() {+ use photocraft_doc::text::TextShape;+ let mut app = new_app();+ ellipse_layer(&mut app);+ // The ellipse's bottom point (400, 500); its perimeter is about 1105 px.+ let Some(PathClick::OnPath { start, .. }) = path_target(&app, 400.0, 500.0) else { panic!("on the outline") };+ assert!((0.0..1110.0).contains(&start), "{start}");+ // A point a quarter of the way further round is about 276 px further along (mod the perimeter).+ 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}");+ click_at(&mut app, 400.0, 500.0);+ let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer);+ assert!(+ matches!(text_layer(&app.session.active().unwrap().doc, id).unwrap().shape, TextShape::Path { start: s, .. } if (f64::from(s) - start).abs() < 0.01)+ );+}++#[test]+fn click_outside_paths_still_makes_point_text() {+ use photocraft_doc::text::TextShape;+ let mut app = new_app();+ ellipse_layer(&mut app);+ assert!(path_target(&app, 1200.0, 700.0).is_none());+ click_at(&mut app, 1200.0, 700.0);+ let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer);+ assert_eq!(text_layer(&app.session.active().unwrap().doc, id).unwrap().shape, TextShape::Point);+ // A drag inside the shape still makes a text box, as in Photoshop.+ let mut app = new_app();+ ellipse_layer(&mut app);+ use crate::canvas::{ToolEvent, tool_event};+ tool_event(&mut app, ToolEvent::Down { x: 300.0, y: 300.0, pressure: 1.0 }, Modifiers::NONE);+ tool_event(&mut app, ToolEvent::Move { x: 450.0, y: 400.0, pressure: 1.0 }, Modifiers::NONE);+ tool_event(&mut app, ToolEvent::Up { x: 450.0, y: 400.0 }, Modifiers::NONE);+ let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer);+ assert!(matches!(text_layer(&app.session.active().unwrap().doc, id).unwrap().shape, TextShape::Box { .. }));+}++#[test]+fn type_mask_tools_ignore_paths() {+ let mut app = new_app();+ ellipse_layer(&mut app);+ app.ui.tool = crate::state::Tool::HorizontalTypeMask;+ click_at(&mut app, 400.0, 350.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);+}