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                width: 0.0,
 602            };
 603            text_layout.Draw(
 604                Some(&renderer_context as *const _ as _),
 605                &text_renderer.0,
 606                0.0,
 607                0.0,
 608            )?;
 609            let width = px(renderer_context.width);
 610
 611            Ok(LineLayout {
 612                font_size,
 613                width,
 614                ascent,
 615                descent,
 616                runs,
 617                len: text.len(),
 618            })
 619        }
 620    }
 621
 622    fn font_metrics(&self, font_id: FontId) -> FontMetrics {
 623        unsafe {
 624            let font_info = &self.fonts[font_id.0];
 625            let mut metrics = std::mem::zeroed();
 626            font_info.font_face.GetMetrics(&mut metrics);
 627
 628            FontMetrics {
 629                units_per_em: metrics.Base.designUnitsPerEm as _,
 630                ascent: metrics.Base.ascent as _,
 631                descent: -(metrics.Base.descent as f32),
 632                line_gap: metrics.Base.lineGap as _,
 633                underline_position: metrics.Base.underlinePosition as _,
 634                underline_thickness: metrics.Base.underlineThickness as _,
 635                cap_height: metrics.Base.capHeight as _,
 636                x_height: metrics.Base.xHeight as _,
 637                bounding_box: Bounds {
 638                    origin: Point {
 639                        x: metrics.glyphBoxLeft as _,
 640                        y: metrics.glyphBoxBottom as _,
 641                    },
 642                    size: Size {
 643                        width: (metrics.glyphBoxRight - metrics.glyphBoxLeft) as _,
 644                        height: (metrics.glyphBoxTop - metrics.glyphBoxBottom) as _,
 645                    },
 646                },
 647            }
 648        }
 649    }
 650
 651    fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
 652        let render_target = &self.components.render_context.dc_target;
 653        unsafe {
 654            render_target.SetUnitMode(D2D1_UNIT_MODE_DIPS);
 655            render_target.SetDpi(96.0 * params.scale_factor, 96.0 * params.scale_factor);
 656        }
 657        let font = &self.fonts[params.font_id.0];
 658        let glyph_id = [params.glyph_id.0 as u16];
 659        let advance = [0.0f32];
 660        let offset = [DWRITE_GLYPH_OFFSET::default()];
 661        let glyph_run = DWRITE_GLYPH_RUN {
 662            fontFace: unsafe { std::mem::transmute_copy(&font.font_face) },
 663            fontEmSize: params.font_size.0,
 664            glyphCount: 1,
 665            glyphIndices: glyph_id.as_ptr(),
 666            glyphAdvances: advance.as_ptr(),
 667            glyphOffsets: offset.as_ptr(),
 668            isSideways: BOOL(0),
 669            bidiLevel: 0,
 670        };
 671        let bounds = unsafe {
 672            render_target.GetGlyphRunWorldBounds(
 673                Vector2 { X: 0.0, Y: 0.0 },
 674                &glyph_run,
 675                DWRITE_MEASURING_MODE_NATURAL,
 676            )?
 677        };
 678        // todo(windows)
 679        // This is a walkaround, deleted when figured out.
 680        let y_offset;
 681        let extra_height;
 682        if params.is_emoji {
 683            y_offset = 0;
 684            extra_height = 0;
 685        } else {
 686            // make some room for scaler.
 687            y_offset = -1;
 688            extra_height = 2;
 689        }
 690
 691        if bounds.right < bounds.left {
 692            Ok(Bounds {
 693                origin: point(0.into(), 0.into()),
 694                size: size(0.into(), 0.into()),
 695            })
 696        } else {
 697            Ok(Bounds {
 698                origin: point(
 699                    ((bounds.left * params.scale_factor).ceil() as i32).into(),
 700                    ((bounds.top * params.scale_factor).ceil() as i32 + y_offset).into(),
 701                ),
 702                size: size(
 703                    (((bounds.right - bounds.left) * params.scale_factor).ceil() as i32).into(),
 704                    (((bounds.bottom - bounds.top) * params.scale_factor).ceil() as i32
 705                        + extra_height)
 706                        .into(),
 707                ),
 708            })
 709        }
 710    }
 711
 712    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
 713        let font_info = &self.fonts[font_id.0];
 714        let codepoints = [ch as u32];
 715        let mut glyph_indices = vec![0u16; 1];
 716        unsafe {
 717            font_info
 718                .font_face
 719                .GetGlyphIndices(codepoints.as_ptr(), 1, glyph_indices.as_mut_ptr())
 720                .log_err()
 721        }
 722        .map(|_| GlyphId(glyph_indices[0] as u32))
 723    }
 724
 725    fn rasterize_glyph(
 726        &self,
 727        params: &RenderGlyphParams,
 728        glyph_bounds: Bounds<DevicePixels>,
 729    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
 730        if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
 731            anyhow::bail!("glyph bounds are empty");
 732        }
 733
 734        let font_info = &self.fonts[params.font_id.0];
 735        let glyph_id = [params.glyph_id.0 as u16];
 736        let advance = [glyph_bounds.size.width.0 as f32];
 737        let offset = [DWRITE_GLYPH_OFFSET {
 738            advanceOffset: -glyph_bounds.origin.x.0 as f32 / params.scale_factor,
 739            ascenderOffset: glyph_bounds.origin.y.0 as f32 / params.scale_factor,
 740        }];
 741        let glyph_run = DWRITE_GLYPH_RUN {
 742            fontFace: unsafe { std::mem::transmute_copy(&font_info.font_face) },
 743            fontEmSize: params.font_size.0,
 744            glyphCount: 1,
 745            glyphIndices: glyph_id.as_ptr(),
 746            glyphAdvances: advance.as_ptr(),
 747            glyphOffsets: offset.as_ptr(),
 748            isSideways: BOOL(0),
 749            bidiLevel: 0,
 750        };
 751
 752        // Add an extra pixel when the subpixel variant isn't zero to make room for anti-aliasing.
 753        let mut bitmap_size = glyph_bounds.size;
 754        if params.subpixel_variant.x > 0 {
 755            bitmap_size.width += DevicePixels(1);
 756        }
 757        if params.subpixel_variant.y > 0 {
 758            bitmap_size.height += DevicePixels(1);
 759        }
 760        let bitmap_size = bitmap_size;
 761
 762        let total_bytes;
 763        let bitmap_format;
 764        let render_target_property;
 765        let bitmap_width;
 766        let bitmap_height;
 767        let bitmap_stride;
 768        let bitmap_dpi;
 769        if params.is_emoji {
 770            total_bytes = bitmap_size.height.0 as usize * bitmap_size.width.0 as usize * 4;
 771            bitmap_format = &GUID_WICPixelFormat32bppPBGRA;
 772            render_target_property = get_render_target_property(
 773                DXGI_FORMAT_B8G8R8A8_UNORM,
 774                D2D1_ALPHA_MODE_PREMULTIPLIED,
 775            );
 776            bitmap_width = bitmap_size.width.0 as u32;
 777            bitmap_height = bitmap_size.height.0 as u32;
 778            bitmap_stride = bitmap_size.width.0 as u32 * 4;
 779            bitmap_dpi = 96.0;
 780        } else {
 781            total_bytes = bitmap_size.height.0 as usize * bitmap_size.width.0 as usize;
 782            bitmap_format = &GUID_WICPixelFormat8bppAlpha;
 783            render_target_property =
 784                get_render_target_property(DXGI_FORMAT_A8_UNORM, D2D1_ALPHA_MODE_STRAIGHT);
 785            bitmap_width = bitmap_size.width.0 as u32 * 2;
 786            bitmap_height = bitmap_size.height.0 as u32 * 2;
 787            bitmap_stride = bitmap_size.width.0 as u32;
 788            bitmap_dpi = 192.0;
 789        }
 790
 791        let bitmap_factory = self.components.bitmap_factory.resolve()?;
 792        unsafe {
 793            let bitmap = bitmap_factory.CreateBitmap(
 794                bitmap_width,
 795                bitmap_height,
 796                bitmap_format,
 797                WICBitmapCacheOnLoad,
 798            )?;
 799            let render_target = self
 800                .components
 801                .d2d1_factory
 802                .CreateWicBitmapRenderTarget(&bitmap, &render_target_property)?;
 803            let brush = render_target.CreateSolidColorBrush(&BRUSH_COLOR, None)?;
 804            let subpixel_shift = params
 805                .subpixel_variant
 806                .map(|v| v as f32 / SUBPIXEL_VARIANTS as f32);
 807            let baseline_origin = Vector2 {
 808                X: subpixel_shift.x / params.scale_factor,
 809                Y: subpixel_shift.y / params.scale_factor,
 810            };
 811
 812            // This `cast()` action here should never fail since we are running on Win10+, and
 813            // ID2D1DeviceContext4 requires Win8+
 814            let render_target = render_target.cast::<ID2D1DeviceContext4>().unwrap();
 815            render_target.SetUnitMode(D2D1_UNIT_MODE_DIPS);
 816            render_target.SetDpi(
 817                bitmap_dpi * params.scale_factor,
 818                bitmap_dpi * params.scale_factor,
 819            );
 820            render_target.SetTextRenderingParams(&self.components.render_context.params);
 821            render_target.BeginDraw();
 822
 823            if params.is_emoji {
 824                // WARN: only DWRITE_GLYPH_IMAGE_FORMATS_COLR has been tested
 825                let enumerator = self.components.factory.TranslateColorGlyphRun(
 826                    baseline_origin,
 827                    &glyph_run as _,
 828                    None,
 829                    DWRITE_GLYPH_IMAGE_FORMATS_COLR
 830                        | DWRITE_GLYPH_IMAGE_FORMATS_SVG
 831                        | DWRITE_GLYPH_IMAGE_FORMATS_PNG
 832                        | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
 833                        | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8,
 834                    DWRITE_MEASURING_MODE_NATURAL,
 835                    None,
 836                    0,
 837                )?;
 838                while enumerator.MoveNext().is_ok() {
 839                    let Ok(color_glyph) = enumerator.GetCurrentRun() else {
 840                        break;
 841                    };
 842                    let color_glyph = &*color_glyph;
 843                    let brush_color = translate_color(&color_glyph.Base.runColor);
 844                    brush.SetColor(&brush_color);
 845                    match color_glyph.glyphImageFormat {
 846                        DWRITE_GLYPH_IMAGE_FORMATS_PNG
 847                        | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
 848                        | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8 => render_target
 849                            .DrawColorBitmapGlyphRun(
 850                                color_glyph.glyphImageFormat,
 851                                baseline_origin,
 852                                &color_glyph.Base.glyphRun,
 853                                color_glyph.measuringMode,
 854                                D2D1_COLOR_BITMAP_GLYPH_SNAP_OPTION_DEFAULT,
 855                            ),
 856                        DWRITE_GLYPH_IMAGE_FORMATS_SVG => render_target.DrawSvgGlyphRun(
 857                            baseline_origin,
 858                            &color_glyph.Base.glyphRun,
 859                            &brush,
 860                            None,
 861                            color_glyph.Base.paletteIndex as u32,
 862                            color_glyph.measuringMode,
 863                        ),
 864                        _ => render_target.DrawGlyphRun(
 865                            baseline_origin,
 866                            &color_glyph.Base.glyphRun,
 867                            Some(color_glyph.Base.glyphRunDescription as *const _),
 868                            &brush,
 869                            color_glyph.measuringMode,
 870                        ),
 871                    }
 872                }
 873            } else {
 874                render_target.DrawGlyphRun(
 875                    baseline_origin,
 876                    &glyph_run,
 877                    None,
 878                    &brush,
 879                    DWRITE_MEASURING_MODE_NATURAL,
 880                );
 881            }
 882            render_target.EndDraw(None, None)?;
 883
 884            let mut raw_data = vec![0u8; total_bytes];
 885            if params.is_emoji {
 886                bitmap.CopyPixels(std::ptr::null() as _, bitmap_stride, &mut raw_data)?;
 887                // Convert from BGRA with premultiplied alpha to BGRA with straight alpha.
 888                for pixel in raw_data.chunks_exact_mut(4) {
 889                    let a = pixel[3] as f32 / 255.;
 890                    pixel[0] = (pixel[0] as f32 / a) as u8;
 891                    pixel[1] = (pixel[1] as f32 / a) as u8;
 892                    pixel[2] = (pixel[2] as f32 / a) as u8;
 893                }
 894            } else {
 895                let scaler = bitmap_factory.CreateBitmapScaler()?;
 896                scaler.Initialize(
 897                    &bitmap,
 898                    bitmap_size.width.0 as u32,
 899                    bitmap_size.height.0 as u32,
 900                    WICBitmapInterpolationModeHighQualityCubic,
 901                )?;
 902                scaler.CopyPixels(std::ptr::null() as _, bitmap_stride, &mut raw_data)?;
 903            }
 904            Ok((bitmap_size, raw_data))
 905        }
 906    }
 907
 908    fn get_typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
 909        unsafe {
 910            let font = &self.fonts[font_id.0].font_face;
 911            let glyph_indices = [glyph_id.0 as u16];
 912            let mut metrics = [DWRITE_GLYPH_METRICS::default()];
 913            font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
 914
 915            let metrics = &metrics[0];
 916            let advance_width = metrics.advanceWidth as i32;
 917            let advance_height = metrics.advanceHeight as i32;
 918            let left_side_bearing = metrics.leftSideBearing;
 919            let right_side_bearing = metrics.rightSideBearing;
 920            let top_side_bearing = metrics.topSideBearing;
 921            let bottom_side_bearing = metrics.bottomSideBearing;
 922            let vertical_origin_y = metrics.verticalOriginY;
 923
 924            let y_offset = vertical_origin_y + bottom_side_bearing - advance_height;
 925            let width = advance_width - (left_side_bearing + right_side_bearing);
 926            let height = advance_height - (top_side_bearing + bottom_side_bearing);
 927
 928            Ok(Bounds {
 929                origin: Point {
 930                    x: left_side_bearing as f32,
 931                    y: y_offset as f32,
 932                },
 933                size: Size {
 934                    width: width as f32,
 935                    height: height as f32,
 936                },
 937            })
 938        }
 939    }
 940
 941    fn get_advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
 942        unsafe {
 943            let font = &self.fonts[font_id.0].font_face;
 944            let glyph_indices = [glyph_id.0 as u16];
 945            let mut metrics = [DWRITE_GLYPH_METRICS::default()];
 946            font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
 947
 948            let metrics = &metrics[0];
 949
 950            Ok(Size {
 951                width: metrics.advanceWidth as f32,
 952                height: 0.0,
 953            })
 954        }
 955    }
 956
 957    fn all_font_names(&self) -> Vec<String> {
 958        let mut result =
 959            get_font_names_from_collection(&self.system_font_collection, &self.components.locale);
 960        result.extend(get_font_names_from_collection(
 961            &self.custom_font_collection,
 962            &self.components.locale,
 963        ));
 964        result
 965    }
 966}
 967
 968impl Drop for DirectWriteState {
 969    fn drop(&mut self) {
 970        unsafe {
 971            let _ = self
 972                .components
 973                .factory
 974                .UnregisterFontFileLoader(&self.components.in_memory_loader);
 975        }
 976    }
 977}
 978
 979struct TextRendererWrapper(pub IDWriteTextRenderer);
 980
 981impl TextRendererWrapper {
 982    pub fn new(locale_str: &str) -> Self {
 983        let inner = TextRenderer::new(locale_str);
 984        TextRendererWrapper(inner.into())
 985    }
 986}
 987
 988#[implement(IDWriteTextRenderer)]
 989struct TextRenderer {
 990    locale: String,
 991}
 992
 993impl TextRenderer {
 994    pub fn new(locale_str: &str) -> Self {
 995        TextRenderer {
 996            locale: locale_str.to_owned(),
 997        }
 998    }
 999}
1000
1001struct RendererContext<'t, 'a, 'b> {
1002    text_system: &'t mut DirectWriteState,
1003    index_converter: StringIndexConverter<'a>,
1004    runs: &'b mut Vec<ShapedRun>,
1005    width: f32,
1006}
1007
1008#[derive(Debug)]
1009struct ClusterAnalyzer<'t> {
1010    utf16_idx: usize,
1011    glyph_idx: usize,
1012    glyph_count: usize,
1013    cluster_map: &'t [u16],
1014}
1015
1016impl<'t> ClusterAnalyzer<'t> {
1017    pub fn new(cluster_map: &'t [u16], glyph_count: usize) -> Self {
1018        ClusterAnalyzer {
1019            utf16_idx: 0,
1020            glyph_idx: 0,
1021            glyph_count,
1022            cluster_map,
1023        }
1024    }
1025}
1026
1027impl Iterator for ClusterAnalyzer<'_> {
1028    type Item = (usize, usize);
1029
1030    fn next(&mut self) -> Option<(usize, usize)> {
1031        if self.utf16_idx >= self.cluster_map.len() {
1032            return None; // No more clusters
1033        }
1034        let start_utf16_idx = self.utf16_idx;
1035        let current_glyph = self.cluster_map[start_utf16_idx] as usize;
1036
1037        // Find the end of current cluster (where glyph index changes)
1038        let mut end_utf16_idx = start_utf16_idx + 1;
1039        while end_utf16_idx < self.cluster_map.len()
1040            && self.cluster_map[end_utf16_idx] as usize == current_glyph
1041        {
1042            end_utf16_idx += 1;
1043        }
1044
1045        let utf16_len = end_utf16_idx - start_utf16_idx;
1046
1047        // Calculate glyph count for this cluster
1048        let next_glyph = if end_utf16_idx < self.cluster_map.len() {
1049            self.cluster_map[end_utf16_idx] as usize
1050        } else {
1051            self.glyph_count
1052        };
1053
1054        let glyph_count = next_glyph - current_glyph;
1055
1056        // Update state for next call
1057        self.utf16_idx = end_utf16_idx;
1058        self.glyph_idx = next_glyph;
1059
1060        Some((utf16_len, glyph_count))
1061    }
1062}
1063
1064#[allow(non_snake_case)]
1065impl IDWritePixelSnapping_Impl for TextRenderer_Impl {
1066    fn IsPixelSnappingDisabled(
1067        &self,
1068        _clientdrawingcontext: *const ::core::ffi::c_void,
1069    ) -> windows::core::Result<BOOL> {
1070        Ok(BOOL(0))
1071    }
1072
1073    fn GetCurrentTransform(
1074        &self,
1075        _clientdrawingcontext: *const ::core::ffi::c_void,
1076        transform: *mut DWRITE_MATRIX,
1077    ) -> windows::core::Result<()> {
1078        unsafe {
1079            *transform = DWRITE_MATRIX {
1080                m11: 1.0,
1081                m12: 0.0,
1082                m21: 0.0,
1083                m22: 1.0,
1084                dx: 0.0,
1085                dy: 0.0,
1086            };
1087        }
1088        Ok(())
1089    }
1090
1091    fn GetPixelsPerDip(
1092        &self,
1093        _clientdrawingcontext: *const ::core::ffi::c_void,
1094    ) -> windows::core::Result<f32> {
1095        Ok(1.0)
1096    }
1097}
1098
1099#[allow(non_snake_case)]
1100impl IDWriteTextRenderer_Impl for TextRenderer_Impl {
1101    fn DrawGlyphRun(
1102        &self,
1103        clientdrawingcontext: *const ::core::ffi::c_void,
1104        _baselineoriginx: f32,
1105        _baselineoriginy: f32,
1106        _measuringmode: DWRITE_MEASURING_MODE,
1107        glyphrun: *const DWRITE_GLYPH_RUN,
1108        glyphrundescription: *const DWRITE_GLYPH_RUN_DESCRIPTION,
1109        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1110    ) -> windows::core::Result<()> {
1111        let glyphrun = unsafe { &*glyphrun };
1112        let glyph_count = glyphrun.glyphCount as usize;
1113        if glyph_count == 0 || glyphrun.fontFace.is_none() {
1114            return Ok(());
1115        }
1116        let desc = unsafe { &*glyphrundescription };
1117        let context = unsafe {
1118            &mut *(clientdrawingcontext as *const RendererContext as *mut RendererContext)
1119        };
1120        let font_face = glyphrun.fontFace.as_ref().unwrap();
1121        // This `cast()` action here should never fail since we are running on Win10+, and
1122        // `IDWriteFontFace3` requires Win10
1123        let font_face = &font_face.cast::<IDWriteFontFace3>().unwrap();
1124        let Some((font_identifier, font_struct, color_font)) =
1125            get_font_identifier_and_font_struct(font_face, &self.locale)
1126        else {
1127            return Ok(());
1128        };
1129
1130        let font_id = if let Some(id) = context
1131            .text_system
1132            .font_id_by_identifier
1133            .get(&font_identifier)
1134        {
1135            *id
1136        } else {
1137            context.text_system.select_font(&font_struct)
1138        };
1139
1140        let glyph_ids = unsafe { std::slice::from_raw_parts(glyphrun.glyphIndices, glyph_count) };
1141        let glyph_advances =
1142            unsafe { std::slice::from_raw_parts(glyphrun.glyphAdvances, glyph_count) };
1143        let glyph_offsets =
1144            unsafe { std::slice::from_raw_parts(glyphrun.glyphOffsets, glyph_count) };
1145        let cluster_map =
1146            unsafe { std::slice::from_raw_parts(desc.clusterMap, desc.stringLength as usize) };
1147
1148        let mut cluster_analyzer = ClusterAnalyzer::new(cluster_map, glyph_count);
1149        let mut utf16_idx = desc.textPosition as usize;
1150        let mut glyph_idx = 0;
1151        let mut glyphs = Vec::with_capacity(glyph_count);
1152        for (cluster_utf16_len, cluster_glyph_count) in cluster_analyzer {
1153            context.index_converter.advance_to_utf16_ix(utf16_idx);
1154            utf16_idx += cluster_utf16_len;
1155            for (cluster_glyph_idx, glyph_id) in glyph_ids
1156                [glyph_idx..(glyph_idx + cluster_glyph_count)]
1157                .iter()
1158                .enumerate()
1159            {
1160                let id = GlyphId(*glyph_id as u32);
1161                let is_emoji = color_font
1162                    && is_color_glyph(font_face, id, &context.text_system.components.factory);
1163                let this_glyph_idx = glyph_idx + cluster_glyph_idx;
1164                glyphs.push(ShapedGlyph {
1165                    id,
1166                    position: point(
1167                        px(context.width + glyph_offsets[this_glyph_idx].advanceOffset),
1168                        px(0.0),
1169                    ),
1170                    index: context.index_converter.utf8_ix,
1171                    is_emoji,
1172                });
1173                context.width += glyph_advances[this_glyph_idx];
1174            }
1175            glyph_idx += cluster_glyph_count;
1176        }
1177        context.runs.push(ShapedRun { font_id, glyphs });
1178        Ok(())
1179    }
1180
1181    fn DrawUnderline(
1182        &self,
1183        _clientdrawingcontext: *const ::core::ffi::c_void,
1184        _baselineoriginx: f32,
1185        _baselineoriginy: f32,
1186        _underline: *const DWRITE_UNDERLINE,
1187        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1188    ) -> windows::core::Result<()> {
1189        Err(windows::core::Error::new(
1190            E_NOTIMPL,
1191            "DrawUnderline unimplemented",
1192        ))
1193    }
1194
1195    fn DrawStrikethrough(
1196        &self,
1197        _clientdrawingcontext: *const ::core::ffi::c_void,
1198        _baselineoriginx: f32,
1199        _baselineoriginy: f32,
1200        _strikethrough: *const DWRITE_STRIKETHROUGH,
1201        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1202    ) -> windows::core::Result<()> {
1203        Err(windows::core::Error::new(
1204            E_NOTIMPL,
1205            "DrawStrikethrough unimplemented",
1206        ))
1207    }
1208
1209    fn DrawInlineObject(
1210        &self,
1211        _clientdrawingcontext: *const ::core::ffi::c_void,
1212        _originx: f32,
1213        _originy: f32,
1214        _inlineobject: windows::core::Ref<IDWriteInlineObject>,
1215        _issideways: BOOL,
1216        _isrighttoleft: BOOL,
1217        _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1218    ) -> windows::core::Result<()> {
1219        Err(windows::core::Error::new(
1220            E_NOTIMPL,
1221            "DrawInlineObject unimplemented",
1222        ))
1223    }
1224}
1225
1226struct StringIndexConverter<'a> {
1227    text: &'a str,
1228    utf8_ix: usize,
1229    utf16_ix: usize,
1230}
1231
1232impl<'a> StringIndexConverter<'a> {
1233    fn new(text: &'a str) -> Self {
1234        Self {
1235            text,
1236            utf8_ix: 0,
1237            utf16_ix: 0,
1238        }
1239    }
1240
1241    #[allow(dead_code)]
1242    fn advance_to_utf8_ix(&mut self, utf8_target: usize) {
1243        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1244            if self.utf8_ix + ix >= utf8_target {
1245                self.utf8_ix += ix;
1246                return;
1247            }
1248            self.utf16_ix += c.len_utf16();
1249        }
1250        self.utf8_ix = self.text.len();
1251    }
1252
1253    fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
1254        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1255            if self.utf16_ix >= utf16_target {
1256                self.utf8_ix += ix;
1257                return;
1258            }
1259            self.utf16_ix += c.len_utf16();
1260        }
1261        self.utf8_ix = self.text.len();
1262    }
1263}
1264
1265impl Into<DWRITE_FONT_STYLE> for FontStyle {
1266    fn into(self) -> DWRITE_FONT_STYLE {
1267        match self {
1268            FontStyle::Normal => DWRITE_FONT_STYLE_NORMAL,
1269            FontStyle::Italic => DWRITE_FONT_STYLE_ITALIC,
1270            FontStyle::Oblique => DWRITE_FONT_STYLE_OBLIQUE,
1271        }
1272    }
1273}
1274
1275impl From<DWRITE_FONT_STYLE> for FontStyle {
1276    fn from(value: DWRITE_FONT_STYLE) -> Self {
1277        match value.0 {
1278            0 => FontStyle::Normal,
1279            1 => FontStyle::Italic,
1280            2 => FontStyle::Oblique,
1281            _ => unreachable!(),
1282        }
1283    }
1284}
1285
1286impl Into<DWRITE_FONT_WEIGHT> for FontWeight {
1287    fn into(self) -> DWRITE_FONT_WEIGHT {
1288        DWRITE_FONT_WEIGHT(self.0 as i32)
1289    }
1290}
1291
1292impl From<DWRITE_FONT_WEIGHT> for FontWeight {
1293    fn from(value: DWRITE_FONT_WEIGHT) -> Self {
1294        FontWeight(value.0 as f32)
1295    }
1296}
1297
1298fn get_font_names_from_collection(
1299    collection: &IDWriteFontCollection1,
1300    locale: &str,
1301) -> Vec<String> {
1302    unsafe {
1303        let mut result = Vec::new();
1304        let family_count = collection.GetFontFamilyCount();
1305        for index in 0..family_count {
1306            let Some(font_family) = collection.GetFontFamily(index).log_err() else {
1307                continue;
1308            };
1309            let Some(localized_family_name) = font_family.GetFamilyNames().log_err() else {
1310                continue;
1311            };
1312            let Some(family_name) = get_name(localized_family_name, locale).log_err() else {
1313                continue;
1314            };
1315            result.push(family_name);
1316        }
1317
1318        result
1319    }
1320}
1321
1322fn get_font_identifier_and_font_struct(
1323    font_face: &IDWriteFontFace3,
1324    locale: &str,
1325) -> Option<(FontIdentifier, Font, bool)> {
1326    let postscript_name = get_postscript_name(font_face, locale).log_err()?;
1327    let localized_family_name = unsafe { font_face.GetFamilyNames().log_err() }?;
1328    let family_name = get_name(localized_family_name, locale).log_err()?;
1329    let weight = unsafe { font_face.GetWeight() };
1330    let style = unsafe { font_face.GetStyle() };
1331    let identifier = FontIdentifier {
1332        postscript_name,
1333        weight: weight.0,
1334        style: style.0,
1335    };
1336    let font_struct = Font {
1337        family: family_name.into(),
1338        features: FontFeatures::default(),
1339        weight: weight.into(),
1340        style: style.into(),
1341        fallbacks: None,
1342    };
1343    let is_emoji = unsafe { font_face.IsColorFont().as_bool() };
1344    Some((identifier, font_struct, is_emoji))
1345}
1346
1347#[inline]
1348fn get_font_identifier(font_face: &IDWriteFontFace3, locale: &str) -> Option<FontIdentifier> {
1349    let weight = unsafe { font_face.GetWeight().0 };
1350    let style = unsafe { font_face.GetStyle().0 };
1351    get_postscript_name(font_face, locale)
1352        .log_err()
1353        .map(|postscript_name| FontIdentifier {
1354            postscript_name,
1355            weight,
1356            style,
1357        })
1358}
1359
1360#[inline]
1361fn get_postscript_name(font_face: &IDWriteFontFace3, locale: &str) -> Result<String> {
1362    let mut info = None;
1363    let mut exists = BOOL(0);
1364    unsafe {
1365        font_face.GetInformationalStrings(
1366            DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_NAME,
1367            &mut info,
1368            &mut exists,
1369        )?
1370    };
1371    if !exists.as_bool() || info.is_none() {
1372        anyhow::bail!("No postscript name found for font face");
1373    }
1374
1375    get_name(info.unwrap(), locale)
1376}
1377
1378// https://learn.microsoft.com/en-us/windows/win32/api/dwrite/ne-dwrite-dwrite_font_feature_tag
1379fn apply_font_features(
1380    direct_write_features: &IDWriteTypography,
1381    features: &FontFeatures,
1382) -> Result<()> {
1383    let tag_values = features.tag_value_list();
1384    if tag_values.is_empty() {
1385        return Ok(());
1386    }
1387
1388    // All of these features are enabled by default by DirectWrite.
1389    // If you want to (and can) peek into the source of DirectWrite
1390    let mut feature_liga = make_direct_write_feature("liga", 1);
1391    let mut feature_clig = make_direct_write_feature("clig", 1);
1392    let mut feature_calt = make_direct_write_feature("calt", 1);
1393
1394    for (tag, value) in tag_values {
1395        if tag.as_str() == "liga" && *value == 0 {
1396            feature_liga.parameter = 0;
1397            continue;
1398        }
1399        if tag.as_str() == "clig" && *value == 0 {
1400            feature_clig.parameter = 0;
1401            continue;
1402        }
1403        if tag.as_str() == "calt" && *value == 0 {
1404            feature_calt.parameter = 0;
1405            continue;
1406        }
1407
1408        unsafe {
1409            direct_write_features.AddFontFeature(make_direct_write_feature(&tag, *value))?;
1410        }
1411    }
1412    unsafe {
1413        direct_write_features.AddFontFeature(feature_liga)?;
1414        direct_write_features.AddFontFeature(feature_clig)?;
1415        direct_write_features.AddFontFeature(feature_calt)?;
1416    }
1417
1418    Ok(())
1419}
1420
1421#[inline]
1422const fn make_direct_write_feature(feature_name: &str, parameter: u32) -> DWRITE_FONT_FEATURE {
1423    let tag = make_direct_write_tag(feature_name);
1424    DWRITE_FONT_FEATURE {
1425        nameTag: tag,
1426        parameter,
1427    }
1428}
1429
1430#[inline]
1431const fn make_open_type_tag(tag_name: &str) -> u32 {
1432    let bytes = tag_name.as_bytes();
1433    debug_assert!(bytes.len() == 4);
1434    u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
1435}
1436
1437#[inline]
1438const fn make_direct_write_tag(tag_name: &str) -> DWRITE_FONT_FEATURE_TAG {
1439    DWRITE_FONT_FEATURE_TAG(make_open_type_tag(tag_name))
1440}
1441
1442#[inline]
1443fn get_name(string: IDWriteLocalizedStrings, locale: &str) -> Result<String> {
1444    let mut locale_name_index = 0u32;
1445    let mut exists = BOOL(0);
1446    unsafe {
1447        string.FindLocaleName(
1448            &HSTRING::from(locale),
1449            &mut locale_name_index,
1450            &mut exists as _,
1451        )?
1452    };
1453    if !exists.as_bool() {
1454        unsafe {
1455            string.FindLocaleName(
1456                DEFAULT_LOCALE_NAME,
1457                &mut locale_name_index as _,
1458                &mut exists as _,
1459            )?
1460        };
1461        anyhow::ensure!(exists.as_bool(), "No localised string for {locale}");
1462    }
1463
1464    let name_length = unsafe { string.GetStringLength(locale_name_index) }? as usize;
1465    let mut name_vec = vec![0u16; name_length + 1];
1466    unsafe {
1467        string.GetString(locale_name_index, &mut name_vec)?;
1468    }
1469
1470    Ok(String::from_utf16_lossy(&name_vec[..name_length]))
1471}
1472
1473#[inline]
1474fn translate_color(color: &DWRITE_COLOR_F) -> D2D1_COLOR_F {
1475    D2D1_COLOR_F {
1476        r: color.r,
1477        g: color.g,
1478        b: color.b,
1479        a: color.a,
1480    }
1481}
1482
1483fn get_system_ui_font_name() -> SharedString {
1484    unsafe {
1485        let mut info: LOGFONTW = std::mem::zeroed();
1486        let font_family = if SystemParametersInfoW(
1487            SPI_GETICONTITLELOGFONT,
1488            std::mem::size_of::<LOGFONTW>() as u32,
1489            Some(&mut info as *mut _ as _),
1490            SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
1491        )
1492        .log_err()
1493        .is_none()
1494        {
1495            // https://learn.microsoft.com/en-us/windows/win32/uxguide/vis-fonts
1496            // Segoe UI is the Windows font intended for user interface text strings.
1497            "Segoe UI".into()
1498        } else {
1499            let font_name = String::from_utf16_lossy(&info.lfFaceName);
1500            font_name.trim_matches(char::from(0)).to_owned().into()
1501        };
1502        log::info!("Use {} as UI font.", font_family);
1503        font_family
1504    }
1505}
1506
1507#[inline]
1508fn get_render_target_property(
1509    pixel_format: DXGI_FORMAT,
1510    alpha_mode: D2D1_ALPHA_MODE,
1511) -> D2D1_RENDER_TARGET_PROPERTIES {
1512    D2D1_RENDER_TARGET_PROPERTIES {
1513        r#type: D2D1_RENDER_TARGET_TYPE_DEFAULT,
1514        pixelFormat: D2D1_PIXEL_FORMAT {
1515            format: pixel_format,
1516            alphaMode: alpha_mode,
1517        },
1518        dpiX: 96.0,
1519        dpiY: 96.0,
1520        usage: D2D1_RENDER_TARGET_USAGE_NONE,
1521        minLevel: D2D1_FEATURE_LEVEL_DEFAULT,
1522    }
1523}
1524
1525// One would think that with newer DirectWrite method: IDWriteFontFace4::GetGlyphImageFormats
1526// but that doesn't seem to work for some glyphs, say โค
1527fn is_color_glyph(
1528    font_face: &IDWriteFontFace3,
1529    glyph_id: GlyphId,
1530    factory: &IDWriteFactory5,
1531) -> bool {
1532    let glyph_run = DWRITE_GLYPH_RUN {
1533        fontFace: unsafe { std::mem::transmute_copy(font_face) },
1534        fontEmSize: 14.0,
1535        glyphCount: 1,
1536        glyphIndices: &(glyph_id.0 as u16),
1537        glyphAdvances: &0.0,
1538        glyphOffsets: &DWRITE_GLYPH_OFFSET {
1539            advanceOffset: 0.0,
1540            ascenderOffset: 0.0,
1541        },
1542        isSideways: BOOL(0),
1543        bidiLevel: 0,
1544    };
1545    unsafe {
1546        factory.TranslateColorGlyphRun(
1547            Vector2::default(),
1548            &glyph_run as _,
1549            None,
1550            DWRITE_GLYPH_IMAGE_FORMATS_COLR
1551                | DWRITE_GLYPH_IMAGE_FORMATS_SVG
1552                | DWRITE_GLYPH_IMAGE_FORMATS_PNG
1553                | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
1554                | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8,
1555            DWRITE_MEASURING_MODE_NATURAL,
1556            None,
1557            0,
1558        )
1559    }
1560    .is_ok()
1561}
1562
1563const DEFAULT_LOCALE_NAME: PCWSTR = windows::core::w!("en-US");
1564const BRUSH_COLOR: D2D1_COLOR_F = D2D1_COLOR_F {
1565    r: 1.0,
1566    g: 1.0,
1567    b: 1.0,
1568    a: 1.0,
1569};
1570
1571#[cfg(test)]
1572mod tests {
1573    use crate::platform::windows::direct_write::ClusterAnalyzer;
1574
1575    #[test]
1576    fn test_cluster_map() {
1577        let cluster_map = [0];
1578        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 1);
1579        let next = analyzer.next();
1580        assert_eq!(next, Some((1, 1)));
1581        let next = analyzer.next();
1582        assert_eq!(next, None);
1583
1584        let cluster_map = [0, 1, 2];
1585        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 3);
1586        let next = analyzer.next();
1587        assert_eq!(next, Some((1, 1)));
1588        let next = analyzer.next();
1589        assert_eq!(next, Some((1, 1)));
1590        let next = analyzer.next();
1591        assert_eq!(next, Some((1, 1)));
1592        let next = analyzer.next();
1593        assert_eq!(next, None);
1594        // ๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ๐Ÿ‘ฉโ€๐Ÿ’ป
1595        let cluster_map = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4];
1596        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 5);
1597        let next = analyzer.next();
1598        assert_eq!(next, Some((11, 4)));
1599        let next = analyzer.next();
1600        assert_eq!(next, Some((5, 1)));
1601        let next = analyzer.next();
1602        assert_eq!(next, None);
1603        // ๐Ÿ‘ฉโ€๐Ÿ’ป
1604        let cluster_map = [0, 0, 0, 0, 0];
1605        let mut analyzer = ClusterAnalyzer::new(&cluster_map, 1);
1606        let next = analyzer.next();
1607        assert_eq!(next, Some((5, 1)));
1608        let next = analyzer.next();
1609        assert_eq!(next, None);
1610    }
1611}