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            bitmap_data =
 809                vec![0u8; bitmap_size.width.0 as usize * bitmap_size.height.0 as usize * 4];
 810
 811            let mut rgba_data = vec![0u8; (texture_width * texture_height * 4) as usize];
 812            unsafe {
 813                glyph_analysis.CreateAlphaTexture(texture_type, &texture_bounds, &mut rgba_data)?;
 814            }
 815
 816            // Copy texture data into bitmap at correct position
 817            let offset_x = texture_bounds.left.max(0) as usize;
 818            let offset_y = texture_bounds.top.max(0) as usize;
 819            for y in 0..texture_height as usize {
 820                for x in 0..texture_width as usize {
 821                    let bitmap_x = offset_x + x;
 822                    let bitmap_y = offset_y + y;
 823
 824                    if bitmap_x < bitmap_size.width.0 as usize
 825                        && bitmap_y < bitmap_size.height.0 as usize
 826                    {
 827                        let texture_idx = (y * texture_width as usize + x) * 4;
 828                        let bitmap_idx = (bitmap_y * bitmap_size.width.0 as usize + bitmap_x) * 4;
 829
 830                        if texture_idx + 3 < rgba_data.len() && bitmap_idx + 3 < bitmap_data.len() {
 831                            bitmap_data[bitmap_idx..bitmap_idx + 4]
 832                                .copy_from_slice(&rgba_data[texture_idx..texture_idx + 4]);
 833                        }
 834                    }
 835                }
 836            }
 837        } else {
 838            bitmap_data = vec![0u8; bitmap_size.width.0 as usize * bitmap_size.height.0 as usize];
 839
 840            let mut alpha_data = vec![0u8; (texture_width * texture_height * 3) as usize];
 841            unsafe {
 842                glyph_analysis.CreateAlphaTexture(
 843                    texture_type,
 844                    &texture_bounds,
 845                    &mut alpha_data,
 846                )?;
 847            }
 848
 849            // Convert ClearType RGB data to grayscale and place in bitmap
 850            let offset_x = texture_bounds.left.max(0) as usize;
 851            let offset_y = texture_bounds.top.max(0) as usize;
 852
 853            for y in 0..texture_height as usize {
 854                for x in 0..texture_width as usize {
 855                    let bitmap_x = offset_x + x;
 856                    let bitmap_y = offset_y + y;
 857
 858                    if bitmap_x < bitmap_size.width.0 as usize
 859                        && bitmap_y < bitmap_size.height.0 as usize
 860                    {
 861                        let texture_idx = (y * texture_width as usize + x) * 3;
 862                        let bitmap_idx = bitmap_y * bitmap_size.width.0 as usize + bitmap_x;
 863
 864                        if texture_idx + 2 < alpha_data.len() && bitmap_idx < bitmap_data.len() {
 865                            let avg = (alpha_data[texture_idx] as u32
 866                                + alpha_data[texture_idx + 1] as u32
 867                                + alpha_data[texture_idx + 2] as u32)
 868                                / 3;
 869                            bitmap_data[bitmap_idx] = avg as u8;
 870                        }
 871                    }
 872                }
 873            }
 874        }
 875
 876        Ok((bitmap_size, bitmap_data))
 877    }
 878
 879    fn get_typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
 880        unsafe {
 881            let font = &self.fonts[font_id.0].font_face;
 882            let glyph_indices = [glyph_id.0 as u16];
 883            let mut metrics = [DWRITE_GLYPH_METRICS::default()];
 884            font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
 885
 886            let metrics = &metrics[0];
 887            let advance_width = metrics.advanceWidth as i32;
 888            let advance_height = metrics.advanceHeight as i32;
 889            let left_side_bearing = metrics.leftSideBearing;
 890            let right_side_bearing = metrics.rightSideBearing;
 891            let top_side_bearing = metrics.topSideBearing;
 892            let bottom_side_bearing = metrics.bottomSideBearing;
 893            let vertical_origin_y = metrics.verticalOriginY;
 894
 895            let y_offset = vertical_origin_y + bottom_side_bearing - advance_height;
 896            let width = advance_width - (left_side_bearing + right_side_bearing);
 897            let height = advance_height - (top_side_bearing + bottom_side_bearing);
 898
 899            Ok(Bounds {
 900                origin: Point {
 901                    x: left_side_bearing as f32,
 902                    y: y_offset as f32,
 903                },
 904                size: Size {
 905                    width: width as f32,
 906                    height: height as f32,
 907                },
 908            })
 909        }
 910    }
 911
 912    fn get_advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
 913        unsafe {
 914            let font = &self.fonts[font_id.0].font_face;
 915            let glyph_indices = [glyph_id.0 as u16];
 916            let mut metrics = [DWRITE_GLYPH_METRICS::default()];
 917            font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
 918
 919            let metrics = &metrics[0];
 920
 921            Ok(Size {
 922                width: metrics.advanceWidth as f32,
 923                height: 0.0,
 924            })
 925        }
 926    }
 927
 928    fn all_font_names(&self) -> Vec<String> {
 929        let mut result =
 930            get_font_names_from_collection(&self.system_font_collection, &self.components.locale);
 931        result.extend(get_font_names_from_collection(
 932            &self.custom_font_collection,
 933            &self.components.locale,
 934        ));
 935        result
 936    }
 937}
 938
 939impl Drop for DirectWriteState {
 940    fn drop(&mut self) {
 941        unsafe {
 942            let _ = self
 943                .components
 944                .factory
 945                .UnregisterFontFileLoader(&self.components.in_memory_loader);
 946        }
 947    }
 948}
 949
 950struct TextRendererWrapper(pub IDWriteTextRenderer);
 951
 952impl TextRendererWrapper {
 953    pub fn new(locale_str: &str) -> Self {
 954        let inner = TextRenderer::new(locale_str);
 955        TextRendererWrapper(inner.into())
 956    }
 957}
 958
 959#[implement(IDWriteTextRenderer)]
 960struct TextRenderer {
 961    locale: String,
 962}
 963
 964impl TextRenderer {
 965    pub fn new(locale_str: &str) -> Self {
 966        TextRenderer {
 967            locale: locale_str.to_owned(),
 968        }
 969    }
 970}
 971
 972struct RendererContext<'t, 'a, 'b> {
 973    text_system: &'t mut DirectWriteState,
 974    index_converter: StringIndexConverter<'a>,
 975    runs: &'b mut Vec<ShapedRun>,
 976    width: f32,
 977}
 978
 979#[derive(Debug)]
 980struct ClusterAnalyzer<'t> {
 981    utf16_idx: usize,
 982    glyph_idx: usize,
 983    glyph_count: usize,
 984    cluster_map: &'t [u16],
 985}
 986
 987impl<'t> ClusterAnalyzer<'t> {
 988    pub fn new(cluster_map: &'t [u16], glyph_count: usize) -> Self {
 989        ClusterAnalyzer {
 990            utf16_idx: 0,
 991            glyph_idx: 0,
 992            glyph_count,
 993            cluster_map,
 994        }
 995    }
 996}
 997
 998impl Iterator for ClusterAnalyzer<'_> {
 999    type Item = (usize, usize);
1000
1001    fn next(&mut self) -> Option<(usize, usize)> {
1002        if self.utf16_idx >= self.cluster_map.len() {
1003            return None; // No more clusters
1004        }
1005        let start_utf16_idx = self.utf16_idx;
1006        let current_glyph = self.cluster_map[start_utf16_idx] as usize;
1007
1008        // Find the end of current cluster (where glyph index changes)
1009        let mut end_utf16_idx = start_utf16_idx + 1;
1010        while end_utf16_idx < self.cluster_map.len()
1011            && self.cluster_map[end_utf16_idx] as usize == current_glyph
1012        {
1013            end_utf16_idx += 1;
1014        }
1015
1016        let utf16_len = end_utf16_idx - start_utf16_idx;
1017
1018        // Calculate glyph count for this cluster
1019        let next_glyph = if end_utf16_idx < self.cluster_map.len() {
1020            self.cluster_map[end_utf16_idx] as usize
1021        } else {
1022            self.glyph_count
1023        };
1024
1025        let glyph_count = next_glyph - current_glyph;
1026
1027        // Update state for next call
1028        self.utf16_idx = end_utf16_idx;
1029        self.glyph_idx = next_glyph;
1030
1031        Some((utf16_len, glyph_count))
1032    }
1033}
1034
1035#[allow(non_snake_case)]
1036impl IDWritePixelSnapping_Impl for TextRenderer_Impl {
1037    fn IsPixelSnappingDisabled(
1038        &self,
1039        _clientdrawingcontext: *const ::core::ffi::c_void,
1040    ) -> windows::core::Result<BOOL> {
1041        Ok(BOOL(0))
1042    }
1043
1044    fn GetCurrentTransform(
1045        &self,
1046        _clientdrawingcontext: *const ::core::ffi::c_void,
1047        transform: *mut DWRITE_MATRIX,
1048    ) -> windows::core::Result<()> {
1049        unsafe {
1050            *transform = DWRITE_MATRIX {
1051                m11: 1.0,
1052                m12: 0.0,
1053                m21: 0.0,
1054                m22: 1.0,
1055                dx: 0.0,
1056                dy: 0.0,
1057            };
1058        }
1059        Ok(())
1060    }
1061
1062    fn GetPixelsPerDip(
1063        &self,
1064        _clientdrawingcontext: *const ::core::ffi::c_void,
1065    ) -> windows::core::Result<f32> {
1066        Ok(1.0)
1067    }
1068}
1069
1070#[allow(non_snake_case)]
1071impl IDWriteTextRenderer_Impl for TextRenderer_Impl {
1072    fn DrawGlyphRun(
1073        &self,
1074        clientdrawingcontext: *const ::core::ffi::c_void,
1075        _baselineoriginx: f32,
1076        _baselineoriginy: f32,
1077        _measuringmode: DWRITE_MEASURING_MODE,
1078        glyphrun: *const DWRITE_GLYPH_RUN,
1079        glyphrundescription: *const DWRITE_GLYPH_RUN_DESCRIPTION,
1080        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1081    ) -> windows::core::Result<()> {
1082        let glyphrun = unsafe { &*glyphrun };
1083        let glyph_count = glyphrun.glyphCount as usize;
1084        if glyph_count == 0 || glyphrun.fontFace.is_none() {
1085            return Ok(());
1086        }
1087        let desc = unsafe { &*glyphrundescription };
1088        let context = unsafe {
1089            &mut *(clientdrawingcontext as *const RendererContext as *mut RendererContext)
1090        };
1091        let font_face = glyphrun.fontFace.as_ref().unwrap();
1092        // This `cast()` action here should never fail since we are running on Win10+, and
1093        // `IDWriteFontFace3` requires Win10
1094        let font_face = &font_face.cast::<IDWriteFontFace3>().unwrap();
1095        let Some((font_identifier, font_struct, color_font)) =
1096            get_font_identifier_and_font_struct(font_face, &self.locale)
1097        else {
1098            return Ok(());
1099        };
1100
1101        let font_id = if let Some(id) = context
1102            .text_system
1103            .font_id_by_identifier
1104            .get(&font_identifier)
1105        {
1106            *id
1107        } else {
1108            context.text_system.select_font(&font_struct)
1109        };
1110
1111        let glyph_ids = unsafe { std::slice::from_raw_parts(glyphrun.glyphIndices, glyph_count) };
1112        let glyph_advances =
1113            unsafe { std::slice::from_raw_parts(glyphrun.glyphAdvances, glyph_count) };
1114        let glyph_offsets =
1115            unsafe { std::slice::from_raw_parts(glyphrun.glyphOffsets, glyph_count) };
1116        let cluster_map =
1117            unsafe { std::slice::from_raw_parts(desc.clusterMap, desc.stringLength as usize) };
1118
1119        let mut cluster_analyzer = ClusterAnalyzer::new(cluster_map, glyph_count);
1120        let mut utf16_idx = desc.textPosition as usize;
1121        let mut glyph_idx = 0;
1122        let mut glyphs = Vec::with_capacity(glyph_count);
1123        for (cluster_utf16_len, cluster_glyph_count) in cluster_analyzer {
1124            context.index_converter.advance_to_utf16_ix(utf16_idx);
1125            utf16_idx += cluster_utf16_len;
1126            for (cluster_glyph_idx, glyph_id) in glyph_ids
1127                [glyph_idx..(glyph_idx + cluster_glyph_count)]
1128                .iter()
1129                .enumerate()
1130            {
1131                let id = GlyphId(*glyph_id as u32);
1132                let is_emoji = color_font
1133                    && is_color_glyph(font_face, id, &context.text_system.components.factory);
1134                let this_glyph_idx = glyph_idx + cluster_glyph_idx;
1135                glyphs.push(ShapedGlyph {
1136                    id,
1137                    position: point(
1138                        px(context.width + glyph_offsets[this_glyph_idx].advanceOffset),
1139                        px(0.0),
1140                    ),
1141                    index: context.index_converter.utf8_ix,
1142                    is_emoji,
1143                });
1144                context.width += glyph_advances[this_glyph_idx];
1145            }
1146            glyph_idx += cluster_glyph_count;
1147        }
1148        context.runs.push(ShapedRun { font_id, glyphs });
1149        Ok(())
1150    }
1151
1152    fn DrawUnderline(
1153        &self,
1154        _clientdrawingcontext: *const ::core::ffi::c_void,
1155        _baselineoriginx: f32,
1156        _baselineoriginy: f32,
1157        _underline: *const DWRITE_UNDERLINE,
1158        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1159    ) -> windows::core::Result<()> {
1160        Err(windows::core::Error::new(
1161            E_NOTIMPL,
1162            "DrawUnderline unimplemented",
1163        ))
1164    }
1165
1166    fn DrawStrikethrough(
1167        &self,
1168        _clientdrawingcontext: *const ::core::ffi::c_void,
1169        _baselineoriginx: f32,
1170        _baselineoriginy: f32,
1171        _strikethrough: *const DWRITE_STRIKETHROUGH,
1172        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1173    ) -> windows::core::Result<()> {
1174        Err(windows::core::Error::new(
1175            E_NOTIMPL,
1176            "DrawStrikethrough unimplemented",
1177        ))
1178    }
1179
1180    fn DrawInlineObject(
1181        &self,
1182        _clientdrawingcontext: *const ::core::ffi::c_void,
1183        _originx: f32,
1184        _originy: f32,
1185        _inlineobject: windows::core::Ref<IDWriteInlineObject>,
1186        _issideways: BOOL,
1187        _isrighttoleft: BOOL,
1188        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1189    ) -> windows::core::Result<()> {
1190        Err(windows::core::Error::new(
1191            E_NOTIMPL,
1192            "DrawInlineObject unimplemented",
1193        ))
1194    }
1195}
1196
1197struct StringIndexConverter<'a> {
1198    text: &'a str,
1199    utf8_ix: usize,
1200    utf16_ix: usize,
1201}
1202
1203impl<'a> StringIndexConverter<'a> {
1204    fn new(text: &'a str) -> Self {
1205        Self {
1206            text,
1207            utf8_ix: 0,
1208            utf16_ix: 0,
1209        }
1210    }
1211
1212    #[allow(dead_code)]
1213    fn advance_to_utf8_ix(&mut self, utf8_target: usize) {
1214        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1215            if self.utf8_ix + ix >= utf8_target {
1216                self.utf8_ix += ix;
1217                return;
1218            }
1219            self.utf16_ix += c.len_utf16();
1220        }
1221        self.utf8_ix = self.text.len();
1222    }
1223
1224    fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
1225        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1226            if self.utf16_ix >= utf16_target {
1227                self.utf8_ix += ix;
1228                return;
1229            }
1230            self.utf16_ix += c.len_utf16();
1231        }
1232        self.utf8_ix = self.text.len();
1233    }
1234}
1235
1236impl Into<DWRITE_FONT_STYLE> for FontStyle {
1237    fn into(self) -> DWRITE_FONT_STYLE {
1238        match self {
1239            FontStyle::Normal => DWRITE_FONT_STYLE_NORMAL,
1240            FontStyle::Italic => DWRITE_FONT_STYLE_ITALIC,
1241            FontStyle::Oblique => DWRITE_FONT_STYLE_OBLIQUE,
1242        }
1243    }
1244}
1245
1246impl From<DWRITE_FONT_STYLE> for FontStyle {
1247    fn from(value: DWRITE_FONT_STYLE) -> Self {
1248        match value.0 {
1249            0 => FontStyle::Normal,
1250            1 => FontStyle::Italic,
1251            2 => FontStyle::Oblique,
1252            _ => unreachable!(),
1253        }
1254    }
1255}
1256
1257impl Into<DWRITE_FONT_WEIGHT> for FontWeight {
1258    fn into(self) -> DWRITE_FONT_WEIGHT {
1259        DWRITE_FONT_WEIGHT(self.0 as i32)
1260    }
1261}
1262
1263impl From<DWRITE_FONT_WEIGHT> for FontWeight {
1264    fn from(value: DWRITE_FONT_WEIGHT) -> Self {
1265        FontWeight(value.0 as f32)
1266    }
1267}
1268
1269fn get_font_names_from_collection(
1270    collection: &IDWriteFontCollection1,
1271    locale: &str,
1272) -> Vec<String> {
1273    unsafe {
1274        let mut result = Vec::new();
1275        let family_count = collection.GetFontFamilyCount();
1276        for index in 0..family_count {
1277            let Some(font_family) = collection.GetFontFamily(index).log_err() else {
1278                continue;
1279            };
1280            let Some(localized_family_name) = font_family.GetFamilyNames().log_err() else {
1281                continue;
1282            };
1283            let Some(family_name) = get_name(localized_family_name, locale).log_err() else {
1284                continue;
1285            };
1286            result.push(family_name);
1287        }
1288
1289        result
1290    }
1291}
1292
1293fn get_font_identifier_and_font_struct(
1294    font_face: &IDWriteFontFace3,
1295    locale: &str,
1296) -> Option<(FontIdentifier, Font, bool)> {
1297    let postscript_name = get_postscript_name(font_face, locale).log_err()?;
1298    let localized_family_name = unsafe { font_face.GetFamilyNames().log_err() }?;
1299    let family_name = get_name(localized_family_name, locale).log_err()?;
1300    let weight = unsafe { font_face.GetWeight() };
1301    let style = unsafe { font_face.GetStyle() };
1302    let identifier = FontIdentifier {
1303        postscript_name,
1304        weight: weight.0,
1305        style: style.0,
1306    };
1307    let font_struct = Font {
1308        family: family_name.into(),
1309        features: FontFeatures::default(),
1310        weight: weight.into(),
1311        style: style.into(),
1312        fallbacks: None,
1313    };
1314    let is_emoji = unsafe { font_face.IsColorFont().as_bool() };
1315    Some((identifier, font_struct, is_emoji))
1316}
1317
1318#[inline]
1319fn get_font_identifier(font_face: &IDWriteFontFace3, locale: &str) -> Option<FontIdentifier> {
1320    let weight = unsafe { font_face.GetWeight().0 };
1321    let style = unsafe { font_face.GetStyle().0 };
1322    get_postscript_name(font_face, locale)
1323        .log_err()
1324        .map(|postscript_name| FontIdentifier {
1325            postscript_name,
1326            weight,
1327            style,
1328        })
1329}
1330
1331#[inline]
1332fn get_postscript_name(font_face: &IDWriteFontFace3, locale: &str) -> Result<String> {
1333    let mut info = None;
1334    let mut exists = BOOL(0);
1335    unsafe {
1336        font_face.GetInformationalStrings(
1337            DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_NAME,
1338            &mut info,
1339            &mut exists,
1340        )?
1341    };
1342    if !exists.as_bool() || info.is_none() {
1343        anyhow::bail!("No postscript name found for font face");
1344    }
1345
1346    get_name(info.unwrap(), locale)
1347}
1348
1349// https://learn.microsoft.com/en-us/windows/win32/api/dwrite/ne-dwrite-dwrite_font_feature_tag
1350fn apply_font_features(
1351    direct_write_features: &IDWriteTypography,
1352    features: &FontFeatures,
1353) -> Result<()> {
1354    let tag_values = features.tag_value_list();
1355    if tag_values.is_empty() {
1356        return Ok(());
1357    }
1358
1359    // All of these features are enabled by default by DirectWrite.
1360    // If you want to (and can) peek into the source of DirectWrite
1361    let mut feature_liga = make_direct_write_feature("liga", 1);
1362    let mut feature_clig = make_direct_write_feature("clig", 1);
1363    let mut feature_calt = make_direct_write_feature("calt", 1);
1364
1365    for (tag, value) in tag_values {
1366        if tag.as_str() == "liga" && *value == 0 {
1367            feature_liga.parameter = 0;
1368            continue;
1369        }
1370        if tag.as_str() == "clig" && *value == 0 {
1371            feature_clig.parameter = 0;
1372            continue;
1373        }
1374        if tag.as_str() == "calt" && *value == 0 {
1375            feature_calt.parameter = 0;
1376            continue;
1377        }
1378
1379        unsafe {
1380            direct_write_features.AddFontFeature(make_direct_write_feature(&tag, *value))?;
1381        }
1382    }
1383    unsafe {
1384        direct_write_features.AddFontFeature(feature_liga)?;
1385        direct_write_features.AddFontFeature(feature_clig)?;
1386        direct_write_features.AddFontFeature(feature_calt)?;
1387    }
1388
1389    Ok(())
1390}
1391
1392#[inline]
1393const fn make_direct_write_feature(feature_name: &str, parameter: u32) -> DWRITE_FONT_FEATURE {
1394    let tag = make_direct_write_tag(feature_name);
1395    DWRITE_FONT_FEATURE {
1396        nameTag: tag,
1397        parameter,
1398    }
1399}
1400
1401#[inline]
1402const fn make_open_type_tag(tag_name: &str) -> u32 {
1403    let bytes = tag_name.as_bytes();
1404    debug_assert!(bytes.len() == 4);
1405    u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
1406}
1407
1408#[inline]
1409const fn make_direct_write_tag(tag_name: &str) -> DWRITE_FONT_FEATURE_TAG {
1410    DWRITE_FONT_FEATURE_TAG(make_open_type_tag(tag_name))
1411}
1412
1413#[inline]
1414fn get_name(string: IDWriteLocalizedStrings, locale: &str) -> Result<String> {
1415    let mut locale_name_index = 0u32;
1416    let mut exists = BOOL(0);
1417    unsafe {
1418        string.FindLocaleName(
1419            &HSTRING::from(locale),
1420            &mut locale_name_index,
1421            &mut exists as _,
1422        )?
1423    };
1424    if !exists.as_bool() {
1425        unsafe {
1426            string.FindLocaleName(
1427                DEFAULT_LOCALE_NAME,
1428                &mut locale_name_index as _,
1429                &mut exists as _,
1430            )?
1431        };
1432        anyhow::ensure!(exists.as_bool(), "No localised string for {locale}");
1433    }
1434
1435    let name_length = unsafe { string.GetStringLength(locale_name_index) }? as usize;
1436    let mut name_vec = vec![0u16; name_length + 1];
1437    unsafe {
1438        string.GetString(locale_name_index, &mut name_vec)?;
1439    }
1440
1441    Ok(String::from_utf16_lossy(&name_vec[..name_length]))
1442}
1443
1444#[inline]
1445fn translate_color(color: &DWRITE_COLOR_F) -> [f32; 4] {
1446    [color.r, color.g, color.b, color.a]
1447}
1448
1449fn get_system_ui_font_name() -> SharedString {
1450    unsafe {
1451        let mut info: LOGFONTW = std::mem::zeroed();
1452        let font_family = if SystemParametersInfoW(
1453            SPI_GETICONTITLELOGFONT,
1454            std::mem::size_of::<LOGFONTW>() as u32,
1455            Some(&mut info as *mut _ as _),
1456            SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
1457        )
1458        .log_err()
1459        .is_none()
1460        {
1461            // https://learn.microsoft.com/en-us/windows/win32/uxguide/vis-fonts
1462            // Segoe UI is the Windows font intended for user interface text strings.
1463            "Segoe UI".into()
1464        } else {
1465            let font_name = String::from_utf16_lossy(&info.lfFaceName);
1466            font_name.trim_matches(char::from(0)).to_owned().into()
1467        };
1468        log::info!("Use {} as UI font.", font_family);
1469        font_family
1470    }
1471}
1472
1473// One would think that with newer DirectWrite method: IDWriteFontFace4::GetGlyphImageFormats
1474// but that doesn't seem to work for some glyphs, say โค
1475fn is_color_glyph(
1476    font_face: &IDWriteFontFace3,
1477    glyph_id: GlyphId,
1478    factory: &IDWriteFactory5,
1479) -> bool {
1480    let glyph_run = DWRITE_GLYPH_RUN {
1481        fontFace: unsafe { std::mem::transmute_copy(font_face) },
1482        fontEmSize: 14.0,
1483        glyphCount: 1,
1484        glyphIndices: &(glyph_id.0 as u16),
1485        glyphAdvances: &0.0,
1486        glyphOffsets: &DWRITE_GLYPH_OFFSET {
1487            advanceOffset: 0.0,
1488            ascenderOffset: 0.0,
1489        },
1490        isSideways: BOOL(0),
1491        bidiLevel: 0,
1492    };
1493    unsafe {
1494        factory.TranslateColorGlyphRun(
1495            Vector2::default(),
1496            &glyph_run as _,
1497            None,
1498            DWRITE_GLYPH_IMAGE_FORMATS_COLR
1499                | DWRITE_GLYPH_IMAGE_FORMATS_SVG
1500                | DWRITE_GLYPH_IMAGE_FORMATS_PNG
1501                | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
1502                | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8,
1503            DWRITE_MEASURING_MODE_NATURAL,
1504            None,
1505            0,
1506        )
1507    }
1508    .is_ok()
1509}
1510
1511const DEFAULT_LOCALE_NAME: PCWSTR = windows::core::w!("en-US");
1512
1513#[cfg(test)]
1514mod tests {
1515    use crate::platform::windows::direct_write::ClusterAnalyzer;
1516
1517    #[test]
1518    fn test_cluster_map() {
1519        let cluster_map = [0];
1520        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 1);
1521        let next = analyzer.next();
1522        assert_eq!(next, Some((1, 1)));
1523        let next = analyzer.next();
1524        assert_eq!(next, None);
1525
1526        let cluster_map = [0, 1, 2];
1527        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 3);
1528        let next = analyzer.next();
1529        assert_eq!(next, Some((1, 1)));
1530        let next = analyzer.next();
1531        assert_eq!(next, Some((1, 1)));
1532        let next = analyzer.next();
1533        assert_eq!(next, Some((1, 1)));
1534        let next = analyzer.next();
1535        assert_eq!(next, None);
1536        // ๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ๐Ÿ‘ฉโ€๐Ÿ’ป
1537        let cluster_map = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4];
1538        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 5);
1539        let next = analyzer.next();
1540        assert_eq!(next, Some((11, 4)));
1541        let next = analyzer.next();
1542        assert_eq!(next, Some((5, 1)));
1543        let next = analyzer.next();
1544        assert_eq!(next, None);
1545        // ๐Ÿ‘ฉโ€๐Ÿ’ป
1546        let cluster_map = [0, 0, 0, 0, 0];
1547        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 1);
1548        let next = analyzer.next();
1549        assert_eq!(next, Some((5, 1)));
1550        let next = analyzer.next();
1551        assert_eq!(next, None);
1552    }
1553}