Skip to content

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

Keyboard Shortcuts: import Photoshop .kys sets; first launch takes Photoshop's live set (#1163) (#1987)

texjera81eaa4187c7
diff --git a/Cargo.lock b/Cargo.lock
index f9e6eb96f..0a49f3dd4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4576,6 +4576,7 @@ dependencies = [
"photocraft-text",
"photocraft-vector",
"rayon",
+ "roxmltree",
"serde",
"serde_json",
"sys-locale",
diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs
index 440d57e18..0755d7143 100644
--- a/apps/photocraft/src/main.rs
+++ b/apps/photocraft/src/main.rs
@@ -39,6 +39,7 @@ mod mac_window;
mod linux_libs;
mod logging;
mod monitor_profile;
+mod photoshop_settings;
mod screen_color;
mod services;
// Windows gets pen pressure from winit (WM_POINTER); the web runner has its own listener.
diff --git a/apps/photocraft/src/photoshop_settings.rs b/apps/photocraft/src/photoshop_settings.rs
new file mode 100644
index 000000000..f51447663
--- /dev/null
+++ b/apps/photocraft/src/photoshop_settings.rs
@@ -0,0 +1,156 @@
+//! Photoshop's live keyboard shortcut set on this machine, for the one-time import at first
+//! launch (`photocraft_ui_egui::kys_import::auto_import`).
+//!
+//! Photoshop keeps the set in use as `Keyboard Shortcuts.psp` in its per-version settings
+//! folder; it is the same XML a saved `.kys` holds, named after the set the user chose.
+//! macOS: `~/Library/Preferences/Adobe Photoshop <version> Settings/`. Windows:
+//! `%APPDATA%\Adobe\Adobe Photoshop <version>\Adobe Photoshop <version> Settings\`. Every
+//! installed version has one; the newest version wins (the number in the folder name, then
+//! the file's modification time), since that is the Photoshop the user runs. Linux has no
+//! Photoshop; a copied set is imported by hand (Edit › Keyboard Shortcuts).
+
+use std::ffi::OsString;
+use std::path::{Path, PathBuf};
+
+/// The file is a few tens of kilobytes; anything far larger is not a shortcut set.
+const MAX_BYTES: u64 = 4 << 20;
+
+/// The platform whose folder layout applies.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Platform {
+ Mac,
+ Windows,
+ Other,
+}
+
+const fn this_platform() -> Platform {
+ if cfg!(target_os = "macos") {
+ Platform::Mac
+ } else if cfg!(target_os = "windows") {
+ Platform::Windows
+ } else {
+ Platform::Other
+ }
+}
+
+/// Every `Adobe Photoshop <version> Settings` folder that could hold a set, newest first.
+pub fn settings_dirs(os: Platform, env: &impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
+ let var = |k: &str| env(k).filter(|v| !v.is_empty()).map(PathBuf::from);
+ let mut dirs = match os {
+ Platform::Mac => var("HOME").map(|h| h.join("Library/Preferences")).into_iter().flat_map(|prefs| settings_in(&prefs)).collect::<Vec<_>>(),
+ // `%APPDATA%\Adobe\Adobe Photoshop 2026\Adobe Photoshop 2026 Settings`.
+ Platform::Windows => var("APPDATA")
+ .map(|a| a.join("Adobe"))
+ .into_iter()
+ .flat_map(|adobe| std::fs::read_dir(adobe).into_iter().flatten().flatten().map(|e| e.path()))
+ .filter(|p| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("Adobe Photoshop ")))
+ .flat_map(|p| settings_in(&p))
+ .collect(),
+ Platform::Other => Vec::new(),
+ };
+ dirs.sort_by_key(|d| std::cmp::Reverse(version_key(d)));
+ dirs
+}
+
+/// `Adobe Photoshop <version> Settings` folders directly inside `parent`.
+fn settings_in(parent: &Path) -> Vec<PathBuf> {
+ std::fs::read_dir(parent)
+ .into_iter()
+ .flatten()
+ .flatten()
+ .map(|e| e.path())
+ .filter(|p| {
+ let name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
+ name.starts_with("Adobe Photoshop ") && name.ends_with(" Settings") && p.is_dir()
+ })
+ .collect()
+}
+
+/// Newest first: the version number in the folder name (2026; CC 2019 → 2019; CS6 → 6), then
+/// the set's modification time.
+fn version_key(dir: &Path) -> (u64, std::time::SystemTime) {
+ let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
+ let number = name.split(|c: char| !c.is_ascii_digit()).filter(|s| !s.is_empty()).filter_map(|s| s.parse::<u64>().ok()).max().unwrap_or(0);
+ let modified = std::fs::metadata(dir.join(FILE)).and_then(|m| m.modified()).unwrap_or(std::time::SystemTime::UNIX_EPOCH);
+ (number, modified)
+}
+
+/// The live set's file name inside a settings folder.
+pub const FILE: &str = "Keyboard Shortcuts.psp";
+
+/// The newest install's live set as (path, XML text), `None` without a readable one. A file that
+/// is not a shortcut set (another version's binary `.psp`, a truncated file) is skipped.
+pub fn live_keyboard_shortcuts_on(os: Platform, env: &impl Fn(&str) -> Option<OsString>) -> Option<(String, String)> {
+ settings_dirs(os, env).into_iter().map(|d| d.join(FILE)).find_map(|path| {
+ let len = std::fs::metadata(&path).ok()?.len();
+ if len > MAX_BYTES {
+ return None;
+ }
+ let text = std::fs::read_to_string(&path).ok()?;
+ text.contains("<photoshop-keyboard-shortcuts").then(|| (path.to_string_lossy().into_owned(), text))
+ })
+}
+
+/// [`live_keyboard_shortcuts_on`] for this platform.
+pub fn live_keyboard_shortcuts(env: &impl Fn(&str) -> Option<OsString>) -> Option<(String, String)> {
+ live_keyboard_shortcuts_on(this_platform(), env)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const SET: &str = "\u{feff}<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<photoshop-keyboard-shortcuts version=\"4\" filename=\"texcuts\" modified=\"1\" multi-undo=\"1\">\n</photoshop-keyboard-shortcuts>\n";
+
+ /// A fresh scratch directory per test (removed first, so a rerun starts clean).
+ fn temp_root(name: &str) -> PathBuf {
+ let d = std::env::temp_dir().join(format!("photocraft-photoshop-settings-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(&d).unwrap();
+ d
+ }
+
+ fn write(dir: &Path, text: &[u8]) {
+ std::fs::create_dir_all(dir).unwrap();
+ std::fs::write(dir.join(FILE), text).unwrap();
+ }
+
+ fn env_for(root: &Path) -> impl Fn(&str) -> Option<OsString> + '_ {
+ move |k| match k {
+ "HOME" => Some(root.join("home").into_os_string()),
+ "APPDATA" => Some(root.join("appdata").into_os_string()),
+ _ => None,
+ }
+ }
+
+ #[test]
+ fn newest_version_wins_on_macos() {
+ let root = temp_root("mac");
+ let prefs = root.join("home/Library/Preferences");
+ write(&prefs.join("Adobe Photoshop 2024 Settings"), SET.as_bytes());
+ write(&prefs.join("Adobe Photoshop 2026 Settings"), SET.replace("texcuts", "newest").as_bytes());
+ write(&prefs.join("Adobe Photoshop CC 2019 Settings"), SET.as_bytes());
+ write(&prefs.join("Adobe Photoshop 2025 Paths"), SET.as_bytes()); // not a Settings folder
+ let env = env_for(&root);
+ let dirs: Vec<String> = settings_dirs(Platform::Mac, &env).iter().map(|d| d.file_name().unwrap().to_string_lossy().into_owned()).collect();
+ assert_eq!(dirs, ["Adobe Photoshop 2026 Settings", "Adobe Photoshop 2024 Settings", "Adobe Photoshop CC 2019 Settings"]);
+ let (path, text) = live_keyboard_shortcuts_on(Platform::Mac, &env).unwrap();
+ assert!(path.replace('\\', "/").ends_with("Adobe Photoshop 2026 Settings/Keyboard Shortcuts.psp"), "{path}");
+ assert!(text.contains("filename=\"newest\""));
+ }
+
+ #[test]
+ fn windows_layout_and_unreadable_sets_are_skipped() {
+ let root = temp_root("win");
+ let adobe = root.join("appdata/Adobe");
+ // The newest install's file is not a shortcut set (binary); the older one is used.
+ write(&adobe.join("Adobe Photoshop 2026/Adobe Photoshop 2026 Settings"), &[0x80, 0x00, 0xff, 0xfe]);
+ write(&adobe.join("Adobe Photoshop 2025/Adobe Photoshop 2025 Settings"), SET.as_bytes());
+ std::fs::create_dir_all(adobe.join("Adobe Illustrator 30/Adobe Illustrator 30 Settings")).unwrap();
+ let env = env_for(&root);
+ let (path, _) = live_keyboard_shortcuts_on(Platform::Windows, &env).unwrap();
+ assert!(path.replace('\\', "/").ends_with("Adobe Photoshop 2025/Adobe Photoshop 2025 Settings/Keyboard Shortcuts.psp"), "{path}");
+ assert!(live_keyboard_shortcuts_on(Platform::Other, &env).is_none());
+ assert!(live_keyboard_shortcuts_on(Platform::Mac, &|_| None).is_none(), "no HOME, no set");
+ }
+}
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs
index e284f6a5d..77df59448 100644
--- a/apps/photocraft/src/services.rs
+++ b/apps/photocraft/src/services.rs
@@ -17,11 +17,12 @@ use std::sync::Arc;
mod recovery_tests;
/// Everything File › Open reads: PhotoCraft, Photoshop and Affinity documents, flat images, and
-/// Photoshop brushes (.abr), gradients (.grd) and swatches (.aco, .ase), which go to the preset libraries.
+/// Photoshop brushes (.abr), gradients (.grd), swatches (.aco, .ase) and keyboard shortcut sets
+/// (.kys), which go to the preset libraries and Edit › Keyboard Shortcuts.
const OPEN_EXTS: &[&str] = &[
"pcraft", "pdn", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm",
- "pam", "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "af",
- "afdesign", "afphoto", "afpub",
+ "pam", "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase",
+ "kys", "af", "afdesign", "afphoto", "afpub",
];
/// Open dialog extensions that also match uppercase and mixed-case names (`IMG_0001.JPG`).
@@ -358,6 +359,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
})
}),
load_prefs: Some(Box::new(|| std::fs::read_to_string(prefs_file()?).ok())),
+ photoshop_shortcuts: Some(Box::new(|| crate::photoshop_settings::live_keyboard_shortcuts(&|k| std::env::var_os(k)))),
save_prefs: Some(Box::new(|text: &str| write_atomic(&prefs_file().ok_or("no config directory")?, text.as_bytes()))),
system_theme: crate::appearance::service(),
append_text: Some(Box::new(|path: &str, text: &str| {
diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml
index 2096bd083..f6b3dd24f 100644
--- a/crates/ui-egui/Cargo.toml
+++ b/crates/ui-egui/Cargo.toml
@@ -34,6 +34,9 @@ serde = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
base64 = "0.22"
+# Edit › Keyboard Shortcuts › Import Photoshop Shortcuts… reads Photoshop's `.kys` XML
+# (already in the tree through egui_extras → resvg → usvg).
+roxmltree = "0.20"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
rayon = { workspace = true }
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index cac622f36..2e7c51cef 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -1321,6 +1321,12 @@
Rename… Přejmenovat…
Resample Převzorkovat
Reset All to Defaults Obnovit vše na výchozí
+ Import Shortcuts… Importovat zkratky…
+ Load a keyboard shortcut set saved as .kys Načíst sadu klávesových zkratek uloženou jako .kys
+ Imported {n} shortcuts from {file}. Click OK to keep them. Importováno zkratek: {n} ze souboru {file}. Klepnutím na OK je ponecháte.
+ {n} commands are not in PhotoCraft. Příkazů, které v PhotoCraftu nejsou: {n}.
+ Keyboard shortcuts imported Klávesové zkratky importovány
+ Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this. Vaše sada klávesových zkratek {set} se zde používá: {n} zkratek se liší od výchozích. Zobrazí je Úpravy › Klávesové zkratky; Obnovit vše na výchozí to vrátí zpět.
Reset Section Obnovit sekci
Reset Transform Obnovit transformaci
Reset to defaults Obnovit výchozí
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index b72dded81..56587d758 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -1305,6 +1305,12 @@
Rename… Umbenennen…
Resample Neu berechnen
Reset All to Defaults Alles auf Standardwerte zurücksetzen
+ Import Shortcuts… Tastaturbefehle importieren…
+ Load a keyboard shortcut set saved as .kys Einen als .kys gespeicherten Tastaturbefehlssatz laden
+ Imported {n} shortcuts from {file}. Click OK to keep them. {n} Tastaturbefehle aus {file} importiert. Mit OK übernehmen.
+ {n} commands are not in PhotoCraft. {n} Befehle gibt es in PhotoCraft nicht.
+ Keyboard shortcuts imported Tastaturbefehle importiert
+ Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this. Dein Tastaturbefehlssatz {set} wird hier verwendet: {n} Tastaturbefehle weichen von den Standardwerten ab. Bearbeiten › Tastaturbefehle zeigt sie; Alles auf Standardwerte zurücksetzen macht es rückgängig.
Reset Section Abschnitt zurücksetzen
Reset Transform Transformation zurücksetzen
Reset to defaults Auf Standardwerte zurücksetzen
diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv
index f127bf31b..5a8e0e03d 100644
--- a/crates/ui-egui/src/i18n/el.tsv
+++ b/crates/ui-egui/src/i18n/el.tsv
@@ -2799,6 +2799,12 @@
Resample Επαναδειγματοληψία
Reselect Επαναφορά προηγούμενης επιλογής
Reset All to Defaults Επαναφορά όλων στις προεπιλογές
+ Import Shortcuts… Εισαγωγή συντομεύσεων…
+ Load a keyboard shortcut set saved as .kys Φόρτωση ενός σετ συντομεύσεων πληκτρολογίου αποθηκευμένου ως .kys
+ Imported {n} shortcuts from {file}. Click OK to keep them. Εισήχθησαν {n} συντομεύσεις από το {file}. Πατήστε OK για να τις κρατήσετε.
+ {n} commands are not in PhotoCraft. {n} εντολές δεν υπάρχουν στο PhotoCraft.
+ Keyboard shortcuts imported Οι συντομεύσεις πληκτρολογίου εισήχθησαν
+ Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this. Το σετ συντομεύσεων πληκτρολογίου {set} χρησιμοποιείται εδώ: {n} συντομεύσεις διαφέρουν από τις προεπιλογές. Το Επεξεργασία › Συντομεύσεις πληκτρολογίου τις δείχνει· η Επαναφορά όλων στις προεπιλογές το αναιρεί.
Reset GPU Backend Επαναφορά συστήματος απόδοσης GPU
Reset Section Επαναφορά ενότητας
Reset Transform Επαναφορά μετασχηματισμού
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index fc99c2366..b389e6413 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -1306,6 +1306,12 @@
Rename… Cambiar nombre…
Resample Remuestrear
Reset All to Defaults Restablecer todo a los valores predeterminados
+ Import Shortcuts… Importar atajos…
+ Load a keyboard shortcut set saved as .kys Cargar un conjunto de atajos de teclado guardado como .kys
+ Imported {n} shortcuts from {file}. Click OK to keep them. Se importaron {n} atajos de {file}. Haz clic en OK para conservarlos.
+ {n} commands are not in PhotoCraft. {n} comandos no existen en PhotoCraft.
+ Keyboard shortcuts imported Atajos de teclado importados
+ Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this. Tu conjunto de atajos de teclado {set} se usa aquí: {n} atajos difieren de los predeterminados. Edición › Atajos de teclado los muestra; Restablecer todo a valores predeterminados lo deshace.
Reset Section Restablecer sección
Reset Transform Restablecer transformación
Reset to defaults Restablecer a los valores predeterminados
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index 789060d4f..fac228bbb 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -1290,6 +1290,12 @@
Rename… Renommer…
Resample Rééchantillonner
Reset All to Defaults Tout réinitialiser aux valeurs par défaut
+ Import Shortcuts… Importer des raccourcis…
+ Load a keyboard shortcut set saved as .kys Charger un jeu de raccourcis clavier enregistré en .kys
+ Imported {n} shortcuts from {file}. Click OK to keep them. {n} raccourcis importés depuis {file}. Cliquez sur OK pour les conserver.
+ {n} commands are not in PhotoCraft. {n} commandes n'existent pas dans PhotoCraft.
+ Keyboard shortcuts imported Raccourcis clavier importés
+ Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this. Votre jeu de raccourcis clavier {set} est utilisé ici : {n} raccourcis diffèrent des valeurs par défaut. Édition › Raccourcis clavier les affiche ; Tout rétablir par défaut annule l'import.
Reset Section Réinitialiser la section
Reset Transform Réinitialiser la transformation
Reset to defaults Réinitialiser aux valeurs par défaut
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index 5a779c728..5b26a435f 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -1284,6 +1284,12 @@
Rename… Ganti Nama…
Resample Resample
Reset All to Defaults Reset Semua ke Default
+ Import Shortcuts… Impor Pintasan…
+ Load a keyboard shortcut set saved as .kys Muat set pintasan keyboard yang disimpan sebagai .kys
+ Imported {n} shortcuts from {file}. Click OK to keep them. {n} pintasan diimpor dari {file}. Klik OK untuk menyimpannya.
+ {n} commands are not in PhotoCraft. {n} perintah tidak ada di PhotoCraft.
+ Keyboard shortcuts imported Pintasan keyboard diimpor
+ Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this. Set pintasan keyboard Anda {set} dipakai di sini: {n} pintasan berbeda dari bawaan. Edit › Pintasan Keyboard menampilkannya; Setel Ulang Semua ke Bawaan membatalkannya.
Reset Section Reset Bagian
Reset Transform Reset Transformasi
Reset to defaults Reset ke default
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 62608d3b7..b0d3279ba 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -1305,6 +1305,12 @@
Rename… Rinomina…
Resample Ricampiona
Reset All to Defaults Ripristina tutto ai predefiniti
+ Import Shortcuts… Importa scelte rapide…
+ Load a keyboard shortcut set saved as .kys Carica un set di scelte rapide da tastiera salvato come .kys
+ Imported {n} shortcuts from {file}. Click OK to keep them. Importate {n} scelte rapide da {file}. Fai clic su OK per conservarle.
+ {n} commands are not in PhotoCraft. {n} comandi non esistono in PhotoCraft.
+ Keyboard shortcuts imported Scelte rapide da tastiera importate
+ Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this. Il tuo set di scelte rapide da tastiera {set} è in uso qui: {n} scelte rapide differiscono dai valori predefiniti. Modifica › Scelte rapide da tastiera le mostra; Ripristina tutto ai valori predefiniti annulla l'importazione.
Reset Section Reimposta sezione
Reset Transform Reimposta trasformazione
Reset to defaults Ripristina predefiniti
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index 42c66a8b3..9f2012745 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -1311,6 +1311,12 @@
Rename… 名前を変更…
Resample 再サンプル
Reset All to Defaults すべて既定に戻す
+ Import Shortcuts… ショートカットを読み込む…
+ Load a keyboard shortcut set saved as .kys .kys として保存されたキーボードショートカットセットを読み込みます
+ Imported {n} shortcuts from {file}. Click OK to keep them. {file} から {n} 個のショートカットを読み込みました。OK をクリックすると保持されます。
+ {n} commands are not in PhotoCraft. {n} 個のコマンドは PhotoCraft にありません。
+ Keyboard shortcuts imported キーボードショートカットを読み込みました
+ Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this. キーボードショートカットセット {set} をここで使用しています。{n} 個のショートカットが既定と異なります。編集 › キーボードショートカットで確認でき、「すべて既定に戻す」で元に戻せます。
Reset Section セクションをリセット
Reset Transform 変形をリセット
Reset to defaults 既定に戻す
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 9b77c05a2..f4c489b41 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -1282,6 +1282,12 @@
Rename… 이름 바꾸기…
Resample 리샘플링
Reset All to Defaults 모두 기본값으로 초기화
+ Import Shortcuts… 단축키 가져오기…
+ Load a keyboard shortcut set saved as .kys .kys로 저장된 키보드 단축키 세트 불러오기
+ Imported {n} shortcuts from {file}. Click OK to keep them. {file}에서 단축키 {n}개를 가져왔습니다. 유지하려면 확인을 클릭하세요.
+ {n} commands are not in PhotoCraft. 명령 {n}개는 PhotoCraft에 없습니다.
+ Keyboard shortcuts imported 키보드 단축키를 가져왔습니다
+ Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this. 키보드 단축키 세트 {set}을(를) 여기서 사용합니다. 단축키 {n}개가 기본값과 다릅니다. 편집 › 키보드 단축키에서 확인할 수 있고, 모두 기본값으로 재설정으로 되돌릴 수 있습니다.
Reset Section 섹션 초기화
Reset Transform 변형 초기화
Reset to defaults 기본값으로 초기화
diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv
index 8af68e5ad..071f517ea 100644
--- a/crates/ui-egui/src/i18n/nl.tsv
+++ b/crates/ui-egui/src/i18n/nl.tsv
@@ -1299,6 +1299,12 @@
Rename… Hernoemen…
Resample Opnieuw bemonsteren
Reset All to Defaults Alles terugzetten naar standaardwaarden
+ Import Shortcuts… Sneltoetsen importeren…
+ Load a keyboard shortcut set saved as .kys Een als .kys opgeslagen sneltoetsenset laden
+ Imported {n} shortcuts from {file}. Click OK to keep them. {n} sneltoetsen geïmporteerd uit {file}. Klik op OK om ze te behouden.
+ {n} commands are not in PhotoCraft. {n} opdrachten bestaan niet in PhotoCraft.
+ Keyboard shortcuts imported Sneltoetsen geïmporteerd
+ Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this. Je sneltoetsenset {set} wordt hier gebruikt: {n} sneltoetsen wijken af van de standaardwaarden. Bewerken › Sneltoetsen toont ze; Alles terugzetten naar standaard maakt dit ongedaan.
Reset Section Sectie herstellen
Reset Transform Transformatie herstellen
Reset to defaults Terugzetten naar standaardwaarden
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index eb3696788..5a8e52404 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -1306,6 +1306,12 @@
Rename… Zmień nazwę…
Resample Przepróbkuj
Reset All to Defaults Przywróć wszystko do wartości domyślnych
+ Import Shortcuts… Importuj skróty…
+ Load a keyboard shortcut set saved as .kys Wczytaj zestaw skrótów klawiaturowych zapisany jako .kys
+ Imported {n} shortcuts from {file}. Click OK to keep them. Zaimportowano skrótów: {n} z pliku {file}. Kliknij OK, aby je zachować.
+ {n} commands are not in PhotoCraft. Poleceń, których nie ma w PhotoCraft: {n}.
+ Keyboard shortcuts imported Zaimportowano skróty klawiaturowe
+ Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this. Twój zestaw skrótów klawiaturowych {set} jest tu używany: skrótów innych niż domyślne: {n}. Edycja › Skróty klawiaturowe je pokazuje; Przywróć wszystkie domyślne cofa import.
Reset Section Resetuj sekcję
Reset Transform Resetuj przekształcenie
Reset to defaults Przywróć wartości domyślne
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index 7293ba6af..c60e0c068 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -1289,6 +1289,12 @@
Rename… Renomear…
Resample Reamostrar
Reset All to Defaults Redefinir tudo para os padrões
+ Import Shortcuts… Importar atalhos…
+ Load a keyboard shortcut set saved as .kys Carregar um conjunto de atalhos de teclado salvo como .kys
+ Imported {n} shortcuts from {file}. Click OK to keep them. {n} atalhos importados de {file}. Clique em OK para mantê-los.
+ {n} commands are not in PhotoCraft. {n} comandos não existem no PhotoCraft.
+ Keyboard shortcuts imported Atalhos de teclado importados
+ Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this. Seu conjunto de atalhos de teclado {set} está em uso aqui: {n} atalhos diferem dos padrões. Editar › Atalhos de teclado os mostra; Redefinir tudo para o padrão desfaz isso.
Reset Section Redefinir seção
Reset Transform Redefinir transformação
Reset to defaults Redefinir para os padrões
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 6966f3f7f..e6785912d 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -532,6 +532,12 @@
Reset Сброс
Reset Section Сбросить раздел
Reset All to Defaults Сбросить всё к значениям по умолчанию
+ Import Shortcuts… Импортировать сочетания клавиш…
+ Load a keyboard shortcut set saved as .kys Загрузить набор сочетаний клавиш, сохранённый как .kys
+ Imported {n} shortcuts from {file}. Click OK to keep them. Импортировано сочетаний: {n} из {file}. Нажмите OK, чтобы сохранить их.
+ {n} commands are not in PhotoCraft. Команд, которых нет в PhotoCraft: {n}.
+ Keyboard shortcuts imported Сочетания клавиш импортированы
+ Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this. Здесь используется ваш набор сочетаний клавиш {set}: сочетаний, отличных от стандартных: {n}. Их показывает Редактирование › Сочетания клавиш; «Сбросить всё к значениям по умолчанию» отменяет импорт.
Defaults restored. Значения по умолчанию восстановлены.
Restore Defaults Восстановить по умолчанию
Restore original size Восстановить исходный размер
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index dea4e8535..b368aba93 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -523,6 +523,12 @@
Reset Скинути
Reset Section Скинути розділ
Reset All to Defaults Скинути все до типових значень
+ Import Shortcuts… Імпортувати сполучення клавіш…
+ Load a keyboard shortcut set saved as .kys Завантажити набір сполучень клавіш, збережений як .kys
+ Imported {n} shortcuts from {file}. Click OK to keep them. Імпортовано сполучень клавіш: {n} із {file}. Натисніть OK, щоб зберегти їх.
+ {n} commands are not in PhotoCraft. Команд, яких немає в PhotoCraft: {n}.
+ Keyboard shortcuts imported Сполучення клавіш імпортовано
+ Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this. Тут використовується ваш набір сполучень клавіш {set}: сполучень, що відрізняються від стандартних: {n}. Їх показує Редагування › Сполучення клавіш; «Скинути все до стандартних» скасовує імпорт.
Defaults restored. Типові значення відновлено.
Restore Defaults Відновити типові значення
Restore original size Відновити початковий розмір
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 346fcc45b..e2fda66dc 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -1315,6 +1315,12 @@
Rename… 重命名…
Resample 重新采样
Reset All to Defaults 全部重置为默认值
+ Import Shortcuts… 导入快捷键…
+ Load a keyboard shortcut set saved as .kys 载入保存为 .kys 的键盘快捷键集
+ Imported {n} shortcuts from {file}. Click OK to keep them. 已从 {file} 导入 {n} 个快捷键。点击“确定”保留。
+ {n} commands are not in PhotoCraft. {n} 个命令在 PhotoCraft 中不存在。
+ Keyboard shortcuts imported 已导入键盘快捷键
+ Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this. 此处正在使用你的键盘快捷键集 {set}:{n} 个快捷键与默认值不同。可在“编辑 › 键盘快捷键”中查看;“全部重置为默认值”可撤销。
Reset Section 重置此部分
Reset Transform 重置变换
Reset to defaults 重置为默认值
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index ccfdfdd87..78e3b6210 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -1312,6 +1312,12 @@
Rename… 重新命名…
Resample 重新取樣
Reset All to Defaults 全部重設為預設值
+ Import Shortcuts… 匯入快速鍵…
+ Load a keyboard shortcut set saved as .kys 載入儲存為 .kys 的鍵盤快速鍵集
+ Imported {n} shortcuts from {file}. Click OK to keep them. 已從 {file} 匯入 {n} 個快速鍵。按一下「確定」即可保留。
+ {n} commands are not in PhotoCraft. {n} 個命令在 PhotoCraft 中不存在。
+ Keyboard shortcuts imported 已匯入鍵盤快速鍵
+ Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this. 此處正在使用你的鍵盤快速鍵集 {set}:{n} 個快速鍵與預設值不同。可在「編輯 › 鍵盤快速鍵」中查看;「全部重設為預設值」可復原。
Reset Section 重設區段
Reset Transform 重設變形
Reset to defaults 重設為預設值
diff --git a/crates/ui-egui/src/kys_import.rs b/crates/ui-egui/src/kys_import.rs
new file mode 100644
index 000000000..110010f6d
--- /dev/null
+++ b/crates/ui-egui/src/kys_import.rs
@@ -0,0 +1,245 @@
+//! Photoshop keyboard shortcut sets (`.kys`, Edit › Keyboard Shortcuts › Save Set) imported
+//! into Edit › Keyboard Shortcuts (#1163): the dialog's Import Photoshop Shortcuts… button,
+//! File › Open and a drop on the window.
+//!
+//! A `.kys` is XML: `<command kind="static|dynamic" name="Gaussian Blur...">` rows, each with
+//! one or more `<shortcut>Control+Opt+Cmd+G</shortcut>`, then the `<tool>` keys. Photoshop
+//! names the command by its menu label alone, so rows are matched to our commands by label.
+//! Where one label sits in several menus (Levels… under Image › Adjustments and Layer › New
+//! Adjustment Layer; All under Select, Edit › Purge, View › Show), the command whose default is
+//! one of the imported keys wins, then the one that has a default at all, then the first in
+//! Photoshop's menu order. Ours are one per command, so a row's first shortcut is the one
+//! kept, unless one of its keys is already the command's default (Zoom In lists `Cmd++`
+//! before `Cmd+=`). Tool keys are not imported: the tool letters are fixed here.
+//!
+//! The import fills the open dialog's overrides, so OK applies them like hand-made changes
+//! (a shortcut moved to a command is taken from its old owner) and Cancel discards them.
+
+use std::collections::{BTreeMap, HashMap};
+
+use serde_json::{Value, json};
+
+use crate::PhotocraftApp;
+
+/// One `<command>` row: Photoshop's label and its shortcuts, first one primary.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct KysCommand {
+ pub name: String,
+ pub shortcuts: Vec<String>,
+}
+
+/// The parsed set: its name, its command rows and how many tools carry a key.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct KysSet {
+ /// The set's name as Photoshop shows it (`texcuts`), from the root's `filename` attribute,
+ /// which a saved set spells `$$$/FileName/Presets/KeyboardCustomization/texcuts=texcuts`.
+ pub name: Option<String>,
+ pub commands: Vec<KysCommand>,
+ pub tool_keys: usize,
+}
+
+/// Parse a `.kys` file (or Photoshop's live `Keyboard Shortcuts.psp`, the same XML). Rows
+/// without a name or a shortcut are skipped.
+pub fn parse(text: &str) -> Result<KysSet, String> {
+ let text = text.trim_start_matches('\u{feff}');
+ let doc = roxmltree::Document::parse(text).map_err(|e| format!("not a keyboard shortcut set (.kys): {e}"))?;
+ let root = doc.root_element();
+ if root.tag_name().name() != "photoshop-keyboard-shortcuts" {
+ return Err("not a keyboard shortcut set (.kys): no <photoshop-keyboard-shortcuts> root".into());
+ }
+ let name = root.attribute("filename").map(|f| f.rsplit(['=', '/']).next().unwrap_or(f).trim()).filter(|n| !n.is_empty()).map(str::to_string);
+ let mut set = KysSet { name, ..Default::default() };
+ for node in root.children().filter(|n| n.is_element()) {
+ match node.tag_name().name() {
+ "command" => {
+ let Some(name) = node.attribute("name").map(str::trim).filter(|n| !n.is_empty()) else { continue };
+ let shortcuts: Vec<String> = node
+ .children()
+ .filter(|n| n.is_element() && n.tag_name().name() == "shortcut")
+ .filter_map(|n| n.text().map(str::trim).filter(|t| !t.is_empty()).map(str::to_string))
+ .collect();
+ if !shortcuts.is_empty() {
+ set.commands.push(KysCommand { name: name.to_string(), shortcuts });
+ }
+ }
+ "tool" if node.text().is_some_and(|t| !t.trim().is_empty()) => set.tool_keys += 1,
+ _ => {}
+ }
+ }
+ Ok(set)
+}
+
+/// What an import would change.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Plan {
+ /// Command id → the normalised shortcut from the file, for every matched row.
+ pub set: BTreeMap<String, String>,
+ /// Photoshop names with no command here (scripts, Bridge, the macOS application menu…).
+ pub unknown: Vec<String>,
+ /// Rows whose shortcut could not be read (`unknown` does not list them).
+ pub unreadable: Vec<String>,
+ /// Second and later shortcuts of a row, which have no place here.
+ pub alternates: usize,
+}
+
+/// Photoshop's label and ours compared loosely: case, a trailing ellipsis (`...` or `…`) and
+/// surrounding space do not count.
+fn key(label: &str) -> String {
+ let l = label.trim().replace("...", "…");
+ l.trim_end_matches('…').trim().to_lowercase()
+}
+
+/// Match the rows to our commands (see the module notes for the tie-breaks).
+pub fn plan(app: &PhotocraftApp, set: &KysSet) -> Plan {
+ // Candidates by label, in Photoshop's menu order, each id once; then engine commands the
+ // menus list under another label (Preferences › General… is the Settings… item).
+ let mut by_label: HashMap<String, Vec<(String, Option<String>)>> = HashMap::new();
+ let items = crate::menus::menu_items(app);
+ let menu = items.iter().filter(|i| i.label != "---" && crate::menus::is_live(&i.id)).map(|i| (i.id.clone(), i.label.clone()));
+ let specs = photocraft_engine::command_specs().iter().filter(|c| !c.menu.is_empty()).map(|c| (c.id.to_string(), c.label.to_string()));
+ for (id, label) in menu.chain(specs) {
+ let entry = by_label.entry(key(&label)).or_default();
+ if !entry.iter().any(|(i, _)| *i == id) {
+ let default = crate::shortcuts::default_shortcut(&id);
+ entry.push((id, default));
+ }
+ }
+ let mut plan = Plan::default();
+ for row in &set.commands {
+ let Some(candidates) = by_label.get(&key(&row.name)) else {
+ plan.unknown.push(row.name.clone());
+ continue;
+ };
+ let Some(sc) = row.shortcuts.first().and_then(|s| photocraft_engine::prefs::normalize_shortcut(s)) else {
+ plan.unreadable.push(row.name.clone());
+ continue;
+ };
+ plan.alternates += row.shortcuts.len().saturating_sub(1);
+ let imported: Vec<String> = row.shortcuts.iter().filter_map(|s| photocraft_engine::prefs::normalize_shortcut(s)).collect();
+ let pick = candidates
+ .iter()
+ .find(|(_, d)| d.as_deref().and_then(photocraft_engine::prefs::normalize_shortcut).is_some_and(|d| imported.contains(&d)))
+ .or_else(|| candidates.iter().find(|(_, d)| d.is_some()))
+ .or_else(|| candidates.first());
+ if let Some((id, default)) = pick {
+ // A row that lists the command's own default among its keys keeps the default
+ // (Zoom In is "Cmd++" then "Cmd+=" in Photoshop; ours is Cmd+=).
+ let default = default.as_deref().and_then(photocraft_engine::prefs::normalize_shortcut);
+ let sc = default.filter(|d| imported.contains(d)).unwrap_or(sc);
+ plan.set.insert(id.clone(), sc);
+ }
+ }
+ plan
+}
+
+/// Put the plan into the open Keyboard Shortcuts dialog (opening one when none is), as
+/// overrides the OK button applies: a key equal to the command's default clears its override.
+/// Returns the dialog id and the plan as JSON.
+pub fn import_text(app: &mut PhotocraftApp, file_name: &str, text: &str) -> Result<Value, String> {
+ let set = parse(text).map_err(|e| format!("{file_name}: {e}"))?;
+ let plan = plan(app, &set);
+ let id = match app.ui.dialogs.iter().find(|d| d.fields.get("__prefsui").and_then(Value::as_str) == Some("shortcuts")) {
+ Some(d) => d.id,
+ None => crate::prefs_ui::open_shortcuts(app, 0),
+ };
+ let f = &mut app.ui.dialog_mut(id).ok_or("the Keyboard Shortcuts dialog is gone")?.fields;
+ let mut overrides: BTreeMap<String, String> = f.get("overrides").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default();
+ for (cmd, sc) in &plan.set {
+ let default = crate::shortcuts::default_shortcut(cmd).and_then(|d| photocraft_engine::prefs::normalize_shortcut(&d));
+ if default.as_deref() == Some(sc.as_str()) {
+ overrides.remove(cmd);
+ } else {
+ overrides.insert(cmd.clone(), sc.clone());
+ }
+ }
+ let shown = std::path::Path::new(file_name).file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| file_name.to_string());
+ let n = plan.set.len().to_string();
+ let mut message = crate::i18n::fmt(tl!("Imported {n} shortcuts from {file}. Click OK to keep them."), &[("n", &n), ("file", &shown)]);
+ if !plan.unknown.is_empty() {
+ let u = plan.unknown.len().to_string();
+ message.push(' ');
+ message.push_str(&crate::i18n::fmt(tl!("{n} commands are not in PhotoCraft."), &[("n", &u)]));
+ }
+ f.insert("tab".into(), json!(0));
+ f.insert("overrides".into(), json!(overrides));
+ f.insert("selected".into(), json!(""));
+ f.insert("capture".into(), json!(false));
+ f.insert("message".into(), json!(message));
+ Ok(json!({
+ "dialog": id,
+ "name": set.name,
+ "imported": plan.set.len(),
+ "set": plan.set,
+ "unknown": plan.unknown,
+ "unreadable": plan.unreadable,
+ "alternates": plan.alternates,
+ "toolKeys": set.tool_keys,
+ }))
+}
+
+/// A `.kys` opened like a document (File › Open, a drop): its bytes are text.
+pub fn open_bytes(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Result<Value, String> {
+ let text = String::from_utf8(bytes.to_vec()).map_err(|_| format!("{name}: not a keyboard shortcut set (.kys): not UTF-8"))?;
+ import_text(app, name, &text)
+}
+
+/// The dialog's Import Photoshop Shortcuts… button: ask for the file, then fill the dialog.
+pub fn import_dialog(app: &mut PhotocraftApp) -> Result<Value, String> {
+ app.pick_file_bytes(|app, name, bytes| open_bytes(app, &name, &bytes))
+}
+
+/// Preferences › `dialogs` key that records the one-time import (its value names the source).
+pub const IMPORTED_PREF: &str = "photoshopShortcuts";
+
+/// First launch on a machine with Photoshop: its live shortcut set ([`crate::Services::photoshop_shortcuts`])
+/// is applied once, so Photoshop's hands work here from the start. Someone who already changed
+/// a shortcut keeps their own set. Either way the preference remembers it, so a later launch
+/// never asks again; Edit › Keyboard Shortcuts › Reset All to Defaults undoes the import.
+pub fn auto_import(app: &mut PhotocraftApp) {
+ if app.session.prefs().dialogs.contains_key(IMPORTED_PREF) {
+ return;
+ }
+ let Some((source, text)) = app.services.photoshop_shortcuts.as_mut().and_then(|f| f()) else { return };
+ let outcome = if app.session.prefs().shortcuts.is_empty() {
+ import_text(app, &source, &text).and_then(|r| {
+ let id = r["dialog"].as_u64().ok_or("no dialog")?;
+ crate::dialogs::confirm(app, id)?;
+ Ok(Some(r))
+ })
+ } else {
+ Ok(None)
+ };
+ app.session.prefs.edit(|p| {
+ p.dialogs.insert(IMPORTED_PREF.into(), json!({"source": source}));
+ });
+ match outcome {
+ Ok(Some(r)) => {
+ let changed = app.session.prefs().shortcuts.len();
+ if changed == 0 {
+ return; // The set is Photoshop's defaults, which are ours too.
+ }
+ let set = r["name"]
+ .as_str()
+ .map_or_else(|| std::path::Path::new(&source).file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default(), str::to_string);
+ let id = crate::notices::post(
+ app,
+ "Keyboard shortcuts imported",
+ vec!["Your keyboard shortcut set {set} is in use here: {n} shortcuts differ from the defaults. Edit › Keyboard Shortcuts shows them; Reset All to Defaults undoes this.".to_owned()],
+ false,
+ None,
+ );
+ if let Some(n) = app.ui.notices.iter_mut().find(|n| n.id == id) {
+ n.args = vec![("set".to_owned(), set), ("n".to_owned(), changed.to_string())];
+ }
+ }
+ Ok(None) => {}
+ Err(e) => {
+ app.ui.status = format!("The keyboard shortcut set was not imported: {e}");
+ app.ui.status_error = true;
+ }
+ }
+}
+
+#[cfg(test)]
+#[path = "kys_import_tests.rs"]
+mod tests;
diff --git a/crates/ui-egui/src/kys_import_tests.rs b/crates/ui-egui/src/kys_import_tests.rs
new file mode 100644
index 000000000..2b9d1eaa5
--- /dev/null
+++ b/crates/ui-egui/src/kys_import_tests.rs
@@ -0,0 +1,250 @@
+//! Photoshop `.kys` sets import into Edit › Keyboard Shortcuts (#1163): rows match our
+//! commands by label, one shortcut per command, with Photoshop's menu order breaking ties.
+
+use egui_kittest::Harness;
+use egui_kittest::kittest::Queryable;
+use serde_json::{Value, json};
+
+use super::{KysCommand, parse, plan};
+use crate::PhotocraftApp;
+use crate::file_dialog::FileDialogAnswer;
+
+/// A cut-down set in Photoshop's own layout: BOM, a dynamic (filter) row, static rows with
+/// their ids, a row with two shortcuts, an entity, scripts, and the tool keys.
+const SAMPLE: &str = "\u{feff}<?xml version=\"1.0\" encoding=\"UTF-8\"?>
+<photoshop-keyboard-shortcuts version=\"4\" filename=\"$$$/FileName/Presets/KeyboardCustomization/texcuts=texcuts\" modified=\"0\" multi-undo=\"2\">
+\t<command kind=\"dynamic\" name=\"Script_6F17BFA7-EFC8-40EA-B850-7B95ED8EA713\">
+\t\t<shortcut>Control+Opt+Cmd+4</shortcut>
+\t</command>
+\t<command kind=\"dynamic\" name=\"Gaussian Blur...\">
+\t\t<shortcut>Control+Opt+Cmd+G</shortcut>
+\t</command>
+\t<command kind=\"static\" name=\"Undo\" id=\"101\">
+\t\t<shortcut>Cmd+Z</shortcut>
+\t\t<shortcut>F1</shortcut>
+\t</command>
+\t<command kind=\"static\" name=\"Zoom In\" id=\"1004\">
+\t\t<shortcut>Cmd++</shortcut>
+\t\t<shortcut>Cmd+=</shortcut>
+\t</command>
+\t<command kind=\"static\" name=\"Levels...\" id=\"1801\">
+\t\t<shortcut>Cmd+L</shortcut>
+\t</command>
+\t<command kind=\"static\" name=\"All\" id=\"1017\">
+\t\t<shortcut>Cmd+A</shortcut>
+\t</command>
+\t<command kind=\"static\" name=\"Layer Via Copy\" id=\"2970\">
+\t\t<shortcut>Cmd+J</shortcut>
+\t</command>
+\t<command kind=\"static\" name=\"Black &amp; White...\" id=\"1824\">
+\t\t<shortcut>Opt+Shift+Cmd+B</shortcut>
+\t</command>
+\t<command kind=\"static\" name=\"General...\" id=\"2311\">
+\t\t<shortcut>Cmd+K</shortcut>
+\t</command>
+\t<command kind=\"static\" name=\"Last Filter\" id=\"1019\">
+\t\t<shortcut>Cmd+F</shortcut>
+\t</command>
+\t<command kind=\"static\" name=\"Hide Photoshop\" id=\"7001\">
+\t\t<shortcut>Cmd+H</shortcut>
+\t</command>
+\t<tool name=\"Move Tool\" type=\"1\" key=\"1819113074\">V</tool>
+\t<tool name=\"Default Foreground/Background Colors\" type=\"2\"></tool>
+</photoshop-keyboard-shortcuts>
+";
+
+fn app() -> PhotocraftApp {
+ PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default())
+}
+
+#[test]
+fn parses_rows_shortcuts_entities_and_tool_keys() {
+ let set = parse(SAMPLE).unwrap();
+ assert_eq!(set.commands.len(), 11);
+ assert_eq!(set.commands[2], KysCommand { name: "Undo".into(), shortcuts: vec!["Cmd+Z".into(), "F1".into()] });
+ assert_eq!(set.commands[7].name, "Black & White...");
+ assert_eq!(set.tool_keys, 1, "the empty Default Colors row carries no key");
+}
+
+#[test]
+fn rejects_other_xml_and_text() {
+ assert!(parse("<svg/>").unwrap_err().contains("not a keyboard shortcut set (.kys)"));
+ assert!(parse("Cmd+K\tPreferences").is_err());
+ assert_eq!(parse("<photoshop-keyboard-shortcuts/>").unwrap(), super::KysSet::default());
+}
+
+#[test]
+fn rows_match_our_commands_by_label_with_photoshop_tie_breaks() {
+ let app = app();
+ let p = plan(&app, &parse(SAMPLE).unwrap());
+ // Photoshop's "..." is our "…"; the dynamic (filter) row is a filter here.
+ assert_eq!(p.set.get("filter.blur.gaussianBlur").map(String::as_str), Some("Cmd+Ctrl+Alt+G"));
+ // Levels… is Image › Adjustments and Layer › New Adjustment Layer: the one whose default is
+ // the imported key wins. All is Select, Edit › Purge, View › Show…: Select › All has the key.
+ assert_eq!(p.set.get("image.adjustments.levels").map(String::as_str), Some("Cmd+L"));
+ assert!(!p.set.contains_key("layer.newAdjustmentLayer.levels"));
+ assert_eq!(p.set.get("select.all").map(String::as_str), Some("Cmd+A"));
+ assert!(!p.set.contains_key("edit.purge.all"));
+ // Undo is Edit › Undo, not Edit › Purge › Undo; only its first shortcut counts.
+ assert_eq!(p.set.get("edit.undo").map(String::as_str), Some("Cmd+Z"));
+ // Zoom In lists Cmd++ first, but Cmd+= is our default and is among its keys: it stays.
+ assert_eq!(p.set.get("view.zoomIn").map(String::as_str), Some("Cmd+="));
+ assert_eq!(p.alternates, 2);
+ // Case does not matter; an entity decodes; the menu's Settings… is the engine's General….
+ assert_eq!(p.set.get("layer.new.layerViaCopy").map(String::as_str), Some("Cmd+J"));
+ assert_eq!(p.set.get("image.adjustments.blackWhite").map(String::as_str), Some("Cmd+Alt+Shift+B"));
+ assert_eq!(p.set.get("edit.preferences.general").map(String::as_str), Some("Cmd+K"));
+ assert_eq!(p.set.get("filter.lastFilter").map(String::as_str), Some("Cmd+F"));
+ // Scripts and the macOS application menu have no command here.
+ assert_eq!(p.unknown, vec!["Script_6F17BFA7-EFC8-40EA-B850-7B95ED8EA713".to_string(), "Hide Photoshop".to_string()]);
+ assert!(p.unreadable.is_empty());
+ assert_eq!(p.set.len(), 9);
+}
+
+#[test]
+fn an_unreadable_shortcut_is_reported_not_imported() {
+ let app = app();
+ let set = super::KysSet { name: None, commands: vec![KysCommand { name: "Undo".into(), shortcuts: vec!["Cmd+Shift+Ctrl".into()] }], tool_keys: 0 };
+ let p = plan(&app, &set);
+ assert!(p.set.is_empty());
+ assert_eq!(p.unreadable, vec!["Undo".to_string()]);
+}
+
+/// The dialog's Import Photoshop Shortcuts… button: the chosen file fills the overrides (a key
+/// equal to the default clears its override), reports what it did, and OK applies the set like
+/// hand-made changes, taking a moved key from its old owner.
+#[test]
+fn import_button_fills_the_dialog_and_ok_applies_the_set() {
+ let answers = vec![Some(FileDialogAnswer::Contents("/sets/texcuts.kys".into(), SAMPLE.as_bytes().to_vec()))];
+ let services = crate::Services { file_dialog: Some(crate::file_dialog::fake(answers).0), ..Default::default() };
+ let mut h = Harness::builder().with_size(egui::vec2(1100.0, 760.0)).with_max_steps(64).build_eframe(|cc| {
+ PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
+ PhotocraftApp::new(photocraft_engine::Session::new(), services)
+ });
+ let ctx = h.ctx.clone();
+ // A hand-made override the file agrees with the default on: the import clears it.
+ h.state_mut().run("edit.keyboardShortcuts", json!({"set": {"edit.undo": "Cmd+Shift+Z"}})).unwrap();
+ let id = crate::menus::invoke(h.state_mut(), &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap();
+ // A short list keeps the button row on screen.
+ h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("filter".into(), json!("gaussian"));
+ h.run_steps(2);
+ h.get_by_label("Import Shortcuts…").click();
+ h.run_steps(3);
+ let field = |h: &Harness<'_, PhotocraftApp>, name: &str| -> Value {
+ h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.get(name).cloned().unwrap_or(Value::Null)
+ };
+ assert_eq!(h.state().ui.status, "", "the import failed");
+ let overrides = field(&h, "overrides");
+ assert_eq!(overrides["filter.blur.gaussianBlur"], json!("Cmd+Ctrl+Alt+G"));
+ assert!(overrides.get("edit.preferences.general").is_none(), "Cmd+K is Preferences' default: {overrides}");
+ assert_eq!(overrides["filter.lastFilter"], json!("Cmd+F"));
+ assert!(overrides.get("edit.undo").is_none(), "Cmd+Z is the default again: {overrides}");
+ assert!(overrides.get("select.all").is_none(), "already the default: {overrides}");
+ assert!(overrides.get("view.zoomIn").is_none(), "Cmd+= is among the keys, so the default stays: {overrides}");
+ let message = field(&h, "message");
+ assert_eq!(message, json!("Imported 9 shortcuts from texcuts.kys. Click OK to keep them. 2 commands are not in PhotoCraft."));
+ assert_eq!(field(&h, "capture"), json!(false));
+ // Nothing is applied until OK.
+ assert_eq!(crate::shortcuts::effective_shortcut(h.state(), "edit.undo", Some("Cmd+Z")).as_deref(), Some("Cmd+Shift+Z"));
+ crate::dialogs::confirm(h.state_mut(), id).unwrap();
+ let app = h.state();
+ assert_eq!(crate::shortcuts::effective_shortcut(app, "edit.undo", Some("Cmd+Z")).as_deref(), Some("Cmd+Z"));
+ assert_eq!(crate::shortcuts::effective_shortcut(app, "filter.blur.gaussianBlur", None).as_deref(), Some("Cmd+Ctrl+Alt+G"));
+ assert_eq!(crate::shortcuts::effective_shortcut(app, "edit.preferences.general", Some("Cmd+K")).as_deref(), Some("Cmd+K"));
+ // Cmd+F went to Last Filter, so Search (Cmd+F by default) lost its key.
+ assert_eq!(crate::shortcuts::effective_shortcut(app, "edit.search", Some("Cmd+F")), None);
+ assert_eq!(crate::shortcuts::effective_shortcut(app, "filter.lastFilter", Some("Cmd+Alt+F")).as_deref(), Some("Cmd+F"));
+}
+
+/// Opening or dropping a `.kys` opens the dialog with the set loaded, so it can be reviewed.
+#[test]
+fn an_opened_kys_file_opens_the_dialog_filled() {
+ let mut app = app();
+ assert!(app.ui.dialogs.is_empty());
+ let r = crate::preset_files_ui::open(&mut app, "texcuts.kys", SAMPLE.as_bytes()).unwrap();
+ r.unwrap();
+ let d = app.ui.dialogs.iter().find(|d| d.fields.get("__prefsui").and_then(Value::as_str) == Some("shortcuts")).unwrap();
+ assert_eq!(d.fields["tab"], json!(0));
+ assert_eq!(d.fields["overrides"]["filter.blur.gaussianBlur"], json!("Cmd+Ctrl+Alt+G"));
+ // A second file lands in the same dialog, on top of the first.
+ let one = "<photoshop-keyboard-shortcuts><command kind=\"static\" name=\"Copy\"><shortcut>F3</shortcut></command></photoshop-keyboard-shortcuts>";
+ crate::preset_files_ui::open(&mut app, "more.kys", one.as_bytes()).unwrap().unwrap();
+ assert_eq!(app.ui.dialogs.len(), 1);
+ let d = &app.ui.dialogs[0];
+ assert_eq!(d.fields["overrides"]["edit.copy"], json!("F3"));
+ assert_eq!(d.fields["overrides"]["filter.blur.gaussianBlur"], json!("Cmd+Ctrl+Alt+G"));
+ assert_eq!(d.fields["message"], json!("Imported 1 shortcuts from more.kys. Click OK to keep them."));
+ let bad = crate::preset_files_ui::open(&mut app, "notes.kys", b"hello").unwrap().unwrap_err();
+ assert!(bad.contains("not a keyboard shortcut set (.kys)"), "{bad}");
+}
+
+type Store = std::sync::Arc<std::sync::Mutex<Option<String>>>;
+
+/// An app beside a Photoshop whose live set is `set`; `saved_prefs` is this app's own saved
+/// preferences file, and the store receives what it writes back.
+fn with_photoshop(set: &'static str, saved_prefs: Option<&'static str>) -> (PhotocraftApp, Store) {
+ let store: Store = Default::default();
+ let written = store.clone();
+ let services = crate::Services {
+ photoshop_shortcuts: Some(Box::new(move || {
+ Some(("/Users/me/Library/Preferences/Adobe Photoshop 2026 Settings/Keyboard Shortcuts.psp".into(), set.into()))
+ })),
+ load_prefs: Some(Box::new(move || saved_prefs.map(str::to_string))),
+ save_prefs: Some(Box::new(move |text: &str| {
+ *written.lock().unwrap() = Some(text.to_string());
+ Ok(())
+ })),
+ ..Default::default()
+ };
+ (PhotocraftApp::new(photocraft_engine::Session::new(), services), store)
+}
+
+/// First launch beside Photoshop: its live set is applied, a notice says so, and the
+/// preference remembers it so the next launch leaves the user's shortcuts alone.
+#[test]
+fn first_launch_imports_photoshops_live_set_once() {
+ let (mut app, store) = with_photoshop(SAMPLE, None);
+ assert!(app.ui.dialogs.is_empty(), "applied without a dialog");
+ assert_eq!(crate::shortcuts::effective_shortcut(&app, "filter.blur.gaussianBlur", None).as_deref(), Some("Cmd+Ctrl+Alt+G"));
+ assert_eq!(crate::shortcuts::effective_shortcut(&app, "filter.lastFilter", Some("Cmd+Alt+F")).as_deref(), Some("Cmd+F"));
+ assert_eq!(crate::shortcuts::effective_shortcut(&app, "edit.search", Some("Cmd+F")), None, "taken by Last Filter");
+ assert_eq!(app.session.prefs().dialogs[super::IMPORTED_PREF]["source"].as_str().map(|s| s.ends_with("Keyboard Shortcuts.psp")), Some(true));
+ let notice = app.ui.notices.last().unwrap();
+ assert_eq!(notice.title, "Keyboard shortcuts imported");
+ let line = notice.text(&notice.lines[0]);
+ assert!(line.starts_with("Your keyboard shortcut set texcuts is in use here: "), "{line}");
+ assert!(line.contains(" shortcuts differ from the defaults."), "{line}");
+ assert!(!app.ui.status_error, "{}", app.ui.status);
+ // The preference moved past the loaded revision, so the next frame saves it.
+ crate::prefs_ui::tick(&mut app, &egui::Context::default());
+ let saved = store.lock().unwrap().clone().unwrap();
+ assert!(saved.contains("Cmd+Ctrl+Alt+G") && saved.contains(super::IMPORTED_PREF), "{saved}");
+ // Reset in the dialog, then a second run: the preference says it was done.
+ app.run("edit.keyboardShortcuts", json!({"reset": true})).unwrap();
+ super::auto_import(&mut app);
+ assert!(app.session.prefs().shortcuts.is_empty());
+}
+
+/// Shortcuts the user already changed are theirs: the set is not applied, but the launch is
+/// still remembered, so it is never applied over them later either.
+#[test]
+fn a_user_with_their_own_shortcuts_keeps_them() {
+ let saved = r#"{"shortcuts": {"edit.undo": "F1"}}"#;
+ let (mut app, _) = with_photoshop(SAMPLE, Some(saved));
+ assert_eq!(crate::shortcuts::effective_shortcut(&app, "edit.undo", Some("Cmd+Z")).as_deref(), Some("F1"));
+ assert_eq!(crate::shortcuts::effective_shortcut(&app, "filter.blur.gaussianBlur", None), None);
+ assert!(app.ui.notices.is_empty());
+ assert!(app.session.prefs().dialogs.contains_key(super::IMPORTED_PREF));
+ // A set that is just Photoshop's defaults changes nothing and says nothing.
+ let defaults = "<photoshop-keyboard-shortcuts><command kind=\"static\" name=\"Undo\"><shortcut>Cmd+Z</shortcut></command></photoshop-keyboard-shortcuts>";
+ let (mut quiet, _) = with_photoshop(defaults, None);
+ assert!(quiet.session.prefs().shortcuts.is_empty());
+ assert!(quiet.ui.notices.is_empty());
+ assert!(quiet.session.prefs().dialogs.contains_key(super::IMPORTED_PREF));
+ // A file that is not a set is reported, not applied, and not retried.
+ let (mut bad, _) = with_photoshop("binary junk", None);
+ assert!(bad.ui.status_error, "{}", bad.ui.status);
+ assert!(bad.ui.status.contains("not a keyboard shortcut set (.kys)"), "{}", bad.ui.status);
+ assert!(bad.session.prefs().dialogs.contains_key(super::IMPORTED_PREF));
+ let _ = (&mut app, &mut quiet, &mut bad);
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index f5a9ca0c8..e7509895c 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -66,9 +66,9 @@ pub mod file_open;
pub mod file_ui;
pub mod fill_ui;
pub mod filter_dialog;
-mod font_preview;
#[cfg(not(target_arch = "wasm32"))]
mod filter_preview_worker;
+mod font_preview;
pub mod gallery_ui;
pub mod gpu_canvas;
pub mod gpu_status;
@@ -78,6 +78,7 @@ pub mod i18n;
mod icon_data;
pub mod icons;
pub mod jobs_ui;
+pub mod kys_import;
pub mod lasso_ui;
pub mod layer_menu_ui;
pub mod layer_pick_ui;
@@ -239,6 +240,9 @@ pub type DiscardAutosaveFn = Box<dyn FnMut(u64)>;
/// List recoverable documents without decoding them. Their data stays until the documents are
/// saved or closed; the shell runs each entry's loader on a background worker.
pub type RecoverFn = Box<dyn FnMut() -> Vec<Recoverable>>;
+/// Photoshop's own keyboard shortcut set on this machine, as (source path, `.kys` XML text):
+/// the newest install's live `Keyboard Shortcuts.psp` on the desktop, `None` without one.
+pub type PhotoshopShortcutsFn = Box<dyn FnMut() -> Option<(String, String)>>;
/// A recovered document (by `DocId` value, once open) takes over its recovery entry (by key):
/// its autosaves replace the entry, and saving or closing it drops the entry.
pub type AdoptAutosaveFn = Box<dyn FnMut(u64, &str)>;
@@ -303,6 +307,8 @@ pub struct Services {
/// the web (see `prefs_ui`).
pub load_prefs: Option<LoadTextFn>,
pub save_prefs: Option<SaveTextFn>,
+ /// Photoshop's live keyboard shortcut set, imported once at first launch (`kys_import`).
+ pub photoshop_shortcuts: Option<PhotoshopShortcutsFn>,
pub system_theme: Option<SystemThemeFn>,
/// The native window is connected directly to a Wayland compositor.
pub is_wayland: bool,
@@ -647,6 +653,8 @@ impl PhotocraftApp {
};
// Saved preferences are in place before the first frame; recovery starts in upkeep.
prefs_ui::load(&mut app);
+ // After the saved preferences and their revision mark, so the imported set is saved.
+ kys_import::auto_import(&mut app);
notices::wayland_file_drop_guidance(&mut app);
// File › Scripts › Script Events Manager: "Start Application".
photocraft_engine::automate_cmds::fire_event(&mut app.session, "startApplication");
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index 3c4be1772..eb72ebc8c 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -3270,7 +3270,9 @@ mod color_tests {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.session.tools.foreground = [1.0, 0.0, 0.0, 1.0];
app.session.tools.background = [0.0, 0.0, 1.0, 1.0];
- let mut h = egui_kittest::Harness::builder().with_size(vec2(80.0, 120.0)).build_ui_state(|ui, app: &mut PhotocraftApp| color_chips(app, ui, two_columns), app);
+ let mut h = egui_kittest::Harness::builder()
+ .with_size(vec2(80.0, 120.0))
+ .build_ui_state(|ui, app: &mut PhotocraftApp| color_chips(app, ui, two_columns), app);
PhotocraftApp::setup_context(&h.ctx, kind);
h.run_steps(2);
h.get_by_label("Swap colours (X)").click();
diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs
index 8628cc3b9..ed0f046ef 100644
--- a/crates/ui-egui/src/prefs_ui.rs
+++ b/crates/ui-egui/src/prefs_ui.rs
@@ -11,9 +11,9 @@ use std::collections::{BTreeMap, HashMap, VecDeque};
use egui::{Color32, RichText, Sense, vec2};
use photocraft_doc::DocId;
+use photocraft_engine::jobs::{JobEvent, JobId, JobOutcome, Started};
#[cfg(test)]
use photocraft_engine::prefs::Theme;
-use photocraft_engine::jobs::{JobEvent, JobId, JobOutcome, Started};
use photocraft_engine::prefs::{self, AppearanceMode, DarkTheme, LightTheme, SECTIONS};
use photocraft_engine::snap::{SnapLine, SnapTargets};
use serde_json::{Map, Value, json};
@@ -1187,7 +1187,14 @@ fn appearance_rows(ui: &mut egui::Ui, obj: &mut Map<String, Value>, system: Opti
ui.horizontal_top(|ui| {
ui.set_min_width(width * 2.0 + 10.0);
ui.allocate_ui_with_layout(vec2(width, 300.0), egui::Layout::top_down(egui::Align::Min), |ui| {
- theme_card(ui, "Light Theme", light_active, &mut light, &[("studioLight", ThemeKind::StudioLight), ("classic", ThemeKind::Classic), ("adwaita", ThemeKind::Adwaita)], width);
+ theme_card(
+ ui,
+ "Light Theme",
+ light_active,
+ &mut light,
+ &[("studioLight", ThemeKind::StudioLight), ("classic", ThemeKind::Classic), ("adwaita", ThemeKind::Adwaita)],
+ width,
+ );
});
ui.add_space(10.0);
ui.allocate_ui_with_layout(vec2(width, 300.0), egui::Layout::top_down(egui::Align::Min), |ui| {
@@ -1499,6 +1506,13 @@ fn shortcuts_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String
overrides.clear();
message = tl!("All shortcuts reset to PhotoCraft defaults.").into();
}
+ // A Photoshop set (`.kys`) fills the overrides; the file arrives after this frame
+ // and `kys_import` writes the dialog's fields then (#1163).
+ if ui.button(tl!("Import Shortcuts…")).on_hover_text(tl!("Load a keyboard shortcut set saved as .kys")).clicked()
+ && let Err(e) = crate::kys_import::import_dialog(app)
+ {
+ message = e;
+ }
});
} else if ui.button(tl!("Show All Menu Items")).clicked() {
hidden.clear();
diff --git a/crates/ui-egui/src/preset_files_ui.rs b/crates/ui-egui/src/preset_files_ui.rs
index 7ec8e55a8..a3fa49df0 100644
--- a/crates/ui-egui/src/preset_files_ui.rs
+++ b/crates/ui-egui/src/preset_files_ui.rs
@@ -2,7 +2,8 @@
//! Import Brushes…, the Preset Manager's Load…): Photoshop brushes (`.abr`) go to the brush
//! library through `brush.presets.importAbr`, gradients (`.grd`) to the Gradients panel through
//! `gradient.presets.importGrd`, swatches (`.aco`, `.ase`) to the Swatches panel through
-//! `swatches.import`, instead of opening as documents.
+//! `swatches.import`, keyboard shortcut sets (`.kys`) to Edit › Keyboard Shortcuts through
+//! [`crate::kys_import`], instead of opening as documents.
use serde_json::{Value, json};
@@ -10,7 +11,9 @@ use crate::PhotocraftApp;
/// Extensions handled here rather than by the document importer (`.aco`/`.ase` swatches go to
/// the Swatches panel through [`crate::swatches_ui::import_bytes`]).
-pub const PRESET_EXTS: &[&str] = &["abr", "grd", "aco", "ase"];
+/// `.psp` is Photoshop's live `Keyboard Shortcuts.psp` (the same XML as a `.kys`); other `.psp`
+/// settings files are refused with a clear message.
+pub const PRESET_EXTS: &[&str] = &["abr", "grd", "aco", "ase", "kys", "psp"];
fn ext(name: &str) -> String {
std::path::Path::new(name).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default()
@@ -37,6 +40,7 @@ pub fn open(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Option<Result<
"abr" => ("brush.presets.importAbr", "brushes"),
"grd" => ("gradient.presets.importGrd", "gradients"),
"aco" | "ase" => return Some(crate::swatches_ui::import_bytes(app, name, bytes, false).map(|_| ())),
+ "kys" | "psp" => return Some(crate::kys_import::open_bytes(app, name, bytes).map(|_| ())),
_ => return None,
};
let stem = std::path::Path::new(name).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| tl!("Imported").into());
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 16660739a..0c247c916 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -166,7 +166,7 @@ the same commands work in the app, the CLI and headless MCP. Paths are dotted ca
| `prefs.set` | `{"path":"cursors.painting","value":"precise"}` or `{"values":{"unitsAndRulers.rulers":"cm","guidesGridAndSlices.gridColor":"#ff8800"}}`. Values are validated (choices, ranges, `#rrggbb` colours, shortcut syntax); a batch applies all or nothing. A section path takes an object and merges it key by key |
| `prefs.reset` | `{"path":"performance"}` (a section or key); no path resets everything. An individual `shortcuts.<id>` or `menus.colors.<id>` reset removes the override and returns `null`, including when it is already absent |
| `edit.preferences.<section>` | the section's values; in the app (no params) it opens the Preferences dialog on that section |
-| `edit.keyboardShortcuts` | `{"set":{"edit.fill":"Cmd+Shift+F"},"reset":true\|["id",…],"removeConflicts":true,"filter":"blur","list":false}`: returns overrides, matching commands and conflicts. A shortcut moved to another command is removed from its old owner unless `removeConflicts` is false. `""` removes a shortcut, `null` restores the default. The held temporary tools are bindable too: `tools.temporary.hand` (Space; also repositions a selection being drawn), `tools.temporary.zoomIn` (Cmd+Space), `tools.temporary.zoomOut` (Cmd+Alt+Space); they list with `"hold": true`. In the app it opens Keyboard Shortcuts and Menus |
+| `edit.keyboardShortcuts` | `{"set":{"edit.fill":"Cmd+Shift+F"},"reset":true\|["id",…],"removeConflicts":true,"filter":"blur","list":false}`: returns overrides, matching commands and conflicts. A shortcut moved to another command is removed from its old owner unless `removeConflicts` is false. `""` removes a shortcut, `null` restores the default. The held temporary tools are bindable too: `tools.temporary.hand` (Space; also repositions a selection being drawn), `tools.temporary.zoomIn` (Cmd+Space), `tools.temporary.zoomOut` (Cmd+Alt+Space); they list with `"hold": true`. In the app it opens Keyboard Shortcuts and Menus, whose Import Photoshop Shortcuts… button loads a Photoshop `.kys` set into the dialog (opening or dropping a `.kys`, or Photoshop's live `Keyboard Shortcuts.psp`, does the same; rows are matched by menu label, tool keys are not imported). On a desktop with Photoshop installed the newest install's live set is imported once, at the first launch that has no shortcut overrides yet (`dialogs.photoshopShortcuts` in the preferences records it) |
| `edit.menus` / `edit.toolbar` | `{"hide":["edit.fade"],"show":[…],"color":{"edit.fill":"red"},"reset":false}` / `{"hidden":["Sponge"],"order":[…]}` |
| `edit.colorSettings` | `{"workingRgb":"display-p3","workingCmyk":"coated-cmyk","workingGray":"sgray","policyRgb":"preserve\|convert\|off",…,"askOnMismatch":true,"intent":"perceptual","bpc":true}`; honoured when opening files (`file.openAs`, the app's File › Open) and by Image › Mode and "working" profile specs. `color.profileMismatch {"action":"preserve\|convert\|discard\|assignWorking"}` answers the mismatch prompt |