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