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