Skip to content

Commit

Permalink
fix: check hotkey and optimize hotkey input, close #287
Browse files Browse the repository at this point in the history
  • Loading branch information
zzzgydi committed Nov 23, 2022
1 parent 6bc83d9 commit db02866
Show file tree
Hide file tree
Showing 6 changed files with 74 additions and 18 deletions.
1 change: 1 addition & 0 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ nanoid = "0.4.0"
chrono = "0.4.19"
sysinfo = "0.26.2"
sysproxy = "0.1"
rquickjs = "0.1.7"
serde_json = "1.0"
serde_yaml = "0.9"
auto-launch = "0.4"
Expand All @@ -37,9 +38,9 @@ tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
reqwest = { version = "0.11", features = ["json"] }
tauri = { version = "1.1.1", features = ["global-shortcut-all", "process-all", "shell-all", "system-tray", "updater", "window-all"] }
rquickjs = { version = "0.1.7" }
window-shadows = { version = "0.2.0" }
tauri-runtime-wry = { version = "0.12" }
window-vibrancy = { version = "0.3.0" }
window-shadows = { version = "0.2.0" }

[target.'cfg(windows)'.dependencies]
runas = "0.2.1"
Expand Down
31 changes: 26 additions & 5 deletions src-tauri/src/core/hotkey.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use once_cell::sync::OnceCell;
use parking_lot::Mutex;
use std::{collections::HashMap, sync::Arc};
use tauri::{AppHandle, GlobalShortcutManager};
use tauri_runtime_wry::wry::application::accelerator::Accelerator;

pub struct Hotkey {
current: Arc<Mutex<Vec<String>>>, // 保存当前的热键设置
Expand Down Expand Up @@ -32,10 +33,15 @@ impl Hotkey {
let func = iter.next();
let key = iter.next();

if func.is_some() && key.is_some() {
log_err!(self.register(key.unwrap(), func.unwrap()));
} else {
log::error!(target: "app", "invalid hotkey \"{}\":\"{}\"", key.unwrap_or("None"), func.unwrap_or("None"));
match (key, func) {
(Some(key), Some(func)) => {
log_err!(Self::check_key(key).and_then(|_| self.register(key, func)));
}
_ => {
let key = key.unwrap_or("None");
let func = func.unwrap_or("None");
log::error!(target: "app", "invalid hotkey `{key}`:`{func}`");
}
}
}
*self.current.lock() = hotkeys.clone();
Expand All @@ -44,10 +50,20 @@ impl Hotkey {
Ok(())
}

/// 检查一个键是否合法
fn check_key(hotkey: &str) -> Result<()> {
// fix #287
// tauri的这几个方法全部有Result expect,会panic,先检测一遍避免挂了
if hotkey.parse::<Accelerator>().is_err() {
bail!("invalid hotkey `{hotkey}`");
}
Ok(())
}

fn get_manager(&self) -> Result<impl GlobalShortcutManager> {
let app_handle = self.app_handle.lock();
if app_handle.is_none() {
bail!("failed to get hotkey manager");
bail!("failed to get the hotkey manager");
}
Ok(app_handle.as_ref().unwrap().global_shortcut_manager())
}
Expand Down Expand Up @@ -92,6 +108,11 @@ impl Hotkey {

let (del, add) = Self::get_diff(old_map, new_map);

// 先检查一遍所有新的热键是不是可以用的
for (hotkey, _) in add.iter() {
Self::check_key(hotkey)?;
}

del.iter().for_each(|key| {
let _ = self.unregister(key);
});
Expand Down
24 changes: 19 additions & 5 deletions src/components/setting/mods/hotkey-input.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useRef, useState } from "react";
import { alpha, Box, IconButton, styled } from "@mui/material";
import { DeleteRounded } from "@mui/icons-material";
import parseHotkey from "@/utils/parse-hotkey";
import { parseHotkey } from "@/utils/parse-hotkey";

const KeyWrapper = styled("div")(({ theme }) => ({
position: "relative",
Expand Down Expand Up @@ -54,10 +55,20 @@ interface Props {
export const HotkeyInput = (props: Props) => {
const { value, onChange } = props;

const changeRef = useRef<string[]>([]);
const [keys, setKeys] = useState(value);

return (
<Box sx={{ display: "flex", alignItems: "center" }}>
<KeyWrapper>
<input
onKeyUp={() => {
const ret = changeRef.current.slice();
if (ret.length) {
onChange(ret);
changeRef.current = [];
}
}}
onKeyDown={(e) => {
const evt = e.nativeEvent;
e.preventDefault();
Expand All @@ -66,13 +77,13 @@ export const HotkeyInput = (props: Props) => {
const key = parseHotkey(evt.key);
if (key === "UNIDENTIFIED") return;

const newList = [...new Set([...value, key])];
onChange(newList);
changeRef.current = [...new Set([...changeRef.current, key])];
setKeys(changeRef.current);
}}
/>

<div className="list">
{value.map((key) => (
{keys.map((key) => (
<div key={key} className="item">
{key}
</div>
Expand All @@ -84,7 +95,10 @@ export const HotkeyInput = (props: Props) => {
size="small"
title="Delete"
color="inherit"
onClick={() => onChange([])}
onClick={() => {
onChange([]);
setKeys([]);
}}
>
<DeleteRounded fontSize="inherit" />
</IconButton>
Expand Down
2 changes: 1 addition & 1 deletion src/components/setting/mods/hotkey-viewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export const HotkeyViewer = forwardRef<DialogRef>((props, ref) => {
.filter(Boolean);

try {
patchVerge({ hotkeys });
await patchVerge({ hotkeys });
setOpen(false);
} catch (err: any) {
Notice.error(err.message || err.toString());
Expand Down
29 changes: 24 additions & 5 deletions src/utils/parse-hotkey.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,26 @@
const parseHotkey = (key: string) => {
const KEY_MAP: Record<string, string> = {
'"': "'",
":": ";",
"?": "/",
">": ".",
"<": ",",
"{": "[",
"}": "]",
"|": "\\",
"!": "1",
"@": "2",
"#": "3",
$: "4",
"%": "5",
"^": "6",
"&": "7",
"*": "8",
"(": "9",
")": "0",
"~": "`",
};

export const parseHotkey = (key: string) => {
let temp = key.toUpperCase();

if (temp.startsWith("ARROW")) {
Expand All @@ -20,10 +42,7 @@ const parseHotkey = (key: string) => {
return "CMD";
case " ":
return "SPACE";

default:
return temp;
return KEY_MAP[temp] || temp;
}
};

export default parseHotkey;

0 comments on commit db02866

Please sign in to comment.