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.CreateFontSetBuilder()?;
85 let mut locale_vec = vec![0u16; LOCALE_NAME_MAX_LENGTH as usize];
86 GetUserDefaultLocaleName(&mut locale_vec);
87 let locale = String::from_utf16_lossy(&locale_vec);
88 let text_renderer = Arc::new(TextRendererWrapper::new(&locale));
89
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 .GetSystemFontCollection(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 .GetSystemFontCollection(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.GetMetrics(&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 Some(&transform as _),
553 DWRITE_RENDERING_MODE1_NATURAL,
554 DWRITE_MEASURING_MODE_NATURAL,
555 DWRITE_GRID_FIT_MODE_DEFAULT,
556 DWRITE_TEXT_ANTIALIAS_MODE_CLEARTYPE,
557 0.0,
558 0.0,
559 )
560 }
561
562 fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
563 unsafe {
564 let glyph_run_analysis = self.get_glyphrun_analysis(params)?;
565 let bounds = glyph_run_analysis.GetAlphaTextureBounds(DWRITE_TEXTURE_CLEARTYPE_3x1)?;
566
567 Ok(Bounds {
568 origin: Point {
569 x: DevicePixels(bounds.left),
570 y: DevicePixels(bounds.top),
571 },
572 size: Size {
573 width: DevicePixels(bounds.right - bounds.left),
574 height: DevicePixels(bounds.bottom - bounds.top),
575 },
576 })
577 }
578 }
579
580 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
581 let font_info = &self.fonts[font_id.0];
582 let codepoints = [ch as u32];
583 let mut glyph_indices = vec![0u16; 1];
584 unsafe {
585 font_info
586 .font_face
587 .GetGlyphIndices(codepoints.as_ptr(), 1, glyph_indices.as_mut_ptr())
588 .log_err()
589 }
590 .map(|_| GlyphId(glyph_indices[0] as u32))
591 }
592
593 fn rasterize_glyph(
594 &self,
595 params: &RenderGlyphParams,
596 glyph_bounds: Bounds<DevicePixels>,
597 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
598 if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
599 return Err(anyhow!("glyph bounds are empty"));
600 }
601
602 let font_info = &self.fonts[params.font_id.0];
603 let glyph_id = [params.glyph_id.0 as u16];
604 let advance = [glyph_bounds.size.width.0 as f32];
605 let offset = [DWRITE_GLYPH_OFFSET {
606 advanceOffset: -glyph_bounds.origin.x.0 as f32 / params.scale_factor,
607 ascenderOffset: glyph_bounds.origin.y.0 as f32 / params.scale_factor,
608 }];
609 let glyph_run = DWRITE_GLYPH_RUN {
610 fontFace: unsafe { std::mem::transmute_copy(&font_info.font_face) },
611 fontEmSize: params.font_size.0,
612 glyphCount: 1,
613 glyphIndices: glyph_id.as_ptr(),
614 glyphAdvances: advance.as_ptr(),
615 glyphOffsets: offset.as_ptr(),
616 isSideways: BOOL(0),
617 bidiLevel: 0,
618 };
619
620 // Add an extra pixel when the subpixel variant isn't zero to make room for anti-aliasing.
621 let mut bitmap_size = glyph_bounds.size;
622 if params.subpixel_variant.x > 0 {
623 bitmap_size.width += DevicePixels(1);
624 }
625 if params.subpixel_variant.y > 0 {
626 bitmap_size.height += DevicePixels(1);
627 }
628 let bitmap_size = bitmap_size;
629 let transform = DWRITE_MATRIX {
630 m11: params.scale_factor,
631 m12: 0.0,
632 m21: 0.0,
633 m22: params.scale_factor,
634 dx: 0.0,
635 dy: 0.0,
636 };
637 let brush_property = D2D1_BRUSH_PROPERTIES {
638 opacity: 1.0,
639 transform: Matrix3x2 {
640 M11: params.scale_factor,
641 M12: 0.0,
642 M21: 0.0,
643 M22: params.scale_factor,
644 M31: 0.0,
645 M32: 0.0,
646 },
647 };
648
649 let total_bytes;
650 let bitmap_format;
651 let render_target_property;
652 let bitmap_stride;
653 if params.is_emoji {
654 total_bytes = bitmap_size.height.0 as usize * bitmap_size.width.0 as usize * 4;
655 bitmap_format = &GUID_WICPixelFormat32bppPBGRA;
656 render_target_property = D2D1_RENDER_TARGET_PROPERTIES {
657 r#type: D2D1_RENDER_TARGET_TYPE_DEFAULT,
658 pixelFormat: D2D1_PIXEL_FORMAT {
659 format: DXGI_FORMAT_B8G8R8A8_UNORM,
660 alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED,
661 },
662 dpiX: params.scale_factor * 96.0,
663 dpiY: params.scale_factor * 96.0,
664 usage: D2D1_RENDER_TARGET_USAGE_NONE,
665 minLevel: D2D1_FEATURE_LEVEL_DEFAULT,
666 };
667 bitmap_stride = bitmap_size.width.0 as u32 * 4;
668 } else {
669 total_bytes = bitmap_size.height.0 as usize * bitmap_size.width.0 as usize;
670 bitmap_format = &GUID_WICPixelFormat8bppAlpha;
671 render_target_property = D2D1_RENDER_TARGET_PROPERTIES {
672 r#type: D2D1_RENDER_TARGET_TYPE_DEFAULT,
673 pixelFormat: D2D1_PIXEL_FORMAT {
674 format: DXGI_FORMAT_A8_UNORM,
675 alphaMode: D2D1_ALPHA_MODE_STRAIGHT,
676 },
677 dpiX: params.scale_factor * 96.0,
678 dpiY: params.scale_factor * 96.0,
679 usage: D2D1_RENDER_TARGET_USAGE_NONE,
680 minLevel: D2D1_FEATURE_LEVEL_DEFAULT,
681 };
682 bitmap_stride = bitmap_size.width.0 as u32;
683 }
684
685 unsafe {
686 let bitmap = self.components.bitmap_factory.CreateBitmap(
687 bitmap_size.width.0 as u32,
688 bitmap_size.height.0 as u32,
689 bitmap_format,
690 WICBitmapCacheOnLoad,
691 )?;
692 let render_target = self
693 .components
694 .d2d1_factory
695 .CreateWicBitmapRenderTarget(&bitmap, &render_target_property)?;
696 let brush = render_target.CreateSolidColorBrush(&BRUSH_COLOR, Some(&brush_property))?;
697 let subpixel_shift = params
698 .subpixel_variant
699 .map(|v| v as f32 / SUBPIXEL_VARIANTS as f32);
700 let baseline_origin = D2D_POINT_2F {
701 x: subpixel_shift.x / params.scale_factor,
702 y: subpixel_shift.y / params.scale_factor,
703 };
704
705 // This `cast()` action here should never fail since we are running on Win10+, and
706 // ID2D1DeviceContext4 requires Win8+
707 let render_target = render_target.cast::<ID2D1DeviceContext4>().unwrap();
708 render_target.BeginDraw();
709 if params.is_emoji {
710 // WARN: only DWRITE_GLYPH_IMAGE_FORMATS_COLR has been tested
711 let enumerator = self.components.factory.TranslateColorGlyphRun(
712 baseline_origin,
713 &glyph_run as _,
714 None,
715 DWRITE_GLYPH_IMAGE_FORMATS_COLR
716 | DWRITE_GLYPH_IMAGE_FORMATS_SVG
717 | DWRITE_GLYPH_IMAGE_FORMATS_PNG
718 | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
719 | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8,
720 DWRITE_MEASURING_MODE_NATURAL,
721 Some(&transform as _),
722 0,
723 )?;
724 while enumerator.MoveNext().is_ok() {
725 let Ok(color_glyph) = enumerator.GetCurrentRun() else {
726 break;
727 };
728 let color_glyph = &*color_glyph;
729 let brush_color = translate_color(&color_glyph.Base.runColor);
730 brush.SetColor(&brush_color);
731 match color_glyph.glyphImageFormat {
732 DWRITE_GLYPH_IMAGE_FORMATS_PNG
733 | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
734 | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8 => render_target
735 .DrawColorBitmapGlyphRun(
736 color_glyph.glyphImageFormat,
737 baseline_origin,
738 &color_glyph.Base.glyphRun,
739 color_glyph.measuringMode,
740 D2D1_COLOR_BITMAP_GLYPH_SNAP_OPTION_DEFAULT,
741 ),
742 DWRITE_GLYPH_IMAGE_FORMATS_SVG => render_target.DrawSvgGlyphRun(
743 baseline_origin,
744 &color_glyph.Base.glyphRun,
745 &brush,
746 None,
747 color_glyph.Base.paletteIndex as u32,
748 color_glyph.measuringMode,
749 ),
750 _ => render_target.DrawGlyphRun(
751 baseline_origin,
752 &color_glyph.Base.glyphRun,
753 Some(color_glyph.Base.glyphRunDescription as *const _),
754 &brush,
755 color_glyph.measuringMode,
756 ),
757 }
758 }
759 } else {
760 render_target.DrawGlyphRun(
761 baseline_origin,
762 &glyph_run,
763 None,
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((font_identifier, font_struct, is_emoji)) =
956 get_font_identifier_and_font_struct(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_identifier
965 .get(&font_identifier)
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
1131fn get_font_identifier_and_font_struct(
1132 font_face: &IDWriteFontFace3,
1133 locale: &str,
1134) -> Option<(FontIdentifier, Font, bool)> {
1135 let Some(postscript_name) = get_postscript_name(font_face, locale) else {
1136 return None;
1137 };
1138 let Some(localized_family_name) = (unsafe { 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 weight = unsafe { font_face.GetWeight() };
1145 let style = unsafe { font_face.GetStyle() };
1146 let identifier = FontIdentifier {
1147 postscript_name,
1148 weight: weight.0,
1149 style: style.0,
1150 };
1151 let font_struct = Font {
1152 family: family_name.into(),
1153 features: FontFeatures::default(),
1154 weight: weight.into(),
1155 style: style.into(),
1156 };
1157 let is_emoji = unsafe { font_face.IsColorFont().as_bool() };
1158 Some((identifier, font_struct, is_emoji))
1159}
1160
1161#[inline]
1162fn get_font_identifier(font_face: &IDWriteFontFace3, locale: &str) -> Option<FontIdentifier> {
1163 let weight = unsafe { font_face.GetWeight().0 };
1164 let style = unsafe { font_face.GetStyle().0 };
1165 get_postscript_name(font_face, locale).map(|postscript_name| FontIdentifier {
1166 postscript_name,
1167 weight,
1168 style,
1169 })
1170}
1171
1172#[inline]
1173fn get_postscript_name(font_face: &IDWriteFontFace3, locale: &str) -> Option<String> {
1174 let mut info = None;
1175 let mut exists = BOOL(0);
1176 unsafe {
1177 font_face
1178 .GetInformationalStrings(
1179 DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_NAME,
1180 &mut info,
1181 &mut exists,
1182 )
1183 .log_err();
1184 }
1185 if !exists.as_bool() || info.is_none() {
1186 return None;
1187 }
1188
1189 get_name(info.unwrap(), locale)
1190}
1191
1192// https://learn.microsoft.com/en-us/windows/win32/api/dwrite/ne-dwrite-dwrite_font_feature_tag
1193fn apply_font_features(
1194 direct_write_features: &IDWriteTypography,
1195 features: &FontFeatures,
1196) -> Result<()> {
1197 let tag_values = features.tag_value_list();
1198 if tag_values.is_empty() {
1199 return Ok(());
1200 }
1201
1202 // All of these features are enabled by default by DirectWrite.
1203 // If you want to (and can) peek into the source of DirectWrite
1204 let mut feature_liga = make_direct_write_feature("liga", 1);
1205 let mut feature_clig = make_direct_write_feature("clig", 1);
1206 let mut feature_calt = make_direct_write_feature("calt", 1);
1207
1208 for (tag, value) in tag_values {
1209 if tag.as_str() == "liga" && *value == 0 {
1210 feature_liga.parameter = 0;
1211 continue;
1212 }
1213 if tag.as_str() == "clig" && *value == 0 {
1214 feature_clig.parameter = 0;
1215 continue;
1216 }
1217 if tag.as_str() == "calt" && *value == 0 {
1218 feature_calt.parameter = 0;
1219 continue;
1220 }
1221
1222 unsafe {
1223 direct_write_features.AddFontFeature(make_direct_write_feature(&tag, *value))?;
1224 }
1225 }
1226 unsafe {
1227 direct_write_features.AddFontFeature(feature_liga)?;
1228 direct_write_features.AddFontFeature(feature_clig)?;
1229 direct_write_features.AddFontFeature(feature_calt)?;
1230 }
1231
1232 Ok(())
1233}
1234
1235#[inline]
1236fn make_direct_write_feature(feature_name: &str, parameter: u32) -> DWRITE_FONT_FEATURE {
1237 let tag = make_direct_write_tag(feature_name);
1238 DWRITE_FONT_FEATURE {
1239 nameTag: tag,
1240 parameter,
1241 }
1242}
1243
1244#[inline]
1245fn make_open_type_tag(tag_name: &str) -> u32 {
1246 assert_eq!(tag_name.chars().count(), 4);
1247 let bytes = tag_name.bytes().collect_vec();
1248 ((bytes[3] as u32) << 24)
1249 | ((bytes[2] as u32) << 16)
1250 | ((bytes[1] as u32) << 8)
1251 | (bytes[0] as u32)
1252}
1253
1254#[inline]
1255fn make_direct_write_tag(tag_name: &str) -> DWRITE_FONT_FEATURE_TAG {
1256 DWRITE_FONT_FEATURE_TAG(make_open_type_tag(tag_name))
1257}
1258
1259#[inline]
1260fn get_name(string: IDWriteLocalizedStrings, locale: &str) -> Option<String> {
1261 let mut locale_name_index = 0u32;
1262 let mut exists = BOOL(0);
1263 unsafe {
1264 string
1265 .FindLocaleName(
1266 &HSTRING::from(locale),
1267 &mut locale_name_index,
1268 &mut exists as _,
1269 )
1270 .log_err();
1271 }
1272 if !exists.as_bool() {
1273 unsafe {
1274 string
1275 .FindLocaleName(
1276 DEFAULT_LOCALE_NAME,
1277 &mut locale_name_index as _,
1278 &mut exists as _,
1279 )
1280 .log_err();
1281 }
1282 if !exists.as_bool() {
1283 return None;
1284 }
1285 }
1286
1287 let name_length = unsafe { string.GetStringLength(locale_name_index).unwrap() } as usize;
1288 let mut name_vec = vec![0u16; name_length + 1];
1289 unsafe {
1290 string.GetString(locale_name_index, &mut name_vec).unwrap();
1291 }
1292
1293 Some(String::from_utf16_lossy(&name_vec[..name_length]))
1294}
1295
1296#[inline]
1297fn translate_color(color: &DWRITE_COLOR_F) -> D2D1_COLOR_F {
1298 D2D1_COLOR_F {
1299 r: color.r,
1300 g: color.g,
1301 b: color.b,
1302 a: color.a,
1303 }
1304}
1305
1306fn get_system_ui_font_name() -> SharedString {
1307 unsafe {
1308 let mut info: LOGFONTW = std::mem::zeroed();
1309 let font_family = if SystemParametersInfoW(
1310 SPI_GETICONTITLELOGFONT,
1311 std::mem::size_of::<LOGFONTW>() as u32,
1312 Some(&mut info as *mut _ as _),
1313 SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
1314 )
1315 .log_err()
1316 .is_none()
1317 {
1318 // https://learn.microsoft.com/en-us/windows/win32/uxguide/vis-fonts
1319 // Segoe UI is the Windows font intended for user interface text strings.
1320 "Segoe UI".into()
1321 } else {
1322 let font_name = String::from_utf16_lossy(&info.lfFaceName);
1323 font_name.trim_matches(char::from(0)).to_owned().into()
1324 };
1325 log::info!("Use {} as UI font.", font_family);
1326 font_family
1327 }
1328}
1329
1330const DEFAULT_LOCALE_NAME: PCWSTR = windows::core::w!("en-US");
1331const BRUSH_COLOR: D2D1_COLOR_F = D2D1_COLOR_F {
1332 r: 1.0,
1333 g: 1.0,
1334 b: 1.0,
1335 a: 1.0,
1336};