tvision_rs/widgets/button.rs
1//! `Button`, the clickable command button (documented on the type).
2
3use crate::capture::TrackMask;
4use crate::command::Command;
5use crate::event::{Event, Key, hot_key, is_alt_hotkey, is_plain_hotkey};
6use crate::theme::Role;
7use crate::timer::TimerId;
8use crate::view::{Context, DrawCtx, Options, Phase, Point, Rect, StateFlag, View, ViewState};
9use std::time::Duration;
10
11/// The press-flash duration before the command fires.
12const ANIMATION_DURATION_MS: u64 = 100;
13
14// ---------------------------------------------------------------------------
15// ButtonFlags — struct-of-bools for the button decoration/behavior flags
16// ---------------------------------------------------------------------------
17
18/// Button flags — the decoration/behavior flags as a struct-of-bools.
19///
20/// All-false is the default. Build with [`ButtonFlags::new`] or struct-update
21/// syntax (`ButtonFlags { default: true, ..Default::default() }`).
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
23pub struct ButtonFlags {
24 /// This is the default button (fires on the default command / Enter).
25 pub default: bool,
26 /// The title is left-justified rather than centered.
27 pub left_just: bool,
28 /// The command is broadcast instead of posted.
29 pub broadcast: bool,
30 /// A mouse-down selects (focuses) the button.
31 pub grab_focus: bool,
32}
33
34impl ButtonFlags {
35 /// Returns all-false flags — equivalent to the C++ `bfNormal` constant ($00).
36 ///
37 /// Use this when you want a plain, non-default, centered button without any
38 /// special behavior. Combine with struct-update syntax to enable individual
39 /// flags: `ButtonFlags { default: true, ..ButtonFlags::new() }`.
40 pub fn new() -> Self {
41 Self::default()
42 }
43}
44
45// ---------------------------------------------------------------------------
46// Button
47// ---------------------------------------------------------------------------
48
49/// A clickable command button: a 2+-row box with a centered (or
50/// left-justified) title, a drop shadow, and an `~`-marked hotkey. Pressing it
51/// (mouse, Alt+hotkey, focused-Space, or — for the default button — the
52/// [`Command::DEFAULT`] broadcast) fires its [`command`](Button::command), either
53/// posted as an `Event::Command` or broadcast.
54///
55/// # Model
56///
57/// [`Button`] embeds [`ViewState`] and branches on its per-instance data; the
58/// decoration/behavior flags are the [`ButtonFlags`] struct-of-bools. Drawing
59/// goes through [`DrawCtx`], events through [`Context`]. Coordinates are
60/// view-local (the group already translated the mouse position into this view's
61/// frame).
62///
63/// # The press animation
64///
65/// A keyboard / [`Command::DEFAULT`] press does not fire immediately: it flips the button
66/// to its pressed look (`down = true`), arms a one-shot 100 ms timer
67/// ([`Context::set_timer`]), and stores the [`TimerId`]. When that timer's
68/// [`Event::Timer`] arrives (it reaches every view), the button compares the id
69/// to its stored [`animation_timer`](Button::animation_timer); on a match it
70/// clears the flash and finally `press`es. Matching the id
71/// against the stored handle means a button only fires on *its own* timer, never
72/// on an unrelated one.
73///
74/// Broadcast and timer events reach every child regardless of its event mask
75/// (the mask only gates `mouse_move`/`mouse_auto`), so opting into the broadcast
76/// class is automatic — no per-button state is needed.
77///
78/// # Mouse hold-tracking
79///
80/// A mouse-down inside the click rectangle begins a modal hold: the button sets
81/// `down = true` and calls [`Context::start_mouse_track`], caching the absolute
82/// screen origin of button-local `(0, 0)` (recorded by the last `draw`) so the
83/// capture can convert absolute mouse coordinates back to button-local.
84///
85/// From the next pump on, the
86/// [`MouseTrackCapture`](crate::capture::MouseTrackCapture) routes every
87/// `MouseMove` (localized to button-local) back into this `handle_event`: each
88/// move flips `down` on tracking-rectangle containment. On `MouseUp` the button
89/// presses iff the last move was still inside the tracking rectangle (`self.down`)
90/// — never the release position — then clears `down`. Both arms are guarded by a
91/// `tracking` flag so a stray, untracked release falls through. Every other event
92/// during the hold is swallowed by the capture (the hold is modal). A button
93/// without an id (an uninserted, test-only button) keeps a single-shot fallback.
94///
95/// # Command-enabled graying
96///
97/// When a [`Command::COMMAND_SET_CHANGED`] broadcast arrives, the button grays
98/// itself out if its command is currently disabled
99/// (`state.disabled = !ctx.command_enabled(command)`). Initial disabled state is
100/// established the same way, by the first command-set-changed broadcast on the
101/// opening idle pass — no separate constructor step is needed. A disabled default
102/// button does not flash on the default-command broadcast.
103///
104/// # Plain-letter accelerator
105///
106/// When the button has its post-process option set, an unmodified letter that
107/// matches its hotkey fires it during the post-processing phase. A focused input
108/// line that consumes the letter first still starves this path, so plain letters
109/// are only stolen when the focused view leaves them live (matching Turbo Vision).
110///
111/// Marker decoration (`showMarkers`/`specialChars`) is not modeled — the button
112/// always draws the no-markers form.
113///
114/// # Turbo Vision heritage
115///
116/// Ports `TButton` (`tbutton.cpp`/`dialogs.h`). Inheritance becomes the `View`
117/// trait plus `ViewState` composition (deviation D2); the C++ button flag word
118/// becomes [`ButtonFlags`] (deviation D5); the view-local grab/release-default
119/// commands become namespaced [`Command::custom`] consts
120/// ([`Button::GRAB_DEFAULT`] / [`Button::RELEASE_DEFAULT`]). The owner up-pointer
121/// is replaced by [`Context`], and a broadcast carries the firing button's
122/// resolvable [`ViewId`] as its `source` (deviations D3, D4). The palette
123/// AttrPairs become explicit (lo, hi) [`Role`] pairs chosen per state (see
124/// `Button::state_roles`); the typed [`Event::Timer(id)`](Event::Timer) payload replaces the
125/// C++ timer-expired broadcast.
126///
127/// [`ViewId`]: crate::view::ViewId
128pub struct Button {
129 /// View state (geometry, flags, cursor) — the composition target.
130 pub state: ViewState,
131 /// The button label displayed on the face. Surround a letter with `~` to
132 /// mark it as the hotkey: `"~O~K"` makes `O` the accelerator, drawn in the
133 /// shortcut (hi) color. The `~` characters themselves are not printed.
134 pub title: String,
135 /// The command fired when the button is pressed. When the `broadcast` flag
136 /// is clear (the default), the command is posted as an [`Event::Command`];
137 /// when the flag is set, it is broadcast with the button's own
138 /// [`ViewId`](crate::view::ViewId) as the source.
139 pub command: Command,
140 /// Controls visual appearance and press behavior. Build with
141 /// [`ButtonFlags::new`] (all false) or struct-update syntax and flip
142 /// individual fields: `ButtonFlags { default: true, ..ButtonFlags::new() }`.
143 pub flags: ButtonFlags,
144 /// Whether the button is currently acting as the dialog's default button —
145 /// that is, the one that fires when [`Command::DEFAULT`] (Enter) is pressed.
146 /// Starts as a copy of `flags.default`; toggled at runtime by
147 /// [`GRAB_DEFAULT`](Button::GRAB_DEFAULT) / [`RELEASE_DEFAULT`](Button::RELEASE_DEFAULT)
148 /// broadcasts. Read this field to query the live default state; to *change*
149 /// it programmatically, send the appropriate broadcast or call
150 /// `make_default`.
151 pub am_default: bool,
152 /// The in-flight press-flash timer, if armed.
153 pub animation_timer: Option<TimerId>,
154 /// The pressed appearance, read each redraw. `true` during the press flash.
155 pub down: bool,
156 /// Absolute screen position of button-local `(0, 0)`, cached each `draw`
157 /// so the mouse-tracking capture
158 /// ([`MouseTrackCapture`](crate::capture::MouseTrackCapture)) can convert
159 /// absolute mouse coordinates to button-local — the same abs-origin caching
160 /// approach used by [`ScrollBar`](crate::widgets::ScrollBar).
161 /// Initialized to `(0, 0)`; updated on the first `draw` pass.
162 abs_origin: Point,
163 /// Whether a mouse hold-track is in flight (between the arming `MouseDown`
164 /// and the terminating `MouseUp`). Guards the `MouseMove`/`MouseUp`
165 /// tracking arms in `handle_event` against stray (untracked) events —
166 /// `MouseUp` is not mask-gated in `Group::wants`.
167 tracking: bool,
168}
169
170impl Button {
171 /// Sent by a focused non-default button to ask the current default button to
172 /// relinquish the default look. A view-local, namespaced command.
173 pub const GRAB_DEFAULT: Command = Command::custom("tv.button.grab_default");
174 /// The inverse of [`GRAB_DEFAULT`](Self::GRAB_DEFAULT): a non-default button
175 /// losing focus asks the default button to take the default look back.
176 pub const RELEASE_DEFAULT: Command = Command::custom("tv.button.release_default");
177
178 /// Build a button from `bounds`, `title`, `command`, `flags`.
179 ///
180 /// `am_default` follows the `default` flag; the press-flash timer starts
181 /// unarmed; the view is selectable and takes part in pre- and
182 /// post-processing.
183 ///
184 /// Opting into the broadcast class is automatic (broadcasts reach every
185 /// child regardless of its event mask), so no per-button state is needed.
186 /// Initial command-enabled graying is established lazily by the first
187 /// command-set-changed broadcast rather than in the constructor; see the
188 /// [`Button`] docs.
189 pub fn new(bounds: Rect, title: &str, command: Command, flags: ButtonFlags) -> Self {
190 let mut state = ViewState::new(bounds);
191 state.options = Options {
192 selectable: true,
193 first_click: true,
194 pre_process: true,
195 post_process: true,
196 ..Default::default()
197 };
198 // Initial command-enabled graying is established lazily: the first
199 // COMMAND_SET_CHANGED broadcast fires on the opening idle pass when
200 // initial_disabled_commands is non-empty. The constructor has no ctx,
201 // so handling it in the broadcast arm is correct.
202 Button {
203 state,
204 title: title.to_string(),
205 command,
206 flags,
207 am_default: flags.default,
208 animation_timer: None,
209 down: false,
210 abs_origin: Point::new(0, 0),
211 tracking: false,
212 }
213 }
214
215 /// The (lo, hi) [`Role`] pair selected for the current state. `lo` is the
216 /// body/label color, `hi` the hotkey-shortcut color (the `~`-toggled half).
217 ///
218 /// * disabled → `(ButtonDisabled, ButtonDisabled)`
219 /// * active + selected → `(ButtonSelected, ButtonSelectedShortcut)`
220 /// * active + acting-as-default → `(ButtonDefault, ButtonDefaultShortcut)`
221 /// * else → `(ButtonNormal, ButtonNormalShortcut)`
222 fn state_roles(&self) -> (Role, Role) {
223 let s = &self.state.state;
224 if s.disabled {
225 (Role::ButtonDisabled, Role::ButtonDisabled)
226 } else if s.active && s.selected {
227 (Role::ButtonSelected, Role::ButtonSelectedShortcut)
228 } else if s.active && self.am_default {
229 (Role::ButtonDefault, Role::ButtonDefaultShortcut)
230 } else {
231 (Role::ButtonNormal, Role::ButtonNormalShortcut)
232 }
233 }
234
235 /// Fire the button. Broadcasts [`Command::RECORD_HISTORY`] first (history with
236 /// no subject → `source = None`), then either broadcasts the command (when the
237 /// `broadcast` flag is set, with `source = self id`) or posts it as an
238 /// `Event::Command` (which carries no source).
239 ///
240 /// Private: the mouse-up press fires from this view's own `MouseUp` arm,
241 /// routed back by the [`MouseTrackCapture`](crate::capture::MouseTrackCapture),
242 /// so no pump-side broker needs to reach in.
243 fn press(&mut self, ctx: &mut Context) {
244 let id = self.state.id();
245 ctx.broadcast(Command::RECORD_HISTORY, None);
246 if self.flags.broadcast {
247 ctx.broadcast(self.command, id);
248 } else {
249 ctx.post(self.command);
250 }
251 }
252
253 /// Grab/release the default look. Only a **non**-default button does anything:
254 /// it broadcasts [`GRAB_DEFAULT`](Self::GRAB_DEFAULT) /
255 /// [`RELEASE_DEFAULT`](Self::RELEASE_DEFAULT) (so the real default button
256 /// relinquishes/retakes the look) and toggles its own `am_default`.
257 ///
258 /// `pub(crate)` so the pump's
259 /// [`MakeButtonDefault`](crate::view::Deferred::MakeButtonDefault) broker can
260 /// drive it on a sibling (a directory list box's focus moving to its directory
261 /// button).
262 pub(crate) fn make_default(&mut self, enable: bool, ctx: &mut Context) {
263 if !self.flags.default {
264 let id = self.state.id();
265 ctx.broadcast(
266 if enable {
267 Self::GRAB_DEFAULT
268 } else {
269 Self::RELEASE_DEFAULT
270 },
271 id,
272 );
273 self.am_default = enable;
274 }
275 }
276
277 /// Arm the press flash: flip to the pressed look and start the one-shot
278 /// animation timer if one is not already running. Shared by the keyboard and
279 /// default-command paths.
280 fn start_animation(&mut self, ctx: &mut Context) {
281 self.down = true;
282 if self.animation_timer.is_none() {
283 self.animation_timer =
284 Some(ctx.set_timer(Duration::from_millis(ANIMATION_DURATION_MS), None));
285 }
286 }
287}
288
289impl View for Button {
290 fn state(&self) -> &ViewState {
291 &self.state
292 }
293
294 fn state_mut(&mut self) -> &mut ViewState {
295 &mut self.state
296 }
297
298 /// Exposes the concrete `Button` so the pump's
299 /// [`MakeButtonDefault`](crate::view::Deferred::MakeButtonDefault) broker can
300 /// downcast a sibling button and call `make_default`.
301 fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
302 Some(self)
303 }
304
305 /// Paint the button, building each row explicitly so the shadow column and
306 /// row land exactly.
307 ///
308 /// Geometry: `s = size.x - 1` (last column), `t = size.y / 2 - 1` (the title
309 /// row). Body rows are `y in 0..=size.y-2`; the bottom row (`size.y-1`) is the
310 /// all-shadow stripe.
311 ///
312 /// Normal (`!down`): each body row is filled with spaces in the button color,
313 /// col 0 gets the shadow style, and the right column `s` gets the shadow style
314 /// plus a shadow glyph (`▄` on the top row, `█` below). The title is drawn at
315 /// `i+l` with `i = 1`. The bottom row is 2 shadow spaces then `▀` across in the
316 /// shadow color.
317 ///
318 /// Pressed (`down`): the body shifts right by one — cols 0..=1 take the shadow
319 /// style, the right-column shadow glyph vanishes (`ch = ' '`), the title is
320 /// drawn with `i = 2`. The bottom row is all shadow spaces.
321 ///
322 /// # Note: DrawState merge
323 ///
324 /// The C++ API exposes a separate `DrawState(bool down)` method called by both
325 /// `Draw` and `HandleEvent`. This port merges the two: the pressed/normal
326 /// distinction is captured in the `self.down` field, which `draw` reads
327 /// directly. There is no separate `draw_state` method.
328 fn draw(&mut self, ctx: &mut DrawCtx) {
329 // Cache the absolute origin for the mouse-tracking capture: the
330 // MouseTrackCapture converts absolute mouse coords to button-local via
331 // this value (the same abs-origin caching pattern as ScrollBar).
332 self.abs_origin = ctx.origin();
333 let down = self.down;
334 let (lo_role, hi_role) = self.state_roles();
335 let c_button = ctx.style(lo_role);
336 let c_button_hi = ctx.style(hi_role);
337 let c_shadow = ctx.style(Role::ButtonShadow);
338 let glyphs = *ctx.glyphs();
339
340 let size = self.state.size;
341 let s = size.x - 1; // last column
342 let t = size.y / 2 - 1; // title row
343 // The fill char for the bottom-row stripe (`▀` when not down, else space).
344 let bottom_ch = if down {
345 ' '
346 } else {
347 glyphs.button_shadow_bottom
348 };
349
350 // -- Body rows: 0 ..= size.y - 2 -------------------------------------
351 for y in 0..=(size.y - 2) {
352 // Fill the whole row with spaces in the button color.
353 // NB: `Rect::new` takes corner coords `(ax, ay, bx, by)`, not w/h.
354 ctx.fill(Rect::new(0, y, size.x, y + 1), ' ', c_button);
355 // Column 0 always takes the shadow attribute.
356 ctx.put_char(0, y, ' ', c_shadow);
357
358 let i = if down {
359 // Pressed: cols 0..=1 are shadow; body shifts right (i = 2); no
360 // right-edge shadow glyph.
361 ctx.put_char(1, y, ' ', c_shadow);
362 2
363 } else {
364 // Normal: the right column takes the shadow attr + a shadow glyph
365 // (`▄` on top row, `█` below).
366 let glyph = if y == 0 {
367 glyphs.button_shadow_top
368 } else {
369 glyphs.button_shadow_side
370 };
371 ctx.put_char(s, y, glyph, c_shadow);
372 1
373 };
374
375 // Title on the vertically-centered row.
376 if y == t && !self.title.is_empty() {
377 // C++ drawTitle: l = bfLeftJust ? 1 : max(1, (s - cstrlen - 1)/2).
378 let l = if self.flags.left_just {
379 1
380 } else {
381 let centered = (s - cstrlen(&self.title) - 1) / 2;
382 centered.max(1)
383 };
384 // Centering uses cstrlen (strips `~`); the raw `~`-bearing title is
385 // drawn through put_cstr's lo/hi toggle.
386 ctx.put_cstr(i + l, y, &self.title, c_button, c_button_hi);
387 }
388 }
389
390 // -- Bottom row: size.y - 1 ------------------------------------------
391 // 2 leading shadow spaces, then `bottom_ch` (▀ when !down) across in the
392 // shadow color (C++ `moveChar(0,' ',cShadow,2); moveChar(2,ch,cShadow,s-1)`).
393 let last = size.y - 1;
394 // C++ moveChar(0, ' ', cShadow, 2): 2 cells at col 0 → cols 0..2.
395 ctx.fill(Rect::new(0, last, 2, last + 1), ' ', c_shadow);
396 // C++ moveChar(2, ch, cShadow, s - 1): `s - 1` cells at col 2 → cols 2..s+1.
397 ctx.fill(Rect::new(2, last, s + 1, last + 1), bottom_ch, c_shadow);
398 }
399
400 /// Handle the button's events — mouse hold-tracking, keyboard/hotkey presses,
401 /// default-look grab/release, and command-set graying. See the [`Button`] docs
402 /// for the per-branch behavior.
403 fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
404 // C++ clickRect = getExtent() shrunk by (a.x+1, b.x-1, b.y-1).
405 let ext = self.state.get_extent();
406 let click_rect = Rect::from_points(
407 Point::new(ext.a.x + 1, ext.a.y),
408 Point::new(ext.b.x - 1, ext.b.y - 1),
409 );
410
411 // Note: the C++ `if(flags & bfGrabFocus) TView::handleEvent(event)`
412 // mouse-down auto-select is relocated to the group via the
413 // `grabs_focus_on_click` hook below — NOT done here.
414
415 let c = hot_key(&self.title);
416
417 match ev {
418 Event::MouseDown(m) => {
419 // Mouse-down outside clickRect is consumed without action (C++ first
420 // clears it, then the disabled/contains gate makes the press a no-op);
421 // either way the result is: press iff !disabled && contains, then clear.
422 if !self.state.state.disabled && click_rect.contains(m.position) {
423 if let Some(id) = self.state.id() {
424 // Normal path (inserted button with a ViewId): this is
425 // the first iteration of the hold loop — the down
426 // position is inside clickRect ⊂ trackRect, so
427 // `down = true` (pressed look) — then enter the loop by
428 // starting a mouse track. The capture routes subsequent
429 // MouseMove/MouseUp back into the arms below,
430 // localized via `abs_origin` (cached by the last draw).
431 self.down = true;
432 self.tracking = true;
433 ctx.start_mouse_track(
434 id,
435 self.abs_origin,
436 TrackMask {
437 mouse_move: true,
438 ..Default::default()
439 },
440 );
441 } else {
442 // Degenerate fallback: an uninserted (test-only) button has no id,
443 // so the capture broker cannot resolve it. Press immediately.
444 self.press(ctx);
445 }
446 }
447 ev.clear();
448 }
449
450 // The hold-loop body, re-entered per tracked MouseMove via
451 // Deferred::MouseTrack (position already button-local): flip `down`
452 // on tracking-rect containment. Tracking rect: clickRect widened by
453 // one on b.x (`clickRect.b.x++`), recomputed per event so it stays
454 // resize-fresh.
455 Event::MouseMove(m) if self.tracking => {
456 let track_rect =
457 Rect::from_points(click_rect.a, Point::new(click_rect.b.x + 1, click_rect.b.y));
458 let inside = track_rect.contains(m.position);
459 if inside != self.down {
460 self.down = inside;
461 }
462 ev.clear();
463 }
464
465 // The post-loop code: press iff the LAST MOVE's tracked
466 // containment (`self.down`) — the loop body never
467 // re-evaluates the up-event's position (`mouseEvent` returns false
468 // on mouse-up before the body runs again), so the up position is
469 // deliberately not read. Guarded by `tracking` against stray ups
470 // (MouseUp is not mask-gated in Group::wants).
471 Event::MouseUp(_) if self.tracking => {
472 self.tracking = false;
473 let pressed = self.down;
474 self.down = false;
475 if pressed {
476 self.press(ctx);
477 }
478 ev.clear();
479 }
480
481 Event::KeyDown(ke) => {
482 // Alt+hotkey, OR postProcess + plain hotkey letter, OR focused +
483 // Space. The Space branch is independent of whether the title
484 // has a hotkey (a hotkey-less button still acts on Space when
485 // focused). The plain-letter leg fires only on the post-process
486 // walk (`ctx.phase() == Phase::PostProcess`): an unfocused
487 // button picks up letters the focused view left unconsumed.
488 let alt_hot = c.map(|c| is_alt_hotkey(ke, c)).unwrap_or(false);
489 let post_plain = ctx.phase() == Phase::PostProcess
490 && c.map(|c| is_plain_hotkey(ke, c)).unwrap_or(false);
491 let focused_space = self.state.state.focused && ke.key == Key::Char(' ');
492 if alt_hot || post_plain || focused_space {
493 self.start_animation(ctx);
494 ev.clear();
495 }
496 }
497
498 Event::Broadcast { command, .. } => match *command {
499 Command::DEFAULT if self.am_default && !self.state.state.disabled => {
500 self.start_animation(ctx);
501 ev.clear();
502 }
503 // Only the bfDefault button reacts to grab/release; NO clearEvent
504 // (C++ — every default button must see it).
505 cmd @ (Self::GRAB_DEFAULT | Self::RELEASE_DEFAULT) if self.flags.default => {
506 self.am_default = cmd == Self::RELEASE_DEFAULT;
507 }
508 // Command graying: disable the button iff its command is disabled.
509 // The COMMAND_SET_CHANGED broadcast fires during the idle phase
510 // whenever the command set changes (including the initial pass via
511 // Program::initial_disabled_commands), so this arm also covers the
512 // initial disabled state — no separate constructor init needed.
513 // Whole-tree redraw replaces the C++ drawView().
514 Command::COMMAND_SET_CHANGED => {
515 self.state.state.disabled = !ctx.command_enabled(self.command);
516 }
517 _ => {}
518 },
519
520 // The press-flash fired: fire iff it is *our* timer.
521 Event::Timer(id) if Some(*id) == self.animation_timer => {
522 self.animation_timer = None;
523 self.down = false;
524 self.press(ctx);
525 ev.clear();
526 }
527
528 _ => {}
529 }
530 }
531
532 /// Flip the propagating flag (replicating the trait-default body, since Rust
533 /// has no `super` for a default method) then, for [`StateFlag::Focused`], run
534 /// `make_default`. No explicit redraw is needed on
535 /// select/activate (the whole tree is redrawn each pass).
536 ///
537 /// Replicate-then-extend (the `Group::set_state` shape): flip the flag and, on
538 /// `Focused`, emit the base focus broadcast ([`Command::RECEIVED_FOCUS`] /
539 /// [`Command::RELEASED_FOCUS`], `source = self`) — *then* `make_default`. So
540 /// focusing a non-default button queues `RECEIVED_FOCUS` **then** `GRAB_DEFAULT`.
541 fn set_state(&mut self, flag: StateFlag, enable: bool, ctx: &mut Context) {
542 // Base behaviour (replicated from the View::set_state default).
543 self.state.set_flag(flag, enable);
544 if flag == StateFlag::Focused {
545 let source = self.state.id(); // self == C++ `this`
546 ctx.broadcast(
547 if enable {
548 Command::RECEIVED_FOCUS
549 } else {
550 Command::RELEASED_FOCUS
551 },
552 source,
553 );
554 // TButton extension.
555 self.make_default(enable, ctx);
556 }
557 }
558
559 /// Opt-in for the mouse-down auto-select: only a button with the `grab_focus`
560 /// flag is selected (focused) by a click; the group consults this hook to
561 /// decide whether a click should focus the button.
562 fn grabs_focus_on_click(&self) -> bool {
563 self.flags.grab_focus
564 }
565}
566
567use crate::text::cstrlen;
568
569// ---------------------------------------------------------------------------
570// Tests
571// ---------------------------------------------------------------------------
572
573#[cfg(test)]
574mod tests {
575 use super::*;
576 use crate::backend::{HeadlessBackend, Renderer};
577 use crate::event::{KeyEvent, KeyModifiers, MouseButtons, MouseEvent};
578 use crate::screen::Buffer;
579 use crate::theme::Theme;
580 use crate::timer::TimerQueue;
581 use crate::view::Deferred;
582 use std::collections::VecDeque;
583
584 // -- helpers ------------------------------------------------------------
585
586 /// Render the button to a snapshot string.
587 fn render(button: &mut Button) -> String {
588 let theme = Theme::classic_blue();
589 let size = button.state.size;
590 let (backend, screen) = HeadlessBackend::new(size.x as u16, size.y as u16);
591 let mut r = Renderer::new(Box::new(backend));
592 r.render(|buf: &mut Buffer| {
593 let bounds = button.state.get_bounds();
594 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
595 button.draw(&mut dc);
596 });
597 screen.snapshot()
598 }
599
600 /// Run a closure with a fresh `Context` over loop-owned locals, returning the
601 /// drained out-events plus the closure's value.
602 fn with_ctx<R>(
603 timers: &mut TimerQueue,
604 now_ms: u64,
605 f: impl FnOnce(&mut Context) -> R,
606 ) -> (Vec<Event>, R) {
607 let mut out = VecDeque::new();
608 let mut deferred: Vec<Deferred> = Vec::new();
609 let r = {
610 let mut ctx = Context::new(&mut out, timers, now_ms, &mut deferred);
611 f(&mut ctx)
612 };
613 (out.into_iter().collect(), r)
614 }
615
616 /// Like [`with_ctx`] but also returns the deferred vec so tests can assert
617 /// on `Deferred::PushCapture` and the button-tracking variants.
618 fn with_ctx_d<R>(
619 timers: &mut TimerQueue,
620 now_ms: u64,
621 f: impl FnOnce(&mut Context) -> R,
622 ) -> (Vec<Event>, Vec<Deferred>, R) {
623 let mut out = VecDeque::new();
624 let mut deferred: Vec<Deferred> = Vec::new();
625 let r = {
626 let mut ctx = Context::new(&mut out, timers, now_ms, &mut deferred);
627 f(&mut ctx)
628 };
629 (out.into_iter().collect(), deferred, r)
630 }
631
632 fn mouse_down(x: i32, y: i32) -> Event {
633 Event::MouseDown(MouseEvent {
634 position: Point::new(x, y),
635 buttons: MouseButtons {
636 left: true,
637 ..Default::default()
638 },
639 ..Default::default()
640 })
641 }
642
643 fn mouse_move(x: i32, y: i32) -> Event {
644 Event::MouseMove(MouseEvent {
645 position: Point::new(x, y),
646 buttons: MouseButtons {
647 left: true,
648 ..Default::default()
649 },
650 ..Default::default()
651 })
652 }
653
654 fn mouse_up(x: i32, y: i32) -> Event {
655 Event::MouseUp(MouseEvent {
656 position: Point::new(x, y),
657 ..Default::default()
658 })
659 }
660
661 fn key(k: Key) -> Event {
662 Event::KeyDown(KeyEvent::new(k, KeyModifiers::default()))
663 }
664
665 fn alt_key(c: char) -> Event {
666 Event::KeyDown(KeyEvent::new(
667 Key::Char(c),
668 KeyModifiers {
669 alt: true,
670 ..Default::default()
671 },
672 ))
673 }
674
675 /// A button stamped with an id (so broadcasts carry `source = Some(id)`), as
676 /// `Group::insert` would do at runtime.
677 fn button_with_id(b: &mut Button) -> crate::view::ViewId {
678 let id = crate::view::ViewId::next();
679 b.state.id = Some(id);
680 id
681 }
682
683 // -- snapshot tests -----------------------------------------------------
684
685 /// Normal button: centered "OK", drop shadow (`▄` top-right, `█` below, `▀`
686 /// bottom stripe offset by 2).
687 #[test]
688 fn snapshot_normal() {
689 let mut b = Button::new(
690 Rect::new(0, 0, 10, 2),
691 "OK",
692 Command::OK,
693 ButtonFlags::new(),
694 );
695 insta::assert_snapshot!(render(&mut b));
696 }
697
698 /// Pressed look (`down = true`): body shifts right by one, shadow glyphs
699 /// vanish, bottom row is all shadow spaces.
700 #[test]
701 fn snapshot_pressed() {
702 let mut b = Button::new(
703 Rect::new(0, 0, 10, 2),
704 "OK",
705 Command::OK,
706 ButtonFlags::new(),
707 );
708 b.down = true;
709 insta::assert_snapshot!(render(&mut b));
710 }
711
712 /// Default button: `bfDefault` + active → ButtonDefault colors (the special
713 /// branch is gated on sfActive, so `state.active` must be set).
714 #[test]
715 fn snapshot_default_active() {
716 let mut b = Button::new(
717 Rect::new(0, 0, 10, 2),
718 "OK",
719 Command::OK,
720 ButtonFlags {
721 default: true,
722 ..Default::default()
723 },
724 );
725 b.state.state.active = true;
726 assert!(b.am_default, "bfDefault initializes am_default");
727 insta::assert_snapshot!(render(&mut b));
728 }
729
730 /// Selected button: active + selected → ButtonSelected colors.
731 #[test]
732 fn snapshot_selected_active() {
733 let mut b = Button::new(
734 Rect::new(0, 0, 10, 2),
735 "OK",
736 Command::OK,
737 ButtonFlags::new(),
738 );
739 b.state.state.active = true;
740 b.state.state.selected = true;
741 insta::assert_snapshot!(render(&mut b));
742 }
743
744 /// Disabled button: ButtonDisabled colors (overrides every other branch).
745 #[test]
746 fn snapshot_disabled() {
747 let mut b = Button::new(
748 Rect::new(0, 0, 10, 2),
749 "OK",
750 Command::OK,
751 ButtonFlags::new(),
752 );
753 b.state.state.disabled = true;
754 insta::assert_snapshot!(render(&mut b));
755 }
756
757 /// Left-justified title (`bfLeftJust`): the title hugs the left (l = 1).
758 #[test]
759 fn snapshot_left_justified() {
760 let mut b = Button::new(
761 Rect::new(0, 0, 16, 2),
762 "Save",
763 Command::SAVE,
764 ButtonFlags {
765 left_just: true,
766 ..Default::default()
767 },
768 );
769 insta::assert_snapshot!(render(&mut b));
770 }
771
772 /// Centered title (default) in a wide button — contrast with the left-just one.
773 #[test]
774 fn snapshot_centered() {
775 let mut b = Button::new(
776 Rect::new(0, 0, 16, 2),
777 "Save",
778 Command::SAVE,
779 ButtonFlags::new(),
780 );
781 insta::assert_snapshot!(render(&mut b));
782 }
783
784 /// `~`-hotkey title: the hotkey letter is drawn in the shortcut (hi) role.
785 #[test]
786 fn snapshot_hotkey_title() {
787 let mut b = Button::new(
788 Rect::new(0, 0, 12, 2),
789 "~C~ancel",
790 Command::CANCEL,
791 ButtonFlags::new(),
792 );
793 insta::assert_snapshot!(render(&mut b));
794 }
795
796 // -- behavior: keyboard / timer animation -------------------------------
797
798 /// Alt+hotkey arms the timer (no command yet); the matching Event::Timer then
799 /// fires the command and resets down / animation_timer. An *unrelated* timer
800 /// id must NOT fire it.
801 #[test]
802 fn alt_hotkey_arms_then_fires_on_own_timer() {
803 let mut b = Button::new(
804 Rect::new(0, 0, 10, 2),
805 "~O~k",
806 Command::OK,
807 ButtonFlags::new(),
808 );
809 let mut timers = TimerQueue::new();
810
811 // Alt+O arms the timer; no command posted yet.
812 let mut ev = alt_key('o');
813 let (out, ()) = with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
814 assert!(ev.is_nothing(), "Alt+hotkey consumes the key");
815 assert!(b.down, "armed → pressed look");
816 let armed = b.animation_timer.expect("timer armed");
817 assert!(
818 !out.iter().any(|e| matches!(e, Event::Command(_))),
819 "no command posted at arm time"
820 );
821
822 // BITE: a foreign timer id must not fire the button. Arm a second, real
823 // timer in the queue (a distinct id) and feed *its* expiry.
824 let other = timers.set_timer(50, Duration::from_millis(100), None);
825 assert_ne!(other, armed, "a fresh timer has a distinct id");
826 let mut ev = Event::Timer(other);
827 let (out, ()) = with_ctx(&mut timers, 50, |ctx| b.handle_event(&mut ev, ctx));
828 assert!(!ev.is_nothing(), "foreign timer is not consumed");
829 assert!(b.down, "still armed after a foreign timer");
830 assert!(b.animation_timer.is_some());
831 assert!(out.is_empty(), "foreign timer fires nothing");
832
833 // Our own timer fires the command and resets.
834 let mut ev = Event::Timer(armed);
835 let (out, ()) = with_ctx(&mut timers, 100, |ctx| b.handle_event(&mut ev, ctx));
836 assert!(ev.is_nothing(), "own timer is consumed");
837 assert!(!b.down, "flash cleared");
838 assert!(b.animation_timer.is_none(), "timer handle cleared");
839 // press(): RECORD_HISTORY then the posted command.
840 assert_eq!(
841 out[0],
842 Event::Broadcast {
843 command: Command::RECORD_HISTORY,
844 source: None
845 }
846 );
847 assert_eq!(out[1], Event::Command(Command::OK));
848 }
849
850 /// The plain hotkey letter arms the press on the post-process walk —
851 /// when the phase is `Phase::PostProcess` and the letter matches the hotkey.
852 #[test]
853 fn plain_hotkey_arms_at_post_process() {
854 let mut b = Button::new(
855 Rect::new(0, 0, 10, 2),
856 "~O~k",
857 Command::OK,
858 ButtonFlags::new(),
859 );
860 let mut timers = TimerQueue::new();
861 // Unfocused, plain 'o', delivered on the post-process leg.
862 let mut ev = key(Key::Char('o'));
863 with_ctx(&mut timers, 0, |ctx| {
864 ctx.set_phase(Phase::PostProcess);
865 b.handle_event(&mut ev, ctx)
866 });
867 assert!(ev.is_nothing(), "the postProcess plain letter is consumed");
868 assert!(b.down, "pressed look armed");
869 assert!(b.animation_timer.is_some(), "animation timer armed");
870 }
871
872 /// The same plain letter at the default (Focused) phase, unfocused, is
873 /// ignored — the plain-letter leg is gated on phPostProcess.
874 #[test]
875 fn plain_hotkey_ignored_outside_post_process() {
876 let mut b = Button::new(
877 Rect::new(0, 0, 10, 2),
878 "~O~k",
879 Command::OK,
880 ButtonFlags::new(),
881 );
882 let mut timers = TimerQueue::new();
883 let mut ev = key(Key::Char('o'));
884 with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
885 assert!(
886 !ev.is_nothing(),
887 "a plain letter outside phPostProcess is left live"
888 );
889 assert!(!b.down, "not pressed");
890 assert!(b.animation_timer.is_none(), "no timer armed");
891 }
892
893 /// A `bfBroadcast` button fires its command as a broadcast carrying its own id.
894 #[test]
895 fn broadcast_button_fires_broadcast_with_source() {
896 let mut b = Button::new(
897 Rect::new(0, 0, 10, 2),
898 "Go",
899 Command::custom("app.go"),
900 ButtonFlags {
901 broadcast: true,
902 ..Default::default()
903 },
904 );
905 let id = button_with_id(&mut b);
906 b.state.state.focused = true;
907 let mut timers = TimerQueue::new();
908
909 // Focused + Space arms.
910 let mut ev = key(Key::Char(' '));
911 with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
912 let armed = b.animation_timer.expect("armed by Space");
913
914 // Own timer fires → broadcast (not post) with source = our id.
915 let mut ev = Event::Timer(armed);
916 let (out, ()) = with_ctx(&mut timers, 100, |ctx| b.handle_event(&mut ev, ctx));
917 assert_eq!(
918 out[0],
919 Event::Broadcast {
920 command: Command::RECORD_HISTORY,
921 source: None
922 }
923 );
924 assert_eq!(
925 out[1],
926 Event::Broadcast {
927 command: Command::custom("app.go"),
928 source: Some(id)
929 }
930 );
931 assert!(
932 !out.iter().any(|e| matches!(e, Event::Command(_))),
933 "broadcast, not post"
934 );
935 }
936
937 /// Focused + Space arms the timer (same animation path); a non-focused Space
938 /// is ignored.
939 #[test]
940 fn focused_space_arms_unfocused_ignored() {
941 let mut b = Button::new(
942 Rect::new(0, 0, 10, 2),
943 "OK",
944 Command::OK,
945 ButtonFlags::new(),
946 );
947 let mut timers = TimerQueue::new();
948
949 // Not focused → Space ignored.
950 let mut ev = key(Key::Char(' '));
951 with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
952 assert!(!ev.is_nothing(), "unfocused Space is not consumed");
953 assert!(b.animation_timer.is_none());
954
955 // Focused → Space arms.
956 b.state.state.focused = true;
957 let mut ev = key(Key::Char(' '));
958 with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
959 assert!(ev.is_nothing());
960 assert!(b.down);
961 assert!(b.animation_timer.is_some());
962 }
963
964 // -- behavior: mouse ----------------------------------------------------
965
966 /// Mouse-down inside clickRect on a button WITH an id: arms tracking.
967 /// The event is consumed, `down` is set, a `PushCapture` is deferred, and
968 /// NO command is posted immediately (the command fires after `MouseUp`).
969 #[test]
970 fn mouse_down_inside_arms_tracking() {
971 let mut b = Button::new(
972 Rect::new(0, 0, 10, 2),
973 "OK",
974 Command::OK,
975 ButtonFlags::new(),
976 );
977 let id = button_with_id(&mut b);
978 let mut timers = TimerQueue::new();
979 // clickRect = (1, 0, 9, 1): (3, 0) is inside.
980 let mut ev = mouse_down(3, 0);
981 let (out, deferred, ()) = with_ctx_d(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
982 assert!(ev.is_nothing(), "mouse-down on the button is consumed");
983 assert!(b.down, "button transitions to pressed look");
984 assert!(
985 b.animation_timer.is_none(),
986 "no animation timer on mouse path"
987 );
988 assert!(out.is_empty(), "no command posted at mouse-down time");
989 // A PushCapture must have been deferred.
990 assert_eq!(deferred.len(), 1, "one PushCapture deferred");
991 assert!(
992 matches!(deferred[0], Deferred::PushCapture(_)),
993 "deferred[0] is PushCapture"
994 );
995 // The pushed capture's view() must return the button's id.
996 if let Deferred::PushCapture(ref h) = deferred[0] {
997 assert_eq!(h.view(), Some(id), "capture tracks the button's id");
998 }
999 }
1000
1001 /// Mouse-down inside clickRect on a button WITHOUT an id (test-only /
1002 /// uninserted): falls back to the old single-shot press (backwards compat).
1003 #[test]
1004 fn mouse_down_without_id_presses_immediately() {
1005 let mut b = Button::new(
1006 Rect::new(0, 0, 10, 2),
1007 "OK",
1008 Command::OK,
1009 ButtonFlags::new(),
1010 );
1011 // No id stamped — the button has never been inserted in a group.
1012 let mut timers = TimerQueue::new();
1013 // clickRect = (1, 0, 9, 1): (3, 0) is inside.
1014 let mut ev = mouse_down(3, 0);
1015 let (out, deferred, ()) = with_ctx_d(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1016 assert!(ev.is_nothing(), "mouse-down on the button is consumed");
1017 assert!(deferred.is_empty(), "no capture pushed for id-less button");
1018 assert_eq!(
1019 out[0],
1020 Event::Broadcast {
1021 command: Command::RECORD_HISTORY,
1022 source: None
1023 }
1024 );
1025 assert_eq!(out[1], Event::Command(Command::OK));
1026 }
1027
1028 /// Mouse-down outside clickRect: consumed, but no press and no capture.
1029 #[test]
1030 fn mouse_down_outside_does_not_press() {
1031 let mut b = Button::new(
1032 Rect::new(0, 0, 10, 2),
1033 "OK",
1034 Command::OK,
1035 ButtonFlags::new(),
1036 );
1037 let _id = button_with_id(&mut b);
1038 let mut timers = TimerQueue::new();
1039 // clickRect = (1, 0, 9, 1): (0, 0) is the shadow column, outside.
1040 let mut ev = mouse_down(0, 0);
1041 let (out, deferred, ()) = with_ctx_d(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1042 assert!(ev.is_nothing(), "mouse-down is still consumed");
1043 assert!(out.is_empty(), "no press outside clickRect");
1044 assert!(deferred.is_empty(), "no capture for an outside click");
1045 assert!(!b.down, "down remains false");
1046 }
1047
1048 /// Disabled button: a mouse-down inside is consumed but does not press and
1049 /// does not push a capture.
1050 #[test]
1051 fn disabled_mouse_down_does_not_press() {
1052 let mut b = Button::new(
1053 Rect::new(0, 0, 10, 2),
1054 "OK",
1055 Command::OK,
1056 ButtonFlags::new(),
1057 );
1058 let _id = button_with_id(&mut b);
1059 b.state.state.disabled = true;
1060 let mut timers = TimerQueue::new();
1061 let mut ev = mouse_down(3, 0);
1062 let (out, deferred, ()) = with_ctx_d(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1063 assert!(ev.is_nothing());
1064 assert!(out.is_empty(), "disabled button does not press");
1065 assert!(deferred.is_empty(), "no capture for disabled button");
1066 }
1067
1068 // -- mouse hold-tracking arm tests (the loop body / post-loop) -------------
1069 //
1070 // The MouseTrackCapture routes localized MouseMove/MouseUp events back into
1071 // the button's own handle_event (Deferred::MouseTrack); these tests drive
1072 // those arms directly with button-local positions, exactly as the pump's
1073 // apply arm does. The router itself is unit-tested in `capture::tests`.
1074
1075 /// Helper: a 10×2 button with an id, armed by a MouseDown inside clickRect
1076 /// (`tracking == true`, `down == true`, one `PushCapture` deferred).
1077 fn tracked_button() -> Button {
1078 let mut b = Button::new(
1079 Rect::new(0, 0, 10, 2),
1080 "OK",
1081 Command::OK,
1082 ButtonFlags::new(),
1083 );
1084 button_with_id(&mut b);
1085 let mut timers = TimerQueue::new();
1086 // clickRect = (1,0,9,1): (3,0) is inside; trackRect = (1,0,10,1).
1087 let mut ev = mouse_down(3, 0);
1088 with_ctx_d(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1089 assert!(b.tracking, "MouseDown inside clickRect arms tracking");
1090 assert!(b.down);
1091 b
1092 }
1093
1094 /// Tracked `MouseMove` outside the track rect flips `down` to false;
1095 /// a move back inside flips it back (the C++ loop body).
1096 #[test]
1097 fn track_move_outside_then_inside_flips_down() {
1098 let mut b = tracked_button();
1099 let mut timers = TimerQueue::new();
1100
1101 // Button-local (0, 0): outside trackRect (x < 1).
1102 let mut ev = mouse_move(0, 0);
1103 with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1104 assert!(ev.is_nothing(), "tracked move is consumed");
1105 assert!(!b.down, "down flipped to false");
1106
1107 // Back inside: (3, 0).
1108 let mut ev = mouse_move(3, 0);
1109 with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1110 assert!(b.down, "down flipped back to true");
1111 assert!(b.tracking, "still tracking until MouseUp");
1112 }
1113
1114 /// Consecutive moves inside keep `down` (containment unchanged — the loop
1115 /// body's `if (down != contains)` no-flip path).
1116 #[test]
1117 fn track_no_flip_when_containment_unchanged() {
1118 let mut b = tracked_button();
1119 let mut timers = TimerQueue::new();
1120
1121 let mut ev = mouse_move(3, 0);
1122 with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1123 assert!(b.down);
1124 let mut ev = mouse_move(4, 0);
1125 with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1126 assert!(b.down, "still down on second inside move");
1127 }
1128
1129 /// `MouseUp` while the last tracked state is inside → press fires
1130 /// (RECORD_HISTORY + the posted command), `down`/`tracking` cleared.
1131 #[test]
1132 fn track_release_inside_fires_press() {
1133 let mut b = tracked_button();
1134 let mut timers = TimerQueue::new();
1135
1136 let mut ev = mouse_up(3, 0);
1137 let (out, ()) = with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1138 assert!(ev.is_nothing(), "tracked up is consumed");
1139 assert!(!b.tracking, "tracking ends on MouseUp");
1140 assert!(!b.down, "pressed look cleared");
1141 assert_eq!(
1142 out[0],
1143 Event::Broadcast {
1144 command: Command::RECORD_HISTORY,
1145 source: None
1146 }
1147 );
1148 assert_eq!(out[1], Event::Command(Command::OK));
1149 }
1150
1151 /// `MouseUp` at an INSIDE position after the last move tracked OUTSIDE →
1152 /// no press: the decision uses the LAST MOVE's containment, never the
1153 /// up-event's position (the hold loop never re-reads it).
1154 #[test]
1155 fn track_release_uses_last_move_not_up_position() {
1156 let mut b = tracked_button();
1157 let mut timers = TimerQueue::new();
1158
1159 // Move outside: down = false.
1160 let mut ev = mouse_move(0, 0);
1161 with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1162 assert!(!b.down);
1163
1164 // Up at (3, 0) — inside clickRect, but the up position must be ignored.
1165 let mut ev = mouse_up(3, 0);
1166 let (out, ()) = with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1167 assert!(ev.is_nothing(), "tracked up is consumed even without press");
1168 assert!(!b.tracking);
1169 assert!(out.is_empty(), "no press: last tracked state was outside");
1170 }
1171
1172 /// A stray `MouseUp` with no tracking in flight falls through untouched
1173 /// (the `tracking` guard — MouseUp is not mask-gated in `Group::wants`).
1174 #[test]
1175 fn stray_mouse_up_without_tracking_is_ignored() {
1176 let mut b = Button::new(
1177 Rect::new(0, 0, 10, 2),
1178 "OK",
1179 Command::OK,
1180 ButtonFlags::new(),
1181 );
1182 button_with_id(&mut b);
1183 let mut timers = TimerQueue::new();
1184 let mut ev = mouse_up(3, 0);
1185 let (out, ()) = with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1186 assert!(!ev.is_nothing(), "stray up is not consumed");
1187 assert!(out.is_empty(), "stray up fires nothing");
1188 assert!(!b.down);
1189 }
1190
1191 /// A `bfBroadcast` button pressed via the mouse-track path fires its command
1192 /// as a broadcast carrying its own id — not as an `Event::Command`. The
1193 /// existing `broadcast_button_fires_broadcast_with_source` covers the
1194 /// keyboard/timer path; this covers the mouse path through the real arms
1195 /// (MouseDown inside, then tracked MouseUp inside).
1196 #[test]
1197 fn track_release_fires_broadcast_for_bf_broadcast_button() {
1198 let mut b = Button::new(
1199 Rect::new(0, 0, 10, 2),
1200 "Go",
1201 Command::custom("app.go"),
1202 ButtonFlags {
1203 broadcast: true,
1204 ..Default::default()
1205 },
1206 );
1207 let id = button_with_id(&mut b);
1208 let mut timers = TimerQueue::new();
1209
1210 let mut ev = mouse_down(3, 0);
1211 with_ctx_d(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1212 assert!(b.tracking);
1213
1214 let mut ev = mouse_up(3, 0);
1215 let (out, ()) = with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1216 assert!(!b.down, "pressed look cleared on release");
1217 // press(): RECORD_HISTORY then the BROADCAST (source = our id), no post.
1218 assert_eq!(
1219 out[0],
1220 Event::Broadcast {
1221 command: Command::RECORD_HISTORY,
1222 source: None
1223 }
1224 );
1225 assert_eq!(
1226 out[1],
1227 Event::Broadcast {
1228 command: Command::custom("app.go"),
1229 source: Some(id)
1230 },
1231 "bfBroadcast fires a broadcast carrying the button's id"
1232 );
1233 assert!(
1234 !out.iter().any(|e| matches!(e, Event::Command(_))),
1235 "broadcast, not post"
1236 );
1237 }
1238
1239 // -- behavior: cmDefault ------------------------------------------------
1240
1241 /// cmDefault arms the default button; a non-default button ignores it.
1242 #[test]
1243 fn cm_default_arms_default_button_only() {
1244 let mut default = Button::new(
1245 Rect::new(0, 0, 10, 2),
1246 "OK",
1247 Command::OK,
1248 ButtonFlags {
1249 default: true,
1250 ..Default::default()
1251 },
1252 );
1253 let mut plain = Button::new(
1254 Rect::new(0, 0, 10, 2),
1255 "No",
1256 Command::NO,
1257 ButtonFlags::new(),
1258 );
1259 let mut timers = TimerQueue::new();
1260
1261 let mut ev = Event::Broadcast {
1262 command: Command::DEFAULT,
1263 source: None,
1264 };
1265 with_ctx(&mut timers, 0, |ctx| default.handle_event(&mut ev, ctx));
1266 assert!(ev.is_nothing(), "default button consumes cmDefault");
1267 assert!(default.down);
1268 assert!(default.animation_timer.is_some());
1269
1270 let mut ev = Event::Broadcast {
1271 command: Command::DEFAULT,
1272 source: None,
1273 };
1274 with_ctx(&mut timers, 0, |ctx| plain.handle_event(&mut ev, ctx));
1275 assert!(!ev.is_nothing(), "non-default button leaves cmDefault live");
1276 assert!(plain.animation_timer.is_none());
1277 }
1278
1279 /// A disabled default button does not arm on cmDefault.
1280 #[test]
1281 fn cm_default_ignored_when_disabled() {
1282 let mut b = Button::new(
1283 Rect::new(0, 0, 10, 2),
1284 "OK",
1285 Command::OK,
1286 ButtonFlags {
1287 default: true,
1288 ..Default::default()
1289 },
1290 );
1291 b.state.state.disabled = true;
1292 let mut timers = TimerQueue::new();
1293 let mut ev = Event::Broadcast {
1294 command: Command::DEFAULT,
1295 source: None,
1296 };
1297 with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1298 assert!(!ev.is_nothing());
1299 assert!(b.animation_timer.is_none());
1300 }
1301
1302 // -- behavior: grab/release default -------------------------------------
1303
1304 /// The bfDefault button toggles am_default on GRAB/RELEASE_DEFAULT; the event
1305 /// is NOT consumed (faithful — every default button must see it).
1306 #[test]
1307 fn bf_default_button_reacts_to_grab_release() {
1308 let mut b = Button::new(
1309 Rect::new(0, 0, 10, 2),
1310 "OK",
1311 Command::OK,
1312 ButtonFlags {
1313 default: true,
1314 ..Default::default()
1315 },
1316 );
1317 assert!(b.am_default);
1318 let mut timers = TimerQueue::new();
1319
1320 // GRAB_DEFAULT → another button is taking the default → am_default = false.
1321 let mut ev = Event::Broadcast {
1322 command: Button::GRAB_DEFAULT,
1323 source: None,
1324 };
1325 with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1326 assert!(!b.am_default);
1327 assert!(!ev.is_nothing(), "grab/release is not consumed");
1328
1329 // RELEASE_DEFAULT → take the default back.
1330 let mut ev = Event::Broadcast {
1331 command: Button::RELEASE_DEFAULT,
1332 source: None,
1333 };
1334 with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1335 assert!(b.am_default);
1336 }
1337
1338 /// A non-default button ignores GRAB/RELEASE_DEFAULT entirely.
1339 #[test]
1340 fn non_default_button_ignores_grab_release() {
1341 let mut b = Button::new(
1342 Rect::new(0, 0, 10, 2),
1343 "OK",
1344 Command::OK,
1345 ButtonFlags::new(),
1346 );
1347 assert!(!b.am_default);
1348 let mut timers = TimerQueue::new();
1349 let mut ev = Event::Broadcast {
1350 command: Button::RELEASE_DEFAULT,
1351 source: None,
1352 };
1353 with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1354 assert!(!b.am_default, "non-default button stays non-default");
1355 }
1356
1357 // -- behavior: set_state / make_default ---------------------------------
1358
1359 /// Focusing a NON-default button: base focus broadcast (RECEIVED_FOCUS,
1360 /// source=self) THEN GRAB_DEFAULT (source=self), in that order; am_default
1361 /// becomes true; the focus bit is flipped.
1362 #[test]
1363 fn set_state_focused_non_default_grabs_default() {
1364 let mut b = Button::new(
1365 Rect::new(0, 0, 10, 2),
1366 "OK",
1367 Command::OK,
1368 ButtonFlags::new(),
1369 );
1370 let id = button_with_id(&mut b);
1371 let mut timers = TimerQueue::new();
1372
1373 let (out, ()) = with_ctx(&mut timers, 0, |ctx| {
1374 b.set_state(StateFlag::Focused, true, ctx)
1375 });
1376 assert!(b.state.state.focused, "focus bit flipped (base preserved)");
1377 assert!(
1378 b.am_default,
1379 "non-default button grabs the default on focus"
1380 );
1381 // Order: RECEIVED_FOCUS first, then GRAB_DEFAULT — both source = self.
1382 assert_eq!(
1383 out[0],
1384 Event::Broadcast {
1385 command: Command::RECEIVED_FOCUS,
1386 source: Some(id)
1387 }
1388 );
1389 assert_eq!(
1390 out[1],
1391 Event::Broadcast {
1392 command: Button::GRAB_DEFAULT,
1393 source: Some(id)
1394 }
1395 );
1396 assert_eq!(out.len(), 2);
1397 }
1398
1399 /// Focusing a bfDefault button: the base focus broadcast fires, but
1400 /// makeDefault's guard means NO grab/release broadcast.
1401 #[test]
1402 fn set_state_focused_default_broadcasts_nothing_extra() {
1403 let mut b = Button::new(
1404 Rect::new(0, 0, 10, 2),
1405 "OK",
1406 Command::OK,
1407 ButtonFlags {
1408 default: true,
1409 ..Default::default()
1410 },
1411 );
1412 let id = button_with_id(&mut b);
1413 let mut timers = TimerQueue::new();
1414 let (out, ()) = with_ctx(&mut timers, 0, |ctx| {
1415 b.set_state(StateFlag::Focused, true, ctx)
1416 });
1417 assert!(b.state.state.focused);
1418 assert_eq!(
1419 out,
1420 vec![Event::Broadcast {
1421 command: Command::RECEIVED_FOCUS,
1422 source: Some(id)
1423 }],
1424 "only the base focus broadcast; makeDefault guard blocks grab/release"
1425 );
1426 }
1427
1428 /// A non-Focused set_state (e.g. Active) flips the bit with no broadcast.
1429 #[test]
1430 fn set_state_active_flips_bit_no_broadcast() {
1431 let mut b = Button::new(
1432 Rect::new(0, 0, 10, 2),
1433 "OK",
1434 Command::OK,
1435 ButtonFlags::new(),
1436 );
1437 let mut timers = TimerQueue::new();
1438 let (out, ()) = with_ctx(&mut timers, 0, |ctx| {
1439 b.set_state(StateFlag::Active, true, ctx)
1440 });
1441 assert!(b.state.state.active);
1442 assert!(out.is_empty(), "Active flip emits nothing");
1443 }
1444
1445 // -- grabs_focus_on_click ----------------------------------------------
1446
1447 #[test]
1448 fn grabs_focus_on_click_reflects_flag() {
1449 let plain = Button::new(
1450 Rect::new(0, 0, 10, 2),
1451 "OK",
1452 Command::OK,
1453 ButtonFlags::new(),
1454 );
1455 assert!(!plain.grabs_focus_on_click());
1456 let grab = Button::new(
1457 Rect::new(0, 0, 10, 2),
1458 "OK",
1459 Command::OK,
1460 ButtonFlags {
1461 grab_focus: true,
1462 ..Default::default()
1463 },
1464 );
1465 assert!(grab.grabs_focus_on_click());
1466 }
1467
1468 // -- boundary tests: mouse outside the click rect ----------------------
1469
1470 /// Mouse-down on the bottom shadow row (y=1 for a 10x2 button, which is
1471 /// excluded by `click_rect.b.y = ext.b.y - 1 = 1`) must not press.
1472 #[test]
1473 fn mouse_down_bottom_shadow_row_does_not_press() {
1474 let mut b = Button::new(
1475 Rect::new(0, 0, 10, 2),
1476 "OK",
1477 Command::OK,
1478 ButtonFlags::new(),
1479 );
1480 // click_rect = (1, 0, 9, 1): the half-open y range is 0..1, so y=1 is outside.
1481 let mut timers = TimerQueue::new();
1482 let mut ev = mouse_down(3, 1);
1483 let (out, ()) = with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1484 assert!(ev.is_nothing(), "mouse-down is still consumed");
1485 assert!(out.is_empty(), "bottom shadow row must not press");
1486 }
1487
1488 /// Mouse-down on the right shadow column (x=9 for a 10x2 button, excluded by
1489 /// `click_rect.b.x = ext.b.x - 1 = 9`) must not press.
1490 #[test]
1491 fn mouse_down_right_shadow_col_does_not_press() {
1492 let mut b = Button::new(
1493 Rect::new(0, 0, 10, 2),
1494 "OK",
1495 Command::OK,
1496 ButtonFlags::new(),
1497 );
1498 // click_rect = (1, 0, 9, 1): the half-open x range is 1..9, so x=9 is outside.
1499 let mut timers = TimerQueue::new();
1500 let mut ev = mouse_down(9, 0);
1501 let (out, ()) = with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1502 assert!(ev.is_nothing(), "mouse-down is still consumed");
1503 assert!(out.is_empty(), "right shadow column must not press");
1504 }
1505
1506 // -- tiny-size smoke tests: draw must not panic ------------------------
1507
1508 /// A 1-row button (size.y=1): the body loop `for y in 0..=size.y-2` is
1509 /// `0..=(-1)` in signed terms — with i32 that is an empty range, so it must
1510 /// produce no iterations and complete without panic.
1511 #[test]
1512 fn draw_one_row_does_not_panic() {
1513 let mut b = Button::new(Rect::new(0, 0, 3, 1), "X", Command::OK, ButtonFlags::new());
1514 // Wrapping size: size.y - 2 == -1, loop range 0..=-1 iterates zero times.
1515 // Only the bottom row is drawn; must not panic.
1516 let snap = render(&mut b);
1517 // Just assert we got something (no panic is the real check).
1518 assert!(!snap.is_empty(), "render completed without panic");
1519 }
1520
1521 /// A 1-column button (size.x=1): `s = size.x - 1 = 0`, `t = size.y/2 - 1 = 0`.
1522 /// The `s - cstrlen - 1` centering formula can go negative; `centered.max(1)`
1523 /// keeps `l` ≥ 1, so `put_cstr` is called at x ≥ i+1 which may exceed the
1524 /// buffer width — must complete without panic.
1525 #[test]
1526 fn draw_one_col_does_not_panic() {
1527 let mut b = Button::new(Rect::new(0, 0, 1, 2), "X", Command::OK, ButtonFlags::new());
1528 let snap = render(&mut b);
1529 assert!(!snap.is_empty(), "render completed without panic");
1530 }
1531
1532 // -- command graying via cmCommandSetChanged broadcast ---------------------
1533
1534 /// `cmCommandSetChanged` with the button's command disabled: the button
1535 /// transitions to `state.disabled = true`.
1536 #[test]
1537 fn command_set_changed_grays_button_when_command_disabled() {
1538 let mut b = Button::new(
1539 Rect::new(0, 0, 10, 2),
1540 "OK",
1541 Command::OK,
1542 ButtonFlags::new(),
1543 );
1544 assert!(!b.state.state.disabled, "starts enabled");
1545 let mut timers = TimerQueue::new();
1546
1547 // Deliver a COMMAND_SET_CHANGED broadcast with OK in the disabled set.
1548 let mut ev = Event::Broadcast {
1549 command: Command::COMMAND_SET_CHANGED,
1550 source: None,
1551 };
1552 let (_, _, ()) = with_ctx_d(&mut timers, 0, |ctx| {
1553 // Seed the snapshot: OK is disabled.
1554 let mut ds = crate::command::CommandSet::new();
1555 ds.insert(Command::OK);
1556 ctx.set_disabled_commands(ds);
1557 b.handle_event(&mut ev, ctx)
1558 });
1559 assert!(
1560 b.state.state.disabled,
1561 "button must be disabled when its command is in the disabled set"
1562 );
1563 // The broadcast is NOT consumed (no clearEvent in the C++ arm either).
1564 assert!(
1565 !ev.is_nothing(),
1566 "cmCommandSetChanged is not consumed by the button"
1567 );
1568 }
1569
1570 /// `cmCommandSetChanged` with the button's command re-enabled: the button
1571 /// transitions back to `state.disabled = false` (the un-gray path).
1572 #[test]
1573 fn command_set_changed_ungrays_button_when_command_enabled() {
1574 let mut b = Button::new(
1575 Rect::new(0, 0, 10, 2),
1576 "OK",
1577 Command::OK,
1578 ButtonFlags::new(),
1579 );
1580 // Start disabled.
1581 b.state.state.disabled = true;
1582 let mut timers = TimerQueue::new();
1583
1584 // COMMAND_SET_CHANGED with an empty disabled set: OK is enabled.
1585 let mut ev = Event::Broadcast {
1586 command: Command::COMMAND_SET_CHANGED,
1587 source: None,
1588 };
1589 with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1590 assert!(
1591 !b.state.state.disabled,
1592 "button must be re-enabled when its command is not in the disabled set"
1593 );
1594 }
1595
1596 /// A disabled button does not arm on `cmDefault` (the `!self.state.state.disabled`
1597 /// guard is pre-existing; this test confirms graying + cmDefault interaction).
1598 #[test]
1599 fn grayed_default_button_ignores_cm_default() {
1600 let mut b = Button::new(
1601 Rect::new(0, 0, 10, 2),
1602 "OK",
1603 Command::OK,
1604 ButtonFlags {
1605 default: true,
1606 ..Default::default()
1607 },
1608 );
1609 let mut timers = TimerQueue::new();
1610
1611 // Gray the button via COMMAND_SET_CHANGED.
1612 let mut ev = Event::Broadcast {
1613 command: Command::COMMAND_SET_CHANGED,
1614 source: None,
1615 };
1616 with_ctx_d(&mut timers, 0, |ctx| {
1617 let mut ds = crate::command::CommandSet::new();
1618 ds.insert(Command::OK);
1619 ctx.set_disabled_commands(ds);
1620 b.handle_event(&mut ev, ctx)
1621 });
1622 assert!(b.state.state.disabled);
1623
1624 // cmDefault must not arm the animation.
1625 let mut ev = Event::Broadcast {
1626 command: Command::DEFAULT,
1627 source: None,
1628 };
1629 with_ctx(&mut timers, 0, |ctx| b.handle_event(&mut ev, ctx));
1630 assert!(
1631 !ev.is_nothing(),
1632 "disabled default button leaves cmDefault live"
1633 );
1634 assert!(
1635 b.animation_timer.is_none(),
1636 "no animation on a disabled button"
1637 );
1638 }
1639}