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