Skip to content

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

Close to the tray on Windows too, and open where the window was closed

VRonGitHubfa2a63785da3
diff --git a/README.md b/README.md
index 0990eb4..0dbec5d 100644
--- a/README.md
+++ b/README.md
@@ -226,7 +226,9 @@ GitHub uses for the releases, and starts the app on a Mac to check it.
- DMs and group DMs, unread state and mention badges synced with Discord
- Friends page (online, all, pending, blocked), quick switcher, invites, muting and notification levels
- Remembers where you were in every server and chat, also after a restart
-- Desktop notifications and a tray icon
+- Desktop notifications, and a tray icon that clicking X can leave RustCord running in
+ (System → General → Minimize RustCord to System Tray)
+- Opens on the monitor, at the place and size it was closed at (Windows)
</details>
diff --git a/apps/rustcord/src/app.rs b/apps/rustcord/src/app.rs
index b5c5cb3..86714e6 100644
--- a/apps/rustcord/src/app.rs
+++ b/apps/rustcord/src/app.rs
@@ -455,6 +455,10 @@ pub struct RustCord {
tray_usable: bool,
/// The window is hidden in the notification area.
window_hidden: bool,
+ /// Where the window was last closed (`window.json`), and later where it
+ /// was when it went to the tray; written again on exit.
+ window_file: Option<std::path::PathBuf>,
+ window_place: Option<crate::window_place::Placement>,
/// Automatic updates (an installed copy on Windows only).
pub updater: Option<crate::updater::Updater>,
/// Discord's "Briefly leave voice?" before restarting into an update.
@@ -570,6 +574,8 @@ impl RustCord {
let nav = crate::features::load_nav(crate::features::nav_file(session.as_ref().map(|(id, _)| *id)).as_deref());
let tray = crate::tray::start(cc.egui_ctx.clone());
let tray_usable = tray.is_some();
+ let window_file = crate::window_place::file(demo);
+ let window_place = crate::window_place::load(window_file.as_deref());
let mut app = Self {
ctx: cc.egui_ctx.clone(),
@@ -764,6 +770,8 @@ impl RustCord {
tray,
tray_usable,
window_hidden: false,
+ window_file,
+ window_place,
updater: crate::updater::Updater::start(&cc.egui_ctx),
update_confirm: false,
corners_rounded: false,
@@ -932,30 +940,57 @@ impl RustCord {
}
/// Whether the title bar's X can hide the window in the notification
- /// area. Linux only for now: on Windows a hidden window gets no frames,
- /// so RustCord would stop handling anything (the tray's picks included)
- /// until it is shown again.
+ /// area (Windows and Linux; macOS has no tray icon).
pub fn tray_available(&self) -> bool {
- cfg!(target_os = "linux") && self.tray.is_some() && self.tray_usable
+ let window_known = self.hwnd != 0 || !cfg!(windows);
+ cfg!(any(windows, target_os = "linux")) && window_known && self.tray.is_some() && self.tray_usable
}
/// "Minimize RustCord to System Tray": the title bar's X hides the window
/// (only that X: a close from outside, like the updater's or a second
- /// launch's, still quits, so settings get saved).
+ /// launch's, still quits, so settings get saved). On Windows it leaves
+ /// the taskbar and minimizes instead of hiding (see `tray::to_tray`).
pub fn hide_to_tray(&mut self, ctx: &egui::Context) {
- ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false));
+ if cfg!(windows) {
+ // Its bounds now: once it's a tool window they read differently.
+ self.window_place = crate::window_place::read(self.hwnd).or(self.window_place);
+ crate::tray::to_tray(self.hwnd);
+ } else {
+ ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false));
+ }
self.window_hidden = true;
log::info!("window: hidden in the notification area");
}
- /// Bring the window back from the notification area.
+ /// Bring the window back from the notification area (or up from the
+ /// taskbar, if it was only minimized).
fn show_window(&mut self, ctx: &egui::Context) {
- ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));
- ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
+ if cfg!(windows) && self.window_hidden {
+ crate::tray::from_tray(self.hwnd);
+ // Its taskbar button is a new one: put the badge back on it once
+ // the taskbar has made it.
+ self.badge = crate::tray::Badge::None;
+ self.badge_at = Some(Instant::now());
+ ctx.request_repaint_after(Duration::from_millis(1100));
+ } else {
+ ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));
+ ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
+ }
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
self.window_hidden = false;
}
+ /// Keep where the window is for the next start (on exit).
+ fn save_window_place(&mut self) {
+ // In the tray, its bounds are the ones kept when it went there.
+ if !self.window_hidden {
+ self.window_place = crate::window_place::read(self.hwnd).or(self.window_place);
+ }
+ if let Some(place) = &self.window_place {
+ crate::window_place::save(self.window_file.as_deref(), place);
+ }
+ }
+
/// What was picked on the tray icon.
fn tray_actions(&mut self, ctx: &egui::Context) {
let picks: Vec<crate::tray::TrayAction> = match &self.tray {
@@ -3881,6 +3916,7 @@ impl eframe::App for RustCord {
fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
self.save_nav();
+ self.save_window_place();
if self.zoom_unsaved.take().is_some() {
self.save_prefs();
}
@@ -3897,6 +3933,11 @@ impl eframe::App for RustCord {
self.hwnd = w.hwnd.get();
crate::tray::round_corners(w.hwnd.get());
crate::tray::set_window_icons(w.hwnd.get());
+ // Where it was last closed. Still hidden: eframe shows
+ // the window once this first frame is drawn.
+ if let Some(place) = &self.window_place {
+ crate::window_place::apply(self.hwnd, place);
+ }
}
}
}
diff --git a/apps/rustcord/src/diagnostics.rs b/apps/rustcord/src/diagnostics.rs
index 54000f2..a8ab748 100644
--- a/apps/rustcord/src/diagnostics.rs
+++ b/apps/rustcord/src/diagnostics.rs
@@ -185,6 +185,16 @@ pub fn close_other_instances() {
if std::env::var_os("RUSTCORD_KEEP_OTHERS").is_some() {
return;
}
+ // Through their tray icon first: the one polite close that reaches a
+ // RustCord whose window is in the tray (see `tray::ask_others_to_quit`).
+ let quitting = crate::tray::ask_others_to_quit();
+ if quitting > 0 {
+ log::info!("asked {quitting} older RustCord window(s) to close");
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
+ while crate::tray::others_running() && std::time::Instant::now() < deadline {
+ std::thread::sleep(std::time::Duration::from_millis(100));
+ }
+ }
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
let me = std::process::id().to_string();
let run = |force: bool| {
@@ -210,7 +220,8 @@ pub fn close_other_instances() {
.map(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("SUCCESS"))
.unwrap_or(false)
};
- // Polite close (WM_CLOSE) so settings get saved, then force anything left.
+ // Then taskkill for any left (versions before 0.4.41): a polite close
+ // (WM_CLOSE) so settings get saved, then forced.
if run(false) {
log::info!("asked older RustCord windows to close");
std::thread::sleep(std::time::Duration::from_millis(1500));
diff --git a/apps/rustcord/src/features.rs b/apps/rustcord/src/features.rs
index 32cda8f..e548e04 100644
--- a/apps/rustcord/src/features.rs
+++ b/apps/rustcord/src/features.rs
@@ -657,15 +657,21 @@ pub fn load_nav(file: Option<&Path>) -> Option<NavState> {
}
pub fn save_nav(file: Option<&Path>, nav: &NavState) {
- let Some(f) = file else { return };
- if let Some(d) = f.parent() {
+ if let Some(f) = file {
+ write_json(f, nav);
+ }
+}
+
+/// Write a small JSON file whole, then rename it into place, so a crash
+/// never leaves half a file.
+pub fn write_json<T: serde::Serialize>(file: &Path, value: &T) {
+ if let Some(d) = file.parent() {
let _ = std::fs::create_dir_all(d);
}
- if let Ok(s) = serde_json::to_string(nav) {
- // Written whole then renamed, so a crash never leaves half a file.
- let tmp = f.with_extension("json.tmp");
+ if let Ok(s) = serde_json::to_string(value) {
+ let tmp = file.with_extension("json.tmp");
if std::fs::write(&tmp, s).is_ok() {
- let _ = std::fs::rename(&tmp, f);
+ let _ = std::fs::rename(&tmp, file);
}
}
}
diff --git a/apps/rustcord/src/main.rs b/apps/rustcord/src/main.rs
index d46d30f..e481bd9 100644
--- a/apps/rustcord/src/main.rs
+++ b/apps/rustcord/src/main.rs
@@ -40,6 +40,7 @@ mod style;
mod ui;
mod updater;
mod video;
+mod window_place;
use eframe::egui;
diff --git a/apps/rustcord/src/tray.rs b/apps/rustcord/src/tray.rs
index ef8f5aa..ecc5322 100644
--- a/apps/rustcord/src/tray.rs
+++ b/apps/rustcord/src/tray.rs
@@ -1,7 +1,7 @@
//! 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: Windows 11's rounded corners for
-//! the frameless window.
+//! 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
@@ -31,7 +31,7 @@ pub enum TrayAction {
}
#[cfg(windows)]
-pub use win::{is_foreground, notify, remove, round_corners, set_badge, set_window_icons, start, system_animations, system_high_contrast, system_light_theme, take_keyboard_focus};
+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};
@@ -44,6 +44,10 @@ 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
}
@@ -233,6 +237,17 @@ mod win {
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 while the
+ /// window is in the tray: it doesn't reach a window that's off the
+ /// taskbar. (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()
@@ -256,6 +271,44 @@ mod win {
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);
@@ -454,6 +507,33 @@ mod win {
}
}
+ /// "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 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));
+ ShowWindow(h, SW_SHOWMINNOACTIVE);
+ }
+ }
+
+ /// 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};
@@ -560,6 +640,10 @@ mod win {
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);
@@ -599,7 +683,7 @@ mod win {
unsafe fn run() {
let hinst = GetModuleHandleW(std::ptr::null());
- let class = wide("RustCordTrayWindow");
+ 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");
@@ -612,6 +696,8 @@ mod win {
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 {
diff --git a/apps/rustcord/src/ui/settings.rs b/apps/rustcord/src/ui/settings.rs
index c177ab5..93eb8a7 100644
--- a/apps/rustcord/src/ui/settings.rs
+++ b/apps/rustcord/src/ui/settings.rs
@@ -546,9 +546,9 @@ const fn page(tab: SettingsTab, label: &'static str, icon: &'static str, subs: &
}
/// The sidebar, as Discord's (2026): group, pages, each page's sections.
-/// System's sections. Discord's General (what the title bar's X does) is on
-/// Linux only for now (see `RustCord::tray_available`).
-const SYSTEM_SECTIONS: &[&str] = if cfg!(target_os = "linux") { &["General", "Custom Keybinds", "Default Keybinds"] } else { &["Custom Keybinds", "Default Keybinds"] };
+/// System's sections. Discord's General (what the title bar's X does) is
+/// left out on macOS, which has no tray icon (see `RustCord::tray_available`).
+const SYSTEM_SECTIONS: &[&str] = if cfg!(any(windows, target_os = "linux")) { &["General", "Custom Keybinds", "Default Keybinds"] } else { &["Custom Keybinds", "Default Keybinds"] };
const NAV: &[(&str, &[Page])] = &[
(
@@ -2746,8 +2746,8 @@ impl RustCord {
}
fn system_tab(&mut self, ui: &mut Ui, t: &Theme) {
- // Discord's General: what the title bar's X does (Linux only for now).
- let general = usize::from(cfg!(target_os = "linux"));
+ // Discord's General: what the title bar's X does (not on macOS).
+ let general = usize::from(cfg!(any(windows, target_os = "linux")));
if general == 1 {
section(ui, t, 0, "General");
if self.tray_available() {
diff --git a/apps/rustcord/src/window_place.rs b/apps/rustcord/src/window_place.rs
new file mode 100644
index 0000000..2ce209a
--- /dev/null
+++ b/apps/rustcord/src/window_place.rs
@@ -0,0 +1,172 @@
+//! 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]);
+ }
+}
diff --git a/apps/setup/src/lib.rs b/apps/setup/src/lib.rs
index 56461ff..7746c6a 100644
--- a/apps/setup/src/lib.rs
+++ b/apps/setup/src/lib.rs
@@ -8,7 +8,7 @@
use std::cell::{Cell, RefCell};
use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
-use windows::core::{Interface, GUID, HRESULT, HSTRING, PCWSTR, PWSTR};
+use windows::core::{w, Interface, GUID, HRESULT, HSTRING, PCWSTR, PWSTR};
use windows::Win32::Foundation::{CloseHandle, BOOL, HWND, LPARAM, S_FALSE, S_OK, WPARAM};
use windows::Win32::Security::Credentials::{CredDeleteW, CredEnumerateW, CredFree, CREDENTIALW, CRED_ENUMERATE_FLAGS, CRED_TYPE_GENERIC};
use windows::Win32::System::SystemInformation::GetSystemDirectoryW;
@@ -28,7 +28,7 @@ use windows::Win32::UI::Shell::{
FOLDERID_Desktop, FOLDERID_Programs, FOLDERID_RoamingAppData, FOLDERID_UserProgramFiles, FileOpenDialog, IFileOpenDialog, IShellItem, IShellLinkW, SHCreateItemFromParsingName, SHGetKnownFolderPath,
SHChangeNotify, ShellLink, SHCNE_ASSOCCHANGED, SHCNF_IDLIST, FOS_FORCEFILESYSTEM, FOS_PICKFOLDERS, KF_FLAG_CREATE, SIGDN_FILESYSPATH,
};
-use windows::Win32::UI::WindowsAndMessaging::{LoadIconW, SendMessageW};
+use windows::Win32::UI::WindowsAndMessaging::{FindWindowExW, GetWindowThreadProcessId, LoadIconW, RegisterWindowMessageW, SendMessageTimeoutW, SendMessageW, SMTO_ABORTIFHUNG};
pub const APP: &str = "RustCord";
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
@@ -307,22 +307,62 @@ pub fn running_from(dir: &Path) -> Vec<u32> {
pids
}
+/// Ask the RustCords with these process ids to quit as their tray menu's
+/// Quit does, saving their settings: a message to their tray window (see
+/// `QUIT_MESSAGE` in apps/rustcord/src/tray.rs). taskkill's polite close
+/// can't do that while RustCord's window is in the tray. Whether any is
+/// quitting (versions before 0.4.41 don't know the message).
+fn ask_to_quit(pids: &[u32]) -> bool {
+ let mut quitting = false;
+ // SAFETY: plain window lookups and a message with no pointers in it.
+ unsafe {
+ let quit = RegisterWindowMessageW(w!("RustCordQuit"));
+ let mut after = HWND::default();
+ while let Ok(window) = FindWindowExW(None, after, w!("RustCordTrayWindow"), None) {
+ let mut pid = 0;
+ GetWindowThreadProcessId(window, Some(&mut pid));
+ if pids.contains(&pid) {
+ let mut answer = 0;
+ SendMessageTimeoutW(window, quit, WPARAM(0), LPARAM(0), SMTO_ABORTIFHUNG, 1000, Some(&mut answer));
+ quitting |= answer == 1;
+ }
+ after = window;
+ }
+ }
+ quitting
+}
+
+/// The ways `close_running` tries, in order.
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Close {
+ Tray,
+ Polite,
+ Force,
+}
+
/// Close RustCord running from `dir`: asked politely first (so it saves its
-/// settings), then forced. True once none is left.
+/// settings), through its tray window and then with taskkill (versions
+/// before 0.4.41), then forced. True once none is left.
pub fn close_running(dir: &Path) -> bool {
- for (force, wait) in [(false, 20), (true, 20)] {
+ for (step, wait) in [(Close::Tray, 20), (Close::Polite, 20), (Close::Force, 20)] {
let pids = running_from(dir);
if pids.is_empty() {
return true;
}
- let mut cmd = std::process::Command::new(system_tool("taskkill.exe"));
- for pid in pids {
- cmd.arg("/PID").arg(pid.to_string());
- }
- if force {
- cmd.arg("/F");
+ if step == Close::Tray {
+ if !ask_to_quit(&pids) {
+ continue;
+ }
+ } else {
+ let mut cmd = std::process::Command::new(system_tool("taskkill.exe"));
+ for pid in pids {
+ cmd.arg("/PID").arg(pid.to_string());
+ }
+ if step == Close::Force {
+ cmd.arg("/F");
+ }
+ let _ = cmd.creation_flags(CREATE_NO_WINDOW).output();
}
- let _ = cmd.creation_flags(CREATE_NO_WINDOW).output();
for _ in 0..wait {
if running_from(dir).is_empty() {
// (Windows lets go of the .exe a moment after the process ends.)