direct_write.rs

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