direct_write.rs

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