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