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}
59
60const CJK_FONTS: [&str; 9] = [
63 "PingFang SC",
64 "Hiragino Sans",
65 "Hiragino Sans GB",
66 "Songti SC",
67 "Heiti SC",
68 "Arial Unicode MS",
69 "Noto Sans CJK SC",
70 "Noto Sans CJK JP",
71 "WenQuanYi Micro Hei",
72];
73
74struct WiderFallback(PlatformFallback);
76
77impl Fallback for WiderFallback {
78 fn common_fallback(&self) -> &[&'static str] {
79 self.0.common_fallback()
80 }
81
82 fn forbidden_fallback(&self) -> &[&'static str] {
83 self.0.forbidden_fallback()
84 }
85
86 fn script_fallback(&self, script: Script, locale: &str) -> &[&'static str] {
87 match script {
88 Script::Han | Script::Hiragana | Script::Katakana => &CJK_FONTS,
89 other => self.0.script_fallback(other, locale),
90 }
91 }
92}
93
94fn system_fonts() -> fontdb::Database {
95 let mut db = fontdb::Database::new();
96 db.load_system_fonts();
97 db
98}
99
100fn drawing_fonts() -> FontSystem {
103 let mut fonts = FontSystem::new_with_locale_and_db_and_fallback(
104 "en-US".to_string(),
105 system_fonts(),
106 WiderFallback(PlatformFallback),
107 );
108 let db = fonts.db_mut();
109 db.load_font_data(INTER.to_vec());
110 db.load_font_data(INTER_ITALIC.to_vec());
111 db.load_font_data(MONO.to_vec());
112 db.load_font_data(MONO_ITALIC.to_vec());
113 db.load_font_data(EMOJI.to_vec());
114 db.set_monospace_family("JetBrains Mono");
115 db.set_sans_serif_family("Inter Variable");
116 if EMOJI_FONT.get().is_none() {
117 let found = find_emoji_font(&mut fonts);
118 EMOJI_FONT.get_or_init(|| found);
119 }
120 fonts
121}
122
123static EMOJI_FONT: std::sync::OnceLock<Option<(String, fontdb::Source)>> =
126 std::sync::OnceLock::new();
127
128const SYSTEM_EMOJI: [&str; 3] = ["Apple Color Emoji", "Noto Color Emoji", "Segoe UI Emoji"];
131const BUILT_IN_EMOJI: &str = "Twemoji Mozilla";
133
134fn set_in(fonts: &mut FontSystem, family: &str, emoji: &str) -> Option<Buffer> {
137 let mut buffer = Buffer::new(fonts, Metrics::new(32.0, 40.0));
138 buffer.set_size(None, Some(40.0));
139 let attrs = Attrs::new().family(Family::Name(family));
140 let rich = std::iter::once((emoji, attrs.clone()));
141 buffer.set_rich_text(rich, &attrs, Shaping::Advanced, None);
142 buffer.shape_until_scroll(fonts, false);
143 let from_it = |glyph: &cosmic_text::LayoutGlyph| {
144 let face = fonts.db().face(glyph.font_id);
145 glyph.glyph_id != 0
146 && face.is_some_and(|face| face.families.iter().any(|(name, _)| name == family))
147 };
148 let glyphs: Vec<&cosmic_text::LayoutGlyph> = buffer
149 .layout_runs()
150 .flat_map(|run| run.glyphs.iter())
151 .collect();
152 let whole = !glyphs.is_empty() && glyphs.into_iter().all(from_it);
153 whole.then_some(buffer)
154}
155
156pub fn built_in_emoji_holds(emoji: &str) -> bool {
160 thread_local! {
161 static FONTS: std::cell::RefCell<FontSystem> = std::cell::RefCell::new({
162 let mut db = fontdb::Database::new();
163 db.load_font_data(EMOJI.to_vec());
164 FontSystem::new_with_locale_and_db("en-US".to_string(), db)
165 });
166 }
167 FONTS.with(|fonts| {
168 let set = set_in(&mut fonts.borrow_mut(), BUILT_IN_EMOJI, emoji);
169 set.is_some_and(|buffer| {
170 let glyphs = buffer.layout_runs().flat_map(|run| run.glyphs.iter());
171 glyphs.filter(|glyph| glyph.w > 0.0).count() == 1
172 })
173 })
174}
175
176fn draws_colour(fonts: &mut FontSystem, family: &str) -> bool {
179 let Some(mut buffer) = set_in(fonts, family, "π") else {
180 return false;
181 };
182 let mut coloured = false;
183 let mut swash = SwashCache::new();
184 let white = Color::rgb(255, 255, 255);
185 buffer.draw(fonts, &mut swash, white, |_, _, _, _, color| {
186 coloured |= color.a() > 0 && (color.r(), color.g(), color.b()) != (255, 255, 255);
187 });
188 coloured
189}
190
191fn find_emoji_font(fonts: &mut FontSystem) -> Option<(String, fontdb::Source)> {
194 let built_in_only = std::env::var("CELLIX_EMOJI").is_ok_and(|choice| choice == "built-in");
197 let own = SYSTEM_EMOJI.iter().copied().filter(|_| !built_in_only);
198 for family in own.chain([BUILT_IN_EMOJI]) {
199 let source = fonts
200 .db()
201 .faces()
202 .find(|face| face.families.iter().any(|(name, _)| name == family))
203 .map(|face| face.source.clone());
204 if let Some(source) = source
205 && draws_colour(fonts, family)
206 {
207 return Some((family.to_string(), source));
208 }
209 }
210 None
211}
212
213pub(crate) fn emoji_font() -> Option<&'static (String, fontdb::Source)> {
216 if EMOJI_FONT.get().is_none() {
217 drop(drawing_fonts());
218 }
219 EMOJI_FONT.get().and_then(Option::as_ref)
220}
221
222const DARK_SHADOW: f32 = 110.0;
224const LIGHT_SHADOW: f32 = 38.0;
225pub const INTERFACE_SIZE: f32 = 0.60;
227const MAX_TEXT_MASKS: usize = 4096;
229
230pub(crate) const INTER: &[u8] = include_bytes!("../fonts/InterVariable.ttf");
231pub(crate) const INTER_ITALIC: &[u8] = include_bytes!("../fonts/InterVariable-Italic.ttf");
232pub(crate) const MONO: &[u8] = include_bytes!("../fonts/JetBrainsMonoVariable.ttf");
233pub(crate) const MONO_ITALIC: &[u8] = include_bytes!("../fonts/JetBrainsMonoVariable-Italic.ttf");
234pub(crate) const EMOJI: &[u8] = include_bytes!("../fonts/TwemojiMozilla.ttf");
236
237pub(crate) fn text_pixels(row_height: usize, font: Font) -> f32 {
239 row_height as f32 * INTERFACE_SIZE * font.size as f32 / 100.0
240}
241
242pub struct SoftwareRasterizer {
245 fonts: FontSystem,
246 emoji: Option<String>,
248 swash: SwashCache,
249 metrics: Metrics,
250 cell: (usize, usize),
251 masks: HashMap<GlyphKey, Mask>,
252 painted: HashMap<GlyphKey, Painted>,
254 text: HashMap<TextKey, Rc<TextMask>>,
255}
256
257impl SoftwareRasterizer {
258 pub fn new(cell_width: usize, cell_height: usize) -> Option<Self> {
261 if cell_width == 0 || cell_height == 0 {
262 return None;
263 }
264 let mut fonts = drawing_fonts();
265 let metrics = fit_font(&mut fonts, cell_width, cell_height)?;
266 let emoji = emoji_font().map(|(family, _)| family.clone());
267 Some(Self {
268 fonts,
269 emoji,
270 swash: SwashCache::new(),
271 metrics,
272 cell: (cell_width, cell_height),
273 masks: HashMap::new(),
274 painted: HashMap::new(),
275 text: HashMap::new(),
276 })
277 }
278
279 fn mask(&mut self, key: &GlyphKey) -> Mask {
280 if let Some(mask) = self.masks.get(key) {
281 return mask.clone();
282 }
283 let (width, height) = (self.cell.0 * 2, self.cell.1);
284 let mut buffer = Buffer::new(&mut self.fonts, self.metrics);
285 buffer.set_size(Some(width as f32 * 2.0), Some(height as f32));
286 let emoji = self.emoji.clone().filter(|_| emoji_letter(&key.symbol));
290 let family = if let Some(emoji) = &emoji {
291 Family::Name(emoji)
292 } else if UnicodeWidthStr::width(key.symbol.as_str()) > 1 {
293 Family::SansSerif
294 } else {
295 Family::Monospace
296 };
297 let mut attrs = Attrs::new().family(family);
298 if key.bold {
299 attrs = attrs.weight(Weight::BOLD);
300 }
301 if key.italic {
302 attrs = attrs.style(FontStyle::Italic);
303 }
304 let rich = std::iter::once((key.symbol.as_str(), attrs.clone()));
305 buffer.set_rich_text(rich, &attrs, Shaping::Advanced, None);
306 buffer.shape_until_scroll(&mut self.fonts, false);
307 let mut pixels = Vec::new();
308 let mut coloured = Vec::new();
309 let white = Color::rgb(255, 255, 255);
310 buffer.draw(
311 &mut self.fonts,
312 &mut self.swash,
313 white,
314 |x, y, w, h, color| {
315 if color.a() == 0 {
316 return;
317 }
318 for py in y..y + h as i32 {
319 for px in x..x + w as i32 {
320 if px >= 0 && py >= 0 && (px as usize) < width && (py as usize) < height {
321 pixels.push((px as u16, py as u16, color.a()));
322 let rgb = Rgb(color.r(), color.g(), color.b());
323 coloured.push((px as u16, py as u16, rgb, color.a()));
324 }
325 }
326 }
327 },
328 );
329 if coloured
331 .iter()
332 .any(|(_, _, rgb, _)| *rgb != Rgb(255, 255, 255))
333 {
334 self.painted.insert(key.clone(), Rc::new(coloured));
335 }
336 let mask = Rc::new(pixels);
337 self.masks.insert(key.clone(), mask.clone());
338 mask
339 }
340
341 fn text_mask(&mut self, text: &str, font: Font) -> Rc<TextMask> {
343 let key = TextKey {
344 text: text.to_string(),
345 font,
346 };
347 if let Some(mask) = self.text.get(&key) {
348 return mask.clone();
349 }
350 if self.text.len() >= MAX_TEXT_MASKS {
351 self.text.clear();
352 }
353 let px = text_pixels(self.cell.1, font);
354 let height = self.cell.1.max((px * 1.45).ceil() as usize);
355 let mut buffer = Buffer::new(&mut self.fonts, Metrics::new(px, height as f32));
356 buffer.set_size(None, Some(height as f32));
357 let emoji = self.emoji.clone();
358 let rich = runs(text, font, emoji.as_deref());
359 buffer.set_rich_text(rich, &attrs(font), Shaping::Advanced, None);
360 buffer.shape_until_scroll(&mut self.fonts, false);
361 let width = buffer
362 .layout_runs()
363 .next()
364 .map_or(0.0, |run| run.line_w)
365 .ceil() as usize
366 + 2;
367 let mut alpha = vec![0; width * height];
368 let white = Rgb(255, 255, 255);
371 let mut drawn = vec![white; width * height];
372 let mut tinted = false;
373 buffer.draw(
374 &mut self.fonts,
375 &mut self.swash,
376 Color::rgb(255, 255, 255),
377 |x, y, w, h, color| {
378 let rgb = Rgb(color.r(), color.g(), color.b());
379 tinted |= color.a() > 0 && rgb != white;
380 for at in spots((width, height), (x, y), (w, h)) {
381 if color.a() >= alpha[at] {
382 drawn[at] = rgb;
383 }
384 alpha[at] = alpha[at].max(color.a());
385 }
386 },
387 );
388 let own = tinted.then(|| {
391 let black = Rgb(0, 0, 0);
392 let mut own = vec![None; width * height];
393 buffer.draw(
394 &mut self.fonts,
395 &mut self.swash,
396 Color::rgb(0, 0, 0),
397 |x, y, w, h, color| {
398 let rgb = Rgb(color.r(), color.g(), color.b());
399 for at in spots((width, height), (x, y), (w, h)) {
400 if color.a() > 0 && (rgb != black || drawn[at] != white) {
401 own[at] = Some(drawn[at]);
402 }
403 }
404 },
405 );
406 own
407 });
408 let mask = Rc::new(TextMask {
409 width,
410 height,
411 alpha,
412 own,
413 });
414 self.text.insert(key, mask.clone());
415 mask
416 }
417
418 fn draw_paint(&mut self, target: &mut Target, paint: &Paint) {
419 let (cw, ch) = (self.cell.0 as f32, self.cell.1 as f32);
420 let scale = |v: i32, cell: f32| v as f32 * cell / UNIT as f32;
421 match paint {
422 Paint::Panel {
423 bounds,
424 radius,
425 fill,
426 border,
427 shadow,
428 dashed,
429 } => {
430 let shape = Shape {
431 x: scale(bounds.x, cw),
432 y: scale(bounds.y, ch),
433 w: scale(bounds.w, cw),
434 h: scale(bounds.h, ch),
435 radius: *radius as f32 * ch / 100.0,
436 };
437 target.panel(shape, (*fill, *border), *shadow, *dashed, ch);
438 }
439 Paint::Wash {
440 bounds,
441 radius,
442 color,
443 alpha,
444 border,
445 } => {
446 let shape = Shape {
447 x: scale(bounds.x, cw),
448 y: scale(bounds.y, ch),
449 w: scale(bounds.w, cw),
450 h: scale(bounds.h, ch),
451 radius: *radius as f32 * ch / 100.0,
452 };
453 target.wash(shape, (*color, *alpha), *border, ch);
454 }
455 Paint::Hairline { bounds, color } => {
456 let thickness = (ch / 24.0).ceil().max(1.0);
457 let shape = Shape {
458 x: scale(bounds.x, cw),
459 y: scale(bounds.y, ch),
460 w: scale(bounds.w, cw).max(thickness),
461 h: scale(bounds.h, ch).max(thickness),
462 radius: 0.0,
463 };
464 target.panel(shape, (Some(*color), None), false, false, ch);
465 }
466 Paint::Text {
467 x,
468 y,
469 max_width,
470 text,
471 color,
472 font,
473 align_right,
474 centred,
475 underline,
476 } => {
477 let mask = self.text_mask(text, *font);
478 let mut left = scale(*x, cw).round() as i32;
479 if *align_right {
480 left -= mask.width as i32;
481 } else if *centred {
482 left -= mask.width as i32 / 2;
483 }
484 let lift = (mask.height as i32 - ch as i32) / 2;
486 let top = scale(*y, ch).round() as i32 - lift;
487 let limit = scale(*max_width, cw).max(0.0) as usize;
488 target.blit(&mask, left, top, limit, *color);
489 if *underline {
490 let thickness = (ch / 24.0).ceil().max(1.0);
491 let shape = Shape {
492 x: left as f32,
493 y: scale(*y, ch) + ch * 0.78,
494 w: mask.width.saturating_sub(2).min(limit) as f32,
495 h: thickness,
496 radius: 0.0,
497 };
498 target.panel(shape, (Some(*color), None), false, false, ch);
499 }
500 }
501 Paint::Icon {
502 bounds,
503 icon,
504 color,
505 } => {
506 let side = scale(bounds.h, ch);
507 let left = scale(bounds.x, cw);
508 let top = scale(bounds.y, ch);
509 target.icon(*icon, left, top, side, *color);
510 }
511 Paint::Corners {
512 bounds,
513 radius,
514 color,
515 which,
516 } => {
517 let shape = Shape {
518 x: scale(bounds.x, cw),
519 y: scale(bounds.y, ch),
520 w: scale(bounds.w, cw),
521 h: scale(bounds.h, ch),
522 radius: *radius as f32 * ch / 100.0,
523 };
524 target.corners(&shape, *color, *which);
525 }
526 Paint::Image {
527 bounds,
528 clip,
529 bitmap,
530 color,
531 } => {
532 let shape = Shape {
533 x: scale(bounds.x, cw),
534 y: scale(bounds.y, ch),
535 w: scale(bounds.w, cw),
536 h: scale(bounds.h, ch),
537 radius: 0.0,
538 };
539 let across = (
540 scale(clip.x, cw) as i32,
541 scale(clip.x + clip.w, cw).ceil() as i32,
542 );
543 let down = (
544 scale(clip.y, ch) as i32,
545 scale(clip.y + clip.h, ch).ceil() as i32,
546 );
547 target.image(&shape, (across, down), bitmap, *color);
548 }
549 Paint::Strips { bounds, strips } => {
550 let (left, top) = (scale(bounds.x, cw), scale(bounds.y, ch));
551 let (width, height) = (scale(bounds.w, cw), scale(bounds.h, ch));
552 let thickness = (ch / 24.0).ceil().max(1.0);
553 for strip in strips {
554 let shape = Shape {
555 x: left + strip.x as f32 * width / 256.0,
556 y: top + strip.y as f32 * height / 256.0,
557 w: (strip.w as f32 * width / 256.0).max(1.0),
558 h: thickness,
559 radius: 0.0,
560 };
561 target.panel(shape, (Some(strip.color), None), false, false, ch);
562 }
563 }
564 }
565 }
566}
567
568fn spots(
570 (width, height): (usize, usize),
571 (x, y): (i32, i32),
572 (w, h): (u32, u32),
573) -> impl Iterator<Item = usize> {
574 let across = x.max(0) as usize..((x + w as i32).max(0) as usize).min(width);
575 let down = y.max(0) as usize..((y + h as i32).max(0) as usize).min(height);
576 down.flat_map(move |py| across.clone().map(move |px| py * width + px))
577}
578
579fn caret_bounds(grid: &Grid) -> Option<Bounds> {
581 grid.caret.or_else(|| {
582 let (x, y) = grid.cursor?;
583 Some(Bounds::cells(x as f32, y as f32 + 0.08, 0.0, 0.84))
584 })
585}
586
587fn caret_color(grid: &Grid) -> Rgb {
588 let Some((x, y)) = grid.cursor else {
589 return Rgb(255, 255, 255);
590 };
591 grid.cell(x.min(grid.width().saturating_sub(1)), y).style.fg
592}
593
594struct Shape {
595 x: f32,
596 y: f32,
597 w: f32,
598 h: f32,
599 radius: f32,
600}
601
602fn rounded_distance(shape: &Shape, x: f32, y: f32) -> f32 {
604 let (cx, cy) = (shape.x + shape.w / 2.0, shape.y + shape.h / 2.0);
605 let qx = (x - cx).abs() - shape.w / 2.0 + shape.radius;
606 let qy = (y - cy).abs() - shape.h / 2.0 + shape.radius;
607 let outside = (qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt();
608 outside + qx.max(qy).min(0.0) - shape.radius
609}
610
611struct Target<'a> {
613 rgb: &'a mut [u8],
614 width: usize,
615 height: usize,
616 top: i32,
617}
618
619impl Target<'_> {
620 fn corners(&mut self, s: &Shape, color: Rgb, which: u8) {
621 let r = s.radius;
622 let spots = [
623 (TOP_LEFT, s.x, s.y, s.x + r, s.y + r),
624 (TOP_RIGHT, s.x + s.w - r, s.y, s.x + s.w - r, s.y + r),
625 (
626 BOTTOM_RIGHT,
627 s.x + s.w - r,
628 s.y + s.h - r,
629 s.x + s.w - r,
630 s.y + s.h - r,
631 ),
632 (BOTTOM_LEFT, s.x, s.y + s.h - r, s.x + r, s.y + s.h - r),
633 ];
634 for (flag, left, top, cx, cy) in spots {
635 if which & flag == 0 {
636 continue;
637 }
638 for y in top.floor() as i32..(top + r).ceil() as i32 {
639 for x in left.floor() as i32..(left + r).ceil() as i32 {
640 let d = ((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt();
641 let outside = (d - r + 0.5).clamp(0.0, 1.0);
642 self.blend(x, y, color, (outside * 255.0) as u8);
643 }
644 }
645 }
646 }
647
648 fn blend(&mut self, x: i32, y: i32, color: Rgb, alpha: u8) {
649 let row = y - self.top;
650 if alpha == 0 || x < 0 || row < 0 || x as usize >= self.width || row as usize >= self.height
651 {
652 return;
653 }
654 let at = (row as usize * self.width + x as usize) * 3;
655 self.rgb[at] = blend(color.0, self.rgb[at], alpha);
656 self.rgb[at + 1] = blend(color.1, self.rgb[at + 1], alpha);
657 self.rgb[at + 2] = blend(color.2, self.rgb[at + 2], alpha);
658 }
659
660 fn panel(
661 &mut self,
662 s: Shape,
663 (fill, border): (Option<Rgb>, Option<Rgb>),
664 shadow: bool,
665 dashed: bool,
666 row: f32,
667 ) {
668 let dash = (row / 4.0).max(2.0);
671 let on_dash = |x: f32, y: f32| {
672 let along_top = x > s.x + s.radius && x < s.x + s.w - s.radius;
673 let run = if along_top { x - s.x } else { y - s.y };
674 (run / dash).floor() as i64 % 2 == 0
675 };
676 let reach = if shadow { row * 0.35 } else { 1.0 };
678 let (x0, x1) = (
679 (s.x - reach).floor() as i32,
680 (s.x + s.w + reach).ceil() as i32,
681 );
682 let above = if shadow { 1.0 } else { reach };
683 let y0 = ((s.y - above).floor() as i32).max(self.top);
684 let y1 = ((s.y + s.h + reach).ceil() as i32).min(self.top + self.height as i32);
685 let stroke = (row / 30.0).max(1.0);
686 for y in y0..y1 {
687 for x in x0..x1 {
688 let d = rounded_distance(&s, x as f32 + 0.5, y as f32 + 0.5);
689 if shadow && d > 0.0 && y as f32 + 0.5 > s.y + s.radius {
690 let fade = (1.0 - d / reach).clamp(0.0, 1.0);
691 let light = fill.is_some_and(|f| f.0 > 180);
693 let depth = if light { LIGHT_SHADOW } else { DARK_SHADOW };
694 self.blend(x, y, Rgb(0, 0, 0), (fade * fade * depth) as u8);
695 }
696 let inside = ((0.5 - d) * 255.0).clamp(0.0, 255.0) as u8;
697 if let Some(color) = fill {
698 self.blend(x, y, color, inside);
699 }
700 if let Some(color) = border
701 && (!dashed || on_dash(x as f32 + 0.5, y as f32 + 0.5))
702 {
703 let edge = ((0.5 - (d + stroke / 2.0).abs() + stroke / 2.0) * 255.0)
704 .clamp(0.0, 255.0) as u8;
705 self.blend(x, y, color, edge);
706 }
707 }
708 }
709 }
710
711 fn wash(&mut self, s: Shape, (color, alpha): (Rgb, u8), border: Option<Rgb>, row: f32) {
713 let (x0, x1) = (s.x.floor() as i32 - 1, (s.x + s.w).ceil() as i32 + 1);
714 let y0 = (s.y.floor() as i32 - 1).max(self.top);
715 let y1 = ((s.y + s.h).ceil() as i32 + 1).min(self.top + self.height as i32);
716 let stroke = (row / 15.0).max(2.0);
717 for y in y0..y1 {
718 for x in x0..x1 {
719 let d = rounded_distance(&s, x as f32 + 0.5, y as f32 + 0.5);
720 let inside = (0.5 - d).clamp(0.0, 1.0);
721 self.blend(x, y, color, (inside * alpha as f32) as u8);
722 if let Some(edge_color) = border {
723 let along = (0.5 - (d + stroke / 2.0).abs() + stroke / 2.0).clamp(0.0, 1.0);
725 self.blend(x, y, edge_color, (along * 255.0) as u8);
726 }
727 }
728 }
729 }
730
731 fn blit(&mut self, mask: &TextMask, left: i32, top: i32, limit: usize, color: Rgb) {
732 let from = (self.top - top).max(0) as usize;
733 let to = ((self.top + self.height as i32 - top).max(0) as usize).min(mask.height);
734 for y in from..to {
735 for x in 0..mask.width.min(limit) {
736 let at = y * mask.width + x;
737 let ink = mask.own.as_ref().and_then(|own| own[at]).unwrap_or(color);
738 self.blend(left + x as i32, top + y as i32, ink, mask.alpha[at]);
739 }
740 }
741 }
742
743 fn image(&mut self, s: &Shape, clip: ((i32, i32), (i32, i32)), bitmap: &Bitmap, color: Rgb) {
745 let (width, height) = (bitmap.width as usize, bitmap.height as usize);
746 if width == 0 || height == 0 || s.w <= 0.0 || s.h <= 0.0 {
747 return;
748 }
749 let channels = match bitmap.kind {
750 Pixels::Coverage => 1,
751 Pixels::Rgba => 4,
752 };
753 let at = |x: usize, y: usize, c: usize| -> f32 {
754 let index = (y.min(height - 1) * width + x.min(width - 1)) * channels + c;
755 bitmap.pixels.get(index).copied().unwrap_or(0) as f32
756 };
757 let sample = |u: f32, v: f32, c: usize| -> f32 {
758 let (fx, fy) = (u.max(0.0), v.max(0.0));
759 let (x, y) = (fx as usize, fy as usize);
760 let (dx, dy) = (fx - x as f32, fy - y as f32);
761 let top = at(x, y, c) * (1.0 - dx) + at(x + 1, y, c) * dx;
762 let bottom = at(x, y + 1, c) * (1.0 - dx) + at(x + 1, y + 1, c) * dx;
763 top * (1.0 - dy) + bottom * dy
764 };
765 let ((left, right), (top, bottom)) = clip;
766 let y0 = (s.y.floor() as i32).max(self.top).max(top);
767 let y1 = ((s.y + s.h).ceil() as i32)
768 .min(self.top + self.height as i32)
769 .min(bottom);
770 let x0 = (s.x.floor() as i32).max(0).max(left);
771 let x1 = ((s.x + s.w).ceil() as i32)
772 .min(self.width as i32)
773 .min(right);
774 let (ax, ay) = (width as f32 / s.w, height as f32 / s.h);
775 if bitmap.kind == Pixels::Rgba && (ax - 1.0).abs() < 0.002 && (ay - 1.0).abs() < 0.002 {
777 let (left, top) = (s.x.round() as i32, s.y.round() as i32);
778 for y in y0..y1 {
779 for x in x0..x1 {
780 let (u, v) = (x - left, y - top);
781 if u < 0 || v < 0 || u as usize >= width || v as usize >= height {
782 continue;
783 }
784 let at = (v as usize * width + u as usize) * 4;
785 if let Some(p) = bitmap.pixels.get(at..at + 4) {
786 self.blend(x, y, Rgb(p[0], p[1], p[2]), p[3]);
787 }
788 }
789 }
790 return;
791 }
792 for y in y0..y1 {
793 for x in x0..x1 {
794 let u = (x as f32 + 0.5 - s.x) * ax - 0.5;
795 let v = (y as f32 + 0.5 - s.y) * ay - 0.5;
796 match bitmap.kind {
797 Pixels::Coverage => self.blend(x, y, color, sample(u, v, 0) as u8),
798 Pixels::Rgba => {
799 let ink = Rgb(
800 sample(u, v, 0) as u8,
801 sample(u, v, 1) as u8,
802 sample(u, v, 2) as u8,
803 );
804 self.blend(x, y, ink, sample(u, v, 3) as u8);
805 }
806 }
807 }
808 }
809 }
810
811 fn icon(&mut self, icon: Icon, left: f32, top: f32, side: f32, color: Rgb) {
812 const SAMPLES: usize = 5;
814 let y0 = (top.floor() as i32).max(self.top);
815 let y1 = ((top + side).ceil() as i32).min(self.top + self.height as i32);
816 for y in y0..y1 {
817 for x in left.floor() as i32..(left + side).ceil() as i32 {
818 let mut hits = 0;
819 for sy in 0..SAMPLES {
820 for sx in 0..SAMPLES {
821 let u = (x as f32 + (sx as f32 + 0.5) / SAMPLES as f32 - left) / side;
822 let v = (y as f32 + (sy as f32 + 0.5) / SAMPLES as f32 - top) / side;
823 if (0.0..1.0).contains(&u) && (0.0..1.0).contains(&v) && inked(icon, u, v) {
824 hits += 1;
825 }
826 }
827 }
828 self.blend(x, y, color, (hits * 255 / (SAMPLES * SAMPLES)) as u8);
829 }
830 }
831 }
832}
833
834fn fit_font(fonts: &mut FontSystem, cell_width: usize, cell_height: usize) -> Option<Metrics> {
836 const PROBE: f32 = 100.0;
837 let mut buffer = Buffer::new(fonts, Metrics::new(PROBE, PROBE * 1.2));
838 buffer.set_size(Some(PROBE * 4.0), Some(PROBE * 2.0));
839 let attrs = Attrs::new().family(Family::Monospace);
840 buffer.set_rich_text(
841 std::iter::once(("M", attrs.clone())),
842 &attrs,
843 Shaping::Advanced,
844 None,
845 );
846 buffer.shape_until_scroll(fonts, false);
847 let advance = buffer.layout_runs().next()?.line_w;
848 if advance <= 0.0 {
849 return None;
850 }
851 let by_width = cell_width as f32 * PROBE / advance;
852 let by_height = cell_height as f32 * 0.8;
853 Some(Metrics::new(by_width.min(by_height), cell_height as f32))
854}
855
856fn draw_icon(
858 rgb: &mut [u8],
859 stride: usize,
860 left: usize,
861 cell: (usize, usize),
862 piece: Piece,
863 fg: Rgb,
864) {
865 const SAMPLES: usize = 4;
866 let (cw, ch) = cell;
867 let (full_w, full_h) = (cw * piece.width as usize, ch * piece.height as usize);
868 let side = full_w.min(full_h) as f32 * 0.94;
869 let (off_x, off_y) = ((full_w as f32 - side) / 2.0, (full_h as f32 - side) / 2.0);
870 for y in 0..ch {
871 for x in 0..cw {
872 let mut hits = 0;
873 for sy in 0..SAMPLES {
874 for sx in 0..SAMPLES {
875 let px = (piece.column as usize * cw + x) as f32
876 + (sx as f32 + 0.5) / SAMPLES as f32;
877 let py =
878 (piece.row as usize * ch + y) as f32 + (sy as f32 + 0.5) / SAMPLES as f32;
879 let (u, v) = ((px - off_x) / side, (py - off_y) / side);
880 if (0.0..1.0).contains(&u) && (0.0..1.0).contains(&v) && inked(piece.icon, u, v)
881 {
882 hits += 1;
883 }
884 }
885 }
886 if hits > 0 {
887 let alpha = (hits * 255 / (SAMPLES * SAMPLES)) as u8;
888 let at = (y * stride + left + x) * 3;
889 rgb[at] = blend(fg.0, rgb[at], alpha);
890 rgb[at + 1] = blend(fg.1, rgb[at + 1], alpha);
891 rgb[at + 2] = blend(fg.2, rgb[at + 2], alpha);
892 }
893 }
894 }
895}
896
897fn blend(fg: u8, bg: u8, alpha: u8) -> u8 {
898 let a = alpha as u32;
899 ((fg as u32 * a + bg as u32 * (255 - a)) / 255) as u8
900}
901
902fn fill(rgb: &mut [u8], stride: usize, x: usize, y: usize, w: usize, h: usize, color: Rgb) {
903 for row in y..y + h {
904 for px in x..x + w {
905 let i = (row * stride + px) * 3;
906 if i + 2 < rgb.len() {
907 rgb[i..i + 3].copy_from_slice(&[color.0, color.1, color.2]);
908 }
909 }
910 }
911}
912
913impl Rasterizer for SoftwareRasterizer {
914 fn row(&mut self, grid: &Grid, y: u16) -> Image {
915 let cells = grid.row(y);
916 let (cw, ch) = self.cell;
917 let width = cw * cells.len();
918 let mut rgb = vec![0; width * ch * 3];
919 for (i, cell) in cells.iter().enumerate() {
921 fill(&mut rgb, width, i * cw, 0, cw, ch, cell.style.bg);
922 }
923 for (i, cell) in cells.iter().enumerate() {
924 let fg = cell.style.fg;
925 if cell.symbol.is_empty() || cell.symbol == " " || cell.style.painted {
926 continue;
927 }
928 if cell.symbol == "β" {
930 fill(&mut rgb, width, i * cw, 0, cw.div_ceil(5), ch, fg);
931 continue;
932 }
933 if let Some(piece) = Piece::decode(&cell.symbol) {
934 draw_icon(&mut rgb, width, i * cw, (cw, ch), piece, fg);
935 continue;
936 }
937 let key = GlyphKey {
938 symbol: cell.symbol.clone(),
939 bold: cell.style.bold,
940 italic: cell.style.italic,
941 };
942 let mask = self.mask(&key);
943 if let Some(painted) = self.painted.get(&key) {
944 for &(x, y, color, alpha) in painted.iter() {
945 let at = (y as usize * width + i * cw + x as usize) * 3;
946 if at + 2 < rgb.len() && (i * cw + x as usize) < width {
947 rgb[at] = blend(color.0, rgb[at], alpha);
948 rgb[at + 1] = blend(color.1, rgb[at + 1], alpha);
949 rgb[at + 2] = blend(color.2, rgb[at + 2], alpha);
950 }
951 }
952 continue;
953 }
954 for &(x, y, alpha) in mask.iter() {
955 let at = (y as usize * width + i * cw + x as usize) * 3;
956 if at + 2 < rgb.len() && (i * cw + x as usize) < width {
957 rgb[at] = blend(fg.0, rgb[at], alpha);
958 rgb[at + 1] = blend(fg.1, rgb[at + 1], alpha);
959 rgb[at + 2] = blend(fg.2, rgb[at + 2], alpha);
960 }
961 }
962 }
963 for (i, cell) in cells.iter().enumerate() {
964 if cell.style.underline && !cell.style.painted {
966 fill(&mut rgb, width, i * cw, ch - 2, cw, 1, cell.style.fg);
967 }
968 }
969 let paint: Vec<Paint> = grid.paint_on_row(y).cloned().collect();
970 let mut target = Target {
971 rgb: &mut rgb,
972 width,
973 height: ch,
974 top: y as i32 * ch as i32,
975 };
976 for item in &paint {
977 self.draw_paint(&mut target, item);
978 }
979 if let Some(bounds) = caret_bounds(grid) {
981 let row = (y as i32 * UNIT, (y as i32 + 1) * UNIT);
982 if bounds.y < row.1 && bounds.y + bounds.h > row.0 {
983 let shape = Shape {
984 x: bounds.x as f32 * cw as f32 / UNIT as f32,
985 y: bounds.y as f32 * ch as f32 / UNIT as f32,
986 w: (cw as f32 / 9.0).max(2.0),
987 h: bounds.h as f32 * ch as f32 / UNIT as f32,
988 radius: 0.0,
989 };
990 let mut target = Target {
991 rgb: &mut rgb,
992 width,
993 height: ch,
994 top: y as i32 * ch as i32,
995 };
996 target.panel(
997 shape,
998 (Some(caret_color(grid)), None),
999 false,
1000 false,
1001 ch as f32,
1002 );
1003 }
1004 }
1005 Image {
1006 width,
1007 height: ch,
1008 rgb,
1009 }
1010 }
1011}
1012
1013#[cfg(test)]
1014mod tests {
1015 use super::*;
1016 use crate::grid::{Grid, Rect, Style};
1017
1018 fn rasterizer() -> Option<SoftwareRasterizer> {
1019 SoftwareRasterizer::new(10, 20)
1020 }
1021
1022 fn style() -> Style {
1023 Style {
1024 fg: Rgb(250, 250, 250),
1025 bg: Rgb(10, 20, 30),
1026 ..Style::default()
1027 }
1028 }
1029
1030 fn lit(image: &Image, cell: usize, width: usize) -> usize {
1031 let mut count = 0;
1032 for y in 0..image.height {
1033 for x in cell * width..(cell + 1) * width {
1034 let i = (y * image.width + x) * 3;
1035 count += usize::from(image.rgb[i] > 128);
1036 }
1037 }
1038 count
1039 }
1040
1041 #[test]
1042 fn row_image_is_exactly_the_grid_size() {
1043 let Some(mut r) = rasterizer() else { return };
1044 let grid = Grid::new(8, 1, style());
1045 let image = r.row(&grid, 0);
1046 assert_eq!((image.width, image.height), (80, 20));
1047 assert_eq!(image.rgb.len(), 80 * 20 * 3);
1048 }
1049
1050 #[test]
1051 fn han_characters_are_drawn_in_the_cells() {
1052 let Some(mut r) = rasterizer() else { return };
1053 let fonts = system_fonts();
1054 let has_han = fonts.faces().any(|face| {
1055 let name = &face.families[0].0;
1056 CJK_FONTS.iter().any(|font| font == name)
1057 });
1058 if !has_han {
1059 return;
1060 }
1061 let mut grid = Grid::new(4, 1, style());
1062 grid.put_str(0, 0, "δΈ", style(), 4);
1063 let image = r.row(&grid, 0);
1064 assert!(lit(&image, 0, 10) > 10);
1065 }
1066
1067 #[test]
1068 fn a_wide_glyph_keeps_its_right_half() {
1069 let Some(mut r) = rasterizer() else { return };
1070 let mut grid = Grid::new(4, 1, style());
1071 grid.put_str(1, 0, "MM", style(), 4);
1072 let image = r.row(&grid, 0);
1073 assert!(lit(&image, 1, 10) > 10);
1074 assert!(
1075 lit(&image, 2, 10) > 10,
1076 "the next cell's colour didn't cover it"
1077 );
1078 }
1079
1080 #[test]
1081 fn glyphs_land_in_their_own_cells() {
1082 let Some(mut r) = rasterizer() else { return };
1083 let mut grid = Grid::new(4, 1, style());
1084 grid.put_str(2, 0, "M", style(), 4);
1085 let image = r.row(&grid, 0);
1086 assert_eq!(lit(&image, 0, 10), 0);
1087 assert!(lit(&image, 2, 10) > 10, "M drew nothing");
1088 assert_eq!(lit(&image, 3, 10), 0, "M spilled into the next cell");
1089 }
1090
1091 #[test]
1092 fn the_caret_is_a_thin_line() {
1093 let Some(mut r) = rasterizer() else { return };
1094 let mut grid = Grid::new(3, 1, style());
1095 grid.cursor = Some((1, 0));
1096 let image = r.row(&grid, 0);
1097 let at = |x: usize| image.rgb[(10 * image.width + x) * 3];
1098 assert_eq!(at(10), 250);
1099 assert_eq!(at(15), 10);
1100 grid.caret = Some(Bounds::cells(1.5, 0.0, 0.0, 1.0));
1101 let image = r.row(&grid, 0);
1102 let at = |x: usize| image.rgb[(10 * image.width + x) * 3];
1103 assert_eq!(at(10), 10, "the exact caret replaces the cell one");
1104 assert_eq!(at(15), 250);
1105 }
1106
1107 #[test]
1108 fn labels_draw_without_their_cell_glyphs() {
1109 let Some(mut r) = rasterizer() else { return };
1110 let mut grid = Grid::new(20, 1, style());
1111 grid.label(1, 0, "Illi", style(), 20);
1112 assert!(grid.cell(1, 0).style.painted);
1113 let with_paint = r.row(&grid, 0);
1114 let lit_right = (0..20)
1116 .flat_map(|y| (40..200).map(move |x| (x, y)))
1117 .any(|(x, y)| with_paint.rgb[(y * with_paint.width + x) * 3] > 128);
1118 assert!(!lit_right, "drew past the narrow label");
1119 }
1120
1121 #[test]
1124 fn an_emoji_in_painted_text_keeps_its_own_colours() {
1125 let Some(mut r) = rasterizer() else { return };
1126 let mask = r.text_mask("ok π", Font::default());
1127 let Some(own) = &mask.own else { return };
1129 let coloured = own.iter().flatten().filter(|rgb| rgb.0 != rgb.2).count();
1130 assert!(coloured > 10, "a rocket has red and blue in it: {coloured}");
1131 let plain = r.text_mask("ok", Font::default());
1132 assert!(plain.own.is_none(), "letters have no colour of their own");
1133 let mut grid = Grid::new(12, 1, style());
1135 let dark = Style {
1136 fg: Rgb(10, 10, 10),
1137 bg: Rgb(240, 240, 240),
1138 ..Style::default()
1139 };
1140 grid.fill(Rect::new(0, 0, 12, 1), dark);
1141 grid.label(0, 0, "ok π", dark, 12);
1142 let image = r.row(&grid, 0);
1143 let pixels: Vec<Rgb> = image.rgb.chunks(3).map(|p| Rgb(p[0], p[1], p[2])).collect();
1144 let tinted = |p: &&Rgb| p.0.abs_diff(p.2) > 60;
1145 assert!(pixels.iter().filter(tinted).count() > 10);
1146 }
1147
1148 #[test]
1149 fn panels_have_rounded_corners() {
1150 let Some(mut r) = rasterizer() else { return };
1151 let mut grid = Grid::new(10, 1, style());
1152 grid.panel(
1153 crate::paint::Bounds::cells(1.0, 0.0, 8.0, 1.0),
1154 40,
1155 Some(Rgb(255, 0, 0)),
1156 None,
1157 );
1158 let image = r.row(&grid, 0);
1159 let red = |x: usize, y: usize| image.rgb[(y * image.width + x) * 3];
1160 assert_eq!(red(50, 10), 255, "the middle is filled");
1161 assert_eq!(red(10, 0), 10, "the corner is cut");
1162 }
1163
1164 #[test]
1165 fn a_wash_lets_what_is_under_it_show() {
1166 let Some(mut r) = rasterizer() else { return };
1167 let mut grid = Grid::new(20, 2, style());
1168 let bounds = crate::paint::Bounds::cells(1.0, 0.0, 18.0, 2.0);
1169 grid.wash(bounds, 10, (Rgb(255, 0, 0), 64), Some(Rgb(0, 0, 255)));
1170 let image = r.row(&grid, 0);
1171 let at = |x: usize, y: usize| {
1172 let i = (y * image.width + x) * 3;
1173 (image.rgb[i], image.rgb[i + 1], image.rgb[i + 2])
1174 };
1175 let middle = at(image.width / 2, image.height - 1);
1176 assert!(middle.0 > 0 && middle.0 < 200, "a little red: {middle:?}");
1177 let edge = at(image.width / 2, 0);
1178 assert!(edge.2 > 200, "the border: {edge:?}");
1179 }
1180
1181 #[test]
1182 fn a_dashed_border_has_gaps() {
1183 let Some(mut r) = rasterizer() else { return };
1184 let mut grid = Grid::new(20, 1, style());
1185 grid.dashed_panel(
1186 crate::paint::Bounds::cells(1.0, 0.0, 18.0, 1.0),
1187 10,
1188 None,
1189 Rgb(255, 0, 0),
1190 );
1191 let image = r.row(&grid, 0);
1192 let y = 0;
1194 let reds: Vec<u8> = (30..170)
1195 .map(|x| image.rgb[(y * image.width + x) * 3])
1196 .collect();
1197 assert!(reds.iter().any(|r| *r > 200), "dashes are drawn");
1198 assert!(reds.iter().any(|r| *r < 60), "with gaps between them");
1199 }
1200
1201 #[test]
1205 fn the_emoji_font_in_the_binary_draws_in_colour_by_itself() {
1206 let mut db = fontdb::Database::new();
1207 for data in [INTER, INTER_ITALIC, MONO, MONO_ITALIC, EMOJI] {
1208 db.load_font_data(data.to_vec());
1209 }
1210 db.set_monospace_family("JetBrains Mono");
1211 db.set_sans_serif_family("Inter Variable");
1212 let mut fonts = FontSystem::new_with_locale_and_db("en-US".to_string(), db);
1213 assert!(draws_colour(&mut fonts, BUILT_IN_EMOJI));
1214 let found = find_emoji_font(&mut fonts).map(|(family, _)| family);
1215 assert_eq!(found.as_deref(), Some(BUILT_IN_EMOJI));
1216 for emoji in ["π", "π―", "β€\u{fe0f}", "π", "π", "π", "π", "β
"] {
1217 assert!(
1218 set_in(&mut fonts, BUILT_IN_EMOJI, emoji).is_some(),
1219 "{emoji}"
1220 );
1221 }
1222 assert!(!draws_colour(&mut fonts, "No Such Emoji"));
1224 for emoji in ["πΉπ·", "π©\u{200d}π»", "β€\u{fe0f}", "1\u{fe0f}\u{20e3}"] {
1226 assert!(built_in_emoji_holds(emoji), "{emoji}");
1227 }
1228 assert!(
1229 !built_in_emoji_holds("π«¨"),
1230 "a face from a year after the font"
1231 );
1232 assert!(!built_in_emoji_holds("ok"));
1233 let metrics = fit_font(&mut fonts, 10, 20).unwrap();
1235 let mut r = SoftwareRasterizer {
1236 fonts,
1237 emoji: Some(BUILT_IN_EMOJI.to_string()),
1238 swash: SwashCache::new(),
1239 metrics,
1240 cell: (10, 20),
1241 masks: HashMap::new(),
1242 painted: HashMap::new(),
1243 text: HashMap::new(),
1244 };
1245 let mask = r.text_mask("ok π β€\u{fe0f}", Font::default());
1246 let own = mask
1247 .own
1248 .as_ref()
1249 .expect("the emoji have colours of their own");
1250 let red = own
1251 .iter()
1252 .flatten()
1253 .filter(|rgb| rgb.0 > 150 && rgb.2 < 120);
1254 assert!(red.count() > 10, "a heart and a rocket's flame are red");
1255 }
1256
1257 #[test]
1258 fn fonts_ship_in_the_binary() {
1259 let mut r = SoftwareRasterizer::new(10, 20).unwrap();
1260 assert!(
1261 r.fonts
1262 .db()
1263 .faces()
1264 .any(|f| f.families.iter().any(|(n, _)| n.contains("Inter")))
1265 );
1266 assert!(
1267 r.text_mask("x", Font::default())
1268 .alpha
1269 .iter()
1270 .any(|a| *a > 0)
1271 );
1272 }
1273
1274 #[test]
1275 fn unknown_cell_size_refuses_pixels() {
1276 assert!(SoftwareRasterizer::new(0, 20).is_none());
1277 }
1278}