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