Skip to content

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

Type: ⇧⌘> / ⇧⌘< change the type size (and work on Nordic/German layouts) (#2402)

Simon Falentin Olesen80519e1a1707
diff --git a/crates/engine/src/type_cmds.rs b/crates/engine/src/type_cmds.rs
index d538a6afc..3357faa9a 100644
--- a/crates/engine/src/type_cmds.rs
+++ b/crates/engine/src/type_cmds.rs
@@ -897,9 +897,52 @@ pub fn specs() -> Vec<CommandSpec> {
}
},
},
+ size_key("type.increaseSize", "Increase Type Size", "Cmd+Shift+.", |s, p| step_size(s, p, true, 2.0)),
+ size_key("type.decreaseSize", "Decrease Type Size", "Cmd+Shift+,", |s, p| step_size(s, p, false, 2.0)),
+ size_key("type.increaseSizeMore", "Increase Type Size by 10", "Cmd+Alt+Shift+.", |s, p| step_size(s, p, true, 10.0)),
+ size_key("type.decreaseSizeMore", "Decrease Type Size by 10", "Cmd+Alt+Shift+,", |s, p| step_size(s, p, false, 10.0)),
]
}
+fn has_type_layer(s: &Session) -> std::result::Result<(), String> {
+ let st = s.active().ok_or("no document open")?;
+ match st.active_layer.and_then(|id| st.doc.layer(id)) {
+ Some(l) if matches!(l.content, LayerContent::Text(_)) => Ok(()),
+ _ => Err("the active layer is not a type layer".into()),
+ }
+}
+
+/// Photoshop's ⇧⌘> / ⇧⌘< (⌥ for bigger steps). On a US keyboard > and < share the . and , keys.
+fn size_key(id: &'static str, label: &'static str, shortcut: &'static str, run: fn(&mut Session, &Value) -> Result<Value>) -> CommandSpec {
+ CommandSpec {
+ id,
+ label,
+ menu: &[],
+ shortcut: Some(shortcut),
+ params: r##"{"layer":id?,"range":[startChar,endChar]? (default all),"by":pt? (as the layer appears)}"##,
+ enabled: has_type_layer,
+ journal: true,
+ run,
+ }
+}
+
+/// Grows or shrinks every character in the range by `by` points as the layer appears, so mixed
+/// sizes keep their differences and a scaled layer steps in the points its size field shows.
+fn step_size(s: &mut Session, p: &Value, up: bool, default_by: f32) -> Result<Value> {
+ let id = layer_id(s, p)?;
+ let by = f32p(p, "by").filter(|v| v.is_finite()).unwrap_or(default_by).abs().min(TYPE_SIZE_MAX_PT as f32);
+ with_text_layer(s, p, "Change Type Size", |t, _, _| {
+ let m = t.transform.m;
+ let scale = (m[0] * m[3] - m[1] * m[2]).abs().sqrt() as f32;
+ let scale = if scale.is_finite() && scale > 1e-3 { scale } else { 1.0 };
+ let delta = if up { by } else { -by } / scale;
+ let (a, b) = range_param(&t.text, p);
+ style_range(t, a, b, &|st| st.size_pt = (st.size_pt + delta).clamp(TYPE_SIZE_MIN_PT as f32, TYPE_SIZE_MAX_PT as f32));
+ Ok(())
+ })?;
+ info(s, &json!({ "layer": id.0 }))
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -1036,6 +1079,42 @@ mod tests {
assert_eq!(layer_name_of(&s, id), "Type Layer");
}
+ #[test]
+ fn size_keys_step_each_run_and_respect_layer_scale() {
+ let mut s = session();
+ let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello world", "size": 12})).unwrap()["layer"].as_u64().unwrap();
+ s.execute("type.setStyle", json!({"layer": id, "range": [6, 11], "size": 20})).unwrap();
+ s.execute("type.increaseSize", json!({})).unwrap();
+ let sizes = |s: &Session| text_layer(s, id).char_runs().iter().map(|r| r.style.size_pt).collect::<Vec<_>>();
+ assert_eq!(sizes(&s), vec![14.0, 22.0], "every run grows by 2 pt");
+ s.execute("type.decreaseSizeMore", json!({"range": [0, 5]})).unwrap();
+ assert_eq!(sizes(&s)[0], 4.0, "only the range, by 10 pt");
+ for _ in 0..2 {
+ s.execute("type.decreaseSize", json!({"range": [0, 5]})).unwrap();
+ }
+ assert_eq!(sizes(&s)[0], TYPE_SIZE_MIN_PT as f32, "never below the smallest size");
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(sizes(&s)[0], 2.0, "one undo step per press");
+
+ let scaled = s.execute("type.create", json!({"x": 0, "y": 80, "text": "Big", "size": 12})).unwrap()["layer"].as_u64().unwrap();
+ s.execute("type.edit", json!({"layer": scaled, "transform": [2.0, 0.0, 0.0, 2.0, 0.0, 80.0]})).unwrap();
+ s.execute("type.increaseSize", json!({"layer": scaled})).unwrap();
+ assert_eq!(text_layer(&s, scaled).char_runs()[0].style.size_pt, 13.0, "a 200% layer shows 24 pt and steps to 26 pt");
+ }
+
+ #[test]
+ fn size_keys_need_a_type_layer() {
+ let mut s = session();
+ assert!(s.execute("type.increaseSize", json!({})).is_err());
+ let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hi", "size": 12})).unwrap()["layer"].as_u64().unwrap();
+ s.execute("type.increaseSize", json!({"by": "big"})).unwrap();
+ s.execute("type.increaseSize", json!({"by": -3})).unwrap();
+ s.execute("type.decreaseSize", json!({"by": 1e30, "range": [9, 0]})).unwrap();
+ assert_eq!(text_layer(&s, id).char_runs()[0].style.size_pt, TYPE_SIZE_MIN_PT as f32, "bad steps fall back or clamp, never panic");
+ assert_eq!(crate::commands::find("type.increaseSize").and_then(|c| c.shortcut), Some("Cmd+Shift+."));
+ assert_eq!(crate::commands::find("type.decreaseSize").and_then(|c| c.shortcut), Some("Cmd+Shift+,"));
+ }
+
#[test]
fn auto_name_skips_leading_blank_lines() {
let mut s = session();
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index a717a1219..d4e4a5cb1 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -381,6 +381,11 @@ 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())
}
+ // ⇧⌘> / ⇧⌘<: the selected characters while typing, else the whole type layer.
+ "type.increaseSize" | "type.decreaseSize" | "type.increaseSizeMore" | "type.decreaseSizeMore" if params.as_object().is_none_or(|o| o.is_empty()) => {
+ let p = crate::type_tool::with_target(app, json!({})).ok_or("the active layer is not a type layer")?;
+ app.run(id, p)
+ }
// Formatting menus follow an inline text selection when editing. Outside an edit,
// snapshot the selected type layers; explicit automation targets retain their scope.
t if (t.starts_with("type.antiAlias.")
diff --git a/crates/ui-egui/src/shortcut_dispatch.rs b/crates/ui-egui/src/shortcut_dispatch.rs
index 7439d56ce..7191b366d 100644
--- a/crates/ui-egui/src/shortcut_dispatch.rs
+++ b/crates/ui-egui/src/shortcut_dispatch.rs
@@ -201,6 +201,10 @@ fn key_owner(app: &PhotocraftApp, ctx: &egui::Context) -> (bool, usize, bool, bo
(crate::menu_nav::is_open(ctx), app.ui.dialogs.len(), app.discard.is_some(), distort, app.ui.text_edit.is_some())
}
+/// Keys whose shortcuts follow the key's position, as in Photoshop: ⇧⌘. is ⇧⌘> on a US layout,
+/// but types `:` on Nordic and German ones, so its character would never match.
+const POSITIONAL: [Key; 2] = [Key::Period, Key::Comma];
+
/// Dispatch this frame's shortcut presses in the order they arrived (⌘Z then ⌘S undoes, then
/// saves the undone state; #440), consuming each. A press matching several bindings goes to the
/// first in table order (⇧⌘Z before ⌘Z). Stops after a shortcut that hands the keyboard to
@@ -216,8 +220,11 @@ pub fn dispatch_pressed(app: &mut PhotocraftApp, ctx: &egui::Context, focus: Foc
let table: Vec<(String, KeyboardShortcut)> =
bindings(app).into_iter().filter(|(id, sc)| focus.allows(sc) && !(editing && TEXT_OWNED.contains(&id.as_str()))).collect();
let command = |e: &egui::Event| match e {
- egui::Event::Key { key, pressed: true, modifiers, .. } => {
- table.iter().find(|(_, sc)| key_matches(sc, *key, *modifiers)).map(|(id, _)| (id.clone(), *key == Key::Tab))
+ egui::Event::Key { key, physical_key, pressed: true, modifiers, .. } => {
+ let by_position = physical_key
+ .filter(|p| POSITIONAL.contains(p))
+ .and_then(|p| table.iter().find(|(_, sc)| sc.logical_key == p && key_matches(sc, p, *modifiers)));
+ by_position.or_else(|| table.iter().find(|(_, sc)| key_matches(sc, *key, *modifiers))).map(|(id, _)| (id.clone(), *key == Key::Tab))
}
_ => None,
};
diff --git a/crates/ui-egui/src/shortcut_dispatch/tests.rs b/crates/ui-egui/src/shortcut_dispatch/tests.rs
index 84b87bb76..5938421ec 100644
--- a/crates/ui-egui/src/shortcut_dispatch/tests.rs
+++ b/crates/ui-egui/src/shortcut_dispatch/tests.rs
@@ -617,3 +617,37 @@ fn f6_while_recording_records_a_named_call_not_the_child_steps() {
h.state_mut().run("actions.stop", json!({})).unwrap();
assert_eq!(h.state().session.actions.list[1].steps, [("actions.play".into(), json!({"action":"LivePrint 2R"}))]);
}
+
+/// ⇧⌘> / ⇧⌘< follow the keys' position: a Nordic or German layout reports ⇧⌘. as `:`, which is
+/// also ⇧⌘; (View › Snap) on a US layout. While typing they size only the selected characters.
+#[test]
+fn type_size_keys_follow_key_position_and_the_typed_selection() {
+ let mut h = harness();
+ let st = h.state().session.active().unwrap();
+ let id = st.doc.walk().into_iter().find(|(_, _, l)| matches!(l.content, LayerContent::Text(_))).unwrap().2.id.0;
+ h.state_mut().session.execute("layer.select", json!({"layer": id})).unwrap();
+ let sizes = |h: &Harness<'_, PhotocraftApp>| match &h.state().session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content {
+ LayerContent::Text(t) => t.char_runs().iter().map(|r| (r.len, r.style.size_pt)).collect::<Vec<_>>(),
+ _ => Vec::new(),
+ };
+ let positional = |h: &mut Harness<'_, PhotocraftApp>, key, physical| {
+ let m = platform(Modifiers::COMMAND | Modifiers::SHIFT);
+ h.event(egui::Event::ModifiersChanged(m));
+ h.event(egui::Event::Key { key, physical_key: Some(physical), pressed: true, repeat: false, modifiers: m });
+ h.event(egui::Event::Key { key, physical_key: Some(physical), pressed: false, repeat: false, modifiers: m });
+ h.event(egui::Event::ModifiersChanged(Modifiers::NONE));
+ h.run_steps(2);
+ };
+ let base = sizes(&h)[0].1;
+ positional(&mut h, egui::Key::Colon, egui::Key::Period);
+ assert_eq!(logged(&h), ["type.increaseSize"]);
+ assert_eq!(sizes(&h), [(5, base + 2.0)], "the whole layer grows from the canvas");
+
+ crate::type_tool::edit_active(h.state_mut()).unwrap();
+ if let Some(ed) = h.state_mut().ui.text_edit.as_mut() {
+ (ed.anchor, ed.caret) = (0, 2);
+ }
+ positional(&mut h, egui::Key::Semicolon, egui::Key::Comma);
+ assert_eq!(logged(&h), ["type.decreaseSize"]);
+ assert_eq!(sizes(&h), [(2, base), (3, base + 2.0)], "only the selected \"He\" shrinks");
+}
diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs
index 069bd9d78..44db2c9b9 100644
--- a/crates/ui-egui/src/type_tool.rs
+++ b/crates/ui-egui/src/type_tool.rs
@@ -1060,6 +1060,20 @@ fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, props: serde_json::Value)
let _ = app.run("type.setStyle", p);
}
+/// `props` aimed at the type target: its layer, the selected characters while typing, and the
+/// typing session's undo step. `None` without a type target.
+pub(crate) fn with_target(app: &PhotocraftApp, mut props: serde_json::Value) -> Option<serde_json::Value> {
+ let (layer, range) = target(app)?;
+ props["layer"] = json!(layer);
+ if let Some(r) = range {
+ props["range"] = json!(r);
+ }
+ if let Some(key) = app.ui.text_edit.as_ref().map(|ed| ed.session.clone()) {
+ props["coalesce"] = json!(key);
+ }
+ Some(props)
+}
+
/// Open the shared Color Picker with a snapshot of the text target. Sampling or cancelling
/// the dialog never changes the text selection, tool colours, or document history.
pub fn open_color_picker(app: &mut PhotocraftApp, rgb: [f32; 3]) -> u64 {