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