1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
//! `TextBox` styling.
//! ==================
//!
//! To construct a `TextBox` object at least a text string, a bounding box and character style are
//! required. For advanced formatting options an additional `TextBoxStyle` object might be used.
//!
//! Text rendering in `embedded-graphics` is designed to be extendable by text renderers for
//! different font formats. `embedded-text` follows this philosophy by using the same text renderer
//! infrastructure. To use a text renderer in an `embedded-text` project each renderer provides a
//! character style object. See the [`embedded-graphics` documentation] for more information.
//!
//! TextBox style
//! ---------------
//!
//! In addition to styling the individual characters the [`TextBox`] drawable also contains a
//! [`TextBoxStyle`] setting. The text box style is used to set the horizontal and vertical
//! alignment, line and paragraph spacing, tab size and some other advanced settings of text box
//! objects.
//!
//! The [`alignment`] option sets the horizontal alignment of the text.
//! **Note: alignment works differently from `embedded-graphics`.**
//! With the default value `Left` the start of each line will be lined up with the left side of the
//! bounding box. Similarly `Right` aligned text will line up the ends of the lines with the right
//! side of the bounding box. `Center`ed text will be positioned at equal distance from the left and
//! right sides. `Justified` text will distribute the text in such a way that both the start and end
//! of a line will align with the respective sides of the bounding box.
//!
//! The [`vertical_alignment`] setting sets the vertical alignment of the text.
//! With the default value `Top` the top of the text is lined up with the top of the bounding box.
//! Similarly `Bottom` aligned text will line up the bottom of the last line of the text with the
//! bottom edge of the bounding box. `Middle` aligned text will be positioned at equal distance from
//! the top and bottom sides.
//!
//! The [`line_height`] option sets the distance between the baselines of the lines of text. It can
//! be specified in either pixels or percentage of the line height defined by the font.
//!
//! The [`paragraph_spacing`] setting sets the distance between paragraphs of text, in addition to
//! the line spacing.
//!
//! The [`tab_size`] setting sets the maximum width of a tab character. It can be specified in
//! either pixels of number of space characters.
//!
//! Advanced settings
//! -----------------
//!
//! The [`height_mode`] setting determines how the `TextBox` adjusts its height to its contents.
//! The default value [`Exact`] does not adjust the height - the text box will be as tall as the
//! bounding box given to it. [`FitToText`] will adjust the height to the height of the text,
//! regardless of the initial bounding box's height. [`ShrinkToText`] will decrease the height
//! of the text box to the height of the text, if the bounding box given to the text box is too
//! tall.
//!
//! `Exact` and `ShrinkToText` have an additional [`VerticalOverdraw`] parameter. This setting
//! specifies how the text outside of the adjusted bounding box is handled. [`Visible`] renders the
//! text regardless of the bounding box. [`Hidden`] renders everything inside the bounding box. If a
//! line is too tall to fit inside the bounding box, it will be drawn partially, the bottom part of
//! the text clipped. [`FullRowsOnly`] only renders lines that are completely inside the bounding
//! box.
//!
//! For examples on how to use height mode settings, see the documentation of [`HeightMode`].
//!
//! The [`leading_spaces`] and [`trailing_spaces`] settings set whether the spaces at the beginning
//! or the end of a line are visible. The default values depend on the [`alignment`] setting.
//!
//! | `alignment` | `leading_spaces` | `trailing_spaces` |
//! | ------------ | ---------------- | ----------------- |
//! | `Left` | `true` | `false` |
//! | `Right` | `false` | `false` |
//! | `Center` | `false` | `false` |
//! | `Justified` | `false` | `false` |
//!
//! # Ways to create and apply text box styles
//!
//! ## Example 1: Setting multiple options using the [`TextBoxStyleBuilder`] object:
//!
//! To build more complex styles, you can use the [`TextBoxStyleBuilder`] object and the
//! [`TextBox::with_textbox_style`] constructor.
//!
//! ```rust
//! # use embedded_graphics::{
//! # mono_font::{ascii::FONT_6X9, MonoTextStyle},
//! # pixelcolor::BinaryColor,
//! # prelude::*,
//! # primitives::Rectangle,
//! # };
//! # let character_style = MonoTextStyle::new(&FONT_6X9, BinaryColor::On);
//! # let bounding_box = Rectangle::new(Point::zero(), Size::new(60, 10));
//! # let text = "";
//! #
//! use embedded_text::{
//! TextBox,
//! style::TextBoxStyleBuilder,
//! alignment::{
//! HorizontalAlignment,
//! VerticalAlignment,
//! },
//! };
//!
//! let textbox_style = TextBoxStyleBuilder::new()
//! .alignment(HorizontalAlignment::Center)
//! .vertical_alignment(VerticalAlignment::Middle)
//! .build();
//!
//! let textbox = TextBox::with_textbox_style(
//! text,
//! bounding_box,
//! character_style,
//! textbox_style,
//! );
//! ```
//!
//! [`TextBox::with_textbox_style`]: crate::TextBox::with_textbox_style
//!
//! ## Examples 2 and 3: Only setting a single option:
//!
//! Both the [`TextBox`] and [`TextBoxStyle`] objects have different constructor methods in case you
//! only want to set a single style option.
//!
//! ```rust
//! # use embedded_graphics::{
//! # mono_font::{ascii::FONT_6X9, MonoTextStyle},
//! # pixelcolor::BinaryColor,
//! # prelude::*,
//! # primitives::Rectangle,
//! # };
//! # let character_style = MonoTextStyle::new(&FONT_6X9, BinaryColor::On);
//! # let bounding_box = Rectangle::new(Point::zero(), Size::new(60, 10));
//! # let text = "";
//! #
//! use embedded_text::{TextBox, alignment::HorizontalAlignment};
//!
//! let textbox = TextBox::with_alignment(
//! text,
//! bounding_box,
//! character_style,
//! HorizontalAlignment::Center,
//! );
//! ```
//!
//! ```rust
//! # use embedded_graphics::{
//! # mono_font::{ascii::FONT_6X9, MonoTextStyle},
//! # pixelcolor::BinaryColor,
//! # prelude::*,
//! # primitives::Rectangle,
//! # };
//! # let character_style = MonoTextStyle::new(&FONT_6X9, BinaryColor::On);
//! # let bounding_box = Rectangle::new(Point::zero(), Size::new(60, 10));
//! # let text = "";
//! #
//! use embedded_text::{TextBox, style::TextBoxStyle, alignment::VerticalAlignment};
//!
//! let textbox_style = TextBoxStyle::with_vertical_alignment(VerticalAlignment::Middle);
//!
//! let textbox = TextBox::with_textbox_style(
//! text,
//! bounding_box,
//! character_style,
//! textbox_style,
//! );
//! ```
//!
//! [`TextBox`]: crate::TextBox
//! [`alignment`]: TextBoxStyle::alignment
//! [`vertical_alignment`]: TextBoxStyle::vertical_alignment
//! [`line_height`]: TextBoxStyle::line_height
//! [`paragraph_spacing`]: TextBoxStyle::paragraph_spacing
//! [`tab_size`]: TextBoxStyle::tab_size
//! [`height_mode`]: TextBoxStyle::height_mode
//! [`leading_spaces`]: TextBoxStyle::leading_spaces
//! [`trailing_spaces`]: TextBoxStyle::trailing_spaces
//! [`Exact`]: HeightMode::Exact
//! [`FitToText`]: HeightMode::FitToText
//! [`ShrinkToText`]: HeightMode::ShrinkToText
//! [`Visible`]: VerticalOverdraw::Visible
//! [`Hidden`]: VerticalOverdraw::Hidden
//! [`FullRowsOnly`]: VerticalOverdraw::FullRowsOnly
//! [`embedded-graphics` documentation]: https://docs.rs/embedded-graphics/0.7.1/embedded_graphics/text/index.html
mod builder;
mod height_mode;
mod vertical_overdraw;
use core::convert::Infallible;
use crate::{
alignment::{HorizontalAlignment, VerticalAlignment},
parser::Parser,
plugin::{NoPlugin, PluginMarker as Plugin, PluginWrapper, ProcessingState},
rendering::{
cursor::LineCursor,
line_iter::{ElementHandler, LineElementParser, LineEndType},
space_config::SpaceConfig,
},
utils::str_width,
};
use az::SaturatingAs;
use embedded_graphics::{
pixelcolor::Rgb888,
text::{renderer::TextRenderer, LineHeight},
};
pub use self::{
builder::TextBoxStyleBuilder, height_mode::HeightMode, vertical_overdraw::VerticalOverdraw,
};
/// Tab size helper
///
/// This type makes it more obvious what unit is used to define the width of tabs.
/// The default tab size is 4 spaces.
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum TabSize {
/// Tab width as a number of pixels.
Pixels(u16),
/// Tab width as a number of space characters.
Spaces(u16),
}
impl TabSize {
/// Returns the default tab size, which is 4 spaces.
#[inline]
pub const fn default() -> Self {
Self::Spaces(4)
}
/// Calculate the rendered with of the next tab
#[inline]
pub(crate) fn into_pixels(self, renderer: &impl TextRenderer) -> u32 {
match self {
TabSize::Pixels(px) => px as u32,
TabSize::Spaces(n) => n as u32 * str_width(renderer, " "),
}
}
}
/// Styling options of a [`TextBox`].
///
/// `TextBoxStyle` contains the font, foreground and background `PixelColor`, line spacing,
/// [`HeightMode`], [`HorizontalAlignment`] and [`VerticalAlignment`] information necessary
/// to draw a [`TextBox`].
///
/// To construct a new `TextBoxStyle` object, use the [`TextBoxStyle::default`] method or
/// the [`TextBoxStyleBuilder`] object.
///
/// [`TextBox`]: crate::TextBox
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
#[non_exhaustive]
#[must_use]
pub struct TextBoxStyle {
/// Horizontal text alignment.
pub alignment: HorizontalAlignment,
/// Vertical text alignment.
pub vertical_alignment: VerticalAlignment,
/// The height behaviour.
pub height_mode: HeightMode,
/// Line height.
pub line_height: LineHeight,
/// Paragraph spacing.
pub paragraph_spacing: u32,
/// Desired column width for tabs
pub tab_size: TabSize,
/// True to render leading spaces
pub leading_spaces: bool,
/// True to render trailing spaces
pub trailing_spaces: bool,
}
impl TextBoxStyle {
/// Creates a new text box style object with default settings.
#[inline]
pub const fn default() -> Self {
TextBoxStyleBuilder::new().build()
}
/// Creates a new text box style with the given alignment.
#[inline]
pub const fn with_alignment(alignment: HorizontalAlignment) -> TextBoxStyle {
TextBoxStyleBuilder::new().alignment(alignment).build()
}
/// Creates a new text box style with the given vertical alignment.
#[inline]
pub const fn with_vertical_alignment(alignment: VerticalAlignment) -> TextBoxStyle {
TextBoxStyleBuilder::new()
.vertical_alignment(alignment)
.build()
}
/// Creates a new text box style with the given [height mode].
///
/// [height mode]: HeightMode
#[inline]
pub const fn with_height_mode(mode: HeightMode) -> TextBoxStyle {
TextBoxStyleBuilder::new().height_mode(mode).build()
}
/// Creates a new text box style with the given line height.
#[inline]
pub const fn with_line_height(line_height: LineHeight) -> TextBoxStyle {
TextBoxStyleBuilder::new().line_height(line_height).build()
}
/// Creates a new text box style with the given paragraph spacing.
#[inline]
pub const fn with_paragraph_spacing(spacing: u32) -> TextBoxStyle {
TextBoxStyleBuilder::new()
.paragraph_spacing(spacing)
.build()
}
/// Creates a new text box style with the given tab size.
#[inline]
pub const fn with_tab_size(tab_size: TabSize) -> TextBoxStyle {
TextBoxStyleBuilder::new().tab_size(tab_size).build()
}
}
/// Information about a line.
#[derive(Debug, Copy, Clone)]
#[must_use]
pub(crate) struct LineMeasurement {
/// Maximum line width in pixels.
pub max_line_width: u32,
/// Width in pixels, using the default space width returned by the text renderer.
pub width: u32,
/// What kind of line ending was encountered.
pub line_end_type: LineEndType,
/// Number of spaces in the current line.
pub space_count: u32,
}
impl LineMeasurement {
pub fn last_line(&self) -> bool {
matches!(
self.line_end_type,
LineEndType::NewLine | LineEndType::EndOfText
)
}
pub fn is_empty(&self) -> bool {
self.width == 0
}
}
struct MeasureLineElementHandler<'a, S> {
style: &'a S,
trailing_spaces: bool,
max_line_width: u32,
cursor: u32,
pos: u32,
right: u32,
partial_space_count: u32,
space_count: u32,
}
impl<'a, S> MeasureLineElementHandler<'a, S> {
fn space_count(&self) -> u32 {
if self.trailing_spaces {
self.partial_space_count
} else {
self.space_count
}
}
fn right(&self) -> u32 {
if self.trailing_spaces {
self.pos
} else {
self.right
}
}
}
impl<'a, S: TextRenderer> ElementHandler for MeasureLineElementHandler<'a, S> {
type Error = Infallible;
type Color = S::Color;
fn measure(&self, st: &str) -> u32 {
str_width(self.style, st)
}
fn whitespace(&mut self, _st: &str, count: u32, width: u32) -> Result<(), Self::Error> {
self.cursor += width;
self.pos = self.pos.max(self.cursor);
self.partial_space_count += count;
Ok(())
}
fn printed_characters(&mut self, str: &str, width: Option<u32>) -> Result<(), Self::Error> {
self.cursor += width.unwrap_or_else(|| self.measure(str));
self.pos = self.pos.max(self.cursor);
self.right = self.pos;
self.space_count = self.partial_space_count;
Ok(())
}
fn move_cursor(&mut self, by: i32) -> Result<(), Self::Error> {
self.cursor = (self.cursor.saturating_as::<i32>() + by)
.clamp(0, self.max_line_width.saturating_as()) as u32;
Ok(())
}
}
impl TextBoxStyle {
/// Measure the width and count spaces in a single line of text.
///
/// Returns (width, rendered space count, carried token)
///
/// Instead of peeking ahead when processing tokens, this function advances the parser before
/// processing a token. If a token opens a new line, it will be returned as the carried token.
/// If the carried token is `None`, the parser has finished processing the text.
#[inline]
pub(crate) fn measure_line<'a, S, M>(
&self,
plugin: &PluginWrapper<'a, M, S::Color>,
character_style: &S,
parser: &mut Parser<'a, S::Color>,
max_line_width: u32,
) -> LineMeasurement
where
S: TextRenderer,
M: Plugin<'a, S::Color>,
S::Color: From<Rgb888>,
{
let cursor = LineCursor::new(max_line_width, self.tab_size.into_pixels(character_style));
let mut iter = LineElementParser::new(
parser,
plugin,
cursor,
SpaceConfig::new(str_width(character_style, " "), None),
self,
);
let mut handler = MeasureLineElementHandler {
style: character_style,
trailing_spaces: self.trailing_spaces,
max_line_width,
cursor: 0,
pos: 0,
right: 0,
partial_space_count: 0,
space_count: 0,
};
let last_token = iter.process(&mut handler).unwrap();
LineMeasurement {
max_line_width,
width: handler.right(),
space_count: handler.space_count(),
line_end_type: last_token,
}
}
/// Measures text height when rendered using a given width.
///
/// # Example: measure height of text when rendered using a 6x9 MonoFont and 72px width.
///
/// ```rust
/// # use embedded_text::style::TextBoxStyleBuilder;
/// # use embedded_graphics::{
/// # mono_font::{ascii::FONT_6X9, MonoTextStyleBuilder},
/// # pixelcolor::BinaryColor,
/// # };
/// #
/// let character_style = MonoTextStyleBuilder::new()
/// .font(&FONT_6X9)
/// .text_color(BinaryColor::On)
/// .build();
/// let style = TextBoxStyleBuilder::new().build();
///
/// let height = style.measure_text_height(
/// &character_style,
/// "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
/// 72,
/// );
///
/// // Expect 7 lines of text, wrapped in something like the following:
///
/// // |Lorem Ipsum |
/// // |is simply |
/// // |dummy text |
/// // |of the |
/// // |printing and|
/// // |typesetting |
/// // |industry. |
///
/// assert_eq!(7 * 9, height);
/// ```
#[inline]
#[must_use]
pub fn measure_text_height<S>(&self, character_style: &S, text: &str, max_width: u32) -> u32
where
S: TextRenderer,
S::Color: From<Rgb888>,
{
let plugin = PluginWrapper::new(NoPlugin::new());
self.measure_text_height_impl(plugin, character_style, text, max_width)
}
pub(crate) fn measure_text_height_impl<'a, S, M>(
&self,
plugin: PluginWrapper<'a, M, S::Color>,
character_style: &S,
text: &'a str,
max_width: u32,
) -> u32
where
S: TextRenderer,
M: Plugin<'a, S::Color>,
S::Color: From<Rgb888>,
{
let mut parser = Parser::parse(text);
let base_line_height = character_style.line_height();
let line_height = self.line_height.to_absolute(base_line_height);
let mut height = base_line_height;
plugin.set_state(ProcessingState::Measure);
let mut prev_end = LineEndType::EndOfText;
loop {
plugin.new_line();
let lm = self.measure_line(&plugin, character_style, &mut parser, max_width);
if prev_end == LineEndType::LineBreak && !lm.is_empty() {
height += line_height;
}
match lm.line_end_type {
LineEndType::CarriageReturn | LineEndType::LineBreak => {}
LineEndType::NewLine => height += line_height + self.paragraph_spacing,
LineEndType::EndOfText => return height,
}
prev_end = lm.line_end_type;
}
}
}
#[cfg(test)]
mod test {
use crate::{
alignment::*,
parser::Parser,
plugin::{NoPlugin, PluginWrapper},
style::{builder::TextBoxStyleBuilder, TextBoxStyle},
};
use embedded_graphics::{
mono_font::{ascii::FONT_6X9, MonoTextStyleBuilder},
pixelcolor::BinaryColor,
text::{renderer::TextRenderer, LineHeight},
};
#[test]
fn no_infinite_loop() {
let character_style = MonoTextStyleBuilder::new()
.font(&FONT_6X9)
.text_color(BinaryColor::On)
.build();
let _ = TextBoxStyleBuilder::new()
.build()
.measure_text_height(&character_style, "a", 5);
}
#[test]
fn test_measure_height() {
let data = [
// (text; max width in characters; number of expected lines)
("", 0, 1),
(" ", 6, 1),
("\r", 6, 1),
("\n", 6, 2),
("\n ", 6, 2),
("word", 4 * 6, 1), // exact fit into 1 line
("word\n", 4 * 6, 2), // newline
("word", 4 * 6 - 1, 2),
("word", 2 * 6, 2), // exact fit into 2 lines
("word word", 4 * 6, 2), // exact fit into 2 lines
("word\n", 2 * 6, 3),
("word\nnext", 50, 2),
("word\n\nnext", 50, 3),
("word\n \nnext", 50, 3),
("verylongword", 50, 2),
("some verylongword", 50, 3),
("1 23456 12345 61234 561", 36, 5),
(" Word ", 36, 2),
("\rcr", 36, 1),
("cr\r", 36, 1),
("cr\rcr", 36, 1),
("Longer\r", 36, 1),
("Longer\rnowrap", 36, 1),
];
let character_style = MonoTextStyleBuilder::new()
.font(&FONT_6X9)
.text_color(BinaryColor::On)
.build();
let style = TextBoxStyle::with_paragraph_spacing(2);
for (i, (text, width, expected_n_lines)) in data.iter().enumerate() {
let height = style.measure_text_height(&character_style, text, *width);
let expected_height = *expected_n_lines * character_style.line_height()
+ (text.chars().filter(|&c| c == '\n').count() as u32) * style.paragraph_spacing;
assert_eq!(
height,
expected_height,
r#"#{}: Height of {:?} is {} but is expected to be {}"#,
i,
text.replace('\r', "\\r").replace('\n', "\\n"),
height,
expected_height
);
}
}
#[test]
fn test_measure_height_ignored_spaces() {
let data = [
("", 0, 1),
(" ", 0, 1),
(" ", 6, 1),
("\n ", 6, 2),
("word\n \nnext", 50, 3),
(" Word ", 36, 1),
];
let character_style = MonoTextStyleBuilder::new()
.font(&FONT_6X9)
.text_color(BinaryColor::On)
.build();
let style = TextBoxStyleBuilder::new()
.alignment(HorizontalAlignment::Center)
.build();
for (i, (text, width, expected_n_lines)) in data.iter().enumerate() {
let height = style.measure_text_height(&character_style, text, *width);
let expected_height = *expected_n_lines * character_style.line_height();
assert_eq!(
height, expected_height,
r#"#{}: Height of "{}" is {} but is expected to be {}"#,
i, text, height, expected_height
);
}
}
#[test]
fn test_measure_line() {
let character_style = MonoTextStyleBuilder::new()
.font(&FONT_6X9)
.text_color(BinaryColor::On)
.build();
let style = TextBoxStyleBuilder::new()
.alignment(HorizontalAlignment::Center)
.build();
let mut text = Parser::parse("123 45 67");
let mut plugin = PluginWrapper::new(NoPlugin::new());
let lm = style.measure_line(
&mut plugin,
&character_style,
&mut text,
6 * FONT_6X9.character_size.width,
);
assert_eq!(lm.width, 6 * FONT_6X9.character_size.width);
}
#[test]
fn test_measure_line_counts_nbsp() {
let character_style = MonoTextStyleBuilder::new()
.font(&FONT_6X9)
.text_color(BinaryColor::On)
.build();
let style = TextBoxStyleBuilder::new()
.alignment(HorizontalAlignment::Center)
.build();
let mut text = Parser::parse("123\u{A0}45");
let mut plugin = PluginWrapper::new(NoPlugin::new());
let lm = style.measure_line(
&mut plugin,
&character_style,
&mut text,
5 * FONT_6X9.character_size.width,
);
assert_eq!(lm.width, 5 * FONT_6X9.character_size.width);
}
#[test]
fn test_measure_height_nbsp() {
let character_style = MonoTextStyleBuilder::new()
.font(&FONT_6X9)
.text_color(BinaryColor::On)
.build();
let style = TextBoxStyleBuilder::new()
.alignment(HorizontalAlignment::Center)
.build();
let text = "123\u{A0}45 123";
let height =
style.measure_text_height(&character_style, text, 5 * FONT_6X9.character_size.width);
assert_eq!(height, 2 * character_style.line_height());
// bug discovered while using the interactive example
let style = TextBoxStyleBuilder::new()
.alignment(HorizontalAlignment::Left)
.build();
let text = "embedded-text also\u{A0}supports non-breaking spaces.";
let height = style.measure_text_height(&character_style, text, 79);
assert_eq!(height, 4 * character_style.line_height());
}
#[test]
fn height_with_line_spacing() {
let character_style = MonoTextStyleBuilder::new()
.font(&FONT_6X9)
.text_color(BinaryColor::On)
.build();
let style = TextBoxStyleBuilder::new()
.line_height(LineHeight::Pixels(11))
.build();
let height = style.measure_text_height(
&character_style,
"Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
72,
);
assert_eq!(height, 6 * 11 + 9);
}
#[test]
fn soft_hyphenated_line_width_includes_hyphen_width() {
let character_style = MonoTextStyleBuilder::new()
.font(&FONT_6X9)
.text_color(BinaryColor::On)
.build();
let style = TextBoxStyleBuilder::new()
.line_height(LineHeight::Pixels(11))
.build();
let mut plugin = PluginWrapper::new(NoPlugin::new());
let lm = style.measure_line(
&mut plugin,
&character_style,
&mut Parser::parse("soft\u{AD}hyphen"),
50,
);
assert_eq!(lm.width, 30);
}
}