GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
feat: add ctrl+c handling for gracefully shutting down wm
Lars Berger95564c9e71c3
diff --git a/packages/wm/src/common/platform/event_window.rs b/packages/wm/src/common/platform/event_window.rsindex dd2c6a27..0a689328 100644--- a/packages/wm/src/common/platform/event_window.rs+++ b/packages/wm/src/common/platform/event_window.rs@@ -4,8 +4,8 @@ use std::{};use anyhow::Result;-use tokio::sync::{mpsc, oneshot};-use tracing::{info, warn};+use tokio::sync::mpsc;+use tracing::{error, info, warn};use windows::Win32::{Foundation::{HWND, LPARAM, LRESULT, WPARAM},UI::WindowsAndMessaging::{@@ -33,7 +33,6 @@ pub struct EventWindowOptions {#[derive(Debug)]pub struct EventWindow {- abort_tx: Option<oneshot::Sender<()>>,window_thread: Option<JoinHandle<Result<()>>>,}@@ -42,8 +41,6 @@ impl EventWindow {event_tx: mpsc::UnboundedSender<PlatformEvent>,options: EventWindowOptions,) -> Self {- let (abort_tx, abort_rx) = oneshot::channel();-let window_thread = thread::spawn(move || {// Initialize the thread-local sender for platform events.PLATFORM_EVENT_TX@@ -61,14 +58,13 @@ impl EventWindow {let handle =Platform::create_message_window(Some(event_window_proc))?;- Platform::run_message_loop(abort_rx);+ Platform::run_message_loop();unsafe { DestroyWindow(HWND(handle)) }?;Ok(())});Self {- abort_tx: Some(abort_tx),window_thread: Some(window_thread),}}@@ -85,25 +81,27 @@ impl EventWindow {}/// Destroys the event window and stops the message loop.- pub fn destroy(&mut self) {- if let Some(abort_tx) = self.abort_tx.take() {- if abort_tx.send(()).is_err() {- warn!("Failed to send abort signal to the event window thread.");- }- }+ pub fn destroy(&mut self) -> anyhow::Result<()> {+ info!("Shutting down event window.");// Wait for the spawned thread to finish.if let Some(window_thread) = self.window_thread.take() {- if let Err(err) = window_thread.join() {- warn!("Failed to join event window thread '{:?}'.", err);- }+ Platform::kill_message_loop(&window_thread)?;++ window_thread+ .join()+ .map_err(|_| anyhow::anyhow!("Thread join failed."))??;}++ Ok(())}}impl Drop for EventWindow {fn drop(&mut self) {- self.destroy();+ if let Err(err) = self.destroy() {+ error!("Failed to gracefully shut down event window: {}", err);+ }}}@@ -124,7 +122,6 @@ pub extern "system" fn event_window_proc(handle_display_change_msg(message, wparam, event_tx)}WM_POWERBROADCAST => {- info!("power mode changed------- {}", wparam.0 as u32);event_tx.send(PlatformEvent::PowerModeChanged).unwrap();LRESULT(0)}diff --git a/packages/wm/src/common/platform/platform.rs b/packages/wm/src/common/platform/platform.rsindex 5f74e12a..58ef91c5 100644--- a/packages/wm/src/common/platform/platform.rs+++ b/packages/wm/src/common/platform/platform.rs@@ -1,12 +1,13 @@-use std::path::Path;+use std::{os::windows::io::AsRawHandle, path::Path, thread::JoinHandle};use anyhow::{bail, Context};-use tokio::sync::oneshot;use windows::{core::{w, PCWSTR},Win32::{- Foundation::{HWND, POINT},- System::Environment::ExpandEnvironmentStringsW,+ Foundation::{HANDLE, HWND, LPARAM, POINT, WPARAM},+ System::{+ Environment::ExpandEnvironmentStringsW, Threading::GetThreadId,+ },UI::{Shell::{ShellExecuteExW, SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS,@@ -14,10 +15,10 @@ use windows::{},WindowsAndMessaging::{CreateWindowExW, DispatchMessageW, GetAncestor, GetDesktopWindow,- GetForegroundWindow, GetMessageW, RegisterClassW, SetCursorPos,- TranslateMessage, WindowFromPoint, CS_HREDRAW, CS_VREDRAW,- CW_USEDEFAULT, GA_ROOT, MSG, SW_NORMAL, WNDCLASSW, WNDPROC,- WS_OVERLAPPEDWINDOW,+ GetForegroundWindow, GetMessageW, PostThreadMessageW,+ RegisterClassW, SetCursorPos, TranslateMessage, WindowFromPoint,+ CS_HREDRAW, CS_VREDRAW, CW_USEDEFAULT, GA_ROOT, MSG, SW_NORMAL,+ WM_QUIT, WNDCLASSW, WNDPROC, WS_OVERLAPPEDWINDOW,},},},@@ -180,17 +181,12 @@ impl Platform {/// Starts a message loop on the current thread.///- /// This function will block until the message loop is aborted via the- /// `abort_rx` channel.- pub fn run_message_loop(mut abort_rx: oneshot::Receiver<()>) {+ /// This function will block until the message loop is killed. Use+ /// `Platform::kill_message_loop` to terminate the message loop.+ pub fn run_message_loop() {let mut msg = MSG::default();loop {- // Check whether the abort signal has been received.- if abort_rx.try_recv().is_ok() {- break;- }-if unsafe { GetMessageW(&mut msg, None, 0, 0) }.as_bool() {unsafe {TranslateMessage(&msg);@@ -202,6 +198,26 @@ impl Platform {}}+ /// Gracefully terminates the message loop on the given thread.+ pub fn kill_message_loop<T>(+ thread: &JoinHandle<T>,+ ) -> anyhow::Result<()> {+ let handle = thread.as_raw_handle();+ let handle = HANDLE(handle as isize);+ let thread_id = unsafe { GetThreadId(handle) };++ unsafe {+ PostThreadMessageW(+ thread_id,+ WM_QUIT,+ WPARAM::default(),+ LPARAM::default(),+ )+ }?;++ Ok(())+ }+/// Parses a command string into a program name/path and arguments. This/// also expands any environment variables found in the command string if/// they are wrapped in `%` characters. If the command string is a path, adiff --git a/packages/wm/src/ipc_server.rs b/packages/wm/src/ipc_server.rsindex 9e4a8c94..171d9ed1 100644--- a/packages/wm/src/ipc_server.rs+++ b/packages/wm/src/ipc_server.rs@@ -345,6 +345,7 @@ impl IpcServer {}pub fn stop(&self) {+ info!("Shutting down IPC server.");self.abort_handle.abort();}}diff --git a/packages/wm/src/main.rs b/packages/wm/src/main.rsindex 417a48eb..acd41bdb 100644--- a/packages/wm/src/main.rs+++ b/packages/wm/src/main.rs@@ -9,7 +9,7 @@ use std::{env, path::PathBuf};use anyhow::{Context, Result};use sys_tray::SystemTray;-use tokio::process::Command;+use tokio::{process::Command, signal};use tracing::{debug, error, info};use crate::{@@ -73,7 +73,7 @@ async fn start_wm();// Ensure that only one instance of the WM is running.- let _ = Platform::new_single_instance()?;+ let _single_instance = Platform::new_single_instance()?;// Parse and validate user config.let mut config = UserConfig::read(config_path).await?;@@ -81,8 +81,8 @@ async fn start_wm(// Start watcher process for restoring hidden windows on crash.start_watcher_process()?;- // Add application to system tray.- let _ = SystemTray::new()?;+ // Add application icon to system tray.+ let _tray = SystemTray::new()?;let mut wm = WindowManager::new(&config)?;@@ -134,6 +134,10 @@ async fn start_wm(error!("Failed to emit event over IPC: {:?}", err);}},+ _ = signal::ctrl_c() => {+ info!("Received SIGINT signal.");+ break Ok(());+ },}}}diff --git a/packages/wm/src/sys_tray.rs b/packages/wm/src/sys_tray.rsindex b6cb6b20..6846a0c2 100644--- a/packages/wm/src/sys_tray.rs+++ b/packages/wm/src/sys_tray.rs@@ -1,7 +1,6 @@use std::thread::JoinHandle;-use tokio::sync::oneshot;-use tracing::warn;+use tracing::{error, info};use tray_icon::{menu::{AboutMetadata, Menu, MenuEvent, MenuItem, PredefinedMenuItem},Icon, TrayIconBuilder,@@ -13,14 +12,11 @@ use crate::common::platform::Platform;const IDI_ICON: u16 = 0x101;pub struct SystemTray {- abort_tx: Option<oneshot::Sender<()>>,icon_thread: Option<JoinHandle<anyhow::Result<()>>>,}impl SystemTray {pub fn new() -> anyhow::Result<Self> {- let (abort_tx, abort_rx) = oneshot::channel();-let icon_thread = std::thread::spawn(move || {let tray_menu = Menu::new();@@ -48,36 +44,37 @@ impl SystemTray {.with_icon(icon).build()?;- Platform::run_message_loop(abort_rx);+ Platform::run_message_loop();Ok(())});Ok(Self {- abort_tx: Some(abort_tx),icon_thread: Some(icon_thread),})}- /// Destroys the event window and stops the message loop.- pub fn destroy(&mut self) {- if let Some(abort_tx) = self.abort_tx.take() {- if abort_tx.send(()).is_err() {- warn!("Failed to send abort signal to the event window thread.");- }- }+ /// Destroys the system tray icon and stops its associated message loop.+ pub fn destroy(&mut self) -> anyhow::Result<()> {+ info!("Shutting down system tray.");// Wait for the spawned thread to finish.- if let Some(window_thread) = self.icon_thread.take() {- if let Err(err) = window_thread.join() {- warn!("Failed to join event window thread '{:?}'.", err);- }+ if let Some(icon_thread) = self.icon_thread.take() {+ Platform::kill_message_loop(&icon_thread)?;++ icon_thread+ .join()+ .map_err(|_| anyhow::anyhow!("Thread join failed."))??;}++ Ok(())}}impl Drop for SystemTray {fn drop(&mut self) {- self.destroy();+ if let Err(err) = self.destroy() {+ error!("Failed to gracefully shut down system tray: {}", err);+ }}}