1use std::{borrow::Cow, sync::Arc};
2
3use ::util::ResultExt;
4use anyhow::Result;
5use collections::HashMap;
6use itertools::Itertools;
7use parking_lot::{RwLock, RwLockUpgradableReadGuard};
8use windows::{
9 Win32::{
10 Foundation::*,
11 Globalization::GetUserDefaultLocaleName,
12 Graphics::{
13 Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, Direct3D11::*, DirectWrite::*,
14 Dxgi::Common::*, Gdi::LOGFONTW,
15 },
16 System::SystemServices::LOCALE_NAME_MAX_LENGTH,
17 UI::WindowsAndMessaging::*,
18 },
19 core::*,
20};
21use windows_numerics::Vector2;
22
23use crate::*;
24
25#[derive(Debug)]
26struct FontInfo {
27 font_family: String,
28 font_face: IDWriteFontFace3,
29 features: IDWriteTypography,
30 fallbacks: Option<IDWriteFontFallback>,
31 is_system_font: bool,
32}
33
34pub(crate) struct DirectWriteTextSystem(RwLock<DirectWriteState>);
35
36struct DirectWriteComponent {
37 locale: String,
38 factory: IDWriteFactory5,
39 in_memory_loader: IDWriteInMemoryFontFileLoader,
40 builder: IDWriteFontSetBuilder1,
41 text_renderer: Arc<TextRendererWrapper>,
42
43 gpu_state: GPUState,
44}
45
46struct GPUState {
47 device: ID3D11Device,
48 device_context: ID3D11DeviceContext,
49 sampler: [Option<ID3D11SamplerState>; 1],
50 blend_state: ID3D11BlendState,
51 vertex_shader: ID3D11VertexShader,
52 pixel_shader: ID3D11PixelShader,
53}
54
55struct DirectWriteState {
56 components: DirectWriteComponent,
57 system_ui_font_name: SharedString,
58 system_font_collection: IDWriteFontCollection1,
59 custom_font_collection: IDWriteFontCollection1,
60 fonts: Vec<FontInfo>,
61 font_selections: HashMap<Font, FontId>,
62 font_id_by_identifier: HashMap<FontIdentifier, FontId>,
63}
64
65#[derive(Debug, Clone, Hash, PartialEq, Eq)]
66struct FontIdentifier {
67 postscript_name: String,
68 weight: i32,
69 style: i32,
70}
71
72impl DirectWriteComponent {
73 pub fn new(gpu_context: &DirectXDevices) -> Result<Self> {
74 // todo: ideally this would not be a large unsafe block but smaller isolated ones for easier auditing
75 unsafe {
76 let factory: IDWriteFactory5 = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED)?;
77 // The `IDWriteInMemoryFontFileLoader` here is supported starting from
78 // Windows 10 Creators Update, which consequently requires the entire
79 // `DirectWriteTextSystem` to run on `win10 1703`+.
80 let in_memory_loader = factory.CreateInMemoryFontFileLoader()?;
81 factory.RegisterFontFileLoader(&in_memory_loader)?;
82 let builder = factory.CreateFontSetBuilder()?;
83 let mut locale_vec = vec![0u16; LOCALE_NAME_MAX_LENGTH as usize];
84 GetUserDefaultLocaleName(&mut locale_vec);
85 let locale = String::from_utf16_lossy(&locale_vec);
86 let text_renderer = Arc::new(TextRendererWrapper::new(&locale));
87
88 let gpu_state = GPUState::new(gpu_context)?;
89
90 Ok(DirectWriteComponent {
91 locale,
92 factory,
93 in_memory_loader,
94 builder,
95 text_renderer,
96 gpu_state,
97 })
98 }
99 }
100}
101
102impl GPUState {
103 fn new(gpu_context: &DirectXDevices) -> Result<Self> {
104 let device = gpu_context.device.clone();
105 let device_context = gpu_context.device_context.clone();
106
107 let blend_state = {
108 let mut blend_state = None;
109 let desc = D3D11_BLEND_DESC {
110 AlphaToCoverageEnable: false.into(),
111 IndependentBlendEnable: false.into(),
112 RenderTarget: [
113 D3D11_RENDER_TARGET_BLEND_DESC {
114 BlendEnable: true.into(),
115 SrcBlend: D3D11_BLEND_SRC_ALPHA,
116 DestBlend: D3D11_BLEND_INV_SRC_ALPHA,
117 BlendOp: D3D11_BLEND_OP_ADD,
118 SrcBlendAlpha: D3D11_BLEND_SRC_ALPHA,
119 DestBlendAlpha: D3D11_BLEND_INV_SRC_ALPHA,
120 BlendOpAlpha: D3D11_BLEND_OP_ADD,
121 RenderTargetWriteMask: D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8,
122 },
123 Default::default(),
124 Default::default(),
125 Default::default(),
126 Default::default(),
127 Default::default(),
128 Default::default(),
129 Default::default(),
130 ],
131 };
132 unsafe { device.CreateBlendState(&desc, Some(&mut blend_state)) }?;
133 blend_state.unwrap()
134 };
135
136 let sampler = {
137 let mut sampler = None;
138 let desc = D3D11_SAMPLER_DESC {
139 Filter: D3D11_FILTER_MIN_MAG_MIP_POINT,
140 AddressU: D3D11_TEXTURE_ADDRESS_BORDER,
141 AddressV: D3D11_TEXTURE_ADDRESS_BORDER,
142 AddressW: D3D11_TEXTURE_ADDRESS_BORDER,
143 MipLODBias: 0.0,
144 MaxAnisotropy: 1,
145 ComparisonFunc: D3D11_COMPARISON_ALWAYS,
146 BorderColor: [0.0, 0.0, 0.0, 0.0],
147 MinLOD: 0.0,
148 MaxLOD: 0.0,
149 };
150 unsafe { device.CreateSamplerState(&desc, Some(&mut sampler)) }?;
151 [sampler]
152 };
153
154 let vertex_shader = {
155 let source = shader_resources::RawShaderBytes::new(
156 shader_resources::ShaderModule::EmojiRasterization,
157 shader_resources::ShaderTarget::Vertex,
158 )?;
159 let mut shader = None;
160 unsafe { device.CreateVertexShader(source.as_bytes(), None, Some(&mut shader)) }?;
161 shader.unwrap()
162 };
163
164 let pixel_shader = {
165 let source = shader_resources::RawShaderBytes::new(
166 shader_resources::ShaderModule::EmojiRasterization,
167 shader_resources::ShaderTarget::Fragment,
168 )?;
169 let mut shader = None;
170 unsafe { device.CreatePixelShader(source.as_bytes(), None, Some(&mut shader)) }?;
171 shader.unwrap()
172 };
173
174 Ok(Self {
175 device,
176 device_context,
177 sampler,
178 blend_state,
179 vertex_shader,
180 pixel_shader,
181 })
182 }
183}
184
185impl DirectWriteTextSystem {
186 pub(crate) fn new(gpu_context: &DirectXDevices) -> Result<Self> {
187 let components = DirectWriteComponent::new(gpu_context)?;
188 let system_font_collection = unsafe {
189 let mut result = std::mem::zeroed();
190 components
191 .factory
192 .GetSystemFontCollection(false, &mut result, true)?;
193 result.unwrap()
194 };
195 let custom_font_set = unsafe { components.builder.CreateFontSet()? };
196 let custom_font_collection = unsafe {
197 components
198 .factory
199 .CreateFontCollectionFromFontSet(&custom_font_set)?
200 };
201 let system_ui_font_name = get_system_ui_font_name();
202
203 Ok(Self(RwLock::new(DirectWriteState {
204 components,
205 system_ui_font_name,
206 system_font_collection,
207 custom_font_collection,
208 fonts: Vec::new(),
209 font_selections: HashMap::default(),
210 font_id_by_identifier: HashMap::default(),
211 })))
212 }
213}
214
215impl PlatformTextSystem for DirectWriteTextSystem {
216 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
217 self.0.write().add_fonts(fonts)
218 }
219
220 fn all_font_names(&self) -> Vec<String> {
221 self.0.read().all_font_names()
222 }
223
224 fn font_id(&self, font: &Font) -> Result<FontId> {
225 let lock = self.0.upgradable_read();
226 if let Some(font_id) = lock.font_selections.get(font) {
227 Ok(*font_id)
228 } else {
229 let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
230 let font_id = lock.select_font(font);
231 lock.font_selections.insert(font.clone(), font_id);
232 Ok(font_id)
233 }
234 }
235
236 fn font_metrics(&self, font_id: FontId) -> FontMetrics {
237 self.0.read().font_metrics(font_id)
238 }
239
240 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
241 self.0.read().get_typographic_bounds(font_id, glyph_id)
242 }
243
244 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Size<f32>> {
245 self.0.read().get_advance(font_id, glyph_id)
246 }
247
248 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
249 self.0.read().glyph_for_char(font_id, ch)
250 }
251
252 fn glyph_raster_bounds(
253 &self,
254 params: &RenderGlyphParams,
255 ) -> anyhow::Result<Bounds<DevicePixels>> {
256 self.0.read().raster_bounds(params)
257 }
258
259 fn rasterize_glyph(
260 &self,
261 params: &RenderGlyphParams,
262 raster_bounds: Bounds<DevicePixels>,
263 ) -> anyhow::Result<(Size<DevicePixels>, Vec<u8>)> {
264 self.0.read().rasterize_glyph(params, raster_bounds)
265 }
266
267 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {
268 self.0
269 .write()
270 .layout_line(text, font_size, runs)
271 .log_err()
272 .unwrap_or(LineLayout {
273 font_size,
274 ..Default::default()
275 })
276 }
277}
278
279impl DirectWriteState {
280 fn add_fonts(&mut self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
281 for font_data in fonts {
282 match font_data {
283 Cow::Borrowed(data) => unsafe {
284 let font_file = self
285 .components
286 .in_memory_loader
287 .CreateInMemoryFontFileReference(
288 &self.components.factory,
289 data.as_ptr() as _,
290 data.len() as _,
291 None,
292 )?;
293 self.components.builder.AddFontFile(&font_file)?;
294 },
295 Cow::Owned(data) => unsafe {
296 let font_file = self
297 .components
298 .in_memory_loader
299 .CreateInMemoryFontFileReference(
300 &self.components.factory,
301 data.as_ptr() as _,
302 data.len() as _,
303 None,
304 )?;
305 self.components.builder.AddFontFile(&font_file)?;
306 },
307 }
308 }
309 let set = unsafe { self.components.builder.CreateFontSet()? };
310 let collection = unsafe {
311 self.components
312 .factory
313 .CreateFontCollectionFromFontSet(&set)?
314 };
315 self.custom_font_collection = collection;
316
317 Ok(())
318 }
319
320 fn generate_font_fallbacks(
321 &self,
322 fallbacks: &FontFallbacks,
323 ) -> Result<Option<IDWriteFontFallback>> {
324 if fallbacks.fallback_list().is_empty() {
325 return Ok(None);
326 }
327 unsafe {
328 let builder = self.components.factory.CreateFontFallbackBuilder()?;
329 let font_set = &self.system_font_collection.GetFontSet()?;
330 for family_name in fallbacks.fallback_list() {
331 let Some(fonts) = font_set
332 .GetMatchingFonts(
333 &HSTRING::from(family_name),
334 DWRITE_FONT_WEIGHT_NORMAL,
335 DWRITE_FONT_STRETCH_NORMAL,
336 DWRITE_FONT_STYLE_NORMAL,
337 )
338 .log_err()
339 else {
340 continue;
341 };
342 if fonts.GetFontCount() == 0 {
343 log::error!("No matching font found for {}", family_name);
344 continue;
345 }
346 let font = fonts.GetFontFaceReference(0)?.CreateFontFace()?;
347 let mut count = 0;
348 font.GetUnicodeRanges(None, &mut count).ok();
349 if count == 0 {
350 continue;
351 }
352 let mut unicode_ranges = vec![DWRITE_UNICODE_RANGE::default(); count as usize];
353 let Some(_) = font
354 .GetUnicodeRanges(Some(&mut unicode_ranges), &mut count)
355 .log_err()
356 else {
357 continue;
358 };
359 let target_family_name = HSTRING::from(family_name);
360 builder.AddMapping(
361 &unicode_ranges,
362 &[target_family_name.as_ptr()],
363 None,
364 None,
365 None,
366 1.0,
367 )?;
368 }
369 let system_fallbacks = self.components.factory.GetSystemFontFallback()?;
370 builder.AddMappings(&system_fallbacks)?;
371 Ok(Some(builder.CreateFontFallback()?))
372 }
373 }
374
375 unsafe fn generate_font_features(
376 &self,
377 font_features: &FontFeatures,
378 ) -> Result<IDWriteTypography> {
379 let direct_write_features = unsafe { self.components.factory.CreateTypography()? };
380 apply_font_features(&direct_write_features, font_features)?;
381 Ok(direct_write_features)
382 }
383
384 unsafe fn get_font_id_from_font_collection(
385 &mut self,
386 family_name: &str,
387 font_weight: FontWeight,
388 font_style: FontStyle,
389 font_features: &FontFeatures,
390 font_fallbacks: Option<&FontFallbacks>,
391 is_system_font: bool,
392 ) -> Option<FontId> {
393 let collection = if is_system_font {
394 &self.system_font_collection
395 } else {
396 &self.custom_font_collection
397 };
398 let fontset = unsafe { collection.GetFontSet().log_err()? };
399 let font = unsafe {
400 fontset
401 .GetMatchingFonts(
402 &HSTRING::from(family_name),
403 font_weight.into(),
404 DWRITE_FONT_STRETCH_NORMAL,
405 font_style.into(),
406 )
407 .log_err()?
408 };
409 let total_number = unsafe { font.GetFontCount() };
410 for index in 0..total_number {
411 let Some(font_face_ref) = (unsafe { font.GetFontFaceReference(index).log_err() })
412 else {
413 continue;
414 };
415 let Some(font_face) = (unsafe { font_face_ref.CreateFontFace().log_err() }) else {
416 continue;
417 };
418 let Some(identifier) = get_font_identifier(&font_face, &self.components.locale) else {
419 continue;
420 };
421 let Some(direct_write_features) =
422 (unsafe { self.generate_font_features(font_features).log_err() })
423 else {
424 continue;
425 };
426 let fallbacks = font_fallbacks
427 .and_then(|fallbacks| self.generate_font_fallbacks(fallbacks).log_err().flatten());
428 let font_info = FontInfo {
429 font_family: family_name.to_owned(),
430 font_face,
431 features: direct_write_features,
432 fallbacks,
433 is_system_font,
434 };
435 let font_id = FontId(self.fonts.len());
436 self.fonts.push(font_info);
437 self.font_id_by_identifier.insert(identifier, font_id);
438 return Some(font_id);
439 }
440 None
441 }
442
443 unsafe fn update_system_font_collection(&mut self) {
444 let mut collection = unsafe { std::mem::zeroed() };
445 if unsafe {
446 self.components
447 .factory
448 .GetSystemFontCollection(false, &mut collection, true)
449 .log_err()
450 .is_some()
451 } {
452 self.system_font_collection = collection.unwrap();
453 }
454 }
455
456 fn select_font(&mut self, target_font: &Font) -> FontId {
457 unsafe {
458 if target_font.family == ".SystemUIFont" {
459 let family = self.system_ui_font_name.clone();
460 self.find_font_id(
461 family.as_ref(),
462 target_font.weight,
463 target_font.style,
464 &target_font.features,
465 target_font.fallbacks.as_ref(),
466 )
467 .unwrap()
468 } else {
469 let family = self.system_ui_font_name.clone();
470 self.find_font_id(
471 font_name_with_fallbacks(target_font.family.as_ref(), family.as_ref()),
472 target_font.weight,
473 target_font.style,
474 &target_font.features,
475 target_font.fallbacks.as_ref(),
476 )
477 .unwrap_or_else(|| {
478 #[cfg(any(test, feature = "test-support"))]
479 {
480 panic!("ERROR: {} font not found!", target_font.family);
481 }
482 #[cfg(not(any(test, feature = "test-support")))]
483 {
484 log::error!("{} not found, use {} instead.", target_font.family, family);
485 self.get_font_id_from_font_collection(
486 family.as_ref(),
487 target_font.weight,
488 target_font.style,
489 &target_font.features,
490 target_font.fallbacks.as_ref(),
491 true,
492 )
493 .unwrap()
494 }
495 })
496 }
497 }
498 }
499
500 unsafe fn find_font_id(
501 &mut self,
502 family_name: &str,
503 weight: FontWeight,
504 style: FontStyle,
505 features: &FontFeatures,
506 fallbacks: Option<&FontFallbacks>,
507 ) -> Option<FontId> {
508 // try to find target font in custom font collection first
509 unsafe {
510 self.get_font_id_from_font_collection(
511 family_name,
512 weight,
513 style,
514 features,
515 fallbacks,
516 false,
517 )
518 .or_else(|| {
519 self.get_font_id_from_font_collection(
520 family_name,
521 weight,
522 style,
523 features,
524 fallbacks,
525 true,
526 )
527 })
528 .or_else(|| {
529 self.update_system_font_collection();
530 self.get_font_id_from_font_collection(
531 family_name,
532 weight,
533 style,
534 features,
535 fallbacks,
536 true,
537 )
538 })
539 }
540 }
541
542 fn layout_line(
543 &mut self,
544 text: &str,
545 font_size: Pixels,
546 font_runs: &[FontRun],
547 ) -> Result<LineLayout> {
548 if font_runs.is_empty() {
549 return Ok(LineLayout {
550 font_size,
551 ..Default::default()
552 });
553 }
554 unsafe {
555 let text_renderer = self.components.text_renderer.clone();
556 let text_wide = text.encode_utf16().collect_vec();
557
558 let mut utf8_offset = 0usize;
559 let mut utf16_offset = 0u32;
560 let text_layout = {
561 let first_run = &font_runs[0];
562 let font_info = &self.fonts[first_run.font_id.0];
563 let collection = if font_info.is_system_font {
564 &self.system_font_collection
565 } else {
566 &self.custom_font_collection
567 };
568 let format: IDWriteTextFormat1 = self
569 .components
570 .factory
571 .CreateTextFormat(
572 &HSTRING::from(&font_info.font_family),
573 collection,
574 font_info.font_face.GetWeight(),
575 font_info.font_face.GetStyle(),
576 DWRITE_FONT_STRETCH_NORMAL,
577 font_size.0,
578 &HSTRING::from(&self.components.locale),
579 )?
580 .cast()?;
581 if let Some(ref fallbacks) = font_info.fallbacks {
582 format.SetFontFallback(fallbacks)?;
583 }
584
585 let layout = self.components.factory.CreateTextLayout(
586 &text_wide,
587 &format,
588 f32::INFINITY,
589 f32::INFINITY,
590 )?;
591 let current_text = &text[utf8_offset..(utf8_offset + first_run.len)];
592 utf8_offset += first_run.len;
593 let current_text_utf16_length = current_text.encode_utf16().count() as u32;
594 let text_range = DWRITE_TEXT_RANGE {
595 startPosition: utf16_offset,
596 length: current_text_utf16_length,
597 };
598 layout.SetTypography(&font_info.features, text_range)?;
599 utf16_offset += current_text_utf16_length;
600
601 layout
602 };
603
604 let mut first_run = true;
605 let mut ascent = Pixels::default();
606 let mut descent = Pixels::default();
607 for run in font_runs {
608 if first_run {
609 first_run = false;
610 let mut metrics = vec![DWRITE_LINE_METRICS::default(); 4];
611 let mut line_count = 0u32;
612 text_layout.GetLineMetrics(Some(&mut metrics), &mut line_count as _)?;
613 ascent = px(metrics[0].baseline);
614 descent = px(metrics[0].height - metrics[0].baseline);
615 continue;
616 }
617 let font_info = &self.fonts[run.font_id.0];
618 let current_text = &text[utf8_offset..(utf8_offset + run.len)];
619 utf8_offset += run.len;
620 let current_text_utf16_length = current_text.encode_utf16().count() as u32;
621
622 let collection = if font_info.is_system_font {
623 &self.system_font_collection
624 } else {
625 &self.custom_font_collection
626 };
627 let text_range = DWRITE_TEXT_RANGE {
628 startPosition: utf16_offset,
629 length: current_text_utf16_length,
630 };
631 utf16_offset += current_text_utf16_length;
632 text_layout.SetFontCollection(collection, text_range)?;
633 text_layout
634 .SetFontFamilyName(&HSTRING::from(&font_info.font_family), text_range)?;
635 text_layout.SetFontSize(font_size.0, text_range)?;
636 text_layout.SetFontStyle(font_info.font_face.GetStyle(), text_range)?;
637 text_layout.SetFontWeight(font_info.font_face.GetWeight(), text_range)?;
638 text_layout.SetTypography(&font_info.features, text_range)?;
639 }
640
641 let mut runs = Vec::new();
642 let renderer_context = RendererContext {
643 text_system: self,
644 index_converter: StringIndexConverter::new(text),
645 runs: &mut runs,
646 width: 0.0,
647 };
648 text_layout.Draw(
649 Some(&renderer_context as *const _ as _),
650 &text_renderer.0,
651 0.0,
652 0.0,
653 )?;
654 let width = px(renderer_context.width);
655
656 Ok(LineLayout {
657 font_size,
658 width,
659 ascent,
660 descent,
661 runs,
662 len: text.len(),
663 })
664 }
665 }
666
667 fn font_metrics(&self, font_id: FontId) -> FontMetrics {
668 unsafe {
669 let font_info = &self.fonts[font_id.0];
670 let mut metrics = std::mem::zeroed();
671 font_info.font_face.GetMetrics(&mut metrics);
672
673 FontMetrics {
674 units_per_em: metrics.Base.designUnitsPerEm as _,
675 ascent: metrics.Base.ascent as _,
676 descent: -(metrics.Base.descent as f32),
677 line_gap: metrics.Base.lineGap as _,
678 underline_position: metrics.Base.underlinePosition as _,
679 underline_thickness: metrics.Base.underlineThickness as _,
680 cap_height: metrics.Base.capHeight as _,
681 x_height: metrics.Base.xHeight as _,
682 bounding_box: Bounds {
683 origin: Point {
684 x: metrics.glyphBoxLeft as _,
685 y: metrics.glyphBoxBottom as _,
686 },
687 size: Size {
688 width: (metrics.glyphBoxRight - metrics.glyphBoxLeft) as _,
689 height: (metrics.glyphBoxTop - metrics.glyphBoxBottom) as _,
690 },
691 },
692 }
693 }
694 }
695
696 fn create_glyph_run_analysis(
697 &self,
698 params: &RenderGlyphParams,
699 ) -> Result<IDWriteGlyphRunAnalysis> {
700 let font = &self.fonts[params.font_id.0];
701 let glyph_id = [params.glyph_id.0 as u16];
702 let advance = [0.0];
703 let offset = [DWRITE_GLYPH_OFFSET::default()];
704 let glyph_run = DWRITE_GLYPH_RUN {
705 fontFace: unsafe { std::mem::transmute_copy(&font.font_face) },
706 fontEmSize: params.font_size.0,
707 glyphCount: 1,
708 glyphIndices: glyph_id.as_ptr(),
709 glyphAdvances: advance.as_ptr(),
710 glyphOffsets: offset.as_ptr(),
711 isSideways: BOOL(0),
712 bidiLevel: 0,
713 };
714 let transform = DWRITE_MATRIX {
715 m11: params.scale_factor,
716 m12: 0.0,
717 m21: 0.0,
718 m22: params.scale_factor,
719 dx: 0.0,
720 dy: 0.0,
721 };
722 let subpixel_shift = params
723 .subpixel_variant
724 .map(|v| v as f32 / SUBPIXEL_VARIANTS as f32);
725 let baseline_origin_x = subpixel_shift.x / params.scale_factor;
726 let baseline_origin_y = subpixel_shift.y / params.scale_factor;
727
728 let mut rendering_mode = DWRITE_RENDERING_MODE1::default();
729 let mut grid_fit_mode = DWRITE_GRID_FIT_MODE::default();
730 unsafe {
731 font.font_face.GetRecommendedRenderingMode(
732 params.font_size.0,
733 // Using 96 as scale is applied by the transform
734 96.0,
735 96.0,
736 Some(&transform),
737 false,
738 DWRITE_OUTLINE_THRESHOLD_ANTIALIASED,
739 DWRITE_MEASURING_MODE_NATURAL,
740 None,
741 &mut rendering_mode,
742 &mut grid_fit_mode,
743 )?;
744 }
745
746 let glyph_analysis = unsafe {
747 self.components.factory.CreateGlyphRunAnalysis(
748 &glyph_run,
749 Some(&transform),
750 rendering_mode,
751 DWRITE_MEASURING_MODE_NATURAL,
752 grid_fit_mode,
753 DWRITE_TEXT_ANTIALIAS_MODE_GRAYSCALE,
754 baseline_origin_x,
755 baseline_origin_y,
756 )
757 }?;
758 Ok(glyph_analysis)
759 }
760
761 fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
762 let glyph_analysis = self.create_glyph_run_analysis(params)?;
763
764 let bounds = unsafe { glyph_analysis.GetAlphaTextureBounds(DWRITE_TEXTURE_ALIASED_1x1)? };
765
766 if bounds.right < bounds.left {
767 Ok(Bounds {
768 origin: point(0.into(), 0.into()),
769 size: size(0.into(), 0.into()),
770 })
771 } else {
772 Ok(Bounds {
773 origin: point(bounds.left.into(), bounds.top.into()),
774 size: size(
775 (bounds.right - bounds.left).into(),
776 (bounds.bottom - bounds.top).into(),
777 ),
778 })
779 }
780 }
781
782 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
783 let font_info = &self.fonts[font_id.0];
784 let codepoints = [ch as u32];
785 let mut glyph_indices = vec![0u16; 1];
786 unsafe {
787 font_info
788 .font_face
789 .GetGlyphIndices(codepoints.as_ptr(), 1, glyph_indices.as_mut_ptr())
790 .log_err()
791 }
792 .map(|_| GlyphId(glyph_indices[0] as u32))
793 }
794
795 fn rasterize_glyph(
796 &self,
797 params: &RenderGlyphParams,
798 glyph_bounds: Bounds<DevicePixels>,
799 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
800 if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
801 anyhow::bail!("glyph bounds are empty");
802 }
803
804 let bitmap_data = if params.is_emoji {
805 if let Ok(color) = self.rasterize_color(params, glyph_bounds) {
806 color
807 } else {
808 let monochrome = self.rasterize_monochrome(params, glyph_bounds)?;
809 monochrome
810 .into_iter()
811 .flat_map(|pixel| [0, 0, 0, pixel])
812 .collect::<Vec<_>>()
813 }
814 } else {
815 self.rasterize_monochrome(params, glyph_bounds)?
816 };
817
818 Ok((glyph_bounds.size, bitmap_data))
819 }
820
821 fn rasterize_monochrome(
822 &self,
823 params: &RenderGlyphParams,
824 glyph_bounds: Bounds<DevicePixels>,
825 ) -> Result<Vec<u8>> {
826 let mut bitmap_data =
827 vec![0u8; glyph_bounds.size.width.0 as usize * glyph_bounds.size.height.0 as usize];
828
829 let glyph_analysis = self.create_glyph_run_analysis(params)?;
830 unsafe {
831 glyph_analysis.CreateAlphaTexture(
832 DWRITE_TEXTURE_ALIASED_1x1,
833 &RECT {
834 left: glyph_bounds.origin.x.0,
835 top: glyph_bounds.origin.y.0,
836 right: glyph_bounds.size.width.0 + glyph_bounds.origin.x.0,
837 bottom: glyph_bounds.size.height.0 + glyph_bounds.origin.y.0,
838 },
839 &mut bitmap_data,
840 )?;
841 }
842
843 Ok(bitmap_data)
844 }
845
846 fn rasterize_color(
847 &self,
848 params: &RenderGlyphParams,
849 glyph_bounds: Bounds<DevicePixels>,
850 ) -> Result<Vec<u8>> {
851 let bitmap_size = glyph_bounds.size;
852 let subpixel_shift = params
853 .subpixel_variant
854 .map(|v| v as f32 / SUBPIXEL_VARIANTS as f32);
855 let baseline_origin_x = subpixel_shift.x / params.scale_factor;
856 let baseline_origin_y = subpixel_shift.y / params.scale_factor;
857
858 let transform = DWRITE_MATRIX {
859 m11: params.scale_factor,
860 m12: 0.0,
861 m21: 0.0,
862 m22: params.scale_factor,
863 dx: 0.0,
864 dy: 0.0,
865 };
866
867 let font = &self.fonts[params.font_id.0];
868 let glyph_id = [params.glyph_id.0 as u16];
869 let advance = [glyph_bounds.size.width.0 as f32];
870 let offset = [DWRITE_GLYPH_OFFSET {
871 advanceOffset: -glyph_bounds.origin.x.0 as f32 / params.scale_factor,
872 ascenderOffset: glyph_bounds.origin.y.0 as f32 / params.scale_factor,
873 }];
874 let glyph_run = DWRITE_GLYPH_RUN {
875 fontFace: unsafe { std::mem::transmute_copy(&font.font_face) },
876 fontEmSize: params.font_size.0,
877 glyphCount: 1,
878 glyphIndices: glyph_id.as_ptr(),
879 glyphAdvances: advance.as_ptr(),
880 glyphOffsets: offset.as_ptr(),
881 isSideways: BOOL(0),
882 bidiLevel: 0,
883 };
884
885 // todo: support formats other than COLR
886 let color_enumerator = unsafe {
887 self.components.factory.TranslateColorGlyphRun(
888 Vector2::new(baseline_origin_x, baseline_origin_y),
889 &glyph_run,
890 None,
891 DWRITE_GLYPH_IMAGE_FORMATS_COLR,
892 DWRITE_MEASURING_MODE_NATURAL,
893 Some(&transform),
894 0,
895 )
896 }?;
897
898 let mut glyph_layers = Vec::new();
899 loop {
900 let color_run = unsafe { color_enumerator.GetCurrentRun() }?;
901 let color_run = unsafe { &*color_run };
902 let image_format = color_run.glyphImageFormat & !DWRITE_GLYPH_IMAGE_FORMATS_TRUETYPE;
903 if image_format == DWRITE_GLYPH_IMAGE_FORMATS_COLR {
904 let color_analysis = unsafe {
905 self.components.factory.CreateGlyphRunAnalysis(
906 &color_run.Base.glyphRun as *const _,
907 Some(&transform),
908 DWRITE_RENDERING_MODE1_NATURAL_SYMMETRIC,
909 DWRITE_MEASURING_MODE_NATURAL,
910 DWRITE_GRID_FIT_MODE_DEFAULT,
911 DWRITE_TEXT_ANTIALIAS_MODE_GRAYSCALE,
912 baseline_origin_x,
913 baseline_origin_y,
914 )
915 }?;
916
917 let color_bounds =
918 unsafe { color_analysis.GetAlphaTextureBounds(DWRITE_TEXTURE_ALIASED_1x1) }?;
919
920 let color_size = size(
921 color_bounds.right - color_bounds.left,
922 color_bounds.bottom - color_bounds.top,
923 );
924 if color_size.width > 0 && color_size.height > 0 {
925 let mut alpha_data = vec![0u8; (color_size.width * color_size.height) as usize];
926 unsafe {
927 color_analysis.CreateAlphaTexture(
928 DWRITE_TEXTURE_ALIASED_1x1,
929 &color_bounds,
930 &mut alpha_data,
931 )
932 }?;
933
934 let run_color = {
935 let run_color = color_run.Base.runColor;
936 Rgba {
937 r: run_color.r,
938 g: run_color.g,
939 b: run_color.b,
940 a: run_color.a,
941 }
942 };
943 let bounds = bounds(point(color_bounds.left, color_bounds.top), color_size);
944 glyph_layers.push(GlyphLayerTexture::new(
945 &self.components.gpu_state,
946 run_color,
947 bounds,
948 &alpha_data,
949 )?);
950 }
951 }
952
953 let has_next = unsafe { color_enumerator.MoveNext() }
954 .map(|e| e.as_bool())
955 .unwrap_or(false);
956 if !has_next {
957 break;
958 }
959 }
960
961 let gpu_state = &self.components.gpu_state;
962 let params_buffer = {
963 let desc = D3D11_BUFFER_DESC {
964 ByteWidth: std::mem::size_of::<GlyphLayerTextureParams>() as u32,
965 Usage: D3D11_USAGE_DYNAMIC,
966 BindFlags: D3D11_BIND_CONSTANT_BUFFER.0 as u32,
967 CPUAccessFlags: D3D11_CPU_ACCESS_WRITE.0 as u32,
968 MiscFlags: 0,
969 StructureByteStride: 0,
970 };
971
972 let mut buffer = None;
973 unsafe {
974 gpu_state
975 .device
976 .CreateBuffer(&desc, None, Some(&mut buffer))
977 }?;
978 [buffer]
979 };
980
981 let render_target_texture = {
982 let mut texture = None;
983 let desc = D3D11_TEXTURE2D_DESC {
984 Width: bitmap_size.width.0 as u32,
985 Height: bitmap_size.height.0 as u32,
986 MipLevels: 1,
987 ArraySize: 1,
988 Format: DXGI_FORMAT_B8G8R8A8_UNORM,
989 SampleDesc: DXGI_SAMPLE_DESC {
990 Count: 1,
991 Quality: 0,
992 },
993 Usage: D3D11_USAGE_DEFAULT,
994 BindFlags: D3D11_BIND_RENDER_TARGET.0 as u32,
995 CPUAccessFlags: 0,
996 MiscFlags: 0,
997 };
998 unsafe {
999 gpu_state
1000 .device
1001 .CreateTexture2D(&desc, None, Some(&mut texture))
1002 }?;
1003 texture.unwrap()
1004 };
1005
1006 let render_target_view = {
1007 let desc = D3D11_RENDER_TARGET_VIEW_DESC {
1008 Format: DXGI_FORMAT_B8G8R8A8_UNORM,
1009 ViewDimension: D3D11_RTV_DIMENSION_TEXTURE2D,
1010 Anonymous: D3D11_RENDER_TARGET_VIEW_DESC_0 {
1011 Texture2D: D3D11_TEX2D_RTV { MipSlice: 0 },
1012 },
1013 };
1014 let mut rtv = None;
1015 unsafe {
1016 gpu_state.device.CreateRenderTargetView(
1017 &render_target_texture,
1018 Some(&desc),
1019 Some(&mut rtv),
1020 )
1021 }?;
1022 [rtv]
1023 };
1024
1025 let staging_texture = {
1026 let mut texture = None;
1027 let desc = D3D11_TEXTURE2D_DESC {
1028 Width: bitmap_size.width.0 as u32,
1029 Height: bitmap_size.height.0 as u32,
1030 MipLevels: 1,
1031 ArraySize: 1,
1032 Format: DXGI_FORMAT_B8G8R8A8_UNORM,
1033 SampleDesc: DXGI_SAMPLE_DESC {
1034 Count: 1,
1035 Quality: 0,
1036 },
1037 Usage: D3D11_USAGE_STAGING,
1038 BindFlags: 0,
1039 CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32,
1040 MiscFlags: 0,
1041 };
1042 unsafe {
1043 gpu_state
1044 .device
1045 .CreateTexture2D(&desc, None, Some(&mut texture))
1046 }?;
1047 texture.unwrap()
1048 };
1049
1050 let device_context = &gpu_state.device_context;
1051 unsafe { device_context.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP) };
1052 unsafe { device_context.VSSetShader(&gpu_state.vertex_shader, None) };
1053 unsafe { device_context.PSSetShader(&gpu_state.pixel_shader, None) };
1054 unsafe { device_context.VSSetConstantBuffers(0, Some(¶ms_buffer)) };
1055 unsafe { device_context.PSSetConstantBuffers(0, Some(¶ms_buffer)) };
1056 unsafe { device_context.OMSetRenderTargets(Some(&render_target_view), None) };
1057 unsafe { device_context.PSSetSamplers(0, Some(&gpu_state.sampler)) };
1058 unsafe { device_context.OMSetBlendState(&gpu_state.blend_state, None, 0xffffffff) };
1059
1060 let crate::FontInfo {
1061 gamma_ratios,
1062 grayscale_enhanced_contrast,
1063 } = DirectXRenderer::get_font_info();
1064
1065 for layer in glyph_layers {
1066 let params = GlyphLayerTextureParams {
1067 run_color: layer.run_color,
1068 bounds: layer.bounds,
1069 gamma_ratios: *gamma_ratios,
1070 grayscale_enhanced_contrast: *grayscale_enhanced_contrast,
1071 _pad: [0f32; 3],
1072 };
1073 unsafe {
1074 let mut dest = std::mem::zeroed();
1075 gpu_state.device_context.Map(
1076 params_buffer[0].as_ref().unwrap(),
1077 0,
1078 D3D11_MAP_WRITE_DISCARD,
1079 0,
1080 Some(&mut dest),
1081 )?;
1082 std::ptr::copy_nonoverlapping(¶ms as *const _, dest.pData as *mut _, 1);
1083 gpu_state
1084 .device_context
1085 .Unmap(params_buffer[0].as_ref().unwrap(), 0);
1086 };
1087
1088 let texture = [Some(layer.texture_view)];
1089 unsafe { device_context.PSSetShaderResources(0, Some(&texture)) };
1090
1091 let viewport = [D3D11_VIEWPORT {
1092 TopLeftX: layer.bounds.origin.x as f32,
1093 TopLeftY: layer.bounds.origin.y as f32,
1094 Width: layer.bounds.size.width as f32,
1095 Height: layer.bounds.size.height as f32,
1096 MinDepth: 0.0,
1097 MaxDepth: 1.0,
1098 }];
1099 unsafe { device_context.RSSetViewports(Some(&viewport)) };
1100
1101 unsafe { device_context.Draw(4, 0) };
1102 }
1103
1104 unsafe { device_context.CopyResource(&staging_texture, &render_target_texture) };
1105
1106 let mapped_data = {
1107 let mut mapped_data = D3D11_MAPPED_SUBRESOURCE::default();
1108 unsafe {
1109 device_context.Map(
1110 &staging_texture,
1111 0,
1112 D3D11_MAP_READ,
1113 0,
1114 Some(&mut mapped_data),
1115 )
1116 }?;
1117 mapped_data
1118 };
1119 let mut rasterized =
1120 vec![0u8; (bitmap_size.width.0 as u32 * bitmap_size.height.0 as u32 * 4) as usize];
1121
1122 for y in 0..bitmap_size.height.0 as usize {
1123 let width = bitmap_size.width.0 as usize;
1124 unsafe {
1125 std::ptr::copy_nonoverlapping::<u8>(
1126 (mapped_data.pData as *const u8).byte_add(mapped_data.RowPitch as usize * y),
1127 rasterized
1128 .as_mut_ptr()
1129 .byte_add(width * y * std::mem::size_of::<u32>()),
1130 width * std::mem::size_of::<u32>(),
1131 )
1132 };
1133 }
1134
1135 Ok(rasterized)
1136 }
1137
1138 fn get_typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
1139 unsafe {
1140 let font = &self.fonts[font_id.0].font_face;
1141 let glyph_indices = [glyph_id.0 as u16];
1142 let mut metrics = [DWRITE_GLYPH_METRICS::default()];
1143 font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
1144
1145 let metrics = &metrics[0];
1146 let advance_width = metrics.advanceWidth as i32;
1147 let advance_height = metrics.advanceHeight as i32;
1148 let left_side_bearing = metrics.leftSideBearing;
1149 let right_side_bearing = metrics.rightSideBearing;
1150 let top_side_bearing = metrics.topSideBearing;
1151 let bottom_side_bearing = metrics.bottomSideBearing;
1152 let vertical_origin_y = metrics.verticalOriginY;
1153
1154 let y_offset = vertical_origin_y + bottom_side_bearing - advance_height;
1155 let width = advance_width - (left_side_bearing + right_side_bearing);
1156 let height = advance_height - (top_side_bearing + bottom_side_bearing);
1157
1158 Ok(Bounds {
1159 origin: Point {
1160 x: left_side_bearing as f32,
1161 y: y_offset as f32,
1162 },
1163 size: Size {
1164 width: width as f32,
1165 height: height as f32,
1166 },
1167 })
1168 }
1169 }
1170
1171 fn get_advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1172 unsafe {
1173 let font = &self.fonts[font_id.0].font_face;
1174 let glyph_indices = [glyph_id.0 as u16];
1175 let mut metrics = [DWRITE_GLYPH_METRICS::default()];
1176 font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
1177
1178 let metrics = &metrics[0];
1179
1180 Ok(Size {
1181 width: metrics.advanceWidth as f32,
1182 height: 0.0,
1183 })
1184 }
1185 }
1186
1187 fn all_font_names(&self) -> Vec<String> {
1188 let mut result =
1189 get_font_names_from_collection(&self.system_font_collection, &self.components.locale);
1190 result.extend(get_font_names_from_collection(
1191 &self.custom_font_collection,
1192 &self.components.locale,
1193 ));
1194 result
1195 }
1196}
1197
1198impl Drop for DirectWriteState {
1199 fn drop(&mut self) {
1200 unsafe {
1201 let _ = self
1202 .components
1203 .factory
1204 .UnregisterFontFileLoader(&self.components.in_memory_loader);
1205 }
1206 }
1207}
1208
1209struct GlyphLayerTexture {
1210 run_color: Rgba,
1211 bounds: Bounds<i32>,
1212 texture_view: ID3D11ShaderResourceView,
1213 // holding on to the texture to not RAII drop it
1214 _texture: ID3D11Texture2D,
1215}
1216
1217impl GlyphLayerTexture {
1218 pub fn new(
1219 gpu_state: &GPUState,
1220 run_color: Rgba,
1221 bounds: Bounds<i32>,
1222 alpha_data: &[u8],
1223 ) -> Result<Self> {
1224 let texture_size = bounds.size;
1225
1226 let desc = D3D11_TEXTURE2D_DESC {
1227 Width: texture_size.width as u32,
1228 Height: texture_size.height as u32,
1229 MipLevels: 1,
1230 ArraySize: 1,
1231 Format: DXGI_FORMAT_R8_UNORM,
1232 SampleDesc: DXGI_SAMPLE_DESC {
1233 Count: 1,
1234 Quality: 0,
1235 },
1236 Usage: D3D11_USAGE_DEFAULT,
1237 BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32,
1238 CPUAccessFlags: D3D11_CPU_ACCESS_WRITE.0 as u32,
1239 MiscFlags: 0,
1240 };
1241
1242 let texture = {
1243 let mut texture: Option<ID3D11Texture2D> = None;
1244 unsafe {
1245 gpu_state
1246 .device
1247 .CreateTexture2D(&desc, None, Some(&mut texture))?
1248 };
1249 texture.unwrap()
1250 };
1251 let texture_view = {
1252 let mut view: Option<ID3D11ShaderResourceView> = None;
1253 unsafe {
1254 gpu_state
1255 .device
1256 .CreateShaderResourceView(&texture, None, Some(&mut view))?
1257 };
1258 view.unwrap()
1259 };
1260
1261 unsafe {
1262 gpu_state.device_context.UpdateSubresource(
1263 &texture,
1264 0,
1265 None,
1266 alpha_data.as_ptr() as _,
1267 texture_size.width as u32,
1268 0,
1269 )
1270 };
1271
1272 Ok(GlyphLayerTexture {
1273 run_color,
1274 bounds,
1275 texture_view,
1276 _texture: texture,
1277 })
1278 }
1279}
1280
1281#[repr(C)]
1282struct GlyphLayerTextureParams {
1283 bounds: Bounds<i32>,
1284 run_color: Rgba,
1285 gamma_ratios: [f32; 4],
1286 grayscale_enhanced_contrast: f32,
1287 _pad: [f32; 3],
1288}
1289
1290struct TextRendererWrapper(pub IDWriteTextRenderer);
1291
1292impl TextRendererWrapper {
1293 pub fn new(locale_str: &str) -> Self {
1294 let inner = TextRenderer::new(locale_str);
1295 TextRendererWrapper(inner.into())
1296 }
1297}
1298
1299#[implement(IDWriteTextRenderer)]
1300struct TextRenderer {
1301 locale: String,
1302}
1303
1304impl TextRenderer {
1305 pub fn new(locale_str: &str) -> Self {
1306 TextRenderer {
1307 locale: locale_str.to_owned(),
1308 }
1309 }
1310}
1311
1312struct RendererContext<'t, 'a, 'b> {
1313 text_system: &'t mut DirectWriteState,
1314 index_converter: StringIndexConverter<'a>,
1315 runs: &'b mut Vec<ShapedRun>,
1316 width: f32,
1317}
1318
1319#[derive(Debug)]
1320struct ClusterAnalyzer<'t> {
1321 utf16_idx: usize,
1322 glyph_idx: usize,
1323 glyph_count: usize,
1324 cluster_map: &'t [u16],
1325}
1326
1327impl<'t> ClusterAnalyzer<'t> {
1328 pub fn new(cluster_map: &'t [u16], glyph_count: usize) -> Self {
1329 ClusterAnalyzer {
1330 utf16_idx: 0,
1331 glyph_idx: 0,
1332 glyph_count,
1333 cluster_map,
1334 }
1335 }
1336}
1337
1338impl Iterator for ClusterAnalyzer<'_> {
1339 type Item = (usize, usize);
1340
1341 fn next(&mut self) -> Option<(usize, usize)> {
1342 if self.utf16_idx >= self.cluster_map.len() {
1343 return None; // No more clusters
1344 }
1345 let start_utf16_idx = self.utf16_idx;
1346 let current_glyph = self.cluster_map[start_utf16_idx] as usize;
1347
1348 // Find the end of current cluster (where glyph index changes)
1349 let mut end_utf16_idx = start_utf16_idx + 1;
1350 while end_utf16_idx < self.cluster_map.len()
1351 && self.cluster_map[end_utf16_idx] as usize == current_glyph
1352 {
1353 end_utf16_idx += 1;
1354 }
1355
1356 let utf16_len = end_utf16_idx - start_utf16_idx;
1357
1358 // Calculate glyph count for this cluster
1359 let next_glyph = if end_utf16_idx < self.cluster_map.len() {
1360 self.cluster_map[end_utf16_idx] as usize
1361 } else {
1362 self.glyph_count
1363 };
1364
1365 let glyph_count = next_glyph - current_glyph;
1366
1367 // Update state for next call
1368 self.utf16_idx = end_utf16_idx;
1369 self.glyph_idx = next_glyph;
1370
1371 Some((utf16_len, glyph_count))
1372 }
1373}
1374
1375#[allow(non_snake_case)]
1376impl IDWritePixelSnapping_Impl for TextRenderer_Impl {
1377 fn IsPixelSnappingDisabled(
1378 &self,
1379 _clientdrawingcontext: *const ::core::ffi::c_void,
1380 ) -> windows::core::Result<BOOL> {
1381 Ok(BOOL(0))
1382 }
1383
1384 fn GetCurrentTransform(
1385 &self,
1386 _clientdrawingcontext: *const ::core::ffi::c_void,
1387 transform: *mut DWRITE_MATRIX,
1388 ) -> windows::core::Result<()> {
1389 unsafe {
1390 *transform = DWRITE_MATRIX {
1391 m11: 1.0,
1392 m12: 0.0,
1393 m21: 0.0,
1394 m22: 1.0,
1395 dx: 0.0,
1396 dy: 0.0,
1397 };
1398 }
1399 Ok(())
1400 }
1401
1402 fn GetPixelsPerDip(
1403 &self,
1404 _clientdrawingcontext: *const ::core::ffi::c_void,
1405 ) -> windows::core::Result<f32> {
1406 Ok(1.0)
1407 }
1408}
1409
1410#[allow(non_snake_case)]
1411impl IDWriteTextRenderer_Impl for TextRenderer_Impl {
1412 fn DrawGlyphRun(
1413 &self,
1414 clientdrawingcontext: *const ::core::ffi::c_void,
1415 _baselineoriginx: f32,
1416 _baselineoriginy: f32,
1417 _measuringmode: DWRITE_MEASURING_MODE,
1418 glyphrun: *const DWRITE_GLYPH_RUN,
1419 glyphrundescription: *const DWRITE_GLYPH_RUN_DESCRIPTION,
1420 _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1421 ) -> windows::core::Result<()> {
1422 let glyphrun = unsafe { &*glyphrun };
1423 let glyph_count = glyphrun.glyphCount as usize;
1424 if glyph_count == 0 || glyphrun.fontFace.is_none() {
1425 return Ok(());
1426 }
1427 let desc = unsafe { &*glyphrundescription };
1428 let context = unsafe {
1429 &mut *(clientdrawingcontext as *const RendererContext as *mut RendererContext)
1430 };
1431 let font_face = glyphrun.fontFace.as_ref().unwrap();
1432 // This `cast()` action here should never fail since we are running on Win10+, and
1433 // `IDWriteFontFace3` requires Win10
1434 let font_face = &font_face.cast::<IDWriteFontFace3>().unwrap();
1435 let Some((font_identifier, font_struct, color_font)) =
1436 get_font_identifier_and_font_struct(font_face, &self.locale)
1437 else {
1438 return Ok(());
1439 };
1440
1441 let font_id = if let Some(id) = context
1442 .text_system
1443 .font_id_by_identifier
1444 .get(&font_identifier)
1445 {
1446 *id
1447 } else {
1448 context.text_system.select_font(&font_struct)
1449 };
1450
1451 let glyph_ids = unsafe { std::slice::from_raw_parts(glyphrun.glyphIndices, glyph_count) };
1452 let glyph_advances =
1453 unsafe { std::slice::from_raw_parts(glyphrun.glyphAdvances, glyph_count) };
1454 let glyph_offsets =
1455 unsafe { std::slice::from_raw_parts(glyphrun.glyphOffsets, glyph_count) };
1456 let cluster_map =
1457 unsafe { std::slice::from_raw_parts(desc.clusterMap, desc.stringLength as usize) };
1458
1459 let mut cluster_analyzer = ClusterAnalyzer::new(cluster_map, glyph_count);
1460 let mut utf16_idx = desc.textPosition as usize;
1461 let mut glyph_idx = 0;
1462 let mut glyphs = Vec::with_capacity(glyph_count);
1463 for (cluster_utf16_len, cluster_glyph_count) in cluster_analyzer {
1464 context.index_converter.advance_to_utf16_ix(utf16_idx);
1465 utf16_idx += cluster_utf16_len;
1466 for (cluster_glyph_idx, glyph_id) in glyph_ids
1467 [glyph_idx..(glyph_idx + cluster_glyph_count)]
1468 .iter()
1469 .enumerate()
1470 {
1471 let id = GlyphId(*glyph_id as u32);
1472 let is_emoji = color_font
1473 && is_color_glyph(font_face, id, &context.text_system.components.factory);
1474 let this_glyph_idx = glyph_idx + cluster_glyph_idx;
1475 glyphs.push(ShapedGlyph {
1476 id,
1477 position: point(
1478 px(context.width + glyph_offsets[this_glyph_idx].advanceOffset),
1479 px(0.0),
1480 ),
1481 index: context.index_converter.utf8_ix,
1482 is_emoji,
1483 });
1484 context.width += glyph_advances[this_glyph_idx];
1485 }
1486 glyph_idx += cluster_glyph_count;
1487 }
1488 context.runs.push(ShapedRun { font_id, glyphs });
1489 Ok(())
1490 }
1491
1492 fn DrawUnderline(
1493 &self,
1494 _clientdrawingcontext: *const ::core::ffi::c_void,
1495 _baselineoriginx: f32,
1496 _baselineoriginy: f32,
1497 _underline: *const DWRITE_UNDERLINE,
1498 _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1499 ) -> windows::core::Result<()> {
1500 Err(windows::core::Error::new(
1501 E_NOTIMPL,
1502 "DrawUnderline unimplemented",
1503 ))
1504 }
1505
1506 fn DrawStrikethrough(
1507 &self,
1508 _clientdrawingcontext: *const ::core::ffi::c_void,
1509 _baselineoriginx: f32,
1510 _baselineoriginy: f32,
1511 _strikethrough: *const DWRITE_STRIKETHROUGH,
1512 _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1513 ) -> windows::core::Result<()> {
1514 Err(windows::core::Error::new(
1515 E_NOTIMPL,
1516 "DrawStrikethrough unimplemented",
1517 ))
1518 }
1519
1520 fn DrawInlineObject(
1521 &self,
1522 _clientdrawingcontext: *const ::core::ffi::c_void,
1523 _originx: f32,
1524 _originy: f32,
1525 _inlineobject: windows::core::Ref<IDWriteInlineObject>,
1526 _issideways: BOOL,
1527 _isrighttoleft: BOOL,
1528 _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1529 ) -> windows::core::Result<()> {
1530 Err(windows::core::Error::new(
1531 E_NOTIMPL,
1532 "DrawInlineObject unimplemented",
1533 ))
1534 }
1535}
1536
1537struct StringIndexConverter<'a> {
1538 text: &'a str,
1539 utf8_ix: usize,
1540 utf16_ix: usize,
1541}
1542
1543impl<'a> StringIndexConverter<'a> {
1544 fn new(text: &'a str) -> Self {
1545 Self {
1546 text,
1547 utf8_ix: 0,
1548 utf16_ix: 0,
1549 }
1550 }
1551
1552 #[allow(dead_code)]
1553 fn advance_to_utf8_ix(&mut self, utf8_target: usize) {
1554 for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1555 if self.utf8_ix + ix >= utf8_target {
1556 self.utf8_ix += ix;
1557 return;
1558 }
1559 self.utf16_ix += c.len_utf16();
1560 }
1561 self.utf8_ix = self.text.len();
1562 }
1563
1564 fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
1565 for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1566 if self.utf16_ix >= utf16_target {
1567 self.utf8_ix += ix;
1568 return;
1569 }
1570 self.utf16_ix += c.len_utf16();
1571 }
1572 self.utf8_ix = self.text.len();
1573 }
1574}
1575
1576impl Into<DWRITE_FONT_STYLE> for FontStyle {
1577 fn into(self) -> DWRITE_FONT_STYLE {
1578 match self {
1579 FontStyle::Normal => DWRITE_FONT_STYLE_NORMAL,
1580 FontStyle::Italic => DWRITE_FONT_STYLE_ITALIC,
1581 FontStyle::Oblique => DWRITE_FONT_STYLE_OBLIQUE,
1582 }
1583 }
1584}
1585
1586impl From<DWRITE_FONT_STYLE> for FontStyle {
1587 fn from(value: DWRITE_FONT_STYLE) -> Self {
1588 match value.0 {
1589 0 => FontStyle::Normal,
1590 1 => FontStyle::Italic,
1591 2 => FontStyle::Oblique,
1592 _ => unreachable!(),
1593 }
1594 }
1595}
1596
1597impl Into<DWRITE_FONT_WEIGHT> for FontWeight {
1598 fn into(self) -> DWRITE_FONT_WEIGHT {
1599 DWRITE_FONT_WEIGHT(self.0 as i32)
1600 }
1601}
1602
1603impl From<DWRITE_FONT_WEIGHT> for FontWeight {
1604 fn from(value: DWRITE_FONT_WEIGHT) -> Self {
1605 FontWeight(value.0 as f32)
1606 }
1607}
1608
1609fn get_font_names_from_collection(
1610 collection: &IDWriteFontCollection1,
1611 locale: &str,
1612) -> Vec<String> {
1613 unsafe {
1614 let mut result = Vec::new();
1615 let family_count = collection.GetFontFamilyCount();
1616 for index in 0..family_count {
1617 let Some(font_family) = collection.GetFontFamily(index).log_err() else {
1618 continue;
1619 };
1620 let Some(localized_family_name) = font_family.GetFamilyNames().log_err() else {
1621 continue;
1622 };
1623 let Some(family_name) = get_name(localized_family_name, locale).log_err() else {
1624 continue;
1625 };
1626 result.push(family_name);
1627 }
1628
1629 result
1630 }
1631}
1632
1633fn get_font_identifier_and_font_struct(
1634 font_face: &IDWriteFontFace3,
1635 locale: &str,
1636) -> Option<(FontIdentifier, Font, bool)> {
1637 let postscript_name = get_postscript_name(font_face, locale).log_err()?;
1638 let localized_family_name = unsafe { font_face.GetFamilyNames().log_err() }?;
1639 let family_name = get_name(localized_family_name, locale).log_err()?;
1640 let weight = unsafe { font_face.GetWeight() };
1641 let style = unsafe { font_face.GetStyle() };
1642 let identifier = FontIdentifier {
1643 postscript_name,
1644 weight: weight.0,
1645 style: style.0,
1646 };
1647 let font_struct = Font {
1648 family: family_name.into(),
1649 features: FontFeatures::default(),
1650 weight: weight.into(),
1651 style: style.into(),
1652 fallbacks: None,
1653 };
1654 let is_emoji = unsafe { font_face.IsColorFont().as_bool() };
1655 Some((identifier, font_struct, is_emoji))
1656}
1657
1658#[inline]
1659fn get_font_identifier(font_face: &IDWriteFontFace3, locale: &str) -> Option<FontIdentifier> {
1660 let weight = unsafe { font_face.GetWeight().0 };
1661 let style = unsafe { font_face.GetStyle().0 };
1662 get_postscript_name(font_face, locale)
1663 .log_err()
1664 .map(|postscript_name| FontIdentifier {
1665 postscript_name,
1666 weight,
1667 style,
1668 })
1669}
1670
1671#[inline]
1672fn get_postscript_name(font_face: &IDWriteFontFace3, locale: &str) -> Result<String> {
1673 let mut info = None;
1674 let mut exists = BOOL(0);
1675 unsafe {
1676 font_face.GetInformationalStrings(
1677 DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_NAME,
1678 &mut info,
1679 &mut exists,
1680 )?
1681 };
1682 if !exists.as_bool() || info.is_none() {
1683 anyhow::bail!("No postscript name found for font face");
1684 }
1685
1686 get_name(info.unwrap(), locale)
1687}
1688
1689// https://learn.microsoft.com/en-us/windows/win32/api/dwrite/ne-dwrite-dwrite_font_feature_tag
1690fn apply_font_features(
1691 direct_write_features: &IDWriteTypography,
1692 features: &FontFeatures,
1693) -> Result<()> {
1694 let tag_values = features.tag_value_list();
1695 if tag_values.is_empty() {
1696 return Ok(());
1697 }
1698
1699 // All of these features are enabled by default by DirectWrite.
1700 // If you want to (and can) peek into the source of DirectWrite
1701 let mut feature_liga = make_direct_write_feature("liga", 1);
1702 let mut feature_clig = make_direct_write_feature("clig", 1);
1703 let mut feature_calt = make_direct_write_feature("calt", 1);
1704
1705 for (tag, value) in tag_values {
1706 if tag.as_str() == "liga" && *value == 0 {
1707 feature_liga.parameter = 0;
1708 continue;
1709 }
1710 if tag.as_str() == "clig" && *value == 0 {
1711 feature_clig.parameter = 0;
1712 continue;
1713 }
1714 if tag.as_str() == "calt" && *value == 0 {
1715 feature_calt.parameter = 0;
1716 continue;
1717 }
1718
1719 unsafe {
1720 direct_write_features.AddFontFeature(make_direct_write_feature(tag, *value))?;
1721 }
1722 }
1723 unsafe {
1724 direct_write_features.AddFontFeature(feature_liga)?;
1725 direct_write_features.AddFontFeature(feature_clig)?;
1726 direct_write_features.AddFontFeature(feature_calt)?;
1727 }
1728
1729 Ok(())
1730}
1731
1732#[inline]
1733const fn make_direct_write_feature(feature_name: &str, parameter: u32) -> DWRITE_FONT_FEATURE {
1734 let tag = make_direct_write_tag(feature_name);
1735 DWRITE_FONT_FEATURE {
1736 nameTag: tag,
1737 parameter,
1738 }
1739}
1740
1741#[inline]
1742const fn make_open_type_tag(tag_name: &str) -> u32 {
1743 let bytes = tag_name.as_bytes();
1744 debug_assert!(bytes.len() == 4);
1745 u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
1746}
1747
1748#[inline]
1749const fn make_direct_write_tag(tag_name: &str) -> DWRITE_FONT_FEATURE_TAG {
1750 DWRITE_FONT_FEATURE_TAG(make_open_type_tag(tag_name))
1751}
1752
1753#[inline]
1754fn get_name(string: IDWriteLocalizedStrings, locale: &str) -> Result<String> {
1755 let mut locale_name_index = 0u32;
1756 let mut exists = BOOL(0);
1757 unsafe {
1758 string.FindLocaleName(
1759 &HSTRING::from(locale),
1760 &mut locale_name_index,
1761 &mut exists as _,
1762 )?
1763 };
1764 if !exists.as_bool() {
1765 unsafe {
1766 string.FindLocaleName(
1767 DEFAULT_LOCALE_NAME,
1768 &mut locale_name_index as _,
1769 &mut exists as _,
1770 )?
1771 };
1772 anyhow::ensure!(exists.as_bool(), "No localised string for {locale}");
1773 }
1774
1775 let name_length = unsafe { string.GetStringLength(locale_name_index) }? as usize;
1776 let mut name_vec = vec![0u16; name_length + 1];
1777 unsafe {
1778 string.GetString(locale_name_index, &mut name_vec)?;
1779 }
1780
1781 Ok(String::from_utf16_lossy(&name_vec[..name_length]))
1782}
1783
1784fn get_system_ui_font_name() -> SharedString {
1785 unsafe {
1786 let mut info: LOGFONTW = std::mem::zeroed();
1787 let font_family = if SystemParametersInfoW(
1788 SPI_GETICONTITLELOGFONT,
1789 std::mem::size_of::<LOGFONTW>() as u32,
1790 Some(&mut info as *mut _ as _),
1791 SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
1792 )
1793 .log_err()
1794 .is_none()
1795 {
1796 // https://learn.microsoft.com/en-us/windows/win32/uxguide/vis-fonts
1797 // Segoe UI is the Windows font intended for user interface text strings.
1798 "Segoe UI".into()
1799 } else {
1800 let font_name = String::from_utf16_lossy(&info.lfFaceName);
1801 font_name.trim_matches(char::from(0)).to_owned().into()
1802 };
1803 log::info!("Use {} as UI font.", font_family);
1804 font_family
1805 }
1806}
1807
1808// One would think that with newer DirectWrite method: IDWriteFontFace4::GetGlyphImageFormats
1809// but that doesn't seem to work for some glyphs, say โค
1810fn is_color_glyph(
1811 font_face: &IDWriteFontFace3,
1812 glyph_id: GlyphId,
1813 factory: &IDWriteFactory5,
1814) -> bool {
1815 let glyph_run = DWRITE_GLYPH_RUN {
1816 fontFace: unsafe { std::mem::transmute_copy(font_face) },
1817 fontEmSize: 14.0,
1818 glyphCount: 1,
1819 glyphIndices: &(glyph_id.0 as u16),
1820 glyphAdvances: &0.0,
1821 glyphOffsets: &DWRITE_GLYPH_OFFSET {
1822 advanceOffset: 0.0,
1823 ascenderOffset: 0.0,
1824 },
1825 isSideways: BOOL(0),
1826 bidiLevel: 0,
1827 };
1828 unsafe {
1829 factory.TranslateColorGlyphRun(
1830 Vector2::default(),
1831 &glyph_run as _,
1832 None,
1833 DWRITE_GLYPH_IMAGE_FORMATS_COLR
1834 | DWRITE_GLYPH_IMAGE_FORMATS_SVG
1835 | DWRITE_GLYPH_IMAGE_FORMATS_PNG
1836 | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
1837 | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8,
1838 DWRITE_MEASURING_MODE_NATURAL,
1839 None,
1840 0,
1841 )
1842 }
1843 .is_ok()
1844}
1845
1846const DEFAULT_LOCALE_NAME: PCWSTR = windows::core::w!("en-US");
1847
1848#[cfg(test)]
1849mod tests {
1850 use crate::platform::windows::direct_write::ClusterAnalyzer;
1851
1852 #[test]
1853 fn test_cluster_map() {
1854 let cluster_map = [0];
1855 let mut analyzer = ClusterAnalyzer::new(&cluster_map, 1);
1856 let next = analyzer.next();
1857 assert_eq!(next, Some((1, 1)));
1858 let next = analyzer.next();
1859 assert_eq!(next, None);
1860
1861 let cluster_map = [0, 1, 2];
1862 let mut analyzer = ClusterAnalyzer::new(&cluster_map, 3);
1863 let next = analyzer.next();
1864 assert_eq!(next, Some((1, 1)));
1865 let next = analyzer.next();
1866 assert_eq!(next, Some((1, 1)));
1867 let next = analyzer.next();
1868 assert_eq!(next, Some((1, 1)));
1869 let next = analyzer.next();
1870 assert_eq!(next, None);
1871 // ๐จโ๐ฉโ๐งโ๐ฆ๐ฉโ๐ป
1872 let cluster_map = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4];
1873 let mut analyzer = ClusterAnalyzer::new(&cluster_map, 5);
1874 let next = analyzer.next();
1875 assert_eq!(next, Some((11, 4)));
1876 let next = analyzer.next();
1877 assert_eq!(next, Some((5, 1)));
1878 let next = analyzer.next();
1879 assert_eq!(next, None);
1880 // ๐ฉโ๐ป
1881 let cluster_map = [0, 0, 0, 0, 0];
1882 let mut analyzer = ClusterAnalyzer::new(&cluster_map, 1);
1883 let next = analyzer.next();
1884 assert_eq!(next, Some((5, 1)));
1885 let next = analyzer.next();
1886 assert_eq!(next, None);
1887 }
1888}