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