From b47670f3912fcb5d330dded84090ae29f9cc54ae Mon Sep 17 00:00:00 2001 From: Shift Date: Wed, 21 Oct 2026 10:07:16 +0800 Subject: [PATCH] fix(editor,drag,hotkeys): unified editor header, drop-to-button routing, single-instance hotkey ownership --- public/drop-preview.html | 20 ----- src-tauri/capabilities/default.json | 1 + src-tauri/src/hotkeys.rs | 123 +++++++++++++++++++++++++++- src-tauri/src/lib.rs | 68 ++++++--------- src/components/MainWindow.tsx | 50 +++++++++-- src/i18n.ts | 15 ++++ src/styles.css | 35 ++++++++ src/types.ts | 2 + 8 files changed, 237 insertions(+), 77 deletions(-) delete mode 100644 public/drop-preview.html diff --git a/public/drop-preview.html b/public/drop-preview.html deleted file mode 100644 index 04a2ead..0000000 --- a/public/drop-preview.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - -
-
- - - -
-
- - diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index a947064..3afa47a 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -14,6 +14,7 @@ "core:window:allow-start-dragging", "core:window:allow-current-monitor", "core:window:allow-outer-position", + "core:webview:allow-webview-position", "core:window:allow-scale-factor", "global-shortcut:default", "dialog:default", diff --git a/src-tauri/src/hotkeys.rs b/src-tauri/src/hotkeys.rs index 28789bc..059cacd 100644 --- a/src-tauri/src/hotkeys.rs +++ b/src-tauri/src/hotkeys.rs @@ -29,6 +29,8 @@ pub struct HotkeyStatus { pub hotkeys: Vec, /// Other running Shift processes. pub others: Vec, + /// True when a second copy tried to start in the last ten minutes. + pub recent_duplicate: bool, } /// True when this process may continue; false when another Shift already holds the lock. @@ -70,14 +72,121 @@ pub fn set_live(live: bool) { } } +/// `recent_duplicate` stays false here; the command layer fills it in because +/// only a command has access to the app's config directory. pub fn status() -> HotkeyStatus { HotkeyStatus { + recent_duplicate: false, live: *HOTKEYS_LIVE.lock().unwrap_or_else(|error| error.into_inner()), hotkeys: HOTKEYS.iter().map(|hotkey| hotkey.to_string()).collect(), others: other_pids(), } } +/// Leave a trace so the running copy can explain why a launch "did nothing". +pub fn mark_duplicate_attempt(app: &AppHandle) { + if let Ok(path) = attempt_path(app) { + let exe = std::env::current_exe() + .map(|value| value.to_string_lossy().to_string()) + .unwrap_or_default(); + let line = format!("{}\t{}\n", std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|value| value.as_secs()) + .unwrap_or_default(), exe); + let _ = std::fs::write(path, line); + } +} + +/// Seconds since a second copy last tried to start, if any. +fn duplicate_attempt_age(app: &AppHandle) -> Option { + let text = std::fs::read_to_string(attempt_path(app).ok()?).ok()?; + let seconds: u64 = text.split('\t').next()?.parse().ok()?; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .ok()? + .as_secs(); + now.checked_sub(seconds) +} + +/// Report a duplicate launch attempt when it is recent, then clear it so the +/// notice is shown once. +pub fn take_duplicate_attempt(app: &AppHandle) -> bool { + match duplicate_attempt_age(app) { + Some(age) if age < 600 => { + if let Ok(path) = attempt_path(app) { + let _ = std::fs::remove_file(path); + } + true + } + _ => false, + } +} + +fn attempt_path(app: &AppHandle) -> Result { + Ok(app + .path() + .app_config_dir() + .map_err(|error| error.to_string())? + .join("shift-duplicate-attempt")) +} + +/// Ask the process that holds the instance lock to show itself. +#[cfg(unix)] +pub fn wake_running_copy(app: &AppHandle) -> bool { + use std::{io::Write, os::unix::net::UnixStream}; + + match socket_path(app) { + Ok(path) => match UnixStream::connect(path) { + Ok(mut stream) => { + stream.write_all(b"show\n").is_ok() + } + Err(_) => false, + }, + Err(_) => false, + } +} + +#[cfg(not(unix))] +pub fn wake_running_copy(_app: &AppHandle) -> bool { + false +} + +/// Accept wake-ups for as long as this process owns the instance lock. +#[cfg(unix)] +pub fn spawn_watcher(app: AppHandle) { + use std::os::unix::net::UnixListener; + + let Ok(path) = socket_path(&app) else { + return; + }; + // A socket left behind by a crashed copy would block the bind forever. + let _ = std::fs::remove_file(&path); + let Ok(listener) = UnixListener::bind(&path) else { + return; + }; + std::thread::spawn(move || { + for stream in listener.incoming() { + if stream.is_ok() { + crate::show_main(&app); + } + } + }); +} + +#[cfg(not(unix))] +pub fn spawn_watcher(_app: AppHandle) {} + +#[cfg(unix)] +fn socket_path(app: &AppHandle) -> Result { + let directory = app.path().app_config_dir().map_err(|error| error.to_string())?; + let path = directory.join("shift.sock"); + // Unix socket paths are capped at ~104 bytes; fall back to the temp dir. + if path.as_os_str().len() > 90 { + return Ok(std::env::temp_dir().join(format!("shift-{}.sock", unsafe { libc::getuid() }))); + } + Ok(path) +} + /// Pids of other Shift processes, excluding this one. pub fn other_pids() -> Vec { let output = std::process::Command::new("/usr/bin/pgrep") @@ -145,8 +254,12 @@ pub fn quit_other_instances() -> usize { } #[tauri::command] -pub fn hotkey_status() -> HotkeyStatus { - status() +pub fn hotkey_status(app: AppHandle) -> HotkeyStatus { + let mut current = status(); + if take_duplicate_attempt(&app) { + current.recent_duplicate = true; + } + current } #[cfg(test)] @@ -173,7 +286,9 @@ mod tests { #[test] fn registration_failures_are_reachable_from_the_ui() { note_registration_failed(); - assert!(!hotkey_status().live); - assert_eq!(hotkey_status().hotkeys, vec!["Alt+Shift+2", "Alt+Shift+3", "Alt+Shift+4"]); + let status = status(); + assert!(!status.live); + assert_eq!(status.hotkeys, vec!["Alt+Shift+2", "Alt+Shift+3", "Alt+Shift+4"]); + assert!(!status.recent_duplicate); } } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 143f9f8..6977e8b 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -167,48 +167,14 @@ fn reclaim_hotkeys(app: AppHandle) -> hotkeys::HotkeyStatus { } -/// Explains the duplicate-instance problem, then quits this copy. -/// -/// The dialog must be driven from a worker thread: the main thread owns the -/// event loop that renders it. -fn warn_about_duplicate_instance(app: AppHandle, zh: bool) { - std::thread::spawn(move || { - use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind}; - let (title, body, confirm) = if zh { - ( - "Shift 已在运行", - "检测到另一个 Shift 进程。macOS 只把全局快捷键交给最先注册的实例,\ - 因此后启动的副本按键盘不会有任何反应。\n\n\ - 点“确定”退出这个副本;另一个 Shift 会正常工作(设置面板里也可以一键退出其他副本)。", - "退出此副本", - ) - } else { - ( - "Shift is already running", - "Another Shift process is already running. macOS delivers a global hotkey to only the \ - copy that registered it first, so the keyboard shortcuts of this copy do nothing.\n\n\ - Press OK to quit this copy; the other Shift keeps working. Settings can also quit \ - the other copies for you.", - "Quit this copy", - ) - }; - std::thread::sleep(std::time::Duration::from_millis(400)); - app.dialog() - .message(body) - .kind(MessageDialogKind::Warning) - .title(title) - .buttons(MessageDialogButtons::OkCustom(confirm.to_string())) - .blocking_show(); - app.exit(0); - }); -} - -/// Best-effort UI language for the very early duplicate-instance dialog. -fn sys_locale_is_zh() -> bool { - std::env::var("APPLELOCALE_ID") - .or_else(|_| std::env::var("LANG")) - .unwrap_or_default() - .starts_with("zh") +/// A second copy can never own the hotkeys, so it defers to the running one: +/// mark the attempt (Settings will explain it), raise the copy that owns the +/// shortcuts, and exit. A modal is useless here — an Accessory app has no +/// activated UI to host it. +fn defer_to_running_copy(app: &AppHandle) { + hotkeys::mark_duplicate_attempt(app); + hotkeys::wake_running_copy(app); + std::thread::sleep(std::time::Duration::from_millis(120)); } fn shortcut_action(shortcut: &Shortcut) -> Option<&'static str> { @@ -320,10 +286,24 @@ pub fn run() { let _ = window.hide(); } } - warn_about_duplicate_instance(app.handle().clone(), sys_locale_is_zh()); - return Ok(()); + defer_to_running_copy(app.handle()); + std::process::exit(0); } + // Restore the persisted switch before the drag monitors start. + let persisted = settings::load(app.handle()); + if let Some(state) = app.try_state::() { + state + .drag_enabled + .store(persisted.drag_enabled, Ordering::Relaxed); + } + if persisted.autostart != autostart::is_enabled() { + if let Err(error) = autostart::set_enabled(persisted.autostart) { + eprintln!("Could not sync launch at login: {error}"); + } + } + + hotkeys::spawn_watcher(app.handle().clone()); setup_tray(app.handle())?; register_shortcuts(app.handle())?; drag_bridge::spawn(app.handle()); diff --git a/src/components/MainWindow.tsx b/src/components/MainWindow.tsx index a75eaa6..9ddb9b2 100644 --- a/src/components/MainWindow.tsx +++ b/src/components/MainWindow.tsx @@ -205,6 +205,7 @@ export function MainWindow() { const [dropAction, setDropAction] = useState(null); const [hotkeys, setHotkeys] = useState(null); const dropTargets = useRef>>({}); + const windowOrigin = useRef<{ x: number; y: number } | null>(null); function flash(message: string, duration = 2600) { if (toastTimer.current) window.clearTimeout(toastTimer.current); @@ -255,12 +256,32 @@ export function MainWindow() { }, 450); } - // Drag positions arrive in physical pixels relative to the webview, while the - // buttons are measured in CSS pixels, so both sides need the same scale. - function actionAt(position: { x: number; y: number }): DropAction | null { + // wry reports drag positions two different ways: AppKit passes draggingLocation, + // i.e. points relative to the webview and therefore 1:1 with CSS pixels, while + // the Windows drag controller forwards OLE screen coordinates in physical + // pixels. Only the second reading needs the window origin and scale removed. + function localPoint(position: { x: number; y: number }): { x: number; y: number } | null { + if (IS_MAC) return position; + const origin = windowOrigin.current; + if (!origin) return null; const scale = window.devicePixelRatio || 1; - const x = position.x / scale; - const y = position.y / scale; + return { x: (position.x - origin.x) / scale, y: (position.y - origin.y) / scale }; + } + + async function readWindowOrigin() { + if (IS_MAC) return; + try { + const position = await getCurrentWebview().position(); + windowOrigin.current = { x: position.x, y: position.y }; + } catch { + windowOrigin.current = null; + } + } + + function actionAt(position: { x: number; y: number }): DropAction | null { + const point = localPoint(position); + if (!point) return null; + const { x, y } = point; const entries: Array<[DropAction, HTMLElement | null | undefined]> = [ ["formats", dropTargets.current.formats], ["tools", dropTargets.current.tools], @@ -384,6 +405,12 @@ export function MainWindow() { // eslint-disable-next-line react-hooks/exhaustive-deps }, []); + // Reading the status also consumes a "second copy tried to start" marker. + useEffect(() => { + if (settingsOpen && isTauri()) void refreshHotkeys(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [settingsOpen]); + useEffect(() => { const unlisteners: Array<() => void> = []; if (isTauri()) { @@ -391,7 +418,9 @@ export function MainWindow() { .onDragDropEvent((event) => { if (event.payload.type === "enter") { setDragging(true); - setDropAction(actionAt(event.payload.position)); + const position = event.payload.position; + // Cache the origin once per drag: it cannot move while dragging. + void readWindowOrigin().then(() => setDropAction(actionAt(position))); } if (event.payload.type === "over") { setDropAction(actionAt(event.payload.position)); @@ -777,6 +806,11 @@ export function MainWindow() { {t("hotkeys")} + {hotkeys && hotkeys.live && hotkeys.others.length === 0 ? ( +

+ {hotkeys.recentDuplicate ? t("hotkeysDuplicate") : t("hotkeysOk")} +

+ ) : null} {hotkeys && (!hotkeys.live || hotkeys.others.length > 0) ? (

@@ -789,9 +823,7 @@ export function MainWindow() { {t("hotkeysFix")}

- ) : ( -

{t("hotkeysOk")}

- )} + ) : null}
{(hotkeys?.hotkeys.length ? hotkeys.hotkeys diff --git a/src/i18n.ts b/src/i18n.ts index 368c452..16a092c 100644 --- a/src/i18n.ts +++ b/src/i18n.ts @@ -131,6 +131,15 @@ const messages: Record> = { dragRingsHint: "Hold Shift while dragging a file to open the radial menu.", autostart: "Launch at login", autostartHint: "Start Shift automatically when you sign in.", + hotkeys: "Keyboard shortcuts", + hotkeysOk: "This copy of Shift owns the shortcuts, so the keyboard works.", + hotkeysDuplicate: + "A second copy of Shift tried to start and was closed automatically. macOS only gives global hotkeys to one copy, so keeping a single copy is what keeps the keyboard shortcuts working.", + hotkeysNotLive: + "macOS refused these shortcuts, usually because another app already uses them. Close the conflicting app and retry.", + hotkeysOthers: + "{count} other Shift process is already running. macOS gives global hotkeys to only one of them, so the shortcuts of the others do nothing.", + hotkeysFix: "Quit the other copies and reclaim the shortcuts", accessCheck: "Write access", accessCheckHint: "Confirm Shift can write to each output folder. macOS may ask for permission the first time.", checking: "Checking…", @@ -275,6 +284,12 @@ const messages: Record> = { dragRingsHint: "在访达或资源管理器中拖动文件时按住 Shift 即可唤出圆环。", autostart: "开机时启动", autostartHint: "登录系统后自动启动 Shift。", + hotkeys: "键盘快捷键", + hotkeysOk: "当前副本已持有快捷键,键盘快捷键可以正常使用。", + hotkeysDuplicate: "刚才有第二个 Shift 副本启动,已自动退出。macOS 只把全局快捷键交给其中一个副本,只保留一个副本才能保证快捷键生效。", + hotkeysNotLive: "macOS 拒绝了这些快捷键,通常是被其他应用占用了。关闭冲突的应用后重试。", + hotkeysOthers: "检测到 {count} 个其他 Shift 进程。macOS 只把全局快捷键交给其中一个,其余副本按键盘不会有任何反应。", + hotkeysFix: "退出其他副本并重新接管快捷键", accessCheck: "写入权限", accessCheckHint: "检查 Shift 是否可写入各输出目录。macOS 可能首次请求授权。", checking: "检测中…", diff --git a/src/styles.css b/src/styles.css index 109e134..6da2d73 100644 --- a/src/styles.css +++ b/src/styles.css @@ -3020,6 +3020,41 @@ kbd { transform: translateX(14px); } +/* Hotkey ownership panel: duplicate copies silently lose the global shortcuts. */ +.home-hotkeys.is-warn { + display: flex; + flex-direction: column; + gap: 8px; + margin-bottom: 10px; + padding: 10px 11px; + border: 1px solid rgba(217, 79, 31, 0.2); + border-radius: 12px; + background: rgba(255, 241, 232, 0.78); +} + +.home-hotkeys.is-warn .home-settings-hint { + margin: 0; + color: #7a3a20; +} + +.home-hotkey-list { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-top: 9px; +} + +.home-hotkey-list span { + padding: 4px 9px; + border: 1px solid rgba(104, 68, 47, 0.12); + border-radius: 8px; + color: #7c5d4d; + background: rgba(255, 255, 255, 0.75); + font-size: 10px; + font-weight: 650; + letter-spacing: 0.02em; +} + .home-checks { display: flex; flex-direction: column; diff --git a/src/types.ts b/src/types.ts index bc6c5ee..6423670 100644 --- a/src/types.ts +++ b/src/types.ts @@ -81,6 +81,8 @@ export interface HotkeyStatus { hotkeys: string[]; /** Pids of other running Shift processes. */ others: number[]; + /** A second copy tried to start in the last ten minutes. */ + recentDuplicate: boolean; } export interface WriteCheck {