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