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