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