winit/src/platform_impl/windows/window_state.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

540 lines
18 KiB
Rust
Raw Normal View History

2022-08-31 18:32:19 +02:00
use std::sync::MutexGuard;
use std::{fmt, io, ptr};
2024-07-07 18:38:50 +02:00
use bitflags::bitflags;
2022-03-07 22:58:12 +01:00
use windows_sys::Win32::Foundation::{HWND, RECT};
use windows_sys::Win32::Graphics::Gdi::InvalidateRgn;
use windows_sys::Win32::UI::WindowsAndMessaging::{
AdjustWindowRectEx, EnableMenuItem, GetMenu, GetSystemMenu, GetWindowLongW, SendMessageW,
SetWindowLongW, SetWindowPos, ShowWindow, GWL_EXSTYLE, GWL_STYLE, HWND_BOTTOM, HWND_NOTOPMOST,
HWND_TOPMOST, MF_BYCOMMAND, MF_DISABLED, MF_ENABLED, SC_CLOSE, SWP_ASYNCWINDOWPOS,
SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOREPOSITION, SWP_NOSIZE, SWP_NOZORDER,
SW_HIDE, SW_MAXIMIZE, SW_MINIMIZE, SW_RESTORE, SW_SHOW, SW_SHOWNOACTIVATE, WINDOWPLACEMENT,
WINDOW_EX_STYLE, WINDOW_STYLE, WS_BORDER, WS_CAPTION, WS_CHILD, WS_CLIPCHILDREN,
WS_CLIPSIBLINGS, WS_EX_ACCEPTFILES, WS_EX_APPWINDOW, WS_EX_LAYERED, WS_EX_NOREDIRECTIONBITMAP,
WS_EX_TOPMOST, WS_EX_TRANSPARENT, WS_EX_WINDOWEDGE, WS_MAXIMIZE, WS_MAXIMIZEBOX, WS_MINIMIZE,
WS_MINIMIZEBOX, WS_OVERLAPPEDWINDOW, WS_POPUP, WS_SIZEBOX, WS_SYSMENU, WS_VISIBLE,
};
use crate::dpi::{PhysicalPosition, PhysicalSize, Size};
use crate::icon::Icon;
use crate::keyboard::ModifiersState;
use crate::monitor::Fullscreen;
use crate::platform_impl::platform::{event_loop, util, SelectedCursor};
use crate::window::{Theme, WindowAttributes};
2024-07-07 18:38:50 +02:00
/// Contains information about states and the window that the callback is going to use.
#[derive(Debug)]
2022-09-21 10:04:28 +02:00
pub(crate) struct WindowState {
pub mouse: MouseProperties,
/// Used by `WM_GETMINMAXINFO`.
pub min_size: Option<Size>,
pub max_size: Option<Size>,
pub surface_resize_increments: Option<Size>,
pub window_icon: Option<Icon>,
pub taskbar_icon: Option<Icon>,
pub saved_window: Option<SavedWindow>,
pub scale_factor: f64,
Move `ModifiersChanged` variant to `WindowEvent` (#1381) * Move `ModifiersChanged` variant to `WindowEvent` * macos: Fix flags_changed for ModifiersChanged variant move I haven't look too deep at what this does internally, but at least cargo-check is fully happy now. :) Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * macos: Fire a ModifiersChanged event on window_did_resign_key From debugging, I determined that macOS' emission of a flagsChanged around window switching is inconsistent. It is fair to assume, I think, that when the user switches windows, they do not expect their former modifiers state to remain effective; so I think it's best to clear that state by sending a ModifiersChanged(ModifiersState::empty()). Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * windows: Fix build I don't know enough about the code to implement the fix as it is done on this branch, but this commit at least fixes the build. Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * windows: Send ModifiersChanged(ModifiersState::empty) on KILLFOCUS Very similar to the changes made in [1], as focus is lost, send an event to the window indicating that the modifiers have been released. It's unclear to me (without a Windows device to test this on) whether this is necessary, but it certainly ensures that unfocused windows will have at least received this event, which is an improvement. [1]: f79f21641a31da3e4039d41be89047cdcc6028f7 Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * macos: Add a hook to update stale modifiers Sometimes, `ViewState` and `event` might have different values for their stored `modifiers` flags. These are internally stored as a bitmask in the latter and an enum in the former. We can check to see if they differ, and if they do, automatically dispatch an event to update consumers of modifier state as well as the stored `state.modifiers`. That's what the hook does. This hook is then called in the key_down, mouse_entered, mouse_exited, mouse_click, scroll_wheel, and pressure_change_with_event callbacks, which each will contain updated modifiers. Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * Only call event_mods once when determining whether to update state Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * flags_changed: Memoize window_id collection Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * window_did_resign_key: Remove synthetic ModifiersChanged event We no longer need to emit this event, since we are checking the state of our modifiers before emitting most other events. Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * mouse_motion: Add a call to update_potentially_stale_modifiers Now, cover all events (that I can think of, at least) where stale modifiers might affect how user programs behave. Effectively, every human-interface event (keypress, mouse click, keydown, etc.) will cause a ModifiersChanged event to be fired if something has changed. Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * key_up: Add a call to update_potentially_stale_modifiers We also want to make sure modifiers state is synchronized here, too. Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * mouse_motion: Remove update_potentially_stale_modifiers invocation Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * Retry CI * ViewState: Promote visibility of modifiers to the macos impl This is so that we can interact with the ViewState directly from the WindowDelegate. Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * window_delegate: Synthetically set modifiers state to empty on resignKey This logic is implemented similarly on other platforms, so we wish to regain parity here. Originally this behavior was implemented to always fire an event with ModifiersState::empty(), but that was not the best as it was not necessarily correct and could be a duplicate event. This solution is perhaps the most elegant possible to implement the desired behavior of sending a synthetic empty modifiers event when a window loses focus, trading some safety for interoperation between the NSWindowDelegate and the NSView (as the objc runtime must now be consulted in order to acquire access to the ViewState which is "owned" by the NSView). Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * Check for modifiers change in window events * Fix modifier changed on macOS Since the `mouse_entered` function was generating a mouse motion, which updates the modifier state, a modifiers changed event was incorrectly generated. The updating of the modifier state has also been changed to make sure it consistently happens before events that have a modifier state attached to it, without happening on any other event. This of course means that no `CursorMoved` event is generated anymore when the user enters the window without it being focused, however I'd say that is consistent with how winit should behave. * Fix unused variable warning * Move changelog entry into `Unreleased` section Co-authored-by: Freya Gentz <zegentzy@protonmail.com> Co-authored-by: Kristofer Rye <kristofer.rye@gmail.com> Co-authored-by: Christian Duerr <contact@christianduerr.com>
2020-03-06 15:43:55 -07:00
pub modifiers_state: ModifiersState,
Add exclusive fullscreen mode (#925) * Add exclusive fullscreen mode * Add `WindowExtMacOS::set_fullscreen_presentation_options` * Capture display for exclusive fullscreen on macOS * Fix applying video mode on macOS after a fullscreen cycle * Fix compilation on iOS * Set monitor appropriately for fullscreen on macOS * Fix exclusive to borderless fullscreen transitions on macOS * Fix borderless to exclusive fullscreen transition on macOS * Sort video modes on Windows * Fix fullscreen issues on Windows * Fix video mode changes during exclusive fullscreen on Windows * Add video mode sorting for macOS and iOS * Fix monitor `ns_screen` returning `None` after video mode change * Fix "multithreaded" example on macOS * Restore video mode upon closing an exclusive fullscreen window * Fix "multithreaded" example closing multiple windows at once * Fix compilation on Linux * Update FEATURES.md * Don't care about logical monitor groups on X11 * Add exclusive fullscreen for X11 * Update FEATURES.md * Fix transitions between exclusive and borderless fullscreen on X11 * Update CHANGELOG.md * Document that Wayland doesn't support exclusive fullscreen * Replace core-graphics display mode bindings on macOS * Use `panic!()` instead of `unreachable!()` in "fullscreen" example * Fix fullscreen "always on top" flag on Windows * Track current monitor for fullscreen in "multithreaded" example * Fix exclusive fullscreen sometimes not positioning window properly * Format * More formatting and fix CI issues * Fix formatting * Fix changelog formatting
2019-07-29 21:16:14 +03:00
pub fullscreen: Option<Fullscreen>,
pub current_theme: Theme,
pub preferred_theme: Option<Theme>,
pub window_flags: WindowFlags,
pub ime_state: ImeState,
pub ime_allowed: bool,
// Used by WM_NCACTIVATE, WM_SETFOCUS and WM_KILLFOCUS
pub is_active: bool,
pub is_focused: bool,
// Flag whether redraw was requested.
pub redraw_requested: bool,
pub dragging: bool,
pub skip_taskbar: bool,
}
#[derive(Clone)]
pub struct SavedWindow {
2022-03-07 22:58:12 +01:00
pub placement: WINDOWPLACEMENT,
}
impl fmt::Debug for SavedWindow {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SavedWindow").finish_non_exhaustive()
}
}
#[derive(Clone, Debug)]
pub struct MouseProperties {
pub(crate) selected_cursor: SelectedCursor,
pub capture_count: u32,
cursor_flags: CursorFlags,
pub last_position: Option<PhysicalPosition<f64>>,
}
bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CursorFlags: u8 {
const GRABBED = 1 << 0;
const HIDDEN = 1 << 1;
const IN_WINDOW = 1 << 2;
}
}
bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WindowFlags: u32 {
const RESIZABLE = 1 << 0;
const MINIMIZABLE = 1 << 1;
const MAXIMIZABLE = 1 << 2;
const CLOSABLE = 1 << 3;
const VISIBLE = 1 << 4;
const ON_TASKBAR = 1 << 5;
const ALWAYS_ON_TOP = 1 << 6;
const ALWAYS_ON_BOTTOM = 1 << 7;
const NO_BACK_BUFFER = 1 << 8;
const TRANSPARENT = 1 << 9;
const CHILD = 1 << 10;
const MAXIMIZED = 1 << 11;
const POPUP = 1 << 12;
/// Marker flag for fullscreen. Should always match `WindowState::fullscreen`, but is
/// included here to make masking easier.
const MARKER_EXCLUSIVE_FULLSCREEN = 1 << 13;
const MARKER_BORDERLESS_FULLSCREEN = 1 << 14;
/// The `WM_SIZE` event contains some parameters that can effect the state of `WindowFlags`.
/// In most cases, it's okay to let those parameters change the state. However, when we're
/// running the `WindowFlags::apply_diff` function, we *don't* want those parameters to
/// effect our stored state, because the purpose of `apply_diff` is to update the actual
/// window's state to match our stored state. This controls whether to accept those changes.
const MARKER_RETAIN_STATE_ON_SIZE = 1 << 15;
const MARKER_IN_SIZE_MOVE = 1 << 16;
const MINIMIZED = 1 << 17;
const IGNORE_CURSOR_EVENT = 1 << 18;
/// Fully decorated window (incl. caption, border and drop shadow).
const MARKER_DECORATIONS = 1 << 19;
/// Drop shadow for undecorated windows.
const MARKER_UNDECORATED_SHADOW = 1 << 20;
const MARKER_ACTIVATE = 1 << 21;
const CLIP_CHILDREN = 1 << 22;
const EXCLUSIVE_FULLSCREEN_OR_MASK = WindowFlags::ALWAYS_ON_TOP.bits();
}
}
#[derive(Debug, Eq, PartialEq, Hash)]
pub enum ImeState {
Disabled,
Enabled,
Preedit,
}
impl WindowState {
pub(crate) fn new(
attributes: &WindowAttributes,
scale_factor: f64,
current_theme: Theme,
preferred_theme: Option<Theme>,
) -> WindowState {
WindowState {
mouse: MouseProperties {
selected_cursor: SelectedCursor::default(),
capture_count: 0,
cursor_flags: CursorFlags::empty(),
last_position: None,
},
min_size: attributes.min_surface_size,
max_size: attributes.max_surface_size,
surface_resize_increments: attributes.surface_resize_increments,
window_icon: attributes.window_icon.clone(),
taskbar_icon: None,
saved_window: None,
scale_factor,
Move `ModifiersChanged` variant to `WindowEvent` (#1381) * Move `ModifiersChanged` variant to `WindowEvent` * macos: Fix flags_changed for ModifiersChanged variant move I haven't look too deep at what this does internally, but at least cargo-check is fully happy now. :) Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * macos: Fire a ModifiersChanged event on window_did_resign_key From debugging, I determined that macOS' emission of a flagsChanged around window switching is inconsistent. It is fair to assume, I think, that when the user switches windows, they do not expect their former modifiers state to remain effective; so I think it's best to clear that state by sending a ModifiersChanged(ModifiersState::empty()). Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * windows: Fix build I don't know enough about the code to implement the fix as it is done on this branch, but this commit at least fixes the build. Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * windows: Send ModifiersChanged(ModifiersState::empty) on KILLFOCUS Very similar to the changes made in [1], as focus is lost, send an event to the window indicating that the modifiers have been released. It's unclear to me (without a Windows device to test this on) whether this is necessary, but it certainly ensures that unfocused windows will have at least received this event, which is an improvement. [1]: f79f21641a31da3e4039d41be89047cdcc6028f7 Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * macos: Add a hook to update stale modifiers Sometimes, `ViewState` and `event` might have different values for their stored `modifiers` flags. These are internally stored as a bitmask in the latter and an enum in the former. We can check to see if they differ, and if they do, automatically dispatch an event to update consumers of modifier state as well as the stored `state.modifiers`. That's what the hook does. This hook is then called in the key_down, mouse_entered, mouse_exited, mouse_click, scroll_wheel, and pressure_change_with_event callbacks, which each will contain updated modifiers. Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * Only call event_mods once when determining whether to update state Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * flags_changed: Memoize window_id collection Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * window_did_resign_key: Remove synthetic ModifiersChanged event We no longer need to emit this event, since we are checking the state of our modifiers before emitting most other events. Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * mouse_motion: Add a call to update_potentially_stale_modifiers Now, cover all events (that I can think of, at least) where stale modifiers might affect how user programs behave. Effectively, every human-interface event (keypress, mouse click, keydown, etc.) will cause a ModifiersChanged event to be fired if something has changed. Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * key_up: Add a call to update_potentially_stale_modifiers We also want to make sure modifiers state is synchronized here, too. Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * mouse_motion: Remove update_potentially_stale_modifiers invocation Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * Retry CI * ViewState: Promote visibility of modifiers to the macos impl This is so that we can interact with the ViewState directly from the WindowDelegate. Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * window_delegate: Synthetically set modifiers state to empty on resignKey This logic is implemented similarly on other platforms, so we wish to regain parity here. Originally this behavior was implemented to always fire an event with ModifiersState::empty(), but that was not the best as it was not necessarily correct and could be a duplicate event. This solution is perhaps the most elegant possible to implement the desired behavior of sending a synthetic empty modifiers event when a window loses focus, trading some safety for interoperation between the NSWindowDelegate and the NSView (as the objc runtime must now be consulted in order to acquire access to the ViewState which is "owned" by the NSView). Signed-off-by: Kristofer Rye <kristofer.rye@gmail.com> * Check for modifiers change in window events * Fix modifier changed on macOS Since the `mouse_entered` function was generating a mouse motion, which updates the modifier state, a modifiers changed event was incorrectly generated. The updating of the modifier state has also been changed to make sure it consistently happens before events that have a modifier state attached to it, without happening on any other event. This of course means that no `CursorMoved` event is generated anymore when the user enters the window without it being focused, however I'd say that is consistent with how winit should behave. * Fix unused variable warning * Move changelog entry into `Unreleased` section Co-authored-by: Freya Gentz <zegentzy@protonmail.com> Co-authored-by: Kristofer Rye <kristofer.rye@gmail.com> Co-authored-by: Christian Duerr <contact@christianduerr.com>
2020-03-06 15:43:55 -07:00
modifiers_state: ModifiersState::default(),
fullscreen: None,
current_theme,
preferred_theme,
window_flags: WindowFlags::empty(),
ime_state: ImeState::Disabled,
ime_allowed: false,
is_active: false,
is_focused: false,
redraw_requested: false,
dragging: false,
skip_taskbar: false,
}
}
pub fn window_flags(&self) -> WindowFlags {
self.window_flags
}
Add exclusive fullscreen mode (#925) * Add exclusive fullscreen mode * Add `WindowExtMacOS::set_fullscreen_presentation_options` * Capture display for exclusive fullscreen on macOS * Fix applying video mode on macOS after a fullscreen cycle * Fix compilation on iOS * Set monitor appropriately for fullscreen on macOS * Fix exclusive to borderless fullscreen transitions on macOS * Fix borderless to exclusive fullscreen transition on macOS * Sort video modes on Windows * Fix fullscreen issues on Windows * Fix video mode changes during exclusive fullscreen on Windows * Add video mode sorting for macOS and iOS * Fix monitor `ns_screen` returning `None` after video mode change * Fix "multithreaded" example on macOS * Restore video mode upon closing an exclusive fullscreen window * Fix "multithreaded" example closing multiple windows at once * Fix compilation on Linux * Update FEATURES.md * Don't care about logical monitor groups on X11 * Add exclusive fullscreen for X11 * Update FEATURES.md * Fix transitions between exclusive and borderless fullscreen on X11 * Update CHANGELOG.md * Document that Wayland doesn't support exclusive fullscreen * Replace core-graphics display mode bindings on macOS * Use `panic!()` instead of `unreachable!()` in "fullscreen" example * Fix fullscreen "always on top" flag on Windows * Track current monitor for fullscreen in "multithreaded" example * Fix exclusive fullscreen sometimes not positioning window properly * Format * More formatting and fix CI issues * Fix formatting * Fix changelog formatting
2019-07-29 21:16:14 +03:00
pub fn set_window_flags<F>(mut this: MutexGuard<'_, Self>, window: HWND, f: F)
where
F: FnOnce(&mut WindowFlags),
{
let old_flags = this.window_flags;
f(&mut this.window_flags);
let new_flags = this.window_flags;
drop(this);
Add exclusive fullscreen mode (#925) * Add exclusive fullscreen mode * Add `WindowExtMacOS::set_fullscreen_presentation_options` * Capture display for exclusive fullscreen on macOS * Fix applying video mode on macOS after a fullscreen cycle * Fix compilation on iOS * Set monitor appropriately for fullscreen on macOS * Fix exclusive to borderless fullscreen transitions on macOS * Fix borderless to exclusive fullscreen transition on macOS * Sort video modes on Windows * Fix fullscreen issues on Windows * Fix video mode changes during exclusive fullscreen on Windows * Add video mode sorting for macOS and iOS * Fix monitor `ns_screen` returning `None` after video mode change * Fix "multithreaded" example on macOS * Restore video mode upon closing an exclusive fullscreen window * Fix "multithreaded" example closing multiple windows at once * Fix compilation on Linux * Update FEATURES.md * Don't care about logical monitor groups on X11 * Add exclusive fullscreen for X11 * Update FEATURES.md * Fix transitions between exclusive and borderless fullscreen on X11 * Update CHANGELOG.md * Document that Wayland doesn't support exclusive fullscreen * Replace core-graphics display mode bindings on macOS * Use `panic!()` instead of `unreachable!()` in "fullscreen" example * Fix fullscreen "always on top" flag on Windows * Track current monitor for fullscreen in "multithreaded" example * Fix exclusive fullscreen sometimes not positioning window properly * Format * More formatting and fix CI issues * Fix formatting * Fix changelog formatting
2019-07-29 21:16:14 +03:00
old_flags.apply_diff(window, new_flags);
}
pub fn set_window_flags_in_place<F>(&mut self, f: F)
where
F: FnOnce(&mut WindowFlags),
{
f(&mut self.window_flags);
}
pub fn has_active_focus(&self) -> bool {
self.is_active && self.is_focused
}
// Updates is_active and returns whether active-focus state has changed
pub fn set_active(&mut self, is_active: bool) -> bool {
let old = self.has_active_focus();
self.is_active = is_active;
old != self.has_active_focus()
}
// Updates is_focused and returns whether active-focus state has changed
pub fn set_focused(&mut self, is_focused: bool) -> bool {
let old = self.has_active_focus();
self.is_focused = is_focused;
old != self.has_active_focus()
}
}
impl MouseProperties {
pub fn cursor_flags(&self) -> CursorFlags {
self.cursor_flags
}
pub fn set_cursor_flags<F>(&mut self, window: HWND, f: F) -> Result<(), io::Error>
where
F: FnOnce(&mut CursorFlags),
{
let old_flags = self.cursor_flags;
f(&mut self.cursor_flags);
match self.cursor_flags.refresh_os_cursor(window) {
Ok(()) => (),
Err(e) => {
self.cursor_flags = old_flags;
return Err(e);
2019-06-24 12:14:55 -04:00
},
}
Ok(())
}
}
impl WindowFlags {
fn mask(mut self) -> WindowFlags {
if self.contains(WindowFlags::MARKER_EXCLUSIVE_FULLSCREEN) {
self |= WindowFlags::EXCLUSIVE_FULLSCREEN_OR_MASK;
}
self
}
2022-03-07 22:58:12 +01:00
pub fn to_window_styles(self) -> (WINDOW_STYLE, WINDOW_EX_STYLE) {
// Required styles to properly support common window functionality like aero snap.
let mut style = WS_CAPTION | WS_BORDER | WS_CLIPSIBLINGS | WS_SYSMENU;
let mut style_ex = WS_EX_WINDOWEDGE | WS_EX_ACCEPTFILES;
if self.contains(WindowFlags::RESIZABLE) {
style |= WS_SIZEBOX;
}
if self.contains(WindowFlags::MAXIMIZABLE) {
style |= WS_MAXIMIZEBOX;
}
if self.contains(WindowFlags::MINIMIZABLE) {
style |= WS_MINIMIZEBOX;
}
if self.contains(WindowFlags::VISIBLE) {
style |= WS_VISIBLE;
}
if self.contains(WindowFlags::ON_TASKBAR) {
style_ex |= WS_EX_APPWINDOW;
}
if self.contains(WindowFlags::ALWAYS_ON_TOP) {
style_ex |= WS_EX_TOPMOST;
}
if self.contains(WindowFlags::NO_BACK_BUFFER) {
style_ex |= WS_EX_NOREDIRECTIONBITMAP;
}
if self.contains(WindowFlags::CHILD) {
style |= WS_CHILD; // This is incompatible with WS_POPUP if that gets added eventually.
// Remove decorations window styles for child
if !self.contains(WindowFlags::MARKER_DECORATIONS) {
style &= !(WS_CAPTION | WS_BORDER);
style_ex &= !WS_EX_WINDOWEDGE;
}
}
if self.contains(WindowFlags::POPUP) {
style |= WS_POPUP;
}
if self.contains(WindowFlags::MINIMIZED) {
style |= WS_MINIMIZE;
}
if self.contains(WindowFlags::MAXIMIZED) {
style |= WS_MAXIMIZE;
}
if self.contains(WindowFlags::IGNORE_CURSOR_EVENT) {
style_ex |= WS_EX_TRANSPARENT | WS_EX_LAYERED;
}
if self.contains(WindowFlags::CLIP_CHILDREN) {
style |= WS_CLIPCHILDREN;
}
if self.intersects(
WindowFlags::MARKER_EXCLUSIVE_FULLSCREEN | WindowFlags::MARKER_BORDERLESS_FULLSCREEN,
) {
style &= !WS_OVERLAPPEDWINDOW;
}
(style, style_ex)
}
/// Adjust the window client rectangle to the return value, if present.
Add exclusive fullscreen mode (#925) * Add exclusive fullscreen mode * Add `WindowExtMacOS::set_fullscreen_presentation_options` * Capture display for exclusive fullscreen on macOS * Fix applying video mode on macOS after a fullscreen cycle * Fix compilation on iOS * Set monitor appropriately for fullscreen on macOS * Fix exclusive to borderless fullscreen transitions on macOS * Fix borderless to exclusive fullscreen transition on macOS * Sort video modes on Windows * Fix fullscreen issues on Windows * Fix video mode changes during exclusive fullscreen on Windows * Add video mode sorting for macOS and iOS * Fix monitor `ns_screen` returning `None` after video mode change * Fix "multithreaded" example on macOS * Restore video mode upon closing an exclusive fullscreen window * Fix "multithreaded" example closing multiple windows at once * Fix compilation on Linux * Update FEATURES.md * Don't care about logical monitor groups on X11 * Add exclusive fullscreen for X11 * Update FEATURES.md * Fix transitions between exclusive and borderless fullscreen on X11 * Update CHANGELOG.md * Document that Wayland doesn't support exclusive fullscreen * Replace core-graphics display mode bindings on macOS * Use `panic!()` instead of `unreachable!()` in "fullscreen" example * Fix fullscreen "always on top" flag on Windows * Track current monitor for fullscreen in "multithreaded" example * Fix exclusive fullscreen sometimes not positioning window properly * Format * More formatting and fix CI issues * Fix formatting * Fix changelog formatting
2019-07-29 21:16:14 +03:00
fn apply_diff(mut self, window: HWND, mut new: WindowFlags) {
self = self.mask();
new = new.mask();
let mut diff = self ^ new;
if diff == WindowFlags::empty() {
return;
}
if new.contains(WindowFlags::VISIBLE) {
let flag = if !self.contains(WindowFlags::MARKER_ACTIVATE) {
self.set(WindowFlags::MARKER_ACTIVATE, true);
SW_SHOWNOACTIVATE
} else {
SW_SHOW
};
unsafe {
ShowWindow(window, flag);
}
}
if diff.intersects(WindowFlags::ALWAYS_ON_TOP | WindowFlags::ALWAYS_ON_BOTTOM) {
unsafe {
2022-03-07 22:58:12 +01:00
SetWindowPos(
window,
match (
new.contains(WindowFlags::ALWAYS_ON_TOP),
new.contains(WindowFlags::ALWAYS_ON_BOTTOM),
) {
(true, false) => HWND_TOPMOST,
(false, false) => HWND_NOTOPMOST,
(false, true) => HWND_BOTTOM,
(true, true) => unreachable!(),
},
0,
0,
0,
0,
2022-03-07 22:58:12 +01:00
SWP_ASYNCWINDOWPOS | SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE,
);
2025-02-23 22:40:11 -05:00
InvalidateRgn(window, ptr::null_mut(), false.into());
}
}
if diff.contains(WindowFlags::MAXIMIZED) || new.contains(WindowFlags::MAXIMIZED) {
unsafe {
ShowWindow(window, match new.contains(WindowFlags::MAXIMIZED) {
2022-03-07 22:58:12 +01:00
true => SW_MAXIMIZE,
false => SW_RESTORE,
});
}
}
// Minimize operations should execute after maximize for proper window animations
if diff.contains(WindowFlags::MINIMIZED) {
unsafe {
ShowWindow(window, match new.contains(WindowFlags::MINIMIZED) {
2022-03-07 22:58:12 +01:00
true => SW_MINIMIZE,
false => SW_RESTORE,
});
}
diff.remove(WindowFlags::MINIMIZED);
}
if diff.contains(WindowFlags::CLOSABLE) || new.contains(WindowFlags::CLOSABLE) {
let flags = MF_BYCOMMAND
2023-03-08 19:34:10 +03:00
| if new.contains(WindowFlags::CLOSABLE) { MF_ENABLED } else { MF_DISABLED };
unsafe {
EnableMenuItem(GetSystemMenu(window, 0), SC_CLOSE, flags);
}
}
if !new.contains(WindowFlags::VISIBLE) {
unsafe {
ShowWindow(window, SW_HIDE);
}
}
if diff != WindowFlags::empty() {
let (style, style_ex) = new.to_window_styles();
unsafe {
SendMessageW(window, event_loop::SET_RETAIN_STATE_ON_SIZE_MSG_ID.get(), 1, 0);
// This condition is necessary to avoid having an unrestorable window
if !new.contains(WindowFlags::MINIMIZED) {
2022-03-07 22:58:12 +01:00
SetWindowLongW(window, GWL_STYLE, style as i32);
SetWindowLongW(window, GWL_EXSTYLE, style_ex as i32);
}
2022-03-07 22:58:12 +01:00
let mut flags = SWP_NOZORDER | SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED;
Add exclusive fullscreen mode (#925) * Add exclusive fullscreen mode * Add `WindowExtMacOS::set_fullscreen_presentation_options` * Capture display for exclusive fullscreen on macOS * Fix applying video mode on macOS after a fullscreen cycle * Fix compilation on iOS * Set monitor appropriately for fullscreen on macOS * Fix exclusive to borderless fullscreen transitions on macOS * Fix borderless to exclusive fullscreen transition on macOS * Sort video modes on Windows * Fix fullscreen issues on Windows * Fix video mode changes during exclusive fullscreen on Windows * Add video mode sorting for macOS and iOS * Fix monitor `ns_screen` returning `None` after video mode change * Fix "multithreaded" example on macOS * Restore video mode upon closing an exclusive fullscreen window * Fix "multithreaded" example closing multiple windows at once * Fix compilation on Linux * Update FEATURES.md * Don't care about logical monitor groups on X11 * Add exclusive fullscreen for X11 * Update FEATURES.md * Fix transitions between exclusive and borderless fullscreen on X11 * Update CHANGELOG.md * Document that Wayland doesn't support exclusive fullscreen * Replace core-graphics display mode bindings on macOS * Use `panic!()` instead of `unreachable!()` in "fullscreen" example * Fix fullscreen "always on top" flag on Windows * Track current monitor for fullscreen in "multithreaded" example * Fix exclusive fullscreen sometimes not positioning window properly * Format * More formatting and fix CI issues * Fix formatting * Fix changelog formatting
2019-07-29 21:16:14 +03:00
// We generally don't want style changes here to affect window
// focus, but for fullscreen windows they must be activated
// (i.e. focused) so that they appear on top of the taskbar
if !new.contains(WindowFlags::MARKER_EXCLUSIVE_FULLSCREEN)
&& !new.contains(WindowFlags::MARKER_BORDERLESS_FULLSCREEN)
{
2022-03-07 22:58:12 +01:00
flags |= SWP_NOACTIVATE;
}
Add exclusive fullscreen mode (#925) * Add exclusive fullscreen mode * Add `WindowExtMacOS::set_fullscreen_presentation_options` * Capture display for exclusive fullscreen on macOS * Fix applying video mode on macOS after a fullscreen cycle * Fix compilation on iOS * Set monitor appropriately for fullscreen on macOS * Fix exclusive to borderless fullscreen transitions on macOS * Fix borderless to exclusive fullscreen transition on macOS * Sort video modes on Windows * Fix fullscreen issues on Windows * Fix video mode changes during exclusive fullscreen on Windows * Add video mode sorting for macOS and iOS * Fix monitor `ns_screen` returning `None` after video mode change * Fix "multithreaded" example on macOS * Restore video mode upon closing an exclusive fullscreen window * Fix "multithreaded" example closing multiple windows at once * Fix compilation on Linux * Update FEATURES.md * Don't care about logical monitor groups on X11 * Add exclusive fullscreen for X11 * Update FEATURES.md * Fix transitions between exclusive and borderless fullscreen on X11 * Update CHANGELOG.md * Document that Wayland doesn't support exclusive fullscreen * Replace core-graphics display mode bindings on macOS * Use `panic!()` instead of `unreachable!()` in "fullscreen" example * Fix fullscreen "always on top" flag on Windows * Track current monitor for fullscreen in "multithreaded" example * Fix exclusive fullscreen sometimes not positioning window properly * Format * More formatting and fix CI issues * Fix formatting * Fix changelog formatting
2019-07-29 21:16:14 +03:00
// Refresh the window frame
2025-02-23 22:40:11 -05:00
SetWindowPos(window, ptr::null_mut(), 0, 0, 0, 0, flags);
SendMessageW(window, event_loop::SET_RETAIN_STATE_ON_SIZE_MSG_ID.get(), 0, 0);
}
}
}
pub fn adjust_rect(self, hwnd: HWND, mut rect: RECT) -> Result<RECT, io::Error> {
unsafe {
let mut style = GetWindowLongW(hwnd, GWL_STYLE) as u32;
let style_ex = GetWindowLongW(hwnd, GWL_EXSTYLE) as u32;
// Frameless style implemented by manually overriding the non-client area in
// `WM_NCCALCSIZE`.
if !self.contains(WindowFlags::MARKER_DECORATIONS) {
style &= !(WS_CAPTION | WS_SIZEBOX);
}
util::win_to_err({
2025-02-23 22:40:11 -05:00
let b_menu = !GetMenu(hwnd).is_null();
if let (Some(get_dpi_for_window), Some(adjust_window_rect_ex_for_dpi)) =
(*util::GET_DPI_FOR_WINDOW, *util::ADJUST_WINDOW_RECT_EX_FOR_DPI)
{
let dpi = get_dpi_for_window(hwnd);
adjust_window_rect_ex_for_dpi(&mut rect, style, b_menu.into(), style_ex, dpi)
} else {
AdjustWindowRectEx(&mut rect, style, b_menu.into(), style_ex)
}
})?;
Ok(rect)
}
}
pub fn adjust_size(self, hwnd: HWND, size: PhysicalSize<u32>) -> PhysicalSize<u32> {
let (width, height): (u32, u32) = size.into();
let rect = RECT { left: 0, right: width as i32, top: 0, bottom: height as i32 };
let rect = self.adjust_rect(hwnd, rect).unwrap_or(rect);
let outer_x = (rect.right - rect.left).abs();
let outer_y = (rect.top - rect.bottom).abs();
PhysicalSize::new(outer_x as _, outer_y as _)
}
pub fn set_size(self, hwnd: HWND, size: PhysicalSize<u32>) {
unsafe {
let (width, height): (u32, u32) = self.adjust_size(hwnd, size).into();
SetWindowPos(
hwnd,
2025-02-23 22:40:11 -05:00
ptr::null_mut(),
0,
0,
width as _,
height as _,
SWP_ASYNCWINDOWPOS | SWP_NOZORDER | SWP_NOREPOSITION | SWP_NOMOVE | SWP_NOACTIVATE,
);
2025-02-23 22:40:11 -05:00
InvalidateRgn(hwnd, ptr::null_mut(), false.into());
}
}
}
impl CursorFlags {
fn refresh_os_cursor(self, window: HWND) -> Result<(), io::Error> {
let client_rect = util::WindowArea::Inner.get_rect(window)?;
if util::is_focused(window) {
let cursor_clip = match self.contains(CursorFlags::GRABBED) {
true => {
if self.contains(CursorFlags::HIDDEN) {
// Confine the cursor to the center of the window if the cursor is hidden.
// This avoids problems with the cursor activating
// the taskbar if the window borders or overlaps that.
let cx = (client_rect.left + client_rect.right) / 2;
let cy = (client_rect.top + client_rect.bottom) / 2;
Some(RECT { left: cx, right: cx + 1, top: cy, bottom: cy + 1 })
} else {
Some(client_rect)
}
},
false => None,
};
let rect_to_tuple = |rect: RECT| (rect.left, rect.top, rect.right, rect.bottom);
let active_cursor_clip = rect_to_tuple(util::get_cursor_clip()?);
let desktop_rect = rect_to_tuple(util::get_desktop_rect());
let active_cursor_clip = match desktop_rect == active_cursor_clip {
true => None,
false => Some(active_cursor_clip),
};
// We do this check because calling `set_cursor_clip` incessantly will flood the event
// loop with `WM_MOUSEMOVE` events, and `refresh_os_cursor` is called by
// `set_cursor_flags` which at times gets called once every iteration of the
// eventloop.
if active_cursor_clip != cursor_clip.map(rect_to_tuple) {
util::set_cursor_clip(cursor_clip)?;
}
}
let cursor_in_client = self.contains(CursorFlags::IN_WINDOW);
if cursor_in_client {
util::set_cursor_hidden(self.contains(CursorFlags::HIDDEN));
} else {
util::set_cursor_hidden(false);
}
Ok(())
}
}