tvision_rs/widgets/scroller.rs
1//! `Scroller`, the base for scrollable content views (documented on the type).
2
3use crate::theme::Role;
4use crate::view::{Context, DrawCtx, Options, Point, Rect, StateFlag, View, ViewId, ViewState};
5
6/// The base scrollable-content view.
7///
8/// The base for scrollable content views (the editor, the text terminal, the
9/// outline viewer). A scroller references **two sibling scroll bars** that live
10/// on the window frame, mirrors their `value` into its own
11/// [`delta`](Scroller::delta) (the scroll offset its subclasses draw with), and
12/// pushes range/value changes back to them.
13///
14/// # The cross-view scrollbar broker — read **and** write
15///
16/// A scroller both *reads* its two scroll bars (their `value`, arrow step) and
17/// *mutates* them (set value/params, show/hide). But a leaf view holds only
18/// `&mut Context` during dispatch — no tree access — and the bars are
19/// window-frame siblings it cannot own, so it can neither read nor mutate them
20/// directly.
21///
22/// **The event loop is the broker, in both directions.** The scroller stores its
23/// bars as [`Option<ViewId>`](crate::view::ViewId) handles and issues
24/// [`Deferred`](crate::view::Deferred) ops naming them; the loop performs every
25/// cross-view read/write at apply time. A
26/// [`SCROLL_BAR_CHANGED`](crate::command::Command::SCROLL_BAR_CHANGED)
27/// broadcast's `source` is the **filter** only (the scroller reacts iff
28/// `source ∈ {h, v}`); the value is not stuffed into the message — the loop
29/// resolves the subject bar and reads its `value`.
30///
31/// # Selected color
32///
33/// The base scroller only ever draws a fill in [`Role::ScrollerNormal`]. The
34/// "selected" scroller color exists in the palette but is never used by the base;
35/// the editor, which selects text, applies its own selection color, so no
36/// `ScrollerSelected` role is wired here.
37///
38/// # Resizing
39///
40/// [`View::change_bounds`](crate::view::View::change_bounds) takes no
41/// [`Context`], but re-publishing scroll-bar parameters after a resize needs one.
42/// So `change_bounds` stays geometry-only, and [`Scroller::set_limit`] /
43/// [`Scroller::scroll_to`] are the public `Context`-taking entries that
44/// (re)publish the parameters; a window or editor that resizes a scroller calls
45/// `set_limit` afterwards. There is no automatic re-emit on a bare bounds change,
46/// because nothing currently drives that path.
47///
48/// Manages scroll state and keeps two sibling scroll bars in sync with its
49/// content offset. The base draws only a uniform fill; subclasses (e.g. the
50/// editor) override [`draw`](View::draw) and use [`delta`](Self::delta) to
51/// shift their content. Wire a `Scroller` into a window by passing the scroll
52/// bar [`ViewId`]s at construction time; call [`set_limit`](Self::set_limit)
53/// whenever the content size changes, and [`scroll_to`](Self::scroll_to) to
54/// jump to a position programmatically.
55///
56/// Cross-view scroll-bar reads and writes are brokered by the event loop, as
57/// described above.
58///
59/// # Turbo Vision heritage
60///
61/// Ports `TScroller` (`tscrolle.cpp`). Owner back-pointers to the sibling scroll
62/// bars become [`ViewId`] handles brokered by the event loop, and the
63/// palette becomes [`Role`]s. The original draw-re-entrancy guard is unneeded
64/// under whole-tree redraw and is dropped.
65pub struct Scroller {
66 /// View state (geometry, flags, etc.) — the composition target.
67 state: ViewState,
68 /// The current scroll offset, mirrored from the scroll bars.
69 ///
70 /// Updated by the event loop (via [`apply_delta`](Self::apply_delta))
71 /// whenever a scroll bar's value changes. Subclasses read this in their
72 /// [`draw`](View::draw) override to shift content: a line at logical row
73 /// `r` is rendered at screen row `r - delta.y`, and similarly for `x`.
74 /// Do not write `delta` directly; use [`scroll_to`](Self::scroll_to) to
75 /// request a position change.
76 pub delta: Point,
77 /// Content extent `(x, y)`. Private; set via [`set_limit`](Self::set_limit).
78 limit: Point,
79 /// The horizontal scrollbar, by id (`None` if absent).
80 h_scroll_bar: Option<ViewId>,
81 /// The vertical scrollbar, by id (`None` if absent).
82 v_scroll_bar: Option<ViewId>,
83}
84
85impl Scroller {
86 /// Create a scroller with the given bounds and optional scroll bar handles.
87 ///
88 /// Pass the [`ViewId`]s of the horizontal and vertical scroll bars, or
89 /// `None` for either axis you don't need. The scroller starts at offset
90 /// `(0, 0)` with an empty content extent; call
91 /// [`set_limit`](Self::set_limit) after construction to publish the initial
92 /// range to the bars. The view is marked selectable so it can receive
93 /// keyboard focus.
94 ///
95 /// Broadcasts are delivered unconditionally — there is no `broadcast` event
96 /// mask bit — so no extra setup is needed to receive
97 /// [`SCROLL_BAR_CHANGED`](crate::command::Command::SCROLL_BAR_CHANGED).
98 pub fn new(bounds: Rect, h_scroll_bar: Option<ViewId>, v_scroll_bar: Option<ViewId>) -> Self {
99 let mut state = ViewState::new(bounds);
100 state.options = Options {
101 selectable: true,
102 ..Default::default()
103 };
104 Scroller {
105 state,
106 delta: Point::new(0, 0),
107 limit: Point::new(0, 0),
108 h_scroll_bar,
109 v_scroll_bar,
110 }
111 }
112
113 /// Return the current content extent as set by [`set_limit`](Self::set_limit).
114 ///
115 /// The returned point `(x, y)` is the logical width and height of the
116 /// scrollable content. Use this in a subclass `draw` implementation if you
117 /// need to know the total content size independently of [`delta`](Self::delta).
118 /// To change the extent, call [`set_limit`](Self::set_limit) — it both
119 /// stores the value and re-publishes the range to the scroll bars.
120 pub fn limit(&self) -> Point {
121 self.limit
122 }
123
124 /// Return the [`ViewId`] of the horizontal scroll bar, if one was supplied.
125 ///
126 /// Use this in a subclass when you need to address the scroll bar directly
127 /// (e.g. to call [`scroll_to`](Self::scroll_to) or query the bar's
128 /// [`ViewId`] for a broker operation). Returns `None` if the scroller was
129 /// created without a horizontal bar.
130 ///
131 /// # Turbo Vision heritage
132 ///
133 /// Corresponds to the public `TScroller::hScrollBar` pointer. In Rust the
134 /// raw pointer becomes a [`ViewId`] handle; the event loop brokers all
135 /// cross-view reads and writes through it rather than allowing direct
136 /// pointer access.
137 pub fn h_scroll_bar(&self) -> Option<ViewId> {
138 self.h_scroll_bar
139 }
140
141 /// Return the [`ViewId`] of the vertical scroll bar, if one was supplied.
142 ///
143 /// Use this in a subclass when you need to address the scroll bar directly.
144 /// Returns `None` if the scroller was created without a vertical bar.
145 ///
146 /// # Turbo Vision heritage
147 ///
148 /// Corresponds to the public `TScroller::vScrollBar` pointer. See
149 /// [`h_scroll_bar`](Self::h_scroll_bar) for the broker rationale.
150 pub fn v_scroll_bar(&self) -> Option<ViewId> {
151 self.v_scroll_bar
152 }
153
154 /// Apply a freshly-resolved scroll offset from the event loop's read broker.
155 ///
156 /// This is the Rust analog of C++ `TScroller::scrollDraw`. It is called
157 /// by the pump after it resolves both scroll bars and reads their current
158 /// `value`s, assembling them into `d`. If `d` differs from the stored
159 /// [`delta`](Self::delta), the cursor is shifted by `old_delta - d` (using
160 /// the **old** value — order matters) and then `delta` is overwritten.
161 /// The whole-tree redraw that follows the pump tick replaces the C++
162 /// `drawView` call.
163 ///
164 /// **Do not call this directly.** It is public so the pump can reach it via
165 /// the `as_any_mut` downcast; call [`scroll_to`](Self::scroll_to) to
166 /// request a position change from user code.
167 ///
168 /// # Turbo Vision heritage
169 ///
170 /// Ports `TScroller::scrollDraw`. The original read the bar values directly
171 /// via raw pointers; here the pump reads them and passes the result in `d`.
172 pub fn apply_delta(&mut self, d: Point) {
173 if d != self.delta {
174 // Shift the cursor using the OLD delta, before overwriting.
175 let new_cursor = self.state.cursor + (self.delta - d);
176 self.state.cursor = new_cursor;
177 self.delta = d;
178 }
179 }
180
181 /// Set the content extent to `(x, y)` and re-publish each bar's range and
182 /// page parameters.
183 ///
184 /// Call this after construction and after any resize to tell the scroll bars
185 /// the total content dimensions. For the horizontal bar: `min = 0`,
186 /// `max = x - view_width`, `page_step = view_width - 1`; the vertical bar
187 /// mirrors on `y` and `view_height`. The current bar `value` and arrow step
188 /// are preserved. Cross-view writes are queued as deferred
189 /// [`ScrollBarSetParams`](crate::view::Deferred::ScrollBarSetParams) ops
190 /// executed by the pump — no direct bar access occurs.
191 ///
192 /// [`on_bounds_changed`](Self::on_bounds_changed) calls `set_limit` automatically
193 /// after a resize with the previously stored extent, so you only need to call
194 /// it explicitly when the *content* size changes.
195 pub fn set_limit(&mut self, x: i32, y: i32, ctx: &mut Context) {
196 self.limit = Point::new(x, y);
197 let size = self.state.size;
198 if let Some(h) = self.h_scroll_bar {
199 ctx.request_scroll_bar_params(
200 h,
201 None, // preserve value
202 Some(0), // min
203 Some(x - size.x), // max
204 Some(size.x - 1), // page_step
205 None, // preserve arrow_step
206 );
207 }
208 if let Some(v) = self.v_scroll_bar {
209 ctx.request_scroll_bar_params(
210 v,
211 None,
212 Some(0),
213 Some(y - size.y),
214 Some(size.y - 1),
215 None,
216 );
217 }
218 }
219
220 /// Request that the scroll bars move to position `(x, y)`, preserving range
221 /// and steps.
222 ///
223 /// Queues a deferred
224 /// [`ScrollBarSetParams`](crate::view::Deferred::ScrollBarSetParams) op for
225 /// each present bar with only `value` updated (the range, page step, and
226 /// arrow step are left unchanged). The bar clamps the value to its live
227 /// range at apply time. The resulting
228 /// [`SCROLL_BAR_CHANGED`](crate::command::Command::SCROLL_BAR_CHANGED)
229 /// broadcast will then trigger the read broker, which calls
230 /// [`apply_delta`](Self::apply_delta) to update [`delta`](Self::delta).
231 ///
232 /// Call this to programmatically jump to a position, e.g. "go to line N" in
233 /// an editor. If you only need to update the bar's range (e.g. after loading
234 /// new content), use [`set_limit`](Self::set_limit) instead.
235 pub fn scroll_to(&mut self, x: i32, y: i32, ctx: &mut Context) {
236 if let Some(h) = self.h_scroll_bar {
237 ctx.request_scroll_bar_params(h, Some(x), None, None, None, None);
238 }
239 if let Some(v) = self.v_scroll_bar {
240 ctx.request_scroll_bar_params(v, Some(y), None, None, None, None);
241 }
242 }
243
244 /// Show or hide one scrollbar based on this scroller's active/selected state:
245 /// shown when either is set, hidden otherwise. Realized as a deferred
246 /// [`SetVisible`](crate::view::Deferred::SetVisible).
247 fn show_sbar(&self, sbar: Option<ViewId>, ctx: &mut Context) {
248 if let Some(id) = sbar {
249 let visible = self.state.state.active || self.state.state.selected;
250 ctx.request_set_visible(id, visible);
251 }
252 }
253}
254
255impl View for Scroller {
256 fn state(&self) -> &ViewState {
257 &self.state
258 }
259
260 fn state_mut(&mut self) -> &mut ViewState {
261 &mut self.state
262 }
263
264 /// A uniform fill of the entire view rect with [`Role::ScrollerNormal`] (no
265 /// active/selected branch). The "selected" scroller color is never used by
266 /// the base; the editor applies its own selection color instead.
267 ///
268 /// Subclasses (the editor) override `draw` and consume [`delta`](Self::delta).
269 fn draw(&mut self, ctx: &mut DrawCtx) {
270 let style = ctx.style(Role::ScrollerNormal);
271 let extent = self.state.get_extent();
272 ctx.fill(extent, ' ', style);
273 }
274
275 /// React to a [`SCROLL_BAR_CHANGED`](crate::command::Command::SCROLL_BAR_CHANGED)
276 /// broadcast whose `source` is one of this scroller's two bars by requesting a
277 /// deferred delta-sync (the read broker; see the [`Scroller`] docs).
278 ///
279 /// The `source ∈ {h_id, v_id}` test is the filter that decides whether this
280 /// scroller owns the firing bar.
281 fn handle_event(&mut self, ev: &mut crate::event::Event, ctx: &mut Context) {
282 if let crate::event::Event::Broadcast { command, source } = *ev
283 && command == crate::command::Command::SCROLL_BAR_CHANGED
284 && source.is_some()
285 && (source == self.h_scroll_bar || source == self.v_scroll_bar)
286 {
287 // The scroller must itself be inserted (have an id) to be addressable.
288 if let Some(scroller) = self.state.id() {
289 ctx.request_scroll_sync(scroller, self.h_scroll_bar, self.v_scroll_bar);
290 }
291 }
292 }
293
294 /// Called by the pump after it reads the sibling scrollbar values. Applies the
295 /// resulting delta to this scroller. A missing bar (`None`) is treated as
296 /// delta 0 — faithful to the previous `.unwrap_or(0)` read in the old pump arm.
297 fn apply_scroll_sync(&mut self, h: Option<i32>, v: Option<i32>, _ctx: &mut Context) {
298 self.apply_delta(Point::new(h.unwrap_or(0), v.unwrap_or(0)));
299 }
300
301 /// Flip a state flag and show or hide the scroll bars when focus changes.
302 ///
303 /// After updating the flag, if `flag` is [`Active`](StateFlag::Active) or
304 /// [`Selected`](StateFlag::Selected), each scroll bar is shown when
305 /// *either* flag is set and hidden when both are clear. This matches the
306 /// C++ behaviour: bars are visible whenever the scroller (or one of its
307 /// ancestors) has input focus. Visibility is applied via a deferred
308 /// [`SetVisible`](crate::view::Deferred::SetVisible) op brokered by the pump,
309 /// not by a direct call into the bar.
310 ///
311 /// When `flag` is [`Focused`](StateFlag::Focused), the standard
312 /// [`RECEIVED_FOCUS`](crate::command::Command::RECEIVED_FOCUS) /
313 /// [`RELEASED_FOCUS`](crate::command::Command::RELEASED_FOCUS) broadcast is
314 /// emitted; no bar visibility change occurs.
315 fn set_state(&mut self, flag: StateFlag, enable: bool, ctx: &mut Context) {
316 // Base: flip the flag (+ the Focused broadcast).
317 self.state_mut().set_flag(flag, enable);
318 if flag == StateFlag::Focused {
319 let source = self.state.id();
320 ctx.broadcast(
321 if enable {
322 crate::command::Command::RECEIVED_FOCUS
323 } else {
324 crate::command::Command::RELEASED_FOCUS
325 },
326 source,
327 );
328 }
329 if flag == StateFlag::Active || flag == StateFlag::Selected {
330 self.show_sbar(self.h_scroll_bar, ctx);
331 self.show_sbar(self.v_scroll_bar, ctx);
332 }
333 }
334
335 /// Re-publish scroll bar range parameters after a bounds change.
336 ///
337 /// Called by the pump after it has applied a `Deferred::ChangeBounds` op,
338 /// so `self.size` already reflects the new dimensions. Calls
339 /// [`set_limit`](Self::set_limit) with the previously stored `limit` values
340 /// so the bars' `max` and `page_step` are recomputed for the new view size.
341 ///
342 /// Subclasses that override this should call `super.on_bounds_changed(ctx)`
343 /// (or call `set_limit` themselves) to keep the bars consistent.
344 fn on_bounds_changed(&mut self, ctx: &mut Context) {
345 let (x, y) = (self.limit.x, self.limit.y);
346 self.set_limit(x, y, ctx);
347 }
348
349 /// Concrete-reach hatch (the sanctioned downcast): retained as a generic
350 /// escape so `Terminal` can delegate `as_any_mut` to its inner `Scroller`.
351 /// The `Deferred::ScrollSync` arm does NOT use this hatch — it dispatches
352 /// `apply_scroll_sync` to the `Scroller` override through the `View` trait
353 /// (delegate forwarder), not via `as_any_mut`.
354 fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
355 Some(self)
356 }
357}
358
359// ---------------------------------------------------------------------------
360// Tests
361// ---------------------------------------------------------------------------
362//
363// The cross-view *broker* (pump-side apply of ScrollSync /
364// ScrollBarSetParams / SetVisible) is tested end-to-end through `Program::pump_once`
365// in `src/app/program.rs` (it needs the pump's `group.find_mut`). Here we test the
366// scroller-side pieces directly: the ctor, `apply_delta` (the cursor-adjust order),
367// the request methods (which `Deferred` they queue), the `source` filter in
368// `handle_event`, `set_state`'s show/hide, and the base fill draw.
369#[cfg(test)]
370mod tests {
371 use super::*;
372 use crate::backend::{HeadlessBackend, Renderer};
373 use crate::command::Command;
374 use crate::event::Event;
375 use crate::screen::Buffer;
376 use crate::theme::Theme;
377 use crate::view::{Deferred, Group, ViewId};
378 use std::collections::VecDeque;
379
380 fn make_ctx<'a>(
381 out: &'a mut VecDeque<Event>,
382 timers: &'a mut crate::timer::TimerQueue,
383 deferred: &'a mut Vec<Deferred>,
384 ) -> Context<'a> {
385 Context::new(out, timers, 0, deferred)
386 }
387
388 /// A fake `ViewId` for filter tests: insert a throwaway view into a group and
389 /// read its stamped id. (Ids are only minted at `Group::insert`.)
390 fn mint_id() -> (Group, ViewId) {
391 let mut g = Group::new(Rect::new(0, 0, 4, 4));
392 let id = g.insert(Box::new(Scroller::new(Rect::new(0, 0, 1, 1), None, None)));
393 (g, id)
394 }
395
396 // -- 1. ctor -------------------------------------------------------------
397
398 #[test]
399 fn ctor_sets_selectable_and_zero_delta_limit() {
400 let s = Scroller::new(Rect::new(0, 0, 10, 5), None, None);
401 assert!(s.state.options.selectable, "ofSelectable set");
402 assert_eq!(s.delta, Point::new(0, 0));
403 assert_eq!(s.limit(), Point::new(0, 0));
404 // NOTE: opting into the broadcast class has no analogue here —
405 // broadcasts are delivered unconditionally (no `broadcast` bit in
406 // EventMask), so there is nothing to assert about the mask here.
407 assert_eq!(s.state.event_mask, crate::event::EventMask::default());
408 }
409
410 #[test]
411 fn ctor_records_scroll_bar_ids() {
412 let (_g, h) = mint_id();
413 let (_g2, v) = mint_id();
414 let s = Scroller::new(Rect::new(0, 0, 10, 5), Some(h), Some(v));
415 assert_eq!(s.h_scroll_bar(), Some(h));
416 assert_eq!(s.v_scroll_bar(), Some(v));
417 }
418
419 // -- 6. cursor adjust (apply_delta order) --------------------------------
420
421 /// The cursor must be shifted by the **old** `delta - d`, then `delta`
422 /// overwritten. Setup: cursor=(5,3), delta=(2,1); apply d=(4,0) →
423 /// cursor = (5,3) + ((2,1) - (4,0)) = (5-2, 3+1) = (3, 4); delta = (4,0).
424 #[test]
425 fn apply_delta_shifts_cursor_by_old_delta_minus_new() {
426 let mut s = Scroller::new(Rect::new(0, 0, 10, 5), None, None);
427 s.state.cursor = Point::new(5, 3);
428 s.delta = Point::new(2, 1);
429 s.apply_delta(Point::new(4, 0));
430 assert_eq!(s.delta, Point::new(4, 0), "delta overwritten with d");
431 assert_eq!(
432 s.state.cursor,
433 Point::new(3, 4),
434 "cursor shifted by OLD delta - d = (2-4, 1-0) = (-2, +1)"
435 );
436 }
437
438 #[test]
439 fn apply_delta_noop_when_unchanged() {
440 let mut s = Scroller::new(Rect::new(0, 0, 10, 5), None, None);
441 s.state.cursor = Point::new(5, 3);
442 s.delta = Point::new(2, 1);
443 s.apply_delta(Point::new(2, 1)); // same delta
444 assert_eq!(s.state.cursor, Point::new(5, 3), "cursor untouched");
445 assert_eq!(s.delta, Point::new(2, 1));
446 }
447
448 // -- 3. set_limit (write broker — queues the right Deferred) -------------
449
450 #[test]
451 fn set_limit_queues_params_preserving_value_and_arrow_step() {
452 let (_g, h) = mint_id();
453 let (_g2, v) = mint_id();
454 // 10×5 scroller (size.x=10, size.y=5).
455 let mut s = Scroller::new(Rect::new(0, 0, 10, 5), Some(h), Some(v));
456
457 let mut out = VecDeque::new();
458 let mut timers = crate::timer::TimerQueue::new();
459 let mut deferred: Vec<Deferred> = vec![];
460 {
461 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
462 s.set_limit(100, 50, &mut ctx);
463 }
464 assert_eq!(s.limit(), Point::new(100, 50));
465 assert_eq!(deferred.len(), 2, "one param op per bar");
466
467 // H bar: min=0, max=100-10=90, page_step=10-1=9, value/arrow preserved (None).
468 match deferred[0] {
469 Deferred::ScrollBarSetParams {
470 id,
471 value,
472 min,
473 max,
474 page_step,
475 arrow_step,
476 } => {
477 assert_eq!(id, h);
478 assert_eq!(value, None, "value preserved");
479 assert_eq!(min, Some(0));
480 assert_eq!(max, Some(90), "max = x - size.x");
481 assert_eq!(page_step, Some(9), "page_step = size.x - 1");
482 assert_eq!(arrow_step, None, "arrow_step preserved");
483 }
484 _ => panic!("expected H ScrollBarSetParams"),
485 }
486 // V bar: min=0, max=50-5=45, page_step=5-1=4.
487 match deferred[1] {
488 Deferred::ScrollBarSetParams {
489 id, max, page_step, ..
490 } => {
491 assert_eq!(id, v);
492 assert_eq!(max, Some(45), "max = y - size.y");
493 assert_eq!(page_step, Some(4), "page_step = size.y - 1");
494 }
495 _ => panic!("expected V ScrollBarSetParams"),
496 }
497 }
498
499 #[test]
500 fn set_limit_with_no_bars_queues_nothing() {
501 let mut s = Scroller::new(Rect::new(0, 0, 10, 5), None, None);
502 let mut out = VecDeque::new();
503 let mut timers = crate::timer::TimerQueue::new();
504 let mut deferred: Vec<Deferred> = vec![];
505 {
506 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
507 s.set_limit(100, 50, &mut ctx);
508 }
509 assert_eq!(s.limit(), Point::new(100, 50));
510 assert!(deferred.is_empty(), "no bars → no param ops");
511 }
512
513 // -- 4. scroll_to (write broker — value only) ----------------------------
514
515 #[test]
516 fn scroll_to_queues_value_only() {
517 let (_g, h) = mint_id();
518 let (_g2, v) = mint_id();
519 let mut s = Scroller::new(Rect::new(0, 0, 10, 5), Some(h), Some(v));
520 let mut out = VecDeque::new();
521 let mut timers = crate::timer::TimerQueue::new();
522 let mut deferred: Vec<Deferred> = vec![];
523 {
524 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
525 s.scroll_to(10, 5, &mut ctx);
526 }
527 assert_eq!(deferred.len(), 2);
528 match deferred[0] {
529 Deferred::ScrollBarSetParams {
530 id,
531 value,
532 min,
533 max,
534 page_step,
535 arrow_step,
536 } => {
537 assert_eq!(id, h);
538 assert_eq!(value, Some(10), "H value set");
539 assert!(
540 min.is_none() && max.is_none() && page_step.is_none() && arrow_step.is_none(),
541 "everything but value preserved"
542 );
543 }
544 _ => panic!("expected H value op"),
545 }
546 match deferred[1] {
547 Deferred::ScrollBarSetParams { id, value, .. } => {
548 assert_eq!(id, v);
549 assert_eq!(value, Some(5), "V value set");
550 }
551 _ => panic!("expected V value op"),
552 }
553 }
554
555 // -- 5. set_state / show_sbar --------------------------------------------
556
557 #[test]
558 fn set_state_select_shows_bars_deselect_hides() {
559 let (_g, h) = mint_id();
560 let (_g2, v) = mint_id();
561 let mut s = Scroller::new(Rect::new(0, 0, 10, 5), Some(h), Some(v));
562
563 // Select → both bars requested visible.
564 let mut out = VecDeque::new();
565 let mut timers = crate::timer::TimerQueue::new();
566 let mut deferred: Vec<Deferred> = vec![];
567 {
568 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
569 s.set_state(StateFlag::Selected, true, &mut ctx);
570 }
571 assert!(s.state.state.selected);
572 assert_eq!(deferred.len(), 2);
573 assert!(matches!(deferred[0], Deferred::SetVisible(id, true) if id == h));
574 assert!(matches!(deferred[1], Deferred::SetVisible(id, true) if id == v));
575
576 // Deselect → both bars requested hidden (active still false).
577 deferred.clear();
578 {
579 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
580 s.set_state(StateFlag::Selected, false, &mut ctx);
581 }
582 assert!(!s.state.state.selected);
583 assert!(matches!(deferred[0], Deferred::SetVisible(id, false) if id == h));
584 assert!(matches!(deferred[1], Deferred::SetVisible(id, false) if id == v));
585 }
586
587 #[test]
588 fn set_state_active_keeps_bars_visible_even_when_not_selected() {
589 // showSBar uses (sfActive | sfSelected): active alone keeps them shown.
590 let (_g, h) = mint_id();
591 let mut s = Scroller::new(Rect::new(0, 0, 10, 5), Some(h), None);
592 let mut out = VecDeque::new();
593 let mut timers = crate::timer::TimerQueue::new();
594 let mut deferred: Vec<Deferred> = vec![];
595 {
596 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
597 s.set_state(StateFlag::Active, true, &mut ctx);
598 }
599 assert!(s.state.state.active);
600 assert!(
601 matches!(deferred[0], Deferred::SetVisible(id, true) if id == h),
602 "active (not selected) still shows the bar"
603 );
604 }
605
606 #[test]
607 fn set_state_non_active_selected_flag_does_not_touch_bars() {
608 let (_g, h) = mint_id();
609 let mut s = Scroller::new(Rect::new(0, 0, 10, 5), Some(h), None);
610 let mut out = VecDeque::new();
611 let mut timers = crate::timer::TimerQueue::new();
612 let mut deferred: Vec<Deferred> = vec![];
613 {
614 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
615 // Focused triggers a broadcast but NOT showSBar.
616 s.set_state(StateFlag::Focused, true, &mut ctx);
617 }
618 assert!(
619 !deferred
620 .iter()
621 .any(|d| matches!(d, Deferred::SetVisible(..))),
622 "Focused must not show/hide bars"
623 );
624 }
625
626 // -- 2. handle_event source filter (read broker request side) ------------
627
628 #[test]
629 fn handle_event_requests_sync_only_for_own_bars() {
630 // The scroller must be inserted to have an id (and to be addressable).
631 let mut group = Group::new(Rect::new(0, 0, 20, 10));
632 let (_gh, h) = mint_id();
633 let (_gv, v) = mint_id();
634 let scroller_id = group.insert(Box::new(Scroller::new(
635 Rect::new(0, 0, 10, 5),
636 Some(h),
637 Some(v),
638 )));
639
640 let mut out = VecDeque::new();
641 let mut timers = crate::timer::TimerQueue::new();
642 let mut deferred: Vec<Deferred> = vec![];
643
644 // (a) Broadcast sourced by the H bar → ScrollSync queued.
645 {
646 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
647 let mut ev = Event::Broadcast {
648 command: Command::SCROLL_BAR_CHANGED,
649 source: Some(h),
650 };
651 group
652 .find_mut(scroller_id)
653 .unwrap()
654 .handle_event(&mut ev, &mut ctx);
655 }
656 assert_eq!(deferred.len(), 1, "own-bar broadcast → one sync request");
657 assert!(matches!(
658 deferred[0],
659 Deferred::ScrollSync { target, h: rh, v: rv }
660 if target == scroller_id && rh == Some(h) && rv == Some(v)
661 ));
662
663 // (b) Broadcast sourced by an UNRELATED view (the scroller itself — a real
664 // id that is neither bar) → filter bites, nothing queued.
665 deferred.clear();
666 {
667 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
668 let mut ev = Event::Broadcast {
669 command: Command::SCROLL_BAR_CHANGED,
670 source: Some(scroller_id),
671 };
672 group
673 .find_mut(scroller_id)
674 .unwrap()
675 .handle_event(&mut ev, &mut ctx);
676 }
677 assert!(
678 deferred.is_empty(),
679 "broadcast from a non-bar source must be ignored (the source filter bites)"
680 );
681
682 // (c) A different command from the H bar → also ignored.
683 {
684 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
685 let mut ev = Event::Broadcast {
686 command: Command::SCROLL_BAR_CLICKED,
687 source: Some(h),
688 };
689 group
690 .find_mut(scroller_id)
691 .unwrap()
692 .handle_event(&mut ev, &mut ctx);
693 }
694 assert!(
695 deferred.is_empty(),
696 "only cmScrollBarChanged triggers a sync"
697 );
698 }
699
700 // -- 7. trivial snapshot -------------------------------------------------
701
702 #[test]
703 fn snapshot_base_scroller_fill() {
704 let theme = Theme::classic_blue();
705 let mut s = Scroller::new(Rect::new(0, 0, 8, 4), None, None);
706
707 let (backend, screen) = HeadlessBackend::new(8, 4);
708 let mut r = Renderer::new(Box::new(backend));
709 r.render(|buf: &mut Buffer| {
710 let bounds = s.state.get_bounds();
711 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
712 s.draw(&mut dc);
713 });
714 insta::assert_snapshot!(screen.snapshot());
715 }
716}