direct_write.rs

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