From b7319af1ed9e5dc3c29d05d6f5de9f325fa64191 Mon Sep 17 00:00:00 2001 From: Irene Knapp Date: Sun, 22 Nov 2026 23:18:13 -0700 Subject: new subdirectory src/x/text/ Force-Push: yes Change-Id: I1c428e1f7b42de263534965422dffe007300082c --- src/x/text/line.rs | 96 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 src/x/text/line.rs (limited to 'src/x/text/line.rs') diff --git a/src/x/text/line.rs b/src/x/text/line.rs new file mode 100644 index 0000000..5e328ed --- /dev/null +++ b/src/x/text/line.rs @@ -0,0 +1,96 @@ +use crate::error::Result; +use crate::geometry::{ Alignment, Point }; +use crate::layout::Parcel; +use crate::x::Color; +use crate::x::text::{ Font, FontGraphicContext, FontList, Span }; + +use std::sync::{ Arc, Mutex }; + + +pub struct Line { + fonts: Arc>, + spans: Vec, +} + + +impl Line { + pub fn new(fonts: Arc>) -> Result { + let spans = Vec::new(); + + Ok(Line { fonts, spans }) + } + + pub fn append_text(&mut self, text: &str) -> Result<()> { + let mut current_span_font: Option> = None; + let mut current_span_text = String::new(); + + for char in text.chars() { + let codepoint = char as u32; + + let new_font = &self.fonts.lock()?.find_codepoint(codepoint)?; + if let Some(old_font) = ¤t_span_font { + if old_font != new_font { + let span = old_font.text_span(¤t_span_text)?; + self.spans.push(span); + + current_span_font = Some(Arc::clone(new_font)); + current_span_text = String::new(); + } + } else { + current_span_font = Some(Arc::clone(new_font)); + } + + current_span_text.push(char); + } + + if let Some(font) = current_span_font + && !current_span_text.is_empty() + { + let span = font.text_span(¤t_span_text)?; + self.spans.push(span); + } + + Ok(()) + } + + pub fn spans(&self) -> impl Iterator + DoubleEndedIterator { + self.spans.iter() + } + + pub fn layout_and_draw(&self, open_parcel: &mut Parcel, + alignment: Alignment, context: &FontGraphicContext, + color: &Color, baseline_position: i16) + -> Result<()> + { + let mut location = Point::::zero(); + location.y += baseline_position as i32; + + match alignment { + Alignment::Left => { + location.x += open_parcel.left as i32; + } + Alignment::Right => { + location.x += open_parcel.right as i32; + } + } + + /* A reversed iterator is a different type, so we need two of this loop. */ + match alignment { + Alignment::Left => { + for span in self.spans() { + span.layout_and_draw(open_parcel, &mut location, + alignment, context, color)?; + } + } + Alignment::Right => { + for span in self.spans().rev() { + span.layout_and_draw(open_parcel, &mut location, + alignment, context, color)?; + } + } + } + + Ok(()) + } +} + -- cgit 1.4.1