gui_shortcuts/
gui_shortcuts.rs

1//! GUI 应用快捷键系统示例
2//! 运行: cargo run --example gui_shortcuts
3
4// use keyboard_codes::*;
5// use std::collections::HashMap;
6
7use keyboard_codes::{
8    current_platform, parse_shortcut_with_aliases, Key, KeyCodeMapper, Modifier, Platform, Shortcut,
9};
10use std::collections::HashMap;
11
12#[derive(Debug, Clone, Copy, PartialEq)]
13enum AppCommand {
14    NewFile,
15    OpenFile,
16    Save,
17    SaveAs,
18    CloseTab,
19    Undo,
20    Redo,
21    Cut,
22    Copy,
23    Paste,
24    SelectAll,
25    Find,
26    Replace,
27    Quit,
28    Preferences,
29}
30
31struct ShortcutManager {
32    platform: Platform,
33    shortcuts: HashMap<Shortcut, AppCommand>,
34}
35
36impl ShortcutManager {
37    fn new(platform: Platform) -> Self {
38        let mut shortcuts = HashMap::new();
39
40        // 文件操作 - 使用安全的添加方法
41        Self::add_shortcut(&mut shortcuts, "ctrl+n", AppCommand::NewFile);
42        Self::add_shortcut(&mut shortcuts, "ctrl+o", AppCommand::OpenFile);
43        Self::add_shortcut(&mut shortcuts, "ctrl+s", AppCommand::Save);
44        Self::add_shortcut(&mut shortcuts, "ctrl+shift+s", AppCommand::SaveAs);
45        Self::add_shortcut(&mut shortcuts, "ctrl+w", AppCommand::CloseTab);
46
47        // 编辑操作
48        Self::add_shortcut(&mut shortcuts, "ctrl+z", AppCommand::Undo);
49        Self::add_shortcut(&mut shortcuts, "ctrl+y", AppCommand::Redo);
50        Self::add_shortcut(&mut shortcuts, "ctrl+x", AppCommand::Cut);
51        Self::add_shortcut(&mut shortcuts, "ctrl+c", AppCommand::Copy);
52        Self::add_shortcut(&mut shortcuts, "ctrl+v", AppCommand::Paste);
53        Self::add_shortcut(&mut shortcuts, "ctrl+a", AppCommand::SelectAll);
54        Self::add_shortcut(&mut shortcuts, "ctrl+f", AppCommand::Find);
55        Self::add_shortcut(&mut shortcuts, "ctrl+h", AppCommand::Replace);
56
57        // 跨平台退出命令 - 修复逗号问题
58        if platform == Platform::MacOS {
59            Self::add_shortcut(&mut shortcuts, "cmd+q", AppCommand::Quit);
60            // 移除有问题的逗号快捷键,改用其他键
61            Self::add_shortcut(&mut shortcuts, "cmd+p", AppCommand::Preferences);
62        } else {
63            Self::add_shortcut(&mut shortcuts, "alt+f4", AppCommand::Quit);
64            Self::add_shortcut(&mut shortcuts, "ctrl+p", AppCommand::Preferences);
65        }
66
67        Self {
68            platform,
69            shortcuts,
70        }
71    }
72
73    // 安全的快捷键添加方法
74    fn add_shortcut(
75        shortcuts: &mut HashMap<Shortcut, AppCommand>,
76        input: &str,
77        command: AppCommand,
78    ) {
79        match parse_shortcut_with_aliases(input) {
80            Ok(shortcut) => {
81                shortcuts.insert(shortcut, command);
82            }
83            Err(e) => {
84                eprintln!("警告: 无法解析快捷键 '{}': {}", input, e);
85            }
86        }
87    }
88
89    fn get_command(&self, modifier_vks: &[usize], key_vk: usize) -> Option<AppCommand> {
90        // 转换修饰键
91        let modifiers: Vec<Modifier> = modifier_vks
92            .iter()
93            .filter_map(|&code| Modifier::from_code(code, self.platform))
94            .collect();
95
96        // 转换主键
97        if let Some(key) = Key::from_code(key_vk, self.platform) {
98            let shortcut = Shortcut::new(modifiers, key);
99            return self.shortcuts.get(&shortcut).copied();
100        }
101
102        None
103    }
104
105    fn print_shortcut_reference(&self) {
106        println!("快捷键参考表:");
107        println!("{:-<40}", "");
108
109        let mut commands: Vec<(&Shortcut, &AppCommand)> = self.shortcuts.iter().collect();
110        commands.sort_by_key(|(_, cmd)| format!("{:?}", cmd));
111
112        for (shortcut, command) in commands {
113            println!("  {:20} -> {:?}", shortcut, command);
114        }
115    }
116}
117
118fn main() {
119    println!("=== GUI 应用快捷键系统示例 ===\n");
120
121    let platform = current_platform();
122    let shortcut_manager = ShortcutManager::new(platform);
123
124    shortcut_manager.print_shortcut_reference();
125
126    // 模拟快捷键输入
127    println!("\n模拟快捷键处理:");
128    let test_combinations = [
129        (vec![0x11], 0x53),       // Ctrl + S (Save)
130        (vec![0x11], 0x43),       // Ctrl + C (Copy)
131        (vec![0x11, 0x10], 0x53), // Ctrl + Shift + S (Save As)
132    ];
133
134    for (modifiers, key) in test_combinations {
135        if let Some(command) = shortcut_manager.get_command(&modifiers, key) {
136            println!("  {:02X?} + {:02X} -> {:?}", modifiers, key, command);
137        } else {
138            println!("  {:02X?} + {:02X} -> 无匹配命令", modifiers, key);
139        }
140    }
141}