egui/viewport.rs
1//! egui supports multiple viewports, corresponding to multiple native windows.
2//!
3//! Not all egui backends support multiple viewports, but `eframe` native does
4//! (but not on web).
5//!
6//! You can spawn a new viewport using [`Context::show_viewport_deferred`] and [`Context::show_viewport_immediate`].
7//! These needs to be called every frame the viewport should be visible.
8//!
9//! This is implemented by the native `eframe` backend, but not the web one.
10//!
11//! ## Viewport classes
12//! The viewports form a tree of parent-child relationships.
13//!
14//! There are different classes of viewports.
15//!
16//! ### Root viewport
17//! The root viewport is the original viewport, and cannot be closed without closing the application.
18//!
19//! ### Deferred viewports
20//! These are created with [`Context::show_viewport_deferred`].
21//! Deferred viewports take a closure that is called by the integration at a later time, perhaps multiple times.
22//! Deferred viewports are repainted independently of the parent viewport.
23//! This means communication with them needs to be done via channels, or `Arc/Mutex`.
24//!
25//! This is the most performant type of child viewport, though a bit more cumbersome to work with compared to immediate viewports.
26//!
27//! ### Immediate viewports
28//! These are created with [`Context::show_viewport_immediate`].
29//! Immediate viewports take a `FnOnce` closure, similar to other egui functions, and is called immediately.
30//! This makes communication with them much simpler than with deferred viewports, but this simplicity comes at a cost: whenever the parent viewports needs to be repainted, so will the child viewport, and vice versa.
31//! This means that if you have `N` viewports you are potentially doing `N` times as much CPU work. However, if all your viewports are showing animations, and thus are repainting constantly anyway, this doesn't matter.
32//!
33//! In short: immediate viewports are simpler to use, but can waste a lot of CPU time.
34//!
35//! ### Embedded viewports
36//! These are not real, independent viewports, but is a fallback mode for when the integration does not support real viewports.
37//! In your callback is called with [`ViewportClass::EmbeddedWindow`] it means the viewport is embedded inside of
38//! a regular [`crate::Window`], trapped in the parent viewport.
39//!
40//!
41//! ## Using the viewports
42//! Only one viewport is active at any one time, identified with [`Context::viewport_id`].
43//! You can modify the current (change the title, resize the window, etc) by sending
44//! a [`ViewportCommand`] to it using [`Context::send_viewport_cmd`].
45//! You can interact with other viewports using [`Context::send_viewport_cmd_to`].
46//!
47//! There is an example in <https://github.com/emilk/egui/tree/main/examples/multiple_viewports/src/main.rs>.
48//!
49//! You can find all available viewports in [`crate::RawInput::viewports`] and the active viewport in
50//! [`crate::InputState::viewport`]:
51//!
52//! ```no_run
53//! # let ctx = &egui::Context::default();
54//! ctx.input(|i| {
55//! dbg!(&i.viewport()); // Current viewport
56//! dbg!(&i.raw.viewports); // All viewports
57//! });
58//! ```
59//!
60//! ## For integrations
61//! * There is a [`crate::InputState::viewport`] with information about the current viewport.
62//! * There is a [`crate::RawInput::viewports`] with information about all viewports.
63//! * The repaint callback set by [`Context::set_request_repaint_callback`] points to which viewport should be repainted.
64//! * [`crate::FullOutput::viewport_output`] is a list of viewports which should result in their own independent windows.
65//! * To support immediate viewports you need to call [`Context::set_immediate_viewport_renderer`].
66//! * If you support viewports, you need to call [`Context::set_embed_viewports`] with `false`, or all new viewports will be embedded (the default behavior).
67//!
68//! ## Future work
69//! There are several more things related to viewports that we want to add.
70//! Read more at <https://github.com/emilk/egui/issues/3556>.
71
72use alloc::sync::Arc;
73
74use crate::{Context, Id, Ui};
75use epaint::{Pos2, Vec2};
76
77// ----------------------------------------------------------------------------
78
79/// The different types of viewports supported by egui.
80#[derive(Clone, Copy, Default, Hash, PartialEq, Eq)]
81#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
82pub enum ViewportClass {
83 /// The root viewport; i.e. the original window.
84 #[default]
85 Root,
86
87 /// A viewport run independently from the parent viewport.
88 ///
89 /// This is the preferred type of viewport from a performance perspective.
90 ///
91 /// Create these with [`crate::Context::show_viewport_deferred`].
92 Deferred,
93
94 /// A viewport run inside the parent viewport.
95 ///
96 /// This is the easier type of viewport to use, but it is less performant
97 /// at it requires both parent and child to repaint if any one of them needs repainting,
98 /// which effectively produces double work for two viewports, and triple work for three viewports, etc.
99 ///
100 /// Create these with [`crate::Context::show_viewport_immediate`].
101 Immediate,
102
103 /// The fallback, when the egui integration doesn't support viewports,
104 /// or [`crate::Context::embed_viewports`] is set to `true`.
105 ///
106 /// If you get this, it is because you are already wrapped in a [`crate::Window`]
107 /// inside of the parent viewport.
108 EmbeddedWindow,
109}
110
111// ----------------------------------------------------------------------------
112
113/// A unique identifier of a viewport.
114///
115/// This is returned by [`Context::viewport_id`] and [`Context::parent_viewport_id`].
116#[derive(Clone, Copy, Hash, PartialEq, Eq)]
117#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
118pub struct ViewportId(pub Id);
119
120// We implement `PartialOrd` and `Ord` so we can use `ViewportId` in a `BTreeMap`,
121// which allows predicatable iteration order, frame-to-frame.
122impl PartialOrd for ViewportId {
123 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
124 Some(self.cmp(other))
125 }
126}
127
128impl Ord for ViewportId {
129 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
130 self.0.value().cmp(&other.0.value())
131 }
132}
133
134impl Default for ViewportId {
135 #[inline]
136 fn default() -> Self {
137 Self::ROOT
138 }
139}
140
141impl core::fmt::Debug for ViewportId {
142 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
143 self.0.short_debug_format().fmt(f)
144 }
145}
146
147impl ViewportId {
148 /// The `ViewportId` of the root viewport.
149 pub const ROOT: Self = Self(Id::NULL);
150
151 #[inline]
152 pub fn from_hash_of(source: impl core::hash::Hash + core::fmt::Debug) -> Self {
153 Self(Id::unique(source))
154 }
155
156 /// The [`Id`] of the root [`crate::Ui`] of this viewport,
157 /// i.e. the `Ui` passed to the closure of [`crate::Context::run_ui`].
158 pub fn root_ui_id(&self) -> Id {
159 Id::unique((*self, "__top_ui"))
160 }
161}
162
163impl From<ViewportId> for Id {
164 #[inline]
165 fn from(id: ViewportId) -> Self {
166 id.0
167 }
168}
169
170impl nohash_hasher::IsEnabled for ViewportId {}
171
172/// A fast hash set of [`ViewportId`].
173pub type ViewportIdSet = nohash_hasher::IntSet<ViewportId>;
174
175/// A fast hash map from [`ViewportId`] to `T`.
176pub type ViewportIdMap<T> = nohash_hasher::IntMap<ViewportId, T>;
177
178/// An order map from [`ViewportId`] to `T`.
179pub type OrderedViewportIdMap<T> = alloc::collections::BTreeMap<ViewportId, T>;
180
181// ----------------------------------------------------------------------------
182
183/// Image data for an application icon.
184///
185/// Use a square image, e.g. 256x256 pixels.
186/// You can use a transparent background.
187#[derive(Clone, Default, PartialEq, Eq)]
188#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
189pub struct IconData {
190 /// RGBA pixels, with separate/unmultiplied alpha.
191 pub rgba: Vec<u8>,
192
193 /// Image width. This should be a multiple of 4.
194 pub width: u32,
195
196 /// Image height. This should be a multiple of 4.
197 pub height: u32,
198}
199
200impl IconData {
201 #[inline]
202 pub fn is_empty(&self) -> bool {
203 self.rgba.is_empty()
204 }
205}
206
207impl core::fmt::Debug for IconData {
208 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
209 f.debug_struct("IconData")
210 .field("width", &self.width)
211 .field("height", &self.height)
212 .finish_non_exhaustive()
213 }
214}
215
216impl From<IconData> for epaint::ColorImage {
217 fn from(icon: IconData) -> Self {
218 profiling::function_scope!();
219 let IconData {
220 rgba,
221 width,
222 height,
223 } = icon;
224 Self::from_rgba_premultiplied([width as usize, height as usize], &rgba)
225 }
226}
227
228impl From<&IconData> for epaint::ColorImage {
229 fn from(icon: &IconData) -> Self {
230 profiling::function_scope!();
231 let IconData {
232 rgba,
233 width,
234 height,
235 } = icon;
236 Self::from_rgba_premultiplied([*width as usize, *height as usize], rgba)
237 }
238}
239
240// ----------------------------------------------------------------------------
241
242/// A pair of [`ViewportId`], used to identify a viewport and its parent.
243#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)]
244#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
245pub struct ViewportIdPair {
246 pub this: ViewportId,
247 pub parent: ViewportId,
248}
249
250impl Default for ViewportIdPair {
251 #[inline]
252 fn default() -> Self {
253 Self::ROOT
254 }
255}
256
257impl ViewportIdPair {
258 /// The `ViewportIdPair` of the root viewport, which is its own parent.
259 pub const ROOT: Self = Self {
260 this: ViewportId::ROOT,
261 parent: ViewportId::ROOT,
262 };
263
264 #[inline]
265 pub fn from_self_and_parent(this: ViewportId, parent: ViewportId) -> Self {
266 Self { this, parent }
267 }
268}
269
270/// The user-code that shows the ui in the viewport, used for deferred viewports.
271pub type DeferredViewportUiCallback = dyn Fn(&mut Ui) + Sync + Send;
272
273/// Render the given viewport, calling the given ui callback.
274pub type ImmediateViewportRendererCallback = dyn for<'a> Fn(&Context, ImmediateViewport<'a>);
275
276/// Control the building of a new egui viewport (i.e. native window).
277///
278/// See [`crate::viewport`] for how to build new viewports (native windows).
279///
280/// The fields are public, but you should use the builder pattern to set them,
281/// and that's where you'll find the documentation too.
282///
283/// Since egui is immediate mode, `ViewportBuilder` is accumulative in nature.
284/// Setting any option to `None` means "keep the current value",
285/// or "Use the default" if it is the first call.
286///
287/// The default values are implementation defined, so you may want to explicitly
288/// configure the size of the window, and what buttons are shown.
289#[derive(Clone, Debug, Default, Eq, PartialEq)]
290pub struct ViewportBuilder {
291 /// The title of the viewport.
292 /// `eframe` will use this as the title of the native window.
293 pub title: Option<String>,
294
295 /// This is wayland only. See [`Self::with_app_id`].
296 pub app_id: Option<String>,
297
298 /// The desired outer position of the window.
299 pub position: Option<Pos2>,
300 pub inner_size: Option<Vec2>,
301 pub min_inner_size: Option<Vec2>,
302 pub max_inner_size: Option<Vec2>,
303
304 /// Whether clamp the window's size to monitor's size. The default is `true` on linux, otherwise it is `false`.
305 ///
306 /// Note: On some Linux systems, a window size larger than the monitor causes crashes
307 pub clamp_size_to_monitor_size: Option<bool>,
308
309 pub fullscreen: Option<bool>,
310 pub maximized: Option<bool>,
311 pub resizable: Option<bool>,
312 pub transparent: Option<bool>,
313 pub decorations: Option<bool>,
314 pub icon: Option<Arc<IconData>>,
315 pub active: Option<bool>,
316 pub visible: Option<bool>,
317
318 // macOS:
319 pub fullsize_content_view: Option<bool>,
320 pub movable_by_window_background: Option<bool>,
321 pub title_shown: Option<bool>,
322 pub titlebar_buttons_shown: Option<bool>,
323 pub titlebar_shown: Option<bool>,
324 pub has_shadow: Option<bool>,
325
326 // windows:
327 pub drag_and_drop: Option<bool>,
328 pub taskbar: Option<bool>,
329
330 pub close_button: Option<bool>,
331 pub minimize_button: Option<bool>,
332 pub maximize_button: Option<bool>,
333
334 pub window_level: Option<WindowLevel>,
335
336 pub mouse_passthrough: Option<bool>,
337
338 // X11
339 pub window_type: Option<X11WindowType>,
340 pub override_redirect: Option<bool>,
341
342 /// Target monitor index for borderless fullscreen.
343 ///
344 /// When set, the window is placed in borderless fullscreen on the monitor at
345 /// the given index in `available_monitors()` order (same order returned by
346 /// winit). Works on Windows, macOS, and Linux (X11 + Wayland).
347 ///
348 /// If the index is out of range, it is ignored and a warning is logged.
349 ///
350 /// Takes precedence over [`Self::with_position`] / [`Self::with_fullscreen`]
351 /// for monitor selection: if both are set, the window will be fullscreen on
352 /// the chosen monitor.
353 pub monitor: Option<usize>,
354}
355
356impl ViewportBuilder {
357 /// Sets the initial title of the window in the title bar.
358 ///
359 /// Look at winit for more details
360 #[inline]
361 pub fn with_title(mut self, title: impl Into<String>) -> Self {
362 self.title = Some(title.into());
363 self
364 }
365
366 /// Sets whether the window should have a border, a title bar, etc.
367 ///
368 /// The default is `true`.
369 ///
370 /// Look at winit for more details
371 #[inline]
372 pub fn with_decorations(mut self, decorations: bool) -> Self {
373 self.decorations = Some(decorations);
374 self
375 }
376
377 /// Sets whether the window should be put into fullscreen upon creation.
378 ///
379 /// The default is `None`.
380 ///
381 /// Look at winit for more details
382 /// This will use borderless
383 #[inline]
384 pub fn with_fullscreen(mut self, fullscreen: bool) -> Self {
385 self.fullscreen = Some(fullscreen);
386 self
387 }
388
389 /// Request that the window is maximized upon creation.
390 ///
391 /// The default is `false`.
392 ///
393 /// Look at winit for more details
394 #[inline]
395 pub fn with_maximized(mut self, maximized: bool) -> Self {
396 self.maximized = Some(maximized);
397 self
398 }
399
400 /// Sets whether the window is resizable or not.
401 ///
402 /// The default is `true`.
403 ///
404 /// Look at winit for more details
405 #[inline]
406 pub fn with_resizable(mut self, resizable: bool) -> Self {
407 self.resizable = Some(resizable);
408 self
409 }
410
411 /// Sets whether the background of the window should be transparent.
412 ///
413 /// You should avoid having a [`crate::CentralPanel`], or make sure its frame is also transparent.
414 ///
415 /// In `eframe` you control the transparency with `eframe::App::clear_color()`.
416 ///
417 /// If this is `true`, writing colors with alpha values different than
418 /// `1.0` will produce a transparent window. On some platforms this
419 /// is more of a hint for the system and you'd still have the alpha
420 /// buffer.
421 ///
422 /// The default is `false`.
423 /// If this is not working, it's because the graphic context doesn't support transparency,
424 /// you will need to set the transparency in the eframe!
425 ///
426 /// ## Platform-specific
427 ///
428 /// **macOS:** When using this feature to create an overlay-like UI, you likely want to combine this with [`Self::with_has_shadow`] set to `false` in order to avoid ghosting artifacts.
429 #[inline]
430 pub fn with_transparent(mut self, transparent: bool) -> Self {
431 self.transparent = Some(transparent);
432 self
433 }
434
435 /// The application icon, e.g. in the Windows task bar or the alt-tab menu.
436 ///
437 /// The default icon is a white `e` on a black background (for "egui" or "eframe").
438 /// If you prefer the OS default, set this to `IconData::default()`.
439 #[inline]
440 pub fn with_icon(mut self, icon: impl Into<Arc<IconData>>) -> Self {
441 self.icon = Some(icon.into());
442 self
443 }
444
445 /// Whether the window will be initially focused or not.
446 ///
447 /// The window should be assumed as not focused by default
448 ///
449 /// ## Platform-specific:
450 ///
451 /// **Android / iOS / X11 / Wayland / Orbital:** Unsupported.
452 ///
453 /// Look at winit for more details
454 #[inline]
455 pub fn with_active(mut self, active: bool) -> Self {
456 self.active = Some(active);
457 self
458 }
459
460 /// Sets whether the window will be initially visible or hidden.
461 ///
462 /// The default is to show the window.
463 ///
464 /// Look at winit for more details
465 #[inline]
466 pub fn with_visible(mut self, visible: bool) -> Self {
467 self.visible = Some(visible);
468 self
469 }
470
471 /// macOS: Makes the window content appear behind the titlebar.
472 ///
473 /// You often want to combine this with [`Self::with_titlebar_shown`]
474 /// and [`Self::with_title_shown`].
475 #[inline]
476 pub fn with_fullsize_content_view(mut self, value: bool) -> Self {
477 self.fullsize_content_view = Some(value);
478 self
479 }
480
481 /// macOS: Set to `true` to allow the window to be moved by dragging the background.
482 /// Enabling this feature can result in unexpected behavior with draggable UI widgets such as sliders.
483 #[inline]
484 pub fn with_movable_by_background(mut self, value: bool) -> Self {
485 self.movable_by_window_background = Some(value);
486 self
487 }
488
489 /// macOS: Set to `false` to hide the window title.
490 #[inline]
491 pub fn with_title_shown(mut self, title_shown: bool) -> Self {
492 self.title_shown = Some(title_shown);
493 self
494 }
495
496 /// macOS: Set to `false` to hide the titlebar button (close, minimize, maximize)
497 #[inline]
498 pub fn with_titlebar_buttons_shown(mut self, titlebar_buttons_shown: bool) -> Self {
499 self.titlebar_buttons_shown = Some(titlebar_buttons_shown);
500 self
501 }
502
503 /// macOS: Set to `false` to make the titlebar transparent, allowing the content to appear behind it.
504 #[inline]
505 pub fn with_titlebar_shown(mut self, shown: bool) -> Self {
506 self.titlebar_shown = Some(shown);
507 self
508 }
509
510 /// macOS: Set to `false` to make the window render without a drop shadow.
511 ///
512 /// The default is `true`.
513 ///
514 /// Disabling this feature can solve ghosting issues experienced if using [`Self::with_transparent`].
515 ///
516 /// Look at winit for more details
517 #[inline]
518 pub fn with_has_shadow(mut self, has_shadow: bool) -> Self {
519 self.has_shadow = Some(has_shadow);
520 self
521 }
522
523 /// windows: Whether show or hide the window icon in the taskbar.
524 #[inline]
525 pub fn with_taskbar(mut self, show: bool) -> Self {
526 self.taskbar = Some(show);
527 self
528 }
529
530 /// Requests the window to be of specific dimensions.
531 ///
532 /// If this is not set, some platform-specific dimensions will be used.
533 ///
534 /// Should be bigger than 0
535 /// Look at winit for more details
536 #[inline]
537 pub fn with_inner_size(mut self, size: impl Into<Vec2>) -> Self {
538 self.inner_size = Some(size.into());
539 self
540 }
541
542 /// Sets the minimum dimensions a window can have.
543 ///
544 /// If this is not set, the window will have no minimum dimensions (aside
545 /// from reserved).
546 ///
547 /// Should be bigger than 0
548 /// Look at winit for more details
549 #[inline]
550 pub fn with_min_inner_size(mut self, size: impl Into<Vec2>) -> Self {
551 self.min_inner_size = Some(size.into());
552 self
553 }
554
555 /// Sets the maximum dimensions a window can have.
556 ///
557 /// If this is not set, the window will have no maximum or will be set to
558 /// the primary monitor's dimensions by the platform.
559 ///
560 /// Should be bigger than 0
561 /// Look at winit for more details
562 #[inline]
563 pub fn with_max_inner_size(mut self, size: impl Into<Vec2>) -> Self {
564 self.max_inner_size = Some(size.into());
565 self
566 }
567
568 /// Sets whether clamp the window's size to monitor's size. The default is `true` on linux, otherwise it is `false`.
569 ///
570 /// Note: On some Linux systems, a window size larger than the monitor causes crashes
571 #[inline]
572 pub fn with_clamp_size_to_monitor_size(mut self, value: bool) -> Self {
573 self.clamp_size_to_monitor_size = Some(value);
574 self
575 }
576
577 /// Does not work on X11.
578 #[inline]
579 pub fn with_close_button(mut self, value: bool) -> Self {
580 self.close_button = Some(value);
581 self
582 }
583
584 /// Does not work on X11.
585 #[inline]
586 pub fn with_minimize_button(mut self, value: bool) -> Self {
587 self.minimize_button = Some(value);
588 self
589 }
590
591 /// Does not work on X11.
592 #[inline]
593 pub fn with_maximize_button(mut self, value: bool) -> Self {
594 self.maximize_button = Some(value);
595 self
596 }
597
598 /// On Windows: enable drag and drop support. Drag and drop can
599 /// not be disabled on other platforms.
600 ///
601 /// See [winit's documentation][drag_and_drop] for information on why you
602 /// might want to disable this on windows.
603 ///
604 /// [drag_and_drop]: https://docs.rs/winit/latest/x86_64-pc-windows-msvc/winit/platform/windows/trait.WindowAttributesExtWindows.html#tymethod.with_drag_and_drop
605 #[inline]
606 pub fn with_drag_and_drop(mut self, value: bool) -> Self {
607 self.drag_and_drop = Some(value);
608 self
609 }
610
611 /// The initial "outer" position of the window,
612 /// i.e. where the top-left corner of the frame/chrome should be.
613 ///
614 /// **`eframe` notes**:
615 ///
616 /// - **iOS:** Sets the top left coordinates of the window in the screen space coordinate system.
617 /// - **Web:** Sets the top-left coordinates relative to the viewport. Doesn't account for CSS
618 /// [`transform`].
619 /// - **Android / Wayland:** Unsupported.
620 ///
621 /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform
622 #[inline]
623 pub fn with_position(mut self, pos: impl Into<Pos2>) -> Self {
624 self.position = Some(pos.into());
625 self
626 }
627
628 /// ### On Wayland
629 /// On Wayland this sets the Application ID for the window.
630 ///
631 /// The application ID is used in several places of the compositor, e.g. for
632 /// grouping windows of the same application. It is also important for
633 /// connecting the configuration of a `.desktop` file with the window, by
634 /// using the application ID as file name. This allows e.g. a proper icon
635 /// handling under Wayland.
636 ///
637 /// See [Waylands XDG shell documentation][xdg-shell] for more information
638 /// on this Wayland-specific option.
639 ///
640 /// The `app_id` should match the `.desktop` file distributed with your program.
641 ///
642 /// For details about application ID conventions, see the
643 /// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id)
644 ///
645 /// [xdg-shell]: https://wayland.app/protocols/xdg-shell#xdg_toplevel:request:set_app_id
646 ///
647 /// ### eframe
648 /// On eframe, the `app_id` of the root window is also used to determine
649 /// the storage location of persistence files.
650 #[inline]
651 pub fn with_app_id(mut self, app_id: impl Into<String>) -> Self {
652 self.app_id = Some(app_id.into());
653 self
654 }
655
656 /// Control if window is always-on-top, always-on-bottom, or neither.
657 ///
658 /// For platform compatibility see [`crate::viewport::WindowLevel`] documentation
659 #[inline]
660 pub fn with_window_level(mut self, level: WindowLevel) -> Self {
661 self.window_level = Some(level);
662 self
663 }
664
665 /// This window is always on top
666 ///
667 /// For platform compatibility see [`crate::viewport::WindowLevel`] documentation
668 #[inline]
669 pub fn with_always_on_top(self) -> Self {
670 self.with_window_level(WindowLevel::AlwaysOnTop)
671 }
672
673 /// On desktop: mouse clicks pass through the window, used for non-interactable overlays.
674 ///
675 /// Generally you would use this in conjunction with [`Self::with_transparent`]
676 /// and [`Self::with_always_on_top`].
677 #[inline]
678 pub fn with_mouse_passthrough(mut self, value: bool) -> Self {
679 self.mouse_passthrough = Some(value);
680 self
681 }
682
683 /// ### On X11
684 /// This sets the window type.
685 /// Maps directly to [`_NET_WM_WINDOW_TYPE`](https://specifications.freedesktop.org/wm/1.5/ar01s05.html#id-1.6.7).
686 #[inline]
687 pub fn with_window_type(mut self, value: X11WindowType) -> Self {
688 self.window_type = Some(value);
689 self
690 }
691
692 /// ### On X11
693 /// This sets the override-redirect flag. When this is set to true the window type should be specified.
694 /// Maps directly to [`Override-redirect windows`](https://specifications.freedesktop.org/wm/1.5/ar01s02.html#id-1.3.13).
695 #[inline]
696 pub fn with_override_redirect(mut self, value: bool) -> Self {
697 self.override_redirect = Some(value);
698 self
699 }
700
701 /// Place the window in borderless fullscreen on the monitor at `index`.
702 ///
703 /// The index refers to the order returned by winit's `available_monitors()`.
704 /// Works cross-platform (Windows, macOS, Linux X11 + Wayland). On Wayland
705 /// this is the only reliable way to target a specific output, since
706 /// absolute window positions are not exposed.
707 ///
708 /// If the index is out of range, the flag is ignored at window creation time.
709 #[inline]
710 pub fn with_monitor(mut self, index: usize) -> Self {
711 self.monitor = Some(index);
712 self
713 }
714
715 /// Update this `ViewportBuilder` with a delta,
716 /// returning a list of commands and a bool indicating if the window needs to be recreated.
717 #[must_use]
718 pub fn patch(&mut self, new_vp_builder: Self) -> (Vec<ViewportCommand>, bool) {
719 #![expect(clippy::useless_let_if_seq)] // False positive
720
721 let Self {
722 title: new_title,
723 app_id: new_app_id,
724 position: new_position,
725 inner_size: new_inner_size,
726 min_inner_size: new_min_inner_size,
727 max_inner_size: new_max_inner_size,
728 clamp_size_to_monitor_size: new_clamp_size_to_monitor_size,
729 fullscreen: new_fullscreen,
730 maximized: new_maximized,
731 resizable: new_resizable,
732 transparent: new_transparent,
733 decorations: new_decorations,
734 icon: new_icon,
735 active: new_active,
736 visible: new_visible,
737 drag_and_drop: new_drag_and_drop,
738 fullsize_content_view: new_fullsize_content_view,
739 movable_by_window_background: new_movable_by_window_background,
740 title_shown: new_title_shown,
741 titlebar_buttons_shown: new_titlebar_buttons_shown,
742 titlebar_shown: new_titlebar_shown,
743 has_shadow: new_has_shadow,
744 close_button: new_close_button,
745 minimize_button: new_minimize_button,
746 maximize_button: new_maximize_button,
747 window_level: new_window_level,
748 mouse_passthrough: new_mouse_passthrough,
749 taskbar: new_taskbar,
750 window_type: new_window_type,
751 override_redirect: new_override_redirect,
752 monitor: new_monitor,
753 } = new_vp_builder;
754
755 let mut commands = Vec::new();
756
757 if let Some(new_title) = new_title
758 && Some(&new_title) != self.title.as_ref()
759 {
760 self.title = Some(new_title.clone());
761 commands.push(ViewportCommand::Title(new_title));
762 }
763
764 if let Some(new_position) = new_position
765 && Some(new_position) != self.position
766 {
767 self.position = Some(new_position);
768 commands.push(ViewportCommand::OuterPosition(new_position));
769 }
770
771 if let Some(new_inner_size) = new_inner_size
772 && Some(new_inner_size) != self.inner_size
773 {
774 self.inner_size = Some(new_inner_size);
775 commands.push(ViewportCommand::InnerSize(new_inner_size));
776 }
777
778 if let Some(new_min_inner_size) = new_min_inner_size
779 && Some(new_min_inner_size) != self.min_inner_size
780 {
781 self.min_inner_size = Some(new_min_inner_size);
782 commands.push(ViewportCommand::MinInnerSize(new_min_inner_size));
783 }
784
785 if let Some(new_max_inner_size) = new_max_inner_size
786 && Some(new_max_inner_size) != self.max_inner_size
787 {
788 self.max_inner_size = Some(new_max_inner_size);
789 commands.push(ViewportCommand::MaxInnerSize(new_max_inner_size));
790 }
791
792 if let Some(new_fullscreen) = new_fullscreen
793 && Some(new_fullscreen) != self.fullscreen
794 {
795 self.fullscreen = Some(new_fullscreen);
796 commands.push(ViewportCommand::Fullscreen(new_fullscreen));
797 }
798
799 if let Some(new_maximized) = new_maximized
800 && Some(new_maximized) != self.maximized
801 {
802 self.maximized = Some(new_maximized);
803 commands.push(ViewportCommand::Maximized(new_maximized));
804 }
805
806 if let Some(new_resizable) = new_resizable
807 && Some(new_resizable) != self.resizable
808 {
809 self.resizable = Some(new_resizable);
810 commands.push(ViewportCommand::Resizable(new_resizable));
811 }
812
813 if let Some(new_transparent) = new_transparent
814 && Some(new_transparent) != self.transparent
815 {
816 self.transparent = Some(new_transparent);
817 commands.push(ViewportCommand::Transparent(new_transparent));
818 }
819
820 if let Some(new_decorations) = new_decorations
821 && Some(new_decorations) != self.decorations
822 {
823 self.decorations = Some(new_decorations);
824 commands.push(ViewportCommand::Decorations(new_decorations));
825 }
826
827 if let Some(new_icon) = new_icon {
828 let is_new = match &self.icon {
829 Some(existing) => !Arc::ptr_eq(&new_icon, existing),
830 None => true,
831 };
832
833 if is_new {
834 commands.push(ViewportCommand::Icon(Some(Arc::clone(&new_icon))));
835 self.icon = Some(new_icon);
836 }
837 }
838
839 if let Some(new_visible) = new_visible
840 && Some(new_visible) != self.visible
841 {
842 self.visible = Some(new_visible);
843 commands.push(ViewportCommand::Visible(new_visible));
844 }
845
846 if let Some(new_mouse_passthrough) = new_mouse_passthrough
847 && Some(new_mouse_passthrough) != self.mouse_passthrough
848 {
849 self.mouse_passthrough = Some(new_mouse_passthrough);
850 commands.push(ViewportCommand::MousePassthrough(new_mouse_passthrough));
851 }
852
853 if let Some(new_window_level) = new_window_level
854 && Some(new_window_level) != self.window_level
855 {
856 self.window_level = Some(new_window_level);
857 commands.push(ViewportCommand::WindowLevel(new_window_level));
858 }
859
860 // --------------------------------------------------------------
861 // Things we don't have commands for require a full window recreation.
862 // The reason we don't have commands for them is that `winit` doesn't support
863 // changing them without recreating the window.
864
865 let mut recreate_window = false;
866
867 if new_clamp_size_to_monitor_size.is_some()
868 && self.clamp_size_to_monitor_size != new_clamp_size_to_monitor_size
869 {
870 self.clamp_size_to_monitor_size = new_clamp_size_to_monitor_size;
871 recreate_window = true;
872 }
873
874 if new_active.is_some() && self.active != new_active {
875 self.active = new_active;
876 recreate_window = true;
877 }
878
879 if new_app_id.is_some() && self.app_id != new_app_id {
880 self.app_id = new_app_id;
881 recreate_window = true;
882 }
883
884 if new_close_button.is_some() && self.close_button != new_close_button {
885 self.close_button = new_close_button;
886 recreate_window = true;
887 }
888
889 if new_minimize_button.is_some() && self.minimize_button != new_minimize_button {
890 self.minimize_button = new_minimize_button;
891 recreate_window = true;
892 }
893
894 if new_maximize_button.is_some() && self.maximize_button != new_maximize_button {
895 self.maximize_button = new_maximize_button;
896 recreate_window = true;
897 }
898
899 if new_title_shown.is_some() && self.title_shown != new_title_shown {
900 self.title_shown = new_title_shown;
901 recreate_window = true;
902 }
903
904 if new_titlebar_buttons_shown.is_some()
905 && self.titlebar_buttons_shown != new_titlebar_buttons_shown
906 {
907 self.titlebar_buttons_shown = new_titlebar_buttons_shown;
908 recreate_window = true;
909 }
910
911 if new_titlebar_shown.is_some() && self.titlebar_shown != new_titlebar_shown {
912 self.titlebar_shown = new_titlebar_shown;
913 recreate_window = true;
914 }
915
916 if new_has_shadow.is_some() && self.has_shadow != new_has_shadow {
917 self.has_shadow = new_has_shadow;
918 recreate_window = true;
919 }
920
921 if new_taskbar.is_some() && self.taskbar != new_taskbar {
922 self.taskbar = new_taskbar;
923 recreate_window = true;
924 }
925
926 if new_fullsize_content_view.is_some()
927 && self.fullsize_content_view != new_fullsize_content_view
928 {
929 self.fullsize_content_view = new_fullsize_content_view;
930 recreate_window = true;
931 }
932
933 if new_movable_by_window_background.is_some()
934 && self.movable_by_window_background != new_movable_by_window_background
935 {
936 self.movable_by_window_background = new_movable_by_window_background;
937 recreate_window = true;
938 }
939
940 if new_drag_and_drop.is_some() && self.drag_and_drop != new_drag_and_drop {
941 self.drag_and_drop = new_drag_and_drop;
942 recreate_window = true;
943 }
944
945 if new_window_type.is_some() && self.window_type != new_window_type {
946 self.window_type = new_window_type;
947 recreate_window = true;
948 }
949
950 if new_override_redirect.is_some() && self.override_redirect != new_override_redirect {
951 self.override_redirect = new_override_redirect;
952 recreate_window = true;
953 }
954
955 if let Some(new_monitor) = new_monitor
956 && Some(new_monitor) != self.monitor
957 {
958 self.monitor = Some(new_monitor);
959 commands.push(ViewportCommand::SetMonitor(new_monitor));
960 }
961
962 (commands, recreate_window)
963 }
964}
965
966/// For winit platform compatibility, see [`winit::WindowLevel` documentation](https://docs.rs/winit/latest/winit/window/enum.WindowLevel.html#platform-specific)
967#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
968#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
969pub enum WindowLevel {
970 #[default]
971 Normal,
972 AlwaysOnBottom,
973 AlwaysOnTop,
974}
975
976#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
977#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
978pub enum X11WindowType {
979 /// This is a normal, top-level window.
980 #[default]
981 Normal,
982
983 /// A desktop feature. This can include a single window containing desktop icons with the same dimensions as the
984 /// screen, allowing the desktop environment to have full control of the desktop, without the need for proxying
985 /// root window clicks.
986 Desktop,
987
988 /// A dock or panel feature. Typically a Window Manager would keep such windows on top of all other windows.
989 Dock,
990
991 /// Toolbar windows. "Torn off" from the main application.
992 Toolbar,
993
994 /// Pinnable menu windows. "Torn off" from the main application.
995 Menu,
996
997 /// A small persistent utility window, such as a palette or toolbox.
998 Utility,
999
1000 /// The window is a splash screen displayed as an application is starting up.
1001 Splash,
1002
1003 /// This is a dialog window.
1004 Dialog,
1005
1006 /// A dropdown menu that usually appears when the user clicks on an item in a menu bar.
1007 /// This property is typically used on override-redirect windows.
1008 DropdownMenu,
1009
1010 /// A popup menu that usually appears when the user right clicks on an object.
1011 /// This property is typically used on override-redirect windows.
1012 PopupMenu,
1013
1014 /// A tooltip window. Usually used to show additional information when hovering over an object with the cursor.
1015 /// This property is typically used on override-redirect windows.
1016 Tooltip,
1017
1018 /// The window is a notification.
1019 /// This property is typically used on override-redirect windows.
1020 Notification,
1021
1022 /// This should be used on the windows that are popped up by combo boxes.
1023 /// This property is typically used on override-redirect windows.
1024 Combo,
1025
1026 /// This indicates the window is being dragged.
1027 /// This property is typically used on override-redirect windows.
1028 Dnd,
1029}
1030
1031#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
1032#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
1033pub enum IMEPurpose {
1034 #[default]
1035 Normal,
1036 Password,
1037 Terminal,
1038}
1039
1040#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1041#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
1042pub enum SystemTheme {
1043 #[default]
1044 SystemDefault,
1045 Light,
1046 Dark,
1047}
1048
1049#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1050#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
1051pub enum CursorGrab {
1052 #[default]
1053 None,
1054 Confined,
1055 Locked,
1056}
1057
1058#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1059#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
1060pub enum ResizeDirection {
1061 North,
1062 South,
1063 East,
1064 West,
1065 NorthEast,
1066 SouthEast,
1067 NorthWest,
1068 SouthWest,
1069}
1070
1071/// An output [viewport](crate::viewport)-command from egui to the backend, e.g. to change the window title or size.
1072///
1073/// You can send a [`ViewportCommand`] to the viewport with [`Context::send_viewport_cmd`].
1074///
1075/// See [`crate::viewport`] for how to build new viewports (native windows).
1076///
1077/// All coordinates are in logical points.
1078///
1079/// [`ViewportCommand`] is essentially a way to diff [`ViewportBuilder`]s.
1080///
1081/// Only commands specific to a viewport are part of [`ViewportCommand`].
1082/// Other commands should be put in [`crate::OutputCommand`].
1083#[derive(Clone, Debug, PartialEq, Eq)]
1084#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
1085pub enum ViewportCommand {
1086 /// Request this viewport to be closed.
1087 ///
1088 /// For the root viewport, this usually results in the application shutting down.
1089 /// For other viewports, the [`crate::ViewportInfo::close_requested`] flag will be set.
1090 Close,
1091
1092 /// Cancel the closing that was signaled by [`crate::ViewportInfo::close_requested`].
1093 CancelClose,
1094
1095 /// Set the window title.
1096 Title(String),
1097
1098 /// Turn the window transparent or not.
1099 Transparent(bool),
1100
1101 /// Set the visibility of the window.
1102 Visible(bool),
1103
1104 /// Moves the window with the left mouse button until the button is released.
1105 ///
1106 /// There's no guarantee that this will work unless the left mouse button was pressed
1107 /// immediately before this function is called.
1108 StartDrag,
1109
1110 /// Set the outer position of the viewport, i.e. moves the window.
1111 OuterPosition(Pos2),
1112
1113 /// Should be bigger than 0
1114 InnerSize(Vec2),
1115
1116 /// Should be bigger than 0
1117 MinInnerSize(Vec2),
1118
1119 /// Should be bigger than 0
1120 MaxInnerSize(Vec2),
1121
1122 /// Should be bigger than 0
1123 ResizeIncrements(Option<Vec2>),
1124
1125 /// Begin resizing the viewport with the left mouse button until the button is released.
1126 ///
1127 /// There's no guarantee that this will work unless the left mouse button was pressed
1128 /// immediately before this function is called.
1129 BeginResize(ResizeDirection),
1130
1131 /// Can the window be resized?
1132 Resizable(bool),
1133
1134 /// Set which window buttons are enabled
1135 EnableButtons {
1136 close: bool,
1137 minimized: bool,
1138 maximize: bool,
1139 },
1140 Minimized(bool),
1141
1142 /// Maximize or unmaximize window.
1143 Maximized(bool),
1144
1145 /// Turn borderless fullscreen on/off.
1146 Fullscreen(bool),
1147
1148 /// Move the window to borderless fullscreen on the monitor at the given index.
1149 ///
1150 /// Index refers to winit's `available_monitors()` order. If out of range, the
1151 /// command is ignored (logged as a warning).
1152 SetMonitor(usize),
1153
1154 /// Show window decorations, i.e. the chrome around the content
1155 /// with the title bar, close buttons, resize handles, etc.
1156 Decorations(bool),
1157
1158 /// Set window to be always-on-top, always-on-bottom, or neither.
1159 WindowLevel(WindowLevel),
1160
1161 /// The window icon.
1162 Icon(Option<Arc<IconData>>),
1163
1164 /// Set the IME cursor editing area.
1165 IMERect(crate::Rect),
1166 IMEAllowed(bool),
1167 IMEPurpose(IMEPurpose),
1168
1169 /// Bring the window into focus (native only).
1170 ///
1171 /// This command puts the window on top of other applications and takes input focus away from them,
1172 /// which, if unexpected, will disturb the user.
1173 ///
1174 /// Has no effect on Wayland, or if the window is minimized or invisible.
1175 Focus,
1176
1177 /// If the window is unfocused, attract the user's attention (native only).
1178 ///
1179 /// Typically, this means that the window will flash on the taskbar, or bounce, until it is interacted with.
1180 ///
1181 /// When the window comes into focus, or if `None` is passed, the attention request will be automatically reset.
1182 ///
1183 /// See [winit's documentation][user_attention_details] for platform-specific effect details.
1184 ///
1185 /// [user_attention_details]: https://docs.rs/winit/latest/winit/window/enum.UserAttentionType.html
1186 RequestUserAttention(crate::UserAttentionType),
1187
1188 SetTheme(SystemTheme),
1189
1190 ContentProtected(bool),
1191
1192 /// Will probably not work as expected!
1193 CursorPosition(Pos2),
1194
1195 CursorGrab(CursorGrab),
1196
1197 CursorVisible(bool),
1198
1199 /// Enable mouse pass-through: mouse clicks pass through the window, used for non-interactable overlays.
1200 MousePassthrough(bool),
1201
1202 /// Take a screenshot of the next frame after this and pass it to a callback.
1203 ///
1204 /// Use [`crate::Context::request_screenshot`] for a convenient way to send this command.
1205 Screenshot(crate::ScreenshotCallback),
1206
1207 /// Request cut of the current selection
1208 ///
1209 /// This is equivalent to the system keyboard shortcut for cut (e.g. CTRL + X).
1210 RequestCut,
1211
1212 /// Request a copy of the current selection.
1213 ///
1214 /// This is equivalent to the system keyboard shortcut for copy (e.g. CTRL + C).
1215 RequestCopy,
1216
1217 /// Request a paste from the clipboard to the current focused `TextEdit` if any.
1218 ///
1219 /// This is equivalent to the system keyboard shortcut for paste (e.g. CTRL + V).
1220 RequestPaste,
1221
1222 /// Run `eframe::App::ui` and paint a frame, even though this window is hidden.
1223 ///
1224 /// Integrations run no pass at all while a window is minimized or occluded
1225 /// (see [`crate::ViewportInfo::visible`]), since nothing would be shown: they run only the
1226 /// app logic, via [`crate::Context::run_logic`]. This asks for the full thing — ui and
1227 /// paint — with nothing on screen to show for it.
1228 ///
1229 /// This is what lets a tool drive an app that sits in the background. `egui_inspection`
1230 /// (and the `egui_mcp` server on top of it) sends this with every request it serves,
1231 /// because each of them needs the ui to run: a screenshot needs the painted pixels, the
1232 /// widget tree is what the pass produces, and injected clicks and keystrokes are only
1233 /// *applied* by a pass. Without it an inspector attached to a backgrounded app can only
1234 /// time out until a human brings the window up again.
1235 ///
1236 /// A pending [`Self::Screenshot`] asks for the same thing, so it needs no company.
1237 ///
1238 /// Holds for one frame; send it again for another.
1239 RequestPaintWhileHidden,
1240}
1241
1242impl ViewportCommand {
1243 /// Construct a command to center the viewport on the monitor, if possible.
1244 pub fn center_on_screen(ctx: &crate::Context) -> Option<Self> {
1245 ctx.input(|i| {
1246 let outer_rect = i.viewport().outer_rect?;
1247 let size = outer_rect.size();
1248 let monitor_size = i.viewport().monitor_size?;
1249 if 1.0 < monitor_size.x && 1.0 < monitor_size.y {
1250 let x = (monitor_size.x - size.x) * 0.5;
1251 let y = (monitor_size.y - size.y) * 0.5;
1252 Some(Self::OuterPosition([x, y].into()))
1253 } else {
1254 None
1255 }
1256 })
1257 }
1258
1259 /// This command requires the parent viewport to repaint.
1260 pub fn requires_parent_repaint(&self) -> bool {
1261 self == &Self::Close
1262 }
1263}
1264
1265// ----------------------------------------------------------------------------
1266
1267/// Describes a viewport, i.e. a native window.
1268///
1269/// This is returned by [`crate::Context::run_ui`] on each frame, and should be applied
1270/// by the integration.
1271#[derive(Clone)]
1272pub struct ViewportOutput {
1273 /// Id of our parent viewport.
1274 pub parent: ViewportId,
1275
1276 /// What type of viewport are we?
1277 ///
1278 /// This will never be [`ViewportClass::EmbeddedWindow`],
1279 /// since those don't result in real viewports.
1280 pub class: ViewportClass,
1281
1282 /// The window attributes such as title, position, size, etc.
1283 ///
1284 /// Use this when first constructing the native window.
1285 /// Also check for changes in it using [`ViewportBuilder::patch`],
1286 /// and apply them as needed.
1287 pub builder: ViewportBuilder,
1288
1289 /// The user-code that shows the GUI, used for deferred viewports.
1290 ///
1291 /// `None` for immediate viewports and the ROOT viewport.
1292 pub viewport_ui_cb: Option<Arc<DeferredViewportUiCallback>>,
1293
1294 /// Commands to change the viewport, e.g. window title and size.
1295 pub commands: Vec<ViewportCommand>,
1296
1297 /// Schedule a repaint of this viewport after this delay.
1298 ///
1299 /// It is preferable to instead install a [`Context::set_request_repaint_callback`],
1300 /// but if you haven't, you can use this instead.
1301 ///
1302 /// If the duration is zero, schedule a repaint immediately.
1303 pub repaint_delay: core::time::Duration,
1304}
1305
1306impl ViewportOutput {
1307 /// Add on new output.
1308 pub fn append(&mut self, newer: Self) {
1309 let Self {
1310 parent,
1311 class,
1312 builder,
1313 viewport_ui_cb,
1314 mut commands,
1315 repaint_delay,
1316 } = newer;
1317
1318 self.parent = parent;
1319 self.class = class;
1320 let _ = self.builder.patch(builder); // we ignore the returned command, because `self.builder` will be the basis of a new patch
1321 self.viewport_ui_cb = viewport_ui_cb;
1322 self.commands.append(&mut commands);
1323 self.repaint_delay = self.repaint_delay.min(repaint_delay);
1324 }
1325}
1326
1327/// Viewport for immediate rendering.
1328pub struct ImmediateViewport<'a> {
1329 /// Id of us and our parent.
1330 pub ids: ViewportIdPair,
1331
1332 pub builder: ViewportBuilder,
1333
1334 /// The user-code that shows the GUI.
1335 pub viewport_ui_cb: Box<dyn FnMut(&mut Ui) + 'a>,
1336}