native_gui_core/events.rs
1use crate::drag::{DragPayload, DragPayloadKind, DragSessionId, DropCancelReason, DropEffect};
2use crate::WidgetId;
3use crate::{MenuId, MenuItemId};
4
5#[cfg(feature = "async")]
6use crate::async_ui::TaskEvent;
7#[cfg(feature = "displays")]
8use crate::displays::DisplayInfo;
9use crate::motion::MotionId;
10use crate::pickers::{FontDescriptor, FontEffects, Rgba};
11use crate::theme::ThemeMode;
12use crate::timer::TimerId;
13use crate::toolbar::ToolId;
14use crate::windowing::PopupDismissReason;
15
16/// Dynamic accessibility updates requested by the shared UI layer.
17///
18/// These are backend notifications, not events delivered to the application.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum AccessibleNotification {
21 /// A widget's numeric value changed.
22 ValueChanged,
23 /// A widget's text changed.
24 TextChanged,
25 /// Keyboard focus moved to a widget.
26 FocusChanged,
27 /// A short message should be announced by assistive technology.
28 Announcement(String),
29}
30
31#[non_exhaustive]
32#[derive(Debug, Clone, PartialEq)]
33pub enum UiEvent {
34 Clicked {
35 widget_id: WidgetId,
36 },
37 Toggled {
38 widget_id: WidgetId,
39 checked: bool,
40 },
41 TextChanged {
42 widget_id: WidgetId,
43 text: String,
44 },
45 SelectionChanged {
46 widget_id: WidgetId,
47 selected: Option<String>,
48 /// Position of the selection within the widget (list/combo/tab),
49 /// when the backend can report it. Prefer this over matching by
50 /// `selected` text, which is not unique.
51 index: Option<usize>,
52 },
53 /// Multi-select list/tree widgets report their selection set by row index.
54 MultiSelectionChanged {
55 widget_id: WidgetId,
56 indices: Vec<usize>,
57 },
58 /// A grid cell was clicked (DataGrid).
59 GridCellClicked {
60 widget_id: WidgetId,
61 row: usize,
62 col: usize,
63 },
64 /// A range of cells was selected (DataGrid).
65 GridSelectionChanged {
66 widget_id: WidgetId,
67 /// List of (row, col) tuples representing selected cells
68 selected_ranges: Vec<(usize, usize)>,
69 },
70 /// In-place editing started on a cell.
71 GridCellEditingStarted {
72 widget_id: WidgetId,
73 row: usize,
74 col: usize,
75 },
76 /// In-place editing finished on a cell.
77 GridCellEditingFinished {
78 widget_id: WidgetId,
79 row: usize,
80 col: usize,
81 new_value: String,
82 },
83 /// A row (list/tree widgets) or line (DataGrid) was activated via
84 /// double-click; `index` is the row/line position when the backend can
85 /// report it.
86 Activated {
87 widget_id: WidgetId,
88 index: Option<usize>,
89 },
90 TextSubmitted {
91 widget_id: WidgetId,
92 text: String,
93 },
94 /// The user accepted a `TextInput` completion suggestion.
95 ///
96 /// Emitted at most once per popup session, when the user commits a
97 /// suggestion with Enter or a click. The application applies `text`
98 /// through [`crate::Ui::set_text`] and moves focus as it sees fit; a
99 /// popup closed without acceptance reports
100 /// [`UiEvent::SuggestionDismissed`] instead.
101 SuggestionSelected {
102 widget_id: WidgetId,
103 text: String,
104 },
105 /// The completion popup closed without acceptance: Escape,
106 /// blur, or a click elsewhere. Never follows a `SuggestionSelected` for
107 /// the same popup session.
108 SuggestionDismissed {
109 widget_id: WidgetId,
110 },
111 ValueChanged {
112 widget_id: WidgetId,
113 value: i32,
114 },
115 DateChanged {
116 widget_id: WidgetId,
117 iso_date: String,
118 },
119 LinkActivated {
120 widget_id: WidgetId,
121 url: String,
122 },
123 ProgressChanged {
124 widget_id: WidgetId,
125 value: f64,
126 },
127 MenuItemSelected {
128 menu_id: MenuId,
129 item_id: MenuItemId,
130 },
131 /// A programmatic confirm dialog (`Ui::show_confirm_dialog`) was answered;
132 /// `token` matches the value returned when the dialog was shown and
133 /// `confirmed` is the Yes/No outcome.
134 DialogResponse {
135 token: u64,
136 confirmed: bool,
137 },
138 /// A function-style file dialog (`Ui::show_file_dialog`) was answered;
139 /// `token` matches the value returned when it was shown. `paths` holds
140 /// the chosen file(s) or folder, and is empty when the user cancelled.
141 FileDialogResponse {
142 token: u64,
143 paths: Vec<std::path::PathBuf>,
144 },
145 /// Live colour preview from an open `ColorDialog`.
146 ///
147 /// Capability-gated: lanes advertise whether the native chooser emits
148 /// previews, and a lane without one never sends this event. Receiving it
149 /// means the user is hovering a candidate colour — the dialog is still
150 /// open, so applications that render the candidate must restore their
151 /// previous state when the final [`UiEvent::ColorSelected`] is a cancel.
152 ColorChanged {
153 widget_id: WidgetId,
154 color: Rgba,
155 },
156 /// Final answer from a `ColorDialog`: the accepted colour, or
157 /// `None` when the user cancelled.
158 ///
159 /// Exactly one of these is delivered per activation, and an accept also
160 /// refreshes the widget's `color_dialog_data.initial` so reopening starts
161 /// where the user finished.
162 ColorSelected {
163 widget_id: WidgetId,
164 color: Option<Rgba>,
165 },
166 /// Live font preview from an open `FontDialog`.
167 ///
168 /// Capability-gated like [`UiEvent::ColorChanged`]: it arrives while the
169 /// dialog is open, so applications that render the candidate must restore
170 /// their previous state when the final selection is a cancel. The size is
171 /// already clamped to the dialog's configured range.
172 FontChanged {
173 widget_id: WidgetId,
174 descriptor: FontDescriptor,
175 },
176 /// Final answer from a `FontDialog`: the accepted descriptor and
177 /// effects, or `None` when the user cancelled.
178 ///
179 /// Exactly one of these is delivered per activation. An accept refreshes
180 /// the widget's `font_dialog_data` (initial descriptor and effects) so
181 /// reopening starts where the user finished, with the shared size clamp
182 /// applied to the stored value.
183 FontSelected {
184 widget_id: WidgetId,
185 selection: Option<(FontDescriptor, FontEffects)>,
186 },
187 /// The user asked for help from a picker dialog whose lane offers a help
188 /// affordance (capability `font_dialog_help`).
189 HelpRequested {
190 widget_id: WidgetId,
191 },
192 /// A toolbar tool was activated by the user.
193 ///
194 /// A checkable tool reports [`UiEvent::ToolToggled`] instead, a dropdown
195 /// tool reports [`UiEvent::ToolDropdown`], and a disabled or hidden tool
196 /// reports nothing — so a click produces exactly one of the three.
197 ToolActivated {
198 widget_id: WidgetId,
199 tool_id: ToolId,
200 },
201 /// A user toggled a checkable toolbar tool; `checked` is the new state.
202 ///
203 /// One event is delivered per changed tool: checking a radio member
204 /// unchecks the previous member, which arrives as its own event in
205 /// toolbar order. Programmatic [`crate::Ui::set_tool_state`] never emits
206 /// these — it returns the changed tools to the caller instead.
207 ToolToggled {
208 widget_id: WidgetId,
209 tool_id: ToolId,
210 checked: bool,
211 },
212 /// The user asked a dropdown tool to open its menu.
213 ///
214 /// The application composes the menu with the existing menu API after
215 /// receiving this event; the shared model never builds popup content.
216 ToolDropdown {
217 widget_id: WidgetId,
218 tool_id: ToolId,
219 },
220 /// The pointer entered (`Some`) or left (`None`) a toolbar tool
221 /// (capability-gated: lanes that cannot report hot-item changes
222 /// never send it).
223 ToolHovered {
224 widget_id: WidgetId,
225 tool_id: Option<ToolId>,
226 },
227 /// A toolbar tool was right-clicked, asking for a context menu.
228 ToolContext {
229 widget_id: WidgetId,
230 tool_id: ToolId,
231 },
232 /// A row drag began on a drag-enabled widget carrying the dragged row
233 /// indices (usually the current selection).
234 DragStarted {
235 widget_id: WidgetId,
236 indices: Vec<usize>,
237 },
238 /// Rows were dropped onto `target_index` of the receiving widget; the
239 /// app performs the move through its core model and refreshes.
240 Dropped {
241 widget_id: WidgetId,
242 target_index: usize,
243 source_indices: Vec<usize>,
244 },
245 /// External files were dropped onto a window or widget from the OS shell (e.g. Explorer, Finder, Nautilus).
246 FilesDropped {
247 widget_id: WidgetId,
248 paths: Vec<String>,
249 },
250 /// URLs dropped onto a window or widget (e.g. from an external browser or link drag).
251 UrlsDropped {
252 widget_id: WidgetId,
253 urls: Vec<String>,
254 offset: Option<usize>,
255 },
256 /// Plain text dropped onto a window or widget.
257 TextDropped {
258 widget_id: WidgetId,
259 text: String,
260 offset: Option<usize>,
261 },
262 /// A text/custom-MIME drag session began on a configured source.
263 DragSessionStarted {
264 widget_id: WidgetId,
265 session: DragSessionId,
266 kinds: Vec<DragPayloadKind>,
267 },
268 /// A drag session entered a configured target with compatible MIME kinds.
269 DragEntered {
270 target: WidgetId,
271 session: DragSessionId,
272 position: (i32, i32),
273 offered: Vec<String>,
274 },
275 /// The pointer moved over the current drag target.
276 DragMoved {
277 target: WidgetId,
278 session: DragSessionId,
279 position: (i32, i32),
280 },
281 /// The pointer left a drag target before drop or cancellation.
282 DragExited {
283 target: WidgetId,
284 session: DragSessionId,
285 },
286 /// A payload was delivered to a compatible target and the session ended.
287 DragDropped {
288 target: WidgetId,
289 session: DragSessionId,
290 position: (i32, i32),
291 payload: DragPayload,
292 effect: DropEffect,
293 },
294 /// A drag session ended without a compatible drop.
295 DragCancelled {
296 session: DragSessionId,
297 reason: DropCancelReason,
298 },
299 WindowResized {
300 widget_id: WidgetId,
301 width: i32,
302 height: i32,
303 },
304 /// A split-pane backend reported a changed divider position.
305 /// `position` is the first pane's extent along the split axis; `extent`
306 /// is the total extent along that axis.
307 SplitPaneMoved {
308 widget_id: WidgetId,
309 position: i32,
310 extent: i32,
311 },
312 /// An OS close request (the window's X button, Alt+F4, the system menu)
313 /// for a window with close interception enabled (`Ui::set_close_guard`).
314 /// The window stays open until the app approves the close —
315 /// typically after asking through `Ui::show_confirm_dialog` (GH-056).
316 CloseRequested {
317 widget_id: WidgetId,
318 },
319 WindowClosed {
320 widget_id: WidgetId,
321 },
322 /// A transient popup session ended because of a user or window-system action.
323 PopupDismissed {
324 widget_id: WidgetId,
325 reason: PopupDismissReason,
326 },
327 /// A timer deadline was serviced on the UI event loop; `elapsed` is
328 /// measured from the original start and `missed` counts coalesced ticks.
329 TimerFired {
330 timer: TimerId,
331 elapsed: std::time::Duration,
332 missed: u32,
333 },
334 /// Linear progress for a UI motion, derived from a coalesced timer deadline.
335 MotionTicked {
336 motion: MotionId,
337 widget_id: WidgetId,
338 progress: f32,
339 },
340 /// A motion reached its duration and will not produce further ticks.
341 MotionFinished {
342 motion: MotionId,
343 widget_id: WidgetId,
344 },
345 /// Pointer input on a canvas widget.
346 ///
347 /// Coordinate contract: `x` and `y` are **logical**
348 /// (96-DPI) coordinates matching the space the layout engine lays the widget out in.
349 /// A lane that receives physical pixels from the OS (Win32 under
350 /// Per-Monitor v2) reports its display scale through
351 /// [`crate::Backend::widget_scale_factor`]; [`crate::Ui`] inverts that
352 /// scaling before dispatch, so app code hit-tests against the same
353 /// coordinate space on every backend. Lanes that already receive logical
354 /// coordinates (GTK4 gestures, Cocoa points, the Mock backend unless a
355 /// display fixture installs a scale) report `1.0` and pass through
356 /// untouched.
357 PointerDown {
358 widget_id: WidgetId,
359 x: f32,
360 y: f32,
361 button: u8,
362 },
363 /// Pointer motion on a canvas widget; see [`UiEvent::PointerDown`] for the
364 /// coordinate contract.
365 PointerMove {
366 widget_id: WidgetId,
367 x: f32,
368 y: f32,
369 },
370 /// Pointer release on a canvas widget; see [`UiEvent::PointerDown`] for
371 /// the coordinate contract.
372 PointerUp {
373 widget_id: WidgetId,
374 x: f32,
375 y: f32,
376 button: u8,
377 },
378 /// Raw keyboard input on a focusable widget. `key` is the
379 /// backend's logical key name for the pressed key and is not layout-
380 /// committed text: use [`UiEvent::Char`] for text input.
381 ///
382 /// Ordering contract: for a stroke that produces text, `KeyDown` is
383 /// reported before its [`UiEvent::Char`] and `KeyUp` after it. A stroke
384 /// claimed by a menu accelerator reports [`UiEvent::MenuItemSelected`]
385 /// instead and produces no `KeyDown` or `Char`; its `KeyUp` is still
386 /// delivered so apps can clear pressed-key state.
387 ///
388 /// Text-editing strokes are the accelerator exception: while a
389 /// `TextInput`/`TextArea` holds focus, clipboard and undo commands
390 /// (Ctrl+C/X/V/Z/Y/A), Delete, and Backspace stay with the control and
391 /// never fire a registered accelerator — otherwise a rename field could
392 /// not paste text while the app's Paste command mirrors it. The
393 /// exception matches GTK, where the focused widget processes those keys
394 /// before application accelerators.
395 KeyDown {
396 widget_id: WidgetId,
397 key: String,
398 ctrl: bool,
399 shift: bool,
400 alt: bool,
401 },
402 KeyUp {
403 widget_id: WidgetId,
404 key: String,
405 ctrl: bool,
406 shift: bool,
407 alt: bool,
408 },
409 /// Committed text input for a widget: direct keyboard input
410 /// and IME commits both report through this event. `text` may contain
411 /// more than one scalar (IME result strings, dead-key sequences).
412 ///
413 /// Exactly one `Char` is reported per committed text. The commit may
414 /// arrive without a preceding `KeyDown` (an IME candidate picked with
415 /// the pointer) and is never interleaved with an unfinished IME
416 /// composition — while a composition is active, text stays in
417 /// [`UiEvent::CompositionChanged`]. Standard text controls report their
418 /// value changes through [`UiEvent::TextChanged`] on top of the commit
419 /// `Char`; backends observe the platform IME result for those controls
420 /// (Win32 `GCS_RESULTSTR`, GTK's widget input context), so apps do not
421 /// need a separate text-input path per control.
422 Char {
423 widget_id: WidgetId,
424 text: String,
425 },
426 /// IME composition state changed for a widget.
427 ///
428 /// `Some(preedit)` carries the live preedit string while a composition
429 /// is active (it may be empty for a just-started composition); `None`
430 /// marks the end of the composition exactly once, for both commits and
431 /// cancels. Repeated preedit updates that report the same string are
432 /// de-duplicated by the backend. A commit also reports
433 /// [`UiEvent::Char`] with the committed text; the relative order of
434 /// that `Char` and the ending `None` is platform-defined (Win32
435 /// commits before the end marker, GTK clears the preedit first), so
436 /// apps must treat both signals independently instead of relying on
437 /// their order.
438 CompositionChanged {
439 widget_id: WidgetId,
440 text: Option<String>,
441 },
442 /// Keyboard focus moved to (`focused: true`) or away from
443 /// (`focused: false`) a widget. Programmatic
444 /// `Ui::focus`/`Ui::focus_next`/`Ui::focus_previous` report through this
445 /// event, and native focus changes produce it; `Ui` keeps its
446 /// focus record in sync from it.
447 FocusChanged {
448 widget_id: WidgetId,
449 focused: bool,
450 },
451 /// The OS light/dark preference changed.
452 ///
453 /// Reported by backends whose `Backend::theme_capabilities().change_events`
454 /// is true when the system setting transitions; the backend de-duplicates
455 /// so the event only arrives on an actual mode change. It is informational:
456 /// the active [`crate::Theme`] is unchanged until the app decides to follow
457 /// the system (for example by calling `Ui::set_theme_mode`), and the current
458 /// preference can always be re-read through `Ui::system_theme_mode`.
459 ThemeChanged {
460 mode: ThemeMode,
461 high_contrast: bool,
462 },
463 /// The window's display metrics changed: a DPI or monitor
464 /// transition was observed.
465 ///
466 /// Reported by backends whose `Backend::display_capabilities()` has
467 /// `dpi_change_events` true. The payload is a fresh [`DisplayInfo`] for
468 /// the display the window is now on. Informational: apps decide whether
469 /// to re-layout or re-query `Ui::displays()`.
470 #[cfg(feature = "displays")]
471 DisplayChanged {
472 display: DisplayInfo,
473 },
474 /// Internal wake marker posted by a backend's event-loop wake hook when
475 /// background commands are queued (see `Backend::wake_handle`). `Ui`
476 /// consumes it while draining and never returns it to application code.
477 TasksPending,
478 /// Background-task lifecycle notification posted through a `UiProxy`.
479 /// See `TaskEvent` for the per-task payloads.
480 #[cfg(feature = "async")]
481 Task(TaskEvent),
482 /// A date was selected in a calendar widget.
483 CalendarDateSelected {
484 widget_id: WidgetId,
485 date: crate::widgets::CalendarDate,
486 selected_dates: Vec<crate::widgets::CalendarDate>,
487 },
488 /// The visible month in a calendar widget changed.
489 CalendarMonthChanged {
490 widget_id: WidgetId,
491 year: i32,
492 month: u32,
493 },
494 /// The user changed a property in a property grid and the value was
495 /// stored. `widget_id` is the grid host.
496 #[cfg(feature = "property-grid")]
497 PropertyChanged {
498 widget_id: WidgetId,
499 property: crate::properties::PropertyId,
500 previous: crate::properties::PropertyValue,
501 value: crate::properties::PropertyValue,
502 },
503 /// With veto mode on, a user edit is waiting for
504 /// [`crate::Ui::resolve_property_change`]; nothing is stored yet.
505 #[cfg(feature = "property-grid")]
506 PropertyChanging {
507 widget_id: WidgetId,
508 property: crate::properties::PropertyId,
509 token: crate::properties::ChangeToken,
510 proposed: crate::properties::PropertyValue,
511 },
512 /// A user edit did not apply: the text did not parse for the property's
513 /// type, the model refused it, or the application vetoed it. The editor
514 /// already shows the stored value again.
515 #[cfg(feature = "property-grid")]
516 PropertyEditRejected {
517 widget_id: WidgetId,
518 property: crate::properties::PropertyId,
519 reason: String,
520 },
521 /// Keyboard focus moved to a property's editor, selecting it.
522 #[cfg(feature = "property-grid")]
523 PropertySelected {
524 widget_id: WidgetId,
525 property: Option<crate::properties::PropertyId>,
526 },
527 /// The user changed the text of a styled text widget: at `position` (in
528 /// characters), `deleted` was replaced by `inserted`. The document,
529 /// styling, markers and indicators are already updated.
530 #[cfg(feature = "styled-text")]
531 StyledTextModified {
532 widget_id: WidgetId,
533 position: usize,
534 deleted: String,
535 inserted: String,
536 },
537 /// A user edit moved a styled text document away from its save point
538 /// (`dirty: true`) or back to it.
539 #[cfg(feature = "styled-text")]
540 StyledTextSavePointChanged {
541 widget_id: WidgetId,
542 dirty: bool,
543 },
544 /// A WebView started loading `url`.
545 #[cfg(feature = "webview")]
546 WebViewLoadStarted {
547 widget_id: WidgetId,
548 url: String,
549 },
550 /// A WebView finished loading `url`.
551 #[cfg(feature = "webview")]
552 WebViewLoadFinished {
553 widget_id: WidgetId,
554 url: String,
555 },
556 /// A WebView could not load `url`; `error` is the engine's description.
557 #[cfg(feature = "webview")]
558 WebViewLoadFailed {
559 widget_id: WidgetId,
560 url: String,
561 error: String,
562 },
563 /// A navigation or new window the page asked for was refused by the
564 /// WebView's navigation prefixes (new windows are always refused).
565 #[cfg(feature = "webview")]
566 WebViewNavigationBlocked {
567 widget_id: WidgetId,
568 url: String,
569 },
570 /// The page's title changed.
571 #[cfg(feature = "webview")]
572 WebViewTitleChanged {
573 widget_id: WidgetId,
574 title: String,
575 },
576 /// The page called `window.nativeGui.postMessage(body)`; `source` is the
577 /// URL of the page that sent it. Treat the body as untrusted input.
578 #[cfg(feature = "webview")]
579 WebViewMessage {
580 widget_id: WidgetId,
581 source: String,
582 body: String,
583 },
584 /// A script started by `Ui::webview_evaluate_script` finished: `Ok` holds
585 /// its value as JSON text, `Err` the message of the exception it threw.
586 #[cfg(feature = "webview")]
587 WebViewScriptResult {
588 widget_id: WidgetId,
589 operation: crate::advanced::OperationId,
590 result: Result<String, String>,
591 },
592 /// The engine failed to start or its content process ended; the WebView
593 /// shows nothing until it is created again.
594 #[cfg(feature = "webview")]
595 WebViewEngineFailed {
596 widget_id: WidgetId,
597 error: String,
598 },
599}
600
601impl UiEvent {
602 /// Whether this event is a deliberate user *action* on its widget.
603 ///
604 /// Actions are the commit-style events an application normally answers
605 /// with a message: a button click, a list/grid row activation, Enter in a
606 /// text field, a checkbox toggle, a selection or value change, a link,
607 /// toolbar tool, calendar date, or picker acceptance, and a finished
608 /// inline grid edit. Incidental traffic — focus changes, raw key and
609 /// pointer strokes, hover, live text edits, live picker previews,
610 /// resizes, drags, and timers — is not an action.
611 ///
612 /// [`Routes::on`](crate::Routes::on) uses this filter so that, for
613 /// example, a button that merely receives keyboard focus does not fire
614 /// its message.
615 pub fn is_action(&self) -> bool {
616 matches!(
617 self,
618 UiEvent::Clicked { .. }
619 | UiEvent::Activated { .. }
620 | UiEvent::TextSubmitted { .. }
621 | UiEvent::Toggled { .. }
622 | UiEvent::SelectionChanged { .. }
623 | UiEvent::MultiSelectionChanged { .. }
624 | UiEvent::SuggestionSelected { .. }
625 | UiEvent::ValueChanged { .. }
626 | UiEvent::DateChanged { .. }
627 | UiEvent::LinkActivated { .. }
628 | UiEvent::ToolActivated { .. }
629 | UiEvent::ToolToggled { .. }
630 | UiEvent::CalendarDateSelected { .. }
631 | UiEvent::ColorSelected { .. }
632 | UiEvent::FontSelected { .. }
633 | UiEvent::GridCellEditingFinished { .. }
634 | UiEvent::MenuItemSelected { .. }
635 ) || self.is_property_action()
636 }
637
638 #[cfg(feature = "property-grid")]
639 fn is_property_action(&self) -> bool {
640 matches!(self, UiEvent::PropertyChanged { .. })
641 }
642
643 #[cfg(not(feature = "property-grid"))]
644 fn is_property_action(&self) -> bool {
645 false
646 }
647}