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