tvision_rs/widgets/scrollbar.rs
1//! `ScrollBar` (documented on the type).
2
3use crate::capture::TrackMask;
4use crate::command::Command;
5use crate::data::FieldValue;
6use crate::event::{Event, Key, MouseWheel, ctrl_to_arrow};
7use crate::theme::Role;
8use crate::view::{Context, DrawCtx, GrowMode, Point, Rect, View, ViewState};
9
10// ---------------------------------------------------------------------------
11// Scrollbar part codes
12// ---------------------------------------------------------------------------
13
14/// Which part of the scrollbar a point hits.
15///
16/// The vertical variants ([`UpArrow`](Part::UpArrow)/[`DownArrow`](Part::DownArrow)/
17/// [`PageUp`](Part::PageUp)/[`PageDown`](Part::PageDown)) mirror the four
18/// horizontal ones; orientation selects which set applies.
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20enum Part {
21 /// Horizontal: left arrow.
22 LeftArrow,
23 /// Horizontal: right arrow.
24 RightArrow,
25 /// Horizontal: page left (trough left of thumb).
26 PageLeft,
27 /// Horizontal: page right (trough right of thumb).
28 PageRight,
29 /// Vertical: up arrow.
30 UpArrow,
31 /// Vertical: down arrow.
32 DownArrow,
33 /// Vertical: page up (trough above thumb).
34 PageUp,
35 /// Vertical: page down (trough below thumb).
36 PageDown,
37 /// The thumb itself.
38 Indicator,
39}
40
41impl Part {
42 /// The scroll step for this part: the arrow step for arrows, the page step
43 /// for troughs, negated for the back (left/up) direction.
44 fn scroll_step(self, ar_step: i32, pg_step: i32) -> i32 {
45 let is_page = matches!(
46 self,
47 Part::PageLeft | Part::PageRight | Part::PageUp | Part::PageDown
48 );
49 let step = if is_page { pg_step } else { ar_step };
50 let is_forward = matches!(
51 self,
52 Part::RightArrow | Part::PageRight | Part::DownArrow | Part::PageDown
53 );
54 if is_forward { step } else { -step }
55 }
56}
57
58// ---------------------------------------------------------------------------
59// ScrollBar
60// ---------------------------------------------------------------------------
61
62/// A single-axis scroll-bar widget: a draggable thumb between two step-arrows,
63/// with paging troughs on either side.
64///
65/// A scroll bar: a draggable thumb, paging troughs, and step arrows, drawn into
66/// its own 1×N (vertical) or N×1 (horizontal) bounds. Orientation is inferred
67/// from the bounds at construction: `width == 1` means vertical, `height == 1`
68/// means horizontal.
69///
70/// # Glyphs
71///
72/// The arrow/page/thumb characters live in [`crate::theme::Glyphs`]
73/// (`sb_v_arrow_back`, `sb_v_arrow_fwd`, `sb_h_arrow_back`, `sb_h_arrow_fwd`,
74/// `sb_page`, `sb_thumb`, `sb_page_no_range`) and are read via `ctx.glyphs()`.
75///
76/// # Broadcasts
77///
78/// When the value changes, the bar broadcasts [`Command::SCROLL_BAR_CHANGED`],
79/// carrying its own [`ViewId`](crate::view::ViewId) as the broadcast `source`, so
80/// an owner with two bars can tell which bar fired. On mouse-down / keyboard
81/// action it likewise broadcasts [`Command::SCROLL_BAR_CLICKED`]. The bar only
82/// emits these; a scroller, list viewer, or editor consumes them (see the
83/// [scroller's read-sync](crate::widgets::Scroller)).
84///
85/// # Press-and-hold auto-repeat
86///
87/// The bar supports two modal holds, each driven through the mouse-track capture:
88///
89/// * **Arrow press-and-hold:** `MouseDown` on an arrow does the first step, then
90/// calls [`Context::start_mouse_track`]. Each auto tick re-derives the part code
91/// under the cursor; if it still matches the clicked part, it steps the value.
92/// `MouseUp` clears tracking.
93///
94/// * **Thumb drag:** `MouseDown` on the indicator (or outside the extent) does
95/// the first recompute, then arms the capture. Each tracked move recomputes the
96/// value from the thumb position. `MouseUp` clears tracking.
97///
98/// # Colors
99///
100/// Two [`Theme`](crate::theme::Theme) roles control the scrollbar appearance:
101///
102/// * [`Role::ScrollBarPage`] — the trough (page) cells.
103/// * [`Role::ScrollBarControls`] — arrow glyphs and the thumb.
104///
105/// The classic blue theme resolves both to blue-on-cyan via the palette chain
106/// `CScrollBar → cpBlueWindow → cpAppColor` (slots 11–12 in the app palette).
107/// The C++ `CScrollBar` has three entries — page slot and two control slots
108/// (arrows + indicator); those two control slots share one RGB value, so Rust
109/// collapses them into the single `ScrollBarControls` role.
110///
111/// Orientation is derived from bounds at construction (`size.x == 1` →
112/// vertical, `size.y == 1` → horizontal). Construct with [`ScrollBar::new`],
113/// then call [`set_params`](Self::set_params) (or the convenience wrappers) to
114/// configure the range. When the user interacts with the bar it broadcasts
115/// [`Command::SCROLL_BAR_CHANGED`]; a paired scroller or list viewer listens
116/// for this broadcast and syncs its own position. The broadcast and press-and-hold protocol is
117/// described above.
118///
119/// # Turbo Vision heritage
120///
121/// Ports `TScrollBar` (`tscrlbar.cpp`/`scrlbar.h`). The hardcoded glyph tables
122/// become [`Glyphs`](crate::theme::Glyphs) fields (D7); the owner back-pointer
123/// plus its event payload become [`Context`] broadcasts that carry a resolvable
124/// [`ViewId`](crate::view::ViewId) `source` (D3, D4).
125pub struct ScrollBar {
126 /// View state (geometry, flags, etc.) — the composition target.
127 pub state: ViewState,
128 /// Current scroll position within `[min_value, max_value]`. Starts at `0`.
129 ///
130 /// This field is readable but treat it as read-only from outside the widget:
131 /// use [`set_value`](Self::set_value) (or [`set_params`](Self::set_params))
132 /// to change the position so the broker broadcast fires and the display
133 /// stays consistent. The broker downcast path reads this field directly via
134 /// [`View::value`].
135 pub value: i32,
136 /// Inclusive lower bound of the scroll range. Starts at `0`.
137 ///
138 /// To update the range, call [`set_range`](Self::set_range) or
139 /// [`set_params`](Self::set_params) — they clamp `value` and fire the
140 /// [`Command::SCROLL_BAR_CHANGED`] broadcast.
141 pub min_value: i32,
142 /// Inclusive upper bound of the scroll range. Starts at `0`.
143 ///
144 /// To update the range, call [`set_range`](Self::set_range) or
145 /// [`set_params`](Self::set_params) — they clamp `value` and fire the
146 /// [`Command::SCROLL_BAR_CHANGED`] broadcast.
147 pub max_value: i32,
148 /// Distance the thumb moves when the user clicks the trough (page area).
149 /// Starts at `1`. To update both steps together, call
150 /// [`set_step`](Self::set_step) or [`set_params`](Self::set_params).
151 pub page_step: i32,
152 /// Distance the thumb moves when the user clicks an arrow or presses an
153 /// arrow key. Starts at `1`. To update both steps together, call
154 /// [`set_step`](Self::set_step) or [`set_params`](Self::set_params).
155 pub arrow_step: i32,
156 /// Whether this is a vertical bar (`size.x == 1`). Derived at construction.
157 vertical: bool,
158 /// Absolute screen position of scrollbar-local `(0, 0)`, cached each `draw`
159 /// so the mouse-tracking capture can convert absolute mouse coords to
160 /// bar-local (the `Button::abs_origin` pattern).
161 abs_origin: Point,
162 /// Whether a mouse hold-track is in flight. Guards the `MouseAuto` /
163 /// `MouseMove` / `MouseUp` tracking arms against stray (untracked) events.
164 tracking: bool,
165 /// The part that was clicked to start an arrow/page hold-track. `None` for
166 /// the thumb/default branch. The part code under the cursor is re-derived on
167 /// each auto tick and compared against this to decide whether to keep stepping.
168 tracked_part: Option<Part>,
169}
170
171impl ScrollBar {
172 /// Create a scrollbar sized to `bounds`.
173 ///
174 /// Orientation is inferred at construction: `bounds.size.x == 1` means
175 /// vertical; `bounds.size.y == 1` means horizontal. The grow mode is set
176 /// accordingly so the bar stays pinned to its owner's edge as the owner
177 /// resizes.
178 ///
179 /// All scroll state starts at zero (`value`, `min_value`, `max_value`) and
180 /// both step sizes start at `1`. Call [`set_params`](Self::set_params) (or
181 /// the convenience wrappers [`set_range`](Self::set_range) /
182 /// [`set_step`](Self::set_step)) after inserting the bar into a group to
183 /// configure the live range.
184 ///
185 /// The bar is not selectable by default (no [`ofSelectable`] flag), which is
186 /// intentional: mouse events are delivered directly by the group, and
187 /// keyboard events reach it only through post-processing (enabled via
188 /// [`with_keyboard`](Self::with_keyboard)).
189 ///
190 /// Arrow/page glyph characters are read from [`DrawCtx::glyphs`](crate::view::DrawCtx::glyphs) at draw
191 /// time — they are not stored on the widget itself.
192 ///
193 /// [`ofSelectable`]: crate::view::Options::selectable
194 pub fn new(bounds: Rect) -> Self {
195 let mut state = ViewState::new(bounds);
196 let vertical = state.size.x == 1;
197
198 // Grow mode per orientation: a vertical bar tracks the right edge and
199 // full height; a horizontal bar tracks the bottom edge and full width.
200 if vertical {
201 state.grow_mode = GrowMode {
202 lo_x: true,
203 hi_x: true,
204 hi_y: true,
205 ..Default::default()
206 };
207 } else {
208 state.grow_mode = GrowMode {
209 lo_y: true,
210 hi_x: true,
211 hi_y: true,
212 ..Default::default()
213 };
214 }
215
216 // Not selectable (no options set). Mouse events are delivered directly;
217 // keyboard events reach it only via post-processing, which
218 // standard_scroll_bar enables when ScrollBarOptions::handle_keyboard is true.
219
220 ScrollBar {
221 state,
222 value: 0,
223 min_value: 0,
224 max_value: 0,
225 page_step: 1,
226 arrow_step: 1,
227 vertical,
228 abs_origin: Point::new(0, 0),
229 tracking: false,
230 tracked_part: None,
231 }
232 }
233
234 /// Enable keyboard scrolling on this bar.
235 ///
236 /// Sets the post-process option (`ofPostProcess`) so the bar receives
237 /// arrow / page / Home / End keys from the focused chain even when the bar
238 /// itself is not the current view. Use this when you want the keyboard to
239 /// scroll a pane that has its own focused content (e.g. an editor with an
240 /// attached vertical scrollbar).
241 ///
242 /// Call this as a builder on [`new`](Self::new):
243 /// ```ignore
244 /// let bar = ScrollBar::new(bounds).with_keyboard();
245 /// ```
246 /// `Window::standard_scroll_bar` passes `handle_keyboard: true` to achieve
247 /// the same effect automatically.
248 pub fn with_keyboard(mut self) -> Self {
249 self.state.options.post_process = true;
250 self
251 }
252
253 /// Whether this bar is oriented vertically (width == 1).
254 pub fn is_vertical(&self) -> bool {
255 self.vertical
256 }
257
258 // -----------------------------------------------------------------------
259 // Value / range logic (ports setParams / setValue / setRange / setStep)
260 // -----------------------------------------------------------------------
261
262 /// Update value, range, and step sizes atomically.
263 ///
264 /// `a_max` is floored to `a_min`; `a_value` is clamped to `[a_min, a_max]`.
265 /// If `value` changed, broadcasts [`Command::SCROLL_BAR_CHANGED`] so that
266 /// a linked scroller or list viewer can sync its own position (see the
267 /// [`ScrollBar`] broadcast docs). Steps are set unconditionally at
268 /// the end, regardless of whether the value or range changed.
269 ///
270 /// The display is repainted automatically on the next whole-tree redraw pass
271 /// — there is no explicit `draw_view()` call here (unlike the C++
272 /// `TScrollBar::setParams`, which called `drawView()` before broadcasting).
273 /// The convenience wrappers [`set_value`](Self::set_value),
274 /// [`set_range`](Self::set_range), and [`set_step`](Self::set_step) all
275 /// forward to this method.
276 pub fn set_params(
277 &mut self,
278 a_value: i32,
279 a_min: i32,
280 a_max: i32,
281 a_pg_step: i32,
282 a_ar_step: i32,
283 ctx: &mut Context,
284 ) {
285 let a_max = a_max.max(a_min);
286 let a_value = a_value.clamp(a_min, a_max);
287 let old_value = self.value;
288
289 if old_value != a_value || self.min_value != a_min || self.max_value != a_max {
290 self.value = a_value;
291 self.min_value = a_min;
292 self.max_value = a_max;
293 if old_value != a_value {
294 self.scroll_draw(ctx);
295 }
296 }
297 self.page_step = a_pg_step;
298 self.arrow_step = a_ar_step;
299 }
300
301 /// Move the scroll position to `a_value`, clamped to `[min_value, max_value]`.
302 ///
303 /// Broadcasts [`Command::SCROLL_BAR_CHANGED`] if the value actually changes.
304 /// Use this when the owner has scrolled programmatically and wants the bar to
305 /// reflect the new position. Forwards to [`set_params`](Self::set_params).
306 pub fn set_value(&mut self, a_value: i32, ctx: &mut Context) {
307 self.set_params(
308 a_value,
309 self.min_value,
310 self.max_value,
311 self.page_step,
312 self.arrow_step,
313 ctx,
314 );
315 }
316
317 /// Update the `[min, max]` range, keeping value and step sizes.
318 ///
319 /// `value` is clamped to the new range and, if it changed, a
320 /// [`Command::SCROLL_BAR_CHANGED`] broadcast is emitted. Call this when the
321 /// total size of the scrollable content changes (e.g. the file being edited
322 /// gains or loses lines). Forwards to [`set_params`](Self::set_params).
323 pub fn set_range(&mut self, a_min: i32, a_max: i32, ctx: &mut Context) {
324 self.set_params(
325 self.value,
326 a_min,
327 a_max,
328 self.page_step,
329 self.arrow_step,
330 ctx,
331 );
332 }
333
334 /// Update the page and arrow step sizes, keeping value and range.
335 ///
336 /// Changing step sizes does not broadcast — only a `value` change triggers
337 /// [`Command::SCROLL_BAR_CHANGED`]. Use this when the visible area of the
338 /// scrollable content changes (e.g. the window is resized), since the page
339 /// size typically tracks the viewport height. Forwards to
340 /// [`set_params`](Self::set_params).
341 pub fn set_step(&mut self, a_pg_step: i32, a_ar_step: i32, ctx: &mut Context) {
342 self.set_params(
343 self.value,
344 self.min_value,
345 self.max_value,
346 a_pg_step,
347 a_ar_step,
348 ctx,
349 );
350 }
351
352 /// Broadcast [`Command::SCROLL_BAR_CHANGED`], carrying this bar's id as the
353 /// broadcast `source` so a two-bar owner can tell which bar fired.
354 fn scroll_draw(&self, ctx: &mut Context) {
355 ctx.broadcast(Command::SCROLL_BAR_CHANGED, self.state().id());
356 }
357
358 // -----------------------------------------------------------------------
359 // Position / size math
360 // -----------------------------------------------------------------------
361
362 /// The scrollbar's active length in cells: the axis length, at least 3.
363 pub fn get_size(&self) -> i32 {
364 let s = if self.vertical {
365 self.state.size.y
366 } else {
367 self.state.size.x
368 };
369 s.max(3)
370 }
371
372 /// The thumb position: a 1-based cell index along the bar's axis
373 /// (`1..=get_size()-2` inclusive).
374 ///
375 /// With an empty range the thumb sits at 1; otherwise the value is mapped
376 /// linearly across the inner cells (`get_size() - 3`), rounded to nearest.
377 pub fn get_pos(&self) -> i32 {
378 let r = self.max_value - self.min_value;
379 if r == 0 {
380 1
381 } else {
382 ((i64::from(self.value - self.min_value) * i64::from(self.get_size() - 3)
383 + i64::from(r >> 1))
384 / i64::from(r)) as i32
385 + 1
386 }
387 }
388
389 // -----------------------------------------------------------------------
390 // Part classification
391 // -----------------------------------------------------------------------
392
393 /// Classify which [`Part`] a point hits.
394 ///
395 /// `mark` is the position along the scrollbar axis (x for horizontal,
396 /// y for vertical), in view-local coords. `pos` is the current thumb
397 /// cell index. `s` is [`get_size`](Self::get_size)` - 1`.
398 ///
399 /// Returns `None` if the point is outside the view extent.
400 fn get_part_code(&self, mark: i32, pos: i32, s: i32) -> Option<Part> {
401 if mark == pos {
402 Some(Part::Indicator)
403 } else if mark < 1 {
404 if self.vertical {
405 Some(Part::UpArrow)
406 } else {
407 Some(Part::LeftArrow)
408 }
409 } else if mark < pos {
410 if self.vertical {
411 Some(Part::PageUp)
412 } else {
413 Some(Part::PageLeft)
414 }
415 } else if mark < s {
416 if self.vertical {
417 Some(Part::PageDown)
418 } else {
419 Some(Part::PageRight)
420 }
421 } else {
422 if self.vertical {
423 Some(Part::DownArrow)
424 } else {
425 Some(Part::RightArrow)
426 }
427 }
428 }
429}
430
431impl View for ScrollBar {
432 fn state(&self) -> &ViewState {
433 &self.state
434 }
435
436 fn state_mut(&mut self) -> &mut ViewState {
437 &mut self.state
438 }
439
440 /// The bar's `value` exposed as the typed transfer currency — a scroller,
441 /// list viewer, or editor read-broker reads this through the trait (the pump
442 /// resolves the bar by id and reads `value`).
443 fn value(&self) -> Option<FieldValue> {
444 Some(FieldValue::Int(self.value))
445 }
446
447 /// Concrete-reach hatch (the sanctioned downcast): the pump downcasts to
448 /// `&mut ScrollBar` to call `set_params` when applying a
449 /// `Deferred::ScrollBarSetParams` from a scroller.
450 fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
451 Some(self)
452 }
453
454 /// Paint the scrollbar into its one-cell-wide (or one-cell-tall) bounds.
455 ///
456 /// The bar is divided into five logical zones (shown for vertical; horizontal
457 /// mirrors on the x-axis):
458 ///
459 /// | Cell(s) | Glyph source | Theme role |
460 /// |-----------------|---------------------------------|---------------------------------|
461 /// | 0 | `glyphs.sb_v_arrow_back` | [`Role::ScrollBarControls`] |
462 /// | 1 .. pos-1 | `glyphs.sb_page` | [`Role::ScrollBarPage`] |
463 /// | pos | `glyphs.sb_thumb` | [`Role::ScrollBarControls`] |
464 /// | pos+1 .. s-1 | `glyphs.sb_page` | [`Role::ScrollBarPage`] |
465 /// | s | `glyphs.sb_v_arrow_fwd` | [`Role::ScrollBarControls`] |
466 ///
467 /// When `min_value == max_value` (empty range), every inner cell is drawn
468 /// with `glyphs.sb_page_no_range` and the thumb is omitted. Glyphs are
469 /// read from [`DrawCtx::glyphs`] at paint time and are never stored on the
470 /// widget. This replaces the C++ `drawPos` helper arrays and the hardcoded
471 /// `vChars`/`hChars` tables.
472 fn draw(&mut self, ctx: &mut DrawCtx) {
473 // Cache absolute origin for the mouse-tracking capture: the
474 // MouseTrackCapture converts absolute mouse coords to bar-local via this
475 // value, mirroring the Button `abs_origin` pattern.
476 self.abs_origin = ctx.origin();
477 let glyphs = *ctx.glyphs();
478 let page_style = ctx.style(Role::ScrollBarPage);
479 let ctrl_style = ctx.style(Role::ScrollBarControls);
480
481 let s = self.get_size() - 1; // last cell index
482 let pos = self.get_pos();
483 let no_range = self.max_value == self.min_value;
484
485 if self.vertical {
486 // Draw each row of the 1×height bar.
487 for row in 0..=s {
488 let (ch, style) = if row == 0 {
489 (glyphs.sb_v_arrow_back, ctrl_style)
490 } else if row == s {
491 (glyphs.sb_v_arrow_fwd, ctrl_style)
492 } else if no_range {
493 (glyphs.sb_page_no_range, page_style)
494 } else if row == pos {
495 (glyphs.sb_thumb, ctrl_style)
496 } else {
497 (glyphs.sb_page, page_style)
498 };
499 ctx.put_char(0, row, ch, style);
500 }
501 } else {
502 // Draw each column of the width×1 bar.
503 for col in 0..=s {
504 let (ch, style) = if col == 0 {
505 (glyphs.sb_h_arrow_back, ctrl_style)
506 } else if col == s {
507 (glyphs.sb_h_arrow_fwd, ctrl_style)
508 } else if no_range {
509 (glyphs.sb_page_no_range, page_style)
510 } else if col == pos {
511 (glyphs.sb_thumb, ctrl_style)
512 } else {
513 (glyphs.sb_page, page_style)
514 };
515 ctx.put_char(col, 0, ch, style);
516 }
517 }
518 }
519
520 /// Keyboard and mouse input.
521 ///
522 /// Handles:
523 /// - Mouse wheel: adjust by `3 * arrow_step`, broadcasting clicked then
524 /// changed (via `set_value`).
525 /// - Mouse down: classify the part hit. Arrow parts do a first step and arm
526 /// an auto-repeat track (`TrackMask { mouse_auto: true }`). The
527 /// indicator/default branch does a first thumb-jump and arms a move track
528 /// (`TrackMask { mouse_move: true }`). Broadcasts clicked.
529 /// - Tracked auto tick: re-derive the part; step only if it still matches the
530 /// originally-clicked part (the arrow/page hold loop body).
531 /// - Tracked move: recompute the thumb value from the cursor position (the
532 /// drag loop body).
533 /// - Tracked mouse up: clear the tracking flag.
534 /// - Key down (when visible + focused): arrow/page/home/end keys; broadcasts
535 /// clicked then adjusts the value.
536 fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
537 let visible = self.state.state.visible;
538
539 match *ev {
540 // ------------------------------------------------------------------
541 // Mouse wheel (evMouseWheel) — visible check matches C++ `sfVisible`
542 // ------------------------------------------------------------------
543 Event::MouseWheel(me) if visible => {
544 let step = if self.vertical {
545 match me.wheel {
546 MouseWheel::Up => -self.arrow_step,
547 MouseWheel::Down => self.arrow_step,
548 _ => 0,
549 }
550 } else {
551 match me.wheel {
552 MouseWheel::Left => -self.arrow_step,
553 MouseWheel::Right => self.arrow_step,
554 _ => 0,
555 }
556 };
557 if step != 0 {
558 ctx.broadcast(Command::SCROLL_BAR_CLICKED, self.state().id());
559 self.set_value(self.value + 3 * step, ctx);
560 ev.clear();
561 }
562 }
563
564 // ------------------------------------------------------------------
565 // Mouse down (evMouseDown) — tscrlbar.cpp:173-210
566 // ------------------------------------------------------------------
567 Event::MouseDown(me) => {
568 ctx.broadcast(Command::SCROLL_BAR_CLICKED, self.state().id());
569
570 // C++:173-179 — capture mouse, extent, pos, size before the
571 // loop (these become `s` / `p` / `extent` globals in C++).
572 let local = me.position; // already in view-local coords
573 let mark = if self.vertical { local.y } else { local.x };
574 let pos = self.get_pos(); // C++ `p = getPos()`
575 let s = self.get_size() - 1; // C++ `s = getSize() - 1`
576
577 // C++:176-178: `extent = getExtent(); extent.grow(1, 1);`
578 // getPartCode returns -1 (None here) when outside this expanded extent.
579 let extent = self.state.get_extent();
580 let expanded = Rect::new(
581 extent.a.x - 1,
582 extent.a.y - 1,
583 extent.b.x + 1,
584 extent.b.y + 1,
585 );
586 // C++:180 — `clickPart = getPartCode()`
587 let click_part = if expanded.contains(local) {
588 self.get_part_code(mark, pos, s)
589 } else {
590 None // C++ getPartCode() == -1 → falls into default: (thumb-jump)
591 };
592
593 match click_part {
594 // Arrow branch: do the first step (the loop body runs once
595 // before the first wait), then arm auto-repeat.
596 Some(
597 p @ (Part::LeftArrow | Part::RightArrow | Part::UpArrow | Part::DownArrow),
598 ) => {
599 // C++:188-190: `mouse = makeLocal(…); if getPartCode()==clickPart
600 // setValue(value + scrollStep(clickPart))`.
601 // First iteration: the click position IS the arrow, so the check
602 // always passes on the first iteration.
603 self.set_value(
604 self.value + p.scroll_step(self.arrow_step, self.page_step),
605 ctx,
606 );
607 // Enter the loop: arm auto-repeat. The C++ loop re-classifies
608 // the part under the cursor on each `evMouseAuto` tick.
609 if let Some(id) = self.state.id() {
610 self.tracking = true;
611 self.tracked_part = Some(p);
612 ctx.start_mouse_track(
613 id,
614 self.abs_origin,
615 TrackMask {
616 mouse_auto: true,
617 ..Default::default()
618 },
619 );
620 }
621 }
622 // C++:193-207 — default branch (page, indicator, out-of-extent):
623 // move the thumb to the cursor position. First iteration of the
624 // `evMouseMove` drag loop.
625 _ => {
626 // C++:195-205: `i = clamp(mouse.y or .x, 1, s-1);
627 // if s>2: setValue(((p-1)*(max-min) + ((s-2)>>1)) / (s-2) + min)`
628 let i = mark.max(1).min(s - 1);
629 if s > 2 {
630 let new_val = (i64::from(i - 1)
631 * i64::from(self.max_value - self.min_value)
632 + i64::from((s - 2) >> 1))
633 / i64::from(s - 2)
634 + i64::from(self.min_value);
635 self.set_value(new_val as i32, ctx);
636 }
637 // Enter the drag loop: arm move-tracking.
638 if let Some(id) = self.state.id() {
639 self.tracking = true;
640 self.tracked_part = None; // thumb branch: no part to re-match
641 ctx.start_mouse_track(
642 id,
643 self.abs_origin,
644 TrackMask {
645 mouse_move: true,
646 ..Default::default()
647 },
648 );
649 }
650 }
651 }
652
653 // Always consume the event after a mouse-down.
654 ev.clear();
655 }
656
657 // ------------------------------------------------------------------
658 // Mouse auto (evMouseAuto) — the arrow hold-loop body. Guarded by
659 // `tracking` AND `tracked_part.is_some()`: there are two SEPARATE
660 // masked loops (auto-only for arrows, move-only for the thumb), so an
661 // auto event during a thumb track must fall through, not hit this arm.
662 // ------------------------------------------------------------------
663 Event::MouseAuto(me) if self.tracking && self.tracked_part.is_some() => {
664 // Position is already bar-local (the capture localized it via abs_origin).
665 let local = me.position;
666 let mark = if self.vertical { local.y } else { local.x };
667 let pos = self.get_pos(); // re-derive the thumb position
668 let s = self.get_size() - 1;
669 // Re-classify under the current cursor and step only if the mouse
670 // is still over the originally-clicked arrow part.
671 let cur_part = self.get_part_code(mark, pos, s);
672 if cur_part == self.tracked_part
673 && let Some(p) = self.tracked_part
674 {
675 // C++:190: `setValue(value + scrollStep(clickPart))`
676 self.set_value(
677 self.value + p.scroll_step(self.arrow_step, self.page_step),
678 ctx,
679 );
680 }
681 ev.clear();
682 }
683
684 // ------------------------------------------------------------------
685 // Mouse move (evMouseMove) — the thumb drag-loop body,
686 // tscrlbar.cpp:195-205. Guarded by `tracking` AND
687 // `tracked_part.is_none()`: mirrors the C++'s two separate masked
688 // loops — a move event during an arrow track must fall through.
689 // ------------------------------------------------------------------
690 Event::MouseMove(me) if self.tracking && self.tracked_part.is_none() => {
691 // C++:195: `mouse = makeLocal(event.mouse.where)` — position is
692 // already bar-local (the capture localized it via abs_origin).
693 let local = me.position;
694 let mark = if self.vertical { local.y } else { local.x };
695 let s = self.get_size() - 1;
696 // C++:197-201: `i = mouse.y or .x; clamp to [1, s-1]`
697 let i = mark.max(1).min(s - 1);
698 // C++:203-204: `if s > 2: setValue(((p-1)*(max-min)+…)/… + min)`
699 if s > 2 {
700 let new_val = (i64::from(i - 1) * i64::from(self.max_value - self.min_value)
701 + i64::from((s - 2) >> 1))
702 / i64::from(s - 2)
703 + i64::from(self.min_value);
704 self.set_value(new_val as i32, ctx);
705 }
706 ev.clear();
707 }
708
709 // ------------------------------------------------------------------
710 // Mouse up — post-loop code (both branches). Guarded by `tracking`
711 // (MouseUp is not mask-gated in Group::wants, so a stray up must
712 // fall through). tscrlbar.cpp:191 / :206 — loop exits on MouseUp.
713 // ------------------------------------------------------------------
714 Event::MouseUp(_) if self.tracking => {
715 self.tracking = false;
716 self.tracked_part = None;
717 ev.clear();
718 }
719
720 // ------------------------------------------------------------------
721 // Key down (evKeyDown) — only when visible (sfVisible check)
722 // ------------------------------------------------------------------
723 Event::KeyDown(ke) if visible => {
724 // `switch (ctrlToArrow(event.keyDown.keyCode))` — WordStar
725 // Ctrl-letter nav aliases (Ctrl+S→Left, Ctrl+E→Up, …). The
726 // helper only maps Ctrl+letter (modifiers cleared on a match);
727 // Ctrl+arrow combos pass through unchanged, so the `ctrl`
728 // reads below still see them.
729 let ke = ctrl_to_arrow(ke);
730 let key = ke.key;
731 let ctrl = ke.modifiers.ctrl;
732
733 // Map key to a part code (or a direct target value).
734 // Horizontal bar (size.y==1) uses Left/Right/Ctrl+Left/Ctrl+Right,
735 // and Home/End jump to min/max.
736 // Vertical bar uses Up/Down/PgUp/PgDn and
737 // Ctrl+PgUp/PgDn jump to min/max.
738 let action: Option<PartOrValue> = if !self.vertical {
739 // Horizontal scrollbar key mapping (faithful to C++ size.y==1 branch).
740 match (key, ctrl) {
741 (Key::Left, false) => Some(PartOrValue::P(Part::LeftArrow)),
742 (Key::Right, false) => Some(PartOrValue::P(Part::RightArrow)),
743 (Key::Left, true) => Some(PartOrValue::P(Part::PageLeft)),
744 (Key::Right, true) => Some(PartOrValue::P(Part::PageRight)),
745 (Key::Up, true) => Some(PartOrValue::P(Part::PageUp)),
746 (Key::Down, true) => Some(PartOrValue::P(Part::PageDown)),
747 (Key::Home, _) => Some(PartOrValue::V(self.min_value)),
748 (Key::End, _) => Some(PartOrValue::V(self.max_value)),
749 _ => None,
750 }
751 } else {
752 // Vertical scrollbar key mapping (faithful to C++ size.y!=1 branch).
753 match (key, ctrl) {
754 (Key::Up, false) => Some(PartOrValue::P(Part::UpArrow)),
755 (Key::Down, false) => Some(PartOrValue::P(Part::DownArrow)),
756 (Key::PageUp, false) => Some(PartOrValue::P(Part::PageUp)),
757 (Key::PageDown, false) => Some(PartOrValue::P(Part::PageDown)),
758 (Key::PageUp, true) => Some(PartOrValue::V(self.min_value)),
759 (Key::PageDown, true) => Some(PartOrValue::V(self.max_value)),
760 _ => None,
761 }
762 };
763
764 if let Some(act) = action {
765 ctx.broadcast(Command::SCROLL_BAR_CLICKED, self.state().id());
766 let new_val = match act {
767 PartOrValue::P(part) => {
768 self.value + part.scroll_step(self.arrow_step, self.page_step)
769 }
770 PartOrValue::V(v) => v,
771 };
772 self.set_value(new_val, ctx);
773 ev.clear();
774 }
775 }
776
777 _ => {}
778 }
779 }
780}
781
782/// Helper: a key event action is either a part (relative step) or a direct value.
783enum PartOrValue {
784 P(Part),
785 V(i32),
786}
787
788// ---------------------------------------------------------------------------
789// Tests
790// ---------------------------------------------------------------------------
791
792#[cfg(test)]
793mod tests {
794 use super::*;
795 use crate::backend::{HeadlessBackend, Renderer};
796 use crate::event::{KeyEvent, KeyModifiers, MouseButtons, MouseEvent, MouseEventFlags};
797 use crate::screen::Buffer;
798 use crate::theme::Theme;
799 use crate::view::Point;
800 use std::collections::VecDeque;
801
802 // -- Helper to build a Context with local backing storage ----------------
803
804 fn make_ctx<'a>(
805 out: &'a mut VecDeque<Event>,
806 timers: &'a mut crate::timer::TimerQueue,
807 deferred: &'a mut Vec<crate::view::Deferred>,
808 ) -> Context<'a> {
809 Context::new(out, timers, 0, deferred)
810 }
811
812 // -- Helpers for building key events -------------------------------------
813
814 fn key_ev(key: Key) -> Event {
815 Event::KeyDown(KeyEvent::from(key))
816 }
817
818 fn ctrl_key_ev(key: Key) -> Event {
819 Event::KeyDown(KeyEvent::new(
820 key,
821 KeyModifiers {
822 ctrl: true,
823 ..Default::default()
824 },
825 ))
826 }
827
828 fn mouse_down_at(x: i32, y: i32) -> Event {
829 Event::MouseDown(MouseEvent {
830 position: Point::new(x, y),
831 buttons: MouseButtons {
832 left: true,
833 ..Default::default()
834 },
835 flags: MouseEventFlags::default(),
836 wheel: MouseWheel::None,
837 modifiers: KeyModifiers::default(),
838 })
839 }
840
841 fn mouse_auto_at(x: i32, y: i32) -> Event {
842 Event::MouseAuto(MouseEvent {
843 position: Point::new(x, y),
844 buttons: MouseButtons {
845 left: true,
846 ..Default::default()
847 },
848 ..Default::default()
849 })
850 }
851
852 fn mouse_move_at(x: i32, y: i32) -> Event {
853 Event::MouseMove(MouseEvent {
854 position: Point::new(x, y),
855 buttons: MouseButtons {
856 left: true,
857 ..Default::default()
858 },
859 ..Default::default()
860 })
861 }
862
863 fn mouse_up_at(x: i32, y: i32) -> Event {
864 Event::MouseUp(MouseEvent {
865 position: Point::new(x, y),
866 ..Default::default()
867 })
868 }
869
870 /// Stamp a fresh ViewId onto a scrollbar (simulating Group::insert).
871 fn stamp_id(sb: &mut ScrollBar) -> crate::view::ViewId {
872 let id = crate::view::ViewId::next();
873 sb.state.id = Some(id);
874 id
875 }
876
877 // -----------------------------------------------------------------------
878 // set_value clamps and broadcasts
879 // -----------------------------------------------------------------------
880
881 #[test]
882 fn set_value_clamps_to_range() {
883 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
884 let mut out = VecDeque::new();
885 let mut timers = crate::timer::TimerQueue::new();
886 let mut deferred: Vec<crate::view::Deferred> = vec![];
887 {
888 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
889 sb.set_params(5, 0, 20, 1, 1, &mut ctx);
890 }
891 assert_eq!(sb.value, 5);
892 assert_eq!(sb.min_value, 0);
893 assert_eq!(sb.max_value, 20);
894
895 // Clamp above max.
896 {
897 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
898 sb.set_value(100, &mut ctx);
899 }
900 assert_eq!(sb.value, 20);
901
902 // Clamp below min.
903 {
904 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
905 sb.set_value(-5, &mut ctx);
906 }
907 assert_eq!(sb.value, 0);
908 }
909
910 #[test]
911 fn set_value_broadcasts_changed_on_value_change() {
912 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
913 let mut out = VecDeque::new();
914 let mut timers = crate::timer::TimerQueue::new();
915 let mut deferred: Vec<crate::view::Deferred> = vec![];
916 {
917 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
918 sb.set_params(0, 0, 20, 1, 1, &mut ctx);
919 }
920 // No broadcast yet — value didn't change (was 0, still 0).
921 assert_eq!(out.len(), 0);
922
923 {
924 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
925 sb.set_value(5, &mut ctx);
926 }
927 assert_eq!(out.len(), 1);
928 assert!(matches!(
929 out[0],
930 Event::Broadcast { command, .. } if command == Command::SCROLL_BAR_CHANGED
931 ));
932 }
933
934 #[test]
935 fn broadcast_source_is_the_inserted_scrollbars_id() {
936 // The `cmScrollBarChanged` broadcast must carry `source == the emitting
937 // scrollbar's id` (the C++ `this`), not `None`. The id is
938 // stamped at `Group::insert`, so the scrollbar must be inserted first.
939 use crate::view::Group;
940
941 let mut out = VecDeque::new();
942 let mut timers = crate::timer::TimerQueue::new();
943 let mut deferred: Vec<crate::view::Deferred> = vec![];
944
945 // Build a scrollbar with a real range, then insert it into a group so it
946 // is assigned a process-global id.
947 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
948 {
949 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
950 sb.set_params(5, 0, 20, 1, 1, &mut ctx);
951 }
952 let mut group = Group::new(Rect::new(0, 0, 20, 10));
953 let id = group.insert(Box::new(sb));
954 out.clear();
955
956 // Drive a value change on the inserted scrollbar (a vertical bar accepts
957 // Key::Down) and capture its broadcast. We send the key straight to the
958 // resolved child via the `View` trait — we only care that the *emitter*
959 // threads its own stamped id, not about group focus routing.
960 {
961 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
962 let child = group.find_mut(id).expect("scrollbar resolves by id");
963 let mut ev = key_ev(Key::Down);
964 child.handle_event(&mut ev, &mut ctx);
965 }
966
967 // The queued CHANGED broadcast must name the scrollbar as its source.
968 assert!(
969 out.iter().any(|e| matches!(
970 e,
971 Event::Broadcast { command, source }
972 if *command == Command::SCROLL_BAR_CHANGED && *source == Some(id)
973 )),
974 "scroll-bar broadcast must carry source == the emitting scrollbar's id, not None"
975 );
976 }
977
978 #[test]
979 fn set_value_no_broadcast_when_value_unchanged() {
980 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
981 let mut out = VecDeque::new();
982 let mut timers = crate::timer::TimerQueue::new();
983 let mut deferred: Vec<crate::view::Deferred> = vec![];
984 {
985 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
986 sb.set_params(5, 0, 20, 1, 1, &mut ctx);
987 }
988 out.clear();
989 // Setting same value should not broadcast.
990 {
991 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
992 sb.set_value(5, &mut ctx);
993 }
994 assert_eq!(out.len(), 0);
995 }
996
997 // -----------------------------------------------------------------------
998 // set_params / set_range / set_step
999 // -----------------------------------------------------------------------
1000
1001 #[test]
1002 fn set_range_clamps_value_if_out_of_new_range() {
1003 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1004 let mut out = VecDeque::new();
1005 let mut timers = crate::timer::TimerQueue::new();
1006 let mut deferred: Vec<crate::view::Deferred> = vec![];
1007 {
1008 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1009 sb.set_params(15, 0, 20, 1, 1, &mut ctx);
1010 }
1011 assert_eq!(sb.value, 15);
1012 out.clear();
1013 {
1014 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1015 sb.set_range(0, 10, &mut ctx);
1016 }
1017 assert_eq!(sb.value, 10, "value clamped to new max");
1018 assert_eq!(out.len(), 1);
1019 assert!(matches!(
1020 out[0],
1021 Event::Broadcast { command, .. } if command == Command::SCROLL_BAR_CHANGED
1022 ));
1023 }
1024
1025 #[test]
1026 fn set_step_updates_steps_without_broadcast() {
1027 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1028 let mut out = VecDeque::new();
1029 let mut timers = crate::timer::TimerQueue::new();
1030 let mut deferred: Vec<crate::view::Deferred> = vec![];
1031 {
1032 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1033 sb.set_step(5, 2, &mut ctx);
1034 }
1035 assert_eq!(sb.page_step, 5);
1036 assert_eq!(sb.arrow_step, 2);
1037 assert_eq!(out.len(), 0);
1038 }
1039
1040 // -----------------------------------------------------------------------
1041 // with_keyboard builder
1042 // -----------------------------------------------------------------------
1043
1044 #[test]
1045 fn with_keyboard_sets_post_process() {
1046 let r = Rect::new(0, 0, 1, 10);
1047 // A plain new() bar must NOT have post_process (the default is false;
1048 // no options are set).
1049 let sb_plain = ScrollBar::new(r);
1050 assert!(
1051 !sb_plain.state.options.post_process,
1052 "plain ScrollBar::new must NOT have post_process"
1053 );
1054 // with_keyboard() sets it.
1055 let sb_kb = ScrollBar::new(r).with_keyboard();
1056 assert!(
1057 sb_kb.state.options.post_process,
1058 "with_keyboard() must set post_process (ofPostProcess / sbHandleKeyboard)"
1059 );
1060 }
1061
1062 // -----------------------------------------------------------------------
1063 // get_pos / get_size math
1064 // -----------------------------------------------------------------------
1065
1066 #[test]
1067 fn get_size_minimum_is_3() {
1068 let sb = ScrollBar::new(Rect::new(0, 0, 1, 2)); // height 2 < 3
1069 assert_eq!(sb.get_size(), 3);
1070 let sb2 = ScrollBar::new(Rect::new(0, 0, 1, 10));
1071 assert_eq!(sb2.get_size(), 10);
1072 }
1073
1074 #[test]
1075 fn get_pos_returns_1_when_range_is_zero() {
1076 let sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1077 // min == max == 0, value == 0
1078 assert_eq!(sb.get_pos(), 1);
1079 }
1080
1081 #[test]
1082 fn get_pos_at_max_is_size_minus_2() {
1083 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1084 let mut out = VecDeque::new();
1085 let mut timers = crate::timer::TimerQueue::new();
1086 let mut deferred: Vec<crate::view::Deferred> = vec![];
1087 {
1088 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1089 sb.set_params(100, 0, 100, 1, 1, &mut ctx);
1090 }
1091 // getPos: ((100-0)*(10-3) + 50) / 100 + 1 = (700+50)/100+1 = 7+1 = 8
1092 // size-1 = 9, size-2 = 8 — thumb at position 8.
1093 assert_eq!(sb.get_pos(), sb.get_size() - 2);
1094 }
1095
1096 #[test]
1097 fn get_pos_midpoint() {
1098 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1099 let mut out = VecDeque::new();
1100 let mut timers = crate::timer::TimerQueue::new();
1101 let mut deferred: Vec<crate::view::Deferred> = vec![];
1102 {
1103 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1104 sb.set_params(50, 0, 100, 1, 1, &mut ctx);
1105 }
1106 // getPos: (50*(10-3) + 50) / 100 + 1 = (350+50)/100 + 1 = 4+1 = 5
1107 assert_eq!(sb.get_pos(), 5);
1108 }
1109
1110 // -----------------------------------------------------------------------
1111 // Key event scrolls one step
1112 // -----------------------------------------------------------------------
1113
1114 #[test]
1115 fn key_up_scrolls_vertical_bar_by_arrow_step() {
1116 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1117 let mut out = VecDeque::new();
1118 let mut timers = crate::timer::TimerQueue::new();
1119 let mut deferred: Vec<crate::view::Deferred> = vec![];
1120 {
1121 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1122 sb.set_params(10, 0, 100, 5, 1, &mut ctx);
1123 }
1124 out.clear();
1125
1126 let mut ev = key_ev(Key::Up);
1127 {
1128 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1129 sb.handle_event(&mut ev, &mut ctx);
1130 }
1131 assert!(ev.is_nothing(), "event consumed");
1132 assert_eq!(sb.value, 9, "arrow_step 1 → value decremented by 1");
1133 // Should have broadcast CLICKED then CHANGED.
1134 assert!(out.iter().any(|e| matches!(
1135 e,
1136 Event::Broadcast { command, .. } if *command == Command::SCROLL_BAR_CLICKED
1137 )));
1138 assert!(out.iter().any(|e| matches!(
1139 e,
1140 Event::Broadcast { command, .. } if *command == Command::SCROLL_BAR_CHANGED
1141 )));
1142 }
1143
1144 #[test]
1145 fn key_page_down_scrolls_by_page_step() {
1146 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1147 let mut out = VecDeque::new();
1148 let mut timers = crate::timer::TimerQueue::new();
1149 let mut deferred: Vec<crate::view::Deferred> = vec![];
1150 {
1151 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1152 sb.set_params(10, 0, 100, 5, 1, &mut ctx);
1153 }
1154 out.clear();
1155
1156 let mut ev = key_ev(Key::PageDown);
1157 {
1158 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1159 sb.handle_event(&mut ev, &mut ctx);
1160 }
1161 assert!(ev.is_nothing());
1162 assert_eq!(sb.value, 15, "page_step 5 → value incremented by 5");
1163 }
1164
1165 #[test]
1166 fn key_home_jumps_to_min() {
1167 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1168 let mut out = VecDeque::new();
1169 let mut timers = crate::timer::TimerQueue::new();
1170 let mut deferred: Vec<crate::view::Deferred> = vec![];
1171 {
1172 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1173 sb.set_params(50, 5, 100, 5, 1, &mut ctx);
1174 }
1175 out.clear();
1176
1177 // The C++ uses Home/End for horizontal bars (size.y==1) and
1178 // Ctrl+PgUp/PgDn for vertical bars:
1179 // - size.y == 1 (horizontal): kbHome → i = minVal, kbEnd → i = maxVal
1180 // - vertical (size.x==1): kbCtrlPgUp → i = minVal, kbCtrlPgDn → i = maxVal
1181 // Our implementation is faithful to this. Verify Ctrl+PageUp → minVal for vertical.
1182 let mut ev = ctrl_key_ev(Key::PageUp);
1183 {
1184 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1185 sb.handle_event(&mut ev, &mut ctx);
1186 }
1187 assert!(ev.is_nothing());
1188 assert_eq!(sb.value, 5, "ctrl+pageup → min_value");
1189 }
1190
1191 #[test]
1192 fn horizontal_key_right_scrolls() {
1193 let mut sb = ScrollBar::new(Rect::new(0, 0, 20, 1)); // horizontal
1194 assert!(!sb.is_vertical());
1195 let mut out = VecDeque::new();
1196 let mut timers = crate::timer::TimerQueue::new();
1197 let mut deferred: Vec<crate::view::Deferred> = vec![];
1198 {
1199 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1200 sb.set_params(10, 0, 100, 5, 2, &mut ctx);
1201 }
1202 out.clear();
1203
1204 let mut ev = key_ev(Key::Right);
1205 {
1206 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1207 sb.handle_event(&mut ev, &mut ctx);
1208 }
1209 assert!(ev.is_nothing());
1210 assert_eq!(sb.value, 12, "arrow_step 2 → value incremented by 2");
1211 }
1212
1213 /// `ctrlToArrow`: Ctrl+S is the WordStar alias for Left (`tscrlbar.cpp`
1214 /// wraps the keyCode through `ctrlToArrow` before the switch).
1215 #[test]
1216 fn ctrl_s_aliases_left_on_horizontal_bar() {
1217 let mut sb = ScrollBar::new(Rect::new(0, 0, 20, 1)); // horizontal
1218 let mut out = VecDeque::new();
1219 let mut timers = crate::timer::TimerQueue::new();
1220 let mut deferred: Vec<crate::view::Deferred> = vec![];
1221 {
1222 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1223 sb.set_params(10, 0, 100, 5, 2, &mut ctx);
1224 }
1225 out.clear();
1226
1227 // Ctrl+S → Left (the helper clears the ctrl modifier on the match,
1228 // so this is LeftArrow, not Ctrl+Left = PageLeft).
1229 let mut ev = ctrl_key_ev(Key::Char('s'));
1230 {
1231 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1232 sb.handle_event(&mut ev, &mut ctx);
1233 }
1234 assert!(ev.is_nothing(), "Ctrl+S is consumed like Left");
1235 assert_eq!(sb.value, 8, "arrow_step 2 → value decremented by 2");
1236 }
1237
1238 // -----------------------------------------------------------------------
1239 // Mouse click on arrow cell scrolls one step
1240 // -----------------------------------------------------------------------
1241
1242 #[test]
1243 fn mouse_click_on_up_arrow_decrements() {
1244 // Vertical bar: height 10, value at 10.
1245 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1246 let mut out = VecDeque::new();
1247 let mut timers = crate::timer::TimerQueue::new();
1248 let mut deferred: Vec<crate::view::Deferred> = vec![];
1249 {
1250 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1251 sb.set_params(10, 0, 100, 5, 1, &mut ctx);
1252 }
1253 out.clear();
1254
1255 // Click at (0, 0) = the up-arrow cell.
1256 let mut ev = mouse_down_at(0, 0);
1257 {
1258 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1259 sb.handle_event(&mut ev, &mut ctx);
1260 }
1261 assert!(ev.is_nothing());
1262 assert_eq!(sb.value, 9);
1263 assert!(out.iter().any(|e| matches!(
1264 e,
1265 Event::Broadcast { command, .. } if *command == Command::SCROLL_BAR_CLICKED
1266 )));
1267 }
1268
1269 #[test]
1270 fn mouse_click_on_down_arrow_increments() {
1271 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1272 let mut out = VecDeque::new();
1273 let mut timers = crate::timer::TimerQueue::new();
1274 let mut deferred: Vec<crate::view::Deferred> = vec![];
1275 {
1276 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1277 sb.set_params(10, 0, 100, 5, 1, &mut ctx);
1278 }
1279 out.clear();
1280
1281 // Click at (0, 9) = the down-arrow cell (s = getSize()-1 = 9).
1282 let mut ev = mouse_down_at(0, 9);
1283 {
1284 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1285 sb.handle_event(&mut ev, &mut ctx);
1286 }
1287 assert!(ev.is_nothing());
1288 assert_eq!(sb.value, 11);
1289 }
1290
1291 /// A mouse-down in the page/trough area must produce a **thumb-jump** to
1292 /// the clicked position, NOT a page-step.
1293 ///
1294 /// Setup: vertical 1×10, value=50 of [0,100], page_step=5.
1295 /// get_pos() = 5, s = 9.
1296 /// Click y=2 → PageUp region.
1297 /// Thumb-jump formula: i=2, ((2-1)*100 + (7>>1)) / 7 + 0 = 103/7 = 14.
1298 /// Page-step would give 50-5 = 45.
1299 /// Arrow-step would give 50-1 = 49.
1300 #[test]
1301 fn mouse_click_on_page_area_thumb_jumps_not_page_steps() {
1302 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1303 let mut out = VecDeque::new();
1304 let mut timers = crate::timer::TimerQueue::new();
1305 let mut deferred: Vec<crate::view::Deferred> = vec![];
1306 {
1307 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1308 // value=50, min=0, max=100, page_step=5, arrow_step=1
1309 sb.set_params(50, 0, 100, 5, 1, &mut ctx);
1310 }
1311 out.clear();
1312
1313 // get_pos() = ((50-0)*(10-3) + 50) / 100 + 1 = (350+50)/100 + 1 = 5
1314 // s = get_size()-1 = 9
1315 // Click y=2: this is in the PageUp region (1 <= 2 < 5 = pos).
1316 let mut ev = mouse_down_at(0, 2);
1317 {
1318 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1319 sb.handle_event(&mut ev, &mut ctx);
1320 }
1321 assert!(ev.is_nothing(), "event consumed");
1322 // Thumb-jump: i=2, ((2-1)*100 + ((9-2)>>1)) / (9-2) + 0
1323 // = (100 + 3) / 7 + 0 = 103/7 = 14 (integer division)
1324 assert_eq!(
1325 sb.value, 14,
1326 "page-area click must thumb-jump (not page-step: 45, not arrow-step: 49)"
1327 );
1328 // Must broadcast CLICKED (not just CHANGED).
1329 assert!(
1330 out.iter().any(|e| matches!(
1331 e,
1332 Event::Broadcast { command, .. } if *command == Command::SCROLL_BAR_CLICKED
1333 )),
1334 "SCROLL_BAR_CLICKED must be broadcast on mouse-down"
1335 );
1336 }
1337
1338 // -----------------------------------------------------------------------
1339 // Snapshot tests
1340 // -----------------------------------------------------------------------
1341
1342 #[test]
1343 fn snapshot_vertical_scrollbar_at_midpoint() {
1344 let theme = Theme::classic_blue();
1345
1346 // Vertical bar: 1×10, value at 50 of 100.
1347 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1348 let mut out = VecDeque::new();
1349 let mut timers = crate::timer::TimerQueue::new();
1350 let mut deferred: Vec<crate::view::Deferred> = vec![];
1351 {
1352 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1353 sb.set_params(50, 0, 100, 5, 1, &mut ctx);
1354 }
1355
1356 let (backend, screen) = HeadlessBackend::new(1, 10);
1357 let mut r = Renderer::new(Box::new(backend));
1358 r.render(|buf: &mut Buffer| {
1359 let bounds = sb.state.get_bounds();
1360 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
1361 sb.draw(&mut dc);
1362 });
1363 insta::assert_snapshot!(screen.snapshot());
1364 }
1365
1366 #[test]
1367 fn snapshot_horizontal_scrollbar_at_start() {
1368 let theme = Theme::classic_blue();
1369
1370 // Horizontal bar: 20×1, value at 0 of 100.
1371 let mut sb = ScrollBar::new(Rect::new(0, 0, 20, 1));
1372 let mut out = VecDeque::new();
1373 let mut timers = crate::timer::TimerQueue::new();
1374 let mut deferred: Vec<crate::view::Deferred> = vec![];
1375 {
1376 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1377 sb.set_params(0, 0, 100, 5, 1, &mut ctx);
1378 }
1379
1380 let (backend, screen) = HeadlessBackend::new(20, 1);
1381 let mut r = Renderer::new(Box::new(backend));
1382 r.render(|buf: &mut Buffer| {
1383 let bounds = sb.state.get_bounds();
1384 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
1385 sb.draw(&mut dc);
1386 });
1387 insta::assert_snapshot!(screen.snapshot());
1388 }
1389
1390 #[test]
1391 fn snapshot_vertical_scrollbar_no_range() {
1392 let theme = Theme::classic_blue();
1393
1394 // Vertical bar with range == 0 (all trough with sb_page_no_range).
1395 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 6));
1396
1397 let (backend, screen) = HeadlessBackend::new(1, 6);
1398 let mut r = Renderer::new(Box::new(backend));
1399 r.render(|buf: &mut Buffer| {
1400 let bounds = sb.state.get_bounds();
1401 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
1402 sb.draw(&mut dc);
1403 });
1404 insta::assert_snapshot!(screen.snapshot());
1405 }
1406
1407 // -----------------------------------------------------------------------
1408 // mouse-track — arrow hold-repeat (evMouseAuto)
1409 // -----------------------------------------------------------------------
1410
1411 /// Mouse-down on the up-arrow does the first step AND arms tracking
1412 /// (`PushCapture` deferred, `tracking == true`, `tracked_part == UpArrow`).
1413 /// The single-shot first-step behavior is unchanged.
1414 #[test]
1415 fn track_arrow_mouse_down_arms_capture() {
1416 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1417 let _id = stamp_id(&mut sb);
1418 let mut out = VecDeque::new();
1419 let mut timers = crate::timer::TimerQueue::new();
1420 let mut deferred: Vec<crate::view::Deferred> = vec![];
1421 {
1422 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1423 sb.set_params(10, 0, 100, 5, 1, &mut ctx);
1424 }
1425 out.clear();
1426 deferred.clear();
1427
1428 // Click at (0, 0) = the up-arrow cell.
1429 let mut ev = mouse_down_at(0, 0);
1430 {
1431 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1432 sb.handle_event(&mut ev, &mut ctx);
1433 }
1434 assert!(ev.is_nothing(), "mouse-down consumed");
1435 assert_eq!(sb.value, 9, "first step applied (10 - arStep=1 = 9)");
1436 assert!(sb.tracking, "tracking flag set");
1437 // A PushCapture must have been deferred.
1438 assert!(
1439 deferred
1440 .iter()
1441 .any(|d| matches!(d, crate::view::Deferred::PushCapture(_))),
1442 "PushCapture deferred for the arrow hold-track"
1443 );
1444 }
1445
1446 /// `MouseAuto` while tracking on the up-arrow, cursor still over the arrow:
1447 /// value decrements again (the loop body repeats).
1448 #[test]
1449 fn track_arrow_auto_repeats_while_on_same_part() {
1450 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1451 let _id = stamp_id(&mut sb);
1452 let mut out = VecDeque::new();
1453 let mut timers = crate::timer::TimerQueue::new();
1454 let mut deferred: Vec<crate::view::Deferred> = vec![];
1455 {
1456 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1457 sb.set_params(10, 0, 100, 5, 1, &mut ctx);
1458 }
1459 // Arm the track via a MouseDown on the up-arrow.
1460 let mut ev = mouse_down_at(0, 0);
1461 {
1462 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1463 sb.handle_event(&mut ev, &mut ctx);
1464 }
1465 assert_eq!(sb.value, 9);
1466 out.clear();
1467 deferred.clear();
1468
1469 // MouseAuto at (0, 0) — still over the up-arrow → another step.
1470 let mut ev = mouse_auto_at(0, 0);
1471 {
1472 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1473 sb.handle_event(&mut ev, &mut ctx);
1474 }
1475 assert!(ev.is_nothing(), "MouseAuto consumed");
1476 assert_eq!(sb.value, 8, "second step: 9 - 1 = 8");
1477 assert!(sb.tracking, "still tracking after auto");
1478 }
1479
1480 /// `MouseAuto` while tracking on the up-arrow, cursor moved off to the page
1481 /// area: value must NOT change (tscrlbar.cpp:189 `getPartCode() == clickPart`).
1482 #[test]
1483 fn track_arrow_auto_pauses_when_off_part() {
1484 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1485 let _id = stamp_id(&mut sb);
1486 let mut out = VecDeque::new();
1487 let mut timers = crate::timer::TimerQueue::new();
1488 let mut deferred: Vec<crate::view::Deferred> = vec![];
1489 {
1490 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1491 sb.set_params(50, 0, 100, 5, 1, &mut ctx);
1492 }
1493 // Arm the track via a MouseDown on the up-arrow.
1494 let mut ev = mouse_down_at(0, 0);
1495 {
1496 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1497 sb.handle_event(&mut ev, &mut ctx);
1498 }
1499 let value_after_first = sb.value;
1500 out.clear();
1501 deferred.clear();
1502
1503 // MouseAuto at (0, 3) — moved into the page-up region, not the up-arrow.
1504 let mut ev = mouse_auto_at(0, 3);
1505 {
1506 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1507 sb.handle_event(&mut ev, &mut ctx);
1508 }
1509 assert!(ev.is_nothing(), "MouseAuto still consumed (modal hold)");
1510 assert_eq!(
1511 sb.value, value_after_first,
1512 "no step when cursor off the arrow"
1513 );
1514 assert!(sb.tracking, "still tracking");
1515 }
1516
1517 /// `MouseUp` clears the tracking flag (post-loop code, tscrlbar.cpp:191).
1518 #[test]
1519 fn track_arrow_mouse_up_clears_tracking() {
1520 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1521 let _id = stamp_id(&mut sb);
1522 let mut out = VecDeque::new();
1523 let mut timers = crate::timer::TimerQueue::new();
1524 let mut deferred: Vec<crate::view::Deferred> = vec![];
1525 {
1526 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1527 sb.set_params(10, 0, 100, 5, 1, &mut ctx);
1528 }
1529 let mut ev = mouse_down_at(0, 0);
1530 {
1531 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1532 sb.handle_event(&mut ev, &mut ctx);
1533 }
1534 assert!(sb.tracking);
1535
1536 let mut ev = mouse_up_at(0, 0);
1537 {
1538 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1539 sb.handle_event(&mut ev, &mut ctx);
1540 }
1541 assert!(ev.is_nothing(), "MouseUp consumed");
1542 assert!(!sb.tracking, "tracking cleared on MouseUp");
1543 }
1544
1545 /// A stray `MouseUp` (no tracking in flight) must fall through — the guard
1546 /// protects against untracked ups (MouseUp not mask-gated in Group::wants).
1547 #[test]
1548 fn track_stray_mouse_up_falls_through() {
1549 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1550 let _id = stamp_id(&mut sb);
1551 let mut out = VecDeque::new();
1552 let mut timers = crate::timer::TimerQueue::new();
1553 let mut deferred: Vec<crate::view::Deferred> = vec![];
1554 // No tracking armed.
1555 let mut ev = mouse_up_at(0, 0);
1556 {
1557 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1558 sb.handle_event(&mut ev, &mut ctx);
1559 }
1560 assert!(
1561 !ev.is_nothing(),
1562 "stray MouseUp falls through (not consumed)"
1563 );
1564 }
1565
1566 // -----------------------------------------------------------------------
1567 // mouse-track — thumb drag (evMouseMove)
1568 // -----------------------------------------------------------------------
1569
1570 /// Mouse-down in the page/trough area arms a move-track (not auto-track).
1571 #[test]
1572 fn track_thumb_mouse_down_arms_move_capture() {
1573 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1574 let _id = stamp_id(&mut sb);
1575 let mut out = VecDeque::new();
1576 let mut timers = crate::timer::TimerQueue::new();
1577 let mut deferred: Vec<crate::view::Deferred> = vec![];
1578 {
1579 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1580 sb.set_params(50, 0, 100, 5, 1, &mut ctx);
1581 }
1582 deferred.clear();
1583 out.clear();
1584
1585 // Click in the trough (y=3, which is in PageUp for value=50, s=9, pos=5).
1586 let mut ev = mouse_down_at(0, 3);
1587 {
1588 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1589 sb.handle_event(&mut ev, &mut ctx);
1590 }
1591 assert!(ev.is_nothing());
1592 assert!(sb.tracking, "tracking armed for thumb drag");
1593 assert!(
1594 deferred
1595 .iter()
1596 .any(|d| matches!(d, crate::view::Deferred::PushCapture(_))),
1597 "PushCapture deferred for the thumb drag-track"
1598 );
1599 }
1600
1601 /// `MouseMove` while tracking in the trough recomputes the value from cursor
1602 /// position (thumb drag loop body, tscrlbar.cpp:195-205).
1603 #[test]
1604 fn track_thumb_move_updates_value() {
1605 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1606 let _id = stamp_id(&mut sb);
1607 let mut out = VecDeque::new();
1608 let mut timers = crate::timer::TimerQueue::new();
1609 let mut deferred: Vec<crate::view::Deferred> = vec![];
1610 {
1611 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1612 sb.set_params(50, 0, 100, 5, 1, &mut ctx);
1613 }
1614 // Arm the drag-track via a MouseDown in the trough.
1615 let mut ev = mouse_down_at(0, 3);
1616 {
1617 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1618 sb.handle_event(&mut ev, &mut ctx);
1619 }
1620 let value_after_down = sb.value;
1621 out.clear();
1622 deferred.clear();
1623
1624 // MouseMove to y=7 (near the bottom): value should jump higher.
1625 // Formula: i=7, ((7-1)*100 + ((9-2)>>1)) / (9-2) + 0 = (600+3)/7 = 86.
1626 let mut ev = mouse_move_at(0, 7);
1627 {
1628 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1629 sb.handle_event(&mut ev, &mut ctx);
1630 }
1631 assert!(ev.is_nothing(), "tracked MouseMove consumed");
1632 assert!(sb.tracking, "still tracking after move");
1633 assert_ne!(sb.value, value_after_down, "value changed on move");
1634 // The exact value is (6*100+3)/7 = 603/7 = 86.
1635 assert_eq!(sb.value, 86);
1636 }
1637
1638 /// The two track kinds are discriminated (two SEPARATE masked tracks): a
1639 /// `MouseAuto` during a THUMB track and a `MouseMove` during an ARROW track
1640 /// must both fall through unconsumed — they belong to the other track's mask,
1641 /// and only the capture's mask filtering makes them unreachable in normal flow.
1642 #[test]
1643 fn track_wrong_event_kind_falls_through() {
1644 let mut out = VecDeque::new();
1645 let mut timers = crate::timer::TimerQueue::new();
1646 let mut deferred: Vec<crate::view::Deferred> = vec![];
1647
1648 // -- Thumb track (tracked_part == None): MouseAuto must fall through.
1649 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1650 let _id = stamp_id(&mut sb);
1651 {
1652 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1653 sb.set_params(50, 0, 100, 5, 1, &mut ctx);
1654 }
1655 let mut ev = mouse_down_at(0, 3); // trough → thumb-drag track
1656 {
1657 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1658 sb.handle_event(&mut ev, &mut ctx);
1659 }
1660 assert!(sb.tracking && sb.tracked_part.is_none());
1661 let value_before = sb.value;
1662
1663 let mut ev = mouse_auto_at(0, 0);
1664 {
1665 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1666 sb.handle_event(&mut ev, &mut ctx);
1667 }
1668 assert!(
1669 !ev.is_nothing(),
1670 "MouseAuto during a thumb track falls through unconsumed"
1671 );
1672 assert_eq!(sb.value, value_before, "…and changes nothing");
1673
1674 // -- Arrow track (tracked_part == Some): MouseMove must fall through.
1675 let mut sb = ScrollBar::new(Rect::new(0, 0, 1, 10));
1676 let _id = stamp_id(&mut sb);
1677 {
1678 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1679 sb.set_params(50, 0, 100, 5, 1, &mut ctx);
1680 }
1681 let mut ev = mouse_down_at(0, 0); // up-arrow → auto track
1682 {
1683 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1684 sb.handle_event(&mut ev, &mut ctx);
1685 }
1686 assert!(sb.tracking && sb.tracked_part.is_some());
1687 let value_before = sb.value;
1688
1689 let mut ev = mouse_move_at(0, 7);
1690 {
1691 let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1692 sb.handle_event(&mut ev, &mut ctx);
1693 }
1694 assert!(
1695 !ev.is_nothing(),
1696 "MouseMove during an arrow track falls through unconsumed"
1697 );
1698 assert_eq!(sb.value, value_before, "…and changes nothing");
1699 }
1700}