1use std::collections::HashMap;
2use std::rc::Rc;
3
4use compact_str::CompactString;
5use cosmic_text::{
6 Attrs, Buffer, Color, Fallback, Family, FontSystem, Metrics, PlatformFallback, Shaping,
7 Style as FontStyle, SwashCache, Weight, fontdb,
8};
9use unicode_script::Script;
10use unicode_width::UnicodeWidthStr;
11
12use crate::grid::{Grid, Rgb};
13use crate::icon::{Icon, Piece, inked};
14use crate::measure::{Font, attrs, emoji_letter, runs};
15use crate::paint::{
16 BOTTOM_LEFT, BOTTOM_RIGHT, Bitmap, Bounds, Paint, Pixels, TOP_LEFT, TOP_RIGHT, UNIT,
17};
18
19#[derive(Clone, Debug, PartialEq, Eq)]
21pub struct Image {
22 pub width: usize,
23 pub height: usize,
24 pub rgb: Vec<u8>,
25}
26
27pub trait Rasterizer {
29 fn row(&mut self, grid: &Grid, y: u16) -> Image;
30}
31
32#[derive(Clone, Hash, PartialEq, Eq)]
33struct GlyphKey {
34 symbol: CompactString,
35 bold: bool,
36 italic: bool,
37}
38
39type Mask = Rc<Vec<(u16, u16, u8)>>;
41type Painted = Rc<Vec<(u16, u16, Rgb, u8)>>;
43
44#[derive(Clone, Hash, PartialEq, Eq)]
45struct TextKey {
46 text: String,
47 font: Font,
48 padding: usize,
49}
50
51struct TextMask {
53 width: usize,
54 height: usize,
55 alpha: Vec<u8>,
56 own: Option<Vec<Option<Rgb>>>,
59 ink: Option<(usize, usize)>,
62}
63
64const INK: u8 = 85;
67
68const SPAN: &str = "H";
74
75const MONOGRAM_SIZE: i32 = 80;
77
78fn ink_rows(alpha: &[u8], width: usize) -> Option<(usize, usize)> {
80 let mut rows = alpha
81 .chunks(width.max(1))
82 .enumerate()
83 .filter(|(_, row)| row.iter().any(|a| *a >= INK))
84 .map(|(y, _)| y);
85 let first = rows.next()?;
86 Some((first, rows.next_back().unwrap_or(first)))
87}
88
89fn ink_columns(mask: &TextMask, first: usize, last: usize) -> (usize, usize) {
91 let (mut left, mut right) = (mask.width, 0);
92 for row in mask.alpha[first * mask.width..(last + 1) * mask.width].chunks_exact(mask.width) {
93 if let Some(first) = row.iter().position(|a| *a >= INK) {
94 left = left.min(first);
95 right = right.max(row.iter().rposition(|a| *a >= INK).unwrap_or(first));
96 }
97 }
98 (left, right)
99}
100
101const CJK_FONTS: [&str; 9] = [
104 "PingFang SC",
105 "Hiragino Sans",
106 "Hiragino Sans GB",
107 "Songti SC",
108 "Heiti SC",
109 "Arial Unicode MS",
110 "Noto Sans CJK SC",
111 "Noto Sans CJK JP",
112 "WenQuanYi Micro Hei",
113];
114
115struct WiderFallback(PlatformFallback);
117
118impl Fallback for WiderFallback {
119 fn common_fallback(&self) -> &[&'static str] {
120 self.0.common_fallback()
121 }
122
123 fn forbidden_fallback(&self) -> &[&'static str] {
124 self.0.forbidden_fallback()
125 }
126
127 fn script_fallback(&self, script: Script, locale: &str) -> &[&'static str] {
128 match script {
129 Script::Han | Script::Hiragana | Script::Katakana => &CJK_FONTS,
130 other => self.0.script_fallback(other, locale),
131 }
132 }
133}
134
135fn system_fonts() -> fontdb::Database {
136 let mut db = fontdb::Database::new();
137 db.load_system_fonts();
138 db
139}
140
141fn drawing_fonts() -> FontSystem {
144 let mut fonts = FontSystem::new_with_locale_and_db_and_fallback(
145 "en-US".to_string(),
146 system_fonts(),
147 WiderFallback(PlatformFallback),
148 );
149 let db = fonts.db_mut();
150 db.load_font_data(INTER.to_vec());
151 db.load_font_data(INTER_ITALIC.to_vec());
152 db.load_font_data(MONO.to_vec());
153 db.load_font_data(MONO_ITALIC.to_vec());
154 db.load_font_data(EMOJI.to_vec());
155 db.set_monospace_family("JetBrains Mono");
156 db.set_sans_serif_family("Inter Variable");
157 if EMOJI_FONT.get().is_none() {
158 let found = find_emoji_font(&mut fonts);
159 EMOJI_FONT.get_or_init(|| found);
160 }
161 fonts
162}
163
164static EMOJI_FONT: std::sync::OnceLock<Option<(String, fontdb::Source)>> =
167 std::sync::OnceLock::new();
168
169const SYSTEM_EMOJI: [&str; 3] = ["Apple Color Emoji", "Noto Color Emoji", "Segoe UI Emoji"];
172const BUILT_IN_EMOJI: &str = "Twemoji Mozilla";
174
175fn set_in(fonts: &mut FontSystem, family: &str, emoji: &str) -> Option<Buffer> {
178 let mut buffer = Buffer::new(fonts, Metrics::new(32.0, 40.0));
179 buffer.set_size(None, Some(40.0));
180 let attrs = Attrs::new().family(Family::Name(family));
181 let rich = std::iter::once((emoji, attrs.clone()));
182 buffer.set_rich_text(rich, &attrs, Shaping::Advanced, None);
183 buffer.shape_until_scroll(fonts, false);
184 let from_it = |glyph: &cosmic_text::LayoutGlyph| {
185 let face = fonts.db().face(glyph.font_id);
186 glyph.glyph_id != 0
187 && face.is_some_and(|face| face.families.iter().any(|(name, _)| name == family))
188 };
189 let glyphs: Vec<&cosmic_text::LayoutGlyph> = buffer
190 .layout_runs()
191 .flat_map(|run| run.glyphs.iter())
192 .collect();
193 let whole = !glyphs.is_empty() && glyphs.into_iter().all(from_it);
194 whole.then_some(buffer)
195}
196
197pub fn built_in_emoji_holds(emoji: &str) -> bool {
201 thread_local! {
202 static FONTS: std::cell::RefCell<FontSystem> = std::cell::RefCell::new({
203 let mut db = fontdb::Database::new();
204 db.load_font_data(EMOJI.to_vec());
205 FontSystem::new_with_locale_and_db("en-US".to_string(), db)
206 });
207 }
208 FONTS.with(|fonts| {
209 let set = set_in(&mut fonts.borrow_mut(), BUILT_IN_EMOJI, emoji);
210 set.is_some_and(|buffer| {
211 let glyphs = buffer.layout_runs().flat_map(|run| run.glyphs.iter());
212 glyphs.filter(|glyph| glyph.w > 0.0).count() == 1
213 })
214 })
215}
216
217fn draws_colour(fonts: &mut FontSystem, family: &str) -> bool {
220 let Some(mut buffer) = set_in(fonts, family, "👍") else {
221 return false;
222 };
223 let mut coloured = false;
224 let mut swash = SwashCache::new();
225 let white = Color::rgb(255, 255, 255);
226 buffer.draw(fonts, &mut swash, white, |_, _, _, _, color| {
227 coloured |= color.a() > 0 && (color.r(), color.g(), color.b()) != (255, 255, 255);
228 });
229 coloured
230}
231
232fn find_emoji_font(fonts: &mut FontSystem) -> Option<(String, fontdb::Source)> {
235 let built_in_only = std::env::var("CELLIX_EMOJI").is_ok_and(|choice| choice == "built-in");
238 let own = SYSTEM_EMOJI.iter().copied().filter(|_| !built_in_only);
239 for family in own.chain([BUILT_IN_EMOJI]) {
240 let source = fonts
241 .db()
242 .faces()
243 .find(|face| face.families.iter().any(|(name, _)| name == family))
244 .map(|face| face.source.clone());
245 if let Some(source) = source
246 && draws_colour(fonts, family)
247 {
248 return Some((family.to_string(), source));
249 }
250 }
251 None
252}
253
254pub(crate) fn emoji_font() -> Option<&'static (String, fontdb::Source)> {
257 if EMOJI_FONT.get().is_none() {
258 drop(drawing_fonts());
259 }
260 EMOJI_FONT.get().and_then(Option::as_ref)
261}
262
263const DARK_SHADOW: f32 = 110.0;
265const LIGHT_SHADOW: f32 = 38.0;
266pub const INTERFACE_SIZE: f32 = 0.70;
269const MAX_TEXT_MASKS: usize = 4096;
271
272pub(crate) const INTER: &[u8] = include_bytes!("../fonts/InterVariable.ttf");
273pub(crate) const INTER_ITALIC: &[u8] = include_bytes!("../fonts/InterVariable-Italic.ttf");
274pub(crate) const MONO: &[u8] = include_bytes!("../fonts/JetBrainsMonoVariable.ttf");
275pub(crate) const MONO_ITALIC: &[u8] = include_bytes!("../fonts/JetBrainsMonoVariable-Italic.ttf");
276pub(crate) const EMOJI: &[u8] = include_bytes!("../fonts/TwemojiMozilla.ttf");
278
279pub(crate) fn text_pixels(row_height: usize, font: Font) -> f32 {
281 row_height as f32 * INTERFACE_SIZE * font.size as f32 / 100.0
282}
283
284pub fn stood(y: i32, h: i32, row: f32, line: f32) -> (f32, f32) {
294 let (top, tall) = (y as f32 * row / UNIT as f32, h as f32 * row / UNIT as f32);
295 if h < UNIT && line < row {
296 let kept = h as f32 * line / UNIT as f32;
297 let share = h as f32 / UNIT as f32;
298 let own = if share >= FILLS {
299 kept.max(row * CONTROL).min(tall)
300 } else if share >= HOLDS {
301 kept.max(row * CHIP).min(tall)
302 } else {
303 kept
304 };
305 (top + (tall - own) / 2.0, own)
306 } else {
307 (top, tall)
308 }
309}
310
311pub fn inset(y: i32, h: i32, row: f32, line: f32) -> (f32, f32) {
317 let (top, tall) = (y as f32 * row / UNIT as f32, h as f32 * row / UNIT as f32);
318 let kept = (h as f32 * line / UNIT as f32).min(tall);
319 (top + (tall - kept) / 2.0, kept)
320}
321
322const FILLS: f32 = 0.8;
325const CONTROL: f32 = 0.78;
326const HOLDS: f32 = 0.7;
328const CHIP: f32 = 0.714;
329
330pub struct SoftwareRasterizer {
333 fonts: FontSystem,
334 emoji: Option<String>,
336 swash: SwashCache,
337 metrics: Metrics,
338 cell: (usize, usize),
339 type_row: usize,
342 masks: HashMap<GlyphKey, Mask>,
343 painted: HashMap<GlyphKey, Painted>,
345 text: HashMap<TextKey, Rc<TextMask>>,
346}
347
348impl SoftwareRasterizer {
349 pub fn new(cell_width: usize, cell_height: usize) -> Option<Self> {
352 if cell_width == 0 || cell_height == 0 {
353 return None;
354 }
355 let mut fonts = drawing_fonts();
356 let metrics = fit_font(&mut fonts, cell_width, cell_height)?;
357 let emoji = emoji_font().map(|(family, _)| family.clone());
358 Some(Self {
359 fonts,
360 emoji,
361 swash: SwashCache::new(),
362 metrics,
363 cell: (cell_width, cell_height),
364 type_row: cell_height,
365 masks: HashMap::new(),
366 painted: HashMap::new(),
367 text: HashMap::new(),
368 })
369 }
370
371 pub fn with_type_row(mut self, rows: usize) -> Self {
375 self.type_row = rows.clamp(1, self.cell.1);
376 self
377 }
378
379 fn stand(&self, y: i32, h: i32) -> (f32, f32) {
383 stood(y, h, self.cell.1 as f32, self.type_row as f32)
384 }
385
386 fn mask(&mut self, key: &GlyphKey) -> Mask {
387 if let Some(mask) = self.masks.get(key) {
388 return mask.clone();
389 }
390 let (width, height) = (self.cell.0 * 2, self.cell.1);
391 let mut buffer = Buffer::new(&mut self.fonts, self.metrics);
392 buffer.set_size(Some(width as f32 * 2.0), Some(height as f32));
393 let emoji = self.emoji.clone().filter(|_| emoji_letter(&key.symbol));
397 let family = if let Some(emoji) = &emoji {
398 Family::Name(emoji)
399 } else if UnicodeWidthStr::width(key.symbol.as_str()) > 1 {
400 Family::SansSerif
401 } else {
402 Family::Monospace
403 };
404 let mut attrs = Attrs::new().family(family);
405 if key.bold {
406 attrs = attrs.weight(Weight::BOLD);
407 }
408 if key.italic {
409 attrs = attrs.style(FontStyle::Italic);
410 }
411 let rich = std::iter::once((key.symbol.as_str(), attrs.clone()));
412 buffer.set_rich_text(rich, &attrs, Shaping::Advanced, None);
413 buffer.shape_until_scroll(&mut self.fonts, false);
414 let mut pixels = Vec::new();
415 let mut coloured = Vec::new();
416 let white = Color::rgb(255, 255, 255);
417 buffer.draw(
418 &mut self.fonts,
419 &mut self.swash,
420 white,
421 |x, y, w, h, color| {
422 if color.a() == 0 {
423 return;
424 }
425 for py in y..y + h as i32 {
426 for px in x..x + w as i32 {
427 if px >= 0 && py >= 0 && (px as usize) < width && (py as usize) < height {
428 pixels.push((px as u16, py as u16, color.a()));
429 let rgb = Rgb(color.r(), color.g(), color.b());
430 coloured.push((px as u16, py as u16, rgb, color.a()));
431 }
432 }
433 }
434 },
435 );
436 if self.type_row < height && boxes(&key.symbol) {
439 pixels = stretched(&pixels, self.type_row, height);
440 coloured.clear();
441 }
442 if coloured
444 .iter()
445 .any(|(_, _, rgb, _)| *rgb != Rgb(255, 255, 255))
446 {
447 self.painted.insert(key.clone(), Rc::new(coloured));
448 }
449 let mask = Rc::new(pixels);
450 self.masks.insert(key.clone(), mask.clone());
451 mask
452 }
453
454 fn text_mask(&mut self, text: &str, font: Font) -> Rc<TextMask> {
456 self.text_mask_with_padding(text, font, 0)
457 }
458
459 fn text_mask_with_padding(&mut self, text: &str, font: Font, padding: usize) -> Rc<TextMask> {
461 let key = TextKey {
462 text: text.to_string(),
463 font,
464 padding,
465 };
466 if let Some(mask) = self.text.get(&key) {
467 return mask.clone();
468 }
469 if self.text.len() >= MAX_TEXT_MASKS {
470 self.text.clear();
471 }
472 let px = text_pixels(self.type_row, font);
473 let height = self.cell.1.max((px * 1.45).ceil() as usize);
474 let mut buffer = Buffer::new(&mut self.fonts, Metrics::new(px, height as f32));
475 buffer.set_size(None, Some(height as f32));
476 let emoji = self.emoji.clone();
477 let rich = runs(text, font, emoji.as_deref());
478 buffer.set_rich_text(rich, &attrs(font), Shaping::Advanced, None);
479 buffer.shape_until_scroll(&mut self.fonts, false);
480 let width = buffer
481 .layout_runs()
482 .next()
483 .map_or(0.0, |run| run.line_w)
484 .ceil() as usize
485 + 2
486 + 2 * padding;
487 let mut alpha = vec![0; width * height];
488 let white = Rgb(255, 255, 255);
491 let mut drawn = vec![white; width * height];
492 let mut tinted = false;
493 buffer.draw(
494 &mut self.fonts,
495 &mut self.swash,
496 Color::rgb(255, 255, 255),
497 |x, y, w, h, color| {
498 let rgb = Rgb(color.r(), color.g(), color.b());
499 tinted |= color.a() > 0 && rgb != white;
500 for at in spots((width, height), (x + padding as i32, y), (w, h)) {
501 if color.a() >= alpha[at] {
502 drawn[at] = rgb;
503 }
504 alpha[at] = alpha[at].max(color.a());
505 }
506 },
507 );
508 let own = tinted.then(|| {
511 let black = Rgb(0, 0, 0);
512 let mut own = vec![None; width * height];
513 buffer.draw(
514 &mut self.fonts,
515 &mut self.swash,
516 Color::rgb(0, 0, 0),
517 |x, y, w, h, color| {
518 let rgb = Rgb(color.r(), color.g(), color.b());
519 for at in spots((width, height), (x + padding as i32, y), (w, h)) {
520 if color.a() > 0 && (rgb != black || drawn[at] != white) {
521 own[at] = Some(drawn[at]);
522 }
523 }
524 },
525 );
526 own
527 });
528 let ink = ink_rows(&alpha, width);
529 let mask = Rc::new(TextMask {
530 width,
531 height,
532 alpha,
533 own,
534 ink,
535 });
536 self.text.insert(key, mask.clone());
537 mask
538 }
539
540 fn draw_paint(&mut self, target: &mut Target, paint: &Paint) {
541 let (cw, ch) = (self.cell.0 as f32, self.cell.1 as f32);
542 let th = self.type_row as f32;
545 let scale = |v: i32, cell: f32| v as f32 * cell / UNIT as f32;
546 let square = |bounds: &Bounds| {
547 let side = scale(bounds.h, th);
548 let left = scale(bounds.x, cw);
549 let top = scale(bounds.y, ch) + (scale(bounds.h, ch) - side) / 2.0;
550 (left, top, side)
551 };
552 match paint {
553 Paint::Panel {
554 bounds,
555 radius,
556 fill,
557 border,
558 shadow,
559 dashed,
560 inset: on_a_wash,
561 } => {
562 let (y, h) = match (*on_a_wash, *shadow) {
563 (true, true) => (scale(bounds.y, ch), scale(bounds.h, ch)),
565 (true, false) => inset(bounds.y, bounds.h, ch, th),
566 _ => self.stand(bounds.y, bounds.h),
567 };
568 let mut shape = Shape {
569 x: scale(bounds.x, cw),
570 y,
571 w: scale(bounds.w, cw),
572 h,
573 radius: *radius as f32 * th / 100.0,
574 };
575 if border.is_some() {
579 let right = (shape.x + shape.w).round();
580 let bottom = (shape.y + shape.h).round();
581 shape.x = shape.x.round();
582 shape.y = shape.y.round();
583 shape.w = right - shape.x;
584 shape.h = bottom - shape.y;
585 }
586 target.panel(shape, (*fill, *border), *shadow, *dashed, th);
587 }
588 Paint::Wash {
589 bounds,
590 radius,
591 color,
592 alpha,
593 border,
594 } => {
595 let (y, h) = self.stand(bounds.y, bounds.h);
596 let shape = Shape {
597 x: scale(bounds.x, cw),
598 y,
599 w: scale(bounds.w, cw),
600 h,
601 radius: *radius as f32 * th / 100.0,
602 };
603 target.wash(shape, (*color, *alpha), *border, th);
604 }
605 Paint::Hairline { bounds, color } => {
606 let thickness = (th / 24.0).ceil().max(1.0);
607 let (x, y) = (scale(bounds.x, cw), scale(bounds.y, ch));
610 let shape = Shape {
611 x: if bounds.w == 0 { x.round() } else { x },
612 y: if bounds.h == 0 { y.round() } else { y },
613 w: scale(bounds.w, cw).max(thickness),
614 h: scale(bounds.h, ch).max(thickness),
615 radius: 0.0,
616 };
617 target.panel(shape, (Some(*color), None), false, false, th);
618 }
619 Paint::Text {
620 x,
621 y,
622 max_width,
623 text,
624 color,
625 font,
626 align_right,
627 centred,
628 underline,
629 span_centred,
630 } => {
631 let mask = self.text_mask(text, *font);
632 let mut left = scale(*x, cw).round() as i32;
633 if *align_right {
634 left -= mask.width as i32;
635 } else if *centred {
636 left -= mask.width as i32 / 2;
637 }
638 let lift = (mask.height as i32 - ch as i32) / 2;
642 let span = span_centred.then(|| self.text_mask(SPAN, *font).ink);
643 let top = match span.flatten() {
644 Some((first, last)) => {
645 let middle = scale(*y, ch) + ch / 2.0;
646 (middle - (first + last + 1) as f32 / 2.0).round() as i32
647 }
648 None => scale(*y, ch).round() as i32 - lift,
649 };
650 let limit = scale(*max_width, cw).max(0.0) as usize;
651 target.blit(&mask, left, top, limit, *color);
652 if *underline {
653 let thickness = (th / 24.0).ceil().max(1.0);
654 let shape = Shape {
655 x: left as f32,
656 y: scale(*y, ch) + (ch - th) / 2.0 + th * 0.78,
658 w: mask.width.saturating_sub(2).min(limit) as f32,
659 h: thickness,
660 radius: 0.0,
661 };
662 target.panel(shape, (Some(*color), None), false, false, th);
663 }
664 }
665 Paint::Icon {
666 bounds,
667 icon,
668 color,
669 } => {
670 let (left, top, side) = square(bounds);
673 target.icon(*icon, left, top, side, *color);
674 }
675 Paint::Monogram {
676 bounds,
677 color,
678 letter,
679 ground,
680 } => {
681 let (left, top, side) = square(bounds);
682 target.icon(Icon::Program, left, top, side, *color);
683 let font = Font {
684 bold: true,
685 size: (bounds.h * MONOGRAM_SIZE / UNIT) as u8,
686 ..Font::default()
687 };
688 let mask = self.text_mask_with_padding(
689 letter.encode_utf8(&mut [0; 4]),
690 font,
691 self.type_row / 2,
692 );
693 if let Some((first, last)) = mask.ink {
694 let (start, end) = ink_columns(&mask, first, last);
695 let x = left + side / 2.0 - (start + end + 1) as f32 / 2.0;
696 let y = top + side / 2.0 - (first + last + 1) as f32 / 2.0;
697 target.blit(
698 &mask,
699 x.round() as i32,
700 y.round() as i32,
701 mask.width,
702 *ground,
703 );
704 }
705 }
706 Paint::Spinner {
707 bounds,
708 color,
709 step,
710 } => {
711 let (left, top, side) = square(bounds);
712 target.spinner(*step, left, top, side, *color);
713 }
714 Paint::Corners {
715 bounds,
716 radius,
717 color,
718 which,
719 } => {
720 let shape = Shape {
721 x: scale(bounds.x, cw),
722 y: scale(bounds.y, ch),
723 w: scale(bounds.w, cw),
724 h: scale(bounds.h, ch),
725 radius: *radius as f32 * th / 100.0,
726 };
727 target.corners(&shape, *color, *which);
728 }
729 Paint::Image {
730 bounds,
731 clip,
732 bitmap,
733 color,
734 } => {
735 let shape = Shape {
736 x: scale(bounds.x, cw),
737 y: scale(bounds.y, ch),
738 w: scale(bounds.w, cw),
739 h: scale(bounds.h, ch),
740 radius: 0.0,
741 };
742 let across = (
743 scale(clip.x, cw) as i32,
744 scale(clip.x + clip.w, cw).ceil() as i32,
745 );
746 let down = (
747 scale(clip.y, ch) as i32,
748 scale(clip.y + clip.h, ch).ceil() as i32,
749 );
750 target.image(&shape, (across, down), bitmap, *color);
751 }
752 Paint::Strips { bounds, strips } => {
753 let (left, top) = (scale(bounds.x, cw), scale(bounds.y, ch));
754 let (width, height) = (scale(bounds.w, cw), scale(bounds.h, ch));
755 let thickness = (th / 24.0).ceil().max(1.0);
756 for strip in strips {
757 let shape = Shape {
758 x: left + strip.x as f32 * width / 256.0,
759 y: top + strip.y as f32 * height / 256.0,
760 w: (strip.w as f32 * width / 256.0).max(1.0),
761 h: thickness,
762 radius: 0.0,
763 };
764 target.panel(shape, (Some(strip.color), None), false, false, ch);
765 }
766 }
767 }
768 }
769}
770
771fn spots(
773 (width, height): (usize, usize),
774 (x, y): (i32, i32),
775 (w, h): (u32, u32),
776) -> impl Iterator<Item = usize> {
777 let across = x.max(0) as usize..((x + w as i32).max(0) as usize).min(width);
778 let down = y.max(0) as usize..((y + h as i32).max(0) as usize).min(height);
779 down.flat_map(move |py| across.clone().map(move |px| py * width + px))
780}
781
782fn caret_bounds(grid: &Grid) -> Option<Bounds> {
784 grid.caret.or_else(|| {
785 let (x, y) = grid.cursor?;
786 Some(Bounds::cells(x as f32, y as f32 + 0.08, 0.0, 0.84))
787 })
788}
789
790fn caret_color(grid: &Grid) -> Rgb {
791 let Some((x, y)) = grid.cursor else {
792 return Rgb(255, 255, 255);
793 };
794 grid.cell(x.min(grid.width().saturating_sub(1)), y).style.fg
795}
796
797struct Shape {
798 x: f32,
799 y: f32,
800 w: f32,
801 h: f32,
802 radius: f32,
803}
804
805fn rounded_distance(shape: &Shape, x: f32, y: f32) -> f32 {
807 let (cx, cy) = (shape.x + shape.w / 2.0, shape.y + shape.h / 2.0);
808 let qx = (x - cx).abs() - shape.w / 2.0 + shape.radius;
809 let qy = (y - cy).abs() - shape.h / 2.0 + shape.radius;
810 let outside = (qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt();
811 outside + qx.max(qy).min(0.0) - shape.radius
812}
813
814struct Target<'a> {
816 rgb: &'a mut [u8],
817 width: usize,
818 height: usize,
819 top: i32,
820}
821
822impl Target<'_> {
823 fn corners(&mut self, s: &Shape, color: Rgb, which: u8) {
824 let r = s.radius;
825 let spots = [
826 (TOP_LEFT, s.x, s.y, s.x + r, s.y + r),
827 (TOP_RIGHT, s.x + s.w - r, s.y, s.x + s.w - r, s.y + r),
828 (
829 BOTTOM_RIGHT,
830 s.x + s.w - r,
831 s.y + s.h - r,
832 s.x + s.w - r,
833 s.y + s.h - r,
834 ),
835 (BOTTOM_LEFT, s.x, s.y + s.h - r, s.x + r, s.y + s.h - r),
836 ];
837 for (flag, left, top, cx, cy) in spots {
838 if which & flag == 0 {
839 continue;
840 }
841 for y in top.floor() as i32..(top + r).ceil() as i32 {
842 for x in left.floor() as i32..(left + r).ceil() as i32 {
843 let d = ((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt();
844 let outside = (d - r + 0.5).clamp(0.0, 1.0);
845 self.blend(x, y, color, (outside * 255.0) as u8);
846 }
847 }
848 }
849 }
850
851 fn blend(&mut self, x: i32, y: i32, color: Rgb, alpha: u8) {
852 let row = y - self.top;
853 if alpha == 0 || x < 0 || row < 0 || x as usize >= self.width || row as usize >= self.height
854 {
855 return;
856 }
857 let at = (row as usize * self.width + x as usize) * 3;
858 self.rgb[at] = blend(color.0, self.rgb[at], alpha);
859 self.rgb[at + 1] = blend(color.1, self.rgb[at + 1], alpha);
860 self.rgb[at + 2] = blend(color.2, self.rgb[at + 2], alpha);
861 }
862
863 fn panel(
864 &mut self,
865 s: Shape,
866 (fill, border): (Option<Rgb>, Option<Rgb>),
867 shadow: bool,
868 dashed: bool,
869 row: f32,
870 ) {
871 let dash = (row / 4.0).max(2.0);
874 let on_dash = |x: f32, y: f32| {
875 let along_top = x > s.x + s.radius && x < s.x + s.w - s.radius;
876 let run = if along_top { x - s.x } else { y - s.y };
877 (run / dash).floor() as i64 % 2 == 0
878 };
879 let reach = if shadow { row * 0.35 } else { 1.0 };
881 let (x0, x1) = (
882 (s.x - reach).floor() as i32,
883 (s.x + s.w + reach).ceil() as i32,
884 );
885 let above = if shadow { 1.0 } else { reach };
886 let y0 = ((s.y - above).floor() as i32).max(self.top);
887 let y1 = ((s.y + s.h + reach).ceil() as i32).min(self.top + self.height as i32);
888 let stroke = (row / 30.0).max(1.0);
889 for y in y0..y1 {
890 for x in x0..x1 {
891 let d = rounded_distance(&s, x as f32 + 0.5, y as f32 + 0.5);
892 if shadow && d > 0.0 && y as f32 + 0.5 > s.y + s.radius {
893 let fade = (1.0 - d / reach).clamp(0.0, 1.0);
894 let light = fill.is_some_and(|f| f.0 > 180);
896 let depth = if light { LIGHT_SHADOW } else { DARK_SHADOW };
897 self.blend(x, y, Rgb(0, 0, 0), (fade * fade * depth) as u8);
898 }
899 let inside = ((0.5 - d) * 255.0).clamp(0.0, 255.0) as u8;
900 if let Some(color) = fill {
901 self.blend(x, y, color, inside);
902 }
903 if let Some(color) = border
904 && (!dashed || on_dash(x as f32 + 0.5, y as f32 + 0.5))
905 {
906 let edge = ((0.5 - (d + stroke / 2.0).abs() + stroke / 2.0) * 255.0)
907 .clamp(0.0, 255.0) as u8;
908 self.blend(x, y, color, edge);
909 }
910 }
911 }
912 }
913
914 fn wash(&mut self, s: Shape, (color, alpha): (Rgb, u8), border: Option<Rgb>, row: f32) {
916 let (x0, x1) = (s.x.floor() as i32 - 1, (s.x + s.w).ceil() as i32 + 1);
917 let y0 = (s.y.floor() as i32 - 1).max(self.top);
918 let y1 = ((s.y + s.h).ceil() as i32 + 1).min(self.top + self.height as i32);
919 let stroke = (row / 15.0).max(2.0);
920 for y in y0..y1 {
921 for x in x0..x1 {
922 let d = rounded_distance(&s, x as f32 + 0.5, y as f32 + 0.5);
923 let inside = (0.5 - d).clamp(0.0, 1.0);
924 self.blend(x, y, color, (inside * alpha as f32) as u8);
925 if let Some(edge_color) = border {
926 let along = (0.5 - (d + stroke / 2.0).abs() + stroke / 2.0).clamp(0.0, 1.0);
928 self.blend(x, y, edge_color, (along * 255.0) as u8);
929 }
930 }
931 }
932 }
933
934 fn blit(&mut self, mask: &TextMask, left: i32, top: i32, limit: usize, color: Rgb) {
935 let from = (self.top - top).max(0) as usize;
936 let to = ((self.top + self.height as i32 - top).max(0) as usize).min(mask.height);
937 for y in from..to {
938 for x in 0..mask.width.min(limit) {
939 let at = y * mask.width + x;
940 let ink = mask.own.as_ref().and_then(|own| own[at]).unwrap_or(color);
941 self.blend(left + x as i32, top + y as i32, ink, mask.alpha[at]);
942 }
943 }
944 }
945
946 fn image(&mut self, s: &Shape, clip: ((i32, i32), (i32, i32)), bitmap: &Bitmap, color: Rgb) {
948 let (width, height) = (bitmap.width as usize, bitmap.height as usize);
949 if width == 0 || height == 0 || s.w <= 0.0 || s.h <= 0.0 {
950 return;
951 }
952 let channels = match bitmap.kind {
953 Pixels::Coverage => 1,
954 Pixels::Rgba => 4,
955 };
956 let at = |x: usize, y: usize, c: usize| -> f32 {
957 let index = (y.min(height - 1) * width + x.min(width - 1)) * channels + c;
958 bitmap.pixels.get(index).copied().unwrap_or(0) as f32
959 };
960 let sample = |u: f32, v: f32, c: usize| -> f32 {
961 let (fx, fy) = (u.max(0.0), v.max(0.0));
962 let (x, y) = (fx as usize, fy as usize);
963 let (dx, dy) = (fx - x as f32, fy - y as f32);
964 let top = at(x, y, c) * (1.0 - dx) + at(x + 1, y, c) * dx;
965 let bottom = at(x, y + 1, c) * (1.0 - dx) + at(x + 1, y + 1, c) * dx;
966 top * (1.0 - dy) + bottom * dy
967 };
968 let ((left, right), (top, bottom)) = clip;
969 let y0 = (s.y.floor() as i32).max(self.top).max(top);
970 let y1 = ((s.y + s.h).ceil() as i32)
971 .min(self.top + self.height as i32)
972 .min(bottom);
973 let x0 = (s.x.floor() as i32).max(0).max(left);
974 let x1 = ((s.x + s.w).ceil() as i32)
975 .min(self.width as i32)
976 .min(right);
977 let (ax, ay) = (width as f32 / s.w, height as f32 / s.h);
978 if bitmap.kind == Pixels::Rgba && (ax - 1.0).abs() < 0.002 && (ay - 1.0).abs() < 0.002 {
980 let (left, top) = (s.x.round() as i32, s.y.round() as i32);
981 for y in y0..y1 {
982 for x in x0..x1 {
983 let (u, v) = (x - left, y - top);
984 if u < 0 || v < 0 || u as usize >= width || v as usize >= height {
985 continue;
986 }
987 let at = (v as usize * width + u as usize) * 4;
988 if let Some(p) = bitmap.pixels.get(at..at + 4) {
989 self.blend(x, y, Rgb(p[0], p[1], p[2]), p[3]);
990 }
991 }
992 }
993 return;
994 }
995 for y in y0..y1 {
996 for x in x0..x1 {
997 let u = (x as f32 + 0.5 - s.x) * ax - 0.5;
998 let v = (y as f32 + 0.5 - s.y) * ay - 0.5;
999 match bitmap.kind {
1000 Pixels::Coverage => self.blend(x, y, color, sample(u, v, 0) as u8),
1001 Pixels::Rgba => {
1002 let ink = Rgb(
1003 sample(u, v, 0) as u8,
1004 sample(u, v, 1) as u8,
1005 sample(u, v, 2) as u8,
1006 );
1007 self.blend(x, y, ink, sample(u, v, 3) as u8);
1008 }
1009 }
1010 }
1011 }
1012 }
1013
1014 fn spinner(&mut self, step: Option<u8>, left: f32, top: f32, side: f32, color: Rgb) {
1017 const SAMPLES: usize = 5;
1018 let y0 = (top.floor() as i32).max(self.top);
1019 let y1 = ((top + side).ceil() as i32).min(self.top + self.height as i32);
1020 for y in y0..y1 {
1021 for x in left.floor() as i32..(left + side).ceil() as i32 {
1022 let (mut ring, mut arc) = (0, 0);
1023 for sy in 0..SAMPLES {
1024 for sx in 0..SAMPLES {
1025 let u = (x as f32 + (sx as f32 + 0.5) / SAMPLES as f32 - left) / side;
1026 let v = (y as f32 + (sy as f32 + 0.5) / SAMPLES as f32 - top) / side;
1027 if (0.0..1.0).contains(&u) && (0.0..1.0).contains(&v) {
1028 let (r, a) = crate::spinner::inked(step, u, v);
1029 ring += usize::from(r);
1030 arc += usize::from(a);
1031 }
1032 }
1033 }
1034 let all = SAMPLES * SAMPLES;
1035 self.blend(x, y, color, (ring * 64 / all) as u8);
1036 self.blend(x, y, color, (arc * 255 / all) as u8);
1037 }
1038 }
1039 }
1040
1041 fn icon(&mut self, icon: Icon, left: f32, top: f32, side: f32, color: Rgb) {
1042 const SAMPLES: usize = 5;
1044 let y0 = (top.floor() as i32).max(self.top);
1045 let y1 = ((top + side).ceil() as i32).min(self.top + self.height as i32);
1046 for y in y0..y1 {
1047 for x in left.floor() as i32..(left + side).ceil() as i32 {
1048 let mut hits = 0;
1049 for sy in 0..SAMPLES {
1050 for sx in 0..SAMPLES {
1051 let u = (x as f32 + (sx as f32 + 0.5) / SAMPLES as f32 - left) / side;
1052 let v = (y as f32 + (sy as f32 + 0.5) / SAMPLES as f32 - top) / side;
1053 if (0.0..1.0).contains(&u) && (0.0..1.0).contains(&v) && inked(icon, u, v) {
1054 hits += 1;
1055 }
1056 }
1057 }
1058 self.blend(x, y, color, (hits * 255 / (SAMPLES * SAMPLES)) as u8);
1059 }
1060 }
1061 }
1062}
1063
1064fn boxes(symbol: &str) -> bool {
1066 let mut chars = symbol.chars();
1067 matches!(
1068 (chars.next(), chars.next()),
1069 (Some('\u{2500}'..='\u{259f}'), None)
1070 )
1071}
1072
1073fn stretched(pixels: &[(u16, u16, u8)], from: usize, to: usize) -> Vec<(u16, u16, u8)> {
1075 let first = (to - from) / 2;
1076 let mut out = Vec::with_capacity(pixels.len() * to / from.max(1) + 1);
1077 for &(x, y, alpha) in pixels {
1078 let line = (y as usize).checked_sub(first).filter(|line| *line < from);
1079 let Some(line) = line else { continue };
1080 for row in line * to / from..(line + 1) * to / from {
1081 out.push((x, row as u16, alpha));
1082 }
1083 }
1084 out
1085}
1086
1087fn fit_font(fonts: &mut FontSystem, cell_width: usize, cell_height: usize) -> Option<Metrics> {
1089 const PROBE: f32 = 100.0;
1090 let mut buffer = Buffer::new(fonts, Metrics::new(PROBE, PROBE * 1.2));
1091 buffer.set_size(Some(PROBE * 4.0), Some(PROBE * 2.0));
1092 let attrs = Attrs::new().family(Family::Monospace);
1093 buffer.set_rich_text(
1094 std::iter::once(("M", attrs.clone())),
1095 &attrs,
1096 Shaping::Advanced,
1097 None,
1098 );
1099 buffer.shape_until_scroll(fonts, false);
1100 let advance = buffer.layout_runs().next()?.line_w;
1101 if advance <= 0.0 {
1102 return None;
1103 }
1104 let by_width = cell_width as f32 * PROBE / advance;
1105 let by_height = cell_height as f32 * 0.8;
1106 Some(Metrics::new(by_width.min(by_height), cell_height as f32))
1107}
1108
1109fn draw_icon(
1111 rgb: &mut [u8],
1112 stride: usize,
1113 left: usize,
1114 cell: (usize, usize),
1115 piece: Piece,
1116 fg: Rgb,
1117) {
1118 const SAMPLES: usize = 4;
1119 let (cw, ch) = cell;
1120 let (full_w, full_h) = (cw * piece.width as usize, ch * piece.height as usize);
1121 let side = full_w.min(full_h) as f32 * 0.94;
1122 let (off_x, off_y) = ((full_w as f32 - side) / 2.0, (full_h as f32 - side) / 2.0);
1123 for y in 0..ch {
1124 for x in 0..cw {
1125 let mut hits = 0;
1126 for sy in 0..SAMPLES {
1127 for sx in 0..SAMPLES {
1128 let px = (piece.column as usize * cw + x) as f32
1129 + (sx as f32 + 0.5) / SAMPLES as f32;
1130 let py =
1131 (piece.row as usize * ch + y) as f32 + (sy as f32 + 0.5) / SAMPLES as f32;
1132 let (u, v) = ((px - off_x) / side, (py - off_y) / side);
1133 if (0.0..1.0).contains(&u) && (0.0..1.0).contains(&v) && inked(piece.icon, u, v)
1134 {
1135 hits += 1;
1136 }
1137 }
1138 }
1139 if hits > 0 {
1140 let alpha = (hits * 255 / (SAMPLES * SAMPLES)) as u8;
1141 let at = (y * stride + left + x) * 3;
1142 rgb[at] = blend(fg.0, rgb[at], alpha);
1143 rgb[at + 1] = blend(fg.1, rgb[at + 1], alpha);
1144 rgb[at + 2] = blend(fg.2, rgb[at + 2], alpha);
1145 }
1146 }
1147 }
1148}
1149
1150fn blend(fg: u8, bg: u8, alpha: u8) -> u8 {
1151 let a = alpha as u32;
1152 ((fg as u32 * a + bg as u32 * (255 - a)) / 255) as u8
1153}
1154
1155fn fill(rgb: &mut [u8], stride: usize, x: usize, y: usize, w: usize, h: usize, color: Rgb) {
1156 for row in y..y + h {
1157 for px in x..x + w {
1158 let i = (row * stride + px) * 3;
1159 if i + 2 < rgb.len() {
1160 rgb[i..i + 3].copy_from_slice(&[color.0, color.1, color.2]);
1161 }
1162 }
1163 }
1164}
1165
1166impl Rasterizer for SoftwareRasterizer {
1167 fn row(&mut self, grid: &Grid, y: u16) -> Image {
1168 let cells = grid.row(y);
1169 let (cw, ch) = self.cell;
1170 let width = cw * cells.len();
1171 let mut rgb = vec![0; width * ch * 3];
1172 for (i, cell) in cells.iter().enumerate() {
1174 fill(&mut rgb, width, i * cw, 0, cw, ch, cell.style.bg);
1175 }
1176 for (i, cell) in cells.iter().enumerate() {
1177 let fg = cell.style.fg;
1178 if cell.symbol.is_empty() || cell.symbol == " " || cell.style.painted {
1179 continue;
1180 }
1181 if cell.symbol == "▌" {
1183 fill(&mut rgb, width, i * cw, 0, cw.div_ceil(5), ch, fg);
1184 continue;
1185 }
1186 if let Some(piece) = Piece::decode(&cell.symbol) {
1187 draw_icon(&mut rgb, width, i * cw, (cw, ch), piece, fg);
1188 continue;
1189 }
1190 let key = GlyphKey {
1191 symbol: cell.symbol.clone(),
1192 bold: cell.style.bold,
1193 italic: cell.style.italic,
1194 };
1195 let mask = self.mask(&key);
1196 if let Some(painted) = self.painted.get(&key) {
1197 for &(x, y, color, alpha) in painted.iter() {
1198 let at = (y as usize * width + i * cw + x as usize) * 3;
1199 if at + 2 < rgb.len() && (i * cw + x as usize) < width {
1200 rgb[at] = blend(color.0, rgb[at], alpha);
1201 rgb[at + 1] = blend(color.1, rgb[at + 1], alpha);
1202 rgb[at + 2] = blend(color.2, rgb[at + 2], alpha);
1203 }
1204 }
1205 continue;
1206 }
1207 for &(x, y, alpha) in mask.iter() {
1208 let at = (y as usize * width + i * cw + x as usize) * 3;
1209 if at + 2 < rgb.len() && (i * cw + x as usize) < width {
1210 rgb[at] = blend(fg.0, rgb[at], alpha);
1211 rgb[at + 1] = blend(fg.1, rgb[at + 1], alpha);
1212 rgb[at + 2] = blend(fg.2, rgb[at + 2], alpha);
1213 }
1214 }
1215 }
1216 for (i, cell) in cells.iter().enumerate() {
1217 if cell.style.underline && !cell.style.painted {
1219 fill(&mut rgb, width, i * cw, ch - 2, cw, 1, cell.style.fg);
1220 }
1221 }
1222 let paint: Vec<Paint> = grid.paint_on_row(y).cloned().collect();
1223 let mut target = Target {
1224 rgb: &mut rgb,
1225 width,
1226 height: ch,
1227 top: y as i32 * ch as i32,
1228 };
1229 for item in &paint {
1230 self.draw_paint(&mut target, item);
1231 }
1232 if let Some(bounds) = caret_bounds(grid) {
1234 let row = (y as i32 * UNIT, (y as i32 + 1) * UNIT);
1235 if bounds.y < row.1 && bounds.y + bounds.h > row.0 {
1236 let tall = bounds.h as f32 * ch as f32 / UNIT as f32;
1238 let own = if bounds.h <= UNIT {
1239 bounds.h as f32 * self.type_row as f32 / UNIT as f32
1240 } else {
1241 tall
1242 };
1243 let shape = Shape {
1244 x: bounds.x as f32 * cw as f32 / UNIT as f32,
1245 y: bounds.y as f32 * ch as f32 / UNIT as f32 + (tall - own) / 2.0,
1246 w: (cw as f32 / 9.0).max(2.0),
1247 h: own,
1248 radius: 0.0,
1249 };
1250 let mut target = Target {
1251 rgb: &mut rgb,
1252 width,
1253 height: ch,
1254 top: y as i32 * ch as i32,
1255 };
1256 target.panel(
1257 shape,
1258 (Some(caret_color(grid)), None),
1259 false,
1260 false,
1261 self.type_row as f32,
1262 );
1263 }
1264 }
1265 Image {
1266 width,
1267 height: ch,
1268 rgb,
1269 }
1270 }
1271}
1272
1273#[cfg(test)]
1274mod tests {
1275 use super::*;
1276 use crate::grid::{Grid, Rect, Style};
1277
1278 fn rasterizer() -> Option<SoftwareRasterizer> {
1279 SoftwareRasterizer::new(10, 20)
1280 }
1281
1282 fn style() -> Style {
1283 Style {
1284 fg: Rgb(250, 250, 250),
1285 bg: Rgb(10, 20, 30),
1286 ..Style::default()
1287 }
1288 }
1289
1290 fn lit(image: &Image, cell: usize, width: usize) -> usize {
1291 let mut count = 0;
1292 for y in 0..image.height {
1293 for x in cell * width..(cell + 1) * width {
1294 let i = (y * image.width + x) * 3;
1295 count += usize::from(image.rgb[i] > 128);
1296 }
1297 }
1298 count
1299 }
1300
1301 #[test]
1302 fn row_image_is_exactly_the_grid_size() {
1303 let Some(mut r) = rasterizer() else { return };
1304 let grid = Grid::new(8, 1, style());
1305 let image = r.row(&grid, 0);
1306 assert_eq!((image.width, image.height), (80, 20));
1307 assert_eq!(image.rgb.len(), 80 * 20 * 3);
1308 }
1309
1310 #[test]
1312 fn program_monograms_center_the_visible_ink() {
1313 let ink = |image: &Image, under: &Image| {
1314 let mut edges = (usize::MAX, 0, usize::MAX, 0);
1315 let pixels = image.rgb.as_chunks::<3>().0;
1316 let grounds = under.rgb.as_chunks::<3>().0;
1317 for (at, (pixel, background)) in pixels.iter().zip(grounds).enumerate() {
1318 if pixel[0].abs_diff(background[0]) >= INK {
1319 let (x, y) = (at % image.width, at / image.width);
1320 edges = (
1321 edges.0.min(x),
1322 edges.1.max(x),
1323 edges.2.min(y),
1324 edges.3.max(y),
1325 );
1326 }
1327 }
1328 assert!(edges.0 <= edges.1 && edges.2 <= edges.3, "no visible ink");
1329 edges
1330 };
1331 for (width, line) in [(10, 20), (17, 36), (21, 46)] {
1332 for row in [line, line + 11] {
1333 let mut r = SoftwareRasterizer::new(width, row)
1334 .unwrap()
1335 .with_type_row(line);
1336 for (color, ground) in [
1337 (Rgb(255, 255, 255), Rgb(0, 0, 0)),
1338 (Rgb(0, 0, 0), Rgb(255, 255, 255)),
1339 ] {
1340 let mut grid = Grid::new(
1341 6,
1342 2,
1343 Style {
1344 bg: ground,
1345 ..Style::default()
1346 },
1347 );
1348 let blank = r.row(&grid, 1);
1349 for size in [0.43, 0.7, 0.86] {
1350 let bounds = Bounds::cells(2.17, 1.0 + (1.0 - size) / 2.0, 2.0, size);
1351 grid.paint.push(Paint::Icon {
1352 bounds,
1353 icon: Icon::Program,
1354 color,
1355 });
1356 let badge = r.row(&grid, 1);
1357 let (left, right, top, bottom) = ink(&badge, &blank);
1358 for letter in ['C', 'I', 'J', 'W', 'Ȉ'] {
1359 grid.paint[0] = Paint::Monogram {
1360 bounds,
1361 color,
1362 letter,
1363 ground,
1364 };
1365 let (l, r, t, b) = ink(&r.row(&grid, 1), &badge);
1366 let horizontal =
1367 (l as isize - left as isize, right as isize - r as isize);
1368 let vertical =
1369 (t as isize - top as isize, bottom as isize - b as isize);
1370 assert!(
1371 horizontal.0 >= 0
1372 && horizontal.1 >= 0
1373 && vertical.0 >= 0
1374 && vertical.1 >= 0
1375 && horizontal.0.abs_diff(horizontal.1) <= 1
1376 && vertical.0.abs_diff(vertical.1) <= 1,
1377 "{letter} at {width}×{line} in a {row}px row ({size}): {horizontal:?} across, {vertical:?} down"
1378 );
1379 }
1380 grid.paint.clear();
1381 }
1382 }
1383 }
1384 }
1385 }
1386
1387 #[test]
1388 fn han_characters_are_drawn_in_the_cells() {
1389 let Some(mut r) = rasterizer() else { return };
1390 let fonts = system_fonts();
1391 let has_han = fonts.faces().any(|face| {
1392 let name = &face.families[0].0;
1393 CJK_FONTS.iter().any(|font| font == name)
1394 });
1395 if !has_han {
1396 return;
1397 }
1398 let mut grid = Grid::new(4, 1, style());
1399 grid.put_str(0, 0, "中", style(), 4);
1400 let image = r.row(&grid, 0);
1401 assert!(lit(&image, 0, 10) > 10);
1402 }
1403
1404 #[test]
1405 fn a_wide_glyph_keeps_its_right_half() {
1406 let Some(mut r) = rasterizer() else { return };
1407 let mut grid = Grid::new(4, 1, style());
1408 grid.put_str(1, 0, "MM", style(), 4);
1409 let image = r.row(&grid, 0);
1410 assert!(lit(&image, 1, 10) > 10);
1411 assert!(
1412 lit(&image, 2, 10) > 10,
1413 "the next cell's colour didn't cover it"
1414 );
1415 }
1416
1417 #[test]
1418 fn glyphs_land_in_their_own_cells() {
1419 let Some(mut r) = rasterizer() else { return };
1420 let mut grid = Grid::new(4, 1, style());
1421 grid.put_str(2, 0, "M", style(), 4);
1422 let image = r.row(&grid, 0);
1423 assert_eq!(lit(&image, 0, 10), 0);
1424 assert!(lit(&image, 2, 10) > 10, "M drew nothing");
1425 assert_eq!(lit(&image, 3, 10), 0, "M spilled into the next cell");
1426 }
1427
1428 #[test]
1429 fn the_caret_is_a_thin_line() {
1430 let Some(mut r) = rasterizer() else { return };
1431 let mut grid = Grid::new(3, 1, style());
1432 grid.cursor = Some((1, 0));
1433 let image = r.row(&grid, 0);
1434 let at = |x: usize| image.rgb[(10 * image.width + x) * 3];
1435 assert_eq!(at(10), 250);
1436 assert_eq!(at(15), 10);
1437 grid.caret = Some(Bounds::cells(1.5, 0.0, 0.0, 1.0));
1438 let image = r.row(&grid, 0);
1439 let at = |x: usize| image.rgb[(10 * image.width + x) * 3];
1440 assert_eq!(at(10), 10, "the exact caret replaces the cell one");
1441 assert_eq!(at(15), 250);
1442 }
1443
1444 #[test]
1445 fn labels_draw_without_their_cell_glyphs() {
1446 let Some(mut r) = rasterizer() else { return };
1447 let mut grid = Grid::new(20, 1, style());
1448 grid.label(1, 0, "Illi", style(), 20);
1449 assert!(grid.cell(1, 0).style.painted);
1450 let with_paint = r.row(&grid, 0);
1451 let lit_right = (0..20)
1453 .flat_map(|y| (40..200).map(move |x| (x, y)))
1454 .any(|(x, y)| with_paint.rgb[(y * with_paint.width + x) * 3] > 128);
1455 assert!(!lit_right, "drew past the narrow label");
1456 }
1457
1458 #[test]
1463 fn words_are_thirteen_points_in_a_terminal_set_to_fourteen() {
1464 use crate::measure::Measure as _;
1465 let Some(mut r) = SoftwareRasterizer::new(17, 37) else {
1466 return;
1467 };
1468 let mut grid = Grid::new(8, 1, style());
1469 grid.label(1, 0, "H", style(), 8);
1470 let image = r.row(&grid, 0);
1471 let inked: Vec<usize> = (0..image.height)
1472 .filter(|y| (0..image.width).any(|x| image.rgb[(y * image.width + x) * 3] > 128))
1473 .collect();
1474 let (top, bottom) = (inked[0], inked[inked.len() - 1]);
1475 let tall = bottom - top + 1;
1476 assert!((18..=20).contains(&tall), "a capital is {tall} px tall");
1477 let (over, under) = (top, image.height - 1 - bottom);
1478 assert!(
1479 over.abs_diff(under) <= 2,
1480 "{over} px over it, {under} under"
1481 );
1482 let wide = crate::measure::FontMeasure::new(17, 37).width("H", Font::default()) * 17.0;
1484 assert!((17.0..21.0).contains(&wide), "an H is {wide} px wide");
1485 }
1486
1487 #[test]
1492 fn a_taller_row_is_air_round_what_stands_in_it() {
1493 use crate::measure::Measure as _;
1494 let Some(r) = SoftwareRasterizer::new(17, 52) else {
1495 return;
1496 };
1497 let mut r = r.with_type_row(37);
1498 let mut grid = Grid::new(8, 1, style());
1499 grid.label(1, 0, "H", style(), 8);
1500 let image = r.row(&grid, 0);
1501 assert_eq!(image.height, 52);
1502 let inked: Vec<usize> = (0..image.height)
1503 .filter(|y| (0..image.width).any(|x| image.rgb[(y * image.width + x) * 3] > 128))
1504 .collect();
1505 let (top, bottom) = (inked[0], inked[inked.len() - 1]);
1506 let tall = bottom - top + 1;
1507 assert!(
1508 (18..=20).contains(&tall),
1509 "a capital is still {tall} px tall"
1510 );
1511 let (over, under) = (top, image.height - 1 - bottom);
1512 assert!(
1513 over.abs_diff(under) <= 2,
1514 "{over} px over it, {under} under"
1515 );
1516 let measure = crate::measure::FontMeasure::new(17, 52).with_type_row(37);
1517 let wide = measure.width("H", Font::default()) * 17.0;
1518 assert!((17.0..21.0).contains(&wide), "and as wide: {wide} px");
1519 let mut grid = Grid::new(8, 1, style());
1523 let chip = crate::paint::Bounds::cells(1.0, 0.1875, 4.0, 0.625);
1524 grid.panel(chip, 20, Some(Rgb(255, 0, 0)), None);
1525 let image = r.row(&grid, 0);
1526 let red: Vec<usize> = (0..image.height)
1527 .filter(|y| {
1528 let at = (y * image.width + 51) * 3;
1529 image.rgb[at] > 200 && image.rgb[at + 1] < 60
1530 })
1531 .collect();
1532 assert!(
1533 (22..=25).contains(&red.len()),
1534 "the badge is {} px tall",
1535 red.len()
1536 );
1537 let (over, under) = (red[0], 51 - red[red.len() - 1]);
1538 assert!(
1539 over.abs_diff(under) <= 2,
1540 "{over} px over it, {under} under"
1541 );
1542 let mut grid = Grid::new(4, 1, style());
1544 grid.put_str(1, 0, "│", style(), 4);
1545 let image = r.row(&grid, 0);
1546 let inked = (0..image.height)
1547 .filter(|y| (17..34).any(|x| image.rgb[(y * image.width + x) * 3] > 100))
1548 .count();
1549 assert!(inked >= 50, "the side is {inked} px of the row's 52");
1550 }
1551
1552 #[test]
1556 fn a_control_is_one_height_on_a_taller_row() {
1557 let Some(r) = SoftwareRasterizer::new(17, 52) else {
1558 return;
1559 };
1560 let mut r = r.with_type_row(37);
1561 for share in [0.89, 0.92, 0.98] {
1564 let mut grid = Grid::new(8, 1, style());
1565 let inset = (1.0 - share) / 2.0;
1566 let field = crate::paint::Bounds::cells(1.0, inset, 4.0, share);
1567 grid.panel(field, 20, Some(Rgb(255, 0, 0)), None);
1568 let image = r.row(&grid, 0);
1569 let red: Vec<usize> = (0..image.height)
1570 .filter(|y| {
1571 let at = (y * image.width + 51) * 3;
1572 image.rgb[at] > 200 && image.rgb[at + 1] < 60
1573 })
1574 .collect();
1575 assert!(
1576 (39..=42).contains(&red.len()),
1577 "a box of {share} is {} px tall",
1578 red.len()
1579 );
1580 let (over, under) = (red[0], 51 - red[red.len() - 1]);
1581 assert!(over.abs_diff(under) <= 2, "{over} over, {under} under");
1582 }
1583 assert_eq!(stood(4, 57, 36.0, 36.0), (2.25, 57.0 * 36.0 / 64.0));
1585 let (top, chip) = stood(8, 48, 52.0, 37.0);
1588 assert!((chip - 52.0 * 0.714).abs() < 0.01, "{chip}");
1589 assert!(
1590 (top + chip / 2.0 - 26.0).abs() < 0.01,
1591 "in the row's middle: {top}"
1592 );
1593 let (_, mark) = stood(12, 40, 52.0, 37.0);
1595 assert!((mark - 40.0 * 37.0 / 64.0).abs() < 0.01, "{mark}");
1596 let (top, tall) = stood(0, 60, 40.0, 37.0);
1598 assert!(top >= 0.0 && tall <= 60.0 * 40.0 / 64.0, "{top} {tall}");
1599 }
1600
1601 #[test]
1605 fn a_spinner_is_a_faint_ring_with_a_quarter_of_it_in_full_colour() {
1606 let Some(r) = SoftwareRasterizer::new(17, 50) else {
1607 return;
1608 };
1609 let mut r = r.with_type_row(37);
1610 let black = Style {
1611 bg: Rgb(0, 0, 0),
1612 ..style()
1613 };
1614 let side = 0.86 * 37.0;
1615 let (left, top) = (17.0, (50.0 - side) / 2.0);
1616 let ring = 3.0 / 24.0;
1617 let mut drawn = |turn: Option<u8>| {
1620 let mut grid = Grid::new(6, 1, black);
1621 grid.turn = turn;
1622 grid.spinner(1.0, 0, 0.86, Rgb(0, 0, 200), black);
1623 let image = r.row(&grid, 0);
1624 assert!(image.rgb.chunks(3).all(|p| p[0] == 0), "only its colour");
1625 move |u: f32, v: f32| {
1626 let (x, y) = ((left + u * side) as usize, (top + v * side) as usize);
1627 image.rgb[(y * image.width + x) * 3 + 2]
1628 }
1629 };
1630 let at = drawn(Some(0));
1633 assert!(
1634 at(1.0 - ring, 0.5) > 150,
1635 "the arc: {}",
1636 at(1.0 - ring, 0.5)
1637 );
1638 assert!(
1639 (25..=70).contains(&at(ring, 0.5)),
1640 "faint: {}",
1641 at(ring, 0.5)
1642 );
1643 assert!((25..=70).contains(&at(0.5, 1.0 - ring)), "and at the foot");
1644 assert_eq!(at(0.5, 0.5), 0, "nothing in its middle");
1645 let at = drawn(Some(5));
1647 assert!(at(ring, 0.5) > 150);
1648 assert!(at(1.0 - ring, 0.5) < 70);
1649 let at = drawn(None);
1651 assert!(at(0.5, 0.5) > 150);
1652 assert_eq!(at(ring, 0.5), 0);
1653 }
1654
1655 #[test]
1656 fn a_button_on_a_rows_wash_stands_inside_it() {
1657 let Some(r) = SoftwareRasterizer::new(17, 50) else {
1658 return;
1659 };
1660 let mut r = r.with_type_row(36);
1661 let mut grid = Grid::new(12, 1, style());
1662 grid.roomy = true;
1663 grid.row_air = 139;
1664 let wash = crate::paint::Bounds::cells(0.4, 0.06, 11.2, 0.88);
1666 grid.panel(wash, 12, Some(Rgb(0, 0, 255)), None);
1667 grid.row_button((6, 0), " ", "", Rgb(255, 0, 0), style());
1668 let image = r.row(&grid, 0);
1669 let rows = |x: usize, red: bool| -> Vec<usize> {
1670 (0..image.height)
1671 .filter(|y| {
1672 let at = (y * image.width + x) * 3;
1673 let (r, b) = (image.rgb[at], image.rgb[at + 2]);
1674 if red {
1675 r > 200 && b < 60
1676 } else {
1677 b > 200 && r < 60
1678 }
1679 })
1680 .collect()
1681 };
1682 let (button, round) = (rows(136, true), rows(136, false));
1684 assert!(
1688 (30..=33).contains(&button.len()),
1689 "{} px of button",
1690 button.len()
1691 );
1692 let over = round.iter().filter(|y| **y < button[0]).count();
1695 let under = round.len() - over;
1696 assert!(
1697 (4..=6).contains(&over) && (2..=4).contains(&under) && over >= under,
1698 "{over} px of wash over the button, {under} under"
1699 );
1700 let tight = grid.paint.iter().any(|p| {
1702 matches!(
1703 p,
1704 Paint::Panel {
1705 inset: true,
1706 radius: 17,
1707 ..
1708 }
1709 )
1710 });
1711 assert!(tight, "17 per cent of the line, where a button's are 22");
1712 assert!((38..=40).contains(&rows(40, false).len()));
1714 assert_eq!(inset(4, 56, 36.0, 36.0), stood(4, 56, 36.0, 36.0));
1716 grid.paint.clear();
1717 grid.roomy = false;
1718 grid.row_button((6, 0), " ", "", Rgb(255, 0, 0), style());
1719 let plain = grid
1720 .paint
1721 .iter()
1722 .any(|p| matches!(p, Paint::Panel { inset: true, .. }));
1723 assert!(!plain, "not inset where a row has no room");
1724 }
1725
1726 #[test]
1730 fn a_row_buttons_words_stand_in_its_middle_tails_and_all() {
1731 let Some(r) = SoftwareRasterizer::new(17, 50) else {
1732 return;
1733 };
1734 let mut r = r.with_type_row(36);
1735 let mut grid = Grid::new(16, 1, style());
1736 grid.roomy = true;
1737 grid.row_air = 139;
1738 grid.row_button((2, 0), " ", "Keep", Rgb(255, 0, 0), style());
1739 let image = r.row(&grid, 0);
1740 let at = |x: usize, y: usize| {
1741 let i = (y * image.width + x) * 3;
1742 (image.rgb[i], image.rgb[i + 1])
1743 };
1744 let button: Vec<usize> = (0..image.height).filter(|y| at(45, *y).0 > 200).collect();
1746 assert!(
1747 (30..=33).contains(&button.len()),
1748 "{} px of button",
1749 button.len()
1750 );
1751 let (top, foot) = (button[0], *button.last().unwrap());
1753 assert!(top >= 8, "{top} px over it");
1754 let [.., caps, tail, baseline] = chip_and_ink(&image, 45, (100, 170));
1757 let (over, under) = (caps - top, foot - baseline);
1758 assert!(
1759 over.abs_diff(under) <= 1 && foot - tail >= 2,
1760 "{over} px over its capitals, {under} under its baseline, {} under its tail",
1761 foot - tail
1762 );
1763 }
1764
1765 fn chip_and_ink(image: &Image, side: usize, (from, to): (usize, usize)) -> [usize; 5] {
1770 let at = |x: usize, y: usize| {
1771 let i = (y * image.width + x) * 3;
1772 (image.rgb[i], image.rgb[i + 1])
1773 };
1774 let chip: Vec<usize> = (0..image.height)
1775 .filter(|y| {
1776 let (r, g) = at(side, *y);
1777 r > 200 && g < 60
1778 })
1779 .collect();
1780 let inked = |x: usize, y: usize| {
1781 let (r, g) = at(x, y);
1782 r > 200 && g > 90
1783 };
1784 let ink: Vec<usize> = (0..image.height)
1785 .filter(|y| (from..to).any(|x| inked(x, *y)))
1786 .collect();
1787 let mut feet = HashMap::new();
1788 for x in from..to {
1789 if let Some(foot) = (0..image.height).rev().find(|y| inked(x, *y)) {
1790 *feet.entry(foot).or_insert(0) += 1;
1791 }
1792 }
1793 let baseline = feet.into_iter().max_by_key(|(_, n)| *n).unwrap().0;
1794 [
1795 chip[0],
1796 *chip.last().unwrap(),
1797 ink[0],
1798 *ink.last().unwrap(),
1799 baseline,
1800 ]
1801 }
1802
1803 #[test]
1813 fn a_buttons_words_stand_on_one_baseline_by_their_fonts_span() {
1814 let red = Rgb(255, 0, 0);
1815 for (row, line, roomy) in [(50, 36, true), (37, 37, false)] {
1816 let Some(r) = SoftwareRasterizer::new(17, row) else {
1817 return;
1818 };
1819 let mut r = r.with_type_row(line);
1820 for large in [false, true] {
1821 let mut baselines = Vec::new();
1822 for label in ["Show Source", "Accept Rewrite", "Next", "Keep", "Dismiss"] {
1823 let mut grid = Grid::new(24, 1, style());
1824 grid.roomy = roomy;
1825 let cells = " ".repeat(20);
1826 if large {
1827 grid.large_button(1, 0, &cells, label, red, style());
1828 } else {
1829 grid.button(1, 0, &cells, label, red, style());
1830 }
1831 let image = r.row(&grid, 0);
1832 let [top, foot, caps, tails, baseline] = chip_and_ink(&image, 21, (40, 330));
1833 baselines.push((label, baseline - top, foot - baseline));
1834 let (over, under) = (caps - top, foot - baseline);
1837 assert!(
1838 over.abs_diff(under) <= 1 && foot - tails >= 2,
1839 "{label} on a row of {row}: {over} px over its capitals, {under} under"
1840 );
1841 }
1842 let first = baselines[0];
1843 assert!(
1844 baselines.iter().all(|b| (b.1, b.2) == (first.1, first.2)),
1845 "one baseline on a row of {row}: {baselines:?}"
1846 );
1847 }
1848 }
1849 let Some(r) = SoftwareRasterizer::new(17, 50) else {
1851 return;
1852 };
1853 let mut r = r.with_type_row(36);
1854 for label in ["Keep", "Install", "Reject"] {
1855 for own in [false, true] {
1856 let mut grid = Grid::new(32, 1, style());
1857 grid.roomy = true;
1858 grid.row_air = 139;
1859 grid.label(1, 0, "Say what a caller", style(), 14);
1860 let cells = " ".repeat(10);
1861 if own {
1862 let from = grid.painted_so_far();
1863 grid.button(18, 0, &cells, label, red, style());
1864 grid.beside_words(from);
1865 } else {
1866 grid.row_button((18, 0), &cells, label, red, style());
1867 }
1868 let image = r.row(&grid, 0);
1869 let [.., words] = chip_and_ink(&image, 18 * 17 + 4, (17, 14 * 17));
1870 let [top, foot, .., baseline] =
1871 chip_and_ink(&image, 18 * 17 + 4, (18 * 17 + 20, 27 * 17));
1872 assert!(
1873 baseline.abs_diff(words) <= 1,
1874 "{label}: its baseline at {baseline}, the words' at {words}"
1875 );
1876 let (over, under) = (top, image.height - 1 - foot);
1879 assert!(
1880 over >= under && (own || under >= 8),
1881 "{label}: {over} px over it, {under} under"
1882 );
1883 }
1884 }
1885 }
1886
1887 #[test]
1890 fn an_emoji_in_painted_text_keeps_its_own_colours() {
1891 let Some(mut r) = rasterizer() else { return };
1892 let mask = r.text_mask("ok 🚀", Font::default());
1893 let Some(own) = &mask.own else { return };
1895 let coloured = own.iter().flatten().filter(|rgb| rgb.0 != rgb.2).count();
1896 assert!(coloured > 10, "a rocket has red and blue in it: {coloured}");
1897 let plain = r.text_mask("ok", Font::default());
1898 assert!(plain.own.is_none(), "letters have no colour of their own");
1899 let mut grid = Grid::new(12, 1, style());
1901 let dark = Style {
1902 fg: Rgb(10, 10, 10),
1903 bg: Rgb(240, 240, 240),
1904 ..Style::default()
1905 };
1906 grid.fill(Rect::new(0, 0, 12, 1), dark);
1907 grid.label(0, 0, "ok 🚀", dark, 12);
1908 let image = r.row(&grid, 0);
1909 let pixels: Vec<Rgb> = image.rgb.chunks(3).map(|p| Rgb(p[0], p[1], p[2])).collect();
1910 let tinted = |p: &&Rgb| p.0.abs_diff(p.2) > 60;
1911 assert!(pixels.iter().filter(tinted).count() > 10);
1912 }
1913
1914 #[test]
1915 fn panels_have_rounded_corners() {
1916 let Some(mut r) = rasterizer() else { return };
1917 let mut grid = Grid::new(10, 1, style());
1918 grid.panel(
1919 crate::paint::Bounds::cells(1.0, 0.0, 8.0, 1.0),
1920 40,
1921 Some(Rgb(255, 0, 0)),
1922 None,
1923 );
1924 let image = r.row(&grid, 0);
1925 let red = |x: usize, y: usize| image.rgb[(y * image.width + x) * 3];
1926 assert_eq!(red(50, 10), 255, "the middle is filled");
1927 assert_eq!(red(10, 0), 10, "the corner is cut");
1928 }
1929
1930 #[test]
1934 fn a_hairline_stands_on_whole_pixels() {
1935 let Some(mut r) = rasterizer() else { return };
1936 let mut grid = Grid::new(10, 1, style());
1937 let line = crate::paint::Bounds::cells(1.0, 1.0 / 3.0, 8.0, 0.0);
1939 grid.hairline(line, Rgb(255, 0, 0));
1940 let image = r.row(&grid, 0);
1941 let red = |y: usize| image.rgb[(y * image.width + 50) * 3];
1942 let touched: Vec<u8> = (0..image.height).map(red).filter(|r| *r > 10).collect();
1943 assert!(!touched.is_empty(), "the line is drawn");
1944 assert!(
1945 touched.iter().all(|r| *r == 255),
1946 "every row it touches in full: {touched:?}"
1947 );
1948 }
1949
1950 #[test]
1951 fn a_wash_lets_what_is_under_it_show() {
1952 let Some(mut r) = rasterizer() else { return };
1953 let mut grid = Grid::new(20, 2, style());
1954 let bounds = crate::paint::Bounds::cells(1.0, 0.0, 18.0, 2.0);
1955 grid.wash(bounds, 10, (Rgb(255, 0, 0), 64), Some(Rgb(0, 0, 255)));
1956 let image = r.row(&grid, 0);
1957 let at = |x: usize, y: usize| {
1958 let i = (y * image.width + x) * 3;
1959 (image.rgb[i], image.rgb[i + 1], image.rgb[i + 2])
1960 };
1961 let middle = at(image.width / 2, image.height - 1);
1962 assert!(middle.0 > 0 && middle.0 < 200, "a little red: {middle:?}");
1963 let edge = at(image.width / 2, 0);
1964 assert!(edge.2 > 200, "the border: {edge:?}");
1965 }
1966
1967 #[test]
1968 fn a_dashed_border_has_gaps() {
1969 let Some(mut r) = rasterizer() else { return };
1970 let mut grid = Grid::new(20, 1, style());
1971 grid.dashed_panel(
1972 crate::paint::Bounds::cells(1.0, 0.0, 18.0, 1.0),
1973 10,
1974 None,
1975 Rgb(255, 0, 0),
1976 );
1977 let image = r.row(&grid, 0);
1978 let y = 0;
1980 let reds: Vec<u8> = (30..170)
1981 .map(|x| image.rgb[(y * image.width + x) * 3])
1982 .collect();
1983 assert!(reds.iter().any(|r| *r > 200), "dashes are drawn");
1984 assert!(reds.iter().any(|r| *r < 60), "with gaps between them");
1985 }
1986
1987 #[test]
1991 fn the_emoji_font_in_the_binary_draws_in_colour_by_itself() {
1992 let mut db = fontdb::Database::new();
1993 for data in [INTER, INTER_ITALIC, MONO, MONO_ITALIC, EMOJI] {
1994 db.load_font_data(data.to_vec());
1995 }
1996 db.set_monospace_family("JetBrains Mono");
1997 db.set_sans_serif_family("Inter Variable");
1998 let mut fonts = FontSystem::new_with_locale_and_db("en-US".to_string(), db);
1999 assert!(draws_colour(&mut fonts, BUILT_IN_EMOJI));
2000 let found = find_emoji_font(&mut fonts).map(|(family, _)| family);
2001 assert_eq!(found.as_deref(), Some(BUILT_IN_EMOJI));
2002 for emoji in ["👍", "💯", "❤\u{fe0f}", "🎉", "😄", "👀", "🚀", "✅"] {
2003 assert!(
2004 set_in(&mut fonts, BUILT_IN_EMOJI, emoji).is_some(),
2005 "{emoji}"
2006 );
2007 }
2008 assert!(!draws_colour(&mut fonts, "No Such Emoji"));
2010 for emoji in ["🇹🇷", "👩\u{200d}💻", "❤\u{fe0f}", "1\u{fe0f}\u{20e3}"] {
2012 assert!(built_in_emoji_holds(emoji), "{emoji}");
2013 }
2014 assert!(
2015 !built_in_emoji_holds("🫨"),
2016 "a face from a year after the font"
2017 );
2018 assert!(!built_in_emoji_holds("ok"));
2019 let metrics = fit_font(&mut fonts, 10, 20).unwrap();
2021 let mut r = SoftwareRasterizer {
2022 fonts,
2023 emoji: Some(BUILT_IN_EMOJI.to_string()),
2024 swash: SwashCache::new(),
2025 metrics,
2026 cell: (10, 20),
2027 type_row: 20,
2028 masks: HashMap::new(),
2029 painted: HashMap::new(),
2030 text: HashMap::new(),
2031 };
2032 let mask = r.text_mask("ok 🚀 ❤\u{fe0f}", Font::default());
2033 let own = mask
2034 .own
2035 .as_ref()
2036 .expect("the emoji have colours of their own");
2037 let red = own
2038 .iter()
2039 .flatten()
2040 .filter(|rgb| rgb.0 > 150 && rgb.2 < 120);
2041 assert!(red.count() > 10, "a heart and a rocket's flame are red");
2042 }
2043
2044 #[test]
2045 fn fonts_ship_in_the_binary() {
2046 let mut r = SoftwareRasterizer::new(10, 20).unwrap();
2047 assert!(
2048 r.fonts
2049 .db()
2050 .faces()
2051 .any(|f| f.families.iter().any(|(n, _)| n.contains("Inter")))
2052 );
2053 assert!(
2054 r.text_mask("x", Font::default())
2055 .alpha
2056 .iter()
2057 .any(|a| *a > 0)
2058 );
2059 }
2060
2061 #[test]
2062 fn unknown_cell_size_refuses_pixels() {
2063 assert!(SoftwareRasterizer::new(0, 20).is_none());
2064 }
2065}