direct_write.rs

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