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