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