Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.
Rust desktop-appdiscorddiscord-clienteguielectron-alternativelightweightlinuxmacosnative-apprustwindows
//! The window opens where it was last closed: on the same monitor, at the
//! same position and size, maximized or not (`window.json` in RustCord's
//! config folder). Windows only for now; elsewhere it opens at its default
//! size.
use std::path::{Path, PathBuf};
/// The window's restored (not maximized) bounds in screen pixels, and
/// whether it was maximized.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Placement {
pub x: i32,
pub y: i32,
pub width: i32,
pub height: i32,
pub maximized: bool,
}
/// Where it is kept. Test windows (`RUSTCORD_KEEP_OTHERS`) and the demo keep
/// none, so they never move yours, unless given their own
/// `RUSTCORD_DEV_WINDOW` file.
pub fn file(demo: bool) -> Option<PathBuf> {
if let Some(f) = crate::diagnostics::dev_var_os("RUSTCORD_DEV_WINDOW") {
return Some(f.into());
}
if demo || std::env::var_os("RUSTCORD_KEEP_OTHERS").is_some() {
return None;
}
crate::accounts::config_dir().map(|d| d.join("window.json"))
}
pub fn load(file: Option<&Path>) -> Option<Placement> {
file.and_then(|f| std::fs::read_to_string(f).ok()).and_then(|s| serde_json::from_str(&s).ok())
}
pub fn save(file: Option<&Path>, place: &Placement) {
if let Some(f) = file {
crate::features::write_json(f, place);
}
}
/// Where a window kept at `place` goes on a monitor whose work area is
/// `work` (left, top, right, bottom): wholly on it, no larger than it, and
/// in its middle when `place`'s own monitor is gone. (x, y, width, height).
#[cfg(any(windows, test))]
fn fit(place: &Placement, work: [i32; 4], unplugged: bool) -> [i32; 4] {
let [left, top, right, bottom] = work;
let width = place.width.min(right - left);
let height = place.height.min(bottom - top);
if unplugged {
[left + (right - left - width) / 2, top + (bottom - top - height) / 2, width, height]
} else {
[place.x.clamp(left, right - width), place.y.clamp(top, bottom - height), width, height]
}
}
#[cfg(windows)]
pub use win::{apply, read};
#[cfg(not(windows))]
pub fn read(_: isize) -> Option<Placement> {
None
}
#[cfg(not(windows))]
pub fn apply(_: isize, _: &Placement) {}
#[cfg(windows)]
mod win {
use super::Placement;
use windows_sys::Win32::Foundation::{HWND, POINT, RECT};
use windows_sys::Win32::Graphics::Dwm::{DwmSetWindowAttribute, DWMWA_CLOAK};
use windows_sys::Win32::Graphics::Gdi::{GetMonitorInfoW, MonitorFromPoint, MonitorFromRect, HMONITOR, MONITORINFO, MONITOR_DEFAULTTONULL, MONITOR_DEFAULTTOPRIMARY};
use windows_sys::Win32::UI::WindowsAndMessaging::*;
unsafe fn work_area(monitor: HMONITOR) -> Option<RECT> {
let mut info: MONITORINFO = std::mem::zeroed();
info.cbSize = std::mem::size_of::<MONITORINFO>() as u32;
(GetMonitorInfoW(monitor, &mut info) != 0).then_some(info.rcWork)
}
/// Where the window is now (or would be, restored), as RustCord keeps it.
pub fn read(hwnd: isize) -> Option<Placement> {
if hwnd == 0 {
return None;
}
unsafe {
let h = hwnd as HWND;
let mut wp: WINDOWPLACEMENT = std::mem::zeroed();
wp.length = std::mem::size_of::<WINDOWPLACEMENT>() as u32;
if GetWindowPlacement(h, &mut wp) == 0 {
return None;
}
// A window on the taskbar gets its bounds in "workspace"
// coordinates, which start at the main monitor's work area
// (they differ from the screen's with the taskbar at the top or
// left); a tool window gets screen coordinates.
let (dx, dy) = if GetWindowLongW(h, GWL_EXSTYLE) as u32 & WS_EX_TOOLWINDOW != 0 {
(0, 0)
} else {
let work = work_area(MonitorFromPoint(POINT { x: 0, y: 0 }, MONITOR_DEFAULTTOPRIMARY))?;
(work.left, work.top)
};
let r = wp.rcNormalPosition;
let shown = wp.showCmd as i32;
let maximized = shown == SW_SHOWMAXIMIZED || (shown == SW_SHOWMINIMIZED && wp.flags & WPF_RESTORETOMAXIMIZED != 0);
Some(Placement { x: r.left + dx, y: r.top + dy, width: r.right - r.left, height: r.bottom - r.top, maximized })
}
}
/// Put the window, still hidden before its first frame, where `place`
/// says. It always comes back whole on a monitor: on the main one, in
/// the middle, if its own was unplugged, and never larger than the
/// monitor's work area.
pub fn apply(hwnd: isize, place: &Placement) {
if hwnd == 0 || place.width <= 0 || place.height <= 0 {
return;
}
unsafe {
let h = hwnd as HWND;
let rect = RECT { left: place.x, top: place.y, right: place.x + place.width, bottom: place.y + place.height };
let mut monitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONULL);
let unplugged = monitor.is_null();
if unplugged {
monitor = MonitorFromRect(&rect, MONITOR_DEFAULTTOPRIMARY);
}
let Some(work) = work_area(monitor) else { return };
let [x, y, width, height] = super::fit(place, [work.left, work.top, work.right, work.bottom], unplugged);
// Twice: a first move onto a monitor with another scale makes
// the window resize itself for that scale.
for _ in 0..2 {
SetWindowPos(h, std::ptr::null_mut(), x, y, width, height, SWP_NOZORDER | SWP_NOACTIVATE);
}
if place.maximized {
// Maximized while hidden, as winit does it, but cloaked so
// that the moment it is shown for that never reaches the
// screen. It keeps the bounds above for when it's restored.
let cloak = |on: i32| DwmSetWindowAttribute(h, DWMWA_CLOAK as u32, &on as *const i32 as *const core::ffi::c_void, 4);
cloak(1);
ShowWindow(h, SW_MAXIMIZE);
ShowWindow(h, SW_HIDE);
cloak(0);
}
}
}
}
#[cfg(test)]
mod tests {
use super::{fit, Placement};
const SECOND: [i32; 4] = [2560, 0, 4480, 1000];
#[test]
fn stays_where_it_was() {
let place = Placement { x: 3000, y: 60, width: 1300, height: 800, maximized: false };
assert_eq!(fit(&place, SECOND, false), [3000, 60, 1300, 800]);
}
#[test]
fn comes_back_wholly_on_its_monitor() {
let off_the_edge = Placement { x: 4000, y: -40, width: 1300, height: 800, maximized: false };
assert_eq!(fit(&off_the_edge, SECOND, false), [3180, 0, 1300, 800]);
let too_big = Placement { x: 2500, y: 0, width: 2500, height: 1400, maximized: true };
assert_eq!(fit(&too_big, SECOND, false), [2560, 0, 1920, 1000]);
}
#[test]
fn unplugged_monitor_means_the_middle_of_the_main_one() {
let place = Placement { x: 6000, y: 60, width: 1300, height: 800, maximized: false };
assert_eq!(fit(&place, [0, 0, 2560, 1000], true), [630, 100, 1300, 800]);
}
}