Skip to main content

cosmic/applet/
column.rs

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