Skip to content

XP event5x XPListening, games, ratings, comments and chat earn five times the XP

leftLeaderboard

juicewrld-desktopsrc-taurisrclike_shortcut.rs

1.4.2Released Nov 21, 2026

like_shortcut.rs

180 lines8.1 KBRust
//! Like or unlike what's playing from anywhere, with a keyboard shortcut of the user's choosing, even while another//! window (a game) has the keyboard (the ideas board, 2026-11-08: "Like/unlike songs with a custom keyboard shortcut//! while gaming, without switching windows").//!//! The site's Settings picks the shortcut (window.juicewrldDesktop.likeShortcut in site.js, the `like_shortcut_set`//! command) and the app registers it with Windows as a global hotkey (tauri-plugin-global-shortcut). Pressed, the app//! tells the site (a `juicewrld:like` event in its page), which likes or unlikes the song playing as its own heart//! does, then asks for a notice (`like_notice`): a Windows notification saying what changed, shown only while the app//! isn't the window in front, since that's when nothing else would show it.//!//! Off until the user picks one. Kept in the app's config folder (like-shortcut.json), registered again at each start.//! A shortcut needs a modifier (Ctrl, Alt, Shift or the Windows key), or to be a function key: a plain letter would be//! taken from every other program. One Windows already gives another program is refused, and the user is told.use crate::from_site;use serde::{Deserialize, Serialize};use std::str::FromStr;use std::sync::Mutex;use tauri::{AppHandle, Manager, Webview};use tauri_plugin_global_shortcut::{Code, GlobalShortcutExt, Modifiers, Shortcut, ShortcutState};use tauri_plugin_notification::NotificationExt;const FILE: &str = "like-shortcut.json";/// The shortcut in force, as the user picked it ("Ctrl+Alt+L"), and Windows' shortcut for it.#[derive(Default)]pub struct LikeShortcut(Mutex<Option<(String, Shortcut)>>);#[derive(Serialize, Deserialize, Default)]struct Saved {    accelerator: Option<String>,}/// The function keys, which may go without a modifier.fn is_function_key(code: Code) -> bool {    matches!(        code,        Code::F1 | Code::F2 | Code::F3 | Code::F4 | Code::F5 | Code::F6 | Code::F7 | Code::F8 | Code::F9 | Code::F10 | Code::F11 | Code::F12            | Code::F13 | Code::F14 | Code::F15 | Code::F16 | Code::F17 | Code::F18 | Code::F19 | Code::F20 | Code::F21 | Code::F22            | Code::F23 | Code::F24    )}/// A shortcut the user may pick: it parses, and has a modifier or is a function key.fn parse(accelerator: &str) -> Result<Shortcut, String> {    if accelerator.len() > 64 {        return Err("That shortcut is too long.".into());    }    let shortcut = Shortcut::from_str(accelerator).map_err(|_| "That isn't a shortcut Windows understands.".to_string())?;    if shortcut.mods.is_empty() && !is_function_key(shortcut.key) {        return Err("Add Ctrl, Alt, Shift or the Windows key, or use a function key (F1 to F24).".into());    }    if shortcut.mods == Modifiers::SHIFT && !is_function_key(shortcut.key) {        return Err("Shift alone would take a capital letter from everything you type. Add Ctrl or Alt.".into());    }    Ok(shortcut)}/// Where the shortcut is kept: the app's config folder, or a debug test run's own (JW_APP_CONFIG, as main.rs's window/// state), so a test never sets the installed app's.fn saved_path(app: &AppHandle) -> Option<std::path::PathBuf> {    #[cfg(debug_assertions)]    if let Some(dir) = std::env::var_os("JW_APP_CONFIG") {        return Some(std::path::PathBuf::from(dir).join(FILE));    }    app.path().app_config_dir().ok().map(|d| d.join(FILE))}fn save(app: &AppHandle, accelerator: Option<&str>) {    let Some(path) = saved_path(app) else { return };    if let Some(dir) = path.parent() {        let _ = std::fs::create_dir_all(dir);    }    let body = serde_json::to_string(&Saved { accelerator: accelerator.map(str::to_string) }).unwrap_or_default();    // Written whole to a temporary name, then moved into place: never half a file.    let tmp = path.with_extension("json.tmp");    if std::fs::write(&tmp, body).is_ok() {        let _ = std::fs::rename(&tmp, &path);    }}/// At start: the user's shortcut, registered again. (Windows gives a shortcut to one program: a second copy of the app/// asking for the same one is refused, and says so in its log.)pub fn startup(app: &AppHandle) {    let Some(path) = saved_path(app) else { return };    let Ok(text) = std::fs::read_to_string(path) else { return };    let Ok(saved) = serde_json::from_str::<Saved>(&text) else { return };    let Some(accelerator) = saved.accelerator else { return };    match parse(&accelerator) {        Ok(shortcut) => match app.global_shortcut().register(shortcut) {            Ok(()) => *app.state::<LikeShortcut>().0.lock().unwrap_or_else(|e| e.into_inner()) = Some((accelerator, shortcut)),            Err(e) => eprintln!("[like] couldn't register {accelerator} ({e})"),        },        Err(e) => eprintln!("[like] saved shortcut {accelerator} refused ({e})"),    }}/// The global shortcut handler: our shortcut pressed tells the site to like or unlike what's playing.pub fn pressed(app: &AppHandle, shortcut: &Shortcut, state: ShortcutState) {    if state != ShortcutState::Pressed {        return;    }    let ours = app.state::<LikeShortcut>().0.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, s)| *s);    if ours != Some(*shortcut) {        return;    }    if let Some(site) = app.get_webview("site") {        let _ = site.eval("window.dispatchEvent(new CustomEvent('juicewrld:like'))");    }}/// The shortcut in force ("Ctrl+Alt+L"), or none.#[tauri::command]pub fn like_shortcut_get(app: AppHandle, webview: Webview) -> Result<Option<String>, String> {    from_site(&webview)?;    Ok(app.state::<LikeShortcut>().0.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(a, _)| a.clone()))}/// Sets the shortcut (none turns it off): the old one goes, the new one is registered and kept. Answers the shortcut in/// force, or why the new one can't be used (the old one then stays).#[tauri::command]pub fn like_shortcut_set(app: AppHandle, webview: Webview, accelerator: Option<String>) -> Result<Option<String>, String> {    from_site(&webview)?;    let next = match accelerator.as_deref().map(str::trim).filter(|a| !a.is_empty()) {        Some(a) => Some((a.to_string(), parse(a)?)),        None => None,    };    let state = app.state::<LikeShortcut>();    let mut current = state.0.lock().unwrap_or_else(|e| e.into_inner());    if current.as_ref().map(|(_, s)| *s) == next.as_ref().map(|(_, s)| *s) {        return Ok(current.as_ref().map(|(a, _)| a.clone()));    }    let shortcuts = app.global_shortcut();    if let Some((label, shortcut)) = &next {        shortcuts            .register(*shortcut)            .map_err(|_| format!("Another program already uses {label}. Pick another shortcut."))?;    }    if let Some((_, old)) = current.take() {        let _ = shortcuts.unregister(old);    }    save(&app, next.as_ref().map(|(a, _)| a.as_str()));    *current = next;    Ok(current.as_ref().map(|(a, _)| a.clone()))}/// After the shortcut liked or unliked a song: a Windows notification saying so, while the app isn't in front.#[tauri::command]pub fn like_notice(app: AppHandle, webview: Webview, title: String, liked: bool, grail: bool) -> Result<(), String> {    from_site(&webview)?;    if webview.window().is_focused().unwrap_or(false) {        return Ok(());    }    let song: String = title.chars().filter(|c| !c.is_control()).take(120).collect();    let heading = match (liked, grail) {        (true, true) => "Added to your grails",        (false, true) => "Removed from your grails",        (true, false) => "Liked",        (false, false) => "Removed from Liked songs",    };    app.notification().builder().title(heading).body(song).show().map_err(|e| e.to_string())}#[cfg(test)]mod tests {    use super::parse;    #[test]    fn a_shortcut_needs_a_modifier_or_a_function_key() {        assert!(parse("Ctrl+Alt+L").is_ok());        assert!(parse("Alt+Super+H").is_ok());        assert!(parse("Ctrl+Shift+K").is_ok());        assert!(parse("F9").is_ok());        assert!(parse("Shift+F8").is_ok());        assert!(parse("L").is_err());        assert!(parse("Shift+L").is_err());        assert!(parse("Ctrl+NotAKey").is_err());        assert!(parse(&"Ctrl+".repeat(20)).is_err());    }}