Guide API
Skip to main content

tvision_rs/
frame.rs

1//! The decorative border [`Frame`] a [`Window`](crate::window::Window) places
2//! around its interior: the box, the centered title, the optional window
3//! number, and the close / zoom / resize icons. It is a passive view — it
4//! never takes focus.
5//!
6//! # How a frame gets its data
7//!
8//! A frame never reaches up into the window that owns it. Instead, [`Frame`]
9//! holds its **own copy** of exactly the data it renders, pushed **down** by the
10//! owning window through public setters:
11//!
12//! * [`title`](Frame::title) — the window title
13//! * [`flags`](Frame::flags) — the window decoration flags ([`WindowFlags`])
14//! * [`number`](Frame::number) — the window number (none → not drawn)
15//! * [`zoomed`](Frame::zoomed) — whether the window is maximized (drives the
16//!   zoom-vs-unzoom icon)
17//! * [`palette`](Frame::palette) — the owner's colour scheme
18//!   ([`WindowPalette`]), which selects the border
19//!   and icon roles: `Blue` → [`Role::FrameActive`] / [`Role::FramePassive`] /
20//!   [`Role::FrameDragging`] / [`Role::FrameIcon`]; `Cyan` → the
21//!   `Role::FrameCyan*` family; `Gray` (dialogs) → the `Role::FrameGray*`
22//!   family.
23//!
24//! The window calls these setters whenever its own state changes. The frame's
25//! active / dragging state instead arrives through the normal
26//! [`View::set_state`] propagation that [`Group`](crate::view::Group) drives
27//! onto every child, so [`Frame::draw`] reads it from its own state directly.
28//!
29//! # Drag, resize, and close
30//!
31//! The frame deliberately leaves window-drag `MouseDown` events (title-bar move,
32//! bottom-corner resize, middle-button move) unconsumed so they fall through to
33//! the owning [`Window`](crate::window::Window), which runs the drag. The close
34//! icon, by contrast, is handled here: pressing it arms a press-and-hold
35//! [`MouseTrackCapture`](crate::capture::MouseTrackCapture) and posts
36//! [`Command::CLOSE`](crate::Command::CLOSE) only if the button is released back
37//! over the close zone.
38//!
39//! **Guide:** [Windows & the desktop](../../../apps/windows.html).
40//!
41//! # Turbo Vision heritage
42//!
43//! Ports `TFrame` (`tframe.cpp` / `framelin.cpp`). The original frame's draw and
44//! event handling reached up through the owner into the window; tvision-rs instead
45//! pushes the needed data down from the window (deviation D3). Inheritance becomes
46//! the [`View`] trait plus [`ViewState`] composition (deviation D2), the frame
47//! flag word becomes [`WindowFlags`] (deviation D5), and palette lookups become
48//! [`Role`]-keyed theme styles (deviation D7).
49//!
50//! The classic sibling tee-walk (`TFrame::frameLine` reaching sideways to read
51//! its siblings' bounds) is **not** reproduced as a sideways walk — deviation D3
52//! forbids a child reaching its siblings. Instead, a window that hosts a joined
53//! [`Splitter`](crate::widgets::Splitter) (opted in via
54//! [`Splitter::joined`](crate::widgets::Splitter::joined)) auto-brokers: it
55//! computes the divider abutments from its `Splitter` child and pushes them
56//! **down** to this frame as
57//! [`JunctionMark`]s via
58//! `set_junction_marks`; the frame then substitutes
59//! the matching tee glyph at each marked edge cell — the same visual result as
60//! `frameLine`, fed by pushed data. A frame with no marks (every window without a
61//! joined splitter) draws plain corners and edges, exactly as before.
62
63use crate::capture::TrackMask;
64use crate::command::Command;
65use crate::event::Event;
66use crate::junction::{Edge, JunctionMark, Weight, frame_junction};
67use crate::theme::Role;
68use crate::view::{Context, DrawCtx, GrowMode, Point, Rect, View, ViewState};
69use crate::window::{WindowFlags, WindowPalette};
70
71// ---------------------------------------------------------------------------
72// Frame
73// ---------------------------------------------------------------------------
74
75/// A window's decorative border: box, title, number, and close/zoom/resize
76/// icons.
77///
78/// Embeds `st: ViewState` and `impl View`, draws through [`DrawCtx`], and
79/// handles events through [`Context`]. The window-owned data it renders
80/// (title / flags / number / zoomed) is pushed down by the owning
81/// [`Window`](crate::window::Window) through the public setters; see the module
82/// docs.
83pub struct Frame {
84    /// View state (geometry, flags, etc.).
85    pub st: ViewState,
86    /// The window title, pushed down by the owning window.
87    title: Option<String>,
88    /// The window decoration flags, pushed down by the owning window.
89    flags: WindowFlags,
90    /// The window number (none → not drawn); drawn only if `Some(n)` and
91    /// `n < 10`. Pushed down by the owning window.
92    number: Option<u8>,
93    /// Whether the window is maximized — drives the zoom-vs-unzoom icon choice.
94    /// Pushed down by the owning window.
95    zoomed: bool,
96    /// The owner's colour scheme, pushed down by the owning window. Selects the
97    /// `Role::Frame*` vs `Role::FrameGray*` family in [`draw`](View::draw).
98    palette: WindowPalette,
99    /// Absolute screen position of view-local `(0, 0)`, cached each `draw` so
100    /// the close-icon mouse-tracking capture can convert absolute mouse coords
101    /// to view-local.
102    abs_origin: Point,
103    /// Whether the close-icon press-and-hold track is in flight. Guarded
104    /// against stray `MouseUp` events.
105    close_pressed: bool,
106    /// Divider abutment marks pushed down by the owning window each draw
107    /// (owner-data-down). Empty = today's plain frame, so non-joined windows are
108    /// byte-for-byte unchanged. See [`set_junction_marks`](Frame::set_junction_marks).
109    junction_marks: Vec<JunctionMark>,
110    /// Whether to draw the border box, title, and icons. `false` for a borderless
111    /// window — the interior background fill stays unconditional, but every
112    /// edge/title/icon is suppressed. Pushed down by the owning window like
113    /// [`zoomed`]. See [`set_border_visible`](Frame::set_border_visible).
114    border_visible: bool,
115}
116
117impl Frame {
118    /// Construct a frame sized to `bounds`.
119    ///
120    /// Normally called only by [`Window::new`](crate::window::Window::new), which
121    /// creates the frame, inserts it as its first child, and then pushes title /
122    /// flags / number / palette down through the owner-data setters. App code that
123    /// subclasses `Window` (by wrapping it and overriding behaviour) does not
124    /// construct a `Frame` directly — the window handles that internally.
125    ///
126    /// The grow mode is set so the frame stretches with its owner on the right and
127    /// bottom edges (`hi_x` + `hi_y`). The frame is **not** selectable (it never
128    /// takes focus). Broadcast and mouse-up events are delivered unconditionally.
129    pub fn new(bounds: Rect) -> Self {
130        let mut st = ViewState::new(bounds);
131        st.grow_mode = GrowMode {
132            hi_x: true,
133            hi_y: true,
134            ..Default::default()
135        };
136        Frame {
137            st,
138            title: None,
139            flags: WindowFlags::default(),
140            number: None,
141            zoomed: false,
142            palette: WindowPalette::Blue,
143            abs_origin: Point::new(0, 0),
144            close_pressed: false,
145            junction_marks: Vec::new(),
146            border_visible: true,
147        }
148    }
149
150    // -- Owner-data-down setters / getters -----------------------------------
151
152    /// Set the window title (pushed down by the owning window).
153    pub fn set_title(&mut self, title: Option<String>) {
154        self.title = title;
155    }
156
157    /// The window title.
158    pub fn title(&self) -> Option<&str> {
159        self.title.as_deref()
160    }
161
162    /// Set the window decoration flags (pushed down by the owning window).
163    pub fn set_flags(&mut self, flags: WindowFlags) {
164        self.flags = flags;
165    }
166
167    /// The window decoration flags.
168    pub fn flags(&self) -> WindowFlags {
169        self.flags
170    }
171
172    /// Set the window number (pushed down by the owning window; none → not drawn).
173    pub fn set_number(&mut self, number: Option<u8>) {
174        self.number = number;
175    }
176
177    /// The window number.
178    pub fn number(&self) -> Option<u8> {
179        self.number
180    }
181
182    /// Set whether the window is maximized (drives the unZoom-vs-zoom icon).
183    pub fn set_zoomed(&mut self, zoomed: bool) {
184        self.zoomed = zoomed;
185    }
186
187    /// Whether the window is maximized.
188    pub fn zoomed(&self) -> bool {
189        self.zoomed
190    }
191
192    /// Show or hide the border box, title, and icons (the interior fill is
193    /// unaffected). The owning [`Window`](crate::window::Window) pushes this from
194    /// its independent `set_bordered` primitive, via the same `child_mut` +
195    /// downcast seam as [`set_zoomed`](Frame::set_zoomed).
196    pub(crate) fn set_border_visible(&mut self, v: bool) {
197        self.border_visible = v;
198    }
199
200    /// Set the owner's colour scheme (pushed down by the owning window).
201    /// [`draw`](View::draw) selects the matching role family:
202    /// `Blue` → `Role::Frame*`, `Cyan` → `Role::FrameCyan*`,
203    /// `Gray` → `Role::FrameGray*`.
204    pub(crate) fn set_palette(&mut self, palette: WindowPalette) {
205        self.palette = palette;
206    }
207
208    /// The owner's colour scheme, which selects the border-role family used
209    /// during [`draw`](View::draw).
210    ///
211    /// `Blue` selects `Role::Frame*` (classic window), `Cyan` selects
212    /// `Role::FrameCyan*`, and `Gray` selects `Role::FrameGray*` (dialogs).
213    /// Reading this value is rarely needed by callers; it is mainly a getter
214    /// companion for the `pub(crate)` `set_palette` that the owning window calls
215    /// when it changes colour scheme.
216    pub fn palette(&self) -> WindowPalette {
217        self.palette
218    }
219
220    /// Owner-data-down: the owning window pushes the divider abutment marks the
221    /// frame should join into its border. Replaced each draw; empty = a plain
222    /// frame (non-joined windows unchanged). Faithful re-expression of TV's
223    /// `frameLine` tee-walk, fed by pushed data instead of a sideways sibling walk.
224    ///
225    /// Called by `Window::draw` when the window opts into joined lines.
226    pub(crate) fn set_junction_marks(&mut self, marks: Vec<JunctionMark>) {
227        self.junction_marks = marks;
228    }
229
230    /// The junction glyph to substitute at an **interior** border cell on `edge`
231    /// at `offset`, if a mark lands there; `None` to keep the plain edge glyph.
232    /// `bar` is the frame's own weight. Callers only invoke this on interior edge
233    /// cells, so corner offsets never reach here — the corner guard is structural
234    /// (the draw loops skip the corners).
235    fn junction_at(
236        &self,
237        edge: Edge,
238        offset: i32,
239        bar: Weight,
240        g: &crate::theme::Glyphs,
241    ) -> Option<char> {
242        self.junction_marks
243            .iter()
244            .find(|m| m.edge == edge && m.offset == offset)
245            .map(|m| frame_junction(edge, bar, m.stem, g))
246    }
247}
248
249impl View for Frame {
250    fn state(&self) -> &ViewState {
251        &self.st
252    }
253
254    fn state_mut(&mut self) -> &mut ViewState {
255        &mut self.st
256    }
257
258    /// Paint the border, title, number and icons.
259    ///
260    /// State selection checks `dragging` first, then `!active`, else `active`; the
261    /// role family follows the owner's [`WindowPalette`] (blue family shown; `Gray`
262    /// substitutes `FrameGray*`):
263    ///
264    /// | state    | border role     | line set    |
265    /// |----------|-----------------|-------------|
266    /// | dragging | `FrameDragging` | single      |
267    /// | passive  | `FramePassive`  | single      |
268    /// | active   | `FrameActive`   | double      |
269    ///
270    /// We draw the box fully first, then overlay the number / title / icons onto
271    /// the top row (and the resize icons onto the bottom row).
272    ///
273    /// Marked interior edge cells get a junction tee (owner-data-down via
274    /// `set_junction_marks`); with no marks the corners/edges are plain. See the
275    /// module docs.
276    fn draw(&mut self, ctx: &mut DrawCtx) {
277        // Cache the absolute origin for the close-icon mouse-tracking capture:
278        // the MouseTrackCapture converts absolute mouse coords to view-local
279        // via this value.
280        self.abs_origin = ctx.origin();
281
282        let glyphs = *ctx.glyphs();
283        let w = self.st.size.x;
284        let h = self.st.size.y;
285        if w <= 0 || h <= 0 {
286            return;
287        }
288
289        // -- Palette → role family (selected by the owner's window palette:
290        // blue window vs cyan window vs gray dialog).
291        let (r_dragging, r_passive, r_active, r_icon) = match self.palette {
292            WindowPalette::Blue => (
293                Role::FrameDragging,
294                Role::FramePassive,
295                Role::FrameActive,
296                Role::FrameIcon,
297            ),
298            WindowPalette::Cyan => (
299                Role::FrameCyanDragging,
300                Role::FrameCyanPassive,
301                Role::FrameCyanActive,
302                Role::FrameCyanIcon,
303            ),
304            WindowPalette::Gray => (
305                Role::FrameGrayDragging,
306                Role::FrameGrayPassive,
307                Role::FrameGrayActive,
308                Role::FrameGrayIcon,
309            ),
310        };
311
312        // -- State → (border role, double-line) -- check dragging first.
313        let (border_role, double) = if self.st.state.dragging {
314            (r_dragging, false)
315        } else if !self.st.state.active {
316            (r_passive, false)
317        } else {
318            (r_active, true)
319        };
320        let bar = if double {
321            Weight::Double
322        } else {
323            Weight::Single
324        };
325        let border = ctx.style(border_role);
326        let icon = ctx.style(r_icon);
327
328        // Pick the single- or double-line box glyphs.
329        let (tl, tr, bl, br, h_edge, v_edge) = if double {
330            (
331                glyphs.frame_tl_d,
332                glyphs.frame_tr_d,
333                glyphs.frame_bl_d,
334                glyphs.frame_br_d,
335                glyphs.frame_h_d,
336                glyphs.frame_v_d,
337            )
338        } else {
339            (
340                glyphs.frame_tl,
341                glyphs.frame_tr,
342                glyphs.frame_bl,
343                glyphs.frame_br,
344                glyphs.frame_h,
345                glyphs.frame_v,
346            )
347        };
348
349        // -- 1a. Interior background fill (UNCONDITIONAL — a frameless window still
350        // paints its body; content overdraws this). Same `border` role that paints
351        // a bordered window's interior.
352        for y in 1..h - 1 {
353            for x in 1..w - 1 {
354                ctx.put_char(x, y, ' ', border);
355            }
356        }
357
358        // -- 1b..6. Border box, title, number, and icons — only when bordered.
359        if self.border_visible {
360            // Top row: tl, ─ (or a tee at a marked cell) across the interior, tr.
361            ctx.put_char(0, 0, tl, border);
362            for x in 1..w - 1 {
363                let ch = self
364                    .junction_at(Edge::Top, x, bar, &glyphs)
365                    .unwrap_or(h_edge);
366                ctx.put_char(x, 0, ch, border);
367            }
368            if w >= 2 {
369                ctx.put_char(w - 1, 0, tr, border);
370            }
371            // Middle-row left/right edges (interior already filled above).
372            for y in 1..h - 1 {
373                let lch = self
374                    .junction_at(Edge::Left, y, bar, &glyphs)
375                    .unwrap_or(v_edge);
376                ctx.put_char(0, y, lch, border);
377                if w >= 2 {
378                    let rch = self
379                        .junction_at(Edge::Right, y, bar, &glyphs)
380                        .unwrap_or(v_edge);
381                    ctx.put_char(w - 1, y, rch, border);
382                }
383            }
384            // Bottom row.
385            if h >= 2 {
386                ctx.put_char(0, h - 1, bl, border);
387                for x in 1..w - 1 {
388                    let ch = self
389                        .junction_at(Edge::Bottom, x, bar, &glyphs)
390                        .unwrap_or(h_edge);
391                    ctx.put_char(x, h - 1, ch, border);
392                }
393                if w >= 2 {
394                    ctx.put_char(w - 1, h - 1, br, border);
395                }
396            }
397
398            // -- 2. Title budget (dropped). ------------------------------------
399            // The original computed a width budget to pass to its title getter, but the
400            // base window's getter ignores that argument and returns the full title;
401            // the drawn width is then recomputed as min(title width, width-10). So the
402            // budget never caps the drawn title for a base window (a subclass could
403            // abbreviate). It is therefore dead here and not computed; we cap the
404            // *drawn* title to `width - 10` in step 4.
405
406            // Window number (top row).
407            if let Some(n) = self.number
408                && n < 10
409            {
410                let i = if self.flags.zoom { 7 } else { 3 };
411                if let Some(digit) = char::from_digit(u32::from(n), 10) {
412                    ctx.put_char(w - i, 0, digit, border);
413                }
414            }
415
416            // Title (top row), centered.
417            if let Some(title) = &self.title {
418                let cap = w - 10;
419                let (end, lw) = crate::text::scroll(title, cap, false);
420                let lw = lw as i32;
421                let truncated = &title[..end];
422                let i = (w - lw) >> 1;
423                ctx.put_char(i - 1, 0, ' ', border);
424                ctx.put_str(i, 0, truncated, border);
425                ctx.put_char(i + lw, 0, ' ', border);
426            }
427
428            // Active-only icons (top row).
429            if self.st.state.active {
430                if self.flags.close {
431                    ctx.put_cstr(2, 0, glyphs.close_icon, border, icon);
432                }
433                if self.flags.zoom {
434                    let zi = if self.zoomed {
435                        glyphs.unzoom_icon
436                    } else {
437                        glyphs.zoom_icon
438                    };
439                    ctx.put_cstr(w - 5, 0, zi, border, icon);
440                }
441            }
442
443            // Active + grow resize icons (bottom row).
444            if self.st.state.active && self.flags.grow && h >= 2 {
445                ctx.put_cstr(0, h - 1, glyphs.drag_left_icon, border, icon);
446                ctx.put_cstr(w - 2, h - 1, glyphs.drag_icon, border, icon);
447            }
448        }
449    }
450
451    /// Handle the close/zoom icon clicks; the window drag loops live in the
452    /// owning [`Window`](crate::window::Window).
453    ///
454    /// The mouse position delivered by [`Group`](crate::view::Group) is already
455    /// **view-local** (the group subtracts the child origin), so the position is
456    /// used directly.
457    ///
458    /// Handled here (top-row clicks while active):
459    /// * **close** — `x` in `2..=4` when the close flag is set and active: arm a
460    ///   mouse-track capture (up-only mask, swallowing everything until release);
461    ///   post [`Command::CLOSE`] only on release over the close zone.
462    /// * **zoom** — `x` in `(w-5)..=(w-3)` (or a double-click) when the zoom flag is
463    ///   set: post [`Command::ZOOM`], consume. Checked *after* close, so a
464    ///   double-click inside the close hot-zone resolves to close.
465    ///
466    /// Drag cases are handled by the owning `Window`:
467    /// * title-bar move drag: the top-row click not on an icon is left unconsumed
468    ///   on purpose — the window starts the move drag.
469    /// * bottom-row grow drags: left unconsumed so the window starts a grow capture.
470    /// * middle-button move: left unconsumed so the window starts a move drag.
471    ///
472    /// A frame is not selectable, so there is no auto-select on click and nothing
473    /// to call through to.
474    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
475        match *ev {
476            Event::MouseDown(m) => {
477                if !self.border_visible {
478                    return; // frameless: no close/zoom/drag hotspots
479                }
480                let w = self.st.size.x;
481                if m.position.y == 0 && self.st.state.active {
482                    if self.flags.close && (2..=4).contains(&m.position.x) {
483                        // Arm an up-only capture (mouse_move / mouse_auto / wheel all
484                        // false — swallows every mouse event until release), then
485                        // confirm the release position in the MouseUp arm.
486                        if let Some(id) = self.st.id() {
487                            self.close_pressed = true;
488                            ctx.start_mouse_track(
489                                id,
490                                self.abs_origin,
491                                TrackMask {
492                                    mouse_move: false,
493                                    mouse_auto: false,
494                                    wheel: false,
495                                },
496                            );
497                            ev.clear();
498                        } else {
499                            // Degenerate fallback (no ViewId — ids are stamped
500                            // at Group::insert, so this is test-only): post ON
501                            // DOWN, skipping the release-confirm.
502                            ctx.post(Command::CLOSE);
503                            ev.clear();
504                        }
505                    } else if self.flags.zoom
506                        && ((w - 5..=w - 3).contains(&m.position.x) || m.flags.double_click)
507                    {
508                        ctx.post(Command::ZOOM);
509                        ev.clear();
510                    }
511                    // else: title-bar move drag — left unconsumed ON PURPOSE so the
512                    // window picks it up and starts the move drag.
513                }
514                // else: bottom-row grow drags + middle-button move — left unconsumed
515                // ON PURPOSE so the window starts the grow/move drag.
516            }
517
518            // ---------------------------------------------------------------
519            // MouseUp arm — release-confirm: post a Close command only if the
520            // button is released over the close zone. Guarded by `close_pressed`
521            // against stray MouseUp events.
522            // ---------------------------------------------------------------
523            Event::MouseUp(m) if self.close_pressed && self.border_visible => {
524                self.close_pressed = false;
525                // Confirm the release is on the top row, over the close zone.
526                if m.position.y == 0 && (2..=4).contains(&m.position.x) {
527                    ctx.post(Command::CLOSE);
528                }
529                ev.clear();
530            }
531
532            _ => {}
533        }
534    }
535
536    /// Downcast seam: `Window::zoom` pushes `set_zoomed` to its frame child via
537    /// [`Group::child_mut`](crate::view::Group::child_mut) +
538    /// `downcast_mut::<Frame>()`. See [`View::as_any_mut`].
539    fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
540        Some(self)
541    }
542}
543
544// ---------------------------------------------------------------------------
545// Tests
546// ---------------------------------------------------------------------------
547
548#[cfg(test)]
549mod tests {
550    use super::*;
551    use crate::backend::{HeadlessBackend, Renderer};
552    use crate::event::{MouseButtons, MouseEvent, MouseEventFlags, MouseWheel};
553    use crate::screen::Buffer;
554    use crate::theme::Theme;
555    use crate::view::Point;
556    use std::collections::VecDeque;
557
558    // -- Context / event helpers --------------------------------------------
559
560    fn make_ctx<'a>(
561        out: &'a mut VecDeque<Event>,
562        timers: &'a mut crate::timer::TimerQueue,
563        deferred: &'a mut Vec<crate::view::Deferred>,
564    ) -> Context<'a> {
565        Context::new(out, timers, 0, deferred)
566    }
567
568    fn mouse_down_at(x: i32, y: i32) -> Event {
569        Event::MouseDown(MouseEvent {
570            position: Point::new(x, y),
571            buttons: MouseButtons {
572                left: true,
573                ..Default::default()
574            },
575            flags: MouseEventFlags::default(),
576            wheel: MouseWheel::None,
577            modifiers: Default::default(),
578        })
579    }
580
581    fn mouse_up_at(x: i32, y: i32) -> Event {
582        Event::MouseUp(MouseEvent {
583            position: Point::new(x, y),
584            buttons: MouseButtons::default(),
585            flags: MouseEventFlags::default(),
586            wheel: MouseWheel::None,
587            modifiers: Default::default(),
588        })
589    }
590
591    fn double_click_at(x: i32, y: i32) -> Event {
592        Event::MouseDown(MouseEvent {
593            position: Point::new(x, y),
594            buttons: MouseButtons {
595                left: true,
596                ..Default::default()
597            },
598            flags: MouseEventFlags {
599                double_click: true,
600                ..Default::default()
601            },
602            wheel: MouseWheel::None,
603            modifiers: Default::default(),
604        })
605    }
606
607    /// Stamp a `ViewId` onto a frame (as `Group::insert` would).
608    fn stamp_id(f: &mut Frame) -> crate::view::ViewId {
609        let id = crate::view::ViewId::next();
610        f.st.id = Some(id);
611        id
612    }
613
614    /// Collect the rendered glyphs of one row as a String.
615    fn row_text(buf: &Buffer, y: u16) -> String {
616        (0..buf.width())
617            .map(|x| buf.get(x, y).symbol().to_string())
618            .collect()
619    }
620
621    fn render_frame(frame: &mut Frame, w: u16, h: u16) -> Buffer {
622        let theme = Theme::classic_blue();
623        let mut buf = Buffer::new(w, h);
624        let bounds = frame.st.get_bounds();
625        let mut dc = DrawCtx::new(&mut buf, &theme, bounds, bounds.a);
626        frame.draw(&mut dc);
627        buf
628    }
629
630    // -- Constructor --------------------------------------------------------
631
632    #[test]
633    fn new_sets_grow_hi_and_is_not_selectable() {
634        let f = Frame::new(Rect::new(0, 0, 20, 6));
635        assert!(f.st.grow_mode.hi_x, "gfGrowHiX must be set");
636        assert!(f.st.grow_mode.hi_y, "gfGrowHiY must be set");
637        assert!(!f.st.grow_mode.lo_x && !f.st.grow_mode.lo_y);
638        assert!(!f.st.options.selectable, "frame is not selectable");
639        assert_eq!(f.title(), None);
640        assert_eq!(f.number(), None);
641        assert!(!f.zoomed());
642        assert_eq!(f.flags(), WindowFlags::default());
643    }
644
645    // -- Owner-data-down setters --------------------------------------------
646
647    #[test]
648    fn setters_push_owner_data_down() {
649        let mut f = Frame::new(Rect::new(0, 0, 20, 6));
650        f.set_title(Some("Hello".into()));
651        f.set_flags(WindowFlags {
652            close: true,
653            zoom: true,
654            ..Default::default()
655        });
656        f.set_number(Some(3));
657        f.set_zoomed(true);
658        assert_eq!(f.title(), Some("Hello"));
659        assert!(f.flags().close && f.flags().zoom);
660        assert_eq!(f.number(), Some(3));
661        assert!(f.zoomed());
662    }
663
664    // -- draw: title cap is width-10 even with close/zoom (faithful title fetch) --
665
666    /// The reduced budget `l` (after the `-6` close/zoom and `-4` number
667    /// subtractions) is passed only to the title-fetch step, which the **base**
668    /// window ignores; the drawn title is capped to `width - 10`. So with close+zoom
669    /// set and a title of 8 cols (≤ width-10 = 10, but > width-10-6 = 4), the
670    /// full 8 chars must still show (not 4).
671    #[test]
672    fn title_cap_is_width_minus_10_regardless_of_close_zoom() {
673        let mut f = Frame::new(Rect::new(0, 0, 20, 6));
674        f.st.state.active = true;
675        f.set_flags(WindowFlags {
676            close: true,
677            zoom: true,
678            ..Default::default()
679        });
680        f.set_title(Some("Document".into())); // 8 cols
681        let buf = render_frame(&mut f, 20, 6);
682        // All 8 letters of "Document" must render. lw = min(8, 10) = 8;
683        // i = (20 - 8) >> 1 = 6. Title occupies cols 6..14.
684        let title: String = (6..14)
685            .map(|x| buf.get(x, 0).symbol().to_string())
686            .collect();
687        assert_eq!(
688            title, "Document",
689            "the reduced budget must NOT cap the drawn title (base getTitle ignores it)"
690        );
691    }
692
693    // -- draw: number drawn only when Some(n<10) ----------------------------
694
695    #[test]
696    fn number_drawn_only_when_present_and_below_ten() {
697        // active so the box is drawn the same way; number is independent of state.
698        let mut f = Frame::new(Rect::new(0, 0, 20, 6));
699        f.st.state.active = true;
700        f.set_number(Some(3));
701        // flags.zoom is false → i = 3 → digit at column w-3 = 17.
702        let buf = render_frame(&mut f, 20, 6);
703        assert_eq!(buf.get(17, 0).symbol(), "3", "number drawn at w-3");
704
705        // n >= 10 → not drawn.
706        let mut f2 = Frame::new(Rect::new(0, 0, 20, 6));
707        f2.st.state.active = true;
708        f2.set_number(Some(10));
709        let buf2 = render_frame(&mut f2, 20, 6);
710        assert_eq!(
711            buf2.get(17, 0).symbol(),
712            "═",
713            "n>=10 leaves the border glyph"
714        );
715
716        // None → not drawn.
717        let mut f3 = Frame::new(Rect::new(0, 0, 20, 6));
718        f3.st.state.active = true;
719        let buf3 = render_frame(&mut f3, 20, 6);
720        assert_eq!(
721            buf3.get(17, 0).symbol(),
722            "═",
723            "no number leaves the border glyph"
724        );
725    }
726
727    // -- draw: long title is truncated + centered within w-10 ---------------
728
729    #[test]
730    fn long_title_truncated_and_centered_within_budget() {
731        // w=20 → title budget l = 20-10 = 10 (no close/zoom/number).
732        let mut f = Frame::new(Rect::new(0, 0, 20, 6));
733        f.st.state.active = true;
734        f.set_title(Some("This title is far too long to fit".into()));
735        let buf = render_frame(&mut f, 20, 6);
736        let row0 = row_text(&buf, 0);
737        // The visible title text must be at most 10 columns wide. Count the
738        // run of ASCII letters/spaces on the top row between the border corners.
739        let title_chars: String = row0
740            .chars()
741            .filter(|c| c.is_ascii_alphanumeric() || *c == ' ')
742            .collect();
743        assert!(
744            title_chars.trim().chars().count() <= 10,
745            "title must be truncated to the 10-column budget, got: {title_chars:?}"
746        );
747        // Centered: budget 10, so i = (20 - 10) >> 1 = 5; the title starts at col 5.
748        assert_eq!(
749            buf.get(5, 0).symbol(),
750            "T",
751            "truncated title starts centered at col 5"
752        );
753    }
754
755    // -- draw: dragging state → single-line box in the FrameDragging style ----
756
757    /// When `dragging` is set, the state match takes the dragging arm (first arm,
758    /// `Role::FrameDragging`, single-line) regardless of `active`. The box must
759    /// use single-line glyphs (┌, not ╔) and the border cells must carry the
760    /// `Role::FrameDragging` style.
761    #[test]
762    fn dragging_draws_single_line_box_in_dragging_style() {
763        let mut f = Frame::new(Rect::new(0, 0, 20, 6));
764        f.st.state.active = true; // dragging wins over active
765        f.st.state.dragging = true;
766        let buf = render_frame(&mut f, 20, 6);
767        // (a) single-line corner, not the double-line active corner.
768        assert_eq!(
769            buf.get(0, 0).symbol(),
770            "┌",
771            "dragging frame uses single-line box glyphs"
772        );
773        assert_ne!(buf.get(0, 0).symbol(), "╔");
774        // (b) border style is the FrameDragging style.
775        let expected = Theme::classic_blue().style(Role::FrameDragging);
776        assert_eq!(buf.get(0, 0).style(), expected, "top-left border style");
777    }
778
779    // -- draw: gray palette → FrameGray* role family ----
780
781    /// With `palette = Gray` (a dialog's frame), the border AND interior must
782    /// carry the `FrameGray*` styles: `FrameGrayActive` when active,
783    /// `FrameGrayPassive` when passive — never the blue `Frame*` family.
784    #[test]
785    fn gray_palette_draws_border_and_interior_in_gray_roles() {
786        let theme = Theme::classic_blue();
787
788        // Active gray frame → FrameGrayActive everywhere (border + interior).
789        let mut f = Frame::new(Rect::new(0, 0, 20, 6));
790        f.st.state.active = true;
791        f.set_palette(WindowPalette::Gray);
792        let buf = render_frame(&mut f, 20, 6);
793        let expected = theme.style(Role::FrameGrayActive);
794        assert_eq!(buf.get(0, 0).style(), expected, "active border corner");
795        assert_eq!(buf.get(5, 2).style(), expected, "active interior fill");
796        assert_ne!(
797            expected,
798            theme.style(Role::FrameActive),
799            "gray and blue active styles must differ for the test to be meaningful"
800        );
801
802        // Passive gray frame → FrameGrayPassive.
803        let mut p = Frame::new(Rect::new(0, 0, 20, 6));
804        p.set_palette(WindowPalette::Gray);
805        let bufp = render_frame(&mut p, 20, 6);
806        let expected_p = theme.style(Role::FrameGrayPassive);
807        assert_eq!(bufp.get(0, 0).style(), expected_p, "passive border corner");
808        assert_eq!(bufp.get(5, 2).style(), expected_p, "passive interior fill");
809
810        // Dragging gray frame → FrameGrayDragging.
811        let mut d = Frame::new(Rect::new(0, 0, 20, 6));
812        d.st.state.active = true;
813        d.st.state.dragging = true;
814        d.set_palette(WindowPalette::Gray);
815        let bufd = render_frame(&mut d, 20, 6);
816        assert_eq!(
817            bufd.get(0, 0).style(),
818            theme.style(Role::FrameGrayDragging),
819            "dragging border corner"
820        );
821    }
822
823    // -- draw: cyan palette → FrameCyan* role family ----
824
825    /// With `palette = Cyan`, the border AND interior must
826    /// carry the `FrameCyan*` styles — never the blue `Frame*` family.
827    #[test]
828    fn cyan_palette_draws_border_and_interior_in_cyan_roles() {
829        let theme = Theme::classic_blue();
830
831        // Active cyan frame → FrameCyanActive everywhere (border + interior).
832        let mut f = Frame::new(Rect::new(0, 0, 20, 6));
833        f.st.state.active = true;
834        f.set_palette(WindowPalette::Cyan);
835        let buf = render_frame(&mut f, 20, 6);
836        let expected = theme.style(Role::FrameCyanActive);
837        assert_eq!(buf.get(0, 0).style(), expected, "active border corner");
838        assert_eq!(buf.get(5, 2).style(), expected, "active interior fill");
839        assert_ne!(
840            expected,
841            theme.style(Role::FrameActive),
842            "cyan and blue active styles must differ for the test to be meaningful"
843        );
844
845        // Passive cyan frame → FrameCyanPassive.
846        let mut p = Frame::new(Rect::new(0, 0, 20, 6));
847        p.set_palette(WindowPalette::Cyan);
848        let bufp = render_frame(&mut p, 20, 6);
849        let expected_p = theme.style(Role::FrameCyanPassive);
850        assert_eq!(bufp.get(0, 0).style(), expected_p, "passive border corner");
851        assert_eq!(bufp.get(5, 2).style(), expected_p, "passive interior fill");
852
853        // Dragging cyan frame → FrameCyanDragging.
854        let mut d = Frame::new(Rect::new(0, 0, 20, 6));
855        d.st.state.active = true;
856        d.st.state.dragging = true;
857        d.set_palette(WindowPalette::Cyan);
858        let bufd = render_frame(&mut d, 20, 6);
859        assert_eq!(
860            bufd.get(0, 0).style(),
861            theme.style(Role::FrameCyanDragging),
862            "dragging border corner"
863        );
864    }
865
866    // -- handle_event: close (release-confirm) --------------------------------
867
868    /// Degenerate fallback (no ViewId — uninserted frame): the Close command fires
869    /// on mouse-**down**, preserving backwards compat for pure-unit tests.
870    #[test]
871    fn click_close_icon_posts_close_on_down_no_id() {
872        let mut f = Frame::new(Rect::new(0, 0, 20, 6));
873        f.st.state.active = true;
874        f.set_flags(WindowFlags {
875            close: true,
876            ..Default::default()
877        });
878        let mut out = VecDeque::new();
879        let mut timers = crate::timer::TimerQueue::new();
880        let mut deferred: Vec<crate::view::Deferred> = vec![];
881        let mut ev = mouse_down_at(3, 0); // close hot-zone is x in 2..=4
882        {
883            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
884            f.handle_event(&mut ev, &mut ctx);
885        }
886        assert!(ev.is_nothing(), "close click consumed");
887        assert_eq!(
888            out.len(),
889            1,
890            "immediate cmClose on down (no ViewId fallback)"
891        );
892        assert_eq!(out[0], Event::Command(Command::CLOSE));
893    }
894
895    /// With a ViewId (inserted frame): mouse-down in close zone arms tracking;
896    /// the Close command fires only on `MouseUp` over the close zone
897    /// (release-confirm).
898    #[test]
899    fn click_close_icon_release_confirm_with_id() {
900        let mut f = Frame::new(Rect::new(0, 0, 20, 6));
901        f.st.state.active = true;
902        f.set_flags(WindowFlags {
903            close: true,
904            ..Default::default()
905        });
906        let _id = stamp_id(&mut f);
907
908        // MouseDown in the close zone: arms tracking, no Close command yet.
909        let mut out = VecDeque::new();
910        let mut timers = crate::timer::TimerQueue::new();
911        let mut deferred: Vec<crate::view::Deferred> = vec![];
912        {
913            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
914            let mut ev = mouse_down_at(3, 0);
915            f.handle_event(&mut ev, &mut ctx);
916            assert!(ev.is_nothing(), "mouse-down consumed");
917        }
918        assert!(
919            out.is_empty(),
920            "no Close command on down — deferred release-confirm"
921        );
922        assert!(f.close_pressed, "tracking armed (no command yet)");
923        assert_eq!(deferred.len(), 1, "PushCapture deferred");
924        assert!(
925            matches!(deferred[0], crate::view::Deferred::PushCapture(_)),
926            "deferred[0] is PushCapture"
927        );
928        if let crate::view::Deferred::PushCapture(ref h) = deferred[0] {
929            assert_eq!(h.view(), Some(_id), "capture routes to this frame's id");
930        }
931
932        // MouseUp over the close zone: the Close command fires.
933        let mut out2 = VecDeque::new();
934        let mut deferred2: Vec<crate::view::Deferred> = vec![];
935        {
936            let mut ctx = make_ctx(&mut out2, &mut timers, &mut deferred2);
937            let mut ev = mouse_up_at(3, 0);
938            f.handle_event(&mut ev, &mut ctx);
939            assert!(ev.is_nothing(), "mouse-up consumed");
940        }
941        assert!(!f.close_pressed, "tracking cleared");
942        assert_eq!(out2.len(), 1);
943        assert_eq!(out2[0], Event::Command(Command::CLOSE));
944    }
945
946    /// Press close icon, release OUTSIDE the close zone: no Close command
947    /// (the position check fails).
948    #[test]
949    fn close_icon_release_outside_no_close() {
950        let mut f = Frame::new(Rect::new(0, 0, 20, 6));
951        f.st.state.active = true;
952        f.set_flags(WindowFlags {
953            close: true,
954            ..Default::default()
955        });
956        let _id = stamp_id(&mut f);
957
958        // MouseDown in the close zone: arm tracking.
959        let mut out = VecDeque::new();
960        let mut timers = crate::timer::TimerQueue::new();
961        let mut deferred: Vec<crate::view::Deferred> = vec![];
962        {
963            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
964            let mut ev = mouse_down_at(3, 0);
965            f.handle_event(&mut ev, &mut ctx);
966        }
967        assert!(f.close_pressed);
968
969        // MouseUp outside the close zone (x = 10, top row): no Close command.
970        let mut out2 = VecDeque::new();
971        let mut deferred2: Vec<crate::view::Deferred> = vec![];
972        {
973            let mut ctx = make_ctx(&mut out2, &mut timers, &mut deferred2);
974            let mut ev = mouse_up_at(10, 0);
975            f.handle_event(&mut ev, &mut ctx);
976            assert!(ev.is_nothing(), "tracked up consumed");
977        }
978        assert!(!f.close_pressed, "tracking cleared even without close");
979        assert!(
980            out2.is_empty(),
981            "no Close command when released outside the close zone"
982        );
983    }
984
985    // -- handle_event: zoom (click inside w-5..=w-3) --------------------------
986
987    #[test]
988    fn click_zoom_icon_posts_zoom_and_consumes() {
989        let mut f = Frame::new(Rect::new(0, 0, 20, 6));
990        f.st.state.active = true;
991        f.set_flags(WindowFlags {
992            zoom: true,
993            ..Default::default()
994        });
995        let mut out = VecDeque::new();
996        let mut timers = crate::timer::TimerQueue::new();
997        let mut deferred: Vec<crate::view::Deferred> = vec![];
998        // w=20 → zoom hot-zone is x in 15..=17. Click at w-4 = 16.
999        let mut ev = mouse_down_at(16, 0);
1000        {
1001            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1002            f.handle_event(&mut ev, &mut ctx);
1003        }
1004        assert!(ev.is_nothing(), "zoom click consumed");
1005        assert_eq!(out[0], Event::Command(Command::ZOOM));
1006    }
1007
1008    // -- handle_event: double-click anywhere on top row → zoom ----------------
1009
1010    #[test]
1011    fn double_click_row0_posts_zoom() {
1012        let mut f = Frame::new(Rect::new(0, 0, 20, 6));
1013        f.st.state.active = true;
1014        f.set_flags(WindowFlags {
1015            zoom: true,
1016            ..Default::default()
1017        });
1018        let mut out = VecDeque::new();
1019        let mut timers = crate::timer::TimerQueue::new();
1020        let mut deferred: Vec<crate::view::Deferred> = vec![];
1021        // Double-click outside the close hot-zone (e.g. x=10) → zoom.
1022        let mut ev = double_click_at(10, 0);
1023        {
1024            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1025            f.handle_event(&mut ev, &mut ctx);
1026        }
1027        assert!(ev.is_nothing());
1028        assert_eq!(out[0], Event::Command(Command::ZOOM));
1029    }
1030
1031    // -- handle_event: passive frame ignores clicks ---------------------------
1032
1033    #[test]
1034    fn passive_frame_ignores_clicks() {
1035        let mut f = Frame::new(Rect::new(0, 0, 20, 6));
1036        // not active
1037        f.set_flags(WindowFlags {
1038            close: true,
1039            zoom: true,
1040            ..Default::default()
1041        });
1042        let mut out = VecDeque::new();
1043        let mut timers = crate::timer::TimerQueue::new();
1044        let mut deferred: Vec<crate::view::Deferred> = vec![];
1045        let mut ev = mouse_down_at(3, 0);
1046        {
1047            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1048            f.handle_event(&mut ev, &mut ctx);
1049        }
1050        assert!(!ev.is_nothing(), "passive frame does not consume the click");
1051        assert!(out.is_empty(), "passive frame posts nothing");
1052    }
1053
1054    // -- handle_event: close takes priority over zoom on overlap --------------
1055
1056    #[test]
1057    fn close_wins_over_zoom_in_close_hot_zone() {
1058        // No stamp_id → exercises the no-id fallback (post on down), which is
1059        // sufficient here: close-vs-zoom priority is structural (`else if`
1060        // branch order), identical on the tracked path.
1061        // A narrow frame where the close zone (2..=4) and zoom zone overlap is
1062        // contrived; instead verify the branch order: with both flags set, a
1063        // click at x=3 (close zone) must post CLOSE, not ZOOM.
1064        let mut f = Frame::new(Rect::new(0, 0, 20, 6));
1065        f.st.state.active = true;
1066        f.set_flags(WindowFlags {
1067            close: true,
1068            zoom: true,
1069            ..Default::default()
1070        });
1071        let mut out = VecDeque::new();
1072        let mut timers = crate::timer::TimerQueue::new();
1073        let mut deferred: Vec<crate::view::Deferred> = vec![];
1074        let mut ev = mouse_down_at(3, 0);
1075        {
1076            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1077            f.handle_event(&mut ev, &mut ctx);
1078        }
1079        assert_eq!(out[0], Event::Command(Command::CLOSE));
1080    }
1081
1082    // -- Snapshot: active frame ---------------------------------------------
1083
1084    /// Active frame: double-line box, centered title, `[■]` close + `[↑]` zoom
1085    /// icons on the top row, resize icons on the bottom row.
1086    #[test]
1087    fn snapshot_active_frame() {
1088        let theme = Theme::classic_blue();
1089        let mut f = Frame::new(Rect::new(0, 0, 20, 6));
1090        f.st.state.active = true; // no group to propagate the active state in the test
1091        f.set_title(Some("Edit".into()));
1092        f.set_flags(WindowFlags {
1093            r#move: true,
1094            grow: true,
1095            close: true,
1096            zoom: true,
1097        });
1098
1099        let (backend, screen) = HeadlessBackend::new(20, 6);
1100        let mut r = Renderer::new(Box::new(backend));
1101        r.render(|buf: &mut Buffer| {
1102            let bounds = f.st.get_bounds();
1103            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
1104            f.draw(&mut dc);
1105        });
1106        insta::assert_snapshot!(screen.snapshot());
1107    }
1108
1109    // -- Snapshot: passive frame --------------------------------------------
1110
1111    /// Passive frame: single-line box, centered title, **no icons** even though
1112    /// the flags are set (icons are active-only).
1113    #[test]
1114    fn snapshot_passive_frame() {
1115        let theme = Theme::classic_blue();
1116        let mut f = Frame::new(Rect::new(0, 0, 20, 6));
1117        // not active → passive single-line, no icons.
1118        f.set_title(Some("Edit".into()));
1119        f.set_flags(WindowFlags {
1120            r#move: true,
1121            grow: true,
1122            close: true,
1123            zoom: true,
1124        });
1125
1126        let (backend, screen) = HeadlessBackend::new(20, 6);
1127        let mut r = Renderer::new(Box::new(backend));
1128        r.render(|buf: &mut Buffer| {
1129            let bounds = f.st.get_bounds();
1130            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
1131            f.draw(&mut dc);
1132        });
1133        insta::assert_snapshot!(screen.snapshot());
1134    }
1135
1136    // -- junction marks: tee substitution ------------------------------------
1137
1138    #[test]
1139    fn junction_marks_substitute_tees_on_interior_edges() {
1140        use crate::junction::{Edge, JunctionMark, Weight};
1141        // Passive (single-line) frame so the bar weight is Single.
1142        let mut f = Frame::new(Rect::new(0, 0, 20, 6));
1143        f.set_junction_marks(vec![
1144            JunctionMark {
1145                edge: Edge::Top,
1146                offset: 8,
1147                stem: Weight::Single,
1148            },
1149            JunctionMark {
1150                edge: Edge::Bottom,
1151                offset: 8,
1152                stem: Weight::Single,
1153            },
1154            JunctionMark {
1155                edge: Edge::Right,
1156                offset: 3,
1157                stem: Weight::Single,
1158            },
1159            JunctionMark {
1160                edge: Edge::Left,
1161                offset: 3,
1162                stem: Weight::Single,
1163            },
1164        ]);
1165        let buf = render_frame(&mut f, 20, 6);
1166        assert_eq!(buf.get(8, 0).symbol(), "┬", "top-edge mark → ┬");
1167        assert_eq!(buf.get(8, 5).symbol(), "┴", "bottom-edge mark → ┴");
1168        assert_eq!(buf.get(19, 3).symbol(), "┤", "right-edge mark → ┤");
1169        assert_eq!(buf.get(0, 3).symbol(), "├", "left-edge mark → ├");
1170        assert_eq!(buf.get(5, 0).symbol(), "─", "unmarked top stays ─");
1171        assert_eq!(buf.get(0, 0).symbol(), "┌");
1172        assert_eq!(buf.get(19, 0).symbol(), "┐");
1173    }
1174
1175    #[test]
1176    fn no_marks_is_byte_for_byte_unchanged() {
1177        let mut a = Frame::new(Rect::new(0, 0, 20, 6));
1178        a.st.state.active = true;
1179        let mut b = Frame::new(Rect::new(0, 0, 20, 6));
1180        b.st.state.active = true;
1181        b.set_junction_marks(vec![]);
1182        let ba = render_frame(&mut a, 20, 6);
1183        let bb = render_frame(&mut b, 20, 6);
1184        for y in 0..6 {
1185            assert_eq!(row_text(&ba, y), row_text(&bb, y), "row {y} identical");
1186        }
1187    }
1188
1189    #[test]
1190    fn active_double_frame_uses_mixed_tee_for_single_stem() {
1191        use crate::junction::{Edge, JunctionMark, Weight};
1192        let mut f = Frame::new(Rect::new(0, 0, 20, 6));
1193        f.st.state.active = true; // double-line bar
1194        f.set_junction_marks(vec![JunctionMark {
1195            edge: Edge::Top,
1196            offset: 8,
1197            stem: Weight::Single,
1198        }]);
1199        let buf = render_frame(&mut f, 20, 6);
1200        assert_eq!(buf.get(8, 0).symbol(), "╤", "double bar + single stem → ╤");
1201    }
1202
1203    // -- frameless: no border, no title, no icons ------------------------------
1204
1205    #[test]
1206    fn frameless_draws_no_border() {
1207        // A frame with border_visible=false fills its interior background but draws
1208        // no box edges, title, or icons.
1209        let theme = crate::theme::Theme::classic_blue();
1210        let (backend, screen) = crate::backend::HeadlessBackend::new(12, 4);
1211        let mut r = crate::backend::Renderer::new(Box::new(backend));
1212        let mut frame = Frame::new(Rect::new(0, 0, 12, 4));
1213        frame.set_title(Some("Hi".into()));
1214        frame.st.state.active = true;
1215        frame.set_border_visible(false);
1216        r.render(|buf: &mut crate::screen::Buffer| {
1217            let b = frame.st.get_bounds();
1218            let mut dc = crate::view::DrawCtx::new(buf, &theme, b, b.a);
1219            frame.draw(&mut dc);
1220        });
1221        let snap = screen.snapshot();
1222        assert!(
1223            !snap.contains('═') && !snap.contains('║'),
1224            "no double-line border"
1225        );
1226        assert!(!snap.contains("Hi"), "no title when frameless");
1227    }
1228
1229    /// The downcast seam: `Frame` overrides `as_any_mut` so an owner can reach
1230    /// it concretely (e.g. a window's zoom pushing `set_zoomed`); a plain view's
1231    /// base `as_any_mut` returns `None`.
1232    #[test]
1233    fn as_any_mut_seam_resolves_frame_but_not_a_plain_view() {
1234        let mut f = Frame::new(Rect::new(0, 0, 10, 5));
1235        // The frame downcasts to its concrete type and is mutable through it.
1236        {
1237            let any = View::as_any_mut(&mut f).expect("Frame overrides as_any_mut");
1238            let frame = any
1239                .downcast_mut::<Frame>()
1240                .expect("downcasts to the concrete Frame");
1241            frame.set_zoomed(true);
1242        }
1243        assert!(f.zoomed(), "the concrete push through the seam took effect");
1244
1245        // A plain view (base impl) returns None.
1246        struct Plain {
1247            st: ViewState,
1248        }
1249        impl View for Plain {
1250            fn state(&self) -> &ViewState {
1251                &self.st
1252            }
1253            fn state_mut(&mut self) -> &mut ViewState {
1254                &mut self.st
1255            }
1256            fn draw(&mut self, _ctx: &mut DrawCtx) {}
1257        }
1258        let mut p = Plain {
1259            st: ViewState::new(Rect::new(0, 0, 4, 4)),
1260        };
1261        assert!(
1262            View::as_any_mut(&mut p).is_none(),
1263            "base as_any_mut returns None"
1264        );
1265    }
1266}