Skip to main content

hyprforge_ui/widgets/
controls.rs

1//! The controls a setting row holds: a switch, a slider with its value
2//! beside it, a dropdown, and a segmented choice.
3//!
4//! Each is iced's own widget with the suite's look applied, not a
5//! reimplementation — the behaviour (keyboard, dragging, the open menu)
6//! is iced's and stays iced's.
7
8use super::field::inset_field_style;
9use crate::density;
10use crate::theme::{self, surface, FontScale};
11use iced::widget::overlay::menu;
12use iced::widget::{button, container, pick_list, row, slider, text, toggler, Toggler};
13use iced::{Background, Border, Element, Length};
14
15// --- toggle ----------------------------------------------------------------
16
17/// A switch's height at 100% scale; iced draws it twice as wide.
18///
19/// The mockup's switch is about 38×22. iced's `size` is the height, and
20/// the track is `2 × size` wide, so 20 lands within a couple of pixels of
21/// both.
22const TOGGLE_BASE: f32 = 20.0;
23
24/// An on/off switch — what every boolean setting is, rather than a
25/// checkbox.
26///
27/// A checkbox reads as "include this in something", which is right for
28/// picking rows and wrong for a setting that is simply on or off. The
29/// caller attaches `on_toggle`; a switch without one is drawn disabled,
30/// which is how iced says "you cannot change this here".
31pub fn toggle<'a, Message: 'a>(is_on: bool, scale: FontScale) -> Toggler<'a, Message> {
32    toggler(is_on).size(scale.apply(TOGGLE_BASE)).style(toggle_style)
33}
34
35/// The switch's look: the accent when on, the border grey when off, a
36/// dark knob either way.
37///
38/// On is the accent because "on" is one of the two things purple means
39/// here (the other is "selected"). Off is not a state colour — off is
40/// not an error — so it is the lightest grey in the ramp.
41pub fn toggle_style(t: &iced::Theme, status: toggler::Status) -> toggler::Style {
42    let palette = t.extended_palette();
43    let (is_on, hovered, disabled) = match status {
44        toggler::Status::Active { is_toggled } => (is_toggled, false, false),
45        toggler::Status::Hovered { is_toggled } => (is_toggled, true, false),
46        toggler::Status::Disabled { is_toggled } => (is_toggled, false, true),
47    };
48    let track = match (is_on, hovered) {
49        (true, false) => palette.primary.base.color,
50        (true, true) => palette.primary.strong.color,
51        (false, _) => surface::card_border(),
52    };
53    let fade = |c: iced::Color| if disabled { iced::Color { a: c.a * 0.5, ..c } } else { c };
54    toggler::Style {
55        background: Background::Color(fade(track)),
56        // Off and hovered gets an outline, so pointing at a switch that
57        // is off still says "this responds" without borrowing the accent
58        // that would make it look on.
59        background_border_width: if hovered && !is_on { 1.0 } else { 0.0 },
60        background_border_color: theme::text_dim(),
61        foreground: Background::Color(fade(surface::sidebar())),
62        foreground_border_width: 0.0,
63        foreground_border_color: iced::Color::TRANSPARENT,
64        text_color: Some(theme::text()),
65        border_radius: None,
66        padding_ratio: 0.14,
67    }
68}
69
70// --- sliders ---------------------------------------------------------------
71
72/// How wide a slider's track is at 100%. The mockup's 150px: long enough
73/// to place a value by eye, short enough to leave the label its room.
74const SLIDER_WIDTH_BASE: f32 = 150.0;
75
76/// Room for the readout beside a slider — "12 px", "1.60×" — so the
77/// track does not shuffle sideways as the number gains a digit.
78const READOUT_WIDTH_BASE: f32 = 56.0;
79
80/// A slider with its value written beside it in the mono font.
81///
82/// The readout is what makes a slider usable for a setting: dragging to
83/// "about there" is fine for volume and useless for a gap in pixels,
84/// where the number is the point. The caller formats it, because only
85/// the caller knows whether it is pixels, a scale or a percentage.
86///
87/// `on_release` is for settings that write a file: sending every
88/// intermediate value of a drag to disk is a rewrite per pixel.
89pub fn value_slider<'a, Message: Clone + 'a>(
90    range: std::ops::RangeInclusive<f32>,
91    value: f32,
92    step: f32,
93    on_change: impl Fn(f32) -> Message + 'a,
94    on_release: Option<Message>,
95    readout: String,
96    scale: FontScale,
97) -> Element<'a, Message> {
98    let mut track = slider(range, value, on_change)
99        .step(step)
100        .width(Length::Fixed(scale.apply(SLIDER_WIDTH_BASE)))
101        .style(slider_style);
102    if let Some(release) = on_release {
103        track = track.on_release(release);
104    }
105    row![
106        track,
107        text(readout)
108            .font(theme::mono_font())
109            .size(scale.apply(density::META_TEXT_BASE))
110            .color(theme::text())
111            .width(Length::Fixed(scale.apply(READOUT_WIDTH_BASE)))
112            .align_x(iced::alignment::Horizontal::Right),
113    ]
114    .spacing(crate::theme::spacing::SM)
115    .align_y(iced::Alignment::Center)
116    .into()
117}
118
119/// A slider over a list of values, where only the listed ones exist.
120///
121/// A monitor's scale is the case this is for: Hyprland accepts 1.0,
122/// 1.25, 1.6 and not 1.4, so a continuous slider would offer values that
123/// get refused. This one slides over *positions* in the list, so there is
124/// no position between two valid values to land on. The caller keeps the
125/// list and looks the value up by index.
126///
127/// A list of one or none has nothing to slide between, so it is drawn as
128/// its readout alone rather than as a track with its handle stuck.
129pub fn stepped_slider<'a, Message: Clone + 'a>(
130    count: usize,
131    index: usize,
132    on_change: impl Fn(usize) -> Message + 'a,
133    on_release: Option<Message>,
134    readout: String,
135    scale: FontScale,
136) -> Element<'a, Message> {
137    if count < 2 {
138        return text(readout)
139            .font(theme::mono_font())
140            .size(scale.apply(density::META_TEXT_BASE))
141            .into();
142    }
143    let last = (count - 1) as f32;
144    value_slider(
145        0.0..=last,
146        index.min(count - 1) as f32,
147        1.0,
148        move |raw| on_change(step_index(count, raw)),
149        on_release,
150        readout,
151        scale,
152    )
153}
154
155/// The list position a slider's raw value means: the nearest one, never
156/// past either end.
157///
158/// iced's `step` already rounds, but a drag can deliver the range's own
159/// end as a float that is not quite an integer, and a value from outside
160/// the range must not index past the list. `NaN` is the first position,
161/// because it is the only answer that is always valid.
162pub fn step_index(count: usize, raw: f32) -> usize {
163    if count == 0 || !raw.is_finite() {
164        return 0;
165    }
166    (raw.round().max(0.0) as usize).min(count - 1)
167}
168
169/// The track: accent up to the handle, border grey after it, and a
170/// light handle — the mockup's rail.
171pub fn slider_style(t: &iced::Theme, status: slider::Status) -> slider::Style {
172    let palette = t.extended_palette();
173    let filled = match status {
174        slider::Status::Active => palette.primary.base.color,
175        slider::Status::Hovered | slider::Status::Dragged => palette.primary.strong.color,
176    };
177    slider::Style {
178        rail: slider::Rail {
179            backgrounds: (Background::Color(filled), Background::Color(surface::card_border())),
180            width: 4.0,
181            border: Border { radius: 2.0.into(), ..Border::default() },
182        },
183        handle: slider::Handle {
184            shape: slider::HandleShape::Circle { radius: 7.0 },
185            background: Background::Color(theme::text()),
186            border_width: 0.0,
187            border_color: iced::Color::TRANSPARENT,
188        },
189    }
190}
191
192// --- dropdown --------------------------------------------------------------
193
194/// A closed `pick_list`'s look: the inset field's, so a dropdown beside a
195/// text field reads as the same kind of control.
196///
197/// Apply as `.style(dropdown_style).menu_style(dropdown_menu_style)`.
198/// Style functions rather than a wrapper widget, because `pick_list` is
199/// generic over what it lists and how, and a wrapper would have to
200/// re-expose every one of those parameters to add nothing.
201pub fn dropdown_style(t: &iced::Theme, status: pick_list::Status) -> pick_list::Style {
202    let inset = inset_field_style(t);
203    let border = match status {
204        pick_list::Status::Active => inset.border,
205        // Hover and open outline in the dim text colour, not the accent:
206        // an open menu is not a selection.
207        pick_list::Status::Hovered | pick_list::Status::Opened { .. } => {
208            Border { color: theme::text_dim(), ..inset.border }
209        }
210    };
211    pick_list::Style {
212        text_color: theme::text(),
213        placeholder_color: theme::text_dim(),
214        handle_color: theme::text_dim(),
215        background: inset.background.unwrap_or(Background::Color(surface::card())),
216        border,
217    }
218}
219
220/// An open dropdown's list. The highlighted option is the selection
221/// colour, because it is the option you are about to select.
222pub fn dropdown_menu_style(t: &iced::Theme) -> menu::Style {
223    let palette = t.extended_palette();
224    menu::Style {
225        background: Background::Color(surface::card()),
226        border: Border {
227            radius: density::inner_radius().into(),
228            width: 1.0,
229            color: surface::card_border(),
230        },
231        text_color: theme::text(),
232        selected_text_color: theme::text(),
233        selected_background: Background::Color(palette.primary.weak.color),
234        shadow: iced::Shadow::default(),
235    }
236}
237
238// --- segmented -------------------------------------------------------------
239
240/// What the lit segment of a segmented control means.
241#[derive(Debug, Clone, Copy, PartialEq, Eq)]
242pub enum SegmentLook {
243    /// A mode of the window — Files' list/grid switch. The lit segment is
244    /// an elevation step, not the accent: the mode is not a selection,
245    /// and a second purple on the bar would compete with the one that
246    /// means "selected".
247    Quiet,
248    /// The value of a setting — Dwindle or Master, Off/Always/Fullscreen.
249    /// The lit segment *is* the chosen value, so it is the accent.
250    Choice,
251}
252
253/// One segment's look, for a button placed inside [`segmented`].
254pub fn segment_style(
255    look: SegmentLook,
256    active: bool,
257) -> impl Fn(&iced::Theme, button::Status) -> button::Style {
258    move |t, status| {
259        let palette = t.extended_palette();
260        let hovered = matches!(status, button::Status::Hovered);
261        let (background, text_color) = match (look, active) {
262            (SegmentLook::Choice, true) => {
263                (Some(palette.primary.base.color), palette.primary.base.text)
264            }
265            (SegmentLook::Quiet, true) => (Some(surface::row()), theme::text()),
266            (_, false) => (hovered.then(surface::row), theme::text_dim()),
267        };
268        button::Style {
269            background: background.map(Background::Color),
270            text_color,
271            border: Border { radius: density::nested_radius().into(), ..Border::default() },
272            ..button::Style::default()
273        }
274    }
275}
276
277/// The groove a row of segments sits in.
278///
279/// Filled with the sidebar's colour rather than the inset fields', so it
280/// reads as a groove cut into the surface rather than as a raised control.
281pub fn segmented<'a, Message: 'a>(
282    segments: impl IntoIterator<Item = Element<'a, Message>>,
283) -> Element<'a, Message> {
284    container(row(segments).spacing(3.0).align_y(iced::Alignment::Center))
285        .padding(3.0)
286        .style(|_t: &iced::Theme| container::Style {
287            background: Some(Background::Color(surface::sidebar())),
288            border: Border {
289                radius: density::inner_radius().into(),
290                width: 1.0,
291                color: surface::card_border(),
292            },
293            ..container::Style::default()
294        })
295        .into()
296}
297
298/// A setting whose value is one of a few named options, shown all at
299/// once — the mockup's `Off | Always | Fullscreen`.
300///
301/// For three or four short options. Past that the row runs out of room
302/// and a dropdown is the honest control.
303pub fn segmented_choice<'a, T, Message>(
304    options: &[T],
305    selected: Option<&T>,
306    label: impl Fn(&T) -> String,
307    on_select: impl Fn(T) -> Message,
308    scale: FontScale,
309) -> Element<'a, Message>
310where
311    T: Clone + PartialEq,
312    Message: Clone + 'a,
313{
314    segmented(options.iter().map(|option| {
315        let active = selected == Some(option);
316        button(text(label(option)).size(scale.apply(density::META_TEXT_BASE)))
317            .padding([2.0, scale.apply(10.0)])
318            .on_press(on_select(option.clone()))
319            .style(segment_style(SegmentLook::Choice, active))
320            .into()
321    }))
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327
328    /// A monitor's scales are a list, not a range: no drag may produce a
329    /// position between two of them, or past either end.
330    #[test]
331    fn the_scale_slider_cannot_land_between_valid_scales() {
332        let scales = [1.0, 1.25, 1.6, 2.0];
333        let n = scales.len();
334        let mut raw = -1.0_f32;
335        while raw <= n as f32 + 1.0 {
336            let i = step_index(n, raw);
337            assert!(i < n, "{raw} indexed past the list");
338            assert!(scales.contains(&scales[i]));
339            raw += 0.05;
340        }
341        assert_eq!(step_index(n, 1.49), 1);
342        assert_eq!(step_index(n, 1.51), 2);
343        assert_eq!(step_index(n, f32::NAN), 0);
344        assert_eq!(step_index(0, 3.0), 0, "an empty list still answers");
345    }
346
347    /// On is the accent and off is not — and off is never a state
348    /// colour, because a setting being off is not an error.
349    #[test]
350    fn a_switch_is_the_accent_when_on_and_plain_grey_when_off() {
351        let t = theme::app_theme();
352        let accent = t.extended_palette().primary.base.color;
353        let on = toggle_style(&t, toggler::Status::Active { is_toggled: true });
354        let off = toggle_style(&t, toggler::Status::Active { is_toggled: false });
355        assert_eq!(on.background, Background::Color(accent));
356        assert_eq!(off.background, Background::Color(surface::card_border()));
357        for state in [theme::error(), theme::warning(), theme::success(), theme::info()] {
358            assert_ne!(off.background, Background::Color(state));
359        }
360    }
361
362    /// Only a `Choice` segment lights up in the accent. Files' view-mode
363    /// switch is a mode, not a value, and a second purple on its bar
364    /// would read as a second selection.
365    #[test]
366    fn only_a_value_choice_lights_its_segment_in_the_accent() {
367        let t = theme::app_theme();
368        let accent = Some(Background::Color(t.extended_palette().primary.base.color));
369        let choice = segment_style(SegmentLook::Choice, true)(&t, button::Status::Active);
370        let quiet = segment_style(SegmentLook::Quiet, true)(&t, button::Status::Active);
371        assert_eq!(choice.background, accent);
372        assert_ne!(quiet.background, accent);
373        for look in [SegmentLook::Choice, SegmentLook::Quiet] {
374            let hovered = segment_style(look, false)(&t, button::Status::Hovered);
375            assert_ne!(hovered.background, accent, "hovering is not choosing ({look:?})");
376        }
377    }
378}