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