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`]
768 /// - **`X11`** doesn't support [`CursorGrabMode::Locked`]
769 /// - **`iOS/Android`** don't have cursors.
770 ///
771 /// 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.
772 pub grab_mode: CursorGrabMode,
773
774 /// Set whether or not mouse events within *this* window are captured or fall through to the Window below.
775 ///
776 /// ## Platform-specific
777 ///
778 /// - iOS / Android / Web / X11: Unsupported.
779 pub hit_test: bool,
780}
781
782impl Default for CursorOptions {
783 fn default() -> Self {
784 CursorOptions {
785 visible: true,
786 grab_mode: CursorGrabMode::None,
787 hit_test: true,
788 }
789 }
790}
791
792/// Defines where a [`Window`] should be placed on the screen.
793#[derive(Default, Debug, Clone, Copy, PartialEq)]
794#[cfg_attr(
795 feature = "bevy_reflect",
796 derive(Reflect),
797 reflect(Debug, PartialEq, Clone)
798)]
799#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
800#[cfg_attr(
801 all(feature = "serialize", feature = "bevy_reflect"),
802 reflect(Serialize, Deserialize)
803)]
804pub enum WindowPosition {
805 /// Position will be set by the window manager.
806 /// Bevy will delegate this decision to the window manager and no guarantees can be made about where the window will be placed.
807 ///
808 /// Used at creation but will be changed to [`At`](WindowPosition::At).
809 #[default]
810 Automatic,
811 /// Window will be centered on the selected monitor.
812 ///
813 /// Note that this does not account for window decorations.
814 ///
815 /// Used at creation or for update but will be changed to [`At`](WindowPosition::At)
816 Centered(MonitorSelection),
817 /// The window's top-left corner should be placed at the specified position (in physical pixels).
818 ///
819 /// (0,0) represents top-left corner of screen space.
820 At(IVec2),
821}
822
823impl WindowPosition {
824 /// Creates a new [`WindowPosition`] at a position.
825 pub fn new(position: IVec2) -> Self {
826 Self::At(position)
827 }
828
829 /// Set the position to a specific point.
830 pub fn set(&mut self, position: IVec2) {
831 *self = WindowPosition::At(position);
832 }
833
834 /// Set the window to a specific monitor.
835 pub fn center(&mut self, monitor: MonitorSelection) {
836 *self = WindowPosition::Centered(monitor);
837 }
838}
839
840/// Controls the size of a [`Window`]
841///
842/// ## Physical, logical and requested sizes
843///
844/// There are three sizes associated with a window:
845/// - the physical size,
846/// which represents the actual height and width in physical pixels
847/// the window occupies on the monitor,
848/// - the logical size,
849/// which represents the size that should be used to scale elements
850/// inside the window, measured in logical pixels,
851/// - the requested size,
852/// measured in logical pixels, which is the value submitted
853/// to the API when creating the window, or requesting that it be resized.
854///
855/// ## Scale factor
856///
857/// The reason logical size and physical size are separated and can be different
858/// is to account for the cases where:
859/// - several monitors have different pixel densities,
860/// - the user has set up a pixel density preference in its operating system,
861/// - the Bevy `App` has specified a specific scale factor between both.
862///
863/// The factor between physical size and logical size can be retrieved with
864/// [`WindowResolution::scale_factor`].
865///
866/// For the first two cases, a scale factor is set automatically by the operating
867/// system through the window backend. You can get it with
868/// [`WindowResolution::base_scale_factor`].
869///
870/// For the third case, you can override this automatic scale factor with
871/// [`WindowResolution::set_scale_factor_override`].
872///
873/// ## Requested and obtained sizes
874///
875/// The logical size should be equal to the requested size after creating/resizing,
876/// when possible.
877/// The reason the requested size and logical size might be different
878/// is because the corresponding physical size might exceed limits (either the
879/// size limits of the monitor, or limits defined in [`WindowResizeConstraints`]).
880///
881/// Note: The requested size is not kept in memory, for example requesting a size
882/// too big for the screen, making the logical size different from the requested size,
883/// and then setting a scale factor that makes the previous requested size within
884/// the limits of the screen will not get back that previous requested size.
885
886#[derive(Debug, Clone, PartialEq)]
887#[cfg_attr(
888 feature = "bevy_reflect",
889 derive(Reflect),
890 reflect(Debug, PartialEq, Default, Clone)
891)]
892#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
893#[cfg_attr(
894 all(feature = "serialize", feature = "bevy_reflect"),
895 reflect(Serialize, Deserialize)
896)]
897pub struct WindowResolution {
898 /// Width of the window in physical pixels.
899 physical_width: u32,
900 /// Height of the window in physical pixels.
901 physical_height: u32,
902 /// Code-provided ratio of physical size to logical size.
903 ///
904 /// Should be used instead of `scale_factor` when set.
905 scale_factor_override: Option<f32>,
906 /// OS-provided ratio of physical size to logical size.
907 ///
908 /// Set automatically depending on the pixel density of the screen.
909 scale_factor: f32,
910}
911
912impl Default for WindowResolution {
913 fn default() -> Self {
914 WindowResolution {
915 physical_width: 1280,
916 physical_height: 720,
917 scale_factor_override: None,
918 scale_factor: 1.0,
919 }
920 }
921}
922
923impl WindowResolution {
924 /// Creates a new [`WindowResolution`].
925 pub fn new(physical_width: u32, physical_height: u32) -> Self {
926 Self {
927 physical_width,
928 physical_height,
929 ..Default::default()
930 }
931 }
932
933 /// Builder method for adding a scale factor override to the resolution.
934 pub fn with_scale_factor_override(mut self, scale_factor_override: f32) -> Self {
935 self.set_scale_factor_override(Some(scale_factor_override));
936 self
937 }
938
939 /// The window's client area width in logical pixels.
940 #[inline]
941 pub fn width(&self) -> f32 {
942 self.physical_width() as f32 / self.scale_factor()
943 }
944
945 /// The window's client area height in logical pixels.
946 #[inline]
947 pub fn height(&self) -> f32 {
948 self.physical_height() as f32 / self.scale_factor()
949 }
950
951 /// The window's client size in logical pixels
952 #[inline]
953 pub fn size(&self) -> Vec2 {
954 Vec2::new(self.width(), self.height())
955 }
956
957 /// The window's client area width in physical pixels.
958 #[inline]
959 pub fn physical_width(&self) -> u32 {
960 self.physical_width
961 }
962
963 /// The window's client area height in physical pixels.
964 #[inline]
965 pub fn physical_height(&self) -> u32 {
966 self.physical_height
967 }
968
969 /// The window's client size in physical pixels
970 #[inline]
971 pub fn physical_size(&self) -> UVec2 {
972 UVec2::new(self.physical_width, self.physical_height)
973 }
974
975 /// The ratio of physical pixels to logical pixels.
976 ///
977 /// `physical_pixels = logical_pixels * scale_factor`
978 pub fn scale_factor(&self) -> f32 {
979 self.scale_factor_override
980 .unwrap_or_else(|| self.base_scale_factor())
981 }
982
983 /// The window scale factor as reported by the window backend.
984 ///
985 /// This value is unaffected by [`WindowResolution::scale_factor_override`].
986 #[inline]
987 pub fn base_scale_factor(&self) -> f32 {
988 self.scale_factor
989 }
990
991 /// The scale factor set with [`WindowResolution::set_scale_factor_override`].
992 ///
993 /// This value may be different from the scale factor reported by the window backend.
994 #[inline]
995 pub fn scale_factor_override(&self) -> Option<f32> {
996 self.scale_factor_override
997 }
998
999 /// Set the window's logical resolution.
1000 #[inline]
1001 pub fn set(&mut self, width: f32, height: f32) {
1002 self.set_physical_resolution(
1003 (width * self.scale_factor()) as u32,
1004 (height * self.scale_factor()) as u32,
1005 );
1006 }
1007
1008 /// Set the window's physical resolution.
1009 ///
1010 /// This will ignore the scale factor setting, so most of the time you should
1011 /// prefer to use [`WindowResolution::set`].
1012 #[inline]
1013 pub fn set_physical_resolution(&mut self, width: u32, height: u32) {
1014 self.physical_width = width;
1015 self.physical_height = height;
1016 }
1017
1018 /// Set the window's scale factor, this may get overridden by the backend.
1019 #[inline]
1020 pub fn set_scale_factor(&mut self, scale_factor: f32) {
1021 self.scale_factor = scale_factor;
1022 }
1023
1024 /// Set the window's scale factor, and apply it to the currently known physical size.
1025 /// This may get overridden by the backend. This is mostly useful on window creation,
1026 /// so that the window is created with the expected size instead of waiting for a resize
1027 /// event after its creation.
1028 #[inline]
1029 #[doc(hidden)]
1030 pub fn set_scale_factor_and_apply_to_physical_size(&mut self, scale_factor: f32) {
1031 self.scale_factor = scale_factor;
1032 self.physical_width = (self.physical_width as f32 * scale_factor) as u32;
1033 self.physical_height = (self.physical_height as f32 * scale_factor) as u32;
1034 }
1035
1036 /// Set the window's scale factor, this will be used over what the backend decides.
1037 ///
1038 /// This can change the logical and physical sizes if the resulting physical
1039 /// size is not within the limits.
1040 #[inline]
1041 pub fn set_scale_factor_override(&mut self, scale_factor_override: Option<f32>) {
1042 self.scale_factor_override = scale_factor_override;
1043 }
1044}
1045
1046impl From<(u32, u32)> for WindowResolution {
1047 fn from((width, height): (u32, u32)) -> Self {
1048 WindowResolution::new(width, height)
1049 }
1050}
1051
1052impl From<[u32; 2]> for WindowResolution {
1053 fn from([width, height]: [u32; 2]) -> WindowResolution {
1054 WindowResolution::new(width, height)
1055 }
1056}
1057
1058impl From<UVec2> for WindowResolution {
1059 fn from(res: UVec2) -> WindowResolution {
1060 WindowResolution::new(res.x, res.y)
1061 }
1062}
1063
1064/// Defines if and how the cursor is grabbed by a [`Window`].
1065///
1066/// ## Platform-specific
1067///
1068/// - **`macOS`** doesn't support [`CursorGrabMode::Confined`]
1069/// - **`X11`** doesn't support [`CursorGrabMode::Locked`]
1070/// - **`iOS/Android`** don't have cursors.
1071///
1072/// 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.
1073#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
1074#[cfg_attr(
1075 feature = "bevy_reflect",
1076 derive(Reflect),
1077 reflect(Debug, PartialEq, Default, Clone)
1078)]
1079#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1080#[cfg_attr(
1081 all(feature = "serialize", feature = "bevy_reflect"),
1082 reflect(Serialize, Deserialize)
1083)]
1084pub enum CursorGrabMode {
1085 /// The cursor can freely leave the window.
1086 #[default]
1087 None,
1088 /// The cursor is confined to the window area.
1089 Confined,
1090 /// The cursor is locked inside the window area to a certain position.
1091 Locked,
1092}
1093
1094/// Stores internal [`Window`] state that isn't directly accessible.
1095#[derive(Default, Debug, Copy, Clone, PartialEq)]
1096#[cfg_attr(
1097 feature = "bevy_reflect",
1098 derive(Reflect),
1099 reflect(Debug, PartialEq, Default, Clone)
1100)]
1101#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1102#[cfg_attr(
1103 all(feature = "serialize", feature = "bevy_reflect"),
1104 reflect(Serialize, Deserialize)
1105)]
1106pub struct InternalWindowState {
1107 /// If this is true then next frame we will ask to minimize the window.
1108 minimize_request: Option<bool>,
1109 /// If this is true then next frame we will ask to maximize/un-maximize the window depending on `maximized`.
1110 maximize_request: Option<bool>,
1111 /// If this is true then next frame we will ask to drag-move the window.
1112 drag_move_request: bool,
1113 /// If this is `Some` then the next frame we will ask to drag-resize the window.
1114 drag_resize_request: Option<CompassOctant>,
1115 /// Unscaled cursor position.
1116 physical_cursor_position: Option<DVec2>,
1117}
1118
1119impl InternalWindowState {
1120 /// Consumes the current maximize request, if it exists. This should only be called by window backends.
1121 pub fn take_maximize_request(&mut self) -> Option<bool> {
1122 self.maximize_request.take()
1123 }
1124
1125 /// Consumes the current minimize request, if it exists. This should only be called by window backends.
1126 pub fn take_minimize_request(&mut self) -> Option<bool> {
1127 self.minimize_request.take()
1128 }
1129
1130 /// Consumes the current move request, if it exists. This should only be called by window backends.
1131 pub fn take_move_request(&mut self) -> bool {
1132 core::mem::take(&mut self.drag_move_request)
1133 }
1134
1135 /// Consumes the current resize request, if it exists. This should only be called by window backends.
1136 pub fn take_resize_request(&mut self) -> Option<CompassOctant> {
1137 self.drag_resize_request.take()
1138 }
1139}
1140
1141/// References a screen monitor.
1142///
1143/// Used when centering a [`Window`] on a monitor.
1144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1145#[cfg_attr(
1146 feature = "bevy_reflect",
1147 derive(Reflect),
1148 reflect(Debug, PartialEq, Clone)
1149)]
1150#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1151#[cfg_attr(
1152 all(feature = "serialize", feature = "bevy_reflect"),
1153 reflect(Serialize, Deserialize)
1154)]
1155pub enum MonitorSelection {
1156 /// Uses the current monitor of the window.
1157 ///
1158 /// If [`WindowPosition::Centered(MonitorSelection::Current)`](WindowPosition::Centered) is used when creating a window,
1159 /// the window doesn't have a monitor yet, this will fall back to [`WindowPosition::Automatic`].
1160 Current,
1161 /// Uses the primary monitor of the system.
1162 Primary,
1163 /// Uses the monitor with the specified index.
1164 Index(usize),
1165 /// Uses a given [`Monitor`](`crate::monitor::Monitor`) entity.
1166 Entity(Entity),
1167}
1168
1169/// References an exclusive fullscreen video mode.
1170///
1171/// Used when setting [`WindowMode::Fullscreen`] on a window.
1172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1173#[cfg_attr(
1174 feature = "bevy_reflect",
1175 derive(Reflect),
1176 reflect(Debug, PartialEq, Clone)
1177)]
1178#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1179#[cfg_attr(
1180 all(feature = "serialize", feature = "bevy_reflect"),
1181 reflect(Serialize, Deserialize)
1182)]
1183pub enum VideoModeSelection {
1184 /// Uses the video mode that the monitor is already in.
1185 Current,
1186 /// Uses a given [`VideoMode`](`crate::monitor::VideoMode`). A list of video modes supported by the monitor
1187 /// is supplied by [`Monitor::video_modes`](`crate::monitor::Monitor::video_modes`).
1188 Specific(VideoMode),
1189}
1190
1191/// Presentation mode for a [`Window`].
1192///
1193/// The presentation mode specifies when a frame is presented to the window. The [`Fifo`]
1194/// option corresponds to a traditional `VSync`, where the framerate is capped by the
1195/// display refresh rate. Both [`Immediate`] and [`Mailbox`] are low-latency and are not
1196/// capped by the refresh rate, but may not be available on all platforms. Tearing
1197/// may be observed with [`Immediate`] mode, but will not be observed with [`Mailbox`] or
1198/// [`Fifo`].
1199///
1200/// [`AutoVsync`] or [`AutoNoVsync`] will gracefully fallback to [`Fifo`] when unavailable.
1201///
1202/// [`Immediate`] or [`Mailbox`] will panic if not supported by the platform.
1203///
1204/// [`Fifo`]: PresentMode::Fifo
1205/// [`FifoRelaxed`]: PresentMode::FifoRelaxed
1206/// [`Immediate`]: PresentMode::Immediate
1207/// [`Mailbox`]: PresentMode::Mailbox
1208/// [`AutoVsync`]: PresentMode::AutoVsync
1209/// [`AutoNoVsync`]: PresentMode::AutoNoVsync
1210#[repr(C)]
1211#[derive(Default, Copy, Clone, Debug, PartialEq, Eq, Hash)]
1212#[cfg_attr(
1213 feature = "bevy_reflect",
1214 derive(Reflect),
1215 reflect(Debug, PartialEq, Hash, Clone)
1216)]
1217#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1218#[cfg_attr(
1219 all(feature = "serialize", feature = "bevy_reflect"),
1220 reflect(Serialize, Deserialize)
1221)]
1222#[doc(alias = "vsync")]
1223pub enum PresentMode {
1224 /// Chooses [`FifoRelaxed`](Self::FifoRelaxed) -> [`Fifo`](Self::Fifo) based on availability.
1225 ///
1226 /// Because of the fallback behavior, it is supported everywhere.
1227 AutoVsync = 0, // NOTE: The explicit ordinal values mirror wgpu.
1228 /// Chooses [`Immediate`](Self::Immediate) -> [`Mailbox`](Self::Mailbox) -> [`Fifo`](Self::Fifo) (on web) based on availability.
1229 ///
1230 /// Because of the fallback behavior, it is supported everywhere.
1231 AutoNoVsync = 1,
1232 /// Presentation frames are kept in a First-In-First-Out queue approximately 3 frames
1233 /// long. Every vertical blanking period, the presentation engine will pop a frame
1234 /// off the queue to display. If there is no frame to display, it will present the same
1235 /// frame again until the next vblank.
1236 ///
1237 /// When a present command is executed on the gpu, the presented image is added on the queue.
1238 ///
1239 /// No tearing will be observed.
1240 ///
1241 /// Calls to `get_current_texture` will block until there is a spot in the queue.
1242 ///
1243 /// Supported on all platforms.
1244 ///
1245 /// If you don't know what mode to choose, choose this mode. This is traditionally called "Vsync On".
1246 #[default]
1247 Fifo = 2,
1248 /// Presentation frames are kept in a First-In-First-Out queue approximately 3 frames
1249 /// long. Every vertical blanking period, the presentation engine will pop a frame
1250 /// off the queue to display. If there is no frame to display, it will present the
1251 /// same frame until there is a frame in the queue. The moment there is a frame in the
1252 /// queue, it will immediately pop the frame off the queue.
1253 ///
1254 /// When a present command is executed on the gpu, the presented image is added on the queue.
1255 ///
1256 /// Tearing will be observed if frames last more than one vblank as the front buffer.
1257 ///
1258 /// Calls to `get_current_texture` will block until there is a spot in the queue.
1259 ///
1260 /// Supported on AMD on Vulkan.
1261 ///
1262 /// This is traditionally called "Adaptive Vsync"
1263 FifoRelaxed = 3,
1264 /// Presentation frames are not queued at all. The moment a present command
1265 /// is executed on the GPU, the presented image is swapped onto the front buffer
1266 /// immediately.
1267 ///
1268 /// Tearing can be observed.
1269 ///
1270 /// Supported on most platforms except older DX12 and Wayland.
1271 ///
1272 /// This is traditionally called "Vsync Off".
1273 Immediate = 4,
1274 /// Presentation frames are kept in a single-frame queue. Every vertical blanking period,
1275 /// the presentation engine will pop a frame from the queue. If there is no frame to display,
1276 /// it will present the same frame again until the next vblank.
1277 ///
1278 /// When a present command is executed on the gpu, the frame will be put into the queue.
1279 /// If there was already a frame in the queue, the new frame will _replace_ the old frame
1280 /// on the queue.
1281 ///
1282 /// No tearing will be observed.
1283 ///
1284 /// Supported on DX11/12 on Windows 10, NVidia on Vulkan and Wayland on Vulkan.
1285 ///
1286 /// This is traditionally called "Fast Vsync"
1287 Mailbox = 5,
1288}
1289
1290/// Specifies how the alpha channel of the textures should be handled during compositing, for a [`Window`].
1291#[repr(C)]
1292#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
1293#[cfg_attr(
1294 feature = "bevy_reflect",
1295 derive(Reflect),
1296 reflect(Debug, PartialEq, Hash, Clone)
1297)]
1298#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1299#[cfg_attr(
1300 all(feature = "serialize", feature = "bevy_reflect"),
1301 reflect(Serialize, Deserialize)
1302)]
1303pub enum CompositeAlphaMode {
1304 /// Chooses either [`Opaque`](CompositeAlphaMode::Opaque) or [`Inherit`](CompositeAlphaMode::Inherit)
1305 /// automatically, depending on the `alpha_mode` that the current surface can support.
1306 #[default]
1307 Auto = 0,
1308 /// The alpha channel, if it exists, of the textures is ignored in the
1309 /// compositing process. Instead, the textures is treated as if it has a
1310 /// constant alpha of 1.0.
1311 Opaque = 1,
1312 /// The alpha channel, if it exists, of the textures is respected in the
1313 /// compositing process. The non-alpha channels of the textures are
1314 /// expected to already be multiplied by the alpha channel by the
1315 /// application.
1316 PreMultiplied = 2,
1317 /// The alpha channel, if it exists, of the textures is respected in the
1318 /// compositing process. The non-alpha channels of the textures are not
1319 /// expected to already be multiplied by the alpha channel by the
1320 /// application; instead, the compositor will multiply the non-alpha
1321 /// channels of the texture by the alpha channel during compositing.
1322 PostMultiplied = 3,
1323 /// The alpha channel, if it exists, of the textures is unknown for processing
1324 /// during compositing. Instead, the application is responsible for setting
1325 /// the composite alpha blending mode using native WSI command. If not set,
1326 /// then a platform-specific default will be used.
1327 Inherit = 4,
1328}
1329
1330/// Defines the way a [`Window`] is displayed.
1331#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
1332#[cfg_attr(
1333 feature = "bevy_reflect",
1334 derive(Reflect),
1335 reflect(Debug, PartialEq, Clone)
1336)]
1337#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1338#[cfg_attr(
1339 all(feature = "serialize", feature = "bevy_reflect"),
1340 reflect(Serialize, Deserialize)
1341)]
1342pub enum WindowMode {
1343 /// The window should take a portion of the screen, using the window resolution size.
1344 #[default]
1345 Windowed,
1346 /// The window should appear fullscreen by being borderless and using the full
1347 /// size of the screen on the given [`MonitorSelection`].
1348 ///
1349 /// When setting this, the window's physical size will be modified to match the size
1350 /// of the current monitor resolution, and the logical size will follow based
1351 /// on the scale factor, see [`WindowResolution`].
1352 ///
1353 /// Note: As this mode respects the scale factor provided by the operating system,
1354 /// the window's logical size may be different from its physical size.
1355 /// If you want to avoid that behavior, you can use the [`WindowResolution::set_scale_factor_override`] function
1356 /// or the [`WindowResolution::with_scale_factor_override`] builder method to set the scale factor to 1.0.
1357 BorderlessFullscreen(MonitorSelection),
1358 /// The window should be in "true"/"legacy"/"exclusive" Fullscreen mode on the given [`MonitorSelection`].
1359 ///
1360 /// The resolution, refresh rate, and bit depth are selected based on the given [`VideoModeSelection`].
1361 ///
1362 /// Note: As this mode respects the scale factor provided by the operating system,
1363 /// the window's logical size may be different from its physical size.
1364 /// If you want to avoid that behavior, you can use the [`WindowResolution::set_scale_factor_override`] function
1365 /// or the [`WindowResolution::with_scale_factor_override`] builder method to set the scale factor to 1.0.
1366 Fullscreen(MonitorSelection, VideoModeSelection),
1367}
1368
1369/// Specifies where a [`Window`] should appear relative to other overlapping windows (on top or under) .
1370///
1371/// Levels are groups of windows with respect to their z-position.
1372///
1373/// The relative ordering between windows in different window levels is fixed.
1374/// The z-order of windows within the same window level may change dynamically on user interaction.
1375///
1376/// ## Platform-specific
1377///
1378/// - **iOS / Android / Web / Wayland:** Unsupported.
1379#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
1380#[cfg_attr(
1381 feature = "bevy_reflect",
1382 derive(Reflect),
1383 reflect(Debug, PartialEq, Clone)
1384)]
1385#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1386#[cfg_attr(
1387 all(feature = "serialize", feature = "bevy_reflect"),
1388 reflect(Serialize, Deserialize)
1389)]
1390pub enum WindowLevel {
1391 /// The window will always be below [`WindowLevel::Normal`] and [`WindowLevel::AlwaysOnTop`] windows.
1392 ///
1393 /// This is useful for a widget-based app.
1394 AlwaysOnBottom,
1395 /// The default group.
1396 #[default]
1397 Normal,
1398 /// The window will always be on top of [`WindowLevel::Normal`] and [`WindowLevel::AlwaysOnBottom`] windows.
1399 AlwaysOnTop,
1400}
1401
1402/// The [`Window`] theme variant to use.
1403#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1404#[cfg_attr(
1405 feature = "bevy_reflect",
1406 derive(Reflect),
1407 reflect(Debug, PartialEq, Clone)
1408)]
1409#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1410#[cfg_attr(
1411 all(feature = "serialize", feature = "bevy_reflect"),
1412 reflect(Serialize, Deserialize)
1413)]
1414pub enum WindowTheme {
1415 /// Use the light variant.
1416 Light,
1417
1418 /// Use the dark variant.
1419 Dark,
1420}
1421
1422/// Specifies which [`Window`] control buttons should be enabled.
1423///
1424/// ## Platform-specific
1425///
1426/// **`iOS`**, **`Android`**, and the **`Web`** do not have window control buttons.
1427///
1428/// On some **`Linux`** environments these values have no effect.
1429#[derive(Debug, Copy, Clone, PartialEq)]
1430#[cfg_attr(
1431 feature = "bevy_reflect",
1432 derive(Reflect),
1433 reflect(Debug, PartialEq, Default, Clone)
1434)]
1435#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1436#[cfg_attr(
1437 all(feature = "serialize", feature = "bevy_reflect"),
1438 reflect(Serialize, Deserialize)
1439)]
1440pub struct EnabledButtons {
1441 /// Enables the functionality of the minimize button.
1442 pub minimize: bool,
1443 /// Enables the functionality of the maximize button.
1444 ///
1445 /// macOS note: When [`Window`] `resizable` member is set to `false`
1446 /// the maximize button will be disabled regardless of this value.
1447 /// Additionally, when `resizable` is set to `true` the window will
1448 /// be maximized when its bar is double-clicked regardless of whether
1449 /// the maximize button is enabled or not.
1450 pub maximize: bool,
1451 /// Enables the functionality of the close button.
1452 pub close: bool,
1453}
1454
1455impl Default for EnabledButtons {
1456 fn default() -> Self {
1457 Self {
1458 minimize: true,
1459 maximize: true,
1460 close: true,
1461 }
1462 }
1463}
1464
1465/// Marker component for a [`Window`] that has been requested to close and
1466/// is in the process of closing (on the next frame).
1467#[derive(Component, Default)]
1468pub struct ClosingWindow;
1469
1470/// The edges of a screen. Corresponds to [`winit::platform::ios::ScreenEdge`].
1471///
1472/// # Platform-specific
1473///
1474/// - Only used on iOS.
1475///
1476/// [`winit::platform::ios::ScreenEdge`]: https://docs.rs/winit/latest/x86_64-apple-darwin/winit/platform/ios/struct.ScreenEdge.html
1477#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
1478#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
1479#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
1480pub enum ScreenEdge {
1481 #[default]
1482 /// No edge.
1483 None,
1484 /// The top edge of the screen.
1485 Top,
1486 /// The left edge of the screen.
1487 Left,
1488 /// The bottom edge of the screen.
1489 Bottom,
1490 /// The right edge of the screen.
1491 Right,
1492 /// All edges of the screen.
1493 All,
1494}
1495
1496#[cfg(test)]
1497mod tests {
1498 use super::*;
1499
1500 // Checks that `Window::physical_cursor_position` returns the cursor position if it is within
1501 // the bounds of the window.
1502 #[test]
1503 fn cursor_position_within_window_bounds() {
1504 let mut window = Window {
1505 resolution: WindowResolution::new(800, 600),
1506 ..Default::default()
1507 };
1508
1509 window.set_physical_cursor_position(Some(DVec2::new(0., 300.)));
1510 assert_eq!(window.physical_cursor_position(), Some(Vec2::new(0., 300.)));
1511
1512 window.set_physical_cursor_position(Some(DVec2::new(400., 0.)));
1513 assert_eq!(window.physical_cursor_position(), Some(Vec2::new(400., 0.)));
1514
1515 window.set_physical_cursor_position(Some(DVec2::new(799.999, 300.)));
1516 assert_eq!(
1517 window.physical_cursor_position(),
1518 Some(Vec2::new(799.999, 300.)),
1519 );
1520
1521 window.set_physical_cursor_position(Some(DVec2::new(400., 599.999)));
1522 assert_eq!(
1523 window.physical_cursor_position(),
1524 Some(Vec2::new(400., 599.999))
1525 );
1526 }
1527
1528 // Checks that `Window::physical_cursor_position` returns `None` if the cursor position is not
1529 // within the bounds of the window.
1530 #[test]
1531 fn cursor_position_not_within_window_bounds() {
1532 let mut window = Window {
1533 resolution: WindowResolution::new(800, 600),
1534 ..Default::default()
1535 };
1536
1537 window.set_physical_cursor_position(Some(DVec2::new(-0.001, 300.)));
1538 assert!(window.physical_cursor_position().is_none());
1539
1540 window.set_physical_cursor_position(Some(DVec2::new(400., -0.001)));
1541 assert!(window.physical_cursor_position().is_none());
1542
1543 window.set_physical_cursor_position(Some(DVec2::new(800., 300.)));
1544 assert!(window.physical_cursor_position().is_none());
1545
1546 window.set_physical_cursor_position(Some(DVec2::new(400., 600.)));
1547 assert!(window.physical_cursor_position().is_none());
1548 }
1549}
1550
1551/// Represents the relationship between a Window and the Monitor it is currently on.
1552///
1553/// # Note
1554/// This component is inserted after window creation, this means that there is a small period of
1555/// time when the Window exists, but does not know the monitor it is on.
1556#[derive(Component, Debug)]
1557#[relationship(relationship_target=crate::monitor::HasWindows)]
1558pub struct OnMonitor(pub Entity);