| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | use std::collections::BTreeMap; |
| 31 | use std::sync::{Mutex, OnceLock}; |
| 32 | |
| 33 | use ab_glyph::{Font, FontRef, GlyphId, PxScale, ScaleFont, point}; |
| 34 | use unicode_bidi::BidiInfo; |
| 35 | |
| 36 | use crate::colorspace::is_sd; |
| 37 | |
| 38 | |
| 39 | |
| 40 | const ARCHIVO: usize = 0; |
| 41 | |
| 42 | const NOTO_SANS: usize = 1; |
| 43 | |
| 44 | const MONO_EMOJI: usize = 6; |
| 45 | |
| 46 | const ARCHIVO_BOLD: usize = 7; |
| 47 | |
| 48 | const OUTLINE_FACES: usize = 8; |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | static OUTLINE_BYTES: [&[u8]; OUTLINE_FACES] = [ |
| 54 | include_bytes!("../../../assets/fonts/Archivo-Medium.ttf"), |
| 55 | include_bytes!("../../../assets/fonts/NotoSans[wght].ttf"), |
| 56 | include_bytes!("../../../assets/fonts/NotoSansArabic[wght].ttf"), |
| 57 | include_bytes!("../../../assets/fonts/NotoSansHebrew[wght].ttf"), |
| 58 | include_bytes!("../../../assets/fonts/NotoSansDevanagari[wght].ttf"), |
| 59 | include_bytes!("../../../assets/fonts/NotoSansThai[wght].ttf"), |
| 60 | |
| 61 | include_bytes!("../../../assets/fonts/NotoEmoji-Regular.ttf"), |
| 62 | include_bytes!("../../../assets/fonts/Archivo-Bold.ttf"), |
| 63 | ]; |
| 64 | |
| 65 | |
| 66 | static PARSED: [OnceLock<Option<FontRef<'static>>>; OUTLINE_FACES] = [const { OnceLock::new() }; OUTLINE_FACES]; |
| 67 | |
| 68 | |
| 69 | fn outline_face(i: usize) -> Option<&'static FontRef<'static>> { |
| 70 | PARSED[i] |
| 71 | .get_or_init(|| FontRef::try_from_slice(OUTLINE_BYTES[i]).ok()) |
| 72 | .as_ref() |
| 73 | } |
| 74 | |
| 75 | static SHAPERS: [OnceLock<Option<rustybuzz::Face<'static>>>; OUTLINE_FACES] = [const { OnceLock::new() }; OUTLINE_FACES]; |
| 76 | |
| 77 | |
| 78 | |
| 79 | fn shaper(i: usize) -> Option<&'static rustybuzz::Face<'static>> { |
| 80 | SHAPERS[i] |
| 81 | .get_or_init(|| rustybuzz::Face::from_slice(OUTLINE_BYTES[i], 0)) |
| 82 | .as_ref() |
| 83 | } |
| 84 | |
| 85 | |
| 86 | const COLOUR_PATHS: [&str; 2] = [ |
| 87 | "/usr/share/fonts/google-noto-color-emoji-fonts/Noto-COLRv1.ttf", |
| 88 | "/usr/share/fonts/noto-emoji/NotoColorEmoji.ttf", |
| 89 | ]; |
| 90 | |
| 91 | |
| 92 | |
| 93 | |
| 94 | const CJK_PATHS: [&str; 4] = [ |
| 95 | "/usr/share/fonts/google-noto-sans-cjk-vf-fonts/NotoSansCJK-VF.ttc", |
| 96 | "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", |
| 97 | "/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc", |
| 98 | "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc", |
| 99 | ]; |
| 100 | |
| 101 | |
| 102 | fn system_bytes(cell: &'static OnceLock<Option<Vec<u8>>>, paths: &[&str]) -> Option<&'static [u8]> { |
| 103 | cell.get_or_init(|| paths.iter().find_map(|p| std::fs::read(p).ok())) |
| 104 | .as_deref() |
| 105 | } |
| 106 | |
| 107 | |
| 108 | fn colour_face() -> Option<&'static ttf_parser::Face<'static>> { |
| 109 | static BYTES: OnceLock<Option<Vec<u8>>> = OnceLock::new(); |
| 110 | static FACE: OnceLock<Option<ttf_parser::Face<'static>>> = OnceLock::new(); |
| 111 | FACE.get_or_init(|| { |
| 112 | let bytes = system_bytes(&BYTES, &COLOUR_PATHS)?; |
| 113 | ttf_parser::Face::parse(bytes, 0).ok() |
| 114 | }) |
| 115 | .as_ref() |
| 116 | } |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | |
| 122 | fn cjk_face() -> Option<&'static ttf_parser::Face<'static>> { |
| 123 | static BYTES: OnceLock<Option<Vec<u8>>> = OnceLock::new(); |
| 124 | static FACE: OnceLock<Option<ttf_parser::Face<'static>>> = OnceLock::new(); |
| 125 | FACE.get_or_init(|| { |
| 126 | let bytes = system_bytes(&BYTES, &CJK_PATHS)?; |
| 127 | let mut face = ttf_parser::Face::parse(bytes, 0).ok()?; |
| 128 | face.set_variation(ttf_parser::Tag::from_bytes(b"wght"), 500.0); |
| 129 | Some(face) |
| 130 | }) |
| 131 | .as_ref() |
| 132 | } |
| 133 | |
| 134 | |
| 135 | |
| 136 | |
| 137 | |
| 138 | |
| 139 | fn face_k() -> &'static [f32; OUTLINE_FACES] { |
| 140 | static K: OnceLock<[f32; OUTLINE_FACES]> = OnceLock::new(); |
| 141 | K.get_or_init(|| { |
| 142 | let mut k = [1.0; OUTLINE_FACES]; |
| 143 | let Some(text) = ttf_parser::Face::parse(OUTLINE_BYTES[ARCHIVO], 0) |
| 144 | .ok() |
| 145 | .and_then(|f| f.x_height()) |
| 146 | else { |
| 147 | return k; |
| 148 | }; |
| 149 | let text_h = outline_face(ARCHIVO).map_or(1.0, |f| f.height_unscaled()); |
| 150 | for (i, slot) in k.iter_mut().enumerate().take(MONO_EMOJI).skip(ARCHIVO + 1) { |
| 151 | let (Some(font), Ok(face)) = ( |
| 152 | outline_face(i), |
| 153 | ttf_parser::Face::parse(OUTLINE_BYTES[i], 0), |
| 154 | ) else { |
| 155 | continue; |
| 156 | }; |
| 157 | if let Some(x) = face.x_height().filter(|&x| x > 0) { |
| 158 | *slot = (font.height_unscaled() / text_h) * (f32::from(text) / f32::from(x)); |
| 159 | } |
| 160 | } |
| 161 | k |
| 162 | }) |
| 163 | } |
| 164 | |
| 165 | |
| 166 | |
| 167 | #[derive(Clone, Copy)] |
| 168 | pub(crate) struct Family { |
| 169 | font: &'static FontRef<'static>, |
| 170 | k: f32, |
| 171 | } |
| 172 | |
| 173 | |
| 174 | fn family_k(font: &FontRef<'_>, data: &[u8], index: u32) -> f32 { |
| 175 | let text_h = outline_face(ARCHIVO).map_or(1.0, |f| f.height_unscaled()); |
| 176 | let text_x = ttf_parser::Face::parse(OUTLINE_BYTES[ARCHIVO], 0).ok().and_then(|f| f.x_height()); |
| 177 | let own_x = ttf_parser::Face::parse(data, index).ok().and_then(|f| f.x_height()).filter(|&x| x > 0); |
| 178 | match (text_x, own_x) { |
| 179 | (Some(t), Some(x)) => (font.height_unscaled() / text_h) * (f32::from(t) / f32::from(x)), |
| 180 | _ => font.height_unscaled() / text_h, |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | pub(crate) fn family_face(name: &str) -> Option<Family> { |
| 188 | static DB: OnceLock<fontdb::Database> = OnceLock::new(); |
| 189 | static FOUND: Mutex<BTreeMap<String, Option<Family>>> = Mutex::new(BTreeMap::new()); |
| 190 | let mut found = FOUND.lock().ok()?; |
| 191 | if let Some(known) = found.get(name) { |
| 192 | return *known; |
| 193 | } |
| 194 | let db = DB.get_or_init(|| { |
| 195 | let mut db = fontdb::Database::new(); |
| 196 | db.load_system_fonts(); |
| 197 | db |
| 198 | }); |
| 199 | let query = fontdb::Query { families: &[fontdb::Family::Name(name)], ..fontdb::Query::default() }; |
| 200 | let family = db.query(&query).and_then(|id| { |
| 201 | db.with_face_data(id, |data, index| { |
| 202 | let data: &'static [u8] = Box::leak(data.to_vec().into_boxed_slice()); |
| 203 | let font = FontRef::try_from_slice_and_index(data, index).ok()?; |
| 204 | let k = family_k(&font, data, index); |
| 205 | Some(Family { font: Box::leak(Box::new(font)), k }) |
| 206 | }) |
| 207 | .flatten() |
| 208 | }); |
| 209 | found.insert(name.to_string(), family); |
| 210 | family |
| 211 | } |
| 212 | |
| 213 | |
| 214 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 215 | enum Src { |
| 216 | |
| 217 | Outline(usize), |
| 218 | |
| 219 | Colour, |
| 220 | |
| 221 | Cjk, |
| 222 | |
| 223 | Family, |
| 224 | } |
| 225 | |
| 226 | |
| 227 | |
| 228 | fn lookup(c: char) -> Option<(Src, u16)> { |
| 229 | let outline = |i: usize| { |
| 230 | let g = outline_face(i)?.glyph_id(c).0; |
| 231 | (g != 0).then_some((Src::Outline(i), g)) |
| 232 | }; |
| 233 | let colour = || { |
| 234 | let face = colour_face()?; |
| 235 | let g = face.glyph_index(c)?; |
| 236 | face.is_color_glyph(g).then_some((Src::Colour, g.0)) |
| 237 | }; |
| 238 | let cjk = || { |
| 239 | let g = cjk_face()?.glyph_index(c)?.0; |
| 240 | (g != 0).then_some((Src::Cjk, g)) |
| 241 | }; |
| 242 | (0..MONO_EMOJI) |
| 243 | .find_map(outline) |
| 244 | .or_else(colour) |
| 245 | .or_else(|| outline(MONO_EMOJI)) |
| 246 | .or_else(cjk) |
| 247 | } |
| 248 | |
| 249 | |
| 250 | |
| 251 | fn pick(c: char) -> (Src, u16) { |
| 252 | lookup(c).unwrap_or((Src::Outline(ARCHIVO), 0)) |
| 253 | } |
| 254 | |
| 255 | |
| 256 | fn pick_in(faces: &Faces, c: char) -> (Src, u16) { |
| 257 | if let Some(family) = faces.family { |
| 258 | let g = family.font.glyph_id(c).0; |
| 259 | if g != 0 { |
| 260 | return (Src::Family, g); |
| 261 | } |
| 262 | } |
| 263 | pick(c) |
| 264 | } |
| 265 | |
| 266 | |
| 267 | pub const SIZE_RANGE: (u32, u32) = (10, 200); |
| 268 | |
| 269 | |
| 270 | |
| 271 | pub const DEFAULT_SIZE: u32 = 50; |
| 272 | |
| 273 | |
| 274 | |
| 275 | const MARGIN: f32 = 0.05; |
| 276 | |
| 277 | |
| 278 | const STACK_GAP: f32 = 0.4; |
| 279 | |
| 280 | |
| 281 | |
| 282 | const BOX_ALPHA: u8 = 153; |
| 283 | |
| 284 | |
| 285 | |
| 286 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 287 | pub enum Outline { |
| 288 | #[default] |
| 289 | None, |
| 290 | Thin, |
| 291 | Thick, |
| 292 | } |
| 293 | |
| 294 | |
| 295 | |
| 296 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 297 | pub enum Place { |
| 298 | #[default] |
| 299 | Bottom, |
| 300 | Top, |
| 301 | Centre, |
| 302 | } |
| 303 | |
| 304 | |
| 305 | |
| 306 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 307 | pub enum HPlace { |
| 308 | #[default] |
| 309 | Centre, |
| 310 | Left, |
| 311 | Right, |
| 312 | } |
| 313 | |
| 314 | |
| 315 | |
| 316 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 317 | pub enum Weight { |
| 318 | #[default] |
| 319 | Regular, |
| 320 | Bold, |
| 321 | } |
| 322 | |
| 323 | |
| 324 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 325 | pub enum Align { |
| 326 | #[default] |
| 327 | Centre, |
| 328 | Left, |
| 329 | Right, |
| 330 | } |
| 331 | |
| 332 | |
| 333 | |
| 334 | |
| 335 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 336 | pub struct TextStyle { |
| 337 | |
| 338 | pub size: u32, |
| 339 | pub outline: Outline, |
| 340 | |
| 341 | pub boxed: bool, |
| 342 | pub place: Place, |
| 343 | |
| 344 | pub hplace: HPlace, |
| 345 | |
| 346 | pub ink: [u8; 3], |
| 347 | pub weight: Weight, |
| 348 | |
| 349 | pub align: Align, |
| 350 | |
| 351 | pub box_color: [u8; 4], |
| 352 | |
| 353 | |
| 354 | pub family: Option<String>, |
| 355 | |
| 356 | |
| 357 | pub caption: crate::captionanim::CaptionStyle, |
| 358 | } |
| 359 | |
| 360 | impl Default for TextStyle { |
| 361 | fn default() -> Self { |
| 362 | Self { |
| 363 | size: DEFAULT_SIZE, |
| 364 | outline: Outline::None, |
| 365 | boxed: true, |
| 366 | place: Place::Bottom, |
| 367 | hplace: HPlace::Centre, |
| 368 | ink: [255, 255, 255], |
| 369 | weight: Weight::Regular, |
| 370 | align: Align::Centre, |
| 371 | box_color: [0, 0, 0, BOX_ALPHA], |
| 372 | family: None, |
| 373 | caption: crate::captionanim::CaptionStyle::default(), |
| 374 | } |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | impl TextStyle { |
| 379 | |
| 380 | |
| 381 | |
| 382 | pub fn clamped(&self) -> Self { |
| 383 | Self { |
| 384 | size: self.size.clamp(SIZE_RANGE.0, SIZE_RANGE.1), |
| 385 | caption: self.caption.clamped(), |
| 386 | ..self.clone() |
| 387 | } |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | |
| 392 | |
| 393 | |
| 394 | |
| 395 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 396 | pub struct Overlay { |
| 397 | width: u32, |
| 398 | height: u32, |
| 399 | |
| 400 | bounds: (u32, u32, u32, u32), |
| 401 | plate: Vec<u8>, |
| 402 | stroke: Vec<u8>, |
| 403 | fill: Vec<u8>, |
| 404 | |
| 405 | |
| 406 | colour: Vec<[u8; 4]>, |
| 407 | |
| 408 | ink: [u8; 3], |
| 409 | |
| 410 | plate_rgb: [u8; 3], |
| 411 | } |
| 412 | |
| 413 | impl Overlay { |
| 414 | fn empty(width: u32, height: u32) -> Self { |
| 415 | let n = width as usize * height as usize; |
| 416 | Self { |
| 417 | width, |
| 418 | height, |
| 419 | bounds: (0, 0, 0, 0), |
| 420 | plate: vec![0; n], |
| 421 | stroke: vec![0; n], |
| 422 | fill: vec![0; n], |
| 423 | colour: Vec::new(), |
| 424 | ink: [255; 3], |
| 425 | plate_rgb: [0; 3], |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | |
| 430 | fn colour_at(&self, i: usize) -> Option<[u8; 4]> { |
| 431 | self.colour.get(i).copied().filter(|c| c[3] > 0) |
| 432 | } |
| 433 | |
| 434 | |
| 435 | |
| 436 | pub fn is_blank(&self) -> bool { |
| 437 | self.bounds.0 >= self.bounds.2 || self.bounds.1 >= self.bounds.3 |
| 438 | } |
| 439 | |
| 440 | |
| 441 | |
| 442 | pub fn fill(&self) -> &[u8] { |
| 443 | &self.fill |
| 444 | } |
| 445 | |
| 446 | |
| 447 | |
| 448 | pub fn stroke(&self) -> &[u8] { |
| 449 | &self.stroke |
| 450 | } |
| 451 | |
| 452 | |
| 453 | |
| 454 | pub fn blend_bgra(&self, canvas: &mut [u8]) { |
| 455 | let (x0, y0, x1, y1) = self.bounds; |
| 456 | let w = self.width as usize; |
| 457 | if canvas.len() < w * self.height as usize * 4 { |
| 458 | return; |
| 459 | } |
| 460 | for y in y0 as usize..y1 as usize { |
| 461 | for x in x0 as usize..x1 as usize { |
| 462 | let i = y * w + x; |
| 463 | let (p, s, f) = (self.plate[i], self.stroke[i], self.fill[i]); |
| 464 | let colour = self.colour_at(i); |
| 465 | if p == 0 && s == 0 && f == 0 && colour.is_none() { |
| 466 | continue; |
| 467 | } |
| 468 | let px = &mut canvas[i * 4..i * 4 + 4]; |
| 469 | |
| 470 | for (k, c) in px[..3].iter_mut().enumerate() { |
| 471 | let v = mix(*c, self.plate_rgb[2 - k], p); |
| 472 | let v = mix(v, 0, s); |
| 473 | *c = mix(v, self.ink[2 - k], f); |
| 474 | } |
| 475 | |
| 476 | if let Some([r, g, b, a]) = colour { |
| 477 | px[0] = mix(px[0], b, a); |
| 478 | px[1] = mix(px[1], g, a); |
| 479 | px[2] = mix(px[2], r, a); |
| 480 | } |
| 481 | } |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | |
| 486 | |
| 487 | |
| 488 | |
| 489 | |
| 490 | pub fn blend_i420(&self, y: &mut [u8], u: &mut [u8], v: &mut [u8], full_range: bool) { |
| 491 | let (w, h) = (self.width as usize, self.height as usize); |
| 492 | if y.len() < w * h || u.len() < w.div_ceil(2) * h.div_ceil(2) || v.len() != u.len() { |
| 493 | return; |
| 494 | } |
| 495 | let black = if full_range { 0 } else { 16 }; |
| 496 | |
| 497 | let bt709 = !is_sd(self.width, self.height); |
| 498 | let (ink_y, ink_cb, ink_cr) = yuv([self.ink[0], self.ink[1], self.ink[2], 255], bt709, full_range); |
| 499 | let (plate_y, plate_cb, plate_cr) = |
| 500 | yuv([self.plate_rgb[0], self.plate_rgb[1], self.plate_rgb[2], 255], bt709, full_range); |
| 501 | let grey = self.ink[0] == self.ink[1] |
| 502 | && self.ink[1] == self.ink[2] |
| 503 | && self.plate_rgb[0] == self.plate_rgb[1] |
| 504 | && self.plate_rgb[1] == self.plate_rgb[2]; |
| 505 | let (x0, y0, x1, y1) = self.bounds; |
| 506 | let cw = w.div_ceil(2); |
| 507 | |
| 508 | let cover = |i: usize| -> u8 { |
| 509 | let (p, s, f) = ( |
| 510 | self.plate[i] as u64, |
| 511 | self.stroke[i] as u64, |
| 512 | self.fill[i] as u64, |
| 513 | ); |
| 514 | let k = self.colour_at(i).map_or(0, |c| c[3]) as u64; |
| 515 | |
| 516 | let kept = (255 - p) * (255 - s) * (255 - f) * (255 - k); |
| 517 | (255 - kept / (255 * 255 * 255)) as u8 |
| 518 | }; |
| 519 | for py in y0 as usize..y1 as usize { |
| 520 | for px in x0 as usize..x1 as usize { |
| 521 | let i = py * w + px; |
| 522 | let (p, s, f) = (self.plate[i], self.stroke[i], self.fill[i]); |
| 523 | let colour = self.colour_at(i); |
| 524 | if p == 0 && s == 0 && f == 0 && colour.is_none() { |
| 525 | continue; |
| 526 | } |
| 527 | let mut luma = y[i]; |
| 528 | luma = mix(luma, plate_y, p); |
| 529 | luma = mix(luma, black, s); |
| 530 | luma = mix(luma, ink_y, f); |
| 531 | if let Some(c) = colour { |
| 532 | let (yc, _, _) = yuv(c, bt709, full_range); |
| 533 | luma = mix(luma, yc, c[3]); |
| 534 | } |
| 535 | y[i] = luma; |
| 536 | } |
| 537 | } |
| 538 | for cy in (y0 as usize / 2)..(y1 as usize).div_ceil(2) { |
| 539 | for cx in (x0 as usize / 2)..(x1 as usize).div_ceil(2) { |
| 540 | let mut sum = 0u32; |
| 541 | let mut n = 0u32; |
| 542 | |
| 543 | |
| 544 | |
| 545 | let mut coloured = false; |
| 546 | let (mut tu, mut tv) = (0f32, 0f32); |
| 547 | for dy in 0..2 { |
| 548 | for dx in 0..2 { |
| 549 | let (px, py) = (cx * 2 + dx, cy * 2 + dy); |
| 550 | if px < w && py < h { |
| 551 | let i = py * w + px; |
| 552 | let c = cover(i) as u32; |
| 553 | sum += c; |
| 554 | n += 1; |
| 555 | let (cb, cr) = match self.colour_at(i) { |
| 556 | Some(k) => { |
| 557 | coloured = true; |
| 558 | let (_, cb, cr) = yuv(k, bt709, full_range); |
| 559 | (f32::from(cb), f32::from(cr)) |
| 560 | } |
| 561 | None => (128.0, 128.0), |
| 562 | }; |
| 563 | tu += c as f32 * cb; |
| 564 | tv += c as f32 * cr; |
| 565 | } |
| 566 | } |
| 567 | } |
| 568 | if n == 0 { |
| 569 | continue; |
| 570 | } |
| 571 | let ci = cy * cw + cx; |
| 572 | if ci < u.len() { |
| 573 | if !grey { |
| 574 | |
| 575 | let (mut p, mut s, mut f, mut ka) = (0u32, 0u32, 0u32, 0u32); |
| 576 | let (mut kcb, mut kcr) = (0f32, 0f32); |
| 577 | for dy in 0..2 { |
| 578 | for dx in 0..2 { |
| 579 | let (px, py) = (cx * 2 + dx, cy * 2 + dy); |
| 580 | if px < w && py < h { |
| 581 | let i = py * w + px; |
| 582 | p += u32::from(self.plate[i]); |
| 583 | s += u32::from(self.stroke[i]); |
| 584 | f += u32::from(self.fill[i]); |
| 585 | if let Some(k) = self.colour_at(i) { |
| 586 | let (_, cb, cr) = yuv(k, bt709, full_range); |
| 587 | ka += u32::from(k[3]); |
| 588 | kcb += f32::from(k[3]) * f32::from(cb); |
| 589 | kcr += f32::from(k[3]) * f32::from(cr); |
| 590 | } |
| 591 | } |
| 592 | } |
| 593 | } |
| 594 | let mean = |t: u32| (t / n) as u8; |
| 595 | for (c, plate, ink) in [(&mut u[ci], plate_cb, ink_cb), (&mut v[ci], plate_cr, ink_cr)] { |
| 596 | *c = mix(*c, plate, mean(p)); |
| 597 | *c = mix(*c, 128, mean(s)); |
| 598 | *c = mix(*c, ink, mean(f)); |
| 599 | } |
| 600 | if ka > 0 { |
| 601 | let a = mean(ka); |
| 602 | u[ci] = mix(u[ci], (kcb / ka as f32).round() as u8, a); |
| 603 | v[ci] = mix(v[ci], (kcr / ka as f32).round() as u8, a); |
| 604 | } |
| 605 | } else if coloured { |
| 606 | let keep = 1.0 - sum as f32 / (255.0 * n as f32); |
| 607 | let target = 1.0 / (255.0 * n as f32); |
| 608 | u[ci] = (f32::from(u[ci]) * keep + tu * target) |
| 609 | .round() |
| 610 | .clamp(0.0, 255.0) as u8; |
| 611 | v[ci] = (f32::from(v[ci]) * keep + tv * target) |
| 612 | .round() |
| 613 | .clamp(0.0, 255.0) as u8; |
| 614 | } else { |
| 615 | let a = (sum / n) as u8; |
| 616 | u[ci] = mix(u[ci], 128, a); |
| 617 | v[ci] = mix(v[ci], 128, a); |
| 618 | } |
| 619 | } |
| 620 | } |
| 621 | } |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | impl Overlay { |
| 626 | |
| 627 | |
| 628 | |
| 629 | pub fn faded(&self, alpha: u8) -> Self { |
| 630 | let scale = |p: &[u8]| -> Vec<u8> { |
| 631 | p.iter() |
| 632 | .map(|&c| ((u32::from(c) * u32::from(alpha) + 127) / 255) as u8) |
| 633 | .collect() |
| 634 | }; |
| 635 | Self { |
| 636 | width: self.width, |
| 637 | height: self.height, |
| 638 | bounds: self.bounds, |
| 639 | ink: self.ink, |
| 640 | plate_rgb: self.plate_rgb, |
| 641 | plate: scale(&self.plate), |
| 642 | stroke: scale(&self.stroke), |
| 643 | fill: scale(&self.fill), |
| 644 | colour: self |
| 645 | .colour |
| 646 | .iter() |
| 647 | .map(|c| { |
| 648 | let a = (u32::from(c[3]) * u32::from(alpha) + 127) / 255; |
| 649 | [c[0], c[1], c[2], a as u8] |
| 650 | }) |
| 651 | .collect(), |
| 652 | } |
| 653 | } |
| 654 | } |
| 655 | |
| 656 | impl Overlay { |
| 657 | |
| 658 | |
| 659 | pub fn moved(&self, dx: i32, dy: i32) -> Self { |
| 660 | let (w, h) = (self.width as i64, self.height as i64); |
| 661 | let shift = |p: &[u8]| -> Vec<u8> { |
| 662 | let mut out = vec![0u8; p.len()]; |
| 663 | let (x0, y0, x1, y1) = self.bounds; |
| 664 | for y in y0 as i64..y1 as i64 { |
| 665 | for x in x0 as i64..x1 as i64 { |
| 666 | let (nx, ny) = (x + i64::from(dx), y + i64::from(dy)); |
| 667 | if (0..w).contains(&nx) && (0..h).contains(&ny) { |
| 668 | out[(ny * w + nx) as usize] = p[(y * w + x) as usize]; |
| 669 | } |
| 670 | } |
| 671 | } |
| 672 | out |
| 673 | }; |
| 674 | let (x0, y0, x1, y1) = self.bounds; |
| 675 | let bounds = ( |
| 676 | (i64::from(x0) + i64::from(dx)).clamp(0, w) as u32, |
| 677 | (i64::from(y0) + i64::from(dy)).clamp(0, h) as u32, |
| 678 | (i64::from(x1) + i64::from(dx)).clamp(0, w) as u32, |
| 679 | (i64::from(y1) + i64::from(dy)).clamp(0, h) as u32, |
| 680 | ); |
| 681 | let mut colour = vec![[0u8; 4]; self.colour.len()]; |
| 682 | if !self.colour.is_empty() { |
| 683 | for y in y0 as i64..y1 as i64 { |
| 684 | for x in x0 as i64..x1 as i64 { |
| 685 | let (nx, ny) = (x + i64::from(dx), y + i64::from(dy)); |
| 686 | if (0..w).contains(&nx) && (0..h).contains(&ny) { |
| 687 | colour[(ny * w + nx) as usize] = self.colour[(y * w + x) as usize]; |
| 688 | } |
| 689 | } |
| 690 | } |
| 691 | } |
| 692 | Self { |
| 693 | width: self.width, |
| 694 | height: self.height, |
| 695 | bounds, |
| 696 | plate: shift(&self.plate), |
| 697 | stroke: shift(&self.stroke), |
| 698 | fill: shift(&self.fill), |
| 699 | colour, |
| 700 | ink: self.ink, |
| 701 | plate_rgb: self.plate_rgb, |
| 702 | } |
| 703 | } |
| 704 | } |
| 705 | |
| 706 | |
| 707 | fn mix(dst: u8, src: u8, a: u8) -> u8 { |
| 708 | let a = u32::from(a); |
| 709 | ((u32::from(dst) * (255 - a) + u32::from(src) * a + 127) / 255) as u8 |
| 710 | } |
| 711 | |
| 712 | |
| 713 | |
| 714 | fn yuv(c: [u8; 4], bt709: bool, full_range: bool) -> (u8, u8, u8) { |
| 715 | let (kr, kb) = if bt709 { |
| 716 | (0.2126, 0.0722) |
| 717 | } else { |
| 718 | (0.299, 0.114) |
| 719 | }; |
| 720 | let kg = 1.0 - kr - kb; |
| 721 | let (r, g, b) = (f32::from(c[0]), f32::from(c[1]), f32::from(c[2])); |
| 722 | let luma = (kr * r + kg * g + kb * b) / 255.0; |
| 723 | let cb = (b / 255.0 - luma) / (2.0 * (1.0 - kb)); |
| 724 | let cr = (r / 255.0 - luma) / (2.0 * (1.0 - kr)); |
| 725 | let (ys, cs, yo) = if full_range { |
| 726 | (255.0, 255.0, 0.0) |
| 727 | } else { |
| 728 | (219.0, 224.0, 16.0) |
| 729 | }; |
| 730 | let to_u8 = |v: f32| v.round().clamp(0.0, 255.0) as u8; |
| 731 | ( |
| 732 | to_u8(yo + ys * luma), |
| 733 | to_u8(128.0 + cs * cb), |
| 734 | to_u8(128.0 + cs * cr), |
| 735 | ) |
| 736 | } |
| 737 | |
| 738 | |
| 739 | type Rect = (f32, f32, f32, f32); |
| 740 | |
| 741 | |
| 742 | fn grow(acc: Option<Rect>, r: Rect) -> Option<Rect> { |
| 743 | Some(match acc { |
| 744 | None => r, |
| 745 | Some(b) => (b.0.min(r.0), b.1.min(r.1), b.2.max(r.2), b.3.max(r.3)), |
| 746 | }) |
| 747 | } |
| 748 | |
| 749 | |
| 750 | |
| 751 | |
| 752 | |
| 753 | pub fn overlay(style: &TextStyle, width: u32, height: u32, lines: &[String]) -> Overlay { |
| 754 | overlay_stack(style, width, height, &[lines.to_vec()]) |
| 755 | } |
| 756 | |
| 757 | |
| 758 | |
| 759 | |
| 760 | |
| 761 | |
| 762 | |
| 763 | |
| 764 | pub fn overlay_stack( |
| 765 | style: &TextStyle, |
| 766 | width: u32, |
| 767 | height: u32, |
| 768 | blocks: &[Vec<String>], |
| 769 | ) -> Overlay { |
| 770 | let plain: Vec<Block> = blocks |
| 771 | .iter() |
| 772 | .map(|b| Block { lines: b.clone(), fx: Vec::new(), kara: Vec::new() }) |
| 773 | .collect(); |
| 774 | overlay_blocks(style, width, height, &plain) |
| 775 | } |
| 776 | |
| 777 | |
| 778 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 779 | pub struct WordFx { |
| 780 | |
| 781 | pub hidden: bool, |
| 782 | |
| 783 | pub scale: f32, |
| 784 | |
| 785 | pub lift: f32, |
| 786 | |
| 787 | |
| 788 | pub highlight: Option<([u8; 3], bool)>, |
| 789 | } |
| 790 | |
| 791 | impl Default for WordFx { |
| 792 | fn default() -> Self { |
| 793 | Self { hidden: false, scale: 1.0, lift: 0.0, highlight: None } |
| 794 | } |
| 795 | } |
| 796 | |
| 797 | |
| 798 | |
| 799 | |
| 800 | #[derive(Clone, Debug, PartialEq)] |
| 801 | pub struct Block { |
| 802 | pub lines: Vec<String>, |
| 803 | pub fx: Vec<WordFx>, |
| 804 | |
| 805 | pub kara: Vec<Syl>, |
| 806 | } |
| 807 | |
| 808 | |
| 809 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 810 | pub struct Syl { |
| 811 | |
| 812 | pub from: usize, |
| 813 | |
| 814 | pub len: usize, |
| 815 | |
| 816 | |
| 817 | pub left: Option<[u8; 3]>, |
| 818 | pub right: Option<[u8; 3]>, |
| 819 | |
| 820 | pub split: f32, |
| 821 | |
| 822 | pub bare: bool, |
| 823 | } |
| 824 | |
| 825 | |
| 826 | pub fn overlay_blocks(style: &TextStyle, width: u32, height: u32, blocks: &[Block]) -> Overlay { |
| 827 | overlay_blocks_shown(style, width, height, blocks, None) |
| 828 | } |
| 829 | |
| 830 | |
| 831 | |
| 832 | |
| 833 | pub fn overlay_revealed(style: &TextStyle, width: u32, height: u32, lines: &[String], ink: usize) -> Overlay { |
| 834 | overlay_blocks_shown(style, width, height, &[Block { lines: lines.to_vec(), fx: Vec::new(), kara: Vec::new() }], Some(ink)) |
| 835 | } |
| 836 | |
| 837 | |
| 838 | fn overlay_blocks_shown(style: &TextStyle, width: u32, height: u32, blocks: &[Block], shown: Option<usize>) -> Overlay { |
| 839 | let mut out = Overlay::empty(width, height); |
| 840 | let blank = |b: &Block| b.lines.iter().all(|l| l.trim().is_empty()); |
| 841 | if width == 0 || height == 0 || blocks.iter().all(blank) { |
| 842 | return out; |
| 843 | } |
| 844 | let style = style.clamped(); |
| 845 | let em = (style.size as f32 / 1000.0 * height as f32).max(6.0); |
| 846 | let Some(faces) = Faces::with_style(em, &style) else { |
| 847 | return out; |
| 848 | }; |
| 849 | out.ink = style.ink; |
| 850 | out.plate_rgb = [style.box_color[0], style.box_color[1], style.box_color[2]]; |
| 851 | let margin = MARGIN * height as f32; |
| 852 | let max_w = (width as f32 - 2.0 * margin).max(em); |
| 853 | let laid: Vec<(Vec<String>, &[WordFx], &[Syl])> = blocks |
| 854 | .iter() |
| 855 | .filter(|b| !blank(b)) |
| 856 | .map(|b| { |
| 857 | let lines = wrap(&faces, &b.lines, max_w); |
| 858 | |
| 859 | let words = lines.iter().map(|l| l.split_whitespace().count()).sum::<usize>(); |
| 860 | let fx: &[WordFx] = if b.fx.len() == words { &b.fx } else { &[] }; |
| 861 | let kara: &[Syl] = if fx.is_empty() { &b.kara } else { &[] }; |
| 862 | (lines, fx, kara) |
| 863 | }) |
| 864 | .filter(|(w, _, _)| !w.is_empty()) |
| 865 | .collect(); |
| 866 | if laid.is_empty() { |
| 867 | return out; |
| 868 | } |
| 869 | let line_h = (faces.text.height() + faces.text.line_gap()) * 1.1; |
| 870 | let heights: Vec<f32> = laid.iter().map(|(w, _, _)| line_h * w.len() as f32).collect(); |
| 871 | let gap = em * STACK_GAP; |
| 872 | let total = heights.iter().sum::<f32>() + gap * (laid.len() - 1) as f32; |
| 873 | |
| 874 | let tops: Vec<f32> = match style.place { |
| 875 | Place::Top => { |
| 876 | let mut y = margin; |
| 877 | heights |
| 878 | .iter() |
| 879 | .map(|h| { |
| 880 | let t = y; |
| 881 | y += h + gap; |
| 882 | t |
| 883 | }) |
| 884 | .collect() |
| 885 | } |
| 886 | Place::Bottom | Place::Centre => { |
| 887 | let mut y = match style.place { |
| 888 | Place::Centre => (height as f32 + total) / 2.0, |
| 889 | _ => height as f32 - margin, |
| 890 | }; |
| 891 | heights |
| 892 | .iter() |
| 893 | .map(|h| { |
| 894 | y -= h; |
| 895 | let t = y; |
| 896 | y -= gap; |
| 897 | t |
| 898 | }) |
| 899 | .collect() |
| 900 | } |
| 901 | }; |
| 902 | |
| 903 | let mut rects: Vec<Rect> = Vec::with_capacity(laid.len()); |
| 904 | |
| 905 | let mut colour_cells: Option<Rect> = None; |
| 906 | let mut scratch: Vec<u8> = Vec::new(); |
| 907 | |
| 908 | let mut seen = 0usize; |
| 909 | |
| 910 | let mut bare: Vec<(String, f32, f32)> = Vec::new(); |
| 911 | for ((lines, fx, kara), top) in laid.iter().zip(&tops) { |
| 912 | let mut rect: Option<Rect> = None; |
| 913 | let mut next_word = 0; |
| 914 | let mut kara_seen = 0; |
| 915 | let block_w = lines.iter().map(|l| string_width(&faces, l)).fold(0.0f32, f32::max); |
| 916 | |
| 917 | let block_x = match style.hplace { |
| 918 | HPlace::Left => margin, |
| 919 | HPlace::Right => width as f32 - margin - block_w, |
| 920 | HPlace::Centre => (width as f32 - block_w) / 2.0, |
| 921 | }; |
| 922 | for (n, line) in lines.iter().enumerate() { |
| 923 | let line_w = string_width(&faces, line); |
| 924 | let x0 = match (style.hplace, style.align) { |
| 925 | |
| 926 | (HPlace::Centre, Align::Centre) => (width as f32 - line_w) / 2.0, |
| 927 | (_, Align::Centre) => block_x + (block_w - line_w) / 2.0, |
| 928 | (_, Align::Left) => block_x, |
| 929 | (_, Align::Right) => block_x + block_w - line_w, |
| 930 | }; |
| 931 | let baseline = top + n as f32 * line_h + faces.text.ascent(); |
| 932 | let r = ( |
| 933 | x0, |
| 934 | top + n as f32 * line_h, |
| 935 | x0 + line_w, |
| 936 | top + (n as f32 + 1.0) * line_h, |
| 937 | ); |
| 938 | rect = grow(rect, r); |
| 939 | let cell = if !kara.is_empty() { |
| 940 | let at = Pen { x0, baseline, top: top + n as f32 * line_h, line_h }; |
| 941 | draw_line_kara(&mut out, &faces, line, at, kara, &mut kara_seen, &mut scratch, &mut bare) |
| 942 | } else if fx.is_empty() { |
| 943 | let clip = reveal_clip(&faces, line, x0, shown, &mut seen); |
| 944 | draw_line(&mut out, &faces, line, x0, baseline, clip) |
| 945 | } else { |
| 946 | let count = line.split_whitespace().count(); |
| 947 | let at = Pen { x0, baseline, top: top + n as f32 * line_h, line_h }; |
| 948 | let cell = draw_line_fx(&mut out, &faces, line, at, &fx[next_word..next_word + count], &mut scratch); |
| 949 | next_word += count; |
| 950 | cell |
| 951 | }; |
| 952 | if let Some(cell) = cell { |
| 953 | colour_cells = grow(colour_cells, cell); |
| 954 | } |
| 955 | } |
| 956 | rects.extend(rect); |
| 957 | } |
| 958 | let stroke_r = match style.outline { |
| 959 | Outline::None => 0, |
| 960 | Outline::Thin => (em / 24.0).round().max(1.0) as u32, |
| 961 | Outline::Thick => (em / 12.0).round().max(2.0) as u32, |
| 962 | }; |
| 963 | |
| 964 | let pad = em * 0.3 + stroke_r as f32; |
| 965 | let mut bounds: Option<Rect> = colour_cells; |
| 966 | for &(bx0, by0, bx1, by1) in &rects { |
| 967 | bounds = grow(bounds, (bx0 - pad, by0 - pad, bx1 + pad, by1 + pad)); |
| 968 | } |
| 969 | if let Some((x0, y0, x1, y1)) = bounds { |
| 970 | out.bounds = ( |
| 971 | x0.floor().max(0.0) as u32, |
| 972 | y0.floor().max(0.0) as u32, |
| 973 | x1.ceil().min(width as f32) as u32, |
| 974 | y1.ceil().min(height as f32) as u32, |
| 975 | ); |
| 976 | } |
| 977 | if stroke_r > 0 { |
| 978 | |
| 979 | let mut shape = out.fill.clone(); |
| 980 | for (s, c) in shape.iter_mut().zip(&out.colour) { |
| 981 | *s = (*s).max(c[3]); |
| 982 | } |
| 983 | out.stroke = dilate(&shape, width, height, stroke_r); |
| 984 | } |
| 985 | for (text, x, baseline) in &bare { |
| 986 | let ink = Some(out.ink); |
| 987 | let reach = (*x, 0.0, x + string_width(&faces, text), height as f32); |
| 988 | draw_split(&mut out, &faces, text, (*x, *baseline), reach, (f32::INFINITY, ink, ink), &mut scratch); |
| 989 | } |
| 990 | if style.boxed { |
| 991 | for &(bx0, by0, bx1, by1) in &rects { |
| 992 | let (px0, py0) = ( |
| 993 | (bx0 - em * 0.3).floor().max(0.0) as u32, |
| 994 | (by0 - em * 0.15).floor().max(0.0) as u32, |
| 995 | ); |
| 996 | let (px1, py1) = ( |
| 997 | (bx1 + em * 0.3).ceil().min(width as f32) as u32, |
| 998 | (by1 + em * 0.15).ceil().min(height as f32) as u32, |
| 999 | ); |
| 1000 | for y in py0..py1 { |
| 1001 | let row = y as usize * width as usize; |
| 1002 | for x in px0..px1 { |
| 1003 | out.plate[row + x as usize] = style.box_color[3]; |
| 1004 | } |
| 1005 | } |
| 1006 | } |
| 1007 | } |
| 1008 | out |
| 1009 | } |
| 1010 | |
| 1011 | |
| 1012 | |
| 1013 | |
| 1014 | |
| 1015 | pub fn layout_share(style: &TextStyle, width: u32, height: u32, lines: &[String]) -> (usize, f32) { |
| 1016 | if width == 0 || height == 0 || lines.iter().all(|l| l.trim().is_empty()) { |
| 1017 | return (0, 0.0); |
| 1018 | } |
| 1019 | let style = style.clamped(); |
| 1020 | let em = (style.size as f32 / 1000.0 * height as f32).max(6.0); |
| 1021 | let Some(faces) = Faces::with_style(em, &style) else { |
| 1022 | return (0, 0.0); |
| 1023 | }; |
| 1024 | let margin = MARGIN * height as f32; |
| 1025 | let max_w = (width as f32 - 2.0 * margin).max(em); |
| 1026 | let count = wrap(&faces, lines, max_w).len(); |
| 1027 | let line_h = (faces.text.height() + faces.text.line_gap()) * 1.1; |
| 1028 | (count, line_h * count as f32 / height as f32) |
| 1029 | } |
| 1030 | |
| 1031 | |
| 1032 | |
| 1033 | pub fn draw_text(canvas: &mut [u8], width: u32, height: u32, style: &TextStyle, lines: &[String]) { |
| 1034 | overlay(style, width, height, lines).blend_bgra(canvas); |
| 1035 | } |
| 1036 | |
| 1037 | |
| 1038 | |
| 1039 | |
| 1040 | |
| 1041 | pub fn missing_glyphs(lines: &[String]) -> Vec<char> { |
| 1042 | let mut out: Vec<char> = Vec::new(); |
| 1043 | for c in lines.iter().flat_map(|l| l.chars()) { |
| 1044 | if c.is_whitespace() || is_invisible(c) || out.contains(&c) { |
| 1045 | continue; |
| 1046 | } |
| 1047 | if lookup(c).is_none() { |
| 1048 | out.push(c); |
| 1049 | } |
| 1050 | } |
| 1051 | out |
| 1052 | } |
| 1053 | |
| 1054 | |
| 1055 | |
| 1056 | |
| 1057 | fn is_invisible(c: char) -> bool { |
| 1058 | matches!(c, '\u{200D}' | '\u{FE00}'..='\u{FE0F}' | '\u{E0100}'..='\u{E01EF}') |
| 1059 | } |
| 1060 | |
| 1061 | |
| 1062 | |
| 1063 | |
| 1064 | struct Faces { |
| 1065 | em: f32, |
| 1066 | |
| 1067 | bold: bool, |
| 1068 | text: Scaled<'static>, |
| 1069 | |
| 1070 | family: Option<Family>, |
| 1071 | } |
| 1072 | |
| 1073 | impl Faces { |
| 1074 | #[cfg(test)] |
| 1075 | fn new(em: f32) -> Option<Self> { |
| 1076 | Self::with_weight(em, Weight::Regular) |
| 1077 | } |
| 1078 | |
| 1079 | fn with_weight(em: f32, weight: Weight) -> Option<Self> { |
| 1080 | let bold = weight == Weight::Bold; |
| 1081 | let text = outline_face(if bold { ARCHIVO_BOLD } else { ARCHIVO })?.as_scaled(PxScale::from(em)); |
| 1082 | Some(Self { em, bold, text, family: None }) |
| 1083 | } |
| 1084 | |
| 1085 | |
| 1086 | fn with_style(em: f32, style: &TextStyle) -> Option<Self> { |
| 1087 | let mut faces = Self::with_weight(em, style.weight)?; |
| 1088 | faces.family = style.family.as_deref().and_then(family_face); |
| 1089 | Some(faces) |
| 1090 | } |
| 1091 | |
| 1092 | |
| 1093 | fn rescaled(&self, em: f32) -> Option<Self> { |
| 1094 | let mut faces = Self::with_weight(em, if self.bold { Weight::Bold } else { Weight::Regular })?; |
| 1095 | faces.family = self.family; |
| 1096 | Some(faces) |
| 1097 | } |
| 1098 | |
| 1099 | |
| 1100 | |
| 1101 | fn font(&self, src: Src) -> Option<Scaled<'static>> { |
| 1102 | match src { |
| 1103 | Src::Outline(i) => { |
| 1104 | let i = if self.bold && i == ARCHIVO { ARCHIVO_BOLD } else { i }; |
| 1105 | let px = PxScale::from(self.em * face_k()[i]); |
| 1106 | Some(outline_face(i)?.as_scaled(px)) |
| 1107 | } |
| 1108 | Src::Family => { |
| 1109 | let family = self.family?; |
| 1110 | Some(family.font.as_scaled(PxScale::from(self.em * family.k))) |
| 1111 | } |
| 1112 | Src::Cjk | Src::Colour => None, |
| 1113 | } |
| 1114 | } |
| 1115 | } |
| 1116 | |
| 1117 | |
| 1118 | |
| 1119 | |
| 1120 | |
| 1121 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 1122 | struct Placed { |
| 1123 | src: Src, |
| 1124 | id: u16, |
| 1125 | kern: f32, |
| 1126 | shift: f32, |
| 1127 | lift: f32, |
| 1128 | advance: f32, |
| 1129 | } |
| 1130 | |
| 1131 | |
| 1132 | |
| 1133 | fn visual_parts(s: &str) -> Vec<(bool, &str)> { |
| 1134 | |
| 1135 | if s.is_ascii() { |
| 1136 | return vec![(false, s)]; |
| 1137 | } |
| 1138 | let info = BidiInfo::new(s, None); |
| 1139 | if !info.has_rtl() { |
| 1140 | return vec![(false, s)]; |
| 1141 | } |
| 1142 | info.paragraphs |
| 1143 | .iter() |
| 1144 | .flat_map(|para| { |
| 1145 | let (levels, runs) = info.visual_runs(para, para.range.clone()); |
| 1146 | runs.into_iter() |
| 1147 | .map(|r| (levels[r.start].is_rtl(), &s[r])) |
| 1148 | .collect::<Vec<_>>() |
| 1149 | }) |
| 1150 | .collect() |
| 1151 | } |
| 1152 | |
| 1153 | |
| 1154 | |
| 1155 | fn segments(faces: &Faces, part: &str) -> Vec<(Src, String)> { |
| 1156 | let mut out: Vec<(Src, String)> = Vec::new(); |
| 1157 | for ch in part.chars() { |
| 1158 | if is_invisible(ch) { |
| 1159 | continue; |
| 1160 | } |
| 1161 | let (src, _) = pick_in(faces, ch); |
| 1162 | match out.last_mut() { |
| 1163 | Some((s, text)) if *s == src => text.push(ch), |
| 1164 | _ => out.push((src, ch.to_string())), |
| 1165 | } |
| 1166 | } |
| 1167 | out |
| 1168 | } |
| 1169 | |
| 1170 | |
| 1171 | |
| 1172 | |
| 1173 | fn run(faces: &Faces, s: &str) -> Vec<Placed> { |
| 1174 | let mut out = Vec::new(); |
| 1175 | for (rtl, part) in visual_parts(s) { |
| 1176 | let mut segs = segments(faces, part); |
| 1177 | if rtl { |
| 1178 | segs.reverse(); |
| 1179 | } |
| 1180 | for (src, text) in segs { |
| 1181 | out.extend(place(faces, src, &text, rtl)); |
| 1182 | } |
| 1183 | } |
| 1184 | out |
| 1185 | } |
| 1186 | |
| 1187 | |
| 1188 | |
| 1189 | |
| 1190 | fn place(faces: &Faces, src: Src, text: &str, rtl: bool) -> Vec<Placed> { |
| 1191 | match src { |
| 1192 | Src::Outline(i) if (NOTO_SANS..MONO_EMOJI).contains(&i) => { |
| 1193 | shape(faces, i, text, rtl).unwrap_or_else(|| plain(faces, src, text)) |
| 1194 | } |
| 1195 | Src::Colour => colour_glyphs(faces, text), |
| 1196 | Src::Cjk => cjk_glyphs(faces, text), |
| 1197 | _ => plain(faces, src, text), |
| 1198 | } |
| 1199 | } |
| 1200 | |
| 1201 | |
| 1202 | |
| 1203 | fn plain(faces: &Faces, src: Src, text: &str) -> Vec<Placed> { |
| 1204 | let Some(font) = faces.font(src) else { |
| 1205 | return Vec::new(); |
| 1206 | }; |
| 1207 | let mut out = Vec::new(); |
| 1208 | let mut prev: Option<GlyphId> = None; |
| 1209 | for c in text.chars() { |
| 1210 | let id = font.glyph_id(c); |
| 1211 | let kern = prev.map_or(0.0, |p| font.kern(p, id)); |
| 1212 | out.push(Placed { |
| 1213 | src, |
| 1214 | id: id.0, |
| 1215 | kern, |
| 1216 | shift: 0.0, |
| 1217 | lift: 0.0, |
| 1218 | advance: font.h_advance(id), |
| 1219 | }); |
| 1220 | prev = Some(id); |
| 1221 | } |
| 1222 | out |
| 1223 | } |
| 1224 | |
| 1225 | |
| 1226 | |
| 1227 | fn shape(faces: &Faces, i: usize, text: &str, rtl: bool) -> Option<Vec<Placed>> { |
| 1228 | let face = shaper(i)?; |
| 1229 | let mut buf = rustybuzz::UnicodeBuffer::new(); |
| 1230 | buf.push_str(text); |
| 1231 | buf.set_direction(if rtl { |
| 1232 | rustybuzz::Direction::RightToLeft |
| 1233 | } else { |
| 1234 | rustybuzz::Direction::LeftToRight |
| 1235 | }); |
| 1236 | let glyphs = rustybuzz::shape(face, &[], buf); |
| 1237 | |
| 1238 | let scale = faces.em / outline_face(i)?.height_unscaled(); |
| 1239 | Some( |
| 1240 | glyphs |
| 1241 | .glyph_infos() |
| 1242 | .iter() |
| 1243 | .zip(glyphs.glyph_positions()) |
| 1244 | .map(|(info, pos)| Placed { |
| 1245 | src: Src::Outline(i), |
| 1246 | id: info.glyph_id as u16, |
| 1247 | kern: 0.0, |
| 1248 | shift: pos.x_offset as f32 * scale, |
| 1249 | lift: pos.y_offset as f32 * scale, |
| 1250 | advance: pos.x_advance as f32 * scale, |
| 1251 | }) |
| 1252 | .collect(), |
| 1253 | ) |
| 1254 | } |
| 1255 | |
| 1256 | |
| 1257 | |
| 1258 | fn cjk_glyphs(faces: &Faces, text: &str) -> Vec<Placed> { |
| 1259 | let Some(face) = cjk_face() else { |
| 1260 | return Vec::new(); |
| 1261 | }; |
| 1262 | let scale = faces.em / f32::from(face.units_per_em()); |
| 1263 | text.chars() |
| 1264 | .filter_map(|c| face.glyph_index(c)) |
| 1265 | .map(|g| Placed { |
| 1266 | src: Src::Cjk, |
| 1267 | id: g.0, |
| 1268 | kern: 0.0, |
| 1269 | shift: 0.0, |
| 1270 | lift: 0.0, |
| 1271 | advance: f32::from(face.glyph_hor_advance(g).unwrap_or(0)) * scale, |
| 1272 | }) |
| 1273 | .collect() |
| 1274 | } |
| 1275 | |
| 1276 | |
| 1277 | |
| 1278 | fn colour_glyphs(faces: &Faces, text: &str) -> Vec<Placed> { |
| 1279 | let Some(face) = colour_face() else { |
| 1280 | return Vec::new(); |
| 1281 | }; |
| 1282 | let scale = em_scale(faces.em, face); |
| 1283 | text.chars() |
| 1284 | .filter_map(|c| face.glyph_index(c)) |
| 1285 | .map(|g| Placed { |
| 1286 | src: Src::Colour, |
| 1287 | id: g.0, |
| 1288 | kern: 0.0, |
| 1289 | shift: 0.0, |
| 1290 | lift: 0.0, |
| 1291 | advance: f32::from(face.glyph_hor_advance(g).unwrap_or(0)) * scale, |
| 1292 | }) |
| 1293 | .collect() |
| 1294 | } |
| 1295 | |
| 1296 | |
| 1297 | struct Pen { |
| 1298 | x0: f32, |
| 1299 | baseline: f32, |
| 1300 | top: f32, |
| 1301 | line_h: f32, |
| 1302 | } |
| 1303 | |
| 1304 | |
| 1305 | |
| 1306 | |
| 1307 | |
| 1308 | fn draw_line_fx( |
| 1309 | out: &mut Overlay, |
| 1310 | faces: &Faces, |
| 1311 | line: &str, |
| 1312 | at: Pen, |
| 1313 | fx: &[WordFx], |
| 1314 | scratch: &mut Vec<u8>, |
| 1315 | ) -> Option<Rect> { |
| 1316 | let words: Vec<&str> = line.split_whitespace().collect(); |
| 1317 | let em = faces.em; |
| 1318 | let mut cells: Option<Rect> = None; |
| 1319 | for (i, (word, f)) in words.iter().zip(fx).enumerate() { |
| 1320 | if f.hidden { |
| 1321 | continue; |
| 1322 | } |
| 1323 | let before = if i == 0 { 0.0 } else { string_width(faces, &format!("{} ", words[..i].join(" "))) }; |
| 1324 | let natural = string_width(faces, word); |
| 1325 | let scaled = faces.rescaled(em * f.scale.max(0.1)); |
| 1326 | let face = scaled.as_ref().unwrap_or(faces); |
| 1327 | let width = string_width(face, word); |
| 1328 | let x = at.x0 + before + (natural - width) / 2.0; |
| 1329 | let baseline = at.baseline - f.lift * em; |
| 1330 | let reach = (x - 0.25 * em, baseline - 1.3 * face.em, x + width + 0.25 * em, baseline + 0.5 * face.em); |
| 1331 | match f.highlight { |
| 1332 | None => { |
| 1333 | if let Some(c) = draw_line(out, face, word, x, baseline, f32::INFINITY) { |
| 1334 | cells = grow(cells, c); |
| 1335 | } |
| 1336 | if f.scale != 1.0 || f.lift != 0.0 { |
| 1337 | cells = grow(cells, reach); |
| 1338 | } |
| 1339 | } |
| 1340 | Some((rgb, boxed)) => { |
| 1341 | let colour = if boxed { |
| 1342 | let (px, py) = (0.2 * em, at.line_h * 0.04); |
| 1343 | let r = (at.x0 + before - px, at.top + py, at.x0 + before + natural + px, at.top + at.line_h - py); |
| 1344 | rounded_box(out, r, rgb); |
| 1345 | cells = grow(cells, r); |
| 1346 | [255, 255, 255] |
| 1347 | } else { |
| 1348 | rgb |
| 1349 | }; |
| 1350 | |
| 1351 | let n = out.fill.len(); |
| 1352 | scratch.clear(); |
| 1353 | scratch.resize(n, 0); |
| 1354 | std::mem::swap(&mut out.fill, scratch); |
| 1355 | let c = draw_line(out, face, word, x, baseline, f32::INFINITY); |
| 1356 | std::mem::swap(&mut out.fill, scratch); |
| 1357 | let (w, h) = (out.width as usize, out.height as usize); |
| 1358 | let (x0, x1) = (reach.0.max(0.0) as usize, (reach.2.ceil().max(0.0) as usize).min(w)); |
| 1359 | let (y0, y1) = (reach.1.max(0.0) as usize, (reach.3.ceil().max(0.0) as usize).min(h)); |
| 1360 | for py in y0..y1 { |
| 1361 | for px in x0..x1 { |
| 1362 | let a = scratch[py * w + px]; |
| 1363 | if a > 0 { |
| 1364 | put_colour(out, py * w + px, colour, a); |
| 1365 | } |
| 1366 | } |
| 1367 | } |
| 1368 | cells = grow(cells, reach); |
| 1369 | if let Some(c) = c { |
| 1370 | cells = grow(cells, c); |
| 1371 | } |
| 1372 | } |
| 1373 | } |
| 1374 | } |
| 1375 | cells |
| 1376 | } |
| 1377 | |
| 1378 | |
| 1379 | |
| 1380 | |
| 1381 | |
| 1382 | |
| 1383 | #[allow(clippy::too_many_arguments)] |
| 1384 | fn draw_line_kara( |
| 1385 | out: &mut Overlay, |
| 1386 | faces: &Faces, |
| 1387 | line: &str, |
| 1388 | at: Pen, |
| 1389 | kara: &[Syl], |
| 1390 | seen: &mut usize, |
| 1391 | scratch: &mut Vec<u8>, |
| 1392 | bare: &mut Vec<(String, f32, f32)>, |
| 1393 | ) -> Option<Rect> { |
| 1394 | |
| 1395 | let letters: Vec<(usize, char)> = line.char_indices().filter(|(_, c)| !c.is_whitespace()).collect(); |
| 1396 | let owner: Vec<Option<usize>> = letters |
| 1397 | .iter() |
| 1398 | .map(|_| { |
| 1399 | *seen += 1; |
| 1400 | kara.iter().position(|k| (k.from..k.from + k.len).contains(&(*seen - 1))) |
| 1401 | }) |
| 1402 | .collect(); |
| 1403 | let mut cells: Option<Rect> = None; |
| 1404 | let mut i = 0; |
| 1405 | while i < letters.len() { |
| 1406 | |
| 1407 | let mut j = i + 1; |
| 1408 | while j < letters.len() && owner[j] == owner[i] { |
| 1409 | j += 1; |
| 1410 | } |
| 1411 | let (start, (last, c)) = (letters[i].0, letters[j - 1]); |
| 1412 | let text = &line[start..last + c.len_utf8()]; |
| 1413 | let x = at.x0 + string_width(faces, &line[..start]); |
| 1414 | match owner[i].map(|k| kara[k]) { |
| 1415 | None => { |
| 1416 | if let Some(c) = draw_line(out, faces, text, x, at.baseline, f32::INFINITY) { |
| 1417 | cells = grow(cells, c); |
| 1418 | } |
| 1419 | } |
| 1420 | Some(k) if k.bare => bare.push((text.to_string(), x, at.baseline)), |
| 1421 | Some(k) => { |
| 1422 | let em = faces.em; |
| 1423 | let w = string_width(faces, text); |
| 1424 | let reach = (x - 0.25 * em, at.baseline - 1.3 * em, x + w + 0.25 * em, at.baseline + 0.5 * em); |
| 1425 | draw_split(out, faces, text, (x, at.baseline), reach, (x + w * k.split, k.left, k.right), scratch); |
| 1426 | cells = grow(cells, reach); |
| 1427 | } |
| 1428 | } |
| 1429 | i = j; |
| 1430 | } |
| 1431 | cells |
| 1432 | } |
| 1433 | |
| 1434 | |
| 1435 | |
| 1436 | fn reveal_clip(faces: &Faces, line: &str, x0: f32, shown: Option<usize>, seen: &mut usize) -> f32 { |
| 1437 | let Some(shown) = shown else { return f32::INFINITY }; |
| 1438 | let ink = line.chars().filter(|c| !c.is_whitespace()).count(); |
| 1439 | let here = shown.saturating_sub(*seen).min(ink); |
| 1440 | *seen += ink; |
| 1441 | if here == ink { |
| 1442 | return f32::INFINITY; |
| 1443 | } |
| 1444 | if here == 0 { |
| 1445 | return f32::NEG_INFINITY; |
| 1446 | } |
| 1447 | |
| 1448 | let cut = line.char_indices().filter(|(_, c)| !c.is_whitespace()).nth(here).map_or(line.len(), |(i, _)| i); |
| 1449 | x0 + string_width(faces, &line[..cut]) |
| 1450 | } |
| 1451 | |
| 1452 | |
| 1453 | |
| 1454 | |
| 1455 | fn draw_split( |
| 1456 | out: &mut Overlay, |
| 1457 | faces: &Faces, |
| 1458 | text: &str, |
| 1459 | (x, baseline): (f32, f32), |
| 1460 | reach: Rect, |
| 1461 | (split, left, right): (f32, Option<[u8; 3]>, Option<[u8; 3]>), |
| 1462 | scratch: &mut Vec<u8>, |
| 1463 | ) { |
| 1464 | |
| 1465 | let n = out.fill.len(); |
| 1466 | scratch.clear(); |
| 1467 | scratch.resize(n, 0); |
| 1468 | std::mem::swap(&mut out.fill, scratch); |
| 1469 | draw_line(out, faces, text, x, baseline, f32::INFINITY); |
| 1470 | std::mem::swap(&mut out.fill, scratch); |
| 1471 | let (w, h) = (out.width as usize, out.height as usize); |
| 1472 | let (x0, x1) = (reach.0.max(0.0) as usize, (reach.2.ceil().max(0.0) as usize).min(w)); |
| 1473 | let (y0, y1) = (reach.1.max(0.0) as usize, (reach.3.ceil().max(0.0) as usize).min(h)); |
| 1474 | for py in y0..y1 { |
| 1475 | for px in x0..x1 { |
| 1476 | let a = scratch[py * w + px]; |
| 1477 | if a == 0 { |
| 1478 | continue; |
| 1479 | } |
| 1480 | match if (px as f32 + 0.5) < split { left } else { right } { |
| 1481 | None => out.fill[py * w + px] = out.fill[py * w + px].max(a), |
| 1482 | Some(rgb) => put_colour(out, py * w + px, rgb, a), |
| 1483 | } |
| 1484 | } |
| 1485 | } |
| 1486 | } |
| 1487 | |
| 1488 | |
| 1489 | fn put_colour(out: &mut Overlay, i: usize, rgb: [u8; 3], a: u8) { |
| 1490 | if out.colour.is_empty() { |
| 1491 | out.colour = vec![[0; 4]; out.width as usize * out.height as usize]; |
| 1492 | } |
| 1493 | let d = out.colour[i]; |
| 1494 | let (sa, da) = (f32::from(a) / 255.0, f32::from(d[3]) / 255.0); |
| 1495 | let oa = sa + da * (1.0 - sa); |
| 1496 | if oa <= 0.0 { |
| 1497 | return; |
| 1498 | } |
| 1499 | let mut v = [0u8; 4]; |
| 1500 | for k in 0..3 { |
| 1501 | let c = (f32::from(rgb[k]) * sa + f32::from(d[k]) * da * (1.0 - sa)) / oa; |
| 1502 | v[k] = c.round().clamp(0.0, 255.0) as u8; |
| 1503 | } |
| 1504 | v[3] = (oa * 255.0).round().clamp(0.0, 255.0) as u8; |
| 1505 | out.colour[i] = v; |
| 1506 | } |
| 1507 | |
| 1508 | |
| 1509 | fn rounded_box(out: &mut Overlay, r: Rect, rgb: [u8; 3]) { |
| 1510 | let (w, h) = (out.width as usize, out.height as usize); |
| 1511 | let rad = (r.3 - r.1) * 0.28; |
| 1512 | let (cx, cy) = ((r.0 + r.2) / 2.0, (r.1 + r.3) / 2.0); |
| 1513 | let (hx, hy) = ((r.2 - r.0) / 2.0 - rad, (r.3 - r.1) / 2.0 - rad); |
| 1514 | let (x0, x1) = (r.0.floor().max(0.0) as usize, (r.2.ceil().max(0.0) as usize).min(w)); |
| 1515 | let (y0, y1) = (r.1.floor().max(0.0) as usize, (r.3.ceil().max(0.0) as usize).min(h)); |
| 1516 | for py in y0..y1 { |
| 1517 | for px in x0..x1 { |
| 1518 | let (dx, dy) = ((px as f32 + 0.5 - cx).abs() - hx, (py as f32 + 0.5 - cy).abs() - hy); |
| 1519 | let d = dx.max(0.0).hypot(dy.max(0.0)) + dx.max(dy).min(0.0) - rad; |
| 1520 | let a = (0.5 - d).clamp(0.0, 1.0); |
| 1521 | if a > 0.0 { |
| 1522 | put_colour(out, py * w + px, rgb, (a * 255.0).round() as u8); |
| 1523 | } |
| 1524 | } |
| 1525 | } |
| 1526 | } |
| 1527 | |
| 1528 | |
| 1529 | |
| 1530 | |
| 1531 | |
| 1532 | fn draw_line(out: &mut Overlay, faces: &Faces, line: &str, x0: f32, baseline: f32, clip: f32) -> Option<Rect> { |
| 1533 | let (width, height) = (out.width, out.height); |
| 1534 | let (w, h) = (width as i32, height as i32); |
| 1535 | let mut caret = x0; |
| 1536 | let mut cells: Option<Rect> = None; |
| 1537 | for p in run(faces, line) { |
| 1538 | caret += p.kern; |
| 1539 | match p.src { |
| 1540 | Src::Colour if caret >= clip => {} |
| 1541 | Src::Colour => { |
| 1542 | if let Some(cell) = draw_colour(out, faces.em, p.id, caret, baseline) { |
| 1543 | cells = grow(cells, cell); |
| 1544 | } |
| 1545 | } |
| 1546 | Src::Cjk if caret >= clip => {} |
| 1547 | Src::Cjk => { |
| 1548 | if let Some(face) = cjk_face() { |
| 1549 | let scale = faces.em / f32::from(face.units_per_em()); |
| 1550 | let cell = draw_outline(out, face, p.id, scale, caret, baseline); |
| 1551 | if let Some(cell) = cell { |
| 1552 | cells = grow(cells, cell); |
| 1553 | } |
| 1554 | } |
| 1555 | } |
| 1556 | src => { |
| 1557 | if let Some(font) = faces.font(src) { |
| 1558 | let at = point(caret + p.shift, baseline - p.lift); |
| 1559 | let glyph = GlyphId(p.id).with_scale_and_position(font.scale(), at); |
| 1560 | if let Some(og) = font.outline_glyph(glyph) { |
| 1561 | let b = og.px_bounds(); |
| 1562 | |
| 1563 | if src != Src::Outline(ARCHIVO) { |
| 1564 | let ink = (b.min.x, b.min.y, b.max.x, b.max.y); |
| 1565 | cells = grow(cells, ink); |
| 1566 | } |
| 1567 | let fill = &mut out.fill; |
| 1568 | og.draw(|gx, gy, c| { |
| 1569 | let x = b.min.x as i32 + gx as i32; |
| 1570 | let y = b.min.y as i32 + gy as i32; |
| 1571 | if x >= 0 && y >= 0 && x < w && y < h && (x as f32) < clip { |
| 1572 | let i = y as usize * width as usize + x as usize; |
| 1573 | fill[i] = fill[i].max((c * 255.0).round() as u8); |
| 1574 | } |
| 1575 | }); |
| 1576 | } |
| 1577 | } |
| 1578 | } |
| 1579 | } |
| 1580 | caret += p.advance; |
| 1581 | } |
| 1582 | cells |
| 1583 | } |
| 1584 | |
| 1585 | |
| 1586 | |
| 1587 | |
| 1588 | fn draw_outline( |
| 1589 | out: &mut Overlay, |
| 1590 | face: &ttf_parser::Face<'_>, |
| 1591 | id: u16, |
| 1592 | scale: f32, |
| 1593 | x: f32, |
| 1594 | baseline: f32, |
| 1595 | ) -> Option<Rect> { |
| 1596 | let bb = face.glyph_bounding_box(ttf_parser::GlyphId(id))?; |
| 1597 | let (ex0, ey0) = ( |
| 1598 | x + f32::from(bb.x_min) * scale, |
| 1599 | baseline - f32::from(bb.y_max) * scale, |
| 1600 | ); |
| 1601 | let (ex1, ey1) = ( |
| 1602 | x + f32::from(bb.x_max) * scale, |
| 1603 | baseline - f32::from(bb.y_min) * scale, |
| 1604 | ); |
| 1605 | |
| 1606 | let (cx0, cy0) = ((ex0.floor() - 1.0).max(0.0), (ey0.floor() - 1.0).max(0.0)); |
| 1607 | let (cx1, cy1) = ( |
| 1608 | (ex1.ceil() + 1.0).min(out.width as f32), |
| 1609 | (ey1.ceil() + 1.0).min(out.height as f32), |
| 1610 | ); |
| 1611 | if cx1 <= cx0 || cy1 <= cy0 { |
| 1612 | return None; |
| 1613 | } |
| 1614 | let (w, h) = ((cx1 - cx0) as usize, (cy1 - cy0) as usize); |
| 1615 | let mut ras = ab_glyph_rasterizer::Rasterizer::new(w, h); |
| 1616 | let mut path = CellPath { |
| 1617 | ras: &mut ras, |
| 1618 | t: IDENTITY, |
| 1619 | scale, |
| 1620 | origin: (x - cx0, baseline - cy0), |
| 1621 | last: ab_glyph_rasterizer::point(0.0, 0.0), |
| 1622 | start: ab_glyph_rasterizer::point(0.0, 0.0), |
| 1623 | }; |
| 1624 | face.outline_glyph(ttf_parser::GlyphId(id), &mut path); |
| 1625 | |
| 1626 | ttf_parser::OutlineBuilder::close(&mut path); |
| 1627 | let stride = out.width as usize; |
| 1628 | let (ox, oy) = (cx0 as usize, cy0 as usize); |
| 1629 | let fill = &mut out.fill; |
| 1630 | ras.for_each_pixel_2d(|px, py, cov| { |
| 1631 | let i = (oy + py as usize) * stride + ox + px as usize; |
| 1632 | fill[i] = fill[i].max((cov.clamp(0.0, 1.0) * 255.0).round() as u8); |
| 1633 | }); |
| 1634 | Some((cx0, cy0, cx1, cy1)) |
| 1635 | } |
| 1636 | |
| 1637 | |
| 1638 | type Scaled<'a> = ab_glyph::PxScaleFont<&'a FontRef<'static>>; |
| 1639 | |
| 1640 | |
| 1641 | fn string_width(faces: &Faces, s: &str) -> f32 { |
| 1642 | run(faces, s).iter().map(|p| p.kern + p.advance).sum() |
| 1643 | } |
| 1644 | |
| 1645 | |
| 1646 | |
| 1647 | fn compose(outer: [f32; 6], inner: [f32; 6]) -> [f32; 6] { |
| 1648 | let [a1, b1, c1, d1, e1, f1] = outer; |
| 1649 | let [a2, b2, c2, d2, e2, f2] = inner; |
| 1650 | [ |
| 1651 | a1 * a2 + c1 * b2, |
| 1652 | b1 * a2 + d1 * b2, |
| 1653 | a1 * c2 + c1 * d2, |
| 1654 | b1 * c2 + d1 * d2, |
| 1655 | a1 * e2 + c1 * f2 + e1, |
| 1656 | b1 * e2 + d1 * f2 + f1, |
| 1657 | ] |
| 1658 | } |
| 1659 | |
| 1660 | const IDENTITY: [f32; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; |
| 1661 | |
| 1662 | |
| 1663 | |
| 1664 | |
| 1665 | |
| 1666 | struct ColourPainter<'a> { |
| 1667 | face: &'a ttf_parser::Face<'a>, |
| 1668 | |
| 1669 | scale: f32, |
| 1670 | |
| 1671 | origin: (f32, f32), |
| 1672 | width: usize, |
| 1673 | height: usize, |
| 1674 | |
| 1675 | transforms: Vec<[f32; 6]>, |
| 1676 | |
| 1677 | glyph: Option<ttf_parser::GlyphId>, |
| 1678 | |
| 1679 | canvas: Vec<[f32; 4]>, |
| 1680 | } |
| 1681 | |
| 1682 | impl ColourPainter<'_> { |
| 1683 | fn top(&self) -> [f32; 6] { |
| 1684 | self.transforms.last().copied().unwrap_or(IDENTITY) |
| 1685 | } |
| 1686 | } |
| 1687 | |
| 1688 | |
| 1689 | struct CellPath<'r> { |
| 1690 | ras: &'r mut ab_glyph_rasterizer::Rasterizer, |
| 1691 | t: [f32; 6], |
| 1692 | scale: f32, |
| 1693 | origin: (f32, f32), |
| 1694 | last: ab_glyph_rasterizer::Point, |
| 1695 | start: ab_glyph_rasterizer::Point, |
| 1696 | } |
| 1697 | |
| 1698 | impl CellPath<'_> { |
| 1699 | fn map(&self, x: f32, y: f32) -> ab_glyph_rasterizer::Point { |
| 1700 | let [a, b, c, d, e, f] = self.t; |
| 1701 | let (tx, ty) = (a * x + c * y + e, b * x + d * y + f); |
| 1702 | ab_glyph_rasterizer::point( |
| 1703 | self.origin.0 + tx * self.scale, |
| 1704 | self.origin.1 - ty * self.scale, |
| 1705 | ) |
| 1706 | } |
| 1707 | } |
| 1708 | |
| 1709 | impl ttf_parser::OutlineBuilder for CellPath<'_> { |
| 1710 | fn move_to(&mut self, x: f32, y: f32) { |
| 1711 | let p = self.map(x, y); |
| 1712 | self.start = p; |
| 1713 | self.last = p; |
| 1714 | } |
| 1715 | |
| 1716 | fn line_to(&mut self, x: f32, y: f32) { |
| 1717 | let p = self.map(x, y); |
| 1718 | self.ras.draw_line(self.last, p); |
| 1719 | self.last = p; |
| 1720 | } |
| 1721 | |
| 1722 | fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) { |
| 1723 | let (c, p) = (self.map(x1, y1), self.map(x, y)); |
| 1724 | self.ras.draw_quad(self.last, c, p); |
| 1725 | self.last = p; |
| 1726 | } |
| 1727 | |
| 1728 | fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) { |
| 1729 | let (c1, c2, p) = (self.map(x1, y1), self.map(x2, y2), self.map(x, y)); |
| 1730 | self.ras.draw_cubic(self.last, c1, c2, p); |
| 1731 | self.last = p; |
| 1732 | } |
| 1733 | |
| 1734 | fn close(&mut self) { |
| 1735 | self.ras.draw_line(self.last, self.start); |
| 1736 | self.last = self.start; |
| 1737 | } |
| 1738 | } |
| 1739 | |
| 1740 | impl<'a> ttf_parser::colr::Painter<'a> for ColourPainter<'a> { |
| 1741 | fn outline_glyph(&mut self, glyph_id: ttf_parser::GlyphId) { |
| 1742 | self.glyph = Some(glyph_id); |
| 1743 | } |
| 1744 | |
| 1745 | fn paint(&mut self, paint: ttf_parser::colr::Paint<'a>) { |
| 1746 | use ttf_parser::colr::Paint; |
| 1747 | let Some(glyph) = self.glyph else { |
| 1748 | return; |
| 1749 | }; |
| 1750 | let colour = match paint { |
| 1751 | Paint::Solid(c) => c, |
| 1752 | Paint::LinearGradient(g) => mean_stop(g.stops(0, &[])), |
| 1753 | Paint::RadialGradient(g) => mean_stop(g.stops(0, &[])), |
| 1754 | Paint::SweepGradient(g) => mean_stop(g.stops(0, &[])), |
| 1755 | }; |
| 1756 | let (w, h) = (self.width, self.height); |
| 1757 | let mut ras = ab_glyph_rasterizer::Rasterizer::new(w, h); |
| 1758 | let mut path = CellPath { |
| 1759 | ras: &mut ras, |
| 1760 | t: self.top(), |
| 1761 | scale: self.scale, |
| 1762 | origin: self.origin, |
| 1763 | last: ab_glyph_rasterizer::point(0.0, 0.0), |
| 1764 | start: ab_glyph_rasterizer::point(0.0, 0.0), |
| 1765 | }; |
| 1766 | self.face.outline_glyph(glyph, &mut path); |
| 1767 | ttf_parser::OutlineBuilder::close(&mut path); |
| 1768 | let alpha = f32::from(colour.alpha) / 255.0; |
| 1769 | let rgb = [ |
| 1770 | f32::from(colour.red) / 255.0, |
| 1771 | f32::from(colour.green) / 255.0, |
| 1772 | f32::from(colour.blue) / 255.0, |
| 1773 | ]; |
| 1774 | let canvas = &mut self.canvas; |
| 1775 | ras.for_each_pixel_2d(|x, y, cover| { |
| 1776 | let sa = cover.clamp(0.0, 1.0) * alpha; |
| 1777 | if sa <= 0.0 || x as usize >= w || y as usize >= h { |
| 1778 | return; |
| 1779 | } |
| 1780 | let d = &mut canvas[y as usize * w + x as usize]; |
| 1781 | let keep = 1.0 - sa; |
| 1782 | *d = [ |
| 1783 | rgb[0] * sa + d[0] * keep, |
| 1784 | rgb[1] * sa + d[1] * keep, |
| 1785 | rgb[2] * sa + d[2] * keep, |
| 1786 | sa + d[3] * keep, |
| 1787 | ]; |
| 1788 | }); |
| 1789 | } |
| 1790 | |
| 1791 | fn push_clip(&mut self) {} |
| 1792 | |
| 1793 | fn push_clip_box(&mut self, _clipbox: ttf_parser::colr::ClipBox) {} |
| 1794 | |
| 1795 | fn pop_clip(&mut self) {} |
| 1796 | |
| 1797 | fn push_layer(&mut self, _mode: ttf_parser::colr::CompositeMode) {} |
| 1798 | |
| 1799 | fn pop_layer(&mut self) {} |
| 1800 | |
| 1801 | fn push_transform(&mut self, t: ttf_parser::Transform) { |
| 1802 | let inner = [t.a, t.b, t.c, t.d, t.e, t.f]; |
| 1803 | self.transforms.push(compose(self.top(), inner)); |
| 1804 | } |
| 1805 | |
| 1806 | fn pop_transform(&mut self) { |
| 1807 | self.transforms.pop(); |
| 1808 | } |
| 1809 | } |
| 1810 | |
| 1811 | |
| 1812 | fn mean_stop(stops: impl Iterator<Item = ttf_parser::colr::ColorStop>) -> ttf_parser::RgbaColor { |
| 1813 | let (mut n, mut r, mut g, mut b, mut a) = (0u32, 0u32, 0u32, 0u32, 0u32); |
| 1814 | for s in stops { |
| 1815 | n += 1; |
| 1816 | r += u32::from(s.color.red); |
| 1817 | g += u32::from(s.color.green); |
| 1818 | b += u32::from(s.color.blue); |
| 1819 | a += u32::from(s.color.alpha); |
| 1820 | } |
| 1821 | let mean = |v: u32| (v / n.max(1)) as u8; |
| 1822 | ttf_parser::RgbaColor { |
| 1823 | red: mean(r), |
| 1824 | green: mean(g), |
| 1825 | blue: mean(b), |
| 1826 | alpha: mean(a), |
| 1827 | } |
| 1828 | } |
| 1829 | |
| 1830 | |
| 1831 | |
| 1832 | fn em_scale(em: f32, face: &ttf_parser::Face<'_>) -> f32 { |
| 1833 | em / (f32::from(face.ascender()) - f32::from(face.descender())) |
| 1834 | } |
| 1835 | |
| 1836 | |
| 1837 | |
| 1838 | |
| 1839 | fn draw_colour(out: &mut Overlay, em: f32, id: u16, pen_x: f32, baseline: f32) -> Option<Rect> { |
| 1840 | let face = colour_face()?; |
| 1841 | let scale = em_scale(em, face); |
| 1842 | |
| 1843 | let (x0, y0) = ((pen_x - 0.25 * em).floor(), (baseline - 1.5 * em).floor()); |
| 1844 | let (x1, y1) = ((pen_x + 1.75 * em).ceil(), (baseline + 0.5 * em).ceil()); |
| 1845 | let (w, h) = ((x1 - x0) as usize, (y1 - y0) as usize); |
| 1846 | let mut painter = ColourPainter { |
| 1847 | face, |
| 1848 | scale, |
| 1849 | origin: (pen_x - x0, baseline - y0), |
| 1850 | width: w, |
| 1851 | height: h, |
| 1852 | transforms: Vec::new(), |
| 1853 | glyph: None, |
| 1854 | canvas: vec![[0.0; 4]; w * h], |
| 1855 | }; |
| 1856 | let black = ttf_parser::RgbaColor { |
| 1857 | red: 0, |
| 1858 | green: 0, |
| 1859 | blue: 0, |
| 1860 | alpha: 255, |
| 1861 | }; |
| 1862 | face.paint_color_glyph(ttf_parser::GlyphId(id), 0, black, &mut painter)?; |
| 1863 | let (ow, oh) = (out.width as i64, out.height as i64); |
| 1864 | let mut hit = false; |
| 1865 | for cy in 0..h { |
| 1866 | for cx in 0..w { |
| 1867 | let [r, g, b, a] = painter.canvas[cy * w + cx]; |
| 1868 | let (x, y) = (x0 as i64 + cx as i64, y0 as i64 + cy as i64); |
| 1869 | if a <= 0.0 || x < 0 || y < 0 || x >= ow || y >= oh { |
| 1870 | continue; |
| 1871 | } |
| 1872 | if out.colour.is_empty() { |
| 1873 | out.colour = vec![[0; 4]; out.width as usize * out.height as usize]; |
| 1874 | } |
| 1875 | let to_u8 = |v: f32| (v * 255.0).round().clamp(0.0, 255.0) as u8; |
| 1876 | let straight = [r / a, g / a, b / a].map(|v| to_u8(v.min(1.0))); |
| 1877 | let alpha = to_u8(a); |
| 1878 | if alpha == 0 { |
| 1879 | continue; |
| 1880 | } |
| 1881 | out.colour[y as usize * out.width as usize + x as usize] = |
| 1882 | [straight[0], straight[1], straight[2], alpha]; |
| 1883 | hit = true; |
| 1884 | } |
| 1885 | } |
| 1886 | hit.then_some((x0, y0, x1, y1)) |
| 1887 | } |
| 1888 | |
| 1889 | |
| 1890 | |
| 1891 | |
| 1892 | |
| 1893 | |
| 1894 | fn wrap(faces: &Faces, lines: &[String], max_w: f32) -> Vec<String> { |
| 1895 | let mut out = Vec::new(); |
| 1896 | for para in lines { |
| 1897 | let words: Vec<&str> = para.split_whitespace().collect(); |
| 1898 | if words.is_empty() { |
| 1899 | out.push(String::new()); |
| 1900 | continue; |
| 1901 | } |
| 1902 | let whole = words.join(" "); |
| 1903 | if string_width(faces, &whole) <= max_w { |
| 1904 | out.push(whole); |
| 1905 | } else if words.iter().any(|w| string_width(faces, w) > max_w) { |
| 1906 | |
| 1907 | out.extend(greedy(faces, &words, max_w)); |
| 1908 | } else { |
| 1909 | let n = greedy(faces, &words, max_w).len(); |
| 1910 | out.extend(balanced(faces, &words, n, max_w)); |
| 1911 | } |
| 1912 | } |
| 1913 | out |
| 1914 | } |
| 1915 | |
| 1916 | |
| 1917 | |
| 1918 | fn greedy(faces: &Faces, words: &[&str], max_w: f32) -> Vec<String> { |
| 1919 | let mut out = Vec::new(); |
| 1920 | let mut line = String::new(); |
| 1921 | for word in words { |
| 1922 | let candidate = match line.is_empty() { |
| 1923 | true => word.to_string(), |
| 1924 | false => format!("{line} {word}"), |
| 1925 | }; |
| 1926 | if string_width(faces, &candidate) <= max_w { |
| 1927 | line = candidate; |
| 1928 | continue; |
| 1929 | } |
| 1930 | if !line.is_empty() { |
| 1931 | out.push(std::mem::take(&mut line)); |
| 1932 | } |
| 1933 | |
| 1934 | let mut piece = String::new(); |
| 1935 | for ch in word.chars() { |
| 1936 | piece.push(ch); |
| 1937 | if string_width(faces, &piece) > max_w && piece.chars().count() > 1 { |
| 1938 | piece.pop(); |
| 1939 | out.push(std::mem::take(&mut piece)); |
| 1940 | piece.push(ch); |
| 1941 | } |
| 1942 | } |
| 1943 | line = piece; |
| 1944 | } |
| 1945 | if !line.is_empty() { |
| 1946 | out.push(line); |
| 1947 | } |
| 1948 | out |
| 1949 | } |
| 1950 | |
| 1951 | |
| 1952 | |
| 1953 | |
| 1954 | |
| 1955 | fn balanced(faces: &Faces, words: &[&str], n: usize, max_w: f32) -> Vec<String> { |
| 1956 | let m = words.len(); |
| 1957 | let width = |i: usize, j: usize| string_width(faces, &words[i..j].join(" ")); |
| 1958 | |
| 1959 | let mut best = vec![vec![f32::INFINITY; m + 1]; n + 1]; |
| 1960 | let mut from = vec![vec![0usize; m + 1]; n + 1]; |
| 1961 | best[0][0] = 0.0; |
| 1962 | for k in 1..=n { |
| 1963 | for j in 1..=m { |
| 1964 | for i in 0..j { |
| 1965 | if !best[k - 1][i].is_finite() { |
| 1966 | continue; |
| 1967 | } |
| 1968 | let w = width(i, j); |
| 1969 | if w > max_w { |
| 1970 | continue; |
| 1971 | } |
| 1972 | let cost = best[k - 1][i] + w * w; |
| 1973 | if cost < best[k][j] { |
| 1974 | best[k][j] = cost; |
| 1975 | from[k][j] = i; |
| 1976 | } |
| 1977 | } |
| 1978 | } |
| 1979 | } |
| 1980 | if !best[n][m].is_finite() { |
| 1981 | return greedy(faces, words, max_w); |
| 1982 | } |
| 1983 | let mut out = Vec::with_capacity(n); |
| 1984 | let (mut j, mut k) = (m, n); |
| 1985 | while k > 0 { |
| 1986 | let i = from[k][j]; |
| 1987 | out.push(words[i..j].join(" ")); |
| 1988 | j = i; |
| 1989 | k -= 1; |
| 1990 | } |
| 1991 | out.reverse(); |
| 1992 | out |
| 1993 | } |
| 1994 | |
| 1995 | |
| 1996 | |
| 1997 | fn dilate(src: &[u8], w: u32, h: u32, r: u32) -> Vec<u8> { |
| 1998 | let (w, h, r) = (w as usize, h as usize, r as usize); |
| 1999 | let mut tmp = vec![0u8; w * h]; |
| 2000 | for y in 0..h { |
| 2001 | let row = &src[y * w..(y + 1) * w]; |
| 2002 | for x in 0..w { |
| 2003 | let lo = x.saturating_sub(r); |
| 2004 | let hi = (x + r).min(w - 1); |
| 2005 | tmp[y * w + x] = row[lo..=hi].iter().copied().max().unwrap_or(0); |
| 2006 | } |
| 2007 | } |
| 2008 | let mut out = vec![0u8; w * h]; |
| 2009 | for y in 0..h { |
| 2010 | let lo = y.saturating_sub(r); |
| 2011 | let hi = (y + r).min(h - 1); |
| 2012 | for x in 0..w { |
| 2013 | out[y * w + x] = (lo..=hi).map(|yy| tmp[yy * w + x]).max().unwrap_or(0); |
| 2014 | } |
| 2015 | } |
| 2016 | out |
| 2017 | } |
| 2018 | |
| 2019 | #[cfg(test)] |
| 2020 | mod tests { |
| 2021 | use super::*; |
| 2022 | |
| 2023 | const W: u32 = 640; |
| 2024 | const H: u32 = 360; |
| 2025 | |
| 2026 | fn lines(s: &str) -> Vec<String> { |
| 2027 | vec![s.to_string()] |
| 2028 | } |
| 2029 | |
| 2030 | |
| 2031 | fn caption_faces() -> Faces { |
| 2032 | Faces::new(60.0 / 1000.0 * 1920.0).unwrap() |
| 2033 | } |
| 2034 | |
| 2035 | |
| 2036 | fn ink_rows(o: &Overlay) -> Vec<u32> { |
| 2037 | let w = o.width as usize; |
| 2038 | (0..o.height as usize) |
| 2039 | .filter(|&y| o.fill[y * w..(y + 1) * w].iter().any(|&c| c > 0)) |
| 2040 | .map(|y| y as u32) |
| 2041 | .collect() |
| 2042 | } |
| 2043 | |
| 2044 | #[test] |
| 2045 | fn draws_non_zero_pixels_over_a_black_canvas() { |
| 2046 | let mut canvas = vec![0u8; (W * H * 4) as usize]; |
| 2047 | let style = TextStyle { |
| 2048 | boxed: false, |
| 2049 | ..TextStyle::default() |
| 2050 | }; |
| 2051 | draw_text(&mut canvas, W, H, &style, &lines("Hello")); |
| 2052 | assert!(canvas.iter().any(|&b| b != 0), "no text was drawn"); |
| 2053 | |
| 2054 | |
| 2055 | let lit = canvas |
| 2056 | .as_chunks::<4>() |
| 2057 | .0 |
| 2058 | .iter() |
| 2059 | .filter(|p| p[0] > 0) |
| 2060 | .count(); |
| 2061 | assert!(lit > 100, "only {lit} lit pixels for five letters"); |
| 2062 | } |
| 2063 | |
| 2064 | |
| 2065 | fn ink_cols(o: &Overlay) -> (usize, usize) { |
| 2066 | let w = o.width as usize; |
| 2067 | let cols: Vec<usize> = (0..w) |
| 2068 | .filter(|&x| (0..o.height as usize).any(|y| o.fill[y * w + x] > 0)) |
| 2069 | .collect(); |
| 2070 | (cols[0], *cols.last().unwrap()) |
| 2071 | } |
| 2072 | |
| 2073 | #[test] |
| 2074 | fn a_title_colour_tints_the_glyphs_in_bgra_and_in_chroma() { |
| 2075 | let style = TextStyle { ink: [255, 0, 0], boxed: false, ..TextStyle::default() }; |
| 2076 | let o = overlay(&style, W, H, &lines("MMMM")); |
| 2077 | let mut canvas = vec![0u8; (W * H * 4) as usize]; |
| 2078 | o.blend_bgra(&mut canvas); |
| 2079 | let i = o.fill.iter().position(|&c| c == 255).expect("a solid glyph pixel"); |
| 2080 | assert_eq!(&canvas[i * 4..i * 4 + 3], &[0, 0, 255], "blue, green, red"); |
| 2081 | |
| 2082 | let (mut y, mut u, mut v) = (vec![16u8; (W * H) as usize], vec![128u8; (W * H / 4) as usize], vec![128u8; (W * H / 4) as usize]); |
| 2083 | o.blend_i420(&mut y, &mut u, &mut v, false); |
| 2084 | assert!(v.iter().any(|&c| c > 200), "red text raises Cr"); |
| 2085 | assert!(u.iter().all(|&c| c <= 128), "red text lowers Cb"); |
| 2086 | |
| 2087 | let white = overlay(&TextStyle { boxed: false, ..TextStyle::default() }, W, H, &lines("MMMM")); |
| 2088 | let (mut y, mut u, mut v) = (vec![16u8; (W * H) as usize], vec![128u8; (W * H / 4) as usize], vec![128u8; (W * H / 4) as usize]); |
| 2089 | white.blend_i420(&mut y, &mut u, &mut v, false); |
| 2090 | assert!(u.iter().chain(&v).all(|&c| c == 128)); |
| 2091 | } |
| 2092 | |
| 2093 | #[test] |
| 2094 | fn a_box_colour_and_opacity_paint_the_plate() { |
| 2095 | let style = TextStyle { box_color: [0, 0, 255, 255], ..TextStyle::default() }; |
| 2096 | let o = overlay(&style, W, H, &lines("Hi")); |
| 2097 | let mut canvas = vec![0u8; (W * H * 4) as usize]; |
| 2098 | o.blend_bgra(&mut canvas); |
| 2099 | let i = o.plate.iter().position(|&a| a == 255).expect("an opaque plate pixel"); |
| 2100 | assert!(o.fill[i] == 0, "a plate pixel clear of ink"); |
| 2101 | assert_eq!(&canvas[i * 4..i * 4 + 3], &[255, 0, 0], "a blue box is blue in BGRA"); |
| 2102 | let faint = overlay(&TextStyle { box_color: [0, 0, 0, 40], ..TextStyle::default() }, W, H, &lines("Hi")); |
| 2103 | assert_eq!(faint.plate.iter().copied().max(), Some(40)); |
| 2104 | } |
| 2105 | |
| 2106 | #[test] |
| 2107 | fn bold_is_wider_and_the_block_goes_to_the_side_asked() { |
| 2108 | let regular = overlay(&TextStyle { boxed: false, ..TextStyle::default() }, W, H, &lines("Heading")); |
| 2109 | let bold = overlay(&TextStyle { boxed: false, weight: Weight::Bold, ..TextStyle::default() }, W, H, &lines("Heading")); |
| 2110 | let sum = |o: &Overlay| o.fill.iter().map(|&c| u64::from(c)).sum::<u64>(); |
| 2111 | assert!(sum(&bold) > sum(®ular), "bold has more ink"); |
| 2112 | let at = |hplace| ink_cols(&overlay(&TextStyle { hplace, boxed: false, ..TextStyle::default() }, W, H, &lines("Heading"))); |
| 2113 | let (l, c, r) = (at(HPlace::Left), at(HPlace::Centre), at(HPlace::Right)); |
| 2114 | assert!(l.0 < c.0 && c.0 < r.0, "{l:?} {c:?} {r:?}"); |
| 2115 | assert!(l.0 as f32 <= MARGIN * H as f32 + 8.0, "left sits on the margin"); |
| 2116 | assert!((W as f32 - r.1 as f32) <= MARGIN * H as f32 + 8.0, "right sits on the margin"); |
| 2117 | } |
| 2118 | |
| 2119 | #[test] |
| 2120 | fn lines_align_inside_the_block() { |
| 2121 | let two = vec!["a much longer line".to_string(), "short".to_string()]; |
| 2122 | let short_left = |align| { |
| 2123 | let o = overlay(&TextStyle { align, hplace: HPlace::Left, boxed: false, ..TextStyle::default() }, W, H, &two[1..]); |
| 2124 | ink_cols(&o).0 |
| 2125 | }; |
| 2126 | |
| 2127 | assert_eq!(short_left(Align::Left), short_left(Align::Right)); |
| 2128 | let both = |align| { |
| 2129 | |
| 2130 | let o = overlay(&TextStyle { align, hplace: HPlace::Left, boxed: false, ..TextStyle::default() }, W, H, &two); |
| 2131 | let rows = ink_rows(&o); |
| 2132 | let bottom = *rows.last().unwrap() as usize; |
| 2133 | let w = W as usize; |
| 2134 | (0..w).find(|&x| o.fill[(bottom - 3) * w + x] > 0 || o.fill[(bottom - 6) * w + x] > 0).unwrap() |
| 2135 | }; |
| 2136 | assert!(both(Align::Left) < both(Align::Centre) && both(Align::Centre) < both(Align::Right)); |
| 2137 | } |
| 2138 | |
| 2139 | #[test] |
| 2140 | fn a_default_look_blends_as_it_always_did() { |
| 2141 | |
| 2142 | let o = overlay(&TextStyle::default(), W, H, &lines("Hello")); |
| 2143 | assert_eq!(o.ink, [255; 3]); |
| 2144 | assert_eq!(o.plate_rgb, [0; 3]); |
| 2145 | assert_eq!(o.plate.iter().copied().max(), Some(BOX_ALPHA)); |
| 2146 | } |
| 2147 | |
| 2148 | #[test] |
| 2149 | fn a_blank_string_or_an_empty_frame_draws_nothing() { |
| 2150 | let mut canvas = vec![7u8; (W * H * 4) as usize]; |
| 2151 | draw_text(&mut canvas, W, H, &TextStyle::default(), &lines(" ")); |
| 2152 | assert!(canvas.iter().all(|&b| b == 7)); |
| 2153 | assert!(overlay(&TextStyle::default(), 0, 0, &lines("x")).is_blank()); |
| 2154 | } |
| 2155 | |
| 2156 | #[test] |
| 2157 | fn a_long_line_wraps_into_at_least_two_lines() { |
| 2158 | |
| 2159 | let faces = Faces::new(DEFAULT_SIZE as f32 / 1000.0 * 360.0).unwrap(); |
| 2160 | let long = |
| 2161 | "a considerably longer caption that cannot possibly fit on one line of a small frame"; |
| 2162 | let wrapped = wrap(&faces, &[long.to_string()], 320.0); |
| 2163 | assert!(wrapped.len() >= 2, "wrapped to {wrapped:?}"); |
| 2164 | assert!( |
| 2165 | wrapped |
| 2166 | .iter() |
| 2167 | .all(|l| string_width(&faces, l) <= 320.0 + 0.5) |
| 2168 | ); |
| 2169 | |
| 2170 | assert_eq!(wrapped.join(" "), long); |
| 2171 | } |
| 2172 | |
| 2173 | |
| 2174 | |
| 2175 | fn caption_wrap(lines: &[&str]) -> Vec<String> { |
| 2176 | let faces = caption_faces(); |
| 2177 | let max_w = 1080.0 - 2.0 * MARGIN * 1920.0; |
| 2178 | let owned: Vec<String> = lines.iter().map(|s| s.to_string()).collect(); |
| 2179 | wrap(&faces, &owned, max_w) |
| 2180 | } |
| 2181 | |
| 2182 | #[test] |
| 2183 | fn a_cue_line_that_fits_keeps_its_own_break() { |
| 2184 | assert_eq!( |
| 2185 | caption_wrap(&["Forty years ago", "this coast"]), |
| 2186 | ["Forty years ago", "this coast"] |
| 2187 | ); |
| 2188 | } |
| 2189 | |
| 2190 | #[test] |
| 2191 | fn a_cue_line_too_wide_breaks_balanced_with_no_orphan_word() { |
| 2192 | let out = caption_wrap(&["Forty years ago, this", "coast was empty sand"]); |
| 2193 | |
| 2194 | |
| 2195 | assert_eq!( |
| 2196 | out, |
| 2197 | ["Forty years", "ago, this", "coast was", "empty sand"], |
| 2198 | "wrapped to {out:?}" |
| 2199 | ); |
| 2200 | } |
| 2201 | |
| 2202 | #[test] |
| 2203 | fn balanced_splits_evenly_and_never_past_the_width() { |
| 2204 | let faces = caption_faces(); |
| 2205 | let words = ["aaaa", "bbbb", "cccc", "dddd", "eeee", "ffff"]; |
| 2206 | let max_w = string_width(&faces, "aaaa bbbb cccc dddd") + 1.0; |
| 2207 | let out = balanced(&faces, &words, 2, max_w); |
| 2208 | assert_eq!(out, ["aaaa bbbb cccc", "dddd eeee ffff"]); |
| 2209 | assert!(out.iter().all(|l| string_width(&faces, l) <= max_w)); |
| 2210 | } |
| 2211 | |
| 2212 | #[test] |
| 2213 | fn an_outline_puts_dark_pixels_around_white_glyphs() { |
| 2214 | |
| 2215 | |
| 2216 | let style = TextStyle { |
| 2217 | outline: Outline::Thick, |
| 2218 | boxed: false, |
| 2219 | ..TextStyle::default() |
| 2220 | }; |
| 2221 | let o = overlay(&style, W, H, &lines("Ill")); |
| 2222 | let fill = o.fill(); |
| 2223 | let stroke = o.stroke(); |
| 2224 | let ring = fill |
| 2225 | .iter() |
| 2226 | .zip(stroke) |
| 2227 | .filter(|(f, s)| **f == 0 && **s > 0) |
| 2228 | .count(); |
| 2229 | assert!(ring > 50, "only {ring} outline pixels around the glyphs"); |
| 2230 | let mut canvas = vec![128u8; (W * H * 4) as usize]; |
| 2231 | o.blend_bgra(&mut canvas); |
| 2232 | let dark = fill |
| 2233 | .iter() |
| 2234 | .zip(stroke) |
| 2235 | .enumerate() |
| 2236 | .filter(|(_, (f, s))| **f == 0 && **s > 0) |
| 2237 | .filter(|(i, _)| canvas[i * 4] < 128) |
| 2238 | .count(); |
| 2239 | assert_eq!(dark, ring, "every outline pixel must darken the grey"); |
| 2240 | } |
| 2241 | |
| 2242 | #[test] |
| 2243 | fn the_i420_overlay_moves_luma_to_white_and_chroma_to_grey() { |
| 2244 | let style = TextStyle { |
| 2245 | boxed: false, |
| 2246 | ..TextStyle::default() |
| 2247 | }; |
| 2248 | let o = overlay(&style, W, H, &lines("Hi")); |
| 2249 | let (cw, ch) = ((W / 2) as usize, (H / 2) as usize); |
| 2250 | let mut y = vec![40u8; (W * H) as usize]; |
| 2251 | let mut u = vec![200u8; cw * ch]; |
| 2252 | let mut v = vec![60u8; cw * ch]; |
| 2253 | o.blend_i420(&mut y, &mut u, &mut v, false); |
| 2254 | let whitest = y.iter().copied().max().unwrap(); |
| 2255 | assert_eq!(whitest, 235, "limited-range white is 235"); |
| 2256 | assert!( |
| 2257 | u.iter().any(|&s| s != 200), |
| 2258 | "chroma under text must move to 128" |
| 2259 | ); |
| 2260 | assert!(y.contains(&40), "pixels off the text must be untouched"); |
| 2261 | } |
| 2262 | |
| 2263 | #[test] |
| 2264 | fn an_emoji_is_drawn_from_a_face_not_as_a_box() { |
| 2265 | |
| 2266 | for emoji in ["\u{1F3AC}", "\u{1F30D}", "\u{1F1F9}", "\u{1F1F7}"] { |
| 2267 | let (src, id) = pick(emoji.chars().next().unwrap()); |
| 2268 | assert_ne!(src, Src::Outline(ARCHIVO), "{emoji} came from Archivo"); |
| 2269 | assert_ne!(id, 0, "{emoji} has no glyph"); |
| 2270 | } |
| 2271 | |
| 2272 | assert_eq!(pick('a').0, Src::Outline(ARCHIVO)); |
| 2273 | |
| 2274 | |
| 2275 | |
| 2276 | let ink = |s: &str| { |
| 2277 | let o = overlay( |
| 2278 | &TextStyle { |
| 2279 | boxed: false, |
| 2280 | ..TextStyle::default() |
| 2281 | }, |
| 2282 | W, |
| 2283 | H, |
| 2284 | &lines(s), |
| 2285 | ); |
| 2286 | let mut canvas = vec![0u8; (W * H * 4) as usize]; |
| 2287 | o.blend_bgra(&mut canvas); |
| 2288 | canvas |
| 2289 | .as_chunks::<4>() |
| 2290 | .0 |
| 2291 | .iter() |
| 2292 | .filter(|p| p[0] | p[1] | p[2] > 0) |
| 2293 | .count() |
| 2294 | }; |
| 2295 | let emoji_ink = ink("\u{1F3AC}"); |
| 2296 | assert!( |
| 2297 | emoji_ink > 30, |
| 2298 | "only {emoji_ink} ink pixels for the clapper" |
| 2299 | ); |
| 2300 | assert_ne!(emoji_ink, ink("\u{10FFFD}"), "emoji drew the empty box"); |
| 2301 | } |
| 2302 | |
| 2303 | #[test] |
| 2304 | fn a_zero_width_joiner_or_selector_draws_nothing_and_is_not_missing() { |
| 2305 | |
| 2306 | |
| 2307 | assert!(missing_glyphs(&lines("\u{1F469}\u{200D}\u{1F680}")).is_empty()); |
| 2308 | assert!(missing_glyphs(&lines("\u{2764}\u{FE0F}")).is_empty()); |
| 2309 | assert_eq!(string_width(&caption_faces(), "\u{FE0F}"), 0.0); |
| 2310 | } |
| 2311 | |
| 2312 | #[test] |
| 2313 | fn a_long_title_reports_its_wrapped_lines_and_its_share_of_the_frame() { |
| 2314 | let style = TextStyle::default(); |
| 2315 | let (n, share) = layout_share(&style, 1280, 720, &lines("Hello")); |
| 2316 | assert_eq!(n, 1); |
| 2317 | assert!(share < 0.1, "{share}"); |
| 2318 | assert_eq!(layout_share(&style, 1280, 720, &lines(" ")), (0, 0.0)); |
| 2319 | let (n, share) = layout_share(&style, 1280, 720, &lines(&"word ".repeat(100))); |
| 2320 | assert!(n > 6 && share > 0.4, "{n} lines, share {share}"); |
| 2321 | } |
| 2322 | |
| 2323 | #[test] |
| 2324 | fn cyrillic_arabic_and_the_other_scripts_have_faces_and_name_no_missing_glyphs() { |
| 2325 | assert!(missing_glyphs(&lines("Привет мир · مرحبا · שלום · नमस्ते · สวัสดี")).is_empty()); |
| 2326 | assert_eq!( |
| 2327 | pick('П'), |
| 2328 | ( |
| 2329 | Src::Outline(NOTO_SANS), |
| 2330 | outline_face(NOTO_SANS).unwrap().glyph_id('П').0 |
| 2331 | ) |
| 2332 | ); |
| 2333 | assert_eq!(pick('م').0, Src::Outline(2), "Arabic is on its own face"); |
| 2334 | assert_eq!(pick('ש').0, Src::Outline(3), "Hebrew is on its own face"); |
| 2335 | assert_eq!( |
| 2336 | pick('न').0, |
| 2337 | Src::Outline(4), |
| 2338 | "Devanagari is on its own face" |
| 2339 | ); |
| 2340 | assert_eq!(pick('ส').0, Src::Outline(5), "Thai is on its own face"); |
| 2341 | assert!(missing_glyphs(&lines("Plain Latin, 1080p! 50%")).is_empty()); |
| 2342 | } |
| 2343 | |
| 2344 | #[test] |
| 2345 | fn every_script_face_has_archivos_x_height_and_archivo_is_unscaled() { |
| 2346 | |
| 2347 | let k = face_k(); |
| 2348 | assert_eq!(k[ARCHIVO], 1.0); |
| 2349 | let x_px = |i: usize| { |
| 2350 | let face = ttf_parser::Face::parse(OUTLINE_BYTES[i], 0).unwrap(); |
| 2351 | let x = f32::from(face.x_height().unwrap()); |
| 2352 | x * k[i] / outline_face(i).unwrap().height_unscaled() |
| 2353 | }; |
| 2354 | let text = x_px(ARCHIVO); |
| 2355 | for i in [NOTO_SANS, 2, 3, 4, 5] { |
| 2356 | assert!( |
| 2357 | (x_px(i) - text).abs() < 1e-4, |
| 2358 | "face {i}: {} vs {text}", |
| 2359 | x_px(i) |
| 2360 | ); |
| 2361 | } |
| 2362 | } |
| 2363 | |
| 2364 | #[test] |
| 2365 | fn cyrillic_text_is_drawn_in_ink_not_boxes() { |
| 2366 | let style = TextStyle { |
| 2367 | boxed: false, |
| 2368 | ..TextStyle::default() |
| 2369 | }; |
| 2370 | let ink = |s: &str| { |
| 2371 | let o = overlay(&style, W, H, &lines(s)); |
| 2372 | o.fill().iter().filter(|&&c| c > 0).count() |
| 2373 | }; |
| 2374 | |
| 2375 | |
| 2376 | let box_ink = ink("\u{10FFFD}"); |
| 2377 | let letter = ink("\u{41F}"); |
| 2378 | assert!( |
| 2379 | letter > 30, |
| 2380 | "only {letter} ink pixels for a Cyrillic capital" |
| 2381 | ); |
| 2382 | assert_ne!(letter, box_ink, "the Cyrillic letter drew the empty box"); |
| 2383 | } |
| 2384 | |
| 2385 | #[test] |
| 2386 | fn arabic_letters_join_so_a_medial_letter_is_not_its_isolated_form() { |
| 2387 | |
| 2388 | |
| 2389 | |
| 2390 | let faces = caption_faces(); |
| 2391 | let bases = |s: &str| -> Vec<u16> { |
| 2392 | run(&faces, s) |
| 2393 | .iter() |
| 2394 | .filter(|p| p.advance > 0.0) |
| 2395 | .map(|p| p.id) |
| 2396 | .collect() |
| 2397 | }; |
| 2398 | let alone = bases("\u{628}"); |
| 2399 | let joined = bases("\u{628}\u{628}"); |
| 2400 | assert_eq!(alone.len(), 1); |
| 2401 | assert_eq!(joined.len(), 2, "joined letters stay two letters"); |
| 2402 | assert_ne!( |
| 2403 | joined[0], alone[0], |
| 2404 | "joining did not change the first letter" |
| 2405 | ); |
| 2406 | assert_ne!( |
| 2407 | joined[1], alone[0], |
| 2408 | "the final letter is not in its isolated form" |
| 2409 | ); |
| 2410 | } |
| 2411 | |
| 2412 | #[test] |
| 2413 | fn hebrew_is_drawn_right_to_left() { |
| 2414 | let faces = caption_faces(); |
| 2415 | |
| 2416 | assert_eq!( |
| 2417 | visual_parts("\u{5D0}\u{5D1}"), |
| 2418 | vec![(true, "\u{5D0}\u{5D1}")] |
| 2419 | ); |
| 2420 | let placed = run(&faces, "\u{5D0}\u{5D1}"); |
| 2421 | let bet = outline_face(3).unwrap().glyph_id('\u{5D1}').0; |
| 2422 | let alef = outline_face(3).unwrap().glyph_id('\u{5D0}').0; |
| 2423 | assert_eq!(placed.len(), 2); |
| 2424 | assert_eq!(placed[0].id, bet, "bet should be drawn first, on the left"); |
| 2425 | assert_eq!( |
| 2426 | placed[1].id, alef, |
| 2427 | "alef should follow, to the right of bet" |
| 2428 | ); |
| 2429 | } |
| 2430 | |
| 2431 | #[test] |
| 2432 | fn devanagari_matra_is_reordered_before_its_consonant() { |
| 2433 | let faces = caption_faces(); |
| 2434 | |
| 2435 | |
| 2436 | let placed = run(&faces, "\u{915}\u{93F}"); |
| 2437 | let ka = outline_face(4).unwrap().glyph_id('\u{915}').0; |
| 2438 | assert_eq!(placed.len(), 2, "{placed:?}"); |
| 2439 | assert_eq!(placed[1].id, ka, "KA should come second on the page"); |
| 2440 | assert_ne!( |
| 2441 | placed[0].id, ka, |
| 2442 | "the vowel sign is not reordered before KA" |
| 2443 | ); |
| 2444 | } |
| 2445 | |
| 2446 | #[test] |
| 2447 | fn a_cjk_character_is_drawn_from_the_system_font_when_there_is_one() { |
| 2448 | let Some(_) = cjk_face() else { |
| 2449 | return; |
| 2450 | }; |
| 2451 | assert_eq!(pick('你').0, Src::Cjk); |
| 2452 | let style = TextStyle { |
| 2453 | boxed: false, |
| 2454 | ..TextStyle::default() |
| 2455 | }; |
| 2456 | let o = overlay(&style, W, H, &lines("你好")); |
| 2457 | assert!( |
| 2458 | o.fill().iter().filter(|&&c| c > 0).count() > 100, |
| 2459 | "CJK drew nothing" |
| 2460 | ); |
| 2461 | } |
| 2462 | |
| 2463 | #[test] |
| 2464 | fn a_colour_emoji_paints_colour_pixels_when_there_is_a_system_colour_font() { |
| 2465 | let Some(_) = colour_face() else { |
| 2466 | return; |
| 2467 | }; |
| 2468 | assert_eq!(pick('\u{1F389}').0, Src::Colour); |
| 2469 | let style = TextStyle { |
| 2470 | boxed: false, |
| 2471 | ..TextStyle::default() |
| 2472 | }; |
| 2473 | let o = overlay(&style, W, H, &lines("\u{1F389}")); |
| 2474 | let mut canvas = vec![0u8; (W * H * 4) as usize]; |
| 2475 | o.blend_bgra(&mut canvas); |
| 2476 | let coloured = canvas |
| 2477 | .as_chunks::<4>() |
| 2478 | .0 |
| 2479 | .iter() |
| 2480 | .filter(|p| p[0].max(p[1]).max(p[2]) - p[0].min(p[1]).min(p[2]) > 40) |
| 2481 | .count(); |
| 2482 | assert!( |
| 2483 | coloured > 30, |
| 2484 | "only {coloured} coloured pixels for the party popper" |
| 2485 | ); |
| 2486 | } |
| 2487 | |
| 2488 | #[test] |
| 2489 | fn a_mixed_script_title_draws_and_keeps_its_glyphs() { |
| 2490 | let style = TextStyle { |
| 2491 | outline: Outline::Thin, |
| 2492 | ..TextStyle::default() |
| 2493 | }; |
| 2494 | |
| 2495 | |
| 2496 | |
| 2497 | let bundled = lines("Привет мир · مرحبا · \u{1F389}"); |
| 2498 | assert!(missing_glyphs(&bundled).is_empty()); |
| 2499 | let text = lines("Привет мир · مرحبا · 你好 · \u{1F389}"); |
| 2500 | if cjk_face().is_some() { |
| 2501 | assert!(missing_glyphs(&text).is_empty()); |
| 2502 | } else { |
| 2503 | assert_eq!(missing_glyphs(&text), vec!['你', '好']); |
| 2504 | } |
| 2505 | let (n, share) = layout_share(&style, W, H, &text); |
| 2506 | assert_eq!(n, 1, "the title should fit one line"); |
| 2507 | assert!(share > 0.0); |
| 2508 | let o = overlay(&style, W, H, &text); |
| 2509 | assert!(o.fill().iter().any(|&c| c > 0)); |
| 2510 | } |
| 2511 | |
| 2512 | #[test] |
| 2513 | fn missing_glyphs_names_only_what_no_face_draws_once_in_order() { |
| 2514 | let text = vec![ |
| 2515 | "Emoji test \u{1F3AC} ok".to_string(), |
| 2516 | "\u{10FFFD} and \u{10FFFD} again \u{10FFFC}".to_string(), |
| 2517 | ]; |
| 2518 | assert_eq!(missing_glyphs(&text), vec!['\u{10FFFD}', '\u{10FFFC}']); |
| 2519 | assert!(missing_glyphs(&lines("plain ascii, 1080p")).is_empty()); |
| 2520 | } |
| 2521 | |
| 2522 | #[test] |
| 2523 | fn overlapping_cues_stack_upward_from_the_bottom_without_covering_each_other() { |
| 2524 | let style = TextStyle { |
| 2525 | boxed: false, |
| 2526 | ..TextStyle::default() |
| 2527 | }; |
| 2528 | let first = overlay(&style, W, H, &lines("First cue")); |
| 2529 | let second = overlay(&style, W, H, &lines("Second cue")); |
| 2530 | let both = overlay_stack(&style, W, H, &[lines("First cue"), lines("Second cue")]); |
| 2531 | |
| 2532 | let first_rows = ink_rows(&first); |
| 2533 | let both_rows = ink_rows(&both); |
| 2534 | assert_eq!(first_rows.last(), both_rows.last(), "first cue moved"); |
| 2535 | |
| 2536 | |
| 2537 | let (top_alone, top_both) = (first_rows[0], both_rows[0]); |
| 2538 | assert!( |
| 2539 | top_both + 20 < top_alone, |
| 2540 | "second cue not stacked above: {top_both} vs {top_alone}" |
| 2541 | ); |
| 2542 | |
| 2543 | |
| 2544 | let ink = |o: &Overlay| o.fill().iter().filter(|&&c| c > 0).count(); |
| 2545 | let (a, b, s) = (ink(&first), ink(&second), ink(&both)); |
| 2546 | assert!( |
| 2547 | (s as i64 - (a + b) as i64).abs() <= ((a + b) / 50) as i64, |
| 2548 | "stack ink {s} is not the sum of its cues {a} + {b}" |
| 2549 | ); |
| 2550 | |
| 2551 | let gap_rows = both_rows.windows(2).filter(|w| w[1] - w[0] > 1).count(); |
| 2552 | assert!(gap_rows >= 1, "the two cues run into one another"); |
| 2553 | } |
| 2554 | |
| 2555 | #[test] |
| 2556 | fn a_stacked_cue_with_no_words_takes_no_room() { |
| 2557 | let style = TextStyle::default(); |
| 2558 | let alone = overlay(&style, W, H, &lines("Hello")); |
| 2559 | let with_blank = overlay_stack(&style, W, H, &[lines(" "), lines("Hello")]); |
| 2560 | assert_eq!(alone.fill(), with_blank.fill()); |
| 2561 | } |
| 2562 | |
| 2563 | const LATIN_BGRA_HASH: u64 = 17148267790522720847; |
| 2564 | const LATIN_I420_HASHES: [u64; 3] = [ |
| 2565 | 3766897427118592358, |
| 2566 | 14679306852776097573, |
| 2567 | 14679306852776097573, |
| 2568 | ]; |
| 2569 | |
| 2570 | |
| 2571 | fn fnv1a(bytes: &[u8]) -> u64 { |
| 2572 | bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| { |
| 2573 | (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3) |
| 2574 | }) |
| 2575 | } |
| 2576 | |
| 2577 | #[test] |
| 2578 | fn latin_text_renders_exactly_as_the_archivo_only_rasteriser_did() { |
| 2579 | |
| 2580 | |
| 2581 | |
| 2582 | let style = TextStyle { |
| 2583 | outline: Outline::Thick, |
| 2584 | boxed: true, |
| 2585 | ..TextStyle::default() |
| 2586 | }; |
| 2587 | let text = lines("Hello, world! 1080p 50% “quotes” — dashes…\nSecond line: fi ffl AV"); |
| 2588 | let o = overlay(&style, W, H, &text); |
| 2589 | let mut canvas = vec![90u8; (W * H * 4) as usize]; |
| 2590 | o.blend_bgra(&mut canvas); |
| 2591 | assert_eq!(fnv1a(&canvas), LATIN_BGRA_HASH, "bgra hash moved"); |
| 2592 | let (cw, ch) = ((W / 2) as usize, (H / 2) as usize); |
| 2593 | let (mut y, mut u, mut v) = ( |
| 2594 | vec![60u8; (W * H) as usize], |
| 2595 | vec![128u8; cw * ch], |
| 2596 | vec![128u8; cw * ch], |
| 2597 | ); |
| 2598 | o.blend_i420(&mut y, &mut u, &mut v, false); |
| 2599 | let planes = [fnv1a(&y), fnv1a(&u), fnv1a(&v)]; |
| 2600 | assert_eq!(planes, LATIN_I420_HASHES, "i420 hashes moved"); |
| 2601 | } |
| 2602 | } |