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