direct_write.rs

   1use std::{borrow::Cow, mem::ManuallyDrop, sync::Arc};
   2
   3use ::util::ResultExt;
   4use anyhow::Result;
   5use collections::HashMap;
   6use itertools::Itertools;
   7use parking_lot::{RwLock, RwLockUpgradableReadGuard};
   8use windows::{
   9    Win32::{
  10        Foundation::*,
  11        Globalization::GetUserDefaultLocaleName,
  12        Graphics::{DirectWrite::*, Dxgi::Common::*, Gdi::LOGFONTW, Imaging::*},
  13        System::SystemServices::LOCALE_NAME_MAX_LENGTH,
  14        UI::WindowsAndMessaging::*,
  15    },
  16    core::*,
  17};
  18use windows_numerics::Vector2;
  19
  20use crate::*;
  21
  22#[derive(Debug)]
  23struct FontInfo {
  24    font_family: String,
  25    font_face: IDWriteFontFace3,
  26    features: IDWriteTypography,
  27    fallbacks: Option<IDWriteFontFallback>,
  28    is_system_font: bool,
  29}
  30
  31pub(crate) struct DirectWriteTextSystem(RwLock<DirectWriteState>);
  32
  33struct DirectWriteComponent {
  34    locale: String,
  35    factory: IDWriteFactory5,
  36    bitmap_factory: AgileReference<IWICImagingFactory>,
  37    in_memory_loader: IDWriteInMemoryFontFileLoader,
  38    builder: IDWriteFontSetBuilder1,
  39    text_renderer: Arc<TextRendererWrapper>,
  40    render_context: GlyphRenderContext,
  41}
  42
  43struct GlyphRenderContext {
  44    params: IDWriteRenderingParams3,
  45}
  46
  47struct DirectWriteState {
  48    components: DirectWriteComponent,
  49    system_ui_font_name: SharedString,
  50    system_font_collection: IDWriteFontCollection1,
  51    custom_font_collection: IDWriteFontCollection1,
  52    fonts: Vec<FontInfo>,
  53    font_selections: HashMap<Font, FontId>,
  54    font_id_by_identifier: HashMap<FontIdentifier, FontId>,
  55}
  56
  57#[derive(Debug, Clone, Hash, PartialEq, Eq)]
  58struct FontIdentifier {
  59    postscript_name: String,
  60    weight: i32,
  61    style: i32,
  62}
  63
  64impl DirectWriteComponent {
  65    pub fn new(bitmap_factory: &IWICImagingFactory) -> Result<Self> {
  66        unsafe {
  67            let factory: IDWriteFactory5 = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED)?;
  68            let bitmap_factory = AgileReference::new(bitmap_factory)?;
  69            // The `IDWriteInMemoryFontFileLoader` here is supported starting from
  70            // Windows 10 Creators Update, which consequently requires the entire
  71            // `DirectWriteTextSystem` to run on `win10 1703`+.
  72            let in_memory_loader = factory.CreateInMemoryFontFileLoader()?;
  73            factory.RegisterFontFileLoader(&in_memory_loader)?;
  74            let builder = factory.CreateFontSetBuilder()?;
  75            let mut locale_vec = vec![0u16; LOCALE_NAME_MAX_LENGTH as usize];
  76            GetUserDefaultLocaleName(&mut locale_vec);
  77            let locale = String::from_utf16_lossy(&locale_vec);
  78            let text_renderer = Arc::new(TextRendererWrapper::new(&locale));
  79            let render_context = GlyphRenderContext::new(&factory)?;
  80
  81            Ok(DirectWriteComponent {
  82                locale,
  83                factory,
  84                bitmap_factory,
  85                in_memory_loader,
  86                builder,
  87                text_renderer,
  88                render_context,
  89            })
  90        }
  91    }
  92}
  93
  94impl GlyphRenderContext {
  95    pub fn new(factory: &IDWriteFactory5) -> Result<Self> {
  96        unsafe {
  97            let default_params: IDWriteRenderingParams3 =
  98                factory.CreateRenderingParams()?.cast()?;
  99            let gamma = default_params.GetGamma();
 100            let enhanced_contrast = default_params.GetEnhancedContrast();
 101            let gray_contrast = default_params.GetGrayscaleEnhancedContrast();
 102            let cleartype_level = default_params.GetClearTypeLevel();
 103            let grid_fit_mode = default_params.GetGridFitMode();
 104
 105            let params = factory.CreateCustomRenderingParams(
 106                gamma,
 107                enhanced_contrast,
 108                gray_contrast,
 109                cleartype_level,
 110                DWRITE_PIXEL_GEOMETRY_RGB,
 111                DWRITE_RENDERING_MODE1_NATURAL_SYMMETRIC,
 112                grid_fit_mode,
 113            )?;
 114
 115            Ok(Self { params })
 116        }
 117    }
 118}
 119
 120impl DirectWriteTextSystem {
 121    pub(crate) fn new(bitmap_factory: &IWICImagingFactory) -> Result<Self> {
 122        let components = DirectWriteComponent::new(bitmap_factory)?;
 123        let system_font_collection = unsafe {
 124            let mut result = std::mem::zeroed();
 125            components
 126                .factory
 127                .GetSystemFontCollection(false, &mut result, true)?;
 128            result.unwrap()
 129        };
 130        let custom_font_set = unsafe { components.builder.CreateFontSet()? };
 131        let custom_font_collection = unsafe {
 132            components
 133                .factory
 134                .CreateFontCollectionFromFontSet(&custom_font_set)?
 135        };
 136        let system_ui_font_name = get_system_ui_font_name();
 137
 138        Ok(Self(RwLock::new(DirectWriteState {
 139            components,
 140            system_ui_font_name,
 141            system_font_collection,
 142            custom_font_collection,
 143            fonts: Vec::new(),
 144            font_selections: HashMap::default(),
 145            font_id_by_identifier: HashMap::default(),
 146        })))
 147    }
 148}
 149
 150impl PlatformTextSystem for DirectWriteTextSystem {
 151    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
 152        self.0.write().add_fonts(fonts)
 153    }
 154
 155    fn all_font_names(&self) -> Vec<String> {
 156        self.0.read().all_font_names()
 157    }
 158
 159    fn font_id(&self, font: &Font) -> Result<FontId> {
 160        let lock = self.0.upgradable_read();
 161        if let Some(font_id) = lock.font_selections.get(font) {
 162            Ok(*font_id)
 163        } else {
 164            let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
 165            let font_id = lock.select_font(font);
 166            lock.font_selections.insert(font.clone(), font_id);
 167            Ok(font_id)
 168        }
 169    }
 170
 171    fn font_metrics(&self, font_id: FontId) -> FontMetrics {
 172        self.0.read().font_metrics(font_id)
 173    }
 174
 175    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
 176        self.0.read().get_typographic_bounds(font_id, glyph_id)
 177    }
 178
 179    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Size<f32>> {
 180        self.0.read().get_advance(font_id, glyph_id)
 181    }
 182
 183    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
 184        self.0.read().glyph_for_char(font_id, ch)
 185    }
 186
 187    fn glyph_raster_bounds(
 188        &self,
 189        params: &RenderGlyphParams,
 190    ) -> anyhow::Result<Bounds<DevicePixels>> {
 191        self.0.read().raster_bounds(params)
 192    }
 193
 194    fn rasterize_glyph(
 195        &self,
 196        params: &RenderGlyphParams,
 197        raster_bounds: Bounds<DevicePixels>,
 198    ) -> anyhow::Result<(Size<DevicePixels>, Vec<u8>)> {
 199        self.0.read().rasterize_glyph(params, raster_bounds)
 200    }
 201
 202    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {
 203        self.0
 204            .write()
 205            .layout_line(text, font_size, runs)
 206            .log_err()
 207            .unwrap_or(LineLayout {
 208                font_size,
 209                ..Default::default()
 210            })
 211    }
 212}
 213
 214impl DirectWriteState {
 215    fn add_fonts(&mut self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
 216        for font_data in fonts {
 217            match font_data {
 218                Cow::Borrowed(data) => unsafe {
 219                    let font_file = self
 220                        .components
 221                        .in_memory_loader
 222                        .CreateInMemoryFontFileReference(
 223                            &self.components.factory,
 224                            data.as_ptr() as _,
 225                            data.len() as _,
 226                            None,
 227                        )?;
 228                    self.components.builder.AddFontFile(&font_file)?;
 229                },
 230                Cow::Owned(data) => unsafe {
 231                    let font_file = self
 232                        .components
 233                        .in_memory_loader
 234                        .CreateInMemoryFontFileReference(
 235                            &self.components.factory,
 236                            data.as_ptr() as _,
 237                            data.len() as _,
 238                            None,
 239                        )?;
 240                    self.components.builder.AddFontFile(&font_file)?;
 241                },
 242            }
 243        }
 244        let set = unsafe { self.components.builder.CreateFontSet()? };
 245        let collection = unsafe {
 246            self.components
 247                .factory
 248                .CreateFontCollectionFromFontSet(&set)?
 249        };
 250        self.custom_font_collection = collection;
 251
 252        Ok(())
 253    }
 254
 255    fn generate_font_fallbacks(
 256        &self,
 257        fallbacks: &FontFallbacks,
 258    ) -> Result<Option<IDWriteFontFallback>> {
 259        if fallbacks.fallback_list().is_empty() {
 260            return Ok(None);
 261        }
 262        unsafe {
 263            let builder = self.components.factory.CreateFontFallbackBuilder()?;
 264            let font_set = &self.system_font_collection.GetFontSet()?;
 265            for family_name in fallbacks.fallback_list() {
 266                let Some(fonts) = font_set
 267                    .GetMatchingFonts(
 268                        &HSTRING::from(family_name),
 269                        DWRITE_FONT_WEIGHT_NORMAL,
 270                        DWRITE_FONT_STRETCH_NORMAL,
 271                        DWRITE_FONT_STYLE_NORMAL,
 272                    )
 273                    .log_err()
 274                else {
 275                    continue;
 276                };
 277                if fonts.GetFontCount() == 0 {
 278                    log::error!("No matching font found for {}", family_name);
 279                    continue;
 280                }
 281                let font = fonts.GetFontFaceReference(0)?.CreateFontFace()?;
 282                let mut count = 0;
 283                font.GetUnicodeRanges(None, &mut count).ok();
 284                if count == 0 {
 285                    continue;
 286                }
 287                let mut unicode_ranges = vec![DWRITE_UNICODE_RANGE::default(); count as usize];
 288                let Some(_) = font
 289                    .GetUnicodeRanges(Some(&mut unicode_ranges), &mut count)
 290                    .log_err()
 291                else {
 292                    continue;
 293                };
 294                let target_family_name = HSTRING::from(family_name);
 295                builder.AddMapping(
 296                    &unicode_ranges,
 297                    &[target_family_name.as_ptr()],
 298                    None,
 299                    None,
 300                    None,
 301                    1.0,
 302                )?;
 303            }
 304            let system_fallbacks = self.components.factory.GetSystemFontFallback()?;
 305            builder.AddMappings(&system_fallbacks)?;
 306            Ok(Some(builder.CreateFontFallback()?))
 307        }
 308    }
 309
 310    unsafe fn generate_font_features(
 311        &self,
 312        font_features: &FontFeatures,
 313    ) -> Result<IDWriteTypography> {
 314        let direct_write_features = unsafe { self.components.factory.CreateTypography()? };
 315        apply_font_features(&direct_write_features, font_features)?;
 316        Ok(direct_write_features)
 317    }
 318
 319    unsafe fn get_font_id_from_font_collection(
 320        &mut self,
 321        family_name: &str,
 322        font_weight: FontWeight,
 323        font_style: FontStyle,
 324        font_features: &FontFeatures,
 325        font_fallbacks: Option<&FontFallbacks>,
 326        is_system_font: bool,
 327    ) -> Option<FontId> {
 328        let collection = if is_system_font {
 329            &self.system_font_collection
 330        } else {
 331            &self.custom_font_collection
 332        };
 333        let fontset = unsafe { collection.GetFontSet().log_err()? };
 334        let font = unsafe {
 335            fontset
 336                .GetMatchingFonts(
 337                    &HSTRING::from(family_name),
 338                    font_weight.into(),
 339                    DWRITE_FONT_STRETCH_NORMAL,
 340                    font_style.into(),
 341                )
 342                .log_err()?
 343        };
 344        let total_number = unsafe { font.GetFontCount() };
 345        for index in 0..total_number {
 346            let Some(font_face_ref) = (unsafe { font.GetFontFaceReference(index).log_err() })
 347            else {
 348                continue;
 349            };
 350            let Some(font_face) = (unsafe { font_face_ref.CreateFontFace().log_err() }) else {
 351                continue;
 352            };
 353            let Some(identifier) = get_font_identifier(&font_face, &self.components.locale) else {
 354                continue;
 355            };
 356            let Some(direct_write_features) =
 357                (unsafe { self.generate_font_features(font_features).log_err() })
 358            else {
 359                continue;
 360            };
 361            let fallbacks = font_fallbacks
 362                .and_then(|fallbacks| self.generate_font_fallbacks(fallbacks).log_err().flatten());
 363            let font_info = FontInfo {
 364                font_family: family_name.to_owned(),
 365                font_face,
 366                features: direct_write_features,
 367                fallbacks,
 368                is_system_font,
 369            };
 370            let font_id = FontId(self.fonts.len());
 371            self.fonts.push(font_info);
 372            self.font_id_by_identifier.insert(identifier, font_id);
 373            return Some(font_id);
 374        }
 375        None
 376    }
 377
 378    unsafe fn update_system_font_collection(&mut self) {
 379        let mut collection = unsafe { std::mem::zeroed() };
 380        if unsafe {
 381            self.components
 382                .factory
 383                .GetSystemFontCollection(false, &mut collection, true)
 384                .log_err()
 385                .is_some()
 386        } {
 387            self.system_font_collection = collection.unwrap();
 388        }
 389    }
 390
 391    fn select_font(&mut self, target_font: &Font) -> FontId {
 392        unsafe {
 393            if target_font.family == ".SystemUIFont" {
 394                let family = self.system_ui_font_name.clone();
 395                self.find_font_id(
 396                    family.as_ref(),
 397                    target_font.weight,
 398                    target_font.style,
 399                    &target_font.features,
 400                    target_font.fallbacks.as_ref(),
 401                )
 402                .unwrap()
 403            } else {
 404                self.find_font_id(
 405                    target_font.family.as_ref(),
 406                    target_font.weight,
 407                    target_font.style,
 408                    &target_font.features,
 409                    target_font.fallbacks.as_ref(),
 410                )
 411                .unwrap_or_else(|| {
 412                    #[cfg(any(test, feature = "test-support"))]
 413                    {
 414                        panic!("ERROR: {} font not found!", target_font.family);
 415                    }
 416                    #[cfg(not(any(test, feature = "test-support")))]
 417                    {
 418                        let family = self.system_ui_font_name.clone();
 419                        log::error!("{} not found, use {} instead.", target_font.family, family);
 420                        self.get_font_id_from_font_collection(
 421                            family.as_ref(),
 422                            target_font.weight,
 423                            target_font.style,
 424                            &target_font.features,
 425                            target_font.fallbacks.as_ref(),
 426                            true,
 427                        )
 428                        .unwrap()
 429                    }
 430                })
 431            }
 432        }
 433    }
 434
 435    unsafe fn find_font_id(
 436        &mut self,
 437        family_name: &str,
 438        weight: FontWeight,
 439        style: FontStyle,
 440        features: &FontFeatures,
 441        fallbacks: Option<&FontFallbacks>,
 442    ) -> Option<FontId> {
 443        // try to find target font in custom font collection first
 444        unsafe {
 445            self.get_font_id_from_font_collection(
 446                family_name,
 447                weight,
 448                style,
 449                features,
 450                fallbacks,
 451                false,
 452            )
 453            .or_else(|| {
 454                self.get_font_id_from_font_collection(
 455                    family_name,
 456                    weight,
 457                    style,
 458                    features,
 459                    fallbacks,
 460                    true,
 461                )
 462            })
 463            .or_else(|| {
 464                self.update_system_font_collection();
 465                self.get_font_id_from_font_collection(
 466                    family_name,
 467                    weight,
 468                    style,
 469                    features,
 470                    fallbacks,
 471                    true,
 472                )
 473            })
 474        }
 475    }
 476
 477    fn layout_line(
 478        &mut self,
 479        text: &str,
 480        font_size: Pixels,
 481        font_runs: &[FontRun],
 482    ) -> Result<LineLayout> {
 483        if font_runs.is_empty() {
 484            return Ok(LineLayout {
 485                font_size,
 486                ..Default::default()
 487            });
 488        }
 489        unsafe {
 490            let text_renderer = self.components.text_renderer.clone();
 491            let text_wide = text.encode_utf16().collect_vec();
 492
 493            let mut utf8_offset = 0usize;
 494            let mut utf16_offset = 0u32;
 495            let text_layout = {
 496                let first_run = &font_runs[0];
 497                let font_info = &self.fonts[first_run.font_id.0];
 498                let collection = if font_info.is_system_font {
 499                    &self.system_font_collection
 500                } else {
 501                    &self.custom_font_collection
 502                };
 503                let format: IDWriteTextFormat1 = self
 504                    .components
 505                    .factory
 506                    .CreateTextFormat(
 507                        &HSTRING::from(&font_info.font_family),
 508                        collection,
 509                        font_info.font_face.GetWeight(),
 510                        font_info.font_face.GetStyle(),
 511                        DWRITE_FONT_STRETCH_NORMAL,
 512                        font_size.0,
 513                        &HSTRING::from(&self.components.locale),
 514                    )?
 515                    .cast()?;
 516                if let Some(ref fallbacks) = font_info.fallbacks {
 517                    format.SetFontFallback(fallbacks)?;
 518                }
 519
 520                let layout = self.components.factory.CreateTextLayout(
 521                    &text_wide,
 522                    &format,
 523                    f32::INFINITY,
 524                    f32::INFINITY,
 525                )?;
 526                let current_text = &text[utf8_offset..(utf8_offset + first_run.len)];
 527                utf8_offset += first_run.len;
 528                let current_text_utf16_length = current_text.encode_utf16().count() as u32;
 529                let text_range = DWRITE_TEXT_RANGE {
 530                    startPosition: utf16_offset,
 531                    length: current_text_utf16_length,
 532                };
 533                layout.SetTypography(&font_info.features, text_range)?;
 534                utf16_offset += current_text_utf16_length;
 535
 536                layout
 537            };
 538
 539            let mut first_run = true;
 540            let mut ascent = Pixels::default();
 541            let mut descent = Pixels::default();
 542            for run in font_runs {
 543                if first_run {
 544                    first_run = false;
 545                    let mut metrics = vec![DWRITE_LINE_METRICS::default(); 4];
 546                    let mut line_count = 0u32;
 547                    text_layout.GetLineMetrics(Some(&mut metrics), &mut line_count as _)?;
 548                    ascent = px(metrics[0].baseline);
 549                    descent = px(metrics[0].height - metrics[0].baseline);
 550                    continue;
 551                }
 552                let font_info = &self.fonts[run.font_id.0];
 553                let current_text = &text[utf8_offset..(utf8_offset + run.len)];
 554                utf8_offset += run.len;
 555                let current_text_utf16_length = current_text.encode_utf16().count() as u32;
 556
 557                let collection = if font_info.is_system_font {
 558                    &self.system_font_collection
 559                } else {
 560                    &self.custom_font_collection
 561                };
 562                let text_range = DWRITE_TEXT_RANGE {
 563                    startPosition: utf16_offset,
 564                    length: current_text_utf16_length,
 565                };
 566                utf16_offset += current_text_utf16_length;
 567                text_layout.SetFontCollection(collection, text_range)?;
 568                text_layout
 569                    .SetFontFamilyName(&HSTRING::from(&font_info.font_family), text_range)?;
 570                text_layout.SetFontSize(font_size.0, text_range)?;
 571                text_layout.SetFontStyle(font_info.font_face.GetStyle(), text_range)?;
 572                text_layout.SetFontWeight(font_info.font_face.GetWeight(), text_range)?;
 573                text_layout.SetTypography(&font_info.features, text_range)?;
 574            }
 575
 576            let mut runs = Vec::new();
 577            let renderer_context = RendererContext {
 578                text_system: self,
 579                index_converter: StringIndexConverter::new(text),
 580                runs: &mut runs,
 581                width: 0.0,
 582            };
 583            text_layout.Draw(
 584                Some(&renderer_context as *const _ as _),
 585                &text_renderer.0,
 586                0.0,
 587                0.0,
 588            )?;
 589            let width = px(renderer_context.width);
 590
 591            Ok(LineLayout {
 592                font_size,
 593                width,
 594                ascent,
 595                descent,
 596                runs,
 597                len: text.len(),
 598            })
 599        }
 600    }
 601
 602    fn font_metrics(&self, font_id: FontId) -> FontMetrics {
 603        unsafe {
 604            let font_info = &self.fonts[font_id.0];
 605            let mut metrics = std::mem::zeroed();
 606            font_info.font_face.GetMetrics(&mut metrics);
 607
 608            FontMetrics {
 609                units_per_em: metrics.Base.designUnitsPerEm as _,
 610                ascent: metrics.Base.ascent as _,
 611                descent: -(metrics.Base.descent as f32),
 612                line_gap: metrics.Base.lineGap as _,
 613                underline_position: metrics.Base.underlinePosition as _,
 614                underline_thickness: metrics.Base.underlineThickness as _,
 615                cap_height: metrics.Base.capHeight as _,
 616                x_height: metrics.Base.xHeight as _,
 617                bounding_box: Bounds {
 618                    origin: Point {
 619                        x: metrics.glyphBoxLeft as _,
 620                        y: metrics.glyphBoxBottom as _,
 621                    },
 622                    size: Size {
 623                        width: (metrics.glyphBoxRight - metrics.glyphBoxLeft) as _,
 624                        height: (metrics.glyphBoxTop - metrics.glyphBoxBottom) as _,
 625                    },
 626                },
 627            }
 628        }
 629    }
 630
 631    fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
 632        let font = &self.fonts[params.font_id.0];
 633        let glyph_id = [params.glyph_id.0 as u16];
 634        let advance = [0.0f32];
 635        let offset = [DWRITE_GLYPH_OFFSET::default()];
 636        let glyph_run = DWRITE_GLYPH_RUN {
 637            fontFace: unsafe { std::mem::transmute_copy(&font.font_face) },
 638            fontEmSize: params.font_size.0,
 639            glyphCount: 1,
 640            glyphIndices: glyph_id.as_ptr(),
 641            glyphAdvances: advance.as_ptr(),
 642            glyphOffsets: offset.as_ptr(),
 643            isSideways: BOOL(0),
 644            bidiLevel: 0,
 645        };
 646
 647        let rendering_mode = DWRITE_RENDERING_MODE1_NATURAL_SYMMETRIC;
 648        let measuring_mode = DWRITE_MEASURING_MODE_NATURAL;
 649        let baseline_origin_x = 0.0;
 650        let baseline_origin_y = 0.0;
 651
 652        let glyph_analysis = unsafe {
 653            self.components.factory.CreateGlyphRunAnalysis(
 654                &glyph_run,
 655                None,
 656                rendering_mode,
 657                measuring_mode,
 658                DWRITE_GRID_FIT_MODE_DEFAULT,
 659                DWRITE_TEXT_ANTIALIAS_MODE_CLEARTYPE,
 660                baseline_origin_x,
 661                baseline_origin_y,
 662            )?
 663        };
 664
 665        let texture_type = DWRITE_TEXTURE_CLEARTYPE_3x1;
 666        let bounds = unsafe { glyph_analysis.GetAlphaTextureBounds(texture_type)? };
 667
 668        // todo(windows)
 669        // This is a walkaround, deleted when figured out.
 670        let y_offset;
 671        let extra_height;
 672        if params.is_emoji {
 673            y_offset = 0;
 674            extra_height = 0;
 675        } else {
 676            // make some room for scaler.
 677            y_offset = -1;
 678            extra_height = 2;
 679        }
 680
 681        if bounds.right < bounds.left {
 682            Ok(Bounds {
 683                origin: point(0.into(), 0.into()),
 684                size: size(0.into(), 0.into()),
 685            })
 686        } else {
 687            Ok(Bounds {
 688                origin: point(
 689                    ((bounds.left as f32 * params.scale_factor).ceil() as i32).into(),
 690                    ((bounds.top as f32 * params.scale_factor).ceil() as i32 + y_offset).into(),
 691                ),
 692                size: size(
 693                    (((bounds.right - bounds.left) as f32 * params.scale_factor).ceil() as i32)
 694                        .into(),
 695                    (((bounds.bottom - bounds.top) as f32 * params.scale_factor).ceil() as i32
 696                        + extra_height)
 697                        .into(),
 698                ),
 699            })
 700        }
 701    }
 702
 703    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
 704        let font_info = &self.fonts[font_id.0];
 705        let codepoints = [ch as u32];
 706        let mut glyph_indices = vec![0u16; 1];
 707        unsafe {
 708            font_info
 709                .font_face
 710                .GetGlyphIndices(codepoints.as_ptr(), 1, glyph_indices.as_mut_ptr())
 711                .log_err()
 712        }
 713        .map(|_| GlyphId(glyph_indices[0] as u32))
 714    }
 715
 716    fn rasterize_glyph(
 717        &self,
 718        params: &RenderGlyphParams,
 719        glyph_bounds: Bounds<DevicePixels>,
 720    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
 721        if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
 722            anyhow::bail!("glyph bounds are empty");
 723        }
 724
 725        let font_info = &self.fonts[params.font_id.0];
 726        let glyph_id = [params.glyph_id.0 as u16];
 727        let advance = [glyph_bounds.size.width.0 as f32];
 728        let offset = [DWRITE_GLYPH_OFFSET {
 729            advanceOffset: -glyph_bounds.origin.x.0 as f32 / params.scale_factor,
 730            ascenderOffset: glyph_bounds.origin.y.0 as f32 / params.scale_factor,
 731        }];
 732        let glyph_run = DWRITE_GLYPH_RUN {
 733            fontFace: ManuallyDrop::new(Some(font_info.font_face.cast()?)),
 734            fontEmSize: params.font_size.0,
 735            glyphCount: 1,
 736            glyphIndices: glyph_id.as_ptr(),
 737            glyphAdvances: advance.as_ptr(),
 738            glyphOffsets: offset.as_ptr(),
 739            isSideways: BOOL(0),
 740            bidiLevel: 0,
 741        };
 742
 743        // Add an extra pixel when the subpixel variant isn't zero to make room for anti-aliasing.
 744        let mut bitmap_size = glyph_bounds.size;
 745        if params.subpixel_variant.x > 0 {
 746            bitmap_size.width += DevicePixels(1);
 747        }
 748        if params.subpixel_variant.y > 0 {
 749            bitmap_size.height += DevicePixels(1);
 750        }
 751        let bitmap_size = bitmap_size;
 752
 753        let subpixel_shift = params
 754            .subpixel_variant
 755            .map(|v| v as f32 / SUBPIXEL_VARIANTS as f32);
 756        let baseline_origin_x = subpixel_shift.x / params.scale_factor;
 757        let baseline_origin_y = subpixel_shift.y / params.scale_factor;
 758
 759        let transform = DWRITE_MATRIX {
 760            m11: params.scale_factor,
 761            m12: 0.0,
 762            m21: 0.0,
 763            m22: params.scale_factor,
 764            dx: 0.0,
 765            dy: 0.0,
 766        };
 767
 768        let rendering_mode = if params.is_emoji {
 769            DWRITE_RENDERING_MODE1_NATURAL
 770        } else {
 771            DWRITE_RENDERING_MODE1_NATURAL_SYMMETRIC
 772        };
 773
 774        let measuring_mode = DWRITE_MEASURING_MODE_NATURAL;
 775
 776        let glyph_analysis = unsafe {
 777            self.components.factory.CreateGlyphRunAnalysis(
 778                &glyph_run,
 779                Some(&transform),
 780                rendering_mode,
 781                measuring_mode,
 782                DWRITE_GRID_FIT_MODE_DEFAULT,
 783                DWRITE_TEXT_ANTIALIAS_MODE_CLEARTYPE,
 784                baseline_origin_x,
 785                baseline_origin_y,
 786            )?
 787        };
 788
 789        let texture_type = DWRITE_TEXTURE_CLEARTYPE_3x1;
 790        let texture_bounds = unsafe { glyph_analysis.GetAlphaTextureBounds(texture_type)? };
 791        let texture_width = (texture_bounds.right - texture_bounds.left) as u32;
 792        let texture_height = (texture_bounds.bottom - texture_bounds.top) as u32;
 793
 794        if texture_width == 0 || texture_height == 0 {
 795            return Ok((
 796                bitmap_size,
 797                vec![
 798                    0u8;
 799                    bitmap_size.width.0 as usize
 800                        * bitmap_size.height.0 as usize
 801                        * if params.is_emoji { 4 } else { 1 }
 802                ],
 803            ));
 804        }
 805
 806        let mut bitmap_data;
 807        if params.is_emoji {
 808            // todo: support more glyph image formats for more exotic fonts, for now it should fallback to monochrome rendering
 809            let color_enumerator = unsafe {
 810                self.components.factory.TranslateColorGlyphRun(
 811                    Vector2::new(baseline_origin_x, baseline_origin_y),
 812                    &glyph_run,
 813                    None,
 814                    DWRITE_GLYPH_IMAGE_FORMATS_COLR
 815                        | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8,
 816                    measuring_mode,
 817                    Some(&transform),
 818                    0,
 819                )
 820            };
 821
 822            // if let Ok(color_enumerator) = color_enumerator {
 823            //     loop {
 824            //         let color_run = unsafe { color_enumerator.GetCurrentRun() };
 825            //         if let Ok(color_run) = color_run {
 826            //             let color_glyph_run = unsafe { &*color_run };
 827            //             let color_value = color_glyph_run.Base.runColor;
 828
 829            //             // Create analysis for this color layer
 830            //             let color_analysis = unsafe {
 831            //                 self.components.factory.CreateGlyphRunAnalysis(
 832            //                     &color_glyph_run.Base.glyphRun as *const _,
 833            //                     Some(&transform),
 834            //                     rendering_mode,
 835            //                     measuring_mode,
 836            //                     DWRITE_GRID_FIT_MODE_DEFAULT,
 837            //                     DWRITE_TEXT_ANTIALIAS_MODE_CLEARTYPE,
 838            //                     baseline_origin_x,
 839            //                     baseline_origin_y,
 840            //                 )
 841            //             };
 842
 843            //             // todo: move this block completely to the gpu
 844            //             // this is important because fonts can bundle quite large icons
 845            //             // and compositing them on the cpu is quite expensive
 846            //             // also the code is ugly
 847            //             if let Ok(color_analysis) = color_analysis {
 848            //                 let color_bounds =
 849            //                     unsafe { color_analysis.GetAlphaTextureBounds(texture_type) };
 850            //                 if let Ok(color_bounds) = color_bounds {
 851            //                     let color_width = (color_bounds.right - color_bounds.left) as u32;
 852            //                     let color_height = (color_bounds.bottom - color_bounds.top) as u32;
 853
 854            //                     if color_width > 0 && color_height > 0 {
 855            //                         let mut alpha_data =
 856            //                             vec![0u8; (color_width * color_height * 3) as usize];
 857            //                         if unsafe {
 858            //                             color_analysis.CreateAlphaTexture(
 859            //                                 texture_type,
 860            //                                 &color_bounds,
 861            //                                 &mut alpha_data,
 862            //                             )
 863            //                         }
 864            //                         .is_ok()
 865            //                         {
 866            //                             let r = (color_value.r * 255.0) as u8;
 867            //                             let g = (color_value.g * 255.0) as u8;
 868            //                             let b = (color_value.b * 255.0) as u8;
 869            //                             let a = (color_value.a * 255.0) as u8;
 870
 871            //                             let offset_x = color_bounds.left.max(0) as usize;
 872            //                             let offset_y = color_bounds.top.max(0) as usize;
 873
 874            //                             for y in 0..color_height as usize {
 875            //                                 for x in 0..color_width as usize {
 876            //                                     let bitmap_x = offset_x + x;
 877            //                                     let bitmap_y = offset_y + y;
 878
 879            //                                     if bitmap_x < bitmap_size.width.0 as usize
 880            //                                         && bitmap_y < bitmap_size.height.0 as usize
 881            //                                     {
 882            //                                         let alpha_idx =
 883            //                                             (y * color_width as usize + x) * 3;
 884            //                                         let bitmap_idx = (bitmap_y
 885            //                                             * bitmap_size.width.0 as usize
 886            //                                             + bitmap_x)
 887            //                                             * 4;
 888
 889            //                                         if alpha_idx + 2 < alpha_data.len()
 890            //                                             && bitmap_idx + 3 < bitmap_data.len()
 891            //                                         {
 892            //                                             let alpha_value = (alpha_data[alpha_idx]
 893            //                                                 as u32
 894            //                                                 + alpha_data[alpha_idx + 1] as u32
 895            //                                                 + alpha_data[alpha_idx + 2] as u32)
 896            //                                                 / 3;
 897            //                                             let final_alpha =
 898            //                                                 ((alpha_value * a as u32) / 255) as u8;
 899
 900            //                                             if final_alpha > 0 {
 901            //                                                 let existing_r =
 902            //                                                     bitmap_data[bitmap_idx];
 903            //                                                 let existing_g =
 904            //                                                     bitmap_data[bitmap_idx + 1];
 905            //                                                 let existing_b =
 906            //                                                     bitmap_data[bitmap_idx + 2];
 907            //                                                 let existing_a =
 908            //                                                     bitmap_data[bitmap_idx + 3];
 909
 910            //                                                 let src_alpha =
 911            //                                                     final_alpha as f32 / 255.0;
 912            //                                                 let dst_alpha =
 913            //                                                     existing_a as f32 / 255.0;
 914            //                                                 let out_alpha = src_alpha
 915            //                                                     + dst_alpha * (1.0 - src_alpha);
 916
 917            //                                                 if out_alpha > 0.0 {
 918            //                                                     bitmap_data[bitmap_idx] =
 919            //                                                         ((r as f32 * src_alpha
 920            //                                                             + existing_r as f32
 921            //                                                                 * dst_alpha
 922            //                                                                 * (1.0 - src_alpha))
 923            //                                                             / out_alpha)
 924            //                                                             as u8;
 925            //                                                     bitmap_data[bitmap_idx + 1] =
 926            //                                                         ((g as f32 * src_alpha
 927            //                                                             + existing_g as f32
 928            //                                                                 * dst_alpha
 929            //                                                                 * (1.0 - src_alpha))
 930            //                                                             / out_alpha)
 931            //                                                             as u8;
 932            //                                                     bitmap_data[bitmap_idx + 2] =
 933            //                                                         ((b as f32 * src_alpha
 934            //                                                             + existing_b as f32
 935            //                                                                 * dst_alpha
 936            //                                                                 * (1.0 - src_alpha))
 937            //                                                             / out_alpha)
 938            //                                                             as u8;
 939            //                                                     bitmap_data[bitmap_idx + 3] =
 940            //                                                         (out_alpha * 255.0) as u8;
 941            //                                                 }
 942            //                                             }
 943            //                                         }
 944            //                                     }
 945            //                                 }
 946            //                             }
 947            //                         }
 948            //                     }
 949            //                 }
 950            //             }
 951            //         }
 952
 953            //         if !unsafe { color_enumerator.MoveNext() }?.as_bool() {
 954            //             break;
 955            //         }
 956            //     }
 957            // } else {
 958            // }
 959            let monochrome_data = Self::rasterize_monochrome(
 960                &glyph_analysis,
 961                bitmap_size,
 962                size(texture_width, texture_height),
 963                &texture_bounds,
 964            )?;
 965            bitmap_data = monochrome_data
 966                .into_iter()
 967                .flat_map(|e| [e, e, e, 255])
 968                .collect::<Vec<u8>>();
 969        } else {
 970            bitmap_data = Self::rasterize_monochrome(
 971                &glyph_analysis,
 972                bitmap_size,
 973                size(texture_width, texture_height),
 974                &texture_bounds,
 975            )?;
 976        }
 977
 978        Ok((bitmap_size, bitmap_data))
 979    }
 980
 981    fn rasterize_monochrome(
 982        glyph_analysis: &IDWriteGlyphRunAnalysis,
 983        bitmap_size: Size<DevicePixels>,
 984        texture_size: Size<u32>,
 985        texture_bounds: &RECT,
 986    ) -> Result<Vec<u8>> {
 987        let mut bitmap_data =
 988            vec![0u8; bitmap_size.width.0 as usize * bitmap_size.height.0 as usize];
 989
 990        let mut alpha_data = vec![0u8; (texture_size.width * texture_size.height * 3) as usize];
 991        unsafe {
 992            glyph_analysis.CreateAlphaTexture(
 993                DWRITE_TEXTURE_CLEARTYPE_3x1,
 994                texture_bounds,
 995                &mut alpha_data,
 996            )?;
 997        }
 998
 999        // Convert ClearType RGB data to grayscale and place in bitmap
1000        let offset_x = texture_bounds.left.max(0) as usize;
1001        let offset_y = texture_bounds.top.max(0) as usize;
1002
1003        for y in 0..texture_size.height as usize {
1004            for x in 0..texture_size.width as usize {
1005                let bitmap_x = offset_x + x;
1006                let bitmap_y = offset_y + y;
1007
1008                if bitmap_x < bitmap_size.width.0 as usize
1009                    && bitmap_y < bitmap_size.height.0 as usize
1010                {
1011                    let texture_idx = (y * texture_size.width as usize + x) * 3;
1012                    let bitmap_idx = bitmap_y * bitmap_size.width.0 as usize + bitmap_x;
1013
1014                    if texture_idx + 2 < alpha_data.len() && bitmap_idx < bitmap_data.len() {
1015                        let avg = (alpha_data[texture_idx] as u32
1016                            + alpha_data[texture_idx + 1] as u32
1017                            + alpha_data[texture_idx + 2] as u32)
1018                            / 3;
1019                        bitmap_data[bitmap_idx] = avg as u8;
1020                    }
1021                }
1022            }
1023        }
1024
1025        Ok(bitmap_data)
1026    }
1027
1028    fn get_typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
1029        unsafe {
1030            let font = &self.fonts[font_id.0].font_face;
1031            let glyph_indices = [glyph_id.0 as u16];
1032            let mut metrics = [DWRITE_GLYPH_METRICS::default()];
1033            font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
1034
1035            let metrics = &metrics[0];
1036            let advance_width = metrics.advanceWidth as i32;
1037            let advance_height = metrics.advanceHeight as i32;
1038            let left_side_bearing = metrics.leftSideBearing;
1039            let right_side_bearing = metrics.rightSideBearing;
1040            let top_side_bearing = metrics.topSideBearing;
1041            let bottom_side_bearing = metrics.bottomSideBearing;
1042            let vertical_origin_y = metrics.verticalOriginY;
1043
1044            let y_offset = vertical_origin_y + bottom_side_bearing - advance_height;
1045            let width = advance_width - (left_side_bearing + right_side_bearing);
1046            let height = advance_height - (top_side_bearing + bottom_side_bearing);
1047
1048            Ok(Bounds {
1049                origin: Point {
1050                    x: left_side_bearing as f32,
1051                    y: y_offset as f32,
1052                },
1053                size: Size {
1054                    width: width as f32,
1055                    height: height as f32,
1056                },
1057            })
1058        }
1059    }
1060
1061    fn get_advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1062        unsafe {
1063            let font = &self.fonts[font_id.0].font_face;
1064            let glyph_indices = [glyph_id.0 as u16];
1065            let mut metrics = [DWRITE_GLYPH_METRICS::default()];
1066            font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
1067
1068            let metrics = &metrics[0];
1069
1070            Ok(Size {
1071                width: metrics.advanceWidth as f32,
1072                height: 0.0,
1073            })
1074        }
1075    }
1076
1077    fn all_font_names(&self) -> Vec<String> {
1078        let mut result =
1079            get_font_names_from_collection(&self.system_font_collection, &self.components.locale);
1080        result.extend(get_font_names_from_collection(
1081            &self.custom_font_collection,
1082            &self.components.locale,
1083        ));
1084        result
1085    }
1086}
1087
1088impl Drop for DirectWriteState {
1089    fn drop(&mut self) {
1090        unsafe {
1091            let _ = self
1092                .components
1093                .factory
1094                .UnregisterFontFileLoader(&self.components.in_memory_loader);
1095        }
1096    }
1097}
1098
1099struct TextRendererWrapper(pub IDWriteTextRenderer);
1100
1101impl TextRendererWrapper {
1102    pub fn new(locale_str: &str) -> Self {
1103        let inner = TextRenderer::new(locale_str);
1104        TextRendererWrapper(inner.into())
1105    }
1106}
1107
1108#[implement(IDWriteTextRenderer)]
1109struct TextRenderer {
1110    locale: String,
1111}
1112
1113impl TextRenderer {
1114    pub fn new(locale_str: &str) -> Self {
1115        TextRenderer {
1116            locale: locale_str.to_owned(),
1117        }
1118    }
1119}
1120
1121struct RendererContext<'t, 'a, 'b> {
1122    text_system: &'t mut DirectWriteState,
1123    index_converter: StringIndexConverter<'a>,
1124    runs: &'b mut Vec<ShapedRun>,
1125    width: f32,
1126}
1127
1128#[derive(Debug)]
1129struct ClusterAnalyzer<'t> {
1130    utf16_idx: usize,
1131    glyph_idx: usize,
1132    glyph_count: usize,
1133    cluster_map: &'t [u16],
1134}
1135
1136impl<'t> ClusterAnalyzer<'t> {
1137    pub fn new(cluster_map: &'t [u16], glyph_count: usize) -> Self {
1138        ClusterAnalyzer {
1139            utf16_idx: 0,
1140            glyph_idx: 0,
1141            glyph_count,
1142            cluster_map,
1143        }
1144    }
1145}
1146
1147impl Iterator for ClusterAnalyzer<'_> {
1148    type Item = (usize, usize);
1149
1150    fn next(&mut self) -> Option<(usize, usize)> {
1151        if self.utf16_idx >= self.cluster_map.len() {
1152            return None; // No more clusters
1153        }
1154        let start_utf16_idx = self.utf16_idx;
1155        let current_glyph = self.cluster_map[start_utf16_idx] as usize;
1156
1157        // Find the end of current cluster (where glyph index changes)
1158        let mut end_utf16_idx = start_utf16_idx + 1;
1159        while end_utf16_idx < self.cluster_map.len()
1160            && self.cluster_map[end_utf16_idx] as usize == current_glyph
1161        {
1162            end_utf16_idx += 1;
1163        }
1164
1165        let utf16_len = end_utf16_idx - start_utf16_idx;
1166
1167        // Calculate glyph count for this cluster
1168        let next_glyph = if end_utf16_idx < self.cluster_map.len() {
1169            self.cluster_map[end_utf16_idx] as usize
1170        } else {
1171            self.glyph_count
1172        };
1173
1174        let glyph_count = next_glyph - current_glyph;
1175
1176        // Update state for next call
1177        self.utf16_idx = end_utf16_idx;
1178        self.glyph_idx = next_glyph;
1179
1180        Some((utf16_len, glyph_count))
1181    }
1182}
1183
1184#[allow(non_snake_case)]
1185impl IDWritePixelSnapping_Impl for TextRenderer_Impl {
1186    fn IsPixelSnappingDisabled(
1187        &self,
1188        _clientdrawingcontext: *const ::core::ffi::c_void,
1189    ) -> windows::core::Result<BOOL> {
1190        Ok(BOOL(0))
1191    }
1192
1193    fn GetCurrentTransform(
1194        &self,
1195        _clientdrawingcontext: *const ::core::ffi::c_void,
1196        transform: *mut DWRITE_MATRIX,
1197    ) -> windows::core::Result<()> {
1198        unsafe {
1199            *transform = DWRITE_MATRIX {
1200                m11: 1.0,
1201                m12: 0.0,
1202                m21: 0.0,
1203                m22: 1.0,
1204                dx: 0.0,
1205                dy: 0.0,
1206            };
1207        }
1208        Ok(())
1209    }
1210
1211    fn GetPixelsPerDip(
1212        &self,
1213        _clientdrawingcontext: *const ::core::ffi::c_void,
1214    ) -> windows::core::Result<f32> {
1215        Ok(1.0)
1216    }
1217}
1218
1219#[allow(non_snake_case)]
1220impl IDWriteTextRenderer_Impl for TextRenderer_Impl {
1221    fn DrawGlyphRun(
1222        &self,
1223        clientdrawingcontext: *const ::core::ffi::c_void,
1224        _baselineoriginx: f32,
1225        _baselineoriginy: f32,
1226        _measuringmode: DWRITE_MEASURING_MODE,
1227        glyphrun: *const DWRITE_GLYPH_RUN,
1228        glyphrundescription: *const DWRITE_GLYPH_RUN_DESCRIPTION,
1229        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1230    ) -> windows::core::Result<()> {
1231        let glyphrun = unsafe { &*glyphrun };
1232        let glyph_count = glyphrun.glyphCount as usize;
1233        if glyph_count == 0 || glyphrun.fontFace.is_none() {
1234            return Ok(());
1235        }
1236        let desc = unsafe { &*glyphrundescription };
1237        let context = unsafe {
1238            &mut *(clientdrawingcontext as *const RendererContext as *mut RendererContext)
1239        };
1240        let font_face = glyphrun.fontFace.as_ref().unwrap();
1241        // This `cast()` action here should never fail since we are running on Win10+, and
1242        // `IDWriteFontFace3` requires Win10
1243        let font_face = &font_face.cast::<IDWriteFontFace3>().unwrap();
1244        let Some((font_identifier, font_struct, color_font)) =
1245            get_font_identifier_and_font_struct(font_face, &self.locale)
1246        else {
1247            return Ok(());
1248        };
1249
1250        let font_id = if let Some(id) = context
1251            .text_system
1252            .font_id_by_identifier
1253            .get(&font_identifier)
1254        {
1255            *id
1256        } else {
1257            context.text_system.select_font(&font_struct)
1258        };
1259
1260        let glyph_ids = unsafe { std::slice::from_raw_parts(glyphrun.glyphIndices, glyph_count) };
1261        let glyph_advances =
1262            unsafe { std::slice::from_raw_parts(glyphrun.glyphAdvances, glyph_count) };
1263        let glyph_offsets =
1264            unsafe { std::slice::from_raw_parts(glyphrun.glyphOffsets, glyph_count) };
1265        let cluster_map =
1266            unsafe { std::slice::from_raw_parts(desc.clusterMap, desc.stringLength as usize) };
1267
1268        let mut cluster_analyzer = ClusterAnalyzer::new(cluster_map, glyph_count);
1269        let mut utf16_idx = desc.textPosition as usize;
1270        let mut glyph_idx = 0;
1271        let mut glyphs = Vec::with_capacity(glyph_count);
1272        for (cluster_utf16_len, cluster_glyph_count) in cluster_analyzer {
1273            context.index_converter.advance_to_utf16_ix(utf16_idx);
1274            utf16_idx += cluster_utf16_len;
1275            for (cluster_glyph_idx, glyph_id) in glyph_ids
1276                [glyph_idx..(glyph_idx + cluster_glyph_count)]
1277                .iter()
1278                .enumerate()
1279            {
1280                let id = GlyphId(*glyph_id as u32);
1281                let is_emoji = color_font
1282                    && is_color_glyph(font_face, id, &context.text_system.components.factory);
1283                let this_glyph_idx = glyph_idx + cluster_glyph_idx;
1284                glyphs.push(ShapedGlyph {
1285                    id,
1286                    position: point(
1287                        px(context.width + glyph_offsets[this_glyph_idx].advanceOffset),
1288                        px(0.0),
1289                    ),
1290                    index: context.index_converter.utf8_ix,
1291                    is_emoji,
1292                });
1293                context.width += glyph_advances[this_glyph_idx];
1294            }
1295            glyph_idx += cluster_glyph_count;
1296        }
1297        context.runs.push(ShapedRun { font_id, glyphs });
1298        Ok(())
1299    }
1300
1301    fn DrawUnderline(
1302        &self,
1303        _clientdrawingcontext: *const ::core::ffi::c_void,
1304        _baselineoriginx: f32,
1305        _baselineoriginy: f32,
1306        _underline: *const DWRITE_UNDERLINE,
1307        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1308    ) -> windows::core::Result<()> {
1309        Err(windows::core::Error::new(
1310            E_NOTIMPL,
1311            "DrawUnderline unimplemented",
1312        ))
1313    }
1314
1315    fn DrawStrikethrough(
1316        &self,
1317        _clientdrawingcontext: *const ::core::ffi::c_void,
1318        _baselineoriginx: f32,
1319        _baselineoriginy: f32,
1320        _strikethrough: *const DWRITE_STRIKETHROUGH,
1321        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1322    ) -> windows::core::Result<()> {
1323        Err(windows::core::Error::new(
1324            E_NOTIMPL,
1325            "DrawStrikethrough unimplemented",
1326        ))
1327    }
1328
1329    fn DrawInlineObject(
1330        &self,
1331        _clientdrawingcontext: *const ::core::ffi::c_void,
1332        _originx: f32,
1333        _originy: f32,
1334        _inlineobject: windows::core::Ref<IDWriteInlineObject>,
1335        _issideways: BOOL,
1336        _isrighttoleft: BOOL,
1337        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1338    ) -> windows::core::Result<()> {
1339        Err(windows::core::Error::new(
1340            E_NOTIMPL,
1341            "DrawInlineObject unimplemented",
1342        ))
1343    }
1344}
1345
1346struct StringIndexConverter<'a> {
1347    text: &'a str,
1348    utf8_ix: usize,
1349    utf16_ix: usize,
1350}
1351
1352impl<'a> StringIndexConverter<'a> {
1353    fn new(text: &'a str) -> Self {
1354        Self {
1355            text,
1356            utf8_ix: 0,
1357            utf16_ix: 0,
1358        }
1359    }
1360
1361    #[allow(dead_code)]
1362    fn advance_to_utf8_ix(&mut self, utf8_target: usize) {
1363        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1364            if self.utf8_ix + ix >= utf8_target {
1365                self.utf8_ix += ix;
1366                return;
1367            }
1368            self.utf16_ix += c.len_utf16();
1369        }
1370        self.utf8_ix = self.text.len();
1371    }
1372
1373    fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
1374        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1375            if self.utf16_ix >= utf16_target {
1376                self.utf8_ix += ix;
1377                return;
1378            }
1379            self.utf16_ix += c.len_utf16();
1380        }
1381        self.utf8_ix = self.text.len();
1382    }
1383}
1384
1385impl Into<DWRITE_FONT_STYLE> for FontStyle {
1386    fn into(self) -> DWRITE_FONT_STYLE {
1387        match self {
1388            FontStyle::Normal => DWRITE_FONT_STYLE_NORMAL,
1389            FontStyle::Italic => DWRITE_FONT_STYLE_ITALIC,
1390            FontStyle::Oblique => DWRITE_FONT_STYLE_OBLIQUE,
1391        }
1392    }
1393}
1394
1395impl From<DWRITE_FONT_STYLE> for FontStyle {
1396    fn from(value: DWRITE_FONT_STYLE) -> Self {
1397        match value.0 {
1398            0 => FontStyle::Normal,
1399            1 => FontStyle::Italic,
1400            2 => FontStyle::Oblique,
1401            _ => unreachable!(),
1402        }
1403    }
1404}
1405
1406impl Into<DWRITE_FONT_WEIGHT> for FontWeight {
1407    fn into(self) -> DWRITE_FONT_WEIGHT {
1408        DWRITE_FONT_WEIGHT(self.0 as i32)
1409    }
1410}
1411
1412impl From<DWRITE_FONT_WEIGHT> for FontWeight {
1413    fn from(value: DWRITE_FONT_WEIGHT) -> Self {
1414        FontWeight(value.0 as f32)
1415    }
1416}
1417
1418fn get_font_names_from_collection(
1419    collection: &IDWriteFontCollection1,
1420    locale: &str,
1421) -> Vec<String> {
1422    unsafe {
1423        let mut result = Vec::new();
1424        let family_count = collection.GetFontFamilyCount();
1425        for index in 0..family_count {
1426            let Some(font_family) = collection.GetFontFamily(index).log_err() else {
1427                continue;
1428            };
1429            let Some(localized_family_name) = font_family.GetFamilyNames().log_err() else {
1430                continue;
1431            };
1432            let Some(family_name) = get_name(localized_family_name, locale).log_err() else {
1433                continue;
1434            };
1435            result.push(family_name);
1436        }
1437
1438        result
1439    }
1440}
1441
1442fn get_font_identifier_and_font_struct(
1443    font_face: &IDWriteFontFace3,
1444    locale: &str,
1445) -> Option<(FontIdentifier, Font, bool)> {
1446    let postscript_name = get_postscript_name(font_face, locale).log_err()?;
1447    let localized_family_name = unsafe { font_face.GetFamilyNames().log_err() }?;
1448    let family_name = get_name(localized_family_name, locale).log_err()?;
1449    let weight = unsafe { font_face.GetWeight() };
1450    let style = unsafe { font_face.GetStyle() };
1451    let identifier = FontIdentifier {
1452        postscript_name,
1453        weight: weight.0,
1454        style: style.0,
1455    };
1456    let font_struct = Font {
1457        family: family_name.into(),
1458        features: FontFeatures::default(),
1459        weight: weight.into(),
1460        style: style.into(),
1461        fallbacks: None,
1462    };
1463    let is_emoji = unsafe { font_face.IsColorFont().as_bool() };
1464    Some((identifier, font_struct, is_emoji))
1465}
1466
1467#[inline]
1468fn get_font_identifier(font_face: &IDWriteFontFace3, locale: &str) -> Option<FontIdentifier> {
1469    let weight = unsafe { font_face.GetWeight().0 };
1470    let style = unsafe { font_face.GetStyle().0 };
1471    get_postscript_name(font_face, locale)
1472        .log_err()
1473        .map(|postscript_name| FontIdentifier {
1474            postscript_name,
1475            weight,
1476            style,
1477        })
1478}
1479
1480#[inline]
1481fn get_postscript_name(font_face: &IDWriteFontFace3, locale: &str) -> Result<String> {
1482    let mut info = None;
1483    let mut exists = BOOL(0);
1484    unsafe {
1485        font_face.GetInformationalStrings(
1486            DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_NAME,
1487            &mut info,
1488            &mut exists,
1489        )?
1490    };
1491    if !exists.as_bool() || info.is_none() {
1492        anyhow::bail!("No postscript name found for font face");
1493    }
1494
1495    get_name(info.unwrap(), locale)
1496}
1497
1498// https://learn.microsoft.com/en-us/windows/win32/api/dwrite/ne-dwrite-dwrite_font_feature_tag
1499fn apply_font_features(
1500    direct_write_features: &IDWriteTypography,
1501    features: &FontFeatures,
1502) -> Result<()> {
1503    let tag_values = features.tag_value_list();
1504    if tag_values.is_empty() {
1505        return Ok(());
1506    }
1507
1508    // All of these features are enabled by default by DirectWrite.
1509    // If you want to (and can) peek into the source of DirectWrite
1510    let mut feature_liga = make_direct_write_feature("liga", 1);
1511    let mut feature_clig = make_direct_write_feature("clig", 1);
1512    let mut feature_calt = make_direct_write_feature("calt", 1);
1513
1514    for (tag, value) in tag_values {
1515        if tag.as_str() == "liga" && *value == 0 {
1516            feature_liga.parameter = 0;
1517            continue;
1518        }
1519        if tag.as_str() == "clig" && *value == 0 {
1520            feature_clig.parameter = 0;
1521            continue;
1522        }
1523        if tag.as_str() == "calt" && *value == 0 {
1524            feature_calt.parameter = 0;
1525            continue;
1526        }
1527
1528        unsafe {
1529            direct_write_features.AddFontFeature(make_direct_write_feature(&tag, *value))?;
1530        }
1531    }
1532    unsafe {
1533        direct_write_features.AddFontFeature(feature_liga)?;
1534        direct_write_features.AddFontFeature(feature_clig)?;
1535        direct_write_features.AddFontFeature(feature_calt)?;
1536    }
1537
1538    Ok(())
1539}
1540
1541#[inline]
1542const fn make_direct_write_feature(feature_name: &str, parameter: u32) -> DWRITE_FONT_FEATURE {
1543    let tag = make_direct_write_tag(feature_name);
1544    DWRITE_FONT_FEATURE {
1545        nameTag: tag,
1546        parameter,
1547    }
1548}
1549
1550#[inline]
1551const fn make_open_type_tag(tag_name: &str) -> u32 {
1552    let bytes = tag_name.as_bytes();
1553    debug_assert!(bytes.len() == 4);
1554    u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
1555}
1556
1557#[inline]
1558const fn make_direct_write_tag(tag_name: &str) -> DWRITE_FONT_FEATURE_TAG {
1559    DWRITE_FONT_FEATURE_TAG(make_open_type_tag(tag_name))
1560}
1561
1562#[inline]
1563fn get_name(string: IDWriteLocalizedStrings, locale: &str) -> Result<String> {
1564    let mut locale_name_index = 0u32;
1565    let mut exists = BOOL(0);
1566    unsafe {
1567        string.FindLocaleName(
1568            &HSTRING::from(locale),
1569            &mut locale_name_index,
1570            &mut exists as _,
1571        )?
1572    };
1573    if !exists.as_bool() {
1574        unsafe {
1575            string.FindLocaleName(
1576                DEFAULT_LOCALE_NAME,
1577                &mut locale_name_index as _,
1578                &mut exists as _,
1579            )?
1580        };
1581        anyhow::ensure!(exists.as_bool(), "No localised string for {locale}");
1582    }
1583
1584    let name_length = unsafe { string.GetStringLength(locale_name_index) }? as usize;
1585    let mut name_vec = vec![0u16; name_length + 1];
1586    unsafe {
1587        string.GetString(locale_name_index, &mut name_vec)?;
1588    }
1589
1590    Ok(String::from_utf16_lossy(&name_vec[..name_length]))
1591}
1592
1593#[inline]
1594fn translate_color(color: &DWRITE_COLOR_F) -> [f32; 4] {
1595    [color.r, color.g, color.b, color.a]
1596}
1597
1598fn get_system_ui_font_name() -> SharedString {
1599    unsafe {
1600        let mut info: LOGFONTW = std::mem::zeroed();
1601        let font_family = if SystemParametersInfoW(
1602            SPI_GETICONTITLELOGFONT,
1603            std::mem::size_of::<LOGFONTW>() as u32,
1604            Some(&mut info as *mut _ as _),
1605            SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
1606        )
1607        .log_err()
1608        .is_none()
1609        {
1610            // https://learn.microsoft.com/en-us/windows/win32/uxguide/vis-fonts
1611            // Segoe UI is the Windows font intended for user interface text strings.
1612            "Segoe UI".into()
1613        } else {
1614            let font_name = String::from_utf16_lossy(&info.lfFaceName);
1615            font_name.trim_matches(char::from(0)).to_owned().into()
1616        };
1617        log::info!("Use {} as UI font.", font_family);
1618        font_family
1619    }
1620}
1621
1622// One would think that with newer DirectWrite method: IDWriteFontFace4::GetGlyphImageFormats
1623// but that doesn't seem to work for some glyphs, say โค
1624fn is_color_glyph(
1625    font_face: &IDWriteFontFace3,
1626    glyph_id: GlyphId,
1627    factory: &IDWriteFactory5,
1628) -> bool {
1629    let glyph_run = DWRITE_GLYPH_RUN {
1630        fontFace: unsafe { std::mem::transmute_copy(font_face) },
1631        fontEmSize: 14.0,
1632        glyphCount: 1,
1633        glyphIndices: &(glyph_id.0 as u16),
1634        glyphAdvances: &0.0,
1635        glyphOffsets: &DWRITE_GLYPH_OFFSET {
1636            advanceOffset: 0.0,
1637            ascenderOffset: 0.0,
1638        },
1639        isSideways: BOOL(0),
1640        bidiLevel: 0,
1641    };
1642    unsafe {
1643        factory.TranslateColorGlyphRun(
1644            Vector2::default(),
1645            &glyph_run as _,
1646            None,
1647            DWRITE_GLYPH_IMAGE_FORMATS_COLR
1648                | DWRITE_GLYPH_IMAGE_FORMATS_SVG
1649                | DWRITE_GLYPH_IMAGE_FORMATS_PNG
1650                | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
1651                | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8,
1652            DWRITE_MEASURING_MODE_NATURAL,
1653            None,
1654            0,
1655        )
1656    }
1657    .is_ok()
1658}
1659
1660const DEFAULT_LOCALE_NAME: PCWSTR = windows::core::w!("en-US");
1661
1662#[cfg(test)]
1663mod tests {
1664    use crate::platform::windows::direct_write::ClusterAnalyzer;
1665
1666    #[test]
1667    fn test_cluster_map() {
1668        let cluster_map = [0];
1669        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 1);
1670        let next = analyzer.next();
1671        assert_eq!(next, Some((1, 1)));
1672        let next = analyzer.next();
1673        assert_eq!(next, None);
1674
1675        let cluster_map = [0, 1, 2];
1676        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 3);
1677        let next = analyzer.next();
1678        assert_eq!(next, Some((1, 1)));
1679        let next = analyzer.next();
1680        assert_eq!(next, Some((1, 1)));
1681        let next = analyzer.next();
1682        assert_eq!(next, Some((1, 1)));
1683        let next = analyzer.next();
1684        assert_eq!(next, None);
1685        // ๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ๐Ÿ‘ฉโ€๐Ÿ’ป
1686        let cluster_map = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4];
1687        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 5);
1688        let next = analyzer.next();
1689        assert_eq!(next, Some((11, 4)));
1690        let next = analyzer.next();
1691        assert_eq!(next, Some((5, 1)));
1692        let next = analyzer.next();
1693        assert_eq!(next, None);
1694        // ๐Ÿ‘ฉโ€๐Ÿ’ป
1695        let cluster_map = [0, 0, 0, 0, 0];
1696        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 1);
1697        let next = analyzer.next();
1698        assert_eq!(next, Some((5, 1)));
1699        let next = analyzer.next();
1700        assert_eq!(next, None);
1701    }
1702}