Skip to main content

hyprforge_ui/widgets/
clamped_text.rs

1//! Text cut to a number of lines, with an ellipsis where it was cut.
2//!
3//! iced 0.14 has no ellipsis. A name too long for its box is either
4//! wrapped past the box and clipped — the bottom line sliced through its
5//! letters, or simply missing with nothing to say more was there — or,
6//! unwrapped, drawn straight across whatever is beside it. Both read as
7//! a bug rather than as "this goes on". Files' grid names at Extra large
8//! were the case that made this a widget: a long name lost its third
9//! line mid-glyph.
10//!
11//! So this measures. In `layout` — the one place the real width is known
12//! — the whole text is shaped by the renderer's own `Paragraph`; if it
13//! takes more than the allowed lines (or, unwrapped, more than the
14//! width), the longest prefix that fits *with* "…" after it is found by
15//! binary search over grapheme boundaries, so the cut never splits an
16//! accented letter or an emoji in two. What is drawn is that prefix; what
17//! is measured is what is drawn, so the box it reports is exact.
18//!
19//! Shaping is the cost, and it is paid once per text, width and size:
20//! the answer is kept in the widget's state and reused by every later
21//! layout that asks the same question — a grid of six hundred names
22//! re-laid out by a hover costs six hundred comparisons, not six hundred
23//! searches.
24
25use iced::advanced::layout;
26use iced::advanced::mouse;
27use iced::advanced::renderer;
28use iced::advanced::text::{self, paragraph, Paragraph, Text};
29use iced::advanced::widget::{tree, Tree};
30use iced::advanced::{Layout, Widget};
31use iced::alignment;
32use iced::widget::text::{LineHeight, Shaping, Wrapping};
33use iced::{Color, Element, Length, Pixels, Rectangle, Size};
34use std::borrow::Cow;
35use unicode_segmentation::UnicodeSegmentation;
36
37/// What is put where the text was cut.
38pub const ELLIPSIS: &str = "\u{2026}";
39
40/// `content`, at most `lines` lines tall, cut with "…" when it would be
41/// taller. `usize::MAX` lines is the whole text — the same widget for a
42/// name shown whole when selected, so selecting it does not change which
43/// widget draws it.
44pub fn clamped_text<'a>(content: impl Into<Cow<'a, str>>, lines: usize) -> ClampedText<'a> {
45    ClampedText {
46        content: content.into(),
47        lines: lines.max(1),
48        size: None,
49        line_height: LineHeight::default(),
50        font: None,
51        width: Length::Shrink,
52        align_x: text::Alignment::Default,
53        wrapping: Wrapping::WordOrGlyph,
54        shaping: Shaping::default(),
55        color: None,
56        _theme: std::marker::PhantomData,
57    }
58}
59
60/// See [`clamped_text`].
61pub struct ClampedText<'a, Theme = iced::Theme, Renderer = iced::Renderer>
62where
63    Renderer: text::Renderer,
64{
65    content: Cow<'a, str>,
66    lines: usize,
67    size: Option<Pixels>,
68    line_height: LineHeight,
69    font: Option<Renderer::Font>,
70    width: Length,
71    align_x: text::Alignment,
72    wrapping: Wrapping,
73    shaping: Shaping,
74    color: Option<Color>,
75    _theme: std::marker::PhantomData<Theme>,
76}
77
78impl<'a, Theme, Renderer> ClampedText<'a, Theme, Renderer>
79where
80    Renderer: text::Renderer,
81{
82    pub fn size(mut self, size: impl Into<Pixels>) -> Self {
83        self.size = Some(size.into());
84        self
85    }
86
87    pub fn line_height(mut self, line_height: impl Into<LineHeight>) -> Self {
88        self.line_height = line_height.into();
89        self
90    }
91
92    pub fn font(mut self, font: impl Into<Renderer::Font>) -> Self {
93        self.font = Some(font.into());
94        self
95    }
96
97    pub fn width(mut self, width: impl Into<Length>) -> Self {
98        self.width = width.into();
99        self
100    }
101
102    pub fn align_x(mut self, align: impl Into<text::Alignment>) -> Self {
103        self.align_x = align.into();
104        self
105    }
106
107    /// How lines break. `WordOrGlyph` by default, so a name with no
108    /// spaces still breaks rather than running out of its box;
109    /// `Wrapping::None` makes it a single line cut at the width — a list
110    /// row's name.
111    pub fn wrapping(mut self, wrapping: Wrapping) -> Self {
112        self.wrapping = wrapping;
113        self
114    }
115
116    pub fn shaping(mut self, shaping: Shaping) -> Self {
117        self.shaping = shaping;
118        self
119    }
120
121    /// The text's colour; the renderer's default text colour otherwise.
122    pub fn color(mut self, color: impl Into<Color>) -> Self {
123        self.color = Some(color.into());
124        self
125    }
126}
127
128/// The question a cut answers, so a later layout asking the same one
129/// reuses the answer.
130#[derive(Debug, Clone, PartialEq)]
131struct Asked {
132    content: String,
133    width: f32,
134    size: f32,
135    lines: usize,
136}
137
138struct State<P: Paragraph> {
139    paragraph: paragraph::Plain<P>,
140    asked: Option<Asked>,
141    shown: String,
142}
143
144impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for ClampedText<'_, Theme, Renderer>
145where
146    Renderer: text::Renderer,
147{
148    fn tag(&self) -> tree::Tag {
149        tree::Tag::of::<State<Renderer::Paragraph>>()
150    }
151
152    fn state(&self) -> tree::State {
153        tree::State::new(State::<Renderer::Paragraph> {
154            paragraph: paragraph::Plain::default(),
155            asked: None,
156            shown: String::new(),
157        })
158    }
159
160    fn size(&self) -> Size<Length> {
161        Size { width: self.width, height: Length::Shrink }
162    }
163
164    fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits) -> layout::Node {
165        let state = tree.state.downcast_mut::<State<Renderer::Paragraph>>();
166        let limits = limits.width(self.width);
167        let width = limits.max().width;
168        let size = self.size.unwrap_or_else(|| renderer.default_size());
169        let font = self.font.unwrap_or_else(|| renderer.default_font());
170        let template = Text {
171            content: "",
172            bounds: Size::new(width, f32::INFINITY),
173            size,
174            line_height: self.line_height,
175            font,
176            align_x: self.align_x,
177            align_y: alignment::Vertical::Top,
178            shaping: self.shaping,
179            wrapping: self.wrapping,
180        };
181        let asked = Asked { content: self.content.to_string(), width, size: size.0, lines: self.lines };
182        if state.asked.as_ref() != Some(&asked) {
183            state.shown = clamp::<Renderer::Paragraph>(Text { content: &self.content, ..template }, self.lines).into_owned();
184            state.asked = Some(asked);
185        }
186        let _ = state.paragraph.update(Text { content: &state.shown, ..template });
187        let measured = state.paragraph.min_bounds();
188        layout::Node::new(limits.resolve(self.width, Length::Shrink, measured))
189    }
190
191    fn draw(
192        &self,
193        tree: &Tree,
194        renderer: &mut Renderer,
195        _theme: &Theme,
196        style: &renderer::Style,
197        layout: Layout<'_>,
198        _cursor: mouse::Cursor,
199        viewport: &Rectangle,
200    ) {
201        let state = tree.state.downcast_ref::<State<Renderer::Paragraph>>();
202        let paragraph = state.paragraph.raw();
203        let anchor = layout.bounds().anchor(paragraph.min_bounds(), paragraph.align_x(), paragraph.align_y());
204        renderer.fill_paragraph(paragraph, anchor, self.color.unwrap_or(style.text_color), *viewport);
205    }
206}
207
208/// `text`'s content, or the longest prefix of it that fits in `lines`
209/// lines with [`ELLIPSIS`] after it. Generic over the paragraph so a test
210/// can measure with a real one and no window.
211///
212/// "Fits" is both directions: no more than `lines` lines tall, and no
213/// wider than the bounds — which only an unwrapped text can be.
214pub fn clamp<'t, P: Paragraph>(text: Text<&'t str, P::Font>, lines: usize) -> Cow<'t, str> {
215    if lines == usize::MAX {
216        return Cow::Borrowed(text.content);
217    }
218    let line = text.line_height.to_absolute(text.size).0;
219    // Half a pixel either way: shaping reports fractions, and a text
220    // exactly two lines tall must not read as a hair over.
221    let tallest = line * lines as f32 + 0.5;
222    let widest = text.bounds.width + 0.5;
223    let fits = |content: &str| {
224        let bounds = P::with_text(Text { content, ..text }).min_bounds();
225        bounds.height <= tallest && bounds.width <= widest
226    };
227    if fits(text.content) {
228        return Cow::Borrowed(text.content);
229    }
230    let cuts: Vec<usize> = text.content.grapheme_indices(true).map(|(at, _)| at).collect();
231    let with_ellipsis = |at: usize| format!("{}{ELLIPSIS}", text.content[..at].trim_end());
232    // The largest number of graphemes kept that still fits. Zero always
233    // "fits" for the search's purposes: a box too small for even "…"
234    // shows "…", which still says something is there.
235    let (mut lo, mut hi) = (0usize, cuts.len());
236    while lo + 1 < hi {
237        let mid = (lo + hi) / 2;
238        if fits(&with_ellipsis(cuts[mid])) {
239            lo = mid;
240        } else {
241            hi = mid;
242        }
243    }
244    Cow::Owned(with_ellipsis(cuts.get(lo).copied().unwrap_or(0)))
245}
246
247impl<'a, Message, Theme, Renderer> From<ClampedText<'a, Theme, Renderer>> for Element<'a, Message, Theme, Renderer>
248where
249    Theme: 'a,
250    Renderer: text::Renderer + 'a,
251{
252    fn from(text: ClampedText<'a, Theme, Renderer>) -> Self {
253        Element::new(text)
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260    use iced::advanced::graphics::text::Paragraph as Shaped;
261    use iced::Font;
262
263    fn text(content: &str, width: f32, wrapping: Wrapping) -> Text<&str, Font> {
264        Text {
265            content,
266            bounds: Size::new(width, f32::INFINITY),
267            size: Pixels(14.0),
268            line_height: LineHeight::default(),
269            font: Font::default(),
270            align_x: text::Alignment::Center,
271            align_y: alignment::Vertical::Top,
272            shaping: Shaping::Advanced,
273            wrapping,
274        }
275    }
276
277    fn lines_of(content: &str, width: f32) -> f32 {
278        let t = text(content, width, Wrapping::WordOrGlyph);
279        Shaped::with_text(t).min_bounds().height / t.line_height.to_absolute(t.size).0
280    }
281
282    /// A short name is drawn as it is — no ellipsis, no copy.
283    #[test]
284    fn text_that_fits_is_left_whole() {
285        let t = text("notes.txt", 200.0, Wrapping::WordOrGlyph);
286        assert!(matches!(clamp::<Shaped>(t, 2), Cow::Borrowed("notes.txt")));
287    }
288
289    /// The case Files' grid had: a long name in a narrow box. It comes
290    /// back ending in "…", within the lines allowed, and as long as it
291    /// can be — one more grapheme would not fit.
292    #[test]
293    fn a_long_text_is_cut_at_the_line_limit_with_an_ellipsis() {
294        let long = "Quarterly report for the regional office, final revision three (approved by everyone).pdf";
295        for lines in 1..=3 {
296            let shown = clamp::<Shaped>(text(long, 120.0, Wrapping::WordOrGlyph), lines).into_owned();
297            assert!(shown.ends_with(ELLIPSIS), "{shown}");
298            assert!(lines_of(&shown, 120.0) <= lines as f32 + 0.01, "{shown} is more than {lines} lines");
299            let kept = shown.trim_end_matches(ELLIPSIS);
300            // The next letter after the cut, past any space the cut
301            // trimmed: keeping it too must not have fitted.
302            let next = long[kept.len()..].char_indices().find(|(_, c)| !c.is_whitespace());
303            let one_more = &long[..next.map_or(long.len(), |(at, c)| kept.len() + at + c.len_utf8())];
304            let longer = format!("{}{ELLIPSIS}", one_more.trim_end());
305            assert!(lines_of(&longer, 120.0) > lines as f32 + 0.01, "{longer} would have fitted in {lines}");
306        }
307    }
308
309    /// The cut is between graphemes: an accented letter written as a
310    /// base and a combining mark is never split from its accent.
311    #[test]
312    fn a_cut_never_splits_a_grapheme() {
313        let decomposed = "e\u{301}".repeat(80);
314        let shown = clamp::<Shaped>(text(&decomposed, 60.0, Wrapping::WordOrGlyph), 1).into_owned();
315        let kept = shown.trim_end_matches(ELLIPSIS);
316        assert!(!kept.is_empty() && kept.len().is_multiple_of(3), "{kept:?} ends inside a grapheme");
317    }
318
319    /// Unwrapped, the limit is the width: a list row's name is one line
320    /// cut at its column's edge.
321    #[test]
322    fn an_unwrapped_text_is_cut_at_the_width() {
323        let t = text("a-very-long-file-name-without-any-spaces-at-all.tar.gz", 100.0, Wrapping::None);
324        let shown = clamp::<Shaped>(t, 1).into_owned();
325        assert!(shown.ends_with(ELLIPSIS));
326        let width = Shaped::with_text(text(&shown, 100.0, Wrapping::None)).min_bounds().width;
327        assert!(width <= 100.5, "{shown} is {width} wide");
328    }
329
330    /// No limit is no limit: the selected cell's whole name.
331    #[test]
332    fn an_unlimited_clamp_is_the_whole_text() {
333        let long = "word ".repeat(100);
334        assert_eq!(clamp::<Shaped>(text(&long, 50.0, Wrapping::WordOrGlyph), usize::MAX), long);
335    }
336
337    /// A box too narrow for anything still says something is there.
338    #[test]
339    fn a_box_too_small_for_one_letter_shows_the_ellipsis() {
340        let shown = clamp::<Shaped>(text("WWWWWWWW", 2.0, Wrapping::None), 1);
341        assert_eq!(shown, ELLIPSIS);
342    }
343}