From 26d1bf247cf1a06656502ffe39bfb0fb3aa274ed Mon Sep 17 00:00:00 2001 From: apyfz Date: Tue, 20 Oct 2026 01:32:07 +0700 Subject: [PATCH 1/3] Add optional Windows hotkey to launch Cleanmeter after Quit --- tauri-app/src-tauri/Cargo.toml | 1 + tauri-app/src-tauri/src/commands.rs | 36 ++- tauri-app/src-tauri/src/launch_hotkey.rs | 243 ++++++++++++++++++ tauri-app/src-tauri/src/lib.rs | 19 +- tauri-app/src-tauri/src/shortcuts.rs | 68 +++++ tauri-app/src-tauri/src/types.rs | 3 + tauri-app/src-tauri/tauri.conf.json | 3 +- .../src-tauri/windows/installer-hooks.nsh | 3 + .../settings/settings/SettingsTab.tsx | 45 +++- tauri-app/src/hooks/useHotkey.ts | 20 +- tauri-app/src/lib/tauri.ts | 5 + tauri-app/src/lib/types.ts | 2 + .../src/stores/settings-store.reset.test.ts | 18 +- tauri-app/src/stores/settings-store.ts | 10 + 14 files changed, 465 insertions(+), 11 deletions(-) create mode 100644 tauri-app/src-tauri/src/launch_hotkey.rs create mode 100644 tauri-app/src-tauri/windows/installer-hooks.nsh diff --git a/tauri-app/src-tauri/Cargo.toml b/tauri-app/src-tauri/Cargo.toml index ab9cdd4..63d85ca 100644 --- a/tauri-app/src-tauri/Cargo.toml +++ b/tauri-app/src-tauri/Cargo.toml @@ -40,6 +40,7 @@ windows = { version = "0.58", features = [ "Win32_Security", "Win32_System_Pipes", "Win32_System_IO", + "Win32_System_Com", "Win32_System_Threading", "Win32_System_Diagnostics_ToolHelp", "Win32_UI_Shell", diff --git a/tauri-app/src-tauri/src/commands.rs b/tauri-app/src-tauri/src/commands.rs index 5f21bb0..7f40587 100644 --- a/tauri-app/src-tauri/src/commands.rs +++ b/tauri-app/src-tauri/src/commands.rs @@ -95,12 +95,46 @@ pub fn get_settings(settings_mgr: State<'_, SettingsManager>) -> OverlaySettings settings_mgr.get_settings() } +#[tauri::command] +pub fn take_pending_overlay_launch(app: AppHandle) -> bool { + let state = app.state::(); + let mut requests = state.0.lock().unwrap(); + requests.ready() +} + +#[tauri::command] +pub fn configure_launch_hotkey(enabled: bool, accelerator: String, settings_mgr: State<'_, SettingsManager>, app: AppHandle) -> Result { + let mut settings = settings_mgr.get_settings(); + if enabled { + crate::launch_hotkey::shell_hotkey(&accelerator)?; + if accelerator == settings.recording_shortcut { return Err("This shortcut is already used for recording.".into()); } + } + crate::shortcuts::apply(&app, crate::shortcuts::ShortcutAction::ToggleOverlay, "")?; + if let Err(error) = crate::launch_hotkey::sync(if enabled { Some(&accelerator) } else { None }) { + crate::shortcuts::apply_all(&app, &settings); + return Err(error); + } + settings.launch_with_hotkey = enabled; + settings.overlay_shortcut = accelerator; + settings_mgr.save_settings(settings.clone()); + crate::shortcuts::apply_all(&app, &settings); + let _ = app.emit("settings-changed", &settings); + Ok(settings) +} + #[tauri::command] pub fn save_settings( - settings: OverlaySettings, + mut settings: OverlaySettings, settings_mgr: State<'_, SettingsManager>, app: AppHandle, ) { + // Launch ownership changes only through configure_launch_hotkey. A delayed + // full-settings save from the other webview must not undo that transaction. + let current = settings_mgr.get_settings(); + settings.launch_with_hotkey = current.launch_with_hotkey; + if current.launch_with_hotkey { + settings.overlay_shortcut = current.overlay_shortcut; + } settings_mgr.save_settings(settings.clone()); // Re-register the global shortcuts from whatever was just saved. // diff --git a/tauri-app/src-tauri/src/launch_hotkey.rs b/tauri-app/src-tauri/src/launch_hotkey.rs new file mode 100644 index 0000000..fb5f9b6 --- /dev/null +++ b/tauri-app/src-tauri/src/launch_hotkey.rs @@ -0,0 +1,243 @@ +//! Explorer owns the optional launch hotkey. No monitoring process is needed +//! while Cleanmeter is closed. This deliberately does not bypass UAC. +use std::sync::Mutex; + +pub const TOGGLE_ARG: &str = "--toggle-overlay"; +pub fn is_overlay_launch(args: &[String]) -> bool { + args.iter().skip(1).any(|arg| arg == TOGGLE_ARG) +} + +// IShellLink stores a virtual key in the low byte and HOTKEYF_* in the high +// byte (different values from RegisterHotKey's MOD_*). Restrict this mode to +// Ctrl+Alt combinations; Win and media keys cannot be represented here. +pub fn shell_hotkey(accelerator: &str) -> Result { + let mut modifiers = 0u16; + let mut key = None; + for part in accelerator.split('+') { + match part { + "Ctrl" | "Control" => modifiers |= 2, + "Alt" => modifiers |= 4, + "Shift" => modifiers |= 1, + value => { + if key.is_some() { + return Err("Choose one key with Ctrl+Alt.".into()); + } + key = Some(match value { + "Space" => 0x20, + v if v.starts_with("Key") && v.len() == 4 && v.as_bytes()[3].is_ascii_uppercase() => v.as_bytes()[3] as u16, + v if v.starts_with("Digit") && v.len() == 6 && v.as_bytes()[5].is_ascii_digit() => v.as_bytes()[5] as u16, + v if v.len() == 1 && v.as_bytes()[0].is_ascii_alphanumeric() => v.as_bytes()[0].to_ascii_uppercase() as u16, + v if v.starts_with('F') => { + let number = v[1..].parse::().unwrap_or(0); + if !(1..=11).contains(&number) { return Err("Use F1 through F11 for a launch shortcut.".into()); } + 0x70 + number - 1 + } + _ => return Err("Launch shortcuts support Ctrl+Alt with a letter, number, Space, or F1–F11.".into()), + }); + } + } + } + if modifiers & 6 != 6 { + return Err("Launch shortcuts require Ctrl+Alt (Shift is optional).".into()); + } + Ok((modifiers << 8) | key.ok_or("Choose a key with Ctrl+Alt.")?) +} + +static APPLIED: Mutex> = Mutex::new(None); + +pub fn sync(accelerator: Option<&str>) -> Result<(), String> { + let mut applied = APPLIED.lock().map_err(|e| e.to_string())?; + let desired = accelerator.unwrap_or(""); + if applied.as_deref() == Some(desired) { + return Ok(()); + } + #[cfg(windows)] + windows_link::update(accelerator)?; + #[cfg(not(windows))] + if accelerator.is_some() { + return Err("Launch shortcuts are only available on Windows.".into()); + } + *applied = Some(desired.to_owned()); + Ok(()) +} + +#[cfg(windows)] +mod windows_link { + use std::path::{Path, PathBuf}; + use windows::core::{Interface, HSTRING, PCWSTR}; + use windows::Win32::System::Com::{ + CoCreateInstance, CoInitializeEx, CoTaskMemFree, CoUninitialize, IPersistFile, + CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, + }; + use windows::Win32::UI::Shell::{ + FOLDERID_Programs, IShellLinkW, SHChangeNotify, SHGetKnownFolderPath, ShellLink, + KF_FLAG_DEFAULT, SHCNE_CREATE, SHCNE_DELETE, SHCNE_UPDATEITEM, SHCNF_FLUSH, SHCNF_PATHW, + }; + + struct Apartment; + impl Drop for Apartment { + fn drop(&mut self) { + unsafe { + CoUninitialize(); + } + } + } + + pub fn update(accelerator: Option<&str>) -> Result<(), String> { + // A fresh STA avoids RPC_E_CHANGED_MODE on Tauri's existing threads. + let accelerator = accelerator.map(str::to_owned); + std::thread::spawn(move || -> Result<(), String> { + unsafe { + CoInitializeEx(None, COINIT_APARTMENTTHREADED) + .ok() + .map_err(|e| e.to_string())?; + } + let _apartment = Apartment; + let folder = unsafe { SHGetKnownFolderPath(&FOLDERID_Programs, KF_FLAG_DEFAULT, None) } + .map_err(|e| e.to_string())?; + let folder_string = unsafe { folder.to_string() }; + unsafe { + CoTaskMemFree(Some(folder.0.cast())); + } + let link = PathBuf::from(folder_string.map_err(|e| e.to_string())?) + .join("Cleanmeter Overlay.lnk"); + let existed = link.exists(); + if let Some(ref accelerator) = accelerator { + let hotkey = super::shell_hotkey(&accelerator)?; + let exe = std::env::current_exe().map_err(|e| e.to_string())?; + write_link(&link, &exe, hotkey).map_err(|e| e.to_string())?; + } else { + match std::fs::remove_file(&link) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(e) => return Err(e.to_string()), + } + } + let path = HSTRING::from(link.as_os_str()); + let event = if accelerator.is_none() { + SHCNE_DELETE + } else if existed { + SHCNE_UPDATEITEM + } else { + SHCNE_CREATE + }; + unsafe { + SHChangeNotify( + event, + SHCNF_PATHW | SHCNF_FLUSH, + Some(path.as_ptr().cast()), + None, + ); + } + Ok(()) + }) + .join() + .map_err(|_| "Could not update the launch shortcut".to_string())? + } + + pub(super) fn write_link(path: &Path, exe: &Path, hotkey: u16) -> windows::core::Result<()> { + unsafe { + let link: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER)?; + link.SetPath(&HSTRING::from(exe.as_os_str()))?; + link.SetArguments(&HSTRING::from(super::TOGGLE_ARG))?; + if let Some(parent) = exe.parent() { + link.SetWorkingDirectory(&HSTRING::from(parent.as_os_str()))?; + } + link.SetIconLocation(&HSTRING::from(exe.as_os_str()), 0)?; + link.SetDescription(&HSTRING::from("Launch Cleanmeter or show/hide the overlay"))?; + link.SetHotkey(hotkey)?; + let file: IPersistFile = link.cast()?; + file.Save(PCWSTR(HSTRING::from(path.as_os_str()).as_ptr()), true) + } + } + + #[cfg(test)] + mod tests { + use super::*; + use windows::Win32::System::Com::STGM_READ; + + #[test] + fn shell_link_round_trips_launch_arguments_and_hotkey() { + // Temp is outside Explorer's shortcut folders: this exercises COM + // persistence without installing a hotkey on the developer's desktop. + unsafe { + CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok().unwrap(); + } + let _apartment = Apartment; + let directory = + std::env::temp_dir().join(format!("cleanmeter-link-test-{}", std::process::id())); + std::fs::create_dir_all(&directory).unwrap(); + let path = directory.join("overlay.lnk"); + let exe = std::env::current_exe().unwrap(); + write_link(&path, &exe, 0x0620).unwrap(); + unsafe { + let link: IShellLinkW = + CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER).unwrap(); + let file: IPersistFile = link.cast().unwrap(); + file.Load(&HSTRING::from(path.as_os_str()), STGM_READ) + .unwrap(); + assert_eq!(link.GetHotkey().unwrap(), 0x0620); + let mut arguments = [0u16; 128]; + link.GetArguments(&mut arguments).unwrap(); + let end = arguments.iter().position(|&c| c == 0).unwrap(); + assert_eq!( + String::from_utf16_lossy(&arguments[..end]), + super::super::TOGGLE_ARG + ); + let mut target = [0u16; 1024]; + link.GetPath(&mut target, std::ptr::null_mut(), 0).unwrap(); + let end = target.iter().position(|&c| c == 0).unwrap(); + assert_eq!(PathBuf::from(String::from_utf16_lossy(&target[..end])), exe); + } + std::fs::remove_file(path).unwrap(); + std::fs::remove_dir(directory).unwrap(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn encodes_shell_modifiers_not_register_hotkey_modifiers() { + assert_eq!(shell_hotkey("Ctrl+Alt+Space").unwrap(), 0x0620); + assert_eq!(shell_hotkey("Ctrl+Alt+F10").unwrap(), 0x0679); + assert_eq!(shell_hotkey("Ctrl+Alt+Shift+KeyC").unwrap(), 0x0743); + assert_eq!(shell_hotkey("Ctrl+Alt+Digit1").unwrap(), 0x0631); + } + #[test] + fn rejects_unrepresentable_or_incomplete_shortcuts() { + for key in [ + "", + "Alt+F10", + "Super+KeyA", + "Ctrl+Alt", + "Ctrl+Alt+F12", + "Ctrl+Alt+MediaPlayPause", + "Ctrl+Alt+KeyA+KeyB", + ] { + assert!(shell_hotkey(key).is_err(), "{key}"); + } + } + #[test] + fn only_exact_launch_argument_routes_to_overlay() { + assert!(is_overlay_launch(&[ + "Cleanmeter.exe".into(), + TOGGLE_ARG.into() + ])); + assert!(!is_overlay_launch(&[TOGGLE_ARG.into()])); + assert!(!is_overlay_launch(&[ + "Cleanmeter.exe".into(), + "--toggle-overlay=false".into() + ])); + } + + #[test] + fn existing_settings_do_not_enable_launch_shortcuts() { + let defaults = crate::types::OverlaySettings::default(); + let mut json = serde_json::to_value(defaults).unwrap(); + json.as_object_mut().unwrap().remove("launchWithHotkey"); + let old: crate::types::OverlaySettings = serde_json::from_value(json).unwrap(); + assert!(!old.launch_with_hotkey); + } +} diff --git a/tauri-app/src-tauri/src/lib.rs b/tauri-app/src-tauri/src/lib.rs index cf6dd54..48859b3 100644 --- a/tauri-app/src-tauri/src/lib.rs +++ b/tauri-app/src-tauri/src/lib.rs @@ -4,6 +4,7 @@ mod feedback_diagnostics; mod pipe_client; mod pipe_input; mod shortcuts; +mod launch_hotkey; mod settings; mod tray; mod types; @@ -50,12 +51,16 @@ fn relaunch_as_admin() { let exe = std::env::current_exe().expect("failed to get exe path"); let exe_wide: Vec = exe.to_string_lossy().encode_utf16().chain(std::iter::once(0)).collect(); let verb: Vec = "runas\0".encode_utf16().collect(); + // Preserve the only supported launch action across self-elevation. + let args: Vec = std::env::args().collect(); + let parameters = if launch_hotkey::is_overlay_launch(&args) { "--toggle-overlay\0" } else { "\0" }; + let parameters: Vec = parameters.encode_utf16().collect(); unsafe { ShellExecuteW( HWND::default(), PCWSTR(verb.as_ptr()), PCWSTR(exe_wide.as_ptr()), - PCWSTR::null(), + PCWSTR(parameters.as_ptr()), PCWSTR::null(), SW_SHOW, ); @@ -285,7 +290,12 @@ pub fn run() { .plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_process::init()) .plugin(tauri_plugin_updater::Builder::new().build()) - .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| { + .manage(shortcuts::OverlayLaunchRequests::default()) + .plugin(tauri_plugin_single_instance::init(|app, args, _cwd| { + if launch_hotkey::is_overlay_launch(&args) { + shortcuts::request_overlay_toggle(app); + return; + } // Focus the existing settings window when a second instance launches if let Some(window) = app.get_webview_window("settings") { let _ = window.show(); @@ -304,7 +314,8 @@ pub fn run() { .app_data_dir() .expect("Failed to get app data dir"); let settings_mgr = SettingsManager::new(app_data_dir); - let start_minimized = settings_mgr.get_preferences().start_minimized; + let start_minimized = settings_mgr.get_preferences().start_minimized + || launch_hotkey::is_overlay_launch(&std::env::args().collect::>()); app.manage(settings_mgr); // One-time autostart migration: older builds registered autostart @@ -674,6 +685,8 @@ pub fn run() { commands::save_settings, commands::clear_settings, commands::set_shortcut_capturing, + commands::configure_launch_hotkey, + commands::take_pending_overlay_launch, commands::get_sidecar_status, commands::get_preferences, commands::save_preferences, diff --git a/tauri-app/src-tauri/src/shortcuts.rs b/tauri-app/src-tauri/src/shortcuts.rs index 00bc482..11e0688 100644 --- a/tauri-app/src-tauri/src/shortcuts.rs +++ b/tauri-app/src-tauri/src/shortcuts.rs @@ -46,6 +46,7 @@ use std::collections::HashMap; use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::atomic::AtomicBool; use std::sync::Mutex; use log::{info, warn}; @@ -121,6 +122,7 @@ impl LowsMode { /// registered for each action. Named Registry, not State, because /// `ShortcutState` is the plugin's own press/release enum. pub struct ShortcutRegistry { + capturing: AtomicBool, /// The sidecar's current lows mode, as a `LowsMode` discriminant. Starts /// Live, which is the sidecar's own startup default — the two have to /// agree without anything being sent, because nothing is sent until the @@ -134,6 +136,7 @@ pub struct ShortcutRegistry { impl ShortcutRegistry { pub fn new() -> Self { ShortcutRegistry { + capturing: AtomicBool::new(false), lows_mode: AtomicU8::new(LowsMode::Live.wire()), registered: Mutex::new(HashMap::new()), } @@ -213,11 +216,22 @@ pub fn toggle_recording(app: &AppHandle) { /// reset to defaults — so there is one place that knows the mapping from /// settings field to action. pub fn apply_all(app: &AppHandle, settings: &OverlaySettings) { + if app.state::().capturing.load(Ordering::Relaxed) { return; } + let shell = settings.launch_with_hotkey && !settings.overlay_shortcut.is_empty(); + // Hand ownership to Explorer before saving the link. Registering the same + // combo here as well would leave one owner silently stealing the other's key. + if shell { let _ = apply(app, ShortcutAction::ToggleOverlay, ""); } + let shell_result = crate::launch_hotkey::sync(if shell { Some(&settings.overlay_shortcut) } else { None }); + if let Err(ref error) = shell_result { + warn!("Launch shortcut: {error}"); + let _ = app.emit("launch-hotkey-error", error); + } let mut unavailable = HashMap::<&'static str, String>::new(); for (action, accelerator) in [ (ShortcutAction::ToggleOverlay, &settings.overlay_shortcut), (ShortcutAction::ToggleRecording, &settings.recording_shortcut), ] { + if action == ShortcutAction::ToggleOverlay && shell && shell_result.is_ok() { continue; } if let Err(accel) = apply(app, action, accelerator) { unavailable.insert(action.settings_key(), accel); } @@ -321,10 +335,17 @@ pub fn apply( /// overlay holds Alt+F1/F2/F3/F9/F10 by default) still never reaches us, and /// nothing here can change that. pub fn set_capturing(app: &AppHandle, capturing: bool, settings: &OverlaySettings) { + if let Some(state) = app.try_state::() { + state.capturing.store(capturing, Ordering::Relaxed); + } if !capturing { apply_all(app, settings); return; } + // Explorer's accelerator must also be released while editing a shortcut. + if let Err(error) = crate::launch_hotkey::sync(None) { + warn!("Could not release launch shortcut for capture: {error}"); + } let Some(state) = app.try_state::() else { return; }; @@ -339,10 +360,57 @@ pub fn set_capturing(app: &AppHandle, capturing: bool, settings: &OverlaySetting info!("Global shortcuts released for capture"); } +#[derive(Default)] +pub struct OverlayLaunchRequests(pub Mutex); + +#[derive(Default)] +pub struct OverlayLaunchState { + ready: bool, + pending: bool, +} + +impl OverlayLaunchState { + fn request(&mut self) -> bool { + if self.ready { return true; } + self.pending = !self.pending; + false + } + + pub fn ready(&mut self) -> bool { + self.ready = true; + std::mem::take(&mut self.pending) + } +} + +pub fn request_overlay_toggle(app: &AppHandle) { + let state = app.state::(); + let mut requests = state.0.lock().unwrap(); + if requests.request() { + let _ = app.emit("hotkey", "toggle-overlay"); + } +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn overlay_launch_requests_wait_for_startup_then_drain_once() { + let mut requests = OverlayLaunchState::default(); + assert!(!requests.request()); + assert!(requests.ready()); + assert!(!requests.ready()); + assert!(requests.request()); + } + + #[test] + fn two_launch_requests_during_startup_cancel_each_other() { + let mut requests = OverlayLaunchState::default(); + assert!(!requests.request()); + assert!(!requests.request()); + assert!(!requests.ready()); + } + /// The hotkey is one key covering three states, so the cycle order IS the /// feature: a live reading you can start a run from, a run you can stop and /// read, and a way back to live. Any reordering strands one of them. diff --git a/tauri-app/src-tauri/src/types.rs b/tauri-app/src-tauri/src/types.rs index 683ce27..a00bb3d 100644 --- a/tauri-app/src-tauri/src/types.rs +++ b/tauri-app/src-tauri/src/types.rs @@ -406,6 +406,8 @@ pub struct OverlaySettings { // combo rather than empty. #[serde(rename = "overlayShortcut", default = "default_overlay_shortcut")] pub overlay_shortcut: String, + #[serde(rename = "launchWithHotkey", default)] + pub launch_with_hotkey: bool, pub sensors: SensorsConfig, } @@ -452,6 +454,7 @@ impl Default for OverlaySettings { selected_gpu_id: String::new(), recording_shortcut: default_recording_shortcut(), overlay_shortcut: default_overlay_shortcut(), + launch_with_hotkey: false, sensors: SensorsConfig::default(), } } diff --git a/tauri-app/src-tauri/tauri.conf.json b/tauri-app/src-tauri/tauri.conf.json index ba91de2..27c8cf9 100644 --- a/tauri-app/src-tauri/tauri.conf.json +++ b/tauri-app/src-tauri/tauri.conf.json @@ -68,7 +68,8 @@ "nsis": { "displayLanguageSelector": false, "installerIcon": "icons/icon.ico", - "installMode": "currentUser" + "installMode": "currentUser", + "installerHooks": "windows/installer-hooks.nsh" }, "signCommand": { "cmd": "powershell", diff --git a/tauri-app/src-tauri/windows/installer-hooks.nsh b/tauri-app/src-tauri/windows/installer-hooks.nsh new file mode 100644 index 0000000..07c8dd6 --- /dev/null +++ b/tauri-app/src-tauri/windows/installer-hooks.nsh @@ -0,0 +1,3 @@ +!macro NSIS_HOOK_POSTUNINSTALL + Delete "$SMPROGRAMS\Cleanmeter Overlay.lnk" +!macroend diff --git a/tauri-app/src/components/settings/settings/SettingsTab.tsx b/tauri-app/src/components/settings/settings/SettingsTab.tsx index cad53a2..9a86ac5 100644 --- a/tauri-app/src/components/settings/settings/SettingsTab.tsx +++ b/tauri-app/src/components/settings/settings/SettingsTab.tsx @@ -11,8 +11,8 @@ import { } from "@/components/shadcn/select"; import { SelectFieldTrigger } from "@/components/ui/SelectField"; import { cn } from "@/lib/utils"; -import { getAutoStart, setAutoStart } from "@/lib/tauri"; -import { systemPrefersDark, useSettingsStore } from "@/stores/settings-store"; +import { configureLaunchHotkey, getAutoStart, setAutoStart, onLaunchHotkeyError } from "@/lib/tauri"; +import { flushSettingsSave, systemPrefersDark, useSettingsStore } from "@/stores/settings-store"; import { useUpdaterStore } from "@/stores/updater-store"; import { POLLING_RATES } from "@/lib/types"; import type { TemperatureUnit } from "@/lib/types"; @@ -152,6 +152,29 @@ function GeneralSection() { function ShortcutsSection() { const settings = useSettingsStore((s) => s.settings); const updateSettings = useSettingsStore((s) => s.updateSettings); + const [pending, setPending] = React.useState(false); + const [launchError, setLaunchError] = React.useState(""); + React.useEffect(() => { + let mounted = true; + let unlisten: (() => void) | undefined; + void onLaunchHotkeyError(setLaunchError).then((stop) => { + if (mounted) unlisten = stop; else stop(); + }); + return () => { mounted = false; unlisten?.(); }; + }, []); + const windows = typeof navigator !== "undefined" && /Windows/i.test(navigator.userAgent); + const configure = async (enabled: boolean, accelerator: string) => { + if (pending) return; + setPending(true); + setLaunchError(""); + try { + await flushSettingsSave(); + const saved = await configureLaunchHotkey(enabled, accelerator); + if (saved) useSettingsStore.setState({ settings: saved }); + } catch (error) { + setLaunchError(String(error)); + } finally { setPending(false); } + }; const overlayAccelerator = settings.overlayShortcut ?? OVERLAY_SHORTCUT_DEFAULT; const recordingAccelerator = settings.recordingShortcut ?? RECORDING_SHORTCUT_DEFAULT; @@ -163,10 +186,26 @@ function ShortcutsSection() { label="Show/hide overlay" accelerator={overlayAccelerator} defaultAccelerator={OVERLAY_SHORTCUT_DEFAULT} - onChange={(overlayShortcut) => updateSettings({ overlayShortcut })} + onChange={(overlayShortcut) => { + if (settings.launchWithHotkey) void configure(!!overlayShortcut, overlayShortcut); + else updateSettings({ overlayShortcut }); + }} conflictsWith={{ "Start/stop FPS lows recording": recordingAccelerator }} className="gap-[var(--spacingL)]" /> + {windows && ( +
+ +

+ Use Ctrl+Alt with a letter, number, Space, or F1–F11. Windows launches Cleanmeter with this shortcut, even after Quit. An administrator prompt may appear. Does not enable startup with Windows. +

+ {launchError &&

{launchError}

} +
+ )} s.toggleOverlay); + const sensorReady = useSettingsStore((s) => s.sensorData !== null); + const [listenerReady, setListenerReady] = useState(false); useEffect(() => { let unlisten: (() => void) | undefined; + let mounted = true; onHotkey((action) => { if (action === "toggle-overlay") { @@ -15,11 +18,24 @@ export function useHotkey() { // The recording keys never come through here: shortcuts.rs handles // them itself, because they have to work with every window closed. }).then((u) => { + if (!mounted) { u(); return; } unlisten = u; + setListenerReady(true); }); return () => { + mounted = false; unlisten?.(); }; }, [toggleOverlay]); + + useEffect(() => { + // Initial sensor arrival auto-shows the overlay. Drain launch requests + // afterwards so a second press during boot hides it rather than having + // its intent overwritten by that initial auto-show. + if (!listenerReady || !sensorReady) return; + void takePendingOverlayLaunch().then((pending) => { + if (pending) toggleOverlay(); + }); + }, [listenerReady, sensorReady, toggleOverlay]); } diff --git a/tauri-app/src/lib/tauri.ts b/tauri-app/src/lib/tauri.ts index ef3ffbe..d2f5390 100644 --- a/tauri-app/src/lib/tauri.ts +++ b/tauri-app/src/lib/tauri.ts @@ -85,6 +85,11 @@ export const getSettings = () => export const saveSettings = (settings: OverlaySettings) => safeInvoke("save_settings", { settings }); export const clearSettings = () => safeInvoke("clear_settings"); +export const configureLaunchHotkey = (enabled: boolean, accelerator: string) => + safeInvoke("configure_launch_hotkey", { enabled, accelerator }); +export const takePendingOverlayLaunch = () => safeInvoke("take_pending_overlay_launch"); +export const onLaunchHotkeyError = (callback: (message: string) => void) => + safeListen("launch-hotkey-error", (event) => callback(event.payload)); export const getPreferences = () => safeInvoke("get_preferences"); /** Polled once on mount: events fired before the webview loaded are lost. */ export const getSidecarStatus = () => safeInvoke("get_sidecar_status"); diff --git a/tauri-app/src/lib/types.ts b/tauri-app/src/lib/types.ts index c64c473..f787596 100644 --- a/tauri-app/src/lib/types.ts +++ b/tauri-app/src/lib/types.ts @@ -150,6 +150,7 @@ export interface OverlaySettings { * what it was; the banner is gone and this card replaced it. */ overlayShortcut: string; + launchWithHotkey: boolean; sensors: SensorsConfig; } @@ -257,6 +258,7 @@ export const DEFAULT_SETTINGS: OverlaySettings = { selectedGpuId: "", recordingShortcut: RECORDING_SHORTCUT_DEFAULT, overlayShortcut: OVERLAY_SHORTCUT_DEFAULT, + launchWithHotkey: false, sensors: { framerate: { isEnabled: true, customReadingId: "", targetAppName: "" }, frametime: { isEnabled: true, customReadingId: "" }, diff --git a/tauri-app/src/stores/settings-store.reset.test.ts b/tauri-app/src/stores/settings-store.reset.test.ts index c8c3a75..02a819b 100644 --- a/tauri-app/src/stores/settings-store.reset.test.ts +++ b/tauri-app/src/stores/settings-store.reset.test.ts @@ -4,6 +4,7 @@ import * as tauri from "@/lib/tauri"; vi.mock("@/lib/tauri", () => ({ saveSettings: vi.fn().mockResolvedValue(undefined), + configureLaunchHotkey: vi.fn().mockResolvedValue(undefined), savePreferences: vi.fn().mockResolvedValue(undefined), setAutoStart: vi.fn().mockResolvedValue(undefined), setPollingRate: vi.fn().mockResolvedValue(undefined), @@ -11,7 +12,7 @@ vi.mock("@/lib/tauri", () => ({ selectPresentMonApp: vi.fn().mockResolvedValue(undefined), })); -const { useSettingsStore } = await import("./settings-store"); +const { useSettingsStore, flushSettingsSave } = await import("./settings-store"); beforeEach(() => { vi.useFakeTimers(); @@ -29,6 +30,21 @@ afterEach(() => { }); describe("reset all settings", () => { + it("flushes pending edits once before configuring a launch shortcut", async () => { + useSettingsStore.getState().updateSettings({ overlayShortcut: "Ctrl+Alt+Space" }); + await flushSettingsSave(); + await vi.runAllTimersAsync(); + expect(tauri.saveSettings).toHaveBeenCalledTimes(1); + expect(vi.mocked(tauri.saveSettings).mock.calls[0][0].overlayShortcut).toBe("Ctrl+Alt+Space"); + }); + it("removes the Windows launch shortcut before saving defaults", async () => { + useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS, launchWithHotkey: true } }); + await useSettingsStore.getState().clearSettings(); + expect(tauri.configureLaunchHotkey).toHaveBeenCalledExactlyOnceWith(false, DEFAULT_SETTINGS.overlayShortcut); + expect(vi.mocked(tauri.configureLaunchHotkey).mock.invocationCallOrder[0]) + .toBeLessThan(vi.mocked(tauri.saveSettings).mock.invocationCallOrder[0]); + expect(useSettingsStore.getState().settings.launchWithHotkey).toBe(false); + }); it("replaces custom settings, cancels pending edits and applies persisted and runtime defaults", async () => { const store = useSettingsStore.getState(); store.updateSettings({ isDarkTheme: true, themeMode: "dark", pollingRate: 100, positionX: 500 }); diff --git a/tauri-app/src/stores/settings-store.ts b/tauri-app/src/stores/settings-store.ts index 822e07b..0f478ea 100644 --- a/tauri-app/src/stores/settings-store.ts +++ b/tauri-app/src/stores/settings-store.ts @@ -243,6 +243,12 @@ function debouncedSave(settings: OverlaySettings) { saveTimer = setTimeout(() => tauri.saveSettings(settings), 300); } +/** Commit pending edits before changing the OS-owned launch shortcut. */ +export async function flushSettingsSave() { + if (saveTimer) { clearTimeout(saveTimer); saveTimer = null; } + await tauri.saveSettings(useSettingsStore.getState().settings); +} + interface SettingsStore { // State settings: OverlaySettings; @@ -524,6 +530,10 @@ export const useSettingsStore = create((set, get) => ({ saveTimer = null; const settings = structuredClone(DEFAULT_SETTINGS); settings.isDarkTheme = systemPrefersDark(); + // Remove Explorer's shortcut before persisting the normal defaults. + if (get().settings.launchWithHotkey) { + await tauri.configureLaunchHotkey(false, settings.overlayShortcut); + } const preferences = { adminConsent: false, startMinimized: false }; set({ settings, preferences, gpuSilence: NO_GPU_SILENCE }); // Use the normal save path to persist and broadcast the same defaults, From 7b4fcb087d79e122ed73e8a89870517db8f00934 Mon Sep 17 00:00:00 2001 From: apyfz Date: Tue, 20 Oct 2026 01:47:31 +0700 Subject: [PATCH 2/3] Avoid elevation prompts for launch hotkey toggles and clarify UX --- tauri-app/src-tauri/src/launch_hotkey.rs | 140 +++++++++++++++++- .../src-tauri/windows/installer-hooks.nsh | 3 + .../settings/settings/SettingsTab.tsx | 6 +- 3 files changed, 141 insertions(+), 8 deletions(-) diff --git a/tauri-app/src-tauri/src/launch_hotkey.rs b/tauri-app/src-tauri/src/launch_hotkey.rs index fb5f9b6..4885d76 100644 --- a/tauri-app/src-tauri/src/launch_hotkey.rs +++ b/tauri-app/src-tauri/src/launch_hotkey.rs @@ -1,8 +1,33 @@ //! Explorer owns the optional launch hotkey. No monitoring process is needed -//! while Cleanmeter is closed. This deliberately does not bypass UAC. +//! while Cleanmeter is closed. The already-elevated app explicitly installs +//! an on-demand task so subsequent toggles do not prompt for elevation. use std::sync::Mutex; pub const TOGGLE_ARG: &str = "--toggle-overlay"; +pub const LAUNCH_TASK: &str = "Cleanmeter Overlay Hotkey"; + +fn task_xml(exe: &str, user: &str) -> String { + fn escape(value: &str) -> String { + value + .replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) + .replace('\'', "'") + } + format!( + r#" + + + {}InteractiveTokenHighestAvailable + ParallelfalsefalsetruePT0S + {}{} +"#, + escape(user), + escape(exe), + TOGGLE_ARG + ) +} pub fn is_overlay_launch(args: &[String]) -> bool { args.iter().skip(1).any(|arg| arg == TOGGLE_ARG) } @@ -75,6 +100,89 @@ mod windows_link { }; struct Apartment; + + fn scheduler(args: &[&str]) -> Result { + use std::os::windows::process::CommandExt; + std::process::Command::new(scheduler_path()?) + .args(args) + .creation_flags(0x08000000) + .output() + .map_err(|e| e.to_string()) + } + + fn scheduler_path() -> Result { + Ok( + PathBuf::from(std::env::var_os("SystemRoot").ok_or("Windows directory unavailable")?) + .join("System32") + .join("schtasks.exe"), + ) + } + + fn register_task(exe: &Path) -> Result<(), String> { + use std::io::Write; + use std::os::windows::fs::OpenOptionsExt; + use std::os::windows::process::CommandExt; + let identity = std::process::Command::new(scheduler_path()?.with_file_name("whoami.exe")) + .args(["/user", "/fo", "csv", "/nh"]) + .creation_flags(0x08000000) + .output() + .map_err(|e| e.to_string())?; + if !identity.status.success() { + return Err("Could not identify the current Windows user".into()); + } + // The SID is ASCII even when the account name uses the OEM code page. + let identity = String::from_utf8_lossy(&identity.stdout); + let user = identity + .trim() + .rsplit(',') + .next() + .unwrap_or("") + .trim_matches('"'); + if !user.starts_with("S-1-") { + return Err("Could not identify the current Windows user".into()); + } + let xml = super::task_xml(&exe.to_string_lossy(), user); + let nonce = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|e| e.to_string())? + .as_nanos(); + let path = std::env::temp_dir().join(format!( + "cleanmeter-launch-{}-{nonce}.xml", + std::process::id() + )); + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .share_mode(1) + .open(&path) + .map_err(|e| e.to_string())?; + let result = (|| { + let bytes: Vec = std::iter::once(0xfeffu16) + .chain(xml.encode_utf16()) + .flat_map(u16::to_le_bytes) + .collect(); + file.write_all(&bytes).map_err(|e| e.to_string())?; + file.flush().map_err(|e| e.to_string())?; + let output = scheduler(&[ + "/Create", + "/TN", + super::LAUNCH_TASK, + "/XML", + &path.to_string_lossy(), + "/F", + ])?; + if !output.status.success() { + return Err(format!( + "Could not create the launch task: {}", + String::from_utf8_lossy(&output.stderr).trim() + )); + } + Ok(()) + })(); + drop(file); + let _ = std::fs::remove_file(path); + result + } impl Drop for Apartment { fn drop(&mut self) { unsafe { @@ -105,8 +213,11 @@ mod windows_link { if let Some(ref accelerator) = accelerator { let hotkey = super::shell_hotkey(&accelerator)?; let exe = std::env::current_exe().map_err(|e| e.to_string())?; + register_task(&exe)?; write_link(&link, &exe, hotkey).map_err(|e| e.to_string())?; } else { + // This task has no logon trigger and is independent of autostart. + let _ = scheduler(&["/Delete", "/TN", super::LAUNCH_TASK, "/F"]); match std::fs::remove_file(&link) { Ok(()) => {} Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), @@ -138,8 +249,13 @@ mod windows_link { pub(super) fn write_link(path: &Path, exe: &Path, hotkey: u16) -> windows::core::Result<()> { unsafe { let link: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER)?; - link.SetPath(&HSTRING::from(exe.as_os_str()))?; - link.SetArguments(&HSTRING::from(super::TOGGLE_ARG))?; + let scheduler = scheduler_path().map_err(|_| windows::core::Error::from_win32())?; + link.SetPath(&HSTRING::from(scheduler.as_os_str()))?; + link.SetArguments(&HSTRING::from(format!( + "/Run /TN \"{}\"", + super::LAUNCH_TASK + )))?; + link.SetShowCmd(windows::Win32::UI::WindowsAndMessaging::SW_HIDE)?; if let Some(parent) = exe.parent() { link.SetWorkingDirectory(&HSTRING::from(parent.as_os_str()))?; } @@ -182,12 +298,16 @@ mod windows_link { let end = arguments.iter().position(|&c| c == 0).unwrap(); assert_eq!( String::from_utf16_lossy(&arguments[..end]), - super::super::TOGGLE_ARG + format!("/Run /TN \"{}\"", super::super::LAUNCH_TASK) ); let mut target = [0u16; 1024]; link.GetPath(&mut target, std::ptr::null_mut(), 0).unwrap(); let end = target.iter().position(|&c| c == 0).unwrap(); - assert_eq!(PathBuf::from(String::from_utf16_lossy(&target[..end])), exe); + assert_eq!( + std::fs::canonicalize(PathBuf::from(String::from_utf16_lossy(&target[..end]))) + .unwrap(), + std::fs::canonicalize(scheduler_path().unwrap()).unwrap() + ); } std::fs::remove_file(path).unwrap(); std::fs::remove_dir(directory).unwrap(); @@ -199,6 +319,16 @@ mod windows_link { mod tests { use super::*; #[test] + fn launch_task_is_on_demand_parallel_and_preserves_quoted_paths() { + let xml = task_xml(r#"C:\Apps & Tools\Cleanmeter.exe"#, r"PC\User"); + assert!(xml.contains("")); + assert!(xml.contains("Parallel")); + assert!(xml.contains("InteractiveToken")); + assert!(xml.contains("PT0S")); + assert!(xml.contains(r"C:\Apps & Tools\Cleanmeter.exe")); + assert!(xml.contains("--toggle-overlay")); + } + #[test] fn encodes_shell_modifiers_not_register_hotkey_modifiers() { assert_eq!(shell_hotkey("Ctrl+Alt+Space").unwrap(), 0x0620); assert_eq!(shell_hotkey("Ctrl+Alt+F10").unwrap(), 0x0679); diff --git a/tauri-app/src-tauri/windows/installer-hooks.nsh b/tauri-app/src-tauri/windows/installer-hooks.nsh index 07c8dd6..f15ca1c 100644 --- a/tauri-app/src-tauri/windows/installer-hooks.nsh +++ b/tauri-app/src-tauri/windows/installer-hooks.nsh @@ -1,3 +1,6 @@ !macro NSIS_HOOK_POSTUNINSTALL + IfFileExists "$SMPROGRAMS\Cleanmeter Overlay.lnk" 0 cleanmeter_hotkey_removed + ExecShellWait "runas" "$SYSDIR\schtasks.exe" '/Delete /TN "Cleanmeter Overlay Hotkey" /F' SW_HIDE Delete "$SMPROGRAMS\Cleanmeter Overlay.lnk" + cleanmeter_hotkey_removed: !macroend diff --git a/tauri-app/src/components/settings/settings/SettingsTab.tsx b/tauri-app/src/components/settings/settings/SettingsTab.tsx index 9a86ac5..8e830cd 100644 --- a/tauri-app/src/components/settings/settings/SettingsTab.tsx +++ b/tauri-app/src/components/settings/settings/SettingsTab.tsx @@ -181,7 +181,7 @@ function ShortcutsSection() { return ( -
+

- Use Ctrl+Alt with a letter, number, Space, or F1–F11. Windows launches Cleanmeter with this shortcut, even after Quit. An administrator prompt may appear. Does not enable startup with Windows. + Use the Show/hide overlay shortcut above to open Cleanmeter after Quit. This does not enable startup with Windows.

{launchError &&

{launchError}

}
@@ -214,7 +214,7 @@ function ShortcutsSection() { conflictsWith={{ "Show/hide overlay": overlayAccelerator }} className="gap-[var(--spacingL)]" /> - +
); } From 42da9df02bd496483965195d110887f678171b36 Mon Sep 17 00:00:00 2001 From: apyfz Date: Tue, 20 Oct 2026 01:50:05 +0700 Subject: [PATCH 3/3] Keep task XML readable by the Windows scheduler --- tauri-app/src-tauri/src/launch_hotkey.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/tauri-app/src-tauri/src/launch_hotkey.rs b/tauri-app/src-tauri/src/launch_hotkey.rs index 4885d76..e6891b6 100644 --- a/tauri-app/src-tauri/src/launch_hotkey.rs +++ b/tauri-app/src-tauri/src/launch_hotkey.rs @@ -119,7 +119,7 @@ mod windows_link { } fn register_task(exe: &Path) -> Result<(), String> { - use std::io::Write; + use std::io::{Read, Write}; use std::os::windows::fs::OpenOptionsExt; use std::os::windows::process::CommandExt; let identity = std::process::Command::new(scheduler_path()?.with_file_name("whoami.exe")) @@ -162,7 +162,19 @@ mod windows_link { .flat_map(u16::to_le_bytes) .collect(); file.write_all(&bytes).map_err(|e| e.to_string())?; - file.flush().map_err(|e| e.to_string())?; + drop(file); + // schtasks opens with read-only sharing, so release our writer, + // then hold a read lock and verify the file before registration. + let mut locked = std::fs::OpenOptions::new() + .read(true) + .share_mode(1) + .open(&path) + .map_err(|e| e.to_string())?; + let mut actual = Vec::new(); + locked.read_to_end(&mut actual).map_err(|e| e.to_string())?; + if actual != bytes { + return Err("Launch task file changed before registration".into()); + } let output = scheduler(&[ "/Create", "/TN", @@ -179,7 +191,6 @@ mod windows_link { } Ok(()) })(); - drop(file); let _ = std::fs::remove_file(path); result }