Skip to main content

pushrod/
widget.rs

1// Widget
2// Pushrod
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! # Widget
17//!
18//! A UI element that exists in a window, whether visible or otherwise, that consumes and
19//! alternatively generates events.
20//!
21//! Every `Widget` owns a [`WidgetCore`], which stores the state that all `Widget`s share: the
22//! ID, parent ID, origin, size, color, visibility, and invalidation flag.  The
23//! `Widget` trait provides default implementations for all of the getters and setters against
24//! the `WidgetCore`, so a new `Widget` only needs to implement three functions:
25//!
26//! ```rust,no_run
27//! use pushrod::paint::{self, Painter};
28//! use pushrod::widget::{Widget, WidgetCore};
29//!
30//! pub struct MyWidget {
31//!     core: WidgetCore,
32//! }
33//!
34//! impl Widget for MyWidget {
35//!     fn core(&self) -> &WidgetCore { &self.core }
36//!     fn core_mut(&mut self) -> &mut WidgetCore { &mut self.core }
37//!
38//!     fn paint(&self, p: &mut dyn Painter) {
39//!         paint::fill(p, self.get_color());
40//!     }
41//! }
42//! ```
43//!
44//! If the compiler is happy, the `Widget` is complete: there are no lists of `Widget` types to
45//! update elsewhere in the library.
46
47use crate::appearance::{Appearance, StateStyle};
48use crate::color::Color;
49use crate::controllers::{Controller, ControllerEvent, Controllers};
50use crate::event::{Event, EventCtx, EventMask, Propagation};
51use crate::geometry::{Point, Size};
52use crate::paint::Painter;
53use bitflags::bitflags;
54use std::any::Any;
55
56/// The ID of a `Widget`.
57///
58/// IDs are assigned by the [`WidgetCache`](crate::cache::WidgetCache) in the order in which
59/// `Widget`s are added, starting with the window's root `Widget` at ID `0`
60/// ([`ROOT_WIDGET_ID`]).  An ID is stable for the lifetime of the `WidgetCache`, which is what
61/// allows forms to be designed, stored, and wired to callbacks by ID.
62pub type WidgetId = u32;
63
64/// The ID of the window's root `Widget`.
65///
66/// The root is created by the `Engine` (a [`RootWidget`](crate::root_widget::RootWidget)), fills
67/// the window, and is the ancestor of every other `Widget`.  It is its own parent.
68pub const ROOT_WIDGET_ID: WidgetId = 0;
69
70bitflags! {
71    /// What a `Widget` can do, stored on its [`WidgetCore`].
72    ///
73    /// Behavior flags describe the `Widget`'s role rather than how it looks right now (that is
74    /// [`VisualState`]), so they work the same for every widget and can be saved in a form file.
75    ///
76    /// # Examples
77    ///
78    /// ```rust
79    /// use pushrod::widget::Behavior;
80    ///
81    /// let ok_button = Behavior::FOCUSABLE | Behavior::DEFAULT_ACTION | Behavior::DISMISSES_DIALOG;
82    ///
83    /// assert!(ok_button.contains(Behavior::DEFAULT_ACTION));
84    /// ```
85    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
86    pub struct Behavior: u16 {
87        /// The `Widget` can receive keyboard focus.
88        const FOCUSABLE = 1 << 0;
89        /// The `Widget` stays pressed after a click, until it is clicked again.
90        const TOGGLE = 1 << 1;
91        /// The `Widget` is activated by the Return key.
92        const DEFAULT_ACTION = 1 << 2;
93        /// The `Widget` is activated by the Escape key.
94        const CANCEL_ACTION = 1 << 3;
95        /// Activating the `Widget` closes the enclosing modal dialog and reports itself.
96        const DISMISSES_DIALOG = 1 << 4;
97        /// The `Widget` fires when the mouse button is pressed, not when it is released.
98        const ACTIVATE_ON_PRESS = 1 << 5;
99        /// Only one sibling with this flag is checked at a time (a radio group).
100        const EXCLUSIVE = 1 << 6;
101        /// The `Widget` and its children are not drawn and do not receive input.
102        const HIDDEN = 1 << 7;
103    }
104}
105
106bitflags! {
107    /// How a `Widget` currently looks, stored on its [`WidgetCore`].
108    ///
109    /// A `Widget` with no flags set is in its normal state.
110    ///
111    /// # Examples
112    ///
113    /// ```rust
114    /// use pushrod::widget::VisualState;
115    ///
116    /// let state = VisualState::CHECKED | VisualState::HOVERED;
117    ///
118    /// assert!(!state.contains(VisualState::DISABLED));
119    /// ```
120    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
121    pub struct VisualState: u16 {
122        /// The mouse button is held down on the `Widget`.
123        const PRESSED = 1 << 0;
124        /// The `Widget` is checked or selected.
125        const CHECKED = 1 << 1;
126        /// The `Widget` is in a mixed (tri-state) condition.
127        const INDETERMINATE = 1 << 2;
128        /// The `Widget` is disabled: it is drawn dimmed and receives no input.
129        const DISABLED = 1 << 3;
130        /// The `Widget` has keyboard focus.
131        const FOCUSED = 1 << 4;
132        /// The pointer is inside the `Widget`.
133        const HOVERED = 1 << 5;
134        /// A drag is currently over the `Widget`.
135        const DRAG_OVER = 1 << 6;
136    }
137}
138
139/// The state that every `Widget` shares.
140///
141/// Store one `WidgetCore` in each `Widget` structure and return it from [`Widget::core`] and
142/// [`Widget::core_mut`]; every getter and setter on the `Widget` trait works against it.  It holds
143/// the `Widget`'s ID and parent ID (assigned by the `WidgetCache`), its origin relative to its
144/// parent, its size, its background color, its [`Behavior`] flags (including hidden) and [`VisualState`] flags, its [`Appearance`] (a style per state), its [`EventMask`], whether it needs repainting, and
145/// the texture its backend paints it into.
146///
147/// # Examples
148///
149/// ```rust
150/// use pushrod::geometry::{point, size};
151/// use pushrod::widget::WidgetCore;
152///
153/// let core = WidgetCore::new(point(10, 20), size(100, 30));
154/// ```
155pub struct WidgetCore {
156    /// The `Widget`'s ID, assigned by the `WidgetCache` when the `Widget` is added.
157    pub(crate) id: WidgetId,
158    /// The ID of the parent `Widget`; the root `Widget` is its own parent.
159    pub(crate) parent: WidgetId,
160    origin: Point,
161    size: Size,
162    color: Color,
163    behavior: Behavior,
164    state: VisualState,
165    appearance: Appearance,
166    event_mask: EventMask,
167    invalidated: bool,
168    controllers: Controllers,
169}
170
171impl WidgetCore {
172    /// Sets the event mask the `Widget` reports from [`Widget::event_mask`].
173    ///
174    /// Use it while building a `Widget`.  To change a mask after the `Widget` is in a window, use
175    /// [`WidgetCache::set_event_mask`](crate::cache::WidgetCache::set_event_mask), which also emits
176    /// the change.
177    ///
178    /// # Arguments
179    ///
180    /// * `mask` - The classes of events the `Widget` wants.
181    pub fn set_event_mask(&mut self, mask: EventMask) {
182        self.event_mask = mask;
183    }
184
185    /// Adds an input controller, and adds the event classes it needs to the event mask.
186    ///
187    /// The default [`Widget::handle_event`] feeds every event to the controllers.  Call
188    /// [`WidgetCore::set_event_mask`] before this, not after, or the added classes are replaced.
189    ///
190    /// # Arguments
191    ///
192    /// * `controller` - The controller, such as [`ClickController`](crate::controllers::ClickController).
193    pub fn add_controller(&mut self, controller: impl Controller + 'static) {
194        self.event_mask = self.event_mask | controller.event_mask();
195        self.controllers.push(Box::new(controller));
196    }
197
198    /// Creates the shared state for a new `Widget`.
199    ///
200    /// The `Widget` starts visible, invalidated (so it is painted on the first frame), with a
201    /// transparent white background color.  Its ID and parent are assigned later, when it is added to
202    /// a `WidgetCache`.
203    ///
204    /// # Arguments
205    ///
206    /// * `origin` - The upper left-hand corner of the `Widget`, relative to its parent.
207    /// * `size` - The width and height of the `Widget` in pixels.
208    ///
209    /// # Returns
210    ///
211    /// A new `WidgetCore`, to be stored in a `Widget` structure.
212    pub fn new(origin: Point, size: Size) -> Self {
213        Self {
214            id: 0,
215            parent: ROOT_WIDGET_ID,
216            origin,
217            size,
218            color: Color::RGBA(255, 255, 255, 0),
219            behavior: Behavior::empty(),
220            state: VisualState::empty(),
221            appearance: Appearance::default(),
222            event_mask: EventMask::NONE,
223            invalidated: true,
224            controllers: Controllers::default(),
225        }
226    }
227}
228
229/// A drawable, interactive object presented in a window.
230///
231/// `Widget`s display information (text, images, graphics) and provide controls the user can
232/// interact with.  Every `Widget` stores a [`WidgetCore`] and implements three functions:
233/// [`core`](Widget::core), [`core_mut`](Widget::core_mut), and [`paint`](Widget::paint).
234/// Interactive `Widget`s also implement [`handle_event`](Widget::handle_event).  Every other
235/// function has a default implementation that works against the `WidgetCore`.
236///
237/// `Widget` requires `Any` so that the `WidgetCache` can return a `Widget` as its concrete type
238/// ([`WidgetCache::get_as`](crate::cache::WidgetCache::get_as)).
239pub trait Widget: Any {
240    /// Returns the `Widget`'s shared state.
241    ///
242    /// # Returns
243    ///
244    /// A reference to the [`WidgetCore`] stored in the `Widget`.
245    fn core(&self) -> &WidgetCore;
246
247    /// Returns the `Widget`'s shared state for modification.
248    ///
249    /// # Returns
250    ///
251    /// A mutable reference to the [`WidgetCore`] stored in the `Widget`.
252    fn core_mut(&mut self) -> &mut WidgetCore;
253
254    /// Paints the `Widget` into its own texture.
255    ///
256    /// The painter is already targeting the `Widget`'s surface, so drawing always starts at `(0, 0)`
257    /// and is bounded by [`get_size`](Widget::get_size).  Compose the look of the `Widget` with the
258    /// functions in the [`paint`](crate::paint) module (`fill`, `border`, `text`).  The `WidgetCache`
259    /// only calls this when the `Widget` is invalidated; between repaints, the texture is reused.
260    ///
261    /// # Arguments
262    ///
263    /// * `p` - The painter, targeting this `Widget`.  It is a Pushrod [`Painter`], never an `SDL2`
264    ///   type, so the `Widget` works with any backend.
265    fn paint(&self, p: &mut dyn Painter);
266
267    /// Handles an event sent to this `Widget`.
268    ///
269    /// The `WidgetCache` sends mouse events to the `Widget` under the pointer (or the `Widget` that
270    /// captured the mouse), and `PointerEntered` and `PointerExited` events when the pointer enters or leaves it.  Events
271    /// the `Widget` generates in response, such as `Clicked`, are queued with
272    /// [`EventCtx::emit`](crate::event::EventCtx::emit) and delivered to the application after event
273    /// processing completes.  The default implementation feeds the event to the `Widget`'s controllers
274    /// (see [`Widget::feed_controllers`]) and otherwise ignores it.
275    ///
276    /// # Arguments
277    ///
278    /// * `event` - The event sent to this `Widget`.
279    /// * `ctx` - The context used to queue events the `Widget` generates;
280    ///   [`EventCtx::phase`](crate::event::EventCtx::phase) says whether the event is being
281    ///   captured, handled as the target, or bubbled.
282    ///
283    /// # Returns
284    ///
285    /// [`Propagation::Stop`] to end delivery of an input event, or [`Propagation::Continue`] (the
286    /// default) to let the next `Widget` in the capture, target, bubble path see it.
287    fn handle_event(&mut self, event: &Event, ctx: &mut EventCtx) -> Propagation {
288        self.feed_controllers(event, ctx)
289    }
290
291    /// Feeds an event to the `Widget`'s controllers and calls
292    /// [`Widget::on_controller_event`] for each result, in order.
293    ///
294    /// The default [`Widget::handle_event`] is this call.  A `Widget` that overrides `handle_event`
295    /// calls it to keep its controllers working.
296    ///
297    /// # Arguments
298    ///
299    /// * `event` - The event sent to this `Widget`.
300    /// * `ctx` - The context passed on to `on_controller_event`.
301    ///
302    /// # Returns
303    ///
304    /// [`Propagation::Stop`] if any `on_controller_event` call returned it, otherwise
305    /// [`Propagation::Continue`].
306    fn feed_controllers(&mut self, event: &Event, ctx: &mut EventCtx) -> Propagation {
307        let id = self.get_id();
308        let results = self.core_mut().controllers.feed(id, event);
309        let mut propagation = Propagation::Continue;
310
311        for result in &results {
312            if self.on_controller_event(result, ctx) == Propagation::Stop {
313                propagation = Propagation::Stop;
314            }
315        }
316
317        propagation
318    }
319
320    /// Receives a high-level result from one of the `Widget`'s controllers.
321    ///
322    /// # Arguments
323    ///
324    /// * `_event` - What the controller reported, such as `ControllerEvent::Clicked`.
325    /// * `_ctx` - The context used to queue events the `Widget` generates.
326    ///
327    /// # Returns
328    ///
329    /// [`Propagation::Stop`] to end delivery of the raw event that produced it; the default
330    /// ignores the result and returns [`Propagation::Continue`].
331    fn on_controller_event(
332        &mut self,
333        _event: &ControllerEvent,
334        _ctx: &mut EventCtx,
335    ) -> Propagation {
336        Propagation::Continue
337    }
338
339    /// Returns `true` if this `Widget` wants input events in the capture phase.
340    ///
341    /// A capturing `Widget` sees pointer and key events *before* its descendants, and can return
342    /// [`Propagation::Stop`] to keep them from reaching the target.  Every `Widget` receives
343    /// events in the bubble phase regardless.
344    ///
345    /// # Returns
346    ///
347    /// `false` by default.
348    fn handles_capture(&self) -> bool {
349        false
350    }
351
352    /// Returns the classes of events this `Widget` wants to receive.
353    ///
354    /// The `WidgetCache` skips the `Widget` for every event whose class is not in this mask, so a
355    /// `Widget` that handles no events costs nothing.  An event is delivered only when it is also
356    /// in the run loop's mask.
357    ///
358    /// # Returns
359    ///
360    /// The mask; [`EventMask::NONE`] by default.  A `Widget` that handles events calls
361    /// `core_mut().set_event_mask(..)` at creation, or an application calls
362    /// [`WidgetCache::set_event_mask`](crate::cache::WidgetCache::set_event_mask).
363    fn event_mask(&self) -> EventMask {
364        self.core().event_mask
365    }
366
367    /// Returns the `Widget`'s ID.
368    ///
369    /// # Returns
370    ///
371    /// The ID assigned by the `WidgetCache` when the `Widget` was added, or `0` if it has not been
372    /// added yet.
373    fn get_id(&self) -> WidgetId {
374        self.core().id
375    }
376
377    /// Returns the ID of the `Widget`'s parent.
378    ///
379    /// # Returns
380    ///
381    /// The parent's ID.  The root `Widget` is its own parent.
382    fn get_parent(&self) -> WidgetId {
383        self.core().parent
384    }
385
386    /// Returns the `Widget`'s origin.
387    ///
388    /// # Returns
389    ///
390    /// The upper left-hand corner of the `Widget`, relative to its parent.  Use
391    /// [`WidgetCache::absolute_origin`](crate::cache::WidgetCache::absolute_origin) for window
392    /// coordinates.
393    fn get_origin(&self) -> Point {
394        self.core().origin
395    }
396
397    /// Returns the `Widget`'s size.
398    ///
399    /// # Returns
400    ///
401    /// The width and height of the `Widget` in pixels.
402    fn get_size(&self) -> Size {
403        self.core().size
404    }
405
406    /// Returns the `Widget`'s main (background) color.
407    ///
408    /// # Returns
409    ///
410    /// The background color.
411    fn get_color(&self) -> Color {
412        self.core().color
413    }
414
415    /// Moves the `Widget`, and invalidates it.
416    ///
417    /// # Arguments
418    ///
419    /// * `point` - The new upper left-hand corner, relative to the parent `Widget`.
420    fn set_origin(&mut self, point: Point) {
421        self.core_mut().origin = point;
422        self.set_invalidated(true);
423    }
424
425    /// Resizes the `Widget`, and invalidates it.  Its texture is resized on the next repaint.
426    ///
427    /// # Arguments
428    ///
429    /// * `size` - The new width and height in pixels.
430    fn set_size(&mut self, size: Size) {
431        self.core_mut().size = size;
432        self.set_invalidated(true);
433    }
434
435    /// Sets the `Widget`'s main (background) color, and invalidates it.
436    ///
437    /// # Arguments
438    ///
439    /// * `color` - The new background color.
440    fn set_color(&mut self, color: Color) {
441        self.core_mut().color = color;
442        self.set_invalidated(true);
443    }
444
445    /// Returns whether the `Widget` is hidden.
446    ///
447    /// Hidden `Widget`s and all of their children are not drawn and do not receive mouse events.
448    ///
449    /// # Returns
450    ///
451    /// `true` if the `Widget` is hidden, `false` if it is shown.
452    fn is_hidden(&self) -> bool {
453        self.core().behavior.contains(Behavior::HIDDEN)
454    }
455
456    /// Hides or shows the `Widget` and all of its children, and invalidates it.
457    ///
458    /// # Arguments
459    ///
460    /// * `state` - `true` to hide the `Widget`, `false` to show it.
461    fn set_hidden(&mut self, state: bool) {
462        self.core_mut().behavior.set(Behavior::HIDDEN, state);
463        self.set_invalidated(true);
464    }
465
466    /// Returns what the `Widget` can do.
467    ///
468    /// # Returns
469    ///
470    /// The `Widget`'s [`Behavior`] flags; none are set on a new `Widget`.
471    fn behavior(&self) -> Behavior {
472        self.core().behavior
473    }
474
475    /// Replaces the `Widget`'s behavior flags, and invalidates it.
476    ///
477    /// Setting or clearing [`Behavior::HIDDEN`] hides or shows the `Widget`, the same as
478    /// [`set_hidden`](Widget::set_hidden).
479    ///
480    /// # Arguments
481    ///
482    /// * `behavior` - The new flags.
483    fn set_behavior(&mut self, behavior: Behavior) {
484        self.core_mut().behavior = behavior;
485        self.set_invalidated(true);
486    }
487
488    /// Returns how the `Widget` currently looks.
489    ///
490    /// # Returns
491    ///
492    /// The `Widget`'s [`VisualState`] flags; none are set (the normal state) on a new `Widget`.
493    fn state(&self) -> VisualState {
494        self.core().state
495    }
496
497    /// Replaces the `Widget`'s visual state flags, and invalidates it only if the change can alter
498    /// how it looks.
499    ///
500    /// A change to `PRESSED`, `CHECKED`, `INDETERMINATE`, `DISABLED` or `FOCUSED` always repaints,
501    /// since built-in looks and the state overlay depend on them.  A change to `HOVERED` or
502    /// `DRAG_OVER` repaints only if the effective style (see [`Widget::style`]) changed.
503    ///
504    /// # Arguments
505    ///
506    /// * `state` - The new flags.
507    fn set_state(&mut self, state: VisualState) {
508        let old = self.core().state;
509
510        if old == state {
511            return;
512        }
513
514        let built_in = VisualState::PRESSED
515            | VisualState::CHECKED
516            | VisualState::INDETERMINATE
517            | VisualState::DISABLED
518            | VisualState::FOCUSED;
519        let appearance = &self.core().appearance;
520        let changed_look = appearance.effective(old) != appearance.effective(state);
521
522        self.core_mut().state = state;
523
524        if changed_look || (old ^ state).intersects(built_in) {
525            self.set_invalidated(true);
526        }
527    }
528
529    /// Returns the `Widget`'s per-state appearance.
530    ///
531    /// # Returns
532    ///
533    /// The [`Appearance`] holding one [`StateStyle`] per visual state.
534    fn appearance(&self) -> &Appearance {
535        &self.core().appearance
536    }
537
538    /// Returns the `Widget`'s per-state appearance for modification, and invalidates the `Widget`.
539    ///
540    /// Use [`Widget::set_style`] to change one state and repaint only when it matters.
541    ///
542    /// # Returns
543    ///
544    /// The [`Appearance`], to be edited in place.
545    fn appearance_mut(&mut self) -> &mut Appearance {
546        self.set_invalidated(true);
547        &mut self.core_mut().appearance
548    }
549
550    /// Sets the style for one visual state, and invalidates the `Widget` only if the effective
551    /// style for its current state changed.
552    ///
553    /// # Arguments
554    ///
555    /// * `state` - The visual state flag to style, such as [`VisualState::HOVERED`]; an empty set
556    ///   styles the normal state.
557    /// * `style` - The overrides for that state.
558    fn set_style(&mut self, state: VisualState, style: StateStyle) {
559        let current = self.core().state;
560        let before = self.core().appearance.effective(current);
561
562        self.core_mut().appearance.set(state, style);
563
564        if self.core().appearance.effective(current) != before {
565            self.set_invalidated(true);
566        }
567    }
568
569    /// Returns the effective style for the `Widget`'s current state.
570    ///
571    /// The style for the highest-priority active state wins, unset fields fall back to `normal`,
572    /// and fields still `None` mean "use the built-in default".  `paint` implementations read
573    /// this.
574    ///
575    /// # Returns
576    ///
577    /// The resolved [`StateStyle`].
578    fn style(&self) -> StateStyle {
579        self.core().appearance.effective(self.core().state)
580    }
581
582    /// Returns whether the `Widget` is enabled.
583    ///
584    /// Disabled `Widget`s ([`VisualState::DISABLED`]) receive no input and cannot take focus.
585    ///
586    /// # Returns
587    ///
588    /// `true` if the `Widget` is enabled, `false` if it is disabled.
589    fn is_enabled(&self) -> bool {
590        !self.core().state.contains(VisualState::DISABLED)
591    }
592
593    /// Enables or disables the `Widget`, and invalidates it if that changed it.
594    ///
595    /// # Arguments
596    ///
597    /// * `enabled` - `true` to enable the `Widget`, `false` to disable it.
598    fn set_enabled(&mut self, enabled: bool) {
599        let mut state = self.core().state;
600
601        state.set(VisualState::DISABLED, !enabled);
602        self.set_state(state);
603    }
604
605    /// Returns whether the `Widget` can take keyboard focus.
606    ///
607    /// # Returns
608    ///
609    /// `true` if the `Widget` is [`Behavior::FOCUSABLE`], enabled, and not hidden.
610    fn is_focusable(&self) -> bool {
611        self.behavior().contains(Behavior::FOCUSABLE) && self.is_enabled() && !self.is_hidden()
612    }
613
614    /// Returns whether the `Widget` is a text editor.
615    ///
616    /// While a `Widget` that returns `true` has the keyboard focus, the `Engine` asks the
617    /// operating system for text input, so typed characters arrive as
618    /// [`Event::TextEntered`].  Override it in text fields and
619    /// editors; the default is `false`.
620    ///
621    /// # Returns
622    ///
623    /// `true` if the `Widget` accepts typed text.
624    fn accepts_text_input(&self) -> bool {
625        false
626    }
627
628    /// Returns whether the `Widget` needs to be repainted.
629    ///
630    /// # Returns
631    ///
632    /// `true` if the `Widget` will be repainted into its texture on the next frame.
633    fn is_invalidated(&self) -> bool {
634        self.core().invalidated
635    }
636
637    /// Sets whether the `Widget` needs to be repainted.
638    ///
639    /// Setters call this automatically.  Call it after changing state that affects how the `Widget`
640    /// looks.  An invalidated `Widget` is repainted into its texture on the next frame, and the screen
641    /// is refreshed.
642    ///
643    /// # Arguments
644    ///
645    /// * `state` - `true` to repaint the `Widget` on the next frame.
646    fn set_invalidated(&mut self, state: bool) {
647        self.core_mut().invalidated = state;
648    }
649}