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
use std::collections::HashMap;
use std::convert::{Into, AsRef};

use super::types::Float;

use vecmath;
use font_atlas;

pub use font_atlas::OutputPosition;

use super::accessors::{HasDisplay, HasFontCache};
use super::color::Color;
use super::error::{LuxError, LuxResult};
use super::raw::{Colored, Transform};
use super::canvas::Canvas;
use super::sprite::{Sprite, IntoSprite};

pub struct FontCache {
    rendered: HashMap<(String, u16), font_atlas::RenderedFont<Sprite>>,
    current: Option<(String, u16)>
}

/// A context that contains information about the text that can be drawn to the screen.
#[must_use = "text references just contains a drawing context, and must be drawn with `draw()`"]
pub struct ContainedText<'a, C: 'a + HasDisplay + HasFontCache + Canvas, S: 'a + AsRef<str>> {
    canvas: &'a mut C,
    text: S,
    pos: (Float, Float),
    transform: [[Float; 4]; 4],
    color: [Float; 4],

    size: u16,
    font_family: String

}

/// Any struct that implements `TextDraw` can draw text to it.
///
/// The only known implementation of `TextDraw` is Frame.
pub trait TextDraw: TextLoad + Canvas {
    /// Starts drawing some text at a position.
    ///
    /// Text size and text font can be configured on the returned `ContainedText`
    /// object and finally drawn to the canvas with `.draw()`.
    fn text<'a, S: 'a + AsRef<str>>(&'a mut self, text: S, x: Float, y: Float) -> ContainedText<'a, Self, S> {
        let (font_fam, size) = self.font_cache().current.clone().unwrap_or_else(|| ("SourceCodePro".to_string(), 20));

        ContainedText {
            canvas: self,
            text: text,
            pos: (x, y),
            size: size,
            font_family: font_fam,
            transform: vecmath::mat4_id(),
            color: [0.0, 0.0, 0.0, 1.0]
        }
    }

}

/// Any struct that implements TextLoad can have fonts atlases added
/// to an internal cache.
///
/// Fonts must be loaded before they can be drawn with `TextDraw`.
pub trait TextLoad: Sized + HasDisplay + HasFontCache {
    /// Adds a rendered font to the font cache.
    fn cache<F: IntoSprite>(&mut self, name: &str, size: u16, rendered: font_atlas::RenderedFont<F>) -> LuxResult<()> {
        let rendered = rendered.map(|i| i.into_sprite(self.borrow_display()))
                               .reskin();
        self.font_cache().cache(name, size, try!(rendered));
        Ok(())
    }

    /// Removes a rendered font from the cache.
    fn clear(&mut self, name: &str, size: u16) {
        self.font_cache().clear(name, size);
    }

    /// Sets a font as the current font.
    fn use_font(&mut self, name: &str, size: u16) -> LuxResult<()> {
        self.font_cache().use_font(name, size).map(|_| ())
    }

}

impl <T> TextLoad for T where T: Sized + HasDisplay + HasFontCache { }
impl <T> TextDraw for T where T: TextLoad + Canvas {  }

impl <'a, C: 'a + HasDisplay + HasFontCache + Canvas, S: 'a + AsRef<str>> ContainedText<'a, C, S> {
    /// Sets the size of the font.
    pub fn size(&mut self, size: u16) -> &mut ContainedText<'a, C, S> {
        self.size = size;
        self
    }

    /// Sets the font to be used.
    pub fn font<A: Into<String>>(&mut self, font_family: A) -> &mut ContainedText<'a, C, S> {
        self.font_family = font_family.into();
        self
    }

    /// Draws the font to the screen.
    pub fn draw(&mut self) -> LuxResult<()> {
        let canvas: &mut C = {
            let x: &mut C = self.canvas;
            unsafe { ::std::mem::transmute(x) }
        };
        let positions = try!(self.absolute_positions());

        let mut fc = self.canvas.font_cache();
        let rendered = try!(fc.use_font(self.font_family.as_ref(), self.size));

        for OutputPosition{c: _, screen_pos: (x, y), char_info} in positions {
            let subsprite = rendered.image().sub_sprite(char_info.image_position,
                                                char_info.image_size);
            if let Some(sp) = subsprite.as_ref() {
                canvas.sprite(
                    sp,
                    x as Float + self.pos.0,
                    y as Float + self.pos.1).color(self.color).draw();
            }
        }
        Ok(())
    }

    /// Returns the height of one line of text with the selected font.
    pub fn line_height(&mut self) -> LuxResult<u32> {
        let mut fc = self.canvas.font_cache();
        let rendered = try!(fc.use_font(self.font_family.as_ref(), self.size));
        Ok(rendered.line_height())
    }

    /// Returns the maximum horizontal distance that a character can move the pen
    /// while drawing.
    pub fn max_advance(&mut self) -> LuxResult<u32> {
        let mut fc = self.canvas.font_cache();
        let rendered = try!(fc.use_font(self.font_family.as_ref(), self.size));
        Ok(rendered.max_width())
    }

    /// Returns an iterator containing each character in the input text along
    /// with the position and the size.
    ///
    /// These positions are absolute, and are not relative to the position that
    /// the text will be drawn on the screen. (they start at position (0, 0))
    pub fn absolute_positions(&mut self) -> LuxResult<Vec<OutputPosition>> {
        let mut fc = self.canvas.font_cache();
        let rendered = try!(fc.use_font(self.font_family.as_ref(), self.size));
        Ok(rendered.positions_for(self.text.as_ref()))
    }

    /// Returns an iterator containing each character in the input text along
    /// with the position and the size.
    ///
    /// These positions are relative to the providex (x, y) coordinates that
    /// the text will be drawn at.
    pub fn positions(&mut self) -> LuxResult<Vec<(char, (Float, Float), (Float, Float))>> {
        self.absolute_positions().map(|poses| {
            poses.into_iter().map(
                |OutputPosition{c, screen_pos: (px, py), char_info}|
                    (c,
                    (px as Float + self.pos.0, py as Float + self.pos.1),
                    (char_info.advance.0 as Float, char_info.advance.1 as Float))
              ).collect()
        })
    }

    /// Returns the bounding box around this text.
    ///
    /// `((start_x, start_y), (width, height))`
    ///
    /// `start_x` and `start_y` are oriented to the top-left of the screen.
    ///
    /// `width` and `height` are pointing down and to the right.
    pub fn bounding_box(&mut self) -> LuxResult<((Float, Float), (Float, Float))> {
        let start = self.pos;
        let end = try!(self.positions())
                  .pop()
                  .map(|(_, (px, py), (sx, sy))| (px + sx, py + sy))
                  .unwrap_or(start);
        Ok((start, end))
    }

    /// Returns the length in pixels of the rendered string.
    pub fn get_length(&mut self) -> LuxResult<u32> {
        self.positions().map(|mut positions| {
            positions.pop().map(|(_, (x, _), (w, _))| (x + w) as u32)
                     .unwrap_or(0)
        })
    }
}

impl <'a, A, B: AsRef<str>> Transform for ContainedText<'a, A, B>
where A: HasDisplay + HasFontCache + Canvas {
    fn current_matrix(&self) -> &[[Float; 4]; 4] {
        &self.transform
    }

    fn current_matrix_mut(&mut self) -> &mut [[Float; 4]; 4] {
        &mut self.transform
    }
}

impl <'a, A, B: AsRef<str>> Colored for ContainedText<'a, A, B>
where A: HasDisplay + HasFontCache + Canvas {
    fn get_color(&self) -> [Float; 4] {
        self.color
    }

    fn color<C: Color>(&mut self, color: C) -> &mut Self {
        self.color = color.to_rgba();
        self
    }
}

impl FontCache {
    pub fn new() -> LuxResult<FontCache> {
        let fc = FontCache {
            rendered: HashMap::new(),
            current: None
        };
        Ok(fc)
    }

    fn cache(&mut self, name: &str, size: u16, rendered: font_atlas::RenderedFont<Sprite>) {
        self.rendered.insert((name.to_string(), size), rendered);
    }
    fn clear(&mut self, name: &str, size: u16) {
        self.rendered.remove(&(name.to_string(), size));
    }

    fn use_font<'a>(&'a mut self, name: &str, size: u16) -> LuxResult<&'a font_atlas::RenderedFont<Sprite>> {
        let tup = (name.to_string(), size);
        let res = self.rendered.get(&tup).ok_or_else(|| LuxError::FontNotLoaded(name.to_string()));
        self.current = Some(tup);
        res
    }
}