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 {
371 font_size,
372 ..Default::default()
373 };
374 }
375 unsafe {
376 let text_renderer = self.components.text_renderer.clone();
377 let text_wide = text.encode_utf16().collect_vec();
378
379 let mut utf8_offset = 0usize;
380 let mut utf16_offset = 0u32;
381 let text_layout = {
382 let first_run = &font_runs[0];
383 let font_info = &self.fonts[first_run.font_id.0];
384 let collection = if font_info.is_system_font {
385 &self.system_font_collection
386 } else {
387 &self.custom_font_collection
388 };
389 let format = self
390 .components
391 .factory
392 .CreateTextFormat(
393 &HSTRING::from(&font_info.font_family),
394 collection,
395 font_info.font_face.GetWeight(),
396 font_info.font_face.GetStyle(),
397 DWRITE_FONT_STRETCH_NORMAL,
398 font_size.0,
399 &HSTRING::from(&self.components.locale),
400 )
401 .unwrap();
402
403 let layout = self
404 .components
405 .factory
406 .CreateTextLayout(&text_wide, &format, f32::INFINITY, f32::INFINITY)
407 .unwrap();
408 let current_text = &text[utf8_offset..(utf8_offset + first_run.len)];
409 utf8_offset += first_run.len;
410 let current_text_utf16_length = current_text.encode_utf16().count() as u32;
411 let text_range = DWRITE_TEXT_RANGE {
412 startPosition: utf16_offset,
413 length: current_text_utf16_length,
414 };
415 layout
416 .SetTypography(&font_info.features, text_range)
417 .unwrap();
418 utf16_offset += current_text_utf16_length;
419
420 layout
421 };
422
423 let mut first_run = true;
424 let mut ascent = Pixels::default();
425 let mut descent = Pixels::default();
426 for run in font_runs {
427 if first_run {
428 first_run = false;
429 let mut metrics = vec![DWRITE_LINE_METRICS::default(); 4];
430 let mut line_count = 0u32;
431 text_layout
432 .GetLineMetrics(Some(&mut metrics), &mut line_count as _)
433 .unwrap();
434 ascent = px(metrics[0].baseline);
435 descent = px(metrics[0].height - metrics[0].baseline);
436 continue;
437 }
438 let font_info = &self.fonts[run.font_id.0];
439 let current_text = &text[utf8_offset..(utf8_offset + run.len)];
440 utf8_offset += run.len;
441 let current_text_utf16_length = current_text.encode_utf16().count() as u32;
442
443 let collection = if font_info.is_system_font {
444 &self.system_font_collection
445 } else {
446 &self.custom_font_collection
447 };
448 let text_range = DWRITE_TEXT_RANGE {
449 startPosition: utf16_offset,
450 length: current_text_utf16_length,
451 };
452 utf16_offset += current_text_utf16_length;
453 text_layout
454 .SetFontCollection(collection, text_range)
455 .unwrap();
456 text_layout
457 .SetFontFamilyName(&HSTRING::from(&font_info.font_family), text_range)
458 .unwrap();
459 text_layout.SetFontSize(font_size.0, text_range).unwrap();
460 text_layout
461 .SetFontStyle(font_info.font_face.GetStyle(), text_range)
462 .unwrap();
463 text_layout
464 .SetFontWeight(font_info.font_face.GetWeight(), text_range)
465 .unwrap();
466 text_layout
467 .SetTypography(&font_info.features, text_range)
468 .unwrap();
469 }
470
471 let mut runs = Vec::new();
472 let renderer_context = RendererContext {
473 text_system: self,
474 index_converter: StringIndexConverter::new(text),
475 runs: &mut runs,
476 utf16_index: 0,
477 width: 0.0,
478 };
479 text_layout
480 .Draw(
481 Some(&renderer_context as *const _ as _),
482 &text_renderer.0,
483 0.0,
484 0.0,
485 )
486 .unwrap();
487 let width = px(renderer_context.width);
488
489 LineLayout {
490 font_size,
491 width,
492 ascent,
493 descent,
494 runs,
495 len: text.len(),
496 }
497 }
498 }
499
500 fn font_metrics(&self, font_id: FontId) -> FontMetrics {
501 unsafe {
502 let font_info = &self.fonts[font_id.0];
503 let mut metrics = std::mem::zeroed();
504 font_info.font_face.GetMetrics2(&mut metrics);
505
506 FontMetrics {
507 units_per_em: metrics.Base.designUnitsPerEm as _,
508 ascent: metrics.Base.ascent as _,
509 descent: -(metrics.Base.descent as f32),
510 line_gap: metrics.Base.lineGap as _,
511 underline_position: metrics.Base.underlinePosition as _,
512 underline_thickness: metrics.Base.underlineThickness as _,
513 cap_height: metrics.Base.capHeight as _,
514 x_height: metrics.Base.xHeight as _,
515 bounding_box: Bounds {
516 origin: Point {
517 x: metrics.glyphBoxLeft as _,
518 y: metrics.glyphBoxBottom as _,
519 },
520 size: Size {
521 width: (metrics.glyphBoxRight - metrics.glyphBoxLeft) as _,
522 height: (metrics.glyphBoxTop - metrics.glyphBoxBottom) as _,
523 },
524 },
525 }
526 }
527 }
528
529 unsafe fn get_glyphrun_analysis(
530 &self,
531 params: &RenderGlyphParams,
532 ) -> windows::core::Result<IDWriteGlyphRunAnalysis> {
533 let font = &self.fonts[params.font_id.0];
534 let glyph_id = [params.glyph_id.0 as u16];
535 let advance = [0.0f32];
536 let offset = [DWRITE_GLYPH_OFFSET::default()];
537 let glyph_run = DWRITE_GLYPH_RUN {
538 fontFace: unsafe { std::mem::transmute_copy(&font.font_face) },
539 fontEmSize: params.font_size.0,
540 glyphCount: 1,
541 glyphIndices: glyph_id.as_ptr(),
542 glyphAdvances: advance.as_ptr(),
543 glyphOffsets: offset.as_ptr(),
544 isSideways: BOOL(0),
545 bidiLevel: 0,
546 };
547 let transform = DWRITE_MATRIX {
548 m11: params.scale_factor,
549 m12: 0.0,
550 m21: 0.0,
551 m22: params.scale_factor,
552 dx: 0.0,
553 dy: 0.0,
554 };
555 self.components.factory.CreateGlyphRunAnalysis(
556 &glyph_run as _,
557 1.0,
558 Some(&transform as _),
559 DWRITE_RENDERING_MODE_NATURAL,
560 DWRITE_MEASURING_MODE_NATURAL,
561 0.0,
562 0.0,
563 )
564 }
565
566 fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
567 unsafe {
568 let glyph_run_analysis = self.get_glyphrun_analysis(params)?;
569 let bounds = glyph_run_analysis.GetAlphaTextureBounds(DWRITE_TEXTURE_CLEARTYPE_3x1)?;
570
571 Ok(Bounds {
572 origin: Point {
573 x: DevicePixels(bounds.left),
574 y: DevicePixels(bounds.top),
575 },
576 size: Size {
577 width: DevicePixels(bounds.right - bounds.left),
578 height: DevicePixels(bounds.bottom - bounds.top),
579 },
580 })
581 }
582 }
583
584 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
585 let font_info = &self.fonts[font_id.0];
586 let codepoints = [ch as u32];
587 let mut glyph_indices = vec![0u16; 1];
588 unsafe {
589 font_info
590 .font_face
591 .GetGlyphIndices(codepoints.as_ptr(), 1, glyph_indices.as_mut_ptr())
592 .log_err()
593 }
594 .map(|_| GlyphId(glyph_indices[0] as u32))
595 }
596
597 fn rasterize_glyph(
598 &self,
599 params: &RenderGlyphParams,
600 glyph_bounds: Bounds<DevicePixels>,
601 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
602 if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
603 return Err(anyhow!("glyph bounds are empty"));
604 }
605
606 let font_info = &self.fonts[params.font_id.0];
607 let glyph_id = [params.glyph_id.0 as u16];
608 let advance = [glyph_bounds.size.width.0 as f32];
609 let offset = [DWRITE_GLYPH_OFFSET {
610 advanceOffset: -glyph_bounds.origin.x.0 as f32 / params.scale_factor,
611 ascenderOffset: glyph_bounds.origin.y.0 as f32 / params.scale_factor,
612 }];
613 let glyph_run = DWRITE_GLYPH_RUN {
614 fontFace: unsafe { std::mem::transmute_copy(&font_info.font_face) },
615 fontEmSize: params.font_size.0,
616 glyphCount: 1,
617 glyphIndices: glyph_id.as_ptr(),
618 glyphAdvances: advance.as_ptr(),
619 glyphOffsets: offset.as_ptr(),
620 isSideways: BOOL(0),
621 bidiLevel: 0,
622 };
623
624 // Add an extra pixel when the subpixel variant isn't zero to make room for anti-aliasing.
625 let mut bitmap_size = glyph_bounds.size;
626 if params.subpixel_variant.x > 0 {
627 bitmap_size.width += DevicePixels(1);
628 }
629 if params.subpixel_variant.y > 0 {
630 bitmap_size.height += DevicePixels(1);
631 }
632 let bitmap_size = bitmap_size;
633 let transform = DWRITE_MATRIX {
634 m11: params.scale_factor,
635 m12: 0.0,
636 m21: 0.0,
637 m22: params.scale_factor,
638 dx: 0.0,
639 dy: 0.0,
640 };
641 let brush_property = D2D1_BRUSH_PROPERTIES {
642 opacity: 1.0,
643 transform: Matrix3x2 {
644 M11: params.scale_factor,
645 M12: 0.0,
646 M21: 0.0,
647 M22: params.scale_factor,
648 M31: 0.0,
649 M32: 0.0,
650 },
651 };
652
653 let total_bytes;
654 let bitmap_format;
655 let render_target_property;
656 let bitmap_stride;
657 if params.is_emoji {
658 total_bytes = bitmap_size.height.0 as usize * bitmap_size.width.0 as usize * 4;
659 bitmap_format = &GUID_WICPixelFormat32bppPBGRA;
660 render_target_property = D2D1_RENDER_TARGET_PROPERTIES {
661 r#type: D2D1_RENDER_TARGET_TYPE_DEFAULT,
662 pixelFormat: D2D1_PIXEL_FORMAT {
663 format: DXGI_FORMAT_B8G8R8A8_UNORM,
664 alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED,
665 },
666 dpiX: params.scale_factor * 96.0,
667 dpiY: params.scale_factor * 96.0,
668 usage: D2D1_RENDER_TARGET_USAGE_NONE,
669 minLevel: D2D1_FEATURE_LEVEL_DEFAULT,
670 };
671 bitmap_stride = bitmap_size.width.0 as u32 * 4;
672 } else {
673 total_bytes = bitmap_size.height.0 as usize * bitmap_size.width.0 as usize;
674 bitmap_format = &GUID_WICPixelFormat8bppAlpha;
675 render_target_property = D2D1_RENDER_TARGET_PROPERTIES {
676 r#type: D2D1_RENDER_TARGET_TYPE_DEFAULT,
677 pixelFormat: D2D1_PIXEL_FORMAT {
678 format: DXGI_FORMAT_A8_UNORM,
679 alphaMode: D2D1_ALPHA_MODE_STRAIGHT,
680 },
681 dpiX: params.scale_factor * 96.0,
682 dpiY: params.scale_factor * 96.0,
683 usage: D2D1_RENDER_TARGET_USAGE_NONE,
684 minLevel: D2D1_FEATURE_LEVEL_DEFAULT,
685 };
686 bitmap_stride = bitmap_size.width.0 as u32;
687 }
688
689 unsafe {
690 let bitmap = self.components.bitmap_factory.CreateBitmap(
691 bitmap_size.width.0 as u32,
692 bitmap_size.height.0 as u32,
693 bitmap_format,
694 WICBitmapCacheOnLoad,
695 )?;
696 let render_target = self
697 .components
698 .d2d1_factory
699 .CreateWicBitmapRenderTarget(&bitmap, &render_target_property)?;
700 let brush = render_target.CreateSolidColorBrush(&BRUSH_COLOR, Some(&brush_property))?;
701 let subpixel_shift = params
702 .subpixel_variant
703 .map(|v| v as f32 / SUBPIXEL_VARIANTS as f32);
704 let baseline_origin = D2D_POINT_2F {
705 x: subpixel_shift.x / params.scale_factor,
706 y: subpixel_shift.y / params.scale_factor,
707 };
708
709 // This `cast()` action here should never fail since we are running on Win10+, and
710 // ID2D1DeviceContext4 requires Win8+
711 let render_target = render_target.cast::<ID2D1DeviceContext4>().unwrap();
712 render_target.BeginDraw();
713 if params.is_emoji {
714 // WARN: only DWRITE_GLYPH_IMAGE_FORMATS_COLR has been tested
715 let enumerator = self.components.factory.TranslateColorGlyphRun2(
716 baseline_origin,
717 &glyph_run as _,
718 None,
719 DWRITE_GLYPH_IMAGE_FORMATS_COLR
720 | DWRITE_GLYPH_IMAGE_FORMATS_SVG
721 | DWRITE_GLYPH_IMAGE_FORMATS_PNG
722 | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
723 | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8,
724 DWRITE_MEASURING_MODE_NATURAL,
725 Some(&transform as _),
726 0,
727 )?;
728 while enumerator.MoveNext().is_ok() {
729 let Ok(color_glyph) = enumerator.GetCurrentRun2() else {
730 break;
731 };
732 let color_glyph = &*color_glyph;
733 let brush_color = translate_color(&color_glyph.Base.runColor);
734 brush.SetColor(&brush_color);
735 match color_glyph.glyphImageFormat {
736 DWRITE_GLYPH_IMAGE_FORMATS_PNG
737 | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
738 | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8 => render_target
739 .DrawColorBitmapGlyphRun(
740 color_glyph.glyphImageFormat,
741 baseline_origin,
742 &color_glyph.Base.glyphRun,
743 color_glyph.measuringMode,
744 D2D1_COLOR_BITMAP_GLYPH_SNAP_OPTION_DEFAULT,
745 ),
746 DWRITE_GLYPH_IMAGE_FORMATS_SVG => render_target.DrawSvgGlyphRun(
747 baseline_origin,
748 &color_glyph.Base.glyphRun,
749 &brush,
750 None,
751 color_glyph.Base.paletteIndex as u32,
752 color_glyph.measuringMode,
753 ),
754 _ => render_target.DrawGlyphRun2(
755 baseline_origin,
756 &color_glyph.Base.glyphRun,
757 Some(color_glyph.Base.glyphRunDescription as *const _),
758 &brush,
759 color_glyph.measuringMode,
760 ),
761 }
762 }
763 } else {
764 render_target.DrawGlyphRun(
765 baseline_origin,
766 &glyph_run,
767 &brush,
768 DWRITE_MEASURING_MODE_NATURAL,
769 );
770 }
771 render_target.EndDraw(None, None)?;
772 let mut raw_data = vec![0u8; total_bytes];
773 bitmap.CopyPixels(std::ptr::null() as _, bitmap_stride, &mut raw_data)?;
774 if params.is_emoji {
775 // Convert from BGRA with premultiplied alpha to BGRA with straight alpha.
776 for pixel in raw_data.chunks_exact_mut(4) {
777 let a = pixel[3] as f32 / 255.;
778 pixel[0] = (pixel[0] as f32 / a) as u8;
779 pixel[1] = (pixel[1] as f32 / a) as u8;
780 pixel[2] = (pixel[2] as f32 / a) as u8;
781 }
782 }
783 Ok((bitmap_size, raw_data))
784 }
785 }
786
787 fn get_typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
788 unsafe {
789 let font = &self.fonts[font_id.0].font_face;
790 let glyph_indices = [glyph_id.0 as u16];
791 let mut metrics = [DWRITE_GLYPH_METRICS::default()];
792 font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
793
794 let metrics = &metrics[0];
795 let advance_width = metrics.advanceWidth as i32;
796 let advance_height = metrics.advanceHeight as i32;
797 let left_side_bearing = metrics.leftSideBearing;
798 let right_side_bearing = metrics.rightSideBearing;
799 let top_side_bearing = metrics.topSideBearing;
800 let bottom_side_bearing = metrics.bottomSideBearing;
801 let vertical_origin_y = metrics.verticalOriginY;
802
803 let y_offset = vertical_origin_y + bottom_side_bearing - advance_height;
804 let width = advance_width - (left_side_bearing + right_side_bearing);
805 let height = advance_height - (top_side_bearing + bottom_side_bearing);
806
807 Ok(Bounds {
808 origin: Point {
809 x: left_side_bearing as f32,
810 y: y_offset as f32,
811 },
812 size: Size {
813 width: width as f32,
814 height: height as f32,
815 },
816 })
817 }
818 }
819
820 fn get_advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
821 unsafe {
822 let font = &self.fonts[font_id.0].font_face;
823 let glyph_indices = [glyph_id.0 as u16];
824 let mut metrics = [DWRITE_GLYPH_METRICS::default()];
825 font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
826
827 let metrics = &metrics[0];
828
829 Ok(Size {
830 width: metrics.advanceWidth as f32,
831 height: 0.0,
832 })
833 }
834 }
835
836 fn all_font_names(&self) -> Vec<String> {
837 let mut result =
838 get_font_names_from_collection(&self.system_font_collection, &self.components.locale);
839 result.extend(get_font_names_from_collection(
840 &self.custom_font_collection,
841 &self.components.locale,
842 ));
843 result
844 }
845
846 fn all_font_families(&self) -> Vec<String> {
847 get_font_names_from_collection(&self.system_font_collection, &self.components.locale)
848 }
849}
850
851impl Drop for DirectWriteState {
852 fn drop(&mut self) {
853 unsafe {
854 let _ = self
855 .components
856 .factory
857 .UnregisterFontFileLoader(&self.components.in_memory_loader);
858 }
859 }
860}
861
862struct TextRendererWrapper(pub IDWriteTextRenderer);
863
864impl TextRendererWrapper {
865 pub fn new(locale_str: &str) -> Self {
866 let inner = TextRenderer::new(locale_str);
867 TextRendererWrapper(inner.into())
868 }
869}
870
871#[implement(IDWriteTextRenderer)]
872struct TextRenderer {
873 locale: String,
874}
875
876impl TextRenderer {
877 pub fn new(locale_str: &str) -> Self {
878 TextRenderer {
879 locale: locale_str.to_owned(),
880 }
881 }
882}
883
884struct RendererContext<'t, 'a, 'b> {
885 text_system: &'t mut DirectWriteState,
886 index_converter: StringIndexConverter<'a>,
887 runs: &'b mut Vec<ShapedRun>,
888 utf16_index: usize,
889 width: f32,
890}
891
892#[allow(non_snake_case)]
893impl IDWritePixelSnapping_Impl for TextRenderer {
894 fn IsPixelSnappingDisabled(
895 &self,
896 _clientdrawingcontext: *const ::core::ffi::c_void,
897 ) -> windows::core::Result<BOOL> {
898 Ok(BOOL(0))
899 }
900
901 fn GetCurrentTransform(
902 &self,
903 _clientdrawingcontext: *const ::core::ffi::c_void,
904 transform: *mut DWRITE_MATRIX,
905 ) -> windows::core::Result<()> {
906 unsafe {
907 *transform = DWRITE_MATRIX {
908 m11: 1.0,
909 m12: 0.0,
910 m21: 0.0,
911 m22: 1.0,
912 dx: 0.0,
913 dy: 0.0,
914 };
915 }
916 Ok(())
917 }
918
919 fn GetPixelsPerDip(
920 &self,
921 _clientdrawingcontext: *const ::core::ffi::c_void,
922 ) -> windows::core::Result<f32> {
923 Ok(1.0)
924 }
925}
926
927#[allow(non_snake_case)]
928impl IDWriteTextRenderer_Impl for TextRenderer {
929 fn DrawGlyphRun(
930 &self,
931 clientdrawingcontext: *const ::core::ffi::c_void,
932 _baselineoriginx: f32,
933 _baselineoriginy: f32,
934 _measuringmode: DWRITE_MEASURING_MODE,
935 glyphrun: *const DWRITE_GLYPH_RUN,
936 glyphrundescription: *const DWRITE_GLYPH_RUN_DESCRIPTION,
937 _clientdrawingeffect: Option<&windows::core::IUnknown>,
938 ) -> windows::core::Result<()> {
939 unsafe {
940 let glyphrun = &*glyphrun;
941 let glyph_count = glyphrun.glyphCount as usize;
942 if glyph_count == 0 {
943 return Ok(());
944 }
945 let desc = &*glyphrundescription;
946 let utf16_length_per_glyph = desc.stringLength as usize / glyph_count;
947 let context =
948 &mut *(clientdrawingcontext as *const RendererContext as *mut RendererContext);
949
950 if glyphrun.fontFace.is_none() {
951 return Ok(());
952 }
953
954 let font_face = glyphrun.fontFace.as_ref().unwrap();
955 // This `cast()` action here should never fail since we are running on Win10+, and
956 // `IDWriteFontFace3` requires Win10
957 let font_face = &font_face.cast::<IDWriteFontFace3>().unwrap();
958 let Some((postscript_name, font_struct, is_emoji)) =
959 get_postscript_name_and_font(font_face, &self.locale)
960 else {
961 log::error!("none postscript name found");
962 return Ok(());
963 };
964
965 let font_id = if let Some(id) = context
966 .text_system
967 .font_id_by_postscript_name
968 .get(&postscript_name)
969 {
970 *id
971 } else {
972 context.text_system.select_font(&font_struct)
973 };
974 let mut glyphs = SmallVec::new();
975 for index in 0..glyph_count {
976 let id = GlyphId(*glyphrun.glyphIndices.add(index) as u32);
977 context
978 .index_converter
979 .advance_to_utf16_ix(context.utf16_index);
980 glyphs.push(ShapedGlyph {
981 id,
982 position: point(px(context.width), px(0.0)),
983 index: context.index_converter.utf8_ix,
984 is_emoji,
985 });
986 context.utf16_index += utf16_length_per_glyph;
987 context.width += *glyphrun.glyphAdvances.add(index);
988 }
989 context.runs.push(ShapedRun { font_id, glyphs });
990 }
991 Ok(())
992 }
993
994 fn DrawUnderline(
995 &self,
996 _clientdrawingcontext: *const ::core::ffi::c_void,
997 _baselineoriginx: f32,
998 _baselineoriginy: f32,
999 _underline: *const DWRITE_UNDERLINE,
1000 _clientdrawingeffect: Option<&windows::core::IUnknown>,
1001 ) -> windows::core::Result<()> {
1002 Err(windows::core::Error::new(
1003 E_NOTIMPL,
1004 "DrawUnderline unimplemented",
1005 ))
1006 }
1007
1008 fn DrawStrikethrough(
1009 &self,
1010 _clientdrawingcontext: *const ::core::ffi::c_void,
1011 _baselineoriginx: f32,
1012 _baselineoriginy: f32,
1013 _strikethrough: *const DWRITE_STRIKETHROUGH,
1014 _clientdrawingeffect: Option<&windows::core::IUnknown>,
1015 ) -> windows::core::Result<()> {
1016 Err(windows::core::Error::new(
1017 E_NOTIMPL,
1018 "DrawStrikethrough unimplemented",
1019 ))
1020 }
1021
1022 fn DrawInlineObject(
1023 &self,
1024 _clientdrawingcontext: *const ::core::ffi::c_void,
1025 _originx: f32,
1026 _originy: f32,
1027 _inlineobject: Option<&IDWriteInlineObject>,
1028 _issideways: BOOL,
1029 _isrighttoleft: BOOL,
1030 _clientdrawingeffect: Option<&windows::core::IUnknown>,
1031 ) -> windows::core::Result<()> {
1032 Err(windows::core::Error::new(
1033 E_NOTIMPL,
1034 "DrawInlineObject unimplemented",
1035 ))
1036 }
1037}
1038
1039struct StringIndexConverter<'a> {
1040 text: &'a str,
1041 utf8_ix: usize,
1042 utf16_ix: usize,
1043}
1044
1045impl<'a> StringIndexConverter<'a> {
1046 fn new(text: &'a str) -> Self {
1047 Self {
1048 text,
1049 utf8_ix: 0,
1050 utf16_ix: 0,
1051 }
1052 }
1053
1054 fn advance_to_utf8_ix(&mut self, utf8_target: usize) {
1055 for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1056 if self.utf8_ix + ix >= utf8_target {
1057 self.utf8_ix += ix;
1058 return;
1059 }
1060 self.utf16_ix += c.len_utf16();
1061 }
1062 self.utf8_ix = self.text.len();
1063 }
1064
1065 fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
1066 for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1067 if self.utf16_ix >= utf16_target {
1068 self.utf8_ix += ix;
1069 return;
1070 }
1071 self.utf16_ix += c.len_utf16();
1072 }
1073 self.utf8_ix = self.text.len();
1074 }
1075}
1076
1077impl Into<DWRITE_FONT_STYLE> for FontStyle {
1078 fn into(self) -> DWRITE_FONT_STYLE {
1079 match self {
1080 FontStyle::Normal => DWRITE_FONT_STYLE_NORMAL,
1081 FontStyle::Italic => DWRITE_FONT_STYLE_ITALIC,
1082 FontStyle::Oblique => DWRITE_FONT_STYLE_OBLIQUE,
1083 }
1084 }
1085}
1086
1087impl From<DWRITE_FONT_STYLE> for FontStyle {
1088 fn from(value: DWRITE_FONT_STYLE) -> Self {
1089 match value.0 {
1090 0 => FontStyle::Normal,
1091 1 => FontStyle::Italic,
1092 2 => FontStyle::Oblique,
1093 _ => unreachable!(),
1094 }
1095 }
1096}
1097
1098impl Into<DWRITE_FONT_WEIGHT> for FontWeight {
1099 fn into(self) -> DWRITE_FONT_WEIGHT {
1100 DWRITE_FONT_WEIGHT(self.0 as i32)
1101 }
1102}
1103
1104impl From<DWRITE_FONT_WEIGHT> for FontWeight {
1105 fn from(value: DWRITE_FONT_WEIGHT) -> Self {
1106 FontWeight(value.0 as f32)
1107 }
1108}
1109
1110fn get_font_names_from_collection(
1111 collection: &IDWriteFontCollection1,
1112 locale: &str,
1113) -> Vec<String> {
1114 unsafe {
1115 let mut result = Vec::new();
1116 let family_count = collection.GetFontFamilyCount();
1117 for index in 0..family_count {
1118 let Some(font_family) = collection.GetFontFamily(index).log_err() else {
1119 continue;
1120 };
1121 let Some(localized_family_name) = font_family.GetFamilyNames().log_err() else {
1122 continue;
1123 };
1124 let Some(family_name) = get_name(localized_family_name, locale) else {
1125 continue;
1126 };
1127 result.push(family_name);
1128 }
1129
1130 result
1131 }
1132}
1133
1134unsafe fn get_postscript_name_and_font(
1135 font_face: &IDWriteFontFace3,
1136 locale: &str,
1137) -> Option<(String, Font, bool)> {
1138 let Some(postscript_name) = get_postscript_name(font_face, locale) else {
1139 return None;
1140 };
1141 let Some(localized_family_name) = font_face.GetFamilyNames().log_err() else {
1142 return None;
1143 };
1144 let Some(family_name) = get_name(localized_family_name, locale) else {
1145 return None;
1146 };
1147 let font_struct = Font {
1148 family: family_name.into(),
1149 features: FontFeatures::default(),
1150 weight: font_face.GetWeight().into(),
1151 style: font_face.GetStyle().into(),
1152 };
1153 let is_emoji = font_face.IsColorFont().as_bool();
1154 Some((postscript_name, font_struct, is_emoji))
1155}
1156
1157unsafe fn get_postscript_name(font_face: &IDWriteFontFace3, locale: &str) -> Option<String> {
1158 let mut info = std::mem::zeroed();
1159 let mut exists = BOOL(0);
1160 font_face
1161 .GetInformationalStrings(
1162 DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_NAME,
1163 &mut info,
1164 &mut exists,
1165 )
1166 .log_err();
1167 if !exists.as_bool() || info.is_none() {
1168 return None;
1169 }
1170
1171 get_name(info.unwrap(), locale)
1172}
1173
1174// https://learn.microsoft.com/en-us/windows/win32/api/dwrite/ne-dwrite-dwrite_font_feature_tag
1175unsafe fn apply_font_features(
1176 direct_write_features: &IDWriteTypography,
1177 features: &FontFeatures,
1178) -> Result<()> {
1179 let tag_values = features.tag_value_list();
1180 if tag_values.is_empty() {
1181 return Ok(());
1182 }
1183
1184 // All of these features are enabled by default by DirectWrite.
1185 // If you want to (and can) peek into the source of DirectWrite
1186 let mut feature_liga = make_direct_write_feature("liga", true);
1187 let mut feature_clig = make_direct_write_feature("clig", true);
1188 let mut feature_calt = make_direct_write_feature("calt", true);
1189
1190 for (tag, enable) in tag_values {
1191 if tag == *"liga" && !enable {
1192 feature_liga.parameter = 0;
1193 continue;
1194 }
1195 if tag == *"clig" && !enable {
1196 feature_clig.parameter = 0;
1197 continue;
1198 }
1199 if tag == *"calt" && !enable {
1200 feature_calt.parameter = 0;
1201 continue;
1202 }
1203
1204 direct_write_features.AddFontFeature(make_direct_write_feature(&tag, enable))?;
1205 }
1206 direct_write_features.AddFontFeature(feature_liga)?;
1207 direct_write_features.AddFontFeature(feature_clig)?;
1208 direct_write_features.AddFontFeature(feature_calt)?;
1209
1210 Ok(())
1211}
1212
1213#[inline]
1214fn make_direct_write_feature(feature_name: &str, enable: bool) -> DWRITE_FONT_FEATURE {
1215 let tag = make_direct_write_tag(feature_name);
1216 if enable {
1217 DWRITE_FONT_FEATURE {
1218 nameTag: tag,
1219 parameter: 1,
1220 }
1221 } else {
1222 DWRITE_FONT_FEATURE {
1223 nameTag: tag,
1224 parameter: 0,
1225 }
1226 }
1227}
1228
1229#[inline]
1230fn make_open_type_tag(tag_name: &str) -> u32 {
1231 assert_eq!(tag_name.chars().count(), 4);
1232 let bytes = tag_name.bytes().collect_vec();
1233 ((bytes[3] as u32) << 24)
1234 | ((bytes[2] as u32) << 16)
1235 | ((bytes[1] as u32) << 8)
1236 | (bytes[0] as u32)
1237}
1238
1239#[inline]
1240fn make_direct_write_tag(tag_name: &str) -> DWRITE_FONT_FEATURE_TAG {
1241 DWRITE_FONT_FEATURE_TAG(make_open_type_tag(tag_name))
1242}
1243
1244unsafe fn get_name(string: IDWriteLocalizedStrings, locale: &str) -> Option<String> {
1245 let mut locale_name_index = 0u32;
1246 let mut exists = BOOL(0);
1247 string
1248 .FindLocaleName(
1249 &HSTRING::from(locale),
1250 &mut locale_name_index,
1251 &mut exists as _,
1252 )
1253 .log_err();
1254 if !exists.as_bool() {
1255 string
1256 .FindLocaleName(
1257 DEFAULT_LOCALE_NAME,
1258 &mut locale_name_index as _,
1259 &mut exists as _,
1260 )
1261 .log_err();
1262 if !exists.as_bool() {
1263 return None;
1264 }
1265 }
1266
1267 let name_length = string.GetStringLength(locale_name_index).unwrap() as usize;
1268 let mut name_vec = vec![0u16; name_length + 1];
1269 string.GetString(locale_name_index, &mut name_vec).unwrap();
1270
1271 Some(String::from_utf16_lossy(&name_vec[..name_length]))
1272}
1273
1274#[inline]
1275fn translate_color(color: &DWRITE_COLOR_F) -> D2D1_COLOR_F {
1276 D2D1_COLOR_F {
1277 r: color.r,
1278 g: color.g,
1279 b: color.b,
1280 a: color.a,
1281 }
1282}
1283
1284fn get_system_ui_font_name() -> SharedString {
1285 unsafe {
1286 let mut info: LOGFONTW = std::mem::zeroed();
1287 let font_family = if SystemParametersInfoW(
1288 SPI_GETICONTITLELOGFONT,
1289 std::mem::size_of::<LOGFONTW>() as u32,
1290 Some(&mut info as *mut _ as _),
1291 SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
1292 )
1293 .log_err()
1294 .is_none()
1295 {
1296 // https://learn.microsoft.com/en-us/windows/win32/uxguide/vis-fonts
1297 // Segoe UI is the Windows font intended for user interface text strings.
1298 "Segoe UI".into()
1299 } else {
1300 String::from_utf16_lossy(&info.lfFaceName).into()
1301 };
1302 log::info!("Use {} as UI font.", font_family);
1303 font_family
1304 }
1305}
1306
1307const DEFAULT_LOCALE_NAME: PCWSTR = windows::core::w!("en-US");
1308const BRUSH_COLOR: D2D1_COLOR_F = D2D1_COLOR_F {
1309 r: 1.0,
1310 g: 1.0,
1311 b: 1.0,
1312 a: 1.0,
1313};