direct_write.rs

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