-
Notifications
You must be signed in to change notification settings - Fork 13
/
terminal.rs
280 lines (255 loc) · 11.5 KB
/
terminal.rs
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
//! Terminal rendering APIs
//!
//! Some simple APIs to handle CLIs.
//!
//! Currently only handles printing, but will eventually support reading as well.
use alloc::prelude::*;
use font_rs::{font, font::{Font, GlyphBitmap}};
use hashmap_core::HashMap;
use window::{Window, Color};
use error::Error;
/// Just an x and a y
#[derive(Copy, Clone, Debug)]
struct Pos {
x: usize,
y: usize,
}
/// A struct for logging text to the window.
/// Renders characters from a .ttf font using the font-rs crate
pub struct Terminal {
framebuffer: Window,
cursor_pos: Pos, /* Cursor pos, in pixels. Does not account for bpp.
Reprensents the pen position on the baseline. */
font: Font<'static>,
cached_glyphs: HashMap<char, GlyphBitmap>, /* We cache ascii glyphs
to avoid rendering them every time */
advance_width: usize, /* Expected to be the same for every glyph since
it should be a monospaced font */
linespace: usize, /* The distance between two baselines */
ascent: usize, /* The maximum ascent in the font. */
descent: usize, /* The maximum descent in the font. */
}
/// The font we choose to render in
static FONT: &'static [u8] = include_bytes!("../fonts/Monaco.ttf");
/// The size we choose to render in
const FONT_SIZE: u32 = 10;
/// Window creation requested size.
pub enum WindowSize {
/// Takes the full screen.
Fullscreen,
/// Takes a given amount of lines.
///
/// The boolean controls whether we draw from the top or the bottom.
///
/// If the amount of lines is negative, then the window will take the whole
/// screen size, minus the given amount of lines.
FontLines(i32, bool),
/// Manually position the window at the given x/y, with a given width and
/// height.
Manual(i32, i32, u32, u32)
}
impl Terminal {
/// Creates a new Window of the requested size for terminal usage.
pub fn new(size: WindowSize) -> Result<Self, Error> {
let my_font = font::parse(FONT)
.expect("Failed parsing provided font");
let my_ascent = my_font.max_ascent(FONT_SIZE).unwrap() as usize;
let my_descent = -my_font.max_descent(FONT_SIZE).unwrap() as usize;
let my_advance_width = my_font.max_advance_width(FONT_SIZE).unwrap() as usize;
let my_linespace = my_descent + my_ascent;
// TODO: Terminal - Get window size from vi
// BODY: Terminal defines a fullscreen size as 1280 * 800, but should
// BODY: really get it from vi instead.
let framebuffer = match size {
WindowSize::Fullscreen => Window::new(0, 0, 1280, 800)?,
WindowSize::FontLines(lines, is_bottom) => {
let height = if lines < 0 {
let max_lines = 800 / my_linespace;
my_linespace * ((max_lines as i32) + lines) as usize
} else if lines == 1 {
// Orycterope's fault. Scrolling expects at least one line
// available above it.
(my_linespace + 1) as usize
} else {
my_linespace * lines as usize
};
let top = if is_bottom {
800 - height
} else {
0
};
Window::new(top as i32, 0, 1280, height as u32)?
}
WindowSize::Manual(top, left, width, height) => Window::new(0, 0, width, height)?
};
Ok(Terminal {
framebuffer,
font: my_font,
cached_glyphs: HashMap::with_capacity(128), // the ascii table
advance_width: my_advance_width,
linespace: my_linespace,
ascent: my_ascent,
descent: my_descent,
cursor_pos: Pos { x: 0, y: my_ascent },
})
}
pub fn draw(&mut self) -> Result<(), Error> {
self.framebuffer.draw()
}
#[inline]
fn carriage_return(&mut self) {
self.cursor_pos.x = 0;
}
#[inline]
fn line_feed(&mut self) {
let _ = self.draw();
// Are we already on the last line ?
if self.cursor_pos.y + self.linespace + self.descent >= self.framebuffer.height() {
self.scroll_screen();
} else {
self.cursor_pos.y += self.linespace;
}
self.carriage_return();
}
#[inline]
fn advance_pos(&mut self) {
self.cursor_pos.x += self.advance_width;
// is next displayed char going to be cut out of screen ?
if self.cursor_pos.x + self.advance_width >= self.framebuffer.width() {
self.line_feed();
}
}
fn move_pos_back(&mut self) {
if self.cursor_pos.x >= self.advance_width {
self.cursor_pos.x -= self.advance_width;
}
}
#[inline]
/// scrolls the whole screen by one line.
/// self.pos must be on last baseline.
fn scroll_screen(&mut self) {
let linespace_size_in_framebuffer = self.framebuffer.get_px_offset(0, self.linespace);
let lastline_top_left_corner = self.framebuffer.get_px_offset(0, self.cursor_pos.y - self.ascent);
// Copy up from the line under it
assert!(lastline_top_left_corner + linespace_size_in_framebuffer < self.framebuffer.get_buffer().len(), "Window is drunk: {} + {} < {}", lastline_top_left_corner, linespace_size_in_framebuffer, self.framebuffer.get_buffer().len());
unsafe {
// memmove in the same slice. Should be safe with the assert above.
::core::ptr::copy(self.framebuffer.get_buffer().as_ptr().offset(linespace_size_in_framebuffer as isize),
self.framebuffer.get_buffer().as_mut_ptr(),
lastline_top_left_corner);
}
// Erase last line
unsafe {
// memset to 0x00. Should be safe with the assert above
::core::ptr::write_bytes(self.framebuffer.get_buffer().as_mut_ptr().offset(lastline_top_left_corner as isize),
0x00,
self.framebuffer.get_buffer().len() - lastline_top_left_corner);
}
}
/// Clears the whole screen and reset cursor
fn clear(&mut self) {
self.framebuffer.clear();
self.cursor_pos = Pos { x: 0, y: self.ascent };
}
/// Prints a string to the screen with attributes
fn print_attr(&mut self, string: &str, fg: Color, bg: Color) {
for mychar in string.chars() {
match mychar {
'\n' => { self.line_feed(); }
'\x08' => {
self.move_pos_back();
let empty_glyph = GlyphBitmap { width: 0, height: 0, top: 0, left: 0, data: Vec::new() };
Self::display_glyph_in_box(&empty_glyph, &mut self.framebuffer,
self.advance_width, self.ascent, self.descent,
&fg, &bg, self.cursor_pos);
}
mychar => {
{
let Terminal {
cached_glyphs, font, advance_width, ascent, descent, cursor_pos, ..
} = self;
// Try to get the rendered char from the cache
if (mychar as u64) < 128 {
// It's ascii, so if it's not already in the cache, add it !
let glyph = cached_glyphs.entry(mychar)
.or_insert_with(|| {
font.lookup_glyph_id(mychar as u32)
.and_then(|glyphid| font.render_glyph(glyphid, FONT_SIZE))
.unwrap_or(GlyphBitmap { width: 0, height: 0, top: 0, left: 0, data: Vec::new() })
});
Self::display_glyph_in_box(glyph, &mut self.framebuffer,
*advance_width, *ascent, *descent,
&fg, &bg, *cursor_pos);
} else {
// Simply render the glyph and display it ...
let glyph = font.lookup_glyph_id(mychar as u32)
.and_then(|glyphid| font.render_glyph(glyphid, FONT_SIZE))
.unwrap_or(GlyphBitmap { width: 0, height: 0, top: 0, left: 0, data: Vec::new() });
Self::display_glyph_in_box(&glyph, &mut self.framebuffer,
*advance_width, *ascent, *descent,
&fg, &bg, *cursor_pos);
}
}
self.advance_pos();
}
}
}
}
/// Copies a rendered character to the screen, displaying it in a bg colored box
///
/// # Panics
///
/// Panics if pos makes writing the glyph overflow the screen
fn display_glyph_in_box(glyph: &GlyphBitmap, framebuffer: &mut Window,
box_width: usize, box_ascent: usize, box_descent: usize,
fg: &Color, bg: &Color, pos: Pos) {
/// Blends foreground and background subpixels together
/// by doing a weighted average of fg and bg
#[inline]
fn blend_subpixels(fg: u8, bg: u8, fg_alpha: u8) -> u8 {
// compute everything u16 to avoid overflows
(( fg as u16 * fg_alpha as u16
+ bg as u16 * (0xFF - fg_alpha) as u16
) / 0xFF // the weight should be (fg_alpha / 0xFF), but we move this division
// as final step so we don't loose precision
) as u8
}
/* The GlyphBitmap represents a small box, that fits inside an imaginary
bigger box, that we want to color */
// The bigger box
for y in -(box_ascent as i32)..=(box_descent as i32) {
for x in 0..(box_width as i32) {
// translate x,y as glyph coordinates
let glyphx: i32 = x - glyph.left;
let glyphy: i32 = y - glyph.top;
// compute the color to display
let to_display =
if glyphx >= 0 && glyphy >= 0
&& glyphx < (glyph.width as i32) && glyphy < (glyph.height as i32) {
// it's inside the glyph box !
// blend foreground and background colors according to intensity
let glyph_alpha = glyph.data[glyphy as usize * glyph.width + glyphx as usize];
Color::rgb(
blend_subpixels(fg.r, bg.r, glyph_alpha),
blend_subpixels(fg.g, bg.g, glyph_alpha),
blend_subpixels(fg.b, bg.b, glyph_alpha),
)
} else {
// it's oustide the glyph box, just paint it bg color
*bg
};
framebuffer.write_px_at((pos.x as i32 + x) as usize,
(pos.y as i32 + y) as usize,
&to_display);
}
}
}
}
impl ::core::fmt::Write for Terminal {
fn write_str(&mut self, s: &str) -> Result<(), ::core::fmt::Error> {
let fg = Color::rgb(255, 255, 255);
let bg = Color::rgb(0, 0, 0);
self.print_attr(s, fg, bg);
Ok(())
}
}