Skip to main content

egui_pop_core/
frame.rs

1//! The window's own frame, for windows drawn without the system's
2//! decorations: a title bar (a caption to drag, double click to
3//! maximize, the minimize, maximize and close buttons, room for a logo
4//! and for the application's items) and resize edges along the window's
5//! sides, never thinner than [`MIN_GRIP_PX`] physical pixels.
6//!
7//! **In full screen** the bar stays (it holds the application's menus and
8//! items) without what only a window needs: no minimize, a button leaving
9//! full screen where maximize was ([`FrameRequest::ExitFullscreen`]), no
10//! drag, a double click asking nothing, and no resize edges.
11//!
12//! The frame **publishes its hit regions** every frame, per window, in
13//! physical client pixels ([`HitRegions`], read through [`HitTable`]):
14//! what a platform layer needs to answer the system's hit tests itself
15//! (on Windows, `WM_NCHITTEST`, so that Snap Layouts show over the
16//! maximize button). [`HitRegions::hit`] maps a point to its region.
17//!
18//! The widget only reports what was asked ([`FrameRequest`]); dragging
19//! and resizing are handed to the system at once. What a request does is
20//! the application's (egui-pop's `frame` plugin turns them into steps
21//! plugins may veto or replace).
22//!
23//! ```
24//! use egui_pop_core::frame::{self, FrameRequest};
25//!
26//! fn ui(ui: &mut egui::Ui) {
27//!     frame::resize_edges(ui.ctx());
28//!     let out = frame::TitleBar::new("My application").show(ui, |_| {}, |_| {});
29//!     match out.request {
30//!         Some(FrameRequest::Close) => ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close),
31//!         Some(FrameRequest::Minimize) => {
32//!             ui.ctx().send_viewport_cmd(egui::ViewportCommand::Minimized(true))
33//!         }
34//!         _ => {}
35//!     }
36//! }
37//! ```
38
39use std::collections::BTreeMap;
40use std::sync::{Arc, Mutex};
41
42use egui::{
43    Color32, Context, CursorIcon, Pos2, Rect, ResizeDirection, Role, Sense, Ui, Vec2,
44    ViewportCommand, ViewportId, pos2, vec2,
45};
46use serde::Serialize;
47
48use crate::a11y;
49use crate::kit::{ButtonsHover, ButtonsSide, Glyph, Kit, KitCx, Part, State, Tone};
50use crate::state::{Slot, lock};
51use crate::theme::Tokens;
52
53/// The thinnest resize edge, in physical pixels, whatever the scale.
54pub const MIN_GRIP_PX: f32 = 6.0;
55
56/// What a point of a window is, for the system's hit test.
57#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
58#[serde(rename_all = "snake_case")]
59pub enum Hit {
60    /// The application's: widgets, content.
61    Client,
62    /// The title bar: drags the window, double click maximizes, a right
63    /// click opens the system menu.
64    Caption,
65    Minimize,
66    Maximize,
67    Close,
68    Left,
69    Right,
70    Top,
71    Bottom,
72    TopLeft,
73    TopRight,
74    BottomLeft,
75    BottomRight,
76}
77
78/// A rectangle in physical client pixels (from the window's client
79/// area's top left corner).
80#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize)]
81pub struct RectPx {
82    pub x: i32,
83    pub y: i32,
84    pub w: i32,
85    pub h: i32,
86}
87
88impl RectPx {
89    /// A rectangle in points, at `ppp` physical pixels per point,
90    /// rounded to the pixels it covers.
91    pub fn from_points(r: Rect, ppp: f32) -> RectPx {
92        let x0 = (r.min.x * ppp).round() as i32;
93        let y0 = (r.min.y * ppp).round() as i32;
94        let x1 = (r.max.x * ppp).round() as i32;
95        let y1 = (r.max.y * ppp).round() as i32;
96        RectPx {
97            x: x0,
98            y: y0,
99            w: (x1 - x0).max(0),
100            h: (y1 - y0).max(0),
101        }
102    }
103
104    pub fn contains(&self, x: i32, y: i32) -> bool {
105        x >= self.x && y >= self.y && x < self.x + self.w && y < self.y + self.h
106    }
107}
108
109/// A window's frame regions, in physical client pixels.
110#[derive(Clone, Debug, Default, PartialEq, Serialize)]
111pub struct HitRegions {
112    /// Physical pixels per point when they were measured.
113    pub pixels_per_point: f32,
114    /// The client area's size.
115    pub size: [i32; 2],
116    /// The title bar.
117    pub caption: Option<RectPx>,
118    /// Widgets on the title bar (a logo, menus, the application's
119    /// buttons): they take their own clicks.
120    pub holes: Vec<RectPx>,
121    pub minimize: Option<RectPx>,
122    pub maximize: Option<RectPx>,
123    pub close: Option<RectPx>,
124    /// The resize edges' width; zero when the window cannot be resized
125    /// from its edges (maximized, full screen).
126    pub grip: i32,
127    /// The window is in full screen: its caption does not move it (a
128    /// platform layer answers it as client area).
129    pub fullscreen: bool,
130}
131
132impl HitRegions {
133    /// The regions of a frame laid out in points.
134    pub fn measure(layout: &FrameLayout, ppp: f32) -> HitRegions {
135        let px = |r: Rect| RectPx::from_points(r, ppp);
136        let window = px(layout.window);
137        HitRegions {
138            pixels_per_point: ppp,
139            size: [window.w, window.h],
140            caption: layout.caption.map(px),
141            holes: layout.holes.iter().copied().map(px).collect(),
142            minimize: layout.minimize.map(px),
143            maximize: layout.maximize.map(px),
144            close: layout.close.map(px),
145            grip: if layout.resizable {
146                (layout.grip * ppp).round().max(MIN_GRIP_PX) as i32
147            } else {
148                0
149            },
150            fullscreen: layout.fullscreen,
151        }
152    }
153
154    /// What the point `(x, y)` (physical client pixels) is: a resize
155    /// edge first, then a button, a widget on the bar, the caption,
156    /// else the client area.
157    pub fn hit(&self, x: i32, y: i32) -> Hit {
158        let [w, h] = self.size;
159        if self.grip > 0 && x >= 0 && y >= 0 && x < w && y < h {
160            let g = self.grip;
161            let (left, right) = (x < g, x >= w - g);
162            let (top, bottom) = (y < g, y >= h - g);
163            let edge = match (left, right, top, bottom) {
164                (true, _, true, _) => Some(Hit::TopLeft),
165                (_, true, true, _) => Some(Hit::TopRight),
166                (true, _, _, true) => Some(Hit::BottomLeft),
167                (_, true, _, true) => Some(Hit::BottomRight),
168                (true, ..) => Some(Hit::Left),
169                (_, true, ..) => Some(Hit::Right),
170                (_, _, true, _) => Some(Hit::Top),
171                (_, _, _, true) => Some(Hit::Bottom),
172                _ => None,
173            };
174            if let Some(e) = edge {
175                return e;
176            }
177        }
178        let inside = |r: &Option<RectPx>| r.is_some_and(|r| r.contains(x, y));
179        if inside(&self.close) {
180            Hit::Close
181        } else if inside(&self.maximize) {
182            Hit::Maximize
183        } else if inside(&self.minimize) {
184            Hit::Minimize
185        } else if self.holes.iter().any(|r| r.contains(x, y)) {
186            Hit::Client
187        } else if inside(&self.caption) {
188            Hit::Caption
189        } else {
190            Hit::Client
191        }
192    }
193}
194
195/// A frame's parts in points, as drawn.
196#[derive(Clone, Debug, PartialEq)]
197pub struct FrameLayout {
198    /// The window's client area.
199    pub window: Rect,
200    pub caption: Option<Rect>,
201    pub holes: Vec<Rect>,
202    pub minimize: Option<Rect>,
203    pub maximize: Option<Rect>,
204    pub close: Option<Rect>,
205    /// The resize edges' width in points (before the pixel minimum).
206    pub grip: f32,
207    pub resizable: bool,
208    /// The window is in full screen.
209    pub fullscreen: bool,
210}
211
212impl Default for FrameLayout {
213    fn default() -> Self {
214        Self {
215            window: Rect::NOTHING,
216            caption: None,
217            holes: Vec::new(),
218            minimize: None,
219            maximize: None,
220            close: None,
221            grip: 0.0,
222            resizable: false,
223            fullscreen: false,
224        }
225    }
226}
227
228/// Every window's published regions, shared: a platform layer keeps a
229/// clone and reads a window's regions without calling into egui. The
230/// lock is held only to swap or clone an `Arc`.
231#[derive(Clone, Debug, Default)]
232pub struct HitTable(Arc<Mutex<BTreeMap<ViewportId, Arc<HitRegions>>>>);
233
234impl HitTable {
235    /// The context's table (one per context, made on first use).
236    pub fn of(ctx: &Context) -> HitTable {
237        const TABLE: Slot<HitTable> = Slot::new("core.frame.table");
238        TABLE.get_or_insert_with(ctx, HitTable::default)
239    }
240
241    /// A window's last published regions.
242    pub fn get(&self, viewport: ViewportId) -> Option<Arc<HitRegions>> {
243        lock(&self.0).get(&viewport).cloned()
244    }
245
246    /// Every window with regions.
247    pub fn viewports(&self) -> Vec<ViewportId> {
248        lock(&self.0).keys().copied().collect()
249    }
250
251    /// Publishes a window's regions.
252    pub fn publish(&self, viewport: ViewportId, regions: HitRegions) {
253        lock(&self.0).insert(viewport, Arc::new(regions));
254    }
255
256    /// Forgets a window (closed, or drawn by the system again).
257    pub fn forget(&self, viewport: ViewportId) {
258        lock(&self.0).remove(&viewport);
259    }
260}
261
262/// The parts of the current window's frame drawn this pass, merged and
263/// published by [`publish`], per window.
264const PENDING: Slot<FrameLayout> = Slot::new("core.frame.pending");
265
266fn pending(ctx: &Context) -> Slot<FrameLayout> {
267    PENDING.keyed(ctx.viewport_id())
268}
269
270fn update_pending(ctx: &Context, f: impl FnOnce(&mut FrameLayout)) {
271    let slot = pending(ctx);
272    let mut layout = slot.get_or_default(ctx);
273    f(&mut layout);
274    slot.set(ctx, layout);
275}
276
277/// Publishes the current window's regions from what the frame drew this
278/// pass (the title bar and the edges); `TitleBar::show` calls it.
279pub fn publish(ctx: &Context) -> HitRegions {
280    let mut layout = pending(ctx).get_or_default(ctx);
281    layout.window = ctx.content_rect();
282    if layout.grip == 0.0 {
283        layout.grip = grip_token(ctx);
284    }
285    layout.resizable = resizable(ctx);
286    layout.fullscreen = full_screen(ctx);
287    let regions = HitRegions::measure(&layout, ctx.pixels_per_point());
288    HitTable::of(ctx).publish(ctx.viewport_id(), regions.clone());
289    regions
290}
291
292/// Says the current window shows no title bar this pass (full screen
293/// without its bar, a zen mode): its caption and buttons are left out of
294/// the next [`publish`].
295pub fn hide_title_bar(ctx: &Context) {
296    update_pending(ctx, |l| {
297        l.caption = None;
298        l.holes.clear();
299        l.minimize = None;
300        l.maximize = None;
301        l.close = None;
302    });
303}
304
305/// The current window's published regions.
306pub fn regions(ctx: &Context) -> Option<Arc<HitRegions>> {
307    HitTable::of(ctx).get(ctx.viewport_id())
308}
309
310/// The line the kit draws around a window the application draws
311/// (`window.rest.border-width`), dimmer while another window has the
312/// focus (`window.inactive.border-color`), or none in full screen. A
313/// maximized window keeps it.
314pub fn outline(ctx: &Context) -> egui::Stroke {
315    if full_screen(ctx) {
316        return egui::Stroke::NONE;
317    }
318    let kit = crate::kit::Kit::of(ctx);
319    // Unknown (a backend that does not say): drawn as the active one.
320    if ctx.input(|i| i.viewport().focused).unwrap_or(true) {
321        kit.window.outline
322    } else {
323        kit.window_edge.inactive
324    }
325}
326
327/// The sides of a window against an edge of its screen (tiled or
328/// snapped there): its corners on those sides stay square.
329#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
330pub struct Stuck {
331    pub left: bool,
332    pub top: bool,
333    pub right: bool,
334    pub bottom: bool,
335}
336
337impl Stuck {
338    /// The sides of `outer` (the window with its frame, in points)
339    /// within a point of an edge of the screen it overlaps most, among
340    /// `screens`; none without screens.
341    pub fn against(outer: Rect, screens: &[Rect]) -> Stuck {
342        let area = |s: &Rect| {
343            let i = s.intersect(outer);
344            if i.is_positive() { i.area() } else { 0.0 }
345        };
346        let Some(screen) = screens
347            .iter()
348            .filter(|s| area(s) > 0.0)
349            .max_by(|a, b| area(a).total_cmp(&area(b)))
350        else {
351            return Stuck::default();
352        };
353        const NEAR: f32 = 1.0;
354        Stuck {
355            left: (outer.left() - screen.left()).abs() <= NEAR,
356            top: (outer.top() - screen.top()).abs() <= NEAR,
357            right: (screen.right() - outer.right()).abs() <= NEAR,
358            bottom: (screen.bottom() - outer.bottom()).abs() <= NEAR,
359        }
360    }
361}
362
363/// Where a window stands, for its corners: maximized, in full screen,
364/// against a screen's edges. `None` is a state the backend does not
365/// tell.
366#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
367pub struct Placement {
368    pub maximized: Option<bool>,
369    pub fullscreen: Option<bool>,
370    pub stuck: Stuck,
371}
372
373impl Placement {
374    /// The current window's, its sides against `screens` (in points) as
375    /// far as the system tells where it is: X11 and Windows do, Wayland
376    /// does not (no window position, and winit 0.30 keeps the
377    /// compositor's tiled states to itself), so a window tiled there
378    /// counts as free.
379    pub fn of(ctx: &Context, screens: &[Rect]) -> Placement {
380        ctx.input(|i| {
381            let v = i.viewport();
382            Placement {
383                maximized: v.maximized,
384                fullscreen: v.fullscreen,
385                stuck: v
386                    .outer_rect
387                    .map(|r| Stuck::against(r, screens))
388                    .unwrap_or_default(),
389            }
390        })
391    }
392
393    /// Whether the window floats free: known not maximized and not in
394    /// full screen.
395    pub fn floating(&self) -> bool {
396        self.maximized == Some(false) && self.fullscreen == Some(false)
397    }
398}
399
400/// A window's corners from its theme's `radius` (in points) and where it
401/// stands: rounded only while it floats free, a corner square on a side
402/// against a screen's edge; all square when maximized, in full screen,
403/// or when the backend does not tell those states.
404pub fn corner_radius(radius: f32, place: &Placement) -> egui::CornerRadius {
405    if radius <= 0.0 || !place.floating() {
406        return egui::CornerRadius::ZERO;
407    }
408    let r = radius.round().clamp(0.0, f32::from(u8::MAX)) as u8;
409    let s = place.stuck;
410    let at = |a: bool, b: bool| if a || b { 0 } else { r };
411    egui::CornerRadius {
412        nw: at(s.left, s.top),
413        ne: at(s.right, s.top),
414        sw: at(s.left, s.bottom),
415        se: at(s.right, s.bottom),
416    }
417}
418
419/// Whether the windows this context decorates may have rounded corners:
420/// they are built transparent (what shows outside a rounded corner is
421/// the desktop). Off unless said ([`set_rounding`]).
422const ROUNDING: Slot<bool> = Slot::new("core.frame.rounding");
423
424/// Says whether the windows the application decorates are built
425/// transparent, so that [`window_edge`] may round their corners.
426pub fn set_rounding(ctx: &Context, on: bool) {
427    ROUNDING.set(ctx, on);
428    if on {
429        // Ready before the first pass that rounds (a plugin added during
430        // a pass only runs from the next).
431        install_rounding(ctx);
432    }
433}
434
435/// Installs the end-of-pass rounding once per context.
436fn install_rounding(ctx: &Context) {
437    let st = crate::state::shared::<RoundState>(ctx, "core.frame.round_state");
438    let mut st = lock(&st);
439    if !st.installed {
440        st.installed = true;
441        ctx.add_plugin(RoundCorners);
442    }
443}
444
445/// Whether [`set_rounding`] turned rounded corners on.
446pub fn rounding(ctx: &Context) -> bool {
447    ROUNDING.get(ctx).unwrap_or(false)
448}
449
450/// The line and corners of the current window's own edge
451/// ([`window_edge`]).
452#[derive(Clone, Copy, Debug, Default, PartialEq)]
453pub struct WindowEdge {
454    /// The line around the window ([`outline`]).
455    pub stroke: egui::Stroke,
456    /// Its corners ([`corner_radius`]); square without [`rounding`].
457    pub corners: egui::CornerRadius,
458}
459
460/// The current window's edge as the kit and its placement say, its sides
461/// against `screens` (in points) square.
462pub fn window_edge(ctx: &Context, screens: &[Rect]) -> WindowEdge {
463    let corners = if rounding(ctx) {
464        corner_radius(
465            crate::kit::Kit::of(ctx).window_edge.radius,
466            &Placement::of(ctx, screens),
467        )
468    } else {
469        egui::CornerRadius::ZERO
470    };
471    WindowEdge {
472        stroke: outline(ctx),
473        corners,
474    }
475}
476
477/// The corners to round in the current window at the end of this pass.
478const ROUND: Slot<egui::CornerRadius> = Slot::new("core.frame.round");
479
480/// Draws the current window's edge: its line over everything, inside
481/// the window, and, with rounded corners, rounds at the end of the pass
482/// what egui painted at the window's corners (the panels' and bars'
483/// backgrounds), so the transparent window shows through outside them.
484/// A mesh there (a picture) is left as painted.
485pub fn paint_window_edge(ctx: &Context, edge: WindowEdge) {
486    let rect = ctx.content_rect();
487    if edge.stroke.width > 0.0 {
488        ctx.layer_painter(egui::LayerId::new(
489            egui::Order::Foreground,
490            egui::Id::unique("egui_pop.window_edge"),
491        ))
492        .rect_stroke(rect, edge.corners, edge.stroke, egui::StrokeKind::Inside);
493    }
494    if edge.corners != egui::CornerRadius::ZERO {
495        install_rounding(ctx);
496        ROUND.keyed(ctx.viewport_id()).set(ctx, edge.corners);
497    }
498}
499
500#[derive(Debug, Default)]
501struct RoundState {
502    installed: bool,
503}
504
505/// Rounds, at the end of a window's pass, the rectangles painted over
506/// its corners ([`paint_window_edge`]).
507#[derive(Debug)]
508struct RoundCorners;
509
510impl egui::plugin::Plugin for RoundCorners {
511    fn debug_name(&self) -> &'static str {
512        "egui_pop_core::frame::round_corners"
513    }
514
515    fn on_end_pass(&mut self, ui: &mut Ui) {
516        let ctx = ui.ctx().clone();
517        let slot = ROUND.keyed(ctx.viewport_id());
518        // Said again each pass it is wanted.
519        let Some(corners) = slot.remove(&ctx) else {
520            return;
521        };
522        let window = ctx.content_rect();
523        let mut layers: Vec<egui::LayerId> = ctx.memory(|m| m.layer_ids().collect());
524        layers.push(egui::LayerId::background());
525        ctx.graphics_mut(|g| {
526            for layer in layers {
527                if let Some(list) = g.get_mut(layer) {
528                    for i in 0..list.next_idx().0 {
529                        list.mutate_shape(egui::layers::ShapeIdx(i), |c| {
530                            round_shape(&mut c.shape, window, corners);
531                        });
532                    }
533                }
534            }
535        });
536    }
537}
538
539/// Rounds `shape`'s corners that cover `window`'s, by `corners`: a
540/// rectangle (and those in a list of shapes) over a corner of the window
541/// or within a line's width of it (the shell inside the window's line),
542/// its radius less what it stands in from the corner. A plain fill
543/// reaching past the window is cut back to it first; a line, a picture
544/// or a shadow keeps its place.
545pub fn round_shape(shape: &mut egui::Shape, window: Rect, corners: egui::CornerRadius) {
546    /// How far in from a corner a rectangle still counts as on it.
547    const NEAR: f32 = 2.0;
548    match shape {
549        egui::Shape::Vec(shapes) => {
550            for s in shapes {
551                round_shape(s, window, corners);
552            }
553        }
554        egui::Shape::Rect(r) => {
555            let fixed = r.stroke.width > 0.0 || r.brush.is_some() || r.blur_width > 0.0;
556            // Per corner: how far in the rectangle stands (negative: past
557            // the window's edge), on each axis.
558            let insets = |rect: Rect| {
559                let (l, t) = (rect.left() - window.left(), rect.top() - window.top());
560                let (rt, b) = (
561                    window.right() - rect.right(),
562                    window.bottom() - rect.bottom(),
563                );
564                [(l, t), (rt, t), (l, b), (rt, b)]
565            };
566            let want = [corners.nw, corners.ne, corners.sw, corners.se];
567            let on = |(x, y): (f32, f32), w: u8| {
568                w > 0 && x <= NEAR && y <= NEAR && (!fixed || (x >= -NEAR && y >= -NEAR))
569            };
570            if !insets(r.rect).iter().zip(want).any(|(i, w)| on(*i, w)) {
571                return;
572            }
573            if !fixed {
574                r.rect = r.rect.intersect(window);
575            }
576            let c = &mut r.corner_radius;
577            let mine = [&mut c.nw, &mut c.ne, &mut c.sw, &mut c.se];
578            for ((inset, w), mine) in insets(r.rect).into_iter().zip(want).zip(mine) {
579                if on(inset, w) {
580                    let less = inset.0.max(inset.1).max(0.0);
581                    let radius = (f32::from(w) - less).round().max(0.0) as u8;
582                    *mine = (*mine).max(radius);
583                }
584            }
585        }
586        _ => {}
587    }
588}
589
590/// Whether the current window is in full screen.
591pub fn full_screen(ctx: &Context) -> bool {
592    ctx.input(|i| i.viewport().fullscreen.unwrap_or(false))
593}
594
595fn resizable(ctx: &Context) -> bool {
596    ctx.input(|i| {
597        let v = i.viewport();
598        !v.maximized.unwrap_or(false) && !v.fullscreen.unwrap_or(false)
599    })
600}
601
602/// The resize edges' width in points here: the token, never under
603/// [`MIN_GRIP_PX`] physical pixels.
604pub fn grip(ctx: &Context) -> f32 {
605    grip_token(ctx).max(MIN_GRIP_PX / ctx.pixels_per_point())
606}
607
608/// The resize edges' width the theme gives (`window.grip`).
609fn grip_token(ctx: &Context) -> f32 {
610    Tokens::of(ctx)
611        .resolved()
612        .dimension("window.grip")
613        .unwrap_or(0.0)
614}
615
616/// Lets the window be resized from its edges and corners, as a system
617/// frame would; call it before drawing the window's content. Returns the
618/// edge under the pointer.
619pub fn resize_edges(ctx: &Context) -> Option<ResizeDirection> {
620    let g = grip(ctx);
621    update_pending(ctx, |l| l.grip = g);
622    if !resizable(ctx) {
623        return None;
624    }
625    let pos = ctx.input(|i| i.pointer.hover_pos())?;
626    let r = ctx.content_rect();
627    let (left, right) = (pos.x - r.left() < g, r.right() - pos.x < g);
628    let (top, bottom) = (pos.y - r.top() < g, r.bottom() - pos.y < g);
629    let direction = match (left, right, top, bottom) {
630        (true, _, true, _) => ResizeDirection::NorthWest,
631        (_, true, true, _) => ResizeDirection::NorthEast,
632        (true, _, _, true) => ResizeDirection::SouthWest,
633        (_, true, _, true) => ResizeDirection::SouthEast,
634        (true, ..) => ResizeDirection::West,
635        (_, true, ..) => ResizeDirection::East,
636        (_, _, true, _) => ResizeDirection::North,
637        (_, _, _, true) => ResizeDirection::South,
638        _ => return None,
639    };
640    ctx.set_cursor_icon(match direction {
641        ResizeDirection::North | ResizeDirection::South => CursorIcon::ResizeVertical,
642        ResizeDirection::East | ResizeDirection::West => CursorIcon::ResizeHorizontal,
643        ResizeDirection::NorthWest | ResizeDirection::SouthEast => CursorIcon::ResizeNwSe,
644        ResizeDirection::NorthEast | ResizeDirection::SouthWest => CursorIcon::ResizeNeSw,
645    });
646    if ctx.input(|i| i.pointer.primary_pressed()) {
647        ctx.send_viewport_cmd(ViewportCommand::BeginResize(direction));
648        compositor_grab(ctx);
649    }
650    Some(direction)
651}
652
653/// Says that the compositor takes the pointer from this pass on, for an
654/// interactive move or resize of the window (`ViewportCommand::StartDrag`,
655/// `BeginResize`): the next pass of this window starts with the primary
656/// button released, if egui still holds it down.
657///
658/// upstream: Wayland compositors (labwc, GNOME's mutter) keep the
659/// button's release for their move, and winit never hands it to the
660/// window: egui then believes the button held until the pointer leaves
661/// the window, every click after it a drag or nothing (docs/upstream.md,
662/// "winit: no release after a compositor move on Wayland"). A release that
663/// does come later finds the button up and changes nothing.
664pub fn compositor_grab(ctx: &Context) {
665    let viewport = ctx.viewport_id();
666    let st = crate::state::shared::<Grabs>(ctx, "core.frame.grabs");
667    let mut grabs = lock(&st);
668    if !grabs.installed {
669        grabs.installed = true;
670        ctx.add_plugin(ReleaseAfterGrab);
671    }
672    if !grabs.pending.contains(&viewport) {
673        grabs.pending.push(viewport);
674    }
675}
676
677/// The windows whose compositor took the pointer ([`compositor_grab`]).
678#[derive(Debug, Default)]
679struct Grabs {
680    installed: bool,
681    pending: Vec<ViewportId>,
682}
683
684/// Releases the primary button in a window's next pass after a
685/// compositor grab ([`compositor_grab`]).
686#[derive(Debug)]
687struct ReleaseAfterGrab;
688
689impl egui::plugin::Plugin for ReleaseAfterGrab {
690    fn debug_name(&self) -> &'static str {
691        "egui_pop_core::frame::release_after_grab"
692    }
693
694    fn input_hook(&mut self, ctx: &Context, input: &mut egui::RawInput) {
695        let viewport = input.viewport_id;
696        {
697            let st = crate::state::shared::<Grabs>(ctx, "core.frame.grabs");
698            let mut grabs = lock(&st);
699            let Some(at) = grabs.pending.iter().position(|v| *v == viewport) else {
700                return;
701            };
702            grabs.pending.swap_remove(at);
703        }
704        let (down, pos) = ctx.input_for(viewport, |i| {
705            (i.pointer.primary_down(), i.pointer.latest_pos())
706        });
707        let released = input.events.iter().any(|e| {
708            matches!(
709                e,
710                egui::Event::PointerButton {
711                    button: egui::PointerButton::Primary,
712                    pressed: false,
713                    ..
714                }
715            )
716        });
717        if down && !released {
718            // Before anything else of the pass: a press that follows is a
719            // new one.
720            input.events.insert(
721                0,
722                egui::Event::PointerButton {
723                    pos: pos.unwrap_or_default(),
724                    button: egui::PointerButton::Primary,
725                    pressed: false,
726                    modifiers: ctx.input_for(viewport, |i| i.modifiers),
727                },
728            );
729        }
730    }
731}
732
733/// What the user asked of the window through its frame.
734#[derive(Clone, Copy, Debug, PartialEq)]
735pub enum FrameRequest {
736    Minimize,
737    /// Maximize, or restore when maximized.
738    ToggleMaximize,
739    Close,
740    /// The system menu, opened at this point (a right click on the
741    /// caption, or the logo).
742    SystemMenu(Pos2),
743    /// Leave full screen (the button in place of maximize).
744    ExitFullscreen,
745}
746
747/// What [`TitleBar::show`] gives back.
748#[derive(Clone, Debug, PartialEq)]
749pub struct TitleBarOutput {
750    pub request: Option<FrameRequest>,
751    /// The bar.
752    pub rect: Rect,
753    /// Where the title was drawn; `None` when there was no room for it.
754    pub title: Option<Rect>,
755    /// Its parts, in points (the window's rectangle is left empty).
756    pub layout: FrameLayout,
757}
758
759/// A window button.
760#[derive(Clone, Copy, Debug, PartialEq, Eq)]
761pub enum Button {
762    Minimize,
763    Maximize,
764    Close,
765}
766
767/// The title bar.
768#[derive(Clone, Debug)]
769pub struct TitleBar<'a> {
770    title: &'a str,
771    buttons: [bool; 3],
772    publish: bool,
773    full_screen: Option<bool>,
774}
775
776impl<'a> TitleBar<'a> {
777    /// A bar showing `title`, with the three buttons.
778    pub fn new(title: &'a str) -> Self {
779        Self {
780            title,
781            buttons: [true; 3],
782            publish: true,
783            full_screen: None,
784        }
785    }
786
787    /// Draws the bar as in full screen (`true`) or not, whatever the
788    /// window is (a preview); by default, as the window is.
789    pub fn full_screen(mut self, on: bool) -> Self {
790        self.full_screen = Some(on);
791        self
792    }
793
794    /// Whether the bar publishes the window's regions (off for a preview
795    /// drawn inside a window).
796    pub fn publish(mut self, on: bool) -> Self {
797        self.publish = on;
798        self
799    }
800
801    /// Shows or hides a button (an auxiliary window without minimize).
802    pub fn button(mut self, which: Button, shown: bool) -> Self {
803        self.buttons[which as usize] = shown;
804        self
805    }
806
807    /// Draws the bar across `ui`'s width (a top panel's `ui`), with
808    /// `leading` items after the start edge (a logo, a menu) and
809    /// `trailing` items before the buttons (the application's buttons);
810    /// both take their own clicks and are published as holes in the
811    /// caption. Publishes the window's regions.
812    pub fn show(
813        self,
814        ui: &mut Ui,
815        leading: impl FnOnce(&mut Ui),
816        trailing: impl FnOnce(&mut Ui),
817    ) -> TitleBarOutput {
818        let ctx = ui.ctx().clone();
819        let t = Tokens::of(&ctx);
820        let kit = Kit::of(&ctx);
821        let height = kit.title_bar.data.height;
822        let maximized = ctx.input(|i| i.viewport().maximized.unwrap_or(false));
823        let fullscreen = self.full_screen.unwrap_or_else(|| full_screen(&ctx));
824        let full = ui.max_rect();
825        let bar = Rect::from_min_size(full.min, vec2(full.width(), height));
826        let ppp = ctx.pixels_per_point();
827        // The bar's box first; its label (the title) after the items.
828        kit.title_bar.paint(
829            &KitCx {
830                painter: ui.painter(),
831                ppp,
832            },
833            &Part {
834                rect: bar,
835                room: bar,
836                state: State::REST,
837                label: None,
838            },
839        );
840        // The caption: drag, double click, right click. Widgets on the
841        // bar are drawn after it and take their clicks first. In full
842        // screen the bar neither moves the window nor maximizes it. No Tab
843        // stop: focused, it would show nothing and answer no key.
844        let drag = ui.interact(
845            bar,
846            ui.scope_id().with("egui_pop.caption"),
847            Sense::CLICK | Sense::DRAG,
848        );
849        let mut request = None;
850        if drag.double_clicked() {
851            if !fullscreen {
852                request = Some(FrameRequest::ToggleMaximize);
853            }
854        } else if drag.drag_started() {
855            if !fullscreen {
856                ctx.send_viewport_cmd(ViewportCommand::StartDrag);
857                compositor_grab(&ctx);
858            }
859        } else if crate::pointer::claim::opens_context_menu(&drag) {
860            let at = drag.interact_pointer_pos().unwrap_or(bar.left_bottom());
861            request = Some(FrameRequest::SystemMenu(at));
862        }
863        let mut layout = FrameLayout {
864            caption: Some(bar),
865            fullscreen,
866            ..FrameLayout::default()
867        };
868        // The buttons, from the edge `title-bar.buttons-side` names, close
869        // outermost: minimize, maximize, close at the end edge; close,
870        // minimize, maximize from the start edge. In full screen: no
871        // minimize, and the way out of full screen where maximize was.
872        let mut buttons = self.buttons;
873        if fullscreen {
874            buttons[Button::Minimize as usize] = false;
875            buttons[Button::Maximize as usize] = true;
876        }
877        let side = kit.window.buttons_side;
878        let order = match side {
879            ButtonsSide::End => [Button::Close, Button::Maximize, Button::Minimize],
880            ButtonsSide::Start => [Button::Close, Button::Minimize, Button::Maximize],
881        };
882        // The buttons and the items are centred above the bar's line.
883        let line = kit.title_bar.style(State::REST).border_width;
884        let inner = bar.with_max_y(bar.bottom() - line);
885        let mut slots: [Option<Rect>; 3] = [None; 3];
886        let mut x = match side {
887            ButtonsSide::End => bar.right(),
888            ButtonsSide::Start => bar.left(),
889        };
890        for which in order {
891            if !buttons[which as usize] {
892                continue;
893            }
894            let w = match which {
895                Button::Close => kit.window_close.data.width,
896                _ => kit.window_button.data.width,
897            };
898            let (x0, x1) = match side {
899                ButtonsSide::End => (x - w, x),
900                ButtonsSide::Start => (x, x + w),
901            };
902            x = match side {
903                ButtonsSide::End => x0,
904                ButtonsSide::Start => x1,
905            };
906            slots[which as usize] = Some(Rect::from_min_max(
907                pos2(x0, inner.top()),
908                pos2(x1, inner.bottom()),
909            ));
910        }
911        // `buttons-hover: group`: all three are hovered while the pointer
912        // is over any of them (egui's pointer, or the system's on Windows).
913        let group = kit.window.buttons_hover == ButtonsHover::Group && {
914            let all = slots
915                .iter()
916                .flatten()
917                .fold(Rect::NOTHING, |a, r| a.union(*r));
918            native_hover(&ctx).is_some() || (all.is_positive() && ui.rect_contains_pointer(all))
919        };
920        for which in order {
921            let Some(r) = slots[which as usize] else {
922                continue;
923            };
924            let look = match which {
925                Button::Maximize if fullscreen => Look::ExitFullscreen,
926                Button::Maximize if maximized => Look::Restore,
927                _ => Look::Plain,
928            };
929            if window_button(ui, r, which, look, group) {
930                request = Some(match which {
931                    Button::Minimize => FrameRequest::Minimize,
932                    Button::Maximize if fullscreen => FrameRequest::ExitFullscreen,
933                    Button::Maximize => FrameRequest::ToggleMaximize,
934                    Button::Close => FrameRequest::Close,
935                });
936            }
937        }
938        layout.minimize = slots[Button::Minimize as usize];
939        layout.maximize = slots[Button::Maximize as usize];
940        layout.close = slots[Button::Close as usize];
941        if fullscreen {
942            // The way out of full screen takes its own clicks: a hole in
943            // the caption, never the system's maximize button (no Snap
944            // Layouts over it).
945            layout.holes.extend(layout.maximize.take());
946        }
947        // The room the items and the title share: between the buttons and
948        // the bar's other edge.
949        let (lo, hi) = match side {
950            ButtonsSide::End => (bar.left(), x),
951            ButtonsSide::Start => (x, bar.right()),
952        };
953        let gap = t.space.m;
954        // The application's items, at the end of that room.
955        let end = Rect::from_min_max(pos2(lo, inner.top()), pos2(hi - gap, inner.bottom()));
956        let mut child = ui.new_child(
957            egui::UiBuilder::new()
958                .max_rect(end)
959                .layout(egui::Layout::right_to_left(egui::Align::Center)),
960        );
961        trailing(&mut child);
962        let trailing_rect = child.min_rect();
963        if trailing_rect.width() > 0.0 {
964            layout.holes.push(trailing_rect);
965        }
966        // Leading items, at its start.
967        let start = Rect::from_min_max(
968            pos2(lo + gap, inner.top()),
969            pos2(trailing_rect.left().min(hi) - gap, inner.bottom()),
970        );
971        let mut child = ui.new_child(
972            egui::UiBuilder::new()
973                .max_rect(start)
974                .layout(egui::Layout::left_to_right(egui::Align::Center)),
975        );
976        leading(&mut child);
977        let leading_rect = child.min_rect();
978        if leading_rect.width() > 0.0 {
979            layout.holes.push(leading_rect);
980        }
981        // The title, where the kit's `title-bar.align` puts it, between
982        // the items. Named for assistive technology and tests; takes no
983        // click, so the bar still drags under it.
984        let room = Rect::from_min_max(
985            pos2(leading_rect.right().max(lo), inner.top()),
986            pos2(trailing_rect.left().min(hi), inner.bottom()),
987        );
988        let width = room.width() - 2.0 * kit.title_bar.data.padding_x;
989        let mut title_rect = None;
990        if width > 0.0 && !self.title.is_empty() {
991            let font = egui::TextStyle::Body.resolve(ui.style());
992            let mut job = egui::text::LayoutJob::simple_singleline(
993                self.title.into(),
994                font,
995                Color32::PLACEHOLDER,
996            );
997            job.wrap = egui::text::TextWrapping::truncate_at_width(width);
998            let galley = ui.fonts_mut(|f| f.layout_job(job));
999            let part = Part {
1000                rect: bar,
1001                room,
1002                state: State::REST,
1003                label: Some(&galley),
1004            };
1005            let at = kit.title_bar.label_rect(&part, galley.size());
1006            title_rect = Some(at);
1007            let title = self.title;
1008            ui.interact(at, ui.scope_id().with("egui_pop.title"), Sense::hover())
1009                .widget_info(|| egui::WidgetInfo::labeled(Role::Label, true, title));
1010            kit.title_bar.paint_label(
1011                &KitCx {
1012                    painter: ui.painter(),
1013                    ppp,
1014                },
1015                &part,
1016            );
1017        }
1018        if !self.publish {
1019            ui.advance_cursor_after_rect(bar);
1020            return TitleBarOutput {
1021                request,
1022                rect: bar,
1023                title: title_rect,
1024                layout,
1025            };
1026        }
1027        let grip = grip(&ctx);
1028        update_pending(&ctx, |l| {
1029            l.caption = layout.caption;
1030            l.holes = layout.holes.clone();
1031            l.minimize = layout.minimize;
1032            l.maximize = layout.maximize;
1033            l.close = layout.close;
1034            l.grip = grip;
1035        });
1036        publish(&ctx);
1037        ui.advance_cursor_after_rect(bar);
1038        TitleBarOutput {
1039            request,
1040            rect: bar,
1041            title: title_rect,
1042            layout,
1043        }
1044    }
1045}
1046
1047/// The window button the system says the pointer is over, per window.
1048const NATIVE_HOVER: Slot<Option<Button>> = Slot::new("core.frame.native_hover");
1049
1050/// Says which window button the pointer is over when the system, not
1051/// egui, sees the pointer there (on Windows the buttons answer the
1052/// system's hit test, so their hover never reaches egui): the button is
1053/// drawn hot. `None` when the pointer left them.
1054pub fn set_native_hover(ctx: &Context, viewport: ViewportId, button: Option<Button>) {
1055    NATIVE_HOVER.keyed(viewport).set(ctx, button);
1056    ctx.request_repaint_of(viewport);
1057}
1058
1059/// The window button the system says the pointer is over.
1060pub fn native_hover(ctx: &Context) -> Option<Button> {
1061    // Read before the memory's lock: the viewport id takes the context's.
1062    let viewport = ctx.viewport_id();
1063    NATIVE_HOVER.keyed(viewport).get(ctx).flatten()
1064}
1065
1066/// How the maximize slot's button shows.
1067#[derive(Clone, Copy, PartialEq, Eq)]
1068enum Look {
1069    Plain,
1070    /// A maximized window's restore.
1071    Restore,
1072    /// A full screen window's way out.
1073    ExitFullscreen,
1074}
1075
1076/// Draws a window button; says whether it was clicked. `group`: the
1077/// pointer is over one of the buttons and the kit hovers them together.
1078///
1079/// Each button carries a tone, which a kit may give to tell them apart
1080/// (the macOS flavour's red, yellow and green): minimize `warning`,
1081/// maximize `success`, close `danger`. A kit giving no tones (the
1082/// default) draws each with its component's own box.
1083fn window_button(ui: &mut Ui, rect: Rect, which: Button, look: Look, group: bool) -> bool {
1084    let name = crate::strings::tr(
1085        ui.ctx(),
1086        match which {
1087            Button::Minimize => &crate::strings::MINIMIZE,
1088            Button::Maximize if look == Look::ExitFullscreen => &crate::strings::EXIT_FULLSCREEN,
1089            Button::Maximize if look == Look::Restore => &crate::strings::RESTORE,
1090            Button::Maximize => &crate::strings::MAXIMIZE,
1091            Button::Close => &crate::strings::CLOSE,
1092        },
1093    );
1094    let name = name.as_str();
1095    let id = ui.scope_id().with(("egui_pop.window_button", which as u8));
1096    let response = ui.interact(rect, id, Sense::click());
1097    a11y::name(&response, Role::Button, name);
1098    let kit = Kit::of(ui.ctx());
1099    // On Windows the system, not egui, may see the pointer over the
1100    // button (its hit test answers for it): drawn as hovered then.
1101    let state = State::from_response(&response)
1102        .with(
1103            State::HOVER,
1104            response.hovered() || group || native_hover(ui.ctx()) == Some(which),
1105        )
1106        .toned(match which {
1107            Button::Minimize => Tone::Warning,
1108            Button::Maximize => Tone::Success,
1109            Button::Close => Tone::Danger,
1110        });
1111    let component = match which {
1112        Button::Close => &kit.window_close,
1113        _ => &kit.window_button,
1114    };
1115    let painter = ui.painter_at(rect);
1116    component.paint(
1117        &KitCx {
1118            painter: &painter,
1119            ppp: ui.ctx().pixels_per_point(),
1120        },
1121        &Part {
1122            rect,
1123            room: rect,
1124            state,
1125            label: None,
1126        },
1127    );
1128    let b = component.style(state);
1129    let glyph = kit.glyph(match which {
1130        Button::Minimize => Glyph::WindowMinimize,
1131        Button::Maximize if look == Look::ExitFullscreen => Glyph::WindowExitFullscreen,
1132        Button::Maximize if look == Look::Restore => Glyph::WindowRestore,
1133        Button::Maximize => Glyph::WindowMaximize,
1134        Button::Close => Glyph::WindowClose,
1135    });
1136    // The state's `indicator-size` when the kit gives one; else ten
1137    // points across, or half the button's own size when it has one
1138    // (`height`: a traffic light's circle).
1139    let h = component.data.height;
1140    let size = if b.indicator_size > 0.0 {
1141        b.indicator_size
1142    } else if h > 0.0 {
1143        (h / 2.0).max(4.0)
1144    } else {
1145        10.0
1146    };
1147    if b.text.a() > 0 {
1148        // On the pixel grid: an icon's texture drawn between pixels blurs.
1149        let ppp = ui.ctx().pixels_per_point();
1150        let min = rect.center() - Vec2::splat(size / 2.0);
1151        let min = pos2((min.x * ppp).round() / ppp, (min.y * ppp).round() / ppp);
1152        glyph.paint(
1153            &painter,
1154            Rect::from_min_size(min, Vec2::splat(size)),
1155            b.text,
1156        );
1157    }
1158    response.on_hover_text(name).clicked()
1159}
1160
1161#[cfg(test)]
1162mod tests {
1163    use super::*;
1164
1165    fn layout() -> FrameLayout {
1166        // A 800 x 600 window, a 32 pt bar, 44 pt buttons, a logo hole.
1167        let bar = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 32.0));
1168        let b = |i: f32| Rect::from_min_size(pos2(800.0 - 44.0 * i, 0.0), vec2(44.0, 32.0));
1169        FrameLayout {
1170            window: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)),
1171            caption: Some(bar),
1172            holes: vec![Rect::from_min_size(pos2(8.0, 4.0), vec2(24.0, 24.0))],
1173            minimize: Some(b(3.0)),
1174            maximize: Some(b(2.0)),
1175            close: Some(b(1.0)),
1176            grip: 4.0,
1177            resizable: true,
1178            fullscreen: false,
1179        }
1180    }
1181
1182    #[test]
1183    fn points_map_to_their_regions_at_every_scale() {
1184        for ppp in [1.0, 1.25, 1.5, 2.0] {
1185            let r = HitRegions::measure(&layout(), ppp);
1186            let px = |x: f32, y: f32| ((x * ppp) as i32, (y * ppp) as i32);
1187            let hit = |x: f32, y: f32| {
1188                let (x, y) = px(x, y);
1189                r.hit(x, y)
1190            };
1191            assert_eq!(hit(400.0, 16.0), Hit::Caption, "{ppp}");
1192            assert_eq!(hit(20.0, 16.0), Hit::Client, "the logo, {ppp}");
1193            assert_eq!(hit(800.0 - 22.0, 16.0), Hit::Close, "{ppp}");
1194            assert_eq!(hit(800.0 - 66.0, 16.0), Hit::Maximize, "{ppp}");
1195            assert_eq!(hit(800.0 - 110.0, 16.0), Hit::Minimize, "{ppp}");
1196            assert_eq!(hit(400.0, 300.0), Hit::Client, "{ppp}");
1197            assert_eq!(hit(0.5, 300.0), Hit::Left, "{ppp}");
1198            assert_eq!(hit(799.5, 300.0), Hit::Right, "{ppp}");
1199            assert_eq!(hit(400.0, 0.5), Hit::Top, "{ppp}");
1200            assert_eq!(hit(400.0, 599.5), Hit::Bottom, "{ppp}");
1201            assert_eq!(hit(0.5, 0.5), Hit::TopLeft, "{ppp}");
1202            assert_eq!(hit(799.5, 599.5), Hit::BottomRight, "{ppp}");
1203            assert_eq!(r.size, [(800.0 * ppp) as i32, (600.0 * ppp) as i32]);
1204        }
1205    }
1206
1207    #[test]
1208    fn edges_never_fall_under_the_pixel_minimum_and_vanish_when_maximized() {
1209        let mut l = layout();
1210        l.grip = 2.0;
1211        assert_eq!(HitRegions::measure(&l, 1.0).grip, MIN_GRIP_PX as i32);
1212        assert_eq!(HitRegions::measure(&l, 4.0).grip, 8);
1213        l.resizable = false;
1214        let r = HitRegions::measure(&l, 1.0);
1215        assert_eq!(r.grip, 0);
1216        assert_eq!(r.hit(0, 300), Hit::Client);
1217        assert_eq!(r.hit(400, 0), Hit::Caption);
1218    }
1219
1220    /// Draws a title bar 800 points wide with a leading item, in a context
1221    /// whose theme is pop-dark with `json` merged, the pointer at
1222    /// `pointer`; gives what the last pass painted.
1223    fn bar_with(
1224        json: &str,
1225        pointer: Option<Pos2>,
1226    ) -> (
1227        TitleBarOutput,
1228        Option<Rect>,
1229        Context,
1230        Vec<egui::epaint::ClippedShape>,
1231    ) {
1232        let mut themes = egui_pop_tokens::Themes::default();
1233        themes
1234            .add_text("frame-test", json)
1235            .expect("test theme reads");
1236        let tokens = Tokens::new(themes.resolve(&egui_pop_tokens::ThemeSpec::new("frame-test")));
1237        let ctx = Context::default();
1238        crate::theme::install_tokens(&ctx, tokens);
1239        let mut out = None;
1240        let mut lead = None;
1241        let mut shapes = Vec::new();
1242        // Twice: the second pass sees the pointer over what the first drew.
1243        for _ in 0..2 {
1244            let input = egui::RawInput {
1245                screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))),
1246                events: pointer
1247                    .map(|p| vec![egui::Event::PointerMoved(p)])
1248                    .unwrap_or_default(),
1249                ..Default::default()
1250            };
1251            let mut full = ctx.run_ui(input, |ui| {
1252                let o = TitleBar::new("Title").show(
1253                    ui,
1254                    |ui| {
1255                        lead = Some(ui.label("Leading").rect);
1256                    },
1257                    |_| {},
1258                );
1259                out = Some(o);
1260            });
1261            full.textures_delta.clear();
1262            shapes = full.shapes;
1263        }
1264        (out.expect("the bar was drawn"), lead, ctx, shapes)
1265    }
1266
1267    const START: &str = r#"
1268                        $extends: "pop-dark"
1269                        title-bar:
1270                          buttons-side: {$type: "string", $value: "start"}
1271                        "#;
1272
1273    #[test]
1274    fn buttons_at_the_start_come_first_and_the_title_stays_centred() {
1275        let (out, lead, ctx, _) = bar_with(START, None);
1276        let kit = Kit::of(&ctx);
1277        assert!(kit.problems.is_empty(), "{:?}", kit.problems);
1278        assert_eq!(kit.window.buttons_side, ButtonsSide::Start);
1279        let l = &out.layout;
1280        let (close, min, max) = (l.close.unwrap(), l.minimize.unwrap(), l.maximize.unwrap());
1281        // Close at the start edge, then minimize, then maximize.
1282        assert_eq!(close.left(), 0.0);
1283        assert_eq!(min.left(), close.right());
1284        assert_eq!(max.left(), min.right());
1285        // The leading items after the buttons, published as a hole.
1286        let lead = lead.unwrap();
1287        assert!(lead.left() > max.right(), "{lead:?} after {max:?}");
1288        assert!(l.holes.iter().any(|h| h.contains_rect(lead)));
1289        // The title on the bar's centre.
1290        let title = out.title.expect("the title was laid out");
1291        assert!((title.center().x - 400.0).abs() < 1.0, "{title:?}");
1292        // The regions a platform layer reads follow the buttons: Snap
1293        // Layouts over maximize wherever it is.
1294        let r = regions(&ctx).expect("published");
1295        let ppp = r.pixels_per_point;
1296        let at = |p: Rect| ((p.center().x * ppp) as i32, (p.center().y * ppp) as i32);
1297        assert_eq!(r.hit(at(max).0, at(max).1), Hit::Maximize);
1298        assert_eq!(r.hit(at(close).0, at(close).1), Hit::Close);
1299        assert_eq!(
1300            r.hit((790.0 * ppp) as i32, (16.0 * ppp) as i32),
1301            Hit::Caption
1302        );
1303    }
1304
1305    #[test]
1306    fn the_default_kit_keeps_the_buttons_at_the_end() {
1307        let (out, lead, _, _) = bar_with(
1308            r#"
1309                                         $extends: "pop-dark"
1310                                         "#,
1311            None,
1312        );
1313        let l = &out.layout;
1314        assert_eq!(l.close.unwrap().right(), 800.0);
1315        assert_eq!(l.maximize.unwrap().right(), l.close.unwrap().left());
1316        assert_eq!(l.minimize.unwrap().right(), l.maximize.unwrap().left());
1317        assert!(lead.unwrap().right() < l.minimize.unwrap().left());
1318    }
1319
1320    /// A compositor that keeps the release of the press that moved the
1321    /// window (labwc, mutter on Wayland): the caption drags the window again, and
1322    /// a window button still clicks.
1323    #[test]
1324    fn the_bar_moves_again_and_its_buttons_click_after_a_move_whose_release_never_came() {
1325        let ctx = Context::default();
1326        crate::theme::install(&ctx, &crate::theme::ThemeSpec::new("pop-dark"));
1327        // Each pass: the minimize button, the bar's request, whether the
1328        // window was handed to the compositor.
1329        let pass = |events: Vec<egui::Event>| {
1330            let input = egui::RawInput {
1331                screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))),
1332                events,
1333                ..Default::default()
1334            };
1335            let (mut minimize, mut request) = (None, None);
1336            let mut full = ctx.run_ui(input, |ui| {
1337                let out = TitleBar::new("Title").show(ui, |_| {}, |_| {});
1338                minimize = out.layout.minimize;
1339                request = out.request;
1340            });
1341            full.textures_delta.clear();
1342            let started = full
1343                .viewport_output
1344                .values()
1345                .any(|v| v.commands.contains(&ViewportCommand::StartDrag));
1346            (minimize, request, started)
1347        };
1348        let press = |pos, pressed| egui::Event::PointerButton {
1349            pos,
1350            button: egui::PointerButton::Primary,
1351            pressed,
1352            modifiers: egui::Modifiers::NONE,
1353        };
1354        let caption = pos2(300.0, 10.0);
1355        pass(vec![egui::Event::PointerMoved(caption)]);
1356        pass(vec![press(caption, true)]);
1357        // The caption dragged: the window is moved by the compositor, which
1358        // never hands the release back.
1359        let away = caption + vec2(40.0, 0.0);
1360        let mut started = pass(vec![egui::Event::PointerMoved(away)]).2;
1361        started |= pass(vec![egui::Event::PointerMoved(away + vec2(5.0, 0.0))]).2;
1362        assert!(started, "the move went to the compositor");
1363        // A second move: a new press on the caption drags it again (egui
1364        // held the first press's drag until a release).
1365        pass(vec![egui::Event::PointerMoved(caption)]);
1366        pass(vec![press(caption, true)]);
1367        let mut again = pass(vec![egui::Event::PointerMoved(away)]).2;
1368        again |= pass(vec![egui::Event::PointerMoved(away + vec2(5.0, 0.0))]).2;
1369        assert!(again, "the window moves a second time");
1370        let (minimize, ..) = pass(vec![egui::Event::PointerMoved(away)]);
1371        let button = minimize.expect("a minimize button").center();
1372        let mut requests = Vec::new();
1373        for events in [
1374            vec![egui::Event::PointerMoved(button)],
1375            vec![press(button, true)],
1376            vec![press(button, false)],
1377            Vec::new(),
1378        ] {
1379            requests.extend(pass(events).1);
1380        }
1381        assert_eq!(requests, [FrameRequest::Minimize]);
1382    }
1383
1384    #[test]
1385    fn in_full_screen_the_bar_keeps_close_and_its_way_out_but_no_edges() {
1386        let ctx = Context::default();
1387        let mut out = None;
1388        for _ in 0..2 {
1389            let mut input = egui::RawInput {
1390                screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))),
1391                ..Default::default()
1392            };
1393            input.viewports.insert(
1394                ViewportId::ROOT,
1395                egui::ViewportInfo {
1396                    fullscreen: Some(true),
1397                    ..Default::default()
1398                },
1399            );
1400            let mut full = ctx.run_ui(input, |ui| {
1401                resize_edges(ui.ctx());
1402                out = Some(TitleBar::new("Title").show(ui, |_| {}, |_| {}));
1403            });
1404            full.textures_delta.clear();
1405        }
1406        let out = out.expect("the bar was drawn");
1407        let l = &out.layout;
1408        assert!(l.fullscreen);
1409        assert!(l.minimize.is_none() && l.maximize.is_none(), "{l:?}");
1410        let close = l.close.expect("close stays");
1411        assert_eq!(close.right(), 800.0);
1412        // The way out, where maximize was: a hole, so client area.
1413        let exit = *l
1414            .holes
1415            .iter()
1416            .find(|h| h.right() == close.left())
1417            .expect("the way out of full screen");
1418        let r = regions(&ctx).expect("published");
1419        assert!(r.fullscreen);
1420        assert_eq!(r.grip, 0, "no resize edges in full screen");
1421        let at = |p: Pos2| (p.x as i32, p.y as i32);
1422        let (x, y) = at(exit.center());
1423        assert_eq!(r.hit(x, y), Hit::Client);
1424        let (x, y) = at(close.center());
1425        assert_eq!(r.hit(x, y), Hit::Close);
1426        assert_eq!(r.hit(400, 16), Hit::Caption);
1427        assert_eq!(r.hit(0, 300), Hit::Client);
1428        assert_eq!(r.hit(400, 0), Hit::Caption);
1429    }
1430
1431    #[test]
1432    fn a_bad_buttons_side_is_reported() {
1433        let (out, _, ctx, _) = bar_with(
1434            r#"
1435            $extends: "pop-dark"
1436            title-bar:
1437              buttons-side: {$type: "string", $value: "left"}
1438            "#,
1439            None,
1440        );
1441        let kit = Kit::of(&ctx);
1442        assert_eq!(kit.window.buttons_side, ButtonsSide::End);
1443        assert_eq!(
1444            kit.problems,
1445            ["title-bar.buttons-side: `left` is not start or end"]
1446        );
1447        assert_eq!(out.layout.close.unwrap().right(), 800.0);
1448    }
1449
1450    #[test]
1451    fn grouped_buttons_hover_together() {
1452        // A close glyph shown only on hover. With `group`, the pointer
1453        // over minimize draws the three hovered: the close glyph shows.
1454        let json = r##"
1455                   $extends: "pop-dark"
1456                   title-bar:
1457                     buttons-side: {$type: "string", $value: "start"}
1458                     buttons-hover: {$type: "string", $value: "group"}
1459                   window-close:
1460                     rest:
1461                       text: {$type: "color", $value: "#00000000"}
1462                     hover:
1463                       text: {$type: "color", $value: "#ff00ff"}
1464                   "##;
1465        let magenta = Color32::from_rgb(255, 0, 255);
1466        let close_glyph = |pointer| {
1467            let (out, _, ctx, shapes) = bar_with(json, pointer);
1468            assert_eq!(Kit::of(&ctx).window.buttons_hover, ButtonsHover::Group);
1469            let shown = shapes.iter().any(|s| match &s.shape {
1470                egui::Shape::LineSegment { stroke, .. } => stroke.color == magenta,
1471                _ => false,
1472            });
1473            (out, shown)
1474        };
1475        let (out, shown) = close_glyph(None);
1476        assert!(!shown);
1477        let over_minimize = out.layout.minimize.unwrap().center();
1478        assert!(close_glyph(Some(over_minimize)).1);
1479        assert!(!close_glyph(Some(pos2(400.0, 300.0))).1);
1480    }
1481
1482    #[test]
1483    fn rectangles_round_to_the_pixels_they_cover() {
1484        let r = RectPx::from_points(Rect::from_min_max(pos2(0.2, 1.0), pos2(10.4, 2.0)), 1.25);
1485        assert_eq!(
1486            r,
1487            RectPx {
1488                x: 0,
1489                y: 1,
1490                w: 13,
1491                h: 2
1492            }
1493        );
1494        assert!(r.contains(0, 1) && !r.contains(13, 1));
1495    }
1496
1497    fn floating() -> Placement {
1498        Placement {
1499            maximized: Some(false),
1500            fullscreen: Some(false),
1501            stuck: Stuck::default(),
1502        }
1503    }
1504
1505    #[test]
1506    fn corners_round_only_while_the_window_floats_free() {
1507        let r = egui::CornerRadius::same(8);
1508        assert_eq!(corner_radius(8.0, &floating()), r);
1509        // No radius: square.
1510        assert_eq!(corner_radius(0.0, &floating()), egui::CornerRadius::ZERO);
1511        // Maximized, full screen, or a state not told: square.
1512        for p in [
1513            Placement {
1514                maximized: Some(true),
1515                ..floating()
1516            },
1517            Placement {
1518                fullscreen: Some(true),
1519                ..floating()
1520            },
1521            Placement {
1522                maximized: None,
1523                ..floating()
1524            },
1525            Placement {
1526                fullscreen: None,
1527                ..floating()
1528            },
1529        ] {
1530            assert_eq!(corner_radius(8.0, &p), egui::CornerRadius::ZERO, "{p:?}");
1531        }
1532        // Tiled against the left edge: the left corners square.
1533        let left = Placement {
1534            stuck: Stuck {
1535                left: true,
1536                ..Stuck::default()
1537            },
1538            ..floating()
1539        };
1540        assert_eq!(
1541            corner_radius(8.0, &left),
1542            egui::CornerRadius {
1543                nw: 0,
1544                ne: 8,
1545                sw: 0,
1546                se: 8
1547            }
1548        );
1549        // In a quarter, top right: only the bottom left corner rounds.
1550        let quarter = Placement {
1551            stuck: Stuck {
1552                top: true,
1553                right: true,
1554                ..Stuck::default()
1555            },
1556            ..floating()
1557        };
1558        assert_eq!(
1559            corner_radius(8.0, &quarter),
1560            egui::CornerRadius {
1561                nw: 0,
1562                ne: 0,
1563                sw: 8,
1564                se: 0
1565            }
1566        );
1567    }
1568
1569    #[test]
1570    fn the_sides_against_a_screen_are_read_on_the_screen_it_is_on() {
1571        let screens = [
1572            Rect::from_min_size(pos2(0.0, 0.0), vec2(1920.0, 1080.0)),
1573            Rect::from_min_size(pos2(1920.0, 0.0), vec2(1280.0, 1024.0)),
1574        ];
1575        // The left half of the second screen.
1576        let half = Rect::from_min_size(pos2(1920.0, 0.0), vec2(640.0, 1024.0));
1577        assert_eq!(
1578            Stuck::against(half, &screens),
1579            Stuck {
1580                left: true,
1581                top: true,
1582                right: false,
1583                bottom: true
1584            }
1585        );
1586        // Free in the middle of the first.
1587        let free = Rect::from_min_size(pos2(200.0, 100.0), vec2(800.0, 600.0));
1588        assert_eq!(Stuck::against(free, &screens), Stuck::default());
1589        // No screens told (Wayland gives no position either): free.
1590        assert_eq!(Stuck::against(half, &[]), Stuck::default());
1591    }
1592
1593    #[test]
1594    fn a_background_over_a_corner_is_rounded_and_cut_to_the_window() {
1595        let window = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0));
1596        let corners = egui::CornerRadius::same(8);
1597        // A panel's fill reaching past the window's top left corner.
1598        let mut fill = egui::Shape::rect_filled(
1599            Rect::from_min_max(pos2(-1.0, -1.0), pos2(100.0, 300.0)),
1600            0.0,
1601            Color32::RED,
1602        );
1603        round_shape(&mut fill, window, corners);
1604        let egui::Shape::Rect(r) = &fill else {
1605            unreachable!()
1606        };
1607        assert_eq!(
1608            r.corner_radius,
1609            egui::CornerRadius {
1610                nw: 8,
1611                ne: 0,
1612                sw: 8,
1613                se: 0
1614            }
1615        );
1616        assert_eq!(r.rect.min, Pos2::ZERO);
1617        // The shell inside a 1 pt line: one less, so it stays inside the
1618        // line's curve.
1619        let mut shell = egui::Shape::rect_filled(window.shrink(1.0), 0.0, Color32::RED);
1620        round_shape(&mut shell, window, corners);
1621        let egui::Shape::Rect(r) = &shell else {
1622            unreachable!()
1623        };
1624        assert_eq!(r.corner_radius, egui::CornerRadius::same(7));
1625        // A button in the middle is left alone, also in a list.
1626        let mut inner = egui::Shape::Vec(vec![egui::Shape::rect_filled(
1627            Rect::from_min_size(pos2(50.0, 50.0), vec2(20.0, 20.0)),
1628            2.0,
1629            Color32::RED,
1630        )]);
1631        let before = inner.clone();
1632        round_shape(&mut inner, window, corners);
1633        assert_eq!(format!("{inner:?}"), format!("{before:?}"));
1634    }
1635
1636    #[test]
1637    fn what_is_painted_over_a_corner_is_rounded_at_the_end_of_the_pass() {
1638        let ctx = Context::default();
1639        let fill = Color32::from_rgb(10, 20, 30);
1640        let corners = egui::CornerRadius::same(8);
1641        let run = || {
1642            ctx.run_ui(egui::RawInput::default(), |ui| {
1643                let ctx = ui.ctx().clone();
1644                ctx.layer_painter(egui::LayerId::background()).rect_filled(
1645                    ctx.content_rect(),
1646                    0.0,
1647                    fill,
1648                );
1649                paint_window_edge(
1650                    &ctx,
1651                    WindowEdge {
1652                        stroke: egui::Stroke::NONE,
1653                        corners,
1654                    },
1655                );
1656            })
1657        };
1658        // The first pass installs the rounding; the next ones round.
1659        run().drop_without_applying_deltas();
1660        let out = run();
1661        let window = ctx.content_rect();
1662        let rounded = out.shapes.iter().any(|c| match &c.shape {
1663            egui::Shape::Rect(r) => {
1664                r.fill == fill && r.rect == window && r.corner_radius == corners
1665            }
1666            _ => false,
1667        });
1668        assert!(rounded, "{:?}", out.shapes);
1669        out.drop_without_applying_deltas();
1670    }
1671}