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