1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
//! egui supports multiple viewports, corresponding to multiple native windows.
//!
//! Not all egui backends support multiple viewports, but `eframe` native does
//! (but not on web).
//!
//! You can spawn a new viewport using [`Context::show_viewport_deferred`] and [`Context::show_viewport_immediate`].
//! These needs to be called every frame the viewport should be visible.
//!
//! This is implemented by the native `eframe` backend, but not the web one.
//!
//! ## Viewport classes
//! The viewports form a tree of parent-child relationships.
//!
//! There are different classes of viewports.
//!
//! ### Root viewport
//! The root viewport is the original viewport, and cannot be closed without closing the application.
//!
//! ### Deferred viewports
//! These are created with [`Context::show_viewport_deferred`].
//! Deferred viewports take a closure that is called by the integration at a later time, perhaps multiple times.
//! Deferred viewports are repainted independenantly of the parent viewport.
//! This means communication with them needs to be done via channels, or `Arc/Mutex`.
//!
//! This is the most performant type of child viewport, though a bit more cumbersome to work with compared to immediate viewports.
//!
//! ### Immediate viewports
//! These are created with [`Context::show_viewport_immediate`].
//! Immediate viewports take a `FnOnce` closure, similar to other egui functions, and is called immediately.
//! 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.
//! 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.
//!
//! In short: immediate viewports are simpler to use, but can waste a lot of CPU time.
//!
//! ### Embedded viewports
//! These are not real, independent viewports, but is a fallback mode for when the integration does not support real viewports. In your callback is called with [`ViewportClass::Embedded`] it means you need to create a [`crate::Window`] to wrap your ui in, which will then be embedded in the parent viewport, unable to escape it.
//!
//!
//! ## Using the viewports
//! Only one viewport is active at any one time, identified with [`Context::viewport_id`].
//! You can modify the current (change the title, resize the window, etc) by sending
//! a [`ViewportCommand`] to it using [`Context::send_viewport_cmd`].
//! You can interact with other viewports using [`Context::send_viewport_cmd_to`].
//!
//! There is an example in <https://github.com/emilk/egui/tree/master/examples/multiple_viewports/src/main.rs>.
//!
//! You can find all available viewports in [`crate::RawInput::viewports`] and the active viewport in
//! [`crate::InputState::viewport`]:
//!
//! ```no_run
//! # let ctx = &egui::Context::default();
//! ctx.input(|i| {
//! dbg!(&i.viewport()); // Current viewport
//! dbg!(&i.raw.viewports); // All viewports
//! });
//! ```
//!
//! ## For integrations
//! * There is a [`crate::InputState::viewport`] with information about the current viewport.
//! * There is a [`crate::RawInput::viewports`] with information about all viewports.
//! * The repaint callback set by [`Context::set_request_repaint_callback`] points to which viewport should be repainted.
//! * [`crate::FullOutput::viewport_output`] is a list of viewports which should result in their own independent windows.
//! * To support immediate viewports you need to call [`Context::set_immediate_viewport_renderer`].
//! * If you support viewports, you need to call [`Context::set_embed_viewports`] with `false`, or all new viewports will be embedded (the default behavior).
//!
//! ## Future work
//! There are several more things related to viewports that we want to add.
//! Read more at <https://github.com/emilk/egui/issues/3556>.
use std::sync::Arc;
use epaint::{Pos2, Vec2};
use crate::{Context, Id};
// ----------------------------------------------------------------------------
/// The different types of viewports supported by egui.
#[derive(Clone, Copy, Default, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum ViewportClass {
/// The root viewport; i.e. the original window.
#[default]
Root,
/// A viewport run independently from the parent viewport.
///
/// This is the preferred type of viewport from a performance perspective.
///
/// Create these with [`crate::Context::show_viewport_deferred`].
Deferred,
/// A viewport run inside the parent viewport.
///
/// This is the easier type of viewport to use, but it is less performant
/// at it requires both parent and child to repaint if any one of them needs repainting,
/// which effectively produces double work for two viewports, and triple work for three viewports, etc.
///
/// Create these with [`crate::Context::show_viewport_immediate`].
Immediate,
/// The fallback, when the egui integration doesn't support viewports,
/// or [`crate::Context::embed_viewports`] is set to `true`.
Embedded,
}
// ----------------------------------------------------------------------------
/// A unique identifier of a viewport.
///
/// This is returned by [`Context::viewport_id`] and [`Context::parent_viewport_id`].
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct ViewportId(pub Id);
impl Default for ViewportId {
#[inline]
fn default() -> Self {
Self::ROOT
}
}
impl std::fmt::Debug for ViewportId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.short_debug_format().fmt(f)
}
}
impl ViewportId {
/// The `ViewportId` of the root viewport.
pub const ROOT: Self = Self(Id::NULL);
#[inline]
pub fn from_hash_of(source: impl std::hash::Hash) -> Self {
Self(Id::new(source))
}
}
impl From<ViewportId> for Id {
#[inline]
fn from(id: ViewportId) -> Self {
id.0
}
}
impl nohash_hasher::IsEnabled for ViewportId {}
/// A fast hash set of [`ViewportId`].
pub type ViewportIdSet = nohash_hasher::IntSet<ViewportId>;
/// A fast hash map from [`ViewportId`] to `T`.
pub type ViewportIdMap<T> = nohash_hasher::IntMap<ViewportId, T>;
// ----------------------------------------------------------------------------
/// Image data for an application icon.
///
/// Use a square image, e.g. 256x256 pixels.
/// You can use a transparent background.
#[derive(Clone, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct IconData {
/// RGBA pixels, with separate/unmultiplied alpha.
pub rgba: Vec<u8>,
/// Image width. This should be a multiple of 4.
pub width: u32,
/// Image height. This should be a multiple of 4.
pub height: u32,
}
impl IconData {
#[inline]
pub fn is_empty(&self) -> bool {
self.rgba.is_empty()
}
}
impl std::fmt::Debug for IconData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("IconData")
.field("width", &self.width)
.field("height", &self.height)
.finish_non_exhaustive()
}
}
impl From<IconData> for epaint::ColorImage {
fn from(icon: IconData) -> Self {
crate::profile_function!();
let IconData {
rgba,
width,
height,
} = icon;
Self::from_rgba_premultiplied([width as usize, height as usize], &rgba)
}
}
impl From<&IconData> for epaint::ColorImage {
fn from(icon: &IconData) -> Self {
crate::profile_function!();
let IconData {
rgba,
width,
height,
} = icon;
Self::from_rgba_premultiplied([*width as usize, *height as usize], rgba)
}
}
// ----------------------------------------------------------------------------
/// A pair of [`ViewportId`], used to identify a viewport and its parent.
#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct ViewportIdPair {
pub this: ViewportId,
pub parent: ViewportId,
}
impl Default for ViewportIdPair {
#[inline]
fn default() -> Self {
Self::ROOT
}
}
impl ViewportIdPair {
/// The `ViewportIdPair` of the root viewport, which is its own parent.
pub const ROOT: Self = Self {
this: ViewportId::ROOT,
parent: ViewportId::ROOT,
};
#[inline]
pub fn from_self_and_parent(this: ViewportId, parent: ViewportId) -> Self {
Self { this, parent }
}
}
/// The user-code that shows the ui in the viewport, used for deferred viewports.
pub type DeferredViewportUiCallback = dyn Fn(&Context) + Sync + Send;
/// Render the given viewport, calling the given ui callback.
pub type ImmediateViewportRendererCallback = dyn for<'a> Fn(&Context, ImmediateViewport<'a>);
/// Control the building of a new egui viewport (i.e. native window).
///
/// See [`crate::viewport`] for how to build new viewports (native windows).
///
/// The fields are public, but you should use the builder pattern to set them,
/// and that's where you'll find the documentation too.
///
/// Since egui is immediate mode, `ViewportBuilder` is accumulative in nature.
/// Setting any option to `None` means "keep the current value",
/// or "Use the default" if it is the first call.
///
/// The default values are implementation defined, so you may want to explicitly
/// configure the size of the window, and what buttons are shown.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[allow(clippy::option_option)]
pub struct ViewportBuilder {
/// The title of the viewport.
/// `eframe` will use this as the title of the native window.
pub title: Option<String>,
/// This is wayland only. See [`Self::with_app_id`].
pub app_id: Option<String>,
/// The desired outer position of the window.
pub position: Option<Pos2>,
pub inner_size: Option<Vec2>,
pub min_inner_size: Option<Vec2>,
pub max_inner_size: Option<Vec2>,
pub fullscreen: Option<bool>,
pub maximized: Option<bool>,
pub resizable: Option<bool>,
pub transparent: Option<bool>,
pub decorations: Option<bool>,
pub icon: Option<Arc<IconData>>,
pub active: Option<bool>,
pub visible: Option<bool>,
pub drag_and_drop: Option<bool>,
// macOS:
pub fullsize_content_view: Option<bool>,
pub title_shown: Option<bool>,
pub titlebar_buttons_shown: Option<bool>,
pub titlebar_shown: Option<bool>,
pub close_button: Option<bool>,
pub minimize_button: Option<bool>,
pub maximize_button: Option<bool>,
pub window_level: Option<WindowLevel>,
pub mouse_passthrough: Option<bool>,
}
impl ViewportBuilder {
/// Sets the initial title of the window in the title bar.
///
/// Look at winit for more details
#[inline]
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
/// Sets whether the window should have a border, a title bar, etc.
///
/// The default is `true`.
///
/// Look at winit for more details
#[inline]
pub fn with_decorations(mut self, decorations: bool) -> Self {
self.decorations = Some(decorations);
self
}
/// Sets whether the window should be put into fullscreen upon creation.
///
/// The default is `None`.
///
/// Look at winit for more details
/// This will use borderless
#[inline]
pub fn with_fullscreen(mut self, fullscreen: bool) -> Self {
self.fullscreen = Some(fullscreen);
self
}
/// Request that the window is maximized upon creation.
///
/// The default is `false`.
///
/// Look at winit for more details
#[inline]
pub fn with_maximized(mut self, maximized: bool) -> Self {
self.maximized = Some(maximized);
self
}
/// Sets whether the window is resizable or not.
///
/// The default is `true`.
///
/// Look at winit for more details
#[inline]
pub fn with_resizable(mut self, resizable: bool) -> Self {
self.resizable = Some(resizable);
self
}
/// Sets whether the background of the window should be transparent.
///
/// You should avoid having a [`crate::CentralPanel`], or make sure its frame is also transparent.
///
/// In `eframe` you control the transparency with `eframe::App::clear_color()`.
///
/// If this is `true`, writing colors with alpha values different than
/// `1.0` will produce a transparent window. On some platforms this
/// is more of a hint for the system and you'd still have the alpha
/// buffer.
///
/// The default is `false`.
/// If this is not working, it's because the graphic context doesn't support transparency,
/// you will need to set the transparency in the eframe!
#[inline]
pub fn with_transparent(mut self, transparent: bool) -> Self {
self.transparent = Some(transparent);
self
}
/// The application icon, e.g. in the Windows task bar or the alt-tab menu.
///
/// The default icon is a white `e` on a black background (for "egui" or "eframe").
/// If you prefer the OS default, set this to `None`.
#[inline]
pub fn with_icon(mut self, icon: impl Into<Arc<IconData>>) -> Self {
self.icon = Some(icon.into());
self
}
/// Whether the window will be initially focused or not.
///
/// The window should be assumed as not focused by default
///
/// ## Platform-specific:
///
/// **Android / iOS / X11 / Wayland / Orbital:** Unsupported.
///
/// Look at winit for more details
#[inline]
pub fn with_active(mut self, active: bool) -> Self {
self.active = Some(active);
self
}
/// Sets whether the window will be initially visible or hidden.
///
/// The default is to show the window.
///
/// Look at winit for more details
#[inline]
pub fn with_visible(mut self, visible: bool) -> Self {
self.visible = Some(visible);
self
}
/// macOS: Makes the window content appear behind the titlebar.
///
/// You often want to combine this with [`Self::with_titlebar_shown`]
/// and [`Self::with_title_shown`].
#[inline]
pub fn with_fullsize_content_view(mut self, value: bool) -> Self {
self.fullsize_content_view = Some(value);
self
}
/// macOS: Set to `false` to hide the window title.
#[inline]
pub fn with_title_shown(mut self, title_shown: bool) -> Self {
self.title_shown = Some(title_shown);
self
}
/// macOS: Set to `false` to hide the titlebar button (close, minimize, maximize)
#[inline]
pub fn with_titlebar_buttons_shown(mut self, titlebar_buttons_shown: bool) -> Self {
self.titlebar_buttons_shown = Some(titlebar_buttons_shown);
self
}
/// macOS: Set to `false` to make the titlebar transparent, allowing the content to appear behind it.
#[inline]
pub fn with_titlebar_shown(mut self, shown: bool) -> Self {
self.titlebar_shown = Some(shown);
self
}
/// Requests the window to be of specific dimensions.
///
/// If this is not set, some platform-specific dimensions will be used.
///
/// Should be bigger than 0
/// Look at winit for more details
#[inline]
pub fn with_inner_size(mut self, size: impl Into<Vec2>) -> Self {
self.inner_size = Some(size.into());
self
}
/// Sets the minimum dimensions a window can have.
///
/// If this is not set, the window will have no minimum dimensions (aside
/// from reserved).
///
/// Should be bigger than 0
/// Look at winit for more details
#[inline]
pub fn with_min_inner_size(mut self, size: impl Into<Vec2>) -> Self {
self.min_inner_size = Some(size.into());
self
}
/// Sets the maximum dimensions a window can have.
///
/// If this is not set, the window will have no maximum or will be set to
/// the primary monitor's dimensions by the platform.
///
/// Should be bigger than 0
/// Look at winit for more details
#[inline]
pub fn with_max_inner_size(mut self, size: impl Into<Vec2>) -> Self {
self.max_inner_size = Some(size.into());
self
}
/// Does not work on X11.
#[inline]
pub fn with_close_button(mut self, value: bool) -> Self {
self.close_button = Some(value);
self
}
/// Does not work on X11.
#[inline]
pub fn with_minimize_button(mut self, value: bool) -> Self {
self.minimize_button = Some(value);
self
}
/// Does not work on X11.
#[inline]
pub fn with_maximize_button(mut self, value: bool) -> Self {
self.maximize_button = Some(value);
self
}
/// On Windows: enable drag and drop support. Drag and drop can
/// not be disabled on other platforms.
///
/// See [winit's documentation][drag_and_drop] for information on why you
/// might want to disable this on windows.
///
/// [drag_and_drop]: https://docs.rs/winit/latest/x86_64-pc-windows-msvc/winit/platform/windows/trait.WindowBuilderExtWindows.html#tymethod.with_drag_and_drop
#[inline]
pub fn with_drag_and_drop(mut self, value: bool) -> Self {
self.drag_and_drop = Some(value);
self
}
/// The initial "outer" position of the window,
/// i.e. where the top-left corner of the frame/chrome should be.
#[inline]
pub fn with_position(mut self, pos: impl Into<Pos2>) -> Self {
self.position = Some(pos.into());
self
}
/// ### On Wayland
/// On Wayland this sets the Application ID for the window.
///
/// The application ID is used in several places of the compositor, e.g. for
/// grouping windows of the same application. It is also important for
/// connecting the configuration of a `.desktop` file with the window, by
/// using the application ID as file name. This allows e.g. a proper icon
/// handling under Wayland.
///
/// See [Waylands XDG shell documentation][xdg-shell] for more information
/// on this Wayland-specific option.
///
/// The `app_id` should match the `.desktop` file distributed with your program.
///
/// For details about application ID conventions, see the
/// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id)
///
/// [xdg-shell]: https://wayland.app/protocols/xdg-shell#xdg_toplevel:request:set_app_id
///
/// ### eframe
/// On eframe, the `app_id` of the root window is also used to determine
/// the storage location of persistence files.
#[inline]
pub fn with_app_id(mut self, app_id: impl Into<String>) -> Self {
self.app_id = Some(app_id.into());
self
}
/// Control if window is always-on-top, always-on-bottom, or neither.
#[inline]
pub fn with_window_level(mut self, level: WindowLevel) -> Self {
self.window_level = Some(level);
self
}
/// This window is always on top
#[inline]
pub fn with_always_on_top(self) -> Self {
self.with_window_level(WindowLevel::AlwaysOnTop)
}
/// On desktop: mouse clicks pass through the window, used for non-interactable overlays.
///
/// Generally you would use this in conjunction with [`Self::with_transparent`]
/// and [`Self::with_always_on_top`].
#[inline]
pub fn with_mouse_passthrough(mut self, value: bool) -> Self {
self.mouse_passthrough = Some(value);
self
}
/// Update this `ViewportBuilder` with a delta,
/// returning a list of commands and a bool indicating if the window needs to be recreated.
#[must_use]
pub fn patch(&mut self, new_vp_builder: Self) -> (Vec<ViewportCommand>, bool) {
let Self {
title: new_title,
app_id: new_app_id,
position: new_position,
inner_size: new_inner_size,
min_inner_size: new_min_inner_size,
max_inner_size: new_max_inner_size,
fullscreen: new_fullscreen,
maximized: new_maximized,
resizable: new_resizable,
transparent: new_transparent,
decorations: new_decorations,
icon: new_icon,
active: new_active,
visible: new_visible,
drag_and_drop: new_drag_and_drop,
fullsize_content_view: new_fullsize_content_view,
title_shown: new_title_shown,
titlebar_buttons_shown: new_titlebar_buttons_shown,
titlebar_shown: new_titlebar_shown,
close_button: new_close_button,
minimize_button: new_minimize_button,
maximize_button: new_maximize_button,
window_level: new_window_level,
mouse_passthrough: new_mouse_passthrough,
} = new_vp_builder;
let mut commands = Vec::new();
if let Some(new_title) = new_title {
if Some(&new_title) != self.title.as_ref() {
self.title = Some(new_title.clone());
commands.push(ViewportCommand::Title(new_title));
}
}
if let Some(new_position) = new_position {
if Some(new_position) != self.position {
self.position = Some(new_position);
commands.push(ViewportCommand::OuterPosition(new_position));
}
}
if let Some(new_inner_size) = new_inner_size {
if Some(new_inner_size) != self.inner_size {
self.inner_size = Some(new_inner_size);
commands.push(ViewportCommand::InnerSize(new_inner_size));
}
}
if let Some(new_min_inner_size) = new_min_inner_size {
if Some(new_min_inner_size) != self.min_inner_size {
self.min_inner_size = Some(new_min_inner_size);
commands.push(ViewportCommand::MinInnerSize(new_min_inner_size));
}
}
if let Some(new_max_inner_size) = new_max_inner_size {
if Some(new_max_inner_size) != self.max_inner_size {
self.max_inner_size = Some(new_max_inner_size);
commands.push(ViewportCommand::MaxInnerSize(new_max_inner_size));
}
}
if let Some(new_fullscreen) = new_fullscreen {
if Some(new_fullscreen) != self.fullscreen {
self.fullscreen = Some(new_fullscreen);
commands.push(ViewportCommand::Fullscreen(new_fullscreen));
}
}
if let Some(new_maximized) = new_maximized {
if Some(new_maximized) != self.maximized {
self.maximized = Some(new_maximized);
commands.push(ViewportCommand::Maximized(new_maximized));
}
}
if let Some(new_resizable) = new_resizable {
if Some(new_resizable) != self.resizable {
self.resizable = Some(new_resizable);
commands.push(ViewportCommand::Resizable(new_resizable));
}
}
if let Some(new_transparent) = new_transparent {
if Some(new_transparent) != self.transparent {
self.transparent = Some(new_transparent);
commands.push(ViewportCommand::Transparent(new_transparent));
}
}
if let Some(new_decorations) = new_decorations {
if Some(new_decorations) != self.decorations {
self.decorations = Some(new_decorations);
commands.push(ViewportCommand::Decorations(new_decorations));
}
}
if let Some(new_icon) = new_icon {
let is_new = match &self.icon {
Some(existing) => !Arc::ptr_eq(&new_icon, existing),
None => true,
};
if is_new {
commands.push(ViewportCommand::Icon(Some(new_icon.clone())));
self.icon = Some(new_icon);
}
}
if let Some(new_visible) = new_visible {
if Some(new_visible) != self.active {
self.visible = Some(new_visible);
commands.push(ViewportCommand::Visible(new_visible));
}
}
if let Some(new_mouse_passthrough) = new_mouse_passthrough {
if Some(new_mouse_passthrough) != self.mouse_passthrough {
self.mouse_passthrough = Some(new_mouse_passthrough);
commands.push(ViewportCommand::MousePassthrough(new_mouse_passthrough));
}
}
if let Some(new_window_level) = new_window_level {
if Some(new_window_level) != self.window_level {
self.window_level = Some(new_window_level);
commands.push(ViewportCommand::WindowLevel(new_window_level));
}
}
// --------------------------------------------------------------
// Things we don't have commands for require a full window recreation.
// The reason we don't have commands for them is that `winit` doesn't support
// changing them without recreating the window.
let mut recreate_window = false;
if new_active.is_some() && self.active != new_active {
self.active = new_active;
recreate_window = true;
}
if new_app_id.is_some() && self.app_id != new_app_id {
self.app_id = new_app_id;
recreate_window = true;
}
if new_close_button.is_some() && self.close_button != new_close_button {
self.close_button = new_close_button;
recreate_window = true;
}
if new_minimize_button.is_some() && self.minimize_button != new_minimize_button {
self.minimize_button = new_minimize_button;
recreate_window = true;
}
if new_maximize_button.is_some() && self.maximize_button != new_maximize_button {
self.maximize_button = new_maximize_button;
recreate_window = true;
}
if new_title_shown.is_some() && self.title_shown != new_title_shown {
self.title_shown = new_title_shown;
recreate_window = true;
}
if new_titlebar_buttons_shown.is_some()
&& self.titlebar_buttons_shown != new_titlebar_buttons_shown
{
self.titlebar_buttons_shown = new_titlebar_buttons_shown;
recreate_window = true;
}
if new_titlebar_shown.is_some() && self.titlebar_shown != new_titlebar_shown {
self.titlebar_shown = new_titlebar_shown;
recreate_window = true;
}
if new_fullsize_content_view.is_some()
&& self.fullsize_content_view != new_fullsize_content_view
{
self.fullsize_content_view = new_fullsize_content_view;
recreate_window = true;
}
if new_drag_and_drop.is_some() && self.drag_and_drop != new_drag_and_drop {
self.drag_and_drop = new_drag_and_drop;
recreate_window = true;
}
(commands, recreate_window)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum WindowLevel {
#[default]
Normal,
AlwaysOnBottom,
AlwaysOnTop,
}
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum IMEPurpose {
#[default]
Normal,
Password,
Terminal,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum SystemTheme {
#[default]
SystemDefault,
Light,
Dark,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum CursorGrab {
#[default]
None,
Confined,
Locked,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum ResizeDirection {
North,
South,
East,
West,
NorthEast,
SouthEast,
NorthWest,
SouthWest,
}
/// An output [viewport](crate::viewport)-command from egui to the backend, e.g. to change the window title or size.
///
/// You can send a [`ViewportCommand`] to the viewport with [`Context::send_viewport_cmd`].
///
/// See [`crate::viewport`] for how to build new viewports (native windows).
///
/// All coordinates are in logical points.
///
/// This is essentially a way to diff [`ViewportBuilder`].
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum ViewportCommand {
/// Request this viewport to be closed.
///
/// For the root viewport, this usually results in the application shutting down.
/// For other viewports, the [`crate::ViewportInfo::close_requested`] flag will be set.
Close,
/// Cancel the closing that was signaled by [`crate::ViewportInfo::close_requested`].
CancelClose,
/// Set the window title.
Title(String),
/// Turn the window transparent or not.
Transparent(bool),
/// Set the visibility of the window.
Visible(bool),
/// Moves the window with the left mouse button until the button is released.
///
/// There's no guarantee that this will work unless the left mouse button was pressed
/// immediately before this function is called.
StartDrag,
/// Set the outer position of the viewport, i.e. moves the window.
OuterPosition(Pos2),
/// Should be bigger than 0
InnerSize(Vec2),
/// Should be bigger than 0
MinInnerSize(Vec2),
/// Should be bigger than 0
MaxInnerSize(Vec2),
/// Should be bigger than 0
ResizeIncrements(Option<Vec2>),
/// Begin resizing the viewport with the left mouse button until the button is released.
///
/// There's no guarantee that this will work unless the left mouse button was pressed
/// immediately before this function is called.
BeginResize(ResizeDirection),
/// Can the window be resized?
Resizable(bool),
/// Set which window buttons are enabled
EnableButtons {
close: bool,
minimized: bool,
maximize: bool,
},
Minimized(bool),
/// Maximize or unmaximize window.
Maximized(bool),
/// Turn borderless fullscreen on/off.
Fullscreen(bool),
/// Show window decorations, i.e. the chrome around the content
/// with the title bar, close buttons, resize handles, etc.
Decorations(bool),
/// Set window to be always-on-top, always-on-bottom, or neither.
WindowLevel(WindowLevel),
/// The the window icon.
Icon(Option<Arc<IconData>>),
/// Set the IME cursor editing area.
IMERect(crate::Rect),
IMEAllowed(bool),
IMEPurpose(IMEPurpose),
/// Bring the window into focus (native only).
///
/// This command puts the window on top of other applications and takes input focus away from them,
/// which, if unexpected, will disturb the user.
///
/// Has no effect on Wayland, or if the window is minimized or invisible.
Focus,
/// If the window is unfocused, attract the user's attention (native only).
///
/// Typically, this means that the window will flash on the taskbar, or bounce, until it is interacted with.
///
/// When the window comes into focus, or if `None` is passed, the attention request will be automatically reset.
///
/// See [winit's documentation][user_attention_details] for platform-specific effect details.
///
/// [user_attention_details]: https://docs.rs/winit/latest/winit/window/enum.UserAttentionType.html
RequestUserAttention(crate::UserAttentionType),
SetTheme(SystemTheme),
ContentProtected(bool),
/// Will probably not work as expected!
CursorPosition(Pos2),
CursorGrab(CursorGrab),
CursorVisible(bool),
/// Enable mouse pass-through: mouse clicks pass through the window, used for non-interactable overlays.
MousePassthrough(bool),
/// Take a screenshot.
///
/// The results are returned in `crate::Event::Screenshot`.
Screenshot,
}
impl ViewportCommand {
/// Construct a command to center the viewport on the monitor, if possible.
pub fn center_on_screen(ctx: &crate::Context) -> Option<Self> {
ctx.input(|i| {
let outer_rect = i.viewport().outer_rect?;
let size = outer_rect.size();
let monitor_size = i.viewport().monitor_size?;
if 1.0 < monitor_size.x && 1.0 < monitor_size.y {
let x = (monitor_size.x - size.x) / 2.0;
let y = (monitor_size.y - size.y) / 2.0;
Some(Self::OuterPosition([x, y].into()))
} else {
None
}
})
}
/// This command requires the parent viewport to repaint.
pub fn requires_parent_repaint(&self) -> bool {
self == &Self::Close
}
}
/// Describes a viewport, i.e. a native window.
///
/// This is returned by [`crate::Context::run`] on each frame, and should be applied
/// by the integration.
#[derive(Clone)]
pub struct ViewportOutput {
/// Id of our parent viewport.
pub parent: ViewportId,
/// What type of viewport are we?
///
/// This will never be [`ViewportClass::Embedded`],
/// since those don't result in real viewports.
pub class: ViewportClass,
/// The window attrbiutes such as title, position, size, etc.
///
/// Use this when first constructing the native window.
/// Also check for changes in it using [`ViewportBuilder::patch`],
/// and apply them as needed.
pub builder: ViewportBuilder,
/// The user-code that shows the GUI, used for deferred viewports.
///
/// `None` for immediate viewports and the ROOT viewport.
pub viewport_ui_cb: Option<Arc<DeferredViewportUiCallback>>,
/// Commands to change the viewport, e.g. window title and size.
pub commands: Vec<ViewportCommand>,
/// Schedule a repaint of this viewport after this delay.
///
/// It is preferable to instead install a [`Context::set_request_repaint_callback`],
/// but if you haven't, you can use this instead.
///
/// If the duration is zero, schedule a repaint immediately.
pub repaint_delay: std::time::Duration,
}
impl ViewportOutput {
/// Add on new output.
pub fn append(&mut self, newer: Self) {
let Self {
parent,
class,
builder,
viewport_ui_cb,
mut commands,
repaint_delay,
} = newer;
self.parent = parent;
self.class = class;
let _ = self.builder.patch(builder); // we ignore the returned command, because `self.builder` will be the basis of a new patch
self.viewport_ui_cb = viewport_ui_cb;
self.commands.append(&mut commands);
self.repaint_delay = self.repaint_delay.min(repaint_delay);
}
}
/// Viewport for immediate rendering.
pub struct ImmediateViewport<'a> {
/// Id of us and our parent.
pub ids: ViewportIdPair,
pub builder: ViewportBuilder,
/// The user-code that shows the GUI.
pub viewport_ui_cb: Box<dyn FnOnce(&Context) + 'a>,
}