Skip to content

GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.

7.9 KB
Raw Blame
use std::{
  cell::RefCell,
  collections::HashMap,
  sync::{
    atomic::{AtomicBool, AtomicUsize, Ordering},
    Arc,
  },
  thread::{self, ThreadId},
};

use windows::{
  core::w,
  Win32::{
    Foundation::{HWND, LPARAM, LRESULT, WPARAM},
    System::Threading::GetCurrentThreadId,
    UI::WindowsAndMessaging::{
      CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW,
      GetMessageW, PostMessageW, PostThreadMessageW, RegisterClassW,
      RegisterWindowMessageW, SendMessageW, TranslateMessage, CS_HREDRAW,
      CS_VREDRAW, CW_USEDEFAULT, MSG, WINDOW_EX_STYLE, WM_QUIT, WNDCLASSW,
      WNDPROC, WS_OVERLAPPEDWINDOW,
    },
  },
};

use crate::{DispatchFn, Dispatcher, WndProcCallback};

thread_local! {
  /// Custom message ID for dispatching closures to be run on the event
  /// loop thread.
  ///
  /// `WPARAM` contains a `Box<Box<dyn FnOnce()>>` that must be retrieved
  /// with `Box::from_raw`. `LPARAM` is unused.
  ///
  /// This message is sent using `PostMessageW` and handled in
  /// [`EventLoop::window_proc`].
  static WM_DISPATCH_CALLBACK: u32 = unsafe { RegisterWindowMessageW(w!("GlazeWM:Dispatch")) };

  /// Registered callbacks that pre-process messages in the event loop's
  /// window procedure.
  ///
  /// Keyed by a unique callback ID for later deregistration.
  static WNDPROC_CALLBACKS: RefCell<HashMap<usize, Box<WndProcCallback>>> =
    RefCell::new(HashMap::new());
}

/// Source for dispatching callbacks onto the event loop thread.
#[derive(Clone)]
pub(crate) struct EventLoopSource {
  pub(crate) message_window_handle: isize,
  pub(crate) thread_id: ThreadId,
  os_thread_id: u32,
  next_callback_id: Arc<AtomicUsize>,
}

impl EventLoopSource {
  pub(crate) fn send_dispatch_async<F>(
    &self,
    dispatch_fn: F,
  ) -> crate::Result<()>
  where
    F: FnOnce() + Send + 'static,
  {
    // Double box the callback to avoid `STATUS_ACCESS_VIOLATION` on
    // Windows. Ref: https://github.com/tauri-apps/tao/blob/dev/src/platform_impl/windows/event_loop.rs#L596
    let dispatch_fn: Box<Box<DispatchFn>> =
      Box::new(Box::new(dispatch_fn));

    // Leak to a raw pointer to then be passed as `WPARAM` in the message.
    let callback_ptr = Box::into_raw(dispatch_fn);

    unsafe {
      if PostMessageW(
        HWND(self.message_window_handle),
        WM_DISPATCH_CALLBACK.with(|v| *v),
        WPARAM(callback_ptr as _),
        LPARAM(0),
      )
      .is_ok()
      {
        Ok(())
      } else {
        // If `PostMessage` fails, we need to clean up the callback.
        let _ = Box::from_raw(callback_ptr);
        Err(crate::Error::WindowMessage(
          "Failed to post message".to_string(),
        ))
      }
    }
  }

  #[allow(clippy::unnecessary_wraps)]
  pub(crate) fn send_dispatch_sync<F>(
    &self,
    dispatch_fn: F,
  ) -> crate::Result<()>
  where
    F: FnOnce() + Send,
  {
    let dispatch_fn: Box<Box<dyn FnOnce() + Send>> =
      Box::new(Box::new(dispatch_fn));
    let callback_ptr = Box::into_raw(dispatch_fn);

    // `SendMessageW` blocks the calling thread until the window procedure
    // processes the message and executes the closure. This guarantees the
    // closure's lifetime remains valid.
    unsafe {
      SendMessageW(
        HWND(self.message_window_handle),
        WM_DISPATCH_CALLBACK.with(|v| *v),
        WPARAM(callback_ptr as _),
        LPARAM(0),
      );
    }

    Ok(())
  }

  pub(crate) fn send_stop(&self) -> crate::Result<()> {
    unsafe {
      PostThreadMessageW(self.os_thread_id, WM_QUIT, WPARAM(0), LPARAM(0))
    }
    .map_err(|_| {
      crate::Error::WindowMessage(
        "Failed to post quit message".to_string(),
      )
    })
  }

  pub(crate) fn register_wndproc_callback(
    &self,
    callback: Box<WndProcCallback>,
  ) -> crate::Result<usize> {
    let id = self.next_callback_id.fetch_add(1, Ordering::Relaxed);

    // The callback is installed asynchronously on the event loop thread.
    self.send_dispatch_async(move || {
      WNDPROC_CALLBACKS.with(|cbs| {
        cbs.borrow_mut().insert(id, callback);
      });
    })?;

    Ok(id)
  }

  pub(crate) fn deregister_wndproc_callback(
    &self,
    id: usize,
  ) -> crate::Result<()> {
    self.send_dispatch_async(move || {
      WNDPROC_CALLBACKS.with(|cbs| {
        cbs.borrow_mut().remove(&id);
      });
    })
  }
}

/// Platform-specific implementation of [`EventLoop`].
pub(crate) struct EventLoop {
  source: EventLoopSource,
}

impl EventLoop {
  /// Implements [`EventLoop::new`].
  pub(crate) fn new() -> crate::Result<(Self, Dispatcher)> {
    // Create a hidden message window on the current thread.
    let window_handle =
      Self::create_message_window(Some(Self::window_proc))?;

    let source = EventLoopSource {
      message_window_handle: window_handle,
      thread_id: thread::current().id(),
      os_thread_id: unsafe { GetCurrentThreadId() },
      next_callback_id: Arc::new(AtomicUsize::new(0)),
    };

    let stopped = Arc::new(AtomicBool::new(false));
    let dispatcher = Dispatcher::new(Some(source.clone()), stopped);

    Ok((Self { source }, dispatcher))
  }

  /// Implements [`EventLoop::run`].
  pub(crate) fn run(&self) -> crate::Result<()> {
    tracing::info!("Starting event loop.");
    let mut msg = MSG::default();

    // Start the message loop. Blocks until `WM_QUIT` is received.
    loop {
      if unsafe { GetMessageW(&raw mut msg, None, 0, 0) }.as_bool() {
        unsafe {
          TranslateMessage(&raw const msg);
          DispatchMessageW(&raw const msg);
        }
      } else {
        break;
      }
    }

    tracing::info!("Event loop thread exiting.");
    unsafe { DestroyWindow(HWND(self.source.message_window_handle)) }?;

    Ok(())
  }

  /// Shuts down the event loop gracefully.
  pub(crate) fn shutdown(&mut self) -> crate::Result<()> {
    tracing::info!("Shutting down event loop.");
    self.source.send_stop()?;

    Ok(())
  }

  /// Creates a hidden message window.
  ///
  /// Returns a handle to the created window.
  fn create_message_window(
    window_procedure: WNDPROC,
  ) -> crate::Result<isize> {
    let wnd_class = WNDCLASSW {
      lpszClassName: w!("MessageWindow"),
      style: CS_HREDRAW | CS_VREDRAW,
      lpfnWndProc: window_procedure,
      ..Default::default()
    };

    unsafe { RegisterClassW(&raw const wnd_class) };

    let handle = unsafe {
      CreateWindowExW(
        WINDOW_EX_STYLE::default(),
        w!("MessageWindow"),
        w!("MessageWindow"),
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        None,
        None,
        wnd_class.hInstance,
        None,
      )
    };

    if handle.0 == 0 {
      return Err(crate::Error::Platform(
        "Creation of message window failed.".to_string(),
      ));
    }

    Ok(handle.0)
  }

  /// Window procedure for handling messages.
  unsafe extern "system" fn window_proc(
    hwnd: HWND,
    msg: u32,
    wparam: WPARAM,
    lparam: LPARAM,
  ) -> LRESULT {
    // Handle dispatch callbacks first.
    if msg == WM_DISPATCH_CALLBACK.with(|v| *v) {
      // Convert the `WPARAM` fn pointer back to a double-boxed function.
      let dispatch_fn: Box<Box<dyn FnOnce() + Send>> =
        Box::from_raw(wparam.0 as *mut _);
      dispatch_fn();
      return LRESULT(0);
    }

    // Let registered callbacks pre-process the message.
    let handled = WNDPROC_CALLBACKS.with(|cbs| {
      for callback in cbs.borrow().values() {
        if let Some(result) = callback(hwnd.0, msg, wparam.0, lparam.0) {
          return Some(LRESULT(result));
        }
      }
      None
    });

    if let Some(result) = handled {
      return result;
    }

    // `WM_QUIT` is handled by the message loop and should be forwarded
    // along with other messages.
    DefWindowProcW(hwnd, msg, wparam, lparam)
  }
}

impl Drop for EventLoop {
  fn drop(&mut self) {
    if let Err(err) = self.shutdown() {
      tracing::warn!("Failed to shut down event loop: {err}");
    }
  }
}