tvision_rs/window/window.rs
1//! [`Window`] core — see the [module docs](super) for the overview.
2
3use crate::capture::{CaptureFlow, CaptureHandler};
4use crate::command::Command;
5use crate::event::{Event, Key};
6use crate::frame::Frame;
7use crate::view::{
8 Context, DividerOp, DragMode, DrawCtx, Group, GrowMode, Point, Rect, StateFlag, View, ViewId,
9};
10use crate::widgets::{Orientation, ScrollBar};
11
12// ---------------------------------------------------------------------------
13// WindowFlags
14// ---------------------------------------------------------------------------
15
16/// Window decoration flags: which of move / grow / close / zoom the window
17/// allows.
18///
19/// Build a customised `WindowFlags` (e.g. at construction) to change which
20/// controls appear on the frame. The default (via `Default`) enables all
21/// four. Disable individual fields to suppress a decoration:
22///
23/// ```rust
24/// use tvision_rs::window::WindowFlags;
25/// let no_zoom = WindowFlags { zoom: false, ..Default::default() };
26/// assert!(!no_zoom.zoom);
27/// ```
28///
29/// **`r#move` spelling:** `move` is a Rust keyword, so the field is accessed as
30/// `flags.r#move`. The raw-identifier syntax is a Rust-only artefact; at the
31/// semantic level it is identical to the C++ `wfMove` bit.
32///
33/// These flags belong to the window; the [`Frame`] receives a pushed-down copy
34/// via [`Frame::set_flags`](crate::frame::Frame::set_flags) and renders the
35/// corresponding icons (close `[×]`, zoom `[↕]`, grow corner `▐`).
36///
37/// # Turbo Vision heritage
38///
39/// Ports the `wfMove / wfGrow / wfClose / wfZoom` flag word (`views.h`) as a
40/// struct-of-bools.
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
42pub struct WindowFlags {
43 /// The window can be moved by dragging its frame.
44 pub r#move: bool,
45 /// The window can be resized by dragging its bottom corners.
46 pub grow: bool,
47 /// The window shows a close icon (and accepts a close command).
48 pub close: bool,
49 /// The window shows a zoom icon (and accepts a zoom command).
50 pub zoom: bool,
51}
52
53// ---------------------------------------------------------------------------
54// WindowPalette
55// ---------------------------------------------------------------------------
56
57/// Which colour scheme the window draws in.
58///
59/// Choose the variant that matches the window's purpose:
60///
61/// - [`Blue`](WindowPalette::Blue) — plain application windows; the default.
62/// Draws in the `Role::FrameActive` / `FramePassive` / `FrameDragging` /
63/// `FrameIcon` / `Role::ScrollBar*` / `Role::Scroller*` role family.
64/// - [`Cyan`](WindowPalette::Cyan) — secondary / highlight windows (e.g.
65/// help viewers). Draws in the `Role::FrameCyanActive` / `FrameCyanPassive`
66/// / `FrameCyanIcon` family.
67/// - [`Gray`](WindowPalette::Gray) — dialog boxes. [`Dialog`](crate::dialog::Dialog)
68/// sets this automatically; use it directly when building a dialog-styled
69/// custom window. Draws in the `Role::FrameGrayActive` / `FrameGrayPassive`
70/// / `FrameGrayIcon` family.
71///
72/// The scheme is stored on the [`Window`] and pushed down to the [`Frame`]
73/// child automatically; no manual frame update is needed when the palette
74/// changes.
75///
76/// # Turbo Vision heritage
77///
78/// Replaces the `wpBlueWindow = 1 / wpCyanWindow = 2 / wpGrayWindow = 3`
79/// integer palette selector (`views.h`; the guide calls these
80/// `dpBlueDialog / dpCyanDialog / dpGrayDialog`) with a typed enum, which the
81/// frame maps to named `Role` entries in the theme. The eight
82/// per-palette entries described in the guide (frame passive, frame active,
83/// frame icon, scrollbar page, scrollbar controls, scroller normal, scroller
84/// selected, reserved) are expressed as named `Role` variants rather than
85/// integer indices.
86#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
87pub enum WindowPalette {
88 /// The default window scheme (`Role::Frame*` family).
89 #[default]
90 Blue,
91 /// The cyan scheme (`Role::FrameCyan*` family).
92 Cyan,
93 /// The gray scheme used by dialogs (`Role::FrameGray*` family).
94 Gray,
95}
96
97// ---------------------------------------------------------------------------
98// Fullscreen
99// ---------------------------------------------------------------------------
100
101/// Whether (and how) a window fills the screen with no frame border.
102///
103/// `Off` is a normal framed window; `Desktop` hides the border and fills the
104/// desktop area; `Screen` additionally covers the menu row (the menu bar
105/// collapses to a `[⋮]` kebab at the top-right). Per-window property, driven by
106/// `set_fullscreen`.
107///
108/// # Turbo Vision heritage
109/// **tvision-rs extension** to `TWindow`.
110#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
111pub enum Fullscreen {
112 /// Normal framed window.
113 #[default]
114 Off,
115 /// Frameless, fills the desktop; menu bar and status line unchanged.
116 Desktop,
117 /// Frameless, also covers the menu row; the menu bar collapses to `[⋮]`.
118 Screen,
119}
120
121impl Fullscreen {
122 /// The next state in the `Off → Desktop → Screen → Off` cycle (the
123 /// `Command::FULLSCREEN` convenience cycler).
124 pub fn next(self) -> Self {
125 match self {
126 Fullscreen::Off => Fullscreen::Desktop,
127 Fullscreen::Desktop => Fullscreen::Screen,
128 Fullscreen::Screen => Fullscreen::Off,
129 }
130 }
131}
132
133// ---------------------------------------------------------------------------
134// ScrollBarOptions — placement + keyboard options for standard_scroll_bar
135// ---------------------------------------------------------------------------
136
137/// Options for [`Window::standard_scroll_bar`]: where to place the bar and
138/// whether it handles the keyboard.
139///
140/// The default (both flags false) is a horizontal bar that does not handle the
141/// keyboard.
142#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
143pub struct ScrollBarOptions {
144 /// Place the bar on the right edge (else the bottom edge).
145 pub vertical: bool,
146 /// The bar opts into post-processing so it handles focused-chain arrow keys
147 /// even when it is not the current view.
148 pub handle_keyboard: bool,
149}
150
151// ---------------------------------------------------------------------------
152// Window
153// ---------------------------------------------------------------------------
154
155/// A framed, selectable window: a [`Group`] that builds a
156/// [`Frame`](crate::frame::Frame) around itself.
157///
158/// Build with [`Window::new`], then drive it as any other [`View`].
159///
160/// # Turbo Vision heritage
161///
162/// Ports `TWindow` (`twindow.cpp`). The base-class container becomes an embedded
163/// [`Group`] (deviation D2); the window pushes the frame's data down rather than
164/// letting the frame reach up (deviation D3).
165pub struct Window {
166 /// The embedded container. A `Window` *is* a group: its state, draw, and
167 /// event routing are the group's.
168 group: Group,
169 /// The frame child's id. The maximize/restore + border primitives push the
170 /// zoomed / border-visible flags through it.
171 frame_id: ViewId,
172 /// The decoration flags.
173 flags: WindowFlags,
174 /// The saved bounds for un-maximize. `None` ⇔ not maximized. The single
175 /// restore slot shared by the `ZOOM` command and fullscreen-Desktop (so they
176 /// cannot desync). See [`maximize`](Self::maximize) / [`restore`](Self::restore).
177 restore_rect: Option<Rect>,
178 /// The interactive-resize floor. Every size clamp (mouse corner drag,
179 /// keyboard resize, ZOOM/restore, owner-driven `calc_bounds`) reads this
180 /// through [`size_limits`](View::size_limits). Defaults to
181 /// [`Self::MIN_WIN_SIZE`] (16×6) and can only be raised, never lowered
182 /// below it ([`set_min_size`](Self::set_min_size) clamps).
183 min_size: Point,
184 /// Whether the frame border is drawn (default `true`). An **independent**
185 /// primitive, decoupled from [`fullscreen`](Self::fullscreen): toggled by
186 /// [`set_bordered`](Self::set_bordered), which also reflows content. Read by
187 /// [`client_rect`](Self::client_rect) and the drag-start guard.
188 bordered: bool,
189 /// The id of the vertical (right-edge) scroll bar minted by
190 /// [`standard_scroll_bar`](Self::standard_scroll_bar), if any. Chrome
191 /// (edge-anchored), so a border toggle re-derives its rect rather than
192 /// applying the content transform. Also used by `client_rect` to exclude
193 /// the bar lane from the content area.
194 vsb_id: Option<ViewId>,
195 /// The id of the horizontal (bottom-edge) scroll bar minted by
196 /// [`standard_scroll_bar`](Self::standard_scroll_bar), if any. Chrome
197 /// (edge-anchored), so a border toggle re-derives its rect rather than
198 /// applying the content transform. Also used by `client_rect` to exclude
199 /// the bar lane from the content area.
200 hsb_id: Option<ViewId>,
201 /// The window number.
202 number: i16,
203 /// The colour scheme. See [`WindowPalette`].
204 palette: WindowPalette,
205 /// The window title.
206 title: Option<String>,
207 /// Whether the window is frameless-fullscreen, and in which mode. Driven by
208 /// [`set_fullscreen`](Self::set_fullscreen); read by the `Command::FULLSCREEN`
209 /// cycler. Composed of the independent border + maximize primitives.
210 fullscreen: Fullscreen,
211 /// Whether a collapsed application menu bar (its `[⋮]` kebab) sits directly
212 /// above this window's top-right corner — true only while the window is in
213 /// `Fullscreen::Screen` *and* the program has a menu bar. Pushed down by the
214 /// pump's fullscreen layout engine (it owns that cross-tree fact) via
215 /// [`set_menu_chrome_above`](Self::set_menu_chrome_above); read by
216 /// [`scroll_bar_rect`](Self::scroll_bar_rect) to inset a right-edge vertical
217 /// scroll bar's **top** one row so its up-arrow clears the kebab.
218 menu_chrome_above: bool,
219}
220
221impl Window {
222 /// The absolute minimum a framed window may shrink to and still render its
223 /// title bar and corner icons legibly. Ports `minWinSize` (`twindow.cpp:30`).
224 /// The default [`size_limits`](View::size_limits) minimum; a larger floor
225 /// can be set with [`set_min_size`](Self::set_min_size).
226 pub const MIN_WIN_SIZE: Point = Point::new(16, 6);
227
228 /// Construct a window over `bounds` with an optional `title` and a window
229 /// `number`.
230 ///
231 /// **`number`:** pass a positive value (`1`–`9`) to make the window reachable
232 /// via the Alt-*N* keyboard shortcut; [`Program`](crate::Program) broadcasts
233 /// [`Command::SELECT_WINDOW_NUM`](crate::Command::SELECT_WINDOW_NUM) and the
234 /// desktop finds the matching window by its number. Pass `0` (the
235 /// `wnNoNumber` sentinel from Turbo Vision) for an unnumbered window that is
236 /// never a select-by-number target — this is the common case for document
237 /// windows that are cycled with `NEXT`/`PREV` instead of by number.
238 ///
239 /// Defaults set at construction: all four decoration flags enabled
240 /// (move/grow/close/zoom); not maximized (no restore rect) and bordered; the
241 /// blue colour scheme; a drop shadow; selectable + top-of-select-group; and a
242 /// relative grow-all mode (children resize proportionally with the window).
243 ///
244 /// **Frame data is pushed down at construction.** We build the [`Frame`]
245 /// **concretely** so we can call its owner-data-down setters
246 /// ([`set_title`](Frame::set_title)/[`set_flags`](Frame::set_flags)/
247 /// [`set_number`](Frame::set_number)) before boxing + inserting.
248 ///
249 /// **A frame is mandatory:** `frame_id` is non-optional. A frameless variant
250 /// has no consumer here, and supporting it would force an `Option<ViewId>`
251 /// ripple for a path no caller exercises, so we always build the frame.
252 pub fn new(bounds: Rect, title: Option<String>, number: i16) -> Self {
253 let mut group = Group::new(bounds);
254
255 // All four decoration flags enabled by default.
256 let flags = WindowFlags {
257 r#move: true,
258 grow: true,
259 close: true,
260 zoom: true,
261 };
262 // Drop shadow; selectable and top-of-select-group.
263 let st = group.state_mut();
264 st.state.shadow = true;
265 st.options.selectable = true;
266 st.options.top_select = true;
267 // Relative grow-all: children resize proportionally with the window.
268 st.grow_mode = GrowMode {
269 rel: true,
270 ..GrowMode::grow_all()
271 };
272
273 let extent = group.state().get_extent();
274
275 // We build the Frame directly and push owner data into it at construction;
276 // the downcast seam reaches it post-insert for `set_zoomed`. A
277 // custom-frame injection hook has no consumer yet; reintroduce it when a
278 // subtype needs a non-default frame.
279 let mut frame = Frame::new(extent);
280 frame.set_title(title.clone());
281 frame.set_flags(flags);
282 frame.set_number(number_to_option(number));
283 let frame_id = group.insert(Box::new(frame));
284
285 Window {
286 group,
287 frame_id,
288 flags,
289 restore_rect: None,
290 min_size: Self::MIN_WIN_SIZE,
291 bordered: true,
292 vsb_id: None,
293 hsb_id: None,
294 number,
295 palette: WindowPalette::Blue,
296 title,
297 fullscreen: Fullscreen::Off,
298 menu_chrome_above: false,
299 }
300 }
301
302 // -- accessors -----------------------------------------------------------
303
304 /// The [`ViewId`] of the [`Frame`](crate::frame::Frame) child that draws the
305 /// window border, title, and icons.
306 ///
307 /// Use this id to reach the frame via `child_mut` + downcast when you need to
308 /// call a frame-specific method (e.g. to read [`Frame::zoomed`]). The window
309 /// itself never holds a direct `&mut Frame` reference across calls; instead it
310 /// always resolves the id on demand — the push-down pattern that avoids upward
311 /// parent pointers.
312 pub fn frame_id(&self) -> ViewId {
313 self.frame_id
314 }
315
316 /// The current decoration flags (which of move / grow / close / zoom are enabled).
317 ///
318 /// Read these to check which operations the window permits; for example,
319 /// `flags().zoom` is true when the zoom icon is shown and the zoom command is
320 /// accepted. To change the flags after construction use `set_flags` (crate-internal).
321 pub fn flags(&self) -> WindowFlags {
322 self.flags
323 }
324
325 /// The saved pre-maximize bounds, or `None` when the window is not maximized.
326 ///
327 /// [`maximize`](Self::maximize) stores the current bounds here before growing
328 /// to fill the owner; [`restore`](Self::restore) consumes them. This is the
329 /// single restore slot shared by the `ZOOM` command and fullscreen-Desktop.
330 /// Primarily useful for testing; normal application code reads
331 /// [`is_maximized`](Self::is_maximized) instead.
332 pub fn restore_rect(&self) -> Option<Rect> {
333 self.restore_rect
334 }
335
336 /// Whether the window is currently maximized (filling its owner via
337 /// [`maximize`](Self::maximize)). Equivalent to `restore_rect().is_some()`.
338 pub fn is_maximized(&self) -> bool {
339 self.restore_rect.is_some()
340 }
341
342 /// Whether the frame border is drawn. An independent primitive (decoupled from
343 /// [`fullscreen`](Self::fullscreen)); toggle with
344 /// [`set_bordered`](Self::set_bordered).
345 pub fn bordered(&self) -> bool {
346 self.bordered
347 }
348
349 // NOTE: the window number is exposed via the `View::number()` trait override
350 // below (returning `Option<i16>` — `None` for an unnumbered window), so Alt-N
351 // can query any `&dyn View` for its number. No inherent getter.
352
353 /// The colour scheme used to draw this window's frame.
354 ///
355 /// Plain windows use [`WindowPalette::Blue`] (the default); dialogs use
356 /// [`WindowPalette::Gray`] (set automatically by [`Dialog`](crate::dialog::Dialog)).
357 /// Inspect this to branch on the active scheme; to change it after construction
358 /// use `set_palette` (crate-internal).
359 pub fn palette(&self) -> WindowPalette {
360 self.palette
361 }
362
363 /// The window title displayed in the frame's title bar, or `None` for an
364 /// untitled window.
365 ///
366 /// Pass the title at construction via [`Window::new`]. To rename the window
367 /// after construction (e.g. after a save-as), use `set_title` (crate-internal),
368 /// which updates both this field and the frame child. The frame truncates the
369 /// title to the available title-bar width at draw time; no explicit length limit
370 /// is needed here.
371 pub fn title(&self) -> Option<&str> {
372 self.title.as_deref()
373 }
374
375 /// The window's current [`Fullscreen`] state.
376 pub fn fullscreen(&self) -> Fullscreen {
377 self.fullscreen
378 }
379
380 /// Update the window title in both the `Window` record and the [`Frame`]
381 /// child. Called from an editor window's event handler on the
382 /// update-title broadcast (an editor fires it after a save-as rename). Because
383 /// the title is stored here and drawn by the frame, this recomputes the title
384 /// and re-pushes it to the frame. Pattern mirrors [`set_flags`]: find the
385 /// frame child, downcast, call the frame setter.
386 pub(crate) fn set_title(&mut self, title: Option<String>) {
387 self.title = title.clone();
388 if let Some(frame) = self
389 .group
390 .child_mut(self.frame_id)
391 .and_then(|v| v.as_any_mut())
392 .and_then(|a| a.downcast_mut::<Frame>())
393 {
394 frame.set_title(title);
395 }
396 }
397
398 // -- setters and builders: public post-construction configuration surface --
399
400 /// Override the decoration flags after construction. Re-pushes to the frame
401 /// child: construction pushes the flags once, so a later change must re-push
402 /// or the frame would still draw the original zoom/grow icons. Resolves the
403 /// frame child then downcasts then calls [`Frame::set_flags`], the same seam
404 /// `zoom` uses.
405 pub fn set_flags(&mut self, flags: WindowFlags) {
406 self.flags = flags;
407 if let Some(frame) = self
408 .group
409 .child_mut(self.frame_id)
410 .and_then(|v| v.as_any_mut())
411 .and_then(|a| a.downcast_mut::<Frame>())
412 {
413 frame.set_flags(flags);
414 }
415 }
416
417 /// Override the colour scheme after construction. Re-pushes to the frame
418 /// child (the [`set_flags`](Self::set_flags) pattern) so the frame renders
419 /// the matching role family: `Blue` → `Role::Frame*`, `Cyan` →
420 /// `Role::FrameCyan*`, `Gray` → `Role::FrameGray*`.
421 pub fn set_palette(&mut self, palette: WindowPalette) {
422 self.palette = palette;
423 if let Some(frame) = self
424 .group
425 .child_mut(self.frame_id)
426 .and_then(|v| v.as_any_mut())
427 .and_then(|a| a.downcast_mut::<Frame>())
428 {
429 frame.set_palette(palette);
430 }
431 }
432
433 /// Override the grow mode after construction (a dialog uses an empty grow
434 /// mode — it does not track its owner's resize).
435 pub fn set_grow_mode(&mut self, grow_mode: GrowMode) {
436 self.group.state_mut().grow_mode = grow_mode;
437 }
438
439 /// Override the drag mode after construction (the screen-edge limits the window
440 /// honors while being dragged). Mirrors [`set_grow_mode`](Self::set_grow_mode):
441 /// a plain write to the embedded group's [`ViewState::drag_mode`](crate::view::ViewState::drag_mode).
442 pub fn set_drag_mode(&mut self, drag_mode: DragMode) {
443 self.group.state_mut().drag_mode = drag_mode;
444 }
445
446 /// Raise the window's interactive-resize floor. The argument is clamped up
447 /// to at least [`Self::MIN_WIN_SIZE`] per axis (title/icons must stay
448 /// legible), so this can only grow the minimum. Consulted by every
449 /// size-clamp path — mouse corner drag, keyboard resize, ZOOM/restore,
450 /// owner-driven resize — via [`size_limits`](View::size_limits).
451 ///
452 /// # Turbo Vision heritage
453 /// In C++ a window subclass raises its floor by overriding the virtual
454 /// `sizeLimits` (e.g. `TFileDialog`, `TEditWindow`), which every clamp
455 /// path calls virtually. Embed-and-delegate composition (D2) has no upward
456 /// dispatch, so the wrapper pushes its floor down into the window instead.
457 pub fn set_min_size(&mut self, min: Point) {
458 self.min_size = Point::new(
459 min.x.max(Self::MIN_WIN_SIZE.x),
460 min.y.max(Self::MIN_WIN_SIZE.y),
461 );
462 }
463
464 /// Builder form of [`set_flags`](Self::set_flags).
465 pub fn with_flags(mut self, flags: WindowFlags) -> Self {
466 self.set_flags(flags);
467 self
468 }
469
470 /// Builder form of [`set_palette`](Self::set_palette).
471 pub fn with_palette(mut self, palette: WindowPalette) -> Self {
472 self.set_palette(palette);
473 self
474 }
475
476 /// Builder form of [`set_grow_mode`](Self::set_grow_mode).
477 pub fn with_grow_mode(mut self, grow_mode: GrowMode) -> Self {
478 self.set_grow_mode(grow_mode);
479 self
480 }
481
482 /// Builder form of [`set_drag_mode`](Self::set_drag_mode).
483 pub fn with_drag_mode(mut self, drag_mode: DragMode) -> Self {
484 self.set_drag_mode(drag_mode);
485 self
486 }
487
488 /// Builder form of [`set_min_size`](Self::set_min_size).
489 pub fn with_min_size(mut self, min: Point) -> Self {
490 self.set_min_size(min);
491 self
492 }
493
494 /// Insert a child view into the embedded group.
495 ///
496 /// Used by the history window (which inserts the history viewer after the
497 /// scroll bars), by [`Dialog`](crate::dialog::Dialog), and by the message box.
498 ///
499 /// Exposed publicly so that example/application code can build custom windows
500 /// with child views.
501 pub fn insert_child(&mut self, view: Box<dyn View>) -> ViewId {
502 self.group.insert(view)
503 }
504
505 /// Reach a direct child of the embedded group by id.
506 ///
507 /// Used by the history window to run the viewer's post-insert setup and to
508 /// read its selection via `as_any_mut` + downcast. Mirrors `Group::child_mut`
509 /// without exposing the group itself.
510 pub fn child_mut(&mut self, id: ViewId) -> Option<&mut dyn View> {
511 self.group.child_mut(id)
512 }
513
514 /// Gather the embedded group's whole record as one ordered
515 /// [`FieldValue::List`](crate::data::FieldValue). Forwards to
516 /// [`Group::gather_list`](crate::view::Group::gather_list).
517 pub fn gather_list(&self) -> crate::data::FieldValue {
518 self.group.gather_list()
519 }
520
521 /// Scatter an ordered [`FieldValue::List`](crate::data::FieldValue) record
522 /// back into the embedded group. Forwards to
523 /// [`Group::scatter_list`](crate::view::Group::scatter_list).
524 pub fn scatter_list(&mut self, record: &crate::data::FieldValue, ctx: &mut Context) {
525 self.group.scatter_list(record, ctx);
526 }
527
528 /// The first non-frame child that downcasts to a [`Splitter`](crate::widgets::Splitter),
529 /// or `None`. Used by the auto-brokering `draw` to read divider abutments.
530 fn interior_splitter_mut(&mut self) -> Option<&mut crate::widgets::Splitter> {
531 let frame_id = self.frame_id;
532 let ids: Vec<ViewId> = self
533 .group
534 .child_ids_in_order()
535 .into_iter()
536 .filter(|&id| id != frame_id)
537 .collect();
538 // Probe-then-reborrow: NLL can't prove the early-return borrow is dropped
539 // on the fall-through path, so we test with one borrow and return with a
540 // fresh one.
541 for id in ids {
542 let is_splitter = self
543 .group
544 .child_mut(id)
545 .and_then(|v| v.as_any_mut())
546 .and_then(|a| a.downcast_mut::<crate::widgets::Splitter>())
547 .is_some();
548 if is_splitter {
549 return self
550 .group
551 .child_mut(id)
552 .and_then(|v| v.as_any_mut())
553 .and_then(|a| a.downcast_mut::<crate::widgets::Splitter>());
554 }
555 }
556 None
557 }
558
559 /// The frame child, downcast to [`Frame`] — the same seam `zoom`/`set_flags` use.
560 fn frame_mut(&mut self) -> Option<&mut Frame> {
561 self.group
562 .child_mut(self.frame_id)
563 .and_then(|v| v.as_any_mut())
564 .and_then(|a| a.downcast_mut::<Frame>())
565 }
566
567 /// Make `id` the current (focused) child of the embedded group, so focused
568 /// (keyboard) events route to it. Test-only: in production the insert → show →
569 /// reset-current cascade is realized by `exec_view`'s post-insert
570 /// `reset_current` plus the pump's `settle_currency` pass, so no per-site
571 /// stand-in is needed.
572 #[cfg(test)]
573 pub(crate) fn select_child(&mut self, id: ViewId, ctx: &mut Context) {
574 self.group
575 .set_current(Some(id), crate::view::SelectMode::Normal, ctx);
576 }
577
578 // -- client rect ---------------------------------------------------------
579
580 /// The window interior inset by the frame only (NOT the scroll-bar lanes) —
581 /// the span a standard scroll bar runs along its edge. Used by
582 /// [`scroll_bar_rect`](Self::scroll_bar_rect) to derive bar placement in
583 /// bordered mode (identical to the old client_rect formula for bordered
584 /// windows).
585 fn frame_interior(&self) -> Rect {
586 let ext = self.group.state().get_extent();
587 let bi = if self.bordered { 1 } else { 0 };
588 Rect::from_points(
589 Point::new(ext.a.x + bi, ext.a.y + bi),
590 Point::new(ext.b.x - bi, ext.b.y - bi),
591 )
592 }
593
594 /// The window's interior content rectangle (view-local). Inset by the frame
595 /// border when [`bordered`](Self::bordered). Scroll-bar lanes are always
596 /// excluded — the right column when a vertical bar is present, the bottom row
597 /// when a horizontal bar is present — so placing content at `client_rect`
598 /// never overlaps the bars regardless of border state. Apps placing window
599 /// content should key off this rather than hardcoding the frame inset.
600 pub fn client_rect(&self) -> Rect {
601 let ext = self.group.state().get_extent();
602 let bi = if self.bordered { 1 } else { 0 };
603 // The bar occupies the last column/row of the EXTENT; in bordered mode the
604 // frame inset already excludes it, so take the max (no double inset).
605 let right = bi.max(i32::from(self.vsb_id.is_some()));
606 let bottom = bi.max(i32::from(self.hsb_id.is_some()));
607 Rect::from_points(
608 Point::new(ext.a.x + bi, ext.a.y + bi),
609 Point::new(ext.b.x - right, ext.b.y - bottom),
610 )
611 }
612
613 // -- border (independent primitive) --------------------------------------
614
615 /// Show or hide the frame border, reflowing content to the new client area.
616 ///
617 /// Border visibility is an **independent** primitive (decoupled from
618 /// [`fullscreen`](Self::fullscreen) and maximize). Toggling it:
619 /// 1. flips the [`Frame`]'s `border_visible` (the inline downcast seam — the
620 /// only path that reaches the frame), and
621 /// 2. reflows content via `reflow_client`: the client
622 /// area grows/shrinks by the border thickness, so each content child reacts
623 /// through its existing `grow_mode` plus a `(∓1, ∓1)` origin shift, exactly
624 /// as on a normal resize. Owned scroll bars are re-derived from the
625 /// `client_rect` formula (they are chrome, not content).
626 ///
627 /// Idempotent if `bordered` is unchanged.
628 pub fn set_bordered(&mut self, bordered: bool, ctx: &mut Context) {
629 if self.bordered == bordered {
630 return;
631 }
632 let old_client = self.client_rect();
633 self.bordered = bordered;
634 if let Some(frame) = self.frame_mut() {
635 frame.set_border_visible(bordered);
636 }
637 let new_client = self.client_rect();
638 self.reflow_client(old_client, new_client, ctx);
639 }
640
641 /// Reflow the window's children to a changed client inset (the window size is
642 /// unchanged; only the frame inset moved). Frame child: skipped (it always
643 /// fills the extent). Owned scroll bars: re-derived from the
644 /// [`scroll_bar_rect`](Self::scroll_bar_rect) formula for the new `bordered`
645 /// state (they anchor to an edge, not the client origin). Every other child is
646 /// content: deliver the client **size** delta through the existing grow-mode
647 /// path ([`View::calc_bounds`]), then translate by the client **origin** delta
648 /// — a fixed-grow child simply shifts; an edge-tracking child also grows.
649 fn reflow_client(&mut self, old: Rect, new: Rect, ctx: &mut Context) {
650 let win_size = self.group.state().size;
651 let size_delta = (new.b - new.a) - (old.b - old.a);
652 let origin_delta = new.a - old.a;
653 let frame_id = self.frame_id;
654 // Snapshot the bar ids before the mutable loop (borrow-checker: we need
655 // them while `self.group.child_mut` holds a mutable borrow).
656 let vsb = self.vsb_id;
657 let hsb = self.hsb_id;
658 for id in self.group.child_ids_in_order() {
659 if id == frame_id {
660 continue;
661 }
662 if Some(id) == vsb || Some(id) == hsb {
663 // Chrome: re-derive the bar's rect for the new bordered state.
664 let vertical = Some(id) == vsb;
665 let r = self.scroll_bar_rect(vertical);
666 if let Some(v) = self.group.child_mut(id) {
667 v.change_bounds(r);
668 v.on_bounds_changed(ctx);
669 }
670 continue;
671 }
672 // Content: grow-mode reaction to the size delta, then the origin shift.
673 if let Some(v) = self.group.child_mut(id) {
674 let resized = v.calc_bounds(win_size, size_delta);
675 let shifted = Rect::from_points(resized.a + origin_delta, resized.b + origin_delta);
676 v.change_bounds(shifted);
677 v.on_bounds_changed(ctx);
678 }
679 }
680 }
681
682 // -- fullscreen (composes border + maximize) -----------------------------
683
684 /// Set the window's frameless-fullscreen [`mode`](Fullscreen) by composing the
685 /// independent primitives:
686 /// - **Off** → [`restore`](Self::restore) (un-maximize) + re-border.
687 /// - **Desktop / Screen** → [`maximize`](Self::maximize) + drop the border.
688 ///
689 /// The window-local work (maximize/restore + border + content reflow) is done
690 /// **inline** (the pump cannot downcast to `Window`); the emitted
691 /// [`Deferred::SetFullscreen`](crate::view::Deferred::SetFullscreen) tells the
692 /// pump to do the cross-tree work (menu bar / desktop) and to track the window
693 /// for resize re-fit and removal-restore.
694 ///
695 /// # Turbo Vision heritage
696 /// **tvision-rs extension** to `TWindow`.
697 pub fn set_fullscreen(&mut self, mode: Fullscreen, ctx: &mut Context) {
698 self.fullscreen = mode;
699 match mode {
700 Fullscreen::Off => {
701 self.restore(ctx);
702 self.set_bordered(true, ctx);
703 }
704 Fullscreen::Desktop | Fullscreen::Screen => {
705 self.maximize(ctx);
706 self.set_bordered(false, ctx);
707 }
708 }
709 if let Some(id) = self.group.state().id() {
710 ctx.set_fullscreen(id, mode);
711 }
712 }
713
714 /// Record whether a collapsed menu bar's kebab sits above this window's
715 /// top-right corner and, if that changed, re-derive the right-edge vertical
716 /// scroll bar so its top clears the kebab row (see
717 /// [`menu_chrome_above`](Self::menu_chrome_above)).
718 ///
719 /// Called by the pump's fullscreen layout engine — the only owner of the
720 /// cross-tree "is there a menu bar" fact — after it re-fits the window. Only
721 /// the vertical bar is touched (the kebab is on the top row; a horizontal bar
722 /// lives on the bottom). The change guard makes repeat calls (e.g. the
723 /// per-resize maintenance pass) cheap; the vertical bar's grow mode keeps its
724 /// top fixed across resizes, so a single inset survives the grow-mode cascade.
725 pub(crate) fn set_menu_chrome_above(&mut self, above: bool, ctx: &mut Context) {
726 if self.menu_chrome_above == above {
727 return;
728 }
729 self.menu_chrome_above = above;
730 if let Some(vsb) = self.vsb_id {
731 let r = self.scroll_bar_rect(true);
732 if let Some(v) = self.group.child_mut(vsb) {
733 v.change_bounds(r);
734 v.on_bounds_changed(ctx);
735 }
736 }
737 }
738
739 // -- standard scroll bar -------------------------------------------------
740
741 /// Insert a standard scroll bar on the right or bottom edge and return its
742 /// [`ViewId`].
743 ///
744 /// Pass [`ScrollBarOptions`] to choose vertical (right edge) or horizontal
745 /// (bottom edge) placement, and whether the bar handles keyboard arrow keys
746 /// when it is not the focused view (`handle_keyboard`).
747 ///
748 /// The bar is sized to fit exactly inside the frame without covering the
749 /// frame corners:
750 /// - **Vertical** (right edge): one cell wide, flush against the right frame
751 /// edge. Bordered: `(width−1, 1) .. (width, height−1)` (frame-corner inset).
752 /// Frameless: spans from the top screen edge to the bottom, stopping one row
753 /// above the horizontal bar's row when both bars are present.
754 /// - **Horizontal** (bottom edge): one cell tall. Bordered: `(2, height−1) ..
755 /// (width−2, height)` (frame-corner inset). Frameless: starts at the left
756 /// screen edge and runs to just before the vertical bar's column when both
757 /// bars are present (no left inset).
758 ///
759 /// Call this method after construction and before the window is shown. The
760 /// returned [`ViewId`] can be passed to a scroller or list viewer as its
761 /// linked scroll bar.
762 ///
763 /// For `handle_keyboard`, post-processing is enabled on the [`ScrollBar`]
764 /// **before** boxing + inserting (the `insert` call consumes the box, so
765 /// the flag must be set first).
766 pub fn standard_scroll_bar(&mut self, opts: ScrollBarOptions) -> ViewId {
767 let r = self.scroll_bar_rect(opts.vertical);
768 let sb = ScrollBar::new(r);
769 let sb = if opts.handle_keyboard {
770 sb.with_keyboard()
771 } else {
772 sb
773 };
774 let id = self.group.insert(Box::new(sb));
775 // Record the minted bar by orientation so a border toggle can re-derive
776 // (not content-shift) its rect, and so client_rect can exclude the lane.
777 if opts.vertical {
778 self.vsb_id = Some(id);
779 } else {
780 self.hsb_id = Some(id);
781 }
782 id
783 }
784
785 /// The edge-anchored rect for a standard scroll bar in the **current**
786 /// `bordered` state — the single formula shared by
787 /// [`standard_scroll_bar`](Self::standard_scroll_bar) (at insert time) and
788 /// [`reflow_client`](Self::reflow_client) (on a border toggle).
789 ///
790 /// Bordered: the bar is inset by the frame corners (identical to the
791 /// pre-existing behaviour). Frameless: the bar extends to the window edges,
792 /// stopping just short of the companion bar's lane (if both bars are present),
793 /// and — when a collapsed menu bar's kebab sits above the top-right corner
794 /// ([`menu_chrome_above`](Self::menu_chrome_above)) — insets its **top** one
795 /// row so the up-arrow is not occluded by (and does not steal clicks from) the
796 /// kebab.
797 fn scroll_bar_rect(&self, vertical: bool) -> Rect {
798 let ext = self.group.state().get_extent();
799 let fi = self.frame_interior();
800 if vertical {
801 // Right column. Bordered: clears the frame corners (unchanged).
802 // Frameless: full height, stopping one row above the h-bar; the top is
803 // nudged down one row when a menu kebab covers the top-right corner.
804 let (top, bottom) = if self.bordered {
805 (fi.a.y, fi.b.y)
806 } else {
807 (
808 ext.a.y + i32::from(self.menu_chrome_above),
809 ext.b.y - i32::from(self.hsb_id.is_some()),
810 )
811 };
812 Rect::from_points(Point::new(ext.b.x - 1, top), Point::new(ext.b.x, bottom))
813 } else {
814 // Bottom row. Bordered: inset to clear the resize-grip corners (unchanged).
815 // Frameless: from the left edge to just before the v-bar.
816 let (left, right) = if self.bordered {
817 (fi.a.x + 1, fi.b.x - 1)
818 } else {
819 (ext.a.x, ext.b.x - i32::from(self.vsb_id.is_some()))
820 };
821 Rect::from_points(Point::new(left, ext.b.y - 1), Point::new(right, ext.b.y))
822 }
823 }
824
825 // -- maximize / restore (the single restore slot) ------------------------
826
827 /// Grow the window to fill its owner, saving the pre-maximize bounds into the
828 /// single [`restore_rect`](Self::restore_rect) slot (if not already maximized).
829 ///
830 /// The maximum size (the owner's size) is reached via the owner-extent-down
831 /// channel ([`Context::owner_size`](crate::view::Context::owner_size)) instead
832 /// of an up-pointer. The window's own [`size_limits`](View::size_limits)
833 /// override (max = owner size, min = `min_size`, default 16×6) is used. Shared
834 /// by the `ZOOM` command and fullscreen-Desktop, so they cannot desync.
835 pub fn maximize(&mut self, ctx: &mut Context) {
836 if self.restore_rect.is_none() {
837 self.restore_rect = Some(self.group.state().get_bounds());
838 }
839 let owner_size = ctx.owner_size();
840 let (_min, max) = View::size_limits(self, owner_size);
841 self.locate(Rect::new(0, 0, max.x, max.y), owner_size);
842 View::on_bounds_changed(self, ctx);
843 self.push_zoomed(true);
844 }
845
846 /// Restore the window to its saved pre-maximize bounds (consuming the
847 /// [`restore_rect`](Self::restore_rect) slot). A no-op on the bounds if the
848 /// window was not maximized; always clears the frame's zoomed icon.
849 pub fn restore(&mut self, ctx: &mut Context) {
850 if let Some(r) = self.restore_rect.take() {
851 let owner_size = ctx.owner_size();
852 self.locate(r, owner_size);
853 View::on_bounds_changed(self, ctx);
854 }
855 self.push_zoomed(false);
856 }
857
858 /// Push the frame's `zoomed` flag through the downcast seam (the frame cannot
859 /// read the owner's size itself, so it picks the zoom vs unzoom icon from this
860 /// bool). [`locate`](Self::locate) re-pushes it on every bounds change too, so
861 /// it stays current.
862 fn push_zoomed(&mut self, zoomed: bool) {
863 if let Some(frame) = self.frame_mut() {
864 frame.set_zoomed(zoomed);
865 }
866 }
867
868 /// Clamp `bounds`'s size to [`size_limits`](View::size_limits) then
869 /// `change_bounds` iff it differs. `owner_size` feeds the (overridden)
870 /// `size_limits`. No shadow/under-rect repaint tail is needed — whole-tree
871 /// redraw + diff makes it redundant.
872 fn locate(&mut self, mut bounds: Rect, owner_size: Point) {
873 let (min, max) = View::size_limits(self, owner_size);
874 bounds.b.x = bounds.a.x + range(bounds.b.x - bounds.a.x, min.x, max.x);
875 bounds.b.y = bounds.a.y + range(bounds.b.y - bounds.a.y, min.y, max.y);
876 if bounds != self.group.state().get_bounds() {
877 // Resize children by the delta.
878 self.group.change_bounds(bounds);
879 // Re-push the zoomed flag so the frame's zoom icon reflects the new
880 // size (pushed through the downcast seam since the frame can't read the
881 // owner's size). Re-pushed here on every bounds change.
882 let zoomed = self.group.state().size == max;
883 if let Some(frame) = self
884 .group
885 .child_mut(self.frame_id)
886 .and_then(|v| v.as_any_mut())
887 .and_then(|a| a.downcast_mut::<Frame>())
888 {
889 frame.set_zoomed(zoomed);
890 }
891 }
892 }
893
894 // -- drag ----------------------------------------------------------------
895
896 /// Start a drag, reached from [`handle_event`](Self::handle_event) on a
897 /// surviving title-bar / corner / middle-button `MouseDown`.
898 ///
899 /// Sets the `Dragging` state flag **on** directly (it has `&mut self` + `ctx`,
900 /// so `Group::set_state` propagates `Dragging` to children incl. the frame,
901 /// flipping it to the single-line dragging border), then pushes a deferred
902 /// [`DragCapture`]. The capture is pushed deferred, so it sees the *next* event
903 /// (the first `MouseMove`), never this `MouseDown` (the `pending_captures`
904 /// contract).
905 ///
906 /// `mouse_local` is the `MouseDown` position in **window-local** coords; adding
907 /// the window's own `origin` gives the absolute mouse-down used to compute the
908 /// constant grab anchor (the coordinate-frame assumption on [`DragCapture`]).
909 /// The owner extent and size limits are read **here** (group-routed dispatch,
910 /// so `ctx.owner_size()` is valid), never at drag time.
911 fn start_drag(&mut self, id: ViewId, kind: DragKind, mouse_local: Point, ctx: &mut Context) {
912 // Set the Dragging flag directly (Group::set_state propagates it to
913 // children incl. the frame).
914 View::set_state(self, StateFlag::Dragging, true, ctx);
915
916 let origin = self.group.state().origin;
917 let size = self.group.state().size;
918 let mouse_abs = mouse_local + origin; // window-local -> absolute
919 // The owner extent and the window's size limits, via the owner-extent-down
920 // channel. owner_size is valid HERE (group-routed dispatch); the capture
921 // must NOT read it at drag time.
922 let owner_size = ctx.owner_size();
923 let limits = Rect::new(0, 0, owner_size.x, owner_size.y); // owner extent
924 let (min, max) = View::size_limits(self, owner_size);
925 // The window's drag mode carries only the limit bits that feed move_grow
926 // (the move/grow choice is already encoded in `kind`); the default limits
927 // the low-y edge.
928 let mode = self.group.state().drag_mode;
929 let anchor = match kind {
930 DragKind::Move => origin - mouse_abs,
931 DragKind::Grow => size - mouse_abs,
932 DragKind::GrowLeft => Point::new(origin.x, origin.y + size.y) - mouse_abs,
933 };
934 let init_bounds = self.group.state().get_bounds();
935 ctx.push_capture(Box::new(DragCapture {
936 window_id: id,
937 kind,
938 init_bounds,
939 anchor,
940 limits,
941 min,
942 max,
943 mode,
944 }));
945 }
946
947 /// Begin a resize session on the body splitter (if any) and return its
948 /// divider targets. The body is the first non-frame child that is a `Splitter`.
949 fn begin_body_splitter_session(&mut self) -> Vec<ResizeTarget> {
950 self.interior_splitter_mut()
951 .map(|sp| {
952 sp.begin_resize_session()
953 .into_iter()
954 .map(|(splitter, index, orientation)| ResizeTarget::Divider {
955 splitter,
956 index,
957 orientation,
958 })
959 .collect()
960 })
961 .unwrap_or_default()
962 }
963
964 /// True if the body splitter has ≥1 movable divider.
965 fn body_has_movable_divider(&mut self) -> bool {
966 self.interior_splitter_mut()
967 .map(|sp| sp.has_movable_divider())
968 .unwrap_or(false)
969 }
970}
971
972/// Clamp `val` into `[min, max]`, pinning `min` to `max` if inverted.
973/// Reimplemented locally (it is two lines) to keep the `locate` seam contained —
974/// the `view.rs` `range` is private there.
975fn range(val: i32, min: i32, max: i32) -> i32 {
976 let min = if min > max { max } else { min };
977 val.clamp(min, max)
978}
979
980/// Map a window number to the frame's `Option<u8>` contract: `0` (no number) →
981/// `None`; `0 < n` → `Some(value)`, pushed down to the frame, whose own `n < 10`
982/// draw guard then suppresses any digit `>= 10`. The `Option<u8>` carrier clamps
983/// `n > 255` to `255` via `unwrap_or(u8::MAX)`, but that branch is unreachable in
984/// practice (numbers are `1..=9`). Negative numbers are out of contract; they map
985/// to `None` (treated as "no number").
986fn number_to_option(number: i16) -> Option<u8> {
987 if number <= 0 {
988 None
989 } else {
990 Some(u8::try_from(number).unwrap_or(u8::MAX))
991 }
992}
993
994// ---------------------------------------------------------------------------
995// Drag — the capture handler that runs an interactive window drag
996// ---------------------------------------------------------------------------
997
998/// Which drag form is running (the mouse branch; the keyboard resize sub-mode
999/// runs through [`KeyboardResizeCapture`]). Selects how each `MouseMove` maps to
1000/// new bounds (see [`DragCapture::compute_bounds`]).
1001enum DragKind {
1002 /// Translate the whole window (title-bar / middle-button move).
1003 Move,
1004 /// Drag the bottom-right corner (origin fixed, size follows).
1005 Grow,
1006 /// Drag the bottom-left corner (top-right fixed).
1007 GrowLeft,
1008}
1009
1010/// The [`CaptureHandler`] that runs an interactive window drag. The *frame*
1011/// cannot start the drag (it has no pointer to the window it would move); the
1012/// [`Window`] starts it (it knows its own id and its owner's size) via
1013/// [`Window::start_drag`], which pushes this handler.
1014///
1015/// **Coordinate-frame assumption (mirrors [`ModalFrame`](crate::app::ModalFrame)).**
1016/// The capture runs at the capture-stack level, *before* any group routing, so it
1017/// sees mouse events in **absolute screen coordinates**. The root `Group` covers
1018/// the whole screen at `(0,0)` and the desktop is its child at `(0,0)`, so
1019/// **absolute == root-local == desktop-local**, and a window's `origin` (relative
1020/// to its owner) is in that same frame — the drag math assumes this.
1021struct DragCapture {
1022 window_id: ViewId,
1023 kind: DragKind,
1024 /// Window bounds at drag start (the fixed corner for Grow/GrowLeft).
1025 init_bounds: Rect,
1026 /// The constant grab offset (see [`compute_bounds`](Self::compute_bounds));
1027 /// per-kind meaning documented in [`Window::start_drag`].
1028 anchor: Point,
1029 /// The owner's extent, captured at push time from `ctx.owner_size()`.
1030 limits: Rect,
1031 /// Minimum window size, captured at push time.
1032 min: Point,
1033 /// Maximum window size, captured at push time.
1034 max: Point,
1035 /// The drag mode — only the limit bits matter to [`move_grow`] (the window's
1036 /// default limits the low-y edge).
1037 mode: DragMode,
1038}
1039
1040impl DragCapture {
1041 /// Map the current `MouseMove`'s absolute position to the window's new bounds,
1042 /// for each of the three drag forms. The anchor is the **constant** grab
1043 /// offset captured at push time (see [`Window::start_drag`]).
1044 fn compute_bounds(&self, mouse_abs: Point) -> Rect {
1045 match self.kind {
1046 // New origin = mouse + (initial origin - mouse-down).
1047 DragKind::Move => {
1048 let sz = self.init_bounds.b - self.init_bounds.a;
1049 let new_origin = mouse_abs + self.anchor;
1050 move_grow(new_origin, sz, self.limits, self.min, self.max, self.mode)
1051 }
1052 // New size = mouse + (initial size - mouse-down).
1053 DragKind::Grow => {
1054 let o = self.init_bounds.a;
1055 let new_size = mouse_abs + self.anchor;
1056 move_grow(o, new_size, self.limits, self.min, self.max, self.mode)
1057 }
1058 // Grow-left: bespoke pre-clamp of the moving bottom-left corner, then
1059 // move_grow. The top-right (`b`) is the fixed anchor.
1060 DragKind::GrowLeft => {
1061 let corner = mouse_abs + self.anchor; // = mouse + (botLeft - mouseDown)
1062 let b = self.init_bounds.b; // fixed top-right anchor
1063 let ax = corner.x.max(b.x - self.max.x).min(b.x - self.min.x);
1064 let a = Point::new(ax, self.init_bounds.a.y); // a.y stays initial
1065 let by = corner.y; // bottom edge follows mouse
1066 move_grow(
1067 a,
1068 Point::new(b.x - a.x, by - a.y),
1069 self.limits,
1070 self.min,
1071 self.max,
1072 self.mode,
1073 )
1074 }
1075 }
1076 }
1077}
1078
1079impl CaptureHandler for DragCapture {
1080 fn handle(&mut self, ev: &mut Event, ctx: &mut Context) -> CaptureFlow {
1081 match ev {
1082 Event::MouseMove(m) => {
1083 // `m.position` is ABSOLUTE here (capture runs before group routing).
1084 let r = self.compute_bounds(m.position);
1085 ctx.request_bounds(self.window_id, r);
1086 CaptureFlow::Consumed
1087 }
1088 Event::MouseUp(_) => {
1089 // The drag ends on mouse-up; clear the Dragging flag (via a
1090 // request, since a capture holds no &mut view) and pop ourselves.
1091 ctx.request_set_state(self.window_id, StateFlag::Dragging, false);
1092 CaptureFlow::ConsumedPop
1093 }
1094 // The drag is modal: swallow everything that is not a mouse-move/up
1095 // (auto-repeat, keys, commands, broadcasts) without moving the window.
1096 // Timer expiries never get here (the pump routes them around the
1097 // capture stack, as C++ `idle` delivers them inside the drag loop).
1098 _ => CaptureFlow::Consumed,
1099 }
1100 }
1101
1102 fn view(&self) -> Option<ViewId> {
1103 Some(self.window_id)
1104 }
1105}
1106
1107// ---------------------------------------------------------------------------
1108// KeyboardResizeCapture — runs an interactive keyboard move/resize
1109// ---------------------------------------------------------------------------
1110
1111/// The capture handler that runs an interactive keyboard move/resize, reached
1112/// from [`Window::handle_event`] on a resize command. Mirrors [`DragCapture`] for
1113/// the mouse side.
1114///
1115/// State captured at push time:
1116/// - `save_bounds` — bounds at entry, restored on Esc.
1117/// - `limits` — owner's extent at entry.
1118/// - `min`, `max` — the size limits at entry.
1119/// - `mode` — the drag mode (limit bits + the move/grow choice).
1120/// - `origin`, `size` — current position/size, updated by each arrow key.
1121///
1122/// Each arrow key produces a delta; if the mode allows moving, the delta shifts
1123/// the origin, and if it allows growing, the delta changes the size. Plain arrows
1124/// map to a 1-cell delta; Ctrl variants to `(±8, 0)` / `(0, ±4)`.
1125/// A keyboard-resize target: the window itself, or one divider of a splitter
1126/// in the window body. Dividers are addressed only by id (the capture never
1127/// touches the `Splitter` inline — it brokers via `DividerOp`).
1128enum ResizeTarget {
1129 Window,
1130 Divider {
1131 splitter: ViewId,
1132 index: usize,
1133 orientation: Orientation,
1134 },
1135}
1136
1137struct KeyboardResizeCapture {
1138 window_id: ViewId,
1139 /// Bounds at entry — restored by Esc.
1140 save_bounds: Rect,
1141 /// The owner's extent, captured at push time.
1142 limits: Rect,
1143 /// Minimum window size.
1144 min: Point,
1145 /// Maximum window size.
1146 max: Point,
1147 /// The drag mode — limit bits + the move/grow choice.
1148 mode: DragMode,
1149 /// Current window origin (top-left), updated by each arrow.
1150 origin: Point,
1151 /// Current window size, updated by each arrow.
1152 size: Point,
1153 /// Cycle targets: `targets[current]` is live. Tab/Shift+Tab move `current`.
1154 targets: Vec<ResizeTarget>,
1155 current: usize,
1156}
1157
1158impl KeyboardResizeCapture {
1159 /// Apply an arrow-key delta to the window target. Faithful to `TView::change`:
1160 /// plain arrows MOVE (when `drag_move`), Shift+arrows GROW (when `drag_grow`).
1161 /// `Ctrl` only scales the step (handled by the caller); it does not pick
1162 /// move-vs-grow.
1163 fn apply_delta(&mut self, delta: Point, shift: bool, ctx: &mut Context) {
1164 if self.mode.drag_move && !shift {
1165 self.origin += delta;
1166 } else if self.mode.drag_grow && shift {
1167 self.size += delta;
1168 }
1169 let r = move_grow(
1170 self.origin,
1171 self.size,
1172 self.limits,
1173 self.min,
1174 self.max,
1175 self.mode,
1176 );
1177 // Sync tracked origin/size to the clamped result so repeated presses stay
1178 // within limits.
1179 self.origin = r.a;
1180 self.size = r.b - r.a;
1181 ctx.request_bounds(self.window_id, r);
1182 }
1183
1184 fn current_is_window(&self) -> bool {
1185 matches!(self.targets.get(self.current), Some(ResizeTarget::Window))
1186 }
1187
1188 /// Turn the current target's highlight on/off.
1189 fn set_highlight(&self, on: bool, ctx: &mut Context) {
1190 match self.targets.get(self.current) {
1191 Some(ResizeTarget::Window) => {
1192 ctx.request_set_state(self.window_id, StateFlag::Dragging, on);
1193 }
1194 Some(ResizeTarget::Divider {
1195 splitter, index, ..
1196 }) => {
1197 ctx.splitter_divider(*splitter, DividerOp::SetActive(on.then_some(*index)));
1198 }
1199 None => {}
1200 }
1201 }
1202
1203 /// Tab/Shift+Tab: hand the highlight from the old target to the next.
1204 fn cycle(&mut self, forward: bool, ctx: &mut Context) {
1205 let n = self.targets.len();
1206 if n < 2 {
1207 return;
1208 }
1209 self.set_highlight(false, ctx);
1210 self.current = if forward {
1211 (self.current + 1) % n
1212 } else {
1213 (self.current + n - 1) % n
1214 };
1215 self.set_highlight(true, ctx);
1216 }
1217
1218 /// A ±1 arrow nudge for a DIVIDER target, along the divider's axis only.
1219 /// Cross-axis arrows are ignored. The window target is handled inline in
1220 /// `handle` (see the arrow-key arm there).
1221 fn arrow(&mut self, key: Key, ctx: &mut Context) {
1222 if let Some(ResizeTarget::Divider {
1223 splitter,
1224 index,
1225 orientation,
1226 }) = self.targets.get(self.current)
1227 {
1228 let delta = match (orientation, key) {
1229 (Orientation::Cols, Key::Left) => -1,
1230 (Orientation::Cols, Key::Right) => 1,
1231 (Orientation::Rows, Key::Up) => -1,
1232 (Orientation::Rows, Key::Down) => 1,
1233 _ => 0,
1234 };
1235 if delta != 0 {
1236 ctx.splitter_divider(
1237 *splitter,
1238 DividerOp::Nudge {
1239 index: *index,
1240 delta,
1241 },
1242 );
1243 }
1244 }
1245 }
1246
1247 /// Enter (commit) / Esc (cancel): clear every highlight and end every session.
1248 fn finish(&self, commit: bool, ctx: &mut Context) {
1249 let mut seen: Vec<ViewId> = Vec::new();
1250 let mut window_in_targets = false;
1251 for t in &self.targets {
1252 match t {
1253 ResizeTarget::Window => window_in_targets = true,
1254 ResizeTarget::Divider { splitter, .. } => {
1255 if !seen.contains(splitter) {
1256 seen.push(*splitter);
1257 ctx.splitter_divider(*splitter, DividerOp::EndSession { commit });
1258 }
1259 }
1260 }
1261 }
1262 if window_in_targets {
1263 if !commit {
1264 ctx.request_bounds(self.window_id, self.save_bounds);
1265 }
1266 ctx.request_set_state(self.window_id, StateFlag::Dragging, false);
1267 }
1268 }
1269}
1270
1271impl CaptureHandler for KeyboardResizeCapture {
1272 /// Each key adjusts origin/size by its delta then clamps via [`move_grow`];
1273 /// Enter accepts, Esc restores.
1274 fn handle(&mut self, ev: &mut Event, ctx: &mut Context) -> CaptureFlow {
1275 let Event::KeyDown(k) = ev else {
1276 // Swallow everything that is not a key (mouse events, commands,
1277 // broadcasts) while the keyboard resize is modal.
1278 return CaptureFlow::Consumed;
1279 };
1280 match k.key {
1281 Key::Tab => {
1282 // Tab cycles the resize target forward; Shift+Tab backward.
1283 self.cycle(!k.modifiers.shift, ctx);
1284 CaptureFlow::Consumed
1285 }
1286 Key::Left | Key::Right | Key::Up | Key::Down => {
1287 if self.current_is_window() {
1288 // Ctrl scales the step (±8 horiz / ±4 vert); Shift picks grow vs move.
1289 let (mh, mv) = if k.modifiers.ctrl { (8, 4) } else { (1, 1) };
1290 let d = match k.key {
1291 Key::Left => Point::new(-mh, 0),
1292 Key::Right => Point::new(mh, 0),
1293 Key::Up => Point::new(0, -mv),
1294 Key::Down => Point::new(0, mv),
1295 _ => Point::new(0, 0),
1296 };
1297 self.apply_delta(d, k.modifiers.shift, ctx);
1298 } else {
1299 // Divider target: ±1 nudge along the divider's axis (Shift/Ctrl ignored).
1300 self.arrow(k.key, ctx);
1301 }
1302 CaptureFlow::Consumed
1303 }
1304 Key::Home if self.current_is_window() => {
1305 // Home: snap the left edge to the owner's left.
1306 // p.x = limits.a.x
1307 self.origin.x = self.limits.a.x;
1308 let r = move_grow(
1309 self.origin,
1310 self.size,
1311 self.limits,
1312 self.min,
1313 self.max,
1314 self.mode,
1315 );
1316 self.origin = r.a;
1317 self.size = r.b - r.a;
1318 ctx.request_bounds(self.window_id, r);
1319 CaptureFlow::Consumed
1320 }
1321 Key::End if self.current_is_window() => {
1322 // End: snap the right edge to the owner's right.
1323 // p.x = limits.b.x - s.x
1324 self.origin.x = self.limits.b.x - self.size.x;
1325 let r = move_grow(
1326 self.origin,
1327 self.size,
1328 self.limits,
1329 self.min,
1330 self.max,
1331 self.mode,
1332 );
1333 self.origin = r.a;
1334 self.size = r.b - r.a;
1335 ctx.request_bounds(self.window_id, r);
1336 CaptureFlow::Consumed
1337 }
1338 Key::PageUp if self.current_is_window() => {
1339 // PageUp: snap the top edge to the owner's top.
1340 // p.y = limits.a.y
1341 self.origin.y = self.limits.a.y;
1342 let r = move_grow(
1343 self.origin,
1344 self.size,
1345 self.limits,
1346 self.min,
1347 self.max,
1348 self.mode,
1349 );
1350 self.origin = r.a;
1351 self.size = r.b - r.a;
1352 ctx.request_bounds(self.window_id, r);
1353 CaptureFlow::Consumed
1354 }
1355 Key::PageDown if self.current_is_window() => {
1356 // PageDown: snap the bottom edge to the owner's bottom.
1357 // p.y = limits.b.y - s.y
1358 self.origin.y = self.limits.b.y - self.size.y;
1359 let r = move_grow(
1360 self.origin,
1361 self.size,
1362 self.limits,
1363 self.min,
1364 self.max,
1365 self.mode,
1366 );
1367 self.origin = r.a;
1368 self.size = r.b - r.a;
1369 ctx.request_bounds(self.window_id, r);
1370 CaptureFlow::Consumed
1371 }
1372 Key::Enter => {
1373 // Accept — clear every highlight + end every session, then pop.
1374 self.finish(true, ctx);
1375 CaptureFlow::ConsumedPop
1376 }
1377 Key::Esc => {
1378 // Cancel — restore window bounds + divider weights, then pop.
1379 self.finish(false, ctx);
1380 CaptureFlow::ConsumedPop
1381 }
1382 _ => {
1383 // Any other key passes through (the resize does not break on
1384 // unknown keys).
1385 CaptureFlow::Pass
1386 }
1387 }
1388 }
1389
1390 fn view(&self) -> Option<ViewId> {
1391 Some(self.window_id)
1392 }
1393}
1394
1395/// Clamp size to `[min, max]` and origin to the limits, honoring the limit-edge
1396/// mode bits, and return the resulting bounds.
1397///
1398/// We return the rect instead of calling `locate` (the capture has no `&mut`
1399/// view; the caller applies it via `change_bounds` — equivalent, since
1400/// `move_grow` already clamps to the same size limits `locate` would).
1401///
1402/// This uses explicit `min(max(..))` **not** [`i32::clamp`]: when `lo > hi`
1403/// (window larger than the limit), `min(max(v, lo), hi)` yields `hi`, whereas
1404/// `clamp` PANICS on `lo > hi`. So we replicate min/max exactly.
1405fn move_grow(
1406 mut p: Point,
1407 mut s: Point,
1408 limits: Rect,
1409 min: Point,
1410 max: Point,
1411 mode: DragMode,
1412) -> Rect {
1413 s.x = s.x.max(min.x).min(max.x);
1414 s.y = s.y.max(min.y).min(max.y);
1415 p.x = p.x.max(limits.a.x - s.x + 1).min(limits.b.x - 1);
1416 p.y = p.y.max(limits.a.y - s.y + 1).min(limits.b.y - 1);
1417 if mode.limit_lo_x {
1418 p.x = p.x.max(limits.a.x);
1419 }
1420 if mode.limit_lo_y {
1421 p.y = p.y.max(limits.a.y);
1422 }
1423 if mode.limit_hi_x {
1424 p.x = p.x.min(limits.b.x - s.x);
1425 }
1426 if mode.limit_hi_y {
1427 p.y = p.y.min(limits.b.y - s.y);
1428 }
1429 Rect::from_points(p, p + s)
1430}
1431
1432#[crate::delegate(to = group, skip(
1433 apply_scroll_sync,
1434 as_any_mut,
1435 calc_bounds,
1436 grabs_focus_on_click,
1437 select_window_num,
1438 set_value,
1439 value,
1440))]
1441impl View for Window {
1442 /// Always delegates the draw to the group; first, if this window hosts a
1443 /// [`Splitter`](crate::widgets::Splitter) body, it reads that splitter's
1444 /// divider abutment marks (parent→child) and pushes them to the frame child
1445 /// (owner-data-down) so the frame composes connected tees. The marks are empty
1446 /// unless the splitter opted in via
1447 /// [`Splitter::joined`](crate::widgets::Splitter::joined), so a plain window —
1448 /// or one whose splitter is not joined — is byte-for-byte unchanged (an empty
1449 /// mark set reverts the frame to a plain border). Both child borrows are
1450 /// sequential (the marks `Vec` is owned between them, so only one `&mut` child
1451 /// is live at a time).
1452 fn draw(&mut self, ctx: &mut DrawCtx) {
1453 let fb = self.group.state().get_extent();
1454 let marks = self
1455 .interior_splitter_mut()
1456 .map(|s| s.frame_junction_marks(fb));
1457 if let Some(marks) = marks
1458 && let Some(frame) = self.frame_mut()
1459 {
1460 frame.set_junction_marks(marks);
1461 }
1462 self.group.draw(ctx);
1463 }
1464
1465 /// Delegate to the group first, then handle the window's own commands and the
1466 /// focus-cycling keys:
1467 ///
1468 /// * **zoom command** (if zoom is allowed) → [`maximize`](Self::maximize) /
1469 /// [`restore`](Self::restore) through the single restore slot + consume.
1470 /// No "is this the right window?" target guard is needed here: it is provably
1471 /// vacuous in this architecture. The frame emits the zoom/close commands only
1472 /// while it is active, so the target is always the *active* window; these are
1473 /// *focused* command events, which the desktop routes solely to its current
1474 /// child = the active window; and the internal queue drains fully before the
1475 /// next event poll, so the active window cannot change between emit and
1476 /// dispatch. A zoom/close therefore always reaches exactly the window it
1477 /// targets. **Trip-wire:** revisit only if a future emitter targets a
1478 /// *non-active* window via a command.
1479 /// * **close command** (if close is allowed) → `request_close` (the loop
1480 /// drains it into `remove_descendant`), or post a cancel command if modal.
1481 /// Same vacuous target-guard reasoning as zoom. The modal-cancel branch is
1482 /// wired here; the broader modal teardown lives in the dialog layer.
1483 /// * **Tab** → cycle focus forward + consume.
1484 /// * **Shift+Tab** → cycle focus backward + consume. Shift+Tab is `Key::Tab` +
1485 /// the `shift` modifier (there is no separate back-tab key).
1486 /// * A surviving title-bar / bottom-corner / middle-button `MouseDown` →
1487 /// `start_drag` (which pushes a `DragCapture`).
1488 /// * **resize command** → enable the `Dragging` flag and push a
1489 /// `KeyboardResizeCapture` that handles arrow keys until Enter (accept) or
1490 /// Esc (restore). The resize command is enabled in
1491 /// [`set_state`](Self::set_state) when the window is selected and move or grow
1492 /// is allowed.
1493 /// * **select-window-by-number** is **not** handled here. The window number is
1494 /// an *integer* argument, so the broadcast-source substrate does not serve
1495 /// it; instead `program_handle_event` asks the desktop
1496 /// ([`Desktop::select_window_num`](crate::desktop::Desktop)) to select the
1497 /// child whose [`number`](View::number) matches
1498 /// ([`Group::focus_by_number`](crate::view::Group)).
1499 fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
1500 self.group.handle_event(ev, ctx);
1501 // A consumed event is already `Nothing`, so each branch self-guards.
1502 if let Event::Command(c) = *ev
1503 && c == Command::ZOOM
1504 && self.flags.zoom
1505 {
1506 // Zoom routes through the single maximize/restore slot (shared with
1507 // fullscreen-Desktop, so they cannot desync). The border is an
1508 // independent primitive — zoom does not touch it.
1509 if self.is_maximized() {
1510 self.restore(ctx);
1511 } else {
1512 self.maximize(ctx);
1513 }
1514 ev.clear();
1515 }
1516 if let Event::Command(c) = *ev
1517 && c == Command::FULLSCREEN
1518 {
1519 self.set_fullscreen(self.fullscreen.next(), ctx);
1520 ev.clear();
1521 }
1522 // Close command. **No target guard** is needed: it is provably vacuous —
1523 // the frame emits close only while active, and focused command events are
1524 // routed to the desktop's current (= active) window, so a close always
1525 // reaches exactly its target (the same trip-wire the zoom branch documents
1526 // above; revisit only if a future emitter targets a non-active window via a
1527 // command). The modal-cancel branch is wired here; the dialog layer owns
1528 // the broader machinery.
1529 if let Event::Command(c) = *ev
1530 && c == Command::CLOSE
1531 && self.flags.close
1532 {
1533 ev.clear(); // consume the close first.
1534 if self.group.state().state.modal {
1535 // Modal: re-issue as a cancel (the dialog layer owns modal teardown).
1536 ctx.post(Command::CANCEL);
1537 } else if self.valid(Command::CLOSE, ctx) {
1538 // Closing is allowed: the loop drains the request and runs
1539 // `remove_descendant` (the close-removal channel).
1540 if let Some(id) = self.group.state().id() {
1541 ctx.request_close(id);
1542 }
1543 }
1544 }
1545 // Resize command: begin a session on the body splitter (if any) and push
1546 // a unified KeyboardResizeCapture whose Tab cycles the resize target
1547 // (window then each divider). Arrow keys move the active target; Enter
1548 // commits, Esc cancels. Runs whenever the window is movable/growable OR
1549 // the body splitter has a movable divider (a fixed window can still
1550 // resize its dividers).
1551 if let Event::Command(c) = *ev
1552 && c == Command::RESIZE
1553 && let Some(id) = self.group.state().id()
1554 {
1555 let can_window = self.flags.r#move || self.flags.grow;
1556 let div_targets = self.begin_body_splitter_session();
1557 if can_window || !div_targets.is_empty() {
1558 let mut targets = Vec::new();
1559 if can_window {
1560 targets.push(ResizeTarget::Window);
1561 }
1562 targets.extend(div_targets);
1563
1564 let owner_size = ctx.owner_size();
1565 let limits = Rect::new(0, 0, owner_size.x, owner_size.y);
1566 let (min, max) = View::size_limits(self, owner_size);
1567 let save_bounds = self.group.state().get_bounds();
1568 let origin = save_bounds.a;
1569 let size = save_bounds.b - save_bounds.a;
1570 // Build a DragMode that carries the window's limit bits AND the
1571 // move/grow bits from the decoration flags.
1572 let mut mode = self.group.state().drag_mode; // limit bits
1573 mode.drag_move = self.flags.r#move;
1574 mode.drag_grow = self.flags.grow;
1575
1576 // Initial highlight for targets[0].
1577 match targets.first() {
1578 Some(ResizeTarget::Window) => {
1579 View::set_state(self, StateFlag::Dragging, true, ctx);
1580 }
1581 Some(ResizeTarget::Divider {
1582 splitter, index, ..
1583 }) => {
1584 ctx.splitter_divider(*splitter, DividerOp::SetActive(Some(*index)));
1585 }
1586 None => {}
1587 }
1588
1589 ctx.push_capture(Box::new(KeyboardResizeCapture {
1590 window_id: id,
1591 save_bounds,
1592 limits,
1593 min,
1594 max,
1595 mode,
1596 origin,
1597 size,
1598 targets,
1599 current: 0,
1600 }));
1601 ev.clear();
1602 }
1603 }
1604 if let Event::KeyDown(k) = *ev
1605 && k.key == Key::Tab
1606 {
1607 // The group's hierarchical Tab pass (in `Group::handle_event`, run via
1608 // the delegation above) already advanced focus within the focused
1609 // subtree, descending into nested groups/splitters. A live Tab here
1610 // means the whole window tree was exhausted — wrap to the first (Tab)
1611 // or last (Shift+Tab) focusable leaf.
1612 self.group.focus_to_edge(k.modifiers.shift, ctx);
1613 ev.clear();
1614 }
1615 // Drag detection. Runs AFTER group delegation: the desktop delivered this
1616 // `MouseDown` to the window in window-local coords; the group routed it
1617 // positionally to the frame, which leaves a title-bar / bottom-corner click
1618 // UNCONSUMED (a close/zoom-icon click → Nothing, an interior-child click
1619 // consumed there). So a still-live `MouseDown` here is a drag spot, its
1620 // position window-local. An inactive window never reaches here on its first
1621 // click (the desktop's positional auto-select consumes the selecting
1622 // click), so the drag only ever starts on the active window — no active
1623 // re-check needed.
1624 // A borderless window has no title bar or grow corners to drag; skip
1625 // entirely (border is the independent primitive that owns the chrome).
1626 if let Event::MouseDown(m) = *ev
1627 && self.bordered
1628 {
1629 let w = self.group.state().size.x;
1630 let h = self.group.state().size.y;
1631 let pos = m.position;
1632 let kind = if m.buttons.middle
1633 && self.flags.r#move
1634 && pos.x > 0
1635 && pos.x < w - 1
1636 && pos.y > 0
1637 && pos.y < h - 1
1638 {
1639 // Middle-button interior move (mutually exclusive by geometry with
1640 // the title/corner cases; the branches do not overlap, so order is
1641 // irrelevant).
1642 Some(DragKind::Move)
1643 } else if pos.y == 0 && self.flags.r#move {
1644 Some(DragKind::Move) // title-bar move
1645 } else if pos.y >= h - 1 && self.flags.grow && pos.x >= w - 2 {
1646 Some(DragKind::Grow) // bottom-right grow
1647 } else if pos.y >= h - 1 && self.flags.grow && pos.x <= 1 {
1648 Some(DragKind::GrowLeft) // bottom-left grow
1649 } else {
1650 None
1651 };
1652 if let Some(kind) = kind
1653 && let Some(id) = self.group.state().id()
1654 {
1655 self.start_drag(id, kind, m.position, ctx);
1656 ev.clear();
1657 }
1658 }
1659 }
1660
1661 /// The **activation** half of state changes.
1662 ///
1663 /// Delegate to `Group::set_state` (flips the flag + propagates to children),
1664 /// then — iff the `Selected` flag is being set — also set the `Active` flag on
1665 /// the group. That `Active` propagation flips **every** child (incl. the frame)
1666 /// active / passive, so the frame does not need to be pushed manually.
1667 ///
1668 /// On selection, the window-command set is enabled (and disabled on
1669 /// deselection):
1670 /// - next/prev window: unconditional (handled by the desktop).
1671 /// - zoom: if zoom is allowed (handled in
1672 /// [`handle_event`](Self::handle_event)).
1673 /// - close: if close is allowed (handled in `handle_event`).
1674 /// - resize: if move or grow is allowed (handled in `handle_event` →
1675 /// `KeyboardResizeCapture`).
1676 fn set_state(&mut self, flag: StateFlag, enable: bool, ctx: &mut Context) {
1677 // Compute BEFORE the closure borrows `ctx` (and `self` immutably).
1678 let has_div = flag == StateFlag::Selected && self.body_has_movable_divider();
1679 self.group.set_state(flag, enable, ctx);
1680 if flag == StateFlag::Selected {
1681 self.group.set_state(StateFlag::Active, enable, ctx);
1682 // Window commands enabled/disabled together while selected.
1683 //
1684 // next/prev are UNCONDITIONAL — they have no flag guard (every
1685 // selectable window can be cycled), so they do NOT go through the
1686 // flag-gated `toggle` closure. Their handler is the desktop.
1687 if enable {
1688 ctx.enable_command(Command::NEXT);
1689 ctx.enable_command(Command::PREV);
1690 } else {
1691 ctx.disable_command(Command::NEXT);
1692 ctx.disable_command(Command::PREV);
1693 }
1694 // The flag-gated subset: close (if close allowed), zoom (if zoom
1695 // allowed), resize (if move or grow allowed) — all handled in
1696 // handle_event.
1697 let mut toggle = |cmd: Command, cond: bool| {
1698 if cond {
1699 if enable {
1700 ctx.enable_command(cmd);
1701 } else {
1702 ctx.disable_command(cmd);
1703 }
1704 }
1705 };
1706 toggle(Command::CLOSE, self.flags.close);
1707 toggle(Command::ZOOM, self.flags.zoom);
1708 toggle(
1709 Command::RESIZE,
1710 self.flags.r#move || self.flags.grow || has_div,
1711 );
1712 }
1713 }
1714
1715 /// The window's size limits: the owner-derived maximum with the minimum forced
1716 /// to [`min_size`](Self::set_min_size) (defaults to [`Self::MIN_WIN_SIZE`],
1717 /// 16×6) — the smallest a window can be while still showing its frame icons
1718 /// legibly.
1719 ///
1720 /// This `size_limits` override is intentionally *not* in the `#[delegate]`
1721 /// skip list, while `calc_bounds` *is* skipped: `calc_bounds` therefore routes
1722 /// through the *trait default*, which calls **this** `size_limits` override
1723 /// (giving the `min_size` floor, default 16×6). If `calc_bounds` were delegated to the inner `Group`, it would
1724 /// use the group's own `size_limits` (min 0×0) and silently bypass the window
1725 /// minimum on owner-driven resizes.
1726 fn size_limits(&self, owner_size: Point) -> (Point, Point) {
1727 let (_min, max) = self.group.size_limits(owner_size);
1728 (self.min_size, max)
1729 }
1730
1731 // NOTE: `calc_bounds` is in the skip list above — NOT forwarded to the group.
1732 // The trait default routes through `Window::size_limits` (this override's
1733 // `min_size` floor, default 16×6) and mutates the group's `ViewState` via `state_mut()`.
1734 // Forwarding to `self.group.calc_bounds` would use the group's `size_limits`
1735 // (min 0×0) and silently bypass the window's minimum on an owner-driven
1736 // resize.
1737
1738 /// The window number (1–9), or `None` for an unnumbered window.
1739 ///
1740 /// A positive number makes the window reachable by Alt+*N* (where *N* is the
1741 /// digit). The program's event handler broadcasts `cmSelectWindowNum` and the
1742 /// desktop walks its children calling `View::number()` on each; the first
1743 /// window whose number matches `N` is focused
1744 /// ([`Group::focus_by_number`](crate::view::Group)). A window constructed with
1745 /// `number == 0` (or any non-positive value) returns `None` and is never a
1746 /// select-by-number target.
1747 fn number(&self) -> Option<i16> {
1748 if self.number > 0 {
1749 Some(self.number)
1750 } else {
1751 None
1752 }
1753 }
1754
1755 /// Concrete-reach hook so the pump's fullscreen layout engine can push the
1756 /// kebab-reservation flag (via the crate-internal `set_menu_chrome_above`).
1757 /// Mirrors the menu-bar collapse downcast; without it the engine cannot reach
1758 /// a `Window` behind `&mut dyn View`.
1759 fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
1760 Some(self)
1761 }
1762}
1763
1764// ---------------------------------------------------------------------------
1765// Tests
1766// ---------------------------------------------------------------------------
1767
1768#[cfg(test)]
1769mod tests {
1770 use super::*;
1771 use crate::backend::{HeadlessBackend, Renderer};
1772 use crate::event::{KeyEvent, KeyModifiers};
1773 use crate::screen::Buffer;
1774 use crate::theme::{Role, Theme};
1775 use crate::timer::TimerQueue;
1776 use crate::view::{DrawCtx, ViewState};
1777 use std::collections::VecDeque;
1778
1779 // -- test harness --------------------------------------------------------
1780
1781 fn with_ctx<R>(
1782 out: &mut VecDeque<Event>,
1783 timers: &mut TimerQueue,
1784 f: impl FnOnce(&mut Context) -> R,
1785 ) -> R {
1786 let mut deferred: Vec<crate::view::Deferred> = Vec::new();
1787 let mut ctx = Context::new(out, timers, 0, &mut deferred);
1788 f(&mut ctx)
1789 }
1790
1791 fn tab_event(shift: bool) -> Event {
1792 Event::KeyDown(KeyEvent::new(
1793 Key::Tab,
1794 KeyModifiers {
1795 shift,
1796 ..Default::default()
1797 },
1798 ))
1799 }
1800
1801 /// A minimal selectable probe view (the frame is not selectable, so Tab
1802 /// cycling needs real selectable children to move between).
1803 struct Probe {
1804 st: ViewState,
1805 }
1806 impl Probe {
1807 fn boxed(bounds: Rect) -> Box<dyn View> {
1808 let mut st = ViewState::new(bounds);
1809 st.options.selectable = true;
1810 Box::new(Probe { st })
1811 }
1812 }
1813 impl View for Probe {
1814 fn state(&self) -> &ViewState {
1815 &self.st
1816 }
1817 fn state_mut(&mut self) -> &mut ViewState {
1818 &mut self.st
1819 }
1820 fn draw(&mut self, _ctx: &mut DrawCtx) {}
1821 }
1822
1823 fn window_with_frame() -> Window {
1824 Window::new(Rect::new(0, 0, 40, 15), Some("Edit".into()), 3)
1825 }
1826
1827 // -- 1. ctor -------------------------------------------------------------
1828
1829 #[test]
1830 fn new_ports_ctor_defaults() {
1831 let w = window_with_frame();
1832 // flags all-true.
1833 assert_eq!(
1834 w.flags(),
1835 WindowFlags {
1836 r#move: true,
1837 grow: true,
1838 close: true,
1839 zoom: true,
1840 }
1841 );
1842 // Not maximized (no restore rect) and bordered by default.
1843 assert_eq!(w.restore_rect(), None);
1844 assert!(!w.is_maximized());
1845 assert!(w.bordered());
1846 // palette == Blue.
1847 assert_eq!(w.palette(), WindowPalette::Blue);
1848 // number stored (now via the View::number() trait override).
1849 assert_eq!(View::number(&w), Some(3));
1850 // group state: shadow, selectable, top_select.
1851 let st = w.state();
1852 assert!(st.state.shadow, "sfShadow set");
1853 assert!(st.options.selectable, "ofSelectable set");
1854 assert!(st.options.top_select, "ofTopSelect set");
1855 // growMode = gfGrowAll | gfGrowRel.
1856 let gm = st.grow_mode;
1857 assert!(gm.lo_x && gm.lo_y && gm.hi_x && gm.hi_y, "gfGrowAll");
1858 assert!(gm.rel, "gfGrowRel");
1859 assert!(!gm.fixed);
1860 // the frame was inserted and its id resolves.
1861 assert!(
1862 w.group.index_of_pub(w.frame_id()).is_some(),
1863 "frame child id resolves"
1864 );
1865 }
1866
1867 /// The frame received the pushed-down title / flags / number at construction.
1868 #[test]
1869 fn new_pushes_frame_data_down() {
1870 let mut w = window_with_frame();
1871 let idx = w.group.index_of_pub(w.frame_id()).unwrap();
1872 // Render the (active) frame and read its title back off the top row.
1873 w.group.child_state_mut(idx).state.active = true;
1874 let theme = Theme::classic_blue();
1875 let mut buf = Buffer::new(40, 15);
1876 {
1877 let bounds = w.state().get_bounds();
1878 let mut dc = DrawCtx::new(&mut buf, &theme, bounds, bounds.a);
1879 w.draw(&mut dc);
1880 }
1881 // Title "Edit" (4 cols): lw = min(4, w-10=30) = 4; i = (40-4)>>1 = 18.
1882 let title: String = (18..22)
1883 .map(|x| buf.get(x, 0).symbol().to_string())
1884 .collect();
1885 assert_eq!(title, "Edit", "pushed-down title renders");
1886 // Number 3 drawn (flags.zoom true → at w-7 = 33).
1887 assert_eq!(buf.get(33, 0).symbol(), "3", "pushed-down number renders");
1888 }
1889
1890 // -- 2. title / size_limits ----------------------------------------------
1891
1892 #[test]
1893 fn title_and_size_limits() {
1894 let w = window_with_frame();
1895 assert_eq!(w.title(), Some("Edit"));
1896 // min defaults to `MIN_WIN_SIZE` {16, 6}; max is the owner size.
1897 let (min, max) = w.size_limits(Point::new(80, 25));
1898 assert_eq!(min, Point::new(16, 6), "window minimum");
1899 assert_eq!(max, Point::new(80, 25), "max is the owner size");
1900 }
1901
1902 /// An owner-driven resize must honour the window's 16×6 floor (because
1903 /// `calc_bounds` routes through the *window's*
1904 /// `size_limits`, NOT the group's 0×0). Shrink the window's right/bottom
1905 /// edges below the floor via `calc_bounds` and assert it clamps to ≥ 16×6.
1906 #[test]
1907 fn calc_bounds_honours_min_win_size() {
1908 let mut w = window_with_frame(); // bounds 0,0,40,15
1909 w.state_mut().grow_mode = GrowMode {
1910 hi_x: true,
1911 hi_y: true,
1912 ..Default::default()
1913 };
1914 // Owner shrank to (10, 4): far below 16×6. delta = new(10,4) - old(40,15).
1915 let owner = Point::new(10, 4);
1916 let delta = Point::new(10 - 40, 4 - 15);
1917 let b = View::calc_bounds(&mut w, owner, delta);
1918 let size = b.b - b.a;
1919 assert!(
1920 size.x >= 16 && size.y >= 6,
1921 "window must not shrink below minWinSize {{16,6}}, got {size:?}"
1922 );
1923 }
1924
1925 /// `set_min_size` raises the interactive-resize floor; `size_limits`
1926 /// reports it (and every clamp path reads through `size_limits`).
1927 #[test]
1928 fn set_min_size_raises_floor() {
1929 let mut w = window_with_frame();
1930 w.set_min_size(Point::new(60, 20));
1931 let (min, max) = w.size_limits(Point::new(100, 40));
1932 assert_eq!(min, Point::new(60, 20), "raised floor");
1933 assert_eq!(max, Point::new(100, 40), "max is still the owner size");
1934 }
1935
1936 /// The floor can only be raised: arguments below `MIN_WIN_SIZE` clamp up
1937 /// per axis (title/icons must stay legible).
1938 #[test]
1939 fn set_min_size_clamps_to_win_min() {
1940 let mut w = window_with_frame();
1941 w.set_min_size(Point::new(4, 2));
1942 let (min, _) = w.size_limits(Point::new(80, 25));
1943 assert_eq!(
1944 min,
1945 Window::MIN_WIN_SIZE,
1946 "cannot go below the 16×6 chrome floor"
1947 );
1948 // Mixed: x above the floor, y below — per-axis clamp.
1949 w.set_min_size(Point::new(60, 2));
1950 let (min, _) = w.size_limits(Point::new(80, 25));
1951 assert_eq!(min, Point::new(60, 6), "per-axis clamp");
1952 }
1953
1954 /// An owner-driven resize (`calc_bounds` trait default) honours a raised
1955 /// floor, same as `calc_bounds_honours_min_win_size` does for 16×6.
1956 #[test]
1957 fn calc_bounds_honours_raised_min() {
1958 let mut w = window_with_frame(); // bounds 0,0,40,15
1959 w.set_min_size(Point::new(60, 20));
1960 w.state_mut().grow_mode = GrowMode {
1961 hi_x: true,
1962 hi_y: true,
1963 ..Default::default()
1964 };
1965 // Owner shrinks by (5,5): raw new size (35,10) — below the raised floor.
1966 let b = View::calc_bounds(&mut w, Point::new(100, 40), Point::new(-5, -5));
1967 let size = b.b - b.a;
1968 assert_eq!(size, Point::new(60, 20), "clamped up to the raised floor");
1969 }
1970
1971 // -- 3. set_state activation flips the frame active ----------------------
1972
1973 #[test]
1974 fn select_activates_window_and_frame() {
1975 let mut w = window_with_frame();
1976 let frame_idx = w.group.index_of_pub(w.frame_id()).unwrap();
1977 assert!(
1978 !w.group.child_state_mut(frame_idx).state.active,
1979 "frame starts passive"
1980 );
1981
1982 let mut out = VecDeque::new();
1983 let mut timers = TimerQueue::new();
1984 with_ctx(&mut out, &mut timers, |ctx| {
1985 View::set_state(&mut w, StateFlag::Selected, true, ctx)
1986 });
1987
1988 // The window (group) is active...
1989 assert!(w.state().state.active, "window active after select");
1990 // ...and the Active propagation flipped the frame child active (no manual push).
1991 let frame_idx = w.group.index_of_pub(w.frame_id()).unwrap();
1992 assert!(
1993 w.group.child_state_mut(frame_idx).state.active,
1994 "frame went active via Group::set_state(Active) propagation"
1995 );
1996
1997 // Deselecting reverses it.
1998 with_ctx(&mut out, &mut timers, |ctx| {
1999 View::set_state(&mut w, StateFlag::Selected, false, ctx)
2000 });
2001 let frame_idx = w.group.index_of_pub(w.frame_id()).unwrap();
2002 assert!(!w.state().state.active, "window passive after deselect");
2003 assert!(
2004 !w.group.child_state_mut(frame_idx).state.active,
2005 "frame went passive again"
2006 );
2007 }
2008
2009 // -- 4. standard_scroll_bar ----------------------------------------------
2010
2011 #[test]
2012 fn standard_scroll_bar_vertical_rect_and_keyboard() {
2013 let mut w = window_with_frame(); // extent 0,0,40,15 -> w=40, h=15
2014 let id = w.standard_scroll_bar(ScrollBarOptions {
2015 vertical: true,
2016 handle_keyboard: true,
2017 });
2018 let idx = w.group.index_of_pub(id).unwrap();
2019 // vertical: (w-1, 1, w, h-1) = (39, 1, 40, 14).
2020 assert_eq!(
2021 w.group.child_state_mut(idx).get_bounds(),
2022 Rect::new(39, 1, 40, 14),
2023 "vertical bar at the right edge"
2024 );
2025 assert!(
2026 w.group.child_state_mut(idx).options.post_process,
2027 "sbHandleKeyboard → ofPostProcess"
2028 );
2029 }
2030
2031 #[test]
2032 fn standard_scroll_bar_horizontal_rect_no_keyboard() {
2033 let mut w = window_with_frame(); // w=40, h=15
2034 let id = w.standard_scroll_bar(ScrollBarOptions::default());
2035 let idx = w.group.index_of_pub(id).unwrap();
2036 // horizontal: (2, h-1, w-2, h) = (2, 14, 38, 15).
2037 assert_eq!(
2038 w.group.child_state_mut(idx).get_bounds(),
2039 Rect::new(2, 14, 38, 15),
2040 "horizontal bar at the bottom edge"
2041 );
2042 assert!(
2043 !w.group.child_state_mut(idx).options.post_process,
2044 "no sbHandleKeyboard → no ofPostProcess"
2045 );
2046 }
2047
2048 // -- 5. Tab focus cycling ------------------------------------------------
2049
2050 #[test]
2051 fn kb_tab_cycles_focus_and_consumes() {
2052 let mut w = window_with_frame();
2053 let mut out = VecDeque::new();
2054 let mut timers = TimerQueue::new();
2055 // Two selectable probe children + a vertical scrollbar (also selectable).
2056 let id_a = w.group.insert(Probe::boxed(Rect::new(1, 1, 10, 5)));
2057 let id_b = w.group.insert(Probe::boxed(Rect::new(1, 6, 10, 10)));
2058 // Establish a current (focus_next/find_next return None if current is None).
2059 with_ctx(&mut out, &mut timers, |ctx| {
2060 w.group
2061 .set_current(Some(id_b), crate::view::SelectMode::Normal, ctx)
2062 });
2063 assert_eq!(w.group.current(), Some(id_b));
2064
2065 // Tab (forwards) moves current to the next selectable child + consumes.
2066 // Children in insert order: [frame, id_a, id_b]; current == id_b. Forward
2067 // tab order is decreasing Vec index with wrap (see `Group::find_next`), so
2068 // from id_b (idx 2) the next eligible child is id_a (idx 1) — the frame
2069 // (idx 0) is not selectable. Focus lands deterministically on id_a.
2070 let mut ev = tab_event(false);
2071 with_ctx(&mut out, &mut timers, |ctx| w.handle_event(&mut ev, ctx));
2072 assert!(ev.is_nothing(), "Tab consumed");
2073 assert_eq!(
2074 w.group.current(),
2075 Some(id_a),
2076 "forward tab moves focus from id_b to id_a"
2077 );
2078
2079 // Shift+Tab (backwards) also consumes.
2080 let mut ev2 = tab_event(true);
2081 with_ctx(&mut out, &mut timers, |ctx| w.handle_event(&mut ev2, ctx));
2082 assert!(ev2.is_nothing(), "Shift+Tab consumed");
2083 }
2084
2085 // -- 6. WindowFlags relocation (compiles + frame tests still pass) --------
2086
2087 /// `WindowFlags` now lives here; the crate-root re-export resolves through
2088 /// this module. `frame.rs` imports it from here (its own tests cover the
2089 /// frame side). This test just exercises the relocated type.
2090 #[test]
2091 fn window_flags_relocated_here() {
2092 let f = WindowFlags {
2093 close: true,
2094 ..Default::default()
2095 };
2096 assert!(f.close && !f.zoom);
2097 // The frame's pushed-down flags use the same (relocated) type.
2098 let mut frame = Frame::new(Rect::new(0, 0, 10, 5));
2099 frame.set_flags(f);
2100 assert!(frame.flags().close);
2101 }
2102
2103 // -- 7. mandatory snapshot -----------------------------------------------
2104
2105 /// End-to-end: a selected (active) `Window` with a title + a vertical
2106 /// scrollbar, drawn through `&mut dyn View` on a `HeadlessBackend`. Shows
2107 /// the double-line active border, centered title, icons, and the scrollbar.
2108 #[test]
2109 fn selected_window_with_scrollbar_snapshot() {
2110 let theme = Theme::classic_blue();
2111 let mut out = VecDeque::new();
2112 let mut timers = TimerQueue::new();
2113 let mut w = Window::new(Rect::new(0, 0, 24, 8), Some("Edit".into()), 1);
2114 w.standard_scroll_bar(ScrollBarOptions {
2115 vertical: true,
2116 handle_keyboard: true,
2117 });
2118 // Select → active frame (double-line border + icons).
2119 with_ctx(&mut out, &mut timers, |ctx| {
2120 View::set_state(&mut w, StateFlag::Selected, true, ctx)
2121 });
2122
2123 let mut view: Box<dyn View> = Box::new(w);
2124 let (backend, screen) = HeadlessBackend::new(24, 8);
2125 let mut r = Renderer::new(Box::new(backend));
2126 r.render(|buf: &mut Buffer| {
2127 let bounds = view.state().get_bounds();
2128 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
2129 view.draw(&mut dc);
2130 });
2131 insta::assert_snapshot!(screen.snapshot());
2132 }
2133
2134 // -- 8. set_state enables/disables the zoom + close commands --------------
2135
2136 /// Selecting a zoom/close-enabled window queues `(Command::ZOOM, true)` and
2137 /// `(Command::CLOSE, true)` on the command-change channel; deselecting queues
2138 /// the matching `false` pairs.
2139 #[test]
2140 fn set_state_select_enables_and_disables_cm_zoom_and_close() {
2141 let mut w = window_with_frame(); // flags.zoom = true, flags.close = true
2142 let mut out = VecDeque::new();
2143 let mut timers = TimerQueue::new();
2144 let mut deferred: Vec<crate::view::Deferred> = Vec::new();
2145
2146 {
2147 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
2148 View::set_state(&mut w, StateFlag::Selected, true, &mut ctx);
2149 }
2150 use crate::view::Deferred;
2151 assert!(
2152 deferred
2153 .iter()
2154 .any(|d| matches!(d, Deferred::EnableCommand(Command::ZOOM))),
2155 "select enables cmZoom"
2156 );
2157 assert!(
2158 deferred
2159 .iter()
2160 .any(|d| matches!(d, Deferred::EnableCommand(Command::CLOSE))),
2161 "select enables cmClose"
2162 );
2163
2164 deferred.clear();
2165 {
2166 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
2167 View::set_state(&mut w, StateFlag::Selected, false, &mut ctx);
2168 }
2169 assert!(
2170 deferred
2171 .iter()
2172 .any(|d| matches!(d, Deferred::DisableCommand(Command::ZOOM))),
2173 "deselect disables cmZoom"
2174 );
2175 assert!(
2176 deferred
2177 .iter()
2178 .any(|d| matches!(d, Deferred::DisableCommand(Command::CLOSE))),
2179 "deselect disables cmClose"
2180 );
2181 }
2182
2183 // -- 9. zoom() toggles bounds + pushes the frame zoomed bool --------------
2184
2185 /// Read the frame child's pushed `zoomed` flag through the downcast seam.
2186 fn frame_zoomed(w: &mut Window) -> bool {
2187 w.group
2188 .child_mut(w.frame_id())
2189 .and_then(|v| v.as_any_mut())
2190 .and_then(|a| a.downcast_mut::<Frame>())
2191 .expect("frame child resolves through child_mut + as_any_mut")
2192 .zoomed()
2193 }
2194
2195 #[test]
2196 fn zoom_toggles_bounds_and_pushes_frame_zoomed() {
2197 // Window smaller than its owner desktop.
2198 let mut w = Window::new(Rect::new(2, 1, 22, 9), Some("Edit".into()), 1); // 20x8
2199 let original = w.state().get_bounds();
2200 let desktop_size = Point::new(80, 25);
2201
2202 let mut out = VecDeque::new();
2203 let mut timers = TimerQueue::new();
2204 let mut deferred: Vec<crate::view::Deferred> = Vec::new();
2205
2206 // Select the window (realism: the desktop would have it selected) and feed
2207 // a zoom command directly. owner_size is set on the ctx (the desktop's
2208 // job): the group.handle_event inside Window restores owner_size to this
2209 // value, so by the time the zoom arm runs zoom(), owner_size ==
2210 // desktop_size.
2211 {
2212 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
2213 View::set_state(&mut w, StateFlag::Selected, true, &mut ctx);
2214 }
2215
2216 // First zoom: fill the owner.
2217 {
2218 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
2219 ctx.set_owner_size(desktop_size);
2220 let mut ev = Event::Command(Command::ZOOM);
2221 w.handle_event(&mut ev, &mut ctx);
2222 assert!(ev.is_nothing(), "cmZoom consumed");
2223 }
2224 assert_eq!(
2225 w.state().get_bounds(),
2226 Rect::new(0, 0, desktop_size.x, desktop_size.y),
2227 "first zoom fills the owner"
2228 );
2229 assert_eq!(
2230 w.restore_rect(),
2231 Some(original),
2232 "restore_rect saved the original bounds"
2233 );
2234 assert!(w.is_maximized(), "window is maximized after the first zoom");
2235 assert!(frame_zoomed(&mut w), "frame pushed zoomed = true");
2236
2237 // Second zoom (toggle): restore.
2238 {
2239 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
2240 ctx.set_owner_size(desktop_size);
2241 let mut ev = Event::Command(Command::ZOOM);
2242 w.handle_event(&mut ev, &mut ctx);
2243 assert!(ev.is_nothing(), "cmZoom consumed");
2244 }
2245 assert_eq!(
2246 w.state().get_bounds(),
2247 original,
2248 "second zoom restores the original bounds"
2249 );
2250 assert_eq!(w.restore_rect(), None, "restore slot consumed on un-zoom");
2251 assert!(!w.is_maximized(), "window no longer maximized");
2252 assert!(!frame_zoomed(&mut w), "frame pushed zoomed = false");
2253 }
2254
2255 // -- 10. mandatory snapshot: restored vs zoomed --------------------------
2256
2257 fn render_window(view: &mut dyn View, theme: &Theme, w: u16, h: u16) -> String {
2258 let (backend, screen) = HeadlessBackend::new(w, h);
2259 let mut r = Renderer::new(Box::new(backend));
2260 r.render(|buf: &mut Buffer| {
2261 let bounds = view.state().get_bounds();
2262 let mut dc = DrawCtx::new(buf, theme, bounds, bounds.a);
2263 view.draw(&mut dc);
2264 });
2265 screen.snapshot()
2266 }
2267
2268 #[test]
2269 fn zoom_restored_vs_filled_snapshot() {
2270 let theme = Theme::classic_blue();
2271 let screen = Point::new(24, 8);
2272 // A window occupying the upper-left, smaller than the 24x8 screen.
2273 let mut w = Window::new(Rect::new(0, 0, 14, 5), Some("Edit".into()), 1);
2274 w.standard_scroll_bar(ScrollBarOptions {
2275 vertical: true,
2276 handle_keyboard: true,
2277 });
2278
2279 let mut out = VecDeque::new();
2280 let mut timers = TimerQueue::new();
2281 let mut deferred: Vec<crate::view::Deferred> = Vec::new();
2282 {
2283 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
2284 View::set_state(&mut w, StateFlag::Selected, true, &mut ctx);
2285 }
2286
2287 // Restored snapshot.
2288 insta::assert_snapshot!("zoom_restored", render_window(&mut w, &theme, 24, 8));
2289
2290 // Zoom to fill the screen.
2291 {
2292 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
2293 ctx.set_owner_size(screen);
2294 let mut ev = Event::Command(Command::ZOOM);
2295 w.handle_event(&mut ev, &mut ctx);
2296 }
2297 assert_eq!(w.state().get_bounds(), Rect::new(0, 0, 24, 8));
2298
2299 // Zoomed snapshot: frame fills the whole 24x8 screen.
2300 insta::assert_snapshot!("zoom_filled", render_window(&mut w, &theme, 24, 8));
2301 }
2302
2303 /// A selected (active) window draws its frame in the double-line
2304 /// [`Role::FrameActive`] style: the top-left corner is the `╔` glyph and the
2305 /// cell's style is `theme.style(Role::FrameActive)`. A cheap direct assertion
2306 /// alongside the snapshot.
2307 #[test]
2308 fn active_frame_uses_active_border_style() {
2309 let mut w = window_with_frame();
2310 let mut out = VecDeque::new();
2311 let mut timers = TimerQueue::new();
2312 with_ctx(&mut out, &mut timers, |ctx| {
2313 View::set_state(&mut w, StateFlag::Selected, true, ctx)
2314 });
2315 let theme = Theme::classic_blue();
2316 let mut buf = Buffer::new(40, 15);
2317 {
2318 let bounds = w.state().get_bounds();
2319 let mut dc = DrawCtx::new(&mut buf, &theme, bounds, bounds.a);
2320 w.draw(&mut dc);
2321 }
2322 // The active border corner uses the double-line glyph in FrameActive style.
2323 assert_eq!(buf.get(0, 0).symbol(), "╔", "active double-line corner");
2324 assert_eq!(
2325 buf.get(0, 0).style(),
2326 theme.style(Role::FrameActive),
2327 "active border style"
2328 );
2329 }
2330
2331 // -- 11. drag-start detection (unit; no pump) -----------------------------
2332
2333 use crate::event::{MouseButtons, MouseEvent};
2334
2335 /// A left-button `MouseDown` at window-local `(x, y)`.
2336 fn mouse_down_local(x: i32, y: i32) -> Event {
2337 Event::MouseDown(MouseEvent {
2338 position: Point::new(x, y),
2339 buttons: MouseButtons {
2340 left: true,
2341 ..Default::default()
2342 },
2343 ..Default::default()
2344 })
2345 }
2346
2347 /// A middle-button `MouseDown` at window-local `(x, y)`.
2348 fn mouse_down_middle(x: i32, y: i32) -> Event {
2349 Event::MouseDown(MouseEvent {
2350 position: Point::new(x, y),
2351 buttons: MouseButtons {
2352 middle: true,
2353 ..Default::default()
2354 },
2355 ..Default::default()
2356 })
2357 }
2358
2359 /// Insert a fresh `Window` into a throwaway parent `Group` so it gets its
2360 /// `ViewId` stamped (the substrate stamps the id at `Group::insert`, NOT at
2361 /// `Window::new`; `start_drag`'s `self.group.state().id()` is `None` otherwise).
2362 /// Returns the parent group (owning the window) + the window's id.
2363 fn window_in_group(bounds: Rect) -> (Group, ViewId) {
2364 let mut parent = Group::new(Rect::new(0, 0, 80, 25));
2365 let w = Window::new(bounds, Some("Edit".into()), 1);
2366 let id = parent.insert(Box::new(w));
2367 (parent, id)
2368 }
2369
2370 /// Helper: build a `Context`, call `handle_event` on the window resolved by
2371 /// `id` inside `parent`, and report (event-consumed, pushed-capture-count).
2372 fn drive_window(
2373 parent: &mut Group,
2374 id: ViewId,
2375 ev: &mut Event,
2376 owner_size: Point,
2377 ) -> (bool, usize) {
2378 let mut out = VecDeque::new();
2379 let mut timers = TimerQueue::new();
2380 let mut deferred: Vec<crate::view::Deferred> = Vec::new();
2381 {
2382 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
2383 ctx.set_owner_size(owner_size);
2384 let win = parent.find_mut(id).expect("window resolves");
2385 win.handle_event(ev, &mut ctx);
2386 }
2387 let pushed = deferred
2388 .iter()
2389 .filter(|d| matches!(d, crate::view::Deferred::PushCapture(_)))
2390 .count();
2391 (ev.is_nothing(), pushed)
2392 }
2393
2394 /// A title-bar `MouseDown` (window-local `y == 0`) starts a Move drag: the
2395 /// window's `dragging` goes true, the event is consumed, and one capture is
2396 /// queued in the local `deferred` Vec.
2397 #[test]
2398 fn title_bar_mouse_down_starts_move_drag() {
2399 let (mut parent, id) = window_in_group(Rect::new(2, 1, 22, 9)); // 20x8
2400 let mut ev = mouse_down_local(6, 0); // title bar, away from icons
2401 let (consumed, pending_len) = drive_window(&mut parent, id, &mut ev, Point::new(80, 25));
2402 assert!(consumed, "drag-start consumes the MouseDown");
2403 assert_eq!(pending_len, 1, "one DragCapture queued");
2404 assert!(
2405 parent.find_mut(id).unwrap().state().state.dragging,
2406 "sfDragging set on the window"
2407 );
2408 }
2409
2410 /// A bottom-right corner `MouseDown` (grow allowed) starts a Grow; a
2411 /// bottom-left corner starts a GrowLeft; both consume + queue one capture.
2412 #[test]
2413 fn bottom_corner_mouse_down_starts_grow() {
2414 // Bottom-right: window-local (w-1, h-1).
2415 let (mut parent, id) = window_in_group(Rect::new(2, 1, 22, 9)); // 20x8
2416 let mut ev = mouse_down_local(19, 7);
2417 let (consumed, n) = drive_window(&mut parent, id, &mut ev, Point::new(80, 25));
2418 assert!(consumed && n == 1, "bottom-right starts a grow drag");
2419 assert!(parent.find_mut(id).unwrap().state().state.dragging);
2420
2421 // Bottom-left: window-local (0, h-1).
2422 let (mut parent2, id2) = window_in_group(Rect::new(2, 1, 22, 9));
2423 let mut ev2 = mouse_down_local(0, 7);
2424 let (consumed2, n2) = drive_window(&mut parent2, id2, &mut ev2, Point::new(80, 25));
2425 assert!(consumed2 && n2 == 1, "bottom-left starts a grow-left drag");
2426 assert!(parent2.find_mut(id2).unwrap().state().state.dragging);
2427 }
2428
2429 /// An interior non-edge left click starts no drag (and reaches no drag spot):
2430 /// nothing is queued and `dragging` stays false.
2431 #[test]
2432 fn interior_mouse_down_starts_no_drag() {
2433 let (mut parent, id) = window_in_group(Rect::new(2, 1, 22, 9)); // 20x8
2434 let mut ev = mouse_down_local(8, 4); // interior, not title/corner
2435 let (_consumed, n) = drive_window(&mut parent, id, &mut ev, Point::new(80, 25));
2436 assert_eq!(n, 0, "no DragCapture queued for an interior click");
2437 assert!(
2438 !parent.find_mut(id).unwrap().state().state.dragging,
2439 "interior click does not start a drag"
2440 );
2441 }
2442
2443 /// A middle-button interior `MouseDown` (move allowed) starts a Move drag.
2444 #[test]
2445 fn middle_button_interior_starts_move_drag() {
2446 let (mut parent, id) = window_in_group(Rect::new(2, 1, 22, 9)); // 20x8
2447 let mut ev = mouse_down_middle(8, 4);
2448 let (consumed, n) = drive_window(&mut parent, id, &mut ev, Point::new(80, 25));
2449 assert!(
2450 consumed && n == 1,
2451 "middle-button interior starts a move drag"
2452 );
2453 assert!(parent.find_mut(id).unwrap().state().state.dragging);
2454 }
2455
2456 /// THE COLLISION TEST. The middle button means "move the window" to a
2457 /// bordered `Window` and "paste the PRIMARY selection" to an `InputLine`.
2458 /// Only ordering keeps them apart: the window's drag detection runs AFTER
2459 /// group delegation and fires only on a still-live `MouseDown`, which the
2460 /// child has already consumed. Pin that, so nobody "simplifies" the drag
2461 /// check to the front of `handle_event` and silently breaks middle-click
2462 /// paste in every dialog field.
2463 #[test]
2464 fn middle_click_on_a_child_input_line_does_not_move_the_window() {
2465 let mut parent = Group::new(Rect::new(0, 0, 80, 25));
2466 let mut w = Window::new(Rect::new(2, 1, 22, 9), Some("Edit".into()), 1);
2467 // A one-row field well inside the frame (window-local coords).
2468 let field = crate::widgets::InputLine::with_limit(Rect::new(2, 3, 18, 4), 64);
2469 let field_id = w.insert_child(Box::new(field));
2470 let id = parent.insert(Box::new(w));
2471
2472 let mut out = VecDeque::new();
2473 let mut timers = TimerQueue::new();
2474 let mut deferred: Vec<crate::view::Deferred> = Vec::new();
2475 let mut ev = mouse_down_middle(5, 3); // on the field, inside the border
2476 {
2477 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
2478 ctx.set_owner_size(Point::new(80, 25));
2479 parent
2480 .find_mut(id)
2481 .expect("window resolves")
2482 .handle_event(&mut ev, &mut ctx);
2483 }
2484
2485 assert!(
2486 !parent.find_mut(id).unwrap().state().state.dragging,
2487 "the window must NOT start a move drag"
2488 );
2489 assert!(
2490 deferred.iter().any(|d| matches!(
2491 d,
2492 crate::view::Deferred::InputLinePastePrimary(i) if *i == field_id
2493 )),
2494 "the field asked for a PRIMARY paste instead"
2495 );
2496 }
2497
2498 // -- 12. move_grow unit tests (pure fn) -----------------------------------
2499
2500 /// `move_grow` must use `min(max())`, NOT `clamp()`. The classic TV inversion
2501 /// is the owner SMALLER than the window's minimum size (`min > max`): then the
2502 /// size clamp is `s.x.max(16).min(10)` = `clamp(16, 10)`, which **panics** with
2503 /// `i32::clamp` (lo > hi) but yields `hi` (= max) with `min(max())`. This test
2504 /// would fail (panic) if someone "simplified" the correct min/max into clamp().
2505 #[test]
2506 fn move_grow_oversized_min_uses_min_max_not_clamp() {
2507 let limits = Rect::new(0, 0, 20, 10);
2508 let min = Point::new(16, 6); // window minimum
2509 let max = Point::new(10, 4); // owner SMALLER than the window minimum (inverted)
2510 let mode = DragMode {
2511 limit_lo_y: true,
2512 ..Default::default()
2513 };
2514 // Reaching the assert at all proves no panic; the size clamps to `hi` (=max)
2515 // per "min(max()) yields hi when lo>hi".
2516 let r = move_grow(Point::new(0, 0), Point::new(20, 20), limits, min, max, mode);
2517 let sz = r.b - r.a;
2518 assert_eq!(
2519 sz,
2520 Point::new(10, 4),
2521 "size clamps to max (hi) when min>max, via min(max()) not clamp()"
2522 );
2523 }
2524
2525 /// An ordinary in-range move: a small window inside a roomy limit, no
2526 /// high-edge limit bits, lands where requested (after the general
2527 /// [a-s+1, b-1] band, which a centrally-placed window is well inside).
2528 #[test]
2529 fn move_grow_in_range_move() {
2530 let limits = Rect::new(0, 0, 80, 25);
2531 let min = Point::new(16, 6);
2532 let max = Point::new(80, 25);
2533 let mode = DragMode {
2534 limit_lo_y: true,
2535 ..Default::default()
2536 };
2537 let r = move_grow(Point::new(10, 5), Point::new(20, 8), limits, min, max, mode);
2538 assert_eq!(r, Rect::new(10, 5, 30, 13), "in-range move passes through");
2539 }
2540
2541 // -- View::number override ------------------------------------------------
2542
2543 #[test]
2544 fn view_number_some_when_positive_none_when_zero() {
2545 // Positive number -> Some(n).
2546 let w = Window::new(Rect::new(0, 0, 20, 6), Some("A".into()), 4);
2547 assert_eq!(View::number(&w), Some(4), "number > 0 -> Some");
2548 // 0 -> None (an unnumbered window is never a select-by-number target).
2549 let w0 = Window::new(Rect::new(0, 0, 20, 6), Some("B".into()), 0);
2550 assert_eq!(View::number(&w0), None, "number == 0 (unnumbered) -> None");
2551 }
2552
2553 #[test]
2554 fn set_state_select_enables_cm_next_and_prev_unconditionally() {
2555 let mut w = window_with_frame();
2556 let mut out = VecDeque::new();
2557 let mut timers = TimerQueue::new();
2558 let mut deferred: Vec<crate::view::Deferred> = Vec::new();
2559 {
2560 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
2561 View::set_state(&mut w, StateFlag::Selected, true, &mut ctx);
2562 }
2563 use crate::view::Deferred;
2564 assert!(
2565 deferred
2566 .iter()
2567 .any(|d| matches!(d, Deferred::EnableCommand(Command::NEXT))),
2568 "select enables cmNext (unconditional)"
2569 );
2570 assert!(
2571 deferred
2572 .iter()
2573 .any(|d| matches!(d, Deferred::EnableCommand(Command::PREV))),
2574 "select enables cmPrev (unconditional)"
2575 );
2576 deferred.clear();
2577 {
2578 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
2579 View::set_state(&mut w, StateFlag::Selected, false, &mut ctx);
2580 }
2581 assert!(
2582 deferred
2583 .iter()
2584 .any(|d| matches!(d, Deferred::DisableCommand(Command::NEXT))),
2585 "deselect disables cmNext"
2586 );
2587 assert!(
2588 deferred
2589 .iter()
2590 .any(|d| matches!(d, Deferred::DisableCommand(Command::PREV))),
2591 "deselect disables cmPrev"
2592 );
2593 }
2594
2595 // -- 13. locate() re-pushes set_zoomed on bounds change (B5) ---------------
2596
2597 /// After `locate` changes the window bounds (non-trivially), the frame's
2598 /// `zoomed` flag is updated to reflect the new size vs max. This verifies
2599 /// B5: the pushed bool no longer goes stale on owner resize / change_bounds.
2600 #[test]
2601 fn locate_repushes_set_zoomed_after_bounds_change() {
2602 let mut w = Window::new(Rect::new(0, 0, 20, 8), Some("Edit".into()), 1);
2603 let desktop_size = Point::new(80, 25);
2604
2605 // Manually set frame zoomed = true to confirm it gets RESET after a
2606 // non-max locate.
2607 {
2608 let frame_id = w.frame_id();
2609 if let Some(frame) = w
2610 .group
2611 .child_mut(frame_id)
2612 .and_then(|v| v.as_any_mut())
2613 .and_then(|a| a.downcast_mut::<Frame>())
2614 {
2615 frame.set_zoomed(true);
2616 }
2617 }
2618 assert!(
2619 frame_zoomed(&mut w),
2620 "precondition: frame zoomed = true before locate"
2621 );
2622
2623 // locate to a smaller-than-max rect → zoomed must become false.
2624 w.locate(Rect::new(5, 3, 30, 12), desktop_size);
2625 assert!(
2626 !frame_zoomed(&mut w),
2627 "locate to non-max rect pushes zoomed = false"
2628 );
2629
2630 // locate to exactly the max rect → zoomed must become true.
2631 let (_, max) = View::size_limits(&w, desktop_size);
2632 w.locate(Rect::new(0, 0, max.x, max.y), desktop_size);
2633 assert!(
2634 frame_zoomed(&mut w),
2635 "locate to max rect pushes zoomed = true"
2636 );
2637 }
2638
2639 // -- 14. joined splitter: divider tees auto-brokered into the frame --------
2640
2641 /// A minimal fill view for splitter-pane snapshot tests.
2642 fn plain_fill(ch: char) -> Box<dyn View> {
2643 struct F(char, ViewState);
2644 impl View for F {
2645 fn state(&self) -> &ViewState {
2646 &self.1
2647 }
2648 fn state_mut(&mut self) -> &mut ViewState {
2649 &mut self.1
2650 }
2651 fn draw(&mut self, ctx: &mut DrawCtx) {
2652 let b = self.1.get_bounds();
2653 let (w, h) = (b.b.x - b.a.x, b.b.y - b.a.y);
2654 ctx.fill(
2655 Rect::new(0, 0, w, h),
2656 self.0,
2657 ctx.style(crate::theme::Role::Normal),
2658 );
2659 }
2660 }
2661 Box::new(F(ch, ViewState::new(Rect::new(0, 0, 1, 1))))
2662 }
2663
2664 #[test]
2665 fn joined_splitter_frame_tees_top_and_bottom() {
2666 use crate::widgets::{Constraints, Splitter};
2667 let theme = Theme::classic_blue();
2668 let mut win = Window::new(Rect::new(0, 0, 16, 6), None, 0);
2669 let ext = win.state().get_extent();
2670 let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);
2671 let split = Splitter::cols()
2672 .pane(plain_fill('A'), Constraints::flex())
2673 .pane(plain_fill('B'), Constraints::flex())
2674 .joined();
2675 let sid = win.insert_child(Box::new(split));
2676 if let Some(v) = win.child_mut(sid) {
2677 v.change_bounds(interior);
2678 }
2679 let (backend, screen) = HeadlessBackend::new(16, 6);
2680 let mut r = Renderer::new(Box::new(backend));
2681 r.render(|buf: &mut Buffer| {
2682 let bounds = win.state().get_bounds();
2683 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
2684 win.draw(&mut dc);
2685 });
2686 insta::assert_snapshot!(screen.snapshot());
2687 }
2688
2689 #[test]
2690 fn joined_splitter_active_frame_uses_mixed_tees() {
2691 use crate::widgets::{Constraints, Splitter};
2692 let theme = Theme::classic_blue();
2693 let mut win = Window::new(Rect::new(0, 0, 16, 6), None, 0);
2694 let ext = win.state().get_extent();
2695 let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);
2696 let split = Splitter::cols()
2697 .pane(plain_fill('A'), Constraints::flex())
2698 .pane(plain_fill('B'), Constraints::flex())
2699 .joined();
2700 let sid = win.insert_child(Box::new(split));
2701 if let Some(v) = win.child_mut(sid) {
2702 v.change_bounds(interior);
2703 }
2704 // Activate the frame CHILD directly so it draws its double-line box (the
2705 // group's own active flag does not propagate to children without set_state).
2706 let fid = win.frame_id();
2707 if let Some(v) = win.child_mut(fid) {
2708 v.state_mut().state.active = true;
2709 }
2710 let (backend, screen) = HeadlessBackend::new(16, 6);
2711 let mut r = Renderer::new(Box::new(backend));
2712 r.render(|buf: &mut Buffer| {
2713 let bounds = win.state().get_bounds();
2714 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
2715 win.draw(&mut dc);
2716 });
2717 insta::assert_snapshot!(screen.snapshot());
2718 }
2719
2720 #[test]
2721 fn unjoined_splitter_frame_is_plain() {
2722 use crate::widgets::{Constraints, Splitter};
2723 let theme = Theme::classic_blue();
2724 let mut win = Window::new(Rect::new(0, 0, 16, 6), None, 0);
2725 let ext = win.state().get_extent();
2726 let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);
2727 // Splitter NOT joined → the window auto-broker pushes empty marks.
2728 let split = Splitter::cols()
2729 .pane(plain_fill('A'), Constraints::flex())
2730 .pane(plain_fill('B'), Constraints::flex());
2731 let sid = win.insert_child(Box::new(split));
2732 if let Some(v) = win.child_mut(sid) {
2733 v.change_bounds(interior);
2734 }
2735 let (backend, screen) = HeadlessBackend::new(16, 6);
2736 let mut r = Renderer::new(Box::new(backend));
2737 r.render(|buf: &mut Buffer| {
2738 let bounds = win.state().get_bounds();
2739 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
2740 win.draw(&mut dc);
2741 });
2742 let snap = screen.snapshot();
2743 // The first interior row (the top frame edge) must contain no junction tee.
2744 let top_edge = snap
2745 .lines()
2746 .find(|l| l.contains('┌') || l.contains('╔'))
2747 .unwrap_or("");
2748 assert!(
2749 !top_edge.contains('┬') && !top_edge.contains('╤'),
2750 "no tee without the flag: {top_edge:?}"
2751 );
2752 // Freeze a baseline reference rendering for the no-flag case.
2753 insta::assert_snapshot!(snap);
2754 }
2755
2756 #[test]
2757 fn toggling_splitter_joined_off_reverts_to_plain_frame() {
2758 use crate::widgets::{Constraints, Splitter};
2759 let theme = Theme::classic_blue();
2760 let mut win = Window::new(Rect::new(0, 0, 16, 6), None, 0);
2761 let ext = win.state().get_extent();
2762 let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);
2763 let split = Splitter::cols()
2764 .pane(plain_fill('A'), Constraints::flex())
2765 .pane(plain_fill('B'), Constraints::flex())
2766 .joined();
2767 let sid = win.insert_child(Box::new(split));
2768 if let Some(v) = win.child_mut(sid) {
2769 v.change_bounds(interior);
2770 }
2771
2772 // First draw with the splitter joined: the auto-broker adds a top tee.
2773 let render = |win: &mut Window| {
2774 let (backend, screen) = HeadlessBackend::new(16, 6);
2775 let mut r = Renderer::new(Box::new(backend));
2776 r.render(|buf: &mut Buffer| {
2777 let bounds = win.state().get_bounds();
2778 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
2779 win.draw(&mut dc);
2780 });
2781 screen.snapshot()
2782 };
2783 let on = render(&mut win);
2784 assert!(on.contains('┬'), "joined: top tee present");
2785
2786 // Un-join the splitter itself; the auto-broker now pushes empty marks and
2787 // the frame reverts to a plain border.
2788 if let Some(sp) = win
2789 .child_mut(sid)
2790 .and_then(|v| v.as_any_mut())
2791 .and_then(|a| a.downcast_mut::<Splitter>())
2792 {
2793 sp.set_joined(false);
2794 }
2795 let off = render(&mut win);
2796 assert!(
2797 !off.contains('┬') && !off.contains('╤'),
2798 "after un-join, plain frame: {off:?}"
2799 );
2800 }
2801
2802 /// A rows (horizontal-divider) splitter inside an ACTIVE (double-line) window
2803 /// frame: the divider's ends abut the LEFT and RIGHT frame edges. At those
2804 /// junctions the frame's double vertical bar (║) meets the divider's single
2805 /// horizontal stem — the correct glyphs are ╟ (left, U+255F) and ╢ (right,
2806 /// U+2562). Before the glyph-table fix this test would see ╞/╡ instead.
2807 #[test]
2808 fn joined_rows_splitter_active_frame_side_tees_are_double_bar_single_stem() {
2809 use crate::widgets::{Constraints, Splitter};
2810 let theme = Theme::classic_blue();
2811 let mut win = Window::new(Rect::new(0, 0, 16, 7), None, 0);
2812 // Activate the frame child directly so it draws its double-line box.
2813 let fid = win.frame_id();
2814 if let Some(v) = win.child_mut(fid) {
2815 v.state_mut().state.active = true;
2816 }
2817 let ext = win.state().get_extent();
2818 let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);
2819 // A rows splitter: two stacked panes with one horizontal divider that
2820 // spans the full interior width → its left end meets the LEFT frame edge
2821 // and its right end meets the RIGHT frame edge.
2822 let split = Splitter::rows()
2823 .pane(plain_fill('A'), Constraints::flex())
2824 .pane(plain_fill('B'), Constraints::flex())
2825 .joined();
2826 let sid = win.insert_child(Box::new(split));
2827 if let Some(v) = win.child_mut(sid) {
2828 v.change_bounds(interior);
2829 }
2830 // Render into a direct Buffer so we can read individual cells.
2831 let mut buf = Buffer::new(16, 7);
2832 {
2833 let bounds = win.state().get_bounds();
2834 let mut dc = DrawCtx::new(&mut buf, &theme, bounds, bounds.a);
2835 win.draw(&mut dc);
2836 }
2837 // Scan interior rows (1..6) for the divider row: the row where the left
2838 // frame cell (col 0) is a tee glyph rather than the plain double bar ║.
2839 let mut divider_row: Option<u16> = None;
2840 for y in 1_u16..6 {
2841 let cell = buf.get(0, y).symbol().to_string();
2842 if cell != "║" {
2843 divider_row = Some(y);
2844 break;
2845 }
2846 }
2847 let y =
2848 divider_row.expect("a left-frame junction must exist on the horizontal divider row");
2849 assert_eq!(
2850 buf.get(0, y).symbol(),
2851 "╟",
2852 "left frame: double bar (║ weight) + single divider stem → ╟ (U+255F)"
2853 );
2854 assert_eq!(
2855 buf.get(15, y).symbol(),
2856 "╢",
2857 "right frame: double bar (║ weight) + single divider stem → ╢ (U+2562)"
2858 );
2859 }
2860
2861 // -- unified keyboard resize: Tab cycles window <-> dividers --------------
2862
2863 /// Build a parent `Group` holding a movable/growable `Window` whose body is a
2864 /// 3-pane cols `Splitter`. Returns `(parent, window_id, splitter_id, pane0_id)`.
2865 /// The splitter fills the window interior so its panes have non-zero bounds.
2866 fn window_with_splitter_body() -> (Group, ViewId, ViewId, ViewId) {
2867 use crate::widgets::{Constraints, Splitter};
2868
2869 let mut parent = Group::new(Rect::new(0, 0, 80, 25));
2870 let mut win = Window::new(Rect::new(2, 2, 42, 14), Some("S".into()), 1); // 40x12
2871
2872 let mut sp = Splitter::cols();
2873 let p0 = sp.insert(Probe::boxed(Rect::new(0, 0, 0, 0)), Constraints::flex());
2874 sp.insert(Probe::boxed(Rect::new(0, 0, 0, 0)), Constraints::flex());
2875 sp.insert(Probe::boxed(Rect::new(0, 0, 0, 0)), Constraints::flex());
2876
2877 let sp_id = win.insert_child(Box::new(sp));
2878 // Size the splitter to the window interior (1-cell frame inset each side).
2879 let ext = win.state().get_extent();
2880 let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);
2881 if let Some(v) = win.child_mut(sp_id) {
2882 v.change_bounds(interior);
2883 }
2884
2885 let id = parent.insert(Box::new(win));
2886 (parent, id, sp_id, p0)
2887 }
2888
2889 /// Read pane `id`'s right boundary (`bounds.b.x`) by resolving it in `parent`.
2890 fn pane_right(parent: &mut Group, id: ViewId) -> i32 {
2891 parent
2892 .find_mut(id)
2893 .map(|v| v.state().get_bounds().b.x)
2894 .expect("pane resolves")
2895 }
2896
2897 /// Apply every `Deferred::SplitterDivider` op in `deferred` to the splitter,
2898 /// mirroring the pump's D3 broker arm (downcast → `Splitter` → method).
2899 ///
2900 /// NOTE: this intentionally applies ONLY `SplitterDivider` ops. All other
2901 /// deferred effects (`request_bounds`, `request_set_state`, `push_capture`,
2902 /// …) are silently ignored — so a future test that asserts on window bounds
2903 /// or the `Dragging` flag through this helper would NOT observe them; such a
2904 /// test must drain those deferreds itself (or drive a real pump).
2905 fn apply_divider_ops(parent: &mut Group, deferred: &[crate::view::Deferred]) {
2906 use crate::view::{Deferred, DividerOp};
2907 use crate::widgets::Splitter;
2908 for d in deferred {
2909 if let Deferred::SplitterDivider { splitter, op } = d
2910 && let Some(sp) = parent
2911 .find_mut(*splitter)
2912 .and_then(|v| v.as_any_mut())
2913 .and_then(|a| a.downcast_mut::<Splitter>())
2914 {
2915 match op {
2916 DividerOp::SetActive(sel) => sp.set_active_divider(*sel),
2917 DividerOp::Nudge { index, delta } => sp.nudge_divider(*index, *delta),
2918 DividerOp::EndSession { commit } => sp.end_resize_session(*commit),
2919 }
2920 }
2921 }
2922 }
2923
2924 /// Drive `handle_event` on the window resolved by `id`, returning the drained
2925 /// deferred Vec (so the caller can inspect/apply the queued ops).
2926 fn drive_collect(
2927 parent: &mut Group,
2928 id: ViewId,
2929 ev: &mut Event,
2930 owner_size: Point,
2931 ) -> Vec<crate::view::Deferred> {
2932 let mut out = VecDeque::new();
2933 let mut timers = TimerQueue::new();
2934 let mut deferred: Vec<crate::view::Deferred> = Vec::new();
2935 {
2936 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
2937 ctx.set_owner_size(owner_size);
2938 let win = parent.find_mut(id).expect("window resolves");
2939 win.handle_event(ev, &mut ctx);
2940 }
2941 deferred
2942 }
2943
2944 /// Feed `ev` to `cap` (a pushed capture) with a fresh `Context`; apply the
2945 /// queued divider ops to `parent` and return the `CaptureFlow`.
2946 fn feed_capture(
2947 parent: &mut Group,
2948 cap: &mut dyn CaptureHandler,
2949 mut ev: Event,
2950 ) -> CaptureFlow {
2951 let mut out = VecDeque::new();
2952 let mut timers = TimerQueue::new();
2953 let mut deferred: Vec<crate::view::Deferred> = Vec::new();
2954 let flow = {
2955 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
2956 ctx.set_owner_size(Point::new(80, 25));
2957 cap.handle(&mut ev, &mut ctx)
2958 };
2959 apply_divider_ops(parent, &deferred);
2960 flow
2961 }
2962
2963 /// Feed `ev` to `cap`; apply divider ops to `parent`; return `(flow, deferred)`.
2964 /// Use this when you also need to inspect `ChangeBounds` or other deferred ops.
2965 fn feed_capture_full(
2966 parent: &mut Group,
2967 cap: &mut dyn CaptureHandler,
2968 mut ev: Event,
2969 ) -> (CaptureFlow, Vec<crate::view::Deferred>) {
2970 let mut out = VecDeque::new();
2971 let mut timers = TimerQueue::new();
2972 let mut deferred: Vec<crate::view::Deferred> = Vec::new();
2973 let flow = {
2974 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
2975 ctx.set_owner_size(Point::new(80, 25));
2976 cap.handle(&mut ev, &mut ctx)
2977 };
2978 apply_divider_ops(parent, &deferred);
2979 (flow, deferred)
2980 }
2981
2982 /// Extract the last `ChangeBounds` rect for `id` from a deferred Vec.
2983 fn last_bounds(deferred: &[crate::view::Deferred], id: ViewId) -> Option<Rect> {
2984 use crate::view::Deferred;
2985 deferred.iter().rev().find_map(|d| {
2986 if let Deferred::ChangeBounds(vid, r) = d
2987 && *vid == id
2988 {
2989 Some(*r)
2990 } else {
2991 None
2992 }
2993 })
2994 }
2995
2996 fn key(k: Key) -> Event {
2997 Event::KeyDown(KeyEvent::new(k, KeyModifiers::default()))
2998 }
2999
3000 fn key_shift(k: Key) -> Event {
3001 Event::KeyDown(KeyEvent::new(
3002 k,
3003 KeyModifiers {
3004 shift: true,
3005 ..Default::default()
3006 },
3007 ))
3008 }
3009
3010 fn key_ctrl(k: Key) -> Event {
3011 Event::KeyDown(KeyEvent::new(
3012 k,
3013 KeyModifiers {
3014 ctrl: true,
3015 ..Default::default()
3016 },
3017 ))
3018 }
3019
3020 fn key_ctrl_shift(k: Key) -> Event {
3021 Event::KeyDown(KeyEvent::new(
3022 k,
3023 KeyModifiers {
3024 ctrl: true,
3025 shift: true,
3026 ..Default::default()
3027 },
3028 ))
3029 }
3030
3031 /// Extract the (single) `PushCapture` handler from a drained deferred Vec.
3032 fn take_capture(deferred: Vec<crate::view::Deferred>) -> Box<dyn CaptureHandler> {
3033 for d in deferred {
3034 if let crate::view::Deferred::PushCapture(h) = d {
3035 return h;
3036 }
3037 }
3038 panic!("RESIZE must push a capture");
3039 }
3040
3041 #[test]
3042 fn resize_mode_tab_cycles_to_divider_and_arrow_moves_it() {
3043 let (mut parent, id, sp_id, p0) = window_with_splitter_body();
3044
3045 // 1+2) deliver Command::RESIZE -> enters resize mode, target = Window.
3046 let mut ev = Event::Command(Command::RESIZE);
3047 let deferred = drive_collect(&mut parent, id, &mut ev, Point::new(80, 25));
3048 apply_divider_ops(&mut parent, &deferred); // no divider op for target[0]=Window
3049 let mut cap = take_capture(deferred);
3050
3051 // Record divider-0 pane width before moving it.
3052 let before = pane_right(&mut parent, p0);
3053
3054 // 3) Tab -> target = divider 0 (window Dragging cleared, divider 0 active).
3055 let f = feed_capture(&mut parent, cap.as_mut(), key(Key::Tab));
3056 assert!(matches!(f, CaptureFlow::Consumed), "Tab is consumed");
3057
3058 // 4) Right -> divider 0 moves +1 along the cols axis.
3059 let f = feed_capture(&mut parent, cap.as_mut(), key(Key::Right));
3060 assert!(matches!(f, CaptureFlow::Consumed), "arrow is consumed");
3061
3062 // 5) Enter -> commit.
3063 let f = feed_capture(&mut parent, cap.as_mut(), key(Key::Enter));
3064 assert!(
3065 matches!(f, CaptureFlow::ConsumedPop),
3066 "Enter commits + pops"
3067 );
3068
3069 let after = pane_right(&mut parent, p0);
3070 assert_eq!(
3071 after,
3072 before + 1,
3073 "Tab→divider 0, Right nudges its right boundary +1 (committed)"
3074 );
3075 let _ = sp_id;
3076 }
3077
3078 #[test]
3079 fn resize_mode_esc_restores_divider() {
3080 let (mut parent, id, _sp_id, p0) = window_with_splitter_body();
3081
3082 let mut ev = Event::Command(Command::RESIZE);
3083 let deferred = drive_collect(&mut parent, id, &mut ev, Point::new(80, 25));
3084 apply_divider_ops(&mut parent, &deferred);
3085 let mut cap = take_capture(deferred);
3086
3087 let before = pane_right(&mut parent, p0);
3088
3089 feed_capture(&mut parent, cap.as_mut(), key(Key::Tab)); // -> divider 0
3090 feed_capture(&mut parent, cap.as_mut(), key(Key::Right));
3091 feed_capture(&mut parent, cap.as_mut(), key(Key::Right));
3092 // moved by +2 before cancel
3093 assert_eq!(pane_right(&mut parent, p0), before + 2, "moved before Esc");
3094
3095 let f = feed_capture(&mut parent, cap.as_mut(), key(Key::Esc));
3096 assert!(matches!(f, CaptureFlow::ConsumedPop), "Esc cancels + pops");
3097
3098 assert_eq!(
3099 pane_right(&mut parent, p0),
3100 before,
3101 "Esc restores divider-0 to its pre-mode position"
3102 );
3103 }
3104
3105 // -- 15. keyboard resize: plain arrow moves, Shift+arrow resizes (faithful TView::change) ---
3106
3107 /// Enter RESIZE mode (target = Window). Feed a plain Right arrow.
3108 /// Assert: origin.x increased by 1, size (width/height) UNCHANGED.
3109 #[test]
3110 fn resize_mode_plain_arrow_moves_window_not_resizes() {
3111 let (mut parent, id, _sp_id, _p0) = window_with_splitter_body();
3112
3113 // Snapshot the window's bounds before entering resize mode.
3114 let init_bounds = parent.find_mut(id).unwrap().state().get_bounds();
3115
3116 // Deliver RESIZE command → enters resize mode, target[0] = Window.
3117 let mut ev = Event::Command(Command::RESIZE);
3118 let deferred = drive_collect(&mut parent, id, &mut ev, Point::new(80, 25));
3119 apply_divider_ops(&mut parent, &deferred);
3120 let window_id = id; // captured for ChangeBounds lookup
3121 let mut cap = take_capture(deferred);
3122
3123 // Feed plain Right (no modifiers) → should MOVE only.
3124 let (_flow, deferred) = feed_capture_full(&mut parent, cap.as_mut(), key(Key::Right));
3125
3126 let new_bounds = last_bounds(&deferred, window_id)
3127 .expect("a plain arrow on the Window target must emit ChangeBounds");
3128
3129 assert_eq!(
3130 new_bounds.b.x - new_bounds.a.x,
3131 init_bounds.b.x - init_bounds.a.x,
3132 "plain Right: window width must be UNCHANGED (move, not grow)"
3133 );
3134 assert_eq!(
3135 new_bounds.b.y - new_bounds.a.y,
3136 init_bounds.b.y - init_bounds.a.y,
3137 "plain Right: window height must be UNCHANGED (move, not grow)"
3138 );
3139 assert_eq!(
3140 new_bounds.a.x,
3141 init_bounds.a.x + 1,
3142 "plain Right: window origin.x must increase by 1"
3143 );
3144 assert_eq!(
3145 new_bounds.a.y, init_bounds.a.y,
3146 "plain Right: window origin.y must be UNCHANGED"
3147 );
3148 }
3149
3150 /// Enter RESIZE mode (target = Window). Feed Shift+Right.
3151 /// Assert: width increased by 1, origin UNCHANGED.
3152 #[test]
3153 fn resize_mode_shift_arrow_resizes_window_not_moves() {
3154 let (mut parent, id, _sp_id, _p0) = window_with_splitter_body();
3155
3156 let init_bounds = parent.find_mut(id).unwrap().state().get_bounds();
3157
3158 let mut ev = Event::Command(Command::RESIZE);
3159 let deferred = drive_collect(&mut parent, id, &mut ev, Point::new(80, 25));
3160 apply_divider_ops(&mut parent, &deferred);
3161 let window_id = id;
3162 let mut cap = take_capture(deferred);
3163
3164 // Feed Shift+Right → should GROW only.
3165 let (_flow, deferred) = feed_capture_full(&mut parent, cap.as_mut(), key_shift(Key::Right));
3166
3167 let new_bounds = last_bounds(&deferred, window_id)
3168 .expect("Shift+arrow on the Window target must emit ChangeBounds");
3169
3170 assert_eq!(
3171 new_bounds.a.x, init_bounds.a.x,
3172 "Shift+Right: window origin.x must be UNCHANGED (grow, not move)"
3173 );
3174 assert_eq!(
3175 new_bounds.a.y, init_bounds.a.y,
3176 "Shift+Right: window origin.y must be UNCHANGED"
3177 );
3178 assert_eq!(
3179 new_bounds.b.x - new_bounds.a.x,
3180 init_bounds.b.x - init_bounds.a.x + 1,
3181 "Shift+Right: window width must increase by 1"
3182 );
3183 assert_eq!(
3184 new_bounds.b.y - new_bounds.a.y,
3185 init_bounds.b.y - init_bounds.a.y,
3186 "Shift+Right: window height must be UNCHANGED"
3187 );
3188 }
3189
3190 /// Enter RESIZE mode (target = Window). Feed Ctrl+Right (big step, no shift).
3191 /// Assert: origin.x increased by 8, size UNCHANGED.
3192 #[test]
3193 fn resize_mode_ctrl_arrow_big_move() {
3194 let (mut parent, id, _sp_id, _p0) = window_with_splitter_body();
3195
3196 let init_bounds = parent.find_mut(id).unwrap().state().get_bounds();
3197
3198 let mut ev = Event::Command(Command::RESIZE);
3199 let deferred = drive_collect(&mut parent, id, &mut ev, Point::new(80, 25));
3200 apply_divider_ops(&mut parent, &deferred);
3201 let window_id = id;
3202 let mut cap = take_capture(deferred);
3203
3204 // Feed Ctrl+Right (big step, plain = move) → origin shifts by 8.
3205 let (_flow, deferred) = feed_capture_full(&mut parent, cap.as_mut(), key_ctrl(Key::Right));
3206
3207 let new_bounds =
3208 last_bounds(&deferred, window_id).expect("Ctrl+arrow on Window must emit ChangeBounds");
3209
3210 // Size must be unchanged.
3211 assert_eq!(
3212 new_bounds.b.x - new_bounds.a.x,
3213 init_bounds.b.x - init_bounds.a.x,
3214 "Ctrl+Right: width unchanged (big move, not grow)"
3215 );
3216 // Origin.x should move by 8 (clamped to limits; the window starts at x=2,
3217 // so +8 = 10 is well within 80-wide owner).
3218 assert_eq!(
3219 new_bounds.a.x,
3220 init_bounds.a.x + 8,
3221 "Ctrl+Right: origin.x increases by the large step (8)"
3222 );
3223 }
3224
3225 /// Enter RESIZE mode (target = Window). Feed Ctrl+Shift+Right (big grow).
3226 /// Ctrl scales the step to 8; Shift selects grow. Assert: width += 8,
3227 /// origin UNCHANGED.
3228 #[test]
3229 fn resize_mode_ctrl_shift_arrow_big_resizes_window() {
3230 let (mut parent, id, _sp_id, _p0) = window_with_splitter_body();
3231
3232 let init_bounds = parent.find_mut(id).unwrap().state().get_bounds();
3233
3234 let mut ev = Event::Command(Command::RESIZE);
3235 let deferred = drive_collect(&mut parent, id, &mut ev, Point::new(80, 25));
3236 apply_divider_ops(&mut parent, &deferred);
3237 let window_id = id;
3238 let mut cap = take_capture(deferred);
3239
3240 // Feed Ctrl+Shift+Right (big step + grow) → width grows by 8.
3241 let (_flow, deferred) =
3242 feed_capture_full(&mut parent, cap.as_mut(), key_ctrl_shift(Key::Right));
3243
3244 let new_bounds = last_bounds(&deferred, window_id)
3245 .expect("Ctrl+Shift+arrow on Window must emit ChangeBounds");
3246
3247 // Origin must be unchanged (grow, not move).
3248 assert_eq!(
3249 new_bounds.a.x, init_bounds.a.x,
3250 "Ctrl+Shift+Right: origin.x must be UNCHANGED (grow, not move)"
3251 );
3252 assert_eq!(
3253 new_bounds.a.y, init_bounds.a.y,
3254 "Ctrl+Shift+Right: origin.y must be UNCHANGED"
3255 );
3256 // Width grows by the large step (8); the window is 40 wide starting at
3257 // x=2, so 40+8 = 48 fits well within the 80-wide owner.
3258 assert_eq!(
3259 new_bounds.b.x - new_bounds.a.x,
3260 init_bounds.b.x - init_bounds.a.x + 8,
3261 "Ctrl+Shift+Right: width grows by the large step (8)"
3262 );
3263 // Height unchanged (horizontal arrow).
3264 assert_eq!(
3265 new_bounds.b.y - new_bounds.a.y,
3266 init_bounds.b.y - init_bounds.a.y,
3267 "Ctrl+Shift+Right: height must be UNCHANGED"
3268 );
3269 }
3270
3271 // -- consumer API: public decoration setters + with_* builders ------------
3272
3273 #[test]
3274 fn flags_off_window_is_a_fixed_iconless_panel() {
3275 // A consumer building TCV's fixed full-desktop panel: all decoration off.
3276 let w = Window::new(Rect::new(0, 0, 24, 8), Some("Catalog".into()), 0)
3277 .with_flags(WindowFlags::default()) // all four false
3278 .with_grow_mode(GrowMode::default())
3279 .with_drag_mode(DragMode::default());
3280 assert_eq!(
3281 w.flags(),
3282 WindowFlags {
3283 r#move: false,
3284 grow: false,
3285 close: false,
3286 zoom: false,
3287 },
3288 "consumer can clear all decoration flags"
3289 );
3290 let gm = w.state().grow_mode;
3291 assert!(
3292 !gm.lo_x && !gm.lo_y && !gm.hi_x && !gm.hi_y && !gm.rel && !gm.fixed,
3293 "consumer can clear grow_mode"
3294 );
3295 }
3296
3297 #[test]
3298 fn with_palette_sets_and_pushes_to_frame() {
3299 let mut w = Window::new(Rect::new(0, 0, 24, 8), Some("Cyan".into()), 1)
3300 .with_palette(WindowPalette::Cyan);
3301 assert_eq!(w.palette(), WindowPalette::Cyan);
3302 let frame_id = w.frame_id();
3303 let frame = w
3304 .child_mut(frame_id)
3305 .and_then(|v| v.as_any_mut())
3306 .and_then(|a| a.downcast_mut::<crate::frame::Frame>())
3307 .expect("window has a Frame child");
3308 assert_eq!(
3309 frame.palette(),
3310 WindowPalette::Cyan,
3311 "with_palette must propagate to the frame child"
3312 );
3313 }
3314
3315 #[test]
3316 fn fullscreen_defaults_off_and_cycles() {
3317 use crate::window::Fullscreen;
3318 let win = Window::new(Rect::new(0, 0, 20, 8), Some("W".into()), 0);
3319 assert_eq!(
3320 win.fullscreen(),
3321 Fullscreen::Off,
3322 "new window is not fullscreen"
3323 );
3324 assert_eq!(Fullscreen::Off.next(), Fullscreen::Desktop);
3325 assert_eq!(Fullscreen::Desktop.next(), Fullscreen::Screen);
3326 assert_eq!(Fullscreen::Screen.next(), Fullscreen::Off);
3327 }
3328
3329 #[test]
3330 fn client_rect_full_when_frameless() {
3331 let mut win = Window::new(Rect::new(0, 0, 20, 8), None, 0);
3332 let ext = win.state().get_extent(); // (0,0,20,8)
3333 // Bordered: inset by one on every side.
3334 let cr = win.client_rect();
3335 assert_eq!(
3336 (cr.a.x, cr.a.y, cr.b.x, cr.b.y),
3337 (1, 1, ext.b.x - 1, ext.b.y - 1)
3338 );
3339 // Frameless: the full extent. `client_rect` keys off `bordered`, not the
3340 // fullscreen mode (the two are now independent primitives).
3341 win.bordered = false;
3342 assert_eq!(win.client_rect(), ext);
3343 }
3344
3345 // -- R2: content reflow on a border toggle (the margin-bug regression) -----
3346
3347 /// Toggling the border reflows content as a grow-mode resize + an origin
3348 /// shift: a content child filling the bordered interior `(1,1,w-1,h-1)` must
3349 /// become the frameless full extent `(0,0,w,h)`, and back. The child tracks
3350 /// the right/bottom edges (`hi_x|hi_y`) so the size delta is delivered through
3351 /// the existing grow path, exactly as on a real resize.
3352 #[test]
3353 fn set_bordered_reflows_content_to_edges() {
3354 let mut w = Window::new(Rect::new(0, 0, 40, 15), Some("W".into()), 0); // w=40,h=15
3355 let mut st = ViewState::new(Rect::new(1, 1, 39, 14));
3356 st.grow_mode = GrowMode {
3357 hi_x: true,
3358 hi_y: true,
3359 ..Default::default()
3360 };
3361 let id = w.insert_child(Box::new(Probe { st }));
3362
3363 let mut out = VecDeque::new();
3364 let mut timers = TimerQueue::new();
3365
3366 // Remove the border: content reflows to the full extent.
3367 with_ctx(&mut out, &mut timers, |ctx| w.set_bordered(false, ctx));
3368 assert_eq!(
3369 w.child_mut(id).unwrap().state().get_bounds(),
3370 Rect::new(0, 0, 40, 15),
3371 "content fills the full extent when frameless"
3372 );
3373
3374 // Re-add the border: content reflows back to the interior.
3375 with_ctx(&mut out, &mut timers, |ctx| w.set_bordered(true, ctx));
3376 assert_eq!(
3377 w.child_mut(id).unwrap().state().get_bounds(),
3378 Rect::new(1, 1, 39, 14),
3379 "content returns to the interior when bordered"
3380 );
3381 }
3382
3383 // -- R2: un-zoom of a fullscreen window is coherent (bug-1 regression) ------
3384
3385 /// Zooming a fullscreen window must produce a COHERENT state: zoom and
3386 /// fullscreen share ONE restore slot, and the border is an independent
3387 /// primitive. After `set_fullscreen(Desktop)` then a `ZOOM` (un-maximize) the
3388 /// window returns to its pre-fullscreen bounds, is no longer maximized, the
3389 /// single restore slot is consumed, and it stays frameless (zoom does not
3390 /// re-border) — an intentional small borderless window, not the old accidental
3391 /// small-but-frameless-with-a-stale-second-slot.
3392 #[test]
3393 fn unzoom_of_fullscreen_is_coherent() {
3394 use crate::window::Fullscreen;
3395 let mut w = Window::new(Rect::new(2, 2, 22, 10), Some("W".into()), 1); // size 20x8
3396 let original = w.state().get_bounds();
3397 let owner = Point::new(80, 25);
3398
3399 let mut out = VecDeque::new();
3400 let mut timers = TimerQueue::new();
3401
3402 // Drive to Desktop fullscreen: maximize + drop the border.
3403 with_ctx(&mut out, &mut timers, |ctx| {
3404 ctx.set_owner_size(owner);
3405 w.set_fullscreen(Fullscreen::Desktop, ctx);
3406 });
3407 assert!(w.is_maximized(), "fullscreen maximized the window");
3408 assert!(!w.bordered(), "fullscreen dropped the border");
3409 assert_eq!(
3410 w.state().get_bounds(),
3411 Rect::new(0, 0, owner.x, owner.y),
3412 "maximized to fill the owner"
3413 );
3414
3415 // ZOOM = un-maximize through the SAME restore slot.
3416 with_ctx(&mut out, &mut timers, |ctx| {
3417 ctx.set_owner_size(owner);
3418 let mut ev = Event::Command(Command::ZOOM);
3419 w.handle_event(&mut ev, ctx);
3420 assert!(ev.is_nothing(), "cmZoom consumed");
3421 });
3422 assert!(!w.is_maximized(), "zoom un-maximized the window");
3423 assert_eq!(
3424 w.restore_rect(),
3425 None,
3426 "the single restore slot is consumed"
3427 );
3428 assert_eq!(
3429 w.state().get_bounds(),
3430 original,
3431 "restored to the pre-fullscreen bounds"
3432 );
3433 assert!(
3434 !w.bordered(),
3435 "zoom does not re-border: a coherent intentional borderless window"
3436 );
3437 }
3438
3439 // -- 17. frameless window: client_rect excludes bar lanes ------------------
3440
3441 /// A frameless 20×10 window with BOTH a vertical and a horizontal bar.
3442 /// `client_rect` must exclude the bar lanes; the bars must reach the window
3443 /// edges (with the appropriate corner stop for the companion bar).
3444 #[test]
3445 fn client_rect_excludes_scrollbar_lanes_when_frameless() {
3446 let w_sz = 20i32;
3447 let h_sz = 10i32;
3448 let ext = Rect::new(0, 0, w_sz, h_sz);
3449
3450 let mut win = Window::new(ext, Some("Test".to_string()), 0);
3451 win.bordered = false;
3452
3453 // Inject fake ids (minted via ViewId::next so they are valid NonZeroU64s
3454 // but not inserted into any group; client_rect / scroll_bar_rect only
3455 // test `.is_some()`, they never resolve).
3456 let fake_vsb = ViewId::next();
3457 let fake_hsb = ViewId::next();
3458 win.vsb_id = Some(fake_vsb);
3459 win.hsb_id = Some(fake_hsb);
3460
3461 // Content rect: full area minus the scroll-bar lanes.
3462 let cr = win.client_rect();
3463 assert_eq!(cr.a, Point::new(0, 0), "content starts at top-left");
3464 assert_eq!(
3465 cr.b,
3466 Point::new(w_sz - 1, h_sz - 1),
3467 "content excludes bar lanes (right column + bottom row)"
3468 );
3469
3470 // Vertical bar: right column, full height stopping above the h-bar corner.
3471 let vr = win.scroll_bar_rect(true);
3472 assert_eq!(vr.a, Point::new(w_sz - 1, 0), "v-bar starts at top-right");
3473 assert_eq!(vr.b, Point::new(w_sz, h_sz - 1), "v-bar stops above h-bar");
3474
3475 // Horizontal bar: bottom row, from left edge to just before the v-bar.
3476 let hr = win.scroll_bar_rect(false);
3477 assert_eq!(hr.a, Point::new(0, h_sz - 1), "h-bar starts at bottom-left");
3478 assert_eq!(hr.b, Point::new(w_sz - 1, h_sz), "h-bar stops before v-bar");
3479 }
3480}