tvision_rs/event/mod.rs
1//! Events — the [`Event`] enum and the key/mouse records that fill it.
2//!
3//! [`Event`] is the sum type a [`View`](crate::view::View) matches arm-by-arm:
4//! mouse presses/releases/moves/wheel, key presses, commands, broadcasts,
5//! timer expiries, and paste. The keyboard side lives in the `key` submodule
6//! ([`Key`], [`KeyEvent`], [`KeyModifiers`]); the mouse record ([`MouseEvent`])
7//! and the [`EventMask`] opt-in for expensive event classes live here.
8//!
9//! Two events carry payloads worth naming up front. [`Event::Broadcast`] adds
10//! an optional **`source: ViewId`** naming *which view the broadcast is about*
11//! (e.g. which scrollbar changed) — a resolvable handle, `None` for broadcasts
12//! about no particular view. [`Event::Timer`] carries *which* [`TimerId`]
13//! expired.
14//!
15//! One primitive is deliberately not reproduced: a synchronous, return-valued
16//! message round-trip (the kind used for "may I close?" vetoes). A view here is
17//! borrowed downward by the event loop and cannot synchronously call back into a
18//! sibling and read a return value, so there is no event that carries a reply.
19//! Code that needs that pattern queries the tree owner directly via
20//! [`find_mut`](crate::view::View::find_mut) instead.
21//!
22//! **Guide:** [Commands & events](../../../apps/commands.html).
23//!
24//! # Turbo Vision heritage
25//!
26//! Replaces the single `TEvent` tagged union (`system.h`) with a Rust sum type
27//! (deviation D4). The original message event carried a command plus an untyped
28//! pointer used three ways; here a command event carries only the [`Command`], the
29//! "which view" case becomes [`Event::Broadcast`]'s resolvable [`ViewId`]
30//! `source`, and the timer-id case becomes the typed [`Event::Timer`] variant.
31
32mod key;
33
34pub use key::{
35 Key, KeyEvent, KeyModifiers, ctrl_to_arrow, hot_key, is_alt_hotkey, is_plain_hotkey,
36};
37
38use crate::command::Command;
39use crate::timer::TimerId;
40use crate::view::{Point, ViewId};
41
42/// An event a [`View`](crate::view::View) handles, matched arm-by-arm.
43///
44/// Match on an `&Event` in [`View::handle_event`](crate::view::View::handle_event) to
45/// selectively react to the cases you care about; return the event unchanged to
46/// let it propagate, or call [`Event::clear`] (or assign `*ev = Event::Nothing`)
47/// to consume it. [`Event::Nothing`] serves dual duty: it is both "no pending
48/// event" and the consumed-event sentinel.
49///
50/// The five mouse variants (`MouseDown`, `MouseUp`, `MouseMove`, `MouseAuto`,
51/// `MouseWheel`) correspond one-to-one to the magiblot C++ event-class constants
52/// (`evMouseDown`, `evMouseUp`, etc.), making each class independently matchable.
53/// To handle any mouse event, match all five; to handle clicks only, match
54/// `MouseDown` and `MouseUp`.
55///
56/// # Turbo Vision heritage
57///
58/// Replaces the `TEvent` tagged union (a bitmask tag plus a `union` of
59/// mouse/key/message records; `system.h`) with a real Rust sum type, matched
60/// arm-by-arm instead of masked (deviation D4).
61#[derive(Clone, Debug, PartialEq, Eq)]
62pub enum Event {
63 /// A mouse button was pressed. Deliver to focused view; position is in
64 /// screen coordinates. Check [`MouseEvent::buttons`] for which button.
65 MouseDown(MouseEvent),
66 /// A mouse button was released. Paired with `MouseDown`; arrives at the
67 /// view that captured the pointer.
68 MouseUp(MouseEvent),
69 /// The mouse moved without a button held (opt-in; see [`EventMask::mouse_move`]).
70 MouseMove(MouseEvent),
71 /// Auto-repeat while a button is held (opt-in; see [`EventMask::mouse_auto`]).
72 MouseAuto(MouseEvent),
73 /// The mouse wheel was rotated. A **distinct event class** from `MouseDown`:
74 /// the wheel is **not** positional and **not** focused, so a
75 /// [`crate::view::Group`] broadcasts it to every child until one consumes it —
76 /// the active window's scrollbar gets it regardless of cursor position.
77 /// Carries a [`MouseEvent`] whose [`MouseEvent::wheel`] is
78 /// `Up`/`Down`/`Left`/`Right`.
79 MouseWheel(MouseEvent),
80 /// A key was pressed. Match `Event::KeyDown(ke)` and inspect `ke.key` and
81 /// `ke.modifiers` (see [`KeyEvent`]).
82 KeyDown(KeyEvent),
83 /// A command targeted at a specific receiver. The event loop routes it
84 /// through the capture stack; the first view that recognises the command
85 /// should consume it via [`Event::clear`].
86 Command(Command),
87 /// A command broadcast to interested views. `source` names *which view this
88 /// broadcast is about* (e.g. which scrollbar changed), as a resolvable
89 /// [`ViewId`]. `None` for broadcasts about no particular view.
90 Broadcast {
91 command: Command,
92 source: Option<ViewId>,
93 },
94 /// A timer fired, carrying *which* [`TimerId`] expired.
95 ///
96 /// The timer id is an integer payload, not a view subject, so it gets its own
97 /// typed variant rather than reusing [`Event::Broadcast`]'s `source` field
98 /// (which is for the view-subject case only). Delivered to all views.
99 Timer(TimerId),
100 /// No pending event, or the consumed-event sentinel after [`Event::clear`].
101 ///
102 /// Both "the queue is empty" and "a handler consumed this event" map to
103 /// this variant. To consume an event inside a handler: call
104 /// `ev.clear()` or assign `*ev = Event::Nothing`. To test whether an event
105 /// was consumed after returning from a sub-handler: call
106 /// [`Event::is_nothing`].
107 Nothing,
108 /// Terminal bracketed-paste — the whole pasted string as delivered by the
109 /// terminal. Routed identically to a key press — delivered only to the focused
110 /// view, not broadcast. Handle it alongside `KeyDown` in input widgets that
111 /// accept text.
112 Paste(String),
113}
114
115impl Event {
116 /// Mark this event as handled by setting it to [`Event::Nothing`].
117 ///
118 /// Call this inside a [`View::handle_event`](crate::view::View::handle_event)
119 /// implementation when your view has fully processed the event and no other
120 /// view should see it. After `clear()` the caller can call
121 /// [`is_nothing`](Self::is_nothing) to confirm the event was consumed.
122 /// Prefer `clear()` over assigning `Event::Nothing` directly — it makes the
123 /// intent explicit.
124 pub fn clear(&mut self) {
125 *self = Event::Nothing;
126 }
127
128 /// Returns `true` if this event is [`Event::Nothing`] — either no event was
129 /// produced or a prior handler consumed it via [`clear`](Self::clear).
130 ///
131 /// Use this to check, after dispatching to a sub-handler, whether the event
132 /// was consumed (so you can skip further routing).
133 pub fn is_nothing(&self) -> bool {
134 matches!(self, Event::Nothing)
135 }
136}
137
138/// A mouse event record: cursor position, buttons down, wheel direction,
139/// click/move flags, and keyboard modifiers held at event time.
140///
141/// Carried by every mouse [`Event`] variant. Construct one with struct-update
142/// syntax; all fields `Default` to safe zeros:
143///
144/// ```
145/// use tvision_rs::event::{MouseEvent, MouseButtons};
146/// let ev = MouseEvent {
147/// buttons: MouseButtons { left: true, ..Default::default() },
148/// ..Default::default()
149/// };
150/// assert!(ev.buttons.left);
151/// ```
152///
153/// # Turbo Vision heritage
154///
155/// Ports `MouseEventType` (`system.h`). The `where` field (a Rust keyword)
156/// becomes `position`; the `mb*`/`me*` bit-words become struct-of-bools / enums
157/// and `controlKeyState` reuses [`KeyModifiers`].
158#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
159pub struct MouseEvent {
160 /// Cursor position in **absolute** screen coordinates at the time of the event.
161 ///
162 /// Coordinates are in the root (screen) space; subtract the view's global
163 /// origin to convert to view-local coordinates before hit-testing. The
164 /// position is always set, even for events that don't logically have one
165 /// (e.g. `MouseAuto` repeats carry the last known position).
166 ///
167 /// The C++ field was named `where` (a Rust keyword), renamed to `position`.
168 ///
169 /// # Turbo Vision heritage
170 ///
171 /// Ports the C++ global `MouseWhere: TPoint` (`drivers.cpp`), which held the
172 /// last known mouse position globally. In tvision-rs the position is carried
173 /// per-event in `MouseEvent::position`; there is no mutable global.
174 pub position: Point,
175 /// Which buttons are currently down at the time of the event.
176 pub buttons: MouseButtons,
177 /// Wheel direction for [`Event::MouseWheel`]; [`MouseWheel::None`] for all
178 /// other event classes.
179 pub wheel: MouseWheel,
180 /// Double/triple-click and mouse-moved flags for this event.
181 pub flags: MouseEventFlags,
182 /// Keyboard modifiers held during the event (shift, ctrl, alt). Reuses
183 /// [`KeyModifiers`] — the same struct used for key-down events.
184 pub modifiers: KeyModifiers,
185}
186
187/// Which mouse buttons are currently held at the time of a [`MouseEvent`].
188///
189/// Check individual fields in a mouse handler to distinguish single-button
190/// from multi-button presses:
191///
192/// ```
193/// use tvision_rs::event::{Event, MouseEvent};
194/// fn handle(ev: &Event) {
195/// if let Event::MouseDown(me) = ev {
196/// if me.buttons.left { /* left click */ }
197/// if me.buttons.right { /* right click / context menu */ }
198/// }
199/// }
200/// ```
201///
202/// # Turbo Vision heritage
203///
204/// The `mb*` button bitmask (`mbLeftButton = 0x01`, `mbRightButton = 0x02`)
205/// becomes a struct-of-bools.
206#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
207pub struct MouseButtons {
208 /// Left mouse button.
209 pub left: bool,
210 /// Right mouse button.
211 pub right: bool,
212 /// Middle mouse button (scroll-wheel click).
213 pub middle: bool,
214}
215
216/// Per-event flags for click-repeat detection and movement — a struct of named
217/// `bool` flags carried in every [`MouseEvent`].
218///
219/// Check `flags.double_click` in a `MouseDown` handler to react to a
220/// double-click without manually tracking timing. Note that there is no wheel
221/// flag here: wheel state is the [`MouseEvent::wheel`] field, because a wheel
222/// event is an independent event *class* (`Event::MouseWheel`), not a flag on
223/// another class.
224///
225/// # Turbo Vision heritage
226///
227/// The magiblot `eventFlags: ushort` bitmask (`meMouseMoved = 0x01`,
228/// `meDoubleClick = 0x02`, `meTripleClick = 0x04`) becomes a struct-of-bools
229/// extending the 1992 guide's single `Double: Boolean` field.
230/// The click count is computed by the event loop, as in magiblot's
231/// `TEventQueue::getMouseEvent`: a press with the same buttons on the same
232/// cell as the previous press, at most 440 ms later (the 1992 guide's
233/// `DoubleDelay` of 8 ticks × 55 ms), is a double click; the next such press is
234/// a triple click; the one after that is a single click again. Apps tune the
235/// interval with [`Program::set_double_delay_ms`](crate::app::Program::set_double_delay_ms).
236#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
237pub struct MouseEventFlags {
238 /// This press completed a double click (the second press with the same
239 /// buttons on the same cell within the double-click interval, default
240 /// 440 ms).
241 ///
242 /// Check this flag in a [`Event::MouseDown`] handler to distinguish a
243 /// double-click from a single click. The event loop computes it for every
244 /// backend; a flag a backend sets itself is overwritten.
245 pub double_click: bool,
246 /// This press completed a triple click (the press after a double click,
247 /// same buttons, same cell, within the double-click interval).
248 pub triple_click: bool,
249 /// The mouse moved since the last event.
250 pub mouse_moved: bool,
251}
252
253/// The direction of mouse wheel motion carried by a [`MouseEvent`].
254///
255/// Only meaningful when the enclosing event is [`Event::MouseWheel`]; for all
256/// other event classes the field is [`MouseWheel::None`]. Match it to scroll
257/// content:
258///
259/// ```
260/// use tvision_rs::event::{Event, MouseWheel};
261/// fn handle(ev: &Event) {
262/// if let Event::MouseWheel(me) = ev {
263/// match me.wheel {
264/// MouseWheel::Up => { /* scroll up */ }
265/// MouseWheel::Down => { /* scroll down */ }
266/// _ => {}
267/// }
268/// }
269/// }
270/// ```
271///
272/// # Turbo Vision heritage
273///
274/// Replaces the magiblot `uchar wheel` field and `mw*` constants with a
275/// closed enum; the `None` variant replaces the `0` value for "no wheel".
276#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
277pub enum MouseWheel {
278 /// No wheel motion (the default; present on non-wheel mouse events).
279 #[default]
280 None,
281 /// Wheel scrolled up (towards the user).
282 Up,
283 /// Wheel scrolled down (away from the user).
284 Down,
285 /// Wheel scrolled left (horizontal scroll).
286 Left,
287 /// Wheel scrolled right (horizontal scroll).
288 Right,
289}
290
291/// Per-view opt-in mask for the *expensive* continuous event classes.
292///
293/// **Most event classes are always on** — `MouseDown`, `MouseUp`, `KeyDown`,
294/// `Command`, `Broadcast`, `Timer`, and `Paste` are delivered unconditionally to
295/// every eligible view. Only the high-frequency classes that are costly to route
296/// through the whole tree need an explicit opt-in:
297///
298/// - [`mouse_move`](Self::mouse_move) — fires on every cursor movement; opt in
299/// only if your view needs real-time tracking (e.g. a custom drag target).
300/// - [`mouse_auto`](Self::mouse_auto) — fires repeatedly while a button is held;
301/// opt in for views like scrollbars that need auto-repeat.
302///
303/// Set these fields on a view's [`EventMask`] field to enable the classes you
304/// need. Views that do not set them never receive the corresponding events, so
305/// there is no performance cost for the common case.
306///
307/// # Turbo Vision heritage
308///
309/// The surviving slice of the `TView::eventMask` bit-word, trimmed to the two
310/// opt-ins that are non-trivial to route selectively. The
311/// always-on classes needed no flag in C++ either; explicitly tracking them here
312/// would be noise.
313#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
314pub struct EventMask {
315 /// Opt in to [`Event::MouseMove`] (fires on every cursor movement).
316 pub mouse_move: bool,
317 /// Opt in to [`Event::MouseAuto`] (fires repeatedly while a button is held).
318 pub mouse_auto: bool,
319}
320
321#[cfg(test)]
322mod tests {
323 use super::*;
324
325 #[test]
326 fn each_variant_constructs() {
327 let m = MouseEvent::default();
328 let _ = Event::MouseDown(m);
329 let _ = Event::MouseUp(m);
330 let _ = Event::MouseMove(m);
331 let _ = Event::MouseAuto(m);
332 let _ = Event::KeyDown(KeyEvent::from(Key::Enter));
333 let _ = Event::Command(Command::OK);
334 let _ = Event::Broadcast {
335 command: Command::OK,
336 source: None,
337 };
338 let _ = Event::Nothing;
339 let _ = Event::Paste("hi".to_string());
340 }
341
342 #[test]
343 fn clear_sets_nothing_and_is_nothing() {
344 let mut ev = Event::KeyDown(KeyEvent::from(Key::Enter));
345 assert!(!ev.is_nothing());
346 ev.clear();
347 assert_eq!(ev, Event::Nothing);
348 assert!(ev.is_nothing());
349 }
350
351 #[test]
352 fn key_down_round_trip() {
353 let ev = Event::KeyDown(KeyEvent::from(Key::Enter));
354 match ev {
355 Event::KeyDown(k) => {
356 assert_eq!(k.key, Key::Enter);
357 assert_eq!(k.modifiers, KeyModifiers::default());
358 }
359 _ => panic!("expected KeyDown"),
360 }
361 }
362
363 #[test]
364 fn mouse_event_default_is_empty() {
365 let m = MouseEvent::default();
366 assert_eq!(m.position, Point::default());
367 assert!(!m.buttons.left);
368 assert!(!m.buttons.right);
369 assert!(!m.buttons.middle);
370 assert_eq!(m.wheel, MouseWheel::None);
371 assert!(!m.flags.double_click);
372 assert!(!m.flags.triple_click);
373 assert!(!m.flags.mouse_moved);
374 assert_eq!(m.modifiers, KeyModifiers::default());
375 }
376
377 #[test]
378 fn struct_of_bools_defaults_all_false() {
379 assert_eq!(
380 MouseButtons::default(),
381 MouseButtons {
382 left: false,
383 right: false,
384 middle: false,
385 }
386 );
387 assert_eq!(
388 MouseEventFlags::default(),
389 MouseEventFlags {
390 double_click: false,
391 triple_click: false,
392 mouse_moved: false,
393 }
394 );
395 assert_eq!(
396 EventMask::default(),
397 EventMask {
398 mouse_move: false,
399 mouse_auto: false,
400 }
401 );
402 }
403
404 #[test]
405 fn wheel_up_mouse_event() {
406 let m = MouseEvent {
407 wheel: MouseWheel::Up,
408 ..Default::default()
409 };
410 let ev = Event::MouseWheel(m);
411 match ev {
412 Event::MouseWheel(me) => assert_eq!(me.wheel, MouseWheel::Up),
413 _ => panic!("expected MouseWheel"),
414 }
415 }
416}