agg_gui/widgets/window.rs
1//! `Window` — a floating, draggable, resizable panel with a title bar.
2//!
3//! # Usage
4//!
5//! Create a `Window` and place it as the **last** child of a [`Stack`] so it
6//! paints on top of everything and receives hit-test priority.
7//!
8//! ```ignore
9//! let win = Window::new("Inspector", font, Box::new(my_content));
10//! Stack::new()
11//! .add(Box::new(main_ui))
12//! .add(Box::new(win))
13//! ```
14//!
15//! # Features
16//!
17//! - **Drag** — click-drag the title bar to move the window.
18//! - **Resize** — drag any of the 8 edges/corners to resize; min size 120×80.
19//! - **Collapse** — click the chevron on the left of the title bar to collapse
20//! to title-bar-only height (click again to expand).
21//! - **Maximize** — double-click the title bar (or click the maximize button)
22//! to toggle between maximised and restored size.
23//! - **Close** — click the × button; syncs with an optional shared `visible_cell`.
24//!
25//! # ⚠ Backbuffer caching gotcha — read before adding a custom Window
26//!
27//! `Window` retains its painted pixels in a GL FBO (or CPU bitmap) and only
28//! re-rasterises on widget setter mutations (`Label::set_text`, hover changes,
29//! etc.). Custom paint code that reads from an `Rc<RefCell<…>>` model the
30//! framework can't observe — telemetry graphs, sensor streams, simulation
31//! views — will blit stale pixels forever unless you tell the window to
32//! invalidate. Two ways:
33//!
34//! - `.with_live_content(true)` — Window self-invalidates every frame
35//! (auto-skipped when collapsed or hidden). Use for streaming data.
36//! - [`Window::invalidate_backbuffer`] — manual flag from the data-arrival
37//! path. Use when invalidation is sparse and you want frame-skip when
38//! nothing changed.
39//!
40//! See [`Window::new`] for the full discussion.
41//!
42//! # Coordinate notes (Y-up)
43//!
44//! `bounds` stores the window's position in its **parent's** coordinate space.
45//! The title bar is at the **top** of the window, i.e. local Y ∈
46//! `[height − TITLE_H .. height]`. The content area fills local Y ∈ `[0 .. height − TITLE_H]`.
47
48use std::cell::{Cell, RefCell};
49use std::rc::Rc;
50use std::sync::Arc;
51
52use web_time::Instant;
53
54use crate::cursor::{set_cursor_icon, CursorIcon};
55use crate::draw_ctx::DrawCtx;
56use crate::event::{Event, EventResult, Key, MouseButton};
57use crate::geometry::{Point, Rect, Size};
58use crate::layout_props::{HAnchor, Insets, VAnchor, WidgetBase};
59use crate::text::Font;
60use crate::widget::{BackbufferKind, BackbufferSpec, BackbufferState, Widget};
61use crate::widgets::window_title_bar::{TitleBarView, WindowTitleBar};
62
63/// Round all four components of a Rect to the nearest integer so widgets
64/// are always placed on exact pixel boundaries (crisp bitmap blits, no blur).
65fn snap(r: Rect) -> Rect {
66 Rect::new(r.x.round(), r.y.round(), r.width.round(), r.height.round())
67}
68
69const TITLE_H: f64 = 28.0;
70const CORNER_R: f64 = 8.0;
71const SHADOW_BLUR: f64 = 14.0;
72const SHADOW_DX: f64 = 2.0;
73const SHADOW_DY: f64 = 6.0;
74const VISIBILITY_FADE_SECS: f64 = 0.18;
75const CLOSE_R: f64 = 6.0;
76const CLOSE_PAD: f64 = 10.0;
77const MAX_PAD: f64 = CLOSE_PAD + CLOSE_R * 2.0 + 4.0; // 26 px
78const RESIZE_EDGE: f64 = 6.0; // px from the edge that counts as a resize zone
79const MIN_W: f64 = 120.0;
80const MIN_H: f64 = 80.0;
81const DBL_CLICK_MS: u128 = 500; // double-click detection window
82
83/// Which edge(s) are being dragged during a resize operation.
84#[derive(Clone, Copy, Debug, PartialEq)]
85pub(crate) enum ResizeDir {
86 N,
87 NE,
88 E,
89 SE,
90 S,
91 SW,
92 W,
93 NW,
94}
95
96/// Interaction mode for the current drag.
97#[derive(Clone, Copy, Debug, PartialEq)]
98enum DragMode {
99 None,
100 Move,
101 Resize(ResizeDir),
102}
103
104/// A floating panel with a draggable/resizable title bar and a single content child.
105pub struct Window {
106 bounds: Rect,
107 children: Vec<Box<dyn Widget>>, // always exactly 1: the content
108 base: WidgetBase,
109
110 font_size: f64,
111
112 visible: bool,
113 visible_cell: Option<Rc<Cell<bool>>>,
114 visibility_anim: crate::animation::Tween,
115 fade_out_active: Cell<bool>,
116 backbuffer: BackbufferState,
117 use_gl_backbuffer: bool,
118 reset_to: Option<Rc<Cell<Option<Rect>>>>,
119 position_cell: Option<Rc<Cell<Rect>>>,
120 maximized_cell: Option<Rc<Cell<bool>>>,
121 /// Runtime-driven flag cells (egui `Window::resizable/collapsible`,
122 /// plus our `auto_size` addition). Read each `layout()` so a demo's
123 /// checkboxes can steer the real host window. `None` means the flag is
124 /// fixed at its builder value.
125 resizable_cell: Option<Rc<Cell<bool>>>,
126 auto_size_cell: Option<Rc<Cell<bool>>>,
127 collapsible_cell: Option<Rc<Cell<bool>>>,
128 /// Live title text. Applied to the title-bar label only — the window's
129 /// identity (`self.title`, used as the persistence / z-order key) is
130 /// deliberately left untouched so retitling can't corrupt saved state.
131 title_cell: Option<Rc<RefCell<String>>>,
132 /// Last title string pushed into the title bar, so we only re-set (and
133 /// invalidate the label's glyph cache) when the text actually changes.
134 last_applied_title: RefCell<String>,
135
136 /// Snapshot of `is_visible()` from the previous `layout()` call. Used
137 /// to detect the false→true transition (demo toggled on in the
138 /// sidebar) so we can request the parent `Stack` raise us to the top.
139 last_visible: Cell<bool>,
140 /// `true` until the first `layout()` runs. A window restored as
141 /// already-visible (e.g. saved-state inspector open) misses the
142 /// rising-edge fit-to-canvas pass, so without this one-shot trigger
143 /// its persisted bounds can land outside a smaller live viewport
144 /// (mobile portrait, resized window, etc.) and the user sees the
145 /// sidebar toggle highlighted but no window. Cleared after the
146 /// first layout completes.
147 needs_initial_fit: Cell<bool>,
148 /// Set to `true` on a visibility rising edge; read + cleared by
149 /// `take_raise_request` on the next parent-layout pass.
150 raise_request: Cell<bool>,
151
152 collapsed: bool,
153 /// Whether the collapse affordance is offered. Driven at runtime by
154 /// `collapsible_cell` when wired. Matches egui `Window::collapsible`.
155 collapsible: bool,
156 /// Height before collapsing, so we can restore it.
157 pre_collapse_h: f64,
158
159 drag_mode: DragMode,
160 /// Cursor world position when drag started.
161 drag_start_world: Point,
162 /// Window bounds when drag started.
163 drag_start_bounds: Rect,
164
165 close_hovered: bool,
166 on_close: Option<Box<dyn FnMut(CloseReason)>>,
167
168 /// What an outside pointer press does to this (modal) window. `None` swallows
169 /// it and stays open; `Close` dismisses via [`Window::close`] with
170 /// [`CloseReason::ClickAway`]. Only consulted while `modal` is set.
171 click_away: ClickAwayAction,
172
173 /// Whether the window is currently maximized (fills the full canvas).
174 maximized: bool,
175 /// Bounds saved before maximizing so we can restore them.
176 pre_maximize_bounds: Rect,
177 maximize_hovered: bool,
178
179 /// Which resize edge/corner the cursor is currently hovering over.
180 /// Cleared to None when the cursor moves into the interior.
181 hover_dir: Option<ResizeDir>,
182
183 /// Time of last left-click in the title bar — for double-click collapse.
184 last_title_click: Option<Instant>,
185
186 /// Title-bar sub-widget — owns the bar fill, separator, chevron,
187 /// title label, maximize/close buttons. Painted manually from
188 /// `paint()` so `clip_children_rect` can keep content clipped to the
189 /// body area. Display state is written into `title_state` every
190 /// layout pass; the sub-widget reads it at paint time.
191 title_bar: WindowTitleBar,
192 title_state: Rc<RefCell<TitleBarView>>,
193
194 /// Canvas size supplied by the last `layout()` call; used for clamping.
195 canvas_size: Size,
196 /// When true, the window is kept fully inside the canvas bounds during drag/resize.
197 constrain: bool,
198
199 /// When true, the window declares itself an app-modal layer while visible
200 /// (see [`Widget::has_active_modal`]). The `App` then routes *all* pointer
201 /// and keyboard events into this window's subtree, so a floating dialog
202 /// (e.g. the colour-wheel picker) swallows every click over its bounds
203 /// instead of leaking them to widgets painted underneath. Opt-in — plain
204 /// windows leave this `false` and hit-test normally.
205 modal: bool,
206
207 /// When true, the window bounds adopt the content's preferred size each
208 /// layout pass (width + height). Keeps the title-bar top edge pinned so
209 /// the window appears to grow/shrink downward. User resize is disabled
210 /// while auto-size is active (dragging still works).
211 auto_size: bool,
212
213 /// Whether the user can resize the window by dragging its edges. When
214 /// `false`, no resize handles are active regardless of `resizable_h` /
215 /// `resizable_v` — matches egui's `.resizable(false)`. Defaults to
216 /// `true` to preserve existing behaviour for call sites that don't
217 /// explicitly opt out.
218 resizable: bool,
219 /// Fine-grained axis control, used when `resizable` is `true`.
220 resizable_h: bool,
221 resizable_v: bool,
222 /// Content-bound resize floor + ceiling. When `true`, the
223 /// window's height is locked to its content's required height
224 /// each layout (snap pre-pass) AND `apply_resize` refuses to
225 /// drag it smaller than content. Matches egui's no-scroll-no-
226 /// clip-no-whitespace W4 contract. Off by default.
227 tight_content_fit: bool,
228 /// Floor-only variant of [`tight_content_fit`]. Same minimum-
229 /// height enforcement, but allows the user to grow the window
230 /// past the content (whitespace below). Used by W5 where a
231 /// `TextArea` flex-fills extra space and the user can pull the
232 /// window taller than the wrapped text. Off by default.
233 floor_content_height: bool,
234 /// Most recently observed content required height (via
235 /// `Widget::measure_min_height`). Updated each layout pass so
236 /// `apply_resize` and the tight-fit pre-pass see a current value
237 /// even when the content tree contains a flex-fill widget.
238 last_content_natural_h: Cell<f64>,
239 /// True between `paint()` and `finish_paint()` when GL compositing opened
240 /// a foreground layer for body/title/children. The shadow stays outside.
241 foreground_layer_active: Cell<bool>,
242
243 /// When `true`, the window's backbuffer is invalidated on every
244 /// frame the window is visible-and-expanded, forcing the content
245 /// widget's `paint()` to run fresh. See [`with_live_content`] and
246 /// the constructor doc-comment for when to set this.
247 live_content: bool,
248
249 /// Window title string — stored so external callers (z-order
250 /// persistence, inspector display, etc.) can identify this window
251 /// without going through the inner `title_bar` sub-widget.
252 title: String,
253 /// Optional callback invoked whenever this window requests a raise
254 /// (click-to-front or visibility rising-edge from the sidebar).
255 /// Receives the window title. Used by the demo's z-order tracker
256 /// to record "most recently raised" so the stacking order survives
257 /// a save/restore round-trip.
258 on_raised: Option<Box<dyn FnMut(&str)>>,
259
260 /// Identity for the snap-layout system. Minted once at
261 /// construction from a process-wide counter and never changes —
262 /// `Snappable` uses it to skip self-matches in the snap engine's
263 /// target list.
264 snap_id: crate::snap::SnapId,
265}
266
267impl Window {
268 /// Create a new window with the given title, font, and content widget.
269 ///
270 /// Default position: `(60, 60)` with `size = (360, 280)`. Call
271 /// [`with_bounds`] to override.
272 ///
273 /// Windows keep a retained backbuffer. Live content must either call
274 /// [`Window::invalidate_backbuffer`] when external data changes or use
275 /// [`Window::with_live_content`] to force repaint while visible.
276 pub fn new(title: impl Into<String>, font: Arc<Font>, content: Box<dyn Widget>) -> Self {
277 let font_size = 13.0;
278 let title_str: String = title.into();
279 let title_state = Rc::new(RefCell::new(TitleBarView::default_visuals()));
280 let title_bar = WindowTitleBar::new(&title_str, Arc::clone(&font), Rc::clone(&title_state));
281 Self {
282 bounds: Rect::new(60.0, 60.0, 360.0, 280.0),
283 children: vec![content],
284 base: WidgetBase::new(),
285 font_size,
286 visible: true,
287 visible_cell: None,
288 visibility_anim: crate::animation::Tween::new(1.0, VISIBILITY_FADE_SECS),
289 fade_out_active: Cell::new(false),
290 backbuffer: BackbufferState::new(),
291 use_gl_backbuffer: true,
292 reset_to: None,
293 position_cell: None,
294 maximized_cell: None,
295 resizable_cell: None,
296 auto_size_cell: None,
297 collapsible_cell: None,
298 title_cell: None,
299 last_applied_title: RefCell::new(title_str.clone()),
300 // Seed `last_visible` to `true` (matches `visible` above) so a
301 // window that's open on first frame doesn't spuriously request
302 // a raise before the user has interacted with it.
303 last_visible: Cell::new(true),
304 needs_initial_fit: Cell::new(true),
305 raise_request: Cell::new(false),
306 collapsed: false,
307 collapsible: true,
308 pre_collapse_h: 280.0,
309 drag_mode: DragMode::None,
310 drag_start_world: Point::ORIGIN,
311 drag_start_bounds: Rect::default(),
312 close_hovered: false,
313 on_close: None,
314 click_away: ClickAwayAction::None,
315 maximized: false,
316 pre_maximize_bounds: Rect::new(60.0, 60.0, 360.0, 280.0),
317 maximize_hovered: false,
318 hover_dir: None,
319 last_title_click: None,
320 title_bar,
321 title_state,
322 // Seed as "unknown" so `layout()`'s shrink-detect guard
323 // (`had_prior = prev.w > 0 && prev.h > 0`) correctly skips the
324 // clamp on the very first layout pass. The old default
325 // `(1280, 720)` was treated as prior, so the first-frame
326 // transition from 1280×720 → <smaller> incorrectly looked like
327 // an OS-window shrink and pulled saved Y-up positions down into
328 // the transient canvas. Real-value `canvas_size` is populated
329 // by `layout()` before any drag/resize/collapse hit-test runs.
330 canvas_size: Size::new(0.0, 0.0),
331 constrain: true,
332 modal: false,
333 auto_size: false,
334 resizable: true,
335 resizable_h: true,
336 resizable_v: true,
337 tight_content_fit: false,
338 floor_content_height: false,
339 last_content_natural_h: Cell::new(0.0),
340 foreground_layer_active: Cell::new(false),
341 title: title_str,
342 on_raised: None,
343 live_content: false,
344 snap_id: crate::snap::next_snap_id(),
345 }
346 }
347
348 /// Returns the window title as it was passed to [`Window::new`].
349 pub fn title(&self) -> &str {
350 &self.title
351 }
352
353 /// Force the window's retained backbuffer to re-rasterise on the next
354 /// paint pass. Use this when the content widget reads from a live
355 /// data source (network feed, animation curve, simulation state)
356 /// that the framework can't observe. Otherwise the cached pixels
357 /// blit unchanged and your live data never reaches the screen.
358 ///
359 /// Pair with [`Window::with_live_content`] for streaming data that
360 /// changes every frame: that flag self-invalidates here automatically
361 /// (and skips when collapsed/hidden).
362 ///
363 /// See [`Window::new`] for the full discussion of when this matters
364 /// and the alternative ("compose live UI out of widgets that
365 /// invalidate on data change") that avoids needing to call this at
366 /// all.
367 pub fn invalidate_backbuffer(&mut self) {
368 self.backbuffer.invalidate();
369 }
370
371 fn requested_visible(&self) -> bool {
372 if let Some(ref cell) = self.visible_cell {
373 cell.get()
374 } else {
375 self.visible
376 }
377 }
378
379 fn layer_outsets() -> (f64, f64, f64, f64) {
380 let left = (SHADOW_BLUR - SHADOW_DX).max(0.0).ceil();
381 let bottom = (SHADOW_BLUR + SHADOW_DY).ceil();
382 let right = (SHADOW_BLUR + SHADOW_DX).ceil();
383 let top = (SHADOW_BLUR - SHADOW_DY).max(0.0).ceil();
384 (left, bottom, right, top)
385 }
386
387 fn clamp_to_canvas(&mut self) {
388 if !self.constrain {
389 return;
390 }
391 // A modal window is constrained to the whole app VIEWPORT rather than the
392 // (often tiny) overlay slot it nests in: `clamp_modal_into_viewport`
393 // pulls it fully on-screen during the clip-free global-overlay paint and
394 // folds any correction back into `bounds`, so a drag can travel across
395 // the entire app and the paint clamp keeps it visible. Applying the
396 // slot-based clamp here would re-cage it to the parent slot — the exact
397 // "locked to a dimension less than the app" bug we're fixing.
398 if self.modal {
399 return;
400 }
401 let cw = self.canvas_size.width;
402 let ch = self.canvas_size.height;
403 // **Policy: keep the TITLE BAR grabbable**, not the whole window.
404 // Horizontally we keep at least `MIN_H_VISIBLE` pixels of the title
405 // bar inside the canvas so the user can always drag the window back
406 // on-screen. Vertically (Y-up) we keep the FULL title bar inside
407 // the canvas — the body may extend above/below, but the drag handle
408 // is always fully reachable. This matches how native OS window
409 // managers constrain child windows against their host monitor.
410 const MIN_H_VISIBLE: f64 = 40.0;
411
412 let min_x = MIN_H_VISIBLE - self.bounds.width;
413 let max_x = (cw - MIN_H_VISIBLE).max(min_x);
414 self.bounds.x = self.bounds.x.clamp(min_x, max_x).round();
415
416 // Title bar Y range in parent coords: [bounds.y + h - TITLE_H, bounds.y + h].
417 // Full title bar visible → `bounds.y >= TITLE_H - h` AND `bounds.y <= ch - h`.
418 // `bounds.height` collapses to `TITLE_H` when the user folds the
419 // window, so the collapsed case naturally falls out of the same math.
420 let min_y = TITLE_H - self.bounds.height;
421 let max_y = (ch - self.bounds.height).max(min_y);
422 self.bounds.y = self.bounds.y.clamp(min_y, max_y).round();
423 }
424
425 fn fit_fully_to_canvas(&mut self, available: Size) {
426 if !self.constrain || available.width <= 1.0 || available.height <= 1.0 {
427 return;
428 }
429 let max_w = available.width.max(MIN_W);
430 let max_h = available.height.max(TITLE_H);
431 self.bounds.width = self.bounds.width.clamp(MIN_W.min(max_w), max_w).round();
432 self.bounds.height = self.bounds.height.clamp(TITLE_H, max_h).round();
433 self.bounds.x = self
434 .bounds
435 .x
436 .clamp(0.0, (available.width - self.bounds.width).max(0.0))
437 .round();
438 self.bounds.y = self
439 .bounds
440 .y
441 .clamp(0.0, (available.height - self.bounds.height).max(0.0))
442 .round();
443 self.pre_collapse_h = self.bounds.height;
444 if self.maximized {
445 self.pre_maximize_bounds = self.bounds;
446 }
447 }
448
449 /// Close the window: hide it, sync the optional `visible_cell`, and fire
450 /// `on_close`. Shared by the title-bar × button, the Escape key (modal
451 /// windows), and any programmatic close so every route runs the same
452 /// teardown — critically the `on_close` hook, which a modal dialog uses to
453 /// unwind in-flight state (e.g. cancelling a live colour preview). Before
454 /// this was factored out, only the × button ran it, so an Escape/close of
455 /// the colour dialog left its preview session dangling.
456 ///
457 /// `reason` distinguishes the dismissal route (× button, Escape, click-away)
458 /// so `on_close` can react differently — the colour dialog commits a live
459 /// change on click-away but cancels it on Escape / ×.
460 fn close(&mut self, reason: CloseReason) {
461 self.visible = false;
462 self.visibility_anim.set_target(0.0);
463 if let Some(ref cell) = self.visible_cell {
464 cell.set(false);
465 }
466 if let Some(cb) = self.on_close.as_mut() {
467 cb(reason);
468 }
469 crate::animation::request_draw();
470 }
471
472 pub fn show(&mut self) {
473 self.visible = true;
474 self.fade_out_active.set(false);
475 self.visibility_anim.set_target(1.0);
476 crate::animation::request_draw();
477 }
478 pub fn hide(&mut self) {
479 self.visible = false;
480 self.visibility_anim.set_target(0.0);
481 crate::animation::request_draw();
482 }
483 pub fn toggle(&mut self) {
484 if self.visible {
485 self.hide();
486 } else {
487 self.show();
488 }
489 }
490 /// Current visibility — honours an optional shared `visible_cell` when
491 /// wired (sidebar toggles, programmatic show/hide). The inherent
492 /// `self.visible` field is a fallback for windows that aren't wired to
493 /// a cell. Must match the Widget-trait impl below so rising-edge
494 /// detection in `layout()` observes sidebar toggles.
495 pub fn is_visible(&self) -> bool {
496 self.requested_visible() || self.fade_out_active.get()
497 }
498
499 fn title_bar_bottom(&self) -> f64 {
500 self.bounds.height - TITLE_H
501 }
502
503 fn in_title_bar(&self, local: Point) -> bool {
504 local.y >= self.title_bar_bottom()
505 && local.y <= self.bounds.height
506 && local.x >= 0.0
507 && local.x <= self.bounds.width
508 }
509
510 fn close_center(&self) -> Point {
511 Point::new(
512 self.bounds.width - CLOSE_PAD,
513 self.bounds.height - TITLE_H * 0.5,
514 )
515 }
516
517 fn in_close_button(&self, local: Point) -> bool {
518 let c = self.close_center();
519 let dx = local.x - c.x;
520 let dy = local.y - c.y;
521 dx * dx + dy * dy <= (CLOSE_R + 3.0) * (CLOSE_R + 3.0)
522 }
523
524 fn maximize_center(&self) -> Point {
525 Point::new(
526 self.bounds.width - MAX_PAD,
527 self.bounds.height - TITLE_H * 0.5,
528 )
529 }
530
531 fn in_maximize_button(&self, local: Point) -> bool {
532 let c = self.maximize_center();
533 let dx = local.x - c.x;
534 let dy = local.y - c.y;
535 dx * dx + dy * dy <= (CLOSE_R + 3.0) * (CLOSE_R + 3.0)
536 }
537
538 /// Toggle collapsed <-> expanded, keeping the top edge of the window
539 /// fixed in place. Factored out of the event path so both the chevron
540 /// click and any future keyboard shortcut go through the same math.
541 fn toggle_collapse(&mut self) {
542 let top = self.bounds.y + self.bounds.height;
543 if self.collapsed {
544 self.bounds.height = self.pre_collapse_h;
545 self.bounds.y = (top - self.pre_collapse_h).round();
546 self.collapsed = false;
547 } else {
548 self.pre_collapse_h = self.bounds.height;
549 self.bounds.height = TITLE_H;
550 self.bounds.y = (top - TITLE_H).round();
551 self.collapsed = true;
552 }
553 self.clamp_to_canvas();
554 }
555
556 fn toggle_maximize(&mut self) {
557 if self.maximized {
558 self.bounds = self.pre_maximize_bounds;
559 self.maximized = false;
560 } else {
561 self.pre_maximize_bounds = self.bounds;
562 self.bounds = snap(Rect::new(
563 0.0,
564 0.0,
565 self.canvas_size.width,
566 self.canvas_size.height,
567 ));
568 self.maximized = true;
569 }
570 if let Some(ref cell) = self.maximized_cell {
571 cell.set(self.maximized);
572 }
573 }
574
575 /// Return the resize direction for `local`, or `None` if the point is in
576 /// the interior (or the window is collapsed).
577 fn resize_dir(&self, local: Point) -> Option<ResizeDir> {
578 if self.collapsed || self.auto_size {
579 return None;
580 }
581 if !self.resizable {
582 return None;
583 }
584 let w = self.bounds.width;
585 let h = self.bounds.height;
586 let x = local.x;
587 let y = local.y;
588
589 // Outside the window altogether.
590 if x < 0.0 || x > w || y < 0.0 || y > h {
591 return None;
592 }
593
594 // Mask each edge to the axes the window is allowed to resize on.
595 let on_n = self.resizable_v && y > h - RESIZE_EDGE;
596 let on_s = self.resizable_v && y < RESIZE_EDGE;
597 let on_w = self.resizable_h && x < RESIZE_EDGE;
598 let on_e = self.resizable_h && x > w - RESIZE_EDGE;
599
600 match (on_n, on_e, on_s, on_w) {
601 (true, true, _, _) => Some(ResizeDir::NE),
602 (true, _, _, true) => Some(ResizeDir::NW),
603 (_, _, true, true) => Some(ResizeDir::SW),
604 (_, true, true, _) => Some(ResizeDir::SE),
605 (true, _, _, _) => Some(ResizeDir::N),
606 (_, true, _, _) => Some(ResizeDir::E),
607 (_, _, true, _) => Some(ResizeDir::S),
608 (_, _, _, true) => Some(ResizeDir::W),
609 _ => None,
610 }
611 }
612
613 /// Effective minimum height for this resize pass. Honours
614 /// either `tight_content_fit` (lock + floor) or
615 /// `floor_content_height` (floor only) so a window whose content
616 /// has a natural height > MIN_H can never be dragged smaller
617 /// than its content.
618 fn effective_min_h(&self) -> f64 {
619 if self.tight_content_fit || self.floor_content_height {
620 let content_min = self.last_content_natural_h.get() + TITLE_H;
621 MIN_H.max(content_min)
622 } else {
623 MIN_H
624 }
625 }
626
627 /// Apply a mouse-world-space delta to bounds according to the resize direction.
628 fn apply_resize(&mut self, world_pos: Point) {
629 let dx = world_pos.x - self.drag_start_world.x;
630 let dy = world_pos.y - self.drag_start_world.y;
631 let sb = self.drag_start_bounds;
632 let min_h = self.effective_min_h();
633
634 let (mut x, mut y, mut w, mut h) = (sb.x, sb.y, sb.width, sb.height);
635
636 if let DragMode::Resize(dir) = self.drag_mode {
637 match dir {
638 ResizeDir::N => {
639 h = (sb.height + dy).max(min_h);
640 }
641 ResizeDir::S => {
642 y = sb.y + dy;
643 h = (sb.height - dy).max(min_h);
644 if h == min_h {
645 y = sb.y + sb.height - min_h;
646 }
647 }
648 ResizeDir::E => {
649 w = (sb.width + dx).max(MIN_W);
650 }
651 ResizeDir::W => {
652 x = sb.x + dx;
653 w = (sb.width - dx).max(MIN_W);
654 if w == MIN_W {
655 x = sb.x + sb.width - MIN_W;
656 }
657 }
658 ResizeDir::NE => {
659 w = (sb.width + dx).max(MIN_W);
660 h = (sb.height + dy).max(min_h);
661 }
662 ResizeDir::NW => {
663 x = sb.x + dx;
664 w = (sb.width - dx).max(MIN_W);
665 if w == MIN_W {
666 x = sb.x + sb.width - MIN_W;
667 }
668 h = (sb.height + dy).max(min_h);
669 }
670 ResizeDir::SE => {
671 w = (sb.width + dx).max(MIN_W);
672 y = sb.y + dy;
673 h = (sb.height - dy).max(min_h);
674 if h == min_h {
675 y = sb.y + sb.height - min_h;
676 }
677 }
678 ResizeDir::SW => {
679 x = sb.x + dx;
680 w = (sb.width - dx).max(MIN_W);
681 if w == MIN_W {
682 x = sb.x + sb.width - MIN_W;
683 }
684 y = sb.y + dy;
685 h = (sb.height - dy).max(min_h);
686 if h == min_h {
687 y = sb.y + sb.height - min_h;
688 }
689 }
690 }
691 }
692
693 self.bounds = snap(Rect::new(x, y, w, h));
694 self.clamp_to_canvas();
695 }
696}
697
698/// Map a resize direction to the appropriate OS cursor icon.
699fn resize_cursor(dir: ResizeDir) -> CursorIcon {
700 match dir {
701 ResizeDir::N => CursorIcon::ResizeNorth,
702 ResizeDir::S => CursorIcon::ResizeSouth,
703 ResizeDir::E => CursorIcon::ResizeEast,
704 ResizeDir::W => CursorIcon::ResizeWest,
705 ResizeDir::NE => CursorIcon::ResizeNorthEast,
706 ResizeDir::NW => CursorIcon::ResizeNorthWest,
707 ResizeDir::SE => CursorIcon::ResizeSouthEast,
708 ResizeDir::SW => CursorIcon::ResizeSouthWest,
709 }
710}
711
712mod builder;
713pub mod chrome;
714mod close;
715mod paint;
716mod snap_glue;
717mod widget_impl;
718
719pub use close::{ClickAwayAction, CloseReason};
720
721pub use chrome::{
722 paint_chevron, paint_chrome_body, paint_chrome_border, paint_chrome_shadow,
723 paint_chrome_title_bar, ChromeStyle,
724};