Skip to main content

egui_pop_api/
window.rs

1//! The window's place, as a plugin ([`WindowPlugin`], in
2//! `DefaultPlugins`): its size, position, maximized and full-screen
3//! states are kept in the store (`settings/window.*`, saved with the
4//! settings, no undo step) and given back at the next start by
5//! `AppBuilder::run_native`, after a repair: a window whose title bar
6//! would be on no screen comes back onto the first one, one larger than
7//! its screen (or than what the GPU can draw) is shrunk.
8//!
9//! **Full screen** (`F11`, View > Full screen) keeps the way out
10//! reachable: the application's title bar keeps a button leaving it
11//! (`frame::FramePlugin`); without that bar (the system draws the frame,
12//! or `window.bar_in_fullscreen` is off), moving the pointer to the top
13//! edge shows a strip with the title and an "Exit full screen" button.
14//!
15//! Where the window manager does not tell the window's position
16//! (Wayland), only the size and the states are kept: the position an
17//! earlier run kept (X11, Windows) stays for the next run where it is
18//! told, never replaced by a made-up one, and the View menu says under
19//! Full screen that the system places the windows ([`POSITIONS_HIDDEN`]).
20
21use egui::{Align2, Context, Id, Order, Pos2, Rect, Ui, Vec2, ViewportCommand};
22use egui_pop_core::kit::{Kit, State};
23use egui_pop_core::lock;
24use egui_pop_core::state::Slot;
25use egui_pop_core::strings;
26
27/// The way out of full screen was shown on the last pass.
28const WAY_OUT: Slot<bool> = Slot::new("api.window.way_out");
29use egui_pop_model::commands::{CommandSpec, Origin};
30use egui_pop_model::ids::{BlockId, CommandId, OwnerId, PluginId};
31use egui_pop_model::values::{Change, Descriptor, Set, SettingsDoc, Value};
32use serde_json::json;
33
34use crate::app::{AppHandle, MENU_VIEW};
35use crate::zones::{self, Block};
36use crate::{Ctx, Plugin, PluginError};
37
38/// Toggles full screen.
39pub const CMD_FULLSCREEN: CommandId = CommandId::from_static("app.fullscreen");
40
41/// Where the window's place is kept.
42pub const RECT: &str = "settings/window.rect";
43pub const MAXIMIZED: &str = "settings/window.maximized";
44pub const FULLSCREEN: &str = "settings/window.fullscreen";
45/// Whether the kept position is known (the window manager told it).
46pub const PLACED: &str = "settings/window.placed";
47/// The context key saying the system tells no window's position and
48/// places windows itself (Wayland): `"true"` there.
49pub const POSITIONS_HIDDEN: &str = "windowPositionsHidden";
50/// The View menu's note, under Full screen, where the system places the
51/// windows ([`POSITIONS_HIDDEN`]).
52pub const LIST_PLACEMENT: &str = "app.window.placement";
53
54/// The largest side kept (a window past the GPU's texture limit cannot
55/// be drawn).
56pub const MAX_SIDE: f32 = 8192.0;
57/// The smallest side kept.
58pub const MIN_SIDE: f32 = 200.0;
59/// How much of a title bar must be on a screen to be reachable.
60const REACHABLE: Vec2 = Vec2::new(64.0, 16.0);
61
62/// The window's place.
63#[derive(Clone, Copy, Debug, PartialEq)]
64pub struct WindowState {
65    /// The outer position, when the window manager tells it.
66    pub position: Option<Pos2>,
67    /// The inner size, in points.
68    pub size: Vec2,
69    pub maximized: bool,
70    pub fullscreen: bool,
71}
72
73impl WindowState {
74    /// As the store keeps it: `[x, y, width, height]`, whether x and y
75    /// are known; a zero size when nothing was kept.
76    pub fn from_store(
77        rect: &[f64],
78        placed: bool,
79        maximized: bool,
80        fullscreen: bool,
81    ) -> Option<WindowState> {
82        let [x, y, w, h] = rect else { return None };
83        if *w <= 0.0 || *h <= 0.0 {
84            return None;
85        }
86        let position = placed.then(|| Pos2::new(*x as f32, *y as f32));
87        Some(WindowState {
88            position,
89            size: Vec2::new(*w as f32, *h as f32),
90            maximized,
91            fullscreen,
92        })
93    }
94
95    #[cfg(test)]
96    fn to_store(self) -> Vec<f64> {
97        let (x, y) = self
98            .position
99            .map_or((0.0, 0.0), |p| (f64::from(p.x), f64::from(p.y)));
100        vec![x, y, f64::from(self.size.x), f64::from(self.size.y)]
101    }
102
103    /// Keeps the window reachable on these screens (none known: only the
104    /// size is bounded, and a position far away is dropped).
105    pub fn repair(mut self, screens: &[Rect]) -> WindowState {
106        self.size = self
107            .size
108            .clamp(Vec2::splat(MIN_SIDE), Vec2::splat(MAX_SIDE));
109        let Some(pos) = self.position else {
110            return self;
111        };
112        if screens.is_empty() {
113            if pos.x.abs() > 65_536.0 || pos.y.abs() > 65_536.0 {
114                self.position = None;
115            }
116            return self;
117        }
118        let title = Rect::from_min_size(pos, Vec2::new(self.size.x, 32.0));
119        let on = screens.iter().find(|s| {
120            let i = s.intersect(title);
121            i.is_positive() && i.width() >= REACHABLE.x && i.height() >= REACHABLE.y
122        });
123        let screen = match on {
124            Some(s) => *s,
125            None => {
126                let s = screens[0];
127                self.size = self.size.min(s.size());
128                self.position = Some(s.center() - self.size / 2.0);
129                s
130            }
131        };
132        self.size = self.size.min(screen.size());
133        self
134    }
135}
136
137/// A screen (a monitor), as the system tells it: its name, its
138/// rectangle in points and its scale factor. Given by whatever runs the
139/// event loop ([`set_screens`]): egui-pop's native runner, or a host
140/// application running eframe on its own loop.
141#[derive(Clone, Debug, PartialEq)]
142pub struct Screen {
143    /// The monitor's name as the system gives it (winit's
144    /// `MonitorHandle::name`), what recognises a screen plugged in
145    /// again; none when the system gives none.
146    pub name: Option<String>,
147    /// Its rectangle, in points: the physical one over [`Self::scale`].
148    pub rect: Rect,
149    /// Physical pixels per point (1.0 when the system tells none).
150    pub scale: f32,
151}
152
153impl Screen {
154    /// A screen from what the system gives in physical pixels (winit's
155    /// `MonitorHandle::{name, position, size, scale_factor}`): its
156    /// rectangle in points is the physical one over its own scale factor
157    /// (1.0 when that is not positive).
158    pub fn from_physical(
159        name: Option<String>,
160        position: (i32, i32),
161        size: (u32, u32),
162        scale: f64,
163    ) -> Screen {
164        let s = if scale > 0.0 { scale as f32 } else { 1.0 };
165        Screen {
166            name,
167            rect: Rect::from_min_size(
168                egui::pos2(position.0 as f32 / s, position.1 as f32 / s),
169                egui::vec2(size.0 as f32 / s, size.1 as f32 / s),
170            ),
171            scale: s,
172        }
173    }
174
175    /// A screen known by its rectangle in points alone (no name, scale
176    /// 1.0): what a test says.
177    pub fn from_rect(rect: Rect) -> Screen {
178        Screen {
179            name: None,
180            rect,
181            scale: 1.0,
182        }
183    }
184}
185
186thread_local! {
187    /// The screens told to egui-pop on this thread ([`set_screens`]).
188    static SCREENS: std::cell::RefCell<Vec<Screen>> =
189        const { std::cell::RefCell::new(Vec::new()) };
190    /// How many times the screens were told on this thread: an
191    /// application follows them from its main window's pass when it
192    /// changed (`pop.screen.added`, `pop.screen.removed`).
193    static TOLD: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
194}
195
196/// The name a layout gives a screen it cannot name: a window detached
197/// where no screen is told by name (Wayland tells no positions, a
198/// system names no monitor). A window kept on it is never docked back
199/// for its screen being gone; its position is still repaired.
200pub const UNNAMED_SCREEN: &str = "primary";
201
202/// The screens, in points, as far as egui-pop knows them: those told by
203/// what runs the event loop ([`set_screens`]; egui-pop's native runner
204/// tells them before the main window is created); none until told. A
205/// window's kept place is repaired against them
206/// ([`WindowState::repair`]) before it opens.
207pub fn screens() -> Vec<Rect> {
208    SCREENS.with_borrow(|s| s.iter().map(|s| s.rect).collect())
209}
210
211/// The screens as told ([`set_screens`]), with their names and scale
212/// factors.
213pub fn screen_list() -> Vec<Screen> {
214    SCREENS.with_borrow(Clone::clone)
215}
216
217/// Tells egui-pop the screens, for the windows of this thread (the one
218/// running the event loop and the application's frames). A host that
219/// runs the event loop itself (eframe on its own winit loop, without the
220/// `create-native` feature) reads the monitors and calls it: before the
221/// main window is created (so its kept place is repaired against them,
222/// [`repair_builder`]), and again when they change (a scale factor
223/// changed, a window moved to another monitor). egui-pop's native runner
224/// calls it the same way. Windows opened after the call (detached panels,
225/// application windows) are repaired against the screens given; an empty
226/// list says none are known (only sizes are bounded).
227///
228/// Each application of the thread follows the change from its main
229/// window's next pass: a screen gone is said as `pop.screen.removed`, a new
230/// one as `pop.screen.added` (by name; [`crate::bus::ScreenRemoved`]), and
231/// every window on a screen gone moves onto one that is left, a detached
232/// panel's window docking back (`pop.window.place`).
233pub fn set_screens(screens: Vec<Screen>) {
234    log::debug!(target: "egui_pop::window", "screens: {screens:?}");
235    SCREENS.set(screens);
236    TOLD.set(TOLD.get() + 1);
237}
238
239/// How many times the screens were told on this thread.
240pub(crate) fn screens_told() -> u64 {
241    TOLD.get()
242}
243
244/// The name of the screen `rect` is on (the one holding its centre, else
245/// the one it overlaps most), as told; none when no screen is told by
246/// name there.
247pub fn screen_name_at(rect: Rect) -> Option<String> {
248    SCREENS.with_borrow(|screens| {
249        let centre = rect.center();
250        screens
251            .iter()
252            .find(|s| s.rect.contains(centre))
253            .or_else(|| {
254                screens
255                    .iter()
256                    .filter(|s| s.rect.intersects(rect))
257                    .max_by(|a, b| {
258                        let area = |s: &Screen| s.rect.intersect(rect).area();
259                        area(a).total_cmp(&area(b))
260                    })
261            })
262            .and_then(|s| s.name.clone())
263    })
264}
265
266/// Says the screens for this thread's windows by their rectangles, in
267/// place of the system's (`None`: none known again). For headless tests
268/// (`egui_pop_test::windows::MultiWindow::set_screens`).
269#[doc(hidden)]
270pub fn set_test_screens(screens: Option<Vec<Rect>>) {
271    set_screens(
272        screens
273            .unwrap_or_default()
274            .into_iter()
275            .map(Screen::from_rect)
276            .collect(),
277    );
278}
279
280/// A native window's builder, its kept place repaired against the
281/// screens told ([`set_screens`]): a position off every screen is pulled
282/// back onto the first, a size larger than its screen shrunk; the
283/// maximized and full-screen flags stay. Unchanged while no screen is
284/// known. Called from eframe's `NativeOptions::window_builder` hook, which
285/// runs as the main window is created (egui-pop's native runner does it).
286pub fn repair_builder(vb: egui::ViewportBuilder) -> egui::ViewportBuilder {
287    repair_place(vb, &screens())
288}
289
290pub(crate) fn repair_place(
291    mut vb: egui::ViewportBuilder,
292    screens: &[Rect],
293) -> egui::ViewportBuilder {
294    if screens.is_empty() {
295        return vb;
296    }
297    let Some(size) = vb.inner_size else {
298        return vb;
299    };
300    let state = WindowState {
301        position: vb.position,
302        size,
303        maximized: false,
304        fullscreen: false,
305    }
306    .repair(screens);
307    vb.position = state.position;
308    vb.inner_size = Some(state.size);
309    vb
310}
311
312/// Reads the window's place from a saved settings document.
313pub fn from_settings(doc: &SettingsDoc) -> Option<WindowState> {
314    let rect: Vec<f64> = doc
315        .values
316        .get(RECT)?
317        .as_array()?
318        .iter()
319        .map(|v| v.as_f64().unwrap_or(0.0))
320        .collect();
321    let flag = |p: &str| doc.values.get(p).and_then(|v| v.as_bool()).unwrap_or(false);
322    WindowState::from_store(&rect, flag(PLACED), flag(MAXIMIZED), flag(FULLSCREEN))
323}
324
325/// Gives a native window the place kept in a settings directory (the
326/// one given to `AppBuilder::persist`), repaired: the screens are not
327/// known before the window exists, so only its size is bounded and a
328/// position far away dropped. Returns the place given, if one was kept.
329/// `AppBuilder::run_native` does it; an application running eframe
330/// itself calls it.
331///
332/// The window's place then has one owner, egui-pop: eframe's own copy
333/// (`NativeOptions::persist_window`, kept with its `persistence` feature)
334/// is turned off, kept place or not, or it would be put over this one as
335/// the window is created.
336#[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
337pub fn restore(
338    dir: impl Into<std::path::PathBuf>,
339    options: &mut eframe::NativeOptions,
340) -> Option<WindowState> {
341    options.persist_window = false;
342    let p = egui_pop_core::persist::Persist::new(dir);
343    let read = p
344        .load::<SettingsDoc>("settings", &egui_pop_model::values::settings_schema())
345        .ok()
346        .flatten()?;
347    let state = from_settings(&read.value)?.repair(&[]);
348    apply(options, state);
349    Some(state)
350}
351
352/// Puts a kept window place into a native window's options.
353#[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
354pub fn apply(options: &mut eframe::NativeOptions, state: WindowState) {
355    let mut v = std::mem::take(&mut options.viewport).with_inner_size(state.size);
356    if let Some(p) = state.position {
357        v = v.with_position(p);
358    }
359    if state.maximized {
360        v = v.with_maximized(true);
361    }
362    if state.fullscreen {
363        v = v.with_fullscreen(true);
364    }
365    options.viewport = v;
366}
367
368/// The plugin.
369#[derive(Debug, Default)]
370pub struct WindowPlugin;
371
372impl Plugin for WindowPlugin {
373    fn id(&self) -> PluginId {
374        PluginId::from_static("egui_pop.window")
375    }
376
377    fn title(&self) -> String {
378        "Window".into()
379    }
380
381    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
382        let owner = ctx.owner().clone();
383        {
384            let store = ctx.app().store();
385            let mut s = lock(&store);
386            let declare = |s: &mut egui_pop_model::values::Store, p: &str, d: Descriptor| {
387                s.declare(&owner, p, d)
388                    .map_err(|e| PluginError::Failed(e.to_string()))
389            };
390            declare(
391                &mut s,
392                RECT,
393                Descriptor::floats("Window", 4, -1.0e6, 1.0e6, &[0.0; 4]),
394            )?;
395            declare(&mut s, PLACED, Descriptor::bool("Window placed", false))?;
396            declare(&mut s, MAXIMIZED, Descriptor::bool("Maximized", false))?;
397            declare(&mut s, FULLSCREEN, Descriptor::bool("Full screen", false))?;
398        }
399        ctx.command(
400            CommandSpec::new(CMD_FULLSCREEN, "Full screen", "View")
401                .icon("fullscreen")
402                .icon_on("exit-fullscreen")
403                .description("Fills the screen; the top edge brings the way out back.")
404                .key("F11")
405                .checked("windowFullscreen")
406                .menu(MENU_VIEW, "9_window", 0),
407            |call| {
408                let on = call.app.context().get("windowFullscreen") != "true";
409                call.app
410                    .egui()
411                    .send_viewport_cmd(ViewportCommand::Fullscreen(on));
412                Ok(json!({ "fullscreen": on }))
413            },
414        )?;
415        // Where the system places windows itself (Wayland), the View menu
416        // says so under Full screen: their place is not lost by a bug.
417        ctx.menu_item(egui_pop_model::menus::MenuItem::list(
418            MENU_VIEW,
419            "9_window",
420            1,
421            LIST_PLACEMENT,
422        ))?;
423        ctx.list_provider(LIST_PLACEMENT, |app, _| {
424            if app.context().get(POSITIONS_HIDDEN) != "true" {
425                return Vec::new();
426            }
427            let note = strings::tr(&app.egui(), &crate::strings::WINDOW_PLACED_BY_SYSTEM);
428            vec![crate::menus::ListItem::new(&note, CMD_FULLSCREEN, json!(null)).disabled()]
429        });
430        ctx.block(
431            zones::OVERLAYS,
432            Block::add(BlockId::from_static("egui_pop.window"), 30, show),
433        );
434        Ok(())
435    }
436}
437
438/// Follows the window's place into the store, and draws the way out of
439/// full screen.
440fn show(ui: &mut Ui, app: &AppHandle) {
441    let ctx = ui.ctx().clone();
442    let info = ctx.input(|i| i.viewport().clone());
443    let fullscreen = info.fullscreen.unwrap_or(false);
444    let maximized = info.maximized.unwrap_or(false);
445    app.set_context(
446        "windowFullscreen",
447        if fullscreen { "true" } else { "false" },
448    );
449    // A window of its own (not embedded: kittest, the web) told no
450    // rectangle while shown: the system hides positions (Wayland).
451    let hidden =
452        !ctx.embed_viewports() && info.inner_rect.is_none() && info.minimized != Some(true);
453    app.set_context(POSITIONS_HIDDEN, if hidden { "true" } else { "false" });
454    let size = ctx.input(|i| i.viewport_rect().size());
455    track(app, &info, size, maximized, fullscreen);
456    // The application's title bar, drawn this pass, holds the way out;
457    // in zen mode, zen's own strip does (leaving it shows the bar).
458    if fullscreen && !app.main_zen() && !crate::frame::bar_shown_in_full_screen(&ctx) {
459        way_out(&ctx, app);
460    }
461}
462
463fn track(
464    app: &AppHandle,
465    info: &egui::ViewportInfo,
466    viewport_size: Vec2,
467    maximized: bool,
468    fullscreen: bool,
469) {
470    let store = app.store();
471    let mut s = lock(&store);
472    // The position an earlier run kept, where the system told it.
473    let kept = match s.get(RECT).map(|e| &e.value) {
474        Some(Value::Floats(r)) if r.len() == 4 => Some((r[0], r[1])),
475        _ => None,
476    };
477    let mut write = |path: &str, v: Value| {
478        if s.get(path).is_some_and(|e| e.value != v) {
479            let _ = s.set(
480                Set::new(path, Change::To(v), Origin::User)
481                    .by(&OwnerId::FRAMEWORK)
482                    .untracked()
483                    .force(),
484            );
485        }
486    };
487    write(MAXIMIZED, Value::Bool(maximized));
488    write(FULLSCREEN, Value::Bool(fullscreen));
489    // The normal place only: not while maximized, full screen or
490    // minimized.
491    if maximized || fullscreen || info.minimized == Some(true) {
492        return;
493    }
494    // Wayland tells no rectangle: the size is the window's own.
495    let size = info.inner_rect.map_or(viewport_size, |r| r.size());
496    if size.x <= 0.0 || size.y <= 0.0 {
497        return;
498    }
499    let (x, y) = match info.outer_rect {
500        Some(r) => {
501            write(PLACED, Value::Bool(true));
502            (f64::from(r.min.x), f64::from(r.min.y))
503        }
504        // Not told (Wayland): the position an earlier run kept stays as
505        // it is, never replaced by a made-up one.
506        None => kept.unwrap_or((0.0, 0.0)),
507    };
508    write(
509        RECT,
510        Value::Floats(vec![x, y, f64::from(size.x), f64::from(size.y)]),
511    );
512}
513
514/// The strip at the top of a full screen window.
515fn way_out(ctx: &Context, app: &AppHandle) {
516    let screen = ctx.content_rect();
517    let near_top = ctx
518        .input(|i| i.pointer.hover_pos())
519        .is_some_and(|p| p.y <= screen.top() + 4.0);
520    let id = Id::unique("egui_pop.window.way_out");
521    let shown_before = WAY_OUT.get(ctx).unwrap_or(false);
522    let mut keep = near_top;
523    if near_top || shown_before {
524        let r = egui::Area::new(id)
525            .order(Order::Foreground)
526            .anchor(Align2::CENTER_TOP, Vec2::ZERO)
527            .show(ctx, |ui| {
528                let shadow = ui.visuals().popup_shadow;
529                Kit::of(ctx)
530                    .fullscreen_exit
531                    .show(ui, State::REST, shadow, |ui| {
532                        ui.horizontal(|ui| {
533                            let title = ctx
534                                .input(|i| i.viewport().title.clone())
535                                .unwrap_or_default();
536                            if !title.is_empty() {
537                                ui.strong(title);
538                            }
539                            let exit = strings::tr(ctx, &crate::strings::WINDOW_EXIT_FULLSCREEN);
540                            if ui.button(exit).clicked() {
541                                app.run(CMD_FULLSCREEN, json!(null));
542                            }
543                        });
544                    })
545            });
546        keep |= r.response.contains_pointer();
547    }
548    WAY_OUT.set(ctx, keep);
549}
550
551/// The windowing system the application's windows are on, as the event
552/// loop's display says it (`runner::windowing`): egui-pop's runner reads
553/// it when the loop resumes, a host running its own loop tells it
554/// (`runner::host::resumed`).
555///
556/// <div class="warning">Experimental: may change in any release
557/// (docs/stability.md).</div>
558#[derive(Clone, Copy, Debug, PartialEq, Eq)]
559pub enum Windowing {
560    /// Wayland: a window can have subsurfaces below it.
561    Wayland,
562    /// X11 (Xlib or XCB).
563    X11,
564    /// Windows.
565    Windows,
566    /// macOS.
567    MacOs,
568    /// Another system, or the web.
569    Other,
570    /// Not told: no event loop seen yet, or egui-pop does not run it and
571    /// the host did not tell.
572    Unknown,
573}
574
575/// How a window that may show a surface below egui (the image viewport's
576/// image surface, a Wayland subsurface) is built on `windowing`:
577/// transparent on Wayland, so that surface shows through; opaque
578/// elsewhere, where there is no such surface to show and a transparent
579/// window only costs the compositor, with the reason.
580///
581/// <div class="warning">Experimental: may change in any release
582/// (docs/stability.md).</div>
583pub fn surface_below_transparency(
584    windowing: Windowing,
585) -> egui_pop_core::window_surface::Transparency {
586    use egui_pop_core::window_surface::Transparency;
587    let elsewhere = |name: &str| {
588        Transparency::Opaque(format!(
589            "{name}: the image surface is a Wayland subsurface, there is none here"
590        ))
591    };
592    match windowing {
593        Windowing::Wayland => Transparency::Transparent,
594        Windowing::X11 => elsewhere("X11"),
595        Windowing::Windows => elsewhere("Windows"),
596        Windowing::MacOs => elsewhere("macOS"),
597        Windowing::Other => elsewhere("this system"),
598        Windowing::Unknown => Transparency::Opaque(
599            "the windowing system is not known: egui-pop does not run the event loop and the \
600             host did not tell it (runner::host::resumed)"
601                .into(),
602        ),
603    }
604}
605
606/// Whether the windows the application decorates are built transparent
607/// for rounded corners (`AppBuilder::rounded_windows`): `asked`, or by
608/// default on Wayland only. X11 needs a compositing window manager (so
609/// only when asked); Windows and macOS round their windows themselves;
610/// the web, headless runs and an unknown system never.
611pub(crate) fn rounded_windows(asked: Option<bool>, windowing: Windowing) -> bool {
612    match (asked, windowing) {
613        (Some(false), _) => false,
614        (_, Windowing::Wayland) => true,
615        (Some(true), Windowing::X11) => true,
616        _ => false,
617    }
618}
619
620/// Builds the main window transparent when its corners may be rounded
621/// ([`rounded_windows`]), decided once the windowing system is known
622/// (eframe's `window_builder` hook runs in `resumed`).
623#[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
624pub(crate) fn transparent_for_corners(options: &mut eframe::NativeOptions, asked: Option<bool>) {
625    if asked == Some(false) {
626        return;
627    }
628    let previous = options.window_builder.take();
629    options.window_builder = Some(Box::new(move |vb| {
630        let vb = match previous {
631            Some(hook) => hook(vb),
632            None => vb,
633        };
634        if rounded_windows(asked, windowing()) {
635            vb.with_transparent(true)
636        } else {
637            vb
638        }
639    }));
640}
641
642/// The windowing system of this run ([`Windowing`]): the runner's, or
643/// [`Windowing::Unknown`] without one (the web, headless, tests).
644///
645/// <div class="warning">Experimental: may change in any release
646/// (docs/stability.md).</div>
647pub fn windowing() -> Windowing {
648    #[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
649    {
650        crate::runner::windowing()
651    }
652    #[cfg(not(all(feature = "eframe", not(target_arch = "wasm32"))))]
653    {
654        Windowing::Unknown
655    }
656}
657
658#[cfg(test)]
659mod tests {
660    #[test]
661    fn rounded_windows_by_default_on_wayland_only() {
662        use super::{Windowing, rounded_windows};
663        assert!(rounded_windows(None, Windowing::Wayland));
664        assert!(!rounded_windows(Some(false), Windowing::Wayland));
665        assert!(!rounded_windows(None, Windowing::X11));
666        assert!(rounded_windows(Some(true), Windowing::X11));
667        for w in [
668            Windowing::Windows,
669            Windowing::MacOs,
670            Windowing::Other,
671            Windowing::Unknown,
672        ] {
673            assert!(!rounded_windows(Some(true), w), "{w:?}");
674            assert!(!rounded_windows(None, w), "{w:?}");
675        }
676    }
677
678    #[test]
679    fn a_window_showing_a_surface_below_is_transparent_on_wayland_only() {
680        use super::{Windowing, surface_below_transparency};
681        assert!(surface_below_transparency(Windowing::Wayland).is_transparent());
682        for (w, name) in [
683            (Windowing::X11, "X11"),
684            (Windowing::Windows, "Windows"),
685            (Windowing::MacOs, "macOS"),
686        ] {
687            let t = surface_below_transparency(w);
688            let why = t.why_opaque().expect("opaque");
689            assert!(why.contains(name) && why.contains("Wayland"), "{why}");
690        }
691        let unknown = surface_below_transparency(Windowing::Unknown);
692        assert!(unknown.why_opaque().unwrap().contains("runner::host"));
693    }
694
695    use super::*;
696
697    fn state(x: f32, y: f32, w: f32, h: f32) -> WindowState {
698        WindowState {
699            position: Some(Pos2::new(x, y)),
700            size: Vec2::new(w, h),
701            maximized: false,
702            fullscreen: false,
703        }
704    }
705
706    #[test]
707    fn a_window_off_every_screen_comes_back_onto_the_first() {
708        let left = Rect::from_min_size(Pos2::new(-1920.0, 0.0), Vec2::new(1920.0, 1080.0));
709        let main = Rect::from_min_size(Pos2::ZERO, Vec2::new(2560.0, 1440.0));
710        // On the left screen: kept as is.
711        let s = state(-1500.0, 100.0, 800.0, 600.0).repair(&[main, left]);
712        assert_eq!(s.position, Some(Pos2::new(-1500.0, 100.0)));
713        // That screen is gone: centred on the first.
714        let s = state(-1500.0, 100.0, 800.0, 600.0).repair(&[main]);
715        assert_eq!(s.position, Some(Pos2::new(880.0, 420.0)));
716        // Only a sliver of the title bar shows: moved too.
717        let s = state(2540.0, 100.0, 800.0, 600.0).repair(&[main]);
718        assert_eq!(s.position, Some(main.center() - Vec2::new(400.0, 300.0)));
719        // Larger than its screen: shrunk to it.
720        let s = state(0.0, 0.0, 4000.0, 3000.0).repair(&[main]);
721        assert_eq!(s.size, Vec2::new(2560.0, 1440.0));
722    }
723
724    #[test]
725    fn without_screens_only_the_size_is_bounded() {
726        let s = state(10.0, 10.0, 20_000.0, 50.0).repair(&[]);
727        assert_eq!(s.size, Vec2::new(MAX_SIDE, MIN_SIDE));
728        assert_eq!(s.position, Some(Pos2::new(10.0, 10.0)));
729        let s = state(1.0e7, 0.0, 800.0, 600.0).repair(&[]);
730        assert_eq!(s.position, None);
731    }
732
733    #[test]
734    fn the_store_keeps_whether_the_position_is_known() {
735        let s = WindowState {
736            position: None,
737            size: Vec2::new(800.0, 600.0),
738            maximized: true,
739            fullscreen: false,
740        };
741        let back = WindowState::from_store(&s.to_store(), false, true, false).unwrap();
742        assert_eq!(back, s);
743        assert!(WindowState::from_store(&[0.0, 0.0, 0.0, 0.0], true, false, false).is_none());
744    }
745
746    /// One owner for the main window's place: once egui-pop restores it,
747    /// eframe keeps none of its own, whether a place was kept or not.
748    #[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
749    #[test]
750    fn restoring_the_place_turns_eframes_copy_off() {
751        let dir =
752            std::env::temp_dir().join(format!("egui-pop-window-restore-{}", std::process::id()));
753        let _ = std::fs::remove_dir_all(&dir);
754        // Nothing kept yet: eframe's copy is off all the same.
755        let mut options = eframe::NativeOptions::default();
756        assert!(options.persist_window);
757        assert_eq!(restore(&dir, &mut options), None);
758        assert!(!options.persist_window);
759        // A place kept: given, eframe's copy off.
760        let mut doc = SettingsDoc::default();
761        doc.values
762            .insert(RECT.into(), json!([40.0, 30.0, 900.0, 700.0]));
763        doc.values.insert(PLACED.into(), json!(true));
764        let text = egui_pop_model::values::settings_schema()
765            .save(&doc)
766            .unwrap();
767        egui_pop_core::persist::Persist::new(&dir)
768            .save_text("settings", &text)
769            .unwrap();
770        let mut options = eframe::NativeOptions::default();
771        let state = restore(&dir, &mut options).expect("a place was kept");
772        assert_eq!(state.position, Some(Pos2::new(40.0, 30.0)));
773        assert_eq!(options.viewport.inner_size, Some(Vec2::new(900.0, 700.0)));
774        assert!(!options.persist_window);
775        let _ = std::fs::remove_dir_all(&dir);
776    }
777}