Guide API
Skip to main content

tvision_rs/desktop/
desktop.rs

1//! `Desktop`, the group every window lives in (documented on the type).
2
3use crate::command::Command;
4use crate::event::Event;
5use crate::view::{Context, Group, Rect, View, ViewId, locate};
6
7use super::Background;
8
9// -- tiling geometry helpers: pure functions, no globals; the grid dimensions
10// (column count, row count, left-over column count) are threaded as parameters.
11
12/// Integer square-root-ish helper used by [`most_equal_divisors`] — a Newton-style
13/// loop that converges on `floor(sqrt(i))`.
14fn i_sqr(i: i32) -> i32 {
15    let mut res1 = 2;
16    let mut res2 = i / res1;
17    while (res1 - res2).abs() > 1 {
18        res1 = (res1 + res2) / 2;
19        res2 = i / res1;
20    }
21    if res1 < res2 { res1 } else { res2 }
22}
23
24/// Factor `n` into the most-equal pair of divisors. Returns `(x, y)` — the grid's
25/// column and row counts. `favor_y` puts the larger factor on `y`.
26fn most_equal_divisors(n: i32, favor_y: bool) -> (i32, i32) {
27    let mut i = i_sqr(n);
28    if n % i != 0 && n % (i + 1) == 0 {
29        i += 1;
30    }
31    if i < n / i {
32        i = n / i;
33    }
34    if favor_y {
35        (n / i, i) // x = n/i, y = i
36    } else {
37        (i, n / i) // x = i,   y = n/i
38    }
39}
40
41/// The `pos`-th of `num` evenly spaced divider coordinates between `lo` and `hi`.
42/// The product is computed in `i64` to avoid overflow, then truncated back to
43/// `i32`.
44fn divider_loc(lo: i32, hi: i32, num: i32, pos: i32) -> i32 {
45    ((hi - lo) as i64 * pos as i64 / num as i64) as i32 + lo
46}
47
48/// The cell rect for tile slot `pos` in the `num_cols × num_rows` grid (with
49/// `left_over` columns carrying an extra row).
50fn calc_tile_rect(pos: i32, r: Rect, num_cols: i32, num_rows: i32, left_over: i32) -> Rect {
51    let d = (num_cols - left_over) * num_rows;
52    let (x, y) = if pos < d {
53        (pos / num_rows, pos % num_rows)
54    } else {
55        (
56            (pos - d) / (num_rows + 1) + (num_cols - left_over),
57            (pos - d) % (num_rows + 1),
58        )
59    };
60    let mut n_rect = Rect::new(0, 0, 0, 0);
61    n_rect.a.x = divider_loc(r.a.x, r.b.x, num_cols, x);
62    n_rect.b.x = divider_loc(r.a.x, r.b.x, num_cols, x + 1);
63    if pos >= d {
64        n_rect.a.y = divider_loc(r.a.y, r.b.y, num_rows + 1, y);
65        n_rect.b.y = divider_loc(r.a.y, r.b.y, num_rows + 1, y + 1);
66    } else {
67        n_rect.a.y = divider_loc(r.a.y, r.b.y, num_rows, y);
68        n_rect.b.y = divider_loc(r.a.y, r.b.y, num_rows, y + 1);
69    }
70    n_rect
71}
72
73/// The default desktop background fill: **U+2591 ░ LIGHT SHADE** (the same shade
74/// family as the scrollbar glyphs in [`theme`](crate::theme)). Not `'▒'`
75/// (U+2592), which appears only in arbitrary test scaffolding.
76const DEFAULT_BKGRND: char = '\u{2591}';
77
78/// The desktop group: an embedded [`Group`] that owns a [`Background`].
79///
80/// A `Desktop` owns a [`Background`](crate::desktop::Background) fill and tiles
81/// or cascades the windows inserted into it. It gives
82/// [`Program`](crate::app::Program) a **named real desktop**, and it is the
83/// first exemplar of the **"a [`View`] that embeds a [`Group`] and delegates the
84/// whole trait"** pattern that [`Window`](crate::window::Window) also uses.
85///
86/// ## Window cycling and tiling
87///
88/// The [`Command::NEXT`]/[`Command::PREV`] commands cycle focus through the open
89/// windows (see [`Desktop::handle_event`]), and Alt-N selects a window by number
90/// via [`Desktop::select_window_num`]. [`tile`](Desktop::tile) and
91/// [`cascade`](Desktop::cascade) lay the windows out — a most-equal grid or an
92/// offset stack — driven by the program's tile/cascade handler. When a layout
93/// cannot fit (a cell would be zero-sized, or a window's minimum exceeds the
94/// cascade rect) the affected bounds are simply left unchanged.
95/// `tile_columns_first` selects the grid orientation (default: rows first).
96///
97/// Build with [`Desktop::new`] supplying a background factory (use
98/// [`Desktop::init_background`] for the faithful default), then drive it as any
99/// other [`View`].
100///
101/// # Turbo Vision heritage
102///
103/// Ports `TDeskTop` (`tdesktop.cpp`), which derived from the group class. That
104/// inheritance becomes an embedded [`Group`] the [`Desktop`] forwards every
105/// [`View`] method to (deviation D2); the background is recorded as a local
106/// [`ViewId`] rather than through an owner back-pointer (deviation D3); and the
107/// streaming machinery is dropped (deviation D12). There is no separate shutdown
108/// phase — the tree is simply dropped.
109pub struct Desktop {
110    /// The embedded container. The desktop *is-a* group: its state, draw, and
111    /// event routing are the group's.
112    group: Group,
113    /// The inserted background child's id.
114    ///
115    /// Consumed by the [`Command::PREV`] arm in
116    /// [`handle_event`](Self::handle_event), which reads `self.background` directly
117    /// to send the current window behind the background (i.e. to the back). Also
118    /// exposed via [`background`](Self::background).
119    background: Option<ViewId>,
120    /// Grid orientation flag read by [`tile`](Self::tile); `favor_y =
121    /// !tile_columns_first`. Defaults to `false` (rows first).
122    tile_columns_first: bool,
123}
124
125impl Desktop {
126    /// Construct the desktop.
127    ///
128    /// Steps:
129    /// 1. Create the embedded group over `bounds`.
130    /// 2. Set the grow mode to grow with both the right and bottom edges.
131    /// 3. Default `tile_columns_first` to `false` (read by [`tile`](Self::tile)).
132    /// 4. If `create_background` yields a view, insert it and record its id.
133    ///
134    /// The background factory is injected (mirroring
135    /// [`Program::new`](crate::app::Program::new)); pass [`Desktop::init_background`]
136    /// for the default. The factory receives the desktop's local-origin extent.
137    pub fn new(
138        bounds: Rect,
139        create_background: impl FnOnce(Rect) -> Option<Box<dyn View>>,
140    ) -> Self {
141        let mut group = Group::new(bounds);
142        // Grow with both the right and bottom edges of the owner.
143        group.state_mut().grow_mode.hi_x = true;
144        group.state_mut().grow_mode.hi_y = true;
145
146        let mut desktop = Desktop {
147            group,
148            background: None,
149            tile_columns_first: false,
150        };
151        // Build the background over the desktop extent and insert it.
152        let extent = desktop.group.state().get_extent();
153        if let Some(view) = create_background(extent) {
154            desktop.background = Some(desktop.group.insert(view));
155        }
156        desktop
157    }
158
159    /// The default background factory: a [`Background`] filled with the default
160    /// shade pattern.
161    pub fn init_background(r: Rect) -> Box<dyn View> {
162        Box::new(Background::new(r, DEFAULT_BKGRND))
163    }
164
165    /// The id of the background child inserted during construction, if any.
166    ///
167    /// Pass this to [`Group::put_in_front_of`](crate::view::Group::put_in_front_of)
168    /// (or equivalent) to send the current window behind the background, which is
169    /// exactly how [`Command::PREV`] cycles windows to the back. Returns `None`
170    /// only when the desktop was created without a background factory
171    /// (`create_background` returned `None`).
172    pub fn background(&self) -> Option<ViewId> {
173        self.background
174    }
175
176    /// Insert an arbitrary view (a window) directly into the embedded group,
177    /// returning its id — the production window-insert seam. Windows must live
178    /// *inside the desktop* because the next/previous-window and Alt-N handlers live
179    /// on it. Used by app code that pre-populates the desktop (see
180    /// `examples/hello.rs`).
181    pub fn insert_view(&mut self, view: Box<dyn View>) -> ViewId {
182        self.group.insert(view)
183    }
184
185    /// The embedded group's current (selected) child — test/inspection hook for
186    /// the A2 currency tests (the group field is module-private).
187    #[cfg(test)]
188    pub(crate) fn current_child(&self) -> Option<ViewId> {
189        self.group.current()
190    }
191
192    /// Insert `view` into the desktop and immediately focus it — the runtime
193    /// window-open seam used by `Program::desktop_insert`. Combines `insert_view`
194    /// with a `focus_child` call so the new window receives keyboard input at once.
195    ///
196    /// See [`Program::desktop_insert`](crate::app::Program::desktop_insert) for the
197    /// deliberate deviation from C++ `TGroup::insertView`'s `CanMoveFocus` guard.
198    pub fn insert_and_focus(
199        &mut self,
200        view: Box<dyn View>,
201        ctx: &mut crate::view::Context,
202    ) -> ViewId {
203        let id = self.group.insert(view);
204        // focus_child gives the window same-instant focus (its self-heal re-asserts
205        // currency when the freshly-inserted window is already topmost). The
206        // window's own INTERNAL currency (its first selectable child, e.g. an
207        // EditWindow's FileEditor) comes from the insert-time `currency_dirty`
208        // marker the `Group::insert` above set: the pump's settle_currency pass
209        // (A2) runs the pending reset_current BEFORE the next event pick, so typing
210        // routes into the new window's child immediately. (The explicit pre-focus
211        // reset_current that used to live here was that cascade's per-site
212        // compensation; retired by A2.)
213        self.group.focus_child(id, ctx);
214        id
215    }
216}
217
218#[crate::delegate(to = group, skip(value, set_value, number, grabs_focus_on_click, apply_scroll_sync))]
219impl View for Desktop {
220    /// Concrete-reach hatch used by `Program::desktop_insert` to downcast
221    /// `&mut dyn View` → `&mut Desktop` and call `insert_and_focus`.
222    fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
223        Some(self)
224    }
225
226    /// Lets the embedded group route the event, then handles the desktop's own
227    /// window cycling: [`Command::NEXT`] focuses the next window and
228    /// [`Command::PREV`] sends the current window to the back (exposing the one
229    /// behind it). Both first check that the focused window will release focus, and
230    /// both consume the command afterward; any other command is left untouched.
231    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
232        self.group.handle_event(ev, ctx);
233        if let Event::Command(cmd) = *ev {
234            match cmd {
235                Command::NEXT => {
236                    if self.group.valid(Command::RELEASED_FOCUS, ctx) {
237                        // Focus the next window (raising any always-on-top window).
238                        // The outgoing validation is already gated by valid() above.
239                        self.group.focus_next(false, ctx);
240                    }
241                    // Consume even when !valid: the guard wraps only the *action*.
242                    ev.clear();
243                }
244                Command::PREV => {
245                    if self.group.valid(Command::RELEASED_FOCUS, ctx)
246                        && let Some(cur) = self.group.current()
247                    {
248                        // Send the current window behind the background, exposing
249                        // the next window. NB: put_in_front_of's `target: None`
250                        // means TO-TOP (the inverse); pass the resolved
251                        // Some(background) so a future refactor cannot silently flip
252                        // this into a raise.
253                        self.group.put_in_front_of(cur, self.background, ctx);
254                    }
255                    ev.clear();
256                }
257                // No consume for other commands.
258                _ => {}
259            }
260        }
261    }
262
263    /// Select the desktop window numbered `num` (the Alt-N shortcut). Walks
264    /// directly into the embedded group (see [`Group::focus_by_number`]). The
265    /// program reaches this through the `select_window_num` trait method — **not**
266    /// an `as_any_mut` downcast — so it stays decoupled from the concrete `Desktop`
267    /// type.
268    fn select_window_num(&mut self, num: i16, ctx: &mut Context) -> bool {
269        self.group.focus_by_number(num, ctx)
270    }
271
272    /// Lay the tileable windows into a most-equal grid of cells over `r`.
273    ///
274    /// Factors the window count into the most-equal column/row grid, then assigns
275    /// each tileable window a cell. The first-visited (topmost) window takes the
276    /// highest-numbered slot. If a cell would be zero-width or zero-height the
277    /// layout is abandoned and bounds are left unchanged. `owner_size` is the
278    /// desktop size, fed to each child's size limits inside `locate`.
279    fn tile(&mut self, r: Rect) {
280        let ids = self.group.tileable_ids(); // visit order
281        let n = ids.len() as i32; // tileable window count
282        if n == 0 {
283            return;
284        }
285        let favor_y = !self.tile_columns_first;
286        let (num_cols, num_rows) = most_equal_divisors(n, favor_y);
287        // Fit guard: a cell would be zero-width or zero-height.
288        if (r.b.x - r.a.x) / num_cols == 0 || (r.b.y - r.a.y) / num_rows == 0 {
289            return;
290        }
291        let left_over = n % num_cols;
292        let owner_size = self.group.state().size;
293        let mut tile_num = n - 1; // FIRST visited gets the highest slot
294        for id in ids {
295            let rect = calc_tile_rect(tile_num, r, num_cols, num_rows, left_over);
296            if let Some(v) = self.group.child_mut(id) {
297                locate(v, rect, owner_size);
298            }
299            tile_num -= 1;
300        }
301        // The windows were re-bounded here, not by the group cascade: let the
302        // caller's `on_bounds_changed` reach them.
303        self.group.mark_bounds_dirty();
304    }
305
306    /// Stack the tileable windows, each offset one cell down-and-right from the
307    /// previous.
308    ///
309    /// The fit check uses the *last*-visited tileable window's minimum size against
310    /// the full window count `n`; if even the deepest offset cannot fit, the layout
311    /// is abandoned and bounds are left unchanged. Otherwise each window's top-left
312    /// is offset by a running counter, so the first-visited (topmost) window gets
313    /// the largest offset `n-1` and the last gets `0`.
314    fn cascade(&mut self, r: Rect) {
315        let ids = self.group.tileable_ids(); // visit order
316        let n = ids.len() as i32; // window count
317        if n == 0 {
318            return;
319        }
320        let owner_size = self.group.state().size;
321        // The last-visited tileable window; the fit check uses the full count n.
322        if let Some(&last_id) = ids.last() {
323            let (min, _max) = self
324                .group
325                .child_mut(last_id)
326                .expect("tileable id resolves")
327                .size_limits(owner_size);
328            if min.x > r.b.x - r.a.x - n || min.y > r.b.y - r.a.y - n {
329                return; // does not fit; leave bounds unchanged
330            }
331        }
332        let mut cascade_num = n - 1; // start the offset at n-1 (topmost deepest)
333        for id in ids {
334            if cascade_num >= 0 {
335                let mut nr = r;
336                nr.a.x += cascade_num;
337                nr.a.y += cascade_num;
338                if let Some(v) = self.group.child_mut(id) {
339                    locate(v, nr, owner_size);
340                }
341                cascade_num -= 1;
342            }
343        }
344        self.group.mark_bounds_dirty();
345    }
346}
347
348#[cfg(test)]
349mod tests {
350    use super::*;
351    use crate::backend::{HeadlessBackend, Renderer};
352    use crate::screen::Buffer;
353    use crate::theme::Theme;
354    use crate::view::{DrawCtx, Point, SelectMode};
355    use crate::window::{ScrollBarOptions, Window};
356    use std::collections::VecDeque;
357
358    /// Build a throwaway `Context` over loop-owned locals, run `f`, return its
359    /// value (the same harness shape the `group`/`window` test modules use).
360    fn with_ctx<R>(f: impl FnOnce(&mut Context) -> R) -> R {
361        let mut out: VecDeque<Event> = VecDeque::new();
362        let mut timers = crate::timer::TimerQueue::new();
363        let mut deferred: Vec<crate::view::Deferred> = Vec::new();
364        let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
365        f(&mut ctx)
366    }
367
368    // -- 1. ctor inserts background + records its id --------------------------
369
370    #[test]
371    fn new_inserts_background_and_records_id() {
372        let desktop = Desktop::new(Rect::new(0, 0, 10, 5), |r| {
373            Some(Desktop::init_background(r))
374        });
375        assert!(
376            desktop.background().is_some(),
377            "the default factory inserts a background and its id is recorded"
378        );
379        assert_eq!(desktop.group.len(), 1, "exactly one child (the background)");
380    }
381
382    // -- 2. grow mode = grow with right + bottom edges -----------------------
383
384    #[test]
385    fn new_sets_grow_hi_x_and_hi_y() {
386        let desktop = Desktop::new(Rect::new(0, 0, 10, 5), |r| {
387            Some(Desktop::init_background(r))
388        });
389        let gm = desktop.state().grow_mode;
390        assert!(gm.hi_x, "gfGrowHiX must be set");
391        assert!(gm.hi_y, "gfGrowHiY must be set");
392        // Others must stay clear.
393        assert!(!gm.lo_x);
394        assert!(!gm.lo_y);
395        assert!(!gm.rel);
396        assert!(!gm.fixed);
397    }
398
399    // -- 3. init_background fill char is ░ (U+2591) --------------------------
400
401    #[test]
402    fn init_background_fills_with_light_shade() {
403        let theme = Theme::classic_blue();
404        let mut bg = Desktop::init_background(Rect::new(0, 0, 4, 2));
405        let mut buf = Buffer::new(4, 2);
406        {
407            let bounds = bg.state().get_bounds();
408            let mut ctx = DrawCtx::new(&mut buf, &theme, bounds, bounds.a);
409            bg.draw(&mut ctx);
410        }
411        // Guards the faithfulness bug directly: must be U+2591 LIGHT SHADE.
412        assert_eq!(
413            buf.get(0, 0).symbol(),
414            "\u{2591}",
415            "default background fill is ░ U+2591 (CP437 0xB0), not ▒"
416        );
417        assert_eq!(buf.get(3, 1).symbol(), "\u{2591}");
418    }
419
420    // -- 4. no-background factory --------------------------------------------
421
422    #[test]
423    fn no_background_factory_leaves_group_empty() {
424        let mut desktop = Desktop::new(Rect::new(0, 0, 10, 5), |_| None);
425        assert_eq!(desktop.background(), None, "no id recorded");
426        assert!(desktop.group.is_empty(), "no children inserted");
427        // draw is a no-op (must not panic).
428        let theme = Theme::classic_blue();
429        let mut buf = Buffer::new(10, 5);
430        let bounds = desktop.state().get_bounds();
431        let mut ctx = DrawCtx::new(&mut buf, &theme, bounds, bounds.a);
432        desktop.draw(&mut ctx);
433    }
434
435    // -- 5. mandatory snapshot -----------------------------------------------
436
437    /// End-to-end snapshot: a `Desktop` (via the faithful `init_background`)
438    /// through the real `Renderer` + `HeadlessBackend`, drawn through
439    /// `&mut dyn View`. A full-area ░ fill.
440    #[test]
441    fn desktop_render_pipeline_snapshot() {
442        let theme = Theme::classic_blue();
443        let mut desktop: Box<dyn View> = Box::new(Desktop::new(Rect::new(0, 0, 8, 4), |r| {
444            Some(Desktop::init_background(r))
445        }));
446        let (backend, screen) = HeadlessBackend::new(8, 4);
447        let mut r = Renderer::new(Box::new(backend));
448        r.render(|buf: &mut Buffer| {
449            let bounds = desktop.state().get_bounds();
450            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
451            desktop.draw(&mut dc);
452        });
453        insta::assert_snapshot!(screen.snapshot());
454    }
455
456    /// Shadow pass: a `Window` (which casts a shadow) inserted over the ░
457    /// desktop background casts the offset-L drop shadow — 2 columns right
458    /// (screen rows 2..5: one below the top edge to one past the bottom) + 1 row below
459    /// (columns 3..10: starting 2 right of the left edge). The shadow cells keep
460    /// their ░ glyph and take the theme's `Role::Shadow` attribute (+no_shadow).
461    #[test]
462    fn window_over_desktop_casts_shadow_snapshot() {
463        let theme = Theme::classic_blue();
464        let mut desktop = Desktop::new(Rect::new(0, 0, 16, 7), |r| {
465            Some(Desktop::init_background(r))
466        });
467        desktop.insert_view(Box::new(Window::new(
468            Rect::new(1, 1, 10, 4),
469            Some("W".into()),
470            1,
471        )));
472        let mut desktop: Box<dyn View> = Box::new(desktop);
473        let (backend, screen) = HeadlessBackend::new(16, 7);
474        let mut r = Renderer::new(Box::new(backend));
475        r.render(|buf: &mut Buffer| {
476            let bounds = desktop.state().get_bounds();
477            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
478            desktop.draw(&mut dc);
479        });
480        insta::assert_snapshot!(screen.snapshot());
481    }
482
483    // -- 6. resize delegates to the group ------------------------------------
484
485    #[test]
486    fn change_bounds_delegates_and_grows_background() {
487        let mut desktop = Desktop::new(Rect::new(0, 0, 20, 10), |r| {
488            Some(Desktop::init_background(r))
489        });
490        // Background was inserted at the desktop's local extent (0,0,20,10) and
491        // grows with the right + bottom edges, so its far edges track the desktop.
492        View::change_bounds(&mut desktop, Rect::new(0, 0, 25, 13)); // UFCS: disambiguate the trait method
493        let child_bounds = desktop.group.child_state_mut(0).get_bounds();
494        assert_eq!(
495            child_bounds,
496            Rect::new(0, 0, 25, 13),
497            "the background grew with the desktop (delegation to Group::change_bounds works)"
498        );
499    }
500
501    // -- 7. tree-walk resolvers through the embedders ------------------------
502
503    /// Build `Desktop` → `Window` → probe (a standard scroll bar) and return the
504    /// desktop plus the window/probe ids. The desktop's `group` is reachable here
505    /// (same module); the window's probe is its scroll bar. The window is made the
506    /// desktop's `current` child so a later removal's `reset_current` is
507    /// observable.
508    fn nested_desktop() -> (Desktop, ViewId, ViewId) {
509        let mut window = Window::new(Rect::new(2, 1, 30, 12), Some("W".into()), 1);
510        let probe_id = window.standard_scroll_bar(ScrollBarOptions {
511            vertical: true,
512            ..Default::default()
513        });
514
515        // Desktop owning the window. Reach the private group directly (same
516        // module) since Desktop exposes no public arbitrary-child insert.
517        let mut desktop = Desktop::new(Rect::new(0, 0, 80, 25), |_| None);
518        let window_id = desktop.group.insert(Box::new(window));
519        with_ctx(|ctx| {
520            desktop
521                .group
522                .set_current(Some(window_id), SelectMode::Normal, ctx)
523        });
524
525        (desktop, window_id, probe_id)
526    }
527
528    #[test]
529    fn find_mut_resolves_through_desktop_and_window() {
530        let (desktop, window_id, probe_id) = nested_desktop();
531        // Wrap the desktop in a plain root group to prove the walk descends
532        // through *both* embedders (root Group -> Desktop -> Window -> group).
533        let mut root = Group::new(Rect::new(0, 0, 80, 25));
534        root.insert(Box::new(desktop));
535
536        // The deeply-nested probe resolves through Desktop -> Window -> group.
537        {
538            let v = root
539                .find_mut(probe_id)
540                .expect("probe resolves through the embedders");
541            v.state_mut().set_cursor(7, 8); // mutate a field through the reference
542        }
543        assert_eq!(
544            root.find_mut(probe_id)
545                .expect("probe resolves")
546                .state()
547                .cursor,
548            Point::new(7, 8),
549            "mutation through the nested find_mut is observed"
550        );
551
552        // The window itself resolves (it is a direct child of the desktop group).
553        assert!(
554            root.find_mut(window_id).is_some(),
555            "the window resolves through the desktop"
556        );
557
558        // A never-inserted id resolves to None.
559        let bogus = ViewId::next();
560        assert!(root.find_mut(bogus).is_none(), "unknown id -> None");
561    }
562
563    /// `remove_descendant` recurses into a child group and removes a grandchild.
564    ///
565    /// The probe is NOT a direct child of the desktop group, so the direct-child
566    /// check fails and the implementation must recurse into the window group —
567    /// exercising the `for child … remove_descendant … return true` branch.
568    #[test]
569    fn remove_descendant_recurses_into_child_group_for_grandchild() {
570        let (mut desktop, window_id, probe_id) = nested_desktop();
571
572        // Remove the probe — it is a child of the window, not of the desktop group.
573        let removed = with_ctx(|ctx| desktop.remove_descendant(probe_id, ctx));
574        assert!(removed, "recursion-success branch returns true");
575
576        // The probe is gone.
577        assert!(
578            desktop.find_mut(probe_id).is_none(),
579            "probe is no longer reachable"
580        );
581        // The window itself is still present.
582        assert!(
583            desktop.find_mut(window_id).is_some(),
584            "the window that owned the probe is still present"
585        );
586    }
587
588    // -- tiling geometry -----------------------------------------------------
589
590    /// A visible, tileable window with number `n` at `bounds`.
591    fn tileable_window(bounds: Rect, n: i16) -> Box<dyn View> {
592        let mut w = Window::new(bounds, Some("W".into()), n);
593        w.state_mut().options.tileable = true;
594        Box::new(w)
595    }
596
597    /// Read a child's current bounds by id (same-module access to the group).
598    fn child_bounds(desktop: &mut Desktop, id: ViewId) -> Rect {
599        desktop.group.child_mut(id).unwrap().state().get_bounds()
600    }
601
602    /// `most_equal_divisors` swaps `(x, y)` on the `favor_y` flag. For a
603    /// non-square `n` the two orientations differ, so this pins the otherwise
604    /// uncovered `favor_y == false` branch (the `tile_columns_first == true` path).
605    ///
606    /// Hand-traced for `n = 6`: `i_sqr(6)` → 2 → `i = 2`; `6 % 2 == 0` (no `+1`);
607    /// `2 < 6/2 == 3` → `i = 3`. Then `favor_y` → `(x, y) = (n/i, i) = (2, 3)`;
608    /// `!favor_y` → `(x, y) = (i, n/i) = (3, 2)`.
609    #[test]
610    fn most_equal_divisors_swaps_on_favor_y() {
611        // favor_y == true (tile_columns_first == false): larger factor on y.
612        assert_eq!(most_equal_divisors(6, true), (2, 3));
613        // favor_y == false (tile_columns_first == true): larger factor on x — swapped.
614        assert_eq!(most_equal_divisors(6, false), (3, 2));
615    }
616
617    /// Test 1 — tile lays N windows into `calc_tile_rect` cells, in visit order.
618    /// Bite: the topmost (last-inserted) window must take `tile_num = n-1`; an
619    /// off-by-one or reversed order lands a window in the wrong cell.
620    #[test]
621    fn tile_lays_windows_into_calc_tile_cells() {
622        let mut desktop = Desktop::new(Rect::new(0, 0, 80, 24), |_| None);
623        // Insert first→last; ids[0] in visit order == the LAST inserted (topmost).
624        let w0 = desktop.insert_view(tileable_window(Rect::new(1, 1, 20, 8), 1));
625        let w1 = desktop.insert_view(tileable_window(Rect::new(2, 2, 21, 9), 2));
626        let w2 = desktop.insert_view(tileable_window(Rect::new(3, 3, 22, 10), 3));
627
628        desktop.tile(Rect::new(0, 0, 80, 24));
629
630        // n=3, favor_y=true → num_cols=1, num_rows=3 → 3 stacked cells.
631        // visit order = [w2, w1, w0]; tile_num = 2,1,0.
632        assert_eq!(
633            child_bounds(&mut desktop, w2),
634            Rect::new(0, 16, 80, 24),
635            "topmost (last-inserted) window gets tile_num n-1 = 2 → bottom cell"
636        );
637        assert_eq!(
638            child_bounds(&mut desktop, w1),
639            Rect::new(0, 8, 80, 16),
640            "middle window gets tile_num 1 → middle cell"
641        );
642        assert_eq!(
643            child_bounds(&mut desktop, w0),
644            Rect::new(0, 0, 80, 8),
645            "first-inserted window gets tile_num 0 → top cell"
646        );
647    }
648
649    /// Test 2 — non-tileable and invisible children are skipped; tileable still
650    /// lay out. Bite: if the filter were dropped, the non-tileable/invisible window
651    /// would move and/or n would be wrong, shifting the tileable cells.
652    #[test]
653    fn tile_skips_non_tileable_and_invisible() {
654        let mut desktop = Desktop::new(Rect::new(0, 0, 80, 24), |_| None);
655        // A plain (non-tileable) window.
656        let plain_bounds = Rect::new(1, 1, 30, 12);
657        let plain = desktop.insert_view(Box::new(Window::new(plain_bounds, Some("P".into()), 1)));
658        // An invisible-but-tileable window.
659        let mut inv = Window::new(Rect::new(2, 2, 31, 13), Some("I".into()), 2);
660        inv.state_mut().options.tileable = true;
661        inv.state_mut().state.visible = false;
662        let inv_bounds = inv.state().get_bounds();
663        let inv_id = desktop.insert_view(Box::new(inv));
664        // Two genuine tileable windows.
665        let a = desktop.insert_view(tileable_window(Rect::new(3, 3, 20, 9), 3));
666        let b = desktop.insert_view(tileable_window(Rect::new(4, 4, 21, 10), 4));
667
668        desktop.tile(Rect::new(0, 0, 80, 24));
669
670        // The non-tileable + invisible windows must NOT move.
671        assert_eq!(
672            child_bounds(&mut desktop, plain),
673            plain_bounds,
674            "non-tileable window untouched"
675        );
676        assert_eq!(
677            child_bounds(&mut desktop, inv_id),
678            inv_bounds,
679            "invisible window untouched"
680        );
681        // n=2 → num_cols=1, num_rows=2 → 2 stacked cells. visit [b, a]; tile_num 1,0.
682        assert_eq!(
683            child_bounds(&mut desktop, b),
684            Rect::new(0, 12, 80, 24),
685            "topmost tileable → tile_num 1 → bottom half"
686        );
687        assert_eq!(
688            child_bounds(&mut desktop, a),
689            Rect::new(0, 0, 80, 12),
690            "other tileable → tile_num 0 → top half"
691        );
692    }
693
694    /// Test 3 — the fit guard (a cell would be zero-width/height) leaves bounds
695    /// unchanged. Bite: without the guard, `divider_loc`/`locate` would still run
696    /// and (after the 16×6 clamp) move the windows.
697    #[test]
698    fn tile_error_guard_leaves_bounds_unchanged() {
699        // Desktop 0,0,2,24: with n=3 → num_cols=1, num_rows=3, (2-0)/1=2 ok but
700        // make it too narrow: width 0 is impossible; use a rect whose width/cols == 0.
701        // n=2 → num_cols=1,num_rows=2; rect width 0 → (0)/1 == 0 → guard trips.
702        let mut desktop = Desktop::new(Rect::new(0, 0, 80, 24), |_| None);
703        let a_bounds = Rect::new(1, 1, 20, 9);
704        let b_bounds = Rect::new(2, 2, 21, 10);
705        let a = desktop.insert_view(tileable_window(a_bounds, 1));
706        let b = desktop.insert_view(tileable_window(b_bounds, 2));
707
708        // Zero-width layout rect → (r.b.x - r.a.x)/num_cols == 0 → guard trips, no-op.
709        desktop.tile(Rect::new(5, 0, 5, 24));
710
711        assert_eq!(child_bounds(&mut desktop, a), a_bounds, "a unchanged");
712        assert_eq!(child_bounds(&mut desktop, b), b_bounds, "b unchanged");
713    }
714
715    /// Test 4 — cascade offsets run `n-1 … 0`: topmost (last-inserted, `ids[0]`)
716    /// gets `a == r.a + (n-1)`; the bottom (first-inserted) gets `a == r.a + 0`.
717    /// Bite: this assertion flips if visit order or the `n-1` start is wrong.
718    #[test]
719    fn cascade_offsets_run_n_minus_1_down_to_0() {
720        let mut desktop = Desktop::new(Rect::new(0, 0, 80, 24), |_| None);
721        let bottom = desktop.insert_view(tileable_window(Rect::new(1, 1, 40, 12), 1));
722        let _mid = desktop.insert_view(tileable_window(Rect::new(2, 2, 41, 13), 2));
723        let top = desktop.insert_view(tileable_window(Rect::new(3, 3, 42, 14), 3));
724
725        let r = Rect::new(0, 0, 80, 24);
726        desktop.cascade(r);
727
728        // n=3 → offsets 2,1,0 in visit order [top, mid, bottom].
729        let top_b = child_bounds(&mut desktop, top);
730        assert_eq!(top_b.a, Point::new(2, 2), "topmost gets r.a + (n-1) = +2");
731        let bottom_b = child_bounds(&mut desktop, bottom);
732        assert_eq!(bottom_b.a, Point::new(0, 0), "bottom gets r.a + 0");
733    }
734
735    /// Test 5 — cascade sub-minimum guard subtracts the FULL count `n` (not `n-1`).
736    /// Bite: desktop width = min.x + n - 1 trips the correct `min.x > w - n` check
737    /// (16 > 17-2) but would NOT trip a buggy `min.x > w - (n-1)` (16 > 17-1 false);
738    /// windows must not move.
739    #[test]
740    fn cascade_sub_minimum_guard_uses_full_count() {
741        // Window min is 16×6. n=2, desktop width = 16 + 2 - 1 = 17.
742        let mut desktop = Desktop::new(Rect::new(0, 0, 17, 24), |_| None);
743        let a_bounds = Rect::new(0, 0, 16, 6);
744        let b_bounds = Rect::new(1, 1, 17, 7);
745        let a = desktop.insert_view(tileable_window(a_bounds, 1));
746        let b = desktop.insert_view(tileable_window(b_bounds, 2));
747
748        // r width 17: min.x(16) > 17 - n(2) == 15 → guard trips → no-op.
749        desktop.cascade(Rect::new(0, 0, 17, 24));
750
751        assert_eq!(
752            child_bounds(&mut desktop, a),
753            a_bounds,
754            "a unchanged (guard)"
755        );
756        assert_eq!(
757            child_bounds(&mut desktop, b),
758            b_bounds,
759            "b unchanged (guard)"
760        );
761    }
762
763    #[test]
764    fn remove_descendant_removes_through_embedders_and_resets_current() {
765        // Operate on the Desktop directly (its `remove_descendant` delegates to
766        // the group), so the owning desktop group's `current` is readable here.
767        let (mut desktop, window_id, probe_id) = nested_desktop();
768        assert_eq!(
769            desktop.group.current(),
770            Some(window_id),
771            "window is current"
772        );
773
774        // Bogus id: false, nothing changes.
775        let removed_bogus = with_ctx(|ctx| desktop.remove_descendant(ViewId::next(), ctx));
776        assert!(!removed_bogus, "unknown id -> false");
777        assert!(
778            desktop.find_mut(window_id).is_some(),
779            "window still present"
780        );
781
782        // Remove the window (a child of the desktop group, reached via the
783        // Desktop delegate). reset_current runs: no other selectable child
784        // remains, so current becomes None.
785        let removed = with_ctx(|ctx| desktop.remove_descendant(window_id, ctx));
786        assert!(removed, "nested removal -> true");
787        assert!(desktop.find_mut(window_id).is_none(), "window gone");
788        assert!(
789            desktop.find_mut(probe_id).is_none(),
790            "the window's child is gone with it"
791        );
792        assert_eq!(
793            desktop.group.current(),
794            None,
795            "reset_current ran on the owning desktop group"
796        );
797    }
798
799    /// A2 delegation: `settle_currency` forwards through the `#[delegate]`
800    /// chain Desktop → Window → inner group (the specs.rs forwarder). A missing
801    /// forwarder would leave an embedder on the no-op trait default and the
802    /// settle would silently never descend — this is the spy the CLAUDE.md
803    /// delegation convention demands for a new `View` method.
804    #[test]
805    fn settle_currency_descends_desktop_window_inner_group() {
806        use crate::widgets::{Button, ButtonFlags};
807
808        let mut window = Window::new(Rect::new(2, 1, 30, 12), Some("W".into()), 1);
809        // A selectable child in the WINDOW's inner group (buttons are selectable).
810        let child_id = window.insert_child(Box::new(Button::new(
811            Rect::new(2, 2, 12, 4),
812            "OK",
813            crate::command::Command::OK,
814            ButtonFlags::new(),
815        )));
816        let mut desktop = Desktop::new(Rect::new(0, 0, 80, 25), |_| None);
817        let window_id = desktop.group.insert(Box::new(window));
818
819        // Plain ctx-less inserts only — currency is fully unsettled.
820        assert_eq!(desktop.group.current(), None, "nothing settled yet");
821
822        with_ctx(|ctx| {
823            let v: &mut dyn View = &mut desktop;
824            v.settle_currency(ctx);
825        });
826
827        assert_eq!(
828            desktop.group.current(),
829            Some(window_id),
830            "the desktop group's own pending reset settled (window current)"
831        );
832        let child_selected = desktop
833            .find_mut(child_id)
834            .map(|v| v.state().state.selected)
835            .expect("child resolves");
836        assert!(
837            child_selected,
838            "the settle DESCENDED through Desktop → Window → inner group \
839             (the child was made current/selected by the window's settled reset)"
840        );
841    }
842}