| 1 | use anyhow::{Context as _, Ok, Result}; |
| 2 | use collections::HashMap; |
| 3 | use cosmic_text::{ |
| 4 | Attrs, AttrsList, Ellipsize, Family, Font as CosmicTextFont, |
| 5 | FontFeatures as CosmicFontFeatures, FontSystem, ShapeBuffer, ShapeLine, Stretch, Style, Weight, |
| 6 | }; |
| 7 | use gpui::{ |
| 8 | Bounds, DevicePixels, FallbackFontClass, Font, FontFallbacks, FontFeatures, FontId, |
| 9 | FontMetrics, FontRun, GlyphId, IsZero as _, LineLayout, MissingGlyph, MissingGlyphSink, Pixels, |
| 10 | PlatformTextSystem, RenderGlyphParams, SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ShapedGlyph, |
| 11 | ShapedRun, SharedString, Size, TextRenderingMode, point, size, |
| 12 | }; |
| 13 | |
| 14 | use itertools::Itertools; |
| 15 | use parking_lot::RwLock; |
| 16 | use smallvec::SmallVec; |
| 17 | use std::{borrow::Cow, ops::Range, sync::Arc}; |
| 18 | use swash::{ |
| 19 | scale::{Render, ScaleContext, Source, StrikeWith}, |
| 20 | zeno::{Format, Vector}, |
| 21 | }; |
| 22 | use unicode_segmentation::UnicodeSegmentation; |
| 23 | |
| 24 | pub struct CosmicTextSystem(RwLock<CosmicTextSystemState>); |
| 25 | |
| 26 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 27 | struct FontKey { |
| 28 | family: SharedString, |
| 29 | features: FontFeatures, |
| 30 | fallbacks: Option<FontFallbacks>, |
| 31 | } |
| 32 | |
| 33 | impl FontKey { |
| 34 | fn new(family: SharedString, features: FontFeatures, fallbacks: Option<FontFallbacks>) -> Self { |
| 35 | Self { |
| 36 | family, |
| 37 | features, |
| 38 | fallbacks, |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 44 | struct LoadedFontKey { |
| 45 | database_id: cosmic_text::fontdb::ID, |
| 46 | font: FontKey, |
| 47 | } |
| 48 | |
| 49 | struct CosmicTextSystemState { |
| 50 | font_system: FontSystem, |
| 51 | scratch: ShapeBuffer, |
| 52 | swash_scale_context: ScaleContext, |
| 53 | pending_glyph_images: HashMap<RenderGlyphParams, swash::scale::image::Image>, |
| 54 | /// Contains all already loaded fonts, including all faces. Indexed by `FontId`. |
| 55 | loaded_fonts: Vec<LoadedFont>, |
| 56 | loaded_font_ids_by_key: HashMap<LoadedFontKey, FontId>, |
| 57 | /// Caches the `FontId`s associated with a specific family to avoid iterating the font database |
| 58 | /// for every font face in a family. |
| 59 | font_ids_by_family_cache: HashMap<FontKey, SmallVec<[FontId; 4]>>, |
| 60 | system_font_fallback: String, |
| 61 | missing_glyph_sink: Option<Arc<dyn MissingGlyphSink>>, |
| 62 | } |
| 63 | |
| 64 | struct LoadedFont { |
| 65 | font: Arc<CosmicTextFont>, |
| 66 | features: CosmicFontFeatures, |
| 67 | is_known_emoji_font: bool, |
| 68 | /// resolved at load time so `layout_line` shares one chain across faces. |
| 69 | /// `Arc` keeps clone cheap on the per-run hot path. |
| 70 | user_fallback_chain: Arc<[(FontId, SharedString)]>, |
| 71 | } |
| 72 | |
| 73 | struct FontMatchProperties { |
| 74 | primary_family_name: SharedString, |
| 75 | stretch: Stretch, |
| 76 | style: Style, |
| 77 | weight: Weight, |
| 78 | features: CosmicFontFeatures, |
| 79 | fallback_chain: Arc<[(FontId, SharedString)]>, |
| 80 | } |
| 81 | |
| 82 | impl FontMatchProperties { |
| 83 | fn attributes<'a>(&'a self, font_id: FontId, family_name: &'a str) -> Attrs<'a> { |
| 84 | Attrs::new() |
| 85 | .metadata(font_id.0) |
| 86 | .family(Family::Name(family_name)) |
| 87 | .stretch(self.stretch) |
| 88 | .style(self.style) |
| 89 | .weight(self.weight) |
| 90 | .font_features(self.features.clone()) |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | impl CosmicTextSystem { |
| 95 | /// Returns the selected face's weight and style, which may differ from the request. |
| 96 | pub fn font_weight_and_style( |
| 97 | &self, |
| 98 | font_id: FontId, |
| 99 | ) -> Result<(gpui::FontWeight, gpui::FontStyle)> { |
| 100 | let state = self.0.read(); |
| 101 | let font = state |
| 102 | .loaded_fonts |
| 103 | .get(font_id.0) |
| 104 | .context("invalid font ID")?; |
| 105 | let face = state |
| 106 | .font_system |
| 107 | .db() |
| 108 | .face(font.font.id()) |
| 109 | .context("font face not found")?; |
| 110 | let style = match face.style { |
| 111 | cosmic_text::Style::Normal => gpui::FontStyle::Normal, |
| 112 | cosmic_text::Style::Italic => gpui::FontStyle::Italic, |
| 113 | cosmic_text::Style::Oblique => gpui::FontStyle::Oblique, |
| 114 | }; |
| 115 | Ok((gpui::FontWeight(face.weight.0 as f32), style)) |
| 116 | } |
| 117 | |
| 118 | /// Builds reports for unresolved source indices after an outer text system |
| 119 | /// has applied its own fallback. |
| 120 | pub fn missing_glyphs( |
| 121 | &self, |
| 122 | text: &str, |
| 123 | font_runs: &[FontRun], |
| 124 | missing_text_indices: impl IntoIterator<Item = usize>, |
| 125 | ) -> Vec<MissingGlyph> { |
| 126 | self.0 |
| 127 | .read() |
| 128 | .missing_glyphs(text, font_runs, missing_text_indices) |
| 129 | } |
| 130 | |
| 131 | pub fn new(system_font_fallback: &str) -> Self { |
| 132 | let font_system = FontSystem::new(); |
| 133 | |
| 134 | Self(RwLock::new(CosmicTextSystemState { |
| 135 | font_system, |
| 136 | scratch: ShapeBuffer::default(), |
| 137 | swash_scale_context: ScaleContext::new(), |
| 138 | pending_glyph_images: HashMap::default(), |
| 139 | loaded_fonts: Vec::new(), |
| 140 | loaded_font_ids_by_key: HashMap::default(), |
| 141 | font_ids_by_family_cache: HashMap::default(), |
| 142 | system_font_fallback: system_font_fallback.to_string(), |
| 143 | missing_glyph_sink: None, |
| 144 | })) |
| 145 | } |
| 146 | |
| 147 | pub fn new_without_system_fonts(system_font_fallback: &str) -> Self { |
| 148 | let font_system = FontSystem::new_with_locale_and_db( |
| 149 | "en-US".to_string(), |
| 150 | cosmic_text::fontdb::Database::new(), |
| 151 | ); |
| 152 | |
| 153 | Self(RwLock::new(CosmicTextSystemState { |
| 154 | font_system, |
| 155 | scratch: ShapeBuffer::default(), |
| 156 | swash_scale_context: ScaleContext::new(), |
| 157 | pending_glyph_images: HashMap::default(), |
| 158 | loaded_fonts: Vec::new(), |
| 159 | loaded_font_ids_by_key: HashMap::default(), |
| 160 | font_ids_by_family_cache: HashMap::default(), |
| 161 | system_font_fallback: system_font_fallback.to_string(), |
| 162 | missing_glyph_sink: None, |
| 163 | })) |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | impl PlatformTextSystem for CosmicTextSystem { |
| 168 | fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> { |
| 169 | self.0.write().add_fonts(fonts) |
| 170 | } |
| 171 | |
| 172 | fn set_missing_glyph_sink(&self, sink: Option<Arc<dyn MissingGlyphSink>>) { |
| 173 | self.0.write().missing_glyph_sink = sink; |
| 174 | } |
| 175 | |
| 176 | fn all_font_names(&self) -> Vec<String> { |
| 177 | let mut result = self |
| 178 | .0 |
| 179 | .read() |
| 180 | .font_system |
| 181 | .db() |
| 182 | .faces() |
| 183 | .filter_map(|face| face.families.first().map(|family| family.0.clone())) |
| 184 | .collect_vec(); |
| 185 | result.sort_unstable(); |
| 186 | result.dedup(); |
| 187 | result |
| 188 | } |
| 189 | |
| 190 | fn font_id(&self, font: &Font) -> Result<FontId> { |
| 191 | let mut state = self.0.write(); |
| 192 | let key = FontKey::new( |
| 193 | font.family.clone(), |
| 194 | font.features.clone(), |
| 195 | font.fallbacks.clone(), |
| 196 | ); |
| 197 | let candidates = if let Some(font_ids) = state.font_ids_by_family_cache.get(&key) { |
| 198 | font_ids.as_slice() |
| 199 | } else { |
| 200 | let font_ids = |
| 201 | state.load_family(&font.family, &font.features, font.fallbacks.as_ref())?; |
| 202 | state.font_ids_by_family_cache.insert(key.clone(), font_ids); |
| 203 | state.font_ids_by_family_cache[&key].as_ref() |
| 204 | }; |
| 205 | |
| 206 | let ix = find_best_match(font, candidates, &state)?; |
| 207 | |
| 208 | Ok(candidates[ix]) |
| 209 | } |
| 210 | |
| 211 | fn prewarm_fonts(&self, font_ids: &[FontId]) { |
| 212 | self.0.write().prewarm_fonts(font_ids); |
| 213 | } |
| 214 | |
| 215 | fn font_metrics(&self, font_id: FontId) -> FontMetrics { |
| 216 | let metrics = self |
| 217 | .0 |
| 218 | .read() |
| 219 | .loaded_font(font_id) |
| 220 | .font |
| 221 | .as_swash() |
| 222 | .metrics(&[]); |
| 223 | |
| 224 | FontMetrics { |
| 225 | units_per_em: metrics.units_per_em as u32, |
| 226 | ascent: metrics.ascent, |
| 227 | descent: -metrics.descent, |
| 228 | line_gap: metrics.leading, |
| 229 | underline_position: metrics.underline_offset, |
| 230 | underline_thickness: metrics.stroke_size, |
| 231 | cap_height: metrics.cap_height, |
| 232 | x_height: metrics.x_height, |
| 233 | bounding_box: Bounds { |
| 234 | origin: point(0.0, 0.0), |
| 235 | size: size(metrics.max_width, metrics.ascent + metrics.descent), |
| 236 | }, |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> { |
| 241 | let lock = self.0.read(); |
| 242 | let glyph_metrics = lock.loaded_font(font_id).font.as_swash().glyph_metrics(&[]); |
| 243 | let glyph_id = glyph_id.0 as u16; |
| 244 | Ok(Bounds { |
| 245 | origin: point(0.0, 0.0), |
| 246 | size: size( |
| 247 | glyph_metrics.advance_width(glyph_id), |
| 248 | glyph_metrics.advance_height(glyph_id), |
| 249 | ), |
| 250 | }) |
| 251 | } |
| 252 | |
| 253 | fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> { |
| 254 | self.0.read().advance(font_id, glyph_id) |
| 255 | } |
| 256 | |
| 257 | fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> { |
| 258 | self.0.read().glyph_for_char(font_id, ch) |
| 259 | } |
| 260 | |
| 261 | fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> { |
| 262 | self.0.write().raster_bounds(params) |
| 263 | } |
| 264 | |
| 265 | fn rasterize_glyph( |
| 266 | &self, |
| 267 | params: &RenderGlyphParams, |
| 268 | raster_bounds: Bounds<DevicePixels>, |
| 269 | ) -> Result<(Size<DevicePixels>, Vec<u8>)> { |
| 270 | self.0.write().rasterize_glyph(params, raster_bounds) |
| 271 | } |
| 272 | |
| 273 | fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout { |
| 274 | self.0.write().layout_line(text, font_size, runs) |
| 275 | } |
| 276 | |
| 277 | fn recommended_rendering_mode( |
| 278 | &self, |
| 279 | _font_id: FontId, |
| 280 | _font_size: Pixels, |
| 281 | ) -> TextRenderingMode { |
| 282 | TextRenderingMode::Subpixel |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | impl CosmicTextSystemState { |
| 287 | fn loaded_font(&self, font_id: FontId) -> &LoadedFont { |
| 288 | &self.loaded_fonts[font_id.0] |
| 289 | } |
| 290 | |
| 291 | fn font_match_properties(&self, font_id: FontId) -> Option<FontMatchProperties> { |
| 292 | let loaded_font = self.loaded_font(font_id); |
| 293 | let Some(face) = self.font_system.db().face(loaded_font.font.id()) else { |
| 294 | log::warn!("font face not found in database for font_id {:?}", font_id); |
| 295 | return None; |
| 296 | }; |
| 297 | let Some(first_family) = face.families.first() else { |
| 298 | log::warn!("font face has no family names for font_id {:?}", font_id); |
| 299 | return None; |
| 300 | }; |
| 301 | |
| 302 | Some(FontMatchProperties { |
| 303 | primary_family_name: first_family.0.clone().into(), |
| 304 | stretch: face.stretch, |
| 305 | style: face.style, |
| 306 | weight: face.weight, |
| 307 | features: loaded_font.features.clone(), |
| 308 | fallback_chain: Arc::clone(&loaded_font.user_fallback_chain), |
| 309 | }) |
| 310 | } |
| 311 | |
| 312 | fn prewarm_fonts(&mut self, font_ids: &[FontId]) { |
| 313 | for &font_id in font_ids { |
| 314 | let Some(properties) = self.font_match_properties(font_id) else { |
| 315 | continue; |
| 316 | }; |
| 317 | let primary_attributes = |
| 318 | properties.attributes(font_id, &properties.primary_family_name); |
| 319 | self.font_system.get_font_matches(&primary_attributes); |
| 320 | |
| 321 | for (fallback_id, fallback_name) in &*properties.fallback_chain { |
| 322 | let fallback_attributes = properties.attributes(*fallback_id, fallback_name); |
| 323 | self.font_system.get_font_matches(&fallback_attributes); |
| 324 | } |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | #[profiling::function] |
| 329 | fn add_fonts(&mut self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> { |
| 330 | self.font_ids_by_family_cache.clear(); |
| 331 | let db = self.font_system.db_mut(); |
| 332 | let installed: std::collections::HashSet<_> = db.faces().map(|face| face.id).collect(); |
| 333 | for bytes in fonts { |
| 334 | db.load_font_source(cosmic_text::fontdb::Source::Binary(Arc::new(bytes))); |
| 335 | } |
| 336 | // A bundled face replaces installed faces of the same family, so a system font the |
| 337 | // renderer cannot draw (COLRv1-only emoji) never wins the family lookup. |
| 338 | let bundled_families: std::collections::HashSet<String> = db |
| 339 | .faces() |
| 340 | .filter(|face| !installed.contains(&face.id)) |
| 341 | .flat_map(|face| face.families.iter().map(|(name, _)| name.clone())) |
| 342 | .collect(); |
| 343 | let shadowed: Vec<_> = db |
| 344 | .faces() |
| 345 | .filter(|face| installed.contains(&face.id)) |
| 346 | .filter(|face| face.families.iter().any(|(name, _)| bundled_families.contains(name))) |
| 347 | .map(|face| face.id) |
| 348 | .collect(); |
| 349 | for id in shadowed { |
| 350 | db.remove_face(id); |
| 351 | } |
| 352 | Ok(()) |
| 353 | } |
| 354 | |
| 355 | #[profiling::function] |
| 356 | fn load_family( |
| 357 | &mut self, |
| 358 | name: &str, |
| 359 | features: &FontFeatures, |
| 360 | fallbacks: Option<&FontFallbacks>, |
| 361 | ) -> Result<SmallVec<[FontId; 4]>> { |
| 362 | let loaded_font_key = FontKey::new( |
| 363 | SharedString::from(name.to_owned()), |
| 364 | features.clone(), |
| 365 | fallbacks.cloned(), |
| 366 | ); |
| 367 | |
| 368 | // recurse with `fallbacks = None` so a fallback family cannot pull in |
| 369 | // another chain. missing fallback families are dropped so a typo in |
| 370 | // settings still lets the primary family load. |
| 371 | let user_fallback_chain: Arc<[(FontId, SharedString)]> = match fallbacks { |
| 372 | Some(fallbacks) if !fallbacks.fallback_list().is_empty() => { |
| 373 | let mut chain: Vec<(FontId, SharedString)> = Vec::new(); |
| 374 | for fallback_name in fallbacks.fallback_list() { |
| 375 | let fb_key = FontKey::new( |
| 376 | SharedString::from(fallback_name.clone()), |
| 377 | features.clone(), |
| 378 | None, |
| 379 | ); |
| 380 | let fb_ids = if let Some(cached) = self.font_ids_by_family_cache.get(&fb_key) { |
| 381 | cached.clone() |
| 382 | } else { |
| 383 | let loaded = self.load_family(fallback_name, features, None)?; |
| 384 | self.font_ids_by_family_cache |
| 385 | .insert(fb_key.clone(), loaded.clone()); |
| 386 | loaded |
| 387 | }; |
| 388 | let Some(&fb_id) = fb_ids.first() else { |
| 389 | continue; |
| 390 | }; |
| 391 | let db_id = self.loaded_fonts[fb_id.0].font.id(); |
| 392 | if let Some(face) = self.font_system.db().face(db_id) |
| 393 | && let Some(family) = face.families.first() |
| 394 | { |
| 395 | chain.push((fb_id, SharedString::from(family.0.clone()))); |
| 396 | } |
| 397 | } |
| 398 | Arc::from(chain) |
| 399 | } |
| 400 | _ => Arc::from(Vec::new()), |
| 401 | }; |
| 402 | |
| 403 | let name = gpui::font_name_with_fallbacks(name, &self.system_font_fallback); |
| 404 | |
| 405 | let families = self |
| 406 | .font_system |
| 407 | .db() |
| 408 | .faces() |
| 409 | .filter(|face| face.families.iter().any(|family| *name == family.0)) |
| 410 | .map(|face| (face.id, face.post_script_name.clone())) |
| 411 | .collect::<SmallVec<[_; 4]>>(); |
| 412 | |
| 413 | let cosmic_features = cosmic_font_features(features)?; |
| 414 | |
| 415 | let mut loaded_font_ids = SmallVec::new(); |
| 416 | for (database_id, postscript_name) in families { |
| 417 | let key = LoadedFontKey { |
| 418 | database_id, |
| 419 | font: loaded_font_key.clone(), |
| 420 | }; |
| 421 | if let Some(&font_id) = self.loaded_font_ids_by_key.get(&key) { |
| 422 | self.loaded_fonts[font_id.0].user_fallback_chain = Arc::clone(&user_fallback_chain); |
| 423 | loaded_font_ids.push(font_id); |
| 424 | continue; |
| 425 | } |
| 426 | |
| 427 | let font = self |
| 428 | .font_system |
| 429 | .get_font(database_id, cosmic_text::Weight::NORMAL) |
| 430 | .context("Could not load font")?; |
| 431 | |
| 432 | // HACK: To let the storybook run and render Windows caption icons. We should actually do better font fallback. |
| 433 | let allowed_bad_font_names = [ |
| 434 | "SegoeFluentIcons", // NOTE: Segoe fluent icons postscript name is inconsistent |
| 435 | "Segoe Fluent Icons", |
| 436 | ]; |
| 437 | |
| 438 | if font.as_swash().charmap().map('m') == 0 |
| 439 | && !allowed_bad_font_names.contains(&postscript_name.as_str()) |
| 440 | { |
| 441 | self.font_system.db_mut().remove_face(font.id()); |
| 442 | continue; |
| 443 | }; |
| 444 | |
| 445 | let font_id = FontId(self.loaded_fonts.len()); |
| 446 | loaded_font_ids.push(font_id); |
| 447 | self.loaded_fonts.push(LoadedFont { |
| 448 | font, |
| 449 | features: cosmic_features.clone(), |
| 450 | is_known_emoji_font: check_is_known_emoji_font(&postscript_name), |
| 451 | user_fallback_chain: Arc::clone(&user_fallback_chain), |
| 452 | }); |
| 453 | self.loaded_font_ids_by_key.insert(key, font_id); |
| 454 | } |
| 455 | |
| 456 | Ok(loaded_font_ids) |
| 457 | } |
| 458 | |
| 459 | fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> { |
| 460 | let glyph_metrics = self.loaded_font(font_id).font.as_swash().glyph_metrics(&[]); |
| 461 | Ok(Size { |
| 462 | width: glyph_metrics.advance_width(glyph_id.0 as u16), |
| 463 | height: glyph_metrics.advance_height(glyph_id.0 as u16), |
| 464 | }) |
| 465 | } |
| 466 | |
| 467 | fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> { |
| 468 | let glyph_id = self.loaded_font(font_id).font.as_swash().charmap().map(ch); |
| 469 | if glyph_id == 0 { |
| 470 | None |
| 471 | } else { |
| 472 | Some(GlyphId(glyph_id.into())) |
| 473 | } |
| 474 | } |
| 475 | |
| 476 | fn raster_bounds(&mut self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> { |
| 477 | let image = self.render_glyph_image(params)?; |
| 478 | let bounds = Bounds { |
| 479 | origin: point(image.placement.left.into(), (-image.placement.top).into()), |
| 480 | size: size(image.placement.width.into(), image.placement.height.into()), |
| 481 | }; |
| 482 | if !bounds.is_zero() { |
| 483 | self.pending_glyph_images.insert(params.clone(), image); |
| 484 | } |
| 485 | Ok(bounds) |
| 486 | } |
| 487 | |
| 488 | #[profiling::function] |
| 489 | fn rasterize_glyph( |
| 490 | &mut self, |
| 491 | params: &RenderGlyphParams, |
| 492 | glyph_bounds: Bounds<DevicePixels>, |
| 493 | ) -> Result<(Size<DevicePixels>, Vec<u8>)> { |
| 494 | if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 { |
| 495 | anyhow::bail!("glyph bounds are empty"); |
| 496 | } |
| 497 | |
| 498 | let mut image = match self.pending_glyph_images.remove(params) { |
| 499 | Some(image) => image, |
| 500 | None => self.render_glyph_image(params)?, |
| 501 | }; |
| 502 | let bitmap_size = glyph_bounds.size; |
| 503 | match image.content { |
| 504 | swash::scale::image::Content::Color | swash::scale::image::Content::SubpixelMask => { |
| 505 | // Convert from RGBA to BGRA. |
| 506 | for pixel in image.data.chunks_exact_mut(4) { |
| 507 | pixel.swap(0, 2); |
| 508 | } |
| 509 | Ok((bitmap_size, image.data)) |
| 510 | } |
| 511 | swash::scale::image::Content::Mask => { |
| 512 | if params.subpixel_rendering { |
| 513 | // We must always return RGBA data when subpixel rendering is requested. |
| 514 | let expanded = image.data.iter().flat_map(|&a| [a, a, a, a]).collect(); |
| 515 | Ok((bitmap_size, expanded)) |
| 516 | } else { |
| 517 | Ok((bitmap_size, image.data)) |
| 518 | } |
| 519 | } |
| 520 | } |
| 521 | } |
| 522 | |
| 523 | fn render_glyph_image( |
| 524 | &mut self, |
| 525 | params: &RenderGlyphParams, |
| 526 | ) -> Result<swash::scale::image::Image> { |
| 527 | let loaded_font = &self.loaded_fonts[params.font_id.0]; |
| 528 | let font_ref = loaded_font.font.as_swash(); |
| 529 | let pixel_size = f32::from(params.font_size); |
| 530 | |
| 531 | let subpixel_offset = Vector::new( |
| 532 | params.subpixel_variant.x as f32 / SUBPIXEL_VARIANTS_X as f32 / params.scale_factor, |
| 533 | params.subpixel_variant.y as f32 / SUBPIXEL_VARIANTS_Y as f32 / params.scale_factor, |
| 534 | ); |
| 535 | |
| 536 | let mut scaler = self |
| 537 | .swash_scale_context |
| 538 | .builder(font_ref) |
| 539 | .size(pixel_size * params.scale_factor) |
| 540 | .hint(true) |
| 541 | .build(); |
| 542 | |
| 543 | let sources: &[Source] = if params.is_emoji { |
| 544 | &[ |
| 545 | Source::ColorOutline(0), |
| 546 | Source::ColorBitmap(StrikeWith::BestFit), |
| 547 | Source::Outline, |
| 548 | ] |
| 549 | } else { |
| 550 | &[Source::Bitmap(StrikeWith::ExactSize), Source::Outline] |
| 551 | }; |
| 552 | |
| 553 | let mut renderer = Render::new(sources); |
| 554 | if params.subpixel_rendering { |
| 555 | // There seems to be a bug in Swash where the B and R values are swapped. |
| 556 | renderer |
| 557 | .format(Format::subpixel_bgra()) |
| 558 | .offset(subpixel_offset); |
| 559 | } else { |
| 560 | renderer.format(Format::Alpha).offset(subpixel_offset); |
| 561 | } |
| 562 | |
| 563 | let glyph_id: u16 = params.glyph_id.0.try_into()?; |
| 564 | renderer |
| 565 | .render(&mut scaler, glyph_id) |
| 566 | .with_context(|| format!("unable to render glyph via swash for {params:?}")) |
| 567 | } |
| 568 | |
| 569 | /// This is used when cosmic_text has chosen a fallback font instead of using the requested |
| 570 | /// font, typically to handle some unicode characters. When this happens, `loaded_fonts` may not |
| 571 | /// yet have an entry for this fallback font, and so one is added. |
| 572 | /// |
| 573 | /// Note that callers shouldn't use this `FontId` somewhere that will retrieve the corresponding |
| 574 | /// `LoadedFont.features`, as it will have an arbitrarily chosen or empty value. The only |
| 575 | /// current use of this field is for the *input* of `layout_line`, and so it's fine to use |
| 576 | /// `font_id_for_cosmic_id` when computing the *output* of `layout_line`. |
| 577 | fn font_id_for_cosmic_id(&mut self, id: cosmic_text::fontdb::ID) -> Result<FontId> { |
| 578 | if let Some(ix) = self |
| 579 | .loaded_fonts |
| 580 | .iter() |
| 581 | .position(|loaded_font| loaded_font.font.id() == id) |
| 582 | { |
| 583 | Ok(FontId(ix)) |
| 584 | } else { |
| 585 | let font = self |
| 586 | .font_system |
| 587 | .get_font(id, cosmic_text::Weight::NORMAL) |
| 588 | .context("failed to get fallback font from cosmic-text font system")?; |
| 589 | let face = self |
| 590 | .font_system |
| 591 | .db() |
| 592 | .face(id) |
| 593 | .context("fallback font face not found in cosmic-text database")?; |
| 594 | |
| 595 | let font_id = FontId(self.loaded_fonts.len()); |
| 596 | self.loaded_fonts.push(LoadedFont { |
| 597 | font, |
| 598 | features: CosmicFontFeatures::new(), |
| 599 | is_known_emoji_font: check_is_known_emoji_font(&face.post_script_name), |
| 600 | user_fallback_chain: Arc::from(Vec::new()), |
| 601 | }); |
| 602 | |
| 603 | Ok(font_id) |
| 604 | } |
| 605 | } |
| 606 | |
| 607 | #[profiling::function] |
| 608 | fn layout_line(&mut self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout { |
| 609 | if contains_paragraph_separator(text) { |
| 610 | self.layout_line_with_separators(text, font_size, font_runs) |
| 611 | } else { |
| 612 | self.layout_line_no_separators(text, font_size, font_runs) |
| 613 | } |
| 614 | } |
| 615 | |
| 616 | fn layout_line_with_separators( |
| 617 | &mut self, |
| 618 | text: &str, |
| 619 | font_size: Pixels, |
| 620 | font_runs: &[FontRun], |
| 621 | ) -> LineLayout { |
| 622 | let mut layout = LineLayout { |
| 623 | font_size, |
| 624 | len: text.len(), |
| 625 | ..Default::default() |
| 626 | }; |
| 627 | let mut paragraph_start = 0; |
| 628 | |
| 629 | for (separator_start, separator) in text |
| 630 | .char_indices() |
| 631 | .filter(|(_, character)| is_paragraph_separator(*character)) |
| 632 | { |
| 633 | let separator_end = separator_start + separator.len_utf8(); |
| 634 | self.shape_segment( |
| 635 | text, |
| 636 | paragraph_start..separator_start, |
| 637 | font_size, |
| 638 | font_runs, |
| 639 | &mut layout, |
| 640 | ); |
| 641 | self.shape_segment( |
| 642 | text, |
| 643 | separator_start..separator_end, |
| 644 | font_size, |
| 645 | font_runs, |
| 646 | &mut layout, |
| 647 | ); |
| 648 | paragraph_start = separator_end; |
| 649 | } |
| 650 | |
| 651 | self.shape_segment( |
| 652 | text, |
| 653 | paragraph_start..text.len(), |
| 654 | font_size, |
| 655 | font_runs, |
| 656 | &mut layout, |
| 657 | ); |
| 658 | |
| 659 | layout |
| 660 | } |
| 661 | |
| 662 | fn shape_segment( |
| 663 | &mut self, |
| 664 | text: &str, |
| 665 | range: Range<usize>, |
| 666 | font_size: Pixels, |
| 667 | font_runs: &[FontRun], |
| 668 | layout: &mut LineLayout, |
| 669 | ) { |
| 670 | if range.is_empty() { |
| 671 | return; |
| 672 | } |
| 673 | |
| 674 | let segment_font_runs = clip_font_runs(font_runs, range.clone()); |
| 675 | let segment = |
| 676 | self.layout_line_no_separators(&text[range.clone()], font_size, &segment_font_runs); |
| 677 | |
| 678 | let mut segment_runs = segment.runs; |
| 679 | for run in &mut segment_runs { |
| 680 | for glyph in &mut run.glyphs { |
| 681 | glyph.index += range.start; |
| 682 | glyph.position.x += layout.width; |
| 683 | } |
| 684 | } |
| 685 | |
| 686 | for mut run in segment_runs { |
| 687 | if let Some(same_run) = layout |
| 688 | .runs |
| 689 | .last_mut() |
| 690 | .filter(|last| last.font_id == run.font_id) |
| 691 | { |
| 692 | same_run.glyphs.append(&mut run.glyphs); |
| 693 | } else { |
| 694 | layout.runs.push(run); |
| 695 | } |
| 696 | } |
| 697 | |
| 698 | layout.width += segment.width; |
| 699 | layout.ascent = layout.ascent.max(segment.ascent); |
| 700 | layout.descent = layout.descent.max(segment.descent); |
| 701 | } |
| 702 | |
| 703 | fn layout_line_no_separators( |
| 704 | &mut self, |
| 705 | text: &str, |
| 706 | font_size: Pixels, |
| 707 | font_runs: &[FontRun], |
| 708 | ) -> LineLayout { |
| 709 | let mut attrs_list = AttrsList::new(&Attrs::new()); |
| 710 | let mut offs = 0; |
| 711 | for run in font_runs { |
| 712 | let run_end = offs + run.len; |
| 713 | |
| 714 | let Some(properties) = self.font_match_properties(run.font_id) else { |
| 715 | offs = run_end; |
| 716 | continue; |
| 717 | }; |
| 718 | |
| 719 | let primary_attrs = properties.attributes(run.font_id, &properties.primary_family_name); |
| 720 | let fallback_attrs: SmallVec<[Attrs<'_>; 4]> = properties |
| 721 | .fallback_chain |
| 722 | .iter() |
| 723 | .map(|(font_id, family_name)| properties.attributes(*font_id, family_name)) |
| 724 | .collect(); |
| 725 | |
| 726 | let spans = if properties.fallback_chain.is_empty() { |
| 727 | let mut spans = SmallVec::<[RunSpan; 4]>::new(); |
| 728 | spans.push(RunSpan { |
| 729 | start: offs, |
| 730 | end: run_end, |
| 731 | slot: None, |
| 732 | font_id: run.font_id, |
| 733 | }); |
| 734 | spans |
| 735 | } else { |
| 736 | let loaded_fonts = &self.loaded_fonts; |
| 737 | let covers = |id: FontId, ch: char| charmap_covers(loaded_fonts, id, ch); |
| 738 | compute_run_spans( |
| 739 | text, |
| 740 | offs, |
| 741 | run.len, |
| 742 | run.font_id, |
| 743 | &properties.fallback_chain, |
| 744 | &covers, |
| 745 | ) |
| 746 | }; |
| 747 | |
| 748 | for span in spans { |
| 749 | let attrs = match span.slot { |
| 750 | None => &primary_attrs, |
| 751 | Some(ix) => &fallback_attrs[ix], |
| 752 | }; |
| 753 | attrs_list.add_span(span.start..span.end, attrs); |
| 754 | } |
| 755 | offs = run_end; |
| 756 | } |
| 757 | |
| 758 | let line = ShapeLine::new( |
| 759 | &mut self.font_system, |
| 760 | text, |
| 761 | &attrs_list, |
| 762 | cosmic_text::Shaping::Advanced, |
| 763 | 4, |
| 764 | ); |
| 765 | let mut layout_lines = Vec::with_capacity(1); |
| 766 | line.layout_to_buffer( |
| 767 | &mut self.scratch, |
| 768 | f32::from(font_size), |
| 769 | None, // We do our own wrapping |
| 770 | cosmic_text::Wrap::None, |
| 771 | Ellipsize::None, |
| 772 | None, |
| 773 | &mut layout_lines, |
| 774 | None, |
| 775 | cosmic_text::Hinting::Disabled, |
| 776 | ); |
| 777 | |
| 778 | let Some(layout) = layout_lines.first() else { |
| 779 | return LineLayout { |
| 780 | font_size, |
| 781 | width: Pixels::ZERO, |
| 782 | ascent: Pixels::ZERO, |
| 783 | descent: Pixels::ZERO, |
| 784 | runs: Vec::new(), |
| 785 | len: text.len(), |
| 786 | }; |
| 787 | }; |
| 788 | |
| 789 | let missing_glyphs = self.missing_glyph_sink.as_ref().map(|_| { |
| 790 | self.missing_glyphs( |
| 791 | text, |
| 792 | font_runs, |
| 793 | layout |
| 794 | .glyphs |
| 795 | .iter() |
| 796 | .filter(|glyph| glyph.glyph_id == 0) |
| 797 | .map(|glyph| glyph.start), |
| 798 | ) |
| 799 | }); |
| 800 | |
| 801 | let mut runs: Vec<ShapedRun> = Vec::new(); |
| 802 | for glyph in &layout.glyphs { |
| 803 | let mut font_id = FontId(glyph.metadata); |
| 804 | let mut loaded_font = self.loaded_font(font_id); |
| 805 | if loaded_font.font.id() != glyph.font_id { |
| 806 | match self.font_id_for_cosmic_id(glyph.font_id) { |
| 807 | std::result::Result::Ok(resolved_id) => { |
| 808 | font_id = resolved_id; |
| 809 | loaded_font = self.loaded_font(font_id); |
| 810 | } |
| 811 | Err(error) => { |
| 812 | log::warn!( |
| 813 | "failed to resolve cosmic font id {:?}: {error:#}", |
| 814 | glyph.font_id |
| 815 | ); |
| 816 | continue; |
| 817 | } |
| 818 | } |
| 819 | } |
| 820 | let is_emoji = loaded_font.is_known_emoji_font; |
| 821 | |
| 822 | // HACK: Prevent crash caused by variation selectors. |
| 823 | if glyph.glyph_id == 3 && is_emoji { |
| 824 | continue; |
| 825 | } |
| 826 | |
| 827 | let shaped_glyph = ShapedGlyph { |
| 828 | id: GlyphId(glyph.glyph_id as u32), |
| 829 | position: point(glyph.x.into(), glyph.y.into()), |
| 830 | index: glyph.start, |
| 831 | is_emoji, |
| 832 | }; |
| 833 | |
| 834 | if let Some(last_run) = runs |
| 835 | .last_mut() |
| 836 | .filter(|last_run| last_run.font_id == font_id) |
| 837 | { |
| 838 | last_run.glyphs.push(shaped_glyph); |
| 839 | } else { |
| 840 | runs.push(ShapedRun { |
| 841 | font_id, |
| 842 | glyphs: vec![shaped_glyph], |
| 843 | }); |
| 844 | } |
| 845 | } |
| 846 | |
| 847 | if let Some((sink, missing_glyphs)) = self.missing_glyph_sink.as_ref().zip(missing_glyphs) { |
| 848 | sink.report(missing_glyphs); |
| 849 | } |
| 850 | |
| 851 | LineLayout { |
| 852 | font_size, |
| 853 | width: layout.w.into(), |
| 854 | ascent: layout.max_ascent.into(), |
| 855 | descent: layout.max_descent.into(), |
| 856 | runs, |
| 857 | len: text.len(), |
| 858 | } |
| 859 | } |
| 860 | |
| 861 | fn missing_glyphs( |
| 862 | &self, |
| 863 | text: &str, |
| 864 | font_runs: &[FontRun], |
| 865 | missing_text_indices: impl IntoIterator<Item = usize>, |
| 866 | ) -> Vec<MissingGlyph> { |
| 867 | let mut missing_text_indices = missing_text_indices.into_iter().peekable(); |
| 868 | if missing_text_indices.peek().is_none() { |
| 869 | return Vec::new(); |
| 870 | } |
| 871 | let mut missing_text_indices = missing_text_indices.collect::<Vec<_>>(); |
| 872 | missing_text_indices.sort_unstable(); |
| 873 | missing_text_indices.dedup(); |
| 874 | |
| 875 | let mut font_run_index = 0; |
| 876 | let mut font_run_end = font_runs.first().map_or(0, |font_run| font_run.len); |
| 877 | let mut missing_glyphs = Vec::new(); |
| 878 | let mut missing_index = 0; |
| 879 | for (grapheme_start, grapheme) in text.grapheme_indices(true) { |
| 880 | let grapheme_end = grapheme_start + grapheme.len(); |
| 881 | while missing_text_indices |
| 882 | .get(missing_index) |
| 883 | .is_some_and(|text_index| *text_index < grapheme_start) |
| 884 | { |
| 885 | missing_index += 1; |
| 886 | } |
| 887 | let Some(&text_index) = missing_text_indices.get(missing_index) else { |
| 888 | break; |
| 889 | }; |
| 890 | if text_index >= grapheme_end { |
| 891 | continue; |
| 892 | } |
| 893 | |
| 894 | while font_run_end <= text_index && font_run_index + 1 < font_runs.len() { |
| 895 | font_run_index += 1; |
| 896 | let Some(font_run) = font_runs.get(font_run_index) else { |
| 897 | break; |
| 898 | }; |
| 899 | font_run_end += font_run.len; |
| 900 | } |
| 901 | let font_class = self.fallback_font_class( |
| 902 | font_runs |
| 903 | .get(font_run_index) |
| 904 | .or_else(|| font_runs.last()) |
| 905 | .map(|font_run| font_run.font_id), |
| 906 | ); |
| 907 | missing_glyphs.push(MissingGlyph::new(grapheme.into(), font_class)); |
| 908 | while missing_text_indices |
| 909 | .get(missing_index) |
| 910 | .is_some_and(|text_index| *text_index < grapheme_end) |
| 911 | { |
| 912 | missing_index += 1; |
| 913 | } |
| 914 | } |
| 915 | missing_glyphs |
| 916 | } |
| 917 | |
| 918 | fn fallback_font_class(&self, font_id: Option<FontId>) -> FallbackFontClass { |
| 919 | let Some(font_id) = font_id else { |
| 920 | return FallbackFontClass::Proportional; |
| 921 | }; |
| 922 | let loaded_font = self.loaded_font(font_id); |
| 923 | let is_monospace = self |
| 924 | .font_system |
| 925 | .db() |
| 926 | .face(loaded_font.font.id()) |
| 927 | .is_some_and(|face| face.monospaced); |
| 928 | if is_monospace { |
| 929 | FallbackFontClass::Monospace |
| 930 | } else { |
| 931 | FallbackFontClass::Proportional |
| 932 | } |
| 933 | } |
| 934 | } |
| 935 | |
| 936 | #[inline(always)] |
| 937 | fn is_paragraph_separator(character: char) -> bool { |
| 938 | unicode_bidi::bidi_class(character) == unicode_bidi::BidiClass::B |
| 939 | } |
| 940 | |
| 941 | fn contains_paragraph_separator(text: &str) -> bool { |
| 942 | if text |
| 943 | .bytes() |
| 944 | .any(|byte| matches!(byte, b'\n' | b'\r' | 0x1c | 0x1d | 0x1e)) |
| 945 | { |
| 946 | return true; |
| 947 | } |
| 948 | |
| 949 | !text.is_ascii() && text.chars().any(is_paragraph_separator) |
| 950 | } |
| 951 | |
| 952 | fn clip_font_runs(font_runs: &[FontRun], range: Range<usize>) -> SmallVec<[FontRun; 4]> { |
| 953 | let mut clipped = SmallVec::new(); |
| 954 | let mut offs = 0; |
| 955 | for run in font_runs { |
| 956 | let run_start = offs; |
| 957 | offs += run.len; |
| 958 | if offs <= range.start { |
| 959 | continue; |
| 960 | } |
| 961 | if run_start >= range.end { |
| 962 | break; |
| 963 | } |
| 964 | let start = run_start.max(range.start); |
| 965 | let end = offs.min(range.end); |
| 966 | if start < end { |
| 967 | clipped.push(FontRun { |
| 968 | len: end - start, |
| 969 | font_id: run.font_id, |
| 970 | }); |
| 971 | } |
| 972 | } |
| 973 | clipped |
| 974 | } |
| 975 | |
| 976 | #[cfg(feature = "font-kit")] |
| 977 | fn find_best_match( |
| 978 | font: &Font, |
| 979 | candidates: &[FontId], |
| 980 | state: &CosmicTextSystemState, |
| 981 | ) -> Result<usize> { |
| 982 | let candidate_properties = candidates |
| 983 | .iter() |
| 984 | .map(|font_id| { |
| 985 | let database_id = state.loaded_font(*font_id).font.id(); |
| 986 | let face_info = state |
| 987 | .font_system |
| 988 | .db() |
| 989 | .face(database_id) |
| 990 | .context("font face not found in database")?; |
| 991 | Ok(face_info_into_properties(face_info)) |
| 992 | }) |
| 993 | .collect::<Result<SmallVec<[_; 4]>>>()?; |
| 994 | |
| 995 | let ix = |
| 996 | font_kit::matching::find_best_match(&candidate_properties, &font_into_properties(font)) |
| 997 | .context("requested font family contains no font matching the other parameters")?; |
| 998 | |
| 999 | Ok(ix) |
| 1000 | } |
| 1001 | |
| 1002 | #[cfg(not(feature = "font-kit"))] |
| 1003 | fn find_best_match( |
| 1004 | font: &Font, |
| 1005 | candidates: &[FontId], |
| 1006 | state: &CosmicTextSystemState, |
| 1007 | ) -> Result<usize> { |
| 1008 | if candidates.is_empty() { |
| 1009 | anyhow::bail!("requested font family contains no font matching the other parameters"); |
| 1010 | } |
| 1011 | if candidates.len() == 1 { |
| 1012 | return Ok(0); |
| 1013 | } |
| 1014 | |
| 1015 | let target_weight = font.weight.0; |
| 1016 | let target_italic = matches!( |
| 1017 | font.style, |
| 1018 | gpui::FontStyle::Italic | gpui::FontStyle::Oblique |
| 1019 | ); |
| 1020 | |
| 1021 | let mut best_index = 0; |
| 1022 | let mut best_score = u32::MAX; |
| 1023 | |
| 1024 | for (index, font_id) in candidates.iter().enumerate() { |
| 1025 | let database_id = state.loaded_font(*font_id).font.id(); |
| 1026 | let face_info = state |
| 1027 | .font_system |
| 1028 | .db() |
| 1029 | .face(database_id) |
| 1030 | .context("font face not found in database")?; |
| 1031 | |
| 1032 | let is_italic = matches!( |
| 1033 | face_info.style, |
| 1034 | cosmic_text::Style::Italic | cosmic_text::Style::Oblique |
| 1035 | ); |
| 1036 | let style_penalty: u32 = if is_italic == target_italic { 0 } else { 1000 }; |
| 1037 | let weight_diff = (face_info.weight.0 as i32 - target_weight as i32).unsigned_abs(); |
| 1038 | let score = style_penalty + weight_diff; |
| 1039 | |
| 1040 | if score < best_score { |
| 1041 | best_score = score; |
| 1042 | best_index = index; |
| 1043 | } |
| 1044 | } |
| 1045 | |
| 1046 | Ok(best_index) |
| 1047 | } |
| 1048 | |
| 1049 | /// one contiguous slice of a `FontRun` that maps to a single slot. `slot` is |
| 1050 | /// `None` for the primary font and `Some(ix)` for `fallback_chain[ix]`. |
| 1051 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1052 | struct RunSpan { |
| 1053 | start: usize, |
| 1054 | end: usize, |
| 1055 | slot: Option<usize>, |
| 1056 | font_id: FontId, |
| 1057 | } |
| 1058 | |
| 1059 | /// walks `text[run_offset..run_offset + run_len]` and groups codepoints into |
| 1060 | /// spans. inheriting codepoints stay in the current span so shaping clusters |
| 1061 | /// like emoji zwj sequences and combining marks are not torn apart. |
| 1062 | fn compute_run_spans( |
| 1063 | text: &str, |
| 1064 | run_offset: usize, |
| 1065 | run_len: usize, |
| 1066 | primary: FontId, |
| 1067 | fallback_chain: &[(FontId, SharedString)], |
| 1068 | covers: &impl Fn(FontId, char) -> bool, |
| 1069 | ) -> SmallVec<[RunSpan; 4]> { |
| 1070 | let mut spans = SmallVec::new(); |
| 1071 | let run_end = run_offset + run_len; |
| 1072 | if run_end <= run_offset { |
| 1073 | return spans; |
| 1074 | } |
| 1075 | if fallback_chain.is_empty() { |
| 1076 | spans.push(RunSpan { |
| 1077 | start: run_offset, |
| 1078 | end: run_end, |
| 1079 | slot: None, |
| 1080 | font_id: primary, |
| 1081 | }); |
| 1082 | return spans; |
| 1083 | } |
| 1084 | let run_text = &text[run_offset..run_end]; |
| 1085 | let mut span_start = run_offset; |
| 1086 | let mut span_slot: Option<usize> = None; |
| 1087 | let mut span_font_id = primary; |
| 1088 | for (grapheme_idx, grapheme) in run_text.grapheme_indices(true) { |
| 1089 | let abs = run_offset + grapheme_idx; |
| 1090 | let ch = grapheme.chars().next().unwrap_or('\0'); |
| 1091 | let next_slot = pick_covering_slot(ch, span_slot, primary, fallback_chain, covers); |
| 1092 | if next_slot == span_slot { |
| 1093 | continue; |
| 1094 | } |
| 1095 | if abs > span_start { |
| 1096 | spans.push(RunSpan { |
| 1097 | start: span_start, |
| 1098 | end: abs, |
| 1099 | slot: span_slot, |
| 1100 | font_id: span_font_id, |
| 1101 | }); |
| 1102 | } |
| 1103 | span_start = abs; |
| 1104 | span_slot = next_slot; |
| 1105 | span_font_id = slot_font_id(next_slot, primary, fallback_chain); |
| 1106 | } |
| 1107 | if span_start < run_end { |
| 1108 | spans.push(RunSpan { |
| 1109 | start: span_start, |
| 1110 | end: run_end, |
| 1111 | slot: span_slot, |
| 1112 | font_id: span_font_id, |
| 1113 | }); |
| 1114 | } |
| 1115 | spans |
| 1116 | } |
| 1117 | |
| 1118 | fn slot_font_id( |
| 1119 | slot: Option<usize>, |
| 1120 | primary: FontId, |
| 1121 | fallback_chain: &[(FontId, SharedString)], |
| 1122 | ) -> FontId { |
| 1123 | match slot { |
| 1124 | None => primary, |
| 1125 | Some(ix) => fallback_chain[ix].0, |
| 1126 | } |
| 1127 | } |
| 1128 | |
| 1129 | fn pick_covering_slot( |
| 1130 | ch: char, |
| 1131 | current: Option<usize>, |
| 1132 | primary: FontId, |
| 1133 | fallback_chain: &[(FontId, SharedString)], |
| 1134 | covers: &impl Fn(FontId, char) -> bool, |
| 1135 | ) -> Option<usize> { |
| 1136 | if (ch as u32) <= 0x7F { |
| 1137 | return None; |
| 1138 | } |
| 1139 | if covers(primary, ch) { |
| 1140 | return None; |
| 1141 | } |
| 1142 | let current_id = slot_font_id(current, primary, fallback_chain); |
| 1143 | if covers(current_id, ch) { |
| 1144 | return current; |
| 1145 | } |
| 1146 | |
| 1147 | fallback_chain |
| 1148 | .iter() |
| 1149 | .position(|(fb_id, _)| covers(*fb_id, ch)) |
| 1150 | } |
| 1151 | |
| 1152 | fn charmap_covers(loaded_fonts: &[LoadedFont], id: FontId, ch: char) -> bool { |
| 1153 | loaded_fonts |
| 1154 | .get(id.0) |
| 1155 | .is_some_and(|loaded| loaded.font.as_swash().charmap().map(ch) != 0) |
| 1156 | } |
| 1157 | |
| 1158 | fn cosmic_font_features(features: &FontFeatures) -> Result<CosmicFontFeatures> { |
| 1159 | let mut result = CosmicFontFeatures::new(); |
| 1160 | for feature in features.0.iter() { |
| 1161 | let name_bytes: [u8; 4] = feature |
| 1162 | .0 |
| 1163 | .as_bytes() |
| 1164 | .try_into() |
| 1165 | .context("Incorrect feature flag format")?; |
| 1166 | |
| 1167 | let tag = cosmic_text::FeatureTag::new(&name_bytes); |
| 1168 | |
| 1169 | result.set(tag, feature.1); |
| 1170 | } |
| 1171 | Ok(result) |
| 1172 | } |
| 1173 | |
| 1174 | #[cfg(feature = "font-kit")] |
| 1175 | fn font_into_properties(font: &gpui::Font) -> font_kit::properties::Properties { |
| 1176 | font_kit::properties::Properties { |
| 1177 | style: match font.style { |
| 1178 | gpui::FontStyle::Normal => font_kit::properties::Style::Normal, |
| 1179 | gpui::FontStyle::Italic => font_kit::properties::Style::Italic, |
| 1180 | gpui::FontStyle::Oblique => font_kit::properties::Style::Oblique, |
| 1181 | }, |
| 1182 | weight: font_kit::properties::Weight(font.weight.0), |
| 1183 | stretch: Default::default(), |
| 1184 | } |
| 1185 | } |
| 1186 | |
| 1187 | #[cfg(feature = "font-kit")] |
| 1188 | fn face_info_into_properties( |
| 1189 | face_info: &cosmic_text::fontdb::FaceInfo, |
| 1190 | ) -> font_kit::properties::Properties { |
| 1191 | font_kit::properties::Properties { |
| 1192 | style: match face_info.style { |
| 1193 | cosmic_text::Style::Normal => font_kit::properties::Style::Normal, |
| 1194 | cosmic_text::Style::Italic => font_kit::properties::Style::Italic, |
| 1195 | cosmic_text::Style::Oblique => font_kit::properties::Style::Oblique, |
| 1196 | }, |
| 1197 | weight: font_kit::properties::Weight(face_info.weight.0.into()), |
| 1198 | stretch: match face_info.stretch { |
| 1199 | cosmic_text::Stretch::Condensed => font_kit::properties::Stretch::CONDENSED, |
| 1200 | cosmic_text::Stretch::Expanded => font_kit::properties::Stretch::EXPANDED, |
| 1201 | cosmic_text::Stretch::ExtraCondensed => font_kit::properties::Stretch::EXTRA_CONDENSED, |
| 1202 | cosmic_text::Stretch::ExtraExpanded => font_kit::properties::Stretch::EXTRA_EXPANDED, |
| 1203 | cosmic_text::Stretch::Normal => font_kit::properties::Stretch::NORMAL, |
| 1204 | cosmic_text::Stretch::SemiCondensed => font_kit::properties::Stretch::SEMI_CONDENSED, |
| 1205 | cosmic_text::Stretch::SemiExpanded => font_kit::properties::Stretch::SEMI_EXPANDED, |
| 1206 | cosmic_text::Stretch::UltraCondensed => font_kit::properties::Stretch::ULTRA_CONDENSED, |
| 1207 | cosmic_text::Stretch::UltraExpanded => font_kit::properties::Stretch::ULTRA_EXPANDED, |
| 1208 | }, |
| 1209 | } |
| 1210 | } |
| 1211 | |
| 1212 | fn check_is_known_emoji_font(postscript_name: &str) -> bool { |
| 1213 | // TODO: Include other common emoji fonts |
| 1214 | postscript_name == "NotoColorEmoji" |
| 1215 | } |
| 1216 | |
| 1217 | #[cfg(test)] |
| 1218 | mod tests { |
| 1219 | use super::*; |
| 1220 | #[cfg(feature = "test-support")] |
| 1221 | use std::{cell::RefCell, rc::Rc}; |
| 1222 | |
| 1223 | #[test] |
| 1224 | fn all_font_names_tracks_available_families() -> Result<()> { |
| 1225 | let text_system = gpui::TextSystem::new(Arc::new( |
| 1226 | CosmicTextSystem::new_without_system_fonts("IBM Plex Sans"), |
| 1227 | )); |
| 1228 | assert!(text_system.all_font_names().is_empty()); |
| 1229 | |
| 1230 | text_system.add_fonts(vec![Cow::Borrowed(include_bytes!( |
| 1231 | "../../../assets/fonts/lilex/Lilex-Regular.ttf" |
| 1232 | ))])?; |
| 1233 | assert_eq!(text_system.all_font_names(), ["Lilex"]); |
| 1234 | |
| 1235 | text_system.add_fonts(vec![ |
| 1236 | Cow::Borrowed(IBM_PLEX), |
| 1237 | Cow::Borrowed(include_bytes!("../../../assets/fonts/lilex/Lilex-Bold.ttf")), |
| 1238 | ])?; |
| 1239 | assert_eq!(text_system.all_font_names(), ["IBM Plex Sans", "Lilex"]); |
| 1240 | Ok(()) |
| 1241 | } |
| 1242 | |
| 1243 | fn fid(i: usize) -> FontId { |
| 1244 | FontId(i) |
| 1245 | } |
| 1246 | |
| 1247 | fn chain(ids: &[usize]) -> SmallVec<[(FontId, SharedString); 4]> { |
| 1248 | ids.iter() |
| 1249 | .map(|&i| (fid(i), SharedString::from(format!("fb{i}")))) |
| 1250 | .collect() |
| 1251 | } |
| 1252 | |
| 1253 | fn span(start: usize, end: usize, slot: Option<usize>, font_id: FontId) -> RunSpan { |
| 1254 | RunSpan { |
| 1255 | start, |
| 1256 | end, |
| 1257 | slot, |
| 1258 | font_id, |
| 1259 | } |
| 1260 | } |
| 1261 | |
| 1262 | const IBM_PLEX: &[u8] = |
| 1263 | include_bytes!("../../../assets/fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf"); |
| 1264 | const LILEX: &[u8] = include_bytes!("../../../assets/fonts/lilex/Lilex-Regular.ttf"); |
| 1265 | |
| 1266 | /// Every code point of `Bidi_Class=B`, each of which starts a new bidi |
| 1267 | /// paragraph and so can split one line into mixed-direction paragraphs. |
| 1268 | const SEPARATORS: &[char] = &[ |
| 1269 | '\u{000a}', '\u{000d}', '\u{001c}', '\u{001d}', '\u{001e}', '\u{0085}', '\u{2029}', |
| 1270 | ]; |
| 1271 | |
| 1272 | fn text_system() -> Result<CosmicTextSystem> { |
| 1273 | let text_system = CosmicTextSystem::new_without_system_fonts("IBM Plex Sans"); |
| 1274 | text_system.add_fonts(vec![Cow::Borrowed(IBM_PLEX)])?; |
| 1275 | Ok(text_system) |
| 1276 | } |
| 1277 | |
| 1278 | #[test] |
| 1279 | fn font_properties_describe_the_selected_face() -> Result<()> { |
| 1280 | let text_system = text_system()?; |
| 1281 | let regular = gpui::font("IBM Plex Sans"); |
| 1282 | let regular_id = text_system.font_id(®ular)?; |
| 1283 | for (weight, style) in [ |
| 1284 | (gpui::FontWeight::MEDIUM, gpui::FontStyle::Normal), |
| 1285 | (gpui::FontWeight::BOLD, gpui::FontStyle::Italic), |
| 1286 | (gpui::FontWeight::NORMAL, gpui::FontStyle::Oblique), |
| 1287 | ] { |
| 1288 | let requested = Font { |
| 1289 | weight, |
| 1290 | style, |
| 1291 | ..regular.clone() |
| 1292 | }; |
| 1293 | let font_id = text_system.font_id(&requested)?; |
| 1294 | assert_eq!(font_id, regular_id); |
| 1295 | assert_eq!( |
| 1296 | text_system.font_weight_and_style(font_id)?, |
| 1297 | (gpui::FontWeight::NORMAL, gpui::FontStyle::Normal) |
| 1298 | ); |
| 1299 | } |
| 1300 | Ok(()) |
| 1301 | } |
| 1302 | |
| 1303 | fn layout_text(text_system: &CosmicTextSystem, text: &str) -> Result<LineLayout> { |
| 1304 | let font_id = text_system.font_id(&gpui::font("IBM Plex Sans"))?; |
| 1305 | let runs = [FontRun { |
| 1306 | len: text.len(), |
| 1307 | font_id, |
| 1308 | }]; |
| 1309 | Ok(text_system.layout_line(text, gpui::px(14.0), &runs)) |
| 1310 | } |
| 1311 | |
| 1312 | /// Mirrors the original crash: mixed-direction text reaching the shaper |
| 1313 | /// through `shape_text`, which only splits lines on `\n`. |
| 1314 | #[test] |
| 1315 | fn shape_text_with_mixed_direction_paragraphs() -> Result<()> { |
| 1316 | let platform_text_system = Arc::new(text_system()?); |
| 1317 | let text_system = Arc::new(gpui::TextSystem::new(platform_text_system)); |
| 1318 | let window_text_system = gpui::WindowTextSystem::new(text_system); |
| 1319 | |
| 1320 | let text: SharedString = "first line\n\u{05d0}\u{001c}A".into(); |
| 1321 | let runs = [gpui::TextRun { |
| 1322 | len: text.len(), |
| 1323 | font: gpui::font("IBM Plex Sans"), |
| 1324 | ..Default::default() |
| 1325 | }]; |
| 1326 | |
| 1327 | let lines = window_text_system.shape_text(text, gpui::px(14.0), &runs, None, None)?; |
| 1328 | |
| 1329 | assert_eq!(lines.len(), 2); |
| 1330 | assert_eq!(lines[1].len(), "\u{05d0}\u{001c}A".len()); |
| 1331 | assert!(lines[1].width() > Pixels::ZERO); |
| 1332 | Ok(()) |
| 1333 | } |
| 1334 | |
| 1335 | #[cfg(feature = "test-support")] |
| 1336 | #[test] |
| 1337 | fn reports_graphemes_that_exhaust_font_fallback() -> Result<()> { |
| 1338 | let platform_text_system = Arc::new(text_system()?); |
| 1339 | let dispatcher = gpui::TestDispatcher::new(0); |
| 1340 | let cx = |
| 1341 | gpui::TestAppContext::build_with_text_system(dispatcher, None, platform_text_system); |
| 1342 | let observed = Rc::new(RefCell::new(Vec::new())); |
| 1343 | let _subscription = cx.update(|cx| { |
| 1344 | let observed = observed.clone(); |
| 1345 | cx.on_missing_glyphs(move |missing_glyphs, _| { |
| 1346 | observed.borrow_mut().extend_from_slice(missing_glyphs); |
| 1347 | }) |
| 1348 | }); |
| 1349 | let text: SharedString = "界".into(); |
| 1350 | |
| 1351 | cx.update(|cx| { |
| 1352 | let text_system = gpui::WindowTextSystem::new(cx.text_system().clone()); |
| 1353 | let runs = [gpui::TextRun { |
| 1354 | len: text.len(), |
| 1355 | font: gpui::font("IBM Plex Sans"), |
| 1356 | ..Default::default() |
| 1357 | }]; |
| 1358 | text_system.shape_line(text, gpui::px(14.0), &runs, None); |
| 1359 | }); |
| 1360 | cx.run_until_parked(); |
| 1361 | |
| 1362 | let observed = observed.borrow(); |
| 1363 | assert_eq!(observed.len(), 1); |
| 1364 | assert_eq!(observed[0].grapheme(), "界"); |
| 1365 | assert_eq!( |
| 1366 | observed[0].font_class(), |
| 1367 | gpui::FallbackFontClass::Proportional |
| 1368 | ); |
| 1369 | Ok(()) |
| 1370 | } |
| 1371 | |
| 1372 | #[test] |
| 1373 | fn combines_missing_glyphs_from_one_grapheme() -> Result<()> { |
| 1374 | let text_system = text_system()?; |
| 1375 | let font_id = text_system.font_id(&gpui::font("IBM Plex Sans"))?; |
| 1376 | let text = "x\u{0301}"; |
| 1377 | let runs = [FontRun { |
| 1378 | len: text.len(), |
| 1379 | font_id, |
| 1380 | }]; |
| 1381 | |
| 1382 | let missing_glyphs = text_system |
| 1383 | .0 |
| 1384 | .read() |
| 1385 | .missing_glyphs(text, &runs, [0, "x".len()]); |
| 1386 | |
| 1387 | assert_eq!(missing_glyphs.len(), 1); |
| 1388 | assert_eq!(missing_glyphs[0].grapheme(), text); |
| 1389 | Ok(()) |
| 1390 | } |
| 1391 | |
| 1392 | #[test] |
| 1393 | fn adding_fonts_invalidates_cached_line_layouts() -> Result<()> { |
| 1394 | let platform_text_system = Arc::new(text_system()?); |
| 1395 | let text_system = Arc::new(gpui::TextSystem::new(platform_text_system.clone())); |
| 1396 | let window_text_system = gpui::WindowTextSystem::new(text_system.clone()); |
| 1397 | let text: SharedString = "cached text".into(); |
| 1398 | let runs = [gpui::TextRun { |
| 1399 | len: text.len(), |
| 1400 | font: gpui::font("IBM Plex Sans"), |
| 1401 | ..Default::default() |
| 1402 | }]; |
| 1403 | |
| 1404 | let first_layout = window_text_system.shape_line(text.clone(), gpui::px(14.0), &runs, None); |
| 1405 | let cached_layout = |
| 1406 | window_text_system.shape_line(text.clone(), gpui::px(14.0), &runs, None); |
| 1407 | assert!(std::ptr::eq::<LineLayout>( |
| 1408 | &**first_layout, |
| 1409 | &**cached_layout |
| 1410 | )); |
| 1411 | let loaded_font_count = platform_text_system.0.read().loaded_fonts.len(); |
| 1412 | |
| 1413 | text_system.add_fonts(vec![Cow::Borrowed(LILEX)])?; |
| 1414 | |
| 1415 | let refreshed_layout = window_text_system.shape_line(text, gpui::px(14.0), &runs, None); |
| 1416 | assert!(!std::ptr::eq::<LineLayout>( |
| 1417 | &**first_layout, |
| 1418 | &**refreshed_layout |
| 1419 | )); |
| 1420 | assert_eq!( |
| 1421 | platform_text_system.0.read().loaded_fonts.len(), |
| 1422 | loaded_font_count |
| 1423 | ); |
| 1424 | Ok(()) |
| 1425 | } |
| 1426 | |
| 1427 | #[test] |
| 1428 | fn layout_line_with_mixed_direction_paragraphs() -> Result<()> { |
| 1429 | let text_system = text_system()?; |
| 1430 | |
| 1431 | for separator in SEPARATORS { |
| 1432 | for text in [ |
| 1433 | format!("\u{05d0}{separator}A"), |
| 1434 | format!("A{separator}\u{05d0}"), |
| 1435 | ] { |
| 1436 | let layout = layout_text(&text_system, &text)?; |
| 1437 | |
| 1438 | assert_eq!(layout.len, text.len(), "{text:?}"); |
| 1439 | assert!(layout.width > Pixels::ZERO, "{text:?}"); |
| 1440 | assert!( |
| 1441 | layout.runs.iter().any(|run| !run.glyphs.is_empty()), |
| 1442 | "{text:?}" |
| 1443 | ); |
| 1444 | } |
| 1445 | } |
| 1446 | |
| 1447 | Ok(()) |
| 1448 | } |
| 1449 | |
| 1450 | #[test] |
| 1451 | fn layout_line_with_separators_at_line_edges() -> Result<()> { |
| 1452 | let text_system = text_system()?; |
| 1453 | |
| 1454 | for text in [ |
| 1455 | "\u{001c}", |
| 1456 | "\u{001c}\u{001c}", |
| 1457 | "\u{001c}\u{05d0}", |
| 1458 | "\u{05d0}\u{001c}", |
| 1459 | "\u{05d0}\u{001c}\u{001c}A", |
| 1460 | "\u{001c}\u{05d0}\u{001c}A\u{001c}", |
| 1461 | ] { |
| 1462 | let layout = layout_text(&text_system, text)?; |
| 1463 | assert_eq!(layout.len, text.len(), "{text:?}"); |
| 1464 | } |
| 1465 | |
| 1466 | Ok(()) |
| 1467 | } |
| 1468 | |
| 1469 | /// Glyph indices must stay absolute and positions ordered across segment |
| 1470 | /// boundaries, otherwise cursor placement and hit testing desync. Uses |
| 1471 | /// single-direction text so visual order matches logical order. |
| 1472 | #[test] |
| 1473 | fn layout_line_keeps_indices_and_positions_ordered_across_paragraphs() -> Result<()> { |
| 1474 | let text_system = text_system()?; |
| 1475 | let text = "ab\u{001c}cd\u{2029}ef"; |
| 1476 | let layout = layout_text(&text_system, text)?; |
| 1477 | |
| 1478 | let glyphs: Vec<_> = layout.runs.iter().flat_map(|run| &run.glyphs).collect(); |
| 1479 | assert!(!glyphs.is_empty()); |
| 1480 | |
| 1481 | for glyph in &glyphs { |
| 1482 | assert!(glyph.index < text.len(), "{:?}", glyph.index); |
| 1483 | assert!(text.is_char_boundary(glyph.index), "{:?}", glyph.index); |
| 1484 | } |
| 1485 | for pair in glyphs.windows(2) { |
| 1486 | assert!(pair[0].index < pair[1].index); |
| 1487 | assert!(pair[0].position.x <= pair[1].position.x); |
| 1488 | } |
| 1489 | |
| 1490 | // Every segment contributes width, so the whole line is wider than its |
| 1491 | // leading paragraph alone. |
| 1492 | assert!(layout.width > layout_text(&text_system, "ab")?.width); |
| 1493 | Ok(()) |
| 1494 | } |
| 1495 | |
| 1496 | /// A font run boundary that does not line up with a paragraph boundary must |
| 1497 | /// still be clipped to the right segments. |
| 1498 | #[test] |
| 1499 | fn layout_line_with_font_run_straddling_a_separator() -> Result<()> { |
| 1500 | let text_system = text_system()?; |
| 1501 | let font_id = text_system.font_id(&gpui::font("IBM Plex Sans"))?; |
| 1502 | let text = "ab\u{001c}\u{05d0}\u{05d1}"; |
| 1503 | |
| 1504 | // The run boundary falls inside the trailing RTL paragraph. |
| 1505 | let runs = [ |
| 1506 | FontRun { |
| 1507 | len: "ab\u{001c}\u{05d0}".len(), |
| 1508 | font_id, |
| 1509 | }, |
| 1510 | FontRun { |
| 1511 | len: "\u{05d1}".len(), |
| 1512 | font_id, |
| 1513 | }, |
| 1514 | ]; |
| 1515 | let layout = text_system.layout_line(text, gpui::px(14.0), &runs); |
| 1516 | |
| 1517 | assert_eq!(layout.len, text.len()); |
| 1518 | assert!(layout.width > Pixels::ZERO); |
| 1519 | Ok(()) |
| 1520 | } |
| 1521 | |
| 1522 | /// Lines with no separator take the fast path and must be shaped exactly as |
| 1523 | /// they were before paragraph splitting existed. |
| 1524 | #[test] |
| 1525 | fn layout_line_without_separators_takes_fast_path() -> Result<()> { |
| 1526 | let text_system = text_system()?; |
| 1527 | |
| 1528 | for text in [ |
| 1529 | "hello world", |
| 1530 | "\u{05d0}\u{05d1}\u{05d2}", |
| 1531 | "mixed \u{05d0}\u{05d1}", |
| 1532 | ] { |
| 1533 | assert!(!contains_paragraph_separator(text), "{text:?}"); |
| 1534 | let layout = layout_text(&text_system, text)?; |
| 1535 | assert_eq!(layout.len, text.len(), "{text:?}"); |
| 1536 | assert!(layout.width > Pixels::ZERO, "{text:?}"); |
| 1537 | } |
| 1538 | |
| 1539 | Ok(()) |
| 1540 | } |
| 1541 | |
| 1542 | /// cosmic-text sums word widths to get a line's width but accumulates glyph |
| 1543 | /// advances to position glyphs, so a trailing zero-advance glyph (here a |
| 1544 | /// zero-width space) can land a few ulps past the width. When that glyph is a |
| 1545 | /// wrap boundary, the row before it extends past the line's width, and hit |
| 1546 | /// testing in that sliver used to panic (ZED-BW8, ZED-75K, ZED-81Z). |
| 1547 | #[test] |
| 1548 | fn index_for_position_past_line_width() -> Result<()> { |
| 1549 | let text_system = Arc::new(gpui::TextSystem::new(Arc::new(text_system()?))); |
| 1550 | let window_text_system = gpui::WindowTextSystem::new(text_system); |
| 1551 | let text: SharedString = "Warning: this will delete files\u{200b}".into(); |
| 1552 | let runs = [gpui::TextRun { |
| 1553 | len: text.len(), |
| 1554 | font: gpui::font("IBM Plex Sans"), |
| 1555 | ..Default::default() |
| 1556 | }]; |
| 1557 | let lines = |
| 1558 | window_text_system.shape_text(text, gpui::px(14.), &runs, Some(gpui::px(4.)), None)?; |
| 1559 | let line = &lines[0]; |
| 1560 | let width = line.unwrapped_layout.width; |
| 1561 | let boundary_glyph = |row: usize| { |
| 1562 | let boundary = line.wrap_boundaries()[row]; |
| 1563 | &line.runs()[boundary.run_ix].glyphs[boundary.glyph_ix] |
| 1564 | }; |
| 1565 | let row = (1..line.wrap_boundaries().len()) |
| 1566 | .find(|row| boundary_glyph(*row).position.x > width) |
| 1567 | .expect("trailing zero-width space should be a wrap boundary past the line width"); |
| 1568 | let row_start_x = f32::from(boundary_glyph(row - 1).position.x); |
| 1569 | let row_end = boundary_glyph(row); |
| 1570 | |
| 1571 | let mut x = f32::from(width) - row_start_x; |
| 1572 | while x + row_start_x < f32::from(width) { |
| 1573 | x = x.next_up(); |
| 1574 | } |
| 1575 | assert!(gpui::px(x + row_start_x) < row_end.position.x); |
| 1576 | |
| 1577 | let line_height = gpui::px(20.); |
| 1578 | let position = gpui::point(gpui::px(x), line_height * row as f32 + gpui::px(1.)); |
| 1579 | assert_eq!( |
| 1580 | line.index_for_position(position, line_height), |
| 1581 | Err(row_end.index) |
| 1582 | ); |
| 1583 | Ok(()) |
| 1584 | } |
| 1585 | |
| 1586 | #[test] |
| 1587 | fn paragraph_separator_detection() { |
| 1588 | for separator in SEPARATORS { |
| 1589 | assert!(is_paragraph_separator(*separator), "{separator:?}"); |
| 1590 | assert!(contains_paragraph_separator(&format!("a{separator}b"))); |
| 1591 | } |
| 1592 | |
| 1593 | for text in [ |
| 1594 | "", |
| 1595 | "plain ascii", |
| 1596 | "\u{05d0}", |
| 1597 | "tab\there", |
| 1598 | "emoji \u{1f600}", |
| 1599 | ] { |
| 1600 | assert!(!contains_paragraph_separator(text), "{text:?}"); |
| 1601 | } |
| 1602 | } |
| 1603 | |
| 1604 | #[test] |
| 1605 | fn font_runs_are_clipped_to_segment() { |
| 1606 | let runs = [ |
| 1607 | FontRun { |
| 1608 | len: 3, |
| 1609 | font_id: fid(1), |
| 1610 | }, |
| 1611 | FontRun { |
| 1612 | len: 4, |
| 1613 | font_id: fid(2), |
| 1614 | }, |
| 1615 | ]; |
| 1616 | |
| 1617 | assert_eq!(clip_font_runs(&runs, 0..7).as_slice(), &runs); |
| 1618 | assert_eq!( |
| 1619 | clip_font_runs(&runs, 2..5).as_slice(), |
| 1620 | &[ |
| 1621 | FontRun { |
| 1622 | len: 1, |
| 1623 | font_id: fid(1) |
| 1624 | }, |
| 1625 | FontRun { |
| 1626 | len: 2, |
| 1627 | font_id: fid(2) |
| 1628 | }, |
| 1629 | ] |
| 1630 | ); |
| 1631 | assert_eq!( |
| 1632 | clip_font_runs(&runs, 3..7).as_slice(), |
| 1633 | &[FontRun { |
| 1634 | len: 4, |
| 1635 | font_id: fid(2) |
| 1636 | }] |
| 1637 | ); |
| 1638 | assert!(clip_font_runs(&runs, 5..5).is_empty()); |
| 1639 | } |
| 1640 | |
| 1641 | #[test] |
| 1642 | fn primary_wins_over_current_fallback_when_primary_covers() { |
| 1643 | let primary = fid(0); |
| 1644 | let fb = chain(&[1, 2]); |
| 1645 | let covers = |id: FontId, _: char| id == fid(0) || id == fid(1); |
| 1646 | assert_eq!( |
| 1647 | pick_covering_slot('a', Some(0), primary, &fb, &covers), |
| 1648 | None |
| 1649 | ); |
| 1650 | } |
| 1651 | |
| 1652 | #[test] |
| 1653 | fn primary_preferred_over_fallback_when_both_cover() { |
| 1654 | let primary = fid(0); |
| 1655 | let fb = chain(&[1]); |
| 1656 | let covers = |_: FontId, _: char| true; |
| 1657 | assert_eq!(pick_covering_slot('a', None, primary, &fb, &covers), None); |
| 1658 | } |
| 1659 | |
| 1660 | #[test] |
| 1661 | fn falls_through_chain_in_order() { |
| 1662 | let primary = fid(0); |
| 1663 | let fb = chain(&[1, 2, 3]); |
| 1664 | // only fallback 2 at index 1 covers. |
| 1665 | let covers = |id: FontId, _: char| id == fid(2); |
| 1666 | assert_eq!( |
| 1667 | pick_covering_slot('字', None, primary, &fb, &covers), |
| 1668 | Some(1) |
| 1669 | ); |
| 1670 | } |
| 1671 | |
| 1672 | #[test] |
| 1673 | fn no_coverage_returns_primary() { |
| 1674 | let primary = fid(0); |
| 1675 | let fb = chain(&[1, 2]); |
| 1676 | let covers = |_: FontId, _: char| false; |
| 1677 | // nothing covers. return `None` so the `cosmic-text` built in script |
| 1678 | // fallback can take over during shaping. |
| 1679 | assert_eq!( |
| 1680 | pick_covering_slot('\u{1F600}', Some(1), primary, &fb, &covers), |
| 1681 | None |
| 1682 | ); |
| 1683 | } |
| 1684 | |
| 1685 | #[test] |
| 1686 | fn empty_chain_always_returns_primary() { |
| 1687 | let primary = fid(0); |
| 1688 | let fb: SmallVec<[(FontId, SharedString); 4]> = SmallVec::new(); |
| 1689 | let covers = |_: FontId, _: char| false; |
| 1690 | assert_eq!(pick_covering_slot('a', None, primary, &fb, &covers), None); |
| 1691 | } |
| 1692 | |
| 1693 | #[test] |
| 1694 | fn slot_font_id_resolution() { |
| 1695 | let primary = fid(7); |
| 1696 | let fb = chain(&[10, 20]); |
| 1697 | assert_eq!(slot_font_id(None, primary, &fb), fid(7)); |
| 1698 | assert_eq!(slot_font_id(Some(0), primary, &fb), fid(10)); |
| 1699 | assert_eq!(slot_font_id(Some(1), primary, &fb), fid(20)); |
| 1700 | } |
| 1701 | |
| 1702 | #[test] |
| 1703 | fn run_spans_with_no_chain_emit_one_primary_span() { |
| 1704 | let primary = fid(0); |
| 1705 | let fb: SmallVec<[(FontId, SharedString); 4]> = SmallVec::new(); |
| 1706 | let covers = |_: FontId, _: char| false; |
| 1707 | let text = "hello"; |
| 1708 | let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers); |
| 1709 | assert_eq!(spans.as_slice(), &[span(0, text.len(), None, primary)]); |
| 1710 | } |
| 1711 | |
| 1712 | #[test] |
| 1713 | fn run_spans_use_byte_offsets_for_multibyte_chars() { |
| 1714 | let primary = fid(0); |
| 1715 | let fb = chain(&[1]); |
| 1716 | // primary covers ascii. fallback covers cjk. |
| 1717 | let covers = |id: FontId, ch: char| { |
| 1718 | if id == primary { |
| 1719 | ch.is_ascii() |
| 1720 | } else { |
| 1721 | !ch.is_ascii() |
| 1722 | } |
| 1723 | }; |
| 1724 | let text = "a字b"; |
| 1725 | let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers); |
| 1726 | // '字' is 3 bytes so split is at 1 then 4. |
| 1727 | assert_eq!( |
| 1728 | spans.as_slice(), |
| 1729 | &[ |
| 1730 | span(0, 1, None, primary), |
| 1731 | span(1, 4, Some(0), fid(1)), |
| 1732 | span(4, 5, None, primary), |
| 1733 | ] |
| 1734 | ); |
| 1735 | } |
| 1736 | |
| 1737 | #[test] |
| 1738 | fn run_spans_respect_run_offset() { |
| 1739 | let primary = fid(0); |
| 1740 | let fb = chain(&[1]); |
| 1741 | let covers = |id: FontId, ch: char| { |
| 1742 | if id == primary { |
| 1743 | ch.is_ascii() |
| 1744 | } else { |
| 1745 | !ch.is_ascii() |
| 1746 | } |
| 1747 | }; |
| 1748 | // outer text has a prefix that is not part of this run. |
| 1749 | let text = "xx字y"; |
| 1750 | let run_offset = 2; |
| 1751 | let run_len = text.len() - run_offset; |
| 1752 | let spans = compute_run_spans(text, run_offset, run_len, primary, &fb, &covers); |
| 1753 | assert_eq!( |
| 1754 | spans.as_slice(), |
| 1755 | &[span(2, 5, Some(0), fid(1)), span(5, 6, None, primary)] |
| 1756 | ); |
| 1757 | } |
| 1758 | |
| 1759 | #[test] |
| 1760 | fn run_spans_keep_combining_marks_with_base_in_fallback() { |
| 1761 | let primary = fid(0); |
| 1762 | let fb = chain(&[1]); |
| 1763 | // primary covers ascii only. fallback covers the base char. |
| 1764 | // combining mark must stay in the fallback span even when fallback |
| 1765 | // does not advertise coverage of it. |
| 1766 | let covers = |id: FontId, ch: char| { |
| 1767 | if id == primary { |
| 1768 | ch.is_ascii() |
| 1769 | } else { |
| 1770 | ch == '\u{0905}' |
| 1771 | } |
| 1772 | }; |
| 1773 | // \u{0905} devanagari short a + \u{0902} candrabindu mark. |
| 1774 | let text = "\u{0905}\u{0902}"; |
| 1775 | let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers); |
| 1776 | assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]); |
| 1777 | } |
| 1778 | |
| 1779 | #[test] |
| 1780 | fn run_spans_keep_zwj_inside_emoji_cluster() { |
| 1781 | let primary = fid(0); |
| 1782 | let fb = chain(&[1]); |
| 1783 | // only fallback covers the emoji codepoints. zwj must not split. |
| 1784 | let covers = |id: FontId, ch: char| id == fid(1) && ch != '\u{200D}'; |
| 1785 | // family zwj sequence woman zwj girl. |
| 1786 | let text = "\u{1F469}\u{200D}\u{1F467}"; |
| 1787 | let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers); |
| 1788 | assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]); |
| 1789 | } |
| 1790 | |
| 1791 | #[test] |
| 1792 | fn run_spans_collapse_adjacent_same_slot() { |
| 1793 | let primary = fid(0); |
| 1794 | let fb = chain(&[1]); |
| 1795 | let covers = |id: FontId, ch: char| { |
| 1796 | if id == primary { |
| 1797 | ch.is_ascii() |
| 1798 | } else { |
| 1799 | !ch.is_ascii() |
| 1800 | } |
| 1801 | }; |
| 1802 | let text = "字字字"; |
| 1803 | let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers); |
| 1804 | assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]); |
| 1805 | } |
| 1806 | |
| 1807 | #[test] |
| 1808 | fn run_spans_empty_run_returns_no_spans() { |
| 1809 | let primary = fid(0); |
| 1810 | let fb = chain(&[1]); |
| 1811 | let covers = |_: FontId, _: char| true; |
| 1812 | let spans = compute_run_spans("anything", 3, 0, primary, &fb, &covers); |
| 1813 | assert!(spans.is_empty()); |
| 1814 | } |
| 1815 | } |