Skip to content

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

Edit type layers by double-clicking their thumbnails (#598)

才倾梦华V3d23a708c2e8
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index 7faf10d1b..206e1c54a 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -2060,3 +2060,4 @@ cameraRaw Color Barvy
Patch Tool Nástroj záplata
Patch: Záplata:
Lasso around an area, then drag the selection Obtáhněte oblast lasem a pak přetáhněte výběr
+ Edit Type Upravit text
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index b801d812b..a734ebb32 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -2137,3 +2137,4 @@ cameraRaw Amount Cantidad
Patch Tool Herramienta Parche
Patch: Parche:
Lasso around an area, then drag the selection Rodee un área con el lazo y arrastre la selección
+ Edit Type Editar texto
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index 6ceec624c..453fa2ad2 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -2490,3 +2490,4 @@ cameraRaw Blending Fusion
4 x 4 4 × 4
5 x 5 5 × 5
Grid: Grille :
+ Edit Type Modifier le texte
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index ccf5e604b..40aff30af 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -2477,3 +2477,4 @@ cameraRaw Blending Pembauran
4 x 4 4 × 4
5 x 5 5 × 5
Grid: Kisi-kisi:
+ Edit Type Edit Teks
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index 984a2f8e6..6cd6fbe16 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -2043,3 +2043,4 @@ cameraRaw Color カラー
Patch Tool パッチツール
Patch: パッチ:
Lasso around an area, then drag the selection 投げ縄で範囲を囲み、選択範囲をドラッグします
+ Edit Type 文字を編集
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 29b335bb8..29159ae71 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -2337,3 +2337,4 @@ cameraRaw Roughness Неровность
Patch Tool Заплатка
Patch: Заплатка:
Lasso around an area, then drag the selection Обведите область лассо, затем перетащите выделение
+ Edit Type Редактировать текст
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index d94dd811d..62816f08c 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -2069,3 +2069,4 @@ cameraRaw Blending 混合
GPU Backend GPU 后端
Details 详细信息
Rendering mode 渲染模式
+ Edit Type 编辑文字
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index d91cb51a3..5168fe32c 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -2038,3 +2038,4 @@ cameraRaw Blending 混合
Patch Tool 修補工具
Patch: 修補:
Lasso around an area, then drag the selection 用套索圈出區域,然後拖曳選取範圍
+ Edit Type 編輯文字
diff --git a/crates/ui-egui/src/layer_row_ui.rs b/crates/ui-egui/src/layer_row_ui.rs
index 3e4ed8917..2696d6cb6 100644
--- a/crates/ui-egui/src/layer_row_ui.rs
+++ b/crates/ui-egui/src/layer_row_ui.rs
@@ -333,3 +333,6 @@ mod tests;
#[cfg(test)]
mod rename_tests;
+
+#[cfg(test)]
+mod edit_tests;
diff --git a/crates/ui-egui/src/layer_row_ui/edit_tests.rs b/crates/ui-egui/src/layer_row_ui/edit_tests.rs
new file mode 100644
index 000000000..feb5a87b4
--- /dev/null
+++ b/crates/ui-egui/src/layer_row_ui/edit_tests.rs
@@ -0,0 +1,160 @@
+//! Type editing through real Layers panel mouse and keyboard events (#537).
+
+use egui::{Event, Modifiers, PointerButton, Pos2, pos2, vec2};
+use egui_kittest::Harness;
+use photocraft_doc::{LayerContent, LayerId};
+use serde_json::json;
+
+use crate::PhotocraftApp;
+
+fn harness(session: photocraft_engine::Session, ppp: f32) -> Harness<'static, PhotocraftApp> {
+ let mut h =
+ Harness::builder().with_size(vec2(1440.0, 900.0)).with_pixels_per_point(ppp).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(move |cc| {
+ PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
+ PhotocraftApp::new(session, crate::Services::default())
+ });
+ let ctx = h.ctx.clone();
+ let (req, _rx) = crate::control::ControlRequest::new("ui.set", json!({"dock": {"collapsed": ["color", "properties", "history", "navigator"]}}));
+ crate::control::handle(h.state_mut(), &ctx, &req);
+ h.run_steps(8);
+ h
+}
+
+fn click(h: &mut Harness<'_, PhotocraftApp>, at: Pos2, button: PointerButton) {
+ h.hover_at(at);
+ h.step();
+ for pressed in [true, false] {
+ h.event(Event::PointerButton { pos: at, button, pressed, modifiers: Modifiers::NONE });
+ h.step();
+ }
+ h.run_steps(3);
+}
+
+fn double_click(h: &mut Harness<'_, PhotocraftApp>, at: Pos2) {
+ for _ in 0..40 {
+ h.step();
+ }
+ click(h, at, PointerButton::Primary);
+ click(h, at, PointerButton::Primary);
+}
+
+fn row(h: &Harness<'_, PhotocraftApp>, id: u64) -> super::RowRects {
+ super::recorded(&h.ctx).into_iter().find(|r| r.layer == id).expect("layer row drawn")
+}
+
+fn thumbnail(h: &Harness<'_, PhotocraftApp>, id: u64) -> Pos2 {
+ let r = row(h, id).row;
+ // Top-level Pro row: 6 pt padding, 28 pt eye column, 24 pt layer thumbnail.
+ pos2(r.left() + 6.0 + 28.0 + 12.0, r.center().y)
+}
+
+fn session() -> photocraft_engine::Session {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 640, "height": 480})).unwrap();
+ s
+}
+
+fn text(h: &Harness<'_, PhotocraftApp>, id: u64) -> String {
+ match &h.state().session.active().unwrap().doc.layer(LayerId(id)).unwrap().content {
+ LayerContent::Text(t) => t.text.clone(),
+ _ => panic!("expected text layer"),
+ }
+}
+
+#[test]
+fn text_thumbnail_opens_inline_editing_and_typing_is_one_undo_step() {
+ for ppp in [1.0, 2.0] {
+ let mut s = session();
+ let id = s.execute("type.create", json!({"text": "Hello 世界", "size": 48, "x": 100, "y": 180})).unwrap()["layer"].as_u64().unwrap();
+ s.execute("layer.new.layer", json!({"name": "Other active layer"})).unwrap();
+ let steps = s.active().unwrap().history.entries().len();
+ let layers = s.active().unwrap().doc.layers.len();
+ let mut h = harness(s, ppp);
+ let at = thumbnail(&h, id);
+ double_click(&mut h, at);
+ assert_eq!(h.state().ui.tool, crate::state::Tool::Type);
+ let ed = h.state().ui.text_edit.as_ref().expect("inline text editor");
+ assert_eq!((ed.layer, ed.anchor, ed.caret, ed.created), (id, 0, 8, false));
+ assert!(h.state().ui.dialogs.is_empty(), "no Layer Style dialog");
+ assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps, "entering native text adds no edit");
+ assert_eq!(h.state().session.active().unwrap().doc.layers.len(), layers);
+ for typed in ["New", " text"] {
+ h.event(Event::Text(typed.into()));
+ h.run_steps(2);
+ }
+ assert_eq!(text(&h, id), "New text");
+ assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps + 1);
+ crate::type_tool::commit(h.state_mut());
+ assert!(h.state_mut().session.undo());
+ assert_eq!(text(&h, id), "Hello 世界");
+ }
+}
+
+#[test]
+fn text_name_still_renames_and_mask_double_click_does_not_edit_text() {
+ let mut s = session();
+ let id = s.execute("type.create", json!({"text": "Hello", "name": "Title"})).unwrap()["layer"].as_u64().unwrap();
+ s.execute("layer.layerMask.revealAll", json!({})).unwrap();
+ let mut h = harness(s, 1.0);
+ let at = row(&h, id).name.unwrap().center();
+ double_click(&mut h, at);
+ assert_eq!(super::renaming(&h.ctx), Some(id));
+ assert!(h.state().ui.text_edit.is_none());
+ super::end_rename(&h.ctx, false);
+ h.run_steps(2);
+ let masks = crate::mask_thumbs_ui::recorded(&h.ctx, id).unwrap().0;
+ let at = masks.iter().find(|(kind, _)| *kind == crate::mask_thumbs_ui::MaskKind::Pixel).unwrap().1.center();
+ double_click(&mut h, at);
+ assert!(h.state().ui.text_edit.is_none());
+ assert!(h.state().ui.dialogs.is_empty());
+}
+
+#[test]
+fn edit_type_command_rejects_missing_or_non_type_layers_without_changes() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ for has_document in [false, true] {
+ if has_document {
+ app.run("file.new", json!({"width": 32, "height": 24})).unwrap();
+ }
+ let tool = app.ui.tool;
+ assert!(!crate::menus::is_enabled(&app, "type.editText"));
+ assert!(crate::menus::invoke(&mut app, &ctx, "type.editText", json!({})).is_err());
+ assert_eq!(app.ui.tool, tool);
+ assert!(app.ui.text_edit.is_none());
+ }
+}
+
+#[test]
+fn reentering_type_edit_keeps_the_session_and_cancel_restores_cached_pixels() {
+ let mut s = session();
+ let id = s.execute("type.create", json!({"text": "Hello", "size": 48, "x": 100, "y": 180})).unwrap()["layer"].as_u64().unwrap();
+ // Stand-in for a PSD's retained Photoshop rendering, displaced from our glyph layout.
+ let cached = {
+ let st = s.active_mut().unwrap();
+ let mut doc = (*st.doc).clone();
+ let LayerContent::Text(t) = &mut doc.layer_mut(LayerId(id)).unwrap().content else { panic!("text") };
+ let mut moved = t.clone();
+ moved.transform = photocraft_geom::Affine::translate(350.0, 280.0);
+ let cache = photocraft_text::shared().lock().unwrap().render(&moved, 72.0, photocraft_color::PixelFormat::RGBA8).1.surface;
+ t.cache = Some(cache.clone());
+ st.doc = std::sync::Arc::new(doc);
+ st.revision += 1;
+ cache
+ };
+ let steps = s.active().unwrap().history.entries().len();
+ let mut h = harness(s, 1.0);
+ let at = thumbnail(&h, id);
+ double_click(&mut h, at);
+ let key = h.state().ui.text_edit.as_ref().expect("inline text editor").session.clone();
+ h.event(Event::Text("Changed".into()));
+ h.run_steps(2);
+ double_click(&mut h, at);
+ assert_eq!(h.state().ui.text_edit.as_ref().unwrap().session, key);
+ assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps + 1);
+ crate::type_tool::cancel(h.state_mut());
+ assert_eq!(text(&h, id), "Hello");
+ let st = h.state().session.active().unwrap();
+ let LayerContent::Text(t) = &st.doc.layer(LayerId(id)).unwrap().content else { panic!("text") };
+ assert_eq!(t.cache.as_ref().unwrap().content_bounds(), cached.content_bounds());
+}
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index e8a491dc1..36dd85dfb 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -32,6 +32,7 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[
("view.show.targetPath", "Target Path", &["View", "Show"], Some("Cmd+Shift+H")),
("view.screenMode.cycle", "Cycle Screen Mode", &[], Some("F")),
("edit.freeTransformCopy", "Free Transform a Copy", &[], Some("Cmd+Alt+T")),
+ ("type.editText", "Edit Type", &[], None),
("view.zoomIn", "Zoom In", &["View"], Some("Cmd+=")),
("view.zoomOut", "Zoom Out", &["View"], Some("Cmd+-")),
("view.fitOnScreen", "Fit on Screen", &["View"], Some("Cmd+0")),
@@ -310,6 +311,13 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:
"layer.layerStyle.blendingOptions" if params.as_object().is_none_or(|o| o.is_empty()) => {
crate::layer_style::open(app, Some(crate::layer_style::BLENDING)).map(|d| json!({"dialog": d})).ok_or_else(|| "no active layer".to_string())
}
+ "type.editText" => {
+ crate::type_tool::edit_active(app)?;
+ if let Some(focus) = ctx.memory(|m| m.focused()) {
+ ctx.memory_mut(|m| m.surrender_focus(focus));
+ }
+ Ok(Value::Null)
+ }
// Layer Content Options…: the adjustment / fill controls live in Properties.
"layer.layerContentOptions" => {
let r = app.run(id, params)?;
@@ -479,6 +487,11 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool {
"edit.paste" | "file.newFromClipboard" => app.session.is_enabled(id) || app.services.clipboard_get_image.is_some(),
"edit.pasteSpecial.pasteInPlace" => app.session.is_enabled(id) || (app.services.clipboard_get_image.is_some() && app.session.active().is_some()),
"select.selectAndMask" => app.session.is_enabled("select.refineEdge"),
+ "type.editText" => app
+ .session
+ .active()
+ .and_then(|s| s.active_layer.and_then(|id| s.doc.layer(id)))
+ .is_some_and(|l| matches!(l.content, photocraft_doc::LayerContent::Text(_))),
"select.transformSelection" => app.ui.transform.is_none() && app.session.is_enabled("select.transformSelection"),
i if (i.starts_with("view.zoom") || i == "view.fitOnScreen" || i == "view.actualPixels") || i == "window.newWindowForDocument" => {
app.session.active().is_some()
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index 24080fa98..63200695a 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -1716,7 +1716,8 @@ fn layer_row(
}
// Double-click: the name renames in place; the Background, which can't be renamed while
// it's locked, becomes a normal layer; an adjustment or fill thumbnail opens its settings and
- // a Smart Object thumbnail its contents; anywhere else on the row opens Layer Style (#350).
+ // a Smart Object thumbnail its contents, and a type thumbnail edits its text; anywhere else
+ // on the row opens Layer Style (#350, #537).
// The first click already made this the active layer.
if resp.double_clicked() {
let pos = resp.interact_pointer_pos();
@@ -1732,6 +1733,7 @@ fn layer_row(
let id = match &l.content {
LayerContent::Adjustment(_) | LayerContent::Fill(_) if on(thumb) => "layer.layerContentOptions",
LayerContent::Smart(_) if on(thumb) => "layer.smartObjects.editContents",
+ LayerContent::Text(_) if on(thumb) => "type.editText",
_ => "layer.layerStyle.blendingOptions",
};
if crate::menus::is_enabled(app, id) {
diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs
index 0489f5608..fe5e83e52 100644
--- a/crates/ui-egui/src/type_tool.rs
+++ b/crates/ui-egui/src/type_tool.rs
@@ -88,14 +88,36 @@ fn shows_own_layout(doc: &Document, t: &TextLayer) -> bool {
/// Start editing an existing type layer. Like Photoshop, editing shows the text as the type
/// engine lays it out, so a PSD layer is re-rendered first (inside the edit session's history
/// step, so Cancel brings Photoshop's pixels back).
-fn begin_edit(app: &mut PhotocraftApp, id: LayerId, key: &str) {
- let Some(st) = app.session.active() else { return };
+fn begin_edit(app: &mut PhotocraftApp, id: LayerId, key: &str) -> Result<(), String> {
+ let st = app.session.active().ok_or("no document open")?;
let doc = st.doc.clone();
if let Some(t) = text_layer(&doc, id)
&& !shows_own_layout(&doc, t)
{
- let _ = app.run("type.edit", json!({"layer": id.0, "coalesce": key}));
+ app.run("type.edit", json!({"layer": id.0, "coalesce": key}))?;
}
+ Ok(())
+}
+
+/// Edit the active type layer from its thumbnail, selecting all text like Photoshop. Reuse the
+/// current session when already editing it, so Cancel and undo still cover the whole edit.
+pub fn edit_active(app: &mut PhotocraftApp) -> Result<(), String> {
+ let st = app.session.active().ok_or("no document open")?;
+ let id = st.active_layer.ok_or("no active layer")?;
+ let n = text_layer(&st.doc, id).ok_or("active layer is not a type layer")?.text.chars().count();
+ if app.ui.text_edit.as_ref().is_none_or(|ed| ed.layer != id.0) {
+ commit(app);
+ let key = session_key(app);
+ begin_edit(app, id, &key)?;
+ app.ui.text_edit = Some(TextEdit { layer: id.0, caret: n, anchor: 0, session: key, created: false, dragging: false, resize: None, preedit: None });
+ } else if let Some(ed) = app.ui.text_edit.as_mut() {
+ ed.anchor = 0;
+ ed.caret = n;
+ }
+ app.ui.tool = crate::state::Tool::Type;
+ app.ui.mask_target = false;
+ app.ui.vector_mask_target = false;
+ Ok(())
}
fn hit_offset(app: &mut PhotocraftApp, id: LayerId, x: f64, y: f64) -> usize {
@@ -202,7 +224,9 @@ pub fn pointer_down(app: &mut PhotocraftApp, x: f64, y: f64, shift: bool) -> boo
if let Some(id) = hit_layer(app, x, y) {
let _ = app.session.select_layer(id);
let key = session_key(app);
- begin_edit(app, id, &key);
+ if begin_edit(app, id, &key).is_err() {
+ return true;
+ }
let off = hit_offset(app, id, x, y);
app.ui.text_edit = Some(TextEdit { layer: id.0, caret: off, anchor: off, session: key, created: false, dragging: true, resize: None, preedit: None });
return true;
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 264d33fb5..f70db1822 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -77,6 +77,10 @@ UI-level commands (`view.zoomIn`, `window.theme.pro`, `edit.search`, …) are al
Commands that read or write files by path, instead of through the automation roots, are refused with "automation command `…` uses ambient filesystem paths and is disabled; use capability-scoped document methods". That covers every `file.*` command except `file.new`, the `file.close*` commands and a few path-free ones such as `file.fileInfo`, so `file.open`, `file.save`, `file.saveAs` and `file.saveACopy` always fail here: open and save with `app.open` / `app.save`. Path parameters of other commands (`layer.exportAs {path}`, `filter.distort.displace {mapPath}`, …) are refused the same way, and the desktop app also refuses `image.mode.*`, which can load the colour profiles set in its preferences. The rules are in `crates/automation/src/workspace.rs`.
+`type.editText` starts inline editing of the active type layer and selects all its text, like
+double-clicking its thumbnail in Layers. Text input, Commit and Cancel use the existing Type tool
+editing session; non-type layers return an error without changing the tool or document.
+
### Background jobs (#210)
Long commands (every `filter.*`, `edit.contentAwareFill`, `edit.contentAwareScale`, `file.automate.photomerge`, `brush.presets.importAbr`) and file opens run as background jobs in the desktop app: the window keeps drawing, the status bar shows progress with a Cancel button, and jobs that lock the active document show a modal progress dialog (Esc cancels). `engine.execute`, `ui.menu.invoke` and `ui.dialog.confirm` still wait for the result by default; pass `"wait": false` to get `{job, pending: true}` at once, then poll `jobs.list` (`state`: running, done, failed, cancelled; `progress` 0–1; the result or error) and stop it with `jobs.cancel {job}`. A cancelled or failed job leaves the document unchanged. While a job runs, commands that would edit its document fail with "… is still running on this document". `ui.inspect` reports `jobs` (running jobs, opening files). Set `PHOTOCRAFT_INLINE_JOBS=1` to run everything inline.