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/latest/file-naming.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 /// Hides the dock and menu bar when a borderless fullscreen window is active.
436 ///
437 /// Corresponds to [`WindowAttributesExtMacOS::with_borderless_game`].
438 ///
439 /// Defaults to `true` as this is the expected behavior for games.
440 ///
441 /// # Platform-specific
442 ///
443 /// - Only used on macOS.
444 ///
445 /// [`WindowAttributesExtMacOS::with_borderless_game`]: https://docs.rs/winit/latest/x86_64-apple-darwin/winit/platform/macos/trait.WindowAttributesExtMacOS.html#tymethod.with_borderless_game
446 pub borderless_game: bool,
447 /// Sets whether the Window prefers the home indicator hidden.
448 ///
449 /// Corresponds to [`WindowAttributesExtIOS::with_prefers_home_indicator_hidden`].
450 ///
451 /// # Platform-specific
452 ///
453 /// - Only used on iOS.
454 ///
455 /// [`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
456 pub prefers_home_indicator_hidden: bool,
457 /// Sets whether the Window prefers the status bar hidden.
458 ///
459 /// Corresponds to [`WindowAttributesExtIOS::with_prefers_status_bar_hidden`].
460 ///
461 /// # Platform-specific
462 ///
463 /// - Only used on iOS.
464 ///
465 /// [`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
466 pub prefers_status_bar_hidden: bool,
467 /// Sets screen edges for which you want your gestures to take precedence
468 /// over the system gestures.
469 ///
470 /// Corresponds to [`WindowAttributesExtIOS::with_preferred_screen_edges_deferring_system_gestures`].
471 ///
472 /// # Platform-specific
473 ///
474 /// - Only used on iOS.
475 ///
476 /// [`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
477 pub preferred_screen_edges_deferring_system_gestures: ScreenEdge,
478}
479
480impl Default for Window {
481 fn default() -> Self {
482 Self {
483 title: DEFAULT_WINDOW_TITLE.to_owned(),
484 name: None,
485 present_mode: Default::default(),
486 mode: Default::default(),
487 position: Default::default(),
488 resolution: Default::default(),
489 internal: Default::default(),
490 composite_alpha_mode: Default::default(),
491 resize_constraints: Default::default(),
492 ime_enabled: Default::default(),
493 ime_position: Default::default(),
494 resizable: true,
495 enabled_buttons: Default::default(),
496 decorations: true,
497 transparent: false,
498 focused: true,
499 window_level: Default::default(),
500 fit_canvas_to_parent: false,
501 prevent_default_event_handling: true,
502 canvas: None,
503 window_theme: None,
504 visible: true,
505 skip_taskbar: false,
506 clip_children: true,
507 desired_maximum_frame_latency: None,
508 recognize_pinch_gesture: false,
509 recognize_rotation_gesture: false,
510 recognize_doubletap_gesture: false,
511 recognize_pan_gesture: None,
512 movable_by_window_background: false,
513 fullsize_content_view: false,
514 has_shadow: true,
515 titlebar_shown: true,
516 titlebar_transparent: false,
517 titlebar_show_title: true,
518 titlebar_show_buttons: true,
519 borderless_game: true,
520 prefers_home_indicator_hidden: false,
521 prefers_status_bar_hidden: false,
522 preferred_screen_edges_deferring_system_gestures: Default::default(),
523 }
524 }
525}
526
527impl Window {
528 /// Setting to true will attempt to maximize the window.
529 ///
530 /// Setting to false will attempt to un-maximize the window.
531 pub fn set_maximized(&mut self, maximized: bool) {
532 self.internal.maximize_request = Some(maximized);
533 }
534
535 /// Setting to true will attempt to minimize the window.
536 ///
537 /// Setting to false will attempt to un-minimize the window.
538 pub fn set_minimized(&mut self, minimized: bool) {
539 self.internal.minimize_request = Some(minimized);
540 }
541
542 /// Calling this will attempt to start a drag-move of the window.
543 ///
544 /// There is no guarantee that this will work unless the left mouse button was
545 /// pressed immediately before this function was called.
546 pub fn start_drag_move(&mut self) {
547 self.internal.drag_move_request = true;
548 }
549
550 /// Calling this will attempt to start a drag-resize of the window.
551 ///
552 /// There is no guarantee that this will work unless the left mouse button was
553 /// pressed immediately before this function was called.
554 pub fn start_drag_resize(&mut self, direction: CompassOctant) {
555 self.internal.drag_resize_request = Some(direction);
556 }
557
558 /// The window's client area width in logical pixels.
559 ///
560 /// See [`WindowResolution`] for an explanation about logical/physical sizes.
561 #[inline]
562 pub fn width(&self) -> f32 {
563 self.resolution.width()
564 }
565
566 /// The window's client area height in logical pixels.
567 ///
568 /// See [`WindowResolution`] for an explanation about logical/physical sizes.
569 #[inline]
570 pub fn height(&self) -> f32 {
571 self.resolution.height()
572 }
573
574 /// The window's client size in logical pixels
575 ///
576 /// See [`WindowResolution`] for an explanation about logical/physical sizes.
577 #[inline]
578 pub fn size(&self) -> Vec2 {
579 self.resolution.size()
580 }
581
582 /// The window's client area width in physical pixels.
583 ///
584 /// See [`WindowResolution`] for an explanation about logical/physical sizes.
585 #[inline]
586 pub fn physical_width(&self) -> u32 {
587 self.resolution.physical_width()
588 }
589
590 /// The window's client area height in physical pixels.
591 ///
592 /// See [`WindowResolution`] for an explanation about logical/physical sizes.
593 #[inline]
594 pub fn physical_height(&self) -> u32 {
595 self.resolution.physical_height()
596 }
597
598 /// The window's client size in physical pixels
599 ///
600 /// See [`WindowResolution`] for an explanation about logical/physical sizes.
601 #[inline]
602 pub fn physical_size(&self) -> UVec2 {
603 self.resolution.physical_size()
604 }
605
606 /// The window's scale factor.
607 ///
608 /// Ratio of physical size to logical size, see [`WindowResolution`].
609 #[inline]
610 pub fn scale_factor(&self) -> f32 {
611 self.resolution.scale_factor()
612 }
613
614 /// The cursor position in this window in logical pixels.
615 ///
616 /// Returns `None` if the cursor is outside the window area.
617 ///
618 /// See [`WindowResolution`] for an explanation about logical/physical sizes.
619 #[inline]
620 pub fn cursor_position(&self) -> Option<Vec2> {
621 self.physical_cursor_position()
622 .map(|position| (position.as_dvec2() / self.scale_factor() as f64).as_vec2())
623 }
624
625 /// The cursor position in this window in physical pixels.
626 ///
627 /// Returns `None` if the cursor is outside the window area.
628 ///
629 /// See [`WindowResolution`] for an explanation about logical/physical sizes.
630 #[inline]
631 pub fn physical_cursor_position(&self) -> Option<Vec2> {
632 match self.internal.physical_cursor_position {
633 Some(position) => {
634 if position.x >= 0.
635 && position.y >= 0.
636 && position.x < self.physical_width() as f64
637 && position.y < self.physical_height() as f64
638 {
639 Some(position.as_vec2())
640 } else {
641 None
642 }
643 }
644 None => None,
645 }
646 }
647
648 /// Set the cursor position in this window in logical pixels.
649 ///
650 /// See [`WindowResolution`] for an explanation about logical/physical sizes.
651 pub fn set_cursor_position(&mut self, position: Option<Vec2>) {
652 self.internal.physical_cursor_position =
653 position.map(|p| p.as_dvec2() * self.scale_factor() as f64);
654 }
655
656 /// Set the cursor position in this window in physical pixels.
657 ///
658 /// See [`WindowResolution`] for an explanation about logical/physical sizes.
659 pub fn set_physical_cursor_position(&mut self, position: Option<DVec2>) {
660 self.internal.physical_cursor_position = position;
661 }
662}
663
664/// The size limits on a [`Window`].
665///
666/// These values are measured in logical pixels (see [`WindowResolution`]), so the user's
667/// scale factor does affect the size limits on the window.
668///
669/// Please note that if the window is resizable, then when the window is
670/// maximized it may have a size outside of these limits. The functionality
671/// required to disable maximizing is not yet exposed by winit.
672#[derive(Debug, Clone, Copy, PartialEq)]
673#[cfg_attr(
674 feature = "bevy_reflect",
675 derive(Reflect),
676 reflect(Debug, PartialEq, Default, Clone)
677)]
678#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
679#[cfg_attr(
680 all(feature = "serialize", feature = "bevy_reflect"),
681 reflect(Serialize, Deserialize)
682)]
683pub struct WindowResizeConstraints {
684 /// The minimum width the window can have.
685 pub min_width: f32,
686 /// The minimum height the window can have.
687 pub min_height: f32,
688 /// The maximum width the window can have.
689 pub max_width: f32,
690 /// The maximum height the window can have.
691 pub max_height: f32,
692}
693
694impl Default for WindowResizeConstraints {
695 fn default() -> Self {
696 Self {
697 min_width: 180.,
698 min_height: 120.,
699 max_width: f32::INFINITY,
700 max_height: f32::INFINITY,
701 }
702 }
703}
704
705impl WindowResizeConstraints {
706 /// Checks if the constraints are valid.
707 ///
708 /// Will output warnings if it isn't.
709 #[must_use]
710 pub fn check_constraints(&self) -> Self {
711 let &WindowResizeConstraints {
712 mut min_width,
713 mut min_height,
714 mut max_width,
715 mut max_height,
716 } = self;
717 min_width = min_width.max(1.);
718 min_height = min_height.max(1.);
719 if max_width < min_width {
720 warn!(
721 "The given maximum width {max_width} is smaller than the minimum width {min_width}"
722 );
723 max_width = min_width;
724 }
725 if max_height < min_height {
726 warn!(
727 "The given maximum height {max_height} is smaller than the minimum height {min_height}",
728 );
729 max_height = min_height;
730 }
731 WindowResizeConstraints {
732 min_width,
733 min_height,
734 max_width,
735 max_height,
736 }
737 }
738}
739
740/// Cursor data for a [`Window`].
741#[derive(Component, Debug, Clone)]
742#[cfg_attr(
743 feature = "bevy_reflect",
744 derive(Reflect),
745 reflect(Component, Debug, Default, Clone)
746)]
747#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
748#[cfg_attr(
749 all(feature = "serialize", feature = "bevy_reflect"),
750 reflect(Serialize, Deserialize)
751)]
752pub struct CursorOptions {
753 /// Whether the cursor is visible or not.
754 ///
755 /// ## Platform-specific
756 ///
757 /// - **`Windows`**, **`X11`**, and **`Wayland`**: The cursor is hidden only when inside the window.
758 /// To stop the cursor from leaving the window, change [`CursorOptions::grab_mode`] to [`CursorGrabMode::Locked`] or [`CursorGrabMode::Confined`]
759 /// - **`macOS`**: The cursor is hidden only when the window is focused.
760 /// - **`iOS`** and **`Android`** do not have cursors
761 pub visible: bool,
762
763 /// Whether or not the cursor is locked by or confined within the window.
764 ///
765 /// ## Platform-specific
766 ///
767 /// - **`macOS`** doesn't support [`CursorGrabMode::Confined`] and falls back to [`CursorGrabMode::None`].
768 /// - **`X11`** doesn't support [`CursorGrabMode::Locked`] and falls back to [`CursorGrabMode::Confined`].
769 /// - **`iOS/Android`** don't have cursors.
770 pub grab_mode: CursorGrabMode,
771
772 /// Set whether or not mouse events within *this* window are captured or fall through to the Window below.
773 ///
774 /// ## Platform-specific
775 ///
776 /// - iOS / Android / Web / X11: Unsupported.
777 pub hit_test: bool,
778}
779
780impl Default for CursorOptions {
781 fn default() -> Self {
782 CursorOptions {
783 visible: true,
784 grab_mode: CursorGrabMode::None,
785 hit_test: true,
786 }
787 }
788}
789
790/// Defines where a [`Window`] should be placed on the screen.
791#[derive(Default, Debug, Clone, Copy, PartialEq)]
792#[cfg_attr(
793 feature = "bevy_reflect",
794 derive(Reflect),
795 reflect(Debug, PartialEq, Clone)
796)]
797#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
798#[cfg_attr(
799 all(feature = "serialize", feature = "bevy_reflect"),
800 reflect(Serialize, Deserialize)
801)]
802pub enum WindowPosition {
803 /// Position will be set by the window manager.
804 /// Bevy will delegate this decision to the window manager and no guarantees can be made about where the window will be placed.
805 ///
806 /// Used at creation but will be changed to [`At`](WindowPosition::At).
807 #[default]
808 Automatic,
809 /// Window will be centered on the selected monitor.
810 ///
811 /// Note that this does not account for window decorations.
812 ///
813 /// Used at creation or for update but will be changed to [`At`](WindowPosition::At)
814 Centered(MonitorSelection),
815 /// The window's top-left corner should be placed at the specified position (in physical pixels).
816 ///
817 /// (0,0) represents top-left corner of screen space.
818 At(IVec2),
819}
820
821impl WindowPosition {
822 /// Creates a new [`WindowPosition`] at a position.
823 pub fn new(position: IVec2) -> Self {
824 Self::At(position)
825 }
826
827 /// Set the position to a specific point.
828 pub fn set(&mut self, position: IVec2) {
829 *self = WindowPosition::At(position);
830 }
831
832 /// Set the window to a specific monitor.
833 pub fn center(&mut self, monitor: MonitorSelection) {
834 *self = WindowPosition::Centered(monitor);
835 }
836}
837
838/// Controls the size of a [`Window`]
839///
840/// ## Physical, logical and requested sizes
841///
842/// There are three sizes associated with a window:
843/// - the physical size,
844/// which represents the actual height and width in physical pixels
845/// the window occupies on the monitor,
846/// - the logical size,
847/// which represents the size that should be used to scale elements
848/// inside the window, measured in logical pixels,
849/// - the requested size,
850/// measured in logical pixels, which is the value submitted
851/// to the API when creating the window, or requesting that it be resized.
852///
853/// ## Scale factor
854///
855/// The reason logical size and physical size are separated and can be different
856/// is to account for the cases where:
857/// - several monitors have different pixel densities,
858/// - the user has set up a pixel density preference in its operating system,
859/// - the Bevy `App` has specified a specific scale factor between both.
860///
861/// The factor between physical size and logical size can be retrieved with
862/// [`WindowResolution::scale_factor`].
863///
864/// For the first two cases, a scale factor is set automatically by the operating
865/// system through the window backend. You can get it with
866/// [`WindowResolution::base_scale_factor`].
867///
868/// For the third case, you can override this automatic scale factor with
869/// [`WindowResolution::set_scale_factor_override`].
870///
871/// ## Requested and obtained sizes
872///
873/// The logical size should be equal to the requested size after creating/resizing,
874/// when possible.
875/// The reason the requested size and logical size might be different
876/// is because the corresponding physical size might exceed limits (either the
877/// size limits of the monitor, or limits defined in [`WindowResizeConstraints`]).
878///
879/// Note: The requested size is not kept in memory, for example requesting a size
880/// too big for the screen, making the logical size different from the requested size,
881/// and then setting a scale factor that makes the previous requested size within
882/// the limits of the screen will not get back that previous requested size.
883
884#[derive(Debug, Clone, PartialEq)]
885#[cfg_attr(
886 feature = "bevy_reflect",
887 derive(Reflect),
888 reflect(Debug, PartialEq, Default, Clone)
889)]
890#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
891#[cfg_attr(
892 all(feature = "serialize", feature = "bevy_reflect"),
893 reflect(Serialize, Deserialize)
894)]
895pub struct WindowResolution {
896 /// Width of the window in physical pixels.
897 physical_width: u32,
898 /// Height of the window in physical pixels.
899 physical_height: u32,
900 /// Code-provided ratio of physical size to logical size.
901 ///
902 /// Should be used instead of `scale_factor` when set.
903 scale_factor_override: Option<f32>,
904 /// OS-provided ratio of physical size to logical size.
905 ///
906 /// Set automatically depending on the pixel density of the screen.
907 scale_factor: f32,
908}
909
910impl Default for WindowResolution {
911 fn default() -> Self {
912 WindowResolution {
913 physical_width: 1280,
914 physical_height: 720,
915 scale_factor_override: None,
916 scale_factor: 1.0,
917 }
918 }
919}
920
921impl WindowResolution {
922 /// Creates a new [`WindowResolution`].
923 pub fn new(physical_width: u32, physical_height: u32) -> Self {
924 Self {
925 physical_width,
926 physical_height,
927 ..Default::default()
928 }
929 }
930
931 /// Builder method for adding a scale factor override to the resolution.
932 pub fn with_scale_factor_override(mut self, scale_factor_override: f32) -> Self {
933 self.set_scale_factor_override(Some(scale_factor_override));
934 self
935 }
936
937 /// The window's client area width in logical pixels.
938 #[inline]
939 pub fn width(&self) -> f32 {
940 self.physical_width() as f32 / self.scale_factor()
941 }
942
943 /// The window's client area height in logical pixels.
944 #[inline]
945 pub fn height(&self) -> f32 {
946 self.physical_height() as f32 / self.scale_factor()
947 }
948
949 /// The window's client size in logical pixels
950 #[inline]
951 pub fn size(&self) -> Vec2 {
952 Vec2::new(self.width(), self.height())
953 }
954
955 /// The window's client area width in physical pixels.
956 #[inline]
957 pub fn physical_width(&self) -> u32 {
958 self.physical_width
959 }
960
961 /// The window's client area height in physical pixels.
962 #[inline]
963 pub fn physical_height(&self) -> u32 {
964 self.physical_height
965 }
966
967 /// The window's client size in physical pixels
968 #[inline]
969 pub fn physical_size(&self) -> UVec2 {
970 UVec2::new(self.physical_width, self.physical_height)
971 }
972
973 /// The ratio of physical pixels to logical pixels.
974 ///
975 /// `physical_pixels = logical_pixels * scale_factor`
976 pub fn scale_factor(&self) -> f32 {
977 self.scale_factor_override
978 .unwrap_or_else(|| self.base_scale_factor())
979 }
980
981 /// The window scale factor as reported by the window backend.
982 ///
983 /// This value is unaffected by [`WindowResolution::scale_factor_override`].
984 #[inline]
985 pub fn base_scale_factor(&self) -> f32 {
986 self.scale_factor
987 }
988
989 /// The scale factor set with [`WindowResolution::set_scale_factor_override`].
990 ///
991 /// This value may be different from the scale factor reported by the window backend.
992 #[inline]
993 pub fn scale_factor_override(&self) -> Option<f32> {
994 self.scale_factor_override
995 }
996
997 /// Set the window's logical resolution.
998 #[inline]
999 pub fn set(&mut self, width: f32, height: f32) {
1000 self.set_physical_resolution(
1001 (width * self.scale_factor()) as u32,
1002 (height * self.scale_factor()) as u32,
1003 );
1004 }
1005
1006 /// Set the window's physical resolution.
1007 ///
1008 /// This will ignore the scale factor setting, so most of the time you should
1009 /// prefer to use [`WindowResolution::set`].
1010 #[inline]
1011 pub fn set_physical_resolution(&mut self, width: u32, height: u32) {
1012 self.physical_width = width;
1013 self.physical_height = height;
1014 }
1015
1016 /// Set the window's scale factor, this may get overridden by the backend.
1017 #[inline]
1018 pub fn set_scale_factor(&mut self, scale_factor: f32) {
1019 self.scale_factor = scale_factor;
1020 }
1021
1022 /// Set the window's scale factor, and apply it to the currently known physical size.
1023 /// This may get overridden by the backend. This is mostly useful on window creation,
1024 /// so that the window is created with the expected size instead of waiting for a resize
1025 /// event after its creation.
1026 #[inline]
1027 #[doc(hidden)]
1028 pub fn set_scale_factor_and_apply_to_physical_size(&mut self, scale_factor: f32) {
1029 self.scale_factor = scale_factor;
1030 self.physical_width = (self.physical_width as f32 * scale_factor) as u32;
1031 self.physical_height = (self.physical_height as f32 * scale_factor) as u32;
1032 }
1033
1034 /// Set the window's scale factor, this will be used over what the backend decides.
1035 ///
1036 /// This can change the logical and physical sizes if the resulting physical
1037 /// size is not within the limits.
1038 #[inline]
1039 pub fn set_scale_factor_override(&mut self, scale_factor_override: Option<f32>) {
1040 self.scale_factor_override = scale_factor_override;
1041 }
1042}
1043
1044impl From<(u32, u32)> for WindowResolution {
1045 fn from((width, height): (u32, u32)) -> Self {
1046 WindowResolution::new(width, height)
1047 }
1048}
1049
1050impl From<[u32; 2]> for WindowResolution {
1051 fn from([width, height]: [u32; 2]) -> WindowResolution {
1052 WindowResolution::new(width, height)
1053 }
1054}
1055
1056impl From<UVec2> for WindowResolution {
1057 fn from(res: UVec2) -> WindowResolution {
1058 WindowResolution::new(res.x, res.y)
1059 }
1060}
1061
1062/// Defines if and how the cursor is grabbed by a [`Window`].
1063///
1064/// ## Platform-specific
1065///
1066/// - **`macOS`** doesn't support [`CursorGrabMode::Confined`] and falls back to [`CursorGrabMode::None`].
1067/// - **`X11`** doesn't support [`CursorGrabMode::Locked`] and falls back to [`CursorGrabMode::Confined`].
1068/// - **`iOS/Android`** don't have cursors.
1069#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
1070#[cfg_attr(
1071 feature = "bevy_reflect",
1072 derive(Reflect),
1073 reflect(Debug, PartialEq, Default, Clone)
1074)]
1075#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1076#[cfg_attr(
1077 all(feature = "serialize", feature = "bevy_reflect"),
1078 reflect(Serialize, Deserialize)
1079)]
1080pub enum CursorGrabMode {
1081 /// The cursor can freely leave the window.
1082 #[default]
1083 None,
1084 /// The cursor is confined to the window area.
1085 Confined,
1086 /// The cursor is locked inside the window area to a certain position.
1087 Locked,
1088}
1089
1090/// Stores internal [`Window`] state that isn't directly accessible.
1091#[derive(Default, Debug, Copy, Clone, PartialEq)]
1092#[cfg_attr(
1093 feature = "bevy_reflect",
1094 derive(Reflect),
1095 reflect(Debug, PartialEq, Default, Clone)
1096)]
1097#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1098#[cfg_attr(
1099 all(feature = "serialize", feature = "bevy_reflect"),
1100 reflect(Serialize, Deserialize)
1101)]
1102pub struct InternalWindowState {
1103 /// If this is true then next frame we will ask to minimize the window.
1104 minimize_request: Option<bool>,
1105 /// If this is true then next frame we will ask to maximize/un-maximize the window depending on `maximized`.
1106 maximize_request: Option<bool>,
1107 /// If this is true then next frame we will ask to drag-move the window.
1108 drag_move_request: bool,
1109 /// If this is `Some` then the next frame we will ask to drag-resize the window.
1110 drag_resize_request: Option<CompassOctant>,
1111 /// Unscaled cursor position.
1112 physical_cursor_position: Option<DVec2>,
1113}
1114
1115impl InternalWindowState {
1116 /// Consumes the current maximize request, if it exists. This should only be called by window backends.
1117 pub fn take_maximize_request(&mut self) -> Option<bool> {
1118 self.maximize_request.take()
1119 }
1120
1121 /// Consumes the current minimize request, if it exists. This should only be called by window backends.
1122 pub fn take_minimize_request(&mut self) -> Option<bool> {
1123 self.minimize_request.take()
1124 }
1125
1126 /// Consumes the current move request, if it exists. This should only be called by window backends.
1127 pub fn take_move_request(&mut self) -> bool {
1128 core::mem::take(&mut self.drag_move_request)
1129 }
1130
1131 /// Consumes the current resize request, if it exists. This should only be called by window backends.
1132 pub fn take_resize_request(&mut self) -> Option<CompassOctant> {
1133 self.drag_resize_request.take()
1134 }
1135}
1136
1137/// References a screen monitor.
1138///
1139/// Used when centering a [`Window`] on a monitor.
1140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1141#[cfg_attr(
1142 feature = "bevy_reflect",
1143 derive(Reflect),
1144 reflect(Debug, PartialEq, Clone)
1145)]
1146#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1147#[cfg_attr(
1148 all(feature = "serialize", feature = "bevy_reflect"),
1149 reflect(Serialize, Deserialize)
1150)]
1151pub enum MonitorSelection {
1152 /// Uses the current monitor of the window.
1153 ///
1154 /// If [`WindowPosition::Centered(MonitorSelection::Current)`](WindowPosition::Centered) is used when creating a window,
1155 /// the window doesn't have a monitor yet, this will fall back to [`WindowPosition::Automatic`].
1156 Current,
1157 /// Uses the primary monitor of the system.
1158 Primary,
1159 /// Uses the monitor with the specified index.
1160 Index(usize),
1161 /// Uses a given [`Monitor`](`crate::monitor::Monitor`) entity.
1162 Entity(Entity),
1163}
1164
1165/// References an exclusive fullscreen video mode.
1166///
1167/// Used when setting [`WindowMode::Fullscreen`] on a window.
1168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1169#[cfg_attr(
1170 feature = "bevy_reflect",
1171 derive(Reflect),
1172 reflect(Debug, PartialEq, Clone)
1173)]
1174#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1175#[cfg_attr(
1176 all(feature = "serialize", feature = "bevy_reflect"),
1177 reflect(Serialize, Deserialize)
1178)]
1179pub enum VideoModeSelection {
1180 /// Uses the video mode that the monitor is already in.
1181 Current,
1182 /// Uses a given [`VideoMode`](`crate::monitor::VideoMode`). A list of video modes supported by the monitor
1183 /// is supplied by [`Monitor::video_modes`](`crate::monitor::Monitor::video_modes`).
1184 Specific(VideoMode),
1185}
1186
1187/// Presentation mode for a [`Window`].
1188///
1189/// The presentation mode specifies when a frame is presented to the window. The [`Fifo`]
1190/// option corresponds to a traditional `VSync`, where the framerate is capped by the
1191/// display refresh rate. Both [`Immediate`] and [`Mailbox`] are low-latency and are not
1192/// capped by the refresh rate, but may not be available on all platforms. Tearing
1193/// may be observed with [`Immediate`] mode, but will not be observed with [`Mailbox`] or
1194/// [`Fifo`].
1195///
1196/// [`AutoVsync`] or [`AutoNoVsync`] will gracefully fallback to [`Fifo`] when unavailable.
1197///
1198/// [`Immediate`] or [`Mailbox`] will panic if not supported by the platform.
1199///
1200/// [`Fifo`]: PresentMode::Fifo
1201/// [`FifoRelaxed`]: PresentMode::FifoRelaxed
1202/// [`Immediate`]: PresentMode::Immediate
1203/// [`Mailbox`]: PresentMode::Mailbox
1204/// [`AutoVsync`]: PresentMode::AutoVsync
1205/// [`AutoNoVsync`]: PresentMode::AutoNoVsync
1206#[repr(C)]
1207#[derive(Default, Copy, Clone, Debug, PartialEq, Eq, Hash)]
1208#[cfg_attr(
1209 feature = "bevy_reflect",
1210 derive(Reflect),
1211 reflect(Debug, PartialEq, Hash, Clone)
1212)]
1213#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1214#[cfg_attr(
1215 all(feature = "serialize", feature = "bevy_reflect"),
1216 reflect(Serialize, Deserialize)
1217)]
1218#[doc(alias = "vsync")]
1219pub enum PresentMode {
1220 /// Chooses [`FifoRelaxed`](Self::FifoRelaxed) -> [`Fifo`](Self::Fifo) based on availability.
1221 ///
1222 /// Because of the fallback behavior, it is supported everywhere.
1223 AutoVsync = 0, // NOTE: The explicit ordinal values mirror wgpu.
1224 /// Chooses [`Immediate`](Self::Immediate) -> [`Mailbox`](Self::Mailbox) -> [`Fifo`](Self::Fifo) (on web) based on availability.
1225 ///
1226 /// Because of the fallback behavior, it is supported everywhere.
1227 AutoNoVsync = 1,
1228 /// Presentation frames are kept in a First-In-First-Out queue approximately 3 frames
1229 /// long. Every vertical blanking period, the presentation engine will pop a frame
1230 /// off the queue to display. If there is no frame to display, it will present the same
1231 /// frame again until the next vblank.
1232 ///
1233 /// When a present command is executed on the gpu, the presented image is added on the queue.
1234 ///
1235 /// No tearing will be observed.
1236 ///
1237 /// Calls to `get_current_texture` will block until there is a spot in the queue.
1238 ///
1239 /// Supported on all platforms.
1240 ///
1241 /// If you don't know what mode to choose, choose this mode. This is traditionally called "Vsync On".
1242 #[default]
1243 Fifo = 2,
1244 /// Presentation frames are kept in a First-In-First-Out queue approximately 3 frames
1245 /// long. Every vertical blanking period, the presentation engine will pop a frame
1246 /// off the queue to display. If there is no frame to display, it will present the
1247 /// same frame until there is a frame in the queue. The moment there is a frame in the
1248 /// queue, it will immediately pop the frame off the queue.
1249 ///
1250 /// When a present command is executed on the gpu, the presented image is added on the queue.
1251 ///
1252 /// Tearing will be observed if frames last more than one vblank as the front buffer.
1253 ///
1254 /// Calls to `get_current_texture` will block until there is a spot in the queue.
1255 ///
1256 /// Supported on AMD on Vulkan.
1257 ///
1258 /// This is traditionally called "Adaptive Vsync"
1259 FifoRelaxed = 3,
1260 /// Presentation frames are not queued at all. The moment a present command
1261 /// is executed on the GPU, the presented image is swapped onto the front buffer
1262 /// immediately.
1263 ///
1264 /// Tearing can be observed.
1265 ///
1266 /// Supported on most platforms except older DX12 and Wayland.
1267 ///
1268 /// This is traditionally called "Vsync Off".
1269 Immediate = 4,
1270 /// Presentation frames are kept in a single-frame queue. Every vertical blanking period,
1271 /// the presentation engine will pop a frame from the queue. If there is no frame to display,
1272 /// it will present the same frame again until the next vblank.
1273 ///
1274 /// When a present command is executed on the gpu, the frame will be put into the queue.
1275 /// If there was already a frame in the queue, the new frame will _replace_ the old frame
1276 /// on the queue.
1277 ///
1278 /// No tearing will be observed.
1279 ///
1280 /// Supported on DX11/12 on Windows 10, NVidia on Vulkan and Wayland on Vulkan.
1281 ///
1282 /// This is traditionally called "Fast Vsync"
1283 Mailbox = 5,
1284}
1285
1286/// Specifies how the alpha channel of the textures should be handled during compositing, for a [`Window`].
1287#[repr(C)]
1288#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
1289#[cfg_attr(
1290 feature = "bevy_reflect",
1291 derive(Reflect),
1292 reflect(Debug, PartialEq, Hash, Clone)
1293)]
1294#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1295#[cfg_attr(
1296 all(feature = "serialize", feature = "bevy_reflect"),
1297 reflect(Serialize, Deserialize)
1298)]
1299pub enum CompositeAlphaMode {
1300 /// Chooses either [`Opaque`](CompositeAlphaMode::Opaque) or [`Inherit`](CompositeAlphaMode::Inherit)
1301 /// automatically, depending on the `alpha_mode` that the current surface can support.
1302 #[default]
1303 Auto = 0,
1304 /// The alpha channel, if it exists, of the textures is ignored in the
1305 /// compositing process. Instead, the textures is treated as if it has a
1306 /// constant alpha of 1.0.
1307 Opaque = 1,
1308 /// The alpha channel, if it exists, of the textures is respected in the
1309 /// compositing process. The non-alpha channels of the textures are
1310 /// expected to already be multiplied by the alpha channel by the
1311 /// application.
1312 PreMultiplied = 2,
1313 /// The alpha channel, if it exists, of the textures is respected in the
1314 /// compositing process. The non-alpha channels of the textures are not
1315 /// expected to already be multiplied by the alpha channel by the
1316 /// application; instead, the compositor will multiply the non-alpha
1317 /// channels of the texture by the alpha channel during compositing.
1318 PostMultiplied = 3,
1319 /// The alpha channel, if it exists, of the textures is unknown for processing
1320 /// during compositing. Instead, the application is responsible for setting
1321 /// the composite alpha blending mode using native WSI command. If not set,
1322 /// then a platform-specific default will be used.
1323 Inherit = 4,
1324}
1325
1326/// Defines the way a [`Window`] is displayed.
1327#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
1328#[cfg_attr(
1329 feature = "bevy_reflect",
1330 derive(Reflect),
1331 reflect(Debug, PartialEq, Clone)
1332)]
1333#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1334#[cfg_attr(
1335 all(feature = "serialize", feature = "bevy_reflect"),
1336 reflect(Serialize, Deserialize)
1337)]
1338pub enum WindowMode {
1339 /// The window should take a portion of the screen, using the window resolution size.
1340 #[default]
1341 Windowed,
1342 /// The window should appear fullscreen by being borderless and using the full
1343 /// size of the screen on the given [`MonitorSelection`].
1344 ///
1345 /// When setting this, the window's physical size will be modified to match the size
1346 /// of the current monitor resolution, and the logical size will follow based
1347 /// on the scale factor, see [`WindowResolution`].
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 BorderlessFullscreen(MonitorSelection),
1354 /// The window should be in "true"/"legacy"/"exclusive" Fullscreen mode on the given [`MonitorSelection`].
1355 ///
1356 /// The resolution, refresh rate, and bit depth are selected based on the given [`VideoModeSelection`].
1357 ///
1358 /// Note: As this mode respects the scale factor provided by the operating system,
1359 /// the window's logical size may be different from its physical size.
1360 /// If you want to avoid that behavior, you can use the [`WindowResolution::set_scale_factor_override`] function
1361 /// or the [`WindowResolution::with_scale_factor_override`] builder method to set the scale factor to 1.0.
1362 Fullscreen(MonitorSelection, VideoModeSelection),
1363}
1364
1365/// Specifies where a [`Window`] should appear relative to other overlapping windows (on top or under) .
1366///
1367/// Levels are groups of windows with respect to their z-position.
1368///
1369/// The relative ordering between windows in different window levels is fixed.
1370/// The z-order of windows within the same window level may change dynamically on user interaction.
1371///
1372/// ## Platform-specific
1373///
1374/// - **iOS / Android / Web / Wayland:** Unsupported.
1375#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
1376#[cfg_attr(
1377 feature = "bevy_reflect",
1378 derive(Reflect),
1379 reflect(Debug, PartialEq, Clone)
1380)]
1381#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1382#[cfg_attr(
1383 all(feature = "serialize", feature = "bevy_reflect"),
1384 reflect(Serialize, Deserialize)
1385)]
1386pub enum WindowLevel {
1387 /// The window will always be below [`WindowLevel::Normal`] and [`WindowLevel::AlwaysOnTop`] windows.
1388 ///
1389 /// This is useful for a widget-based app.
1390 AlwaysOnBottom,
1391 /// The default group.
1392 #[default]
1393 Normal,
1394 /// The window will always be on top of [`WindowLevel::Normal`] and [`WindowLevel::AlwaysOnBottom`] windows.
1395 AlwaysOnTop,
1396}
1397
1398/// The [`Window`] theme variant to use.
1399#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1400#[cfg_attr(
1401 feature = "bevy_reflect",
1402 derive(Reflect),
1403 reflect(Debug, PartialEq, Clone)
1404)]
1405#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1406#[cfg_attr(
1407 all(feature = "serialize", feature = "bevy_reflect"),
1408 reflect(Serialize, Deserialize)
1409)]
1410pub enum WindowTheme {
1411 /// Use the light variant.
1412 Light,
1413
1414 /// Use the dark variant.
1415 Dark,
1416}
1417
1418/// Specifies which [`Window`] control buttons should be enabled.
1419///
1420/// ## Platform-specific
1421///
1422/// **`iOS`**, **`Android`**, and the **`Web`** do not have window control buttons.
1423///
1424/// On some **`Linux`** environments these values have no effect.
1425#[derive(Debug, Copy, Clone, PartialEq)]
1426#[cfg_attr(
1427 feature = "bevy_reflect",
1428 derive(Reflect),
1429 reflect(Debug, PartialEq, Default, Clone)
1430)]
1431#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1432#[cfg_attr(
1433 all(feature = "serialize", feature = "bevy_reflect"),
1434 reflect(Serialize, Deserialize)
1435)]
1436pub struct EnabledButtons {
1437 /// Enables the functionality of the minimize button.
1438 pub minimize: bool,
1439 /// Enables the functionality of the maximize button.
1440 ///
1441 /// macOS note: When [`Window`] `resizable` member is set to `false`
1442 /// the maximize button will be disabled regardless of this value.
1443 /// Additionally, when `resizable` is set to `true` the window will
1444 /// be maximized when its bar is double-clicked regardless of whether
1445 /// the maximize button is enabled or not.
1446 pub maximize: bool,
1447 /// Enables the functionality of the close button.
1448 pub close: bool,
1449}
1450
1451impl Default for EnabledButtons {
1452 fn default() -> Self {
1453 Self {
1454 minimize: true,
1455 maximize: true,
1456 close: true,
1457 }
1458 }
1459}
1460
1461/// Marker component for a [`Window`] that has been requested to close and
1462/// is in the process of closing (on the next frame).
1463#[derive(Component, Default)]
1464pub struct ClosingWindow;
1465
1466/// The edges of a screen. Corresponds to [`winit::platform::ios::ScreenEdge`].
1467///
1468/// # Platform-specific
1469///
1470/// - Only used on iOS.
1471///
1472/// [`winit::platform::ios::ScreenEdge`]: https://docs.rs/winit/latest/x86_64-apple-darwin/winit/platform/ios/struct.ScreenEdge.html
1473#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
1474#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
1475#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1476pub enum ScreenEdge {
1477 #[default]
1478 /// No edge.
1479 None,
1480 /// The top edge of the screen.
1481 Top,
1482 /// The left edge of the screen.
1483 Left,
1484 /// The bottom edge of the screen.
1485 Bottom,
1486 /// The right edge of the screen.
1487 Right,
1488 /// All edges of the screen.
1489 All,
1490}
1491
1492#[cfg(test)]
1493mod tests {
1494 use super::*;
1495
1496 // Checks that `Window::physical_cursor_position` returns the cursor position if it is within
1497 // the bounds of the window.
1498 #[test]
1499 fn cursor_position_within_window_bounds() {
1500 let mut window = Window {
1501 resolution: WindowResolution::new(800, 600),
1502 ..Default::default()
1503 };
1504
1505 window.set_physical_cursor_position(Some(DVec2::new(0., 300.)));
1506 assert_eq!(window.physical_cursor_position(), Some(Vec2::new(0., 300.)));
1507
1508 window.set_physical_cursor_position(Some(DVec2::new(400., 0.)));
1509 assert_eq!(window.physical_cursor_position(), Some(Vec2::new(400., 0.)));
1510
1511 window.set_physical_cursor_position(Some(DVec2::new(799.999, 300.)));
1512 assert_eq!(
1513 window.physical_cursor_position(),
1514 Some(Vec2::new(799.999, 300.)),
1515 );
1516
1517 window.set_physical_cursor_position(Some(DVec2::new(400., 599.999)));
1518 assert_eq!(
1519 window.physical_cursor_position(),
1520 Some(Vec2::new(400., 599.999))
1521 );
1522 }
1523
1524 // Checks that `Window::physical_cursor_position` returns `None` if the cursor position is not
1525 // within the bounds of the window.
1526 #[test]
1527 fn cursor_position_not_within_window_bounds() {
1528 let mut window = Window {
1529 resolution: WindowResolution::new(800, 600),
1530 ..Default::default()
1531 };
1532
1533 window.set_physical_cursor_position(Some(DVec2::new(-0.001, 300.)));
1534 assert!(window.physical_cursor_position().is_none());
1535
1536 window.set_physical_cursor_position(Some(DVec2::new(400., -0.001)));
1537 assert!(window.physical_cursor_position().is_none());
1538
1539 window.set_physical_cursor_position(Some(DVec2::new(800., 300.)));
1540 assert!(window.physical_cursor_position().is_none());
1541
1542 window.set_physical_cursor_position(Some(DVec2::new(400., 600.)));
1543 assert!(window.physical_cursor_position().is_none());
1544 }
1545}
1546
1547/// Represents the relationship between a Window and the Monitor it is currently on.
1548///
1549/// # Note
1550/// This component is inserted after window creation, this means that there is a small period of
1551/// time when the Window exists, but does not know the monitor it is on.
1552#[derive(Component, Debug)]
1553#[relationship(relationship_target=crate::monitor::HasWindows)]
1554pub struct OnMonitor(pub Entity);