direct_write.rs

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