direct_write.rs

   1use std::{
   2    borrow::Cow,
   3    ffi::{c_uint, c_void},
   4    sync::Arc,
   5};
   6
   7use ::util::ResultExt;
   8use anyhow::{Context, Result};
   9use collections::HashMap;
  10use itertools::Itertools;
  11use parking_lot::{RwLock, RwLockUpgradableReadGuard};
  12use windows::{
  13    Win32::{
  14        Foundation::*,
  15        Globalization::GetUserDefaultLocaleName,
  16        Graphics::{
  17            Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, Direct3D11::*, DirectWrite::*,
  18            Dxgi::Common::*, Gdi::LOGFONTW,
  19        },
  20        System::SystemServices::LOCALE_NAME_MAX_LENGTH,
  21        UI::WindowsAndMessaging::*,
  22    },
  23    core::*,
  24};
  25use windows_numerics::Vector2;
  26
  27use crate::*;
  28
  29#[derive(Debug)]
  30struct FontInfo {
  31    font_family: String,
  32    font_face: IDWriteFontFace3,
  33    features: IDWriteTypography,
  34    fallbacks: Option<IDWriteFontFallback>,
  35    is_system_font: bool,
  36}
  37
  38pub(crate) struct DirectWriteTextSystem(RwLock<DirectWriteState>);
  39
  40struct DirectWriteComponent {
  41    locale: String,
  42    factory: IDWriteFactory5,
  43    in_memory_loader: IDWriteInMemoryFontFileLoader,
  44    builder: IDWriteFontSetBuilder1,
  45    text_renderer: Arc<TextRendererWrapper>,
  46
  47    gpu_state: GPUState,
  48}
  49
  50struct GPUState {
  51    device: ID3D11Device,
  52    device_context: ID3D11DeviceContext,
  53    sampler: [Option<ID3D11SamplerState>; 1],
  54    blend_state: ID3D11BlendState,
  55    vertex_shader: ID3D11VertexShader,
  56    pixel_shader: ID3D11PixelShader,
  57}
  58
  59struct DirectWriteState {
  60    components: DirectWriteComponent,
  61    system_ui_font_name: SharedString,
  62    system_font_collection: IDWriteFontCollection1,
  63    custom_font_collection: IDWriteFontCollection1,
  64    fonts: Vec<FontInfo>,
  65    font_selections: HashMap<Font, FontId>,
  66    font_id_by_identifier: HashMap<FontIdentifier, FontId>,
  67    system_subpixel_rendering: bool,
  68}
  69
  70#[derive(Debug, Clone, Hash, PartialEq, Eq)]
  71struct FontIdentifier {
  72    postscript_name: String,
  73    weight: i32,
  74    style: i32,
  75}
  76
  77impl DirectWriteComponent {
  78    pub fn new(directx_devices: &DirectXDevices) -> Result<Self> {
  79        // todo: ideally this would not be a large unsafe block but smaller isolated ones for easier auditing
  80        unsafe {
  81            let factory: IDWriteFactory5 = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED)?;
  82            // The `IDWriteInMemoryFontFileLoader` here is supported starting from
  83            // Windows 10 Creators Update, which consequently requires the entire
  84            // `DirectWriteTextSystem` to run on `win10 1703`+.
  85            let in_memory_loader = factory.CreateInMemoryFontFileLoader()?;
  86            factory.RegisterFontFileLoader(&in_memory_loader)?;
  87            let builder = factory.CreateFontSetBuilder()?;
  88            let mut locale_vec = vec![0u16; LOCALE_NAME_MAX_LENGTH as usize];
  89            GetUserDefaultLocaleName(&mut locale_vec);
  90            let locale = String::from_utf16_lossy(&locale_vec);
  91            let text_renderer = Arc::new(TextRendererWrapper::new(&locale));
  92
  93            let gpu_state = GPUState::new(directx_devices)?;
  94
  95            Ok(DirectWriteComponent {
  96                locale,
  97                factory,
  98                in_memory_loader,
  99                builder,
 100                text_renderer,
 101                gpu_state,
 102            })
 103        }
 104    }
 105}
 106
 107impl GPUState {
 108    fn new(directx_devices: &DirectXDevices) -> Result<Self> {
 109        let device = directx_devices.device.clone();
 110        let device_context = directx_devices.device_context.clone();
 111
 112        let blend_state = {
 113            let mut blend_state = None;
 114            let desc = D3D11_BLEND_DESC {
 115                AlphaToCoverageEnable: false.into(),
 116                IndependentBlendEnable: false.into(),
 117                RenderTarget: [
 118                    D3D11_RENDER_TARGET_BLEND_DESC {
 119                        BlendEnable: true.into(),
 120                        SrcBlend: D3D11_BLEND_ONE,
 121                        DestBlend: D3D11_BLEND_INV_SRC_ALPHA,
 122                        BlendOp: D3D11_BLEND_OP_ADD,
 123                        SrcBlendAlpha: D3D11_BLEND_ONE,
 124                        DestBlendAlpha: D3D11_BLEND_INV_SRC_ALPHA,
 125                        BlendOpAlpha: D3D11_BLEND_OP_ADD,
 126                        RenderTargetWriteMask: D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8,
 127                    },
 128                    Default::default(),
 129                    Default::default(),
 130                    Default::default(),
 131                    Default::default(),
 132                    Default::default(),
 133                    Default::default(),
 134                    Default::default(),
 135                ],
 136            };
 137            unsafe { device.CreateBlendState(&desc, Some(&mut blend_state)) }?;
 138            blend_state.unwrap()
 139        };
 140
 141        let sampler = {
 142            let mut sampler = None;
 143            let desc = D3D11_SAMPLER_DESC {
 144                Filter: D3D11_FILTER_MIN_MAG_MIP_POINT,
 145                AddressU: D3D11_TEXTURE_ADDRESS_BORDER,
 146                AddressV: D3D11_TEXTURE_ADDRESS_BORDER,
 147                AddressW: D3D11_TEXTURE_ADDRESS_BORDER,
 148                MipLODBias: 0.0,
 149                MaxAnisotropy: 1,
 150                ComparisonFunc: D3D11_COMPARISON_ALWAYS,
 151                BorderColor: [0.0, 0.0, 0.0, 0.0],
 152                MinLOD: 0.0,
 153                MaxLOD: 0.0,
 154            };
 155            unsafe { device.CreateSamplerState(&desc, Some(&mut sampler)) }?;
 156            [sampler]
 157        };
 158
 159        let vertex_shader = {
 160            let source = shader_resources::RawShaderBytes::new(
 161                shader_resources::ShaderModule::EmojiRasterization,
 162                shader_resources::ShaderTarget::Vertex,
 163            )?;
 164            let mut shader = None;
 165            unsafe { device.CreateVertexShader(source.as_bytes(), None, Some(&mut shader)) }?;
 166            shader.unwrap()
 167        };
 168
 169        let pixel_shader = {
 170            let source = shader_resources::RawShaderBytes::new(
 171                shader_resources::ShaderModule::EmojiRasterization,
 172                shader_resources::ShaderTarget::Fragment,
 173            )?;
 174            let mut shader = None;
 175            unsafe { device.CreatePixelShader(source.as_bytes(), None, Some(&mut shader)) }?;
 176            shader.unwrap()
 177        };
 178
 179        Ok(Self {
 180            device,
 181            device_context,
 182            sampler,
 183            blend_state,
 184            vertex_shader,
 185            pixel_shader,
 186        })
 187    }
 188}
 189
 190impl DirectWriteTextSystem {
 191    pub(crate) fn new(directx_devices: &DirectXDevices) -> Result<Self> {
 192        let components = DirectWriteComponent::new(directx_devices)?;
 193        let system_font_collection = unsafe {
 194            let mut result = std::mem::zeroed();
 195            components
 196                .factory
 197                .GetSystemFontCollection(false, &mut result, true)?;
 198            result.unwrap()
 199        };
 200        let custom_font_set = unsafe { components.builder.CreateFontSet()? };
 201        let custom_font_collection = unsafe {
 202            components
 203                .factory
 204                .CreateFontCollectionFromFontSet(&custom_font_set)?
 205        };
 206        let system_ui_font_name = get_system_ui_font_name();
 207        let system_subpixel_rendering = get_system_subpixel_rendering();
 208
 209        Ok(Self(RwLock::new(DirectWriteState {
 210            components,
 211            system_ui_font_name,
 212            system_font_collection,
 213            custom_font_collection,
 214            fonts: Vec::new(),
 215            font_selections: HashMap::default(),
 216            font_id_by_identifier: HashMap::default(),
 217            system_subpixel_rendering,
 218        })))
 219    }
 220
 221    pub(crate) fn handle_gpu_lost(&self, directx_devices: &DirectXDevices) -> Result<()> {
 222        self.0.write().handle_gpu_lost(directx_devices)
 223    }
 224}
 225
 226impl PlatformTextSystem for DirectWriteTextSystem {
 227    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
 228        self.0.write().add_fonts(fonts)
 229    }
 230
 231    fn all_font_names(&self) -> Vec<String> {
 232        self.0.read().all_font_names()
 233    }
 234
 235    fn font_id(&self, font: &Font) -> Result<FontId> {
 236        let lock = self.0.upgradable_read();
 237        if let Some(font_id) = lock.font_selections.get(font) {
 238            Ok(*font_id)
 239        } else {
 240            let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
 241            let font_id = lock
 242                .select_font(font)
 243                .with_context(|| format!("Failed to select font: {:?}", font))?;
 244            lock.font_selections.insert(font.clone(), font_id);
 245            Ok(font_id)
 246        }
 247    }
 248
 249    fn font_metrics(&self, font_id: FontId) -> FontMetrics {
 250        self.0.read().font_metrics(font_id)
 251    }
 252
 253    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
 254        self.0.read().get_typographic_bounds(font_id, glyph_id)
 255    }
 256
 257    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Size<f32>> {
 258        self.0.read().get_advance(font_id, glyph_id)
 259    }
 260
 261    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
 262        self.0.read().glyph_for_char(font_id, ch)
 263    }
 264
 265    fn glyph_raster_bounds(
 266        &self,
 267        params: &RenderGlyphParams,
 268    ) -> anyhow::Result<Bounds<DevicePixels>> {
 269        self.0.read().raster_bounds(params)
 270    }
 271
 272    fn rasterize_glyph(
 273        &self,
 274        params: &RenderGlyphParams,
 275        raster_bounds: Bounds<DevicePixels>,
 276    ) -> anyhow::Result<(Size<DevicePixels>, Vec<u8>)> {
 277        self.0.read().rasterize_glyph(params, raster_bounds)
 278    }
 279
 280    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {
 281        self.0
 282            .write()
 283            .layout_line(text, font_size, runs)
 284            .log_err()
 285            .unwrap_or(LineLayout {
 286                font_size,
 287                ..Default::default()
 288            })
 289    }
 290
 291    fn recommended_rendering_mode(
 292        &self,
 293        _font_id: FontId,
 294        _font_size: Pixels,
 295    ) -> TextRenderingMode {
 296        if self.0.read().system_subpixel_rendering {
 297            TextRenderingMode::Subpixel
 298        } else {
 299            TextRenderingMode::Grayscale
 300        }
 301    }
 302}
 303
 304impl DirectWriteState {
 305    fn add_fonts(&mut self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
 306        for font_data in fonts {
 307            match font_data {
 308                Cow::Borrowed(data) => unsafe {
 309                    let font_file = self
 310                        .components
 311                        .in_memory_loader
 312                        .CreateInMemoryFontFileReference(
 313                            &self.components.factory,
 314                            data.as_ptr() as _,
 315                            data.len() as _,
 316                            None,
 317                        )?;
 318                    self.components.builder.AddFontFile(&font_file)?;
 319                },
 320                Cow::Owned(data) => unsafe {
 321                    let font_file = self
 322                        .components
 323                        .in_memory_loader
 324                        .CreateInMemoryFontFileReference(
 325                            &self.components.factory,
 326                            data.as_ptr() as _,
 327                            data.len() as _,
 328                            None,
 329                        )?;
 330                    self.components.builder.AddFontFile(&font_file)?;
 331                },
 332            }
 333        }
 334        let set = unsafe { self.components.builder.CreateFontSet()? };
 335        let collection = unsafe {
 336            self.components
 337                .factory
 338                .CreateFontCollectionFromFontSet(&set)?
 339        };
 340        self.custom_font_collection = collection;
 341
 342        Ok(())
 343    }
 344
 345    fn generate_font_fallbacks(
 346        &self,
 347        fallbacks: &FontFallbacks,
 348    ) -> Result<Option<IDWriteFontFallback>> {
 349        if fallbacks.fallback_list().is_empty() {
 350            return Ok(None);
 351        }
 352        unsafe {
 353            let builder = self.components.factory.CreateFontFallbackBuilder()?;
 354            let font_set = &self.system_font_collection.GetFontSet()?;
 355            for family_name in fallbacks.fallback_list() {
 356                let Some(fonts) = font_set
 357                    .GetMatchingFonts(
 358                        &HSTRING::from(family_name),
 359                        DWRITE_FONT_WEIGHT_NORMAL,
 360                        DWRITE_FONT_STRETCH_NORMAL,
 361                        DWRITE_FONT_STYLE_NORMAL,
 362                    )
 363                    .log_err()
 364                else {
 365                    continue;
 366                };
 367                if fonts.GetFontCount() == 0 {
 368                    log::error!("No matching font found for {}", family_name);
 369                    continue;
 370                }
 371                let font = fonts.GetFontFaceReference(0)?.CreateFontFace()?;
 372                let mut count = 0;
 373                font.GetUnicodeRanges(None, &mut count).ok();
 374                if count == 0 {
 375                    continue;
 376                }
 377                let mut unicode_ranges = vec![DWRITE_UNICODE_RANGE::default(); count as usize];
 378                let Some(_) = font
 379                    .GetUnicodeRanges(Some(&mut unicode_ranges), &mut count)
 380                    .log_err()
 381                else {
 382                    continue;
 383                };
 384                let target_family_name = HSTRING::from(family_name);
 385                builder.AddMapping(
 386                    &unicode_ranges,
 387                    &[target_family_name.as_ptr()],
 388                    None,
 389                    None,
 390                    None,
 391                    1.0,
 392                )?;
 393            }
 394            let system_fallbacks = self.components.factory.GetSystemFontFallback()?;
 395            builder.AddMappings(&system_fallbacks)?;
 396            Ok(Some(builder.CreateFontFallback()?))
 397        }
 398    }
 399
 400    unsafe fn generate_font_features(
 401        &self,
 402        font_features: &FontFeatures,
 403    ) -> Result<IDWriteTypography> {
 404        let direct_write_features = unsafe { self.components.factory.CreateTypography()? };
 405        apply_font_features(&direct_write_features, font_features)?;
 406        Ok(direct_write_features)
 407    }
 408
 409    unsafe fn get_font_id_from_font_collection(
 410        &mut self,
 411        family_name: &str,
 412        font_weight: FontWeight,
 413        font_style: FontStyle,
 414        font_features: &FontFeatures,
 415        font_fallbacks: Option<&FontFallbacks>,
 416        is_system_font: bool,
 417    ) -> Option<FontId> {
 418        let collection = if is_system_font {
 419            &self.system_font_collection
 420        } else {
 421            &self.custom_font_collection
 422        };
 423        let fontset = unsafe { collection.GetFontSet().log_err()? };
 424        let font = unsafe {
 425            fontset
 426                .GetMatchingFonts(
 427                    &HSTRING::from(family_name),
 428                    font_weight.into(),
 429                    DWRITE_FONT_STRETCH_NORMAL,
 430                    font_style.into(),
 431                )
 432                .log_err()?
 433        };
 434        let total_number = unsafe { font.GetFontCount() };
 435        for index in 0..total_number {
 436            let Some(font_face_ref) = (unsafe { font.GetFontFaceReference(index).log_err() })
 437            else {
 438                continue;
 439            };
 440            let Some(font_face) = (unsafe { font_face_ref.CreateFontFace().log_err() }) else {
 441                continue;
 442            };
 443            let Some(identifier) = get_font_identifier(&font_face, &self.components.locale) else {
 444                continue;
 445            };
 446            let Some(direct_write_features) =
 447                (unsafe { self.generate_font_features(font_features).log_err() })
 448            else {
 449                continue;
 450            };
 451            let fallbacks = font_fallbacks
 452                .and_then(|fallbacks| self.generate_font_fallbacks(fallbacks).log_err().flatten());
 453            let font_info = FontInfo {
 454                font_family: family_name.to_owned(),
 455                font_face,
 456                features: direct_write_features,
 457                fallbacks,
 458                is_system_font,
 459            };
 460            let font_id = FontId(self.fonts.len());
 461            self.fonts.push(font_info);
 462            self.font_id_by_identifier.insert(identifier, font_id);
 463            return Some(font_id);
 464        }
 465        None
 466    }
 467
 468    unsafe fn update_system_font_collection(&mut self) {
 469        let mut collection = unsafe { std::mem::zeroed() };
 470        if unsafe {
 471            self.components
 472                .factory
 473                .GetSystemFontCollection(false, &mut collection, true)
 474                .log_err()
 475                .is_some()
 476        } {
 477            self.system_font_collection = collection.unwrap();
 478        }
 479    }
 480
 481    fn select_font(&mut self, target_font: &Font) -> Option<FontId> {
 482        unsafe {
 483            if target_font.family == ".SystemUIFont" {
 484                let family = self.system_ui_font_name.clone();
 485                self.find_font_id(
 486                    family.as_ref(),
 487                    target_font.weight,
 488                    target_font.style,
 489                    &target_font.features,
 490                    target_font.fallbacks.as_ref(),
 491                )
 492            } else {
 493                let family = self.system_ui_font_name.clone();
 494                self.find_font_id(
 495                    font_name_with_fallbacks(target_font.family.as_ref(), family.as_ref()),
 496                    target_font.weight,
 497                    target_font.style,
 498                    &target_font.features,
 499                    target_font.fallbacks.as_ref(),
 500                )
 501                .or_else(|| {
 502                    #[cfg(any(test, feature = "test-support"))]
 503                    {
 504                        panic!("ERROR: {} font not found!", target_font.family);
 505                    }
 506                    #[cfg(not(any(test, feature = "test-support")))]
 507                    {
 508                        log::error!("{} not found, use {} instead.", target_font.family, family);
 509                        self.get_font_id_from_font_collection(
 510                            family.as_ref(),
 511                            target_font.weight,
 512                            target_font.style,
 513                            &target_font.features,
 514                            target_font.fallbacks.as_ref(),
 515                            true,
 516                        )
 517                    }
 518                })
 519            }
 520        }
 521    }
 522
 523    unsafe fn find_font_id(
 524        &mut self,
 525        family_name: &str,
 526        weight: FontWeight,
 527        style: FontStyle,
 528        features: &FontFeatures,
 529        fallbacks: Option<&FontFallbacks>,
 530    ) -> Option<FontId> {
 531        // try to find target font in custom font collection first
 532        unsafe {
 533            self.get_font_id_from_font_collection(
 534                family_name,
 535                weight,
 536                style,
 537                features,
 538                fallbacks,
 539                false,
 540            )
 541            .or_else(|| {
 542                self.get_font_id_from_font_collection(
 543                    family_name,
 544                    weight,
 545                    style,
 546                    features,
 547                    fallbacks,
 548                    true,
 549                )
 550            })
 551            .or_else(|| {
 552                self.update_system_font_collection();
 553                self.get_font_id_from_font_collection(
 554                    family_name,
 555                    weight,
 556                    style,
 557                    features,
 558                    fallbacks,
 559                    true,
 560                )
 561            })
 562        }
 563    }
 564
 565    fn layout_line(
 566        &mut self,
 567        text: &str,
 568        font_size: Pixels,
 569        font_runs: &[FontRun],
 570    ) -> Result<LineLayout> {
 571        if font_runs.is_empty() {
 572            return Ok(LineLayout {
 573                font_size,
 574                ..Default::default()
 575            });
 576        }
 577        unsafe {
 578            let text_renderer = self.components.text_renderer.clone();
 579            let text_wide = text.encode_utf16().collect_vec();
 580
 581            let mut utf8_offset = 0usize;
 582            let mut utf16_offset = 0u32;
 583            let text_layout = {
 584                let first_run = &font_runs[0];
 585                let font_info = &self.fonts[first_run.font_id.0];
 586                let collection = if font_info.is_system_font {
 587                    &self.system_font_collection
 588                } else {
 589                    &self.custom_font_collection
 590                };
 591                let format: IDWriteTextFormat1 = self
 592                    .components
 593                    .factory
 594                    .CreateTextFormat(
 595                        &HSTRING::from(&font_info.font_family),
 596                        collection,
 597                        font_info.font_face.GetWeight(),
 598                        font_info.font_face.GetStyle(),
 599                        DWRITE_FONT_STRETCH_NORMAL,
 600                        font_size.0,
 601                        &HSTRING::from(&self.components.locale),
 602                    )?
 603                    .cast()?;
 604                if let Some(ref fallbacks) = font_info.fallbacks {
 605                    format.SetFontFallback(fallbacks)?;
 606                }
 607
 608                let layout = self.components.factory.CreateTextLayout(
 609                    &text_wide,
 610                    &format,
 611                    f32::INFINITY,
 612                    f32::INFINITY,
 613                )?;
 614                let current_text = &text[utf8_offset..(utf8_offset + first_run.len)];
 615                utf8_offset += first_run.len;
 616                let current_text_utf16_length = current_text.encode_utf16().count() as u32;
 617                let text_range = DWRITE_TEXT_RANGE {
 618                    startPosition: utf16_offset,
 619                    length: current_text_utf16_length,
 620                };
 621                layout.SetTypography(&font_info.features, text_range)?;
 622                utf16_offset += current_text_utf16_length;
 623
 624                layout
 625            };
 626
 627            let mut first_run = true;
 628            let mut ascent = Pixels::default();
 629            let mut descent = Pixels::default();
 630            let mut break_ligatures = false;
 631            for run in font_runs {
 632                if first_run {
 633                    first_run = false;
 634                    let mut metrics = vec![DWRITE_LINE_METRICS::default(); 4];
 635                    let mut line_count = 0u32;
 636                    text_layout.GetLineMetrics(Some(&mut metrics), &mut line_count as _)?;
 637                    ascent = px(metrics[0].baseline);
 638                    descent = px(metrics[0].height - metrics[0].baseline);
 639                    break_ligatures = !break_ligatures;
 640                    continue;
 641                }
 642                let font_info = &self.fonts[run.font_id.0];
 643                let current_text = &text[utf8_offset..(utf8_offset + run.len)];
 644                utf8_offset += run.len;
 645                let current_text_utf16_length = current_text.encode_utf16().count() as u32;
 646
 647                let collection = if font_info.is_system_font {
 648                    &self.system_font_collection
 649                } else {
 650                    &self.custom_font_collection
 651                };
 652                let text_range = DWRITE_TEXT_RANGE {
 653                    startPosition: utf16_offset,
 654                    length: current_text_utf16_length,
 655                };
 656                utf16_offset += current_text_utf16_length;
 657                text_layout.SetFontCollection(collection, text_range)?;
 658                text_layout
 659                    .SetFontFamilyName(&HSTRING::from(&font_info.font_family), text_range)?;
 660                let font_size = if break_ligatures {
 661                    font_size.0.next_up()
 662                } else {
 663                    font_size.0
 664                };
 665                text_layout.SetFontSize(font_size, text_range)?;
 666                text_layout.SetFontStyle(font_info.font_face.GetStyle(), text_range)?;
 667                text_layout.SetFontWeight(font_info.font_face.GetWeight(), text_range)?;
 668                text_layout.SetTypography(&font_info.features, text_range)?;
 669
 670                break_ligatures = !break_ligatures;
 671            }
 672
 673            let mut runs = Vec::new();
 674            let renderer_context = RendererContext {
 675                text_system: self,
 676                index_converter: StringIndexConverter::new(text),
 677                runs: &mut runs,
 678                width: 0.0,
 679            };
 680            text_layout.Draw(
 681                Some(&renderer_context as *const _ as _),
 682                &text_renderer.0,
 683                0.0,
 684                0.0,
 685            )?;
 686            let width = px(renderer_context.width);
 687
 688            Ok(LineLayout {
 689                font_size,
 690                width,
 691                ascent,
 692                descent,
 693                runs,
 694                len: text.len(),
 695            })
 696        }
 697    }
 698
 699    fn font_metrics(&self, font_id: FontId) -> FontMetrics {
 700        unsafe {
 701            let font_info = &self.fonts[font_id.0];
 702            let mut metrics = std::mem::zeroed();
 703            font_info.font_face.GetMetrics(&mut metrics);
 704
 705            FontMetrics {
 706                units_per_em: metrics.Base.designUnitsPerEm as _,
 707                ascent: metrics.Base.ascent as _,
 708                descent: -(metrics.Base.descent as f32),
 709                line_gap: metrics.Base.lineGap as _,
 710                underline_position: metrics.Base.underlinePosition as _,
 711                underline_thickness: metrics.Base.underlineThickness as _,
 712                cap_height: metrics.Base.capHeight as _,
 713                x_height: metrics.Base.xHeight as _,
 714                bounding_box: Bounds {
 715                    origin: Point {
 716                        x: metrics.glyphBoxLeft as _,
 717                        y: metrics.glyphBoxBottom as _,
 718                    },
 719                    size: Size {
 720                        width: (metrics.glyphBoxRight - metrics.glyphBoxLeft) as _,
 721                        height: (metrics.glyphBoxTop - metrics.glyphBoxBottom) as _,
 722                    },
 723                },
 724            }
 725        }
 726    }
 727
 728    fn create_glyph_run_analysis(
 729        &self,
 730        params: &RenderGlyphParams,
 731    ) -> Result<IDWriteGlyphRunAnalysis> {
 732        let font = &self.fonts[params.font_id.0];
 733        let glyph_id = [params.glyph_id.0 as u16];
 734        let advance = [0.0];
 735        let offset = [DWRITE_GLYPH_OFFSET::default()];
 736        let glyph_run = DWRITE_GLYPH_RUN {
 737            fontFace: unsafe { std::mem::transmute_copy(&font.font_face) },
 738            fontEmSize: params.font_size.0,
 739            glyphCount: 1,
 740            glyphIndices: glyph_id.as_ptr(),
 741            glyphAdvances: advance.as_ptr(),
 742            glyphOffsets: offset.as_ptr(),
 743            isSideways: BOOL(0),
 744            bidiLevel: 0,
 745        };
 746        let transform = DWRITE_MATRIX {
 747            m11: params.scale_factor,
 748            m12: 0.0,
 749            m21: 0.0,
 750            m22: params.scale_factor,
 751            dx: 0.0,
 752            dy: 0.0,
 753        };
 754        let baseline_origin_x =
 755            params.subpixel_variant.x as f32 / SUBPIXEL_VARIANTS_X as f32 / params.scale_factor;
 756        let baseline_origin_y =
 757            params.subpixel_variant.y as f32 / SUBPIXEL_VARIANTS_Y as f32 / params.scale_factor;
 758
 759        let mut rendering_mode = DWRITE_RENDERING_MODE1::default();
 760        let mut grid_fit_mode = DWRITE_GRID_FIT_MODE::default();
 761        unsafe {
 762            font.font_face.GetRecommendedRenderingMode(
 763                params.font_size.0,
 764                // Using 96 as scale is applied by the transform
 765                96.0,
 766                96.0,
 767                Some(&transform),
 768                false,
 769                DWRITE_OUTLINE_THRESHOLD_ANTIALIASED,
 770                DWRITE_MEASURING_MODE_NATURAL,
 771                None,
 772                &mut rendering_mode,
 773                &mut grid_fit_mode,
 774            )?;
 775        }
 776        let rendering_mode = match rendering_mode {
 777            DWRITE_RENDERING_MODE1_OUTLINE => DWRITE_RENDERING_MODE1_NATURAL_SYMMETRIC,
 778            m => m,
 779        };
 780
 781        let antialias_mode = if params.subpixel_rendering {
 782            DWRITE_TEXT_ANTIALIAS_MODE_CLEARTYPE
 783        } else {
 784            DWRITE_TEXT_ANTIALIAS_MODE_GRAYSCALE
 785        };
 786
 787        let glyph_analysis = unsafe {
 788            self.components.factory.CreateGlyphRunAnalysis(
 789                &glyph_run,
 790                Some(&transform),
 791                rendering_mode,
 792                DWRITE_MEASURING_MODE_NATURAL,
 793                grid_fit_mode,
 794                antialias_mode,
 795                baseline_origin_x,
 796                baseline_origin_y,
 797            )
 798        }?;
 799        Ok(glyph_analysis)
 800    }
 801
 802    fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
 803        let glyph_analysis = self.create_glyph_run_analysis(params)?;
 804
 805        let texture_type = if params.subpixel_rendering {
 806            DWRITE_TEXTURE_CLEARTYPE_3x1
 807        } else {
 808            DWRITE_TEXTURE_ALIASED_1x1
 809        };
 810
 811        let bounds = unsafe { glyph_analysis.GetAlphaTextureBounds(texture_type)? };
 812
 813        if bounds.right < bounds.left {
 814            Ok(Bounds {
 815                origin: point(0.into(), 0.into()),
 816                size: size(0.into(), 0.into()),
 817            })
 818        } else {
 819            Ok(Bounds {
 820                origin: point(bounds.left.into(), bounds.top.into()),
 821                size: size(
 822                    (bounds.right - bounds.left).into(),
 823                    (bounds.bottom - bounds.top).into(),
 824                ),
 825            })
 826        }
 827    }
 828
 829    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
 830        let font_info = &self.fonts[font_id.0];
 831        let codepoints = [ch as u32];
 832        let mut glyph_indices = vec![0u16; 1];
 833        unsafe {
 834            font_info
 835                .font_face
 836                .GetGlyphIndices(codepoints.as_ptr(), 1, glyph_indices.as_mut_ptr())
 837                .log_err()
 838        }
 839        .map(|_| GlyphId(glyph_indices[0] as u32))
 840    }
 841
 842    fn rasterize_glyph(
 843        &self,
 844        params: &RenderGlyphParams,
 845        glyph_bounds: Bounds<DevicePixels>,
 846    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
 847        if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
 848            anyhow::bail!("glyph bounds are empty");
 849        }
 850
 851        let bitmap_data = if params.is_emoji {
 852            if let Ok(color) = self.rasterize_color(params, glyph_bounds) {
 853                color
 854            } else {
 855                let monochrome = self.rasterize_monochrome(params, glyph_bounds)?;
 856                monochrome
 857                    .into_iter()
 858                    .flat_map(|pixel| [0, 0, 0, pixel])
 859                    .collect::<Vec<_>>()
 860            }
 861        } else {
 862            self.rasterize_monochrome(params, glyph_bounds)?
 863        };
 864
 865        Ok((glyph_bounds.size, bitmap_data))
 866    }
 867
 868    fn rasterize_monochrome(
 869        &self,
 870        params: &RenderGlyphParams,
 871        glyph_bounds: Bounds<DevicePixels>,
 872    ) -> Result<Vec<u8>> {
 873        if !params.subpixel_rendering {
 874            let mut bitmap_data =
 875                vec![0u8; glyph_bounds.size.width.0 as usize * glyph_bounds.size.height.0 as usize];
 876
 877            let glyph_analysis = self.create_glyph_run_analysis(params)?;
 878            unsafe {
 879                glyph_analysis.CreateAlphaTexture(
 880                    DWRITE_TEXTURE_ALIASED_1x1,
 881                    &RECT {
 882                        left: glyph_bounds.origin.x.0,
 883                        top: glyph_bounds.origin.y.0,
 884                        right: glyph_bounds.size.width.0 + glyph_bounds.origin.x.0,
 885                        bottom: glyph_bounds.size.height.0 + glyph_bounds.origin.y.0,
 886                    },
 887                    &mut bitmap_data,
 888                )?;
 889            }
 890
 891            return Ok(bitmap_data);
 892        }
 893
 894        let width = glyph_bounds.size.width.0 as usize;
 895        let height = glyph_bounds.size.height.0 as usize;
 896        let pixel_count = width * height;
 897
 898        let mut bitmap_data = vec![0u8; pixel_count * 4];
 899
 900        let glyph_analysis = self.create_glyph_run_analysis(params)?;
 901        unsafe {
 902            glyph_analysis.CreateAlphaTexture(
 903                DWRITE_TEXTURE_CLEARTYPE_3x1,
 904                &RECT {
 905                    left: glyph_bounds.origin.x.0,
 906                    top: glyph_bounds.origin.y.0,
 907                    right: glyph_bounds.size.width.0 + glyph_bounds.origin.x.0,
 908                    bottom: glyph_bounds.size.height.0 + glyph_bounds.origin.y.0,
 909                },
 910                &mut bitmap_data[..pixel_count * 3],
 911            )?;
 912        }
 913
 914        // The output buffer expects RGBA data, so pad the alpha channel with zeros.
 915        for pixel_ix in (0..pixel_count).rev() {
 916            let src = pixel_ix * 3;
 917            let dst = pixel_ix * 4;
 918            (
 919                bitmap_data[dst],
 920                bitmap_data[dst + 1],
 921                bitmap_data[dst + 2],
 922                bitmap_data[dst + 3],
 923            ) = (
 924                bitmap_data[src],
 925                bitmap_data[src + 1],
 926                bitmap_data[src + 2],
 927                0,
 928            );
 929        }
 930
 931        Ok(bitmap_data)
 932    }
 933
 934    fn rasterize_color(
 935        &self,
 936        params: &RenderGlyphParams,
 937        glyph_bounds: Bounds<DevicePixels>,
 938    ) -> Result<Vec<u8>> {
 939        let bitmap_size = glyph_bounds.size;
 940        let subpixel_shift = params
 941            .subpixel_variant
 942            .map(|v| v as f32 / SUBPIXEL_VARIANTS_X as f32);
 943        let baseline_origin_x = subpixel_shift.x / params.scale_factor;
 944        let baseline_origin_y = subpixel_shift.y / params.scale_factor;
 945
 946        let transform = DWRITE_MATRIX {
 947            m11: params.scale_factor,
 948            m12: 0.0,
 949            m21: 0.0,
 950            m22: params.scale_factor,
 951            dx: 0.0,
 952            dy: 0.0,
 953        };
 954
 955        let font = &self.fonts[params.font_id.0];
 956        let glyph_id = [params.glyph_id.0 as u16];
 957        let advance = [glyph_bounds.size.width.0 as f32];
 958        let offset = [DWRITE_GLYPH_OFFSET {
 959            advanceOffset: -glyph_bounds.origin.x.0 as f32 / params.scale_factor,
 960            ascenderOffset: glyph_bounds.origin.y.0 as f32 / params.scale_factor,
 961        }];
 962        let glyph_run = DWRITE_GLYPH_RUN {
 963            fontFace: unsafe { std::mem::transmute_copy(&font.font_face) },
 964            fontEmSize: params.font_size.0,
 965            glyphCount: 1,
 966            glyphIndices: glyph_id.as_ptr(),
 967            glyphAdvances: advance.as_ptr(),
 968            glyphOffsets: offset.as_ptr(),
 969            isSideways: BOOL(0),
 970            bidiLevel: 0,
 971        };
 972
 973        // todo: support formats other than COLR
 974        let color_enumerator = unsafe {
 975            self.components.factory.TranslateColorGlyphRun(
 976                Vector2::new(baseline_origin_x, baseline_origin_y),
 977                &glyph_run,
 978                None,
 979                DWRITE_GLYPH_IMAGE_FORMATS_COLR,
 980                DWRITE_MEASURING_MODE_NATURAL,
 981                Some(&transform),
 982                0,
 983            )
 984        }?;
 985
 986        let mut glyph_layers = Vec::new();
 987        loop {
 988            let color_run = unsafe { color_enumerator.GetCurrentRun() }?;
 989            let color_run = unsafe { &*color_run };
 990            let image_format = color_run.glyphImageFormat & !DWRITE_GLYPH_IMAGE_FORMATS_TRUETYPE;
 991            if image_format == DWRITE_GLYPH_IMAGE_FORMATS_COLR {
 992                let color_analysis = unsafe {
 993                    self.components.factory.CreateGlyphRunAnalysis(
 994                        &color_run.Base.glyphRun as *const _,
 995                        Some(&transform),
 996                        DWRITE_RENDERING_MODE1_NATURAL_SYMMETRIC,
 997                        DWRITE_MEASURING_MODE_NATURAL,
 998                        DWRITE_GRID_FIT_MODE_DEFAULT,
 999                        DWRITE_TEXT_ANTIALIAS_MODE_GRAYSCALE,
1000                        baseline_origin_x,
1001                        baseline_origin_y,
1002                    )
1003                }?;
1004
1005                let color_bounds =
1006                    unsafe { color_analysis.GetAlphaTextureBounds(DWRITE_TEXTURE_ALIASED_1x1) }?;
1007
1008                let color_size = size(
1009                    color_bounds.right - color_bounds.left,
1010                    color_bounds.bottom - color_bounds.top,
1011                );
1012                if color_size.width > 0 && color_size.height > 0 {
1013                    let mut alpha_data = vec![0u8; (color_size.width * color_size.height) as usize];
1014                    unsafe {
1015                        color_analysis.CreateAlphaTexture(
1016                            DWRITE_TEXTURE_ALIASED_1x1,
1017                            &color_bounds,
1018                            &mut alpha_data,
1019                        )
1020                    }?;
1021
1022                    let run_color = {
1023                        let run_color = color_run.Base.runColor;
1024                        Rgba {
1025                            r: run_color.r,
1026                            g: run_color.g,
1027                            b: run_color.b,
1028                            a: run_color.a,
1029                        }
1030                    };
1031                    let bounds = bounds(point(color_bounds.left, color_bounds.top), color_size);
1032                    glyph_layers.push(GlyphLayerTexture::new(
1033                        &self.components.gpu_state,
1034                        run_color,
1035                        bounds,
1036                        &alpha_data,
1037                    )?);
1038                }
1039            }
1040
1041            let has_next = unsafe { color_enumerator.MoveNext() }
1042                .map(|e| e.as_bool())
1043                .unwrap_or(false);
1044            if !has_next {
1045                break;
1046            }
1047        }
1048
1049        let gpu_state = &self.components.gpu_state;
1050        let params_buffer = {
1051            let desc = D3D11_BUFFER_DESC {
1052                ByteWidth: std::mem::size_of::<GlyphLayerTextureParams>() as u32,
1053                Usage: D3D11_USAGE_DYNAMIC,
1054                BindFlags: D3D11_BIND_CONSTANT_BUFFER.0 as u32,
1055                CPUAccessFlags: D3D11_CPU_ACCESS_WRITE.0 as u32,
1056                MiscFlags: 0,
1057                StructureByteStride: 0,
1058            };
1059
1060            let mut buffer = None;
1061            unsafe {
1062                gpu_state
1063                    .device
1064                    .CreateBuffer(&desc, None, Some(&mut buffer))
1065            }?;
1066            [buffer]
1067        };
1068
1069        let render_target_texture = {
1070            let mut texture = None;
1071            let desc = D3D11_TEXTURE2D_DESC {
1072                Width: bitmap_size.width.0 as u32,
1073                Height: bitmap_size.height.0 as u32,
1074                MipLevels: 1,
1075                ArraySize: 1,
1076                Format: DXGI_FORMAT_B8G8R8A8_UNORM,
1077                SampleDesc: DXGI_SAMPLE_DESC {
1078                    Count: 1,
1079                    Quality: 0,
1080                },
1081                Usage: D3D11_USAGE_DEFAULT,
1082                BindFlags: D3D11_BIND_RENDER_TARGET.0 as u32,
1083                CPUAccessFlags: 0,
1084                MiscFlags: 0,
1085            };
1086            unsafe {
1087                gpu_state
1088                    .device
1089                    .CreateTexture2D(&desc, None, Some(&mut texture))
1090            }?;
1091            texture.unwrap()
1092        };
1093
1094        let render_target_view = {
1095            let desc = D3D11_RENDER_TARGET_VIEW_DESC {
1096                Format: DXGI_FORMAT_B8G8R8A8_UNORM,
1097                ViewDimension: D3D11_RTV_DIMENSION_TEXTURE2D,
1098                Anonymous: D3D11_RENDER_TARGET_VIEW_DESC_0 {
1099                    Texture2D: D3D11_TEX2D_RTV { MipSlice: 0 },
1100                },
1101            };
1102            let mut rtv = None;
1103            unsafe {
1104                gpu_state.device.CreateRenderTargetView(
1105                    &render_target_texture,
1106                    Some(&desc),
1107                    Some(&mut rtv),
1108                )
1109            }?;
1110            [rtv]
1111        };
1112
1113        let staging_texture = {
1114            let mut texture = None;
1115            let desc = D3D11_TEXTURE2D_DESC {
1116                Width: bitmap_size.width.0 as u32,
1117                Height: bitmap_size.height.0 as u32,
1118                MipLevels: 1,
1119                ArraySize: 1,
1120                Format: DXGI_FORMAT_B8G8R8A8_UNORM,
1121                SampleDesc: DXGI_SAMPLE_DESC {
1122                    Count: 1,
1123                    Quality: 0,
1124                },
1125                Usage: D3D11_USAGE_STAGING,
1126                BindFlags: 0,
1127                CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32,
1128                MiscFlags: 0,
1129            };
1130            unsafe {
1131                gpu_state
1132                    .device
1133                    .CreateTexture2D(&desc, None, Some(&mut texture))
1134            }?;
1135            texture.unwrap()
1136        };
1137
1138        let device_context = &gpu_state.device_context;
1139        unsafe { device_context.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP) };
1140        unsafe { device_context.VSSetShader(&gpu_state.vertex_shader, None) };
1141        unsafe { device_context.PSSetShader(&gpu_state.pixel_shader, None) };
1142        unsafe { device_context.VSSetConstantBuffers(0, Some(&params_buffer)) };
1143        unsafe { device_context.PSSetConstantBuffers(0, Some(&params_buffer)) };
1144        unsafe { device_context.OMSetRenderTargets(Some(&render_target_view), None) };
1145        unsafe { device_context.PSSetSamplers(0, Some(&gpu_state.sampler)) };
1146        unsafe { device_context.OMSetBlendState(&gpu_state.blend_state, None, 0xffffffff) };
1147
1148        let crate::FontInfo {
1149            gamma_ratios,
1150            grayscale_enhanced_contrast,
1151            ..
1152        } = DirectXRenderer::get_font_info();
1153
1154        for layer in glyph_layers {
1155            let params = GlyphLayerTextureParams {
1156                run_color: layer.run_color,
1157                bounds: layer.bounds,
1158                gamma_ratios: *gamma_ratios,
1159                grayscale_enhanced_contrast: *grayscale_enhanced_contrast,
1160                _pad: [0f32; 3],
1161            };
1162            unsafe {
1163                let mut dest = std::mem::zeroed();
1164                gpu_state.device_context.Map(
1165                    params_buffer[0].as_ref().unwrap(),
1166                    0,
1167                    D3D11_MAP_WRITE_DISCARD,
1168                    0,
1169                    Some(&mut dest),
1170                )?;
1171                std::ptr::copy_nonoverlapping(&params as *const _, dest.pData as *mut _, 1);
1172                gpu_state
1173                    .device_context
1174                    .Unmap(params_buffer[0].as_ref().unwrap(), 0);
1175            };
1176
1177            let texture = [Some(layer.texture_view)];
1178            unsafe { device_context.PSSetShaderResources(0, Some(&texture)) };
1179
1180            let viewport = [D3D11_VIEWPORT {
1181                TopLeftX: layer.bounds.origin.x as f32,
1182                TopLeftY: layer.bounds.origin.y as f32,
1183                Width: layer.bounds.size.width as f32,
1184                Height: layer.bounds.size.height as f32,
1185                MinDepth: 0.0,
1186                MaxDepth: 1.0,
1187            }];
1188            unsafe { device_context.RSSetViewports(Some(&viewport)) };
1189
1190            unsafe { device_context.Draw(4, 0) };
1191        }
1192
1193        unsafe { device_context.CopyResource(&staging_texture, &render_target_texture) };
1194
1195        let mapped_data = {
1196            let mut mapped_data = D3D11_MAPPED_SUBRESOURCE::default();
1197            unsafe {
1198                device_context.Map(
1199                    &staging_texture,
1200                    0,
1201                    D3D11_MAP_READ,
1202                    0,
1203                    Some(&mut mapped_data),
1204                )
1205            }?;
1206            mapped_data
1207        };
1208        let mut rasterized =
1209            vec![0u8; (bitmap_size.width.0 as u32 * bitmap_size.height.0 as u32 * 4) as usize];
1210
1211        for y in 0..bitmap_size.height.0 as usize {
1212            let width = bitmap_size.width.0 as usize;
1213            unsafe {
1214                std::ptr::copy_nonoverlapping::<u8>(
1215                    (mapped_data.pData as *const u8).byte_add(mapped_data.RowPitch as usize * y),
1216                    rasterized
1217                        .as_mut_ptr()
1218                        .byte_add(width * y * std::mem::size_of::<u32>()),
1219                    width * std::mem::size_of::<u32>(),
1220                )
1221            };
1222        }
1223
1224        // Convert from premultiplied to straight alpha
1225        for chunk in rasterized.chunks_exact_mut(4) {
1226            let b = chunk[0] as f32;
1227            let g = chunk[1] as f32;
1228            let r = chunk[2] as f32;
1229            let a = chunk[3] as f32;
1230            if a > 0.0 {
1231                let inv_a = 255.0 / a;
1232                chunk[0] = (b * inv_a).clamp(0.0, 255.0) as u8;
1233                chunk[1] = (g * inv_a).clamp(0.0, 255.0) as u8;
1234                chunk[2] = (r * inv_a).clamp(0.0, 255.0) as u8;
1235            }
1236        }
1237
1238        Ok(rasterized)
1239    }
1240
1241    fn get_typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
1242        unsafe {
1243            let font = &self.fonts[font_id.0].font_face;
1244            let glyph_indices = [glyph_id.0 as u16];
1245            let mut metrics = [DWRITE_GLYPH_METRICS::default()];
1246            font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
1247
1248            let metrics = &metrics[0];
1249            let advance_width = metrics.advanceWidth as i32;
1250            let advance_height = metrics.advanceHeight as i32;
1251            let left_side_bearing = metrics.leftSideBearing;
1252            let right_side_bearing = metrics.rightSideBearing;
1253            let top_side_bearing = metrics.topSideBearing;
1254            let bottom_side_bearing = metrics.bottomSideBearing;
1255            let vertical_origin_y = metrics.verticalOriginY;
1256
1257            let y_offset = vertical_origin_y + bottom_side_bearing - advance_height;
1258            let width = advance_width - (left_side_bearing + right_side_bearing);
1259            let height = advance_height - (top_side_bearing + bottom_side_bearing);
1260
1261            Ok(Bounds {
1262                origin: Point {
1263                    x: left_side_bearing as f32,
1264                    y: y_offset as f32,
1265                },
1266                size: Size {
1267                    width: width as f32,
1268                    height: height as f32,
1269                },
1270            })
1271        }
1272    }
1273
1274    fn get_advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1275        unsafe {
1276            let font = &self.fonts[font_id.0].font_face;
1277            let glyph_indices = [glyph_id.0 as u16];
1278            let mut metrics = [DWRITE_GLYPH_METRICS::default()];
1279            font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
1280
1281            let metrics = &metrics[0];
1282
1283            Ok(Size {
1284                width: metrics.advanceWidth as f32,
1285                height: 0.0,
1286            })
1287        }
1288    }
1289
1290    fn all_font_names(&self) -> Vec<String> {
1291        let mut result =
1292            get_font_names_from_collection(&self.system_font_collection, &self.components.locale);
1293        result.extend(get_font_names_from_collection(
1294            &self.custom_font_collection,
1295            &self.components.locale,
1296        ));
1297        result
1298    }
1299
1300    fn handle_gpu_lost(&mut self, directx_devices: &DirectXDevices) -> Result<()> {
1301        try_to_recover_from_device_lost(|| {
1302            GPUState::new(directx_devices).context("Recreating GPU state for DirectWrite")
1303        })
1304        .map(|gpu_state| self.components.gpu_state = gpu_state)
1305    }
1306}
1307
1308impl Drop for DirectWriteState {
1309    fn drop(&mut self) {
1310        unsafe {
1311            let _ = self
1312                .components
1313                .factory
1314                .UnregisterFontFileLoader(&self.components.in_memory_loader);
1315        }
1316    }
1317}
1318
1319struct GlyphLayerTexture {
1320    run_color: Rgba,
1321    bounds: Bounds<i32>,
1322    texture_view: ID3D11ShaderResourceView,
1323    // holding on to the texture to not RAII drop it
1324    _texture: ID3D11Texture2D,
1325}
1326
1327impl GlyphLayerTexture {
1328    pub fn new(
1329        gpu_state: &GPUState,
1330        run_color: Rgba,
1331        bounds: Bounds<i32>,
1332        alpha_data: &[u8],
1333    ) -> Result<Self> {
1334        let texture_size = bounds.size;
1335
1336        let desc = D3D11_TEXTURE2D_DESC {
1337            Width: texture_size.width as u32,
1338            Height: texture_size.height as u32,
1339            MipLevels: 1,
1340            ArraySize: 1,
1341            Format: DXGI_FORMAT_R8_UNORM,
1342            SampleDesc: DXGI_SAMPLE_DESC {
1343                Count: 1,
1344                Quality: 0,
1345            },
1346            Usage: D3D11_USAGE_DEFAULT,
1347            BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32,
1348            CPUAccessFlags: 0,
1349            MiscFlags: 0,
1350        };
1351
1352        let texture = {
1353            let mut texture: Option<ID3D11Texture2D> = None;
1354            unsafe {
1355                gpu_state
1356                    .device
1357                    .CreateTexture2D(&desc, None, Some(&mut texture))?
1358            };
1359            texture.unwrap()
1360        };
1361        let texture_view = {
1362            let mut view: Option<ID3D11ShaderResourceView> = None;
1363            unsafe {
1364                gpu_state
1365                    .device
1366                    .CreateShaderResourceView(&texture, None, Some(&mut view))?
1367            };
1368            view.unwrap()
1369        };
1370
1371        unsafe {
1372            gpu_state.device_context.UpdateSubresource(
1373                &texture,
1374                0,
1375                None,
1376                alpha_data.as_ptr() as _,
1377                texture_size.width as u32,
1378                0,
1379            )
1380        };
1381
1382        Ok(GlyphLayerTexture {
1383            run_color,
1384            bounds,
1385            texture_view,
1386            _texture: texture,
1387        })
1388    }
1389}
1390
1391#[repr(C)]
1392struct GlyphLayerTextureParams {
1393    bounds: Bounds<i32>,
1394    run_color: Rgba,
1395    gamma_ratios: [f32; 4],
1396    grayscale_enhanced_contrast: f32,
1397    _pad: [f32; 3],
1398}
1399
1400struct TextRendererWrapper(pub IDWriteTextRenderer);
1401
1402impl TextRendererWrapper {
1403    pub fn new(locale_str: &str) -> Self {
1404        let inner = TextRenderer::new(locale_str);
1405        TextRendererWrapper(inner.into())
1406    }
1407}
1408
1409#[implement(IDWriteTextRenderer)]
1410struct TextRenderer {
1411    locale: String,
1412}
1413
1414impl TextRenderer {
1415    pub fn new(locale_str: &str) -> Self {
1416        TextRenderer {
1417            locale: locale_str.to_owned(),
1418        }
1419    }
1420}
1421
1422struct RendererContext<'t, 'a, 'b> {
1423    text_system: &'t mut DirectWriteState,
1424    index_converter: StringIndexConverter<'a>,
1425    runs: &'b mut Vec<ShapedRun>,
1426    width: f32,
1427}
1428
1429#[derive(Debug)]
1430struct ClusterAnalyzer<'t> {
1431    utf16_idx: usize,
1432    glyph_idx: usize,
1433    glyph_count: usize,
1434    cluster_map: &'t [u16],
1435}
1436
1437impl<'t> ClusterAnalyzer<'t> {
1438    pub fn new(cluster_map: &'t [u16], glyph_count: usize) -> Self {
1439        ClusterAnalyzer {
1440            utf16_idx: 0,
1441            glyph_idx: 0,
1442            glyph_count,
1443            cluster_map,
1444        }
1445    }
1446}
1447
1448impl Iterator for ClusterAnalyzer<'_> {
1449    type Item = (usize, usize);
1450
1451    fn next(&mut self) -> Option<(usize, usize)> {
1452        if self.utf16_idx >= self.cluster_map.len() {
1453            return None; // No more clusters
1454        }
1455        let start_utf16_idx = self.utf16_idx;
1456        let current_glyph = self.cluster_map[start_utf16_idx] as usize;
1457
1458        // Find the end of current cluster (where glyph index changes)
1459        let mut end_utf16_idx = start_utf16_idx + 1;
1460        while end_utf16_idx < self.cluster_map.len()
1461            && self.cluster_map[end_utf16_idx] as usize == current_glyph
1462        {
1463            end_utf16_idx += 1;
1464        }
1465
1466        let utf16_len = end_utf16_idx - start_utf16_idx;
1467
1468        // Calculate glyph count for this cluster
1469        let next_glyph = if end_utf16_idx < self.cluster_map.len() {
1470            self.cluster_map[end_utf16_idx] as usize
1471        } else {
1472            self.glyph_count
1473        };
1474
1475        let glyph_count = next_glyph - current_glyph;
1476
1477        // Update state for next call
1478        self.utf16_idx = end_utf16_idx;
1479        self.glyph_idx = next_glyph;
1480
1481        Some((utf16_len, glyph_count))
1482    }
1483}
1484
1485#[allow(non_snake_case)]
1486impl IDWritePixelSnapping_Impl for TextRenderer_Impl {
1487    fn IsPixelSnappingDisabled(
1488        &self,
1489        _clientdrawingcontext: *const ::core::ffi::c_void,
1490    ) -> windows::core::Result<BOOL> {
1491        Ok(BOOL(0))
1492    }
1493
1494    fn GetCurrentTransform(
1495        &self,
1496        _clientdrawingcontext: *const ::core::ffi::c_void,
1497        transform: *mut DWRITE_MATRIX,
1498    ) -> windows::core::Result<()> {
1499        unsafe {
1500            *transform = DWRITE_MATRIX {
1501                m11: 1.0,
1502                m12: 0.0,
1503                m21: 0.0,
1504                m22: 1.0,
1505                dx: 0.0,
1506                dy: 0.0,
1507            };
1508        }
1509        Ok(())
1510    }
1511
1512    fn GetPixelsPerDip(
1513        &self,
1514        _clientdrawingcontext: *const ::core::ffi::c_void,
1515    ) -> windows::core::Result<f32> {
1516        Ok(1.0)
1517    }
1518}
1519
1520#[allow(non_snake_case)]
1521impl IDWriteTextRenderer_Impl for TextRenderer_Impl {
1522    fn DrawGlyphRun(
1523        &self,
1524        clientdrawingcontext: *const ::core::ffi::c_void,
1525        _baselineoriginx: f32,
1526        _baselineoriginy: f32,
1527        _measuringmode: DWRITE_MEASURING_MODE,
1528        glyphrun: *const DWRITE_GLYPH_RUN,
1529        glyphrundescription: *const DWRITE_GLYPH_RUN_DESCRIPTION,
1530        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1531    ) -> windows::core::Result<()> {
1532        let glyphrun = unsafe { &*glyphrun };
1533        let glyph_count = glyphrun.glyphCount as usize;
1534        if glyph_count == 0 || glyphrun.fontFace.is_none() {
1535            return Ok(());
1536        }
1537        let desc = unsafe { &*glyphrundescription };
1538        let context = unsafe {
1539            &mut *(clientdrawingcontext as *const RendererContext as *mut RendererContext)
1540        };
1541        let font_face = glyphrun.fontFace.as_ref().unwrap();
1542        // This `cast()` action here should never fail since we are running on Win10+, and
1543        // `IDWriteFontFace3` requires Win10
1544        let font_face = &font_face.cast::<IDWriteFontFace3>().unwrap();
1545        let Some((font_identifier, font_struct, color_font)) =
1546            get_font_identifier_and_font_struct(font_face, &self.locale)
1547        else {
1548            return Ok(());
1549        };
1550
1551        let font_id = if let Some(id) = context
1552            .text_system
1553            .font_id_by_identifier
1554            .get(&font_identifier)
1555        {
1556            *id
1557        } else if let Some(id) = context.text_system.select_font(&font_struct) {
1558            id
1559        } else {
1560            return Err(Error::new(DWRITE_E_NOFONT, "Failed to select font"));
1561        };
1562
1563        let glyph_ids = unsafe { std::slice::from_raw_parts(glyphrun.glyphIndices, glyph_count) };
1564        let glyph_advances =
1565            unsafe { std::slice::from_raw_parts(glyphrun.glyphAdvances, glyph_count) };
1566        let glyph_offsets =
1567            unsafe { std::slice::from_raw_parts(glyphrun.glyphOffsets, glyph_count) };
1568        let cluster_map =
1569            unsafe { std::slice::from_raw_parts(desc.clusterMap, desc.stringLength as usize) };
1570
1571        let mut cluster_analyzer = ClusterAnalyzer::new(cluster_map, glyph_count);
1572        let mut utf16_idx = desc.textPosition as usize;
1573        let mut glyph_idx = 0;
1574        let mut glyphs = Vec::with_capacity(glyph_count);
1575        for (cluster_utf16_len, cluster_glyph_count) in cluster_analyzer {
1576            context.index_converter.advance_to_utf16_ix(utf16_idx);
1577            utf16_idx += cluster_utf16_len;
1578            for (cluster_glyph_idx, glyph_id) in glyph_ids
1579                [glyph_idx..(glyph_idx + cluster_glyph_count)]
1580                .iter()
1581                .enumerate()
1582            {
1583                let id = GlyphId(*glyph_id as u32);
1584                let is_emoji = color_font
1585                    && is_color_glyph(font_face, id, &context.text_system.components.factory);
1586                let this_glyph_idx = glyph_idx + cluster_glyph_idx;
1587                glyphs.push(ShapedGlyph {
1588                    id,
1589                    position: point(
1590                        px(context.width + glyph_offsets[this_glyph_idx].advanceOffset),
1591                        px(-glyph_offsets[this_glyph_idx].ascenderOffset),
1592                    ),
1593                    index: context.index_converter.utf8_ix,
1594                    is_emoji,
1595                });
1596                context.width += glyph_advances[this_glyph_idx];
1597            }
1598            glyph_idx += cluster_glyph_count;
1599        }
1600        context.runs.push(ShapedRun { font_id, glyphs });
1601        Ok(())
1602    }
1603
1604    fn DrawUnderline(
1605        &self,
1606        _clientdrawingcontext: *const ::core::ffi::c_void,
1607        _baselineoriginx: f32,
1608        _baselineoriginy: f32,
1609        _underline: *const DWRITE_UNDERLINE,
1610        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1611    ) -> windows::core::Result<()> {
1612        Err(windows::core::Error::new(
1613            E_NOTIMPL,
1614            "DrawUnderline unimplemented",
1615        ))
1616    }
1617
1618    fn DrawStrikethrough(
1619        &self,
1620        _clientdrawingcontext: *const ::core::ffi::c_void,
1621        _baselineoriginx: f32,
1622        _baselineoriginy: f32,
1623        _strikethrough: *const DWRITE_STRIKETHROUGH,
1624        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1625    ) -> windows::core::Result<()> {
1626        Err(windows::core::Error::new(
1627            E_NOTIMPL,
1628            "DrawStrikethrough unimplemented",
1629        ))
1630    }
1631
1632    fn DrawInlineObject(
1633        &self,
1634        _clientdrawingcontext: *const ::core::ffi::c_void,
1635        _originx: f32,
1636        _originy: f32,
1637        _inlineobject: windows::core::Ref<IDWriteInlineObject>,
1638        _issideways: BOOL,
1639        _isrighttoleft: BOOL,
1640        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1641    ) -> windows::core::Result<()> {
1642        Err(windows::core::Error::new(
1643            E_NOTIMPL,
1644            "DrawInlineObject unimplemented",
1645        ))
1646    }
1647}
1648
1649struct StringIndexConverter<'a> {
1650    text: &'a str,
1651    utf8_ix: usize,
1652    utf16_ix: usize,
1653}
1654
1655impl<'a> StringIndexConverter<'a> {
1656    fn new(text: &'a str) -> Self {
1657        Self {
1658            text,
1659            utf8_ix: 0,
1660            utf16_ix: 0,
1661        }
1662    }
1663
1664    #[allow(dead_code)]
1665    fn advance_to_utf8_ix(&mut self, utf8_target: usize) {
1666        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1667            if self.utf8_ix + ix >= utf8_target {
1668                self.utf8_ix += ix;
1669                return;
1670            }
1671            self.utf16_ix += c.len_utf16();
1672        }
1673        self.utf8_ix = self.text.len();
1674    }
1675
1676    fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
1677        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1678            if self.utf16_ix >= utf16_target {
1679                self.utf8_ix += ix;
1680                return;
1681            }
1682            self.utf16_ix += c.len_utf16();
1683        }
1684        self.utf8_ix = self.text.len();
1685    }
1686}
1687
1688impl Into<DWRITE_FONT_STYLE> for FontStyle {
1689    fn into(self) -> DWRITE_FONT_STYLE {
1690        match self {
1691            FontStyle::Normal => DWRITE_FONT_STYLE_NORMAL,
1692            FontStyle::Italic => DWRITE_FONT_STYLE_ITALIC,
1693            FontStyle::Oblique => DWRITE_FONT_STYLE_OBLIQUE,
1694        }
1695    }
1696}
1697
1698impl From<DWRITE_FONT_STYLE> for FontStyle {
1699    fn from(value: DWRITE_FONT_STYLE) -> Self {
1700        match value.0 {
1701            0 => FontStyle::Normal,
1702            1 => FontStyle::Italic,
1703            2 => FontStyle::Oblique,
1704            _ => unreachable!(),
1705        }
1706    }
1707}
1708
1709impl Into<DWRITE_FONT_WEIGHT> for FontWeight {
1710    fn into(self) -> DWRITE_FONT_WEIGHT {
1711        DWRITE_FONT_WEIGHT(self.0 as i32)
1712    }
1713}
1714
1715impl From<DWRITE_FONT_WEIGHT> for FontWeight {
1716    fn from(value: DWRITE_FONT_WEIGHT) -> Self {
1717        FontWeight(value.0 as f32)
1718    }
1719}
1720
1721fn get_font_names_from_collection(
1722    collection: &IDWriteFontCollection1,
1723    locale: &str,
1724) -> Vec<String> {
1725    unsafe {
1726        let mut result = Vec::new();
1727        let family_count = collection.GetFontFamilyCount();
1728        for index in 0..family_count {
1729            let Some(font_family) = collection.GetFontFamily(index).log_err() else {
1730                continue;
1731            };
1732            let Some(localized_family_name) = font_family.GetFamilyNames().log_err() else {
1733                continue;
1734            };
1735            let Some(family_name) = get_name(localized_family_name, locale).log_err() else {
1736                continue;
1737            };
1738            result.push(family_name);
1739        }
1740
1741        result
1742    }
1743}
1744
1745fn get_font_identifier_and_font_struct(
1746    font_face: &IDWriteFontFace3,
1747    locale: &str,
1748) -> Option<(FontIdentifier, Font, bool)> {
1749    let postscript_name = get_postscript_name(font_face, locale).log_err()?;
1750    let localized_family_name = unsafe { font_face.GetFamilyNames().log_err() }?;
1751    let family_name = get_name(localized_family_name, locale).log_err()?;
1752    let weight = unsafe { font_face.GetWeight() };
1753    let style = unsafe { font_face.GetStyle() };
1754    let identifier = FontIdentifier {
1755        postscript_name,
1756        weight: weight.0,
1757        style: style.0,
1758    };
1759    let font_struct = Font {
1760        family: family_name.into(),
1761        features: FontFeatures::default(),
1762        weight: weight.into(),
1763        style: style.into(),
1764        fallbacks: None,
1765    };
1766    let is_emoji = unsafe { font_face.IsColorFont().as_bool() };
1767    Some((identifier, font_struct, is_emoji))
1768}
1769
1770#[inline]
1771fn get_font_identifier(font_face: &IDWriteFontFace3, locale: &str) -> Option<FontIdentifier> {
1772    let weight = unsafe { font_face.GetWeight().0 };
1773    let style = unsafe { font_face.GetStyle().0 };
1774    get_postscript_name(font_face, locale)
1775        .log_err()
1776        .map(|postscript_name| FontIdentifier {
1777            postscript_name,
1778            weight,
1779            style,
1780        })
1781}
1782
1783#[inline]
1784fn get_postscript_name(font_face: &IDWriteFontFace3, locale: &str) -> Result<String> {
1785    let mut info = None;
1786    let mut exists = BOOL(0);
1787    unsafe {
1788        font_face.GetInformationalStrings(
1789            DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_NAME,
1790            &mut info,
1791            &mut exists,
1792        )?
1793    };
1794    if !exists.as_bool() || info.is_none() {
1795        anyhow::bail!("No postscript name found for font face");
1796    }
1797
1798    get_name(info.unwrap(), locale)
1799}
1800
1801// https://learn.microsoft.com/en-us/windows/win32/api/dwrite/ne-dwrite-dwrite_font_feature_tag
1802fn apply_font_features(
1803    direct_write_features: &IDWriteTypography,
1804    features: &FontFeatures,
1805) -> Result<()> {
1806    let tag_values = features.tag_value_list();
1807    if tag_values.is_empty() {
1808        return Ok(());
1809    }
1810
1811    // All of these features are enabled by default by DirectWrite.
1812    // If you want to (and can) peek into the source of DirectWrite
1813    let mut feature_liga = make_direct_write_feature("liga", 1);
1814    let mut feature_clig = make_direct_write_feature("clig", 1);
1815    let mut feature_calt = make_direct_write_feature("calt", 1);
1816
1817    for (tag, value) in tag_values {
1818        if tag.as_str() == "liga" && *value == 0 {
1819            feature_liga.parameter = 0;
1820            continue;
1821        }
1822        if tag.as_str() == "clig" && *value == 0 {
1823            feature_clig.parameter = 0;
1824            continue;
1825        }
1826        if tag.as_str() == "calt" && *value == 0 {
1827            feature_calt.parameter = 0;
1828            continue;
1829        }
1830
1831        unsafe {
1832            direct_write_features.AddFontFeature(make_direct_write_feature(tag, *value))?;
1833        }
1834    }
1835    unsafe {
1836        direct_write_features.AddFontFeature(feature_liga)?;
1837        direct_write_features.AddFontFeature(feature_clig)?;
1838        direct_write_features.AddFontFeature(feature_calt)?;
1839    }
1840
1841    Ok(())
1842}
1843
1844#[inline]
1845const fn make_direct_write_feature(feature_name: &str, parameter: u32) -> DWRITE_FONT_FEATURE {
1846    let tag = make_direct_write_tag(feature_name);
1847    DWRITE_FONT_FEATURE {
1848        nameTag: tag,
1849        parameter,
1850    }
1851}
1852
1853#[inline]
1854const fn make_open_type_tag(tag_name: &str) -> u32 {
1855    let bytes = tag_name.as_bytes();
1856    debug_assert!(bytes.len() == 4);
1857    u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
1858}
1859
1860#[inline]
1861const fn make_direct_write_tag(tag_name: &str) -> DWRITE_FONT_FEATURE_TAG {
1862    DWRITE_FONT_FEATURE_TAG(make_open_type_tag(tag_name))
1863}
1864
1865#[inline]
1866fn get_name(string: IDWriteLocalizedStrings, locale: &str) -> Result<String> {
1867    let mut locale_name_index = 0u32;
1868    let mut exists = BOOL(0);
1869    unsafe {
1870        string.FindLocaleName(
1871            &HSTRING::from(locale),
1872            &mut locale_name_index,
1873            &mut exists as _,
1874        )?
1875    };
1876    if !exists.as_bool() {
1877        unsafe {
1878            string.FindLocaleName(
1879                DEFAULT_LOCALE_NAME,
1880                &mut locale_name_index as _,
1881                &mut exists as _,
1882            )?
1883        };
1884        anyhow::ensure!(exists.as_bool(), "No localised string for {locale}");
1885    }
1886
1887    let name_length = unsafe { string.GetStringLength(locale_name_index) }? as usize;
1888    let mut name_vec = vec![0u16; name_length + 1];
1889    unsafe {
1890        string.GetString(locale_name_index, &mut name_vec)?;
1891    }
1892
1893    Ok(String::from_utf16_lossy(&name_vec[..name_length]))
1894}
1895
1896fn get_system_subpixel_rendering() -> bool {
1897    let mut value = c_uint::default();
1898    let result = unsafe {
1899        SystemParametersInfoW(
1900            SPI_GETFONTSMOOTHINGTYPE,
1901            0,
1902            Some((&mut value) as *mut c_uint as *mut c_void),
1903            SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS::default(),
1904        )
1905    };
1906    if result.log_err().is_some() {
1907        value == FE_FONTSMOOTHINGCLEARTYPE
1908    } else {
1909        true
1910    }
1911}
1912
1913fn get_system_ui_font_name() -> SharedString {
1914    unsafe {
1915        let mut info: LOGFONTW = std::mem::zeroed();
1916        let font_family = if SystemParametersInfoW(
1917            SPI_GETICONTITLELOGFONT,
1918            std::mem::size_of::<LOGFONTW>() as u32,
1919            Some(&mut info as *mut _ as _),
1920            SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
1921        )
1922        .log_err()
1923        .is_none()
1924        {
1925            // https://learn.microsoft.com/en-us/windows/win32/uxguide/vis-fonts
1926            // Segoe UI is the Windows font intended for user interface text strings.
1927            "Segoe UI".into()
1928        } else {
1929            let font_name = String::from_utf16_lossy(&info.lfFaceName);
1930            font_name.trim_matches(char::from(0)).to_owned().into()
1931        };
1932        log::info!("Use {} as UI font.", font_family);
1933        font_family
1934    }
1935}
1936
1937// One would think that with newer DirectWrite method: IDWriteFontFace4::GetGlyphImageFormats
1938// but that doesn't seem to work for some glyphs, say โค
1939fn is_color_glyph(
1940    font_face: &IDWriteFontFace3,
1941    glyph_id: GlyphId,
1942    factory: &IDWriteFactory5,
1943) -> bool {
1944    let glyph_run = DWRITE_GLYPH_RUN {
1945        fontFace: unsafe { std::mem::transmute_copy(font_face) },
1946        fontEmSize: 14.0,
1947        glyphCount: 1,
1948        glyphIndices: &(glyph_id.0 as u16),
1949        glyphAdvances: &0.0,
1950        glyphOffsets: &DWRITE_GLYPH_OFFSET {
1951            advanceOffset: 0.0,
1952            ascenderOffset: 0.0,
1953        },
1954        isSideways: BOOL(0),
1955        bidiLevel: 0,
1956    };
1957    unsafe {
1958        factory.TranslateColorGlyphRun(
1959            Vector2::default(),
1960            &glyph_run as _,
1961            None,
1962            DWRITE_GLYPH_IMAGE_FORMATS_COLR
1963                | DWRITE_GLYPH_IMAGE_FORMATS_SVG
1964                | DWRITE_GLYPH_IMAGE_FORMATS_PNG
1965                | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
1966                | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8,
1967            DWRITE_MEASURING_MODE_NATURAL,
1968            None,
1969            0,
1970        )
1971    }
1972    .is_ok()
1973}
1974
1975const DEFAULT_LOCALE_NAME: PCWSTR = windows::core::w!("en-US");
1976
1977#[cfg(test)]
1978mod tests {
1979    use crate::platform::windows::direct_write::ClusterAnalyzer;
1980
1981    #[test]
1982    fn test_cluster_map() {
1983        let cluster_map = [0];
1984        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 1);
1985        let next = analyzer.next();
1986        assert_eq!(next, Some((1, 1)));
1987        let next = analyzer.next();
1988        assert_eq!(next, None);
1989
1990        let cluster_map = [0, 1, 2];
1991        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 3);
1992        let next = analyzer.next();
1993        assert_eq!(next, Some((1, 1)));
1994        let next = analyzer.next();
1995        assert_eq!(next, Some((1, 1)));
1996        let next = analyzer.next();
1997        assert_eq!(next, Some((1, 1)));
1998        let next = analyzer.next();
1999        assert_eq!(next, None);
2000        // ๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ๐Ÿ‘ฉโ€๐Ÿ’ป
2001        let cluster_map = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4];
2002        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 5);
2003        let next = analyzer.next();
2004        assert_eq!(next, Some((11, 4)));
2005        let next = analyzer.next();
2006        assert_eq!(next, Some((5, 1)));
2007        let next = analyzer.next();
2008        assert_eq!(next, None);
2009        // ๐Ÿ‘ฉโ€๐Ÿ’ป
2010        let cluster_map = [0, 0, 0, 0, 0];
2011        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 1);
2012        let next = analyzer.next();
2013        assert_eq!(next, Some((5, 1)));
2014        let next = analyzer.next();
2015        assert_eq!(next, None);
2016    }
2017}