diff --git a/crates/ui-egui/src/canvas/cursor_policy.rs b/crates/ui-egui/src/canvas/cursor_policy.rs index f5e61808771..5aac0cc5f0a 100644 --- a/crates/ui-egui/src/canvas/cursor_policy.rs +++ b/crates/ui-egui/src/canvas/cursor_policy.rs @@ -50,17 +50,22 @@ pub(crate) fn sample_target() -> Cursor { /// The pointer of a painting tool that acts on a click and has no brush tip: the Paint Bucket's /// arrow with the bucket below right of it, the hotspot on the arrow's tip, so a click fills the -/// pixel under the tip (#12539), and the Magic Eraser's crosshair. Precise Other Cursors (or Caps -/// Lock, `precise`) gives the Paint Bucket the crosshair too (#3968). `None` for a tool that -/// strokes with the brush. +/// pixel under the tip (#12539), and the Magic Eraser's own icon with the hotspot on the eraser's +/// end at the lower left (#12001). Precise Other Cursors (or Caps Lock, `precise`) gives both the +/// crosshair (#3968). `None` for a tool that strokes with the brush. pub(crate) fn click_tool_cursor(tool: Tool, precise: bool) -> Option { match tool { Tool::PaintBucket if !precise => Some(Cursor::Painted(PaintedCursor::pointer_tool(PointerGlyph::Arrow, crate::icons::tool_icon(tool)))), + Tool::MagicEraser if !precise => Some(Cursor::Painted(PaintedCursor::tool(crate::icons::tool_icon(tool), MAGIC_ERASER_HOTSPOT, None))), Tool::PaintBucket | Tool::MagicEraser => Some(Cursor::Painted(PaintedCursor::Crosshair)), _ => None, } } +/// The Magic Eraser icon's point that sits on the pointer, in its 24-unit box: the middle of the eraser's end, which +/// lies at the lower left of the `eraser_magic` glyph (#12001). +pub(crate) const MAGIC_ERASER_HOTSPOT: egui::Vec2 = egui::vec2(4.6, 18.4); + /// Path Selection's own pointer (#13295): the light arrow, and the solid one with ⌥ (without ⌘) /// where a press would land on a component (`path_components::over_component`). ⌘ keeps the light /// one; Precise Other Cursors (or Caps Lock, `precise`) the crosshair. `mods` and `at` are the @@ -161,3 +166,7 @@ mod triangle_alt_eyedropper_tests; #[cfg(test)] #[path = "custom_shape_alt_eyedropper_tests.rs"] mod custom_shape_alt_eyedropper_tests; + +#[cfg(test)] +#[path = "magic_eraser_cursor_tests.rs"] +mod magic_eraser_cursor_tests; diff --git a/crates/ui-egui/src/canvas/magic_eraser_cursor_tests.rs b/crates/ui-egui/src/canvas/magic_eraser_cursor_tests.rs new file mode 100644 index 00000000000..aed908d1fe9 --- /dev/null +++ b/crates/ui-egui/src/canvas/magic_eraser_cursor_tests.rs @@ -0,0 +1,46 @@ +//! #12001: the Magic Eraser's cursor is its own toolbar icon with the hotspot on the eraser's end at the lower left, +//! also with Shift held; Precise Other Cursors and Caps Lock give the crosshair. Driven through real egui input on +//! the real canvas; the assertions read the cursor the tool asked the tool host for. + +use craft::behavior::{Cursor, PaintedCursor}; +use craft::ui::runtime::windows::WindowHost; +use egui::Modifiers; +use egui_kittest::Harness; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::guide_cursor_tests::{harness, hover}; +use crate::state::Tool; + +/// A point away from the harness's guide at x = 200. +const AT: [f32; 2] = [100.0, 150.0]; + +fn cursor_with(h: &mut Harness<'static, Box>, mods: Modifiers) -> Option { + hover(h, AT[0], AT[1], mods); + h.state().canvas_tools.last_response.as_ref().and_then(|r| r.cursor.clone()) +} + +#[test] +fn the_standard_cursor_is_the_magic_eraser_icon_with_its_tip_at_the_lower_left() { + let mut h = harness(Tool::MagicEraser); + let Some(Cursor::Painted(PaintedCursor::Tool { icon, hotspot, badge, .. })) = cursor_with(&mut h, Modifiers::NONE) else { + panic!("an icon cursor, not the crosshair"); + }; + assert_eq!(icon, crate::icons::tool_icon(Tool::MagicEraser), "the toolbar's own icon"); + // The eraser end of the glyph, at the lower left of its 24-unit box: pinned by value so a moved constant fails. + assert_eq!(hotspot, egui::vec2(4.6, 18.4), "the eraser tip"); + assert!(badge.is_none()); + assert_eq!(cursor_with(&mut h, Modifiers::SHIFT), cursor_with(&mut h, Modifiers::NONE), "Shift keeps it"); +} + +#[test] +fn precise_other_cursors_and_caps_lock_give_the_crosshair() { + let mut h = harness(Tool::MagicEraser); + let crosshair = Some(Cursor::Painted(PaintedCursor::Crosshair)); + h.state_mut().run("prefs.set", json!({"path": "cursors.other", "value": "precise"})).unwrap(); + assert_eq!(cursor_with(&mut h, Modifiers::NONE), crosshair, "Precise: the crosshair"); + h.state_mut().run("prefs.set", json!({"path": "cursors.other", "value": "standard"})).unwrap(); + assert_ne!(cursor_with(&mut h, Modifiers::NONE), crosshair, "Standard again: the icon"); + WindowHost::of(&h.ctx).set_caps_lock(Some(true)); + assert_eq!(cursor_with(&mut h, Modifiers::NONE), crosshair, "Caps Lock: the crosshair"); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index cea327ebd41..6fb92685cf9 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -30,7 +30,7 @@ pub(crate) mod params { use super::{ PhotocraftApp, alerts, brush_preset_dialog, canvas_input, channel_options_ui, color_picker_ui, color_table_ui, count_group_name_ui, duplicate_layer_ui, equalize_ui, file_forms, fill_ui, filter_dialog, history_options_ui, image_processor_ui, merge_channels_ui, new_group_ui, new_layer_ui, - smart_filter_dialog, snapshot_dialog, stack_dialog, stroke_ui, + paragraph_text_size, smart_filter_dialog, snapshot_dialog, stack_dialog, stroke_ui, }; use crate::canvas::document_display::CanvasHost; @@ -82,6 +82,7 @@ pub(crate) mod params { ParamFamily::new(history_options_ui::owns, history_options_ui::run), ParamFamily::new(brush_preset_dialog::owns, brush_preset_dialog::run), ParamFamily { check: Some(equalize_ui::check), ..ParamFamily::new(equalize_ui::owns, equalize_ui::run) }, + ParamFamily::new(paragraph_text_size::owns, paragraph_text_size::run), ParamFamily::new(channel_options_ui::owns, channel_options_ui::run), ParamFamily { check: Some(merge_channels_ui::check), ..ParamFamily::new(merge_channels_ui::owns, merge_channels_ui::run) }, ParamFamily { @@ -753,6 +754,7 @@ pub mod new_guide_ui; pub mod new_layer_ui; pub mod open_prompt; pub mod palette; +pub mod paragraph_text_size; #[cfg(test)] mod paths_export_default_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/paragraph_text_size.rs b/crates/ui-egui/src/dialogs/paragraph_text_size.rs new file mode 100644 index 00000000000..7e29c0908da --- /dev/null +++ b/crates/ui-egui/src/dialogs/paragraph_text_size.rs @@ -0,0 +1,102 @@ +//! Paragraph Text Size: Alt+drag with the Type tool sizes the new paragraph box in a hosted +//! parameter dialog instead of committing the drag (#12044). Width and Height open in document +//! pixels with the size that was dragged, decimals kept (a ~100 px drag prefills 99.5), and the box +//! keeps its top-left where the drag started. OK runs the same `type.create` a plain drag does, so +//! the placeholder text lands selected exactly as it does there; Cancel closes the dialog and +//! creates nothing. +//! +//! Only what the ticket measured is here. No field rule was measured — no unit menu, no minimum, +//! no maximum — so the number goes to `type.create` as typed and the engine refuses a box it +//! cannot make. A drag upwards or to the left of its start keeps today's rule (the box is the +//! rectangle between the two points), and Cancel beyond closing the dialog is not specified. +//! +//! The dialog is a hosted parameter dialog with a key of its own, so `ui.inspect`, `ui.dialog.set` +//! and `ui.dialog.confirm` drive it like the other parameter dialogs. The drag's top-left, the +//! document it was made in and the tool, type options and placeholder preference the new layer is +//! built from are not fields: they are the family's captured value, read by [`run`]. The last of +//! those three is taken when the dialog opens rather than at OK, because the reference application's +//! dialog is modal — the layer keeps what was active at the drag (#12044). + +use craft::ui::dialog::DialogId; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamResult}; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::dialogs::params; + +/// The dialog family's key. The dialog sizes the box for a `type.create`, but it is not that +/// command's own form, so it carries a key of its own and never routes the plain parameter form. +const KEY: &str = "type.paragraphTextSize"; +const WIDTH: &str = "width"; +const HEIGHT: &str = "height"; + +/// Whether `key` is the Paragraph Text Size dialog's. +pub fn owns(key: &str) -> bool { + key == KEY +} + +/// The two rows, Width and Height in document pixels, opening at the size that was dragged. One +/// decimal shows a dragged half pixel (99.5) as such; no range is measured, so the field keeps the +/// number typed and `type.create` refuses a box it cannot make. +fn build(w: f64, h: f64) -> impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static { + move |_fields: &mut DialogFields| { + let rows = vec![Param::number(WIDTH, tl!("Width"), w, 1.0, 1), Param::number(HEIGHT, tl!("Height"), h, 1.0, 1)]; + ParamDialog::new(KEY, tl!("Paragraph Text Size"), rows) + } +} + +/// Open the dialog on the box an Alt+drag drew: top-left `(x, y)`, size `w` × `h`, in document +/// pixels and exactly as dragged (the fields keep the decimals). The top-left, the document the drag +/// was made in and the settings the new layer is built from are captured for [`run`]: OK creates the +/// text only while that document is still the active one, and with the tool and options that were +/// active at the drag. +/// +/// The settings are snapshotted here rather than read at OK because the reference application's +/// dialog is modal: nothing can change the tool (horizontal or vertical) or its options between the +/// Alt+drag and OK, so the box always uses what was active at the drag. A control that changes them +/// while the dialog happens to be open therefore cannot leak into the new layer (#12044). +pub fn open(app: &mut PhotocraftApp, at: [f64; 2], w: f64, h: f64) -> DialogId { + let captured = json!({ + "at": [at[0], at[1]], + "document": app.session.active().map(|st| json!(st.doc.id)).unwrap_or(Value::Null), + "settings": crate::type_tool::TypeSnapshot::live(app), + }); + let fields = DialogFields::from_pairs([(WIDTH, FieldValue::Number(w)), (HEIGHT, FieldValue::Number(h))]); + params::open_param_unsaved(app, KEY, fields, captured, build(w, h)) +} + +/// OK: create the paragraph text the dialog sized, the same layer a plain drag of the same box +/// would have made, and hand the keyboard to its editor as the drag's release does. +pub fn run(app: &mut PhotocraftApp, ctx: &egui::Context, result: ParamResult) { + let captured = params::captured(app, &result.key); + // The box was dragged in one document: never put the text into another one that became active since. + if captured.get("document") != app.session.active().map(|st| json!(st.doc.id)).as_ref() { + crate::dialogs::alerts::report_error(app, "the document the box was dragged in is no longer the active one"); + return; + } + let at = captured.get("at").and_then(Value::as_array); + let (Some(x), Some(y)) = (at.as_ref().and_then(|a| a.first()).and_then(Value::as_f64), at.as_ref().and_then(|a| a.get(1)).and_then(Value::as_f64)) else { + crate::dialogs::alerts::report_error(app, "the Paragraph Text Size dialog has no position"); + return; + }; + let (Some(w), Some(h)) = (result.fields.number(WIDTH), result.fields.number(HEIGHT)) else { + crate::dialogs::alerts::report_error(app, "the Paragraph Text Size dialog has no size"); + return; + }; + // The settings are the ones the drag had, not the ones the app has now: the reference dialog is + // modal, so a control that switched the tool or edited the options while it was open has no say + // in this layer (#12044). + let Ok(settings) = serde_json::from_value(captured.get("settings").cloned().unwrap_or(Value::Null)) else { + crate::dialogs::alerts::report_error(app, "the Paragraph Text Size dialog has no settings snapshot"); + return; + }; + let mut p = crate::type_tool::create_params(app, true, &settings); + p["box"] = json!([x, y, w, h]); + // A refused create already said why in the status bar, as the gesture's own create does. + if crate::type_tool::create_layer(app, p, None, &settings).is_ok() { + crate::type_tool::focus_editor(ctx); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/paragraph_text_size/tests.rs b/crates/ui-egui/src/dialogs/paragraph_text_size/tests.rs new file mode 100644 index 00000000000..475d1716d9c --- /dev/null +++ b/crates/ui-egui/src/dialogs/paragraph_text_size/tests.rs @@ -0,0 +1,328 @@ +//! Alt+drag with the Type tool and the Paragraph Text Size dialog it opens (#12044): the dialog is +//! measured (prefilled with the dragged size, decimals kept, OK creates the box at the drag start +//! and adds one History state, Cancel creates nothing and adds none), and the neighbours of that +//! route are checked to keep today's behaviour: a plain drag still makes the box directly, Alt+click +//! is still point text, the vertical Type tool keeps its plain drag, ⌥ is read at the press so it can +//! come up or go down mid-drag, a second drag while the dialog is open is swallowed by that dialog, +//! the layer keeps the tool, the type options and the placeholder preference that were active when +//! the dialog opened, and a name the dialog does not show as a field is refused. +//! +//! The gestures go through the canvas pass (`canvas::testing`), the way the released Type tool does +//! on the hosted framework: a press with ⌥ held, a move, a release. The dialog is driven the way a +//! control answer drives a hosted parameter dialog: fields through `set_json_field`, OK through +//! `dialogs::confirm`, Cancel through the host. + +use craft::ui::dialog::DialogId; +use egui::Modifiers; +use photocraft_doc::LayerContent; +use serde_json::{Value, json}; + +use super::*; +use crate::canvas::testing::{ToolEvent, frame, tool_event}; +use crate::state::Tool; +use crate::type_tool::PLACEHOLDER; + +/// A 400 × 200 document with the Type tool ready. +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Type; + app +} + +/// Press at `from` with `down` held, drag to `to` and release with `up` held, as the canvas pass +/// sees it (the move carries `up`, the state just before the release). ⌥ can change mid-gesture: +/// the Alt+drag rule reads it from the press, and these two modifiers are how a test says so. +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], down: Modifiers, up: Modifiers) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, down); + if from != to { + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, up); + } + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, up); +} + +fn layers(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.layers.len() +} + +/// The active document's History entries: the ticket's "adds no history state" is measured here. +fn history_len(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.entries().len() +} + +/// The open hosted dialogs: id, key and fields. Asserts that the Alt+drag opened one dialog and +/// that it is the Paragraph Text Size family's. +fn only_dialog(app: &PhotocraftApp) -> (DialogId, Value) { + let open = app.framework.dialogs.open_dialogs(); + assert_eq!(open.len(), 1, "the Alt+drag opens one dialog"); + let d = &open[0]; + assert_eq!(d.key.as_deref(), Some(KEY), "it is the Paragraph Text Size dialog"); + (d.id, d.fields.clone().unwrap_or_default()) +} + +/// Set dialog fields without confirming them, the way a control `ui.dialog.set` does. +fn set(app: &mut PhotocraftApp, id: DialogId, fields: [(&str, Value); 2]) { + let ctx = app.ctx().clone(); + for (field, value) in fields { + for (field, value) in crate::control::dialogs::map_request(app, id, field, value) { + app.framework.dialogs.set_json_field(&ctx, id, &field, value).unwrap(); + } + } +} + +fn text(app: &PhotocraftApp, id: u64) -> photocraft_doc::TextLayer { + let st = app.session.active().unwrap(); + let layer = st.doc.layer(photocraft_doc::LayerId(id)).unwrap(); + let LayerContent::Text(t) = &layer.content else { panic!("not a type layer") }; + t.clone() +} + +/// The paragraph box of `id` in document pixels: its top-left through the layer transform, then its +/// width and height. +fn box_rect(app: &PhotocraftApp, id: u64) -> [f64; 4] { + let t = text(app, id); + let photocraft_doc::text::TextShape::Box { x, y, width, height } = t.shape else { panic!("not paragraph text") }; + [t.transform.m[4] + f64::from(x), t.transform.m[5] + f64::from(y), f64::from(width), f64::from(height)] +} + +/// #12044: Alt+drag opens the parameter dialog instead of creating the text, prefilled with the +/// size that was dragged — including its decimals. +#[test] +fn alt_drag_opens_the_dialog_prefilled_with_the_dragged_size() { + let mut app = app(); + let before = layers(&app); + drag(&mut app, [10.0, 10.0], [109.5, 60.0], Modifiers::ALT, Modifiers::ALT); + let (_id, f) = only_dialog(&app); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(99.5), Some(50.0)), "the dragged size, decimals kept"); + assert_eq!(layers(&app), before, "the drag itself creates nothing"); + assert!(app.ui.text_edit.is_none(), "and starts no edit session"); +} + +/// OK creates the paragraph layer with the box the dialog holds, top-left at the drag's start, and +/// the placeholder selected — as a plain drag of that box does. +#[test] +fn confirming_creates_the_paragraph_box_at_the_drag_start() { + let mut app = app(); + drag(&mut app, [10.0, 10.0], [109.5, 60.0], Modifiers::ALT, Modifiers::ALT); + let (d, _) = only_dialog(&app); + set(&mut app, d, [("width", json!(250.0)), ("height", json!(120.0))]); + let steps = history_len(&app); + let ctx = app.ctx().clone(); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + assert!(app.framework.dialogs.open_dialogs().is_empty(), "OK closes the dialog"); + assert_eq!(history_len(&app), steps + 1, "OK adds one History state, as the drag's create does"); + let ed = app.ui.text_edit.as_ref().expect("OK starts the edit session, as the drag does"); + assert_eq!(box_rect(&app, ed.layer), [10.0, 10.0, 250.0, 120.0], "the dialog's box at the drag's start"); + assert_eq!((ed.anchor, ed.caret), (0, PLACEHOLDER.chars().count()), "placeholder text, all of it selected"); + assert_eq!(text(&app, ed.layer).text, PLACEHOLDER); +} + +/// Cancel closes the dialog and creates nothing: no layer, no edit session. Cancel goes through +/// the host, the way `ui.dialog.cancel` and the rendered Cancel button both do. +#[test] +fn cancelling_creates_nothing() { + let mut app = app(); + drag(&mut app, [10.0, 10.0], [109.5, 60.0], Modifiers::ALT, Modifiers::ALT); + let (id, _) = only_dialog(&app); + let before = layers(&app); + let steps = history_len(&app); + let ctx = app.ctx().clone(); + app.framework.dialogs.cancel_by_id(&ctx, id); + frame(&mut app); + assert!(app.framework.dialogs.open_dialogs().is_empty(), "Cancel closes the dialog"); + assert_eq!(layers(&app), before, "Cancel creates nothing"); + assert_eq!(history_len(&app), steps, "and adds no History state"); + assert!(app.ui.text_edit.is_none()); +} + +/// The dialog belongs to the document the Alt+drag was made in: when another document is active at +/// OK, nothing is created in it (or anywhere), and the dialog closes with the reason in the status. +#[test] +fn confirming_after_another_document_became_active_creates_nothing() { + let mut app = app(); + drag(&mut app, [10.0, 10.0], [109.5, 60.0], Modifiers::ALT, Modifiers::ALT); + let (d, _) = only_dialog(&app); + let first = app.session.active_index().unwrap(); + let first_layers = layers(&app); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.sync_views(); + assert_ne!(app.session.active_index(), Some(first), "the second document is active"); + let second_layers = layers(&app); + let ctx = app.ctx().clone(); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + assert!(app.framework.dialogs.open_dialogs().is_empty(), "the dialog closes"); + assert!(app.ui.status_error, "OK in another document says why: {}", app.ui.status); + assert_eq!(layers(&app), second_layers, "nothing lands in the active document"); + assert!(app.session.set_active(first)); + assert_eq!(layers(&app), first_layers, "nor in the original one"); + assert!(app.ui.text_edit.is_none()); +} + +/// Not measured by the ticket, so unchanged: a drag without Alt still commits the box directly. +#[test] +fn a_plain_drag_still_makes_the_box_directly() { + let mut app = app(); + drag(&mut app, [10.0, 10.0], [110.0, 60.0], Modifiers::NONE, Modifiers::NONE); + assert!(app.framework.dialogs.open_dialogs().is_empty(), "a plain drag opens no dialog"); + let ed = app.ui.text_edit.as_ref().expect("the drag creates the text at once"); + assert_eq!(box_rect(&app, ed.layer), [10.0, 10.0, 100.0, 50.0]); +} + +/// Not measured by the ticket, so unchanged: Alt+click (no drag) stays point text. +#[test] +fn an_alt_click_is_still_point_text() { + let mut app = app(); + drag(&mut app, [50.0, 100.0], [50.0, 100.0], Modifiers::ALT, Modifiers::ALT); + assert!(app.framework.dialogs.open_dialogs().is_empty(), "a click opens no dialog"); + let ed = app.ui.text_edit.as_ref().expect("the click creates point text"); + let t = text(&app, ed.layer); + assert!(matches!(t.shape, photocraft_doc::text::TextShape::Point), "point text"); + assert_eq!([t.transform.m[4], t.transform.m[5]], [50.0, 100.0]); +} + +/// Guard (pattern 8, the order of checks): ⌥ is read at the press of the gesture, so letting it up +/// mid-drag does not take the dialog away. Pinning the chosen latch, so it passes with the rule read +/// at the release too only if that rule were in the code: with the release read instead, this drag +/// has no ⌥ left at the release and no dialog opens - seen red. +#[test] +fn alt_released_mid_drag_still_opens_the_dialog() { + let mut app = app(); + let before = layers(&app); + drag(&mut app, [10.0, 10.0], [109.5, 60.0], Modifiers::ALT, Modifiers::NONE); + let (_id, f) = only_dialog(&app); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(99.5), Some(50.0)), "the dragged size, decimals kept"); + assert_eq!(layers(&app), before, "the drag itself still creates nothing"); + assert!(app.ui.text_edit.is_none(), "and still starts no edit session"); +} + +/// The same latch the other way, guard as well: ⌥ pressed only as the button comes up opens nothing, +/// the gesture stays today's plain drag (rounded to the pixel, as it has always been). +#[test] +fn alt_pressed_mid_drag_makes_the_plain_box_instead() { + let mut app = app(); + drag(&mut app, [10.0, 10.0], [109.5, 60.0], Modifiers::NONE, Modifiers::ALT); + assert!(app.framework.dialogs.open_dialogs().is_empty(), "⌥ pressed mid-drag opens no dialog"); + let ed = app.ui.text_edit.as_ref().expect("the drag creates the text at once"); + assert_eq!(box_rect(&app, ed.layer), [10.0, 10.0, 100.0, 50.0], "the plain drag's rounded box"); +} + +/// Guard: the dialog the first drag opened stays the only one, and a second canvas gesture while it +/// is open reaches neither the rule nor `type.create`: nothing is created, nothing is edited. +#[test] +fn a_second_drag_while_the_dialog_is_open_creates_nothing() { + let mut app = app(); + drag(&mut app, [10.0, 10.0], [109.5, 60.0], Modifiers::ALT, Modifiers::ALT); + let (_id, _) = only_dialog(&app); + let before = layers(&app); + drag(&mut app, [200.0, 20.0], [260.0, 70.0], Modifiers::ALT, Modifiers::ALT); + assert_eq!(app.framework.dialogs.open_dialogs().len(), 1, "the second drag opens no second dialog"); + assert_eq!(layers(&app), before, "and creates nothing"); + assert!(app.ui.text_edit.is_none(), "and starts no edit session"); +} + +/// Guard (pattern 4, scope): the ticket measured the horizontal Type tool alone, so the vertical one +/// keeps today's gesture - an Alt+drag there still commits the box at once, with no dialog. +#[test] +fn an_alt_drag_with_the_vertical_type_tool_still_makes_the_box_directly() { + let mut app = app(); + app.ui.tool = Tool::VerticalType; + drag(&mut app, [10.0, 10.0], [110.0, 60.0], Modifiers::ALT, Modifiers::ALT); + assert!(app.framework.dialogs.open_dialogs().is_empty(), "the vertical Type tool opens no dialog"); + let ed = app.ui.text_edit.as_ref().expect("the drag creates the text at once"); + assert_eq!(box_rect(&app, ed.layer), [10.0, 10.0, 100.0, 50.0], "the plain drag's box"); +} + +/// The point size of the new layer's first run, as `type.create` stored it. +fn size_pt(app: &PhotocraftApp, id: u64) -> f32 { + text(app, id).char_runs().into_iter().next().expect("the new layer has one run").style.size_pt +} + +/// #12044 review: the reference dialog is modal, so nothing can change the tool or its options +/// between the Alt+drag and OK. The dialog therefore snapshots the tool, the type options and the +/// placeholder preference when it opens, and OK creates from that snapshot: a control that switches +/// to the vertical Type tool and changes the size while the dialog is open does not leak into the +/// new layer, which stays horizontal at the size the drag had. +#[test] +fn the_layer_keeps_the_tool_and_options_active_at_the_drag() { + let mut app = app(); + app.ui.tool_options.type_font = "Drag Font".into(); + app.ui.tool_options.type_style = "Regular".into(); + app.ui.tool_options.type_size = 24.0; + drag(&mut app, [10.0, 10.0], [109.5, 60.0], Modifiers::ALT, Modifiers::ALT); + let (d, _) = only_dialog(&app); + // Change the settings the dialog is about to read, while it is open. + app.ui.tool = Tool::VerticalType; + app.ui.tool_options.type_font = "Later Font".into(); + app.ui.tool_options.type_size = 72.0; + let ctx = app.ctx().clone(); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + let ed = app.ui.text_edit.as_ref().expect("OK starts the edit session, as the drag does"); + let t = text(&app, ed.layer); + assert_eq!(t.orientation, photocraft_doc::text::Orientation::Horizontal, "the tool held at the drag, not the one at OK"); + assert_eq!(size_pt(&app, ed.layer), 24.0, "the size held at the drag, not the one at OK"); + assert_eq!(t.char_runs()[0].style.font_family, "Drag Font", "and the family held at the drag"); + assert_eq!(box_rect(&app, ed.layer), [10.0, 10.0, 99.5, 50.0], "still the box the drag drew"); +} + +/// The same snapshot covers the placeholder preference: turning "Fill new type layers with +/// placeholder text" off while the dialog is open does not leave the new layer empty. +#[test] +fn the_layer_keeps_the_placeholder_preference_active_at_the_drag() { + let mut app = app(); + drag(&mut app, [10.0, 10.0], [109.5, 60.0], Modifiers::ALT, Modifiers::ALT); + let (d, _) = only_dialog(&app); + app.session.edit_prefs(|p| p.type_.fill_new_type_layers_with_placeholder = false); + let ctx = app.ctx().clone(); + crate::dialogs::confirm(&mut app, &ctx, d).unwrap(); + let ed = app.ui.text_edit.as_ref().expect("OK starts the edit session, as the drag does"); + assert_eq!(text(&app, ed.layer).text, PLACEHOLDER, "the preference held at the drag, not the one at OK"); + assert_eq!((ed.anchor, ed.caret), (0, PLACEHOLDER.chars().count()), "and its placeholder stays selected"); +} + +/// Not changed by the snapshot: a plain drag reads the tool and its options at the moment it ends. +/// Pinned so the snapshot stays inside the dialog's route. +#[test] +fn a_plain_drag_reads_the_settings_at_its_own_release() { + let mut app = app(); + app.ui.tool = Tool::VerticalType; + app.ui.tool_options.type_font = "Drag Font".into(); + app.ui.tool_options.type_size = 24.0; + drag(&mut app, [10.0, 10.0], [110.0, 60.0], Modifiers::NONE, Modifiers::NONE); + let ed = app.ui.text_edit.as_ref().expect("the drag creates the text at once"); + let t = text(&app, ed.layer); + assert_eq!(t.orientation, photocraft_doc::text::Orientation::Vertical, "the tool in hand at the release"); + assert_eq!(size_pt(&app, ed.layer), 24.0, "and the options in hand at the release"); + assert_eq!(t.char_runs()[0].style.font_family, "Drag Font"); +} + +/// The other unchanged neighbour: a click reads the live settings too, including the placeholder +/// preference as it is at that moment. +#[test] +fn a_click_reads_the_settings_at_its_own_release() { + let mut app = app(); + app.session.edit_prefs(|p| p.type_.fill_new_type_layers_with_placeholder = false); + app.ui.tool_options.type_size = 30.0; + drag(&mut app, [50.0, 100.0], [50.0, 100.0], Modifiers::NONE, Modifiers::NONE); + let ed = app.ui.text_edit.as_ref().expect("the click creates point text"); + let t = text(&app, ed.layer); + assert!(matches!(t.shape, photocraft_doc::text::TextShape::Point), "point text"); + assert_eq!(t.text, "", "the preference as it stands at the click"); + assert_eq!(size_pt(&app, ed.layer), 30.0, "and the options as they stand at the click"); +} + +/// Guard (pattern 9, no guessing from a name): the drag's top-left, the document it was made in and +/// the settings snapshot are the family's captured value, not fields - a control `set_json_field` +/// for a name the dialog does not show is refused, so neither the geometry nor the tool and its +/// options can be pushed in through the field map. +#[test] +fn a_name_the_dialog_does_not_show_as_a_field_is_refused() { + let mut app = app(); + drag(&mut app, [10.0, 10.0], [109.5, 60.0], Modifiers::ALT, Modifiers::ALT); + let (id, _) = only_dialog(&app); + let ctx = app.ctx().clone(); + for field in ["at", "document", "settings", "box", "text"] { + assert!(app.framework.dialogs.set_json_field(&ctx, id, field, json!(1.0)).is_err(), "`{field}` is not a field of this dialog"); + } + assert_eq!(only_dialog(&app).1["width"].as_f64(), Some(99.5), "and the two real fields keep the dragged size"); +} diff --git a/crates/ui-egui/src/layers_footer_tests.rs b/crates/ui-egui/src/layers_footer_tests.rs index 6ffa5ba4765..bbbc2ddf517 100644 --- a/crates/ui-egui/src/layers_footer_tests.rs +++ b/crates/ui-egui/src/layers_footer_tests.rs @@ -1,7 +1,8 @@ //! The Layers panel footer's buttons run PhotoCraft's commands (#2561, #153, #4728). New Group: like //! Photoshop CC 2014 and later, a click with two or more layers selected puts them in a new, //! collapsed group, and with one layer it adds an empty group; Shift-click groups the selection -//! too, Alt-click asks in the New Group dialog first and Cmd-click adds the empty group below the +//! too, Alt-click asks in the New Group dialog first (New Group from Layers also with one +//! non-Background layer active, which it groups, #14717) and Cmd-click adds the empty group below the //! active layer. New Layer: Cmd-click adds it below the active layer. Delete removes the targeted //! mask at once, or asks before deleting the layer (Alt deletes without asking). Add a mask //! targets the new mask; with a path selected it is a vector mask from that path. @@ -44,6 +45,14 @@ fn two(both: bool) -> Session { s } +/// `two(false)` with the Background active. +fn background_active() -> Session { + let mut s = two(false); + let bg = s.active().unwrap().doc.layers[0].id; + s.execute("layer.select", json!({"layer": bg.0})).unwrap(); + s +} + /// "Masked" (pixel and vector mask, both linked to it) and the "Badge" shape layer over it. fn masked(linked: bool) -> Session { let mut s = Session::new(); @@ -185,14 +194,66 @@ fn footer_buttons_run_photocraft_commands() { }, }, Case { - case: "Alt New Group, one selected", + case: "Alt New Group, one selected: New Group from Layers groups it (#14717)", doc: || two(false), before: none, button: "Create a new group", mods: Modifiers::ALT, + after: |h| { + group_dialog(h, "layer.new.groupFromLayers"); + let groups = groups(h); + assert_eq!(groups.len(), 1); + let children: Vec<&str> = groups[0].children().unwrap().iter().map(|l| l.name.as_str()).collect(); + assert_eq!(children, ["B"]); + assert_eq!(top(h)[1..], ["A".to_string(), groups[0].name.clone()], "the group takes B's place"); + }, + }, + Case { + case: "Alt New Group, Background active: an empty group", + doc: background_active, + before: none, + button: "Create a new group", + mods: Modifiers::ALT, after: |h| { group_dialog(h, "layer.new.group"); - empty_group(h, ["A", "B", "*"]); + assert!(groups(h)[0].children().unwrap().is_empty()); + assert!(layer(h, "Background").is_some_and(|l| !l.is_group())); + }, + }, + Case { + case: "Alt New Group, no layer active: an empty group", + doc: || { + let mut s = two(false); + s.execute("select.deselectLayers", json!({})).unwrap(); + s + }, + before: none, + button: "Create a new group", + mods: Modifiers::ALT, + after: |h| { + group_dialog(h, "layer.new.group"); + assert!(groups(h)[0].children().unwrap().is_empty()); + }, + }, + Case { + case: "Alt New Group, one artboard active: an empty group, the artboard stays a board", + doc: || { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + s.execute("layer.new.artboard", json!({"name": "Board", "rect": [0, 0, 100, 100]})).unwrap(); + s + }, + before: none, + button: "Create a new group", + mods: Modifiers::ALT, + after: |h| { + let id = h.state().framework.dialogs.stack().top().expect("the New Group dialog opened"); + confirm(h, id); + h.run_steps(4); + let plain: Vec = groups(h).into_iter().filter(|g| g.artboard().is_none()).collect(); + assert_eq!(plain.len(), 1, "OK adds one group: {:?}", top(h)); + assert!(plain[0].children().unwrap().is_empty()); + assert!(doc(h).layers.iter().any(|l| l.artboard().is_some()), "the artboard stays at the top level"); }, }, Case { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 971b53a2184..06b906f0d2f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -160,6 +160,7 @@ pub use dialogs::new_guide_ui; pub use dialogs::new_layer_ui; pub use dialogs::open_prompt; pub use dialogs::palette; +pub use dialogs::paragraph_text_size; pub(crate) use dialogs::pattern_fill_ui; pub use dialogs::preset_group_prompt; pub use dialogs::rasterize_prompt; diff --git a/crates/ui-egui/src/panels/layers_events.rs b/crates/ui-egui/src/panels/layers_events.rs index 4b519c25085..36344f5f94c 100644 --- a/crates/ui-egui/src/panels/layers_events.rs +++ b/crates/ui-egui/src/panels/layers_events.rs @@ -494,8 +494,12 @@ fn footer(app: &mut PhotocraftApp, picked: Option, LayersFooterAction::NewGroup { from_selection, ask, below, .. } => { let groups = from_selection && active.is_some(); if ask { - // Null params go through the menu path, which opens the dialog. - let cmd = if groups { crate::new_group_ui::FROM_LAYERS } else { crate::new_group_ui::NEW_GROUP }; + // Null params go through the menu path, which opens the dialog. Like Photoshop, + // ⌥-click asks for New Group from Layers also with one non-Background layer + // active, and OK puts that layer in the group (#14717). An artboard can't go into + // a group, so a lone artboard keeps New Group. + let one = active.is_some_and(|l| !doc.is_background(l.id) && l.artboard().is_none()); + let cmd = if groups || one { crate::new_group_ui::FROM_LAYERS } else { crate::new_group_ui::NEW_GROUP }; actions.push((cmd.into(), Value::Null)); } else if below { actions.push(("layer.new.group".into(), json!({"position": "below"}))); diff --git a/crates/ui-egui/src/tools/type_tool.rs b/crates/ui-egui/src/tools/type_tool.rs index 9ad4ea23d28..1f39f6da3bd 100644 --- a/crates/ui-egui/src/tools/type_tool.rs +++ b/crates/ui-egui/src/tools/type_tool.rs @@ -54,7 +54,7 @@ pub(crate) use panel::toggle_opentype; pub use panel::{character_panel, type_properties}; #[cfg(test)] pub(crate) use pointer::{PathClick, path_target}; -pub(crate) use pointer::{TypeState, box_shape, drain, tool}; +pub(crate) use pointer::{TypeSnapshot, TypeState, box_shape, create_layer, create_params, drain, tool}; pub(crate) use values::doc_unit; pub const PLACEHOLDER: &str = "Lorem Ipsum"; diff --git a/crates/ui-egui/src/tools/type_tool/canvas_tests.rs b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs index d88505cb7a9..0cd9005cf71 100644 --- a/crates/ui-egui/src/tools/type_tool/canvas_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs @@ -417,7 +417,7 @@ mod panel_defaults { let mut app = new_app(); app.ui.tool_options.type_style_defaults = json!({"tracking": 20, "text": "Injected", "box": [0, 0, 2, 2], "coalesce": "unrelated"}).as_object().unwrap().clone(); - let p = super::super::default_style_params(&app); + let p = super::super::default_style_params(&app, &app.ui.tool_options); assert_eq!(p["tracking"], 20); assert!(p.get("text").is_none() && p.get("box").is_none() && p.get("coalesce").is_none()); app.ui.tool_options.type_style_defaults = json!({ @@ -427,7 +427,7 @@ mod panel_defaults { .as_object() .unwrap() .clone(); - let p = super::super::default_style_params(&app); + let p = super::super::default_style_params(&app, &app.ui.tool_options); for key in ["tracking", "leading", "spaceAfter", "variations", "features"] { assert!(p.get(key).is_none(), "hostile {key} is ignored"); } diff --git a/crates/ui-egui/src/tools/type_tool/defaults.rs b/crates/ui-egui/src/tools/type_tool/defaults.rs index 9477b2e60b0..48b9408096d 100644 --- a/crates/ui-egui/src/tools/type_tool/defaults.rs +++ b/crates/ui-egui/src/tools/type_tool/defaults.rs @@ -59,9 +59,10 @@ pub(super) fn shown_scale(app: &PhotocraftApp) -> f32 { /// The styles a new Type-tool layer will receive. Use the same command parameters for the /// panels and creation so defaults also survive action recording/replay. The older options-bar -/// fields remain authoritative, and text colour continues to follow the foreground colour. -pub(super) fn default_style_params(app: &PhotocraftApp) -> serde_json::Value { - let o = &app.ui.tool_options; +/// fields remain authoritative, and text colour continues to follow the foreground colour. `o` is +/// the options-bar state to read: today's live one for a panel or a plain gesture, a snapshot taken +/// when the Paragraph Text Size dialog opened for its OK (#12044). +pub(super) fn default_style_params(app: &PhotocraftApp, o: &crate::state::ToolOptions) -> serde_json::Value { let mut p = json!({}); // Settings are editable JSON: only recognized formatting keys may reach type.create. // In particular a stray `text`, `box`, or `coalesce` key must not become a create parameter. @@ -149,7 +150,7 @@ fn finite_style_value(value: &serde_json::Value) -> bool { pub(super) fn default_styles(app: &PhotocraftApp) -> (photocraft_doc::text::CharStyle, photocraft_doc::text::ParagraphStyle) { let (mut c, mut para) = app.session.type_defaults.clone().unwrap_or_default(); - let mut p = default_style_params(app); + let mut p = default_style_params(app, &app.ui.tool_options); // The saved panels can appear on the very first frame. Style parsing resolves the named // font through shared(), which waits for the font scan; display the saved names meanwhile, // and let fonts_ready/axis_sliders expose the font controls when try_shared is ready. diff --git a/crates/ui-egui/src/tools/type_tool/pointer.rs b/crates/ui-egui/src/tools/type_tool/pointer.rs index ff6f7a3ca38..304ad523eca 100644 --- a/crates/ui-egui/src/tools/type_tool/pointer.rs +++ b/crates/ui-egui/src/tools/type_tool/pointer.rs @@ -34,6 +34,9 @@ pub(crate) struct TypeState { /// Where the running press began, in document units: the corner of the box a drag makes, or the point of a /// click. Set by a press that starts new text, taken by its release. pub(super) press: Option, + /// Whether ⌥ was held at the press of the running gesture. Set with `press`, taken by its release: an Alt+drag + /// opens the Paragraph Text Size dialog instead of making the box (#12044), the modifier read at the press. + pub(super) press_alt: bool, /// The press of this pass ended an open session (the editor commits on a background press): it starts no new /// text, as in Photoshop. Set by the canvas controls before the tool runs, taken by the press, cleared by `drain`. pub(super) began_with_session: bool, @@ -59,6 +62,7 @@ pub(crate) fn drain(app: &mut PhotocraftApp, state: &mut TypeState, _response: & state.began_with_session = false; if !crate::canvas::tools::in_gesture(app) { state.press = None; + state.press_alt = false; } } @@ -211,72 +215,129 @@ fn press_at(app: &mut PhotocraftApp, ctx: &egui::Context, x: f64, y: f64, mods: ToolAction::Done } -/// A release that makes new text: from `start` to `end` in document units. A drag of at least 4 screen pixels both -/// ways makes a paragraph box; anything less is a click, which makes point text, or text on or in the path under it. -fn create_text(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) { - let (w, h) = ((end[0] - start[0]).abs(), (end[1] - start[1]).abs()); - let o = app.ui.tool_options.clone(); - let mask = app.ui.tool.is_type_mask(); - let is_box = makes_box(app, start, end); - // 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 && !is_box { path_target(app, start[0], start[1]) } else { None }; +/// The settings a `type.create` is built from: the tool in hand (horizontal or vertical, and which +/// Type Mask), the options bar's type settings and the placeholder preference. A plain drag or a +/// click reads them live at its release, through [`TypeSnapshot::live`]. The Paragraph Text Size +/// dialog instead takes the snapshot when it opens and hands it to its OK (#12044): that dialog is +/// modal in the reference application, so nothing can change the tool or its options between the +/// Alt+drag and OK, and the box it makes uses what was active at the drag even when a control +/// changes them while the dialog is open. +#[derive(Clone, serde::Serialize, serde::Deserialize)] +pub(crate) struct TypeSnapshot { + pub tool: crate::state::Tool, + pub options: crate::state::ToolOptions, + pub placeholder: bool, +} + +impl TypeSnapshot { + /// Read from the app as it stands at this moment: today's live reading, what the plain drag and + /// the click create with. + pub(crate) fn live(app: &PhotocraftApp) -> Self { + Self { tool: app.ui.tool, options: app.ui.tool_options.clone(), placeholder: app.session.prefs().type_.fill_new_type_layers_with_placeholder } + } +} + +/// The `type.create` parameters a Type-tool gesture ending now starts from: the placeholder or +/// empty text, the tool's orientation and the options bar's styles. The caller adds the geometry +/// (`box` for a dragged paragraph, `x`/`y` for point text), and [`create_layer`] adds the session's +/// `coalesce` key. `is_box` says whether the gesture that ends was a paragraph drag, which #12077's +/// mask style applies only to a click; `s` names the tool and settings to create with. +pub(crate) fn create_params(app: &PhotocraftApp, is_box: bool, s: &TypeSnapshot) -> serde_json::Value { + let mask = s.tool.is_type_mask(); // Preferences ▸ Type: "Fill new type layers with placeholder text" (on by default). The // Horizontal Type Mask gets the Type tool's placeholder, as Photoshop's does (#12072); the // vertical mask's placeholder is not measured yet, so it keeps starting empty. - let placeholder = app.ui.tool != crate::state::Tool::VerticalTypeMask && app.session.prefs().type_.fill_new_type_layers_with_placeholder; + let placeholder = s.tool != crate::state::Tool::VerticalTypeMask && s.placeholder; let text = if placeholder { PLACEHOLDER } else { "" }; - let mut p = default_style_params(app); + let mut p = default_style_params(app, &s.options); // #12077: the measured case - a click, not a paragraph box, with the Horizontal Type Mask over // a horizontal text layer - starts the mask in that layer's font, style and size, as the // options bar shows them for the layer. The vertical mask and a box drag are not measured in // the issue, so they keep today's tool options. if mask && !is_box - && app.ui.tool == crate::state::Tool::HorizontalTypeMask + && s.tool == crate::state::Tool::HorizontalTypeMask && let Some(style) = mask_style_from_active_layer(app) && let (Some(params), Some(style)) = (p.as_object_mut(), style.as_object()) { params.extend(style.clone()); } p["text"] = json!(text); - p["orientation"] = json!(if app.ui.tool.is_vertical_type() { "vertical" } else { "horizontal" }); + p["orientation"] = json!(if s.tool.is_vertical_type() { "vertical" } else { "horizontal" }); + p +} + +/// Create the type layer `p` describes, and finish what a released Type-tool gesture does with it: +/// the path target of a click, the options bar's antialiasing, the Type Mask tools' hidden working +/// layer, and the edit session with the placeholder selected. `s` is the snapshot `p` was built +/// from, so the antialiasing and the Type Mask handling follow those settings and not the live ones. +/// The id of the new layer, or why creating it failed (the status bar already says so, since +/// [`PhotocraftApp::run`] reported it). +pub(crate) fn create_layer(app: &mut PhotocraftApp, mut p: serde_json::Value, target: Option, s: &TypeSnapshot) -> Result { + let o = &s.options; + let mask = s.tool.is_type_mask(); + let n = p.get("text").and_then(serde_json::Value::as_str).unwrap_or("").chars().count(); + let key = session_key(app); + p["coalesce"] = json!(key); + let v = app.run("type.create", p)?; + let Some(id) = v.get("layer").and_then(serde_json::Value::as_u64) else { + return Err("type.create returned no layer".to_string()); + }; + // A failed follow-up leaves point text; say why instead of passing over it. + let follow_up = match &target { + Some(PathClick::Area { shape }) => app.run("type.fillPath", json!({"layer": id, "shape": shape, "coalesce": key})), + Some(PathClick::OnPath { shape, subpath, start }) => { + app.run("type.attachToPath", json!({"layer": id, "shape": shape, "subpath": subpath, "start": start, "coalesce": key})) + } + None => Ok(serde_json::Value::Null), + }; + if let Err(e) = follow_up { + app.ui.status = e; + app.ui.status_error = true; + } + if o.type_aa != "sharp" { + let _ = app.run("type.edit", json!({"layer": id, "antialias": o.type_aa, "coalesce": key})); + } + // A Type Mask's text is a hidden working layer: the canvas shows the mask overlay + // instead, and committing turns it into the selection. + if mask { + let _ = app.run("layer.setProps", json!({"layer": id, "visible": false, "coalesce": key})); + } + // Like Photoshop: the placeholder is selected, so typing replaces it. + app.ui.text_edit = Some(TextEdit { layer: id, document: active_doc_id(app), caret: n, anchor: 0, session: key, created: true, mask }); + app.ui.text_edit_return_tool = None; + Ok(id) +} + +/// A release that makes new text: from `start` to `end` in document units. A drag of at least 4 screen pixels both +/// ways makes a paragraph box; anything less is a click, which makes point text, or text on or in the path under it. +/// `alt_at_press` is ⌥ held at the press of the gesture. +fn create_text(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2], alt_at_press: bool) { + let (w, h) = ((end[0] - start[0]).abs(), (end[1] - start[1]).abs()); + let is_box = makes_box(app, start, end); + // Photoshop (#12044): Alt+drag with the Type tool sizes the new paragraph box in the + // Paragraph Text Size dialog instead of committing the drag, and its OK creates the text. + // Measured for the horizontal Type tool alone, so the vertical and Type Mask tools keep the + // plain drag; Alt+click (a drag too small for a box) stays point text. + if alt_at_press && is_box && app.ui.tool == crate::state::Tool::Type { + crate::paragraph_text_size::open(app, [start[0].min(end[0]), start[1].min(end[1])], w, h); + return; + } + 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 && !is_box { path_target(app, start[0], start[1]) } else { None }; + // A plain drag or click reads the tool, its options and the placeholder preference as they + // stand at its release, as they always have (#12044). + let snapshot = TypeSnapshot::live(app); + let mut p = create_params(app, is_box, &snapshot); if is_box { p["box"] = json!([start[0].min(end[0]).round(), start[1].min(end[1]).round(), w.round(), h.round()]); } else { p["x"] = json!(start[0].round()); p["y"] = json!(start[1].round()); } - let key = session_key(app); - p["coalesce"] = json!(key); - if let Ok(v) = app.run("type.create", p) - && let Some(id) = v.get("layer").and_then(serde_json::Value::as_u64) - { - // A failed follow-up leaves point text; say why instead of passing over it. - let follow_up = match &target { - Some(PathClick::Area { shape }) => app.run("type.fillPath", json!({"layer": id, "shape": shape, "coalesce": key})), - Some(PathClick::OnPath { shape, subpath, start }) => { - app.run("type.attachToPath", json!({"layer": id, "shape": shape, "subpath": subpath, "start": start, "coalesce": key})) - } - None => Ok(serde_json::Value::Null), - }; - if let Err(e) = follow_up { - app.ui.status = e; - app.ui.status_error = true; - } - if o.type_aa != "sharp" { - let _ = app.run("type.edit", json!({"layer": id, "antialias": o.type_aa, "coalesce": key})); - } - // A Type Mask's text is a hidden working layer: the canvas shows the mask overlay - // instead, and committing turns it into the selection. - if mask { - let _ = app.run("layer.setProps", json!({"layer": id, "visible": false, "coalesce": key})); - } - // Like Photoshop: the placeholder is selected, so typing replaces it. - let n = text.chars().count(); - app.ui.text_edit = Some(TextEdit { layer: id, document: active_doc_id(app), caret: n, anchor: 0, session: key, created: true, mask }); - app.ui.text_edit_return_tool = None; - } + let _ = create_layer(app, p, target, &snapshot); } impl CanvasTool for TypeTool<'_> { @@ -290,6 +351,7 @@ impl CanvasTool for TypeTool<'_> { let ctx = self.scope.ctx().clone(); let action = self.scope.with_app(|app| press_at(app, &ctx, at.x, at.y, pointer.mods)); self.state.press = (action == ToolAction::Claimed).then_some(at); + self.state.press_alt = action == ToolAction::Claimed && pointer.mods.alt; action } @@ -311,11 +373,12 @@ impl CanvasTool for TypeTool<'_> { fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { let Some(start) = self.state.press.take() else { return }; + let alt = std::mem::take(&mut self.state.press_alt); let Some(space) = cx.space() else { return }; let end = space.view.to_doc(pointer.pos); let ctx = self.scope.ctx().clone(); self.scope.with_app(|app| { - create_text(app, [start.x, start.y], [end.x, end.y]); + create_text(app, [start.x, start.y], [end.x, end.y], alt); // The new session's editor takes the keyboard from the pass it opens, as an edit of existing text does. if app.ui.text_edit.is_some() { super::editing::focus_editor(&ctx); @@ -325,6 +388,7 @@ impl CanvasTool for TypeTool<'_> { fn cancel(&mut self, _reason: CancelReason, _cx: &mut ToolContext<'_>) { self.state.press = None; + self.state.press_alt = false; self.state.began_with_session = false; } diff --git a/crates/ui-egui/src/tools/type_tool/tests.rs b/crates/ui-egui/src/tools/type_tool/tests.rs index 35adeb9e3da..f0a254b9507 100644 --- a/crates/ui-egui/src/tools/type_tool/tests.rs +++ b/crates/ui-egui/src/tools/type_tool/tests.rs @@ -56,7 +56,7 @@ fn layer_text(app: &PhotocraftApp) -> String { fn stacked_variant(app: &mut PhotocraftApp, s: &str) -> LayerId { // A click on the stack's spot would edit the text under it, so the layer is made where the click would. app.ui.text_edit = None; - let mut p = default_style_params(app); + let mut p = default_style_params(app, &app.ui.tool_options); p["text"] = json!(s); p["orientation"] = json!("horizontal"); p["x"] = json!(50.0);