juicewrld-desktopsrc-taurisrcmain.rs
1.4.2Released Nov 21, 2026
main.rs
948 lines43.0 KBRust//! juicewrld.io for Windows: one undecorated window holding two webviews, the app's own title bar (ui/) on//! top and https://juicewrld.io below it (or under it, the bar see-through to the page's colour, while the page leaves//! it the room: site_under_bar), plus Discord Rich Presence for what's playing here or in the member's other browsers//! (presence.rs), Discord sign-in through the default browser (handoff.rs), updates from the site (update.rs), the//! user's own plugins in the site's studio (plugins/, run by juicewrld-plugins.exe, host/), managed in a window of their//! own (the plugin manager, plugins/manager.rs and ui/plugins.html), a keyboard shortcut that likes what's playing from//! anywhere (like_shortcut.rs), Windows notifications for the site's messages, notes and alerts (notices.rs), and//! closing to the system tray, the music and the Discord status running on (tray.rs).mod handoff;mod like_shortcut;mod notices;mod plugins;mod presence;mod tray;mod update;use handoff::Handoff;use notices::Notices;use presence::{Now, Presence, Update};use serde::Serialize;use serde_json::json;use std::sync::Mutex;use tauri::webview::{DownloadEvent, NewWindowResponse, PageLoadEvent, WebviewBuilder};use tauri::window::{Color, WindowBuilder};use tauri::{ AppHandle, Manager, PhysicalPosition, PhysicalSize, Position, Rect, RunEvent, Size, Theme, Url, Webview, WebviewUrl, Window, WindowEvent,};use tauri_plugin_deep_link::DeepLinkExt;use tauri_plugin_window_state::StateFlags;const SITE: &str = "https://juicewrld.io/";/// The title bar's height in logical pixels.const BAR: f64 = 36.0;/// The page colour, behind both webviews until they paint.const BG: Color = Color(11, 11, 14, 255);/// WebView2's defaults (wry's) plus the hardware media keys, which WebView2 leaves to the host. Every webview of the app/// passes the same (WebView2 refuses a second set of options for the same profile: the debug test page's too)./// AudioServiceOutOfProcess off: Chromium's audio runs in WebView2's browser process, a child of juicewrld.exe, rather/// than a utility process of its own, a grandchild. Discord's application audio (a screen share of this window) takes/// the shared app's process and its children only: out of process, people watching heard nothing (measured with/// Windows' process loopback on a stand-in: 0 out of process, the page's own level in the browser process)./// No background throttling: closed to the tray (tray.rs) the window is hidden, and Chromium would slow a hidden page's/// timers to once a minute, which leaves the Discord status (site.js's 1 s check, the 15 s ask for the other browsers'/// song) minutes behind.pub const BROWSER_ARGS: &str = "--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection,AudioServiceOutOfProcess --enable-features=HardwareMediaKeyHandling --disable-background-timer-throttling --disable-renderer-backgrounding --disable-backgrounding-occluded-windows";/// What the title bar mirrors from the page below.struct Chrome { back: bool, forward: bool, loading: bool, maximized: bool, /// The site fills the window under a see-through bar (site_under_bar), rather than starting below it. under: bool, /// Below the bar, the colour along the page's top edge ("rgb(r g b)"), which the solid bar takes (site_under_bar). tint: Option<String>,}struct BarState { maximized: bool, loading: bool, nav: serde_json::Value, now: Now, update: Option<update::Offer>, overlay: bool, tint: Option<String>,}fn main() { let builder = tauri::Builder::default(); let builder = plugins::testpage::protocol(builder); // A second launch brings the open window forward instead, and hands it any juicewrld:// link it was opened with // (the deep-link feature passes those on to on_open_url below). A debug build's test run beside the installed app // (JW_ALONE) runs on its own instead of handing over to it. let builder = if test_switch("JW_ALONE") { builder } else { builder.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| focus(app))) }; builder .plugin(tauri_plugin_deep_link::init()) .plugin(window_state()) // Rust only (update.rs): no capability grants its commands, so neither webview can call them. .plugin(tauri_plugin_updater::Builder::new().build()) // The like shortcut (like_shortcut.rs): Windows tells us when it's pressed, whatever window is in front; and // its notice. Rust only: no capability grants either plugin's own commands. .plugin(tauri_plugin_global_shortcut::Builder::new().with_handler(|app, shortcut, event| like_shortcut::pressed(app, shortcut, event.state())).build()) .plugin(tauri_plugin_notification::init()) .manage(like_shortcut::LikeShortcut::default()) .manage(Presence::start()) .manage(Handoff::default()) .manage(Notices::default()) .manage(update::Updates::default()) .manage(tray::Tray::default()) .manage(Mutex::new(Chrome::default())) .invoke_handler(tauri::generate_handler![ presence, bar, bar_state, site_under_bar, notices::notify, like_shortcut::like_shortcut_get, like_shortcut::like_shortcut_set, like_shortcut::like_notice, plugins::plugins_status, plugins::plugins_subscribe, plugins::plugins_request_enable, plugins::plugins_request_scan, plugins::plugins_list, plugins::plugins_unsupported, plugins::plugins_manage, plugins::plugins_open, plugins::plugins_close, plugins::plugins_editor, plugins::plugins_get_state, plugins::plugins_set_state, plugins::plugins_params, plugins::plugins_set_param, plugins::plugins_reset, plugins::plugins_bypass, plugins::plugins_stream, plugins::plugins_stream_close, plugins::plugins_render, plugins::plugins_bench_echo, plugins::plugins_bench_channel, plugins::plugins_test_action, plugins::manager::manager_state, plugins::manager::manager_subscribe, plugins::manager::manager_enable, plugins::manager::manager_scan, plugins::manager::manager_stop, plugins::manager::manager_retry, plugins::manager::manager_favourite, plugins::manager::manager_hide, plugins::manager::manager_folder, plugins::manager::manager_add_folder, plugins::manager::manager_remove_folder, ]) // The tray's menu (tray.rs) and the title bar's (plugins/mod.rs). .on_menu_event(|app, event| { let id = event.id().as_ref(); if !tray::on_menu(app, id) { plugins::on_menu(app, id); } }) .setup(|app| { app.manage(plugins::Plugins::new(app.handle())); // juicewrld:// opens this app: the installer registers it, and so does every start, so a portable copy // works from wherever it was saved. // (Not a test run beside the installed app: juicewrld:// stays the installed app's.) if !test_switch("JW_ALONE") { if let Err(e) = app.deep_link().register("juicewrld") { eprintln!("[app] couldn't register juicewrld:// ({e})"); } } let handle = app.handle().clone(); app.deep_link().on_open_url(move |event| { for link in event.urls() { deep_link(&handle, &link); } }); // Started by a sign-in link: this new process started no sign-in, so the link is ignored (handoff.rs). Started // by a notification's (the app was closed when it was clicked): its page was the old process's to know, so // the app just opens (notices.rs). let started_by = app.deep_link().get_current().ok().flatten().unwrap_or_default(); if started_by.iter().any(|link| handoff::signin_code(link).is_some()) { eprintln!("[handoff] started by a sign-in link, with no sign-in waiting here: ignored"); } if started_by.iter().any(|link| notices::link_token(link).is_some()) { eprintln!("[notify] started by a notification from an earlier run: opening the home page"); } open_window(app.handle(), SITE.parse().expect("site url"))?; // Without its icon, Close quits as it used to (tray.rs). if let Err(e) = tray::create(app.handle()) { eprintln!("[tray] couldn't add the tray icon ({e}); closing the window quits"); } update::start(app.handle()); like_shortcut::startup(app.handle()); // With plugins on, a quick check of the plugin folders runs a moment after start-up, in the background // (plugins/; nothing at all while they're off). A debug build can open the plugin test page at once (the // title bar's menu opens it too). plugins::startup(app.handle()); if std::env::var_os("JW_PLUGIN_TEST").is_some() { plugins::testpage::open(app.handle())?; } Ok(()) }) .build(tauri::generate_context!()) .expect("juicewrld.io couldn't start") .run(|app, event| { if let RunEvent::Exit = event { app.state::<Presence>().stop(); plugins::shutdown(app); // Last: a downloaded update installs as the app closes. update::on_exit(app); } });}/// Window size, position and maximized state, remembered in the app's config folder.fn window_state() -> tauri::plugin::TauriPlugin<tauri::Wry> { let b = tauri_plugin_window_state::Builder::new().with_state_flags(StateFlags::SIZE | StateFlags::POSITION | StateFlags::MAXIMIZED); // A debug build's test run keeps its window state in its own folder (an absolute name replaces the config folder). let b = match debug_config_dir() { Some(dir) => b.with_filename(dir.join(".window-state.json").to_string_lossy()), None => b, }; // A quiet test run never restores a maximized window (maximizing brings a window forward). let b = if test_switch("JW_NO_FOCUS") { b.skip_initial_state("main") } else { b }; b.build()}/// Debug builds' switches for scripted test runs, read from the run's own environment (never set anywhere else):/// JW_MUTE starts every webview muted (ICoreWebView2_8::IsMuted; the run passes Chromium's --mute-audio too, which/// keeps the audio clock running), JW_NO_FOCUS opens the app's windows without taking focus and behind the other/// windows on the screen, JW_ALONE runs beside an installed copy that's open (no single instance, juicewrld:// left/// registered to the installed app, no Discord status). A test run makes no sound and doesn't get in the way of the/// person at the PC. A release build has none of them.pub fn test_switch(name: &str) -> bool { cfg!(debug_assertions) && std::env::var_os(name).is_some_and(|v| !v.is_empty() && v != "0")}/// A test run (JW_MUTE): mutes this webview before it plays anything, and logs the state read back.////// # Safety/// Inside `with_webview`, on the main thread.pub unsafe fn mute_for_test(core: &webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2, label: &str) { use webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2_8; use windows::core::{Interface, BOOL}; if !test_switch("JW_MUTE") { return; } let muted = core.cast::<ICoreWebView2_8>().and_then(|c| { c.SetIsMuted(true)?; let mut m = BOOL::default(); c.IsMuted(&mut m)?; Ok(m.as_bool()) }); match muted { Ok(true) => eprintln!("[app] test run: the {label} webview is muted"), Ok(false) => eprintln!("[app] test run: the {label} webview did NOT mute"), Err(e) => eprintln!("[app] test run: couldn't mute the {label} webview ({e})"), }}/// A test run (JW_NO_FOCUS): the window goes behind every other window, without taking focus.pub fn to_back(hwnd: isize) { use windows::Win32::Foundation::HWND; use windows::Win32::UI::WindowsAndMessaging::{SetWindowPos, HWND_BOTTOM, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE}; // SAFETY: a plain Win32 call about one of this app's own windows. unsafe { let _ = SetWindowPos(HWND(hwnd as *mut _), Some(HWND_BOTTOM), 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); }}/// Debug builds: JW_APP_CONFIG names a settings folder for a test run (window state, plugin settings and scan), so it/// never reads or writes the installed app's own.fn debug_config_dir() -> Option<std::path::PathBuf> { std::env::var_os("JW_APP_CONFIG").map(std::path::PathBuf::from)}fn focus(app: &AppHandle) { if let Some(w) = app.get_window("main") { let _ = w.unminimize(); let _ = w.show(); let _ = w.set_focus(); }}/// juicewrld://signin?code=: the browser finished a Discord sign-in for this app; claim it in the site webview. Only/// while a sign-in started here is waiting: any other link (a stray one, or one sent to break a sign-in or stop the/// music) leaves the page as it is. juicewrld://notification?n=: one of this window's notifications was clicked; its/// page opens, only for a token this process made (notices.rs).fn deep_link(app: &AppHandle, link: &Url) { if let Some(token) = notices::link_token(link) { match app.state::<Notices>().page(&token) { Some(page) => open_page(app, &page), None => eprintln!("[notify] a notification link this window didn't make: ignored"), } return; } let Some(code) = handoff::signin_code(link) else { return }; let Some(url) = app.state::<Handoff>().claim(&code) else { eprintln!("[handoff] sign-in link with no sign-in waiting here: ignored"); return; }; eprintln!("[handoff] sign-in link received; claiming it"); if let Some(site) = app.get_webview("site") { let _ = site.navigate(url); let _ = site.set_focus(); } focus(app);}fn open_window(app: &AppHandle, start: Url) -> tauri::Result<()> { // A quiet test run's window is shown as it's made, without taking focus (shown later, Windows would bring it // forward), and sent behind the other windows. let quiet = test_switch("JW_NO_FOCUS"); let window = WindowBuilder::new(app, "main") .title("juicewrld.io") .inner_size(1280.0, 820.0) .min_inner_size(480.0, 560.0) .center() .decorations(false) .theme(Some(Theme::Dark)) .background_color(BG) .visible(quiet) .focused(!quiet) .build()?; if quiet { if let Ok(h) = window.hwnd() { to_back(h.0 as isize); } } // Below the bar until a page says it leaves the bar its room (site_under_bar). let (bar_rect, site_rect) = layout(&window, false)?; // The site first, then the bar: each webview goes on top of the window's others as it's made, and the bar has to // lie over the site's top while the site is under it. // The site starts on a blank page: its user agent gets the app's mark first (with_site below), then it // loads juicewrld.io. let nav_app = app.clone(); let popup_app = app.clone(); let load_app = app.clone(); let download_app = app.clone(); let site = WebviewBuilder::new("site", WebviewUrl::External("about:blank".parse().expect("about:blank"))) .initialization_script(plugins::site_script(None)) .background_color(BG) .additional_browser_args(BROWSER_ARGS) .focused(!quiet) // The site has its own drag and drop (playlists, uploads): the app takes no file drops. .disable_drag_drop_handler() .zoom_hotkeys_enabled(true) // WebView2 saves the file and shows nothing. The title bar says so, the same way a sign-in does. .on_download(move |_webview, event| { let name = match &event { DownloadEvent::Requested { destination, .. } => destination.file_name().and_then(|n| n.to_str()), DownloadEvent::Finished { path, .. } => path.as_ref().and_then(|p| p.file_name()).and_then(|n| n.to_str()), _ => None, } .filter(|n| !n.is_empty()) .unwrap_or("file") .to_string(); let msg = match &event { DownloadEvent::Requested { .. } => format!("Downloading {name}"), DownloadEvent::Finished { success: true, .. } => format!("Downloaded {name}"), DownloadEvent::Finished { .. } => format!("Couldn't download {name}"), _ => String::new(), }; if !msg.is_empty() { bar_call(&download_app, "notice", json!(msg)); } true }) .on_navigation(move |url| { // The page the webview starts on, and nothing else that isn't a web address: no data:, blob:, // javascript: or file: page ever fills the window, where one could pass for a sign-in (no address bar). if is_blank(url) { return true; } let handoff = nav_app.state::<Handoff>(); // Discord sign-in finishes in the default browser, where Discord knows the member (handoff.rs). if let Some(browser) = handoff.browser_signin(url) { eprintln!("[handoff] Discord sign-in opened in the browser"); outside(&nav_app, &browser); bar_call(&nav_app, "notice", json!("Sign-in continues in your browser")); return false; } // The claim only as the app opens it, never from a link on a page. if handoff::is_claim(url) { return handoff.allow_claim(url); } if stays_inside(url) { return true; } outside(&nav_app, url); false }) // New windows (target=_blank, window.open): the site's own pages open in place, other web and mail links in // the browser, and anything else (about:blank, data:, blob:, javascript:, file:) nowhere. .on_new_window(move |url, _features| { if stays_inside(&url) { if let Some(site) = popup_app.get_webview("site") { let _ = site.navigate(url); } } else { outside(&popup_app, &url); } NewWindowResponse::Deny }) .on_page_load(move |webview, payload| { if payload.url().scheme() == "about" { return; } let started = matches!(payload.event(), PageLoadEvent::Started); if !started { // Where a claim lands says whether the sign-in is over (handoff.rs). webview.state::<Handoff>().landed(payload.url()); } set_chrome(&load_app, |c| c.loading = started); if started { // A new document: whatever played on the old one has stopped, and its plugins close. if let Some(now) = webview.state::<Presence>().clear() { bar_call(&load_app, "now", json!(now)); } plugins::page_changed(&load_app, "site"); // A page of another site (Discord's sign-in) knows nothing of the bar: it starts below it. The site's // own next page keeps the layout this one had, and says again (site.js). if !is_site(payload.url()) { set_under(&load_app, false); } } }); let site = window.add_child(site, site_rect.position, site_rect.size)?; with_site(app, &site, start); let bar = WebviewBuilder::new("bar", WebviewUrl::App("index.html".into())) // See-through, so the page's colour runs up behind it while the site is under it; bar.css paints it solid // otherwise (and while it loads, nothing is drawn over the window's own colour). .transparent(true) .additional_browser_args(BROWSER_ARGS) .focused(!quiet) .disable_drag_drop_handler(); let bar = window.add_child(bar, bar_rect.position, bar_rect.size)?; raise(&bar); let _ = bar.with_webview(|w| unsafe { if let Ok(core) = w.controller().CoreWebView2() { mute_for_test(&core, "bar"); } }); // Resizing an undecorated window from its edges needs Tauri's resize handler, which it only attaches to // a window's own webview: asking again attaches it over the child webviews too. window.set_resizable(true)?; let resize_app = app.clone(); window.on_window_event(move |event| match event { WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } => relayout(&resize_app), WindowEvent::Focused(on) => bar_call(&resize_app, "focus", json!(on)), // Close (the bar's X, Alt+F4, the taskbar's) hides the window to the tray; the tray's Quit ends the app. WindowEvent::CloseRequested { api, .. } => { api.prevent_close(); tray::close_to_tray(&resize_app); } _ => {} }); relayout(app); if quiet { if let Ok(h) = window.hwnd() { to_back(h.0 as isize); } return Ok(()); } window.show()?; let _ = site.set_focus(); Ok(())}/// The bar's height in physical pixels at the window's scale.fn bar_height(window: &Window) -> tauri::Result<u32> { Ok((BAR * window.scale_factor()?).round() as u32)}/// Where the bar and the site go, as (top, height) in physical pixels: the bar across the top, the site below it, or/// (`under`) filling the window with the bar over its top.fn split(height: u32, bar_h: u32, under: bool) -> ((u32, u32), (u32, u32)) { let bar_h = bar_h.min(height); let top = if under { 0 } else { bar_h }; ((0, bar_h), (top, height - top))}/// The bar and the site (split), in physical pixels so they meet without a gap at any scale.fn layout(window: &Window, under: bool) -> tauri::Result<(Rect, Rect)> { let size = window.inner_size()?; let (bar, site) = split(size.height, bar_height(window)?, under); let rect = |(y, h): (u32, u32)| Rect { position: Position::Physical(PhysicalPosition::new(0, y as i32)), size: Size::Physical(PhysicalSize::new(size.width, h)), }; Ok((rect(bar), rect(site)))}fn relayout(app: &AppHandle) { let Some(window) = app.get_window("main") else { return }; // Minimized (Windows then reports a tiny client area): nothing to lay out until it's back. let minimized = window.is_minimized().unwrap_or(false); if minimized || window.inner_size().map(|s| s.width == 0 || s.height == 0).unwrap_or(true) { return; } let under = app.state::<Mutex<Chrome>>().lock().unwrap_or_else(|e| e.into_inner()).under; if let Ok((bar_rect, site_rect)) = layout(&window, under) { if let Some(bar) = app.get_webview("bar") { let _ = bar.set_bounds(bar_rect); } if let Some(site) = app.get_webview("site") { let _ = site.set_bounds(site_rect); } } let maximized = window.is_maximized().unwrap_or(false); let changed = { let chrome = app.state::<Mutex<Chrome>>(); let mut c = chrome.lock().unwrap_or_else(|e| e.into_inner()); std::mem::replace(&mut c.maximized, maximized) != maximized }; if changed { bar_call(app, "max", json!(maximized)); }}/// Updates the mirrored page state and tells the bar.fn set_chrome(app: &AppHandle, f: impl FnOnce(&mut Chrome)) { let (nav, loading) = { let chrome = app.state::<Mutex<Chrome>>(); let mut c = chrome.lock().unwrap_or_else(|e| e.into_inner()); f(&mut c); (json!({ "back": c.back, "forward": c.forward }), c.loading) }; bar_call(app, "nav", nav); bar_call(app, "loading", json!(loading));}/// Calls `jw.<name>(value)` in the title bar (bar.js), if it has loaded.fn bar_call(app: &AppHandle, name: &str, value: serde_json::Value) { if let Some(bar) = app.get_webview("bar") { let _ = bar.eval(format!("window.jw && jw.{name}({value})")); }}/// The hosts that stay in the app, exactly: the site, and Discord, whose login and sign-in (OAuth, discord.com/login/// and /oauth2/authorize) return to it. Nothing under them: no other host has a reason to fill the window.const INSIDE: [&str; 2] = ["juicewrld.io", "discord.com"];/// juicewrld.io stays in the app, and so does Discord's sign-in; https only.fn stays_inside(url: &Url) -> bool { url.scheme() == "https" && url.host_str().is_some_and(|h| INSIDE.contains(&h))}/// about:blank, the page the site webview starts on before with_site loads juicewrld.io.fn is_blank(url: &Url) -> bool { url.as_str() == "about:blank"}/// Any other web or mail link opens in the default browser or mail app; other schemes go nowhere.fn outside(_app: &AppHandle, url: &Url) { if opens_outside(url) { let _ = open::that_detached(url.as_str()); }}/// Web and mail links, the only ones handed to the system.fn opens_outside(url: &Url) -> bool { matches!(url.scheme(), "http" | "https" | "mailto")}/// WebView2 specifics for the site: the user agent gains "JuiceWRLDDesktop/<version>" (so the site can tell/// the app apart later), the bar follows its back and forward history, and then `start` loads.fn with_site(app: &AppHandle, site: &Webview, start: Url) { use webview2_com::HistoryChangedEventHandler; use webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Settings2; use windows::core::{Interface, BOOL, HSTRING, PWSTR}; let app = app.clone(); let fallback = site.clone(); let first = start.clone(); let result = site.with_webview(move |w| unsafe { let run = || -> windows::core::Result<()> { let core = w.controller().CoreWebView2()?; // A test run's site is muted before it loads (debug builds, JW_MUTE). mute_for_test(&core, "site"); let settings: ICoreWebView2Settings2 = core.Settings()?.cast()?; let mut ua = PWSTR::null(); settings.UserAgent(&mut ua)?; let base = webview2_com::take_pwstr(ua); let mark = format!("JuiceWRLDDesktop/{}.{}", env!("CARGO_PKG_VERSION_MAJOR"), env!("CARGO_PKG_VERSION_MINOR")); settings.SetUserAgent(&HSTRING::from(format!("{base} {mark}")))?; let history_app = app.clone(); let mut token = 0i64; core.add_HistoryChanged( &HistoryChangedEventHandler::create(Box::new(move |sender, _| { if let Some(core) = sender { let (mut back, mut forward) = (BOOL::default(), BOOL::default()); core.CanGoBack(&mut back)?; core.CanGoForward(&mut forward)?; set_chrome(&history_app, |c| { c.back = back.as_bool(); c.forward = forward.as_bool(); }); } Ok(()) })), &mut token, )?; // The plugin API's AudioWorklet, answered by the app at a path of the site's own (so the site's CSP lets // the page load it), when this copy can run plugins. if plugins::supported() { serve_worklet(&w, &core)?; } core.Navigate(&HSTRING::from(first.as_str()))?; Ok(()) }; if let Err(e) = run() { eprintln!("[app] WebView2 setup failed ({e}); loading the site as is"); let _ = fallback.navigate(first.clone()); } }); if result.is_err() { let _ = site.navigate(start); }}/// Answers https://juicewrld.io/__juicewrld-desktop/plugins-worklet-1.js with the app's own worklet (plugins/worklet.js):/// that one address, nothing else on the site; the request never leaves the app.unsafe fn serve_worklet(w: &tauri::webview::PlatformWebview, core: &webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2) -> windows::core::Result<()> { use webview2_com::Microsoft::Web::WebView2::Win32::COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL; use webview2_com::WebResourceRequestedEventHandler; use windows::core::{HSTRING, PWSTR}; let url = format!("https://juicewrld.io{}", plugins::WORKLET_PATH); core.AddWebResourceRequestedFilter(&HSTRING::from(url.as_str()), COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL)?; let env = w.environment(); let mut token = 0i64; core.add_WebResourceRequested( &WebResourceRequestedEventHandler::create(Box::new(move |_, args| { let Some(args) = args else { return Ok(()) }; let mut uri = PWSTR::null(); args.Request()?.Uri(&mut uri)?; if webview2_com::take_pwstr(uri) != url { return Ok(()); } let stream = windows::Win32::UI::Shell::SHCreateMemStream(Some(plugins::WORKLET_JS.as_bytes())); let headers = HSTRING::from("Content-Type: text/javascript; charset=utf-8\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff"); let response = env.CreateWebResourceResponse(stream.as_ref(), 200, &HSTRING::from("OK"), &headers)?; args.SetResponse(&response) })), &mut token, )}/// The site reports what's playing (site.js): in this window, or with `source: "web"` in another browser of the/// member's account, which Discord shows only while this window plays nothing and the title bar never does/// (presence.rs).fn presence(app: AppHandle, webview: Webview, update: Update, source: Option<String>) { if webview.label() != "site" || test_switch("JW_ALONE") { return; } if source.as_deref() == Some("web") { let (state, title) = (update.state.clone(), update.title.clone()); if app.state::<Presence>().update_web(update) { eprintln!("[presence] another browser: {state} {title:?}"); } return; } eprintln!( "[presence] {} {:?} by {:?} at {:.0}/{:.0}s", update.state, update.title, update.artist, update.position, update.duration ); if let Some(now) = app.state::<Presence>().update(update) { bar_call(&app, "now", json!(now)); }}/// The title bar's buttons. `x` and `y` place the menu (the menu button's corner, in the bar's CSS pixels).fn bar(app: AppHandle, webview: Webview, action: String, x: Option<f64>, y: Option<f64>) -> Result<(), String> { if webview.label() != "bar" { return Err("not the title bar".into()); } match action.as_str() { // The app's menu: plugins in the studio on or off, Manage plugins…, Scan (plugins/mod.rs). "menu" => return plugins::show_menu(&app, x.unwrap_or(0.0), y.unwrap_or(BAR)).map_err(|e| e.to_string()), // The bar's prompt, answered (plugins_request_enable asked it). "plugins-on" => return Ok(plugins::answer(&app, true)), "plugins-not-now" => return Ok(plugins::answer(&app, false)), _ => {} } let window = webview.window(); let site = app.get_webview("site").ok_or("no site")?; let r = match action.as_str() { "minimize" => window.minimize(), "maximize" => { if window.is_maximized().unwrap_or(false) { window.unmaximize() } else { window.maximize() } } "close" => window.close(), "back" => site.eval("history.back()"), "forward" => site.eval("history.forward()"), "reload" => site.reload(), // Through the site's own links where it has one, so the music keeps playing (a client-side move), // else a plain page load. "home" => site.eval(follow("a[href=\"/\"]", SITE)), "song" => { let url = app.state::<Presence>().now().url; let url = if url.is_empty() { SITE.to_string() } else { url }; site.eval(follow("a.pl-bar__title[href]", &url)) } // Update ready: closes the app, which installs the update and opens again (update.rs). "update" => return update::restart(&app), _ => return Err(format!("unknown action {action}")), }; if !matches!(action.as_str(), "minimize" | "close") { let _ = site.set_focus(); } r.map_err(|e| e.to_string())}/// JS for the site: click the first link matching `selector`, else go to `url`.fn follow(selector: &str, url: &str) -> String { let (selector, url) = (json!(selector), json!(url)); format!("(() => {{ const a = document.querySelector({selector}); if (a) a.click(); else location.assign({url}); }})()")}/// JS for the site: a `juicewrld:open` event with `url`, which the site's notifications answer with a client-side move/// (components/desktop-alerts.tsx, so what plays keeps playing); a page load when nothing takes it.fn open_script(url: &Url) -> String { let url = json!(url.as_str()); format!("(() => {{ const e = new CustomEvent('juicewrld:open', {{ detail: {url}, cancelable: true }}); if (window.dispatchEvent(e)) location.assign({url}); }})()")}/// A clicked notification's page in the site webview, the window brought forward (notices.rs).fn open_page(app: &AppHandle, page: &Url) { eprintln!("[notify] notification clicked: opening {}", page.path()); if let Some(site) = app.get_webview("site") { let _ = site.eval(open_script(page)); let _ = site.set_focus(); } focus(app);}/// The site's own webview on https://juicewrld.io: who may ask for the like shortcut, notifications and the bar's room.pub fn from_site(webview: &Webview) -> Result<(), String> { let ok = webview.label() == "site" && webview.url().map(|u| is_site(&u)).unwrap_or(false); if ok { Ok(()) } else { Err("not the site".into()) }}/// A page of the site itself (not Discord's, not a blank or error page).fn is_site(url: &Url) -> bool { url.scheme() == "https" && url.host_str() == Some("juicewrld.io") && url.port().is_none()}/// The bar's webview over the site's: its window first among the main window's children (each webview's window is the/// child its controller was made in).fn raise(bar: &Webview) { use windows::Win32::Foundation::HWND; use windows::Win32::UI::WindowsAndMessaging::{SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE}; let _ = bar.with_webview(|w| unsafe { let mut hwnd = HWND::default(); if w.controller().ParentWindow(&mut hwnd).is_ok() && !hwnd.is_invalid() { let _ = SetWindowPos(hwnd, Some(HWND_TOP), 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } });}/// The site under the bar or below it: the webviews laid out again and the bar told, when it changed.fn set_under(app: &AppHandle, under: bool) { let changed = { let chrome = app.state::<Mutex<Chrome>>(); let mut c = chrome.lock().unwrap_or_else(|e| e.into_inner()); std::mem::replace(&mut c.under, under) != under }; if changed { relayout(app); bar_call(app, "overlay", json!(under)); }}/// The solid bar's colour as the page gave it, kept to "rgb(r g b)" with three numbers 0 to 255: anything else is none.fn clean_tint(raw: Option<&str>) -> Option<String> { let s = raw?.trim(); let inner = s.strip_prefix("rgb(")?.strip_suffix(')')?; let parts: Vec<u8> = inner.split([' ', ',']).filter(|p| !p.is_empty()).map(|p| p.parse::<u8>()).collect::<Result<_, _>>().ok()?; (parts.len() == 3).then(|| format!("rgb({} {} {})", parts[0], parts[1], parts[2]))}/// The solid bar's colour: the bar told, when it changed.fn set_tint(app: &AppHandle, tint: Option<String>) { let changed = { let chrome = app.state::<Mutex<Chrome>>(); let mut c = chrome.lock().unwrap_or_else(|e| e.into_inner()); if c.tint == tint { false } else { c.tint = tint.clone(); true } }; if changed { bar_call(app, "tint", json!(tint)); }}/// The page says whether it lies under the bar (site.js): a page with the site's own top chrome, which moves down by/// the bar's height (--app-bar-h, the room the page leaves it, src/app/globals.css), fills the window and the bar goes/// see-through over it; any other (the studio, the admin, a page with no chrome of the site's) starts below the bar,/// which is solid. Answers the bar's height in physical pixels: the page's room is that over its devicePixelRatio, so/// its own zoom (Ctrl+wheel) is accounted for. Below the bar, `tint` is the colour along the page's top edge, which the/// solid bar takes so the two read as one (1.4.1).fn site_under_bar(app: AppHandle, webview: Webview, under: bool, tint: Option<String>) -> Result<u32, String> { from_site(&webview)?; set_tint(&app, if under { None } else { clean_tint(tint.as_deref()) }); set_under(&app, under); bar_height(&webview.window()).map_err(|e| e.to_string())}/// The bar's first look at the window and the page.fn bar_state(app: AppHandle, webview: Webview) -> Result<BarState, String> { if webview.label() != "bar" { return Err("not the title bar".into()); } let chrome = app.state::<Mutex<Chrome>>(); let c = chrome.lock().unwrap_or_else(|e| e.into_inner()); Ok(BarState { maximized: c.maximized, loading: c.loading, nav: json!({ "back": c.back, "forward": c.forward }), now: app.state::<Presence>().now(), update: app.state::<update::Updates>().offer(), overlay: c.under, tint: c.tint.clone(), })}mod tests { use super::*; fn a_tint_is_three_numbers_or_none() { assert_eq!(clean_tint(Some("rgb(16 16 19)")).as_deref(), Some("rgb(16 16 19)")); assert_eq!(clean_tint(Some(" rgb(16, 16, 19) ")).as_deref(), Some("rgb(16 16 19)")); assert_eq!(clean_tint(Some("rgb(16 16 300)")), None); assert_eq!(clean_tint(Some("rgb(16 16)")), None); assert_eq!(clean_tint(Some("red; background: url(x)")), None); assert_eq!(clean_tint(Some("rgb(1 2 3) }")), None); assert_eq!(clean_tint(None), None); } fn url(s: &str) -> Url { Url::parse(s).unwrap() } fn only_the_site_and_discord_stay_in_the_window() { for inside in ["https://juicewrld.io/", "https://juicewrld.io/song/x?y=1", "https://discord.com/oauth2/authorize?client_id=1", "https://discord.com/login"] { assert!(stays_inside(&url(inside)), "{inside}"); } for other in [ "http://juicewrld.io/", "https://www.juicewrld.io/", "https://evil.juicewrld.io/", "https://juicewrld.io.evil.com/", "https://notjuicewrld.io/", "https://cdn.discord.com/x", "https://discord.com.evil.com/", "https://discord.gg/wrld", "https://example.com/", ] { assert!(!stays_inside(&url(other)), "{other}"); } } fn test_switches_are_a_debug_builds_alone() { // PATH is always set: as a switch it reads on in a debug build, and never in a release build. assert_eq!(test_switch("PATH"), cfg!(debug_assertions)); assert!(!test_switch("JW_NO_SUCH_SWITCH_EVER")); } fn no_page_of_its_own_fills_the_window() { // Only the blank page the webview starts on; a script's data:, blob:, javascript: or file: page goes nowhere, // in place or as a new window (neither inside nor handed to the system). assert!(is_blank(&url("about:blank"))); for page in [ "about:srcdoc", "about:blank#x", "data:text/html,<h1>Sign in</h1>", "data:text/html;base64,PGgxPkhpPC9oMT4=", "blob:https://juicewrld.io/4f6f1c2e-0000-4000-8000-000000000000", "blob:https://discord.com/4f6f1c2e-0000-4000-8000-000000000000", "javascript:alert(1)", "file:///C:/Windows/win.ini", ] { let u = url(page); assert!(!is_blank(&u) && !stays_inside(&u) && !opens_outside(&u), "{page}"); } // about:blank as a new window isn't the site's either: denied, never navigated to in place. assert!(!stays_inside(&url("about:blank")) && !opens_outside(&url("about:blank"))); assert!(opens_outside(&url("https://example.com/")) && opens_outside(&url("mailto:[email protected]"))); } fn the_site_fills_the_window_only_while_it_lies_under_the_bar() { // 820 tall at 125%: the bar is 45 physical pixels. assert_eq!(split(820, 45, false), ((0, 45), (45, 775)), "below the bar"); assert_eq!(split(820, 45, true), ((0, 45), (0, 820)), "the whole window, the bar over its top"); // A window shorter than the bar (as it's minimized): nothing goes negative. assert_eq!(split(30, 45, false), ((0, 30), (30, 0))); assert_eq!(split(30, 45, true), ((0, 30), (0, 30))); } fn only_the_sites_own_pages_lie_under_the_bar() { assert!(is_site(&url("https://juicewrld.io/")) && is_site(&url("https://juicewrld.io/studio/x"))); for other in ["https://discord.com/login", "about:blank", "http://juicewrld.io/", "https://juicewrld.io:8443/", "https://www.juicewrld.io/"] { assert!(!is_site(&url(other)), "{other}"); } } fn a_notifications_page_opens_through_the_site_first() { let js = open_script(&url("https://juicewrld.io/messages/12")); assert!(js.contains("new CustomEvent('juicewrld:open'") && js.contains("cancelable: true")); assert!(js.contains("location.assign(\"https://juicewrld.io/messages/12\")")); // The address goes in as a JSON string, never as code. let odd = open_script(&url("https://juicewrld.io/search?q=%22);alert(1)//")); assert!(!odd.contains("\");alert(1)")); } fn a_hidden_window_runs_at_full_speed() { // Closed to the tray: no throttled timers, no backgrounded renderer, and the earlier switches kept. for arg in ["--disable-background-timer-throttling", "--disable-renderer-backgrounding", "--disable-backgrounding-occluded-windows"] { assert!(BROWSER_ARGS.split(' ').any(|a| a == arg), "{arg}"); } assert!(BROWSER_ARGS.contains("AudioServiceOutOfProcess") && BROWSER_ARGS.contains("--enable-features=HardwareMediaKeyHandling")); assert_eq!(BROWSER_ARGS.matches("--disable-features=").count(), 1, "one --disable-features list"); } fn site_js_knows_the_bars_height() { // site.js lays the page's room out from this before the app's first answer (BAR_PX, then bar over dpr). assert!(include_str!("site.js").contains(&format!("const BAR_CSS = {};", BAR as u32))); }}