Skip to main content

pushrod/
paint.rs

1// Paint
2// Pushrod
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! # Paint
17//!
18//! The backend-neutral drawing API.  A [`Widget`](crate::widget::Widget) draws by calling the
19//! [`Painter`] it is handed, never an `SDL2` type, so widgets (and widget libraries) work with any
20//! backend.  Reusable building blocks compose a `Widget`'s `paint`, all drawing into the `Widget`'s
21//! own surface:
22//!
23//! ```text
24//!   RootWidget   = fill
25//!   BaseWidget   = fill
26//!   BoxWidget    = fill + border
27//!   TextWidget   = fill + text
28//!   ButtonWidget = fill + text + border   (+ pressed state)
29//! ```
30//!
31//! The `pushrod-sdl2` crate's `Sdl2Painter` is the default backend: each `Widget` paints
32//! into its own GPU texture only when invalidated, and frames are blits of cached textures.  A
33//! backend declares its [`CachePolicy`].  The [`RecordingPainter`](crate::backend::headless::RecordingPainter)
34//! records calls for unit tests, without a window.
35
36use crate::color::{Color, FontStyle};
37use crate::error::Error;
38use crate::geometry::{Point, Rect, Size};
39use crate::widget::VisualState;
40use unicode_segmentation::UnicodeSegmentation;
41
42/// Horizontal alignment of text within its bounds.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum TextJustify {
45    /// Aligned to the left edge.
46    Left,
47    /// Centered horizontally.
48    Center,
49    /// Aligned to the right edge.
50    Right,
51}
52
53/// What [`text`] does with text that is wider than its rectangle.
54///
55/// The text is shortened on a grapheme boundary (never inside a character) and an ellipsis (`…`),
56/// measured in the same font, marks the cut.  Truncation applies to single-line text; text that
57/// contains a newline is left alone.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
59pub enum Truncate {
60    /// Don't shorten the text; it is clipped (or wrapped) as before.
61    None,
62    /// Keep the start and cut the end: `Quarterly rep…`.
63    #[default]
64    End,
65    /// Keep the end and cut the start: `…report.txt`.
66    Start,
67    /// Keep both ends and cut the middle: `Quart….txt`, for paths and file names.
68    Middle,
69}
70
71/// How [`paragraph`] breaks text into lines.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
73pub enum Wrap {
74    /// One line; [`text`] draws it (see [`Truncate`]).
75    #[default]
76    None,
77    /// Break at spaces; a word wider than the width is broken between graphemes.
78    Word,
79    /// Break between any two graphemes, as late as possible.
80    Anywhere,
81}
82
83/// The ellipsis drawn where text is cut.
84pub const ELLIPSIS: &str = "\u{2026}";
85
86/// The result of [`text`].
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub struct TextDrawn {
89    /// The size of the text drawn; `0` by `0` if nothing was drawn.
90    pub size: Size,
91    /// Whether the text was shortened to fit (see [`Truncate`]), so a tooltip can show it in full.
92    pub truncated: bool,
93}
94
95/// How a backend keeps painted `Widget`s between frames.
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
97pub enum CachePolicy {
98    /// Each `Widget` paints into its own cached surface (a GPU texture) when invalidated, and frames
99    /// are blits of those surfaces.  Used by GPU backends such as `SDL2`.
100    #[default]
101    TextureCache,
102
103    /// Invalidated `Widget`s are painted straight to the screen with clipping, with no per-widget
104    /// surface.  For memory-poor systems.  Declared by backends that need it; the `SDL2` backend
105    /// never uses it.
106    DirectDraw,
107}
108
109/// The font and alignment used to draw text with [`text`].
110#[derive(Debug, Clone, PartialEq)]
111pub struct TextStyle {
112    /// Path to the TrueType font file.
113    pub font_name: String,
114
115    /// Font style (normal, bold, italic, ...)
116    pub font_style: FontStyle,
117
118    /// Font size in points.
119    pub font_size: u16,
120
121    /// Text color.
122    pub font_color: Color,
123
124    /// Horizontal justification.
125    pub justification: TextJustify,
126}
127
128impl TextStyle {
129    /// Creates a `TextStyle`.
130    ///
131    /// # Arguments
132    ///
133    /// * `font_name` - Path to the TrueType font file.
134    /// * `font_style` - The font style (normal, bold, italic, ...).
135    /// * `font_size` - The font size in points.
136    /// * `font_color` - The text color.
137    /// * `justification` - The horizontal alignment.
138    ///
139    /// # Returns
140    ///
141    /// The new `TextStyle`.
142    pub fn new(
143        font_name: String,
144        font_style: FontStyle,
145        font_size: u16,
146        font_color: Color,
147        justification: TextJustify,
148    ) -> Self {
149        Self {
150            font_name,
151            font_style,
152            font_size,
153            font_color,
154            justification,
155        }
156    }
157}
158
159/// The drawing operations a `Widget`'s `paint` can use.  Kept small: only what the helpers in this
160/// module need.
161///
162/// Coordinates are relative to the `Widget`'s own upper left-hand corner.  A backend decides where
163/// the pixels go (a GPU texture, a memory buffer, the screen with clipping).
164pub trait Painter {
165    /// Returns how this backend caches painted `Widget`s.
166    ///
167    /// # Returns
168    ///
169    /// The backend's [`CachePolicy`].
170    fn cache_policy(&self) -> CachePolicy;
171
172    /// Fills the whole drawing surface with a color.
173    ///
174    /// # Arguments
175    ///
176    /// * `color` - The fill color.
177    fn fill(&mut self, color: Color);
178
179    /// Fills a rectangle with a color.
180    ///
181    /// # Arguments
182    ///
183    /// * `bounds` - The rectangle to fill.
184    /// * `color` - The fill color.
185    fn fill_rect(&mut self, bounds: Rect, color: Color);
186
187    /// Draws a one-pixel rectangle outline.
188    ///
189    /// # Arguments
190    ///
191    /// * `bounds` - The rectangle to outline.
192    /// * `color` - The line color.
193    fn rect(&mut self, bounds: Rect, color: Color);
194
195    /// Draws a one-pixel line.
196    ///
197    /// # Arguments
198    ///
199    /// * `from` - The start point.
200    /// * `to` - The end point.
201    /// * `color` - The line color.
202    fn line(&mut self, from: Point, to: Point, color: Color);
203
204    /// Draws text within a rectangle, aligned by `style`, wrapped at the rectangle's width, and
205    /// centered vertically when it fits (top-aligned when it doesn't).
206    ///
207    /// # Arguments
208    ///
209    /// * `bounds` - The rectangle to draw within.
210    /// * `style` - The font and alignment.
211    /// * `color` - The text color (overrides `style.font_color`).
212    /// * `msg` - The text to draw.
213    ///
214    /// # Returns
215    ///
216    /// The size of the text drawn; `0` by `0` if nothing was drawn.
217    fn text(&mut self, bounds: Rect, style: &TextStyle, color: Color, msg: &str) -> Size;
218
219    /// Returns the height of one line of text in a font.
220    ///
221    /// # Arguments
222    ///
223    /// * `style` - The font.
224    ///
225    /// # Returns
226    ///
227    /// The line height in pixels.
228    fn line_height(&mut self, style: &TextStyle) -> u32;
229
230    /// Measures how wide text is on one line, without drawing it.
231    ///
232    /// # Arguments
233    ///
234    /// * `style` - The font.
235    /// * `msg` - The text.
236    ///
237    /// # Returns
238    ///
239    /// The width in pixels.
240    fn text_width(&mut self, style: &TextStyle, msg: &str) -> u32;
241
242    /// Draws an image file, scaled to a rectangle.
243    ///
244    /// # Arguments
245    ///
246    /// * `path` - Path to the image file.
247    /// * `bounds` - The rectangle to draw into.
248    ///
249    /// # Returns
250    ///
251    /// `Ok(())` once the image is drawn.
252    ///
253    /// # Errors
254    ///
255    /// Returns [`Error::Image`] if the image cannot be loaded or drawn.
256    fn image(&mut self, path: &str, bounds: Rect) -> Result<(), Error>;
257
258    /// Fills a rectangle with a 50% checkerboard of two colors, for backends and displays with few
259    /// colors.  The pixel at the rectangle's upper left-hand corner is `first`.
260    ///
261    /// # Arguments
262    ///
263    /// * `bounds` - The rectangle to fill.
264    /// * `first` - The color of the corner pixel.
265    /// * `second` - The other color.
266    fn dither(&mut self, bounds: Rect, first: Color, second: Color);
267
268    /// Draws a color over every other pixel of a rectangle (the pixels a [`dither`](Painter::dither)
269    /// would draw in `first`), blending with what is already there and leaving the other pixels
270    /// untouched.  The pixel at the rectangle's upper left-hand corner is drawn.
271    ///
272    /// # Arguments
273    ///
274    /// * `bounds` - The rectangle to draw over.
275    /// * `color` - The color to blend; its alpha sets the strength.
276    fn dither_overlay(&mut self, bounds: Rect, color: Color);
277
278    /// Limits later drawing to a rectangle, or removes the limit.
279    ///
280    /// # Arguments
281    ///
282    /// * `bounds` - The rectangle to draw within, or `None` for no limit.
283    fn clip(&mut self, bounds: Option<Rect>);
284}
285
286/// Fills the whole drawing surface with a color.
287///
288/// This is the background of most `Widget`s, and usually the first thing their `paint` draws.
289///
290/// # Arguments
291///
292/// * `p` - The painter, targeting the `Widget`.
293/// * `color` - The fill color.
294pub fn fill(p: &mut dyn Painter, color: Color) {
295    p.fill(color);
296}
297
298/// Draws a border inside the edges of the surface.
299///
300/// The border is `width` one-pixel rectangles, each inset one pixel further.  A `width` of `0`
301/// draws nothing, and drawing stops early if the border would cover the whole surface.
302///
303/// # Arguments
304///
305/// * `p` - The painter, targeting the `Widget`.
306/// * `size` - The size of the surface (the `Widget`'s size).
307/// * `color` - The border color.
308/// * `width` - The border width in pixels.
309pub fn border(p: &mut dyn Painter, size: Size, color: Color, width: u8) {
310    for i in 0..width as u32 {
311        if i * 2 >= size.w || i * 2 >= size.h {
312            break;
313        }
314
315        p.rect(
316            Rect::new(i as i32, i as i32, size.w - i * 2, size.h - i * 2),
317            color,
318        );
319    }
320}
321
322/// Draws the generic look of a `Widget`'s visual state on top of what its `paint` drew.
323///
324/// Call it after `paint` (the `WidgetCache` does this for every `Widget`):
325///
326/// - [`VisualState::DISABLED`]: a 50% white dither washes out the `Widget`.
327/// - [`VisualState::FOCUSED`]: a dotted outline, inset one pixel.
328/// - [`VisualState::INDETERMINATE`]: a dotted horizontal bar through the middle.
329///
330/// The other states (`PRESSED`, `CHECKED`, `HOVERED`, `DRAG_OVER`) are drawn by the `Widget`, since
331/// their look depends on what the `Widget` is.
332///
333/// # Arguments
334///
335/// * `p` - The painter, targeting the `Widget`.
336/// * `size` - The size of the surface (the `Widget`'s size).
337/// * `state` - The `Widget`'s visual state.
338pub fn state_overlay(p: &mut dyn Painter, size: Size, state: VisualState) {
339    if size.w == 0 || size.h == 0 {
340        return;
341    }
342
343    if state.contains(VisualState::INDETERMINATE) && size.h >= 3 {
344        let y = (size.h / 2) as i32;
345
346        p.dither_overlay(
347            Rect::new(1, y, size.w.saturating_sub(2).max(1), 1),
348            Color::BLACK,
349        );
350    }
351
352    if state.contains(VisualState::FOCUSED) && size.w > 2 && size.h > 2 {
353        let outline = Color::BLACK;
354        let (w, h) = (size.w - 2, size.h - 2);
355
356        p.dither_overlay(Rect::new(1, 1, w, 1), outline);
357        p.dither_overlay(Rect::new(1, h as i32, w, 1), outline);
358        p.dither_overlay(Rect::new(1, 1, 1, h), outline);
359        p.dither_overlay(Rect::new(w as i32, 1, 1, h), outline);
360    }
361
362    if state.contains(VisualState::DISABLED) {
363        p.dither_overlay(Rect::new(0, 0, size.w, size.h), Color::WHITE);
364    }
365}
366
367/// Draws a string of text within a rectangle.
368///
369/// The text is aligned horizontally according to `style`, wraps at the rectangle's width, and is
370/// centered vertically when it fits (top-aligned when it doesn't).  If it is wider than the
371/// rectangle, `truncate` shortens it with an ellipsis (see [`fit_text`]).  An empty string, or a
372/// rectangle with no width, draws nothing.
373///
374/// # Arguments
375///
376/// * `p` - The painter, targeting the `Widget`.
377/// * `bounds` - The rectangle to draw within, in `Widget` coordinates.
378/// * `style` - The font and alignment.
379/// * `color` - The text color (overrides `style.font_color`, so a `Widget` can invert it).
380/// * `msg` - The text to draw.
381/// * `truncate` - How to shorten text that doesn't fit.
382///
383/// # Returns
384///
385/// The size of the text drawn (`0` by `0` if nothing was drawn) and whether it was shortened.
386pub fn text(
387    p: &mut dyn Painter,
388    bounds: Rect,
389    style: &TextStyle,
390    color: Color,
391    msg: &str,
392    truncate: Truncate,
393) -> TextDrawn {
394    if msg.is_empty() || bounds.w == 0 {
395        return TextDrawn {
396            size: Size::new(0, 0),
397            truncated: false,
398        };
399    }
400
401    let shortened = fit_text(msg, bounds.w, truncate, &mut |s| p.text_width(style, s));
402    let truncated = shortened.is_some();
403    let drawn = shortened.as_deref().unwrap_or(msg);
404
405    if drawn.is_empty() {
406        return TextDrawn {
407            size: Size::new(0, 0),
408            truncated,
409        };
410    }
411
412    TextDrawn {
413        size: p.text(bounds, style, color, drawn),
414        truncated,
415    }
416}
417
418/// Shortens text so it fits a width, cutting on grapheme boundaries and marking the cut with an
419/// ellipsis.  The ellipsis is measured with the same `measure` function as the text, so the result
420/// never overflows `max_width`.
421///
422/// # Arguments
423///
424/// * `msg` - The text.
425/// * `max_width` - The width in pixels the text must fit.
426/// * `mode` - Which part of the text to cut.
427/// * `measure` - Returns the width in pixels of a string in the font being drawn.
428///
429/// # Returns
430///
431/// `None` if the text fits as is, or if `mode` is [`Truncate::None`] or the text has a newline.
432/// Otherwise the shortened text, which is empty if not even the ellipsis fits.
433pub fn fit_text(
434    msg: &str,
435    max_width: u32,
436    mode: Truncate,
437    measure: &mut dyn FnMut(&str) -> u32,
438) -> Option<String> {
439    if mode == Truncate::None || msg.contains('\n') || measure(msg) <= max_width {
440        return None;
441    }
442
443    let graphemes: Vec<&str> = msg.graphemes(true).collect();
444    let build = |keep: usize| -> String {
445        match mode {
446            Truncate::Start => {
447                format!("{ELLIPSIS}{}", graphemes[graphemes.len() - keep..].concat())
448            }
449            Truncate::Middle => {
450                let head = keep.div_ceil(2);
451                let tail = keep - head;
452
453                format!(
454                    "{}{ELLIPSIS}{}",
455                    graphemes[..head].concat(),
456                    graphemes[graphemes.len() - tail..].concat()
457                )
458            }
459            _ => format!("{}{ELLIPSIS}", graphemes[..keep].concat()),
460        }
461    };
462
463    // Width grows with the number of kept graphemes, so binary search for the most that fit.
464    let (mut low, mut high) = (0, graphemes.len());
465    let mut best: Option<String> = None;
466
467    while low <= high {
468        let mid = (low + high) / 2;
469        let candidate = build(mid);
470
471        if measure(&candidate) <= max_width {
472            best = Some(candidate);
473            low = mid + 1;
474        } else if mid == 0 {
475            break;
476        } else {
477            high = mid - 1;
478        }
479    }
480
481    Some(best.unwrap_or_default())
482}
483
484/// Breaks text into lines no wider than a width.
485///
486/// Explicit `\n` always starts a new line (an empty line stays empty).  With [`Wrap::Word`] lines
487/// break at spaces (runs of spaces collapse to one) and a word wider than the width is broken
488/// between graphemes; with [`Wrap::Anywhere`] they break between graphemes.  [`Wrap::None`] only
489/// splits at `\n`.  If `max_lines` is set and the text needs more lines, the last line is cut
490/// and ends in an ellipsis.
491///
492/// # Arguments
493///
494/// * `msg` - The text.
495/// * `max_width` - The width in pixels each line must fit (a single grapheme wider than this is
496///   still put on its own line).
497/// * `wrap` - How to break lines.
498/// * `max_lines` - The most lines to return (at least one is returned), or `None` for no limit.
499/// * `measure` - Returns the width in pixels of a string in the font being drawn.
500///
501/// # Returns
502///
503/// The lines, top to bottom, and whether the last line was cut to honor `max_lines`.
504pub fn wrap_text(
505    msg: &str,
506    max_width: u32,
507    wrap: Wrap,
508    max_lines: Option<usize>,
509    measure: &mut dyn FnMut(&str) -> u32,
510) -> (Vec<String>, bool) {
511    let mut lines: Vec<String> = Vec::new();
512
513    for paragraph in msg.split('\n') {
514        match wrap {
515            Wrap::None => lines.push(paragraph.to_string()),
516            Wrap::Anywhere => break_graphemes(paragraph, max_width, measure, &mut lines),
517            Wrap::Word => break_words(paragraph, max_width, measure, &mut lines),
518        }
519    }
520
521    let Some(limit) = max_lines.map(|n| n.max(1)) else {
522        return (lines, false);
523    };
524
525    if lines.len() <= limit {
526        return (lines, false);
527    }
528
529    lines.truncate(limit);
530
531    // Dropping the trailing ellipsis from the candidate is what fit_text does when it must cut, so
532    // the result always ends in exactly one ellipsis.
533    let last = format!("{}{ELLIPSIS}", lines[limit - 1]);
534    let cut = fit_text(&last, max_width, Truncate::End, measure).unwrap_or(last);
535
536    lines[limit - 1] = cut;
537
538    (lines, true)
539}
540
541/// Breaks one paragraph between graphemes, as late as possible, appending the lines to `out`.
542///
543/// # Arguments
544///
545/// * `text` - The paragraph (no newlines).
546/// * `max_width` - The width each line must fit.
547/// * `measure` - Measures a string.
548/// * `out` - Receives the lines; an empty paragraph adds one empty line.
549fn break_graphemes(
550    text: &str,
551    max_width: u32,
552    measure: &mut dyn FnMut(&str) -> u32,
553    out: &mut Vec<String>,
554) {
555    let mut current = String::new();
556
557    for g in text.graphemes(true) {
558        let candidate = format!("{current}{g}");
559
560        if current.is_empty() || measure(&candidate) <= max_width {
561            current = candidate;
562        } else {
563            out.push(std::mem::replace(&mut current, g.to_string()));
564        }
565    }
566
567    out.push(current);
568}
569
570/// Breaks one paragraph at spaces, appending the lines to `out`.
571///
572/// # Arguments
573///
574/// * `text` - The paragraph (no newlines).
575/// * `max_width` - The width each line must fit.
576/// * `measure` - Measures a string.
577/// * `out` - Receives the lines; an empty paragraph adds one empty line.
578fn break_words(
579    text: &str,
580    max_width: u32,
581    measure: &mut dyn FnMut(&str) -> u32,
582    out: &mut Vec<String>,
583) {
584    let mut current = String::new();
585
586    for word in text.split(' ').filter(|w| !w.is_empty()) {
587        let candidate = if current.is_empty() {
588            word.to_string()
589        } else {
590            format!("{current} {word}")
591        };
592
593        if measure(&candidate) <= max_width {
594            current = candidate;
595            continue;
596        }
597
598        if !current.is_empty() {
599            out.push(std::mem::take(&mut current));
600        }
601
602        if measure(word) <= max_width {
603            current = word.to_string();
604        } else {
605            // A word wider than the width: break it between graphemes; the last piece may take
606            // the next word.
607            let mut pieces = Vec::new();
608
609            break_graphemes(word, max_width, measure, &mut pieces);
610            current = pieces.pop().unwrap_or_default();
611            out.extend(pieces);
612        }
613    }
614
615    out.push(current);
616}
617
618/// Measures the height of wrapped text for a given width, so a layout can give a label the height
619/// it needs.
620///
621/// # Arguments
622///
623/// * `p` - The painter (it measures).
624/// * `style` - The font.
625/// * `msg` - The text.
626/// * `width` - The width in pixels the text will be drawn at.
627/// * `wrap` - How lines break; [`Wrap::None`] is one line per `\n`.
628/// * `max_lines` - The most lines, or `None`.
629///
630/// # Returns
631///
632/// The height in pixels: the number of lines times the line height.
633pub fn height_for_width(
634    p: &mut dyn Painter,
635    style: &TextStyle,
636    msg: &str,
637    width: u32,
638    wrap: Wrap,
639    max_lines: Option<usize>,
640) -> u32 {
641    if msg.is_empty() {
642        return 0;
643    }
644
645    let (lines, _) = wrap_text(msg, width, wrap, max_lines, &mut |s| p.text_width(style, s));
646
647    lines.len() as u32 * p.line_height(style)
648}
649
650/// Draws wrapped text: a block of lines, each aligned by `style.justification` within the
651/// rectangle, centered vertically when the block fits (top-aligned when it doesn't).  Lines that
652/// start below the rectangle are not drawn.
653///
654/// # Arguments
655///
656/// * `p` - The painter, targeting the `Widget`.
657/// * `bounds` - The rectangle to draw within, in `Widget` coordinates.
658/// * `style` - The font and alignment.
659/// * `color` - The text color.
660/// * `msg` - The text; `\n` starts a new line.
661/// * `wrap` - How lines break (see [`wrap_text`]).
662/// * `max_lines` - The most lines; the last is cut with an ellipsis if the text needs more.
663///
664/// # Returns
665///
666/// The size of the block drawn (`0` by `0` if nothing was drawn) and whether the text was cut to
667/// honor `max_lines`.
668pub fn paragraph(
669    p: &mut dyn Painter,
670    bounds: Rect,
671    style: &TextStyle,
672    color: Color,
673    msg: &str,
674    wrap: Wrap,
675    max_lines: Option<usize>,
676) -> TextDrawn {
677    if msg.is_empty() || bounds.w == 0 {
678        return TextDrawn {
679            size: Size::new(0, 0),
680            truncated: false,
681        };
682    }
683
684    let (lines, truncated) = wrap_text(msg, bounds.w, wrap, max_lines, &mut |s| {
685        p.text_width(style, s)
686    });
687    let line_h = p.line_height(style);
688    let block_h = lines.len() as u32 * line_h;
689    let top = if block_h < bounds.h {
690        bounds.y + (bounds.h - block_h) as i32 / 2
691    } else {
692        bounds.y
693    };
694    let bottom = bounds.y + bounds.h as i32;
695    let mut widest = 0;
696
697    for (i, line) in lines.iter().enumerate() {
698        let y = top + i as i32 * line_h as i32;
699
700        if y >= bottom {
701            break;
702        }
703
704        if !line.is_empty() {
705            let drawn = p.text(Rect::new(bounds.x, y, bounds.w, line_h), style, color, line);
706
707            widest = widest.max(drawn.w);
708        }
709    }
710
711    TextDrawn {
712        size: Size::new(widest, block_h),
713        truncated,
714    }
715}
716
717/// Computes where text of a given size is drawn within a rectangle.
718///
719/// Backends use this so every backend aligns text the same way: horizontally by `justification`,
720/// and vertically centered when the text fits (top-aligned when it doesn't).
721///
722/// # Arguments
723///
724/// * `bounds` - The rectangle to draw within.
725/// * `text_size` - The size of the rendered text.
726/// * `justification` - The horizontal alignment.
727///
728/// # Returns
729///
730/// The rectangle the text occupies.
731pub fn align_text(bounds: Rect, text_size: Size, justification: TextJustify) -> Rect {
732    let bounds_width = bounds.w as i32;
733    let x = bounds.x
734        + match justification {
735            TextJustify::Left => 0,
736            TextJustify::Right => bounds_width - text_size.w as i32,
737            TextJustify::Center => (bounds_width - text_size.w as i32) / 2,
738        };
739    let y = if text_size.h < bounds.h {
740        bounds.y + (bounds.h - text_size.h) as i32 / 2
741    } else {
742        bounds.y
743    };
744
745    Rect::new(x, y, text_size.w, text_size.h)
746}
747
748#[cfg(test)]
749mod tests {
750    use super::*;
751    use crate::backend::headless::{PaintCall, RecordingPainter};
752
753    fn style(justification: TextJustify) -> TextStyle {
754        TextStyle::new(
755            String::from("font.ttf"),
756            FontStyle::NORMAL,
757            10,
758            Color::BLACK,
759            justification,
760        )
761    }
762
763    #[test]
764    fn state_overlay_draws_nothing_for_the_normal_state() {
765        let mut p = RecordingPainter::default();
766        state_overlay(&mut p, Size::new(40, 20), VisualState::empty());
767        state_overlay(
768            &mut p,
769            Size::new(40, 20),
770            VisualState::CHECKED | VisualState::HOVERED,
771        );
772        assert!(p.calls.is_empty());
773    }
774
775    #[test]
776    fn state_overlay_dims_disabled_widgets_last() {
777        let mut p = RecordingPainter::default();
778        state_overlay(
779            &mut p,
780            Size::new(40, 20),
781            VisualState::DISABLED | VisualState::FOCUSED,
782        );
783
784        assert_eq!(
785            p.calls.last(),
786            Some(&PaintCall::DitherOverlay(
787                Rect::new(0, 0, 40, 20),
788                Color::WHITE
789            ))
790        );
791        assert_eq!(p.calls.len(), 5, "four focus edges, then the dim");
792    }
793
794    #[test]
795    fn state_overlay_draws_a_focus_outline_and_an_indeterminate_bar() {
796        let mut p = RecordingPainter::default();
797        state_overlay(&mut p, Size::new(40, 20), VisualState::FOCUSED);
798        assert_eq!(p.calls.len(), 4);
799
800        let mut p = RecordingPainter::default();
801        state_overlay(&mut p, Size::new(40, 20), VisualState::INDETERMINATE);
802        assert_eq!(
803            p.calls,
804            vec![PaintCall::DitherOverlay(
805                Rect::new(1, 10, 38, 1),
806                Color::BLACK
807            )]
808        );
809    }
810
811    #[test]
812    fn state_overlay_ignores_empty_and_tiny_surfaces() {
813        let mut p = RecordingPainter::default();
814        state_overlay(&mut p, Size::new(0, 10), VisualState::DISABLED);
815        state_overlay(
816            &mut p,
817            Size::new(2, 2),
818            VisualState::FOCUSED | VisualState::INDETERMINATE,
819        );
820        assert!(p.calls.is_empty());
821    }
822
823    #[test]
824    fn fill_records_one_call() {
825        let mut p = RecordingPainter::default();
826        fill(&mut p, Color::RED);
827        assert_eq!(p.calls, vec![PaintCall::Fill(Color::RED)]);
828    }
829
830    #[test]
831    fn border_insets_each_ring() {
832        let mut p = RecordingPainter::default();
833        border(&mut p, Size::new(10, 10), Color::BLUE, 2);
834        assert_eq!(
835            p.calls,
836            vec![
837                PaintCall::Rect(Rect::new(0, 0, 10, 10), Color::BLUE),
838                PaintCall::Rect(Rect::new(1, 1, 8, 8), Color::BLUE),
839            ]
840        );
841    }
842
843    #[test]
844    fn border_zero_width_draws_nothing() {
845        let mut p = RecordingPainter::default();
846        border(&mut p, Size::new(10, 10), Color::BLUE, 0);
847        assert!(p.calls.is_empty());
848    }
849
850    #[test]
851    fn border_stops_when_it_covers_the_surface() {
852        let mut p = RecordingPainter::default();
853        border(&mut p, Size::new(4, 10), Color::BLUE, 9);
854        assert_eq!(p.calls.len(), 2);
855    }
856
857    #[test]
858    fn empty_text_or_zero_width_draws_nothing() {
859        let mut p = RecordingPainter::default();
860        let s = style(TextJustify::Left);
861        assert_eq!(
862            text(
863                &mut p,
864                Rect::new(0, 0, 50, 20),
865                &s,
866                Color::BLACK,
867                "",
868                Truncate::End
869            )
870            .size,
871            Size::new(0, 0)
872        );
873        assert_eq!(
874            text(
875                &mut p,
876                Rect::new(0, 0, 0, 20),
877                &s,
878                Color::BLACK,
879                "hi",
880                Truncate::End
881            )
882            .size,
883            Size::new(0, 0)
884        );
885        assert!(p.calls.is_empty());
886    }
887
888    #[test]
889    fn text_is_recorded() {
890        let mut p = RecordingPainter::default();
891        let s = style(TextJustify::Left);
892        let drawn = text(
893            &mut p,
894            Rect::new(0, 0, 100, 20),
895            &s,
896            Color::WHITE,
897            "hi",
898            Truncate::End,
899        );
900        assert_ne!(drawn.size, Size::new(0, 0));
901        assert!(!drawn.truncated, "text that fits is drawn unchanged");
902        assert_eq!(
903            p.calls,
904            vec![PaintCall::Text(
905                Rect::new(0, 0, 100, 20),
906                String::from("hi"),
907                Color::WHITE
908            )]
909        );
910    }
911
912    #[test]
913    fn align_text_justifies_and_centers() {
914        let bounds = Rect::new(10, 20, 100, 40);
915        let t = Size::new(30, 10);
916        assert_eq!(
917            align_text(bounds, t, TextJustify::Left),
918            Rect::new(10, 35, 30, 10)
919        );
920        assert_eq!(
921            align_text(bounds, t, TextJustify::Right),
922            Rect::new(80, 35, 30, 10)
923        );
924        assert_eq!(
925            align_text(bounds, t, TextJustify::Center),
926            Rect::new(45, 35, 30, 10)
927        );
928    }
929
930    #[test]
931    fn align_text_top_aligns_when_too_tall() {
932        let bounds = Rect::new(0, 5, 100, 10);
933        assert_eq!(
934            align_text(bounds, Size::new(20, 30), TextJustify::Left),
935            Rect::new(0, 5, 20, 30)
936        );
937    }
938
939    #[test]
940    fn cache_policy_defaults_to_texture_cache() {
941        assert_eq!(CachePolicy::default(), CachePolicy::TextureCache);
942    }
943
944    /// Draws `msg` in a 50-pixel-wide box (ten characters at 5 pixels each) and returns what the
945    /// painter recorded, plus whether the text was shortened.
946    fn drawn_text(msg: &str, mode: Truncate) -> (String, bool) {
947        let mut p = RecordingPainter::default();
948        let s = style(TextJustify::Left);
949        let drawn = text(&mut p, Rect::new(0, 0, 50, 20), &s, Color::BLACK, msg, mode);
950        let recorded = match p.calls.first() {
951            Some(PaintCall::Text(_, t, _)) => t.clone(),
952            _ => String::new(),
953        };
954
955        (recorded, drawn.truncated)
956    }
957
958    #[test]
959    fn text_that_fits_is_unchanged_in_every_mode() {
960        for mode in [
961            Truncate::None,
962            Truncate::End,
963            Truncate::Start,
964            Truncate::Middle,
965        ] {
966            assert_eq!(
967                drawn_text("0123456789", mode),
968                (String::from("0123456789"), false)
969            );
970        }
971    }
972
973    #[test]
974    fn end_start_and_middle_cut_with_an_ellipsis() {
975        let msg = "Quarterly report.txt";
976
977        assert_eq!(
978            drawn_text(msg, Truncate::End),
979            (String::from("Quarterly\u{2026}"), true)
980        );
981        assert_eq!(
982            drawn_text(msg, Truncate::Start),
983            (String::from("\u{2026}eport.txt"), true)
984        );
985        assert_eq!(
986            drawn_text(msg, Truncate::Middle),
987            (String::from("Quart\u{2026}.txt"), true)
988        );
989    }
990
991    #[test]
992    fn none_leaves_long_text_for_the_backend_to_clip() {
993        assert_eq!(
994            drawn_text("Quarterly report.txt", Truncate::None),
995            (String::from("Quarterly report.txt"), false)
996        );
997    }
998
999    #[test]
1000    fn truncated_text_never_overflows() {
1001        let mut measure = |s: &str| s.chars().count() as u32 * 5;
1002
1003        for mode in [Truncate::End, Truncate::Start, Truncate::Middle] {
1004            for width in 0..60 {
1005                let cut = fit_text("The quick brown fox jumps", width, mode, &mut measure).unwrap();
1006                assert!(measure(&cut) <= width, "{mode:?} at {width}: {cut:?}");
1007            }
1008        }
1009    }
1010
1011    #[test]
1012    fn a_width_too_small_for_the_ellipsis_draws_nothing() {
1013        let mut p = RecordingPainter::default();
1014        let s = style(TextJustify::Left);
1015        let drawn = text(
1016            &mut p,
1017            Rect::new(0, 0, 4, 20),
1018            &s,
1019            Color::BLACK,
1020            "hello",
1021            Truncate::End,
1022        );
1023
1024        assert!(drawn.truncated);
1025        assert_eq!(drawn.size, Size::new(0, 0));
1026        assert!(p.calls.is_empty());
1027    }
1028
1029    #[test]
1030    fn cuts_fall_on_grapheme_boundaries() {
1031        // "e" + combining acute, a flag (two scalars), and a family emoji (a ZWJ sequence).
1032        let msg = "e\u{301}e\u{301}e\u{301}\u{1F1FA}\u{1F1F8}\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}ab";
1033        let mut by_graphemes = |s: &str| s.graphemes(true).count() as u32;
1034
1035        for mode in [Truncate::End, Truncate::Start, Truncate::Middle] {
1036            let cut = fit_text(msg, 4, mode, &mut by_graphemes).unwrap();
1037            assert_eq!(cut.graphemes(true).count(), 4, "{mode:?}: {cut:?}");
1038        }
1039
1040        let end = fit_text(msg, 4, Truncate::End, &mut by_graphemes).unwrap();
1041        assert_eq!(end, "e\u{301}e\u{301}e\u{301}\u{2026}");
1042    }
1043
1044    #[test]
1045    fn text_with_a_newline_is_not_truncated() {
1046        let mut measure = |s: &str| s.chars().count() as u32 * 5;
1047
1048        assert_eq!(
1049            fit_text("a long first line\nb", 10, Truncate::End, &mut measure),
1050            None
1051        );
1052    }
1053
1054    #[test]
1055    fn end_is_the_default_mode() {
1056        assert_eq!(Truncate::default(), Truncate::End);
1057    }
1058
1059    /// Five pixels per character, like the recording painter at font size 10.
1060    fn five(s: &str) -> u32 {
1061        s.chars().count() as u32 * 5
1062    }
1063
1064    #[test]
1065    fn word_wrap_breaks_at_spaces_and_reflows() {
1066        let msg = "the quick brown fox jumps";
1067        let (wide, _) = wrap_text(msg, 100, Wrap::Word, None, &mut five);
1068        let (narrow, _) = wrap_text(msg, 50, Wrap::Word, None, &mut five);
1069
1070        assert_eq!(wide, vec!["the quick brown fox", "jumps"]);
1071        assert_eq!(narrow, vec!["the quick", "brown fox", "jumps"]);
1072        assert!(narrow.iter().all(|l| five(l) <= 50));
1073    }
1074
1075    #[test]
1076    fn explicit_newlines_are_kept_and_blank_lines_stay() {
1077        let (lines, _) = wrap_text("a\n\nb c", 100, Wrap::Word, None, &mut five);
1078
1079        assert_eq!(lines, vec!["a", "", "b c"]);
1080    }
1081
1082    #[test]
1083    fn a_word_wider_than_the_width_is_broken() {
1084        let (lines, _) = wrap_text("abcdefghij kl", 20, Wrap::Word, None, &mut five);
1085
1086        assert_eq!(lines, vec!["abcd", "efgh", "ij", "kl"]);
1087    }
1088
1089    #[test]
1090    fn anywhere_breaks_between_graphemes() {
1091        let (lines, _) = wrap_text("abcdefghij", 25, Wrap::Anywhere, None, &mut five);
1092
1093        assert_eq!(lines, vec!["abcde", "fghij"]);
1094
1095        let (lines, _) = wrap_text(
1096            "e\u{301}e\u{301}e\u{301}",
1097            5,
1098            Wrap::Anywhere,
1099            None,
1100            &mut |s| s.graphemes(true).count() as u32 * 5,
1101        );
1102
1103        assert_eq!(
1104            lines,
1105            vec!["e\u{301}", "e\u{301}", "e\u{301}"],
1106            "accents stay with their letter"
1107        );
1108    }
1109
1110    #[test]
1111    fn max_lines_cuts_the_last_line_with_an_ellipsis() {
1112        let (lines, cut) = wrap_text(
1113            "the quick brown fox jumps",
1114            50,
1115            Wrap::Word,
1116            Some(2),
1117            &mut five,
1118        );
1119
1120        assert!(cut);
1121        assert_eq!(lines.len(), 2);
1122        assert_eq!(lines[0], "the quick");
1123        assert_eq!(lines[1], "brown fox\u{2026}");
1124        assert!(lines.iter().all(|l| five(l) <= 50));
1125
1126        let (lines, cut) = wrap_text("a\nb", 100, Wrap::Word, Some(1), &mut five);
1127
1128        assert!(cut, "an explicit break past the limit also cuts");
1129        assert_eq!(lines, vec!["a\u{2026}"]);
1130
1131        let (_, cut) = wrap_text("a b", 100, Wrap::Word, Some(2), &mut five);
1132
1133        assert!(!cut, "text that fits is not cut");
1134    }
1135
1136    #[test]
1137    fn paragraph_aligns_each_line_and_reports_height() {
1138        let mut p = RecordingPainter::default();
1139        let s = style(TextJustify::Right);
1140        let drawn = paragraph(
1141            &mut p,
1142            Rect::new(0, 0, 50, 40),
1143            &s,
1144            Color::BLACK,
1145            "the quick brown fox",
1146            Wrap::Word,
1147            None,
1148        );
1149
1150        assert_eq!(drawn.size.h, 20, "two lines of ten pixels");
1151        assert!(!drawn.truncated);
1152        assert_eq!(
1153            p.calls,
1154            vec![
1155                PaintCall::Text(
1156                    Rect::new(0, 10, 50, 10),
1157                    String::from("the quick"),
1158                    Color::BLACK
1159                ),
1160                PaintCall::Text(
1161                    Rect::new(0, 20, 50, 10),
1162                    String::from("brown fox"),
1163                    Color::BLACK
1164                ),
1165            ],
1166            "each line gets its own rectangle, so the justification applies per line"
1167        );
1168    }
1169
1170    #[test]
1171    fn paragraph_skips_lines_below_the_bounds() {
1172        let mut p = RecordingPainter::default();
1173        let s = style(TextJustify::Left);
1174
1175        paragraph(
1176            &mut p,
1177            Rect::new(0, 0, 50, 15),
1178            &s,
1179            Color::BLACK,
1180            "a\nb\nc",
1181            Wrap::Word,
1182            None,
1183        );
1184
1185        assert_eq!(
1186            p.calls.len(),
1187            2,
1188            "lines at y 0 and 10 start inside; y 20 does not"
1189        );
1190    }
1191
1192    #[test]
1193    fn height_for_width_grows_as_the_width_shrinks() {
1194        let mut p = RecordingPainter::default();
1195        let s = style(TextJustify::Left);
1196        let msg = "the quick brown fox jumps";
1197
1198        assert_eq!(height_for_width(&mut p, &s, msg, 100, Wrap::Word, None), 20);
1199        assert_eq!(height_for_width(&mut p, &s, msg, 50, Wrap::Word, None), 30);
1200        assert_eq!(
1201            height_for_width(&mut p, &s, msg, 50, Wrap::Word, Some(2)),
1202            20
1203        );
1204        assert_eq!(height_for_width(&mut p, &s, "", 50, Wrap::Word, None), 0);
1205    }
1206}