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