PhotoCraft: An open-source, photo editor written by scratch in pure Rust
M9: create vertical type from the Type tool flyout (#784)
midasdf0675a253ddc4
diff --git a/crates/engine/src/type_cmds.rs b/crates/engine/src/type_cmds.rsindex 0633b36e6..5847c5ace 100644--- a/crates/engine/src/type_cmds.rs+++ b/crates/engine/src/type_cmds.rs@@ -10,7 +10,7 @@ use std::sync::Arc;use photocraft_color::Color;use photocraft_doc::text::{- AntiAlias, Caps, CharStyle, FontFeature, FontVariation, Kerning, ParagraphRun, ParagraphStyle, TextAlign, TextDirection, TextRun, TextShape,+ AntiAlias, Caps, CharStyle, FontFeature, FontVariation, Kerning, Orientation, ParagraphRun, ParagraphStyle, TextAlign, TextDirection, TextRun, TextShape,};use photocraft_doc::{Affine, Document, Layer, LayerContent, LayerId, TextLayer};use serde_json::{Value, json};@@ -513,10 +513,16 @@ pub fn specs() -> Vec<CommandSpec> {label: "New Type Layer",menu: &["Layer", "New"],shortcut: None,- params: r##"{"x":px,"y":px (baseline anchor of point text),"text":str,"box":[x,y,w,h]? (paragraph text),"name":str?,"align":"left|center|right|justify…"?, …character keys: "font","size":pt=12,"color",…}"##,+ params: r##"{"x":px,"y":px (baseline anchor of point text),"text":str,"box":[x,y,w,h]? (paragraph text),"name":str?,"align":"left|center|right|justify…"?,"orientation":"horizontal|vertical"="horizontal", …character keys: "font","size":pt=12,"color",…}"##,enabled: has_doc,journal: true,run: |s, p| {+ let orientation = match p.get("orientation") {+ None => Orientation::Horizontal,+ Some(Value::String(value)) if value == "horizontal" => Orientation::Horizontal,+ Some(Value::String(value)) if value == "vertical" => Orientation::Vertical,+ _ => return Err(bad("type.create", "orientation must be horizontal or vertical")),+ };check_size_tracking(p).map_err(|m| bad("type.create", m))?;let text = norm_text(p.get("text").and_then(Value::as_str).unwrap_or(""));// Type › Save Default Type Styles sets the starting styles; the colour is always@@ -542,6 +548,7 @@ pub fn specs() -> Vec<CommandSpec> {text,shape,transform,+ orientation,..Default::default()};t.sync_summary();@@ -1170,4 +1177,25 @@ mod tests {assert!(s.undo() && s.undo());assert_eq!(kerning_of(&s, id)[0], (Kerning::Metrics, 0.0));}+ #[test]+ fn create_vertical_type_is_atomic_and_invalid_orientation_is_rejected() {+ for boxed in [false, true] {+ let mut s = session();+ let before = s.active().unwrap().history.entries().len();+ for orientation in [json!("diagonal"), json!(null), json!(true)] {+ assert!(s.execute("type.create", json!({"text": "test", "orientation": orientation})).is_err());+ assert_eq!(s.active().unwrap().history.entries().len(), before);+ }+ let mut p = json!({"text": "test", "orientation": "vertical", "x": 20, "y": 20});+ if boxed {+ p["box"] = json!([20, 20, 80, 60]);+ }+ let id = s.execute("type.create", p).unwrap()["layer"].as_u64().unwrap();+ let t = text_layer(&s, id);+ assert_eq!(t.orientation, Orientation::Vertical);+ assert_eq!(matches!(t.shape, TextShape::Box { .. }), boxed);+ s.execute("edit.undo", json!({})).unwrap();+ assert!(s.active().unwrap().doc.layer(LayerId(id)).is_none());+ }+ }}diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 212612bce..73cadc0ec 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -1827,7 +1827,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:if app.ui.transform.is_some() && response.double_clicked() {crate::transform_tool::commit(app);}- if tool == Tool::Type && response.double_clicked() {+ if tool.is_type() && response.double_clicked() {crate::type_tool::select_word(app);}if app.ui.extras.grid && app.ui.view.extras {@@ -1929,7 +1929,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:}}// Preferences › Cursors › Other Cursors: Precise shows a crosshair for every tool.- Tool::Move | Tool::Type | Tool::Eyedropper if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise => {+ Tool::Move | Tool::Type | Tool::VerticalType | Tool::Eyedropper+ if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise =>+ {egui::CursorIcon::Crosshair}Tool::Move => egui::CursorIcon::Move,@@ -1947,7 +1949,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:egui::CursorIcon::ZoomIn}}- Tool::Type => egui::CursorIcon::Text,+ Tool::Type | Tool::VerticalType => egui::CursorIcon::Text,_ => egui::CursorIcon::Crosshair,};ui.ctx().set_cursor_icon(icon);@@ -2219,7 +2221,7 @@ fn draw_drag_preview(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &Viewpainter.circle_filled(a, 3.0, Color32::WHITE);painter.circle_filled(b, 3.0, Color32::WHITE);}- Tool::Type => {+ Tool::Type | Tool::VerticalType => {let r = Rect::from_two_pos(xf.to_screen(d.start[0] as f32, d.start[1] as f32), xf.to_screen(last[0] as f32, last[1] as f32));let pts = [r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom(), r.left_top()];painter.add(egui::Shape::line(pts.to_vec(), Stroke::new(1.0, Color32::WHITE)));@@ -2283,7 +2285,7 @@ pub(crate) fn composite_color(app: &mut PhotocraftApp, x: f64, y: f64) -> Option/// and update the live stroke once (see `canvas_view`).fn tool_move(app: &mut PhotocraftApp, x: f64, y: f64, pressure: f32, mods: egui::Modifiers) {let tool = app.ui.tool;- if tool == Tool::Type && app.drag.is_none() {+ if tool.is_type() && app.drag.is_none() {crate::type_tool::pointer_move(app, x, y);}if tool == Tool::Pen {@@ -2460,7 +2462,7 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)polygon_click(app, x, y, mods);return;}- Tool::Type if crate::type_tool::pointer_down(app, x, y, mods.shift) => return,+ Tool::Type | Tool::VerticalType if crate::type_tool::pointer_down(app, x, y, mods.shift) => return,_ => {}}crate::paint_mouse::sync_tool_smoothing(app);@@ -2485,7 +2487,7 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)feed_live_stroke(app);}ToolEvent::Up { x, y } => {- if tool == Tool::Type+ if tool.is_type()&& let Some(e) = app.ui.text_edit.as_mut(){e.dragging = false;@@ -2597,7 +2599,7 @@ pub(crate) fn finish_gesture(app: &mut PhotocraftApp, d: Drag) {Tool::ObjectSelection => crate::retouch_ui::finish_object_selection(app, d.start, [end[0], end[1]], d.modifiers),t if crate::vector_ui::is_shape_tool(t) => crate::vector_ui::finish_shape(app, t, d.start, [end[0], end[1]], d.modifiers),Tool::PathSelection => crate::vector_ui::path_selection_finish(app, d.start, [end[0], end[1]]),- Tool::Type => crate::type_tool::pointer_up(app, d.start, [end[0], end[1]]),+ Tool::Type | Tool::VerticalType => crate::type_tool::pointer_up(app, d.start, [end[0], end[1]]),Tool::Brush | Tool::Pencil | Tool::Eraser => {let live = app.live_stroke.take();let mut p = stroke_params(app, d.tool, d.erase, &app.stylus.stroke_points(&d.points));diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex dba5c433d..5fa159230 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -2048,6 +2048,7 @@ cameraRaw Color カラーPatch: パッチ:Lasso around an area, then drag the selection 投げ縄で範囲を囲み、選択範囲をドラッグしますEdit Type 文字を編集+ Vertical Type Tool 縦書き文字ツールFull-resolution preview unavailable フル解像度のプレビューを利用できませんNo patterns パターンなしEnable {name} {name}を有効にするdiff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rsindex 4a433bf5f..dbb58cdd1 100644--- a/crates/ui-egui/src/icons.rs+++ b/crates/ui-egui/src/icons.rs@@ -80,7 +80,7 @@ pub fn tool_icon(t: Tool) -> &'static str {Tool::SliceSelect => "square-dashed-mouse-pointer",Tool::Gradient => "blend",Tool::PaintBucket => "paint-bucket",- Tool::Type => "type",+ Tool::Type | Tool::VerticalType => "type",Tool::Hand => "hand",Tool::Zoom => "zoom-in",Tool::SpotHealing | Tool::Healing => "bandage",diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 960b55191..114c12f49 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -931,7 +931,7 @@ impl eframe::App for PhotocraftApp {self.checker = None;}self.drain_control(ctx);- if self.ui.text_edit.is_some() && self.ui.tool != state::Tool::Type {+ if self.ui.text_edit.is_some() && !self.ui.tool.is_type() {type_tool::commit(self);}if self.ui.pen.is_some() && self.ui.tool != state::Tool::Pen {diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex c58171536..19c960b1e 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -35,7 +35,7 @@ const TOOL_SECTIONS: &[&[&[Tool]]] = &[],&[&[Tool::Pen],- &[Tool::Type],+ &[Tool::Type, Tool::VerticalType],&[Tool::PathSelection],&[Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Line, Tool::CustomShape],],@@ -86,6 +86,10 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {}ui.spacing_mut().item_spacing = vec2(2.0, 3.0);let flyout_id = egui::Id::new("tool-flyout");+ let held_id = flyout_id.with("held");+ if ui.input(|i| i.pointer.any_pressed()) {+ ui.data_mut(|d| d.remove::<egui::Id>(held_id));+ }let mut slot_index = 0usize;for (si, section) in TOOL_SECTIONS.iter().enumerate() {// Photoshop 2026 draws one uninterrupted column (no group dividers).@@ -110,14 +114,25 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {let tri = vec![r.right_bottom() + vec2(-2.0, -2.0), r.right_bottom() + vec2(-6.0, -2.0), r.right_bottom() + vec2(-2.0, -6.0)];ui.painter().add(egui::Shape::convex_polygon(tri, t.text_faint, Stroke::NONE));}- if resp.clicked() {+ if resp.clicked() && ui.data(|d| d.get_temp::<egui::Id>(held_id)) != Some(key) {app.ui.tool = tool;}// Right-click or long-press opens the flyout (Photoshop).- let long_press =- resp.is_pointer_button_down_on() && ui.input(|i| i.pointer.press_start_time().is_some_and(|t0| i.time - t0 > 0.35));+ let held_for = resp.is_pointer_button_down_on().then(|| ui.input(|i| i.pointer.press_start_time().map(|t0| i.time - t0))).flatten();+ if slot.len() > 1+ && let Some(seconds) = held_for+ && seconds < 0.35+ {+ ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(0.35 - seconds));+ }+ let long_press = held_for.is_some_and(|seconds| seconds >= 0.35);if slot.len() > 1 && (resp.secondary_clicked() || long_press) {- ui.data_mut(|d| d.insert_temp(flyout_id, (key, resp.rect)));+ ui.data_mut(|d| {+ d.insert_temp(flyout_id, (key, resp.rect));+ if long_press {+ d.insert_temp(held_id, key);+ }+ });}if slot.len() > 1 && long_press {ui.ctx().request_repaint();@@ -179,7 +194,8 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {}});});- let clicked_outside = ui.input(|i| i.pointer.any_click()) && !area.response.hovered() && !resp.hovered();+ let held_release = resp.clicked() && ui.data(|d| d.get_temp::<egui::Id>(held_id)) == Some(key);+ let clicked_outside = ui.input(|i| i.pointer.any_click()) && !held_release && !area.response.hovered() && !resp.hovered();if clicked_outside || ui.input(|i| i.key_pressed(egui::Key::Escape)) {ui.data_mut(|d| d.remove::<(egui::Id, Rect)>(flyout_id));}@@ -710,7 +726,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {}});}- Tool::Type if t.pro => crate::type_tool::options_bar(app, ui),+ Tool::Type | Tool::VerticalType if t.pro => 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:"));@@ -811,7 +827,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {),Tool::Gradient => hint(ui, tl!("Drag to draw a gradient")),Tool::PaintBucket => hint(ui, tl!("Click to fill similar colours")),- Tool::Type => hint(ui, tl!("Click to add text")),+ Tool::Type | Tool::VerticalType => hint(ui, tl!("Click to add text")),// Retouching and smart-selection tools draw their bar in `retouch_ui::options_bar`._ => {}}@@ -2763,6 +2779,56 @@ mod swatch_type_tests {}}+#[cfg(test)]+mod type_flyout_tests {+ use super::*;++ fn frame(app: &mut PhotocraftApp, ctx: &egui::Context, time: f64, events: Vec<egui::Event>) {+ let mut out = ctx.run_ui(+ egui::RawInput { time: Some(time), events, screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1200.0, 1800.0))), ..Default::default() },+ |ui| toolbar(app, ui),+ );+ out.textures_delta.clear();+ }++ #[test]+ fn long_press_type_button_selects_vertical_without_selecting_on_release() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ let initial = app.ui.tool;+ let ctx = egui::Context::default();+ PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]);+ frame(&mut app, &ctx, 0.0, vec![]);+ frame(&mut app, &ctx, 0.1, vec![]);+ let index = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).position(|slot| slot.contains(&Tool::Type)).unwrap();+ let bx = if Tokens::get(&ctx).pro { 30.0 } else { 36.0 };+ let mut buttons: Vec<Rect> = ctx.viewport(|v| {+ v.prev_pass+ .widgets+ .layers()+ .flat_map(|(_, w)| w.iter())+ .filter(|w| w.rect.size() == Vec2::splat(bx) && w.sense.senses_click())+ .map(|w| w.rect)+ .collect()+ });+ buttons.sort_by(|a, b| a.top().total_cmp(&b.top()));+ let at = buttons[index].center();+ let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };+ frame(&mut app, &ctx, 1.0, vec![egui::Event::PointerMoved(at), pointer(at, true)]);+ frame(&mut app, &ctx, 1.36, vec![]);+ assert_eq!(ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::new("tool-flyout"))).map(|(id, _)| id), Some(egui::Id::new(("tool-slot", index))));+ frame(&mut app, &ctx, 1.4, vec![pointer(at, false)]);+ frame(&mut app, &ctx, 1.45, vec![]);+ assert_eq!(app.ui.tool, initial);+ let key = egui::Id::new(("tool-slot", index));+ let menu = ctx.memory(|m| m.area_rect(key.with("flyout"))).unwrap();+ let row = egui::pos2(menu.left() + 65.0, menu.top() + 39.0 + 8.0);+ frame(&mut app, &ctx, 2.0, vec![egui::Event::PointerMoved(row), pointer(row, true)]);+ frame(&mut app, &ctx, 2.05, vec![pointer(row, false)]);+ assert_eq!(app.ui.tool, Tool::VerticalType);+ assert!(ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::new("tool-flyout"))).is_none());+ }+}+#[cfg(test)]mod properties_card_tests {use super::*;diff --git a/crates/ui-egui/src/snap_ui.rs b/crates/ui-egui/src/snap_ui.rsindex 975e5a2b4..fbc74d400 100644--- a/crates/ui-egui/src/snap_ui.rs+++ b/crates/ui-egui/src/snap_ui.rs@@ -94,6 +94,7 @@ fn is_point_tool(t: Tool) -> bool {| Tool::Polygon| Tool::Line| Tool::Type+ | Tool::VerticalType)}diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex 8ab8cfbe3..dc9f7ab05 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -82,6 +82,7 @@ pub enum Tool {Gradient,PaintBucket,Type,+ VerticalType,Hand,Zoom,SpotHealing,@@ -111,7 +112,7 @@ pub enum Tool {}impl Tool {- pub const ALL: [Tool; 46] = [+ pub const ALL: [Tool; 47] = [Tool::Move,Tool::RectMarquee,Tool::EllipseMarquee,@@ -132,6 +133,7 @@ impl Tool {Tool::Gradient,Tool::PaintBucket,Tool::Type,+ Tool::VerticalType,Tool::Hand,Tool::Zoom,Tool::SpotHealing,@@ -184,6 +186,7 @@ impl Tool {Tool::Gradient => "Gradient Tool",Tool::PaintBucket => "Paint Bucket Tool",Tool::Type => "Horizontal Type Tool",+ Tool::VerticalType => "Vertical Type Tool",Tool::Hand => "Hand Tool",Tool::Zoom => "Zoom Tool",Tool::SpotHealing => "Spot Healing Brush Tool",@@ -210,6 +213,10 @@ impl Tool {Tool::CustomShape => "Custom Shape Tool",}}+ pub fn is_type(self) -> bool {+ matches!(self, Self::Type | Self::VerticalType)+ }+/// Retouching and painting tools that stroke with the brush (share the brush cursor and chip).pub fn is_brushlike(self) -> bool {matches!(@@ -243,7 +250,7 @@ impl Tool {Tool::MagicWand => 'W',Tool::Crop | Tool::Slice | Tool::SliceSelect => 'C',Tool::Gradient | Tool::PaintBucket => 'G',- Tool::Type => 'T',+ Tool::Type | Tool::VerticalType => 'T',Tool::Hand => 'H',Tool::Zoom => 'Z',Tool::SpotHealing | Tool::Healing | Tool::Patch | Tool::ContentAwareMove => 'J',@@ -271,7 +278,7 @@ impl Tool {Tool::MagicWand => "W",Tool::Crop => "C",Tool::Gradient | Tool::PaintBucket => "G",- Tool::Type => "T",+ Tool::Type | Tool::VerticalType => "T",Tool::Hand => "✋",Tool::Zoom => "🔍",_ => "•",diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rsindex dd7ec9017..fcc36fa5c 100644--- a/crates/ui-egui/src/type_tool.rs+++ b/crates/ui-egui/src/type_tool.rs@@ -110,7 +110,8 @@ pub fn edit_active(app: &mut PhotocraftApp) -> Result<(), String> {ed.anchor = 0;ed.caret = n;}- app.ui.tool = crate::state::Tool::Type;+ let vertical = app.session.active().and_then(|st| text_layer(&st.doc, id)).is_some_and(|t| t.orientation == photocraft_doc::text::Orientation::Vertical);+ app.ui.tool = if vertical { crate::state::Tool::VerticalType } else { crate::state::Tool::Type };app.ui.mask_target = false;app.ui.vector_mask_target = false;Ok(())@@ -256,6 +257,7 @@ pub fn pointer_up(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) {let o = app.ui.tool_options.clone();let mut p = json!({"text": PLACEHOLDER,+ "orientation": if app.ui.tool == crate::state::Tool::VerticalType { "vertical" } else { "horizontal" },"font": o.type_font,"fontStyle": o.type_style,"size": o.type_size,diff --git a/crates/ui-egui/src/type_tool_tests.rs b/crates/ui-egui/src/type_tool_tests.rsindex c100032db..301ea0ef3 100644--- a/crates/ui-egui/src/type_tool_tests.rs+++ b/crates/ui-egui/src/type_tool_tests.rs@@ -411,3 +411,26 @@ fn foreground_colour_recolours_only_selected_type() {assert_eq!((rgb_at(&app, id, 6), rgb_at(&app, id, 10)), ([0, 255, 0, 255], [0, 255, 0, 255]));assert_eq!(app.session.active().unwrap().history.entries().len(), steps + 1, "one step for the session");}++#[test]+fn vertical_type_tool_creates_point_and_paragraph_text_with_one_undo() {+ use crate::canvas::{ToolEvent, tool_event};+ use photocraft_doc::text::{Orientation, TextShape};+ for end in [[100.0, 100.0], [240.0, 230.0]] {+ let mut app = new_app();+ app.ui.tool = crate::state::Tool::VerticalType;+ let before = app.session.active().unwrap().history.entries().len();+ tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, Modifiers::NONE);+ tool_event(&mut app, ToolEvent::Move { x: end[0], y: end[1], pressure: 1.0 }, Modifiers::NONE);+ tool_event(&mut app, ToolEvent::Up { x: end[0], y: end[1] }, Modifiers::NONE);+ let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer);+ let st = app.session.active().unwrap();+ let text = text_layer(&st.doc, id).unwrap();+ assert_eq!(text.orientation, Orientation::Vertical);+ assert_eq!(matches!(text.shape, TextShape::Box { .. }), end != [100.0, 100.0]);+ assert_eq!(st.history.entries().len(), before + 1);+ super::commit(&mut app);+ app.run("edit.undo", json!({})).unwrap();+ assert!(app.session.active().unwrap().doc.layer(id).is_none());+ }+}