Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

29.8 KB
Raw Blame
//! The notification-area (tray) icon, like Discord's and Vesktop's: click it
//! to bring RustCord up; right-click for Open, About, Reset RustCord,
//! Restart and Quit (in a dark menu). Also: closing the window to it on
//! Windows, and Windows 11's rounded corners for the frameless window.
//!
//! The icon lives on its own thread with a hidden window for its messages
//! (plain Win32: Shell_NotifyIcon, TrackPopupMenu); picks reach the app over a
//! channel and wake it. On Linux it is a StatusNotifierItem on the session bus
//! (`ksni`), which is what KDE, XFCE and Cinnamon panels show.

#[cfg(not(any(windows, target_os = "linux")))]
use std::sync::mpsc::Receiver;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TrayAction {
    Open,
    About,
    /// Confirmed: log out, clear RustCord's settings and cache, restart.
    Reset,
    Restart,
    Quit,
    /// A RustCord notification was clicked.
    Notification,
    /// Linux: the desktop started showing status notifier items again.
    #[cfg(target_os = "linux")]
    TrayUp,
    /// Linux: the desktop stopped showing them (a panel restart, or GNOME
    /// without the AppIndicator extension). The window must not stay hidden.
    #[cfg(target_os = "linux")]
    TrayDown,
}

#[cfg(windows)]
pub use win::{ask_others_to_quit, from_tray, is_foreground, notify, others_running, remove, round_corners, set_badge, set_window_icons, start, system_animations, system_high_contrast, system_light_theme, take_keyboard_focus, to_tray};
#[cfg(target_os = "linux")]
pub use linux::{remove, start};

#[cfg(not(any(windows, target_os = "linux")))]
pub fn start(_: eframe::egui::Context) -> Option<Receiver<TrayAction>> {
    None
}
#[cfg(not(any(windows, target_os = "linux")))]
pub fn remove() {}
#[cfg(not(windows))]
pub fn round_corners(_: isize) {}
#[cfg(not(windows))]
pub fn to_tray(_: isize) {}
#[cfg(not(windows))]
pub fn from_tray(_: isize) {}
#[cfg(not(windows))]
pub fn is_foreground(_: isize) -> Option<bool> {
    None
}
#[cfg(not(windows))]
pub fn take_keyboard_focus(_: isize) {}
#[cfg(not(windows))]
pub fn set_window_icons(_: isize) {}
#[cfg(not(windows))]
pub fn notify(_: &str, _: &str) {}
#[cfg(not(any(windows, target_os = "macos")))]
pub fn set_badge(_: isize, _: Badge) {}

/// macOS: the badge on RustCord's Dock icon, as Discord's app shows it: the
/// mention count, or a dot for unread messages.
#[cfg(target_os = "macos")]
pub fn set_badge(_: isize, badge: Badge) {
    use objc2_app_kit::NSApplication;
    use objc2_foundation::NSString;
    // The Dock is reached from the main thread, which the UI runs on.
    let Some(mtm) = objc2::MainThreadMarker::new() else { return };
    let label = match badge {
        Badge::None => None,
        Badge::Dot => Some(NSString::from_str("•")),
        Badge::Count(n) => Some(NSString::from_str(&n.to_string())),
    };
    NSApplication::sharedApplication(mtm).dockTile().setBadgeLabel(label.as_deref());
}
#[cfg(not(windows))]
pub fn system_animations() -> bool {
    true
}
#[cfg(not(windows))]
pub fn system_light_theme() -> bool {
    false
}
#[cfg(not(windows))]
pub fn system_high_contrast() -> bool {
    false
}

/// Linux: the notification-area icon, a StatusNotifierItem on D-Bus (what
/// KDE, XFCE and Cinnamon show; GNOME needs the AppIndicator extension).
#[cfg(target_os = "linux")]
mod linux {
    use super::TrayAction;
    use std::sync::mpsc::{Receiver, Sender};
    use std::sync::{Mutex, OnceLock};

    /// The running tray service, kept so it can be taken down before exiting.
    static TRAY: OnceLock<Mutex<Option<ksni::blocking::Handle<Tray>>>> = OnceLock::new();

    struct Tray {
        tx: Sender<TrayAction>,
        ctx: eframe::egui::Context,
    }

    impl Tray {
        fn send(&self, action: TrayAction) {
            let _ = self.tx.send(action);
            // The window may be hidden: wake the UI so it sees the pick.
            self.ctx.request_repaint();
        }
    }

    impl ksni::Tray for Tray {
        fn id(&self) -> String {
            "rustcord".into()
        }
        fn title(&self) -> String {
            "RustCord".into()
        }
        fn icon_pixmap(&self) -> Vec<ksni::Icon> {
            icon()
        }
        /// Left click, like Windows' tray icon: bring RustCord up.
        fn activate(&mut self, _x: i32, _y: i32) {
            self.send(TrayAction::Open);
        }
        fn menu(&self) -> Vec<ksni::MenuItem<Self>> {
            use ksni::menu::{MenuItem, StandardItem};
            // (Windows also offers Reset; its native message box asks first.
            // There's no confirmation dialog here yet, so it's left out.)
            vec![
                StandardItem { label: "Open".into(), activate: Box::new(|t: &mut Tray| t.send(TrayAction::Open)), ..Default::default() }.into(),
                StandardItem { label: "About".into(), activate: Box::new(|t: &mut Tray| t.send(TrayAction::About)), ..Default::default() }.into(),
                StandardItem { label: "Restart".into(), activate: Box::new(|t: &mut Tray| t.send(TrayAction::Restart)), ..Default::default() }.into(),
                MenuItem::Separator,
                StandardItem { label: "Quit".into(), activate: Box::new(|t: &mut Tray| t.send(TrayAction::Quit)), ..Default::default() }.into(),
            ]
        }
        /// A panel restart takes the watcher away for a moment: keep the
        /// service waiting, and tell the app so a hidden window comes back.
        fn watcher_offline(&self, _reason: ksni::OfflineReason) -> bool {
            self.send(TrayAction::TrayDown);
            true
        }
        fn watcher_online(&self) {
            self.send(TrayAction::TrayUp);
        }
    }

    /// RustCord's icon at the sizes panels ask for. A host scales whatever it
    /// gets, but a few exact sizes stay crisp.
    fn icon() -> Vec<ksni::Icon> {
        static ICON: OnceLock<Vec<ksni::Icon>> = OnceLock::new();
        ICON.get_or_init(|| {
            let img = match image::load_from_memory(include_bytes!("../assets/icon-256.png")) {
                Ok(img) => img,
                Err(e) => {
                    log::warn!("tray: couldn't decode the icon ({e})");
                    return Vec::new();
                }
            };
            [16u32, 22, 24, 32, 48]
                .into_iter()
                .map(|size| {
                    let img = img.resize_exact(size, size, image::imageops::FilterType::Lanczos3).into_rgba8();
                    let (width, height) = img.dimensions();
                    let mut data = img.into_vec();
                    // ksni wants ARGB32 in network byte order; image gives RGBA.
                    for pixel in data.as_chunks_mut::<4>().0 {
                        pixel.rotate_right(1);
                    }
                    ksni::Icon { width: width as i32, height: height as i32, data }
                })
                .collect()
        })
        .clone()
    }

    /// Start the tray icon. Picks arrive on the returned channel. `None` when
    /// the desktop has no StatusNotifier host.
    pub fn start(ctx: eframe::egui::Context) -> Option<Receiver<TrayAction>> {
        use ksni::blocking::TrayMethods;
        let (tx, rx) = std::sync::mpsc::channel();
        match (Tray { tx, ctx }).spawn() {
            Ok(handle) => {
                *TRAY.get_or_init(|| Mutex::new(None)).lock().ok()? = Some(handle);
                log::info!("tray: Linux status notifier started");
                Some(rx)
            }
            Err(e) => {
                // GNOME without its AppIndicator extension is the usual case.
                log::info!("tray: no notification-area icon on this desktop ({e})");
                None
            }
        }
    }

    /// Take the icon away before exiting.
    pub fn remove() {
        if let Some(handle) = TRAY.get().and_then(|t| t.lock().ok()).and_then(|mut slot| slot.take()) {
            let _ = handle.shutdown();
        }
    }
}

/// What the taskbar button's badge shows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Badge {
    None,
    /// Unread messages, no mentions.
    Dot,
    /// This many mentions and DMs.
    Count(u32),
}

#[cfg(windows)]
mod win {
    use super::TrayAction;
    use std::sync::atomic::{AtomicIsize, Ordering};
    use std::sync::mpsc::{Receiver, Sender};
    use std::sync::{Mutex, OnceLock};
    use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, WPARAM};
    use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
    use windows_sys::Win32::UI::Shell::{Shell_NotifyIconW, NIF_ICON, NIF_INFO, NIF_MESSAGE, NIF_TIP, NIIF_NOSOUND, NIIF_USER, NIM_ADD, NIM_DELETE, NIM_MODIFY, NOTIFYICONDATAW};
    use windows_sys::Win32::UI::WindowsAndMessaging::*;

    const WM_TRAY: u32 = WM_APP + 1;
    const ID_OPEN: usize = 1;
    const ID_ABOUT: usize = 2;
    const ID_RESET: usize = 3;
    const ID_RESTART: usize = 4;
    const ID_QUIT: usize = 5;

    static TX: OnceLock<Mutex<Sender<TrayAction>>> = OnceLock::new();
    static CTX: OnceLock<eframe::egui::Context> = OnceLock::new();
    static TRAY_HWND: AtomicIsize = AtomicIsize::new(0);
    static TASKBAR_CREATED: AtomicIsize = AtomicIsize::new(0);
    /// What another RustCord program (a second launch, the installer) sends
    /// this window to have RustCord quit as the tray menu's Quit does, with
    /// its settings saved; the answer 1 means it is quitting (versions before
    /// 0.4.41 answer 0). taskkill's polite close can't do that: it only
    /// sends the window to the tray ("Minimize RustCord to System Tray"),
    /// and once it's there it doesn't reach it at all. (The setup sends it
    /// too: apps/setup/src/lib.rs.)
    const QUIT_MESSAGE: &str = "RustCordQuit";
    const CLASS: &str = "RustCordTrayWindow";
    static QUIT: AtomicIsize = AtomicIsize::new(0);
    /// The window's extended style from before it went to the tray.
    static EX_STYLE: AtomicIsize = AtomicIsize::new(0);

    fn wide(s: &str) -> Vec<u16> {
        s.encode_utf16().chain(std::iter::once(0)).collect()
    }

    fn send(a: TrayAction) {
        if let Some(tx) = TX.get().and_then(|t| t.lock().ok()) {
            let _ = tx.send(a);
        }
        if let Some(ctx) = CTX.get() {
            ctx.request_repaint();
        }
    }

    /// Start the tray icon. Picks arrive on the returned channel.
    pub fn start(ctx: eframe::egui::Context) -> Option<Receiver<TrayAction>> {
        let (tx, rx) = std::sync::mpsc::channel();
        TX.set(Mutex::new(tx)).ok()?;
        let _ = CTX.set(ctx);
        std::thread::Builder::new().name("rustcord-tray".into()).spawn(|| unsafe { run() }).ok()?;
        Some(rx)
    }

    /// Other RustCords' tray windows on this desktop, with their process ids.
    fn other_tray_windows() -> Vec<(HWND, u32)> {
        let class = wide(CLASS);
        let mut found = Vec::new();
        let mut after: HWND = std::ptr::null_mut();
        loop {
            after = unsafe { FindWindowExW(std::ptr::null_mut(), after, class.as_ptr(), std::ptr::null()) };
            if after.is_null() {
                return found;
            }
            let mut pid = 0;
            unsafe { GetWindowThreadProcessId(after, &mut pid) };
            if pid != std::process::id() {
                found.push((after, pid));
            }
        }
    }

    /// Ask every other RustCord to quit, with its settings saved. How many
    /// are quitting (versions before 0.4.41 don't know the message).
    pub fn ask_others_to_quit() -> usize {
        let name = wide(QUIT_MESSAGE);
        let quit = unsafe { RegisterWindowMessageW(name.as_ptr()) };
        let mut quitting = 0;
        for (window, _) in other_tray_windows() {
            let mut answer = 0;
            unsafe { SendMessageTimeoutW(window, quit, 0, 0, SMTO_ABORTIFHUNG, 1000, &mut answer) };
            quitting += usize::from(answer == 1);
        }
        quitting
    }

    /// Whether another RustCord is still running (its tray window goes away
    /// as it quits).
    pub fn others_running() -> bool {
        !other_tray_windows().is_empty()
    }

    /// Take the icon away (before exiting, so no "ghost" icon stays behind).
    pub fn remove() {
        let h = TRAY_HWND.load(Ordering::Acquire);
        if h != 0 {
            unsafe {
                PostMessageW(h as HWND, WM_CLOSE, 0, 0);
            }
            std::thread::sleep(std::time::Duration::from_millis(60));
        }
    }

    /// A Windows notification from the tray icon (silent: RustCord plays its
    /// own sound). Clicking it sends [`TrayAction::Notification`].
    pub fn notify(title: &str, text: &str) {
        let h = TRAY_HWND.load(Ordering::Acquire);
        if h == 0 {
            return;
        }
        unsafe {
            let mut nid = icon_data(h as HWND);
            nid.uFlags = NIF_INFO;
            nid.dwInfoFlags = NIIF_USER | NIIF_NOSOUND;
            let put = |text: &str, out: &mut [u16]| {
                let max = out.len() - 1;
                for (i, c) in text.encode_utf16().take(max).enumerate() {
                    out[i] = c;
                }
            };
            put(title, &mut nid.szInfoTitle);
            // An empty text would remove the notification instead of showing it.
            put(if text.is_empty() { " " } else { text }, &mut nid.szInfo);
            Shell_NotifyIconW(NIM_MODIFY, &nid);
        }
    }

    /// Windows' "Animation effects" (Settings → Accessibility → Visual effects).
    pub fn system_animations() -> bool {
        let mut on: i32 = 1;
        unsafe {
            SystemParametersInfoW(SPI_GETCLIENTAREAANIMATION, 0, &mut on as *mut i32 as *mut core::ffi::c_void, 0);
        }
        on != 0
    }

    /// A Windows contrast theme is on (Settings → Accessibility → Contrast themes).
    pub fn system_high_contrast() -> bool {
        // HIGHCONTRASTW
        #[repr(C)]
        struct HighContrast {
            size: u32,
            flags: u32,
            scheme: *mut u16,
        }
        let mut hc = HighContrast { size: std::mem::size_of::<HighContrast>() as u32, flags: 0, scheme: std::ptr::null_mut() };
        // SPI_GETHIGHCONTRAST = 0x42, HCF_HIGHCONTRASTON = 1.
        let ok = unsafe { SystemParametersInfoW(0x42, hc.size, &mut hc as *mut HighContrast as *mut core::ffi::c_void, 0) };
        ok != 0 && hc.flags & 1 != 0
    }

    /// Windows' app mode is Light (Settings → Personalisation → Colours).
    pub fn system_light_theme() -> bool {
        use windows_sys::Win32::System::Registry::{RegGetValueW, HKEY_CURRENT_USER, RRF_RT_REG_DWORD};
        let key = wide("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize");
        let name = wide("AppsUseLightTheme");
        let mut value: u32 = 0;
        let mut size = 4u32;
        let ok = unsafe { RegGetValueW(HKEY_CURRENT_USER, key.as_ptr(), name.as_ptr(), RRF_RT_REG_DWORD, std::ptr::null_mut(), &mut value as *mut u32 as *mut core::ffi::c_void, &mut size) };
        ok == 0 && value != 0
    }

    /// 5×7 digits and "+", a row per byte (bit 4 = left).
    const GLYPHS: [[u8; 7]; 11] = [
        [0x0e, 0x11, 0x13, 0x15, 0x19, 0x11, 0x0e],
        [0x04, 0x0c, 0x04, 0x04, 0x04, 0x04, 0x0e],
        [0x0e, 0x11, 0x01, 0x02, 0x04, 0x08, 0x1f],
        [0x1f, 0x02, 0x04, 0x02, 0x01, 0x11, 0x0e],
        [0x02, 0x06, 0x0a, 0x12, 0x1f, 0x02, 0x02],
        [0x1f, 0x10, 0x1e, 0x01, 0x01, 0x11, 0x0e],
        [0x06, 0x08, 0x10, 0x1e, 0x11, 0x11, 0x0e],
        [0x1f, 0x01, 0x02, 0x04, 0x08, 0x08, 0x08],
        [0x0e, 0x11, 0x11, 0x0e, 0x11, 0x11, 0x0e],
        [0x0e, 0x11, 0x11, 0x0f, 0x01, 0x02, 0x0c],
        [0x00, 0x04, 0x04, 0x1f, 0x04, 0x04, 0x00],
    ];

    /// The badge as a 32 px icon: Discord's red circle with the count (or a
    /// white dot) in it.
    unsafe fn badge_icon(badge: super::Badge) -> HICON {
        use windows_sys::Win32::Graphics::Gdi::{CreateBitmap, DeleteObject};
        const N: usize = 32;
        let mut px = vec![0u8; N * N * 4];
        let mut put = |x: usize, y: usize, [r, g, b]: [u8; 3], a: f32| {
            let i = (y * N + x) * 4;
            let a = a.clamp(0.0, 1.0);
            let old = px[i + 3] as f32 / 255.0;
            let out = a + old * (1.0 - a);
            if out <= 0.0 {
                return;
            }
            // Premultiplied BGRA, which is what a 32-bit icon wants.
            for (k, c) in [b, g, r].into_iter().enumerate() {
                let prev = px[i + k] as f32;
                px[i + k] = (c as f32 * a + prev * (1.0 - a)).round() as u8;
            }
            px[i + 3] = (out * 255.0).round() as u8;
        };
        let disc = |put: &mut dyn FnMut(usize, usize, [u8; 3], f32), radius: f32, color: [u8; 3]| {
            for y in 0..N {
                for x in 0..N {
                    let d = ((x as f32 - 15.5).powi(2) + (y as f32 - 15.5).powi(2)).sqrt();
                    put(x, y, color, radius + 0.5 - d);
                }
            }
        };
        disc(&mut put, 15.0, [0xf2, 0x3f, 0x43]);
        match badge {
            super::Badge::Count(n) => {
                let glyphs: Vec<usize> = if n > 9 { vec![9, 10] } else { vec![n.max(1) as usize] };
                let scale = if glyphs.len() > 1 { 2 } else { 3 };
                let w = glyphs.len() * 5 * scale + (glyphs.len() - 1) * scale;
                let (x0, y0) = ((N - w) / 2, (N - 7 * scale) / 2);
                for (gi, g) in glyphs.iter().enumerate() {
                    for (row, bits) in GLYPHS[*g].iter().enumerate() {
                        for col in 0..5 {
                            if bits & (0x10 >> col) != 0 {
                                for dy in 0..scale {
                                    for dx in 0..scale {
                                        put(x0 + gi * 6 * scale + col * scale + dx, y0 + row * scale + dy, [255, 255, 255], 1.0);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            _ => disc(&mut put, 6.0, [255, 255, 255]),
        }
        let color = CreateBitmap(N as i32, N as i32, 1, 32, px.as_ptr() as *const core::ffi::c_void);
        let mask_bits = vec![0u8; N * N / 8];
        let mask = CreateBitmap(N as i32, N as i32, 1, 1, mask_bits.as_ptr() as *const core::ffi::c_void);
        let info = ICONINFO { fIcon: 1, xHotspot: 0, yHotspot: 0, hbmMask: mask, hbmColor: color };
        let icon = CreateIconIndirect(&info);
        DeleteObject(color as _);
        DeleteObject(mask as _);
        icon
    }

    /// Put the badge on RustCord's taskbar button (call from the UI thread).
    pub fn set_badge(hwnd: isize, badge: super::Badge) {
        use windows::Win32::System::Com::{CoCreateInstance, CLSCTX_INPROC_SERVER};
        use windows::Win32::UI::Shell::{ITaskbarList3, TaskbarList};
        thread_local! {
            static TASKBAR: Option<ITaskbarList3> = unsafe { CoCreateInstance(&TaskbarList, None, CLSCTX_INPROC_SERVER).ok() };
        }
        TASKBAR.with(|tb| {
            let Some(tb) = tb else { return };
            unsafe {
                let h = windows::Win32::Foundation::HWND(hwnd as *mut core::ffi::c_void);
                if badge == super::Badge::None {
                    let _ = tb.SetOverlayIcon(h, windows::Win32::UI::WindowsAndMessaging::HICON::default(), windows::core::PCWSTR::null());
                    return;
                }
                let icon = badge_icon(badge);
                if icon.is_null() {
                    return;
                }
                let text = wide("Unread messages");
                let _ = tb.SetOverlayIcon(h, windows::Win32::UI::WindowsAndMessaging::HICON(icon as *mut core::ffi::c_void), windows::core::PCWSTR(text.as_ptr()));
                DestroyIcon(icon);
            }
        });
    }

    /// Is `hwnd` (or a window it owns, like a menu) the one the user is
    /// using? Windows' own answer; None when there is no foreground window
    /// (switching, the lock screen), when nothing can be said.
    pub fn is_foreground(hwnd: isize) -> Option<bool> {
        unsafe {
            let fg = GetForegroundWindow();
            if fg.is_null() {
                return None;
            }
            Some(fg as isize == hwnd || GetAncestor(fg, GA_ROOTOWNER) as isize == hwnd)
        }
    }

    /// Give `hwnd` the keyboard back if a child window (an embedded player's
    /// WebView2) has it. Only while RustCord is the foreground window.
    pub fn take_keyboard_focus(hwnd: isize) {
        use windows_sys::Win32::UI::Input::KeyboardAndMouse::{GetFocus, SetFocus};
        unsafe {
            let f = GetFocus();
            if f as isize != hwnd {
                SetFocus(hwnd as HWND);
            }
        }
    }

    /// "Minimize RustCord to System Tray": the window leaves the taskbar and
    /// Alt+Tab (it becomes a tool window) and is minimized. It isn't hidden:
    /// Windows sends a hidden window no paint messages, and RustCord's frames
    /// run on those, so it would stop handling anything (its connection, the
    /// tray's own menu) until it came back. The taskbar only looks at the
    /// style when a window is shown, hence hiding it for that moment.
    pub fn to_tray(hwnd: isize) {
        unsafe {
            let h = hwnd as HWND;
            let maximized = IsZoomed(h) != 0;
            let ex = GetWindowLongW(h, GWL_EXSTYLE);
            EX_STYLE.store(ex as isize, Ordering::Relaxed);
            ShowWindow(h, SW_HIDE);
            SetWindowLongW(h, GWL_EXSTYLE, (ex | WS_EX_TOOLWINDOW as i32) & !(WS_EX_APPWINDOW as i32));
            // Minimized off the screen, where Windows keeps minimized windows
            // that are on the taskbar: one that isn't would otherwise sit as
            // a small bar above the taskbar.
            let mut wp: WINDOWPLACEMENT = std::mem::zeroed();
            wp.length = std::mem::size_of::<WINDOWPLACEMENT>() as u32;
            if GetWindowPlacement(h, &mut wp) == 0 {
                ShowWindow(h, SW_SHOWMINNOACTIVE);
                return;
            }
            wp.showCmd = SW_SHOWMINNOACTIVE as u32;
            wp.flags = WPF_SETMINPOSITION | if maximized { WPF_RESTORETOMAXIMIZED } else { 0 };
            wp.ptMinPosition = POINT { x: -32000, y: -32000 };
            SetWindowPlacement(h, &wp);
        }
    }

    /// Back from the tray: on the taskbar again, as it was (maximized or not).
    pub fn from_tray(hwnd: isize) {
        unsafe {
            let h = hwnd as HWND;
            ShowWindow(h, SW_HIDE);
            SetWindowLongW(h, GWL_EXSTYLE, EX_STYLE.load(Ordering::Relaxed) as i32);
            ShowWindow(h, SW_RESTORE);
        }
    }

    /// Windows 11 rounds a frameless window's corners only when asked.
    pub fn round_corners(hwnd: isize) {
        use windows_sys::Win32::Graphics::Dwm::{DwmSetWindowAttribute, DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_ROUND};
        let pref = DWMWCP_ROUND;
        unsafe {
            DwmSetWindowAttribute(hwnd as HWND, DWMWA_WINDOW_CORNER_PREFERENCE as u32, &pref as *const _ as *const core::ffi::c_void, std::mem::size_of_val(&pref) as u32);
        }
    }

    /// The window's taskbar / Alt+Tab (big) and title (small) icons, taken
    /// from the exe's own icon at exactly the sizes Windows asks for: the
    /// one eframe sets is a single 256 px image Windows scales down roughly.
    pub fn set_window_icons(hwnd: isize) {
        unsafe {
            let hinst = GetModuleHandleW(std::ptr::null());
            for (kind, cx, cy) in [(ICON_BIG, SM_CXICON, SM_CYICON), (ICON_SMALL, SM_CXSMICON, SM_CYSMICON)] {
                let icon = LoadImageW(hinst, 1 as *const u16, IMAGE_ICON, GetSystemMetrics(cx), GetSystemMetrics(cy), LR_DEFAULTCOLOR);
                if !icon.is_null() {
                    SendMessageW(hwnd as HWND, WM_SETICON, kind as WPARAM, icon as LPARAM);
                }
            }
        }
    }

    unsafe fn icon_data(hwnd: HWND) -> NOTIFYICONDATAW {
        let mut nid: NOTIFYICONDATAW = std::mem::zeroed();
        nid.cbSize = std::mem::size_of::<NOTIFYICONDATAW>() as u32;
        nid.hWnd = hwnd;
        nid.uID = 1;
        nid
    }

    unsafe fn add_icon(hwnd: HWND) {
        let hinst = GetModuleHandleW(std::ptr::null());
        // The exe's icon (rustcord.rc: resource 1), at the small-icon size.
        let icon = LoadImageW(hinst, 1 as *const u16, IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR);
        let mut nid = icon_data(hwnd);
        nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
        nid.uCallbackMessage = WM_TRAY;
        nid.hIcon = icon as HICON;
        let tip = wide("RustCord");
        for (i, c) in tip.iter().take(nid.szTip.len() - 1).enumerate() {
            nid.szTip[i] = *c;
        }
        Shell_NotifyIconW(NIM_ADD, &nid);
    }

    unsafe fn show_menu(hwnd: HWND) {
        let menu = CreatePopupMenu();
        let items: [(usize, &str); 5] = [(ID_OPEN, "Open"), (ID_ABOUT, "About"), (ID_RESET, "Reset RustCord"), (ID_RESTART, "Restart"), (ID_QUIT, "Quit")];
        for (id, label) in items {
            if id == ID_RESTART {
                AppendMenuW(menu, MF_SEPARATOR, 0, std::ptr::null());
            }
            let w = wide(label);
            AppendMenuW(menu, MF_STRING, id, w.as_ptr());
        }
        SetMenuDefaultItem(menu, ID_OPEN as u32, 0);
        let mut pt = POINT { x: 0, y: 0 };
        GetCursorPos(&mut pt);
        // Without this the menu doesn't close when you click elsewhere.
        SetForegroundWindow(hwnd);
        TrackPopupMenu(menu, TPM_RIGHTBUTTON | TPM_BOTTOMALIGN, pt.x, pt.y, 0, hwnd, std::ptr::null());
        PostMessageW(hwnd, WM_NULL, 0, 0);
        DestroyMenu(menu);
    }

    unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
        match msg {
            WM_TRAY => {
                match (lparam & 0xffff) as u32 {
                    WM_LBUTTONUP => send(TrayAction::Open),
                    WM_RBUTTONUP | WM_CONTEXTMENU => show_menu(hwnd),
                    // NIN_BALLOONUSERCLICK: RustCord's notification was clicked.
                    0x0405 => send(TrayAction::Notification),
                    _ => {}
                }
                0
            }
            WM_COMMAND => {
                match wparam & 0xffff {
                    ID_OPEN => send(TrayAction::Open),
                    ID_ABOUT => send(TrayAction::About),
                    ID_RESET => {
                        let text = wide("Reset RustCord?\n\nThis logs you out, clears RustCord's cache and resets all of its settings. RustCord restarts afterwards.");
                        let title = wide("Reset RustCord");
                        if MessageBoxW(hwnd, text.as_ptr(), title.as_ptr(), MB_YESNO | MB_ICONWARNING | MB_SETFOREGROUND) == IDYES {
                            send(TrayAction::Reset);
                        }
                    }
                    ID_RESTART => send(TrayAction::Restart),
                    ID_QUIT => send(TrayAction::Quit),
                    _ => {}
                }
                0
            }
            WM_CLOSE => {
                let nid = icon_data(hwnd);
                Shell_NotifyIconW(NIM_DELETE, &nid);
                DestroyWindow(hwnd);
                0
            }
            WM_DESTROY => {
                PostQuitMessage(0);
                0
            }
            m if m != 0 && m as isize == QUIT.load(Ordering::Relaxed) => {
                send(TrayAction::Quit);
                1
            }
            // Explorer restarted: the icon has to be added again.
            m if m != 0 && m as isize == TASKBAR_CREATED.load(Ordering::Relaxed) => {
                add_icon(hwnd);
                0
            }
            _ => DefWindowProcW(hwnd, msg, wparam, lparam),
        }
    }

    /// Dark context menus, like Discord's: Windows themes a process's popup
    /// menus dark only when it opts in through uxtheme's SetPreferredAppMode
    /// (ordinal 135, Windows 10 1903+; "ForceDark" = 2) and AllowDarkModeForWindow
    /// (133) on the menu's owner; FlushMenuThemes (136) applies it. Only
    /// exported by ordinal, so looked up at run time; older Windows keeps
    /// light menus.
    unsafe fn dark_menus(hwnd: HWND) {
        use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW};
        let name = wide("uxtheme.dll");
        let ux = LoadLibraryW(name.as_ptr());
        if ux.is_null() {
            return;
        }
        let ordinal = |n: usize| GetProcAddress(ux, n as *const u8);
        if let Some(f) = ordinal(135) {
            let set_mode: unsafe extern "system" fn(i32) -> i32 = std::mem::transmute(f);
            set_mode(2);
        }
        if let Some(f) = ordinal(133) {
            let allow: unsafe extern "system" fn(HWND, i32) -> i32 = std::mem::transmute(f);
            allow(hwnd, 1);
        }
        if let Some(f) = ordinal(136) {
            let flush: unsafe extern "system" fn() = std::mem::transmute(f);
            flush();
        }
    }

    unsafe fn run() {
        let hinst = GetModuleHandleW(std::ptr::null());
        let class = wide(CLASS);
        let wc = WNDCLASSW { lpfnWndProc: Some(wndproc), hInstance: hinst, lpszClassName: class.as_ptr(), ..std::mem::zeroed() };
        RegisterClassW(&wc);
        let title = wide("RustCord tray");
        let hwnd = CreateWindowExW(0, class.as_ptr(), title.as_ptr(), WS_OVERLAPPED, 0, 0, 0, 0, std::ptr::null_mut(), std::ptr::null_mut(), hinst, std::ptr::null());
        if hwnd.is_null() {
            log::warn!("tray: couldn't create the tray window");
            return;
        }
        TRAY_HWND.store(hwnd as isize, Ordering::Release);
        dark_menus(hwnd);
        let tc = wide("TaskbarCreated");
        TASKBAR_CREATED.store(RegisterWindowMessageW(tc.as_ptr()) as isize, Ordering::Relaxed);
        let quit = wide(QUIT_MESSAGE);
        QUIT.store(RegisterWindowMessageW(quit.as_ptr()) as isize, Ordering::Relaxed);
        add_icon(hwnd);
        let mut msg: MSG = std::mem::zeroed();
        while GetMessageW(&mut msg, std::ptr::null_mut(), 0, 0) > 0 {
            TranslateMessage(&msg);
            DispatchMessageW(&msg);
        }
        TRAY_HWND.store(0, Ordering::Release);
    }
}