Skip to main content

hyprforge_ui/widgets/
marquee.rs

1//! Rubber-band selection: drag across empty space to draw a box, and
2//! everything the box touches is selected — what every desktop file
3//! manager does, and the one way to select a block of icons in a grid
4//! without the keyboard.
5//!
6//! A widget of its own around the whole listing, not around the rows,
7//! because the band almost always *starts* where there are no rows: in
8//! the gap beside a short list, or below the last icon. It hands every
9//! press to its content first and starts a band only when nothing there
10//! took it ([`Shell::is_event_captured`]) — so a press on a row is still
11//! that row's click, its double click, its drag, and the band is exactly
12//! "a press on nothing".
13//!
14//! It knows nothing about rows. The caller tags each one with a container
15//! [`Id`] and hands over `targets`, id to index; the band asks the layout
16//! which of those containers it meets, through an [`Operation`] over its
17//! own content — scrolled content reports bounds that have not moved with
18//! the scroll, so the operation carries each scrollable's translation and
19//! visible region, as `hyprforge-files-core`'s drop hit-test does. The
20//! caller can leave `targets` empty until it hears `on_start`, so a frame
21//! with no band in progress tags nothing.
22//!
23//! The band is anchored in the *content*, not the window: scroll while
24//! dragging — the wheel, or the automatic scroll near an edge — and the
25//! corner you started at moves with what was under it, the way it does in
26//! every file manager, rather than staying put on the screen while the
27//! rows slide past it.
28
29use iced::advanced::layout;
30use iced::advanced::mouse;
31use iced::advanced::overlay;
32use iced::advanced::renderer;
33use iced::advanced::widget::operation::scrollable::AbsoluteOffset;
34use iced::advanced::widget::operation::{self, Operation};
35use iced::advanced::widget::{tree, Id, Tree};
36use iced::advanced::{Clipboard, Layout, Shell, Widget};
37use iced::{keyboard, window, Border, Color, Element, Event, Length, Point, Rectangle, Size, Vector};
38use std::collections::HashMap;
39
40/// How far a press on empty space travels before it is a band rather
41/// than a click — the same as a row's drag threshold, so the hand finds
42/// one distance for both.
43pub const THRESHOLD: f32 = 8.0;
44
45/// How close to the top or bottom edge the pointer has to be, in logical
46/// pixels, before the listing scrolls on its own to follow the band.
47pub const EDGE: f32 = 36.0;
48
49/// The fastest automatic scroll, in logical pixels per frame — reached
50/// with the pointer at or past the edge, scaled down further in.
51pub const SPEED: f32 = 18.0;
52
53/// What `on_select` is handed: the targets met, and whether the band adds.
54type OnSelect<'a, Message> = Box<dyn Fn(Vec<usize>, bool) -> Message + 'a>;
55
56/// `content`, with a rubber band drawn across empty space. See the
57/// module doc.
58pub struct Marquee<'a, Message, Theme = iced::Theme, Renderer = iced::Renderer> {
59    content: Element<'a, Message, Theme, Renderer>,
60    targets: HashMap<Id, usize>,
61    scroll: Option<Id>,
62    on_start: Option<Message>,
63    on_select: Option<OnSelect<'a, Message>>,
64    on_end: Option<Message>,
65    on_clear: Option<Message>,
66}
67
68pub fn marquee<'a, Message, Theme, Renderer>(
69    content: impl Into<Element<'a, Message, Theme, Renderer>>,
70) -> Marquee<'a, Message, Theme, Renderer> {
71    Marquee {
72        content: content.into(),
73        targets: HashMap::new(),
74        scroll: None,
75        on_start: None,
76        on_select: None,
77        on_end: None,
78        on_clear: None,
79    }
80}
81
82impl<'a, Message, Theme, Renderer> Marquee<'a, Message, Theme, Renderer> {
83    /// The containers the band can select, by id, and what each is to the
84    /// caller — a row's index.
85    pub fn targets(mut self, targets: HashMap<Id, usize>) -> Self {
86        self.targets = targets;
87        self
88    }
89
90    /// The scrollable inside that holds the targets: what the band
91    /// anchors to, and what scrolls when the pointer nears an edge.
92    pub fn scroll(mut self, id: Id) -> Self {
93        self.scroll = Some(id);
94        self
95    }
96
97    /// A band began — the press on nothing has travelled past
98    /// `THRESHOLD`.
99    pub fn on_start(mut self, message: Message) -> Self {
100        self.on_start = Some(message);
101        self
102    }
103
104    /// The targets the band meets now, in ascending order, and whether
105    /// Ctrl or Shift is held — adding to what was selected before the
106    /// band began rather than replacing it. Published only when the set
107    /// changes.
108    pub fn on_select(mut self, f: impl Fn(Vec<usize>, bool) -> Message + 'a) -> Self {
109        self.on_select = Some(Box::new(f));
110        self
111    }
112
113    /// The band was let go.
114    pub fn on_end(mut self, message: Message) -> Self {
115        self.on_end = Some(message);
116        self
117    }
118
119    /// A click on empty space that never became a band: in every file
120    /// manager, what clears the selection.
121    pub fn on_clear(mut self, message: Message) -> Self {
122        self.on_clear = Some(message);
123        self
124    }
125}
126
127/// The band's own state between events.
128#[derive(Debug, Clone, Default)]
129struct State {
130    /// Where an uncaptured left press went down, in window coordinates,
131    /// while the button is held.
132    press: Option<Point>,
133    /// The same point in the scrolled content's coordinates — the corner
134    /// that moves with the rows.
135    anchor: Point,
136    /// Past the threshold: a band, not a click.
137    active: bool,
138    /// The pointer, in window coordinates.
139    cursor: Point,
140    /// The scroll translation last seen for `scroll`.
141    translation: Vector,
142    /// What `on_select` last published, so an unchanged set is not sent
143    /// again on every pixel of movement.
144    last: Vec<usize>,
145    modifiers: keyboard::Modifiers,
146}
147
148/// The rectangle between the anchor — moved by however far the content
149/// has scrolled since — and the pointer, in window coordinates.
150pub fn band_rect(anchor: Point, translation: Vector, cursor: Point) -> Rectangle {
151    let start = anchor - translation;
152    let (x0, x1) = (start.x.min(cursor.x), start.x.max(cursor.x));
153    let (y0, y1) = (start.y.min(cursor.y), start.y.max(cursor.y));
154    Rectangle { x: x0, y: y0, width: x1 - x0, height: y1 - y0 }
155}
156
157/// How far to scroll this frame for a pointer at `y` over a viewport
158/// spanning `top..bottom`: nothing in the middle, up to `SPEED` at and
159/// past either edge, proportionally within `EDGE` of it.
160pub fn edge_scroll(y: f32, top: f32, bottom: f32) -> f32 {
161    let ramp = |into: f32| SPEED * (1.0 - (into / EDGE)).clamp(0.0, 1.0);
162    if y < top + EDGE {
163        -ramp(y - top)
164    } else if y > bottom - EDGE {
165        ramp(bottom - y)
166    } else {
167        0.0
168    }
169}
170
171/// Which targets a rectangle meets, and the translation of the
172/// scrollable named `scroll`.
173struct Gather<'t> {
174    rect: Rectangle,
175    targets: &'t HashMap<Id, usize>,
176    scroll: Option<&'t Id>,
177    found: Vec<usize>,
178    translation: Option<Vector>,
179    frames: Vec<Frame>,
180    entering: Option<Frame>,
181}
182
183#[derive(Clone, Copy)]
184struct Frame {
185    translation: Vector,
186    visible: Option<Rectangle>,
187}
188
189impl<'t> Gather<'t> {
190    fn new(rect: Rectangle, targets: &'t HashMap<Id, usize>, scroll: Option<&'t Id>) -> Self {
191        Gather {
192            rect,
193            targets,
194            scroll,
195            found: Vec::new(),
196            translation: None,
197            frames: vec![Frame { translation: Vector::ZERO, visible: None }],
198            entering: None,
199        }
200    }
201
202    fn frame(&self) -> Frame {
203        self.frames.last().copied().unwrap_or(Frame { translation: Vector::ZERO, visible: None })
204    }
205}
206
207impl Operation for Gather<'_> {
208    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
209        let next = self.entering.take().unwrap_or_else(|| self.frame());
210        self.frames.push(next);
211        operate(self);
212        self.frames.pop();
213    }
214
215    fn container(&mut self, id: Option<&Id>, bounds: Rectangle) {
216        let Some(&index) = id.and_then(|id| self.targets.get(id)) else { return };
217        let frame = self.frame();
218        // Where the container is drawn: its layout, moved by the scroll.
219        let drawn = Rectangle { x: bounds.x - frame.translation.x, y: bounds.y - frame.translation.y, ..bounds };
220        // Only the part actually on screen: a row scrolled out of sight
221        // still has a layout, and must not be selected by a band drawn
222        // over whatever is shown where it would have been.
223        let shown = match frame.visible {
224            Some(visible) => visible.intersection(&drawn),
225            None => Some(drawn),
226        };
227        if shown.is_some_and(|shown| shown.intersects(&self.rect)) {
228            self.found.push(index);
229        }
230    }
231
232    fn scrollable(
233        &mut self,
234        id: Option<&Id>,
235        bounds: Rectangle,
236        _content_bounds: Rectangle,
237        translation: Vector,
238        _state: &mut dyn operation::Scrollable,
239    ) {
240        if self.scroll.is_some() && id == self.scroll {
241            self.translation = Some(translation);
242        }
243        let outer = self.frame();
244        let viewport = Rectangle { x: bounds.x - outer.translation.x, y: bounds.y - outer.translation.y, ..bounds };
245        let visible = match outer.visible {
246            Some(v) => v.intersection(&viewport),
247            None => Some(viewport),
248        };
249        self.entering = Some(Frame {
250            translation: outer.translation + translation,
251            visible: Some(visible.unwrap_or(Rectangle::new(Point::ORIGIN, Size::ZERO))),
252        });
253    }
254}
255
256impl<'a, Message, Theme, Renderer> Marquee<'a, Message, Theme, Renderer>
257where
258    Renderer: renderer::Renderer,
259    Message: Clone,
260{
261    /// Asks the layout what `rect` meets, and remembers the scroll.
262    fn gather(&mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, rect: Rectangle) -> (Vec<usize>, Vector) {
263        let mut gather = Gather::new(rect, &self.targets, self.scroll.as_ref());
264        self.content.as_widget_mut().operate(&mut tree.children[0], layout, renderer, &mut gather);
265        let mut found = gather.found;
266        found.sort_unstable();
267        found.dedup();
268        (found, gather.translation.unwrap_or(Vector::ZERO))
269    }
270
271    /// Re-reads what the band meets and publishes it if it changed.
272    fn reselect(&mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, shell: &mut Shell<'_, Message>) {
273        let state: &State = tree.state.downcast_ref();
274        let rect = band_rect(state.anchor, state.translation, state.cursor);
275        let (found, translation) = self.gather(tree, layout, renderer, rect);
276        let state: &mut State = tree.state.downcast_mut();
277        state.translation = translation;
278        if found != state.last {
279            state.last = found.clone();
280            if let Some(on_select) = &self.on_select {
281                let additive = state.modifiers.control() || state.modifiers.shift();
282                shell.publish(on_select(found, additive));
283            }
284        }
285    }
286}
287
288impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Marquee<'_, Message, Theme, Renderer>
289where
290    Renderer: renderer::Renderer,
291    Message: Clone,
292{
293    fn tag(&self) -> tree::Tag {
294        tree::Tag::of::<State>()
295    }
296
297    fn state(&self) -> tree::State {
298        tree::State::new(State::default())
299    }
300
301    fn children(&self) -> Vec<Tree> {
302        vec![Tree::new(&self.content)]
303    }
304
305    fn diff(&self, tree: &mut Tree) {
306        tree.diff_children(std::slice::from_ref(&self.content));
307    }
308
309    fn size(&self) -> Size<Length> {
310        self.content.as_widget().size()
311    }
312
313    fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits) -> layout::Node {
314        self.content.as_widget_mut().layout(&mut tree.children[0], renderer, limits)
315    }
316
317    fn operate(&mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation) {
318        self.content.as_widget_mut().operate(&mut tree.children[0], layout, renderer, operation);
319    }
320
321    fn update(
322        &mut self,
323        tree: &mut Tree,
324        event: &Event,
325        layout: Layout<'_>,
326        cursor: mouse::Cursor,
327        renderer: &Renderer,
328        clipboard: &mut dyn Clipboard,
329        shell: &mut Shell<'_, Message>,
330        viewport: &Rectangle,
331    ) {
332        if let Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) = event {
333            tree.state.downcast_mut::<State>().modifiers = *modifiers;
334        }
335        let active = tree.state.downcast_ref::<State>().active;
336
337        match event {
338            // The content first: a press it takes is a row's, and the
339            // band only ever starts on a press nothing took.
340            Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => {
341                self.content
342                    .as_widget_mut()
343                    .update(&mut tree.children[0], event, layout, cursor, renderer, clipboard, shell, viewport);
344                if shell.is_event_captured() {
345                    return;
346                }
347                let Some(at) = cursor.position_over(layout.bounds()) else { return };
348                let (_, translation) = self.gather(tree, layout, renderer, Rectangle::new(at, Size::ZERO));
349                let state: &mut State = tree.state.downcast_mut();
350                *state = State {
351                    press: Some(at),
352                    anchor: at + translation,
353                    cursor: at,
354                    translation,
355                    modifiers: state.modifiers,
356                    ..State::default()
357                };
358                return;
359            }
360            Event::Mouse(mouse::Event::CursorMoved { position }) => {
361                let state: &mut State = tree.state.downcast_mut();
362                if let Some(press) = state.press {
363                    state.cursor = *position;
364                    if !state.active && press.distance(*position) >= THRESHOLD {
365                        state.active = true;
366                        if let Some(start) = &self.on_start {
367                            shell.publish(start.clone());
368                        }
369                    }
370                    if state.active {
371                        self.reselect(tree, layout, renderer, shell);
372                        shell.request_redraw();
373                        // The band has the pointer: rows under it must
374                        // not light up as hovered while it passes.
375                        shell.capture_event();
376                        return;
377                    }
378                }
379            }
380            Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => {
381                let state: &mut State = tree.state.downcast_mut();
382                let (pressed, was_active) = (state.press.take(), state.active);
383                state.active = false;
384                state.last.clear();
385                if was_active {
386                    if let Some(end) = &self.on_end {
387                        shell.publish(end.clone());
388                    }
389                    shell.request_redraw();
390                    shell.capture_event();
391                    return;
392                }
393                if pressed.is_some() {
394                    if let Some(clear) = &self.on_clear {
395                        shell.publish(clear.clone());
396                    }
397                }
398            }
399            // Following the band past an edge: one step per frame while
400            // the pointer is near it, and another frame asked for until
401            // it moves away or lets go.
402            Event::Window(window::Event::RedrawRequested(_)) if active => {
403                let bounds = layout.bounds();
404                let y = tree.state.downcast_ref::<State>().cursor.y;
405                let step = edge_scroll(y, bounds.y, bounds.y + bounds.height);
406                if step != 0.0 {
407                    if let Some(id) = self.scroll.clone() {
408                        let mut scroll = operation::scrollable::scroll_by::<()>(id, AbsoluteOffset { x: 0.0, y: step });
409                        self.content.as_widget_mut().operate(&mut tree.children[0], layout, renderer, &mut scroll);
410                        self.reselect(tree, layout, renderer, shell);
411                    }
412                    shell.request_redraw();
413                }
414            }
415            _ => {}
416        }
417
418        self.content
419            .as_widget_mut()
420            .update(&mut tree.children[0], event, layout, cursor, renderer, clipboard, shell, viewport);
421
422        // The wheel scrolled the rows under a band: what it meets changed.
423        if active && matches!(event, Event::Mouse(mouse::Event::WheelScrolled { .. })) {
424            self.reselect(tree, layout, renderer, shell);
425            shell.request_redraw();
426        }
427    }
428
429    fn mouse_interaction(
430        &self,
431        tree: &Tree,
432        layout: Layout<'_>,
433        cursor: mouse::Cursor,
434        viewport: &Rectangle,
435        renderer: &Renderer,
436    ) -> mouse::Interaction {
437        if tree.state.downcast_ref::<State>().active {
438            return mouse::Interaction::Crosshair;
439        }
440        self.content
441            .as_widget()
442            .mouse_interaction(&tree.children[0], layout, cursor, viewport, renderer)
443    }
444
445    fn draw(
446        &self,
447        tree: &Tree,
448        renderer: &mut Renderer,
449        theme: &Theme,
450        style: &renderer::Style,
451        layout: Layout<'_>,
452        cursor: mouse::Cursor,
453        viewport: &Rectangle,
454    ) {
455        self.content
456            .as_widget()
457            .draw(&tree.children[0], renderer, theme, style, layout, cursor, viewport);
458        let state: &State = tree.state.downcast_ref();
459        if !state.active {
460            return;
461        }
462        let Some(clip) = layout.bounds().intersection(viewport) else { return };
463        let Some(band) = band_rect(state.anchor, state.translation, state.cursor).intersection(&clip) else {
464            return;
465        };
466        // The accent, because the band is a selection being made and the
467        // accent is what selected means; faint inside so the rows stay
468        // readable through it, solid at the edge so its extent is clear.
469        let accent = crate::color::to_iced(crate::theme::active().accent);
470        renderer.with_layer(clip, |renderer| {
471            renderer.fill_quad(
472                renderer::Quad {
473                    bounds: band,
474                    border: Border { color: accent, width: 1.0, radius: 2.0.into() },
475                    ..renderer::Quad::default()
476                },
477                Color { a: 0.18, ..accent },
478            );
479        });
480    }
481
482    fn overlay<'b>(
483        &'b mut self,
484        tree: &'b mut Tree,
485        layout: Layout<'b>,
486        renderer: &Renderer,
487        viewport: &Rectangle,
488        translation: Vector,
489    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
490        self.content
491            .as_widget_mut()
492            .overlay(&mut tree.children[0], layout, renderer, viewport, translation)
493    }
494}
495
496impl<'a, Message, Theme, Renderer> From<Marquee<'a, Message, Theme, Renderer>> for Element<'a, Message, Theme, Renderer>
497where
498    Message: 'a + Clone,
499    Theme: 'a,
500    Renderer: 'a + renderer::Renderer,
501{
502    fn from(marquee: Marquee<'a, Message, Theme, Renderer>) -> Self {
503        Element::new(marquee)
504    }
505}
506
507#[cfg(test)]
508mod tests {
509    use super::*;
510
511    #[test]
512    fn the_band_spans_its_corners_whichever_way_it_was_drawn() {
513        let up_left = band_rect(Point::new(100.0, 100.0), Vector::ZERO, Point::new(40.0, 20.0));
514        assert_eq!(up_left, Rectangle { x: 40.0, y: 20.0, width: 60.0, height: 80.0 });
515    }
516
517    /// Scrolled down 50 since the press, the corner it started at is 50
518    /// higher on screen — it moved with the row it was beside.
519    #[test]
520    fn the_anchor_moves_with_the_scrolled_content() {
521        let rect = band_rect(Point::new(10.0, 200.0), Vector::new(0.0, 50.0), Point::new(60.0, 300.0));
522        assert_eq!(rect.y, 150.0);
523        assert_eq!(rect.height, 150.0);
524    }
525
526    #[test]
527    fn the_listing_scrolls_only_near_an_edge_and_fastest_at_it() {
528        assert_eq!(edge_scroll(300.0, 0.0, 600.0), 0.0);
529        assert_eq!(edge_scroll(0.0, 0.0, 600.0), -SPEED);
530        assert_eq!(edge_scroll(-40.0, 0.0, 600.0), -SPEED, "past the edge is the fastest, not faster");
531        assert_eq!(edge_scroll(600.0, 0.0, 600.0), SPEED);
532        let partway = edge_scroll(600.0 - EDGE / 2.0, 0.0, 600.0);
533        assert!(partway > 0.0 && partway < SPEED);
534    }
535
536    /// Only targets actually on screen are met: a row scrolled out of the
537    /// viewport keeps its layout, and must not be selected by a band
538    /// drawn over whatever is there now.
539    #[test]
540    fn a_target_scrolled_out_of_sight_is_not_met() {
541        let a = Id::unique();
542        let b = Id::unique();
543        let targets = HashMap::from([(a.clone(), 0), (b.clone(), 1)]);
544        let scroll = Id::unique();
545        let mut gather = Gather::new(Rectangle::new(Point::new(0.0, 0.0), Size::new(100.0, 100.0)), &targets, Some(&scroll));
546        struct Inert;
547        impl operation::Scrollable for Inert {
548            fn snap_to(&mut self, _: operation::scrollable::RelativeOffset<Option<f32>>) {}
549            fn scroll_to(&mut self, _: AbsoluteOffset<Option<f32>>) {}
550            fn scroll_by(&mut self, _: AbsoluteOffset, _: Rectangle, _: Rectangle) {}
551        }
552        // A viewport 0..100 scrolled down by 200.
553        gather.scrollable(
554            Some(&scroll),
555            Rectangle::new(Point::ORIGIN, Size::new(100.0, 100.0)),
556            Rectangle::new(Point::ORIGIN, Size::new(100.0, 1000.0)),
557            Vector::new(0.0, 200.0),
558            &mut Inert,
559        );
560        gather.traverse(&mut |op| {
561            // Row a is laid out at 0..20: scrolled away above the top.
562            op.container(Some(&a), Rectangle::new(Point::new(0.0, 0.0), Size::new(100.0, 20.0)));
563            // Row b at 220..240: on screen at 20..40.
564            op.container(Some(&b), Rectangle::new(Point::new(0.0, 220.0), Size::new(100.0, 20.0)));
565        });
566        assert_eq!(gather.found, [1]);
567        assert_eq!(gather.translation, Some(Vector::new(0.0, 200.0)));
568    }
569}