tvision_rs/capture.rs
1//! The capture stack — the single mechanism behind modality, mouse tracking,
2//! window drag/resize, and press-and-hold.
3//!
4//! A **LIFO stack of capture handlers** see each event *before* normal view-tree
5//! routing and may consume it or pass it through. Modality, drag, and
6//! press-tracking are all handlers rather than nested loops: a modal handler that
7//! consumes every otherwise-unhandled event *is* the modal loop. Handlers hold a
8//! [`ViewId`], never a view reference. The live event loop in
9//! [`Program`](crate::app::Program) owns this stack and drives
10//! [`CaptureStack::dispatch`]; the `tests` module here hand-plays the loop to
11//! prove the protocol composes.
12//!
13//! **Guide:** [Event capture](../../../port/capture.html).
14//!
15//! # Turbo Vision heritage
16//! Turbo Vision implements modality, view dragging, and a pressed button's
17//! mouse-tracking by spinning *nested* blocking event loops (`tgroup.cpp`,
18//! `tview.cpp`). Rust cannot nest a blocking loop that re-borrows the view tree,
19//! so tvision-rs collapses all of them into one non-recursive event loop plus this LIFO
20//! capture stack (deviation D9). Handlers hold a [`ViewId`] rather than a view
21//! pointer (deviation D3).
22
23use crate::event::Event;
24use crate::view::{Context, Point, Rect, ViewId};
25
26/// What a capture handler did with an event it was offered.
27///
28/// The return value is **authoritative** for routing — handlers must *not* rely
29/// on [`Event::clear`] to signal "consumed" to the capture stack (clearing is a
30/// separate downstream concern handled by normal view routing).
31///
32/// # Turbo Vision heritage
33/// Makes explicit the consumed-vs-passed convention that Turbo Vision encodes
34/// implicitly by clearing the event in place (`tview.cpp`); the self-removing
35/// [`ConsumedPop`](CaptureFlow::ConsumedPop) variant replaces a nested modal
36/// loop returning from its `execute` (deviation D9).
37#[derive(Debug)]
38pub enum CaptureFlow {
39 /// Did not handle the event — offer it to the next (lower) handler, and
40 /// then to normal view-tree routing if every handler passes.
41 Pass,
42 /// Handled the event; stop routing. The handler stays on the stack.
43 Consumed,
44 /// Handled the event **and** removes ITSELF from the stack (e.g. a modal
45 /// dialog closing). Unambiguous: "pop" always means the handler that just
46 /// ran.
47 ConsumedPop,
48}
49
50/// A capture handler — a participant in the capture stack that stands in for a
51/// nested modal/drag/press loop.
52///
53/// Handlers are offered each event before normal view-tree routing. Identity is
54/// a [`ViewId`]: a handler never holds a view reference.
55///
56/// # Turbo Vision heritage
57/// Replaces the nested blocking loops Turbo Vision spins for modality, view
58/// dragging, and a held button's mouse-tracking (`tgroup.cpp`, `tview.cpp`),
59/// folding them into one event loop plus stacked handlers (deviation D9). Each
60/// handler holds a [`ViewId`] instead of a view pointer (deviation D3).
61pub trait CaptureHandler {
62 /// Offered an event before normal routing. May read/mutate `ctx` (post
63 /// commands, schedule timers, push a *nested* capture via
64 /// [`Context::push_capture`]).
65 ///
66 /// The returned [`CaptureFlow`] is **authoritative** for routing — do *not*
67 /// rely on `Event::clear()` to signal "consumed" to the capture stack.
68 fn handle(&mut self, ev: &mut Event, ctx: &mut Context) -> CaptureFlow;
69
70 /// The view this handler is associated with, if any. Identity is [`ViewId`].
71 fn view(&self) -> Option<ViewId> {
72 None
73 }
74
75 /// Returns `true` if this handler is a modal-bounds gate (a [`ModalFrame`](crate::app::ModalFrame)
76 /// equivalent). Used by the pump's outside-modal redirect to distinguish a
77 /// true modal frame from other capture handlers that also have a `view()`
78 /// (drag, menu-box, etc.). **Default is `false`** — only `ModalFrame`
79 /// overrides this.
80 fn is_modal_gate(&self) -> bool {
81 false
82 }
83
84 /// Returns the help context of the currently highlighted menu item, if this
85 /// handler is a [`MenuSession`](crate::menu::MenuSession).
86 ///
87 /// Used by the status-line refresh to surface per-item help context while a
88 /// menu is open. **Default is `None`** — only `MenuSession` overrides this.
89 fn menu_help_ctx(&self) -> Option<crate::help::HelpCtx> {
90 None
91 }
92
93 /// Update the handler's cached gating bounds for its associated view, called
94 /// by [`CaptureStack::sync_gate_bounds`] before each dispatch so a handler
95 /// that gates events by the view's *position* (e.g. a modal frame) follows
96 /// the view when it is moved/resized (a dragged dialog).
97 ///
98 /// **Default is a no-op** — only a handler that gates by bounds overrides it.
99 /// In particular a drag handler must NOT override it: its grab anchor /
100 /// initial bounds are fixed for the duration of the drag and resyncing them
101 /// from the (live, moving) tree would corrupt the drag math.
102 fn set_gate_bounds(&mut self, _bounds: Rect) {}
103}
104
105// ---------------------------------------------------------------------------
106// MouseTrackCapture — the mouse hold-tracking seam
107// ---------------------------------------------------------------------------
108
109/// Which mouse event classes the hold-tracker forwards to its view while a
110/// button is held (everything else is discarded until the terminating
111/// [`MouseUp`](crate::event::Event::MouseUp)).
112///
113/// Different widgets opt into different subsets: a button or list viewer wants
114/// only moves; a scrollbar, editor, or menu wants moves plus auto-repeat; a
115/// frame wants every mouse class including the wheel. This struct-of-bools
116/// names each forwarded class.
117///
118/// # Turbo Vision heritage
119/// The idiomatic form of the `evMouse*` bit-mask `mouseEvent` accepted in
120/// `tview.cpp`: `mouse_move` ↔ `evMouseMove`, `mouse_auto` ↔ `evMouseAuto`,
121/// `wheel` ↔ the `evMouseWheel` slice of `evMouse`.
122#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
123pub struct TrackMask {
124 /// Forward [`MouseMove`](crate::event::Event::MouseMove) to the tracked view.
125 pub mouse_move: bool,
126 /// Forward [`MouseAuto`](crate::event::Event::MouseAuto) (auto-repeat while held).
127 pub mouse_auto: bool,
128 /// Forward [`MouseWheel`](crate::event::Event::MouseWheel) events.
129 pub wheel: bool,
130}
131
132/// The hold-tracking router: while a mouse button is held, it localizes and
133/// forwards masked mouse events to the tracked view, swallows everything else,
134/// and pops on [`MouseUp`](crate::event::Event::MouseUp) (forwarding the
135/// localized up too — a button/frame reads the up position after the hold ends).
136///
137/// **A pure router, not a strategy.** The per-event handling logic stays in the
138/// widgets (their `MouseMove`/`MouseAuto` arms run while held, their `MouseUp`
139/// arm runs once at release): captures are `'static` and hold no view borrow,
140/// and several tracked views ([`ListViewer`](crate::widgets::ListViewer),
141/// [`Outline`](crate::widgets::Outline)) are trait objects the pump could not
142/// downcast — so the capture only routes, via
143/// [`Deferred::MouseTrack`](crate::view::Deferred), which the pump applies by
144/// calling the view's `handle_event` directly. Pushed via
145/// [`Context::start_mouse_track`]; because a capture push is itself applied
146/// through the deferred channel, the capture sees the **next** event — so the
147/// widget runs its handling once on the press before the first forwarded event.
148///
149/// `origin` is the absolute screen position of view-local `(0, 0)`, cached by
150/// the widget's last `draw` at push time (the `Button::abs_origin` pattern).
151/// Like the window drag capture, the
152/// origin is fixed for the duration of the hold: if the tracked view is moved /
153/// resized mid-hold the localization goes stale — acceptable, since a hold is
154/// short-lived and nothing moves the view while the (modal) hold swallows all
155/// other input.
156///
157/// # Turbo Vision heritage
158/// Replaces the blocking mouse-hold loop `do { … } while (mouseEvent(event,
159/// mask))` (`tview.cpp:636-643`; the cluster/frame post-loop reads at
160/// `tcluster.cpp:181-184` / `tframe.cpp:159-160`) with a capture handler
161/// (deviation D9) that routes via the deferred channel instead of holding a view
162/// borrow (deviation D3). The `do{}while` running its body once before the first
163/// wait is why the capture is applied deferred (sees the next event).
164pub struct MouseTrackCapture {
165 /// The view being tracked (identity only, per the capture contract).
166 view: ViewId,
167 /// Absolute screen position of view-local `(0, 0)` at push time.
168 origin: Point,
169 /// Which event classes to forward (the tracked-event mask).
170 mask: TrackMask,
171}
172
173impl MouseTrackCapture {
174 /// Build a tracker for `view`. Constructed only by
175 /// [`Context::start_mouse_track`] (widgets never build one directly).
176 pub(crate) fn new(view: ViewId, origin: Point, mask: TrackMask) -> Self {
177 MouseTrackCapture { view, origin, mask }
178 }
179}
180
181impl CaptureHandler for MouseTrackCapture {
182 fn handle(&mut self, ev: &mut Event, ctx: &mut Context) -> CaptureFlow {
183 /// Localize an absolute-position mouse record against the push-time origin.
184 fn localize(m: &crate::event::MouseEvent, origin: Point) -> crate::event::MouseEvent {
185 let mut local = *m;
186 local.position -= origin;
187 local
188 }
189 match ev {
190 Event::MouseMove(m) if self.mask.mouse_move => {
191 ctx.request_mouse_track(self.view, Event::MouseMove(localize(m, self.origin)));
192 CaptureFlow::Consumed
193 }
194 Event::MouseAuto(m) if self.mask.mouse_auto => {
195 ctx.request_mouse_track(self.view, Event::MouseAuto(localize(m, self.origin)));
196 CaptureFlow::Consumed
197 }
198 // Mouse-wheel events (see `crossterm_backend`) — the wheel slice of
199 // the tracked-event mask (the frame's hold loop).
200 Event::MouseWheel(m) if self.mask.wheel => {
201 ctx.request_mouse_track(self.view, Event::MouseWheel(localize(m, self.origin)));
202 CaptureFlow::Consumed
203 }
204 // A mouse-up always ends the hold (it is implicitly always tracked):
205 // forward the localized up — cluster/frame read its position
206 // post-loop — and pop this handler.
207 Event::MouseUp(m) => {
208 ctx.request_mouse_track(self.view, Event::MouseUp(localize(m, self.origin)));
209 CaptureFlow::ConsumedPop
210 }
211 // Broadcasts pass THROUGH to normal routing (like `ModalFrame`).
212 // A broadcast is a synchronous notification, not a queued input
213 // event — the original hold loop only ever consumed queued input, so
214 // it never saw a broadcast to discard. tvision-rs delivers that notification
215 // as a queued `Event::Broadcast`, so to stay faithful the hold must let
216 // it pass — otherwise a scrollbar-changed broadcast emitted by the very
217 // bar being dragged (its own value update → redraw) is swallowed and
218 // the editor/scroller never scrolls. (The bug this fixes: dragging a
219 // scrollbar did not move the associated text.)
220 Event::Broadcast { .. } => CaptureFlow::Pass,
221 // Everything else (unmasked mouse classes, keys, commands) is
222 // discarded until the mouse-up, as the C++ hold loop discards what
223 // its `getEvent` returns outside the mask. Timer expiries never get
224 // here: the pump routes them around the capture stack, because C++
225 // delivers them from `idle` inside that same `getEvent`.
226 _ => CaptureFlow::Consumed,
227 }
228 }
229
230 fn view(&self) -> Option<ViewId> {
231 Some(self.view)
232 }
233}
234
235/// A LIFO stack of [`CaptureHandler`]s.
236///
237/// The most-recently pushed handler is offered events first. The live event loop
238/// in [`Program`](crate::app::Program) owns this stack and drives
239/// [`dispatch`](Self::dispatch); a handler that wants to push a nested capture
240/// does so through [`Context::push_capture`], whose deferred queue the loop
241/// applies *after* dispatch — so the stack is never aliased while a handler runs.
242///
243/// # Turbo Vision heritage
244/// Has no direct analogue as a data structure: it replaces the nesting of
245/// blocking event loops Turbo Vision uses for modality, drag, and press-tracking
246/// with one non-recursive loop plus this stack (deviation D9).
247#[derive(Default)]
248pub struct CaptureStack {
249 handlers: Vec<Box<dyn CaptureHandler>>,
250}
251
252impl CaptureStack {
253 /// An empty capture stack.
254 pub fn new() -> Self {
255 CaptureStack {
256 handlers: Vec::new(),
257 }
258 }
259
260 /// Push a handler onto the top of the stack (it will see events first).
261 pub fn push(&mut self, handler: Box<dyn CaptureHandler>) {
262 self.handlers.push(handler);
263 }
264
265 /// Refresh every handler's gating bounds from the live tree before a dispatch.
266 ///
267 /// For each handler associated with a view ([`CaptureHandler::view`]), resolve
268 /// that view's current bounds via `resolve` and push them down through
269 /// [`CaptureHandler::set_gate_bounds`]. A bounds-gating handler (a modal frame)
270 /// thus follows its view when it is dragged/resized; a handler that does not
271 /// override `set_gate_bounds` (a drag handler) is unaffected. The loop owns the
272 /// stack, so this is the loop's responsibility, not a handler's.
273 pub fn sync_gate_bounds(&mut self, mut resolve: impl FnMut(ViewId) -> Option<Rect>) {
274 for h in &mut self.handlers {
275 if let Some(id) = h.view()
276 && let Some(bounds) = resolve(id)
277 {
278 h.set_gate_bounds(bounds);
279 }
280 }
281 }
282
283 /// Remove and return the top handler, if any. Used by
284 /// [`Program::exec_view`](crate::app::Program::exec_view) to remove the
285 /// [`ModalFrame`](crate::app::ModalFrame) it pushed once the modal loop ends —
286 /// the **one** place a frame is popped other than a handler self-popping via
287 /// [`CaptureFlow::ConsumedPop`]. (The loop owns the stack; a handler cannot
288 /// reach it to do a `valid(end_state)`-conditional pop, so the owner-side
289 /// `exec_view` does it.)
290 pub fn pop(&mut self) -> Option<Box<dyn CaptureHandler>> {
291 self.handlers.pop()
292 }
293
294 /// Number of handlers currently on the stack.
295 pub fn len(&self) -> usize {
296 self.handlers.len()
297 }
298
299 /// Whether the stack has no handlers.
300 pub fn is_empty(&self) -> bool {
301 self.handlers.is_empty()
302 }
303
304 /// Returns the [`ViewId`] of the innermost executing modal view: the
305 /// topmost modal gate ([`CaptureHandler::is_modal_gate`]) on the stack,
306 /// even when a drag or menu handler sits above it. `None` when no modal
307 /// view executes. The pump routes focused events to this view, as C++
308 /// `TGroup::execute` hands them to the modal view's own `handleEvent`.
309 pub fn modal_view(&self) -> Option<ViewId> {
310 self.handlers
311 .iter()
312 .rev()
313 .find(|h| h.is_modal_gate())
314 .and_then(|h| h.view())
315 }
316
317 /// Returns the [`ViewId`] of the top capture handler only when it is a
318 /// modal-bounds gate ([`CaptureHandler::is_modal_gate`] == `true`).
319 /// Used by the pump's outside-modal redirect to avoid firing on drag or
320 /// menu-box handlers that also carry a `view()`.
321 pub fn top_modal_view(&self) -> Option<ViewId> {
322 self.handlers
323 .last()
324 .and_then(|h| if h.is_modal_gate() { h.view() } else { None })
325 }
326
327 /// Returns the help context from an active [`MenuSession`](crate::menu::MenuSession) on the stack, if
328 /// any. Consults **only the topmost handler**: a menu preempts the help
329 /// context iff it is the topmost capture handler, matching C++
330 /// `TopView()->getHelpCtx()` where `TopView()` is the active `TMenuView`.
331 /// Checking only the top handler avoids a scan that would let a menu sitting
332 /// *below* a dialog wrongly win.
333 ///
334 /// Used by the status-line refresh to surface per-item help while a menu is
335 /// open, without disturbing the existing `top_modal_view` path.
336 pub fn active_menu_help_ctx(&self) -> Option<crate::help::HelpCtx> {
337 self.handlers.last().and_then(|h| h.menu_help_ctx())
338 }
339
340 /// Offer `ev` to the handlers top-down (last pushed first).
341 ///
342 /// - [`CaptureFlow::Pass`] → continue to the next lower handler;
343 /// - [`CaptureFlow::Consumed`] → stop, return `true`;
344 /// - [`CaptureFlow::ConsumedPop`] → remove *that* handler, stop, return
345 /// `true`.
346 ///
347 /// Returns `false` if every handler passed (the loop then runs normal
348 /// view-tree routing).
349 ///
350 /// A handler may push a nested capture during its `handle` call — but that
351 /// goes into [`Context`]'s separate deferred queue, never into
352 /// `self.handlers`, so there is no aliasing of the stack. The `ConsumedPop`
353 /// removal happens *after* `handle` returns (NLL releases the index borrow
354 /// at the end of the call expression).
355 pub fn dispatch(&mut self, ev: &mut Event, ctx: &mut Context) -> bool {
356 for i in (0..self.handlers.len()).rev() {
357 match self.handlers[i].handle(ev, ctx) {
358 CaptureFlow::Pass => {}
359 CaptureFlow::Consumed => return true,
360 CaptureFlow::ConsumedPop => {
361 self.handlers.remove(i);
362 return true;
363 }
364 }
365 }
366 false
367 }
368}
369
370#[cfg(test)]
371mod tests {
372 use super::*;
373 use crate::command::Command;
374 use crate::event::{Event, Key, KeyEvent};
375 use crate::timer::TimerQueue;
376 use crate::view::Context;
377 use std::cell::RefCell;
378 use std::collections::VecDeque;
379 use std::rc::Rc;
380 use std::time::Duration;
381
382 /// A test handler that records every event it is offered and returns a
383 /// configured [`CaptureFlow`].
384 struct Recorder {
385 log: Rc<RefCell<Vec<Event>>>,
386 flow: fn() -> CaptureFlow,
387 }
388
389 impl Recorder {
390 fn new(log: Rc<RefCell<Vec<Event>>>, flow: fn() -> CaptureFlow) -> Self {
391 Recorder { log, flow }
392 }
393 }
394
395 impl CaptureHandler for Recorder {
396 fn handle(&mut self, ev: &mut Event, _ctx: &mut Context) -> CaptureFlow {
397 self.log.borrow_mut().push(ev.clone());
398 (self.flow)()
399 }
400 }
401
402 /// A handler that, on its first (and every) event, pushes another handler
403 /// via the deferred `ctx.push_capture` queue, then consumes the event.
404 struct Pusher {
405 /// The recorder log the pushed handler will write to.
406 pushed_log: Rc<RefCell<Vec<Event>>>,
407 /// Set once we've pushed, so we only push a single nested handler.
408 pushed: bool,
409 }
410
411 impl CaptureHandler for Pusher {
412 fn handle(&mut self, _ev: &mut Event, ctx: &mut Context) -> CaptureFlow {
413 if !self.pushed {
414 // Exercise the full `ctx.*` surface *during dispatch*, exactly as
415 // the doc contract on `CaptureHandler::handle` promises a handler
416 // may: post / broadcast / schedule a timer / push a nested capture.
417 ctx.post(Command::OK);
418 ctx.broadcast(Command::COMMAND_SET_CHANGED, None);
419 let _tid = ctx.set_timer(Duration::from_millis(50), None);
420 let inner = Recorder::new(self.pushed_log.clone(), || CaptureFlow::Consumed);
421 ctx.push_capture(Box::new(inner));
422 self.pushed = true;
423 }
424 CaptureFlow::Consumed
425 }
426 }
427
428 fn key_event(k: Key) -> Event {
429 Event::KeyDown(KeyEvent::from(k))
430 }
431
432 // -- per-piece protocol facts -------------------------------------------
433
434 #[test]
435 fn pass_lets_lower_handler_see_event() {
436 let lower_log = Rc::new(RefCell::new(Vec::new()));
437 let upper_log = Rc::new(RefCell::new(Vec::new()));
438
439 let mut stack = CaptureStack::new();
440 // lower pushed first -> seen last
441 stack.push(Box::new(Recorder::new(lower_log.clone(), || {
442 CaptureFlow::Consumed
443 })));
444 stack.push(Box::new(Recorder::new(upper_log.clone(), || {
445 CaptureFlow::Pass
446 })));
447
448 let mut out = VecDeque::new();
449 let mut timers = TimerQueue::new();
450 let mut deferred: Vec<crate::view::Deferred> = Vec::new();
451 let mut ev = key_event(Key::Enter);
452
453 let consumed = {
454 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
455 stack.dispatch(&mut ev, &mut ctx)
456 };
457 for effect in deferred.drain(..) {
458 if let crate::view::Deferred::PushCapture(h) = effect {
459 stack.push(h);
460 }
461 }
462
463 // Upper passed, lower consumed.
464 assert!(consumed);
465 assert_eq!(upper_log.borrow().len(), 1, "upper handler saw the event");
466 assert_eq!(
467 lower_log.borrow().len(),
468 1,
469 "lower handler saw it after Pass"
470 );
471 // Both still on the stack (Pass + Consumed neither pop).
472 assert_eq!(stack.len(), 2);
473 }
474
475 #[test]
476 fn consumed_stops_routing_and_stays() {
477 let lower_log = Rc::new(RefCell::new(Vec::new()));
478 let upper_log = Rc::new(RefCell::new(Vec::new()));
479
480 let mut stack = CaptureStack::new();
481 stack.push(Box::new(Recorder::new(lower_log.clone(), || {
482 CaptureFlow::Consumed
483 })));
484 stack.push(Box::new(Recorder::new(upper_log.clone(), || {
485 CaptureFlow::Consumed
486 })));
487
488 let mut out = VecDeque::new();
489 let mut timers = TimerQueue::new();
490 let mut deferred: Vec<crate::view::Deferred> = Vec::new();
491 let mut ev = key_event(Key::Esc);
492
493 let consumed = {
494 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
495 stack.dispatch(&mut ev, &mut ctx)
496 };
497 for effect in deferred.drain(..) {
498 if let crate::view::Deferred::PushCapture(h) = effect {
499 stack.push(h);
500 }
501 }
502
503 assert!(consumed);
504 assert_eq!(upper_log.borrow().len(), 1, "upper consumed it");
505 assert_eq!(
506 lower_log.borrow().len(),
507 0,
508 "lower never saw it (routing stopped)"
509 );
510 assert_eq!(stack.len(), 2, "Consumed keeps the handler on the stack");
511 }
512
513 #[test]
514 fn consumed_pop_removes_handler() {
515 let log = Rc::new(RefCell::new(Vec::new()));
516
517 let mut stack = CaptureStack::new();
518 stack.push(Box::new(Recorder::new(log.clone(), || {
519 CaptureFlow::ConsumedPop
520 })));
521 assert_eq!(stack.len(), 1);
522
523 let mut out = VecDeque::new();
524 let mut timers = TimerQueue::new();
525 let mut deferred: Vec<crate::view::Deferred> = Vec::new();
526
527 // First event: consumed-and-popped.
528 let mut ev1 = key_event(Key::Enter);
529 let consumed1 = {
530 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
531 stack.dispatch(&mut ev1, &mut ctx)
532 };
533 for effect in deferred.drain(..) {
534 if let crate::view::Deferred::PushCapture(h) = effect {
535 stack.push(h);
536 }
537 }
538 assert!(consumed1);
539 assert_eq!(stack.len(), 0, "ConsumedPop removed the handler");
540 assert_eq!(log.borrow().len(), 1);
541
542 // Second event: the popped handler must not see it (stack empty -> false).
543 let mut ev2 = key_event(Key::Esc);
544 let consumed2 = {
545 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
546 stack.dispatch(&mut ev2, &mut ctx)
547 };
548 for effect in deferred.drain(..) {
549 if let crate::view::Deferred::PushCapture(h) = effect {
550 stack.push(h);
551 }
552 }
553 assert!(!consumed2, "no handler left to consume");
554 assert_eq!(
555 log.borrow().len(),
556 1,
557 "popped handler did not see the later event"
558 );
559 }
560
561 // -- the full compose test ----------------------------------------------
562
563 #[test]
564 fn compose_full_protocol() {
565 // Loop-owned state as locals, exactly as the real event loop holds it.
566 let mut out: VecDeque<Event> = VecDeque::new();
567 let mut timers = TimerQueue::new();
568 let mut deferred: Vec<crate::view::Deferred> = Vec::new();
569
570 let pushed_log = Rc::new(RefCell::new(Vec::new()));
571
572 let mut stack = CaptureStack::new();
573 // Bottom of the stack: a Pusher that defers a nested handler then consumes.
574 stack.push(Box::new(Pusher {
575 pushed_log: pushed_log.clone(),
576 pushed: false,
577 }));
578
579 // -- Event 1: drives the Pusher. ------------------------------------
580 // `Pusher::handle` itself posts/broadcasts/schedules a timer and pushes a
581 // nested capture during dispatch (the `ctx.*` handler contract); we assert
582 // those side effects landed in the loop-owned state afterward.
583 let mut ev1 = key_event(Key::Char('a'));
584 let consumed1 = {
585 let mut ctx = Context::new(&mut out, &mut timers, 1_000, &mut deferred);
586 assert_eq!(ctx.now_ms(), 1_000);
587 stack.dispatch(&mut ev1, &mut ctx)
588 };
589 // The deferred push is still in `deferred` and has NOT been applied yet.
590 assert_eq!(deferred.len(), 1, "push_capture deferred the handler");
591 assert_eq!(
592 pushed_log.borrow().len(),
593 0,
594 "pushed handler must NOT see the current event"
595 );
596 assert!(consumed1, "Pusher consumed event 1");
597
598 // The loop applies deferred pushes AFTER dispatch.
599 for effect in deferred.drain(..) {
600 if let crate::view::Deferred::PushCapture(h) = effect {
601 stack.push(h);
602 }
603 }
604 assert_eq!(stack.len(), 2, "nested handler now on the stack");
605
606 // post / broadcast landed in out_events.
607 assert_eq!(out.len(), 2);
608 assert_eq!(out[0], Event::Command(Command::OK));
609 assert_eq!(
610 out[1],
611 Event::Broadcast {
612 command: Command::COMMAND_SET_CHANGED,
613 source: None
614 }
615 );
616 // set_timer registered in the queue.
617 assert_eq!(timers.len(), 1);
618
619 // -- Event 2: the nested handler (top of stack) now sees it. --------
620 let mut ev2 = key_event(Key::Char('b'));
621 let consumed2 = {
622 let mut ctx = Context::new(&mut out, &mut timers, 1_050, &mut deferred);
623 stack.dispatch(&mut ev2, &mut ctx)
624 };
625 for effect in deferred.drain(..) {
626 if let crate::view::Deferred::PushCapture(h) = effect {
627 stack.push(h);
628 }
629 }
630 assert!(consumed2);
631 assert_eq!(
632 pushed_log.borrow().len(),
633 1,
634 "pushed handler saw the NEXT event after the deferred push was applied"
635 );
636 assert_eq!(pushed_log.borrow()[0], key_event(Key::Char('b')));
637 }
638
639 // -- MouseTrackCapture (the hold-tracking router) ----------------------
640
641 use crate::event::{MouseButtons, MouseEvent, MouseWheel};
642 use crate::view::Deferred;
643
644 /// Origin used by all router tests: view-local (0,0) sits at abs (5,3).
645 const ORIGIN: Point = Point::new(5, 3);
646
647 fn track_stack(mask: TrackMask) -> (CaptureStack, ViewId) {
648 let id = ViewId::next();
649 let mut stack = CaptureStack::new();
650 stack.push(Box::new(MouseTrackCapture::new(id, ORIGIN, mask)));
651 (stack, id)
652 }
653
654 fn mouse_record(x: i32, y: i32) -> MouseEvent {
655 MouseEvent {
656 position: Point::new(x, y),
657 buttons: MouseButtons {
658 left: true,
659 ..Default::default()
660 },
661 ..Default::default()
662 }
663 }
664
665 /// Dispatch one event through the stack, returning (consumed, deferred).
666 fn play(stack: &mut CaptureStack, mut ev: Event) -> (bool, Vec<crate::view::Deferred>) {
667 let mut out = VecDeque::new();
668 let mut timers = TimerQueue::new();
669 let mut deferred: Vec<crate::view::Deferred> = Vec::new();
670 let consumed = {
671 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
672 stack.dispatch(&mut ev, &mut ctx)
673 };
674 (consumed, deferred)
675 }
676
677 /// A masked `MouseMove` is forwarded as a **localized** `Deferred::MouseTrack`
678 /// payload; the handler stays on the stack (`Consumed`).
679 #[test]
680 fn track_masked_move_forwards_localized() {
681 let (mut stack, id) = track_stack(TrackMask {
682 mouse_move: true,
683 ..Default::default()
684 });
685 let (consumed, deferred) = play(&mut stack, Event::MouseMove(mouse_record(8, 4)));
686 assert!(consumed);
687 assert_eq!(stack.len(), 1, "Consumed keeps the tracker on the stack");
688 assert_eq!(deferred.len(), 1);
689 match &deferred[0] {
690 Deferred::MouseTrack {
691 view,
692 event: Event::MouseMove(m),
693 } => {
694 assert_eq!(*view, id);
695 assert_eq!(m.position, Point::new(3, 1), "abs (8,4) − origin (5,3)");
696 }
697 _ => panic!("expected a localized MouseTrack MouseMove"),
698 }
699 }
700
701 /// A masked `MouseAuto` forwards localized, like the move.
702 #[test]
703 fn track_masked_auto_forwards_localized() {
704 let (mut stack, id) = track_stack(TrackMask {
705 mouse_auto: true,
706 ..Default::default()
707 });
708 let (consumed, deferred) = play(&mut stack, Event::MouseAuto(mouse_record(6, 3)));
709 assert!(consumed);
710 assert_eq!(deferred.len(), 1);
711 match &deferred[0] {
712 Deferred::MouseTrack {
713 view,
714 event: Event::MouseAuto(m),
715 } => {
716 assert_eq!(*view, id);
717 assert_eq!(m.position, Point::new(1, 0));
718 }
719 _ => panic!("expected a localized MouseTrack MouseAuto"),
720 }
721 }
722
723 /// An UNmasked mouse class is swallowed without forwarding (the hold is
724 /// modal — only masked classes and the terminating up reach the view).
725 #[test]
726 fn track_unmasked_classes_are_swallowed() {
727 let (mut stack, _id) = track_stack(TrackMask {
728 mouse_move: true,
729 ..Default::default()
730 });
731 // MouseAuto not in the mask: consumed, nothing forwarded.
732 let (consumed, deferred) = play(&mut stack, Event::MouseAuto(mouse_record(8, 4)));
733 assert!(consumed, "unmasked auto is still consumed (modal hold)");
734 assert!(deferred.is_empty(), "…but not forwarded");
735 assert_eq!(stack.len(), 1);
736 }
737
738 /// An `evMouseWheel` event forwards only under `mask.wheel`; a real-button
739 /// `MouseDown` is swallowed regardless.
740 #[test]
741 fn track_wheel_event_respects_wheel_mask() {
742 // wheel-masked: forwarded localized.
743 let (mut stack, id) = track_stack(TrackMask {
744 wheel: true,
745 ..Default::default()
746 });
747 let wheel_down = Event::MouseWheel(MouseEvent {
748 position: Point::new(7, 5),
749 wheel: MouseWheel::Up,
750 ..Default::default()
751 });
752 let (consumed, deferred) = play(&mut stack, wheel_down);
753 assert!(consumed);
754 assert_eq!(deferred.len(), 1);
755 match &deferred[0] {
756 Deferred::MouseTrack {
757 view,
758 event: Event::MouseWheel(m),
759 } => {
760 assert_eq!(*view, id);
761 assert_eq!(m.position, Point::new(2, 2));
762 assert_eq!(m.wheel, MouseWheel::Up);
763 }
764 _ => panic!("expected a localized MouseTrack wheel event"),
765 }
766
767 // A real-button down is swallowed even with mask.wheel.
768 let (consumed, deferred) = play(&mut stack, Event::MouseDown(mouse_record(7, 5)));
769 assert!(consumed);
770 assert!(deferred.is_empty(), "buttoned down is not a wheel event");
771
772 // Without mask.wheel the wheel is swallowed too.
773 let (mut stack, _id) = track_stack(TrackMask::default());
774 let wheel_down = Event::MouseWheel(MouseEvent {
775 wheel: MouseWheel::Down,
776 ..Default::default()
777 });
778 let (consumed, deferred) = play(&mut stack, wheel_down);
779 assert!(consumed);
780 assert!(deferred.is_empty());
781 }
782
783 /// A `Broadcast` during the hold PASSES THROUGH (not consumed) so normal
784 /// routing delivers it to the tree. A broadcast is a synchronous notification,
785 /// not queued input, so the hold must not swallow it. This is what lets a
786 /// scrollbar being dragged notify the editor/scroller (its value-changed
787 /// broadcast) so the text scrolls.
788 #[test]
789 fn track_broadcast_passes_through() {
790 let (mut stack, _id) = track_stack(TrackMask {
791 mouse_move: true,
792 mouse_auto: true,
793 wheel: true,
794 });
795 let bcast = Event::Broadcast {
796 command: Command::COMMAND_SET_CHANGED,
797 source: None,
798 };
799 let (consumed, deferred) = play(&mut stack, bcast);
800 assert!(
801 !consumed,
802 "broadcast passes through the hold (C++ message() bypasses the loop)"
803 );
804 assert!(
805 deferred.is_empty(),
806 "the tracker forwards nothing for a broadcast"
807 );
808 assert_eq!(stack.len(), 1, "tracker stays on the stack until MouseUp");
809 }
810
811 /// A `KeyDown` during the hold vanishes: consumed, nothing forwarded
812 /// (everything outside `mask | evMouseUp` is discarded, tview.cpp:636).
813 #[test]
814 fn track_key_down_vanishes() {
815 let (mut stack, _id) = track_stack(TrackMask {
816 mouse_move: true,
817 mouse_auto: true,
818 wheel: true,
819 });
820 let (consumed, deferred) = play(&mut stack, key_event(Key::Char('x')));
821 assert!(consumed, "key is swallowed (hold is modal)");
822 assert!(deferred.is_empty(), "nothing forwarded for a key");
823 assert_eq!(stack.len(), 1, "tracker stays until MouseUp");
824 }
825
826 /// `MouseUp` pops the tracker AND forwards the localized up (cluster/frame
827 /// read the up position post-loop) — regardless of the mask.
828 #[test]
829 fn track_mouse_up_pops_and_forwards() {
830 let (mut stack, id) = track_stack(TrackMask::default());
831 let up = Event::MouseUp(MouseEvent {
832 position: Point::new(9, 4),
833 ..Default::default()
834 });
835 let (consumed, deferred) = play(&mut stack, up);
836 assert!(consumed);
837 assert_eq!(stack.len(), 0, "MouseUp pops the tracker");
838 assert_eq!(deferred.len(), 1);
839 match &deferred[0] {
840 Deferred::MouseTrack {
841 view,
842 event: Event::MouseUp(m),
843 } => {
844 assert_eq!(*view, id);
845 assert_eq!(m.position, Point::new(4, 1), "localized up position");
846 }
847 _ => panic!("expected a localized MouseTrack MouseUp"),
848 }
849 }
850}