bevy_window/
window.rs

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