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 ascent = Pixels::default();
 610            let mut descent = Pixels::default();
 611            for run in font_runs {
 612                if first_run {
 613                    first_run = false;
 614                    let mut metrics = vec![DWRITE_LINE_METRICS::default(); 4];
 615                    let mut line_count = 0u32;
 616                    text_layout.GetLineMetrics(Some(&mut metrics), &mut line_count as _)?;
 617                    ascent = px(metrics[0].baseline);
 618                    descent = px(metrics[0].height - metrics[0].baseline);
 619                    continue;
 620                }
 621                let font_info = &self.fonts[run.font_id.0];
 622                let current_text = &text[utf8_offset..(utf8_offset + run.len)];
 623                utf8_offset += run.len;
 624                let current_text_utf16_length = current_text.encode_utf16().count() as u32;
 625
 626                let collection = if font_info.is_system_font {
 627                    &self.system_font_collection
 628                } else {
 629                    &self.custom_font_collection
 630                };
 631                let text_range = DWRITE_TEXT_RANGE {
 632                    startPosition: utf16_offset,
 633                    length: current_text_utf16_length,
 634                };
 635                utf16_offset += current_text_utf16_length;
 636                text_layout.SetFontCollection(collection, text_range)?;
 637                text_layout
 638                    .SetFontFamilyName(&HSTRING::from(&font_info.font_family), text_range)?;
 639                text_layout.SetFontSize(font_size.0, text_range)?;
 640                text_layout.SetFontStyle(font_info.font_face.GetStyle(), text_range)?;
 641                text_layout.SetFontWeight(font_info.font_face.GetWeight(), text_range)?;
 642                text_layout.SetTypography(&font_info.features, text_range)?;
 643            }
 644
 645            let mut runs = Vec::new();
 646            let renderer_context = RendererContext {
 647                text_system: self,
 648                index_converter: StringIndexConverter::new(text),
 649                runs: &mut runs,
 650                width: 0.0,
 651            };
 652            text_layout.Draw(
 653                Some(&renderer_context as *const _ as _),
 654                &text_renderer.0,
 655                0.0,
 656                0.0,
 657            )?;
 658            let width = px(renderer_context.width);
 659
 660            Ok(LineLayout {
 661                font_size,
 662                width,
 663                ascent,
 664                descent,
 665                runs,
 666                len: text.len(),
 667            })
 668        }
 669    }
 670
 671    fn font_metrics(&self, font_id: FontId) -> FontMetrics {
 672        unsafe {
 673            let font_info = &self.fonts[font_id.0];
 674            let mut metrics = std::mem::zeroed();
 675            font_info.font_face.GetMetrics(&mut metrics);
 676
 677            FontMetrics {
 678                units_per_em: metrics.Base.designUnitsPerEm as _,
 679                ascent: metrics.Base.ascent as _,
 680                descent: -(metrics.Base.descent as f32),
 681                line_gap: metrics.Base.lineGap as _,
 682                underline_position: metrics.Base.underlinePosition as _,
 683                underline_thickness: metrics.Base.underlineThickness as _,
 684                cap_height: metrics.Base.capHeight as _,
 685                x_height: metrics.Base.xHeight as _,
 686                bounding_box: Bounds {
 687                    origin: Point {
 688                        x: metrics.glyphBoxLeft as _,
 689                        y: metrics.glyphBoxBottom as _,
 690                    },
 691                    size: Size {
 692                        width: (metrics.glyphBoxRight - metrics.glyphBoxLeft) as _,
 693                        height: (metrics.glyphBoxTop - metrics.glyphBoxBottom) as _,
 694                    },
 695                },
 696            }
 697        }
 698    }
 699
 700    fn create_glyph_run_analysis(
 701        &self,
 702        params: &RenderGlyphParams,
 703    ) -> Result<IDWriteGlyphRunAnalysis> {
 704        let font = &self.fonts[params.font_id.0];
 705        let glyph_id = [params.glyph_id.0 as u16];
 706        let advance = [0.0];
 707        let offset = [DWRITE_GLYPH_OFFSET::default()];
 708        let glyph_run = DWRITE_GLYPH_RUN {
 709            fontFace: unsafe { std::mem::transmute_copy(&font.font_face) },
 710            fontEmSize: params.font_size.0,
 711            glyphCount: 1,
 712            glyphIndices: glyph_id.as_ptr(),
 713            glyphAdvances: advance.as_ptr(),
 714            glyphOffsets: offset.as_ptr(),
 715            isSideways: BOOL(0),
 716            bidiLevel: 0,
 717        };
 718        let transform = DWRITE_MATRIX {
 719            m11: params.scale_factor,
 720            m12: 0.0,
 721            m21: 0.0,
 722            m22: params.scale_factor,
 723            dx: 0.0,
 724            dy: 0.0,
 725        };
 726        let baseline_origin_x =
 727            params.subpixel_variant.x as f32 / SUBPIXEL_VARIANTS_X as f32 / params.scale_factor;
 728        let baseline_origin_y =
 729            params.subpixel_variant.y as f32 / SUBPIXEL_VARIANTS_Y as f32 / params.scale_factor;
 730
 731        let mut rendering_mode = DWRITE_RENDERING_MODE1::default();
 732        let mut grid_fit_mode = DWRITE_GRID_FIT_MODE::default();
 733        unsafe {
 734            font.font_face.GetRecommendedRenderingMode(
 735                params.font_size.0,
 736                // Using 96 as scale is applied by the transform
 737                96.0,
 738                96.0,
 739                Some(&transform),
 740                false,
 741                DWRITE_OUTLINE_THRESHOLD_ANTIALIASED,
 742                DWRITE_MEASURING_MODE_NATURAL,
 743                None,
 744                &mut rendering_mode,
 745                &mut grid_fit_mode,
 746            )?;
 747        }
 748        let rendering_mode = match rendering_mode {
 749            DWRITE_RENDERING_MODE1_OUTLINE => DWRITE_RENDERING_MODE1_NATURAL_SYMMETRIC,
 750            m => m,
 751        };
 752
 753        let glyph_analysis = unsafe {
 754            self.components.factory.CreateGlyphRunAnalysis(
 755                &glyph_run,
 756                Some(&transform),
 757                rendering_mode,
 758                DWRITE_MEASURING_MODE_NATURAL,
 759                grid_fit_mode,
 760                DWRITE_TEXT_ANTIALIAS_MODE_GRAYSCALE,
 761                baseline_origin_x,
 762                baseline_origin_y,
 763            )
 764        }?;
 765        Ok(glyph_analysis)
 766    }
 767
 768    fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
 769        let glyph_analysis = self.create_glyph_run_analysis(params)?;
 770
 771        let bounds = unsafe { glyph_analysis.GetAlphaTextureBounds(DWRITE_TEXTURE_ALIASED_1x1)? };
 772
 773        if bounds.right < bounds.left {
 774            Ok(Bounds {
 775                origin: point(0.into(), 0.into()),
 776                size: size(0.into(), 0.into()),
 777            })
 778        } else {
 779            Ok(Bounds {
 780                origin: point(bounds.left.into(), bounds.top.into()),
 781                size: size(
 782                    (bounds.right - bounds.left).into(),
 783                    (bounds.bottom - bounds.top).into(),
 784                ),
 785            })
 786        }
 787    }
 788
 789    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
 790        let font_info = &self.fonts[font_id.0];
 791        let codepoints = [ch as u32];
 792        let mut glyph_indices = vec![0u16; 1];
 793        unsafe {
 794            font_info
 795                .font_face
 796                .GetGlyphIndices(codepoints.as_ptr(), 1, glyph_indices.as_mut_ptr())
 797                .log_err()
 798        }
 799        .map(|_| GlyphId(glyph_indices[0] as u32))
 800    }
 801
 802    fn rasterize_glyph(
 803        &self,
 804        params: &RenderGlyphParams,
 805        glyph_bounds: Bounds<DevicePixels>,
 806    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
 807        if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
 808            anyhow::bail!("glyph bounds are empty");
 809        }
 810
 811        let bitmap_data = if params.is_emoji {
 812            if let Ok(color) = self.rasterize_color(params, glyph_bounds) {
 813                color
 814            } else {
 815                let monochrome = self.rasterize_monochrome(params, glyph_bounds)?;
 816                monochrome
 817                    .into_iter()
 818                    .flat_map(|pixel| [0, 0, 0, pixel])
 819                    .collect::<Vec<_>>()
 820            }
 821        } else {
 822            self.rasterize_monochrome(params, glyph_bounds)?
 823        };
 824
 825        Ok((glyph_bounds.size, bitmap_data))
 826    }
 827
 828    fn rasterize_monochrome(
 829        &self,
 830        params: &RenderGlyphParams,
 831        glyph_bounds: Bounds<DevicePixels>,
 832    ) -> Result<Vec<u8>> {
 833        let mut bitmap_data =
 834            vec![0u8; glyph_bounds.size.width.0 as usize * glyph_bounds.size.height.0 as usize];
 835
 836        let glyph_analysis = self.create_glyph_run_analysis(params)?;
 837        unsafe {
 838            glyph_analysis.CreateAlphaTexture(
 839                DWRITE_TEXTURE_ALIASED_1x1,
 840                &RECT {
 841                    left: glyph_bounds.origin.x.0,
 842                    top: glyph_bounds.origin.y.0,
 843                    right: glyph_bounds.size.width.0 + glyph_bounds.origin.x.0,
 844                    bottom: glyph_bounds.size.height.0 + glyph_bounds.origin.y.0,
 845                },
 846                &mut bitmap_data,
 847            )?;
 848        }
 849
 850        Ok(bitmap_data)
 851    }
 852
 853    fn rasterize_color(
 854        &self,
 855        params: &RenderGlyphParams,
 856        glyph_bounds: Bounds<DevicePixels>,
 857    ) -> Result<Vec<u8>> {
 858        let bitmap_size = glyph_bounds.size;
 859        let subpixel_shift = params
 860            .subpixel_variant
 861            .map(|v| v as f32 / SUBPIXEL_VARIANTS_X as f32);
 862        let baseline_origin_x = subpixel_shift.x / params.scale_factor;
 863        let baseline_origin_y = subpixel_shift.y / params.scale_factor;
 864
 865        let transform = DWRITE_MATRIX {
 866            m11: params.scale_factor,
 867            m12: 0.0,
 868            m21: 0.0,
 869            m22: params.scale_factor,
 870            dx: 0.0,
 871            dy: 0.0,
 872        };
 873
 874        let font = &self.fonts[params.font_id.0];
 875        let glyph_id = [params.glyph_id.0 as u16];
 876        let advance = [glyph_bounds.size.width.0 as f32];
 877        let offset = [DWRITE_GLYPH_OFFSET {
 878            advanceOffset: -glyph_bounds.origin.x.0 as f32 / params.scale_factor,
 879            ascenderOffset: glyph_bounds.origin.y.0 as f32 / params.scale_factor,
 880        }];
 881        let glyph_run = DWRITE_GLYPH_RUN {
 882            fontFace: unsafe { std::mem::transmute_copy(&font.font_face) },
 883            fontEmSize: params.font_size.0,
 884            glyphCount: 1,
 885            glyphIndices: glyph_id.as_ptr(),
 886            glyphAdvances: advance.as_ptr(),
 887            glyphOffsets: offset.as_ptr(),
 888            isSideways: BOOL(0),
 889            bidiLevel: 0,
 890        };
 891
 892        // todo: support formats other than COLR
 893        let color_enumerator = unsafe {
 894            self.components.factory.TranslateColorGlyphRun(
 895                Vector2::new(baseline_origin_x, baseline_origin_y),
 896                &glyph_run,
 897                None,
 898                DWRITE_GLYPH_IMAGE_FORMATS_COLR,
 899                DWRITE_MEASURING_MODE_NATURAL,
 900                Some(&transform),
 901                0,
 902            )
 903        }?;
 904
 905        let mut glyph_layers = Vec::new();
 906        loop {
 907            let color_run = unsafe { color_enumerator.GetCurrentRun() }?;
 908            let color_run = unsafe { &*color_run };
 909            let image_format = color_run.glyphImageFormat & !DWRITE_GLYPH_IMAGE_FORMATS_TRUETYPE;
 910            if image_format == DWRITE_GLYPH_IMAGE_FORMATS_COLR {
 911                let color_analysis = unsafe {
 912                    self.components.factory.CreateGlyphRunAnalysis(
 913                        &color_run.Base.glyphRun as *const _,
 914                        Some(&transform),
 915                        DWRITE_RENDERING_MODE1_NATURAL_SYMMETRIC,
 916                        DWRITE_MEASURING_MODE_NATURAL,
 917                        DWRITE_GRID_FIT_MODE_DEFAULT,
 918                        DWRITE_TEXT_ANTIALIAS_MODE_GRAYSCALE,
 919                        baseline_origin_x,
 920                        baseline_origin_y,
 921                    )
 922                }?;
 923
 924                let color_bounds =
 925                    unsafe { color_analysis.GetAlphaTextureBounds(DWRITE_TEXTURE_ALIASED_1x1) }?;
 926
 927                let color_size = size(
 928                    color_bounds.right - color_bounds.left,
 929                    color_bounds.bottom - color_bounds.top,
 930                );
 931                if color_size.width > 0 && color_size.height > 0 {
 932                    let mut alpha_data = vec![0u8; (color_size.width * color_size.height) as usize];
 933                    unsafe {
 934                        color_analysis.CreateAlphaTexture(
 935                            DWRITE_TEXTURE_ALIASED_1x1,
 936                            &color_bounds,
 937                            &mut alpha_data,
 938                        )
 939                    }?;
 940
 941                    let run_color = {
 942                        let run_color = color_run.Base.runColor;
 943                        Rgba {
 944                            r: run_color.r,
 945                            g: run_color.g,
 946                            b: run_color.b,
 947                            a: run_color.a,
 948                        }
 949                    };
 950                    let bounds = bounds(point(color_bounds.left, color_bounds.top), color_size);
 951                    glyph_layers.push(GlyphLayerTexture::new(
 952                        &self.components.gpu_state,
 953                        run_color,
 954                        bounds,
 955                        &alpha_data,
 956                    )?);
 957                }
 958            }
 959
 960            let has_next = unsafe { color_enumerator.MoveNext() }
 961                .map(|e| e.as_bool())
 962                .unwrap_or(false);
 963            if !has_next {
 964                break;
 965            }
 966        }
 967
 968        let gpu_state = &self.components.gpu_state;
 969        let params_buffer = {
 970            let desc = D3D11_BUFFER_DESC {
 971                ByteWidth: std::mem::size_of::<GlyphLayerTextureParams>() as u32,
 972                Usage: D3D11_USAGE_DYNAMIC,
 973                BindFlags: D3D11_BIND_CONSTANT_BUFFER.0 as u32,
 974                CPUAccessFlags: D3D11_CPU_ACCESS_WRITE.0 as u32,
 975                MiscFlags: 0,
 976                StructureByteStride: 0,
 977            };
 978
 979            let mut buffer = None;
 980            unsafe {
 981                gpu_state
 982                    .device
 983                    .CreateBuffer(&desc, None, Some(&mut buffer))
 984            }?;
 985            [buffer]
 986        };
 987
 988        let render_target_texture = {
 989            let mut texture = None;
 990            let desc = D3D11_TEXTURE2D_DESC {
 991                Width: bitmap_size.width.0 as u32,
 992                Height: bitmap_size.height.0 as u32,
 993                MipLevels: 1,
 994                ArraySize: 1,
 995                Format: DXGI_FORMAT_B8G8R8A8_UNORM,
 996                SampleDesc: DXGI_SAMPLE_DESC {
 997                    Count: 1,
 998                    Quality: 0,
 999                },
1000                Usage: D3D11_USAGE_DEFAULT,
1001                BindFlags: D3D11_BIND_RENDER_TARGET.0 as u32,
1002                CPUAccessFlags: 0,
1003                MiscFlags: 0,
1004            };
1005            unsafe {
1006                gpu_state
1007                    .device
1008                    .CreateTexture2D(&desc, None, Some(&mut texture))
1009            }?;
1010            texture.unwrap()
1011        };
1012
1013        let render_target_view = {
1014            let desc = D3D11_RENDER_TARGET_VIEW_DESC {
1015                Format: DXGI_FORMAT_B8G8R8A8_UNORM,
1016                ViewDimension: D3D11_RTV_DIMENSION_TEXTURE2D,
1017                Anonymous: D3D11_RENDER_TARGET_VIEW_DESC_0 {
1018                    Texture2D: D3D11_TEX2D_RTV { MipSlice: 0 },
1019                },
1020            };
1021            let mut rtv = None;
1022            unsafe {
1023                gpu_state.device.CreateRenderTargetView(
1024                    &render_target_texture,
1025                    Some(&desc),
1026                    Some(&mut rtv),
1027                )
1028            }?;
1029            [rtv]
1030        };
1031
1032        let staging_texture = {
1033            let mut texture = None;
1034            let desc = D3D11_TEXTURE2D_DESC {
1035                Width: bitmap_size.width.0 as u32,
1036                Height: bitmap_size.height.0 as u32,
1037                MipLevels: 1,
1038                ArraySize: 1,
1039                Format: DXGI_FORMAT_B8G8R8A8_UNORM,
1040                SampleDesc: DXGI_SAMPLE_DESC {
1041                    Count: 1,
1042                    Quality: 0,
1043                },
1044                Usage: D3D11_USAGE_STAGING,
1045                BindFlags: 0,
1046                CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32,
1047                MiscFlags: 0,
1048            };
1049            unsafe {
1050                gpu_state
1051                    .device
1052                    .CreateTexture2D(&desc, None, Some(&mut texture))
1053            }?;
1054            texture.unwrap()
1055        };
1056
1057        let device_context = &gpu_state.device_context;
1058        unsafe { device_context.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP) };
1059        unsafe { device_context.VSSetShader(&gpu_state.vertex_shader, None) };
1060        unsafe { device_context.PSSetShader(&gpu_state.pixel_shader, None) };
1061        unsafe { device_context.VSSetConstantBuffers(0, Some(&params_buffer)) };
1062        unsafe { device_context.PSSetConstantBuffers(0, Some(&params_buffer)) };
1063        unsafe { device_context.OMSetRenderTargets(Some(&render_target_view), None) };
1064        unsafe { device_context.PSSetSamplers(0, Some(&gpu_state.sampler)) };
1065        unsafe { device_context.OMSetBlendState(&gpu_state.blend_state, None, 0xffffffff) };
1066
1067        let crate::FontInfo {
1068            gamma_ratios,
1069            grayscale_enhanced_contrast,
1070        } = DirectXRenderer::get_font_info();
1071
1072        for layer in glyph_layers {
1073            let params = GlyphLayerTextureParams {
1074                run_color: layer.run_color,
1075                bounds: layer.bounds,
1076                gamma_ratios: *gamma_ratios,
1077                grayscale_enhanced_contrast: *grayscale_enhanced_contrast,
1078                _pad: [0f32; 3],
1079            };
1080            unsafe {
1081                let mut dest = std::mem::zeroed();
1082                gpu_state.device_context.Map(
1083                    params_buffer[0].as_ref().unwrap(),
1084                    0,
1085                    D3D11_MAP_WRITE_DISCARD,
1086                    0,
1087                    Some(&mut dest),
1088                )?;
1089                std::ptr::copy_nonoverlapping(&params as *const _, dest.pData as *mut _, 1);
1090                gpu_state
1091                    .device_context
1092                    .Unmap(params_buffer[0].as_ref().unwrap(), 0);
1093            };
1094
1095            let texture = [Some(layer.texture_view)];
1096            unsafe { device_context.PSSetShaderResources(0, Some(&texture)) };
1097
1098            let viewport = [D3D11_VIEWPORT {
1099                TopLeftX: layer.bounds.origin.x as f32,
1100                TopLeftY: layer.bounds.origin.y as f32,
1101                Width: layer.bounds.size.width as f32,
1102                Height: layer.bounds.size.height as f32,
1103                MinDepth: 0.0,
1104                MaxDepth: 1.0,
1105            }];
1106            unsafe { device_context.RSSetViewports(Some(&viewport)) };
1107
1108            unsafe { device_context.Draw(4, 0) };
1109        }
1110
1111        unsafe { device_context.CopyResource(&staging_texture, &render_target_texture) };
1112
1113        let mapped_data = {
1114            let mut mapped_data = D3D11_MAPPED_SUBRESOURCE::default();
1115            unsafe {
1116                device_context.Map(
1117                    &staging_texture,
1118                    0,
1119                    D3D11_MAP_READ,
1120                    0,
1121                    Some(&mut mapped_data),
1122                )
1123            }?;
1124            mapped_data
1125        };
1126        let mut rasterized =
1127            vec![0u8; (bitmap_size.width.0 as u32 * bitmap_size.height.0 as u32 * 4) as usize];
1128
1129        for y in 0..bitmap_size.height.0 as usize {
1130            let width = bitmap_size.width.0 as usize;
1131            unsafe {
1132                std::ptr::copy_nonoverlapping::<u8>(
1133                    (mapped_data.pData as *const u8).byte_add(mapped_data.RowPitch as usize * y),
1134                    rasterized
1135                        .as_mut_ptr()
1136                        .byte_add(width * y * std::mem::size_of::<u32>()),
1137                    width * std::mem::size_of::<u32>(),
1138                )
1139            };
1140        }
1141
1142        // Convert from premultiplied to straight alpha
1143        for chunk in rasterized.chunks_exact_mut(4) {
1144            let b = chunk[0] as f32;
1145            let g = chunk[1] as f32;
1146            let r = chunk[2] as f32;
1147            let a = chunk[3] as f32;
1148            if a > 0.0 {
1149                let inv_a = 255.0 / a;
1150                chunk[0] = (b * inv_a).clamp(0.0, 255.0) as u8;
1151                chunk[1] = (g * inv_a).clamp(0.0, 255.0) as u8;
1152                chunk[2] = (r * inv_a).clamp(0.0, 255.0) as u8;
1153            }
1154        }
1155
1156        Ok(rasterized)
1157    }
1158
1159    fn get_typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
1160        unsafe {
1161            let font = &self.fonts[font_id.0].font_face;
1162            let glyph_indices = [glyph_id.0 as u16];
1163            let mut metrics = [DWRITE_GLYPH_METRICS::default()];
1164            font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
1165
1166            let metrics = &metrics[0];
1167            let advance_width = metrics.advanceWidth as i32;
1168            let advance_height = metrics.advanceHeight as i32;
1169            let left_side_bearing = metrics.leftSideBearing;
1170            let right_side_bearing = metrics.rightSideBearing;
1171            let top_side_bearing = metrics.topSideBearing;
1172            let bottom_side_bearing = metrics.bottomSideBearing;
1173            let vertical_origin_y = metrics.verticalOriginY;
1174
1175            let y_offset = vertical_origin_y + bottom_side_bearing - advance_height;
1176            let width = advance_width - (left_side_bearing + right_side_bearing);
1177            let height = advance_height - (top_side_bearing + bottom_side_bearing);
1178
1179            Ok(Bounds {
1180                origin: Point {
1181                    x: left_side_bearing as f32,
1182                    y: y_offset as f32,
1183                },
1184                size: Size {
1185                    width: width as f32,
1186                    height: height as f32,
1187                },
1188            })
1189        }
1190    }
1191
1192    fn get_advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1193        unsafe {
1194            let font = &self.fonts[font_id.0].font_face;
1195            let glyph_indices = [glyph_id.0 as u16];
1196            let mut metrics = [DWRITE_GLYPH_METRICS::default()];
1197            font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
1198
1199            let metrics = &metrics[0];
1200
1201            Ok(Size {
1202                width: metrics.advanceWidth as f32,
1203                height: 0.0,
1204            })
1205        }
1206    }
1207
1208    fn all_font_names(&self) -> Vec<String> {
1209        let mut result =
1210            get_font_names_from_collection(&self.system_font_collection, &self.components.locale);
1211        result.extend(get_font_names_from_collection(
1212            &self.custom_font_collection,
1213            &self.components.locale,
1214        ));
1215        result
1216    }
1217
1218    fn handle_gpu_lost(&mut self, directx_devices: &DirectXDevices) {
1219        try_to_recover_from_device_lost(
1220            || GPUState::new(directx_devices).context("Recreating GPU state for DirectWrite"),
1221            |gpu_state| self.components.gpu_state = gpu_state,
1222            || {
1223                log::error!(
1224                    "Failed to recreate GPU state for DirectWrite after multiple attempts."
1225                );
1226                // Do something here?
1227                // At this point, the device loss is considered unrecoverable.
1228            },
1229        );
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_view: ID3D11ShaderResourceView,
1248    // holding on to the texture to not RAII drop it
1249    _texture: ID3D11Texture2D,
1250}
1251
1252impl GlyphLayerTexture {
1253    pub fn new(
1254        gpu_state: &GPUState,
1255        run_color: Rgba,
1256        bounds: Bounds<i32>,
1257        alpha_data: &[u8],
1258    ) -> Result<Self> {
1259        let texture_size = bounds.size;
1260
1261        let desc = D3D11_TEXTURE2D_DESC {
1262            Width: texture_size.width as u32,
1263            Height: texture_size.height as u32,
1264            MipLevels: 1,
1265            ArraySize: 1,
1266            Format: DXGI_FORMAT_R8_UNORM,
1267            SampleDesc: DXGI_SAMPLE_DESC {
1268                Count: 1,
1269                Quality: 0,
1270            },
1271            Usage: D3D11_USAGE_DEFAULT,
1272            BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32,
1273            CPUAccessFlags: 0,
1274            MiscFlags: 0,
1275        };
1276
1277        let texture = {
1278            let mut texture: Option<ID3D11Texture2D> = None;
1279            unsafe {
1280                gpu_state
1281                    .device
1282                    .CreateTexture2D(&desc, None, Some(&mut texture))?
1283            };
1284            texture.unwrap()
1285        };
1286        let texture_view = {
1287            let mut view: Option<ID3D11ShaderResourceView> = None;
1288            unsafe {
1289                gpu_state
1290                    .device
1291                    .CreateShaderResourceView(&texture, None, Some(&mut view))?
1292            };
1293            view.unwrap()
1294        };
1295
1296        unsafe {
1297            gpu_state.device_context.UpdateSubresource(
1298                &texture,
1299                0,
1300                None,
1301                alpha_data.as_ptr() as _,
1302                texture_size.width as u32,
1303                0,
1304            )
1305        };
1306
1307        Ok(GlyphLayerTexture {
1308            run_color,
1309            bounds,
1310            texture_view,
1311            _texture: texture,
1312        })
1313    }
1314}
1315
1316#[repr(C)]
1317struct GlyphLayerTextureParams {
1318    bounds: Bounds<i32>,
1319    run_color: Rgba,
1320    gamma_ratios: [f32; 4],
1321    grayscale_enhanced_contrast: f32,
1322    _pad: [f32; 3],
1323}
1324
1325struct TextRendererWrapper(pub IDWriteTextRenderer);
1326
1327impl TextRendererWrapper {
1328    pub fn new(locale_str: &str) -> Self {
1329        let inner = TextRenderer::new(locale_str);
1330        TextRendererWrapper(inner.into())
1331    }
1332}
1333
1334#[implement(IDWriteTextRenderer)]
1335struct TextRenderer {
1336    locale: String,
1337}
1338
1339impl TextRenderer {
1340    pub fn new(locale_str: &str) -> Self {
1341        TextRenderer {
1342            locale: locale_str.to_owned(),
1343        }
1344    }
1345}
1346
1347struct RendererContext<'t, 'a, 'b> {
1348    text_system: &'t mut DirectWriteState,
1349    index_converter: StringIndexConverter<'a>,
1350    runs: &'b mut Vec<ShapedRun>,
1351    width: f32,
1352}
1353
1354#[derive(Debug)]
1355struct ClusterAnalyzer<'t> {
1356    utf16_idx: usize,
1357    glyph_idx: usize,
1358    glyph_count: usize,
1359    cluster_map: &'t [u16],
1360}
1361
1362impl<'t> ClusterAnalyzer<'t> {
1363    pub fn new(cluster_map: &'t [u16], glyph_count: usize) -> Self {
1364        ClusterAnalyzer {
1365            utf16_idx: 0,
1366            glyph_idx: 0,
1367            glyph_count,
1368            cluster_map,
1369        }
1370    }
1371}
1372
1373impl Iterator for ClusterAnalyzer<'_> {
1374    type Item = (usize, usize);
1375
1376    fn next(&mut self) -> Option<(usize, usize)> {
1377        if self.utf16_idx >= self.cluster_map.len() {
1378            return None; // No more clusters
1379        }
1380        let start_utf16_idx = self.utf16_idx;
1381        let current_glyph = self.cluster_map[start_utf16_idx] as usize;
1382
1383        // Find the end of current cluster (where glyph index changes)
1384        let mut end_utf16_idx = start_utf16_idx + 1;
1385        while end_utf16_idx < self.cluster_map.len()
1386            && self.cluster_map[end_utf16_idx] as usize == current_glyph
1387        {
1388            end_utf16_idx += 1;
1389        }
1390
1391        let utf16_len = end_utf16_idx - start_utf16_idx;
1392
1393        // Calculate glyph count for this cluster
1394        let next_glyph = if end_utf16_idx < self.cluster_map.len() {
1395            self.cluster_map[end_utf16_idx] as usize
1396        } else {
1397            self.glyph_count
1398        };
1399
1400        let glyph_count = next_glyph - current_glyph;
1401
1402        // Update state for next call
1403        self.utf16_idx = end_utf16_idx;
1404        self.glyph_idx = next_glyph;
1405
1406        Some((utf16_len, glyph_count))
1407    }
1408}
1409
1410#[allow(non_snake_case)]
1411impl IDWritePixelSnapping_Impl for TextRenderer_Impl {
1412    fn IsPixelSnappingDisabled(
1413        &self,
1414        _clientdrawingcontext: *const ::core::ffi::c_void,
1415    ) -> windows::core::Result<BOOL> {
1416        Ok(BOOL(0))
1417    }
1418
1419    fn GetCurrentTransform(
1420        &self,
1421        _clientdrawingcontext: *const ::core::ffi::c_void,
1422        transform: *mut DWRITE_MATRIX,
1423    ) -> windows::core::Result<()> {
1424        unsafe {
1425            *transform = DWRITE_MATRIX {
1426                m11: 1.0,
1427                m12: 0.0,
1428                m21: 0.0,
1429                m22: 1.0,
1430                dx: 0.0,
1431                dy: 0.0,
1432            };
1433        }
1434        Ok(())
1435    }
1436
1437    fn GetPixelsPerDip(
1438        &self,
1439        _clientdrawingcontext: *const ::core::ffi::c_void,
1440    ) -> windows::core::Result<f32> {
1441        Ok(1.0)
1442    }
1443}
1444
1445#[allow(non_snake_case)]
1446impl IDWriteTextRenderer_Impl for TextRenderer_Impl {
1447    fn DrawGlyphRun(
1448        &self,
1449        clientdrawingcontext: *const ::core::ffi::c_void,
1450        _baselineoriginx: f32,
1451        _baselineoriginy: f32,
1452        _measuringmode: DWRITE_MEASURING_MODE,
1453        glyphrun: *const DWRITE_GLYPH_RUN,
1454        glyphrundescription: *const DWRITE_GLYPH_RUN_DESCRIPTION,
1455        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1456    ) -> windows::core::Result<()> {
1457        let glyphrun = unsafe { &*glyphrun };
1458        let glyph_count = glyphrun.glyphCount as usize;
1459        if glyph_count == 0 || glyphrun.fontFace.is_none() {
1460            return Ok(());
1461        }
1462        let desc = unsafe { &*glyphrundescription };
1463        let context = unsafe {
1464            &mut *(clientdrawingcontext as *const RendererContext as *mut RendererContext)
1465        };
1466        let font_face = glyphrun.fontFace.as_ref().unwrap();
1467        // This `cast()` action here should never fail since we are running on Win10+, and
1468        // `IDWriteFontFace3` requires Win10
1469        let font_face = &font_face.cast::<IDWriteFontFace3>().unwrap();
1470        let Some((font_identifier, font_struct, color_font)) =
1471            get_font_identifier_and_font_struct(font_face, &self.locale)
1472        else {
1473            return Ok(());
1474        };
1475
1476        let font_id = if let Some(id) = context
1477            .text_system
1478            .font_id_by_identifier
1479            .get(&font_identifier)
1480        {
1481            *id
1482        } else {
1483            context.text_system.select_font(&font_struct)
1484        };
1485
1486        let glyph_ids = unsafe { std::slice::from_raw_parts(glyphrun.glyphIndices, glyph_count) };
1487        let glyph_advances =
1488            unsafe { std::slice::from_raw_parts(glyphrun.glyphAdvances, glyph_count) };
1489        let glyph_offsets =
1490            unsafe { std::slice::from_raw_parts(glyphrun.glyphOffsets, glyph_count) };
1491        let cluster_map =
1492            unsafe { std::slice::from_raw_parts(desc.clusterMap, desc.stringLength as usize) };
1493
1494        let mut cluster_analyzer = ClusterAnalyzer::new(cluster_map, glyph_count);
1495        let mut utf16_idx = desc.textPosition as usize;
1496        let mut glyph_idx = 0;
1497        let mut glyphs = Vec::with_capacity(glyph_count);
1498        for (cluster_utf16_len, cluster_glyph_count) in cluster_analyzer {
1499            context.index_converter.advance_to_utf16_ix(utf16_idx);
1500            utf16_idx += cluster_utf16_len;
1501            for (cluster_glyph_idx, glyph_id) in glyph_ids
1502                [glyph_idx..(glyph_idx + cluster_glyph_count)]
1503                .iter()
1504                .enumerate()
1505            {
1506                let id = GlyphId(*glyph_id as u32);
1507                let is_emoji = color_font
1508                    && is_color_glyph(font_face, id, &context.text_system.components.factory);
1509                let this_glyph_idx = glyph_idx + cluster_glyph_idx;
1510                glyphs.push(ShapedGlyph {
1511                    id,
1512                    position: point(
1513                        px(context.width + glyph_offsets[this_glyph_idx].advanceOffset),
1514                        px(0.0),
1515                    ),
1516                    index: context.index_converter.utf8_ix,
1517                    is_emoji,
1518                });
1519                context.width += glyph_advances[this_glyph_idx];
1520            }
1521            glyph_idx += cluster_glyph_count;
1522        }
1523        context.runs.push(ShapedRun { font_id, glyphs });
1524        Ok(())
1525    }
1526
1527    fn DrawUnderline(
1528        &self,
1529        _clientdrawingcontext: *const ::core::ffi::c_void,
1530        _baselineoriginx: f32,
1531        _baselineoriginy: f32,
1532        _underline: *const DWRITE_UNDERLINE,
1533        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1534    ) -> windows::core::Result<()> {
1535        Err(windows::core::Error::new(
1536            E_NOTIMPL,
1537            "DrawUnderline unimplemented",
1538        ))
1539    }
1540
1541    fn DrawStrikethrough(
1542        &self,
1543        _clientdrawingcontext: *const ::core::ffi::c_void,
1544        _baselineoriginx: f32,
1545        _baselineoriginy: f32,
1546        _strikethrough: *const DWRITE_STRIKETHROUGH,
1547        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1548    ) -> windows::core::Result<()> {
1549        Err(windows::core::Error::new(
1550            E_NOTIMPL,
1551            "DrawStrikethrough unimplemented",
1552        ))
1553    }
1554
1555    fn DrawInlineObject(
1556        &self,
1557        _clientdrawingcontext: *const ::core::ffi::c_void,
1558        _originx: f32,
1559        _originy: f32,
1560        _inlineobject: windows::core::Ref<IDWriteInlineObject>,
1561        _issideways: BOOL,
1562        _isrighttoleft: BOOL,
1563        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1564    ) -> windows::core::Result<()> {
1565        Err(windows::core::Error::new(
1566            E_NOTIMPL,
1567            "DrawInlineObject unimplemented",
1568        ))
1569    }
1570}
1571
1572struct StringIndexConverter<'a> {
1573    text: &'a str,
1574    utf8_ix: usize,
1575    utf16_ix: usize,
1576}
1577
1578impl<'a> StringIndexConverter<'a> {
1579    fn new(text: &'a str) -> Self {
1580        Self {
1581            text,
1582            utf8_ix: 0,
1583            utf16_ix: 0,
1584        }
1585    }
1586
1587    #[allow(dead_code)]
1588    fn advance_to_utf8_ix(&mut self, utf8_target: usize) {
1589        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1590            if self.utf8_ix + ix >= utf8_target {
1591                self.utf8_ix += ix;
1592                return;
1593            }
1594            self.utf16_ix += c.len_utf16();
1595        }
1596        self.utf8_ix = self.text.len();
1597    }
1598
1599    fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
1600        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1601            if self.utf16_ix >= utf16_target {
1602                self.utf8_ix += ix;
1603                return;
1604            }
1605            self.utf16_ix += c.len_utf16();
1606        }
1607        self.utf8_ix = self.text.len();
1608    }
1609}
1610
1611impl Into<DWRITE_FONT_STYLE> for FontStyle {
1612    fn into(self) -> DWRITE_FONT_STYLE {
1613        match self {
1614            FontStyle::Normal => DWRITE_FONT_STYLE_NORMAL,
1615            FontStyle::Italic => DWRITE_FONT_STYLE_ITALIC,
1616            FontStyle::Oblique => DWRITE_FONT_STYLE_OBLIQUE,
1617        }
1618    }
1619}
1620
1621impl From<DWRITE_FONT_STYLE> for FontStyle {
1622    fn from(value: DWRITE_FONT_STYLE) -> Self {
1623        match value.0 {
1624            0 => FontStyle::Normal,
1625            1 => FontStyle::Italic,
1626            2 => FontStyle::Oblique,
1627            _ => unreachable!(),
1628        }
1629    }
1630}
1631
1632impl Into<DWRITE_FONT_WEIGHT> for FontWeight {
1633    fn into(self) -> DWRITE_FONT_WEIGHT {
1634        DWRITE_FONT_WEIGHT(self.0 as i32)
1635    }
1636}
1637
1638impl From<DWRITE_FONT_WEIGHT> for FontWeight {
1639    fn from(value: DWRITE_FONT_WEIGHT) -> Self {
1640        FontWeight(value.0 as f32)
1641    }
1642}
1643
1644fn get_font_names_from_collection(
1645    collection: &IDWriteFontCollection1,
1646    locale: &str,
1647) -> Vec<String> {
1648    unsafe {
1649        let mut result = Vec::new();
1650        let family_count = collection.GetFontFamilyCount();
1651        for index in 0..family_count {
1652            let Some(font_family) = collection.GetFontFamily(index).log_err() else {
1653                continue;
1654            };
1655            let Some(localized_family_name) = font_family.GetFamilyNames().log_err() else {
1656                continue;
1657            };
1658            let Some(family_name) = get_name(localized_family_name, locale).log_err() else {
1659                continue;
1660            };
1661            result.push(family_name);
1662        }
1663
1664        result
1665    }
1666}
1667
1668fn get_font_identifier_and_font_struct(
1669    font_face: &IDWriteFontFace3,
1670    locale: &str,
1671) -> Option<(FontIdentifier, Font, bool)> {
1672    let postscript_name = get_postscript_name(font_face, locale).log_err()?;
1673    let localized_family_name = unsafe { font_face.GetFamilyNames().log_err() }?;
1674    let family_name = get_name(localized_family_name, locale).log_err()?;
1675    let weight = unsafe { font_face.GetWeight() };
1676    let style = unsafe { font_face.GetStyle() };
1677    let identifier = FontIdentifier {
1678        postscript_name,
1679        weight: weight.0,
1680        style: style.0,
1681    };
1682    let font_struct = Font {
1683        family: family_name.into(),
1684        features: FontFeatures::default(),
1685        weight: weight.into(),
1686        style: style.into(),
1687        fallbacks: None,
1688    };
1689    let is_emoji = unsafe { font_face.IsColorFont().as_bool() };
1690    Some((identifier, font_struct, is_emoji))
1691}
1692
1693#[inline]
1694fn get_font_identifier(font_face: &IDWriteFontFace3, locale: &str) -> Option<FontIdentifier> {
1695    let weight = unsafe { font_face.GetWeight().0 };
1696    let style = unsafe { font_face.GetStyle().0 };
1697    get_postscript_name(font_face, locale)
1698        .log_err()
1699        .map(|postscript_name| FontIdentifier {
1700            postscript_name,
1701            weight,
1702            style,
1703        })
1704}
1705
1706#[inline]
1707fn get_postscript_name(font_face: &IDWriteFontFace3, locale: &str) -> Result<String> {
1708    let mut info = None;
1709    let mut exists = BOOL(0);
1710    unsafe {
1711        font_face.GetInformationalStrings(
1712            DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_NAME,
1713            &mut info,
1714            &mut exists,
1715        )?
1716    };
1717    if !exists.as_bool() || info.is_none() {
1718        anyhow::bail!("No postscript name found for font face");
1719    }
1720
1721    get_name(info.unwrap(), locale)
1722}
1723
1724// https://learn.microsoft.com/en-us/windows/win32/api/dwrite/ne-dwrite-dwrite_font_feature_tag
1725fn apply_font_features(
1726    direct_write_features: &IDWriteTypography,
1727    features: &FontFeatures,
1728) -> Result<()> {
1729    let tag_values = features.tag_value_list();
1730    if tag_values.is_empty() {
1731        return Ok(());
1732    }
1733
1734    // All of these features are enabled by default by DirectWrite.
1735    // If you want to (and can) peek into the source of DirectWrite
1736    let mut feature_liga = make_direct_write_feature("liga", 1);
1737    let mut feature_clig = make_direct_write_feature("clig", 1);
1738    let mut feature_calt = make_direct_write_feature("calt", 1);
1739
1740    for (tag, value) in tag_values {
1741        if tag.as_str() == "liga" && *value == 0 {
1742            feature_liga.parameter = 0;
1743            continue;
1744        }
1745        if tag.as_str() == "clig" && *value == 0 {
1746            feature_clig.parameter = 0;
1747            continue;
1748        }
1749        if tag.as_str() == "calt" && *value == 0 {
1750            feature_calt.parameter = 0;
1751            continue;
1752        }
1753
1754        unsafe {
1755            direct_write_features.AddFontFeature(make_direct_write_feature(tag, *value))?;
1756        }
1757    }
1758    unsafe {
1759        direct_write_features.AddFontFeature(feature_liga)?;
1760        direct_write_features.AddFontFeature(feature_clig)?;
1761        direct_write_features.AddFontFeature(feature_calt)?;
1762    }
1763
1764    Ok(())
1765}
1766
1767#[inline]
1768const fn make_direct_write_feature(feature_name: &str, parameter: u32) -> DWRITE_FONT_FEATURE {
1769    let tag = make_direct_write_tag(feature_name);
1770    DWRITE_FONT_FEATURE {
1771        nameTag: tag,
1772        parameter,
1773    }
1774}
1775
1776#[inline]
1777const fn make_open_type_tag(tag_name: &str) -> u32 {
1778    let bytes = tag_name.as_bytes();
1779    debug_assert!(bytes.len() == 4);
1780    u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
1781}
1782
1783#[inline]
1784const fn make_direct_write_tag(tag_name: &str) -> DWRITE_FONT_FEATURE_TAG {
1785    DWRITE_FONT_FEATURE_TAG(make_open_type_tag(tag_name))
1786}
1787
1788#[inline]
1789fn get_name(string: IDWriteLocalizedStrings, locale: &str) -> Result<String> {
1790    let mut locale_name_index = 0u32;
1791    let mut exists = BOOL(0);
1792    unsafe {
1793        string.FindLocaleName(
1794            &HSTRING::from(locale),
1795            &mut locale_name_index,
1796            &mut exists as _,
1797        )?
1798    };
1799    if !exists.as_bool() {
1800        unsafe {
1801            string.FindLocaleName(
1802                DEFAULT_LOCALE_NAME,
1803                &mut locale_name_index as _,
1804                &mut exists as _,
1805            )?
1806        };
1807        anyhow::ensure!(exists.as_bool(), "No localised string for {locale}");
1808    }
1809
1810    let name_length = unsafe { string.GetStringLength(locale_name_index) }? as usize;
1811    let mut name_vec = vec![0u16; name_length + 1];
1812    unsafe {
1813        string.GetString(locale_name_index, &mut name_vec)?;
1814    }
1815
1816    Ok(String::from_utf16_lossy(&name_vec[..name_length]))
1817}
1818
1819fn get_system_ui_font_name() -> SharedString {
1820    unsafe {
1821        let mut info: LOGFONTW = std::mem::zeroed();
1822        let font_family = if SystemParametersInfoW(
1823            SPI_GETICONTITLELOGFONT,
1824            std::mem::size_of::<LOGFONTW>() as u32,
1825            Some(&mut info as *mut _ as _),
1826            SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
1827        )
1828        .log_err()
1829        .is_none()
1830        {
1831            // https://learn.microsoft.com/en-us/windows/win32/uxguide/vis-fonts
1832            // Segoe UI is the Windows font intended for user interface text strings.
1833            "Segoe UI".into()
1834        } else {
1835            let font_name = String::from_utf16_lossy(&info.lfFaceName);
1836            font_name.trim_matches(char::from(0)).to_owned().into()
1837        };
1838        log::info!("Use {} as UI font.", font_family);
1839        font_family
1840    }
1841}
1842
1843// One would think that with newer DirectWrite method: IDWriteFontFace4::GetGlyphImageFormats
1844// but that doesn't seem to work for some glyphs, say โค
1845fn is_color_glyph(
1846    font_face: &IDWriteFontFace3,
1847    glyph_id: GlyphId,
1848    factory: &IDWriteFactory5,
1849) -> bool {
1850    let glyph_run = DWRITE_GLYPH_RUN {
1851        fontFace: unsafe { std::mem::transmute_copy(font_face) },
1852        fontEmSize: 14.0,
1853        glyphCount: 1,
1854        glyphIndices: &(glyph_id.0 as u16),
1855        glyphAdvances: &0.0,
1856        glyphOffsets: &DWRITE_GLYPH_OFFSET {
1857            advanceOffset: 0.0,
1858            ascenderOffset: 0.0,
1859        },
1860        isSideways: BOOL(0),
1861        bidiLevel: 0,
1862    };
1863    unsafe {
1864        factory.TranslateColorGlyphRun(
1865            Vector2::default(),
1866            &glyph_run as _,
1867            None,
1868            DWRITE_GLYPH_IMAGE_FORMATS_COLR
1869                | DWRITE_GLYPH_IMAGE_FORMATS_SVG
1870                | DWRITE_GLYPH_IMAGE_FORMATS_PNG
1871                | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
1872                | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8,
1873            DWRITE_MEASURING_MODE_NATURAL,
1874            None,
1875            0,
1876        )
1877    }
1878    .is_ok()
1879}
1880
1881const DEFAULT_LOCALE_NAME: PCWSTR = windows::core::w!("en-US");
1882
1883#[cfg(test)]
1884mod tests {
1885    use crate::platform::windows::direct_write::ClusterAnalyzer;
1886
1887    #[test]
1888    fn test_cluster_map() {
1889        let cluster_map = [0];
1890        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 1);
1891        let next = analyzer.next();
1892        assert_eq!(next, Some((1, 1)));
1893        let next = analyzer.next();
1894        assert_eq!(next, None);
1895
1896        let cluster_map = [0, 1, 2];
1897        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 3);
1898        let next = analyzer.next();
1899        assert_eq!(next, Some((1, 1)));
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, None);
1906        // ๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ๐Ÿ‘ฉโ€๐Ÿ’ป
1907        let cluster_map = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4];
1908        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 5);
1909        let next = analyzer.next();
1910        assert_eq!(next, Some((11, 4)));
1911        let next = analyzer.next();
1912        assert_eq!(next, Some((5, 1)));
1913        let next = analyzer.next();
1914        assert_eq!(next, None);
1915        // ๐Ÿ‘ฉโ€๐Ÿ’ป
1916        let cluster_map = [0, 0, 0, 0, 0];
1917        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 1);
1918        let next = analyzer.next();
1919        assert_eq!(next, Some((5, 1)));
1920        let next = analyzer.next();
1921        assert_eq!(next, None);
1922    }
1923}