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};
  25use windows_numerics::Vector2;
  26
  27use crate::*;
  28
  29#[derive(Debug)]
  30struct FontInfo {
  31    font_family: String,
  32    font_face: IDWriteFontFace3,
  33    features: IDWriteTypography,
  34    fallbacks: Option<IDWriteFontFallback>,
  35    is_system_font: bool,
  36    is_emoji: bool,
  37}
  38
  39pub(crate) struct DirectWriteTextSystem(RwLock<DirectWriteState>);
  40
  41struct DirectWriteComponent {
  42    locale: String,
  43    factory: IDWriteFactory5,
  44    bitmap_factory: AgileReference<IWICImagingFactory>,
  45    d2d1_factory: ID2D1Factory,
  46    in_memory_loader: IDWriteInMemoryFontFileLoader,
  47    builder: IDWriteFontSetBuilder1,
  48    text_renderer: Arc<TextRendererWrapper>,
  49    render_context: GlyphRenderContext,
  50}
  51
  52struct GlyphRenderContext {
  53    params: IDWriteRenderingParams3,
  54    dc_target: ID2D1DeviceContext4,
  55}
  56
  57struct DirectWriteState {
  58    components: DirectWriteComponent,
  59    system_ui_font_name: SharedString,
  60    system_font_collection: IDWriteFontCollection1,
  61    custom_font_collection: IDWriteFontCollection1,
  62    fonts: Vec<FontInfo>,
  63    font_selections: HashMap<Font, FontId>,
  64    font_id_by_identifier: HashMap<FontIdentifier, FontId>,
  65}
  66
  67#[derive(Debug, Clone, Hash, PartialEq, Eq)]
  68struct FontIdentifier {
  69    postscript_name: String,
  70    weight: i32,
  71    style: i32,
  72}
  73
  74impl DirectWriteComponent {
  75    pub fn new(bitmap_factory: &IWICImagingFactory) -> Result<Self> {
  76        unsafe {
  77            let factory: IDWriteFactory5 = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED)?;
  78            let bitmap_factory = AgileReference::new(bitmap_factory)?;
  79            let d2d1_factory: ID2D1Factory =
  80                D2D1CreateFactory(D2D1_FACTORY_TYPE_MULTI_THREADED, None)?;
  81            // The `IDWriteInMemoryFontFileLoader` here is supported starting from
  82            // Windows 10 Creators Update, which consequently requires the entire
  83            // `DirectWriteTextSystem` to run on `win10 1703`+.
  84            let in_memory_loader = factory.CreateInMemoryFontFileLoader()?;
  85            factory.RegisterFontFileLoader(&in_memory_loader)?;
  86            let builder = factory.CreateFontSetBuilder()?;
  87            let mut locale_vec = vec![0u16; LOCALE_NAME_MAX_LENGTH as usize];
  88            GetUserDefaultLocaleName(&mut locale_vec);
  89            let locale = String::from_utf16_lossy(&locale_vec);
  90            let text_renderer = Arc::new(TextRendererWrapper::new(&locale));
  91            let render_context = GlyphRenderContext::new(&factory, &d2d1_factory)?;
  92
  93            Ok(DirectWriteComponent {
  94                locale,
  95                factory,
  96                bitmap_factory,
  97                d2d1_factory,
  98                in_memory_loader,
  99                builder,
 100                text_renderer,
 101                render_context,
 102            })
 103        }
 104    }
 105}
 106
 107impl GlyphRenderContext {
 108    pub fn new(factory: &IDWriteFactory5, d2d1_factory: &ID2D1Factory) -> Result<Self> {
 109        unsafe {
 110            let default_params: IDWriteRenderingParams3 =
 111                factory.CreateRenderingParams()?.cast()?;
 112            let gamma = default_params.GetGamma();
 113            let enhanced_contrast = default_params.GetEnhancedContrast();
 114            let gray_contrast = default_params.GetGrayscaleEnhancedContrast();
 115            let cleartype_level = default_params.GetClearTypeLevel();
 116            let grid_fit_mode = default_params.GetGridFitMode();
 117
 118            let params = factory.CreateCustomRenderingParams(
 119                gamma,
 120                enhanced_contrast,
 121                gray_contrast,
 122                cleartype_level,
 123                DWRITE_PIXEL_GEOMETRY_RGB,
 124                DWRITE_RENDERING_MODE1_NATURAL_SYMMETRIC,
 125                grid_fit_mode,
 126            )?;
 127            let dc_target = {
 128                let target = d2d1_factory.CreateDCRenderTarget(&get_render_target_property(
 129                    DXGI_FORMAT_B8G8R8A8_UNORM,
 130                    D2D1_ALPHA_MODE_PREMULTIPLIED,
 131                ))?;
 132                let target = target.cast::<ID2D1DeviceContext4>()?;
 133                target.SetTextRenderingParams(&params);
 134                target
 135            };
 136
 137            Ok(Self { params, dc_target })
 138        }
 139    }
 140}
 141
 142impl DirectWriteTextSystem {
 143    pub(crate) fn new(bitmap_factory: &IWICImagingFactory) -> Result<Self> {
 144        let components = DirectWriteComponent::new(bitmap_factory)?;
 145        let system_font_collection = unsafe {
 146            let mut result = std::mem::zeroed();
 147            components
 148                .factory
 149                .GetSystemFontCollection(false, &mut result, true)?;
 150            result.unwrap()
 151        };
 152        let custom_font_set = unsafe { components.builder.CreateFontSet()? };
 153        let custom_font_collection = unsafe {
 154            components
 155                .factory
 156                .CreateFontCollectionFromFontSet(&custom_font_set)?
 157        };
 158        let system_ui_font_name = get_system_ui_font_name();
 159
 160        Ok(Self(RwLock::new(DirectWriteState {
 161            components,
 162            system_ui_font_name,
 163            system_font_collection,
 164            custom_font_collection,
 165            fonts: Vec::new(),
 166            font_selections: HashMap::default(),
 167            font_id_by_identifier: HashMap::default(),
 168        })))
 169    }
 170}
 171
 172impl PlatformTextSystem for DirectWriteTextSystem {
 173    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
 174        self.0.write().add_fonts(fonts)
 175    }
 176
 177    fn all_font_names(&self) -> Vec<String> {
 178        self.0.read().all_font_names()
 179    }
 180
 181    fn font_id(&self, font: &Font) -> Result<FontId> {
 182        let lock = self.0.upgradable_read();
 183        if let Some(font_id) = lock.font_selections.get(font) {
 184            Ok(*font_id)
 185        } else {
 186            let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
 187            let font_id = lock.select_font(font);
 188            lock.font_selections.insert(font.clone(), font_id);
 189            Ok(font_id)
 190        }
 191    }
 192
 193    fn font_metrics(&self, font_id: FontId) -> FontMetrics {
 194        self.0.read().font_metrics(font_id)
 195    }
 196
 197    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
 198        self.0.read().get_typographic_bounds(font_id, glyph_id)
 199    }
 200
 201    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Size<f32>> {
 202        self.0.read().get_advance(font_id, glyph_id)
 203    }
 204
 205    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
 206        self.0.read().glyph_for_char(font_id, ch)
 207    }
 208
 209    fn glyph_raster_bounds(
 210        &self,
 211        params: &RenderGlyphParams,
 212    ) -> anyhow::Result<Bounds<DevicePixels>> {
 213        self.0.read().raster_bounds(params)
 214    }
 215
 216    fn rasterize_glyph(
 217        &self,
 218        params: &RenderGlyphParams,
 219        raster_bounds: Bounds<DevicePixels>,
 220    ) -> anyhow::Result<(Size<DevicePixels>, Vec<u8>)> {
 221        self.0.read().rasterize_glyph(params, raster_bounds)
 222    }
 223
 224    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {
 225        self.0
 226            .write()
 227            .layout_line(text, font_size, runs)
 228            .log_err()
 229            .unwrap_or(LineLayout {
 230                font_size,
 231                ..Default::default()
 232            })
 233    }
 234}
 235
 236impl DirectWriteState {
 237    fn add_fonts(&mut self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
 238        for font_data in fonts {
 239            match font_data {
 240                Cow::Borrowed(data) => unsafe {
 241                    let font_file = self
 242                        .components
 243                        .in_memory_loader
 244                        .CreateInMemoryFontFileReference(
 245                            &self.components.factory,
 246                            data.as_ptr() as _,
 247                            data.len() as _,
 248                            None,
 249                        )?;
 250                    self.components.builder.AddFontFile(&font_file)?;
 251                },
 252                Cow::Owned(data) => unsafe {
 253                    let font_file = self
 254                        .components
 255                        .in_memory_loader
 256                        .CreateInMemoryFontFileReference(
 257                            &self.components.factory,
 258                            data.as_ptr() as _,
 259                            data.len() as _,
 260                            None,
 261                        )?;
 262                    self.components.builder.AddFontFile(&font_file)?;
 263                },
 264            }
 265        }
 266        let set = unsafe { self.components.builder.CreateFontSet()? };
 267        let collection = unsafe {
 268            self.components
 269                .factory
 270                .CreateFontCollectionFromFontSet(&set)?
 271        };
 272        self.custom_font_collection = collection;
 273
 274        Ok(())
 275    }
 276
 277    fn generate_font_fallbacks(
 278        &self,
 279        fallbacks: &FontFallbacks,
 280    ) -> Result<Option<IDWriteFontFallback>> {
 281        if fallbacks.fallback_list().is_empty() {
 282            return Ok(None);
 283        }
 284        unsafe {
 285            let builder = self.components.factory.CreateFontFallbackBuilder()?;
 286            let font_set = &self.system_font_collection.GetFontSet()?;
 287            for family_name in fallbacks.fallback_list() {
 288                let Some(fonts) = font_set
 289                    .GetMatchingFonts(
 290                        &HSTRING::from(family_name),
 291                        DWRITE_FONT_WEIGHT_NORMAL,
 292                        DWRITE_FONT_STRETCH_NORMAL,
 293                        DWRITE_FONT_STYLE_NORMAL,
 294                    )
 295                    .log_err()
 296                else {
 297                    continue;
 298                };
 299                if fonts.GetFontCount() == 0 {
 300                    log::error!("No matching font found for {}", family_name);
 301                    continue;
 302                }
 303                let font = fonts.GetFontFaceReference(0)?.CreateFontFace()?;
 304                let mut count = 0;
 305                font.GetUnicodeRanges(None, &mut count).ok();
 306                if count == 0 {
 307                    continue;
 308                }
 309                let mut unicode_ranges = vec![DWRITE_UNICODE_RANGE::default(); count as usize];
 310                let Some(_) = font
 311                    .GetUnicodeRanges(Some(&mut unicode_ranges), &mut count)
 312                    .log_err()
 313                else {
 314                    continue;
 315                };
 316                let target_family_name = HSTRING::from(family_name);
 317                builder.AddMapping(
 318                    &unicode_ranges,
 319                    &[target_family_name.as_ptr()],
 320                    None,
 321                    None,
 322                    None,
 323                    1.0,
 324                )?;
 325            }
 326            let system_fallbacks = self.components.factory.GetSystemFontFallback()?;
 327            builder.AddMappings(&system_fallbacks)?;
 328            Ok(Some(builder.CreateFontFallback()?))
 329        }
 330    }
 331
 332    unsafe fn generate_font_features(
 333        &self,
 334        font_features: &FontFeatures,
 335    ) -> Result<IDWriteTypography> {
 336        let direct_write_features = self.components.factory.CreateTypography()?;
 337        apply_font_features(&direct_write_features, font_features)?;
 338        Ok(direct_write_features)
 339    }
 340
 341    unsafe fn get_font_id_from_font_collection(
 342        &mut self,
 343        family_name: &str,
 344        font_weight: FontWeight,
 345        font_style: FontStyle,
 346        font_features: &FontFeatures,
 347        font_fallbacks: Option<&FontFallbacks>,
 348        is_system_font: bool,
 349    ) -> Option<FontId> {
 350        let collection = if is_system_font {
 351            &self.system_font_collection
 352        } else {
 353            &self.custom_font_collection
 354        };
 355        let fontset = collection.GetFontSet().log_err()?;
 356        let font = fontset
 357            .GetMatchingFonts(
 358                &HSTRING::from(family_name),
 359                font_weight.into(),
 360                DWRITE_FONT_STRETCH_NORMAL,
 361                font_style.into(),
 362            )
 363            .log_err()?;
 364        let total_number = font.GetFontCount();
 365        for index in 0..total_number {
 366            let Some(font_face_ref) = font.GetFontFaceReference(index).log_err() else {
 367                continue;
 368            };
 369            let Some(font_face) = font_face_ref.CreateFontFace().log_err() else {
 370                continue;
 371            };
 372            let Some(identifier) = get_font_identifier(&font_face, &self.components.locale) else {
 373                continue;
 374            };
 375            let is_emoji = font_face.IsColorFont().as_bool();
 376            let Some(direct_write_features) = self.generate_font_features(font_features).log_err()
 377            else {
 378                continue;
 379            };
 380            let fallbacks = font_fallbacks
 381                .and_then(|fallbacks| self.generate_font_fallbacks(fallbacks).log_err().flatten());
 382            let font_info = FontInfo {
 383                font_family: family_name.to_owned(),
 384                font_face,
 385                features: direct_write_features,
 386                fallbacks,
 387                is_system_font,
 388                is_emoji,
 389            };
 390            let font_id = FontId(self.fonts.len());
 391            self.fonts.push(font_info);
 392            self.font_id_by_identifier.insert(identifier, font_id);
 393            return Some(font_id);
 394        }
 395        None
 396    }
 397
 398    unsafe fn update_system_font_collection(&mut self) {
 399        let mut collection = std::mem::zeroed();
 400        if self
 401            .components
 402            .factory
 403            .GetSystemFontCollection(false, &mut collection, true)
 404            .log_err()
 405            .is_some()
 406        {
 407            self.system_font_collection = collection.unwrap();
 408        }
 409    }
 410
 411    fn select_font(&mut self, target_font: &Font) -> FontId {
 412        unsafe {
 413            if target_font.family == ".SystemUIFont" {
 414                let family = self.system_ui_font_name.clone();
 415                self.find_font_id(
 416                    family.as_ref(),
 417                    target_font.weight,
 418                    target_font.style,
 419                    &target_font.features,
 420                    target_font.fallbacks.as_ref(),
 421                )
 422                .unwrap()
 423            } else {
 424                self.find_font_id(
 425                    target_font.family.as_ref(),
 426                    target_font.weight,
 427                    target_font.style,
 428                    &target_font.features,
 429                    target_font.fallbacks.as_ref(),
 430                )
 431                .unwrap_or_else(|| {
 432                    #[cfg(any(test, feature = "test-support"))]
 433                    {
 434                        panic!("ERROR: {} font not found!", target_font.family);
 435                    }
 436                    #[cfg(not(any(test, feature = "test-support")))]
 437                    {
 438                        let family = self.system_ui_font_name.clone();
 439                        log::error!("{} not found, use {} instead.", target_font.family, family);
 440                        self.get_font_id_from_font_collection(
 441                            family.as_ref(),
 442                            target_font.weight,
 443                            target_font.style,
 444                            &target_font.features,
 445                            target_font.fallbacks.as_ref(),
 446                            true,
 447                        )
 448                        .unwrap()
 449                    }
 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                Vector2 { 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 = Vector2 {
 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
 967impl Drop for DirectWriteState {
 968    fn drop(&mut self) {
 969        unsafe {
 970            let _ = self
 971                .components
 972                .factory
 973                .UnregisterFontFileLoader(&self.components.in_memory_loader);
 974        }
 975    }
 976}
 977
 978struct TextRendererWrapper(pub IDWriteTextRenderer);
 979
 980impl TextRendererWrapper {
 981    pub fn new(locale_str: &str) -> Self {
 982        let inner = TextRenderer::new(locale_str);
 983        TextRendererWrapper(inner.into())
 984    }
 985}
 986
 987#[implement(IDWriteTextRenderer)]
 988struct TextRenderer {
 989    locale: String,
 990}
 991
 992impl TextRenderer {
 993    pub fn new(locale_str: &str) -> Self {
 994        TextRenderer {
 995            locale: locale_str.to_owned(),
 996        }
 997    }
 998}
 999
1000struct RendererContext<'t, 'a, 'b> {
1001    text_system: &'t mut DirectWriteState,
1002    index_converter: StringIndexConverter<'a>,
1003    runs: &'b mut Vec<ShapedRun>,
1004    utf16_index: usize,
1005    width: f32,
1006}
1007
1008#[allow(non_snake_case)]
1009impl IDWritePixelSnapping_Impl for TextRenderer_Impl {
1010    fn IsPixelSnappingDisabled(
1011        &self,
1012        _clientdrawingcontext: *const ::core::ffi::c_void,
1013    ) -> windows::core::Result<BOOL> {
1014        Ok(BOOL(0))
1015    }
1016
1017    fn GetCurrentTransform(
1018        &self,
1019        _clientdrawingcontext: *const ::core::ffi::c_void,
1020        transform: *mut DWRITE_MATRIX,
1021    ) -> windows::core::Result<()> {
1022        unsafe {
1023            *transform = DWRITE_MATRIX {
1024                m11: 1.0,
1025                m12: 0.0,
1026                m21: 0.0,
1027                m22: 1.0,
1028                dx: 0.0,
1029                dy: 0.0,
1030            };
1031        }
1032        Ok(())
1033    }
1034
1035    fn GetPixelsPerDip(
1036        &self,
1037        _clientdrawingcontext: *const ::core::ffi::c_void,
1038    ) -> windows::core::Result<f32> {
1039        Ok(1.0)
1040    }
1041}
1042
1043#[allow(non_snake_case)]
1044impl IDWriteTextRenderer_Impl for TextRenderer_Impl {
1045    fn DrawGlyphRun(
1046        &self,
1047        clientdrawingcontext: *const ::core::ffi::c_void,
1048        _baselineoriginx: f32,
1049        _baselineoriginy: f32,
1050        _measuringmode: DWRITE_MEASURING_MODE,
1051        glyphrun: *const DWRITE_GLYPH_RUN,
1052        glyphrundescription: *const DWRITE_GLYPH_RUN_DESCRIPTION,
1053        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1054    ) -> windows::core::Result<()> {
1055        unsafe {
1056            let glyphrun = &*glyphrun;
1057            let glyph_count = glyphrun.glyphCount as usize;
1058            if glyph_count == 0 {
1059                return Ok(());
1060            }
1061            let desc = &*glyphrundescription;
1062            let utf16_length_per_glyph = desc.stringLength as usize / glyph_count;
1063            let context =
1064                &mut *(clientdrawingcontext as *const RendererContext as *mut RendererContext);
1065
1066            if glyphrun.fontFace.is_none() {
1067                return Ok(());
1068            }
1069
1070            let font_face = glyphrun.fontFace.as_ref().unwrap();
1071            // This `cast()` action here should never fail since we are running on Win10+, and
1072            // `IDWriteFontFace3` requires Win10
1073            let font_face = &font_face.cast::<IDWriteFontFace3>().unwrap();
1074            let Some((font_identifier, font_struct, color_font)) =
1075                get_font_identifier_and_font_struct(font_face, &self.locale)
1076            else {
1077                return Ok(());
1078            };
1079
1080            let font_id = if let Some(id) = context
1081                .text_system
1082                .font_id_by_identifier
1083                .get(&font_identifier)
1084            {
1085                *id
1086            } else {
1087                context.text_system.select_font(&font_struct)
1088            };
1089            let mut glyphs = SmallVec::new();
1090            for index in 0..glyph_count {
1091                let id = GlyphId(*glyphrun.glyphIndices.add(index) as u32);
1092                context
1093                    .index_converter
1094                    .advance_to_utf16_ix(context.utf16_index);
1095                let is_emoji = color_font
1096                    && is_color_glyph(font_face, id, &context.text_system.components.factory);
1097                glyphs.push(ShapedGlyph {
1098                    id,
1099                    position: point(px(context.width), px(0.0)),
1100                    index: context.index_converter.utf8_ix,
1101                    is_emoji,
1102                });
1103                context.utf16_index += utf16_length_per_glyph;
1104                context.width += *glyphrun.glyphAdvances.add(index);
1105            }
1106            context.runs.push(ShapedRun { font_id, glyphs });
1107        }
1108        Ok(())
1109    }
1110
1111    fn DrawUnderline(
1112        &self,
1113        _clientdrawingcontext: *const ::core::ffi::c_void,
1114        _baselineoriginx: f32,
1115        _baselineoriginy: f32,
1116        _underline: *const DWRITE_UNDERLINE,
1117        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1118    ) -> windows::core::Result<()> {
1119        Err(windows::core::Error::new(
1120            E_NOTIMPL,
1121            "DrawUnderline unimplemented",
1122        ))
1123    }
1124
1125    fn DrawStrikethrough(
1126        &self,
1127        _clientdrawingcontext: *const ::core::ffi::c_void,
1128        _baselineoriginx: f32,
1129        _baselineoriginy: f32,
1130        _strikethrough: *const DWRITE_STRIKETHROUGH,
1131        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1132    ) -> windows::core::Result<()> {
1133        Err(windows::core::Error::new(
1134            E_NOTIMPL,
1135            "DrawStrikethrough unimplemented",
1136        ))
1137    }
1138
1139    fn DrawInlineObject(
1140        &self,
1141        _clientdrawingcontext: *const ::core::ffi::c_void,
1142        _originx: f32,
1143        _originy: f32,
1144        _inlineobject: windows::core::Ref<IDWriteInlineObject>,
1145        _issideways: BOOL,
1146        _isrighttoleft: BOOL,
1147        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1148    ) -> windows::core::Result<()> {
1149        Err(windows::core::Error::new(
1150            E_NOTIMPL,
1151            "DrawInlineObject unimplemented",
1152        ))
1153    }
1154}
1155
1156struct StringIndexConverter<'a> {
1157    text: &'a str,
1158    utf8_ix: usize,
1159    utf16_ix: usize,
1160}
1161
1162impl<'a> StringIndexConverter<'a> {
1163    fn new(text: &'a str) -> Self {
1164        Self {
1165            text,
1166            utf8_ix: 0,
1167            utf16_ix: 0,
1168        }
1169    }
1170
1171    fn advance_to_utf8_ix(&mut self, utf8_target: usize) {
1172        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1173            if self.utf8_ix + ix >= utf8_target {
1174                self.utf8_ix += ix;
1175                return;
1176            }
1177            self.utf16_ix += c.len_utf16();
1178        }
1179        self.utf8_ix = self.text.len();
1180    }
1181
1182    fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
1183        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1184            if self.utf16_ix >= utf16_target {
1185                self.utf8_ix += ix;
1186                return;
1187            }
1188            self.utf16_ix += c.len_utf16();
1189        }
1190        self.utf8_ix = self.text.len();
1191    }
1192}
1193
1194impl Into<DWRITE_FONT_STYLE> for FontStyle {
1195    fn into(self) -> DWRITE_FONT_STYLE {
1196        match self {
1197            FontStyle::Normal => DWRITE_FONT_STYLE_NORMAL,
1198            FontStyle::Italic => DWRITE_FONT_STYLE_ITALIC,
1199            FontStyle::Oblique => DWRITE_FONT_STYLE_OBLIQUE,
1200        }
1201    }
1202}
1203
1204impl From<DWRITE_FONT_STYLE> for FontStyle {
1205    fn from(value: DWRITE_FONT_STYLE) -> Self {
1206        match value.0 {
1207            0 => FontStyle::Normal,
1208            1 => FontStyle::Italic,
1209            2 => FontStyle::Oblique,
1210            _ => unreachable!(),
1211        }
1212    }
1213}
1214
1215impl Into<DWRITE_FONT_WEIGHT> for FontWeight {
1216    fn into(self) -> DWRITE_FONT_WEIGHT {
1217        DWRITE_FONT_WEIGHT(self.0 as i32)
1218    }
1219}
1220
1221impl From<DWRITE_FONT_WEIGHT> for FontWeight {
1222    fn from(value: DWRITE_FONT_WEIGHT) -> Self {
1223        FontWeight(value.0 as f32)
1224    }
1225}
1226
1227fn get_font_names_from_collection(
1228    collection: &IDWriteFontCollection1,
1229    locale: &str,
1230) -> Vec<String> {
1231    unsafe {
1232        let mut result = Vec::new();
1233        let family_count = collection.GetFontFamilyCount();
1234        for index in 0..family_count {
1235            let Some(font_family) = collection.GetFontFamily(index).log_err() else {
1236                continue;
1237            };
1238            let Some(localized_family_name) = font_family.GetFamilyNames().log_err() else {
1239                continue;
1240            };
1241            let Some(family_name) = get_name(localized_family_name, locale).log_err() else {
1242                continue;
1243            };
1244            result.push(family_name);
1245        }
1246
1247        result
1248    }
1249}
1250
1251fn get_font_identifier_and_font_struct(
1252    font_face: &IDWriteFontFace3,
1253    locale: &str,
1254) -> Option<(FontIdentifier, Font, bool)> {
1255    let postscript_name = get_postscript_name(font_face, locale).log_err()?;
1256    let localized_family_name = unsafe { font_face.GetFamilyNames().log_err() }?;
1257    let family_name = get_name(localized_family_name, locale).log_err()?;
1258    let weight = unsafe { font_face.GetWeight() };
1259    let style = unsafe { font_face.GetStyle() };
1260    let identifier = FontIdentifier {
1261        postscript_name,
1262        weight: weight.0,
1263        style: style.0,
1264    };
1265    let font_struct = Font {
1266        family: family_name.into(),
1267        features: FontFeatures::default(),
1268        weight: weight.into(),
1269        style: style.into(),
1270        fallbacks: None,
1271    };
1272    let is_emoji = unsafe { font_face.IsColorFont().as_bool() };
1273    Some((identifier, font_struct, is_emoji))
1274}
1275
1276#[inline]
1277fn get_font_identifier(font_face: &IDWriteFontFace3, locale: &str) -> Option<FontIdentifier> {
1278    let weight = unsafe { font_face.GetWeight().0 };
1279    let style = unsafe { font_face.GetStyle().0 };
1280    get_postscript_name(font_face, locale)
1281        .log_err()
1282        .map(|postscript_name| FontIdentifier {
1283            postscript_name,
1284            weight,
1285            style,
1286        })
1287}
1288
1289#[inline]
1290fn get_postscript_name(font_face: &IDWriteFontFace3, locale: &str) -> Result<String> {
1291    let mut info = None;
1292    let mut exists = BOOL(0);
1293    unsafe {
1294        font_face.GetInformationalStrings(
1295            DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_NAME,
1296            &mut info,
1297            &mut exists,
1298        )?
1299    };
1300    if !exists.as_bool() || info.is_none() {
1301        return Err(anyhow!("No postscript name found for font face"));
1302    }
1303
1304    get_name(info.unwrap(), locale)
1305}
1306
1307// https://learn.microsoft.com/en-us/windows/win32/api/dwrite/ne-dwrite-dwrite_font_feature_tag
1308fn apply_font_features(
1309    direct_write_features: &IDWriteTypography,
1310    features: &FontFeatures,
1311) -> Result<()> {
1312    let tag_values = features.tag_value_list();
1313    if tag_values.is_empty() {
1314        return Ok(());
1315    }
1316
1317    // All of these features are enabled by default by DirectWrite.
1318    // If you want to (and can) peek into the source of DirectWrite
1319    let mut feature_liga = make_direct_write_feature("liga", 1);
1320    let mut feature_clig = make_direct_write_feature("clig", 1);
1321    let mut feature_calt = make_direct_write_feature("calt", 1);
1322
1323    for (tag, value) in tag_values {
1324        if tag.as_str() == "liga" && *value == 0 {
1325            feature_liga.parameter = 0;
1326            continue;
1327        }
1328        if tag.as_str() == "clig" && *value == 0 {
1329            feature_clig.parameter = 0;
1330            continue;
1331        }
1332        if tag.as_str() == "calt" && *value == 0 {
1333            feature_calt.parameter = 0;
1334            continue;
1335        }
1336
1337        unsafe {
1338            direct_write_features.AddFontFeature(make_direct_write_feature(&tag, *value))?;
1339        }
1340    }
1341    unsafe {
1342        direct_write_features.AddFontFeature(feature_liga)?;
1343        direct_write_features.AddFontFeature(feature_clig)?;
1344        direct_write_features.AddFontFeature(feature_calt)?;
1345    }
1346
1347    Ok(())
1348}
1349
1350#[inline]
1351fn make_direct_write_feature(feature_name: &str, parameter: u32) -> DWRITE_FONT_FEATURE {
1352    let tag = make_direct_write_tag(feature_name);
1353    DWRITE_FONT_FEATURE {
1354        nameTag: tag,
1355        parameter,
1356    }
1357}
1358
1359#[inline]
1360fn make_open_type_tag(tag_name: &str) -> u32 {
1361    let bytes = tag_name.bytes().collect_vec();
1362    assert_eq!(bytes.len(), 4);
1363    ((bytes[3] as u32) << 24)
1364        | ((bytes[2] as u32) << 16)
1365        | ((bytes[1] as u32) << 8)
1366        | (bytes[0] as u32)
1367}
1368
1369#[inline]
1370fn make_direct_write_tag(tag_name: &str) -> DWRITE_FONT_FEATURE_TAG {
1371    DWRITE_FONT_FEATURE_TAG(make_open_type_tag(tag_name))
1372}
1373
1374#[inline]
1375fn get_name(string: IDWriteLocalizedStrings, locale: &str) -> Result<String> {
1376    let mut locale_name_index = 0u32;
1377    let mut exists = BOOL(0);
1378    unsafe {
1379        string.FindLocaleName(
1380            &HSTRING::from(locale),
1381            &mut locale_name_index,
1382            &mut exists as _,
1383        )?
1384    };
1385    if !exists.as_bool() {
1386        unsafe {
1387            string.FindLocaleName(
1388                DEFAULT_LOCALE_NAME,
1389                &mut locale_name_index as _,
1390                &mut exists as _,
1391            )?
1392        };
1393        if !exists.as_bool() {
1394            return Err(anyhow!("No localised string for {}", locale));
1395        }
1396    }
1397
1398    let name_length = unsafe { string.GetStringLength(locale_name_index) }? as usize;
1399    let mut name_vec = vec![0u16; name_length + 1];
1400    unsafe {
1401        string.GetString(locale_name_index, &mut name_vec)?;
1402    }
1403
1404    Ok(String::from_utf16_lossy(&name_vec[..name_length]))
1405}
1406
1407#[inline]
1408fn translate_color(color: &DWRITE_COLOR_F) -> D2D1_COLOR_F {
1409    D2D1_COLOR_F {
1410        r: color.r,
1411        g: color.g,
1412        b: color.b,
1413        a: color.a,
1414    }
1415}
1416
1417fn get_system_ui_font_name() -> SharedString {
1418    unsafe {
1419        let mut info: LOGFONTW = std::mem::zeroed();
1420        let font_family = if SystemParametersInfoW(
1421            SPI_GETICONTITLELOGFONT,
1422            std::mem::size_of::<LOGFONTW>() as u32,
1423            Some(&mut info as *mut _ as _),
1424            SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
1425        )
1426        .log_err()
1427        .is_none()
1428        {
1429            // https://learn.microsoft.com/en-us/windows/win32/uxguide/vis-fonts
1430            // Segoe UI is the Windows font intended for user interface text strings.
1431            "Segoe UI".into()
1432        } else {
1433            let font_name = String::from_utf16_lossy(&info.lfFaceName);
1434            font_name.trim_matches(char::from(0)).to_owned().into()
1435        };
1436        log::info!("Use {} as UI font.", font_family);
1437        font_family
1438    }
1439}
1440
1441#[inline]
1442fn get_render_target_property(
1443    pixel_format: DXGI_FORMAT,
1444    alpha_mode: D2D1_ALPHA_MODE,
1445) -> D2D1_RENDER_TARGET_PROPERTIES {
1446    D2D1_RENDER_TARGET_PROPERTIES {
1447        r#type: D2D1_RENDER_TARGET_TYPE_DEFAULT,
1448        pixelFormat: D2D1_PIXEL_FORMAT {
1449            format: pixel_format,
1450            alphaMode: alpha_mode,
1451        },
1452        dpiX: 96.0,
1453        dpiY: 96.0,
1454        usage: D2D1_RENDER_TARGET_USAGE_NONE,
1455        minLevel: D2D1_FEATURE_LEVEL_DEFAULT,
1456    }
1457}
1458
1459// One would think that with newer DirectWrite method: IDWriteFontFace4::GetGlyphImageFormats
1460// but that doesn't seem to work for some glyphs, say ❤
1461fn is_color_glyph(
1462    font_face: &IDWriteFontFace3,
1463    glyph_id: GlyphId,
1464    factory: &IDWriteFactory5,
1465) -> bool {
1466    let glyph_run = DWRITE_GLYPH_RUN {
1467        fontFace: unsafe { std::mem::transmute_copy(font_face) },
1468        fontEmSize: 14.0,
1469        glyphCount: 1,
1470        glyphIndices: &(glyph_id.0 as u16),
1471        glyphAdvances: &0.0,
1472        glyphOffsets: &DWRITE_GLYPH_OFFSET {
1473            advanceOffset: 0.0,
1474            ascenderOffset: 0.0,
1475        },
1476        isSideways: BOOL(0),
1477        bidiLevel: 0,
1478    };
1479    unsafe {
1480        factory.TranslateColorGlyphRun(
1481            Vector2::default(),
1482            &glyph_run as _,
1483            None,
1484            DWRITE_GLYPH_IMAGE_FORMATS_COLR
1485                | DWRITE_GLYPH_IMAGE_FORMATS_SVG
1486                | DWRITE_GLYPH_IMAGE_FORMATS_PNG
1487                | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
1488                | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8,
1489            DWRITE_MEASURING_MODE_NATURAL,
1490            None,
1491            0,
1492        )
1493    }
1494    .is_ok()
1495}
1496
1497const DEFAULT_LOCALE_NAME: PCWSTR = windows::core::w!("en-US");
1498const BRUSH_COLOR: D2D1_COLOR_F = D2D1_COLOR_F {
1499    r: 1.0,
1500    g: 1.0,
1501    b: 1.0,
1502    a: 1.0,
1503};