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