direct_write.rs

   1use std::{borrow::Cow, sync::Arc};
   2
   3use ::util::ResultExt;
   4use anyhow::{anyhow, Result};
   5use collections::HashMap;
   6use itertools::Itertools;
   7use parking_lot::{RwLock, RwLockUpgradableReadGuard};
   8use smallvec::SmallVec;
   9use windows::{
  10    core::*,
  11    Win32::{
  12        Foundation::*,
  13        Globalization::GetUserDefaultLocaleName,
  14        Graphics::{
  15            Direct2D::{Common::*, *},
  16            DirectWrite::*,
  17            Dxgi::Common::*,
  18            Gdi::LOGFONTW,
  19            Imaging::*,
  20        },
  21        System::SystemServices::LOCALE_NAME_MAX_LENGTH,
  22        UI::WindowsAndMessaging::*,
  23    },
  24};
  25
  26use crate::*;
  27
  28#[derive(Debug)]
  29struct FontInfo {
  30    font_family: String,
  31    font_face: IDWriteFontFace3,
  32    features: IDWriteTypography,
  33    fallbacks: Option<IDWriteFontFallback>,
  34    is_system_font: bool,
  35    is_emoji: bool,
  36}
  37
  38pub(crate) struct DirectWriteTextSystem(RwLock<DirectWriteState>);
  39
  40struct DirectWriteComponent {
  41    locale: String,
  42    factory: IDWriteFactory5,
  43    bitmap_factory: AgileReference<IWICImagingFactory>,
  44    d2d1_factory: ID2D1Factory,
  45    in_memory_loader: IDWriteInMemoryFontFileLoader,
  46    builder: IDWriteFontSetBuilder1,
  47    text_renderer: Arc<TextRendererWrapper>,
  48    render_context: GlyphRenderContext,
  49}
  50
  51struct GlyphRenderContext {
  52    params: IDWriteRenderingParams3,
  53    dc_target: ID2D1DeviceContext4,
  54}
  55
  56struct DirectWriteState {
  57    components: DirectWriteComponent,
  58    system_ui_font_name: SharedString,
  59    system_font_collection: IDWriteFontCollection1,
  60    custom_font_collection: IDWriteFontCollection1,
  61    fonts: Vec<FontInfo>,
  62    font_selections: HashMap<Font, FontId>,
  63    font_id_by_identifier: HashMap<FontIdentifier, FontId>,
  64}
  65
  66#[derive(Debug, Clone, Hash, PartialEq, Eq)]
  67struct FontIdentifier {
  68    postscript_name: String,
  69    weight: i32,
  70    style: i32,
  71}
  72
  73impl DirectWriteComponent {
  74    pub fn new(bitmap_factory: &IWICImagingFactory) -> Result<Self> {
  75        unsafe {
  76            let factory: IDWriteFactory5 = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED)?;
  77            let bitmap_factory = AgileReference::new(bitmap_factory)?;
  78            let d2d1_factory: ID2D1Factory =
  79                D2D1CreateFactory(D2D1_FACTORY_TYPE_MULTI_THREADED, None)?;
  80            // The `IDWriteInMemoryFontFileLoader` here is supported starting from
  81            // Windows 10 Creators Update, which consequently requires the entire
  82            // `DirectWriteTextSystem` to run on `win10 1703`+.
  83            let in_memory_loader = factory.CreateInMemoryFontFileLoader()?;
  84            factory.RegisterFontFileLoader(&in_memory_loader)?;
  85            let builder = factory.CreateFontSetBuilder()?;
  86            let mut locale_vec = vec![0u16; LOCALE_NAME_MAX_LENGTH as usize];
  87            GetUserDefaultLocaleName(&mut locale_vec);
  88            let locale = String::from_utf16_lossy(&locale_vec);
  89            let text_renderer = Arc::new(TextRendererWrapper::new(&locale));
  90            let render_context = GlyphRenderContext::new(&factory, &d2d1_factory)?;
  91
  92            Ok(DirectWriteComponent {
  93                locale,
  94                factory,
  95                bitmap_factory,
  96                d2d1_factory,
  97                in_memory_loader,
  98                builder,
  99                text_renderer,
 100                render_context,
 101            })
 102        }
 103    }
 104}
 105
 106impl GlyphRenderContext {
 107    pub fn new(factory: &IDWriteFactory5, d2d1_factory: &ID2D1Factory) -> Result<Self> {
 108        unsafe {
 109            let default_params: IDWriteRenderingParams3 =
 110                factory.CreateRenderingParams()?.cast()?;
 111            let gamma = default_params.GetGamma();
 112            let enhanced_contrast = default_params.GetEnhancedContrast();
 113            let gray_contrast = default_params.GetGrayscaleEnhancedContrast();
 114            let cleartype_level = default_params.GetClearTypeLevel();
 115            let grid_fit_mode = default_params.GetGridFitMode();
 116
 117            let params = factory.CreateCustomRenderingParams(
 118                gamma,
 119                enhanced_contrast,
 120                gray_contrast,
 121                cleartype_level,
 122                DWRITE_PIXEL_GEOMETRY_RGB,
 123                DWRITE_RENDERING_MODE1_NATURAL_SYMMETRIC,
 124                grid_fit_mode,
 125            )?;
 126            let dc_target = {
 127                let target = d2d1_factory.CreateDCRenderTarget(&get_render_target_property(
 128                    DXGI_FORMAT_B8G8R8A8_UNORM,
 129                    D2D1_ALPHA_MODE_PREMULTIPLIED,
 130                ))?;
 131                let target = target.cast::<ID2D1DeviceContext4>()?;
 132                target.SetTextRenderingParams(&params);
 133                target
 134            };
 135
 136            Ok(Self { params, dc_target })
 137        }
 138    }
 139}
 140
 141impl DirectWriteTextSystem {
 142    pub(crate) fn new(bitmap_factory: &IWICImagingFactory) -> Result<Self> {
 143        let components = DirectWriteComponent::new(bitmap_factory)?;
 144        let system_font_collection = unsafe {
 145            let mut result = std::mem::zeroed();
 146            components
 147                .factory
 148                .GetSystemFontCollection(false, &mut result, true)?;
 149            result.unwrap()
 150        };
 151        let custom_font_set = unsafe { components.builder.CreateFontSet()? };
 152        let custom_font_collection = unsafe {
 153            components
 154                .factory
 155                .CreateFontCollectionFromFontSet(&custom_font_set)?
 156        };
 157        let system_ui_font_name = get_system_ui_font_name();
 158
 159        Ok(Self(RwLock::new(DirectWriteState {
 160            components,
 161            system_ui_font_name,
 162            system_font_collection,
 163            custom_font_collection,
 164            fonts: Vec::new(),
 165            font_selections: HashMap::default(),
 166            font_id_by_identifier: HashMap::default(),
 167        })))
 168    }
 169}
 170
 171impl PlatformTextSystem for DirectWriteTextSystem {
 172    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
 173        self.0.write().add_fonts(fonts)
 174    }
 175
 176    fn all_font_names(&self) -> Vec<String> {
 177        self.0.read().all_font_names()
 178    }
 179
 180    fn font_id(&self, font: &Font) -> Result<FontId> {
 181        let lock = self.0.upgradable_read();
 182        if let Some(font_id) = lock.font_selections.get(font) {
 183            Ok(*font_id)
 184        } else {
 185            let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
 186            let font_id = lock.select_font(font);
 187            lock.font_selections.insert(font.clone(), font_id);
 188            Ok(font_id)
 189        }
 190    }
 191
 192    fn font_metrics(&self, font_id: FontId) -> FontMetrics {
 193        self.0.read().font_metrics(font_id)
 194    }
 195
 196    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
 197        self.0.read().get_typographic_bounds(font_id, glyph_id)
 198    }
 199
 200    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Size<f32>> {
 201        self.0.read().get_advance(font_id, glyph_id)
 202    }
 203
 204    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
 205        self.0.read().glyph_for_char(font_id, ch)
 206    }
 207
 208    fn glyph_raster_bounds(
 209        &self,
 210        params: &RenderGlyphParams,
 211    ) -> anyhow::Result<Bounds<DevicePixels>> {
 212        self.0.read().raster_bounds(params)
 213    }
 214
 215    fn rasterize_glyph(
 216        &self,
 217        params: &RenderGlyphParams,
 218        raster_bounds: Bounds<DevicePixels>,
 219    ) -> anyhow::Result<(Size<DevicePixels>, Vec<u8>)> {
 220        self.0.read().rasterize_glyph(params, raster_bounds)
 221    }
 222
 223    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {
 224        self.0
 225            .write()
 226            .layout_line(text, font_size, runs)
 227            .log_err()
 228            .unwrap_or(LineLayout {
 229                font_size,
 230                ..Default::default()
 231            })
 232    }
 233}
 234
 235impl DirectWriteState {
 236    fn add_fonts(&mut self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
 237        for font_data in fonts {
 238            match font_data {
 239                Cow::Borrowed(data) => unsafe {
 240                    let font_file = self
 241                        .components
 242                        .in_memory_loader
 243                        .CreateInMemoryFontFileReference(
 244                            &self.components.factory,
 245                            data.as_ptr() as _,
 246                            data.len() as _,
 247                            None,
 248                        )?;
 249                    self.components.builder.AddFontFile(&font_file)?;
 250                },
 251                Cow::Owned(data) => unsafe {
 252                    let font_file = self
 253                        .components
 254                        .in_memory_loader
 255                        .CreateInMemoryFontFileReference(
 256                            &self.components.factory,
 257                            data.as_ptr() as _,
 258                            data.len() as _,
 259                            None,
 260                        )?;
 261                    self.components.builder.AddFontFile(&font_file)?;
 262                },
 263            }
 264        }
 265        let set = unsafe { self.components.builder.CreateFontSet()? };
 266        let collection = unsafe {
 267            self.components
 268                .factory
 269                .CreateFontCollectionFromFontSet(&set)?
 270        };
 271        self.custom_font_collection = collection;
 272
 273        Ok(())
 274    }
 275
 276    fn generate_font_fallbacks(
 277        &self,
 278        fallbacks: &FontFallbacks,
 279    ) -> Result<Option<IDWriteFontFallback>> {
 280        if fallbacks.fallback_list().is_empty() {
 281            return Ok(None);
 282        }
 283        unsafe {
 284            let builder = self.components.factory.CreateFontFallbackBuilder()?;
 285            let font_set = &self.system_font_collection.GetFontSet()?;
 286            for family_name in fallbacks.fallback_list() {
 287                let Some(fonts) = font_set
 288                    .GetMatchingFonts(
 289                        &HSTRING::from(family_name),
 290                        DWRITE_FONT_WEIGHT_NORMAL,
 291                        DWRITE_FONT_STRETCH_NORMAL,
 292                        DWRITE_FONT_STYLE_NORMAL,
 293                    )
 294                    .log_err()
 295                else {
 296                    continue;
 297                };
 298                if fonts.GetFontCount() == 0 {
 299                    log::error!("No matching font found for {}", family_name);
 300                    continue;
 301                }
 302                let font = fonts.GetFontFaceReference(0)?.CreateFontFace()?;
 303                let mut count = 0;
 304                font.GetUnicodeRanges(None, &mut count).ok();
 305                if count == 0 {
 306                    continue;
 307                }
 308                let mut unicode_ranges = vec![DWRITE_UNICODE_RANGE::default(); count as usize];
 309                let Some(_) = font
 310                    .GetUnicodeRanges(Some(&mut unicode_ranges), &mut count)
 311                    .log_err()
 312                else {
 313                    continue;
 314                };
 315                let target_family_name = HSTRING::from(family_name);
 316                builder.AddMapping(
 317                    &unicode_ranges,
 318                    &[target_family_name.as_ptr()],
 319                    None,
 320                    None,
 321                    None,
 322                    1.0,
 323                )?;
 324            }
 325            let system_fallbacks = self.components.factory.GetSystemFontFallback()?;
 326            builder.AddMappings(&system_fallbacks)?;
 327            Ok(Some(builder.CreateFontFallback()?))
 328        }
 329    }
 330
 331    unsafe fn generate_font_features(
 332        &self,
 333        font_features: &FontFeatures,
 334    ) -> Result<IDWriteTypography> {
 335        let direct_write_features = self.components.factory.CreateTypography()?;
 336        apply_font_features(&direct_write_features, font_features)?;
 337        Ok(direct_write_features)
 338    }
 339
 340    unsafe fn get_font_id_from_font_collection(
 341        &mut self,
 342        family_name: &str,
 343        font_weight: FontWeight,
 344        font_style: FontStyle,
 345        font_features: &FontFeatures,
 346        font_fallbacks: Option<&FontFallbacks>,
 347        is_system_font: bool,
 348    ) -> Option<FontId> {
 349        let collection = if is_system_font {
 350            &self.system_font_collection
 351        } else {
 352            &self.custom_font_collection
 353        };
 354        let fontset = collection.GetFontSet().log_err()?;
 355        let font = fontset
 356            .GetMatchingFonts(
 357                &HSTRING::from(family_name),
 358                font_weight.into(),
 359                DWRITE_FONT_STRETCH_NORMAL,
 360                font_style.into(),
 361            )
 362            .log_err()?;
 363        let total_number = font.GetFontCount();
 364        for index in 0..total_number {
 365            let Some(font_face_ref) = font.GetFontFaceReference(index).log_err() else {
 366                continue;
 367            };
 368            let Some(font_face) = font_face_ref.CreateFontFace().log_err() else {
 369                continue;
 370            };
 371            let Some(identifier) = get_font_identifier(&font_face, &self.components.locale) else {
 372                continue;
 373            };
 374            let is_emoji = font_face.IsColorFont().as_bool();
 375            let Some(direct_write_features) = self.generate_font_features(font_features).log_err()
 376            else {
 377                continue;
 378            };
 379            let fallbacks = font_fallbacks
 380                .and_then(|fallbacks| self.generate_font_fallbacks(fallbacks).log_err().flatten());
 381            let font_info = FontInfo {
 382                font_family: family_name.to_owned(),
 383                font_face,
 384                features: direct_write_features,
 385                fallbacks,
 386                is_system_font,
 387                is_emoji,
 388            };
 389            let font_id = FontId(self.fonts.len());
 390            self.fonts.push(font_info);
 391            self.font_id_by_identifier.insert(identifier, font_id);
 392            return Some(font_id);
 393        }
 394        None
 395    }
 396
 397    unsafe fn update_system_font_collection(&mut self) {
 398        let mut collection = std::mem::zeroed();
 399        if self
 400            .components
 401            .factory
 402            .GetSystemFontCollection(false, &mut collection, true)
 403            .log_err()
 404            .is_some()
 405        {
 406            self.system_font_collection = collection.unwrap();
 407        }
 408    }
 409
 410    fn select_font(&mut self, target_font: &Font) -> FontId {
 411        unsafe {
 412            if target_font.family == ".SystemUIFont" {
 413                let family = self.system_ui_font_name.clone();
 414                self.find_font_id(
 415                    family.as_ref(),
 416                    target_font.weight,
 417                    target_font.style,
 418                    &target_font.features,
 419                    target_font.fallbacks.as_ref(),
 420                )
 421                .unwrap()
 422            } else {
 423                self.find_font_id(
 424                    target_font.family.as_ref(),
 425                    target_font.weight,
 426                    target_font.style,
 427                    &target_font.features,
 428                    target_font.fallbacks.as_ref(),
 429                )
 430                .unwrap_or_else(|| {
 431                    let family = self.system_ui_font_name.clone();
 432                    log::error!("{} not found, use {} instead.", target_font.family, family);
 433                    self.get_font_id_from_font_collection(
 434                        family.as_ref(),
 435                        target_font.weight,
 436                        target_font.style,
 437                        &target_font.features,
 438                        target_font.fallbacks.as_ref(),
 439                        true,
 440                    )
 441                    .unwrap()
 442                })
 443            }
 444        }
 445    }
 446
 447    unsafe fn find_font_id(
 448        &mut self,
 449        family_name: &str,
 450        weight: FontWeight,
 451        style: FontStyle,
 452        features: &FontFeatures,
 453        fallbacks: Option<&FontFallbacks>,
 454    ) -> Option<FontId> {
 455        // try to find target font in custom font collection first
 456        self.get_font_id_from_font_collection(
 457            family_name,
 458            weight,
 459            style,
 460            features,
 461            fallbacks,
 462            false,
 463        )
 464        .or_else(|| {
 465            self.get_font_id_from_font_collection(
 466                family_name,
 467                weight,
 468                style,
 469                features,
 470                fallbacks,
 471                true,
 472            )
 473        })
 474        .or_else(|| {
 475            self.update_system_font_collection();
 476            self.get_font_id_from_font_collection(
 477                family_name,
 478                weight,
 479                style,
 480                features,
 481                fallbacks,
 482                true,
 483            )
 484        })
 485    }
 486
 487    fn layout_line(
 488        &mut self,
 489        text: &str,
 490        font_size: Pixels,
 491        font_runs: &[FontRun],
 492    ) -> Result<LineLayout> {
 493        if font_runs.is_empty() {
 494            return Ok(LineLayout {
 495                font_size,
 496                ..Default::default()
 497            });
 498        }
 499        unsafe {
 500            let text_renderer = self.components.text_renderer.clone();
 501            let text_wide = text.encode_utf16().collect_vec();
 502
 503            let mut utf8_offset = 0usize;
 504            let mut utf16_offset = 0u32;
 505            let text_layout = {
 506                let first_run = &font_runs[0];
 507                let font_info = &self.fonts[first_run.font_id.0];
 508                let collection = if font_info.is_system_font {
 509                    &self.system_font_collection
 510                } else {
 511                    &self.custom_font_collection
 512                };
 513                let format: IDWriteTextFormat1 = self
 514                    .components
 515                    .factory
 516                    .CreateTextFormat(
 517                        &HSTRING::from(&font_info.font_family),
 518                        collection,
 519                        font_info.font_face.GetWeight(),
 520                        font_info.font_face.GetStyle(),
 521                        DWRITE_FONT_STRETCH_NORMAL,
 522                        font_size.0,
 523                        &HSTRING::from(&self.components.locale),
 524                    )?
 525                    .cast()?;
 526                if let Some(ref fallbacks) = font_info.fallbacks {
 527                    format.SetFontFallback(fallbacks)?;
 528                }
 529
 530                let layout = self.components.factory.CreateTextLayout(
 531                    &text_wide,
 532                    &format,
 533                    f32::INFINITY,
 534                    f32::INFINITY,
 535                )?;
 536                let current_text = &text[utf8_offset..(utf8_offset + first_run.len)];
 537                utf8_offset += first_run.len;
 538                let current_text_utf16_length = current_text.encode_utf16().count() as u32;
 539                let text_range = DWRITE_TEXT_RANGE {
 540                    startPosition: utf16_offset,
 541                    length: current_text_utf16_length,
 542                };
 543                layout.SetTypography(&font_info.features, text_range)?;
 544                utf16_offset += current_text_utf16_length;
 545
 546                layout
 547            };
 548
 549            let mut first_run = true;
 550            let mut ascent = Pixels::default();
 551            let mut descent = Pixels::default();
 552            for run in font_runs {
 553                if first_run {
 554                    first_run = false;
 555                    let mut metrics = vec![DWRITE_LINE_METRICS::default(); 4];
 556                    let mut line_count = 0u32;
 557                    text_layout.GetLineMetrics(Some(&mut metrics), &mut line_count as _)?;
 558                    ascent = px(metrics[0].baseline);
 559                    descent = px(metrics[0].height - metrics[0].baseline);
 560                    continue;
 561                }
 562                let font_info = &self.fonts[run.font_id.0];
 563                let current_text = &text[utf8_offset..(utf8_offset + run.len)];
 564                utf8_offset += run.len;
 565                let current_text_utf16_length = current_text.encode_utf16().count() as u32;
 566
 567                let collection = if font_info.is_system_font {
 568                    &self.system_font_collection
 569                } else {
 570                    &self.custom_font_collection
 571                };
 572                let text_range = DWRITE_TEXT_RANGE {
 573                    startPosition: utf16_offset,
 574                    length: current_text_utf16_length,
 575                };
 576                utf16_offset += current_text_utf16_length;
 577                text_layout.SetFontCollection(collection, text_range)?;
 578                text_layout
 579                    .SetFontFamilyName(&HSTRING::from(&font_info.font_family), text_range)?;
 580                text_layout.SetFontSize(font_size.0, text_range)?;
 581                text_layout.SetFontStyle(font_info.font_face.GetStyle(), text_range)?;
 582                text_layout.SetFontWeight(font_info.font_face.GetWeight(), text_range)?;
 583                text_layout.SetTypography(&font_info.features, text_range)?;
 584            }
 585
 586            let mut runs = Vec::new();
 587            let renderer_context = RendererContext {
 588                text_system: self,
 589                index_converter: StringIndexConverter::new(text),
 590                runs: &mut runs,
 591                utf16_index: 0,
 592                width: 0.0,
 593            };
 594            text_layout.Draw(
 595                Some(&renderer_context as *const _ as _),
 596                &text_renderer.0,
 597                0.0,
 598                0.0,
 599            )?;
 600            let width = px(renderer_context.width);
 601
 602            Ok(LineLayout {
 603                font_size,
 604                width,
 605                ascent,
 606                descent,
 607                runs,
 608                len: text.len(),
 609            })
 610        }
 611    }
 612
 613    fn font_metrics(&self, font_id: FontId) -> FontMetrics {
 614        unsafe {
 615            let font_info = &self.fonts[font_id.0];
 616            let mut metrics = std::mem::zeroed();
 617            font_info.font_face.GetMetrics(&mut metrics);
 618
 619            FontMetrics {
 620                units_per_em: metrics.Base.designUnitsPerEm as _,
 621                ascent: metrics.Base.ascent as _,
 622                descent: -(metrics.Base.descent as f32),
 623                line_gap: metrics.Base.lineGap as _,
 624                underline_position: metrics.Base.underlinePosition as _,
 625                underline_thickness: metrics.Base.underlineThickness as _,
 626                cap_height: metrics.Base.capHeight as _,
 627                x_height: metrics.Base.xHeight as _,
 628                bounding_box: Bounds {
 629                    origin: Point {
 630                        x: metrics.glyphBoxLeft as _,
 631                        y: metrics.glyphBoxBottom as _,
 632                    },
 633                    size: Size {
 634                        width: (metrics.glyphBoxRight - metrics.glyphBoxLeft) as _,
 635                        height: (metrics.glyphBoxTop - metrics.glyphBoxBottom) as _,
 636                    },
 637                },
 638            }
 639        }
 640    }
 641
 642    fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
 643        let render_target = &self.components.render_context.dc_target;
 644        unsafe {
 645            render_target.SetUnitMode(D2D1_UNIT_MODE_DIPS);
 646            render_target.SetDpi(96.0 * params.scale_factor, 96.0 * params.scale_factor);
 647        }
 648        let font = &self.fonts[params.font_id.0];
 649        let glyph_id = [params.glyph_id.0 as u16];
 650        let advance = [0.0f32];
 651        let offset = [DWRITE_GLYPH_OFFSET::default()];
 652        let glyph_run = DWRITE_GLYPH_RUN {
 653            fontFace: unsafe { std::mem::transmute_copy(&font.font_face) },
 654            fontEmSize: params.font_size.0,
 655            glyphCount: 1,
 656            glyphIndices: glyph_id.as_ptr(),
 657            glyphAdvances: advance.as_ptr(),
 658            glyphOffsets: offset.as_ptr(),
 659            isSideways: BOOL(0),
 660            bidiLevel: 0,
 661        };
 662        let bounds = unsafe {
 663            render_target.GetGlyphRunWorldBounds(
 664                D2D_POINT_2F { x: 0.0, y: 0.0 },
 665                &glyph_run,
 666                DWRITE_MEASURING_MODE_NATURAL,
 667            )?
 668        };
 669        // todo(windows)
 670        // This is a walkaround, deleted when figured out.
 671        let y_offset;
 672        let extra_height;
 673        if params.is_emoji {
 674            y_offset = 0;
 675            extra_height = 0;
 676        } else {
 677            // make some room for scaler.
 678            y_offset = -1;
 679            extra_height = 2;
 680        }
 681
 682        if bounds.right < bounds.left {
 683            Ok(Bounds {
 684                origin: point(0.into(), 0.into()),
 685                size: size(0.into(), 0.into()),
 686            })
 687        } else {
 688            Ok(Bounds {
 689                origin: point(
 690                    ((bounds.left * params.scale_factor).ceil() as i32).into(),
 691                    ((bounds.top * params.scale_factor).ceil() as i32 + y_offset).into(),
 692                ),
 693                size: size(
 694                    (((bounds.right - bounds.left) * params.scale_factor).ceil() as i32).into(),
 695                    (((bounds.bottom - bounds.top) * params.scale_factor).ceil() as i32
 696                        + extra_height)
 697                        .into(),
 698                ),
 699            })
 700        }
 701    }
 702
 703    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
 704        let font_info = &self.fonts[font_id.0];
 705        let codepoints = [ch as u32];
 706        let mut glyph_indices = vec![0u16; 1];
 707        unsafe {
 708            font_info
 709                .font_face
 710                .GetGlyphIndices(codepoints.as_ptr(), 1, glyph_indices.as_mut_ptr())
 711                .log_err()
 712        }
 713        .map(|_| GlyphId(glyph_indices[0] as u32))
 714    }
 715
 716    fn rasterize_glyph(
 717        &self,
 718        params: &RenderGlyphParams,
 719        glyph_bounds: Bounds<DevicePixels>,
 720    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
 721        if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
 722            return Err(anyhow!("glyph bounds are empty"));
 723        }
 724
 725        let font_info = &self.fonts[params.font_id.0];
 726        let glyph_id = [params.glyph_id.0 as u16];
 727        let advance = [glyph_bounds.size.width.0 as f32];
 728        let offset = [DWRITE_GLYPH_OFFSET {
 729            advanceOffset: -glyph_bounds.origin.x.0 as f32 / params.scale_factor,
 730            ascenderOffset: glyph_bounds.origin.y.0 as f32 / params.scale_factor,
 731        }];
 732        let glyph_run = DWRITE_GLYPH_RUN {
 733            fontFace: unsafe { std::mem::transmute_copy(&font_info.font_face) },
 734            fontEmSize: params.font_size.0,
 735            glyphCount: 1,
 736            glyphIndices: glyph_id.as_ptr(),
 737            glyphAdvances: advance.as_ptr(),
 738            glyphOffsets: offset.as_ptr(),
 739            isSideways: BOOL(0),
 740            bidiLevel: 0,
 741        };
 742
 743        // Add an extra pixel when the subpixel variant isn't zero to make room for anti-aliasing.
 744        let mut bitmap_size = glyph_bounds.size;
 745        if params.subpixel_variant.x > 0 {
 746            bitmap_size.width += DevicePixels(1);
 747        }
 748        if params.subpixel_variant.y > 0 {
 749            bitmap_size.height += DevicePixels(1);
 750        }
 751        let bitmap_size = bitmap_size;
 752
 753        let total_bytes;
 754        let bitmap_format;
 755        let render_target_property;
 756        let bitmap_width;
 757        let bitmap_height;
 758        let bitmap_stride;
 759        let bitmap_dpi;
 760        if params.is_emoji {
 761            total_bytes = bitmap_size.height.0 as usize * bitmap_size.width.0 as usize * 4;
 762            bitmap_format = &GUID_WICPixelFormat32bppPBGRA;
 763            render_target_property = get_render_target_property(
 764                DXGI_FORMAT_B8G8R8A8_UNORM,
 765                D2D1_ALPHA_MODE_PREMULTIPLIED,
 766            );
 767            bitmap_width = bitmap_size.width.0 as u32;
 768            bitmap_height = bitmap_size.height.0 as u32;
 769            bitmap_stride = bitmap_size.width.0 as u32 * 4;
 770            bitmap_dpi = 96.0;
 771        } else {
 772            total_bytes = bitmap_size.height.0 as usize * bitmap_size.width.0 as usize;
 773            bitmap_format = &GUID_WICPixelFormat8bppAlpha;
 774            render_target_property =
 775                get_render_target_property(DXGI_FORMAT_A8_UNORM, D2D1_ALPHA_MODE_STRAIGHT);
 776            bitmap_width = bitmap_size.width.0 as u32 * 2;
 777            bitmap_height = bitmap_size.height.0 as u32 * 2;
 778            bitmap_stride = bitmap_size.width.0 as u32;
 779            bitmap_dpi = 192.0;
 780        }
 781
 782        let bitmap_factory = self.components.bitmap_factory.resolve()?;
 783        unsafe {
 784            let bitmap = bitmap_factory.CreateBitmap(
 785                bitmap_width,
 786                bitmap_height,
 787                bitmap_format,
 788                WICBitmapCacheOnLoad,
 789            )?;
 790            let render_target = self
 791                .components
 792                .d2d1_factory
 793                .CreateWicBitmapRenderTarget(&bitmap, &render_target_property)?;
 794            let brush = render_target.CreateSolidColorBrush(&BRUSH_COLOR, None)?;
 795            let subpixel_shift = params
 796                .subpixel_variant
 797                .map(|v| v as f32 / SUBPIXEL_VARIANTS as f32);
 798            let baseline_origin = D2D_POINT_2F {
 799                x: subpixel_shift.x / params.scale_factor,
 800                y: subpixel_shift.y / params.scale_factor,
 801            };
 802
 803            // This `cast()` action here should never fail since we are running on Win10+, and
 804            // ID2D1DeviceContext4 requires Win8+
 805            let render_target = render_target.cast::<ID2D1DeviceContext4>().unwrap();
 806            render_target.SetUnitMode(D2D1_UNIT_MODE_DIPS);
 807            render_target.SetDpi(
 808                bitmap_dpi * params.scale_factor,
 809                bitmap_dpi * params.scale_factor,
 810            );
 811            render_target.SetTextRenderingParams(&self.components.render_context.params);
 812            render_target.BeginDraw();
 813
 814            if params.is_emoji {
 815                // WARN: only DWRITE_GLYPH_IMAGE_FORMATS_COLR has been tested
 816                let enumerator = self.components.factory.TranslateColorGlyphRun(
 817                    baseline_origin,
 818                    &glyph_run as _,
 819                    None,
 820                    DWRITE_GLYPH_IMAGE_FORMATS_COLR
 821                        | DWRITE_GLYPH_IMAGE_FORMATS_SVG
 822                        | DWRITE_GLYPH_IMAGE_FORMATS_PNG
 823                        | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
 824                        | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8,
 825                    DWRITE_MEASURING_MODE_NATURAL,
 826                    None,
 827                    0,
 828                )?;
 829                while enumerator.MoveNext().is_ok() {
 830                    let Ok(color_glyph) = enumerator.GetCurrentRun() else {
 831                        break;
 832                    };
 833                    let color_glyph = &*color_glyph;
 834                    let brush_color = translate_color(&color_glyph.Base.runColor);
 835                    brush.SetColor(&brush_color);
 836                    match color_glyph.glyphImageFormat {
 837                        DWRITE_GLYPH_IMAGE_FORMATS_PNG
 838                        | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
 839                        | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8 => render_target
 840                            .DrawColorBitmapGlyphRun(
 841                                color_glyph.glyphImageFormat,
 842                                baseline_origin,
 843                                &color_glyph.Base.glyphRun,
 844                                color_glyph.measuringMode,
 845                                D2D1_COLOR_BITMAP_GLYPH_SNAP_OPTION_DEFAULT,
 846                            ),
 847                        DWRITE_GLYPH_IMAGE_FORMATS_SVG => render_target.DrawSvgGlyphRun(
 848                            baseline_origin,
 849                            &color_glyph.Base.glyphRun,
 850                            &brush,
 851                            None,
 852                            color_glyph.Base.paletteIndex as u32,
 853                            color_glyph.measuringMode,
 854                        ),
 855                        _ => render_target.DrawGlyphRun(
 856                            baseline_origin,
 857                            &color_glyph.Base.glyphRun,
 858                            Some(color_glyph.Base.glyphRunDescription as *const _),
 859                            &brush,
 860                            color_glyph.measuringMode,
 861                        ),
 862                    }
 863                }
 864            } else {
 865                render_target.DrawGlyphRun(
 866                    baseline_origin,
 867                    &glyph_run,
 868                    None,
 869                    &brush,
 870                    DWRITE_MEASURING_MODE_NATURAL,
 871                );
 872            }
 873            render_target.EndDraw(None, None)?;
 874
 875            let mut raw_data = vec![0u8; total_bytes];
 876            if params.is_emoji {
 877                bitmap.CopyPixels(std::ptr::null() as _, bitmap_stride, &mut raw_data)?;
 878                // Convert from BGRA with premultiplied alpha to BGRA with straight alpha.
 879                for pixel in raw_data.chunks_exact_mut(4) {
 880                    let a = pixel[3] as f32 / 255.;
 881                    pixel[0] = (pixel[0] as f32 / a) as u8;
 882                    pixel[1] = (pixel[1] as f32 / a) as u8;
 883                    pixel[2] = (pixel[2] as f32 / a) as u8;
 884                }
 885            } else {
 886                let scaler = bitmap_factory.CreateBitmapScaler()?;
 887                scaler.Initialize(
 888                    &bitmap,
 889                    bitmap_size.width.0 as u32,
 890                    bitmap_size.height.0 as u32,
 891                    WICBitmapInterpolationModeHighQualityCubic,
 892                )?;
 893                scaler.CopyPixels(std::ptr::null() as _, bitmap_stride, &mut raw_data)?;
 894            }
 895            Ok((bitmap_size, raw_data))
 896        }
 897    }
 898
 899    fn get_typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
 900        unsafe {
 901            let font = &self.fonts[font_id.0].font_face;
 902            let glyph_indices = [glyph_id.0 as u16];
 903            let mut metrics = [DWRITE_GLYPH_METRICS::default()];
 904            font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
 905
 906            let metrics = &metrics[0];
 907            let advance_width = metrics.advanceWidth as i32;
 908            let advance_height = metrics.advanceHeight as i32;
 909            let left_side_bearing = metrics.leftSideBearing;
 910            let right_side_bearing = metrics.rightSideBearing;
 911            let top_side_bearing = metrics.topSideBearing;
 912            let bottom_side_bearing = metrics.bottomSideBearing;
 913            let vertical_origin_y = metrics.verticalOriginY;
 914
 915            let y_offset = vertical_origin_y + bottom_side_bearing - advance_height;
 916            let width = advance_width - (left_side_bearing + right_side_bearing);
 917            let height = advance_height - (top_side_bearing + bottom_side_bearing);
 918
 919            Ok(Bounds {
 920                origin: Point {
 921                    x: left_side_bearing as f32,
 922                    y: y_offset as f32,
 923                },
 924                size: Size {
 925                    width: width as f32,
 926                    height: height as f32,
 927                },
 928            })
 929        }
 930    }
 931
 932    fn get_advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
 933        unsafe {
 934            let font = &self.fonts[font_id.0].font_face;
 935            let glyph_indices = [glyph_id.0 as u16];
 936            let mut metrics = [DWRITE_GLYPH_METRICS::default()];
 937            font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
 938
 939            let metrics = &metrics[0];
 940
 941            Ok(Size {
 942                width: metrics.advanceWidth as f32,
 943                height: 0.0,
 944            })
 945        }
 946    }
 947
 948    fn all_font_names(&self) -> Vec<String> {
 949        let mut result =
 950            get_font_names_from_collection(&self.system_font_collection, &self.components.locale);
 951        result.extend(get_font_names_from_collection(
 952            &self.custom_font_collection,
 953            &self.components.locale,
 954        ));
 955        result
 956    }
 957}
 958
 959impl Drop for DirectWriteState {
 960    fn drop(&mut self) {
 961        unsafe {
 962            let _ = self
 963                .components
 964                .factory
 965                .UnregisterFontFileLoader(&self.components.in_memory_loader);
 966        }
 967    }
 968}
 969
 970struct TextRendererWrapper(pub IDWriteTextRenderer);
 971
 972impl TextRendererWrapper {
 973    pub fn new(locale_str: &str) -> Self {
 974        let inner = TextRenderer::new(locale_str);
 975        TextRendererWrapper(inner.into())
 976    }
 977}
 978
 979#[implement(IDWriteTextRenderer)]
 980struct TextRenderer {
 981    locale: String,
 982}
 983
 984impl TextRenderer {
 985    pub fn new(locale_str: &str) -> Self {
 986        TextRenderer {
 987            locale: locale_str.to_owned(),
 988        }
 989    }
 990}
 991
 992struct RendererContext<'t, 'a, 'b> {
 993    text_system: &'t mut DirectWriteState,
 994    index_converter: StringIndexConverter<'a>,
 995    runs: &'b mut Vec<ShapedRun>,
 996    utf16_index: usize,
 997    width: f32,
 998}
 999
1000#[allow(non_snake_case)]
1001impl IDWritePixelSnapping_Impl for TextRenderer_Impl {
1002    fn IsPixelSnappingDisabled(
1003        &self,
1004        _clientdrawingcontext: *const ::core::ffi::c_void,
1005    ) -> windows::core::Result<BOOL> {
1006        Ok(BOOL(0))
1007    }
1008
1009    fn GetCurrentTransform(
1010        &self,
1011        _clientdrawingcontext: *const ::core::ffi::c_void,
1012        transform: *mut DWRITE_MATRIX,
1013    ) -> windows::core::Result<()> {
1014        unsafe {
1015            *transform = DWRITE_MATRIX {
1016                m11: 1.0,
1017                m12: 0.0,
1018                m21: 0.0,
1019                m22: 1.0,
1020                dx: 0.0,
1021                dy: 0.0,
1022            };
1023        }
1024        Ok(())
1025    }
1026
1027    fn GetPixelsPerDip(
1028        &self,
1029        _clientdrawingcontext: *const ::core::ffi::c_void,
1030    ) -> windows::core::Result<f32> {
1031        Ok(1.0)
1032    }
1033}
1034
1035#[allow(non_snake_case)]
1036impl IDWriteTextRenderer_Impl for TextRenderer_Impl {
1037    fn DrawGlyphRun(
1038        &self,
1039        clientdrawingcontext: *const ::core::ffi::c_void,
1040        _baselineoriginx: f32,
1041        _baselineoriginy: f32,
1042        _measuringmode: DWRITE_MEASURING_MODE,
1043        glyphrun: *const DWRITE_GLYPH_RUN,
1044        glyphrundescription: *const DWRITE_GLYPH_RUN_DESCRIPTION,
1045        _clientdrawingeffect: Option<&windows::core::IUnknown>,
1046    ) -> windows::core::Result<()> {
1047        unsafe {
1048            let glyphrun = &*glyphrun;
1049            let glyph_count = glyphrun.glyphCount as usize;
1050            if glyph_count == 0 {
1051                return Ok(());
1052            }
1053            let desc = &*glyphrundescription;
1054            let utf16_length_per_glyph = desc.stringLength as usize / glyph_count;
1055            let context =
1056                &mut *(clientdrawingcontext as *const RendererContext as *mut RendererContext);
1057
1058            if glyphrun.fontFace.is_none() {
1059                return Ok(());
1060            }
1061
1062            let font_face = glyphrun.fontFace.as_ref().unwrap();
1063            // This `cast()` action here should never fail since we are running on Win10+, and
1064            // `IDWriteFontFace3` requires Win10
1065            let font_face = &font_face.cast::<IDWriteFontFace3>().unwrap();
1066            let Some((font_identifier, font_struct, color_font)) =
1067                get_font_identifier_and_font_struct(font_face, &self.locale)
1068            else {
1069                return Ok(());
1070            };
1071
1072            let font_id = if let Some(id) = context
1073                .text_system
1074                .font_id_by_identifier
1075                .get(&font_identifier)
1076            {
1077                *id
1078            } else {
1079                context.text_system.select_font(&font_struct)
1080            };
1081            let mut glyphs = SmallVec::new();
1082            for index in 0..glyph_count {
1083                let id = GlyphId(*glyphrun.glyphIndices.add(index) as u32);
1084                context
1085                    .index_converter
1086                    .advance_to_utf16_ix(context.utf16_index);
1087                let is_emoji = color_font
1088                    && is_color_glyph(font_face, id, &context.text_system.components.factory);
1089                glyphs.push(ShapedGlyph {
1090                    id,
1091                    position: point(px(context.width), px(0.0)),
1092                    index: context.index_converter.utf8_ix,
1093                    is_emoji,
1094                });
1095                context.utf16_index += utf16_length_per_glyph;
1096                context.width += *glyphrun.glyphAdvances.add(index);
1097            }
1098            context.runs.push(ShapedRun { font_id, glyphs });
1099        }
1100        Ok(())
1101    }
1102
1103    fn DrawUnderline(
1104        &self,
1105        _clientdrawingcontext: *const ::core::ffi::c_void,
1106        _baselineoriginx: f32,
1107        _baselineoriginy: f32,
1108        _underline: *const DWRITE_UNDERLINE,
1109        _clientdrawingeffect: Option<&windows::core::IUnknown>,
1110    ) -> windows::core::Result<()> {
1111        Err(windows::core::Error::new(
1112            E_NOTIMPL,
1113            "DrawUnderline unimplemented",
1114        ))
1115    }
1116
1117    fn DrawStrikethrough(
1118        &self,
1119        _clientdrawingcontext: *const ::core::ffi::c_void,
1120        _baselineoriginx: f32,
1121        _baselineoriginy: f32,
1122        _strikethrough: *const DWRITE_STRIKETHROUGH,
1123        _clientdrawingeffect: Option<&windows::core::IUnknown>,
1124    ) -> windows::core::Result<()> {
1125        Err(windows::core::Error::new(
1126            E_NOTIMPL,
1127            "DrawStrikethrough unimplemented",
1128        ))
1129    }
1130
1131    fn DrawInlineObject(
1132        &self,
1133        _clientdrawingcontext: *const ::core::ffi::c_void,
1134        _originx: f32,
1135        _originy: f32,
1136        _inlineobject: Option<&IDWriteInlineObject>,
1137        _issideways: BOOL,
1138        _isrighttoleft: BOOL,
1139        _clientdrawingeffect: Option<&windows::core::IUnknown>,
1140    ) -> windows::core::Result<()> {
1141        Err(windows::core::Error::new(
1142            E_NOTIMPL,
1143            "DrawInlineObject unimplemented",
1144        ))
1145    }
1146}
1147
1148struct StringIndexConverter<'a> {
1149    text: &'a str,
1150    utf8_ix: usize,
1151    utf16_ix: usize,
1152}
1153
1154impl<'a> StringIndexConverter<'a> {
1155    fn new(text: &'a str) -> Self {
1156        Self {
1157            text,
1158            utf8_ix: 0,
1159            utf16_ix: 0,
1160        }
1161    }
1162
1163    fn advance_to_utf8_ix(&mut self, utf8_target: usize) {
1164        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1165            if self.utf8_ix + ix >= utf8_target {
1166                self.utf8_ix += ix;
1167                return;
1168            }
1169            self.utf16_ix += c.len_utf16();
1170        }
1171        self.utf8_ix = self.text.len();
1172    }
1173
1174    fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
1175        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1176            if self.utf16_ix >= utf16_target {
1177                self.utf8_ix += ix;
1178                return;
1179            }
1180            self.utf16_ix += c.len_utf16();
1181        }
1182        self.utf8_ix = self.text.len();
1183    }
1184}
1185
1186impl Into<DWRITE_FONT_STYLE> for FontStyle {
1187    fn into(self) -> DWRITE_FONT_STYLE {
1188        match self {
1189            FontStyle::Normal => DWRITE_FONT_STYLE_NORMAL,
1190            FontStyle::Italic => DWRITE_FONT_STYLE_ITALIC,
1191            FontStyle::Oblique => DWRITE_FONT_STYLE_OBLIQUE,
1192        }
1193    }
1194}
1195
1196impl From<DWRITE_FONT_STYLE> for FontStyle {
1197    fn from(value: DWRITE_FONT_STYLE) -> Self {
1198        match value.0 {
1199            0 => FontStyle::Normal,
1200            1 => FontStyle::Italic,
1201            2 => FontStyle::Oblique,
1202            _ => unreachable!(),
1203        }
1204    }
1205}
1206
1207impl Into<DWRITE_FONT_WEIGHT> for FontWeight {
1208    fn into(self) -> DWRITE_FONT_WEIGHT {
1209        DWRITE_FONT_WEIGHT(self.0 as i32)
1210    }
1211}
1212
1213impl From<DWRITE_FONT_WEIGHT> for FontWeight {
1214    fn from(value: DWRITE_FONT_WEIGHT) -> Self {
1215        FontWeight(value.0 as f32)
1216    }
1217}
1218
1219fn get_font_names_from_collection(
1220    collection: &IDWriteFontCollection1,
1221    locale: &str,
1222) -> Vec<String> {
1223    unsafe {
1224        let mut result = Vec::new();
1225        let family_count = collection.GetFontFamilyCount();
1226        for index in 0..family_count {
1227            let Some(font_family) = collection.GetFontFamily(index).log_err() else {
1228                continue;
1229            };
1230            let Some(localized_family_name) = font_family.GetFamilyNames().log_err() else {
1231                continue;
1232            };
1233            let Some(family_name) = get_name(localized_family_name, locale).log_err() else {
1234                continue;
1235            };
1236            result.push(family_name);
1237        }
1238
1239        result
1240    }
1241}
1242
1243fn get_font_identifier_and_font_struct(
1244    font_face: &IDWriteFontFace3,
1245    locale: &str,
1246) -> Option<(FontIdentifier, Font, bool)> {
1247    let postscript_name = get_postscript_name(font_face, locale).log_err()?;
1248    let localized_family_name = unsafe { font_face.GetFamilyNames().log_err() }?;
1249    let family_name = get_name(localized_family_name, locale).log_err()?;
1250    let weight = unsafe { font_face.GetWeight() };
1251    let style = unsafe { font_face.GetStyle() };
1252    let identifier = FontIdentifier {
1253        postscript_name,
1254        weight: weight.0,
1255        style: style.0,
1256    };
1257    let font_struct = Font {
1258        family: family_name.into(),
1259        features: FontFeatures::default(),
1260        weight: weight.into(),
1261        style: style.into(),
1262        fallbacks: None,
1263    };
1264    let is_emoji = unsafe { font_face.IsColorFont().as_bool() };
1265    Some((identifier, font_struct, is_emoji))
1266}
1267
1268#[inline]
1269fn get_font_identifier(font_face: &IDWriteFontFace3, locale: &str) -> Option<FontIdentifier> {
1270    let weight = unsafe { font_face.GetWeight().0 };
1271    let style = unsafe { font_face.GetStyle().0 };
1272    get_postscript_name(font_face, locale)
1273        .log_err()
1274        .map(|postscript_name| FontIdentifier {
1275            postscript_name,
1276            weight,
1277            style,
1278        })
1279}
1280
1281#[inline]
1282fn get_postscript_name(font_face: &IDWriteFontFace3, locale: &str) -> Result<String> {
1283    let mut info = None;
1284    let mut exists = BOOL(0);
1285    unsafe {
1286        font_face.GetInformationalStrings(
1287            DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_NAME,
1288            &mut info,
1289            &mut exists,
1290        )?
1291    };
1292    if !exists.as_bool() || info.is_none() {
1293        return Err(anyhow!("No postscript name found for font face"));
1294    }
1295
1296    get_name(info.unwrap(), locale)
1297}
1298
1299// https://learn.microsoft.com/en-us/windows/win32/api/dwrite/ne-dwrite-dwrite_font_feature_tag
1300fn apply_font_features(
1301    direct_write_features: &IDWriteTypography,
1302    features: &FontFeatures,
1303) -> Result<()> {
1304    let tag_values = features.tag_value_list();
1305    if tag_values.is_empty() {
1306        return Ok(());
1307    }
1308
1309    // All of these features are enabled by default by DirectWrite.
1310    // If you want to (and can) peek into the source of DirectWrite
1311    let mut feature_liga = make_direct_write_feature("liga", 1);
1312    let mut feature_clig = make_direct_write_feature("clig", 1);
1313    let mut feature_calt = make_direct_write_feature("calt", 1);
1314
1315    for (tag, value) in tag_values {
1316        if tag.as_str() == "liga" && *value == 0 {
1317            feature_liga.parameter = 0;
1318            continue;
1319        }
1320        if tag.as_str() == "clig" && *value == 0 {
1321            feature_clig.parameter = 0;
1322            continue;
1323        }
1324        if tag.as_str() == "calt" && *value == 0 {
1325            feature_calt.parameter = 0;
1326            continue;
1327        }
1328
1329        unsafe {
1330            direct_write_features.AddFontFeature(make_direct_write_feature(&tag, *value))?;
1331        }
1332    }
1333    unsafe {
1334        direct_write_features.AddFontFeature(feature_liga)?;
1335        direct_write_features.AddFontFeature(feature_clig)?;
1336        direct_write_features.AddFontFeature(feature_calt)?;
1337    }
1338
1339    Ok(())
1340}
1341
1342#[inline]
1343fn make_direct_write_feature(feature_name: &str, parameter: u32) -> DWRITE_FONT_FEATURE {
1344    let tag = make_direct_write_tag(feature_name);
1345    DWRITE_FONT_FEATURE {
1346        nameTag: tag,
1347        parameter,
1348    }
1349}
1350
1351#[inline]
1352fn make_open_type_tag(tag_name: &str) -> u32 {
1353    let bytes = tag_name.bytes().collect_vec();
1354    assert_eq!(bytes.len(), 4);
1355    ((bytes[3] as u32) << 24)
1356        | ((bytes[2] as u32) << 16)
1357        | ((bytes[1] as u32) << 8)
1358        | (bytes[0] as u32)
1359}
1360
1361#[inline]
1362fn make_direct_write_tag(tag_name: &str) -> DWRITE_FONT_FEATURE_TAG {
1363    DWRITE_FONT_FEATURE_TAG(make_open_type_tag(tag_name))
1364}
1365
1366#[inline]
1367fn get_name(string: IDWriteLocalizedStrings, locale: &str) -> Result<String> {
1368    let mut locale_name_index = 0u32;
1369    let mut exists = BOOL(0);
1370    unsafe {
1371        string.FindLocaleName(
1372            &HSTRING::from(locale),
1373            &mut locale_name_index,
1374            &mut exists as _,
1375        )?
1376    };
1377    if !exists.as_bool() {
1378        unsafe {
1379            string.FindLocaleName(
1380                DEFAULT_LOCALE_NAME,
1381                &mut locale_name_index as _,
1382                &mut exists as _,
1383            )?
1384        };
1385        if !exists.as_bool() {
1386            return Err(anyhow!("No localised string for {}", locale));
1387        }
1388    }
1389
1390    let name_length = unsafe { string.GetStringLength(locale_name_index) }? as usize;
1391    let mut name_vec = vec![0u16; name_length + 1];
1392    unsafe {
1393        string.GetString(locale_name_index, &mut name_vec)?;
1394    }
1395
1396    Ok(String::from_utf16_lossy(&name_vec[..name_length]))
1397}
1398
1399#[inline]
1400fn translate_color(color: &DWRITE_COLOR_F) -> D2D1_COLOR_F {
1401    D2D1_COLOR_F {
1402        r: color.r,
1403        g: color.g,
1404        b: color.b,
1405        a: color.a,
1406    }
1407}
1408
1409fn get_system_ui_font_name() -> SharedString {
1410    unsafe {
1411        let mut info: LOGFONTW = std::mem::zeroed();
1412        let font_family = if SystemParametersInfoW(
1413            SPI_GETICONTITLELOGFONT,
1414            std::mem::size_of::<LOGFONTW>() as u32,
1415            Some(&mut info as *mut _ as _),
1416            SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
1417        )
1418        .log_err()
1419        .is_none()
1420        {
1421            // https://learn.microsoft.com/en-us/windows/win32/uxguide/vis-fonts
1422            // Segoe UI is the Windows font intended for user interface text strings.
1423            "Segoe UI".into()
1424        } else {
1425            let font_name = String::from_utf16_lossy(&info.lfFaceName);
1426            font_name.trim_matches(char::from(0)).to_owned().into()
1427        };
1428        log::info!("Use {} as UI font.", font_family);
1429        font_family
1430    }
1431}
1432
1433#[inline]
1434fn get_render_target_property(
1435    pixel_format: DXGI_FORMAT,
1436    alpha_mode: D2D1_ALPHA_MODE,
1437) -> D2D1_RENDER_TARGET_PROPERTIES {
1438    D2D1_RENDER_TARGET_PROPERTIES {
1439        r#type: D2D1_RENDER_TARGET_TYPE_DEFAULT,
1440        pixelFormat: D2D1_PIXEL_FORMAT {
1441            format: pixel_format,
1442            alphaMode: alpha_mode,
1443        },
1444        dpiX: 96.0,
1445        dpiY: 96.0,
1446        usage: D2D1_RENDER_TARGET_USAGE_NONE,
1447        minLevel: D2D1_FEATURE_LEVEL_DEFAULT,
1448    }
1449}
1450
1451// One would think that with newer DirectWrite method: IDWriteFontFace4::GetGlyphImageFormats
1452// but that doesn't seem to work for some glyphs, say ❤
1453fn is_color_glyph(
1454    font_face: &IDWriteFontFace3,
1455    glyph_id: GlyphId,
1456    factory: &IDWriteFactory5,
1457) -> bool {
1458    let glyph_run = DWRITE_GLYPH_RUN {
1459        fontFace: unsafe { std::mem::transmute_copy(font_face) },
1460        fontEmSize: 14.0,
1461        glyphCount: 1,
1462        glyphIndices: &(glyph_id.0 as u16),
1463        glyphAdvances: &0.0,
1464        glyphOffsets: &DWRITE_GLYPH_OFFSET {
1465            advanceOffset: 0.0,
1466            ascenderOffset: 0.0,
1467        },
1468        isSideways: BOOL(0),
1469        bidiLevel: 0,
1470    };
1471    unsafe {
1472        factory.TranslateColorGlyphRun(
1473            D2D_POINT_2F::default(),
1474            &glyph_run as _,
1475            None,
1476            DWRITE_GLYPH_IMAGE_FORMATS_COLR
1477                | DWRITE_GLYPH_IMAGE_FORMATS_SVG
1478                | DWRITE_GLYPH_IMAGE_FORMATS_PNG
1479                | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
1480                | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8,
1481            DWRITE_MEASURING_MODE_NATURAL,
1482            None,
1483            0,
1484        )
1485    }
1486    .is_ok()
1487}
1488
1489const DEFAULT_LOCALE_NAME: PCWSTR = windows::core::w!("en-US");
1490const BRUSH_COLOR: D2D1_COLOR_F = D2D1_COLOR_F {
1491    r: 1.0,
1492    g: 1.0,
1493    b: 1.0,
1494    a: 1.0,
1495};