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