tvision_rs/widgets/outline.rs
1//! A collapsible tree view: [`Node`], [`OutlineViewer`], and [`Outline`].
2//!
3//! # A trait, not a concrete struct
4//!
5//! An outline viewer's overridable methods
6//! (`get_root`/`get_next`/`get_child`/`get_text`/`is_expanded`/`has_children`/`adjust`)
7//! are called from inside the base's own `draw`/`handle_event`/`update` — the
8//! same constraint that made
9//! [`ListViewer`](crate::widgets::list_viewer::ListViewer) a trait rather than an
10//! embedded struct. So it follows the same shape: [`OutlineViewer`] carries the
11//! overridable methods, [`OutlineViewerState`] carries the data members, and the
12//! shared draw / event / traversal logic lives as **free functions generic over
13//! `<L: OutlineViewer + ?Sized>`** so a concrete widget's `View` impl reuses them
14//! verbatim.
15//!
16//! # The cross-view scrollbar read-sync
17//!
18//! An outline viewer holds only `&mut Context` during dispatch and so can neither
19//! read nor mutate its window-frame sibling scroll bars. The pump is the broker:
20//! on a [`SCROLL_BAR_CHANGED`](crate::command::Command::SCROLL_BAR_CHANGED)
21//! broadcast naming one of its bars as `source`, the viewer requests
22//! [`Deferred::ScrollSync`](crate::view::Deferred::ScrollSync);
23//! the pump reads both bars' `value`s and calls `apply_scroll_sync`, which writes
24//! the resulting `(dx, dy)` into the viewer's [`delta`](OutlineViewerState::delta).
25//! This read-sync is **read-only** (no focus write-back), so it terminates without
26//! a change-guard.
27//!
28//! # Mouse press-and-hold
29//!
30//! A mouse-down arms the mouse-track capture; the subsequent move/auto/up events
31//! route the hold loop, auto-scrolling when the mouse moves out of view. A
32//! `dragged` gate distinguishes a click (which toggles the node's expand state)
33//! from a drag.
34//!
35//! # Colors
36//!
37//! Each role is a [`Role`]: [`Role::OutlineNormal`] / [`Role::OutlineSurface`] /
38//! [`Role::OutlineFocused`] / [`Role::OutlineSelected`] /
39//! [`Role::OutlineNotExpanded`]. The normal row uses the shared three-surface
40//! rule ([`DrawCtx::content_surface`](crate::view::DrawCtx::content_surface)):
41//! `OutlineNormal`/`OutlineSurface`/`OutlineInactive` cross `owner_active` with
42//! the outline's own focus and selectability.
43//!
44//! # Construction
45//!
46//! Building an outline does not publish its scroll-bar parameters, because that
47//! needs a [`Context`] that is not available at construction. The consumer calls
48//! [`ov_update`] once after inserting the outline into a group (the same
49//! constraint the scroller and list-viewer constructors hit — see
50//! [`Outline::new`]).
51//!
52//! # Turbo Vision heritage
53//!
54//! Ports `TNode`, `TOutlineViewer`, and `TOutline` (`toutline.cpp`). The
55//! viewer's abstract-class inheritance becomes a trait plus a state struct plus
56//! generic free functions (D2), because the base's draw must call back into the
57//! subclass's overrides. Owner back-pointers to the sibling scroll bars become
58//! [`ViewId`] handles brokered by the event loop (D3), and the palette becomes
59//! [`Role`]s. The node's recursive destructor becomes the automatic `Box<Node>`
60//! drop.
61
62use crate::capture::TrackMask;
63use crate::command::Command;
64use crate::event::{Event, Key, ctrl_to_arrow};
65use crate::theme::{Role, SurfaceRoles};
66use crate::view::{
67 Context, DrawCtx, GrowMode, Options, Point, Rect, StateFlag, View, ViewId, ViewState,
68};
69
70/// Outline's surface triple for [`DrawCtx::content_surface`].
71const SURFACE_ROLES: SurfaceRoles = SurfaceRoles {
72 normal: Role::OutlineNormal,
73 surface: Role::OutlineSurface,
74 inactive: Role::OutlineInactive,
75};
76
77/// Graph flag: the node is drawn as expanded (no children, or expanded).
78const OV_EXPANDED: u16 = 0x01;
79/// Graph flag: the node has children AND is expanded (draw the child-link).
80const OV_CHILDREN: u16 = 0x02;
81/// Graph flag: the node is the last child of its parent (└ vs ├).
82const OV_LAST: u16 = 0x04;
83
84/// Number of auto-repeat ticks to accumulate before stepping the focus by ±1
85/// when the mouse is held outside the view.
86const MOUSE_AUTO_TO_SKIP: i32 = 3;
87
88/// Per-hold mouse-tracking state for the outline viewer.
89#[derive(Clone, Copy, Debug)]
90pub(crate) struct OvTrack {
91 /// Accumulated auto-repeat ticks since the last step/reset.
92 count: i32,
93 /// Iteration counter, capped at 2. After the hold, `dragged < 2`
94 /// distinguishes a "click" from a "drag": only a click can toggle the graph
95 /// expansion column.
96 dragged: u8,
97}
98
99// ---------------------------------------------------------------------------
100// Node — the tree node
101// ---------------------------------------------------------------------------
102
103/// One outline tree node.
104///
105/// A node owns its first child (`child_list`) and its next sibling (`next`), both
106/// as `Option<Box<Node>>`; the recursive `Box` drop frees the whole subtree
107/// automatically when the node is dropped or replaced.
108/// `text` is the displayed label; `expanded` controls whether children are shown
109/// in the outline viewer.
110///
111/// Build a tree with [`Node::new`] and the builder methods, then pass the root
112/// to [`Outline::new`]:
113///
114/// ```rust
115/// use tvision_rs::widgets::outline::Node;
116/// let root = Box::new(
117/// Node::new("Animals")
118/// .with_children(Box::new(
119/// Node::new("Cats")
120/// .with_next(Box::new(Node::new("Dogs")))
121/// ))
122/// );
123/// ```
124///
125/// # Turbo Vision heritage
126///
127/// Ports `TNode` (`toutline.cpp`); the recursive node destructor becomes the
128/// automatic `Box<Node>` drop.
129#[derive(Debug, Clone, PartialEq, Eq)]
130pub struct Node {
131 /// The text displayed in the outline row for this node.
132 ///
133 /// Displayed verbatim; assign a new value and call [`ov_update`] to refresh
134 /// the column widths.
135 pub text: String,
136 /// The first child of this node, or `None` if the node is a leaf.
137 ///
138 /// Siblings of the first child chain through their [`Node::next`] fields.
139 /// Set this (or use [`Node::with_children`]) before inserting the node into
140 /// an [`Outline`]; then call [`ov_update`] to publish the new extents.
141 pub child_list: Option<Box<Node>>,
142 /// The next sibling of this node, or `None` if this is the last sibling.
143 ///
144 /// Use [`Node::with_next`] in the builder chain, or assign directly when
145 /// building a sibling list manually.
146 pub next: Option<Box<Node>>,
147 /// Whether this node's children are currently shown (`true`) or hidden
148 /// (`false`).
149 ///
150 /// New nodes default to `true` (expanded). Set to `false` via
151 /// [`Node::with_expanded`] to start collapsed, or let the user collapse
152 /// the node interactively via the `-` key or a click on the graph column.
153 pub expanded: bool,
154}
155
156impl Node {
157 /// Create a leaf node with the given display text.
158 ///
159 /// The new node has no children or next sibling and starts expanded.
160 /// Chain [`with_children`](Self::with_children), [`with_next`](Self::with_next),
161 /// and [`with_expanded`](Self::with_expanded) to build a full subtree before
162 /// boxing and passing to [`Outline::new`].
163 pub fn new(text: impl Into<String>) -> Self {
164 Node {
165 text: text.into(),
166 child_list: None,
167 next: None,
168 expanded: true,
169 }
170 }
171
172 /// Attach a next sibling to this node and return `self`.
173 ///
174 /// The next sibling (and its own `next` chain) is freed automatically when
175 /// this node is dropped. To build a sibling list for use as children, chain
176 /// `with_next` calls starting from the last sibling:
177 ///
178 /// ```rust
179 /// use tvision_rs::widgets::outline::Node;
180 /// // "Cats" → "Dogs" sibling pair.
181 /// let siblings = Box::new(Node::new("Cats").with_next(Box::new(Node::new("Dogs"))));
182 /// ```
183 pub fn with_next(mut self, next: Box<Node>) -> Self {
184 self.next = Some(next);
185 self
186 }
187
188 /// Attach a first child to this node and return `self`.
189 ///
190 /// Additional children are siblings of `children`, chained via
191 /// [`with_next`](Self::with_next). The entire subtree is freed automatically
192 /// when this node is dropped.
193 pub fn with_children(mut self, children: Box<Node>) -> Self {
194 self.child_list = Some(children);
195 self
196 }
197
198 /// Set whether this node starts expanded or collapsed and return `self`.
199 ///
200 /// Pass `false` to start collapsed; the user can then expand it with the
201 /// `+` key or a click on the graph column. When `false`, [`Node::child_list`]
202 /// is owned but not shown until expanded.
203 pub fn with_expanded(mut self, expanded: bool) -> Self {
204 self.expanded = expanded;
205 self
206 }
207}
208
209// ---------------------------------------------------------------------------
210// OutlineViewerState — the data members
211// ---------------------------------------------------------------------------
212
213/// The shared state of every outline viewer. A concrete outline widget embeds
214/// one and exposes it via [`OutlineViewer::ov`]/[`OutlineViewer::ov_mut`].
215///
216/// # Turbo Vision heritage
217///
218/// The data half of `TOutlineViewer` (`toutline.cpp`) plus the scroll
219/// offset/limit it inherits from the scroller base.
220pub struct OutlineViewerState {
221 /// View state (geometry, flags, …) — the `View` composition target.
222 pub state: ViewState,
223 /// The scroll offset: `x` is the number of character columns to skip on
224 /// the left; `y` is the DFS position of the first visible row.
225 ///
226 /// Read `delta` to find out which part of the tree is visible. Do not assign
227 /// it directly — changes come from scrollbar broadcasts that the pump
228 /// resolves and applies via [`apply_delta`](Self::apply_delta).
229 pub delta: Point,
230 /// The content extent: `x` is the maximum graph+text width (in character
231 /// columns); `y` is the total number of currently-visible nodes.
232 ///
233 /// Updated by [`ov_update`] after every tree mutation. Read it to know the
234 /// scrollable content size; do not assign directly.
235 pub limit: Point,
236 /// The horizontal scrollbar view id, or `None` if none was wired.
237 ///
238 /// Set at construction via [`OutlineViewerState::new`]; the outline viewer
239 /// reads and writes its value through the pump broker.
240 pub h_scroll_bar: Option<ViewId>,
241 /// The vertical scrollbar view id, or `None` if none was wired.
242 ///
243 /// Set at construction via [`OutlineViewerState::new`]; the outline viewer
244 /// reads and writes its value through the pump broker.
245 pub v_scroll_bar: Option<ViewId>,
246 /// The DFS position (0-based) of the focused node.
247 ///
248 /// Read this to find out which node is focused. To move the focus
249 /// programmatically, call [`adjust_focus`] (it also scrolls the focused row
250 /// into view and notifies the trait via
251 /// [`OutlineViewer::focused_item`]). Do not assign directly.
252 pub foc: i32,
253 /// Absolute screen position of this view's `(0, 0)`, cached by the last
254 /// `draw` call — feeds the [`MouseTrackCapture`] origin.
255 pub(crate) abs_origin: Point,
256 /// Per-hold mouse-tracking state — `Some` while a track is in flight
257 /// (between `MouseDown` and `MouseUp`), `None` otherwise. Guards the
258 /// tracking arms against stray (untracked) events.
259 pub(crate) track: Option<OvTrack>,
260 /// Whether the initial [`ov_update`] has run; gates the auto-seed so it
261 /// happens exactly once. Do not assign directly.
262 pub(crate) seeded: bool,
263}
264
265impl OutlineViewerState {
266 /// Create the shared state for an outline viewer.
267 ///
268 /// `bounds` sets the initial geometry; `h` and `v` are the optional
269 /// horizontal and vertical scrollbar ids (pass `None` when scrollbars are
270 /// absent). The view starts selectable, grows with its lower-right corner,
271 /// and focuses at DFS position 0 with a zero scroll offset.
272 ///
273 /// The initial scrollbar population is seeded automatically the first time a
274 /// context-bearing lifecycle call reaches the viewer (event, state change, or
275 /// bounds change), so no explicit [`ov_update`] is needed after construction.
276 /// Call [`ov_update`] explicitly only after mutating the tree (swapping
277 /// [`Outline::root`], or expanding/collapsing programmatically) to recount
278 /// visible nodes and republish the limits.
279 pub fn new(bounds: Rect, h: Option<ViewId>, v: Option<ViewId>) -> Self {
280 let mut state = ViewState::new(bounds);
281 state.options = Options {
282 selectable: true,
283 ..Default::default()
284 };
285 state.grow_mode = GrowMode {
286 hi_x: true,
287 hi_y: true,
288 ..Default::default()
289 };
290 OutlineViewerState {
291 state,
292 delta: Point::new(0, 0),
293 limit: Point::new(0, 0),
294 h_scroll_bar: h,
295 v_scroll_bar: v,
296 foc: 0,
297 abs_origin: Point::new(0, 0),
298 track: None,
299 seeded: false,
300 }
301 }
302
303 /// Set the content extent and (re)publish each bar's range/page params.
304 /// Same formula as [`Scroller::set_limit`](crate::widgets::Scroller::set_limit).
305 pub fn set_limit(&mut self, x: i32, y: i32, ctx: &mut Context) {
306 self.limit = Point::new(x, y);
307 let size = self.state.size;
308 if let Some(h) = self.h_scroll_bar {
309 ctx.request_scroll_bar_params(
310 h,
311 None,
312 Some(0),
313 Some(x - size.x),
314 Some(size.x - 1),
315 None,
316 );
317 }
318 if let Some(v) = self.v_scroll_bar {
319 ctx.request_scroll_bar_params(
320 v,
321 None,
322 Some(0),
323 Some(y - size.y),
324 Some(size.y - 1),
325 None,
326 );
327 }
328 }
329
330 /// Set each bar's value (preserving range and steps).
331 /// Same as [`Scroller::scroll_to`](crate::widgets::Scroller::scroll_to).
332 pub fn scroll_to(&mut self, x: i32, y: i32, ctx: &mut Context) {
333 if let Some(h) = self.h_scroll_bar {
334 ctx.request_scroll_bar_params(h, Some(x), None, None, None, None);
335 }
336 if let Some(v) = self.v_scroll_bar {
337 ctx.request_scroll_bar_params(v, Some(y), None, None, None, None);
338 }
339 }
340
341 /// Apply a freshly-read scrollbar delta. Unlike the scroller's `apply_delta`
342 /// there is no cursor adjust (the outline viewer has no editor cursor); just
343 /// overwrite `delta`. Called by the pump (the read broker) after it resolves
344 /// the bars and reads their `value`s.
345 pub fn apply_delta(&mut self, d: Point) {
346 self.delta = d;
347 }
348
349 /// Show/hide one bar per this viewer's active/selected state: shown when
350 /// either is set, hidden otherwise.
351 fn show_sbar(&self, sbar: Option<ViewId>, ctx: &mut Context) {
352 if let Some(id) = sbar {
353 let visible = self.state.state.active || self.state.state.selected;
354 ctx.request_set_visible(id, visible);
355 }
356 }
357}
358
359// ---------------------------------------------------------------------------
360// OutlineViewer — the overridable methods (a trait)
361// ---------------------------------------------------------------------------
362
363/// The abstract outline-viewer base, as a trait of overridable methods.
364/// Concrete outline widgets implement [`ov`](Self::ov)/[`ov_mut`](Self::ov_mut)
365/// (the data accessors) and the tree-navigation methods; the shared draw / event
366/// / traversal logic (the free functions in this module) is generic over `L:
367/// OutlineViewer` and calls back into these.
368///
369/// Intentionally **not object-safe** (the `'a`-bound getters) — that is fine,
370/// concrete widgets are `Box<dyn View>` and `OutlineViewer` is only ever a generic
371/// bound behind a concrete type (same as [`ListViewer`](crate::widgets::ListViewer)).
372///
373/// **Wiring caveat (no compile-time enforcement):** a concrete outline widget MUST
374/// delegate the relevant `View` methods to this module's free functions: [`ov_draw`],
375/// [`ov_handle_event`], [`ov_set_state`], and [`View::as_any_mut`]
376/// (the cross-view broker downcasts through it).
377///
378/// # Turbo Vision heritage
379///
380/// The trait half of `TOutlineViewer` (`toutline.cpp`): its overridable
381/// tree-navigation virtuals, with the data members in [`OutlineViewerState`] and
382/// the shared logic in this module's free functions.
383pub trait OutlineViewer: View {
384 /// Borrow the embedded [`OutlineViewerState`].
385 fn ov(&self) -> &OutlineViewerState;
386 /// Mutably borrow the embedded [`OutlineViewerState`].
387 fn ov_mut(&mut self) -> &mut OutlineViewerState;
388
389 // -- Abstract read-only virtuals (borrow `&Node`s out of `&self`) ---------
390
391 /// Return the root node of the tree, or `None` if the tree is empty.
392 ///
393 /// Called at the start of every traversal (draw, update, expand-all). The
394 /// concrete widget returns the root of its owned tree; the lifetime `'a`
395 /// ties the returned reference to `&'a self` so that callers can keep it
396 /// alive while iterating.
397 fn get_root(&self) -> Option<&Node>;
398
399 /// Return `node`'s next sibling, or `None` if `node` is the last sibling.
400 ///
401 /// The traversal walks siblings by repeatedly calling this method; `'a`
402 /// ties the returned node to the same lifetime as `node` (which is itself
403 /// already tied to `&'a self` at the call site).
404 fn get_next<'a>(&'a self, node: &'a Node) -> Option<&'a Node>;
405
406 /// Return the `i`-th child of `node` (0-based), or `None` if out of range.
407 ///
408 /// The traversal calls this with `i = 0` to obtain the first child, then
409 /// follows [`get_next`](Self::get_next) for subsequent siblings. A concrete
410 /// widget that stores children in a `Vec` may use `children.get(i as usize)`.
411 fn get_child<'a>(&'a self, node: &'a Node, i: i32) -> Option<&'a Node>;
412
413 /// Return the number of direct children of `node`.
414 ///
415 /// Used by the traversal and by [`ov_update`] to decide whether to recurse.
416 /// Must agree with [`has_children`](Self::has_children): return `0` iff
417 /// `has_children` returns `false`.
418 fn get_num_children(&self, node: &Node) -> i32;
419
420 /// Return the display text for `node`, borrowed from `self`.
421 ///
422 /// Displayed verbatim in the outline row to the right of the graph prefix.
423 /// The lifetime `'a` allows returning a `&str` into the node's own storage
424 /// without copying.
425 fn get_text<'a>(&'a self, node: &'a Node) -> &'a str;
426
427 /// Return `true` if `node`'s children are currently shown.
428 ///
429 /// The traversal recurses into `node` only when both `has_children` and
430 /// `is_expanded` return `true`. For [`Outline`], this reads
431 /// [`Node::expanded`]. Override to store the expanded state externally (for
432 /// example in a `HashMap<NodeId, bool>`).
433 fn is_expanded(&self, node: &Node) -> bool;
434
435 /// Return `true` if `node` has at least one child.
436 ///
437 /// Determines whether the graph prefix shows an expand/collapse indicator
438 /// and whether the traversal may recurse. Must agree with
439 /// [`get_num_children`](Self::get_num_children).
440 fn has_children(&self, node: &Node) -> bool;
441
442 // -- Abstract mutation method ---------------------------------------------
443
444 /// Set the expanded state of the node at DFS position `pos` in the
445 /// **currently visible** tree (0-based, same numbering as
446 /// [`foc`](OutlineViewerState::foc)).
447 ///
448 /// Called by the keyboard handler (`+`/`-`/`*` keys) and by the mouse
449 /// handler when the user clicks the graph prefix column. After `adjust`
450 /// returns, the caller invokes [`ov_update`] to recount visible nodes and
451 /// republish scrollbar limits.
452 ///
453 /// The contract is keyed by DFS position rather than a node reference,
454 /// because the shared free functions only hold `&self`; the concrete widget
455 /// resolves `pos` to the owned node mutably.
456 fn adjust(&mut self, pos: i32, expand: bool);
457
458 // -- Overridable with defaults --------------------------------------------
459
460 /// Notify the concrete widget that node at DFS position `i` received focus.
461 ///
462 /// The default writes `i` to [`OutlineViewerState::foc`]. Override to
463 /// maintain additional per-item focus state, such as a selection set.
464 /// Always call `self.ov_mut().foc = i` (or `super`) to keep the default
465 /// rendering consistent.
466 fn focused_item(&mut self, i: i32) {
467 self.ov_mut().foc = i;
468 }
469
470 /// Return `true` if DFS position `i` should be drawn in the selected color.
471 ///
472 /// The default returns `i == foc` (single-selection mode). Override in a
473 /// multi-select widget to highlight a range or set of positions in addition
474 /// to the focused one.
475 fn is_selected(&self, i: i32) -> bool {
476 self.ov().foc == i
477 }
478
479 /// The user committed to DFS position `i` (double-click or Enter key).
480 ///
481 /// The default does nothing. Override to react — for example, broadcast
482 /// [`Command::OUTLINE_ITEM_SELECTED`] so that an enclosing dialog can read
483 /// the focused node and act on it.
484 fn selected(&mut self, _i: i32) {}
485}
486
487// ---------------------------------------------------------------------------
488// Traversal core — the DFS visitor
489// ---------------------------------------------------------------------------
490
491/// The inner recursion of a tree traversal: visit `node` and (if expanded) its
492/// visible subtree, calling `action(this, node, level, position, lines, flags)`.
493/// Returns `true` if the visitor stopped the traversal.
494///
495/// `flags`: [`OV_EXPANDED`] if the node is a leaf or expanded; [`OV_CHILDREN`]
496/// if it has children and is expanded; [`OV_LAST`] if it is its parent's last
497/// child. `lines`: bit N set means level N has a continuation bar at/below this
498/// node. `position` is pre-incremented before each visit (so 0-based after the
499/// first).
500///
501/// Root-level siblings are handled by the caller [`traverse`], NOT here — we
502/// only ever enter this for a node already chosen by `traverse`.
503fn traverse_inner<L, F>(
504 this: &L,
505 action: &mut F,
506 node: &Node,
507 level: i32,
508 lines: i64,
509 position: &mut i32,
510 last_child: bool,
511) -> bool
512where
513 L: OutlineViewer + ?Sized,
514 F: FnMut(&L, &Node, i32, i32, i64, u16) -> bool,
515{
516 let children = this.has_children(node);
517 let expanded = this.is_expanded(node);
518
519 let mut flags: u16 = 0;
520 if last_child {
521 flags |= OV_LAST;
522 }
523 if children && expanded {
524 flags |= OV_CHILDREN;
525 }
526 if !children || expanded {
527 flags |= OV_EXPANDED;
528 }
529
530 *position += 1;
531 if action(this, node, level, *position, lines, flags) {
532 return true;
533 }
534
535 if children && expanded {
536 let child_lines = if !last_child {
537 lines | (1i64 << level)
538 } else {
539 lines
540 };
541 let mut child = this.get_child(node, 0);
542 while let Some(c) = child {
543 let next = this.get_next(c);
544 let is_last = next.is_none();
545 if traverse_inner(this, action, c, level + 1, child_lines, position, is_last) {
546 return true;
547 }
548 child = next;
549 }
550 }
551 false
552}
553
554/// DFS-visit every currently visible node, calling `action` for each.
555///
556/// The visitor signature is `(this, node, level, position, lines, flags) -> bool`,
557/// where `level` is the nesting depth (0 = root), `position` is the 0-based DFS
558/// counter, `lines` is a bitmask of levels that have a continuation bar, and
559/// `flags` is a combination of `OV_EXPANDED`, `OV_CHILDREN`, and `OV_LAST`.
560/// Returning `true` from `action` stops the traversal early (like C++ `firstThat`);
561/// returning `false` visits all nodes (like C++ `forEach`).
562///
563/// Collapsed subtrees are skipped — only the nodes that are visually present are
564/// visited. Use this when you need to count visible nodes, build a row list, or
565/// search the visible tree.
566///
567/// # Turbo Vision heritage
568///
569/// Collapses the two C++ methods `TOutlineViewer::firstThat` (stop on `true`)
570/// and `forEach` (visit all) into one generic function.
571pub fn traverse<L, F>(this: &L, action: &mut F)
572where
573 L: OutlineViewer + ?Sized,
574 F: FnMut(&L, &Node, i32, i32, i64, u16) -> bool,
575{
576 let Some(root) = this.get_root() else {
577 return;
578 };
579 let mut position = -1i32;
580
581 let root_last = this.get_next(root).is_none();
582 if traverse_inner(this, action, root, 0, 0, &mut position, root_last) {
583 return;
584 }
585
586 // Root-level siblings.
587 let mut sibling = this.get_next(root);
588 while let Some(s) = sibling {
589 let next = this.get_next(s);
590 let is_last = next.is_none();
591 if traverse_inner(this, action, s, 0, 0, &mut position, is_last) {
592 return;
593 }
594 sibling = next;
595 }
596}
597
598/// Return the `(level, lines, flags)` of the node at DFS position `pos`,
599/// or `None` if `pos` is out of range.
600///
601/// `level` is the nesting depth (0 = root); `lines` is the continuation-bar
602/// bitmask used by `create_graph`; `flags` combines `OV_EXPANDED`,
603/// `OV_CHILDREN`, and `OV_LAST`.
604///
605/// The draw and event code uses this to retrieve graph-draw parameters for the
606/// focused node so it can determine whether a mouse click landed in the graph
607/// column. You can call it directly when you need the structural metadata of a
608/// specific DFS position.
609///
610/// # Turbo Vision heritage
611///
612/// Replaces `TOutlineViewer::getNode`, which returned a raw `TNode*`. Returning
613/// `(level, lines, flags)` instead avoids exposing a mutable pointer into the
614/// owned tree.
615pub fn ov_get_node_info<L: OutlineViewer + ?Sized>(this: &L, pos: i32) -> Option<(i32, i64, u16)> {
616 let mut result = None;
617 traverse(this, &mut |_ov: &L,
618 _node: &Node,
619 level,
620 position,
621 lines,
622 flags| {
623 if position == pos {
624 result = Some((level, lines, flags));
625 true
626 } else {
627 false
628 }
629 });
630 result
631}
632
633// ---------------------------------------------------------------------------
634// create_graph / get_graph — the indent/box-drawing prefix
635// ---------------------------------------------------------------------------
636
637/// Build the box-drawing prefix string for one outline row.
638///
639/// Returns the indent and connector graphic that appears to the left of each
640/// node's text label. `level` is the nesting depth (0 = root);
641/// `lines` is the continuation-bar bitmask (bit `k` set means level `k` draws a
642/// vertical bar through this row); `flags` combines `OV_EXPANDED`, `OV_CHILDREN`,
643/// and `OV_LAST`; `lev_width` and `end_width` are the column widths of the
644/// per-level indent and the connector end-graphic (both 3 in the default style).
645///
646/// `chars` maps symbol roles to characters:
647/// `[0]` = level filler (space), `[1]` = level continuation bar (│),
648/// `[2]` = end connector for a non-last child (├), `[3]` = end connector for
649/// the last child (└), `[4]` = end filler / straight run (─),
650/// `[5]` = end child-link indicator (─ or a custom char), `[6]` = retracted
651/// (collapsed, `+`), `[7]` = expanded (─ or space).
652///
653/// Use [`ov_get_graph`] for the default style. Call `create_graph` directly only
654/// when you need a custom character set or different column widths.
655///
656/// # Turbo Vision heritage
657///
658/// Ports `TOutlineViewer::createGraph` (`toutline.cpp`). The C++ `const char*`
659/// byte string becomes a `&[char; 8]` typed array.
660pub fn create_graph(
661 level: i32,
662 mut lines: i64,
663 flags: u16,
664 lev_width: i32,
665 mut end_width: i32,
666 chars: &[char; 8],
667) -> String {
668 const FILLER_OR_BAR: usize = 0;
669 const Y_OR_L: usize = 2;
670 const STRAIGHT_OR_TEE: usize = 4;
671 const RETRACTED: usize = 6;
672
673 let expanded = (flags & OV_EXPANDED) != 0;
674 let children = (flags & OV_CHILDREN) != 0;
675 let last = (flags & OV_LAST) != 0;
676
677 let mut graph = String::new();
678
679 // Level marks: per level, the mark-or-filler, then `lev_width - 1` fillers.
680 let mut lev = level;
681 while lev > 0 {
682 graph.push(if lines & 1 != 0 {
683 chars[FILLER_OR_BAR + 1]
684 } else {
685 chars[FILLER_OR_BAR]
686 });
687 for _ in 0..(lev_width - 1) {
688 graph.push(chars[FILLER_OR_BAR]);
689 }
690 lev -= 1;
691 lines >>= 1;
692 }
693
694 // End graphic (the decrementing end-width cascade).
695 end_width -= 1;
696 if end_width > 0 {
697 graph.push(if last {
698 chars[Y_OR_L + 1]
699 } else {
700 chars[Y_OR_L]
701 });
702 end_width -= 1;
703 if end_width > 0 {
704 end_width -= 1;
705 if end_width > 0 {
706 for _ in 0..end_width {
707 graph.push(chars[STRAIGHT_OR_TEE]);
708 }
709 }
710 graph.push(if children {
711 chars[STRAIGHT_OR_TEE + 1]
712 } else {
713 chars[STRAIGHT_OR_TEE]
714 });
715 }
716 graph.push(if expanded {
717 chars[RETRACTED + 1]
718 } else {
719 chars[RETRACTED]
720 });
721 }
722
723 graph
724}
725
726/// Return the default box-drawing prefix for one outline row.
727///
728/// Uses a level width and end width of 3, and the classic box-drawing character
729/// set (space, │, ├, └, ─, ─, +, ─). Called from [`ov_draw`] for every visible
730/// row. To use a different character set or column widths, build an outline
731/// viewer that does not call `ov_draw` and instead calls [`create_graph`]
732/// directly with the desired parameters.
733///
734/// # Turbo Vision heritage
735///
736/// Ports `TOutlineViewer::getGraph` (`toutline.cpp`). The C++ virtual method
737/// becomes a free function; a concrete widget that wants a different style
738/// replaces the call rather than overriding the method.
739pub fn ov_get_graph<L: OutlineViewer + ?Sized>(
740 _this: &L,
741 level: i32,
742 lines: i64,
743 flags: u16,
744 ctx: &DrawCtx,
745) -> String {
746 let g = ctx.glyphs();
747 // "\x20\xB3\xC3\xC0\xC4\xC4+\xC4": space, │, ├, └, ─, ─, +, ─.
748 let chars: [char; 8] = [
749 ' ',
750 g.frame_v,
751 g.frame_tee_l,
752 g.frame_bl,
753 g.frame_h,
754 g.frame_h,
755 '+',
756 g.frame_h,
757 ];
758 create_graph(level, lines, flags, 3, 3, &chars)
759}
760
761// ---------------------------------------------------------------------------
762// ov_draw — render the visible tree
763// ---------------------------------------------------------------------------
764
765/// Render every visible node.
766///
767/// Per visible node: compute the color (focused / selected / normal), fill the
768/// row, draw the graph then the text (the text uses the dim color when the node
769/// is not expanded), shifted left by `delta.x`. After the traversal the remaining
770/// rows are blank-filled.
771///
772/// NOTE: `this: &mut L` (not `&L`) — the `abs_origin` cache write requires
773/// mutability. The drawing is logically read-only, but the origin is stored here
774/// to feed [`Context::start_mouse_track`] (the `Button::abs_origin` pattern).
775pub fn ov_draw<L: OutlineViewer + ?Sized>(this: &mut L, ctx: &mut DrawCtx) {
776 // Cache the absolute origin for the mouse-tracking capture, which converts
777 // absolute mouse coords to view-local via this value.
778 this.ov_mut().abs_origin = ctx.origin();
779 let size = this.ov().state.size;
780 let delta = this.ov().delta;
781 let foc = this.ov().foc;
782 let focused_state = this.ov().state.state.focused;
783
784 // Normal-row surface: the shared three-surface rule (see
785 // `DrawCtx::content_surface`) — `owner_active` recedes the whole outline to
786 // OutlineInactive regardless of its own focus; within an active pane, own
787 // focus picks well-vs-surface — a focused outline (or one that can never be
788 // selected) is the OutlineNormal well, and an unfocused *selectable* sibling
789 // sits on OutlineSurface. classic_blue collapses all three to the same
790 // color, so unthemed outlines are unchanged.
791 let nrm_color = ctx.content_surface(
792 SURFACE_ROLES,
793 focused_state,
794 this.ov().state.options.selectable,
795 );
796 let focused_color = ctx.style(Role::OutlineFocused);
797 let selected_color = ctx.style(Role::OutlineSelected);
798 let not_expanded_color = ctx.style(Role::OutlineNotExpanded);
799
800 // Last drawn position (-1 if nothing drawn).
801 let mut aux_pos = -1i32;
802
803 // The closure cannot borrow `ctx` (it would need a second &mut alongside the
804 // generic `this`), so we gather the draw instructions and apply them after.
805 struct Row {
806 position: i32,
807 level: i32,
808 lines: i64,
809 flags: u16,
810 text: String,
811 }
812 let mut rows: Vec<Row> = Vec::new();
813
814 traverse(this, &mut |this: &L,
815 node: &Node,
816 level,
817 position,
818 lines,
819 flags| {
820 if position >= delta.y {
821 if position >= delta.y + size.y {
822 return true; // past the bottom — stop
823 }
824 rows.push(Row {
825 position,
826 level,
827 lines,
828 flags,
829 text: this.get_text(node).to_string(),
830 });
831 aux_pos = position;
832 }
833 false
834 });
835
836 for row in &rows {
837 // Color selection: each row has a base color and a "dim" color used for
838 // the text of a not-expanded node. For focused/selected rows the dim
839 // color equals the base color; only a normal row dims to NotExpanded.
840 let (color, dim_color) = if row.position == foc && focused_state {
841 (focused_color, focused_color)
842 } else if this.is_selected(row.position) {
843 (selected_color, selected_color)
844 } else {
845 (nrm_color, not_expanded_color)
846 };
847
848 let y = row.position - delta.y;
849 // Fill the whole row first.
850 ctx.fill(Rect::new(0, y, size.x, y + 1), ' ', color);
851
852 // Graph: drawn from column 0, shifted left by delta.x.
853 let graph = ov_get_graph(this, row.level, row.lines, row.flags, ctx);
854 let graph_w = graph.chars().count() as i32;
855 // The text starts at max(0, graph_width - delta.x).
856 let x = graph_w - delta.x;
857 if x > 0 {
858 // Skip delta.x leading columns of the graph.
859 ctx.put_str_part(0, y, &graph, delta.x, color);
860 }
861
862 // Text: dim color when not expanded, else the row color.
863 let text_color = if row.flags & OV_EXPANDED != 0 {
864 color
865 } else {
866 dim_color
867 };
868 let text_x = x.max(0);
869 let text_skip = (-x).max(0);
870 ctx.put_str_part(text_x, y, &row.text, text_skip, text_color);
871 }
872
873 // Blank the remaining rows below the last drawn node. The last drawn DFS
874 // position (`aux_pos`) is converted to a view-local row by subtracting
875 // `delta.y`, so the fill never draws off the top when scrolled.
876 let first_blank = aux_pos + 1 - delta.y;
877 if first_blank < size.y {
878 ctx.fill(
879 Rect::new(0, first_blank.max(0), size.x, size.y),
880 ' ',
881 nrm_color,
882 );
883 }
884}
885
886// ---------------------------------------------------------------------------
887// Focus / navigation / event handling
888// ---------------------------------------------------------------------------
889
890/// Clamp `new_focus`, focus it, and scroll it into view.
891pub fn adjust_focus<L: OutlineViewer + ?Sized>(
892 this: &mut L,
893 mut new_focus: i32,
894 ctx: &mut Context,
895) {
896 let limit_y = this.ov().limit.y;
897 if new_focus < 0 {
898 new_focus = 0;
899 } else if new_focus >= limit_y {
900 new_focus = limit_y - 1;
901 }
902 if this.ov().foc != new_focus {
903 this.focused_item(new_focus);
904 }
905 let delta = this.ov().delta;
906 let size_y = this.ov().state.size.y;
907 if new_focus < delta.y {
908 this.ov_mut().scroll_to(delta.x, new_focus, ctx);
909 } else if (new_focus - size_y) >= delta.y {
910 this.ov_mut()
911 .scroll_to(delta.x, new_focus - size_y + 1, ctx);
912 }
913}
914
915/// Recount the visible nodes, republish the scrollbar limits, and re-clamp the
916/// focus.
917///
918/// This is invoked automatically on first display or interaction via
919/// `ensure_seeded`, so you only need to call it explicitly after mutating the
920/// tree (node inserted, removed, or expanded/collapsed programmatically).
921///
922/// Internally this counts only the currently-visible nodes (collapsed subtrees
923/// are excluded), computes the maximum row width, calls
924/// [`OutlineViewerState::set_limit`] to publish those extents to the scrollbars,
925/// and then calls [`adjust_focus`] to re-clamp `foc` within the new count.
926pub fn ov_update<L: OutlineViewer + ?Sized>(this: &mut L, ctx: &mut Context) {
927 // Count visible nodes and the max graph+text width. The default graph width
928 // is deterministic — `level * 3 + 3` (level width = end width = 3) — so we
929 // compute it analytically rather than building the graph string per node.
930 let mut count = 0i32;
931 let mut max_x = 0i32;
932 traverse(this, &mut |this: &L,
933 node: &Node,
934 level,
935 _position,
936 _lines,
937 _flags| {
938 count += 1;
939 let graph_w = level * 3 + 3;
940 let text_w = this.get_text(node).chars().count() as i32;
941 let len = graph_w + text_w;
942 if max_x < len {
943 max_x = len;
944 }
945 false
946 });
947 this.ov_mut().seeded = true;
948 this.ov_mut().set_limit(max_x, count, ctx);
949 let foc = this.ov().foc;
950 adjust_focus(this, foc, ctx);
951}
952
953/// Expand the node at DFS position `pos` and all of its descendants.
954///
955/// Sibling nodes of the subtree at `pos` are left unchanged. This is the
956/// operation bound to the `*` key: press `*` to recursively expand everything
957/// under the focused node.
958///
959/// Because DFS positions shift each time a node expands, the algorithm restarts
960/// the traversal each round: it finds the nesting depth of `pos` once, then
961/// repeatedly locates the first unexpanded node-with-children inside that
962/// subtree and calls [`OutlineViewer::adjust`] to expand it. The loop
963/// terminates when no unexpanded node-with-children remains in the subtree.
964///
965/// After the loop, call [`ov_update`] to recount visible nodes and publish the
966/// new scrollbar limits.
967pub fn ov_expand_all<L: OutlineViewer + ?Sized>(this: &mut L, pos: i32) {
968 // 1. Find the level of the node at `pos`.
969 let mut start_level = 0i32;
970 let mut found_start = false;
971 traverse(this, &mut |_ov: &L,
972 _node: &Node,
973 level,
974 position,
975 _lines,
976 _flags| {
977 if position == pos {
978 start_level = level;
979 found_start = true;
980 true
981 } else {
982 false
983 }
984 });
985 if !found_start {
986 return;
987 }
988
989 // 2. Loop: expand the first eligible unexpanded node-with-children.
990 loop {
991 let mut to_expand: Option<i32> = None;
992 traverse(this, &mut |ov: &L,
993 node: &Node,
994 level,
995 position,
996 _lines,
997 _flags| {
998 if position < pos {
999 return false;
1000 }
1001 // A node at the start level or shallower past `pos` is a sibling (or
1002 // ancestor's sibling) — stop the scan.
1003 if level <= start_level && position > pos {
1004 return true;
1005 }
1006 if ov.has_children(node) && !ov.is_expanded(node) {
1007 to_expand = Some(position);
1008 return true;
1009 }
1010 false
1011 });
1012 match to_expand {
1013 Some(p) => this.adjust(p, true),
1014 None => break,
1015 }
1016 }
1017}
1018
1019/// Run the initial [`ov_update`] exactly once, the first time a context-bearing
1020/// lifecycle call reaches the viewer. After this, navigation and scrollbars are
1021/// correct without the consumer calling `ov_update` manually; an explicit
1022/// `ov_update` is still required after MUTATING the tree (see its docs).
1023fn ensure_seeded<L: OutlineViewer + ?Sized>(this: &mut L, ctx: &mut Context) {
1024 if !this.ov().seeded {
1025 ov_update(this, ctx); // sets seeded = true
1026 }
1027}
1028
1029/// Apply a view-state flag change to an outline viewer.
1030///
1031/// Delegates to the concrete widget's [`View`] method. In addition to flipping
1032/// the flag, this function:
1033/// - On [`StateFlag::Focused`]: broadcasts [`Command::RECEIVED_FOCUS`] or
1034/// [`Command::RELEASED_FOCUS`] so the rest of the application can track which
1035/// outline has keyboard focus.
1036/// - On [`StateFlag::Active`] or [`StateFlag::Selected`]: shows or hides both
1037/// scrollbars to match the visibility convention (bars appear when the viewer
1038/// is active or selected, hide otherwise).
1039///
1040/// Concrete widgets that delegate `View::set_state` to this function
1041/// (as [`Outline`] does) get the scroller-compatible show/hide behavior for
1042/// free without duplicating it.
1043pub fn ov_set_state<L: OutlineViewer + ?Sized>(
1044 this: &mut L,
1045 flag: StateFlag,
1046 enable: bool,
1047 ctx: &mut Context,
1048) {
1049 ensure_seeded(this, ctx);
1050 this.ov_mut().state.set_flag(flag, enable);
1051 if flag == StateFlag::Focused {
1052 let source = this.ov().state.id();
1053 ctx.broadcast(
1054 if enable {
1055 Command::RECEIVED_FOCUS
1056 } else {
1057 Command::RELEASED_FOCUS
1058 },
1059 source,
1060 );
1061 }
1062 if flag == StateFlag::Active || flag == StateFlag::Selected {
1063 let h = this.ov().h_scroll_bar;
1064 let v = this.ov().v_scroll_bar;
1065 this.ov().show_sbar(h, ctx);
1066 this.ov().show_sbar(v, ctx);
1067 }
1068}
1069
1070/// The scrollbar broadcast filter (inherited from the scroller), mouse
1071/// hold-tracking, and the keyboard nav switch.
1072///
1073/// The press-and-hold / edge auto-scroll loop runs through the
1074/// `MouseTrackCapture`: `MouseDown` arms the capture; tracked
1075/// `MouseMove`/`MouseAuto` route the loop body; `MouseUp` runs the post-loop
1076/// graph-toggle logic (`dragged < 2` distinguishes click from drag).
1077pub fn ov_handle_event<L: OutlineViewer + View + ?Sized>(
1078 this: &mut L,
1079 ev: &mut Event,
1080 ctx: &mut Context,
1081) {
1082 ensure_seeded(this, ctx);
1083 // The scroll-bar-changed read-sync filter (same as the scroller). Do NOT
1084 // clear the event — it stays live for the scrollbar's own handling.
1085 if let Event::Broadcast { command, source } = *ev
1086 && command == Command::SCROLL_BAR_CHANGED
1087 && source.is_some()
1088 && (source == this.ov().h_scroll_bar || source == this.ov().v_scroll_bar)
1089 && let Some(id) = this.ov().state.id()
1090 {
1091 ctx.request_scroll_sync(id, this.ov().h_scroll_bar, this.ov().v_scroll_bar);
1092 }
1093
1094 match *ev {
1095 // -------------------------------------------------------------------
1096 // evMouseDown — first loop iteration: position, then arm the
1097 // mouse-track capture.
1098 //
1099 // The loop body runs once per DOWN, MOVE, or AUTO event; the post-loop
1100 // block (double-click / graph-toggle) runs after the hold ends.
1101 //
1102 // Unlike ListViewer, the post-loop logic is COMPLEX — it depends on
1103 // `dragged` (how many iterations ran) and `mouse.x` at exit. We store
1104 // `dragged` in `OvTrack` so the MouseUp arm can perform the post-loop
1105 // checks faithfully.
1106 // -------------------------------------------------------------------
1107 Event::MouseDown(me) => {
1108 let delta = this.ov().delta;
1109 let limit_y = this.ov().limit.y;
1110 let foc = this.ov().foc;
1111 // mouse is view-local already (the group delivers view-local coords).
1112 let mouse = me.position;
1113 // mouseInView: the click landed inside this view's extent.
1114 let in_view = mouse.x >= 0
1115 && mouse.y >= 0
1116 && mouse.x < this.ov().state.size.x
1117 && mouse.y < this.ov().state.size.y;
1118 let new_focus = if in_view {
1119 let i = delta.y + mouse.y;
1120 if i < limit_y { i } else { foc }
1121 } else {
1122 foc
1123 };
1124
1125 // First loop iteration: position (C++ body line 436-462).
1126 // `dragged` starts at 0, then incremented to 1 on the first
1127 // iteration (C++ `if (dragged < 2) dragged++`).
1128 let dragged: u8 = 1; // after first iteration
1129 if foc != new_focus {
1130 adjust_focus(this, new_focus, ctx);
1131 }
1132
1133 if me.flags.double_click {
1134 // Double-click: break immediately (no tracking), then
1135 // post-loop: `selected(foc)`. `foc` is the focused item at
1136 // break time (which is `new_focus` after the first iteration).
1137 this.selected(this.ov().foc);
1138 ev.clear();
1139 } else if let Some(id) = this.ov().state.id() {
1140 // Non-double-click: arm the mouse-track capture. The post-loop
1141 // graph-toggle logic runs in the MouseUp arm.
1142 let abs_origin = this.ov().abs_origin;
1143 this.ov_mut().track = Some(OvTrack { count: 0, dragged });
1144 ctx.start_mouse_track(
1145 id,
1146 abs_origin,
1147 TrackMask {
1148 mouse_move: true,
1149 mouse_auto: true,
1150 ..Default::default()
1151 },
1152 );
1153 ev.clear();
1154 } else {
1155 // Uninserted (test/degenerate) widget: single-shot behavior, no
1156 // hold tracking.
1157 if let Some((level, _lines, flags)) = ov_get_node_info(this, this.ov().foc) {
1158 let graph_w = level * 3 + 3;
1159 if mouse.x < graph_w {
1160 let cur_pos = this.ov().foc;
1161 let expanded = flags & OV_EXPANDED != 0;
1162 this.adjust(cur_pos, !expanded);
1163 ov_update(this, ctx);
1164 }
1165 }
1166 ev.clear();
1167 }
1168 }
1169
1170 // -------------------------------------------------------------------
1171 // evMouseMove (tracked) — the loop body's in-view move case.
1172 //
1173 // C++ toutline.cpp:437-462: `if (dragged < 2) dragged++` fires first
1174 // (every iteration), then `if (mouseInView)` → compute newFocus.
1175 // Out-of-view moves do nothing (only evMouseAuto steps the focus).
1176 // Guarded by `track.is_some()`.
1177 // -------------------------------------------------------------------
1178 Event::MouseMove(me) if this.ov().track.is_some() => {
1179 let delta = this.ov().delta;
1180 let limit_y = this.ov().limit.y;
1181 let foc = this.ov().foc;
1182 let mouse = me.position;
1183 let size = this.ov().state.size;
1184 let in_view = mouse.x >= 0 && mouse.y >= 0 && mouse.x < size.x && mouse.y < size.y;
1185
1186 // Increment dragged (capped at 2) — faithful: first in the loop body.
1187 if let Some(t) = this.ov_mut().track.as_mut()
1188 && t.dragged < 2
1189 {
1190 t.dragged += 1;
1191 }
1192
1193 if in_view {
1194 let new_focus = {
1195 let i = delta.y + mouse.y;
1196 if i < limit_y { i } else { foc }
1197 };
1198 if foc != new_focus {
1199 adjust_focus(this, new_focus, ctx);
1200 }
1201 }
1202 // Out-of-view moves: no-op (only evMouseAuto steps for out-of-view).
1203 ev.clear();
1204 }
1205
1206 // -------------------------------------------------------------------
1207 // evMouseAuto (tracked) — the loop body's auto-scroll case.
1208 //
1209 // C++ toutline.cpp:437-462: `if (dragged < 2) dragged++`; then
1210 // `if (mouseInView)` → compute newFocus; else: `count++`, if
1211 // `count == mouseAutoToSkip` (3): reset, step by ±1 based on y.
1212 // Guarded by `track.is_some()`.
1213 // -------------------------------------------------------------------
1214 Event::MouseAuto(me) if this.ov().track.is_some() => {
1215 let delta = this.ov().delta;
1216 let limit_y = this.ov().limit.y;
1217 let foc = this.ov().foc;
1218 let mouse = me.position;
1219 let size = this.ov().state.size;
1220 let in_view = mouse.x >= 0 && mouse.y >= 0 && mouse.x < size.x && mouse.y < size.y;
1221
1222 // Increment dragged (capped at 2) — faithful: first in the loop body.
1223 if let Some(t) = this.ov_mut().track.as_mut()
1224 && t.dragged < 2
1225 {
1226 t.dragged += 1;
1227 }
1228
1229 let new_focus = if in_view {
1230 let i = delta.y + mouse.y;
1231 if i < limit_y { i } else { foc }
1232 } else {
1233 // Out-of-view AUTO: increment count, step every MOUSE_AUTO_TO_SKIP ticks.
1234 let stepped = if let Some(t) = this.ov_mut().track.as_mut() {
1235 t.count += 1;
1236 if t.count == MOUSE_AUTO_TO_SKIP {
1237 t.count = 0;
1238 true
1239 } else {
1240 false
1241 }
1242 } else {
1243 false
1244 };
1245 if stepped {
1246 if mouse.y < 0 {
1247 foc - 1
1248 } else if mouse.y >= size.y {
1249 foc + 1
1250 } else {
1251 foc
1252 }
1253 } else {
1254 foc
1255 }
1256 };
1257
1258 if foc != new_focus {
1259 adjust_focus(this, new_focus, ctx);
1260 }
1261 ev.clear();
1262 }
1263
1264 // -------------------------------------------------------------------
1265 // evMouseUp (tracked) — post-loop logic (toutline.cpp:465-480).
1266 //
1267 // C++ post-loop:
1268 // if (meDoubleClick) selected(foc);
1269 // else if (dragged < 2 && firstThat(isFocused) != 0) {
1270 // graph = getGraph(focLevel,focLines,focFlags);
1271 // if (mouse.x < strwidth(graph)) { adjust; update; }
1272 // }
1273 //
1274 // `meDoubleClick` cannot arrive via a MouseUp (it's only on a down event),
1275 // so in the capture flow the double-click branch is unreachable here.
1276 // `dragged < 2` gates the graph-toggle: only a short press (≤1 iteration
1277 // after the first) toggles expansion; a drag must NOT toggle.
1278 // `mouse` at exit is the last localized position, which for MouseUp is
1279 // the release position (the capture forwards the localized up event).
1280 // Guarded by `track.is_some()`.
1281 // -------------------------------------------------------------------
1282 Event::MouseUp(me) if this.ov().track.is_some() => {
1283 let mouse = me.position;
1284 let dragged = this.ov().track.map(|t| t.dragged).unwrap_or(2);
1285 this.ov_mut().track = None;
1286
1287 // Post-loop graph-toggle: only if dragged < 2 (it was a click, not
1288 // a drag) and there is a focused node with a graph column.
1289 if dragged < 2
1290 && let Some((level, _lines, flags)) = ov_get_node_info(this, this.ov().foc)
1291 {
1292 let graph_w = level * 3 + 3;
1293 if mouse.x < graph_w {
1294 let cur_pos = this.ov().foc;
1295 let expanded = flags & OV_EXPANDED != 0;
1296 this.adjust(cur_pos, !expanded);
1297 ov_update(this, ctx);
1298 }
1299 }
1300 ev.clear();
1301 }
1302
1303 Event::KeyDown(ke) => {
1304 let foc = this.ov().foc;
1305 let size_y = this.ov().state.size.y;
1306 let delta = this.ov().delta;
1307 let limit_y = this.ov().limit.y;
1308
1309 let mut new_focus = foc;
1310 let mapped = ctrl_to_arrow(ke);
1311
1312 // kbCtrlPgUp / kbCtrlPgDn first (matched on the decomposed key, like the
1313 // list viewer — ctrl_to_arrow leaves PageUp/PageDown unchanged).
1314 if matches!(ke.key, Key::PageUp) && ke.modifiers.ctrl {
1315 new_focus = 0;
1316 clear_and_adjust(this, new_focus, ctx, ev);
1317 return;
1318 }
1319 if matches!(ke.key, Key::PageDown) && ke.modifiers.ctrl {
1320 new_focus = limit_y - 1;
1321 clear_and_adjust(this, new_focus, ctx, ev);
1322 return;
1323 }
1324
1325 match mapped.key {
1326 Key::Up | Key::Left => {
1327 new_focus -= 1;
1328 clear_and_adjust(this, new_focus, ctx, ev);
1329 }
1330 Key::Down | Key::Right => {
1331 new_focus += 1;
1332 clear_and_adjust(this, new_focus, ctx, ev);
1333 }
1334 Key::PageDown => {
1335 new_focus += size_y - 1;
1336 clear_and_adjust(this, new_focus, ctx, ev);
1337 }
1338 Key::PageUp => {
1339 new_focus -= size_y - 1;
1340 clear_and_adjust(this, new_focus, ctx, ev);
1341 }
1342 Key::Home => {
1343 new_focus = delta.y;
1344 clear_and_adjust(this, new_focus, ctx, ev);
1345 }
1346 Key::End => {
1347 new_focus = delta.y + size_y - 1;
1348 clear_and_adjust(this, new_focus, ctx, ev);
1349 }
1350 Key::Enter => {
1351 // kbEnter / kbCtrlEnter → selected(newFocus).
1352 this.selected(new_focus);
1353 clear_and_adjust(this, new_focus, ctx, ev);
1354 }
1355 Key::Char(c) => match c {
1356 '+' => {
1357 let cur = this.ov().foc;
1358 this.adjust(cur, true);
1359 ov_update(this, ctx);
1360 clear_and_adjust(this, new_focus, ctx, ev);
1361 }
1362 '-' => {
1363 let cur = this.ov().foc;
1364 this.adjust(cur, false);
1365 ov_update(this, ctx);
1366 clear_and_adjust(this, new_focus, ctx, ev);
1367 }
1368 '*' => {
1369 let cur = this.ov().foc;
1370 ov_expand_all(this, cur);
1371 ov_update(this, ctx);
1372 clear_and_adjust(this, new_focus, ctx, ev);
1373 }
1374 _ => {} // C++ default: return (event left live).
1375 },
1376 _ => {} // unhandled nav key — return (event left live).
1377 }
1378 }
1379
1380 _ => {}
1381 }
1382}
1383
1384/// Helper for the keyboard handler: clear the event, then adjust the focus.
1385fn clear_and_adjust<L: OutlineViewer + ?Sized>(
1386 this: &mut L,
1387 new_focus: i32,
1388 ctx: &mut Context,
1389 ev: &mut Event,
1390) {
1391 ev.clear();
1392 adjust_focus(this, new_focus, ctx);
1393}
1394
1395// ---------------------------------------------------------------------------
1396// Outline — the concrete outline over an owned tree
1397// ---------------------------------------------------------------------------
1398
1399/// A collapsible tree widget backed by an owned [`Node`] tree.
1400///
1401/// `Outline` is the ready-to-use concrete outline viewer. Build a [`Node`]
1402/// tree with [`Node::new`] and the builder methods, pass it to [`Outline::new`],
1403/// insert the widget into a group, and call [`ov_update`] once to publish the
1404/// scrollbar parameters. After that, the widget handles keyboard and mouse
1405/// navigation on its own.
1406///
1407/// To replace the displayed tree at runtime, assign a new value to
1408/// [`Outline::root`] and call [`ov_update`] again so the scrollbar limits
1409/// reflect the new content.
1410///
1411/// # Turbo Vision heritage
1412///
1413/// Ports `TOutline` (`toutline.cpp`). The C++ pointer-based tree becomes owned
1414/// `Box<Node>` links whose recursive drop replaces the explicit `disposeNode`
1415/// destructor.
1416pub struct Outline {
1417 ov: OutlineViewerState,
1418 /// The owned root node of the displayed tree, or `None` for an empty outline.
1419 ///
1420 /// Siblings chain through [`Node::next`] and children through
1421 /// [`Node::child_list`]; the recursive `Box<Node>` drop frees the entire
1422 /// subtree when this field is replaced or the `Outline` is dropped.
1423 ///
1424 /// To swap the tree at runtime, replace this field and call [`ov_update`]
1425 /// so the scrollbar limits stay consistent with the new content.
1426 pub root: Option<Box<Node>>,
1427}
1428
1429impl Outline {
1430 /// Create an `Outline` over `bounds`, with optional horizontal (`h`) and
1431 /// vertical (`v`) scrollbar ids and an initial tree `root`.
1432 ///
1433 /// The initial scrollbar population is now seeded **automatically** on the
1434 /// first display or interaction (the first context-bearing lifecycle call —
1435 /// `handle_event`, `set_state`, or `on_bounds_changed`). You do not need to
1436 /// call [`ov_update`] manually just to make navigation work after construction.
1437 ///
1438 /// You still need to call [`ov_update`] explicitly after **mutating** the
1439 /// tree — swapping [`Outline::root`], or expanding/collapsing nodes
1440 /// programmatically — so the scrollbar limits reflect the updated node count.
1441 pub fn new(
1442 bounds: Rect,
1443 h: Option<ViewId>,
1444 v: Option<ViewId>,
1445 root: Option<Box<Node>>,
1446 ) -> Self {
1447 Outline {
1448 ov: OutlineViewerState::new(bounds, h, v),
1449 root,
1450 }
1451 }
1452}
1453
1454/// Collect, in DFS pre-order, raw pointers to every currently-visible node
1455/// (a node and — if expanded — its visible subtree). The same visible walk as
1456/// [`traverse`] without the flags/lines bookkeeping; the caller iterates root
1457/// siblings separately.
1458/// Recursively find the visible node at DFS position `target` (pre-order, 0-based)
1459/// and set its `expanded` flag. `counter` starts at the position of `node`.
1460///
1461/// Visits `node`, then its visible children (via `child_list`), then its next
1462/// sibling (via `next`) — matching the DFS order of `traverse`. Returns `true`
1463/// when the target is found so callers can short-circuit.
1464fn set_expanded_at_pos(node: &mut Node, target: i32, counter: &mut i32, expand: bool) -> bool {
1465 if *counter == target {
1466 node.expanded = expand;
1467 return true;
1468 }
1469 // Recurse into visible children first.
1470 if node.expanded
1471 && let Some(child) = node.child_list.as_deref_mut()
1472 {
1473 *counter += 1;
1474 if set_expanded_at_pos(child, target, counter, expand) {
1475 return true;
1476 }
1477 }
1478 // Then continue to the next sibling (handles both child-level siblings and,
1479 // when called on root, root-level siblings — same DFS order as `traverse`).
1480 if let Some(next) = node.next.as_deref_mut() {
1481 *counter += 1;
1482 set_expanded_at_pos(next, target, counter, expand)
1483 } else {
1484 false
1485 }
1486}
1487
1488impl OutlineViewer for Outline {
1489 fn ov(&self) -> &OutlineViewerState {
1490 &self.ov
1491 }
1492 fn ov_mut(&mut self) -> &mut OutlineViewerState {
1493 &mut self.ov
1494 }
1495
1496 /// Returns `self.root.as_deref()` — the root of the owned node tree.
1497 fn get_root(&self) -> Option<&Node> {
1498 self.root.as_deref()
1499 }
1500
1501 /// Returns the next sibling of `node` by following [`Node::next`].
1502 fn get_next<'a>(&'a self, node: &'a Node) -> Option<&'a Node> {
1503 node.next.as_deref()
1504 }
1505
1506 /// Returns the `i`-th child of `node` (0-based) by walking the
1507 /// [`Node::child_list`] → [`Node::next`] sibling chain `i` steps.
1508 /// Returns `None` if `i` is out of range.
1509 fn get_child<'a>(&'a self, node: &'a Node, i: i32) -> Option<&'a Node> {
1510 // C++ getChild walks childList->next i times.
1511 let mut p = node.child_list.as_deref();
1512 let mut idx = 0;
1513 while idx < i {
1514 match p {
1515 Some(n) => p = n.next.as_deref(),
1516 None => break,
1517 }
1518 idx += 1;
1519 }
1520 p
1521 }
1522
1523 /// Counts `node`'s direct children by walking the sibling chain starting
1524 /// at [`Node::child_list`].
1525 fn get_num_children(&self, node: &Node) -> i32 {
1526 let mut i = 0;
1527 let mut p = node.child_list.as_deref();
1528 while let Some(n) = p {
1529 i += 1;
1530 p = n.next.as_deref();
1531 }
1532 i
1533 }
1534
1535 /// Returns `node.text` as a `&str`.
1536 fn get_text<'a>(&'a self, node: &'a Node) -> &'a str {
1537 &node.text
1538 }
1539
1540 /// Returns `node.expanded`.
1541 fn is_expanded(&self, node: &Node) -> bool {
1542 node.expanded
1543 }
1544
1545 /// Returns `true` when [`Node::child_list`] is `Some`.
1546 fn has_children(&self, node: &Node) -> bool {
1547 node.child_list.is_some()
1548 }
1549
1550 /// Set the expanded state of the node at DFS position `pos` in the
1551 /// currently visible tree.
1552 ///
1553 /// Unlike the C++ `TOutline::adjust`, which takes a raw node pointer,
1554 /// this implementation takes a DFS position index. It walks the owned tree
1555 /// with `set_expanded_at_pos` to find and mutate the node — making the
1556 /// shared traversal code position-keyed throughout rather than mixing
1557 /// positions and pointers.
1558 fn adjust(&mut self, pos: i32, expand: bool) {
1559 if pos < 0 {
1560 return;
1561 }
1562 if let Some(root) = self.root.as_deref_mut() {
1563 set_expanded_at_pos(root, pos, &mut 0i32, expand);
1564 }
1565 }
1566}
1567
1568impl View for Outline {
1569 fn state(&self) -> &ViewState {
1570 &self.ov.state
1571 }
1572 fn state_mut(&mut self) -> &mut ViewState {
1573 &mut self.ov.state
1574 }
1575 fn draw(&mut self, ctx: &mut DrawCtx) {
1576 ov_draw(self, ctx);
1577 }
1578 fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
1579 ov_handle_event(self, ev, ctx);
1580 }
1581 fn set_state(&mut self, flag: StateFlag, enable: bool, ctx: &mut Context) {
1582 ov_set_state(self, flag, enable, ctx);
1583 }
1584
1585 /// Return the index of the currently focused node as
1586 /// `Some(FieldValue::Int(foc))`, matching the [`crate::widgets::ListBox`]
1587 /// contract. Returns `Some(FieldValue::Int(-1))` when no node is focused
1588 /// (e.g. before [`ov_update`] is called on an empty tree).
1589 fn value(&self) -> Option<crate::data::FieldValue> {
1590 Some(crate::data::FieldValue::Int(self.ov().foc))
1591 }
1592
1593 /// Re-publish scrollbar range/page params with the stored `limit` and the new
1594 /// `size` after the loop applies new bounds (identical to the scroller, which
1595 /// the outline viewer derives from). Also auto-seeds the limit on the first
1596 /// call so the initial bounds application produces a correct first-frame state.
1597 fn on_bounds_changed(&mut self, ctx: &mut Context) {
1598 ensure_seeded(self, ctx);
1599 let (x, y) = (self.ov().limit.x, self.ov().limit.y);
1600 self.ov_mut().set_limit(x, y, ctx);
1601 }
1602
1603 fn apply_scroll_sync(&mut self, h: Option<i32>, v: Option<i32>, _ctx: &mut Context) {
1604 // Read-only, like the scroller: a missing bar is delta 0 (faithful to the
1605 // old dedicated pump arm's `.unwrap_or(0)` read).
1606 self.ov_mut()
1607 .apply_delta(Point::new(h.unwrap_or(0), v.unwrap_or(0)));
1608 }
1609
1610 fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
1611 Some(self)
1612 }
1613}
1614
1615#[cfg(test)]
1616mod tests {
1617 use super::*;
1618 use crate::backend::{HeadlessBackend, Renderer};
1619 use crate::screen::Buffer;
1620 use crate::theme::Theme;
1621 use crate::view::{Deferred, Group};
1622 use std::collections::VecDeque;
1623
1624 fn make_ctx<'a>(
1625 out: &'a mut VecDeque<Event>,
1626 timers: &'a mut crate::timer::TimerQueue,
1627 deferred: &'a mut Vec<Deferred>,
1628 ) -> Context<'a> {
1629 Context::new(out, timers, 0, deferred)
1630 }
1631
1632 /// Mint a real `ViewId` by inserting a throwaway view into a group.
1633 fn mint_id() -> (Group, ViewId) {
1634 let mut g = Group::new(Rect::new(0, 0, 4, 4));
1635 let id = g.insert(Box::new(Outline::new(
1636 Rect::new(0, 0, 1, 1),
1637 None,
1638 None,
1639 None,
1640 )));
1641 (g, id)
1642 }
1643
1644 /// Build: root "Animals" with children "Cats" → "Dogs".
1645 fn animals_tree() -> Box<Node> {
1646 let children = Box::new(Node::new("Cats").with_next(Box::new(Node::new("Dogs"))));
1647 Box::new(Node::new("Animals").with_children(children))
1648 }
1649
1650 // -- Node -----------------------------------------------------------------
1651
1652 #[test]
1653 fn node_new_defaults() {
1654 let n = Node::new("hi");
1655 assert_eq!(n.text, "hi");
1656 assert!(n.child_list.is_none());
1657 assert!(n.next.is_none());
1658 assert!(n.expanded, "new node is expanded");
1659 }
1660
1661 #[test]
1662 fn node_builders() {
1663 let n = Node::new("a")
1664 .with_next(Box::new(Node::new("b")))
1665 .with_children(Box::new(Node::new("c")))
1666 .with_expanded(false);
1667 assert_eq!(n.next.as_ref().unwrap().text, "b");
1668 assert_eq!(n.child_list.as_ref().unwrap().text, "c");
1669 assert!(!n.expanded);
1670 }
1671
1672 // -- traversal / getChild / getNumChildren --------------------------------
1673
1674 #[test]
1675 fn traverse_dfs_positions_and_flags() {
1676 let o = Outline::new(Rect::new(0, 0, 20, 10), None, None, Some(animals_tree()));
1677 let mut visited: Vec<(String, i32, i32, u16)> = Vec::new();
1678 traverse(&o, &mut |this: &Outline,
1679 node,
1680 level,
1681 position,
1682 _lines,
1683 flags| {
1684 visited.push((this.get_text(node).to_string(), level, position, flags));
1685 false
1686 });
1687 // Animals (level 0, pos 0, has children + expanded), Cats (level 1, pos 1),
1688 // Dogs (level 1, pos 2, last child).
1689 assert_eq!(visited.len(), 3);
1690 assert_eq!(visited[0].0, "Animals");
1691 assert_eq!(visited[0].1, 0);
1692 assert_eq!(visited[0].2, 0);
1693 assert_ne!(visited[0].3 & OV_CHILDREN, 0, "Animals has children");
1694 assert_ne!(visited[0].3 & OV_LAST, 0, "Animals is the only root → last");
1695
1696 assert_eq!(visited[1].0, "Cats");
1697 assert_eq!(visited[1].1, 1);
1698 assert_eq!(visited[1].2, 1);
1699 assert_eq!(visited[1].3 & OV_LAST, 0, "Cats is not the last child");
1700
1701 assert_eq!(visited[2].0, "Dogs");
1702 assert_eq!(visited[2].2, 2);
1703 assert_ne!(visited[2].3 & OV_LAST, 0, "Dogs is the last child");
1704 }
1705
1706 #[test]
1707 fn collapsed_node_hides_children() {
1708 // Collapse the root: only "Animals" is visible.
1709 let mut root = animals_tree();
1710 root.expanded = false;
1711 let o = Outline::new(Rect::new(0, 0, 20, 10), None, None, Some(root));
1712 let mut count = 0;
1713 traverse(&o, &mut |_o: &Outline, _n, _l, _p, _li, _f| {
1714 count += 1;
1715 false
1716 });
1717 assert_eq!(count, 1, "collapsed root hides its children");
1718 }
1719
1720 #[test]
1721 fn get_child_and_num_children() {
1722 let o = Outline::new(Rect::new(0, 0, 20, 10), None, None, Some(animals_tree()));
1723 let root = o.get_root().unwrap();
1724 assert_eq!(o.get_num_children(root), 2);
1725 assert_eq!(o.get_child(root, 0).unwrap().text, "Cats");
1726 assert_eq!(o.get_child(root, 1).unwrap().text, "Dogs");
1727 assert!(o.get_child(root, 2).is_none());
1728 }
1729
1730 // -- createGraph ----------------------------------------------------------
1731
1732 #[test]
1733 fn create_graph_root_shapes() {
1734 // levWidth = endWidth = 3, level 0.
1735 let chars: [char; 8] = [' ', '│', '├', '└', '─', '─', '+', '─'];
1736 // Last child, no children → "└──".
1737 let g = create_graph(0, 0, OV_EXPANDED | OV_LAST, 3, 3, &chars);
1738 assert_eq!(g, "└──");
1739 // Not last, has children, expanded → "├──".
1740 let g = create_graph(0, 0, OV_EXPANDED | OV_CHILDREN, 3, 3, &chars);
1741 assert_eq!(g, "├──");
1742 // Last, has children, collapsed (not expanded) → "└─+".
1743 let g = create_graph(
1744 0,
1745 0,
1746 OV_CHILDREN /* but not EXPANDED */ | OV_LAST,
1747 3,
1748 3,
1749 &chars,
1750 );
1751 // Note OV_CHILDREN without OV_EXPANDED is not a real traversal state, but
1752 // exercises the retract char path.
1753 assert_eq!(g, "└─+");
1754 }
1755
1756 #[test]
1757 fn create_graph_level_indent() {
1758 let chars: [char; 8] = [' ', '│', '├', '└', '─', '─', '+', '─'];
1759 // Level 1, continuation bar at level 0 (lines bit 0 set), last child.
1760 let g = create_graph(1, 0b1, OV_EXPANDED | OV_LAST, 3, 3, &chars);
1761 // 3 chars indent ("│ ") + 3 end chars ("└──").
1762 assert_eq!(g, "│ └──");
1763 // Level 1, no continuation bar.
1764 let g = create_graph(1, 0, OV_EXPANDED | OV_LAST, 3, 3, &chars);
1765 assert_eq!(g, " └──");
1766 }
1767
1768 // -- ov_update / set_limit ------------------------------------------------
1769
1770 #[test]
1771 fn ov_update_counts_and_sets_limit() {
1772 let (_gh, h) = mint_id();
1773 let (_gv, v) = mint_id();
1774 let mut o = Outline::new(
1775 Rect::new(0, 0, 20, 5),
1776 Some(h),
1777 Some(v),
1778 Some(animals_tree()),
1779 );
1780 let mut out = VecDeque::new();
1781 let mut timers = crate::timer::TimerQueue::new();
1782 let mut deferred: Vec<Deferred> = vec![];
1783 {
1784 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1785 ov_update(&mut o, &mut ctx);
1786 }
1787 // 3 visible nodes → limit.y = 3. max_x: "Animals" graph 3 + text 7 = 10;
1788 // "Cats"/"Dogs" graph 6 + text 4 = 10. → 10.
1789 assert_eq!(o.ov().limit, Point::new(10, 3));
1790 }
1791
1792 // -- adjust (expand/collapse via DFS position) ----------------------------
1793
1794 #[test]
1795 fn adjust_collapses_and_expands_by_position() {
1796 let mut o = Outline::new(Rect::new(0, 0, 20, 5), None, None, Some(animals_tree()));
1797 // Collapse position 0 (root).
1798 o.adjust(0, false);
1799 assert!(!o.root.as_ref().unwrap().expanded);
1800 // Re-expand.
1801 o.adjust(0, true);
1802 assert!(o.root.as_ref().unwrap().expanded);
1803 // Collapse a child (position 1 = "Cats").
1804 o.adjust(1, false);
1805 assert!(
1806 !o.root
1807 .as_ref()
1808 .unwrap()
1809 .child_list
1810 .as_ref()
1811 .unwrap()
1812 .expanded
1813 );
1814 }
1815
1816 // -- ov_expand_all --------------------------------------------------------
1817
1818 #[test]
1819 fn expand_all_expands_subtree_not_siblings() {
1820 // root "R" with children A (collapsed, with child A1) and B (collapsed,
1821 // with child B1). Start at A; expanding all from A must expand A (and A1's
1822 // parent chain) but NOT B.
1823 let a1 = Box::new(Node::new("A1"));
1824 let a = Box::new(Node::new("A").with_children(a1).with_expanded(false));
1825 let b1 = Box::new(Node::new("B1"));
1826 let b = Box::new(Node::new("B").with_children(b1).with_expanded(false));
1827 let children = Box::new(*a).with_next(b);
1828 let root = Box::new(Node::new("R").with_children(Box::new(children)));
1829 let mut o = Outline::new(Rect::new(0, 0, 20, 10), None, None, Some(root));
1830
1831 // Visible: R(0), A(1), B(2). expandAll from A (position 1).
1832 ov_expand_all(&mut o, 1);
1833
1834 // A must now be expanded; B must remain collapsed.
1835 let root = o.root.as_ref().unwrap();
1836 let a = root.child_list.as_ref().unwrap();
1837 assert_eq!(a.text, "A");
1838 assert!(a.expanded, "A expanded by expandAll");
1839 let b = a.next.as_ref().unwrap();
1840 assert_eq!(b.text, "B");
1841 assert!(!b.expanded, "B (sibling of A) NOT expanded");
1842 }
1843
1844 // -- handle_event: scrollbar filter --------------------------------------
1845
1846 #[test]
1847 fn scrollbar_changed_filter_requests_sync_only_for_own_bars() {
1848 let mut group = Group::new(Rect::new(0, 0, 30, 20));
1849 let (_gh, h) = mint_id();
1850 let (_gv, v) = mint_id();
1851 let id = group.insert(Box::new(Outline::new(
1852 Rect::new(0, 0, 10, 5),
1853 Some(h),
1854 Some(v),
1855 Some(animals_tree()),
1856 )));
1857 let mut out = VecDeque::new();
1858 let mut timers = crate::timer::TimerQueue::new();
1859 let mut deferred: Vec<Deferred> = vec![];
1860
1861 // Pre-seed: the first context-bearing call triggers the auto-seed, which
1862 // queues SetScrollBarParams entries. Clear those before the targeted test
1863 // so deferred counts are unambiguous.
1864 {
1865 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1866 group
1867 .find_mut(id)
1868 .unwrap()
1869 .handle_event(&mut Event::Nothing, &mut ctx);
1870 }
1871 deferred.clear();
1872
1873 // CHANGED from own h-bar → ScrollSync queued.
1874 let mut ev = Event::Broadcast {
1875 command: Command::SCROLL_BAR_CHANGED,
1876 source: Some(h),
1877 };
1878 {
1879 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1880 group.find_mut(id).unwrap().handle_event(&mut ev, &mut ctx);
1881 }
1882 assert_eq!(deferred.len(), 1);
1883 assert!(matches!(
1884 deferred[0],
1885 Deferred::ScrollSync { target: viewer, h: rh, v: rv }
1886 if viewer == id && rh == Some(h) && rv == Some(v)
1887 ));
1888
1889 // CHANGED from a foreign source → nothing.
1890 deferred.clear();
1891 let mut ev = Event::Broadcast {
1892 command: Command::SCROLL_BAR_CHANGED,
1893 source: Some(id),
1894 };
1895 {
1896 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1897 group.find_mut(id).unwrap().handle_event(&mut ev, &mut ctx);
1898 }
1899 assert!(deferred.is_empty(), "foreign source ignored");
1900 }
1901
1902 // -- handle_event: keyboard nav ------------------------------------------
1903
1904 #[test]
1905 fn key_down_moves_focus() {
1906 let mut o = Outline::new(Rect::new(0, 0, 20, 5), None, None, Some(animals_tree()));
1907 let mut out = VecDeque::new();
1908 let mut timers = crate::timer::TimerQueue::new();
1909 let mut deferred = vec![];
1910 // limit.y must be set for adjust_focus clamping.
1911 {
1912 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1913 ov_update(&mut o, &mut ctx);
1914 }
1915 let mut ev = Event::KeyDown(crate::event::KeyEvent::new(
1916 Key::Down,
1917 crate::event::KeyModifiers::default(),
1918 ));
1919 {
1920 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1921 o.handle_event(&mut ev, &mut ctx);
1922 }
1923 assert_eq!(o.ov().foc, 1, "Down → focus position 1");
1924 assert!(ev.is_nothing(), "Down consumed");
1925 }
1926
1927 #[test]
1928 fn value_returns_focused_index() {
1929 // Before ov_update, foc = 0 and limit.y = 0. value() still returns Some.
1930 let mut o = Outline::new(Rect::new(0, 0, 20, 5), None, None, Some(animals_tree()));
1931 assert_eq!(
1932 o.value(),
1933 Some(crate::data::FieldValue::Int(0)),
1934 "value() returns Some(Int(foc)) before ov_update"
1935 );
1936
1937 let mut out = VecDeque::new();
1938 let mut timers = crate::timer::TimerQueue::new();
1939 let mut deferred = vec![];
1940 {
1941 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1942 ov_update(&mut o, &mut ctx);
1943 }
1944 // foc is still 0 after ov_update (no navigation yet).
1945 assert_eq!(
1946 o.value(),
1947 Some(crate::data::FieldValue::Int(0)),
1948 "value() returns Some(Int(0)) at start"
1949 );
1950
1951 // Navigate down once → foc = 1.
1952 let mut ev = Event::KeyDown(crate::event::KeyEvent::new(
1953 Key::Down,
1954 crate::event::KeyModifiers::default(),
1955 ));
1956 {
1957 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1958 o.handle_event(&mut ev, &mut ctx);
1959 }
1960 assert_eq!(
1961 o.value(),
1962 Some(crate::data::FieldValue::Int(1)),
1963 "value() tracks focused index after Down"
1964 );
1965 }
1966
1967 #[test]
1968 fn key_minus_collapses_focused() {
1969 let mut o = Outline::new(Rect::new(0, 0, 20, 5), None, None, Some(animals_tree()));
1970 let mut out = VecDeque::new();
1971 let mut timers = crate::timer::TimerQueue::new();
1972 let mut deferred = vec![];
1973 {
1974 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1975 ov_update(&mut o, &mut ctx);
1976 }
1977 // foc = 0 (root). '-' collapses it.
1978 let mut ev = Event::KeyDown(crate::event::KeyEvent::new(
1979 Key::Char('-'),
1980 crate::event::KeyModifiers::default(),
1981 ));
1982 {
1983 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1984 o.handle_event(&mut ev, &mut ctx);
1985 }
1986 assert!(!o.root.as_ref().unwrap().expanded, "'-' collapsed the root");
1987 assert!(ev.is_nothing(), "'-' consumed");
1988 }
1989
1990 // -- draw snapshot --------------------------------------------------------
1991
1992 fn render_outline(outline: &mut Outline, w: u16, h: u16) -> String {
1993 let theme = Theme::classic_blue();
1994 let (backend, screen) = HeadlessBackend::new(w, h);
1995 let mut r = Renderer::new(Box::new(backend));
1996 r.render(|buf: &mut Buffer| {
1997 let bounds = outline.state().get_bounds();
1998 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
1999 outline.draw(&mut dc);
2000 });
2001 screen.snapshot()
2002 }
2003
2004 #[test]
2005 fn draw_simple_tree() {
2006 let mut outline = Outline::new(Rect::new(0, 0, 20, 5), None, None, Some(animals_tree()));
2007 // Mark focused so the focused-row color branch applies.
2008 outline.ov_mut().state.state.focused = true;
2009 outline.ov_mut().foc = 0;
2010 // Set the limit by hand (ov_update needs a Context); the draw only reads
2011 // delta/size/foc, so limit is not strictly required for this snapshot.
2012 outline.ov_mut().limit = Point::new(10, 3);
2013 insta::assert_snapshot!(render_outline(&mut outline, 20, 5));
2014 }
2015
2016 #[test]
2017 fn draw_focused_collapsed_parent_uses_focused_text_color() {
2018 // A focused, COLLAPSED parent must draw its text in the Focused color
2019 // (C++ `color >> 8` of the 0x0202 pair = Focused), NOT the NotExpanded
2020 // dim color — the case the expanded `draw_simple_tree` snapshot can't see.
2021 let mut root = animals_tree();
2022 root.expanded = false; // collapse the root → only "Animals" visible
2023 let mut outline = Outline::new(Rect::new(0, 0, 20, 5), None, None, Some(root));
2024 outline.ov_mut().state.state.focused = true;
2025 outline.ov_mut().foc = 0; // the collapsed parent is focused
2026 outline.ov_mut().limit = Point::new(10, 1);
2027 // The "Animals" row's text attr must be the Focused style (white-on-blue),
2028 // not NotExpanded (darkgray-on-blue) — the snapshot legend makes this
2029 // visible and a regression to `not_expanded_color` would change it.
2030 insta::assert_snapshot!(render_outline(&mut outline, 20, 5));
2031 }
2032
2033 /// Render `outline` with `theme` into a fresh buffer, with the `DrawCtx`'s
2034 /// `owner_active` set explicitly, and return the style of the cell at
2035 /// `(x, y)`.
2036 fn cell_style(
2037 outline: &mut Outline,
2038 theme: &Theme,
2039 x: u16,
2040 y: u16,
2041 owner_active: bool,
2042 ) -> crate::color::Style {
2043 let bounds = outline.state().get_bounds();
2044 let mut buf = Buffer::new(bounds.b.x as u16, bounds.b.y as u16);
2045 let mut dc = DrawCtx::new(&mut buf, theme, bounds, bounds.a);
2046 dc.set_owner_active(owner_active);
2047 outline.draw(&mut dc);
2048 buf.get(x, y).style()
2049 }
2050
2051 /// The normal-row surface follows the shared three-surface rule
2052 /// ([`DrawCtx::content_surface`](crate::view::DrawCtx::content_surface)):
2053 /// an inactive pane recedes to `OutlineInactive` regardless of the
2054 /// outline's own focus; within an active pane, the outline's own focus
2055 /// picks well-vs-surface — a focused (or never-selectable) outline is the
2056 /// `OutlineNormal` well, and an unfocused *selectable* sibling sits on
2057 /// `OutlineSurface`. Uses a theme where all three roles differ
2058 /// (classic_blue makes them identical).
2059 #[test]
2060 fn normal_row_surface_follows_owner_active_not_own_focus() {
2061 use crate::color::{Color, Style};
2062
2063 let mut theme = Theme::classic_blue();
2064 theme.set_style(
2065 Role::OutlineSurface,
2066 Style::new(Color::bios_rgb(0x0), Color::bios_rgb(0x7)),
2067 );
2068 theme.set_style(
2069 Role::OutlineInactive,
2070 Style::new(Color::bios_rgb(0x8), Color::bios_rgb(0x4)),
2071 );
2072 let normal_bg = theme.style(Role::OutlineNormal).bg;
2073 let surface_bg = theme.style(Role::OutlineSurface).bg;
2074 let inactive_bg = theme.style(Role::OutlineInactive).bg;
2075 assert!(
2076 normal_bg != surface_bg && surface_bg != inactive_bg && normal_bg != inactive_bg,
2077 "test theme must distinguish all three roles"
2078 );
2079
2080 // Root "Animals" (pos 0) with normal children "Cats"/"Dogs".
2081 let mut outline = Outline::new(Rect::new(0, 0, 20, 5), None, None, Some(animals_tree()));
2082 outline.ov_mut().foc = 0;
2083 outline.ov_mut().limit = Point::new(10, 3);
2084
2085 // Active pane, focused outline → the well.
2086 outline.ov_mut().state.state.focused = true;
2087 assert_eq!(cell_style(&mut outline, &theme, 15, 1, true).bg, normal_bg);
2088
2089 // Active pane, unfocused SELECTABLE outline → the pane surface (a
2090 // selectable sibling won the focus contest).
2091 outline.ov_mut().state.state.focused = false;
2092 assert_eq!(cell_style(&mut outline, &theme, 15, 1, true).bg, surface_bg);
2093
2094 // Inactive pane → receded, regardless of the outline's own focus.
2095 outline.ov_mut().state.state.focused = true;
2096 assert_eq!(
2097 cell_style(&mut outline, &theme, 15, 1, false).bg,
2098 inactive_bg
2099 );
2100 outline.ov_mut().state.state.focused = false;
2101 assert_eq!(
2102 cell_style(&mut outline, &theme, 15, 1, false).bg,
2103 inactive_bg
2104 );
2105
2106 // Active pane, unfocused NON-selectable outline → OutlineNormal: it
2107 // can never win (or lose) a focus contest, so it always stays the well.
2108 outline.ov_mut().state.state.focused = false;
2109 outline.ov_mut().state.options.selectable = false;
2110 assert_eq!(cell_style(&mut outline, &theme, 15, 1, true).bg, normal_bg);
2111 }
2112
2113 /// The focused-row HIGHLIGHT (the outline's own current position) still
2114 /// follows the outline's own `state.focused`, independent of
2115 /// `owner_active` — unchanged by the surface re-key above.
2116 #[test]
2117 fn focused_row_highlight_follows_own_focus_not_owner_active() {
2118 let theme = Theme::classic_blue();
2119 let focused_fg = theme.style(Role::OutlineFocused).fg;
2120 let normal_fg = theme.style(Role::OutlineNormal).fg;
2121 assert_ne!(
2122 focused_fg, normal_fg,
2123 "classic_blue must distinguish the roles"
2124 );
2125
2126 let mut outline = Outline::new(Rect::new(0, 0, 20, 5), None, None, Some(animals_tree()));
2127 outline.ov_mut().foc = 0; // root row is the outline's current position
2128 outline.ov_mut().limit = Point::new(10, 3);
2129
2130 // owner_active=true, outline's own focus=true: highlight applies.
2131 outline.ov_mut().state.state.focused = true;
2132 assert_eq!(cell_style(&mut outline, &theme, 0, 0, true).fg, focused_fg);
2133
2134 // owner_active=false, outline's own focus=true: highlight STILL
2135 // applies — the highlight ignores owner_active.
2136 assert_eq!(cell_style(&mut outline, &theme, 0, 0, false).fg, focused_fg);
2137
2138 // owner_active=true, outline's own focus=false: highlight does NOT
2139 // apply (falls back to the normal surface fg) — the highlight
2140 // follows the outline's own focus.
2141 outline.ov_mut().state.state.focused = false;
2142 assert_ne!(cell_style(&mut outline, &theme, 0, 0, true).fg, focused_fg);
2143 }
2144
2145 // -- mouse-track: Outline -------------------------------------------------
2146 //
2147 // These tests verify that MouseDown arms tracking with the view-id payload,
2148 // MouseMove/MouseAuto route focus, MouseAuto out-of-view scrolls after the
2149 // skip count, and MouseUp performs the post-loop graph-toggle logic:
2150 // drag (dragged >= 2) must NOT toggle; a click (dragged < 2) DOES toggle.
2151
2152 fn ov_mouse_down(x: i32, y: i32) -> Event {
2153 Event::MouseDown(crate::event::MouseEvent {
2154 position: Point::new(x, y),
2155 buttons: crate::event::MouseButtons {
2156 left: true,
2157 ..Default::default()
2158 },
2159 ..Default::default()
2160 })
2161 }
2162
2163 fn ov_mouse_move(x: i32, y: i32) -> Event {
2164 Event::MouseMove(crate::event::MouseEvent {
2165 position: Point::new(x, y),
2166 buttons: crate::event::MouseButtons {
2167 left: true,
2168 ..Default::default()
2169 },
2170 ..Default::default()
2171 })
2172 }
2173
2174 fn ov_mouse_auto(x: i32, y: i32) -> Event {
2175 Event::MouseAuto(crate::event::MouseEvent {
2176 position: Point::new(x, y),
2177 ..Default::default()
2178 })
2179 }
2180
2181 fn ov_mouse_up(x: i32, y: i32) -> Event {
2182 Event::MouseUp(crate::event::MouseEvent {
2183 position: Point::new(x, y),
2184 ..Default::default()
2185 })
2186 }
2187
2188 fn ov_double_click(x: i32, y: i32) -> Event {
2189 Event::MouseDown(crate::event::MouseEvent {
2190 position: Point::new(x, y),
2191 flags: crate::event::MouseEventFlags {
2192 double_click: true,
2193 ..Default::default()
2194 },
2195 buttons: crate::event::MouseButtons {
2196 left: true,
2197 ..Default::default()
2198 },
2199 ..Default::default()
2200 })
2201 }
2202
2203 /// Stamp an outline with a ViewId (as Group::insert would do).
2204 fn give_ov_id(o: &mut Outline) -> ViewId {
2205 let id = ViewId::next();
2206 o.ov.state.id = Some(id);
2207 id
2208 }
2209
2210 /// `MouseDown` (non-double-click) on an inserted outline: arms tracking
2211 /// with the correct view-id payload in the PushCapture deferred.
2212 #[test]
2213 fn ov_mouse_down_arms_tracking_and_pushes_capture() {
2214 // 20×5 outline, 3-node "Animals" tree (limit.y = 3 after ov_update).
2215 let mut o = Outline::new(Rect::new(0, 0, 20, 5), None, None, Some(animals_tree()));
2216 let id = give_ov_id(&mut o);
2217 let mut out = VecDeque::new();
2218 let mut timers = crate::timer::TimerQueue::new();
2219 let mut deferred: Vec<Deferred> = vec![];
2220 {
2221 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2222 ov_update(&mut o, &mut ctx);
2223 }
2224 deferred.clear();
2225
2226 // Click at (5, 1): delta.y=0, i = 0+1=1 < limit_y=3 → new_focus = 1.
2227 let mut ev = ov_mouse_down(5, 1);
2228 {
2229 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2230 o.handle_event(&mut ev, &mut ctx);
2231 }
2232 assert!(ev.is_nothing(), "MouseDown consumed");
2233 assert_eq!(o.ov().foc, 1, "focus positioned to item 1");
2234 assert!(o.ov().track.is_some(), "track state armed");
2235 // The PushCapture deferred must name this outline's id.
2236 assert_eq!(deferred.len(), 1, "one PushCapture deferred");
2237 assert!(
2238 matches!(deferred[0], Deferred::PushCapture(_)),
2239 "deferred[0] is PushCapture"
2240 );
2241 if let Deferred::PushCapture(ref h) = deferred[0] {
2242 assert_eq!(h.view(), Some(id), "capture tracks the outline's id");
2243 }
2244 }
2245
2246 /// `MouseDown` without an id: single-shot behavior, no tracking.
2247 #[test]
2248 fn ov_mouse_down_without_id_is_single_shot() {
2249 let mut o = Outline::new(Rect::new(0, 0, 20, 5), None, None, Some(animals_tree()));
2250 // No id.
2251 let mut out = VecDeque::new();
2252 let mut timers = crate::timer::TimerQueue::new();
2253 let mut deferred: Vec<Deferred> = vec![];
2254 {
2255 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2256 ov_update(&mut o, &mut ctx);
2257 }
2258 deferred.clear();
2259
2260 let mut ev = ov_mouse_down(5, 1);
2261 {
2262 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2263 o.handle_event(&mut ev, &mut ctx);
2264 }
2265 assert!(o.ov().track.is_none(), "no track without an id");
2266 assert!(
2267 deferred
2268 .iter()
2269 .all(|d| !matches!(d, Deferred::PushCapture(_))),
2270 "no capture pushed for id-less outline"
2271 );
2272 }
2273
2274 /// `MouseMove` in-view while tracking: repositions focus.
2275 #[test]
2276 fn ov_mouse_move_in_view_recomputes_focus() {
2277 let mut o = Outline::new(Rect::new(0, 0, 20, 5), None, None, Some(animals_tree()));
2278 give_ov_id(&mut o);
2279 let mut out = VecDeque::new();
2280 let mut timers = crate::timer::TimerQueue::new();
2281 let mut deferred: Vec<Deferred> = vec![];
2282 {
2283 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2284 ov_update(&mut o, &mut ctx);
2285 }
2286 deferred.clear();
2287
2288 // Arm tracking with a click at row 0.
2289 let mut ev = ov_mouse_down(5, 0);
2290 {
2291 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2292 o.handle_event(&mut ev, &mut ctx);
2293 }
2294 assert_eq!(o.ov().foc, 0);
2295 deferred.clear();
2296
2297 // MouseMove to row 2: i = delta.y(0) + 2 = 2 < limit_y(3) → new_focus = 2.
2298 let mut ev = ov_mouse_move(5, 2);
2299 {
2300 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2301 o.handle_event(&mut ev, &mut ctx);
2302 }
2303 assert!(ev.is_nothing(), "MouseMove consumed");
2304 assert_eq!(o.ov().foc, 2, "focus moves to row 2");
2305 assert!(o.ov().track.is_some(), "still tracking after move");
2306 // dragged increments: was 1 after down, now 2.
2307 assert_eq!(o.ov().track.unwrap().dragged, 2, "dragged incremented");
2308 }
2309
2310 /// `MouseAuto` out-of-view (tracking): skips 2 ticks, then steps on the 3rd.
2311 #[test]
2312 fn ov_mouse_auto_out_of_view_skips_then_steps() {
2313 let mut o = Outline::new(Rect::new(0, 0, 20, 5), None, None, Some(animals_tree()));
2314 give_ov_id(&mut o);
2315 let mut out = VecDeque::new();
2316 let mut timers = crate::timer::TimerQueue::new();
2317 let mut deferred: Vec<Deferred> = vec![];
2318 {
2319 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2320 ov_update(&mut o, &mut ctx);
2321 }
2322 // Focus item 1 (Cats), arm tracking manually.
2323 o.ov_mut().foc = 1;
2324 o.ov_mut().track = Some(OvTrack {
2325 count: 0,
2326 dragged: 1,
2327 });
2328 deferred.clear();
2329
2330 // 2 ticks below (y >= size.y = 5): count reaches 1, 2 — no step.
2331 for tick in 1..=2 {
2332 let mut ev = ov_mouse_auto(5, 6); // y=6 >= size.y=5
2333 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2334 o.handle_event(&mut ev, &mut ctx);
2335 assert_eq!(o.ov().foc, 1, "tick {tick}: no step yet");
2336 }
2337 // 3rd tick: count == MOUSE_AUTO_TO_SKIP → step forward.
2338 let mut ev = ov_mouse_auto(5, 6);
2339 {
2340 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2341 o.handle_event(&mut ev, &mut ctx);
2342 }
2343 assert_eq!(o.ov().foc, 2, "3rd tick steps focus by +1 (below view)");
2344 }
2345
2346 /// `MouseUp` while tracking + `dragged < 2` (click): graph-toggle fires if
2347 /// the release x is within the graph column.
2348 #[test]
2349 fn ov_mouse_up_click_toggles_graph_expansion() {
2350 // Build a tree with Animals (expanded, has children) at position 0.
2351 // Animals at level 0 → graph_w = 0*3 + 3 = 3. Click at x < 3 → toggle.
2352 let mut o = Outline::new(Rect::new(0, 0, 20, 5), None, None, Some(animals_tree()));
2353 give_ov_id(&mut o);
2354 let mut out = VecDeque::new();
2355 let mut timers = crate::timer::TimerQueue::new();
2356 let mut deferred: Vec<Deferred> = vec![];
2357 {
2358 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2359 ov_update(&mut o, &mut ctx);
2360 }
2361 o.ov_mut().foc = 0;
2362 // Arm tracking with dragged = 1 (click — fewer than 2 iterations).
2363 o.ov_mut().track = Some(OvTrack {
2364 count: 0,
2365 dragged: 1,
2366 });
2367 deferred.clear();
2368
2369 // MouseUp at (1, 0): x=1 < graph_w=3 → should toggle Animals (expanded → collapsed).
2370 assert!(o.root.as_ref().unwrap().expanded, "Animals starts expanded");
2371 let mut ev = ov_mouse_up(1, 0);
2372 {
2373 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2374 o.handle_event(&mut ev, &mut ctx);
2375 }
2376 assert!(ev.is_nothing(), "MouseUp consumed");
2377 assert!(o.ov().track.is_none(), "track cleared on MouseUp");
2378 assert!(
2379 !o.root.as_ref().unwrap().expanded,
2380 "Animals collapsed after click on graph"
2381 );
2382 }
2383
2384 /// `MouseUp` while tracking + `dragged >= 2` (drag): graph-toggle does NOT
2385 /// fire — the drag discriminator (toutline.cpp:469 `if (dragged < 2)`) gates it.
2386 #[test]
2387 fn ov_mouse_up_drag_does_not_toggle_graph() {
2388 let mut o = Outline::new(Rect::new(0, 0, 20, 5), None, None, Some(animals_tree()));
2389 give_ov_id(&mut o);
2390 let mut out = VecDeque::new();
2391 let mut timers = crate::timer::TimerQueue::new();
2392 let mut deferred: Vec<Deferred> = vec![];
2393 {
2394 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2395 ov_update(&mut o, &mut ctx);
2396 }
2397 o.ov_mut().foc = 0;
2398 // Arm tracking with dragged = 2 (drag — 2+ iterations).
2399 o.ov_mut().track = Some(OvTrack {
2400 count: 0,
2401 dragged: 2,
2402 });
2403 deferred.clear();
2404
2405 assert!(o.root.as_ref().unwrap().expanded, "Animals starts expanded");
2406 let mut ev = ov_mouse_up(1, 0); // x < graph_w — would toggle without the guard
2407 {
2408 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2409 o.handle_event(&mut ev, &mut ctx);
2410 }
2411 assert!(o.ov().track.is_none(), "track cleared");
2412 assert!(
2413 o.root.as_ref().unwrap().expanded,
2414 "Animals still expanded (drag must NOT toggle graph)"
2415 );
2416 }
2417
2418 /// `MouseUp` outside the graph column (click): does NOT toggle.
2419 #[test]
2420 fn ov_mouse_up_click_outside_graph_no_toggle() {
2421 let mut o = Outline::new(Rect::new(0, 0, 20, 5), None, None, Some(animals_tree()));
2422 give_ov_id(&mut o);
2423 let mut out = VecDeque::new();
2424 let mut timers = crate::timer::TimerQueue::new();
2425 let mut deferred: Vec<Deferred> = vec![];
2426 {
2427 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2428 ov_update(&mut o, &mut ctx);
2429 }
2430 o.ov_mut().foc = 0;
2431 o.ov_mut().track = Some(OvTrack {
2432 count: 0,
2433 dragged: 1,
2434 });
2435 deferred.clear();
2436
2437 // graph_w = 3; release at x = 5 (outside graph) → no toggle.
2438 let mut ev = ov_mouse_up(5, 0);
2439 {
2440 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2441 o.handle_event(&mut ev, &mut ctx);
2442 }
2443 assert!(o.root.as_ref().unwrap().expanded, "Animals still expanded");
2444 }
2445
2446 /// Stray `MouseUp` (not tracking) falls through unconsumed.
2447 #[test]
2448 fn ov_stray_mouse_up_falls_through() {
2449 let mut o = Outline::new(Rect::new(0, 0, 20, 5), None, None, Some(animals_tree()));
2450 give_ov_id(&mut o);
2451 let mut out = VecDeque::new();
2452 let mut timers = crate::timer::TimerQueue::new();
2453 let mut deferred: Vec<Deferred> = vec![];
2454
2455 let mut ev = ov_mouse_up(5, 2);
2456 {
2457 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2458 o.handle_event(&mut ev, &mut ctx);
2459 }
2460 assert!(
2461 !ev.is_nothing(),
2462 "stray MouseUp falls through (not consumed)"
2463 );
2464 }
2465
2466 /// Stray `MouseMove` (not tracking) falls through unconsumed.
2467 #[test]
2468 fn ov_stray_mouse_move_falls_through() {
2469 let mut o = Outline::new(Rect::new(0, 0, 20, 5), None, None, Some(animals_tree()));
2470 give_ov_id(&mut o);
2471 let mut out = VecDeque::new();
2472 let mut timers = crate::timer::TimerQueue::new();
2473 let mut deferred: Vec<Deferred> = vec![];
2474
2475 let mut ev = ov_mouse_move(5, 2);
2476 {
2477 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2478 o.handle_event(&mut ev, &mut ctx);
2479 }
2480 assert!(
2481 !ev.is_nothing(),
2482 "stray MouseMove falls through (not consumed)"
2483 );
2484 }
2485
2486 /// Double-click: calls `selected(foc)`, no tracking armed.
2487 #[test]
2488 fn ov_double_click_calls_selected_no_tracking() {
2489 // Override selected() to record the call by changing foc to a sentinel.
2490 struct CountingOutline {
2491 ov: OutlineViewerState,
2492 root: Option<Box<Node>>,
2493 selected_called: bool,
2494 }
2495 impl OutlineViewer for CountingOutline {
2496 fn ov(&self) -> &OutlineViewerState {
2497 &self.ov
2498 }
2499 fn ov_mut(&mut self) -> &mut OutlineViewerState {
2500 &mut self.ov
2501 }
2502 fn get_root(&self) -> Option<&Node> {
2503 self.root.as_deref()
2504 }
2505 fn get_next<'a>(&'a self, n: &'a Node) -> Option<&'a Node> {
2506 n.next.as_deref()
2507 }
2508 fn get_child<'a>(&'a self, n: &'a Node, i: i32) -> Option<&'a Node> {
2509 let mut p = n.child_list.as_deref();
2510 let mut idx = 0;
2511 while idx < i {
2512 p = p.and_then(|x| x.next.as_deref());
2513 idx += 1;
2514 }
2515 p
2516 }
2517 fn get_num_children(&self, n: &Node) -> i32 {
2518 let mut i = 0;
2519 let mut p = n.child_list.as_deref();
2520 while let Some(x) = p {
2521 i += 1;
2522 p = x.next.as_deref();
2523 }
2524 i
2525 }
2526 fn get_text<'a>(&'a self, n: &'a Node) -> &'a str {
2527 &n.text
2528 }
2529 fn is_expanded(&self, n: &Node) -> bool {
2530 n.expanded
2531 }
2532 fn has_children(&self, n: &Node) -> bool {
2533 n.child_list.is_some()
2534 }
2535 fn adjust(&mut self, pos: i32, expand: bool) {
2536 if let Some(root) = self.root.as_deref_mut() {
2537 set_expanded_at_pos(root, pos, &mut 0i32, expand);
2538 }
2539 }
2540 fn selected(&mut self, _i: i32) {
2541 self.selected_called = true;
2542 }
2543 }
2544 impl View for CountingOutline {
2545 fn state(&self) -> &ViewState {
2546 &self.ov.state
2547 }
2548 fn state_mut(&mut self) -> &mut ViewState {
2549 &mut self.ov.state
2550 }
2551 fn draw(&mut self, ctx: &mut DrawCtx) {
2552 ov_draw(self, ctx);
2553 }
2554 fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
2555 ov_handle_event(self, ev, ctx);
2556 }
2557 fn set_state(&mut self, flag: StateFlag, enable: bool, ctx: &mut Context) {
2558 ov_set_state(self, flag, enable, ctx);
2559 }
2560 fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
2561 Some(self)
2562 }
2563 }
2564
2565 let mut o = CountingOutline {
2566 ov: OutlineViewerState::new(Rect::new(0, 0, 20, 5), None, None),
2567 root: Some(animals_tree()),
2568 selected_called: false,
2569 };
2570 let id = ViewId::next();
2571 o.ov.state.id = Some(id);
2572 let mut out = VecDeque::new();
2573 let mut timers = crate::timer::TimerQueue::new();
2574 let mut deferred: Vec<Deferred> = vec![];
2575 {
2576 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2577 ov_update(&mut o, &mut ctx);
2578 }
2579 deferred.clear();
2580
2581 // Double-click at row 1.
2582 let mut ev = ov_double_click(5, 1);
2583 {
2584 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2585 o.handle_event(&mut ev, &mut ctx);
2586 }
2587 assert!(ev.is_nothing(), "double-click consumed");
2588 assert!(o.selected_called, "selected() called on double-click");
2589 assert!(o.ov.track.is_none(), "no tracking armed on double-click");
2590 assert!(
2591 deferred
2592 .iter()
2593 .all(|d| !matches!(d, Deferred::PushCapture(_))),
2594 "double-click does NOT arm tracking"
2595 );
2596 }
2597
2598 // -- auto-seed: limit populated without explicit ov_update ----------------
2599
2600 /// `Outline` auto-seeds scrollbar limits on the first context-bearing call.
2601 ///
2602 /// Construct the outline with a known tree, do NOT call `ov_update`, then
2603 /// drive a single `ov_set_state` call and assert the limits are now correct.
2604 /// A second call must not change the result (idempotent / seeded-once).
2605 #[test]
2606 fn auto_seeds_limit_on_first_event() {
2607 // animals_tree has 3 visible nodes (Animals, Cats, Dogs).
2608 let mut o = Outline::new(Rect::new(0, 0, 20, 5), None, None, Some(animals_tree()));
2609 // Confirm we start unseeded with limit.y == 0.
2610 assert!(!o.ov().seeded, "seeded starts false");
2611 assert_eq!(o.ov().limit.y, 0, "limit.y starts at 0 before auto-seed");
2612
2613 let mut out = VecDeque::new();
2614 let mut timers = crate::timer::TimerQueue::new();
2615 let mut deferred: Vec<Deferred> = vec![];
2616
2617 // Drive ov_set_state — this is the first context-bearing call.
2618 {
2619 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2620 ov_set_state(&mut o, StateFlag::Selected, true, &mut ctx);
2621 }
2622
2623 // limit.y should now equal 3 (all three nodes are visible).
2624 assert!(
2625 o.ov().seeded,
2626 "seeded is true after first context-bearing call"
2627 );
2628 assert_eq!(
2629 o.ov().limit.y,
2630 3,
2631 "limit.y = 3 after auto-seed (Animals + Cats + Dogs)"
2632 );
2633
2634 // Drive a second call — limit must not change (idempotent).
2635 let limit_after_first = o.ov().limit;
2636 {
2637 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2638 ov_set_state(&mut o, StateFlag::Selected, false, &mut ctx);
2639 }
2640 assert_eq!(
2641 o.ov().limit,
2642 limit_after_first,
2643 "limit unchanged after second call (ensure_seeded is a no-op once seeded)"
2644 );
2645 }
2646
2647 /// `ov_handle_event` also auto-seeds; verify via a keyboard event.
2648 #[test]
2649 fn auto_seeds_via_handle_event() {
2650 let mut o = Outline::new(Rect::new(0, 0, 20, 5), None, None, Some(animals_tree()));
2651 assert_eq!(o.ov().limit.y, 0, "pre-seed limit is 0");
2652
2653 let mut out = VecDeque::new();
2654 let mut timers = crate::timer::TimerQueue::new();
2655 let mut deferred: Vec<Deferred> = vec![];
2656
2657 // A KeyDown event that ov_handle_event will not consume (an unbound key).
2658 let mut ev = Event::KeyDown(crate::event::KeyEvent::new(
2659 Key::Char('z'),
2660 crate::event::KeyModifiers::default(),
2661 ));
2662 {
2663 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2664 o.handle_event(&mut ev, &mut ctx);
2665 }
2666 assert!(o.ov().seeded, "seeded after handle_event");
2667 assert_eq!(
2668 o.ov().limit.y,
2669 3,
2670 "limit.y = 3 after auto-seed via handle_event"
2671 );
2672 }
2673}