iced_widget/
rule.rs

1//! Rules divide space horizontally or vertically.
2//!
3//! # Example
4//! ```no_run
5//! # mod iced { pub mod widget { pub use iced_widget::*; } }
6//! # pub type State = ();
7//! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
8//! use iced::widget::horizontal_rule;
9//!
10//! #[derive(Clone)]
11//! enum Message {
12//!     // ...,
13//! }
14//!
15//! fn view(state: &State) -> Element<'_, Message> {
16//!     horizontal_rule(2).into()
17//! }
18//! ```
19use crate::core;
20use crate::core::border;
21use crate::core::layout;
22use crate::core::mouse;
23use crate::core::renderer;
24use crate::core::widget::Tree;
25use crate::core::{
26    Color, Element, Layout, Length, Pixels, Rectangle, Size, Theme, Widget,
27};
28
29/// Display a horizontal or vertical rule for dividing content.
30///
31/// # Example
32/// ```no_run
33/// # mod iced { pub mod widget { pub use iced_widget::*; } }
34/// # pub type State = ();
35/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
36/// use iced::widget::horizontal_rule;
37///
38/// #[derive(Clone)]
39/// enum Message {
40///     // ...,
41/// }
42///
43/// fn view(state: &State) -> Element<'_, Message> {
44///     horizontal_rule(2).into()
45/// }
46/// ```
47#[allow(missing_debug_implementations)]
48pub struct Rule<'a, Theme = crate::Theme>
49where
50    Theme: Catalog,
51{
52    width: Length,
53    height: Length,
54    is_horizontal: bool,
55    class: Theme::Class<'a>,
56}
57
58impl<'a, Theme> Rule<'a, Theme>
59where
60    Theme: Catalog,
61{
62    /// Creates a horizontal [`Rule`] with the given height.
63    pub fn horizontal(height: impl Into<Pixels>) -> Self {
64        Rule {
65            width: Length::Fill,
66            height: Length::Fixed(height.into().0),
67            is_horizontal: true,
68            class: Theme::default(),
69        }
70    }
71
72    /// Creates a vertical [`Rule`] with the given width.
73    pub fn vertical(width: impl Into<Pixels>) -> Self {
74        Rule {
75            width: Length::Fixed(width.into().0),
76            height: Length::Fill,
77            is_horizontal: false,
78            class: Theme::default(),
79        }
80    }
81
82    /// Sets the style of the [`Rule`].
83    #[must_use]
84    pub fn style(mut self, style: impl Fn(&Theme) -> Style + 'a) -> Self
85    where
86        Theme::Class<'a>: From<StyleFn<'a, Theme>>,
87    {
88        self.class = (Box::new(style) as StyleFn<'a, Theme>).into();
89        self
90    }
91
92    /// Sets the style class of the [`Rule`].
93    #[cfg(feature = "advanced")]
94    #[must_use]
95    pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self {
96        self.class = class.into();
97        self
98    }
99}
100
101impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
102    for Rule<'_, Theme>
103where
104    Renderer: core::Renderer,
105    Theme: Catalog,
106{
107    fn size(&self) -> Size<Length> {
108        Size {
109            width: self.width,
110            height: self.height,
111        }
112    }
113
114    fn layout(
115        &self,
116        _tree: &mut Tree,
117        _renderer: &Renderer,
118        limits: &layout::Limits,
119    ) -> layout::Node {
120        layout::atomic(limits, self.width, self.height)
121    }
122
123    fn draw(
124        &self,
125        _state: &Tree,
126        renderer: &mut Renderer,
127        theme: &Theme,
128        _style: &renderer::Style,
129        layout: Layout<'_>,
130        _cursor: mouse::Cursor,
131        _viewport: &Rectangle,
132    ) {
133        let bounds = layout.bounds();
134        let style = theme.style(&self.class);
135
136        let bounds = if self.is_horizontal {
137            let line_y = (bounds.y + (bounds.height / 2.0)
138                - (style.width as f32 / 2.0))
139                .round();
140
141            let (offset, line_width) = style.fill_mode.fill(bounds.width);
142            let line_x = bounds.x + offset;
143
144            Rectangle {
145                x: line_x,
146                y: line_y,
147                width: line_width,
148                height: style.width as f32,
149            }
150        } else {
151            let line_x = (bounds.x + (bounds.width / 2.0)
152                - (style.width as f32 / 2.0))
153                .round();
154
155            let (offset, line_height) = style.fill_mode.fill(bounds.height);
156            let line_y = bounds.y + offset;
157
158            Rectangle {
159                x: line_x,
160                y: line_y,
161                width: style.width as f32,
162                height: line_height,
163            }
164        };
165
166        renderer.fill_quad(
167            renderer::Quad {
168                bounds,
169                border: border::rounded(style.radius),
170                snap: style.snap,
171                ..renderer::Quad::default()
172            },
173            style.color,
174        );
175    }
176}
177
178impl<'a, Message, Theme, Renderer> From<Rule<'a, Theme>>
179    for Element<'a, Message, Theme, Renderer>
180where
181    Message: 'a,
182    Theme: 'a + Catalog,
183    Renderer: 'a + core::Renderer,
184{
185    fn from(rule: Rule<'a, Theme>) -> Element<'a, Message, Theme, Renderer> {
186        Element::new(rule)
187    }
188}
189
190/// The appearance of a rule.
191#[derive(Debug, Clone, Copy, PartialEq)]
192pub struct Style {
193    /// The color of the rule.
194    pub color: Color,
195    /// The width (thickness) of the rule line.
196    pub width: u16,
197    /// The radius of the line corners.
198    pub radius: border::Radius,
199    /// The [`FillMode`] of the rule.
200    pub fill_mode: FillMode,
201    /// Whether the rule should be snapped to the pixel grid.
202    pub snap: bool,
203}
204
205/// The fill mode of a rule.
206#[derive(Debug, Clone, Copy, PartialEq)]
207pub enum FillMode {
208    /// Fill the whole length of the container.
209    Full,
210    /// Fill a percent of the length of the container. The rule
211    /// will be centered in that container.
212    ///
213    /// The range is `[0.0, 100.0]`.
214    Percent(f32),
215    /// Uniform offset from each end, length units.
216    Padded(u16),
217    /// Different offset on each end of the rule, length units.
218    /// First = top or left.
219    AsymmetricPadding(u16, u16),
220}
221
222impl FillMode {
223    /// Return the starting offset and length of the rule.
224    ///
225    /// * `space` - The space to fill.
226    ///
227    /// # Returns
228    ///
229    /// * (`starting_offset`, `length`)
230    pub fn fill(&self, space: f32) -> (f32, f32) {
231        match *self {
232            FillMode::Full => (0.0, space),
233            FillMode::Percent(percent) => {
234                if percent >= 100.0 {
235                    (0.0, space)
236                } else {
237                    let percent_width = (space * percent / 100.0).round();
238
239                    (((space - percent_width) / 2.0).round(), percent_width)
240                }
241            }
242            FillMode::Padded(padding) => {
243                if padding == 0 {
244                    (0.0, space)
245                } else {
246                    let padding = padding as f32;
247                    let mut line_width = space - (padding * 2.0);
248                    if line_width < 0.0 {
249                        line_width = 0.0;
250                    }
251
252                    (padding, line_width)
253                }
254            }
255            FillMode::AsymmetricPadding(first_pad, second_pad) => {
256                let first_pad = first_pad as f32;
257                let second_pad = second_pad as f32;
258                let mut line_width = space - first_pad - second_pad;
259                if line_width < 0.0 {
260                    line_width = 0.0;
261                }
262
263                (first_pad, line_width)
264            }
265        }
266    }
267}
268
269/// The theme catalog of a [`Rule`].
270pub trait Catalog: Sized {
271    /// The item class of the [`Catalog`].
272    type Class<'a>;
273
274    /// The default class produced by the [`Catalog`].
275    fn default<'a>() -> Self::Class<'a>;
276
277    /// The [`Style`] of a class with the given status.
278    fn style(&self, class: &Self::Class<'_>) -> Style;
279}
280
281/// A styling function for a [`Rule`].
282///
283/// This is just a boxed closure: `Fn(&Theme, Status) -> Style`.
284pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme) -> Style + 'a>;
285
286impl Catalog for Theme {
287    type Class<'a> = StyleFn<'a, Self>;
288
289    fn default<'a>() -> Self::Class<'a> {
290        Box::new(default)
291    }
292
293    fn style(&self, class: &Self::Class<'_>) -> Style {
294        class(self)
295    }
296}
297
298/// The default styling of a [`Rule`].
299pub fn default(theme: &Theme) -> Style {
300    let palette = theme.extended_palette();
301
302    Style {
303        color: palette.background.strong.color,
304        width: 1,
305        radius: 0.0.into(),
306        fill_mode: FillMode::Full,
307        snap: true,
308    }
309}