direct_write.rs

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