about summary refs log tree commit diff
path: root/src/x/text/line.rs
blob: 5f0274269e5df2b1661a8b874d37eac0ac4707ef (plain)
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
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;

use async_lock::Mutex;


pub struct Line {
  fonts: Arc<Mutex<FontList>>,
  spans: Vec<Span>,
}


impl Line {
  pub fn new(fonts: Arc<Mutex<FontList>>) -> Result<Line> {
    let spans = Vec::new();

    Ok(Line { fonts, spans })
  }

  pub fn append_text(&mut self, text: &str) -> Result<()> {
    let mut current_span_font: Option<Arc<Font>> = None;
    let mut current_span_text = String::new();

    for char in text.chars() {
      let codepoint = char as u32;

      let new_font = &self.fonts.lock_blocking().find_codepoint(codepoint)?;
      if let Some(old_font) = &current_span_font {
        if old_font != new_font {
          let span = old_font.text_span(&current_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(&current_span_text)?;
      self.spans.push(span);
    }

    Ok(())
  }

  pub fn spans(&self) -> impl Iterator<Item=&Span> + 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::<i32>::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(())
  }
}