Document WidthDB

This commit is contained in:
Joscha 2022-05-28 10:14:15 +02:00
parent 79e8813884
commit 833defd1ce
3 changed files with 17 additions and 0 deletions

View file

@ -1,3 +1,5 @@
//! Rendering the next frame.
use crossterm::style::ContentStyle; use crossterm::style::ContentStyle;
use crate::buffer::Buffer; use crate::buffer::Buffer;

View file

@ -1,3 +1,5 @@
//! Displaying frames on a terminal.
use std::io::Write; use std::io::Write;
use std::{io, mem}; use std::{io, mem};

View file

@ -8,6 +8,7 @@ use crossterm::QueueableCommand;
use unicode_segmentation::UnicodeSegmentation; use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr; use unicode_width::UnicodeWidthStr;
/// Measures and stores the with (in terminal coordinates) of graphemes.
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct WidthDB { pub struct WidthDB {
known: HashMap<String, u8>, known: HashMap<String, u8>,
@ -15,6 +16,10 @@ pub struct WidthDB {
} }
impl WidthDB { impl WidthDB {
/// Determine the width of a string based on its graphemes.
///
/// If the width of a grapheme has not been measured yet, it is estimated
/// using the Unicode Standard Annex #11.
pub fn width(&mut self, s: &str) -> u8 { pub fn width(&mut self, s: &str) -> u8 {
let mut total = 0; let mut total = 0;
for grapheme in s.graphemes(true) { for grapheme in s.graphemes(true) {
@ -28,10 +33,18 @@ impl WidthDB {
total total
} }
/// Whether any new graphemes have been seen since the last time
/// [`Self::measure_widths`] was called.
pub fn measuring_required(&self) -> bool { pub fn measuring_required(&self) -> bool {
!self.requested.is_empty() !self.requested.is_empty()
} }
/// Measure the width of all new graphemes that have been seen since the
/// last time this function was called.
///
/// This function measures the actual width of graphemes by writing them to
/// the terminal. After it finishes, the terminal's contents should be
/// assumed to be garbage and a full redraw should be performed.
pub fn measure_widths(&mut self, out: &mut impl Write) -> io::Result<()> { pub fn measure_widths(&mut self, out: &mut impl Write) -> io::Result<()> {
for grapheme in self.requested.drain() { for grapheme in self.requested.drain() {
out.queue(Clear(ClearType::All))? out.queue(Clear(ClearType::All))?