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