Skip to main content

egui_pop_api/
frame.rs

1//! The window's own frame, as a plugin ([`FramePlugin`], opt-in): the
2//! application draws its title bar (in the [`zones::TITLE`] zone, above
3//! the menu bar) and its resize edges, instead of the system, as VS Code
4//! does. A setting (`window.frame`) switches between the application's
5//! frame and the system's; the system's comes back at once.
6//!
7//! The bar holds, from the start edge, the blocks of the
8//! [`zones::CAPTION_START`] zone (by default [`BLOCK_MENU`]: a button
9//! opening the system menu, also `Alt+Space` and a right click on the
10//! caption, then the application's logo when it gave one
11//! ([`FramePlugin::logo`]) and its name), the window's title, the blocks
12//! of the [`zones::CAPTION`] zone (the application's buttons) and the
13//! minimize, maximize and close buttons. Its hit regions are published
14//! per window ([`egui_pop_core::frame::HitTable`]) and shown by the debug
15//! bridge's `frame` collector.
16//!
17//! **In full screen** the bar stays, with its zones (the menus and the
18//! application's items live there): close stays, minimize goes, and a
19//! button leaving full screen (the `frame.exit_fullscreen` step) takes
20//! maximize's place. The bar no longer moves the window and a double
21//! click on it does nothing (the way out is that button, or `F11`); the
22//! resize edges go. A setting (`window.bar_in_fullscreen`, on by default)
23//! turns this off: then in full screen the bar is not drawn and publishes
24//! no caption, and the window plugin's strip at the top edge is the way
25//! out.
26//!
27//! **VS Code's layout controls** come at the end of the bar, before the
28//! window's buttons, when the application asks
29//! (`FramePlugin::own().layout_controls(true)`): a "Customize layout"
30//! button opening the layout menu, and a toggle per area (the primary
31//! side bar, the panel, the secondary side bar), filled while the area
32//! shows; see [`crate::layout_controls`].
33//!
34//! An application puts its logo at the start of the bar by replacing the
35//! menu block; the bar itself ([`BLOCK_TITLE`]) still follows the
36//! setting:
37//!
38//! ```no_run
39//! # use egui_pop_api::{Ctx, zones::{self, Block}, frame};
40//! # use egui_pop_core::ui::UiPop;
41//! # use egui_pop_model::ids::BlockId;
42//! # fn connect(ctx: &mut Ctx<'_>) {
43//! ctx.block(
44//!     zones::CAPTION_START,
45//!     Block::replace(frame::BLOCK_MENU, BlockId::from_static("app.logo"), |ui, app| {
46//!         frame::menu_button(ui, app);
47//!         ui.strong_text("My app");
48//!     }),
49//! );
50//! # }
51//! ```
52//!
53//! Steps (ADR 0011), each with a default a plugin may veto or replace:
54//!
55//! | Step | Arguments | Default |
56//! |---|---|---|
57//! | `frame.minimize` | `{}` | minimizes the window |
58//! | `frame.maximize` | `{ "maximized": bool }` (the state asked for) | maximizes or restores |
59//! | `frame.close` | `{ "viewport": "root" }` | closes the window: the main one's `pop.window.close`; an application window's close request, its content may refuse, then its `pop.window.close` |
60//! | `frame.system_menu` | `{ "x", "y" }` (points) | opens the system menu there |
61//! | `frame.exit_fullscreen` | `{ "viewport": "root" }` | leaves full screen |
62//! | `frame.hit_test` | `{ "viewport": "root", "install": bool }` | on Windows, takes over the window's hit testing (or gives it back) |
63//!
64//! ## Windows: the system's hit test
65//!
66//! winit cannot answer `WM_NCHITTEST` (see `docs/upstream.md`), so on
67//! Windows, when the application draws the frame, the plugin subclasses
68//! the main window through `egui-pop-win32` and answers it from the
69//! published regions: the caption moves the window natively (Aero Snap),
70//! the maximize button shows Snap Layouts, the edges resize. Clicks on
71//! the buttons, a double click and a right click on the caption come back
72//! as the usual requests, so the steps above still run. In full screen the
73//! caption is answered as client area (the system must not move the
74//! window), and the button leaving full screen is client area too: Snap
75//! Layouts never show in full screen. The handle comes
76//! from eframe when the application is started with
77//! `AppBuilder::run_native` (or `run_native_with`); an application
78//! starting eframe itself gives it with [`set_native_window`]. Only the
79//! main window is subclassed for now.
80//!
81//! ## Corners
82//!
83//! A window without the system's decorations has square corners on
84//! Windows 11; the plugin asks the system for the kit's `window.corners`
85//! (`round`, `small` or `square`) when it draws the frame, again when
86//! the theme changes it, and gives the system's default back with the
87//! system's frame. Windows 10 refuses, harmlessly. The outcome is in the
88//! `frame` collector (`corners`), never silent. Elsewhere nothing is
89//! asked: no other system has a portable request for a window's
90//! corners (Wayland and X11 leave them to the compositor or the window
91//! manager, macOS rounds its own windows), so egui-pop draws them:
92//! every window it decorates gets a line around it (the kit's
93//! `window.rest.border-*`, dimmer while another window has the focus)
94//! and, where it is built transparent (`AppBuilder::rounded_windows`, by
95//! default on Wayland), rounded corners while it floats free
96//! ([`egui_pop_core::frame::Placement`]): square when maximized, in full
97//! screen or on a side against a screen's edge. Wayland does not tell a
98//! tiled window (no position, and winit 0.30 keeps the tiled states):
99//! there one keeps its rounded corners.
100
101use egui::{Context, Rect, Ui, Vec2, ViewportCommand};
102use egui_pop_core::frame::{FrameRequest, HitTable, TitleBar};
103use egui_pop_core::icon::{Icon, Size};
104use egui_pop_core::lock;
105use egui_pop_core::overlay::{self, Anchor, Kind, OverlaySpec};
106use egui_pop_core::placement::Side;
107use egui_pop_core::state::Slot;
108use egui_pop_core::strings;
109use egui_pop_model::commands::CommandSpec;
110use egui_pop_model::ids::{BlockId, CommandId, MenuId, PluginId, SettingId, StepId};
111use egui_pop_model::values::Descriptor;
112use serde_json::{Value as Json, json};
113
114use crate::app::{AppHandle, MENU_VIEW};
115use crate::steps::StepSpec;
116use crate::strings as txt;
117use crate::zones::{self, Block};
118use crate::{Ctx, Plugin, PluginError};
119
120/// The setting: `own` (the application draws the frame) or `system`.
121pub const SETTING_FRAME: SettingId = SettingId::from_static("window.frame");
122
123/// The setting: whether the application's title bar stays in full screen
124/// (on by default).
125pub const SETTING_BAR_IN_FULLSCREEN: SettingId = SettingId::from_static("window.bar_in_fullscreen");
126
127/// The system menu (restore, minimize, maximize, close); plugins may add
128/// to it.
129pub const MENU_SYSTEM: MenuId = MenuId::from_static("app.menu.system");
130
131pub const CMD_MINIMIZE: CommandId = CommandId::from_static("app.window.minimize");
132pub const CMD_MAXIMIZE: CommandId = CommandId::from_static("app.window.maximize");
133pub const CMD_CLOSE: CommandId = CommandId::from_static("app.window.close");
134pub const CMD_SYSTEM_MENU: CommandId = CommandId::from_static("app.window.menu");
135
136pub const STEP_MINIMIZE: StepId = StepId::from_static("frame.minimize");
137pub const STEP_MAXIMIZE: StepId = StepId::from_static("frame.maximize");
138pub const STEP_CLOSE: StepId = StepId::from_static("frame.close");
139pub const STEP_SYSTEM_MENU: StepId = StepId::from_static("frame.system_menu");
140pub const STEP_HIT_TEST: StepId = StepId::from_static("frame.hit_test");
141pub const STEP_EXIT_FULLSCREEN: StepId = StepId::from_static("frame.exit_fullscreen");
142
143/// The title bar, in the [`zones::TITLE`] zone: it keeps the window's
144/// decorations in line with the setting, so it is better wrapped or
145/// extended than replaced.
146pub const BLOCK_TITLE: BlockId = BlockId::from_static("egui_pop.frame");
147/// The start of the title bar, in the [`zones::CAPTION_START`] zone: the
148/// system menu button and the application's name.
149pub const BLOCK_MENU: BlockId = BlockId::from_static("egui_pop.frame.menu");
150
151/// The application's logo in the title bar: its image, asked each frame
152/// ([`FramePlugin::logo`]).
153pub type Logo = std::sync::Arc<dyn Fn(&Context) -> egui::ImageSource<'static> + Send + Sync>;
154
155/// The plugin: `FramePlugin::own()` draws the frame by default,
156/// `FramePlugin::system()` leaves it to the system until the setting
157/// says otherwise.
158#[derive(Clone, Default)]
159pub struct FramePlugin {
160    own: bool,
161    name: String,
162    layout_controls: bool,
163    logo: Option<Logo>,
164}
165
166impl std::fmt::Debug for FramePlugin {
167    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
168        f.debug_struct("FramePlugin")
169            .field("own", &self.own)
170            .field("name", &self.name)
171            .field("layout_controls", &self.layout_controls)
172            .field("logo", &self.logo.is_some())
173            .finish()
174    }
175}
176
177impl FramePlugin {
178    /// The application draws its frame by default.
179    pub fn own() -> Self {
180        Self {
181            own: true,
182            ..Self::default()
183        }
184    }
185
186    /// The system draws the frame by default.
187    pub fn system() -> Self {
188        Self::default()
189    }
190
191    /// The name shown after the system menu button; without one, the
192    /// application's (`AppBuilder::name`).
193    pub fn name(mut self, name: &str) -> Self {
194        self.name = name.into();
195        self
196    }
197
198    /// The application's logo, drawn after the system menu button and
199    /// before its name, a toolbar icon's size (`size.icon.toolbar`), so the
200    /// application keeps the frame's menu block instead of replacing it.
201    /// `image` gives the logo's image each frame: a texture the
202    /// application loaded once (`ImageSource::Texture`), or a source egui's
203    /// image loaders read (`egui::include_image!`).
204    ///
205    /// ```
206    /// use egui_pop_api::frame::FramePlugin;
207    ///
208    /// let frame = FramePlugin::own().logo(|_| egui::ImageSource::Uri("file://logo.png".into()));
209    /// # let _ = frame;
210    /// ```
211    ///
212    /// Need (image): an application's logo in its own title bar, beside its name.
213    pub fn logo(
214        mut self,
215        image: impl Fn(&Context) -> egui::ImageSource<'static> + Send + Sync + 'static,
216    ) -> Self {
217        self.logo = Some(std::sync::Arc::new(image));
218        self
219    }
220
221    /// Draws VS Code's layout controls at the end of the title bar
222    /// (off by default): the "Customize layout" button and the area
223    /// toggles ([`crate::layout_controls::show`], the
224    /// `egui_pop.frame.layout` block of the [`zones::CAPTION`] zone,
225    /// before the application's own items).
226    pub fn layout_controls(mut self, on: bool) -> Self {
227        self.layout_controls = on;
228        self
229    }
230}
231
232/// The application's logo, a toolbar icon's size, an image named for
233/// screen readers ("Helios logo").
234fn logo_image(ui: &mut Ui, logo: &Logo, name: &str) {
235    let side = egui_pop_core::theme::Tokens::of(ui.ctx()).size.icon_toolbar;
236    let image = egui::Image::new(logo(ui.ctx()))
237        .fit_to_exact_size(egui::vec2(side, side))
238        .sense(egui::Sense::hover());
239    let response = ui.add(image);
240    let label = strings::tr_args(ui.ctx(), &txt::FRAME_LOGO, &[("application", name)]);
241    egui_pop_core::a11y::name(&response, egui::Role::Image, &label);
242}
243
244/// Whether the application draws the window's frame now.
245pub fn own_frame(app: &AppHandle) -> bool {
246    lock(&app.store())
247        .get(&format!("settings/{SETTING_FRAME}"))
248        .and_then(|e| e.value.as_choice().map(|c| c == "own"))
249        .unwrap_or(false)
250}
251
252/// Whether the application's title bar stays in full screen
253/// (`window.bar_in_fullscreen`).
254pub fn bar_in_fullscreen(app: &AppHandle) -> bool {
255    lock(&app.store())
256        .get(&format!("settings/{SETTING_BAR_IN_FULLSCREEN}"))
257        .and_then(|e| e.value.as_bool())
258        .unwrap_or(true)
259}
260
261fn viewport_name(ctx: &Context) -> String {
262    if ctx.viewport_id() == egui::ViewportId::ROOT {
263        "root".into()
264    } else {
265        format!("{:?}", ctx.viewport_id())
266    }
267}
268
269/// Asks the frame's step for a request, with its default.
270pub fn request(app: &AppHandle, ctx: &Context, r: FrameRequest) {
271    let c = ctx.clone();
272    match r {
273        FrameRequest::Minimize => {
274            app.step(&STEP_MINIMIZE, json!({}), move |_, _| {
275                c.send_viewport_cmd(ViewportCommand::Minimized(true));
276                Ok(json!({ "minimized": true }))
277            });
278        }
279        FrameRequest::ToggleMaximize => {
280            let to = !ctx.input(|i| i.viewport().maximized.unwrap_or(false));
281            app.step(
282                &STEP_MAXIMIZE,
283                json!({ "maximized": to }),
284                move |_, args| {
285                    let to = args["maximized"].as_bool().unwrap_or(true);
286                    c.send_viewport_cmd(ViewportCommand::Maximized(to));
287                    Ok(json!({ "maximized": to }))
288                },
289            );
290        }
291        FrameRequest::Close => {
292            app.step(
293                &STEP_CLOSE,
294                json!({ "viewport": viewport_name(ctx) }),
295                move |app, _| Ok(json!({ "closed": app.frame_close(&c) })),
296            );
297        }
298        FrameRequest::ExitFullscreen => {
299            app.step(
300                &STEP_EXIT_FULLSCREEN,
301                json!({ "viewport": viewport_name(ctx) }),
302                move |_, _| {
303                    c.send_viewport_cmd(ViewportCommand::Fullscreen(false));
304                    Ok(json!({ "fullscreen": false }))
305                },
306            );
307        }
308        FrameRequest::SystemMenu(at) => {
309            app.step(
310                &STEP_SYSTEM_MENU,
311                json!({ "x": at.x, "y": at.y }),
312                move |_, args| {
313                    let x = args["x"].as_f64().unwrap_or(0.0) as f32;
314                    let y = args["y"].as_f64().unwrap_or(0.0) as f32;
315                    let pass = c.cumulative_pass_nr();
316                    SYSTEM_MENU.set(&c, Some((egui::pos2(x, y), pass)));
317                    Ok(json!({ "open": true }))
318                },
319            );
320        }
321    }
322}
323
324/// Where the system menu was asked open, and on which pass.
325const SYSTEM_MENU: Slot<Option<(egui::Pos2, u64)>> = Slot::new("api.frame.system_menu");
326/// Whether the window's own frame was last applied, per window.
327const DECORATED: Slot<bool> = Slot::new("api.frame.decorated");
328/// The pass the title bar was last drawn in full screen, per window.
329const BAR_IN_FULL_SCREEN: Slot<u64> = Slot::new("api.frame.bar_in_full_screen");
330/// A window's native handle, per window.
331const NATIVE_WINDOW: Slot<isize> = Slot::new("api.frame.native_window");
332/// The main window's X11 id, when it is an X11 window.
333const X11_WINDOW: Slot<u64> = Slot::new("api.frame.x11_window");
334
335impl Plugin for FramePlugin {
336    fn id(&self) -> PluginId {
337        PluginId::from_static("egui_pop.frame")
338    }
339
340    fn title(&self) -> String {
341        "Window frame".into()
342    }
343
344    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
345        ctx.setting(
346            SETTING_FRAME,
347            Descriptor::choice(
348                "Window frame",
349                &["own", "system"],
350                if self.own { "own" } else { "system" },
351            )
352            .description(
353                "Who draws the window's title bar and edges: the application (own), or the desktop (system).",
354            ),
355        )?;
356        ctx.setting(
357            SETTING_BAR_IN_FULLSCREEN,
358            Descriptor::bool("Title bar in full screen", true).description(
359                "Keeps the application's title bar (its buttons and items) in full screen; off, full screen hides it.",
360            ),
361        )?;
362        for spec in [
363            StepSpec::new(STEP_MINIMIZE, "The frame minimizes the window.").args(json!({})),
364            StepSpec::new(
365                STEP_MAXIMIZE,
366                "The frame maximizes or restores the window (`maximized`: the state asked for).",
367            )
368            .args(json!({ "maximized": true })),
369            StepSpec::new(
370                STEP_CLOSE,
371                "The frame closes a window (`viewport`: `root` for the main one).",
372            )
373            .args(json!({ "viewport": "root" })),
374            StepSpec::new(
375                STEP_SYSTEM_MENU,
376                "The frame opens the system menu at a point (`x`, `y`).",
377            )
378            .args(json!({ "x": 8.0, "y": 32.0 })),
379            StepSpec::new(
380                STEP_EXIT_FULLSCREEN,
381                "The title bar's button leaves full screen (`viewport`: `root` for the main window).",
382            )
383            .args(json!({ "viewport": "root" })),
384            StepSpec::new(
385                STEP_HIT_TEST,
386                "On Windows, the frame takes over the window's hit testing (`install`: true) or gives it back (false); a veto keeps the system's.",
387            )
388            .args(json!({ "viewport": "root", "install": true })),
389        ] {
390            ctx.step(spec)?;
391        }
392        ctx.zone(zones::CAPTION, "Title bar items")?;
393        ctx.zone(zones::CAPTION_START, "Title bar start")?;
394        ctx.command(
395            CommandSpec::new(CMD_MINIMIZE, "Minimize", "Window")
396                .icon("window-minimize")
397                .description("Minimizes the window.")
398                .menu(MENU_SYSTEM, "1_size", 1)
399                .no_agent(),
400            |call| {
401                request(call.app, &call.app.egui(), FrameRequest::Minimize);
402                Ok(Json::Null)
403            },
404        )?
405        .command(
406            CommandSpec::new(CMD_MAXIMIZE, "Maximize", "Window")
407                .icon("window-maximize")
408                .icon_on("window-restore")
409                .description("Maximizes the window, or restores it.")
410                .checked("windowMaximized")
411                .menu(MENU_SYSTEM, "1_size", 2)
412                .no_agent(),
413            |call| {
414                request(call.app, &call.app.egui(), FrameRequest::ToggleMaximize);
415                Ok(Json::Null)
416            },
417        )?
418        .command(
419            CommandSpec::new(CMD_CLOSE, "Close window", "Window")
420                .icon("window-close")
421                .description("Closes the window, as its close button does.")
422                .menu(MENU_SYSTEM, "9_close", 0)
423                .no_agent(),
424            |call| {
425                request(call.app, &call.app.egui(), FrameRequest::Close);
426                Ok(Json::Null)
427            },
428        )?
429        .command(
430            CommandSpec::new(CMD_SYSTEM_MENU, "Window menu", "Window")
431                .icon("menu")
432                .description("Opens the window's menu (restore, minimize, maximize, close).")
433                .key("Alt+Space")
434                .when("windowOwnFrame")
435                .menu(MENU_VIEW, "9_window", 1)
436                .no_agent(),
437            |call| {
438                let ctx = call.app.egui();
439                let at = HitTable::of(&ctx)
440                    .get(egui::ViewportId::ROOT)
441                    .and_then(|r| r.caption)
442                    .map_or(egui::pos2(0.0, 0.0), |c| {
443                        let ppp = ctx.pixels_per_point();
444                        egui::pos2(c.x as f32 / ppp, (c.y + c.h) as f32 / ppp)
445                    });
446                request(call.app, &ctx, FrameRequest::SystemMenu(at));
447                Ok(Json::Null)
448            },
449        )?;
450        let name = self.name.clone();
451        let logo = self.logo.clone();
452        ctx.block(zones::TITLE, Block::add(BLOCK_TITLE, 0, title_block));
453        if self.layout_controls {
454            // Nearest the window's buttons: drawn first from the end.
455            ctx.block(
456                zones::CAPTION,
457                Block::add(
458                    crate::layout_controls::BLOCK_LAYOUT_CONTROLS,
459                    -1000,
460                    crate::layout_controls::show,
461                ),
462            );
463        }
464        ctx.block(
465            zones::CAPTION_START,
466            Block::add(BLOCK_MENU, 0, move |ui, app| {
467                menu_button(ui, app);
468                let name = if name.is_empty() {
469                    app.name()
470                } else {
471                    name.clone()
472                };
473                if let Some(logo) = &logo {
474                    logo_image(ui, logo, &name);
475                }
476                if !name.is_empty() {
477                    ui.add(
478                        egui::Label::new(egui::RichText::new(&name).strong())
479                            .selectable(false)
480                            .sense(egui::Sense::hover()),
481                    );
482                }
483            }),
484        );
485        ctx.block(
486            zones::OVERLAYS,
487            Block::add(
488                BlockId::from_static("egui_pop.frame.edges"),
489                40,
490                |ui, app| {
491                    edges(ui, app);
492                },
493            ),
494        );
495        let (w1, w2) = (ctx.app().downgrade(), ctx.app().downgrade());
496        ctx.collector(
497            egui_pop_core::debug::FnCollector::new(
498                "frame",
499                "The window frame: drawn by the application or the system; each window's hit regions in physical pixels (caption, buttons, edges).",
500            )
501            .snapshot(move |ctx| {
502                let Ok(app) = w1.get() else { return Json::Null };
503                let table = HitTable::of(ctx);
504                json!({
505                    "own": own_frame(&app),
506                    "hit_test": native::describe(ctx),
507                    "corners": native::describe_corners(ctx),
508                    "windows": table.viewports().into_iter().map(|v| json!({
509                        "viewport": if v == egui::ViewportId::ROOT { "root".to_string() } else { format!("{v:?}") },
510                        "regions": table.get(v).map(|r| (*r).clone()),
511                    })).collect::<Vec<_>>(),
512                })
513            })
514            .action(
515                "hit",
516                "What a point of the main window is (`x`, `y` in physical pixels): caption, a button, an edge or client.",
517                false,
518                move |ctx, args| {
519                    w2.get()?;
520                    let x = args.get("x").and_then(Json::as_i64).ok_or("`x` is missing")? as i32;
521                    let y = args.get("y").and_then(Json::as_i64).ok_or("`y` is missing")? as i32;
522                    let r = HitTable::of(ctx)
523                        .get(egui::ViewportId::ROOT)
524                        .ok_or("the main window publishes no regions (the system draws its frame)")?;
525                    Ok(json!(r.hit(x, y)))
526                },
527            )
528            .args(json!({ "x": 10, "y": 10 })),
529        )?;
530        Ok(())
531    }
532}
533
534/// Keeps the window's decorations in line with the setting; returns
535/// whether the application draws the frame.
536fn follow_setting(ui: &Ui, app: &AppHandle) -> bool {
537    let ctx = ui.ctx();
538    let own = own_frame(app);
539    app.set_context("windowOwnFrame", if own { "true" } else { "false" });
540    let maximized = ctx.input(|i| i.viewport().maximized.unwrap_or(false));
541    app.set_context("windowMaximized", if maximized { "true" } else { "false" });
542    native::follow(ctx, app, own);
543    native::corners(ctx, own);
544    // Given once here; a change of the setting is followed by
545    // `pop.frame.decorations`.
546    if DECORATED.keyed(ctx.viewport_id()).get(ctx).is_none() {
547        decorate(ctx, ctx.viewport_id(), own);
548    }
549    own
550}
551
552/// Gives a window the decorations `own` asks for (none when the
553/// application draws the frame), when it has others.
554fn decorate(ctx: &Context, viewport: egui::ViewportId, own: bool) {
555    let key = DECORATED.keyed(viewport);
556    if key.get(ctx) == Some(own) {
557        return;
558    }
559    // A web page has no window decorations: eframe's web runner does not
560    // handle the command and logs it.
561    #[cfg(not(target_arch = "wasm32"))]
562    ctx.send_viewport_cmd_to(viewport, ViewportCommand::Decorations(!own));
563    key.set(ctx, own);
564    if !own {
565        HitTable::of(ctx).forget(viewport);
566    }
567}
568
569/// Registers `pop.frame.decorations`, egui-pop's local listener of
570/// `pop.settings.changed`: the main window takes the decorations
571/// [`SETTING_FRAME`] asks for in the call that changed it.
572pub(crate) fn listen(app: &AppHandle) {
573    use crate::bus::{FRAME_DECORATIONS, OWNER, SettingsChanged, asking};
574    let listened = app.bus().listen_local::<SettingsChanged>(
575        FRAME_DECORATIONS,
576        bus_contract::ListenOpts::new().owner(OWNER),
577        |change, ()| {
578            if change.id() != SETTING_FRAME.as_str() {
579                return Ok(());
580            }
581            let Some(app) = asking() else { return Ok(()) };
582            decorate(&app.egui(), egui::ViewportId::ROOT, own_frame(&app));
583            Ok(())
584        },
585    );
586    if let Err(e) = listened {
587        log::error!(target: "egui_pop", "{FRAME_DECORATIONS}: {e}");
588    }
589}
590
591fn bar_in_full_screen(ctx: &Context) -> Slot<u64> {
592    BAR_IN_FULL_SCREEN.keyed(ctx.viewport_id())
593}
594
595/// Whether the application drew the current window's title bar in full
596/// screen this pass or the one before (the window plugin's strip at the
597/// top edge is not needed then). The previous pass counts because the
598/// window plugin may draw before the title bar within a pass.
599pub(crate) fn bar_shown_in_full_screen(ctx: &Context) -> bool {
600    bar_in_full_screen(ctx)
601        .get(ctx)
602        .is_some_and(|pass| pass + 1 >= ctx.cumulative_pass_nr())
603}
604
605/// The button opening the system menu (the [`BLOCK_MENU`] block draws
606/// it); an application replacing that block calls it to keep the menu.
607/// A click asks for the menu through the `frame.system_menu` step.
608pub fn menu_button(ui: &mut Ui, app: &AppHandle) -> egui::Response {
609    let r = ui.add(
610        Icon::Menu
611            .size(Size::Toolbar)
612            .label(&strings::tr(ui.ctx(), &txt::FRAME_WINDOW_MENU))
613            .sense_click(),
614    );
615    if r.clicked() {
616        request(
617            app,
618            ui.ctx(),
619            FrameRequest::SystemMenu(r.rect.left_bottom()),
620        );
621    }
622    r
623}
624
625/// The title bar, in the title zone; in full screen, as the
626/// `window.bar_in_fullscreen` setting says.
627fn title_block(ui: &mut Ui, app: &AppHandle) {
628    if !follow_setting(ui, app) {
629        return;
630    }
631    let ctx = ui.ctx().clone();
632    for r in native::requests(&ctx) {
633        request(app, &ctx, r);
634    }
635    if egui_pop_core::frame::full_screen(&ctx) {
636        if !bar_in_fullscreen(app) {
637            egui_pop_core::frame::hide_title_bar(&ctx);
638            return;
639        }
640        let pass = ctx.cumulative_pass_nr();
641        bar_in_full_screen(&ctx).set(&ctx, pass);
642    }
643    let title = ctx
644        .input(|i| i.viewport().title.clone())
645        .unwrap_or_default();
646    let out = TitleBar::new(&title).show(
647        ui,
648        |ui| {
649            if app.zone_has_blocks(&zones::CAPTION_START) {
650                app.show_zone(ui, &zones::CAPTION_START);
651            }
652        },
653        |ui| {
654            if app.zone_has_blocks(&zones::CAPTION) {
655                app.show_zone(ui, &zones::CAPTION);
656            }
657        },
658    );
659    if let Some(r) = out.request {
660        request(app, &ctx, r);
661    }
662}
663
664/// An application window's own frame, when the application draws it (the
665/// `window.frame` setting): a title bar across the top of `ui` with the
666/// window's title and its minimize, maximize and close buttons, the same
667/// bar and accessible names as the main window's, then `content` below
668/// it. Drawn at the top of each application window, and around a
669/// window's content moved into the main window (whose shell, and the
670/// shell's bar, left with it). With `caption_start`, the bar holds the
671/// [`zones::CAPTION_START`] zone at its start, as the main window's does
672/// (`WindowSpec::shell_bars`). The system's frame, or full screen without
673/// the bar, draws `content` alone.
674pub(crate) fn window_frame(
675    ui: &mut Ui,
676    app: &AppHandle,
677    title: &str,
678    caption_start: bool,
679    content: impl FnOnce(&mut Ui),
680) {
681    let ctx = ui.ctx().clone();
682    let root = ctx.viewport_id() == egui::ViewportId::ROOT;
683    // The main window follows the setting itself (its decorations, the
684    // native hit test); an application window is built with the
685    // decorations the setting asks for.
686    let own = if root {
687        follow_setting(ui, app)
688    } else {
689        own_frame(app)
690    };
691    if !own {
692        return content(ui);
693    }
694    if egui_pop_core::frame::full_screen(&ctx) && !bar_in_fullscreen(app) {
695        egui_pop_core::frame::hide_title_bar(&ctx);
696        return content(ui);
697    }
698    if root {
699        // The main window's edges are an overlay block: only its native
700        // requests (Windows' hit test) are left to take here.
701        for r in native::requests(&ctx) {
702            request(app, &ctx, r);
703        }
704    } else {
705        egui_pop_core::frame::resize_edges(&ctx);
706        // Its edge (the main window's is the shell's, `App::outlined`).
707        egui_pop_core::frame::paint_window_edge(
708            &ctx,
709            egui_pop_core::frame::window_edge(&ctx, &crate::window::screens()),
710        );
711    }
712    let full = ui.max_rect();
713    let out = ui
714        .scope_builder(egui::UiBuilder::new().max_rect(full), |ui| {
715            egui_pop_core::focus::scope(ui, "titleBar", &[], |ui| {
716                TitleBar::new(title).show(
717                    ui,
718                    |ui| {
719                        if caption_start && app.zone_has_blocks(&zones::CAPTION_START) {
720                            app.show_zone(ui, &zones::CAPTION_START);
721                        }
722                    },
723                    |_| {},
724                )
725            })
726        })
727        .inner;
728    if let Some(r) = out.request {
729        request(app, &ctx, r);
730    }
731    let rest = Rect::from_min_max(egui::pos2(full.left(), out.rect.bottom()), full.max);
732    ui.scope_builder(egui::UiBuilder::new().max_rect(rest), content);
733}
734
735/// The resize edges, and the system menu when open.
736fn edges(ui: &mut Ui, app: &AppHandle) {
737    let ctx = ui.ctx().clone();
738    if !own_frame(app) {
739        return;
740    }
741    egui_pop_core::frame::resize_edges(&ctx);
742    egui_pop_core::frame::publish(&ctx);
743    let at = SYSTEM_MENU.get(&ctx).flatten();
744    let Some((at, opened)) = at else { return };
745    let spec = OverlaySpec::new("egui_pop.frame.system_menu", "Window menu", Kind::Menu);
746    let mut open = true;
747    let anchor = Anchor {
748        rect: Rect::from_min_size(at, Vec2::ZERO),
749        side: Side::Bottom,
750    };
751    let mut clicked = false;
752    overlay::show(&ctx, &spec, &mut open, Some(anchor), |ui| {
753        crate::menus::show(ui, app, &MENU_SYSTEM);
754        // A click after the one that opened it: an item was chosen (a
755        // click outside closes the overlay by itself).
756        clicked =
757            ui.ctx().cumulative_pass_nr() > opened && ui.ctx().input(|i| i.pointer.any_click());
758    });
759    if !open || clicked {
760        let how = if clicked {
761            overlay::Closing::Chosen
762        } else {
763            overlay::Closing::Owner
764        };
765        app.close_overlay(&ctx, spec.id, how);
766        SYSTEM_MENU.set(&ctx, None);
767    }
768}
769
770/// Records a window's native handle (an `HWND` on Windows), for the
771/// frame's hit testing. `AppBuilder::run_native` does it for the main
772/// window; an application starting eframe itself calls it from its
773/// creation context.
774pub fn set_native_window(ctx: &Context, viewport: egui::ViewportId, handle: isize) {
775    NATIVE_WINDOW.keyed(viewport).set(ctx, handle);
776}
777
778/// Forgets the handle recorded for `viewport` ([`set_native_window`]),
779/// once its window is gone.
780pub fn forget_native_window(ctx: &Context, viewport: egui::ViewportId) {
781    NATIVE_WINDOW.keyed(viewport).remove(ctx);
782}
783
784/// Records the main window's X11 id (Linux, the window on X11 or Xwayland):
785/// what a native view inside it, such as the viewer's web view, is made a
786/// child of. `AppBuilder::run_native` does it; an application starting
787/// eframe itself calls [`record_native_window`].
788pub fn set_x11_window(ctx: &Context, window: u64) {
789    X11_WINDOW.set(ctx, window);
790}
791
792/// The main window's X11 id, when it is an X11 window: none on Wayland, on
793/// other systems, headless, or when it was not recorded.
794pub fn x11_window(ctx: &Context) -> Option<u64> {
795    X11_WINDOW.get(ctx)
796}
797
798/// Records the main window's native handle from eframe's creation context:
799/// the `HWND` on Windows ([`set_native_window`]), the X11 id on Linux's X11
800/// ([`set_x11_window`]), and the window itself, which the system's file
801/// chooser asked from it is attached to (`files::set_parent_window`).
802/// `AppBuilder::run_native` calls it; an application starting eframe
803/// itself calls it from its creation context.
804#[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
805pub fn record_native_window(cc: &eframe::CreationContext<'_>) {
806    if let Some(window) = cc.winit_window() {
807        let window: std::sync::Arc<dyn crate::files::ParentWindow> = window.clone();
808        crate::files::set_parent_window(&cc.egui_ctx, egui::ViewportId::ROOT, window);
809    }
810    #[cfg(windows)]
811    {
812        use raw_window_handle::{HasWindowHandle, RawWindowHandle};
813        if let Ok(h) = cc.window_handle()
814            && let RawWindowHandle::Win32(w) = h.as_raw()
815        {
816            set_native_window(&cc.egui_ctx, egui::ViewportId::ROOT, w.hwnd.get());
817        }
818    }
819    #[cfg(target_os = "linux")]
820    {
821        use raw_window_handle::{HasWindowHandle, RawWindowHandle};
822        if let Ok(h) = cc.window_handle() {
823            match h.as_raw() {
824                // `c_ulong`: 64 bits here, 32 on a 32-bit system.
825                #[allow(
826                    clippy::useless_conversion,
827                    reason = "`c_ulong` is 64 bits here, 32 on a 32-bit system, where the conversion is needed"
828                )]
829                RawWindowHandle::Xlib(w) => set_x11_window(&cc.egui_ctx, u64::from(w.window)),
830                RawWindowHandle::Xcb(w) => set_x11_window(&cc.egui_ctx, w.window.get().into()),
831                _ => {}
832            }
833        }
834    }
835    #[cfg(not(any(windows, target_os = "linux")))]
836    let _ = cc;
837}
838
839/// The frame's Windows layer: the hit-test handler over the published
840/// regions and the requests it hands back.
841mod native {
842    use std::sync::{Arc, Mutex};
843
844    use egui::{Context, ViewportId};
845    use egui_pop_core::frame::{self as core_frame, Button, FrameRequest, Hit, HitTable};
846    use egui_pop_core::kit::{Kit, WindowCorners};
847    use egui_pop_core::lock;
848    use egui_pop_core::state::Slot;
849    use egui_pop_win32::{Area, Corners, Handler, NcEvent, Subclassed};
850    use serde_json::{Value as Json, json};
851
852    use super::STEP_HIT_TEST;
853    use crate::app::AppHandle;
854
855    /// The main window's native handle.
856    fn root_handle(ctx: &Context) -> Option<isize> {
857        super::NATIVE_WINDOW.keyed(ViewportId::ROOT).get(ctx)
858    }
859
860    /// What the layer holds.
861    const NATIVE: Slot<Native> = Slot::new("api.frame.native");
862
863    /// What the layer holds, shared with the window procedure.
864    #[derive(Clone, Debug, Default)]
865    struct Native {
866        installed: Arc<Mutex<Option<Subclassed>>>,
867        events: Arc<Mutex<Vec<NcEvent>>>,
868        error: Arc<Mutex<Option<String>>>,
869        /// The corners last asked for, and what the system said.
870        corners: Arc<Mutex<Option<Asked>>>,
871    }
872
873    /// Corners asked for, and the system's answer.
874    type Asked = (Corners, Result<(), String>);
875
876    fn native(ctx: &Context) -> Native {
877        NATIVE.get_or_insert_with(ctx, Native::default)
878    }
879
880    /// Maps the frame's regions to the system's areas.
881    pub(super) fn area(hit: Hit) -> Area {
882        match hit {
883            Hit::Client => Area::Client,
884            Hit::Caption => Area::Caption,
885            Hit::Minimize => Area::Minimize,
886            Hit::Maximize => Area::Maximize,
887            Hit::Close => Area::Close,
888            Hit::Left => Area::Left,
889            Hit::Right => Area::Right,
890            Hit::Top => Area::Top,
891            Hit::Bottom => Area::Bottom,
892            Hit::TopLeft => Area::TopLeft,
893            Hit::TopRight => Area::TopRight,
894            Hit::BottomLeft => Area::BottomLeft,
895            Hit::BottomRight => Area::BottomRight,
896        }
897    }
898
899    /// Answers the window's hit tests from the published regions; hands
900    /// what the system saw back to the next frame.
901    #[derive(Debug)]
902    pub(super) struct Bridge {
903        pub(super) table: HitTable,
904        pub(super) viewport: ViewportId,
905        pub(super) ctx: Context,
906        pub(super) events: Arc<Mutex<Vec<NcEvent>>>,
907    }
908
909    impl Handler for Bridge {
910        fn hit(&self, x: i32, y: i32) -> Area {
911            self.table.get(self.viewport).map_or(Area::Client, |r| {
912                match r.hit(x, y) {
913                    // In full screen the bar never moves the window: its
914                    // drag, double and right clicks are egui's.
915                    Hit::Caption if r.fullscreen => Area::Client,
916                    hit => area(hit),
917                }
918            })
919        }
920
921        fn event(&self, event: NcEvent) {
922            lock(&self.events).push(event);
923            self.ctx.request_repaint_of(self.viewport);
924        }
925    }
926
927    /// Installs or removes the layer as the setting says, through the
928    /// `frame.hit_test` step (main window only).
929    pub(super) fn follow(ctx: &Context, app: &AppHandle, own: bool) {
930        if ctx.viewport_id() != ViewportId::ROOT {
931            return;
932        }
933        let Some(hwnd) = root_handle(ctx) else {
934            return;
935        };
936        let n = native(ctx);
937        if lock(&n.installed).is_some() == own || (own && lock(&n.error).is_some()) {
938            return;
939        }
940        let (c, n2) = (ctx.clone(), n.clone());
941        app.step(
942            &STEP_HIT_TEST,
943            json!({ "viewport": "root", "install": own }),
944            move |_, args| {
945                let install = args["install"].as_bool().unwrap_or(own);
946                let mut slot = lock(&n2.installed);
947                if !install {
948                    if let Some(s) = slot.take() {
949                        s.remove();
950                    }
951                    core_frame::set_native_hover(&c, ViewportId::ROOT, None);
952                    return Ok(json!({ "installed": false }));
953                }
954                let bridge = Bridge {
955                    table: HitTable::of(&c),
956                    viewport: ViewportId::ROOT,
957                    ctx: c.clone(),
958                    events: n2.events.clone(),
959                };
960                match egui_pop_win32::install(hwnd, Arc::new(bridge)) {
961                    Ok(s) => {
962                        *slot = Some(s);
963                        Ok(json!({ "installed": true }))
964                    }
965                    Err(e) => {
966                        *lock(&n2.error) = Some(e.to_string());
967                        Err(e.to_string())
968                    }
969                }
970            },
971        );
972        if !own {
973            *lock(&n.error) = None;
974        }
975    }
976
977    /// The system's corners for the kit's `window.corners`.
978    pub(super) fn corners_of(c: WindowCorners) -> Corners {
979        match c {
980            WindowCorners::Round => Corners::Round,
981            WindowCorners::Small => Corners::Small,
982            WindowCorners::Square => Corners::Square,
983        }
984    }
985
986    fn corners_name(c: Corners) -> &'static str {
987        match c {
988            Corners::System => "system",
989            Corners::Square => "square",
990            Corners::Round => "round",
991            Corners::Small => "small",
992        }
993    }
994
995    /// Asks the system for the kit's corners while the application draws
996    /// the frame, and for its own default when it no longer does; again
997    /// only when that changes (a theme naming other corners). Main window
998    /// only. What is asked and answered is kept for the debug bridge and
999    /// logged.
1000    pub(super) fn corners(ctx: &Context, own: bool) {
1001        if ctx.viewport_id() != ViewportId::ROOT {
1002            return;
1003        }
1004        let wanted = if own {
1005            corners_of(Kit::of(ctx).window.corners)
1006        } else {
1007            Corners::System
1008        };
1009        let n = native(ctx);
1010        let mut last = lock(&n.corners);
1011        match last.as_ref() {
1012            Some((asked, _)) if *asked == wanted => return,
1013            // Never asked, and the system's frame: nothing to give back.
1014            None if !own => return,
1015            _ => {}
1016        }
1017        let hwnd = root_handle(ctx);
1018        let outcome = match hwnd {
1019            _ if !egui_pop_win32::SUPPORTED => Err(
1020                "not asked: only Windows rounds the corners of a window drawn by the application on request"
1021                    .to_string(),
1022            ),
1023            None => Err("not asked: the window's handle is unknown (see `set_native_window`)".into()),
1024            Some(h) => egui_pop_win32::set_corners(h, wanted).map_err(|e| e.to_string()),
1025        };
1026        match &outcome {
1027            Ok(()) => {
1028                log::info!(target: "egui_pop", "frame: corners `{}` applied", corners_name(wanted))
1029            }
1030            Err(e) => {
1031                log::info!(target: "egui_pop", "frame: corners `{}`: {e}", corners_name(wanted))
1032            }
1033        }
1034        *last = Some((wanted, outcome));
1035    }
1036
1037    /// The corners asked for and the answer, for the debug bridge.
1038    pub(super) fn describe_corners(ctx: &Context) -> Json {
1039        match lock(&native(ctx).corners).as_ref() {
1040            None => json!({ "asked": Json::Null }),
1041            Some((asked, outcome)) => json!({
1042                "asked": corners_name(*asked),
1043                "applied": outcome.is_ok(),
1044                "error": outcome.as_ref().err(),
1045            }),
1046        }
1047    }
1048
1049    /// The requests the system handed back since the last frame.
1050    pub(super) fn requests(ctx: &Context) -> Vec<FrameRequest> {
1051        let n = native(ctx);
1052        let events = std::mem::take(&mut *lock(&n.events));
1053        let ppp = ctx.pixels_per_point();
1054        let mut out = Vec::new();
1055        for e in events {
1056            match e {
1057                NcEvent::Hover(b) => {
1058                    let b = b.and_then(|a| match a {
1059                        Area::Minimize => Some(Button::Minimize),
1060                        Area::Maximize => Some(Button::Maximize),
1061                        Area::Close => Some(Button::Close),
1062                        _ => None,
1063                    });
1064                    core_frame::set_native_hover(ctx, ViewportId::ROOT, b);
1065                }
1066                NcEvent::Press(_) => {}
1067                NcEvent::Click(Area::Minimize) => out.push(FrameRequest::Minimize),
1068                NcEvent::Click(Area::Maximize) | NcEvent::DoubleClick(_) => {
1069                    out.push(FrameRequest::ToggleMaximize);
1070                }
1071                NcEvent::Click(Area::Close) => out.push(FrameRequest::Close),
1072                NcEvent::Click(_) => {}
1073                NcEvent::ContextMenu { x, y } => out.push(FrameRequest::SystemMenu(egui::pos2(
1074                    x as f32 / ppp,
1075                    y as f32 / ppp,
1076                ))),
1077            }
1078        }
1079        out
1080    }
1081
1082    /// What the debug bridge shows.
1083    pub(super) fn describe(ctx: &Context) -> Json {
1084        let n = native(ctx);
1085        json!({
1086            "supported": egui_pop_win32::SUPPORTED,
1087            "window": root_handle(ctx).is_some(),
1088            "installed": lock(&n.installed).is_some(),
1089            "error": lock(&n.error).clone(),
1090        })
1091    }
1092
1093    #[cfg(test)]
1094    mod tests {
1095        use super::*;
1096
1097        #[test]
1098        fn the_kit_corners_are_asked_once_and_reported() {
1099            let ctx = Context::default();
1100            assert_eq!(describe_corners(&ctx), json!({ "asked": null }));
1101            // The system's frame, never the application's: nothing asked.
1102            corners(&ctx, false);
1103            assert_eq!(describe_corners(&ctx)["asked"], Json::Null);
1104            corners(&ctx, true);
1105            let d = describe_corners(&ctx);
1106            assert_eq!(d["asked"], "round");
1107            if !egui_pop_win32::SUPPORTED {
1108                assert_eq!(d["applied"], false);
1109                assert!(d["error"].as_str().unwrap().starts_with("not asked"));
1110            }
1111            // A theme asking for square corners is asked again.
1112            let mut themes = egui_pop_core::theme::Themes::default();
1113            themes
1114                .add_text(
1115                    "square",
1116                    r#"
1117                    $extends: "pop-dark"
1118                    window:
1119                      corners: {$type: "string", $value: "square"}
1120                    "#,
1121                )
1122                .unwrap();
1123            egui_pop_core::theme::install_tokens(
1124                &ctx,
1125                egui_pop_core::theme::Tokens::new(
1126                    themes.resolve(&egui_pop_core::theme::ThemeSpec::new("square")),
1127                ),
1128            );
1129            corners(&ctx, true);
1130            assert_eq!(describe_corners(&ctx)["asked"], "square");
1131            // The system's frame again: its default is given back.
1132            corners(&ctx, false);
1133            assert_eq!(describe_corners(&ctx)["asked"], "system");
1134            assert_eq!(corners_of(WindowCorners::Small), Corners::Small);
1135        }
1136
1137        #[test]
1138        fn the_bridge_answers_from_the_table_and_queues_requests() {
1139            let ctx = Context::default();
1140            let table = HitTable::of(&ctx);
1141            let layout = core_frame::FrameLayout {
1142                window: egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)),
1143                caption: Some(egui::Rect::from_min_size(
1144                    egui::Pos2::ZERO,
1145                    egui::vec2(800.0, 32.0),
1146                )),
1147                maximize: Some(egui::Rect::from_min_size(
1148                    egui::pos2(712.0, 0.0),
1149                    egui::vec2(44.0, 32.0),
1150                )),
1151                grip: 4.0,
1152                resizable: true,
1153                ..Default::default()
1154            };
1155            table.publish(
1156                ViewportId::ROOT,
1157                core_frame::HitRegions::measure(&layout, 1.5),
1158            );
1159            let events = native(&ctx).events;
1160            let b = Bridge {
1161                table,
1162                viewport: ViewportId::ROOT,
1163                ctx: ctx.clone(),
1164                events: events.clone(),
1165            };
1166            assert_eq!(b.hit(600, 24), Area::Caption);
1167            assert_eq!(b.hit((734.0 * 1.5) as i32, 24), Area::Maximize);
1168            assert_eq!(b.hit(2, 400), Area::Left);
1169            assert_eq!(b.hit(600, 400), Area::Client);
1170            for e in [
1171                NcEvent::Hover(Some(Area::Maximize)),
1172                NcEvent::Click(Area::Maximize),
1173                NcEvent::DoubleClick(Area::Caption),
1174                NcEvent::ContextMenu { x: 30, y: 15 },
1175                NcEvent::Click(Area::Close),
1176            ] {
1177                b.event(e);
1178            }
1179            let r = requests(&ctx);
1180            assert_eq!(
1181                r,
1182                vec![
1183                    FrameRequest::ToggleMaximize,
1184                    FrameRequest::ToggleMaximize,
1185                    FrameRequest::SystemMenu(egui::pos2(30.0, 15.0)),
1186                    FrameRequest::Close,
1187                ]
1188            );
1189            assert_eq!(core_frame::native_hover(&ctx), Some(Button::Maximize));
1190            assert!(requests(&ctx).is_empty());
1191            // In full screen, the caption is client area: the system
1192            // must not move the window.
1193            b.table.publish(
1194                ViewportId::ROOT,
1195                core_frame::HitRegions::measure(
1196                    &core_frame::FrameLayout {
1197                        fullscreen: true,
1198                        resizable: false,
1199                        ..layout
1200                    },
1201                    1.5,
1202                ),
1203            );
1204            assert_eq!(b.hit(600, 24), Area::Client);
1205            assert_eq!(b.hit(2, 400), Area::Client);
1206        }
1207    }
1208}