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