Skip to main content

cosmic/applet/
row.rs

1//! Distribute content horizontally.
2use crate::iced;
3use iced::core::alignment::{self, Alignment};
4use iced::core::event::Event;
5use iced::core::layout::{self, Layout};
6use iced::core::widget::{Operation, Tree};
7use iced::core::{
8    Clipboard, Element, Length, Padding, Pixels, Rectangle, Shell, Size, Vector, Widget, mouse,
9    overlay, renderer, widget,
10};
11
12/// A container that distributes its contents horizontally.
13///
14/// # Example
15/// ```no_run
16/// # mod iced { pub mod widget { pub use iced_widget::*; } }
17/// # pub type State = ();
18/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
19/// use iced::widget::{button, row};
20///
21/// #[derive(Debug, Clone)]
22/// enum Message {
23///     // ...
24/// }
25///
26/// fn view(state: &State) -> Element<'_, Message> {
27///     row![
28///         "I am to the left!",
29///         button("I am in the middle!"),
30///         "I am to the right!",
31///     ].into()
32/// }
33/// ```
34#[allow(missing_debug_implementations)]
35#[must_use]
36pub struct Row<'a, Message, Theme = iced::Theme, Renderer = iced::Renderer> {
37    spacing: f32,
38    padding: Padding,
39    width: Length,
40    height: Length,
41    align: Alignment,
42    clip: bool,
43    children: Vec<Element<'a, Message, Theme, Renderer>>,
44}
45
46impl<'a, Message, Theme, Renderer> Row<'a, Message, Theme, Renderer>
47where
48    Renderer: iced::core::Renderer,
49{
50    /// Creates an empty [`Row`].
51    pub fn new() -> Self {
52        Self::from_vec(Vec::new())
53    }
54
55    /// Creates a [`Row`] with the given capacity.
56    pub fn with_capacity(capacity: usize) -> Self {
57        Self::from_vec(Vec::with_capacity(capacity))
58    }
59
60    /// Creates a [`Row`] with the given elements.
61    pub fn with_children(
62        children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>,
63    ) -> Self {
64        let iterator = children.into_iter();
65
66        Self::with_capacity(iterator.size_hint().0).extend(iterator)
67    }
68
69    /// Creates a [`Row`] from an already allocated [`Vec`].
70    ///
71    /// Keep in mind that the [`Row`] will not inspect the [`Vec`], which means
72    /// it won't automatically adapt to the sizing strategy of its contents.
73    ///
74    /// If any of the children have a [`Length::Fill`] strategy, you will need to
75    /// call [`Row::width`] or [`Row::height`] accordingly.
76    pub fn from_vec(children: Vec<Element<'a, Message, Theme, Renderer>>) -> Self {
77        Self {
78            spacing: 0.0,
79            padding: Padding::ZERO,
80            width: Length::Shrink,
81            height: Length::Shrink,
82            align: Alignment::Start,
83            clip: false,
84            children,
85        }
86    }
87
88    /// Sets the horizontal spacing _between_ elements.
89    ///
90    /// Custom margins per element do not exist in iced. You should use this
91    /// method instead! While less flexible, it helps you keep spacing between
92    /// elements consistent.
93    pub fn spacing(mut self, amount: impl Into<Pixels>) -> Self {
94        self.spacing = amount.into().0;
95        self
96    }
97
98    /// Sets the [`Padding`] of the [`Row`].
99    pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self {
100        self.padding = padding.into();
101        self
102    }
103
104    /// Sets the width of the [`Row`].
105    pub fn width(mut self, width: impl Into<Length>) -> Self {
106        self.width = width.into();
107        self
108    }
109
110    /// Sets the height of the [`Row`].
111    pub fn height(mut self, height: impl Into<Length>) -> Self {
112        self.height = height.into();
113        self
114    }
115
116    /// Sets the vertical alignment of the contents of the [`Row`] .
117    pub fn align_y(mut self, align: impl Into<alignment::Vertical>) -> Self {
118        self.align = Alignment::from(align.into());
119        self
120    }
121
122    /// Sets whether the contents of the [`Row`] should be clipped on
123    /// overflow.
124    pub fn clip(mut self, clip: bool) -> Self {
125        self.clip = clip;
126        self
127    }
128
129    /// Adds an [`Element`] to the [`Row`].
130    pub fn push(mut self, child: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self {
131        let child = child.into();
132        let child_size = child.as_widget().size_hint();
133
134        self.width = self.width.enclose(child_size.width);
135        self.height = self.height.enclose(child_size.height);
136
137        self.children.push(child);
138        self
139    }
140
141    /// Adds an element to the [`Row`], if `Some`.
142    pub fn push_maybe(
143        self,
144        child: Option<impl Into<Element<'a, Message, Theme, Renderer>>>,
145    ) -> Self {
146        if let Some(child) = child {
147            self.push(child)
148        } else {
149            self
150        }
151    }
152
153    /// Extends the [`Row`] with the given children.
154    pub fn extend(
155        self,
156        children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>,
157    ) -> Self {
158        children.into_iter().fold(self, Self::push)
159    }
160}
161
162impl<'a, Message, Renderer> Default for Row<'a, Message, Renderer>
163where
164    Renderer: iced::core::Renderer,
165{
166    fn default() -> Self {
167        Self::new()
168    }
169}
170
171impl<'a, Message, Theme, Renderer: iced::core::Renderer>
172    FromIterator<Element<'a, Message, Theme, Renderer>> for Row<'a, Message, Theme, Renderer>
173{
174    fn from_iter<T: IntoIterator<Item = Element<'a, Message, Theme, Renderer>>>(iter: T) -> Self {
175        Self::with_children(iter)
176    }
177}
178
179impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
180    for Row<'_, Message, Theme, Renderer>
181where
182    Renderer: iced::core::Renderer,
183{
184    fn children(&self) -> Vec<Tree> {
185        self.children.iter().map(Tree::new).collect()
186    }
187
188    fn state(&self) -> widget::tree::State {
189        widget::tree::State::new(State::default())
190    }
191
192    fn tag(&self) -> widget::tree::Tag {
193        widget::tree::Tag::of::<State>()
194    }
195
196    fn diff(&mut self, tree: &mut Tree) {
197        tree.diff_children(&mut self.children);
198    }
199
200    fn size(&self) -> Size<Length> {
201        Size {
202            width: self.width,
203            height: self.height,
204        }
205    }
206
207    fn layout(
208        &mut self,
209        tree: &mut Tree,
210        renderer: &Renderer,
211        limits: &layout::Limits,
212    ) -> layout::Node {
213        layout::flex::resolve(
214            layout::flex::Axis::Horizontal,
215            renderer,
216            limits,
217            self.width,
218            self.height,
219            self.padding,
220            self.spacing,
221            self.align,
222            &mut self.children,
223            &mut tree.children,
224        )
225    }
226
227    fn operate(
228        &mut self,
229        tree: &mut Tree,
230        layout: Layout<'_>,
231        renderer: &Renderer,
232        operation: &mut dyn Operation,
233    ) {
234        operation.container(None, layout.bounds());
235        operation.traverse(&mut |operation| {
236            self.children
237                .iter_mut()
238                .zip(&mut tree.children)
239                .zip(layout.children())
240                .for_each(|((child, state), c_layout)| {
241                    child.as_widget_mut().operate(
242                        state,
243                        c_layout.with_virtual_offset(layout.virtual_offset()),
244                        renderer,
245                        operation,
246                    );
247                });
248        });
249    }
250
251    fn update(
252        &mut self,
253        tree: &mut Tree,
254        event: &Event,
255        layout: Layout<'_>,
256        cursor: mouse::Cursor,
257        renderer: &Renderer,
258        clipboard: &mut dyn Clipboard,
259        shell: &mut Shell<'_, Message>,
260        viewport: &Rectangle,
261    ) {
262        let my_state = tree.state.downcast_mut::<State>();
263
264        if let Some(hovered) = my_state.hovered {
265            let child_layout = layout.children().nth(hovered);
266            if let Some(child_layout) = child_layout
267                && cursor.is_over(child_layout.bounds())
268            {
269                // if mouse event, we can skip checking other children
270                if let Event::Mouse(e) = &event {
271                    if !matches!(
272                        e,
273                        mouse::Event::CursorLeft | mouse::Event::ButtonReleased { .. }
274                    ) {
275                        return self.children[hovered].as_widget_mut().update(
276                            &mut tree.children[hovered],
277                            event,
278                            child_layout.with_virtual_offset(layout.virtual_offset()),
279                            cursor,
280                            renderer,
281                            clipboard,
282                            shell,
283                            viewport,
284                        );
285                    }
286                } else if let Event::Touch(t) = &event
287                    && !matches!(
288                        t,
289                        iced::core::touch::Event::FingerLifted { .. }
290                            | iced::core::touch::Event::FingerLost { .. }
291                    )
292                {
293                    return self.children[hovered].as_widget_mut().update(
294                        &mut tree.children[hovered],
295                        event,
296                        child_layout.with_virtual_offset(layout.virtual_offset()),
297                        cursor,
298                        renderer,
299                        clipboard,
300                        shell,
301                        viewport,
302                    );
303                }
304            } else {
305                my_state.hovered = None;
306            }
307        }
308
309        for (((i, child), state), c_layout) in self
310            .children
311            .iter_mut()
312            .enumerate()
313            .zip(&mut tree.children)
314            .zip(layout.children())
315        {
316            let mut cursor_virtual = cursor;
317
318            if matches!(
319                event,
320                Event::Mouse(mouse::Event::CursorMoved { .. } | mouse::Event::CursorEntered)
321                    | Event::Touch(
322                        iced_core::touch::Event::FingerMoved { .. }
323                            | iced_core::touch::Event::FingerPressed { .. }
324                    )
325            ) && cursor.is_over(c_layout.bounds())
326            {
327                my_state.hovered = Some(i);
328                return child.as_widget_mut().update(
329                    state,
330                    event,
331                    c_layout.with_virtual_offset(layout.virtual_offset()),
332                    cursor_virtual,
333                    renderer,
334                    clipboard,
335                    shell,
336                    viewport,
337                );
338            } else if my_state.hovered.is_some_and(|h| i != h) {
339                cursor_virtual = mouse::Cursor::Unavailable;
340            }
341
342            child.as_widget_mut().update(
343                state,
344                event,
345                c_layout.with_virtual_offset(layout.virtual_offset()),
346                cursor_virtual,
347                renderer,
348                clipboard,
349                shell,
350                viewport,
351            );
352        }
353    }
354
355    fn mouse_interaction(
356        &self,
357        tree: &Tree,
358        layout: Layout<'_>,
359        cursor: mouse::Cursor,
360        viewport: &Rectangle,
361        renderer: &Renderer,
362    ) -> mouse::Interaction {
363        self.children
364            .iter()
365            .zip(&tree.children)
366            .zip(layout.children())
367            .map(|((child, state), c_layout)| {
368                child.as_widget().mouse_interaction(
369                    state,
370                    c_layout.with_virtual_offset(layout.virtual_offset()),
371                    cursor,
372                    viewport,
373                    renderer,
374                )
375            })
376            .max()
377            .unwrap_or_default()
378    }
379
380    fn draw(
381        &self,
382        tree: &Tree,
383        renderer: &mut Renderer,
384        theme: &Theme,
385        style: &renderer::Style,
386        layout: Layout<'_>,
387        cursor: mouse::Cursor,
388        viewport: &Rectangle,
389    ) {
390        if let Some(clipped_viewport) = layout.bounds().intersection(viewport) {
391            let my_state = tree.state.downcast_ref::<State>();
392
393            let viewport = if self.clip {
394                &clipped_viewport
395            } else {
396                viewport
397            };
398
399            for (i, ((child, state), c_layout)) in self
400                .children
401                .iter()
402                .zip(&tree.children)
403                .zip(layout.children())
404                .filter(|(_, layout)| layout.bounds().intersects(viewport))
405                .enumerate()
406            {
407                child.as_widget().draw(
408                    state,
409                    renderer,
410                    theme,
411                    style,
412                    c_layout.with_virtual_offset(layout.virtual_offset()),
413                    if my_state.hovered.is_some_and(|h| i == h) {
414                        cursor
415                    } else {
416                        mouse::Cursor::Unavailable
417                    },
418                    viewport,
419                );
420            }
421        }
422    }
423
424    fn overlay<'b>(
425        &'b mut self,
426        tree: &'b mut Tree,
427        layout: Layout<'b>,
428        renderer: &Renderer,
429        viewport: &Rectangle,
430        translation: Vector,
431    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
432        overlay::from_children(
433            &mut self.children,
434            tree,
435            layout,
436            renderer,
437            viewport,
438            translation,
439        )
440    }
441
442    #[cfg(feature = "a11y")]
443    /// get the a11y nodes for the widget
444    fn a11y_nodes(
445        &self,
446        layout: Layout<'_>,
447        state: &Tree,
448        cursor: mouse::Cursor,
449    ) -> iced_accessibility::A11yTree {
450        use iced_accessibility::A11yTree;
451        A11yTree::join(
452            self.children
453                .iter()
454                .zip(layout.children())
455                .zip(state.children.iter())
456                .map(|((c, c_layout), state)| {
457                    c.as_widget().a11y_nodes(
458                        c_layout.with_virtual_offset(layout.virtual_offset()),
459                        state,
460                        cursor,
461                    )
462                }),
463        )
464    }
465
466    fn drag_destinations(
467        &self,
468        state: &Tree,
469        layout: Layout<'_>,
470        renderer: &Renderer,
471        dnd_rectangles: &mut iced::core::clipboard::DndDestinationRectangles,
472    ) {
473        for ((e, c_layout), state) in self
474            .children
475            .iter()
476            .zip(layout.children())
477            .zip(state.children.iter())
478        {
479            e.as_widget().drag_destinations(
480                state,
481                c_layout.with_virtual_offset(layout.virtual_offset()),
482                renderer,
483                dnd_rectangles,
484            );
485        }
486    }
487}
488
489impl<'a, Message, Theme, Renderer> From<Row<'a, Message, Theme, Renderer>>
490    for Element<'a, Message, Theme, Renderer>
491where
492    Message: 'a,
493    Theme: 'a,
494    Renderer: iced::core::Renderer + 'a,
495{
496    fn from(row: Row<'a, Message, Theme, Renderer>) -> Self {
497        Self::new(row)
498    }
499}
500
501#[derive(Debug, Clone, Copy, PartialEq, Default)]
502pub struct State {
503    hovered: Option<usize>,
504}