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
281
282
283
#![no_std]
#![warn(rust_2018_idioms, unreachable_pub)]
#![forbid(unsafe_code)]

/*!
This crate provides bitmap fonts for the `embedded-graphics` crate without requiring generics. All
fonts provided are concrete, constant instances of [`BitmapFont`]. This means you can use these
bitmap fonts without any generics, unlike those fonts shipped with `embedded-graphics` where each
font is implemented via its own struct. Also, this allows pixel-double fonts to share their bitmap
data with the non-doubled font, reducing the flash size required.

# Usage Example

```rust
use bitmap_font::{BitmapFont, WithFont, FONT_7x13};
use embedded_graphics::{fonts::Text, prelude::*};
# use embedded_graphics::{drawable::Pixel, geometry::Size, pixelcolor::BinaryColor};
# use core::convert::Infallible;
# struct Display;
# impl DrawTarget<BinaryColor> for Display {
#   type Error = Infallible;
#   fn draw_pixel(&mut self, pixel: Pixel<BinaryColor>) -> Result<(), Infallible> { Ok(()) }
#   fn size(&self) -> Size { unimplemented!() }
# }
# fn main() -> Result<(), Infallible> {
# let mut display = Display;

let font: BitmapFont = FONT_7x13;
let text = Text::new("Hello World!", Point::zero());
text.with_font(font, BinaryColor::On).draw(&mut display)?;
# Ok(())
# }
```
*/

use embedded_graphics::{
	drawable::{Drawable, Pixel},
	fonts::Text,
	geometry::{Dimensions, Point, Size},
	pixelcolor::BinaryColor,
	transform::Transform,
	DrawTarget
};

mod generated;
pub use generated::*;

/// Stores the font bitmap and some additional info for each font.
#[derive(Clone, Copy)]
pub struct BitmapFont {
	/// The raw bitmap data for the font.
	bitmap: &'static [u8],

	/// The width of the raw bitmap data.
	bitmap_width: u32,

	/// The width of each character in the raw bitmap data.
	width: u32,

	/// The height of each character in the raw bitmap data.
	height: u32,

	/// The amount of pixels to draw per each font pixel. Set to `2` for pixel-double font.
	pixels: u32
}

impl BitmapFont {
	/// Return the width of each character.
	pub const fn width(self) -> u32 {
		self.width * self.pixels
	}

	/// Return the height of each character.
	pub const fn height(self) -> u32 {
		self.height * self.pixels
	}

	/// Return the char offset in the raw bitmap data.
	fn char_offset(c: char) -> u32 {
		match c {
			' '..='~' => c as u32 - ' ' as u32,
			_ => '?' as u32 - ' ' as u32
		}
	}

	/// Returns `true` if the pixel `(x, y)` is turned on in the character `c`.
	// inspired by https://docs.rs/embedded-graphics/0.6.2/src/embedded_graphics/fonts/mod.rs.html#246
	pub fn pixel(self, c: char, x: u32, y: u32) -> bool {
		let x = x / self.pixels;
		let y = y / self.pixels;

		let char_per_row = self.bitmap_width / self.width;
		let offset = Self::char_offset(c);
		let row = offset / char_per_row;

		let char_x = (offset - (row * char_per_row)) * self.width;
		let char_y = row * self.height;

		let bitmap_bit_index = char_x + x + ((char_y + y) * self.bitmap_width);
		let bitmap_byte = bitmap_bit_index / 8;
		let bitmap_bit = 7 - (bitmap_bit_index % 8);

		self.bitmap[bitmap_byte as usize] & (1 << bitmap_bit) != 0
	}

	/// Returns a pixel-double version of this font.
	pub const fn pixel_double(mut self) -> Self {
		self.pixels *= 2;
		self
	}
}

mod private {
	use super::BitmapFont;
	use embedded_graphics::pixelcolor::BinaryColor;

	pub struct Styled<T> {
		pub(super) primitive: T,
		pub(super) font: BitmapFont,
		pub(super) color: BinaryColor
	}

	pub struct Sealed;
}
use private::*;

/// Style a [Text] with a font and color.
pub trait WithFont: Sized {
	#[doc(hidden)]
	const SEALED: Sealed;

	/// Style this text with a font and color.
	fn with_font(self, font: BitmapFont, color: BinaryColor) -> Styled<Self>;
}

impl WithFont for Text<'_> {
	#[doc(hidden)]
	const SEALED: Sealed = Sealed;

	fn with_font(self, font: BitmapFont, color: BinaryColor) -> Styled<Self> {
		Styled {
			primitive: self,
			font,
			color
		}
	}
}

impl Transform for Styled<Text<'_>> {
	fn translate(&self, by: Point) -> Self {
		Self {
			primitive: self.primitive.translate(by),
			font: self.font,
			color: self.color
		}
	}

	fn translate_mut(&mut self, by: Point) -> &mut Self {
		self.primitive.translate_mut(by);
		self
	}
}

impl Dimensions for Styled<Text<'_>> {
	fn top_left(&self) -> Point {
		self.primitive.position
	}

	fn bottom_right(&self) -> Point {
		self.top_left() + self.size()
	}

	// inspired by https://docs.rs/embedded-graphics/0.6.2/src/embedded_graphics/fonts/text.rs.html#118
	fn size(&self) -> Size {
		if self.primitive.text.is_empty() {
			return Size::zero();
		}

		let width = self
			.primitive
			.text
			.lines()
			.map(|l| l.len() as u32 * self.font.width())
			.max()
			.unwrap_or(0);
		let height = self.primitive.text.lines().count() as u32 * self.font.height();
		Size::new(width, height)
	}
}

struct PixelIterator<'a> {
	text: &'a str,
	idx: usize,
	font: BitmapFont,
	color: BinaryColor,

	top_left: Point,
	pos: Point,

	char_width: u32,
	char_walk_x: i32,
	char_walk_y: i32,
	current_char: Option<char>
}

impl Iterator for PixelIterator<'_> {
	type Item = Pixel<BinaryColor>;

	// inspired by https://docs.rs/embedded-graphics/0.6.2/src/embedded_graphics/fonts/text.rs.html#170
	fn next(&mut self) -> Option<Self::Item> {
		loop {
			if self.current_char == Some('\n') {
				self.pos.x = self.top_left.x;
				self.pos.y += self.font.height() as i32;
				self.idx += 1;
				self.current_char = self.text.chars().nth(self.idx);
			} else if self.char_walk_x < 0 {
				self.char_walk_y += 1;
				if self.char_walk_y >= self.font.height() as i32 {
					self.char_walk_y = 0;
					self.char_walk_x += 1;
				}
			} else if let Some(current_char) = self.current_char {
				if self.char_width == 0 {
					self.char_width = self.font.width();
				}

				let color = self
					.font
					.pixel(current_char, self.char_walk_x as _, self.char_walk_y as _)
					.then(|| self.color);
				let x = self.pos.x + self.char_walk_x;
				let y = self.pos.y + self.char_walk_y;
				self.char_walk_x += 1;

				if self.char_walk_x >= self.font.width() as i32 {
					self.char_walk_x = 0;
					self.char_walk_y += 1;

					if self.char_walk_y >= self.font.height() as i32 {
						self.pos.x += self.char_width as i32;
						self.char_width = 0;
						self.char_walk_y = 0;
						self.idx += 1;
						self.current_char = self.text.chars().nth(self.idx);
					}
				}

				if let Some(color) = color {
					break Some(Pixel(Point::new(x, y), color));
				}
			} else {
				break None;
			}
		}
	}
}

impl Drawable<BinaryColor> for &Styled<Text<'_>> {
	fn draw<D: DrawTarget<BinaryColor>>(self, display: &mut D) -> Result<(), D::Error> {
		let iter = PixelIterator {
			text: self.primitive.text,
			idx: 0,
			font: self.font,
			color: self.color,

			top_left: self.primitive.position,
			pos: self.primitive.position,

			char_width: 0,
			char_walk_x: 0,
			char_walk_y: 0,
			current_char: self.primitive.text.chars().next()
		};
		display.draw_iter(iter)
	}
}

impl Drawable<BinaryColor> for Styled<Text<'_>> {
	fn draw<D: DrawTarget<BinaryColor>>(self, display: &mut D) -> Result<(), D::Error> {
		<&Self as Drawable<BinaryColor>>::draw(&self, display)
	}
}