Skip to main content

pushrod/
appearance.rs

1// Per-state appearance
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//! # Per-state appearance
17//!
18//! A [`StateStyle`] is a set of optional look overrides (background, foreground, border color,
19//! border width, font).  An [`Appearance`] holds one `StateStyle` for each visual state a `Widget`
20//! can be in.  `Widget`s read the *effective* style for their current [`VisualState`] with
21//! [`Widget::style`](crate::widget::Widget::style), so applications can say "this button turns blue
22//! on hover" without any widget code.
23//!
24//! ```text
25//! state change ──> effective style = appearance[state] ⟶ falls back to appearance.normal ⟶ built-in default
26//!                   │
27//!                   └─> repaint only if the effective style changed
28//! ```
29//!
30//! # Examples
31//!
32//! ```rust
33//! use pushrod::appearance::{Appearance, StateStyle};
34//! use pushrod::color::Color;
35//! use pushrod::widget::VisualState;
36//!
37//! let mut appearance = Appearance::default();
38//!
39//! appearance.set(
40//!     VisualState::HOVERED,
41//!     StateStyle {
42//!         background: Some(Color::BLUE),
43//!         ..StateStyle::default()
44//!     },
45//! );
46//!
47//! assert_eq!(appearance.effective(VisualState::HOVERED).background, Some(Color::BLUE));
48//! assert_eq!(appearance.effective(VisualState::empty()).background, None);
49//! ```
50
51use crate::color::Color;
52use crate::paint::TextStyle;
53use crate::widget::VisualState;
54
55/// Look overrides for one visual state.  A field left `None` is not overridden: it falls back to
56/// the `normal` style, and then to the `Widget`'s built-in default.
57#[derive(Debug, Clone, PartialEq, Default)]
58pub struct StateStyle {
59    /// The background fill color.
60    pub background: Option<Color>,
61    /// The text (foreground) color.
62    pub foreground: Option<Color>,
63    /// The border color.
64    pub border_color: Option<Color>,
65    /// The border width in pixels.
66    pub border_width: Option<u8>,
67    /// The font, size, and alignment of the text.
68    pub font: Option<TextStyle>,
69}
70
71impl StateStyle {
72    /// Returns whether no field is overridden.
73    ///
74    /// # Returns
75    ///
76    /// `true` if every field is `None`.
77    pub fn is_empty(&self) -> bool {
78        *self == StateStyle::default()
79    }
80
81    /// Fills each field that is `None` from `fallback`.
82    ///
83    /// # Arguments
84    ///
85    /// * `fallback` - The style that supplies the missing fields.
86    ///
87    /// # Returns
88    ///
89    /// The merged style.
90    pub fn or(self, fallback: &StateStyle) -> StateStyle {
91        StateStyle {
92            background: self.background.or(fallback.background),
93            foreground: self.foreground.or(fallback.foreground),
94            border_color: self.border_color.or(fallback.border_color),
95            border_width: self.border_width.or(fallback.border_width),
96            font: self.font.or_else(|| fallback.font.clone()),
97        }
98    }
99}
100
101/// The order in which active states are looked up: the first state that is set *and* has a style
102/// wins.  `DISABLED` always beats the interaction states.
103const PRIORITY: [VisualState; 6] = [
104    VisualState::DISABLED,
105    VisualState::DRAG_OVER,
106    VisualState::PRESSED,
107    VisualState::CHECKED,
108    VisualState::HOVERED,
109    VisualState::FOCUSED,
110];
111
112/// One [`StateStyle`] for each visual state of a `Widget`.
113///
114/// `INDETERMINATE` has no style of its own; it is drawn by the generic state overlay.
115#[derive(Debug, Clone, PartialEq, Default)]
116pub struct Appearance {
117    /// The look with no state flags set; every other state falls back to it.
118    pub normal: StateStyle,
119    /// The mouse button is held down on the `Widget`.
120    pub pressed: StateStyle,
121    /// The pointer is inside the `Widget`.
122    pub hovered: StateStyle,
123    /// The `Widget` has keyboard focus.
124    pub focused: StateStyle,
125    /// The `Widget` is disabled.
126    pub disabled: StateStyle,
127    /// The `Widget` is checked or selected.
128    pub checked: StateStyle,
129    /// A drag is over the `Widget`.
130    pub drag_over: StateStyle,
131}
132
133impl Appearance {
134    /// Returns the style stored for one state.
135    ///
136    /// # Arguments
137    ///
138    /// * `state` - One visual state flag; an empty set selects `normal`.  Anything else without
139    ///   its own style (such as `INDETERMINATE`) also selects `normal`.
140    ///
141    /// # Returns
142    ///
143    /// A reference to the stored style.
144    pub fn get(&self, state: VisualState) -> &StateStyle {
145        match state {
146            s if s == VisualState::PRESSED => &self.pressed,
147            s if s == VisualState::HOVERED => &self.hovered,
148            s if s == VisualState::FOCUSED => &self.focused,
149            s if s == VisualState::DISABLED => &self.disabled,
150            s if s == VisualState::CHECKED => &self.checked,
151            s if s == VisualState::DRAG_OVER => &self.drag_over,
152            _ => &self.normal,
153        }
154    }
155
156    /// Replaces the style stored for one state.
157    ///
158    /// # Arguments
159    ///
160    /// * `state` - One visual state flag; an empty set (or a flag with no style) sets `normal`.
161    /// * `style` - The new style.
162    pub fn set(&mut self, state: VisualState, style: StateStyle) {
163        match state {
164            s if s == VisualState::PRESSED => self.pressed = style,
165            s if s == VisualState::HOVERED => self.hovered = style,
166            s if s == VisualState::FOCUSED => self.focused = style,
167            s if s == VisualState::DISABLED => self.disabled = style,
168            s if s == VisualState::CHECKED => self.checked = style,
169            s if s == VisualState::DRAG_OVER => self.drag_over = style,
170            _ => self.normal = style,
171        }
172    }
173
174    /// Resolves the style to draw for a set of state flags.
175    ///
176    /// The active states are checked in the order disabled, drag-over, pressed, checked, hovered,
177    /// focused; the first one that has a style wins.  Fields it leaves unset come from `normal`.
178    /// Fields still unset are `None`, meaning "use the `Widget`'s built-in default".
179    ///
180    /// # Arguments
181    ///
182    /// * `state` - The `Widget`'s current visual state flags.
183    ///
184    /// # Returns
185    ///
186    /// The effective style.
187    pub fn effective(&self, state: VisualState) -> StateStyle {
188        PRIORITY
189            .iter()
190            .filter(|flag| state.contains(**flag))
191            .map(|flag| self.get(*flag))
192            .find(|style| !style.is_empty())
193            .cloned()
194            .unwrap_or_default()
195            .or(&self.normal)
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202    use crate::color::Color;
203
204    fn bg(color: Color) -> StateStyle {
205        StateStyle {
206            background: Some(color),
207            ..StateStyle::default()
208        }
209    }
210
211    #[test]
212    fn empty_appearance_resolves_to_no_overrides() {
213        let a = Appearance::default();
214
215        assert!(a.effective(VisualState::empty()).is_empty());
216        assert!(
217            a.effective(VisualState::HOVERED | VisualState::PRESSED)
218                .is_empty()
219        );
220    }
221
222    #[test]
223    fn unset_state_falls_back_to_normal() {
224        let mut a = Appearance::default();
225
226        a.set(VisualState::empty(), bg(Color::GRAY));
227
228        assert_eq!(
229            a.effective(VisualState::HOVERED).background,
230            Some(Color::GRAY)
231        );
232    }
233
234    #[test]
235    fn unset_fields_fall_back_to_normal_field_by_field() {
236        let mut a = Appearance::default();
237
238        a.set(
239            VisualState::empty(),
240            StateStyle {
241                background: Some(Color::WHITE),
242                border_width: Some(1),
243                ..StateStyle::default()
244            },
245        );
246        a.set(VisualState::HOVERED, bg(Color::BLUE));
247
248        let e = a.effective(VisualState::HOVERED);
249
250        assert_eq!(e.background, Some(Color::BLUE));
251        assert_eq!(e.border_width, Some(1));
252    }
253
254    #[test]
255    fn priority_is_disabled_dragover_pressed_checked_hovered_focused() {
256        let mut a = Appearance::default();
257
258        a.set(VisualState::FOCUSED, bg(Color::GREEN));
259        a.set(VisualState::HOVERED, bg(Color::CYAN));
260        a.set(VisualState::CHECKED, bg(Color::YELLOW));
261        a.set(VisualState::PRESSED, bg(Color::BLUE));
262        a.set(VisualState::DRAG_OVER, bg(Color::MAGENTA));
263        a.set(VisualState::DISABLED, bg(Color::GRAY));
264
265        let all = VisualState::all();
266
267        assert_eq!(a.effective(all).background, Some(Color::GRAY));
268        assert_eq!(
269            a.effective(all - VisualState::DISABLED).background,
270            Some(Color::MAGENTA)
271        );
272        assert_eq!(
273            a.effective(VisualState::PRESSED | VisualState::CHECKED | VisualState::HOVERED)
274                .background,
275            Some(Color::BLUE)
276        );
277        assert_eq!(
278            a.effective(VisualState::CHECKED | VisualState::HOVERED)
279                .background,
280            Some(Color::YELLOW)
281        );
282        assert_eq!(
283            a.effective(VisualState::HOVERED | VisualState::FOCUSED)
284                .background,
285            Some(Color::CYAN)
286        );
287    }
288
289    #[test]
290    fn an_active_state_without_a_style_is_skipped() {
291        let mut a = Appearance::default();
292
293        a.set(VisualState::HOVERED, bg(Color::CYAN));
294
295        // PRESSED is active but has no style, so HOVERED still applies.
296        assert_eq!(
297            a.effective(VisualState::PRESSED | VisualState::HOVERED)
298                .background,
299            Some(Color::CYAN)
300        );
301    }
302
303    #[test]
304    fn set_and_get_round_trip_every_state() {
305        let mut a = Appearance::default();
306        let states = [
307            VisualState::PRESSED,
308            VisualState::HOVERED,
309            VisualState::FOCUSED,
310            VisualState::DISABLED,
311            VisualState::CHECKED,
312            VisualState::DRAG_OVER,
313            VisualState::empty(),
314        ];
315
316        for (i, state) in states.iter().enumerate() {
317            a.set(*state, bg(Color::RGB(i as u8, 0, 0)));
318        }
319
320        for (i, state) in states.iter().enumerate() {
321            assert_eq!(a.get(*state).background, Some(Color::RGB(i as u8, 0, 0)));
322        }
323    }
324}