bevy_window/
window.rs

1use std::num::NonZeroU32;
2
3use bevy_ecs::{
4    entity::{Entity, EntityMapper, MapEntities},
5    prelude::{Component, ReflectComponent},
6};
7use bevy_math::{DVec2, IVec2, UVec2, Vec2};
8use bevy_reflect::{std_traits::ReflectDefault, Reflect};
9
10#[cfg(feature = "serialize")]
11use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
12
13use bevy_utils::tracing::warn;
14
15use crate::CursorIcon;
16
17/// Marker [`Component`] for the window considered the primary window.
18///
19/// Currently this is assumed to only exist on 1 entity at a time.
20///
21/// [`WindowPlugin`](crate::WindowPlugin) will spawn a [`Window`] entity
22/// with this component if [`primary_window`](crate::WindowPlugin::primary_window)
23/// is `Some`.
24#[derive(Default, Debug, Component, PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Reflect)]
25#[reflect(Component)]
26pub struct PrimaryWindow;
27
28/// Reference to a [`Window`], whether it be a direct link to a specific entity or
29/// a more vague defaulting choice.
30#[repr(C)]
31#[derive(Default, Copy, Clone, Debug, Reflect)]
32#[cfg_attr(
33    feature = "serialize",
34    derive(serde::Serialize, serde::Deserialize),
35    reflect(Serialize, Deserialize)
36)]
37pub enum WindowRef {
38    /// This will be linked to the primary window that is created by default
39    /// in the [`WindowPlugin`](crate::WindowPlugin::primary_window).
40    #[default]
41    Primary,
42    /// A more direct link to a window entity.
43    ///
44    /// Use this if you want to reference a secondary/tertiary/... window.
45    ///
46    /// To create a new window you can spawn an entity with a [`Window`],
47    /// then you can use that entity here for usage in cameras.
48    Entity(Entity),
49}
50
51impl WindowRef {
52    /// Normalize the window reference so that it can be compared to other window references.
53    pub fn normalize(&self, primary_window: Option<Entity>) -> Option<NormalizedWindowRef> {
54        let entity = match self {
55            Self::Primary => primary_window,
56            Self::Entity(entity) => Some(*entity),
57        };
58
59        entity.map(NormalizedWindowRef)
60    }
61}
62
63impl MapEntities for WindowRef {
64    fn map_entities<M: EntityMapper>(&mut self, entity_mapper: &mut M) {
65        match self {
66            Self::Entity(entity) => {
67                *entity = entity_mapper.map_entity(*entity);
68            }
69            Self::Primary => {}
70        };
71    }
72}
73
74/// A flattened representation of a window reference for equality/hashing purposes.
75///
76/// For most purposes you probably want to use the unnormalized version [`WindowRef`].
77#[repr(C)]
78#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Reflect)]
79#[cfg_attr(
80    feature = "serialize",
81    derive(serde::Serialize, serde::Deserialize),
82    reflect(Serialize, Deserialize)
83)]
84pub struct NormalizedWindowRef(Entity);
85
86impl NormalizedWindowRef {
87    /// Fetch the entity of this window reference
88    pub fn entity(&self) -> Entity {
89        self.0
90    }
91}
92
93/// The defining [`Component`] for window entities,
94/// storing information about how it should appear and behave.
95///
96/// Each window corresponds to an entity, and is uniquely identified by the value of their [`Entity`].
97/// When the [`Window`] component is added to an entity, a new window will be opened.
98/// When it is removed or the entity is despawned, the window will close.
99///
100/// The primary window entity (and the corresponding window) is spawned by default
101/// by [`WindowPlugin`](crate::WindowPlugin) and is marked with the [`PrimaryWindow`] component.
102///
103/// This component is synchronized with `winit` through `bevy_winit`:
104/// it will reflect the current state of the window and can be modified to change this state.
105///
106/// # Example
107///
108/// Because this component is synchronized with `winit`, it can be used to perform
109/// OS-integrated windowing operations. For example, here's a simple system
110/// to change the cursor type:
111///
112/// ```
113/// # use bevy_ecs::query::With;
114/// # use bevy_ecs::system::Query;
115/// # use bevy_window::{CursorIcon, PrimaryWindow, Window};
116/// fn change_cursor(mut windows: Query<&mut Window, With<PrimaryWindow>>) {
117///     // Query returns one window typically.
118///     for mut window in windows.iter_mut() {
119///         window.cursor.icon = CursorIcon::Wait;
120///     }
121/// }
122/// ```
123#[derive(Component, Debug, Clone, Reflect)]
124#[cfg_attr(
125    feature = "serialize",
126    derive(serde::Serialize, serde::Deserialize),
127    reflect(Serialize, Deserialize)
128)]
129#[reflect(Component, Default)]
130pub struct Window {
131    /// The cursor of this window.
132    pub cursor: Cursor,
133    /// What presentation mode to give the window.
134    pub present_mode: PresentMode,
135    /// Which fullscreen or windowing mode should be used.
136    pub mode: WindowMode,
137    /// Where the window should be placed.
138    pub position: WindowPosition,
139    /// What resolution the window should have.
140    pub resolution: WindowResolution,
141    /// Stores the title of the window.
142    pub title: String,
143    /// Stores the application ID (on **`Wayland`**), `WM_CLASS` (on **`X11`**) or window class name (on **`Windows`**) of the window.
144    ///
145    /// For details about application ID conventions, see the [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id).
146    /// For details about `WM_CLASS`, see the [X11 Manual Pages](https://www.x.org/releases/current/doc/man/man3/XAllocClassHint.3.xhtml).
147    /// For details about **`Windows`**'s window class names, see [About Window Classes](https://learn.microsoft.com/en-us/windows/win32/winmsg/about-window-classes).
148    ///
149    /// ## Platform-specific
150    ///
151    /// - **`Windows`**: Can only be set while building the window, setting the window's window class name.
152    /// - **`Wayland`**: Can only be set while building the window, setting the window's application ID.
153    /// - **`X11`**: Can only be set while building the window, setting the window's `WM_CLASS`.
154    /// - **`macOS`**, **`iOS`**, **`Android`**, and **`Web`**: not applicable.
155    ///
156    /// Notes: Changing this field during runtime will have no effect for now.
157    pub name: Option<String>,
158    /// How the alpha channel of textures should be handled while compositing.
159    pub composite_alpha_mode: CompositeAlphaMode,
160    /// The limits of the window's logical size
161    /// (found in its [`resolution`](WindowResolution)) when resizing.
162    pub resize_constraints: WindowResizeConstraints,
163    /// Should the window be resizable?
164    ///
165    /// Note: This does not stop the program from fullscreening/setting
166    /// the size programmatically.
167    pub resizable: bool,
168    /// Specifies which window control buttons should be enabled.
169    ///
170    /// ## Platform-specific
171    ///
172    /// **`iOS`**, **`Android`**, and the **`Web`** do not have window control buttons.
173    ///
174    /// On some **`Linux`** environments these values have no effect.
175    pub enabled_buttons: EnabledButtons,
176    /// Should the window have decorations enabled?
177    ///
178    /// (Decorations are the minimize, maximize, and close buttons on desktop apps)
179    ///
180    /// ## Platform-specific
181    ///
182    /// **`iOS`**, **`Android`**, and the **`Web`** do not have decorations.
183    pub decorations: bool,
184    /// Should the window be transparent?
185    ///
186    /// Defines whether the background of the window should be transparent.
187    ///
188    /// ## Platform-specific
189    /// - iOS / Android / Web: Unsupported.
190    /// - macOS: Not working as expected.
191    ///
192    /// macOS transparent works with winit out of the box, so this issue might be related to: <https://github.com/gfx-rs/wgpu/issues/687>.
193    /// You should also set the window `composite_alpha_mode` to `CompositeAlphaMode::PostMultiplied`.
194    pub transparent: bool,
195    /// Get/set whether the window is focused.
196    pub focused: bool,
197    /// Where should the window appear relative to other overlapping window.
198    ///
199    /// ## Platform-specific
200    ///
201    /// - iOS / Android / Web / Wayland: Unsupported.
202    pub window_level: WindowLevel,
203    /// The "html canvas" element selector.
204    ///
205    /// If set, this selector will be used to find a matching html canvas element,
206    /// rather than creating a new one.
207    /// Uses the [CSS selector format](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector).
208    ///
209    /// This value has no effect on non-web platforms.
210    pub canvas: Option<String>,
211    /// Whether or not to fit the canvas element's size to its parent element's size.
212    ///
213    /// **Warning**: this will not behave as expected for parents that set their size according to the size of their
214    /// children. This creates a "feedback loop" that will result in the canvas growing on each resize. When using this
215    /// feature, ensure the parent's size is not affected by its children.
216    ///
217    /// This value has no effect on non-web platforms.
218    pub fit_canvas_to_parent: bool,
219    /// Whether or not to stop events from propagating out of the canvas element
220    ///
221    ///  When `true`, this will prevent common browser hotkeys like F5, F12, Ctrl+R, tab, etc.
222    /// from performing their default behavior while the bevy app has focus.
223    ///
224    /// This value has no effect on non-web platforms.
225    pub prevent_default_event_handling: bool,
226    /// Stores internal state that isn't directly accessible.
227    pub internal: InternalWindowState,
228    /// Should the window use Input Method Editor?
229    ///
230    /// If enabled, the window will receive [`Ime`](crate::Ime) events instead of
231    /// [`ReceivedCharacter`](crate::ReceivedCharacter) or
232    /// `KeyboardInput` from `bevy_input`.
233    ///
234    /// IME should be enabled during text input, but not when you expect to get the exact key pressed.
235    ///
236    ///  ## Platform-specific
237    ///
238    /// - iOS / Android / Web: Unsupported.
239    pub ime_enabled: bool,
240    /// Sets location of IME candidate box in client area coordinates relative to the top left.
241    ///
242    ///  ## Platform-specific
243    ///
244    /// - iOS / Android / Web: Unsupported.
245    pub ime_position: Vec2,
246    /// Sets a specific theme for the window.
247    ///
248    /// If `None` is provided, the window will use the system theme.
249    ///
250    /// ## Platform-specific
251    ///
252    /// - iOS / Android / Web: Unsupported.
253    pub window_theme: Option<WindowTheme>,
254    /// Sets the window's visibility.
255    ///
256    /// If `false`, this will hide the window completely, it won't appear on the screen or in the task bar.
257    /// If `true`, this will show the window.
258    /// Note that this doesn't change its focused or minimized state.
259    ///
260    /// ## Platform-specific
261    ///
262    /// - **Android / Wayland / Web:** Unsupported.
263    pub visible: bool,
264    /// Sets whether the window should be shown in the taskbar.
265    ///
266    /// If `true`, the window will not appear in the taskbar.
267    /// If `false`, the window will appear in the taskbar.
268    ///
269    /// Note that this will only take effect on window creation.
270    ///
271    /// ## Platform-specific
272    ///
273    /// - Only supported on Windows.
274    pub skip_taskbar: bool,
275    /// Optional hint given to the rendering API regarding the maximum number of queued frames admissible on the GPU.
276    ///
277    /// Given values are usually within the 1-3 range. If not provided, this will default to 2.
278    ///
279    /// See [`wgpu::SurfaceConfiguration::desired_maximum_frame_latency`].
280    ///
281    /// [`wgpu::SurfaceConfiguration::desired_maximum_frame_latency`]:
282    /// https://docs.rs/wgpu/latest/wgpu/type.SurfaceConfiguration.html#structfield.desired_maximum_frame_latency
283    pub desired_maximum_frame_latency: Option<NonZeroU32>,
284    /// Sets whether this window recognizes [`PinchGesture`]
285    ///
286    /// ## Platform-specific
287    ///
288    /// - Only used on iOS.
289    /// - On macOS, they are recognized by default and can't be disabled.
290    pub recognize_pinch_gesture: bool,
291    /// Sets whether this window recognizes [`RotationGesture`]
292    ///
293    /// ## Platform-specific
294    ///
295    /// - Only used on iOS.
296    /// - On macOS, they are recognized by default and can't be disabled.
297    pub recognize_rotation_gesture: bool,
298    /// Sets whether this window recognizes [`DoubleTapGesture`]
299    ///
300    /// ## Platform-specific
301    ///
302    /// - Only used on iOS.
303    /// - On macOS, they are recognized by default and can't be disabled.
304    pub recognize_doubletap_gesture: bool,
305    /// Sets whether this window recognizes [`PanGesture`], with a number of fingers between the first value and the last.
306    ///
307    /// ## Platform-specific
308    ///
309    /// - Only used on iOS.
310    pub recognize_pan_gesture: Option<(u8, u8)>,
311}
312
313impl Default for Window {
314    fn default() -> Self {
315        Self {
316            title: "App".to_owned(),
317            name: None,
318            cursor: Default::default(),
319            present_mode: Default::default(),
320            mode: Default::default(),
321            position: Default::default(),
322            resolution: Default::default(),
323            internal: Default::default(),
324            composite_alpha_mode: Default::default(),
325            resize_constraints: Default::default(),
326            ime_enabled: Default::default(),
327            ime_position: Default::default(),
328            resizable: true,
329            enabled_buttons: Default::default(),
330            decorations: true,
331            transparent: false,
332            focused: true,
333            window_level: Default::default(),
334            fit_canvas_to_parent: false,
335            prevent_default_event_handling: true,
336            canvas: None,
337            window_theme: None,
338            visible: true,
339            skip_taskbar: false,
340            desired_maximum_frame_latency: None,
341            recognize_pinch_gesture: false,
342            recognize_rotation_gesture: false,
343            recognize_doubletap_gesture: false,
344            recognize_pan_gesture: None,
345        }
346    }
347}
348
349impl Window {
350    /// Setting to true will attempt to maximize the window.
351    ///
352    /// Setting to false will attempt to un-maximize the window.
353    pub fn set_maximized(&mut self, maximized: bool) {
354        self.internal.maximize_request = Some(maximized);
355    }
356
357    /// Setting to true will attempt to minimize the window.
358    ///
359    /// Setting to false will attempt to un-minimize the window.
360    pub fn set_minimized(&mut self, minimized: bool) {
361        self.internal.minimize_request = Some(minimized);
362    }
363
364    /// The window's client area width in logical pixels.
365    ///
366    /// See [`WindowResolution`] for an explanation about logical/physical sizes.
367    #[inline]
368    pub fn width(&self) -> f32 {
369        self.resolution.width()
370    }
371
372    /// The window's client area height in logical pixels.
373    ///
374    /// See [`WindowResolution`] for an explanation about logical/physical sizes.
375    #[inline]
376    pub fn height(&self) -> f32 {
377        self.resolution.height()
378    }
379
380    /// The window's client size in logical pixels
381    ///
382    /// See [`WindowResolution`] for an explanation about logical/physical sizes.
383    #[inline]
384    pub fn size(&self) -> Vec2 {
385        self.resolution.size()
386    }
387
388    /// The window's client area width in physical pixels.
389    ///
390    /// See [`WindowResolution`] for an explanation about logical/physical sizes.
391    #[inline]
392    pub fn physical_width(&self) -> u32 {
393        self.resolution.physical_width()
394    }
395
396    /// The window's client area height in physical pixels.
397    ///
398    /// See [`WindowResolution`] for an explanation about logical/physical sizes.
399    #[inline]
400    pub fn physical_height(&self) -> u32 {
401        self.resolution.physical_height()
402    }
403
404    /// The window's client size in physical pixels
405    ///
406    /// See [`WindowResolution`] for an explanation about logical/physical sizes.
407    #[inline]
408    pub fn physical_size(&self) -> bevy_math::UVec2 {
409        self.resolution.physical_size()
410    }
411
412    /// The window's scale factor.
413    ///
414    /// Ratio of physical size to logical size, see [`WindowResolution`].
415    #[inline]
416    pub fn scale_factor(&self) -> f32 {
417        self.resolution.scale_factor()
418    }
419
420    /// The cursor position in this window in logical pixels.
421    ///
422    /// Returns `None` if the cursor is outside the window area.
423    ///
424    /// See [`WindowResolution`] for an explanation about logical/physical sizes.
425    #[inline]
426    pub fn cursor_position(&self) -> Option<Vec2> {
427        self.physical_cursor_position()
428            .map(|position| (position.as_dvec2() / self.scale_factor() as f64).as_vec2())
429    }
430
431    /// The cursor position in this window in physical pixels.
432    ///
433    /// Returns `None` if the cursor is outside the window area.
434    ///
435    /// See [`WindowResolution`] for an explanation about logical/physical sizes.
436    #[inline]
437    pub fn physical_cursor_position(&self) -> Option<Vec2> {
438        match self.internal.physical_cursor_position {
439            Some(position) => {
440                if position.x >= 0.
441                    && position.y >= 0.
442                    && position.x < self.physical_width() as f64
443                    && position.y < self.physical_height() as f64
444                {
445                    Some(position.as_vec2())
446                } else {
447                    None
448                }
449            }
450            None => None,
451        }
452    }
453
454    /// Set the cursor position in this window in logical pixels.
455    ///
456    /// See [`WindowResolution`] for an explanation about logical/physical sizes.
457    pub fn set_cursor_position(&mut self, position: Option<Vec2>) {
458        self.internal.physical_cursor_position =
459            position.map(|p| p.as_dvec2() * self.scale_factor() as f64);
460    }
461
462    /// Set the cursor position in this window in physical pixels.
463    ///
464    /// See [`WindowResolution`] for an explanation about logical/physical sizes.
465    pub fn set_physical_cursor_position(&mut self, position: Option<DVec2>) {
466        self.internal.physical_cursor_position = position;
467    }
468}
469
470/// The size limits on a [`Window`].
471///
472/// These values are measured in logical pixels (see [`WindowResolution`]), so the user's
473/// scale factor does affect the size limits on the window.
474///
475/// Please note that if the window is resizable, then when the window is
476/// maximized it may have a size outside of these limits. The functionality
477/// required to disable maximizing is not yet exposed by winit.
478#[derive(Debug, Clone, Copy, PartialEq, Reflect)]
479#[cfg_attr(
480    feature = "serialize",
481    derive(serde::Serialize, serde::Deserialize),
482    reflect(Serialize, Deserialize)
483)]
484#[reflect(Debug, PartialEq, Default)]
485pub struct WindowResizeConstraints {
486    /// The minimum width the window can have.
487    pub min_width: f32,
488    /// The minimum height the window can have.
489    pub min_height: f32,
490    /// The maximum width the window can have.
491    pub max_width: f32,
492    /// The maximum height the window can have.
493    pub max_height: f32,
494}
495
496impl Default for WindowResizeConstraints {
497    fn default() -> Self {
498        Self {
499            min_width: 180.,
500            min_height: 120.,
501            max_width: f32::INFINITY,
502            max_height: f32::INFINITY,
503        }
504    }
505}
506
507impl WindowResizeConstraints {
508    /// Checks if the constraints are valid.
509    ///
510    /// Will output warnings if it isn't.
511    #[must_use]
512    pub fn check_constraints(&self) -> Self {
513        let WindowResizeConstraints {
514            mut min_width,
515            mut min_height,
516            mut max_width,
517            mut max_height,
518        } = self;
519        min_width = min_width.max(1.);
520        min_height = min_height.max(1.);
521        if max_width < min_width {
522            warn!(
523                "The given maximum width {} is smaller than the minimum width {}",
524                max_width, min_width
525            );
526            max_width = min_width;
527        }
528        if max_height < min_height {
529            warn!(
530                "The given maximum height {} is smaller than the minimum height {}",
531                max_height, min_height
532            );
533            max_height = min_height;
534        }
535        WindowResizeConstraints {
536            min_width,
537            min_height,
538            max_width,
539            max_height,
540        }
541    }
542}
543
544/// Cursor data for a [`Window`].
545#[derive(Debug, Copy, Clone, Reflect)]
546#[cfg_attr(
547    feature = "serialize",
548    derive(serde::Serialize, serde::Deserialize),
549    reflect(Serialize, Deserialize)
550)]
551#[reflect(Debug, Default)]
552pub struct Cursor {
553    /// What the cursor should look like while inside the window.
554    pub icon: CursorIcon,
555
556    /// Whether the cursor is visible or not.
557    ///
558    /// ## Platform-specific
559    ///
560    /// - **`Windows`**, **`X11`**, and **`Wayland`**: The cursor is hidden only when inside the window.
561    /// To stop the cursor from leaving the window, change [`Cursor::grab_mode`] to [`CursorGrabMode::Locked`] or [`CursorGrabMode::Confined`]
562    /// - **`macOS`**: The cursor is hidden only when the window is focused.
563    /// - **`iOS`** and **`Android`** do not have cursors
564    pub visible: bool,
565
566    /// Whether or not the cursor is locked by or confined within the window.
567    ///
568    /// ## Platform-specific
569    ///
570    /// - **`Windows`** doesn't support [`CursorGrabMode::Locked`]
571    /// - **`macOS`** doesn't support [`CursorGrabMode::Confined`]
572    /// - **`iOS/Android`** don't have cursors.
573    ///
574    /// Since `Windows` and `macOS` have different [`CursorGrabMode`] support, we first try to set the grab mode that was asked for. If it doesn't work then use the alternate grab mode.
575    pub grab_mode: CursorGrabMode,
576
577    /// Set whether or not mouse events within *this* window are captured or fall through to the Window below.
578    ///
579    /// ## Platform-specific
580    ///
581    /// - iOS / Android / Web / X11: Unsupported.
582    pub hit_test: bool,
583}
584
585impl Default for Cursor {
586    fn default() -> Self {
587        Cursor {
588            icon: CursorIcon::Default,
589            visible: true,
590            grab_mode: CursorGrabMode::None,
591            hit_test: true,
592        }
593    }
594}
595
596/// Defines where a [`Window`] should be placed on the screen.
597#[derive(Default, Debug, Clone, Copy, PartialEq, Reflect)]
598#[cfg_attr(
599    feature = "serialize",
600    derive(serde::Serialize, serde::Deserialize),
601    reflect(Serialize, Deserialize)
602)]
603#[reflect(Debug, PartialEq)]
604pub enum WindowPosition {
605    /// Position will be set by the window manager.
606    /// Bevy will delegate this decision to the window manager and no guarantees can be made about where the window will be placed.
607    ///
608    /// Used at creation but will be changed to [`At`](WindowPosition::At).
609    #[default]
610    Automatic,
611    /// Window will be centered on the selected monitor.
612    ///
613    /// Note that this does not account for window decorations.
614    ///
615    /// Used at creation or for update but will be changed to [`At`](WindowPosition::At)
616    Centered(MonitorSelection),
617    /// The window's top-left corner should be placed at the specified position (in physical pixels).
618    ///
619    /// (0,0) represents top-left corner of screen space.
620    At(IVec2),
621}
622
623impl WindowPosition {
624    /// Creates a new [`WindowPosition`] at a position.
625    pub fn new(position: IVec2) -> Self {
626        Self::At(position)
627    }
628
629    /// Set the position to a specific point.
630    pub fn set(&mut self, position: IVec2) {
631        *self = WindowPosition::At(position);
632    }
633
634    /// Set the window to a specific monitor.
635    pub fn center(&mut self, monitor: MonitorSelection) {
636        *self = WindowPosition::Centered(monitor);
637    }
638}
639
640/// Controls the size of a [`Window`]
641///
642/// ## Physical, logical and requested sizes
643///
644/// There are three sizes associated with a window:
645/// - the physical size,
646/// which represents the actual height and width in physical pixels
647/// the window occupies on the monitor,
648/// - the logical size,
649/// which represents the size that should be used to scale elements
650/// inside the window, measured in logical pixels,
651/// - the requested size,
652/// measured in logical pixels, which is the value submitted
653/// to the API when creating the window, or requesting that it be resized.
654///
655/// ## Scale factor
656///
657/// The reason logical size and physical size are separated and can be different
658/// is to account for the cases where:
659/// - several monitors have different pixel densities,
660/// - the user has set up a pixel density preference in its operating system,
661/// - the Bevy `App` has specified a specific scale factor between both.
662///
663/// The factor between physical size and logical size can be retrieved with
664/// [`WindowResolution::scale_factor`].
665///
666/// For the first two cases, a scale factor is set automatically by the operating
667/// system through the window backend. You can get it with
668/// [`WindowResolution::base_scale_factor`].
669///
670/// For the third case, you can override this automatic scale factor with
671/// [`WindowResolution::set_scale_factor_override`].
672///
673/// ## Requested and obtained sizes
674///
675/// The logical size should be equal to the requested size after creating/resizing,
676/// when possible.
677/// The reason the requested size and logical size might be different
678/// is because the corresponding physical size might exceed limits (either the
679/// size limits of the monitor, or limits defined in [`WindowResizeConstraints`]).
680///
681/// Note: The requested size is not kept in memory, for example requesting a size
682/// too big for the screen, making the logical size different from the requested size,
683/// and then setting a scale factor that makes the previous requested size within
684/// the limits of the screen will not get back that previous requested size.
685
686#[derive(Debug, Clone, PartialEq, Reflect)]
687#[cfg_attr(
688    feature = "serialize",
689    derive(serde::Serialize, serde::Deserialize),
690    reflect(Serialize, Deserialize)
691)]
692#[reflect(Debug, PartialEq, Default)]
693pub struct WindowResolution {
694    /// Width of the window in physical pixels.
695    physical_width: u32,
696    /// Height of the window in physical pixels.
697    physical_height: u32,
698    /// Code-provided ratio of physical size to logical size.
699    ///
700    /// Should be used instead of `scale_factor` when set.
701    scale_factor_override: Option<f32>,
702    /// OS-provided ratio of physical size to logical size.
703    ///
704    /// Set automatically depending on the pixel density of the screen.
705    scale_factor: f32,
706}
707
708impl Default for WindowResolution {
709    fn default() -> Self {
710        WindowResolution {
711            physical_width: 1280,
712            physical_height: 720,
713            scale_factor_override: None,
714            scale_factor: 1.0,
715        }
716    }
717}
718
719impl WindowResolution {
720    /// Creates a new [`WindowResolution`].
721    pub fn new(physical_width: f32, physical_height: f32) -> Self {
722        Self {
723            physical_width: physical_width as u32,
724            physical_height: physical_height as u32,
725            ..Default::default()
726        }
727    }
728
729    /// Builder method for adding a scale factor override to the resolution.
730    pub fn with_scale_factor_override(mut self, scale_factor_override: f32) -> Self {
731        self.set_scale_factor_override(Some(scale_factor_override));
732        self
733    }
734
735    /// The window's client area width in logical pixels.
736    #[inline]
737    pub fn width(&self) -> f32 {
738        self.physical_width() as f32 / self.scale_factor()
739    }
740
741    /// The window's client area height in logical pixels.
742    #[inline]
743    pub fn height(&self) -> f32 {
744        self.physical_height() as f32 / self.scale_factor()
745    }
746
747    /// The window's client size in logical pixels
748    #[inline]
749    pub fn size(&self) -> Vec2 {
750        Vec2::new(self.width(), self.height())
751    }
752
753    /// The window's client area width in physical pixels.
754    #[inline]
755    pub fn physical_width(&self) -> u32 {
756        self.physical_width
757    }
758
759    /// The window's client area height in physical pixels.
760    #[inline]
761    pub fn physical_height(&self) -> u32 {
762        self.physical_height
763    }
764
765    /// The window's client size in physical pixels
766    #[inline]
767    pub fn physical_size(&self) -> UVec2 {
768        UVec2::new(self.physical_width, self.physical_height)
769    }
770
771    /// The ratio of physical pixels to logical pixels.
772    ///
773    /// `physical_pixels = logical_pixels * scale_factor`
774    pub fn scale_factor(&self) -> f32 {
775        self.scale_factor_override
776            .unwrap_or_else(|| self.base_scale_factor())
777    }
778
779    /// The window scale factor as reported by the window backend.
780    ///
781    /// This value is unaffected by [`WindowResolution::scale_factor_override`].
782    #[inline]
783    pub fn base_scale_factor(&self) -> f32 {
784        self.scale_factor
785    }
786
787    /// The scale factor set with [`WindowResolution::set_scale_factor_override`].
788    ///
789    /// This value may be different from the scale factor reported by the window backend.
790    #[inline]
791    pub fn scale_factor_override(&self) -> Option<f32> {
792        self.scale_factor_override
793    }
794
795    /// Set the window's logical resolution.
796    #[inline]
797    pub fn set(&mut self, width: f32, height: f32) {
798        self.set_physical_resolution(
799            (width * self.scale_factor()) as u32,
800            (height * self.scale_factor()) as u32,
801        );
802    }
803
804    /// Set the window's physical resolution.
805    ///
806    /// This will ignore the scale factor setting, so most of the time you should
807    /// prefer to use [`WindowResolution::set`].
808    #[inline]
809    pub fn set_physical_resolution(&mut self, width: u32, height: u32) {
810        self.physical_width = width;
811        self.physical_height = height;
812    }
813
814    /// Set the window's scale factor, this may get overridden by the backend.
815    #[inline]
816    pub fn set_scale_factor(&mut self, scale_factor: f32) {
817        self.scale_factor = scale_factor;
818    }
819
820    /// Set the window's scale factor, and apply it to the currently known physical size.
821    /// This may get overridden by the backend. This is mostly useful on window creation,
822    /// so that the window is created with the expected size instead of waiting for a resize
823    /// event after its creation.
824    #[inline]
825    #[doc(hidden)]
826    pub fn set_scale_factor_and_apply_to_physical_size(&mut self, scale_factor: f32) {
827        self.scale_factor = scale_factor;
828        self.physical_width = (self.physical_width as f32 * scale_factor) as u32;
829        self.physical_height = (self.physical_height as f32 * scale_factor) as u32;
830    }
831
832    /// Set the window's scale factor, this will be used over what the backend decides.
833    ///
834    /// This can change the logical and physical sizes if the resulting physical
835    /// size is not within the limits.
836    #[inline]
837    pub fn set_scale_factor_override(&mut self, scale_factor_override: Option<f32>) {
838        self.scale_factor_override = scale_factor_override;
839    }
840}
841
842impl<I> From<(I, I)> for WindowResolution
843where
844    I: Into<f32>,
845{
846    fn from((width, height): (I, I)) -> WindowResolution {
847        WindowResolution::new(width.into(), height.into())
848    }
849}
850
851impl<I> From<[I; 2]> for WindowResolution
852where
853    I: Into<f32>,
854{
855    fn from([width, height]: [I; 2]) -> WindowResolution {
856        WindowResolution::new(width.into(), height.into())
857    }
858}
859
860impl From<Vec2> for WindowResolution {
861    fn from(res: Vec2) -> WindowResolution {
862        WindowResolution::new(res.x, res.y)
863    }
864}
865
866impl From<DVec2> for WindowResolution {
867    fn from(res: DVec2) -> WindowResolution {
868        WindowResolution::new(res.x as f32, res.y as f32)
869    }
870}
871
872/// Defines if and how the [`Cursor`] is grabbed by a [`Window`].
873///
874/// ## Platform-specific
875///
876/// - **`Windows`** doesn't support [`CursorGrabMode::Locked`]
877/// - **`macOS`** doesn't support [`CursorGrabMode::Confined`]
878/// - **`iOS/Android`** don't have cursors.
879///
880/// Since `Windows` and `macOS` have different [`CursorGrabMode`] support, we first try to set the grab mode that was asked for. If it doesn't work then use the alternate grab mode.
881#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Reflect)]
882#[cfg_attr(
883    feature = "serialize",
884    derive(serde::Serialize, serde::Deserialize),
885    reflect(Serialize, Deserialize)
886)]
887#[reflect(Debug, PartialEq, Default)]
888pub enum CursorGrabMode {
889    /// The cursor can freely leave the window.
890    #[default]
891    None,
892    /// The cursor is confined to the window area.
893    Confined,
894    /// The cursor is locked inside the window area to a certain position.
895    Locked,
896}
897
898/// Stores internal [`Window`] state that isn't directly accessible.
899#[derive(Default, Debug, Copy, Clone, PartialEq, Reflect)]
900#[cfg_attr(
901    feature = "serialize",
902    derive(serde::Serialize, serde::Deserialize),
903    reflect(Serialize, Deserialize)
904)]
905#[reflect(Debug, PartialEq, Default)]
906pub struct InternalWindowState {
907    /// If this is true then next frame we will ask to minimize the window.
908    minimize_request: Option<bool>,
909    /// If this is true then next frame we will ask to maximize/un-maximize the window depending on `maximized`.
910    maximize_request: Option<bool>,
911    /// Unscaled cursor position.
912    physical_cursor_position: Option<DVec2>,
913}
914
915impl InternalWindowState {
916    /// Consumes the current maximize request, if it exists. This should only be called by window backends.
917    pub fn take_maximize_request(&mut self) -> Option<bool> {
918        self.maximize_request.take()
919    }
920
921    /// Consumes the current minimize request, if it exists. This should only be called by window backends.
922    pub fn take_minimize_request(&mut self) -> Option<bool> {
923        self.minimize_request.take()
924    }
925}
926
927/// References a screen monitor.
928///
929/// Used when centering a [`Window`] on a monitor.
930#[derive(Debug, Clone, Copy, PartialEq, Eq, Reflect)]
931#[cfg_attr(
932    feature = "serialize",
933    derive(serde::Serialize, serde::Deserialize),
934    reflect(Serialize, Deserialize)
935)]
936#[reflect(Debug, PartialEq)]
937pub enum MonitorSelection {
938    /// Uses the current monitor of the window.
939    ///
940    /// If [`WindowPosition::Centered(MonitorSelection::Current)`](WindowPosition::Centered) is used when creating a window,
941    /// the window doesn't have a monitor yet, this will fall back to [`WindowPosition::Automatic`].
942    Current,
943    /// Uses the primary monitor of the system.
944    Primary,
945    /// Uses the monitor with the specified index.
946    Index(usize),
947}
948
949/// Presentation mode for a [`Window`].
950///
951/// The presentation mode specifies when a frame is presented to the window. The [`Fifo`]
952/// option corresponds to a traditional `VSync`, where the framerate is capped by the
953/// display refresh rate. Both [`Immediate`] and [`Mailbox`] are low-latency and are not
954/// capped by the refresh rate, but may not be available on all platforms. Tearing
955/// may be observed with [`Immediate`] mode, but will not be observed with [`Mailbox`] or
956/// [`Fifo`].
957///
958/// [`AutoVsync`] or [`AutoNoVsync`] will gracefully fallback to [`Fifo`] when unavailable.
959///
960/// [`Immediate`] or [`Mailbox`] will panic if not supported by the platform.
961///
962/// [`Fifo`]: PresentMode::Fifo
963/// [`FifoRelaxed`]: PresentMode::FifoRelaxed
964/// [`Immediate`]: PresentMode::Immediate
965/// [`Mailbox`]: PresentMode::Mailbox
966/// [`AutoVsync`]: PresentMode::AutoVsync
967/// [`AutoNoVsync`]: PresentMode::AutoNoVsync
968///
969#[repr(C)]
970#[derive(Default, Copy, Clone, Debug, PartialEq, Eq, Hash, Reflect)]
971#[cfg_attr(
972    feature = "serialize",
973    derive(serde::Serialize, serde::Deserialize),
974    reflect(Serialize, Deserialize)
975)]
976#[reflect(Debug, PartialEq, Hash)]
977#[doc(alias = "vsync")]
978pub enum PresentMode {
979    /// Chooses [`FifoRelaxed`](Self::FifoRelaxed) -> [`Fifo`](Self::Fifo) based on availability.
980    ///
981    /// Because of the fallback behavior, it is supported everywhere.
982    AutoVsync = 0, // NOTE: The explicit ordinal values mirror wgpu.
983    /// Chooses [`Immediate`](Self::Immediate) -> [`Mailbox`](Self::Mailbox) -> [`Fifo`](Self::Fifo) (on web) based on availability.
984    ///
985    /// Because of the fallback behavior, it is supported everywhere.
986    AutoNoVsync = 1,
987    /// Presentation frames are kept in a First-In-First-Out queue approximately 3 frames
988    /// long. Every vertical blanking period, the presentation engine will pop a frame
989    /// off the queue to display. If there is no frame to display, it will present the same
990    /// frame again until the next vblank.
991    ///
992    /// When a present command is executed on the gpu, the presented image is added on the queue.
993    ///
994    /// No tearing will be observed.
995    ///
996    /// Calls to `get_current_texture` will block until there is a spot in the queue.
997    ///
998    /// Supported on all platforms.
999    ///
1000    /// If you don't know what mode to choose, choose this mode. This is traditionally called "Vsync On".
1001    #[default]
1002    Fifo = 2,
1003    /// Presentation frames are kept in a First-In-First-Out queue approximately 3 frames
1004    /// long. Every vertical blanking period, the presentation engine will pop a frame
1005    /// off the queue to display. If there is no frame to display, it will present the
1006    /// same frame until there is a frame in the queue. The moment there is a frame in the
1007    /// queue, it will immediately pop the frame off the queue.
1008    ///
1009    /// When a present command is executed on the gpu, the presented image is added on the queue.
1010    ///
1011    /// Tearing will be observed if frames last more than one vblank as the front buffer.
1012    ///
1013    /// Calls to `get_current_texture` will block until there is a spot in the queue.
1014    ///
1015    /// Supported on AMD on Vulkan.
1016    ///
1017    /// This is traditionally called "Adaptive Vsync"
1018    FifoRelaxed = 3,
1019    /// Presentation frames are not queued at all. The moment a present command
1020    /// is executed on the GPU, the presented image is swapped onto the front buffer
1021    /// immediately.
1022    ///
1023    /// Tearing can be observed.
1024    ///
1025    /// Supported on most platforms except older DX12 and Wayland.
1026    ///
1027    /// This is traditionally called "Vsync Off".
1028    Immediate = 4,
1029    /// Presentation frames are kept in a single-frame queue. Every vertical blanking period,
1030    /// the presentation engine will pop a frame from the queue. If there is no frame to display,
1031    /// it will present the same frame again until the next vblank.
1032    ///
1033    /// When a present command is executed on the gpu, the frame will be put into the queue.
1034    /// If there was already a frame in the queue, the new frame will _replace_ the old frame
1035    /// on the queue.
1036    ///
1037    /// No tearing will be observed.
1038    ///
1039    /// Supported on DX11/12 on Windows 10, NVidia on Vulkan and Wayland on Vulkan.
1040    ///
1041    /// This is traditionally called "Fast Vsync"
1042    Mailbox = 5,
1043}
1044
1045/// Specifies how the alpha channel of the textures should be handled during compositing, for a [`Window`].
1046#[repr(C)]
1047#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect)]
1048#[cfg_attr(
1049    feature = "serialize",
1050    derive(serde::Serialize, serde::Deserialize),
1051    reflect(Serialize, Deserialize)
1052)]
1053#[reflect(Debug, PartialEq, Hash)]
1054pub enum CompositeAlphaMode {
1055    /// Chooses either [`Opaque`](CompositeAlphaMode::Opaque) or [`Inherit`](CompositeAlphaMode::Inherit)
1056    /// automatically, depending on the `alpha_mode` that the current surface can support.
1057    #[default]
1058    Auto = 0,
1059    /// The alpha channel, if it exists, of the textures is ignored in the
1060    /// compositing process. Instead, the textures is treated as if it has a
1061    /// constant alpha of 1.0.
1062    Opaque = 1,
1063    /// The alpha channel, if it exists, of the textures is respected in the
1064    /// compositing process. The non-alpha channels of the textures are
1065    /// expected to already be multiplied by the alpha channel by the
1066    /// application.
1067    PreMultiplied = 2,
1068    /// The alpha channel, if it exists, of the textures is respected in the
1069    /// compositing process. The non-alpha channels of the textures are not
1070    /// expected to already be multiplied by the alpha channel by the
1071    /// application; instead, the compositor will multiply the non-alpha
1072    /// channels of the texture by the alpha channel during compositing.
1073    PostMultiplied = 3,
1074    /// The alpha channel, if it exists, of the textures is unknown for processing
1075    /// during compositing. Instead, the application is responsible for setting
1076    /// the composite alpha blending mode using native WSI command. If not set,
1077    /// then a platform-specific default will be used.
1078    Inherit = 4,
1079}
1080
1081/// Defines the way a [`Window`] is displayed.
1082#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Reflect)]
1083#[cfg_attr(
1084    feature = "serialize",
1085    derive(serde::Serialize, serde::Deserialize),
1086    reflect(Serialize, Deserialize)
1087)]
1088#[reflect(Debug, PartialEq)]
1089pub enum WindowMode {
1090    /// The window should take a portion of the screen, using the window resolution size.
1091    #[default]
1092    Windowed,
1093    /// The window should appear fullscreen by being borderless and using the full
1094    /// size of the screen.
1095    ///
1096    /// When setting this, the window's physical size will be modified to match the size
1097    /// of the current monitor resolution, and the logical size will follow based
1098    /// on the scale factor, see [`WindowResolution`].
1099    ///
1100    /// Note: As this mode respects the scale factor provided by the operating system,
1101    /// the window's logical size may be different from its physical size.
1102    /// If you want to avoid that behavior, you can use the [`WindowResolution::set_scale_factor_override`] function
1103    /// or the [`WindowResolution::with_scale_factor_override`] builder method to set the scale factor to 1.0.
1104    BorderlessFullscreen,
1105    /// The window should be in "true"/"legacy" Fullscreen mode.
1106    ///
1107    /// When setting this, the operating system will be requested to use the
1108    /// **closest** resolution available for the current monitor to match as
1109    /// closely as possible the window's physical size.
1110    /// After that, the window's physical size will be modified to match
1111    /// that monitor resolution, and the logical size will follow based on the
1112    /// scale factor, see [`WindowResolution`].
1113    SizedFullscreen,
1114    /// The window should be in "true"/"legacy" Fullscreen mode.
1115    ///
1116    /// When setting this, the operating system will be requested to use the
1117    /// **biggest** resolution available for the current monitor.
1118    /// After that, the window's physical size will be modified to match
1119    /// that monitor resolution, and the logical size will follow based on the
1120    /// scale factor, see [`WindowResolution`].
1121    ///
1122    /// Note: As this mode respects the scale factor provided by the operating system,
1123    /// the window's logical size may be different from its physical size.
1124    /// If you want to avoid that behavior, you can use the [`WindowResolution::set_scale_factor_override`] function
1125    /// or the [`WindowResolution::with_scale_factor_override`] builder method to set the scale factor to 1.0.
1126    Fullscreen,
1127}
1128
1129/// Specifies where a [`Window`] should appear relative to other overlapping windows (on top or under) .
1130///
1131/// Levels are groups of windows with respect to their z-position.
1132///
1133/// The relative ordering between windows in different window levels is fixed.
1134/// The z-order of windows within the same window level may change dynamically on user interaction.
1135///
1136/// ## Platform-specific
1137///
1138/// - **iOS / Android / Web / Wayland:** Unsupported.
1139#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Reflect)]
1140#[cfg_attr(
1141    feature = "serialize",
1142    derive(serde::Serialize, serde::Deserialize),
1143    reflect(Serialize, Deserialize)
1144)]
1145#[reflect(Debug, PartialEq)]
1146pub enum WindowLevel {
1147    /// The window will always be below [`WindowLevel::Normal`] and [`WindowLevel::AlwaysOnTop`] windows.
1148    ///
1149    /// This is useful for a widget-based app.
1150    AlwaysOnBottom,
1151    /// The default group.
1152    #[default]
1153    Normal,
1154    /// The window will always be on top of [`WindowLevel::Normal`] and [`WindowLevel::AlwaysOnBottom`] windows.
1155    AlwaysOnTop,
1156}
1157
1158/// The [`Window`] theme variant to use.
1159#[derive(Debug, Clone, Copy, PartialEq, Eq, Reflect)]
1160#[cfg_attr(
1161    feature = "serialize",
1162    derive(serde::Serialize, serde::Deserialize),
1163    reflect(Serialize, Deserialize)
1164)]
1165#[reflect(Debug, PartialEq)]
1166pub enum WindowTheme {
1167    /// Use the light variant.
1168    Light,
1169
1170    /// Use the dark variant.
1171    Dark,
1172}
1173
1174/// Specifies which [`Window`] control buttons should be enabled.
1175///
1176/// ## Platform-specific
1177///
1178/// **`iOS`**, **`Android`**, and the **`Web`** do not have window control buttons.
1179///
1180/// On some **`Linux`** environments these values have no effect.
1181#[derive(Debug, Copy, Clone, PartialEq, Reflect)]
1182#[cfg_attr(
1183    feature = "serialize",
1184    derive(serde::Serialize, serde::Deserialize),
1185    reflect(Serialize, Deserialize)
1186)]
1187#[reflect(Debug, PartialEq, Default)]
1188pub struct EnabledButtons {
1189    /// Enables the functionality of the minimize button.
1190    pub minimize: bool,
1191    /// Enables the functionality of the maximize button.
1192    ///
1193    /// macOS note: When [`Window`] `resizable` member is set to `false`
1194    /// the maximize button will be disabled regardless of this value.
1195    /// Additionally, when `resizable` is set to `true` the window will
1196    /// be maximized when its bar is double-clicked regardless of whether
1197    /// the maximize button is enabled or not.
1198    pub maximize: bool,
1199    /// Enables the functionality of the close button.
1200    pub close: bool,
1201}
1202
1203impl Default for EnabledButtons {
1204    fn default() -> Self {
1205        Self {
1206            minimize: true,
1207            maximize: true,
1208            close: true,
1209        }
1210    }
1211}
1212
1213/// Marker component for a [`Window`] that has been requested to close and
1214/// is in the process of closing (on the next frame).
1215#[derive(Component)]
1216pub struct ClosingWindow;
1217
1218#[cfg(test)]
1219mod tests {
1220    use super::*;
1221
1222    // Checks that `Window::physical_cursor_position` returns the cursor position if it is within
1223    // the bounds of the window.
1224    #[test]
1225    fn cursor_position_within_window_bounds() {
1226        let mut window = Window {
1227            resolution: WindowResolution::new(800., 600.),
1228            ..Default::default()
1229        };
1230
1231        window.set_physical_cursor_position(Some(DVec2::new(0., 300.)));
1232        assert_eq!(window.physical_cursor_position(), Some(Vec2::new(0., 300.)));
1233
1234        window.set_physical_cursor_position(Some(DVec2::new(400., 0.)));
1235        assert_eq!(window.physical_cursor_position(), Some(Vec2::new(400., 0.)));
1236
1237        window.set_physical_cursor_position(Some(DVec2::new(799.999, 300.)));
1238        assert_eq!(
1239            window.physical_cursor_position(),
1240            Some(Vec2::new(799.999, 300.)),
1241        );
1242
1243        window.set_physical_cursor_position(Some(DVec2::new(400., 599.999)));
1244        assert_eq!(
1245            window.physical_cursor_position(),
1246            Some(Vec2::new(400., 599.999))
1247        );
1248    }
1249
1250    // Checks that `Window::physical_cursor_position` returns `None` if the cursor position is not
1251    // within the bounds of the window.
1252    #[test]
1253    fn cursor_position_not_within_window_bounds() {
1254        let mut window = Window {
1255            resolution: WindowResolution::new(800., 600.),
1256            ..Default::default()
1257        };
1258
1259        window.set_physical_cursor_position(Some(DVec2::new(-0.001, 300.)));
1260        assert!(window.physical_cursor_position().is_none());
1261
1262        window.set_physical_cursor_position(Some(DVec2::new(400., -0.001)));
1263        assert!(window.physical_cursor_position().is_none());
1264
1265        window.set_physical_cursor_position(Some(DVec2::new(800., 300.)));
1266        assert!(window.physical_cursor_position().is_none());
1267
1268        window.set_physical_cursor_position(Some(DVec2::new(400., 600.)));
1269        assert!(window.physical_cursor_position().is_none());
1270    }
1271}