use embedded_graphics::{
Drawable,
draw_target::{DrawTarget, DrawTargetExt},
geometry::{AnchorPoint, Dimensions, Point, Size},
pixelcolor::PixelColor,
primitives::{Primitive, PrimitiveStyle, Rectangle},
};
use crate::style::{FontStyle, FrameStyle};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct CursorStyle<C> {
pub color: C,
pub width: u32,
pub gap: u32,
}
impl<C: PixelColor> CursorStyle<C> {
#[must_use]
pub const fn new(color: C) -> Self {
Self {
color,
width: 1,
gap: 1,
}
}
#[must_use]
pub const fn with_width(mut self, width: u32) -> Self {
self.width = width;
self
}
#[must_use]
pub const fn with_gap(mut self, gap: u32) -> Self {
self.gap = gap;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct TextFieldStyle<C, S> {
pub frame: FrameStyle<C>,
pub font: S,
pub title_font: S,
pub title_gap: u32,
pub padding: u32,
pub cursor: Option<CursorStyle<C>>,
}
impl<C: PixelColor, S> TextFieldStyle<C, S> {
#[must_use]
pub const fn new(font: S, title_font: S) -> Self {
Self {
frame: FrameStyle::new(),
font,
title_font,
title_gap: 4,
padding: 8,
cursor: None,
}
}
#[must_use]
pub const fn with_frame(mut self, frame: FrameStyle<C>) -> Self {
self.frame = frame;
self
}
#[must_use]
pub const fn with_title_gap(mut self, gap: u32) -> Self {
self.title_gap = gap;
self
}
#[must_use]
pub const fn with_padding(mut self, padding: u32) -> Self {
self.padding = padding;
self
}
#[must_use]
pub const fn with_cursor(mut self, cursor: CursorStyle<C>) -> Self {
self.cursor = Some(cursor);
self
}
}
impl<C: PixelColor, S: FontStyle<C>> TextFieldStyle<C, S> {
#[must_use]
pub fn height(&self, with_title: bool) -> u32 {
let title = if with_title {
(self.title_font.measure(REFERENCE_TEXT).height).saturating_add(self.title_gap)
} else {
0
};
let margins = self
.padding
.saturating_add(self.frame.effective_border_width())
.saturating_mul(2);
title
.saturating_add(self.font.measure(REFERENCE_TEXT).height)
.saturating_add(margins)
}
}
const REFERENCE_TEXT: &str = "Ag";
#[derive(Debug, Clone, Copy)]
pub struct TextField<'a, C, S> {
bounds: Rectangle,
value: &'a str,
title: Option<&'a str>,
show_cursor: bool,
cursor_position: Option<usize>,
style: &'a TextFieldStyle<C, S>,
}
impl<'a, C, S> TextField<'a, C, S>
where
C: PixelColor,
S: FontStyle<C>,
{
#[must_use]
pub const fn new(bounds: Rectangle, value: &'a str, style: &'a TextFieldStyle<C, S>) -> Self {
Self {
bounds,
value,
title: None,
show_cursor: true,
cursor_position: None,
style,
}
}
#[must_use]
pub const fn with_title(mut self, title: &'a str) -> Self {
self.title = Some(title);
self
}
#[must_use]
pub const fn with_cursor_visible(mut self, visible: bool) -> Self {
self.show_cursor = visible;
self
}
#[must_use]
pub const fn with_cursor_position(mut self, index: usize) -> Self {
self.cursor_position = Some(index);
self
}
fn cursor_index(&self) -> usize {
let mut index = self
.cursor_position
.map_or(self.value.len(), |i| i.min(self.value.len()));
while !self.value.is_char_boundary(index) {
index -= 1;
}
index
}
fn title_height(&self) -> u32 {
self.title.map_or(0, |title| {
(self.style.title_font.measure(title).height).saturating_add(self.style.title_gap)
})
}
#[must_use]
pub fn frame_bounds(&self) -> Rectangle {
let title_h = self.title_height().min(self.bounds.size.height);
Rectangle::new(
self.bounds.top_left + Point::new(0, title_h as i32),
Size::new(self.bounds.size.width, self.bounds.size.height - title_h),
)
}
}
impl<C, S> Dimensions for TextField<'_, C, S> {
fn bounding_box(&self) -> Rectangle {
self.bounds
}
}
impl<C, S> Drawable for TextField<'_, C, S>
where
C: PixelColor,
S: FontStyle<C>,
{
type Color = C;
type Output = ();
fn draw<D: DrawTarget<Color = C>>(&self, target: &mut D) -> Result<(), D::Error> {
let style = self.style;
if let Some(title) = self.title {
style.title_font.draw_anchored(
&mut target.clipped(&self.bounds),
title,
self.bounds.top_left,
AnchorPoint::TopLeft,
)?;
}
let frame = self.frame_bounds();
style.frame.draw(target, frame)?;
let content = style.frame.content_area(frame);
let content = Rectangle::new(
content.top_left + Point::new(style.padding as i32, 0),
Size::new(
content
.size
.width
.saturating_sub(style.padding.saturating_mul(2)),
content.size.height,
),
);
let cursor = style.cursor.filter(|_| self.show_cursor);
let cursor_w = cursor.map_or(0, |c| c.gap.saturating_add(c.width));
let text_size = style.font.measure(self.value);
let cursor_x = style.font.measure(&self.value[..self.cursor_index()]).width;
let overflow = (text_size.width.saturating_add(cursor_w))
.saturating_sub(content.size.width)
.min(cursor_x);
let text_left = content.top_left.x - overflow as i32;
let center_y = content.center().y;
let mut clipped = target.clipped(&content);
style.font.draw_anchored(
&mut clipped,
self.value,
Point::new(text_left, center_y),
AnchorPoint::CenterLeft,
)?;
if let Some(cursor) = cursor {
let height = style
.font
.measure(REFERENCE_TEXT)
.height
.min(content.size.height);
let origin = Point::new(
text_left + cursor_x.saturating_add(cursor.gap) as i32,
center_y - (height / 2) as i32,
);
Rectangle::new(origin, Size::new(cursor.width, height))
.into_styled(PrimitiveStyle::with_fill(cursor.color))
.draw(&mut clipped)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use embedded_graphics::{
mock_display::MockDisplay,
mono_font::{MonoTextStyle, ascii::FONT_6X10},
pixelcolor::BinaryColor,
};
const BOUNDS: Rectangle = Rectangle::new(Point::new(2, 2), Size::new(60, 40));
fn style() -> TextFieldStyle<BinaryColor, MonoTextStyle<'static, BinaryColor>> {
let font = MonoTextStyle::new(&FONT_6X10, BinaryColor::On);
TextFieldStyle::new(font, font)
.with_frame(FrameStyle::new().with_border(BinaryColor::On, 2))
.with_padding(3)
.with_cursor(CursorStyle::new(BinaryColor::On))
}
#[test]
fn title_sits_above_the_frame() {
let style = style();
let field = TextField::new(BOUNDS, "", &style);
assert_eq!(field.frame_bounds(), BOUNDS);
let field = field.with_title("Title");
let frame = field.frame_bounds();
assert_eq!(frame.top_left.y, BOUNDS.top_left.y + 10 + 4);
assert_eq!(frame.bottom_right(), BOUNDS.bottom_right());
}
#[test]
fn height_fits_title_text_padding_and_border() {
let style = style();
assert_eq!(style.height(false), 10 + 2 * (3 + 2));
assert_eq!(style.height(true), 10 + 4 + 10 + 2 * (3 + 2));
}
#[test]
fn long_text_is_clipped_to_the_frame() {
let style = style();
let field =
TextField::new(BOUNDS, "a very long text that overflows", &style).with_title("T");
let mut display = MockDisplay::new();
display.set_allow_overdraw(true);
field.draw(&mut display).unwrap();
assert!(BOUNDS.contains(display.affected_area().top_left));
assert!(BOUNDS.contains(display.affected_area().bottom_right().unwrap()));
let content = style.frame.content_area(field.frame_bounds());
let last_x = content.top_left.x + content.size.width as i32 - 1 - 3;
let lit = (content.top_left.y..content.top_left.y + content.size.height as i32)
.any(|y| display.get_pixel(Point::new(last_x, y)) == Some(BinaryColor::On));
assert!(lit);
}
#[test]
fn long_title_is_clipped_to_the_bounds() {
let style = style();
let field =
TextField::new(BOUNDS, "", &style).with_title("a title much wider than the field");
let mut display = MockDisplay::new();
display.set_allow_overdraw(true);
field.draw(&mut display).unwrap();
assert!(BOUNDS.contains(display.affected_area().bottom_right().unwrap()));
}
#[test]
fn huge_padding_does_not_overflow() {
let style = style().with_padding(u32::MAX);
assert_eq!(style.height(true), u32::MAX);
}
fn lit_columns(
field: &TextField<'_, BinaryColor, MonoTextStyle<'static, BinaryColor>>,
) -> [bool; 60] {
let mut display = MockDisplay::new();
display.set_allow_overdraw(true);
field.draw(&mut display).unwrap();
let content = field.style.frame.content_area(field.frame_bounds());
let mut lit = [false; 60];
for (x, column) in lit.iter_mut().enumerate() {
*column = (content.top_left.y..content.top_left.y + content.size.height as i32)
.any(|y| display.get_pixel(Point::new(x as i32, y)) == Some(BinaryColor::On));
}
lit
}
#[test]
fn cursor_is_drawn_at_its_position() {
let style = style();
let field = TextField::new(BOUNDS, " ", &style);
let lit = lit_columns(&field);
assert!(lit[7 + 18 + 1] && !lit[7 + 6 + 1]);
let lit = lit_columns(&field.with_cursor_position(1));
assert!(lit[7 + 6 + 1] && !lit[7 + 18 + 1]);
let lit = lit_columns(&field.with_cursor_position(99));
assert!(lit[7 + 18 + 1]);
let field = TextField::new(BOUNDS, " \u{e9}", &style).with_cursor_position(2);
assert_eq!(field.cursor_index(), 1);
}
#[test]
fn scrolling_keeps_the_cursor_visible() {
let style = style();
let field = TextField::new(BOUNDS, "a very long text that overflows", &style)
.with_cursor_position(0);
let lit = lit_columns(&field);
assert!(lit[7 + 1]);
}
}