1use std::{borrow::Cow, sync::Arc};
2
3use ::util::ResultExt;
4use anyhow::{anyhow, Result};
5use collections::HashMap;
6use itertools::Itertools;
7use parking_lot::{RwLock, RwLockUpgradableReadGuard};
8use smallvec::SmallVec;
9use windows::{
10 core::*,
11 Win32::{
12 Foundation::*,
13 Globalization::GetUserDefaultLocaleName,
14 Graphics::{
15 Direct2D::{Common::*, *},
16 DirectWrite::*,
17 Dxgi::Common::*,
18 Gdi::LOGFONTW,
19 Imaging::*,
20 },
21 System::SystemServices::LOCALE_NAME_MAX_LENGTH,
22 UI::WindowsAndMessaging::*,
23 },
24};
25
26use crate::*;
27
28#[derive(Debug)]
29struct FontInfo {
30 font_family: String,
31 font_face: IDWriteFontFace3,
32 features: IDWriteTypography,
33 fallbacks: Option<IDWriteFontFallback>,
34 is_system_font: bool,
35 is_emoji: bool,
36}
37
38pub(crate) struct DirectWriteTextSystem(RwLock<DirectWriteState>);
39
40struct DirectWriteComponent {
41 locale: String,
42 factory: IDWriteFactory5,
43 bitmap_factory: AgileReference<IWICImagingFactory>,
44 d2d1_factory: ID2D1Factory,
45 in_memory_loader: IDWriteInMemoryFontFileLoader,
46 builder: IDWriteFontSetBuilder1,
47 text_renderer: Arc<TextRendererWrapper>,
48 render_context: GlyphRenderContext,
49}
50
51struct GlyphRenderContext {
52 params: IDWriteRenderingParams3,
53 dc_target: ID2D1DeviceContext4,
54}
55
56struct DirectWriteState {
57 components: DirectWriteComponent,
58 system_ui_font_name: SharedString,
59 system_font_collection: IDWriteFontCollection1,
60 custom_font_collection: IDWriteFontCollection1,
61 fonts: Vec<FontInfo>,
62 font_selections: HashMap<Font, FontId>,
63 font_id_by_identifier: HashMap<FontIdentifier, FontId>,
64}
65
66#[derive(Debug, Clone, Hash, PartialEq, Eq)]
67struct FontIdentifier {
68 postscript_name: String,
69 weight: i32,
70 style: i32,
71}
72
73impl DirectWriteComponent {
74 pub fn new(bitmap_factory: &IWICImagingFactory) -> Result<Self> {
75 unsafe {
76 let factory: IDWriteFactory5 = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED)?;
77 let bitmap_factory = AgileReference::new(bitmap_factory)?;
78 let d2d1_factory: ID2D1Factory =
79 D2D1CreateFactory(D2D1_FACTORY_TYPE_MULTI_THREADED, None)?;
80 // The `IDWriteInMemoryFontFileLoader` here is supported starting from
81 // Windows 10 Creators Update, which consequently requires the entire
82 // `DirectWriteTextSystem` to run on `win10 1703`+.
83 let in_memory_loader = factory.CreateInMemoryFontFileLoader()?;
84 factory.RegisterFontFileLoader(&in_memory_loader)?;
85 let builder = factory.CreateFontSetBuilder()?;
86 let mut locale_vec = vec![0u16; LOCALE_NAME_MAX_LENGTH as usize];
87 GetUserDefaultLocaleName(&mut locale_vec);
88 let locale = String::from_utf16_lossy(&locale_vec);
89 let text_renderer = Arc::new(TextRendererWrapper::new(&locale));
90 let render_context = GlyphRenderContext::new(&factory, &d2d1_factory)?;
91
92 Ok(DirectWriteComponent {
93 locale,
94 factory,
95 bitmap_factory,
96 d2d1_factory,
97 in_memory_loader,
98 builder,
99 text_renderer,
100 render_context,
101 })
102 }
103 }
104}
105
106impl GlyphRenderContext {
107 pub fn new(factory: &IDWriteFactory5, d2d1_factory: &ID2D1Factory) -> Result<Self> {
108 unsafe {
109 let default_params: IDWriteRenderingParams3 =
110 factory.CreateRenderingParams()?.cast()?;
111 let gamma = default_params.GetGamma();
112 let enhanced_contrast = default_params.GetEnhancedContrast();
113 let gray_contrast = default_params.GetGrayscaleEnhancedContrast();
114 let cleartype_level = default_params.GetClearTypeLevel();
115 let grid_fit_mode = default_params.GetGridFitMode();
116
117 let params = factory.CreateCustomRenderingParams(
118 gamma,
119 enhanced_contrast,
120 gray_contrast,
121 cleartype_level,
122 DWRITE_PIXEL_GEOMETRY_RGB,
123 DWRITE_RENDERING_MODE1_NATURAL_SYMMETRIC,
124 grid_fit_mode,
125 )?;
126 let dc_target = {
127 let target = d2d1_factory.CreateDCRenderTarget(&get_render_target_property(
128 DXGI_FORMAT_B8G8R8A8_UNORM,
129 D2D1_ALPHA_MODE_PREMULTIPLIED,
130 ))?;
131 let target = target.cast::<ID2D1DeviceContext4>()?;
132 target.SetTextRenderingParams(¶ms);
133 target
134 };
135
136 Ok(Self { params, dc_target })
137 }
138 }
139}
140
141impl DirectWriteTextSystem {
142 pub(crate) fn new(bitmap_factory: &IWICImagingFactory) -> Result<Self> {
143 let components = DirectWriteComponent::new(bitmap_factory)?;
144 let system_font_collection = unsafe {
145 let mut result = std::mem::zeroed();
146 components
147 .factory
148 .GetSystemFontCollection(false, &mut result, true)?;
149 result.unwrap()
150 };
151 let custom_font_set = unsafe { components.builder.CreateFontSet()? };
152 let custom_font_collection = unsafe {
153 components
154 .factory
155 .CreateFontCollectionFromFontSet(&custom_font_set)?
156 };
157 let system_ui_font_name = get_system_ui_font_name();
158
159 Ok(Self(RwLock::new(DirectWriteState {
160 components,
161 system_ui_font_name,
162 system_font_collection,
163 custom_font_collection,
164 fonts: Vec::new(),
165 font_selections: HashMap::default(),
166 font_id_by_identifier: HashMap::default(),
167 })))
168 }
169}
170
171impl PlatformTextSystem for DirectWriteTextSystem {
172 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
173 self.0.write().add_fonts(fonts)
174 }
175
176 fn all_font_names(&self) -> Vec<String> {
177 self.0.read().all_font_names()
178 }
179
180 fn font_id(&self, font: &Font) -> Result<FontId> {
181 let lock = self.0.upgradable_read();
182 if let Some(font_id) = lock.font_selections.get(font) {
183 Ok(*font_id)
184 } else {
185 let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
186 let font_id = lock.select_font(font);
187 lock.font_selections.insert(font.clone(), font_id);
188 Ok(font_id)
189 }
190 }
191
192 fn font_metrics(&self, font_id: FontId) -> FontMetrics {
193 self.0.read().font_metrics(font_id)
194 }
195
196 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
197 self.0.read().get_typographic_bounds(font_id, glyph_id)
198 }
199
200 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Size<f32>> {
201 self.0.read().get_advance(font_id, glyph_id)
202 }
203
204 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
205 self.0.read().glyph_for_char(font_id, ch)
206 }
207
208 fn glyph_raster_bounds(
209 &self,
210 params: &RenderGlyphParams,
211 ) -> anyhow::Result<Bounds<DevicePixels>> {
212 self.0.read().raster_bounds(params)
213 }
214
215 fn rasterize_glyph(
216 &self,
217 params: &RenderGlyphParams,
218 raster_bounds: Bounds<DevicePixels>,
219 ) -> anyhow::Result<(Size<DevicePixels>, Vec<u8>)> {
220 self.0.read().rasterize_glyph(params, raster_bounds)
221 }
222
223 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {
224 self.0
225 .write()
226 .layout_line(text, font_size, runs)
227 .log_err()
228 .unwrap_or(LineLayout {
229 font_size,
230 ..Default::default()
231 })
232 }
233}
234
235impl DirectWriteState {
236 fn add_fonts(&mut self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
237 for font_data in fonts {
238 match font_data {
239 Cow::Borrowed(data) => unsafe {
240 let font_file = self
241 .components
242 .in_memory_loader
243 .CreateInMemoryFontFileReference(
244 &self.components.factory,
245 data.as_ptr() as _,
246 data.len() as _,
247 None,
248 )?;
249 self.components.builder.AddFontFile(&font_file)?;
250 },
251 Cow::Owned(data) => unsafe {
252 let font_file = self
253 .components
254 .in_memory_loader
255 .CreateInMemoryFontFileReference(
256 &self.components.factory,
257 data.as_ptr() as _,
258 data.len() as _,
259 None,
260 )?;
261 self.components.builder.AddFontFile(&font_file)?;
262 },
263 }
264 }
265 let set = unsafe { self.components.builder.CreateFontSet()? };
266 let collection = unsafe {
267 self.components
268 .factory
269 .CreateFontCollectionFromFontSet(&set)?
270 };
271 self.custom_font_collection = collection;
272
273 Ok(())
274 }
275
276 fn generate_font_fallbacks(
277 &self,
278 fallbacks: &FontFallbacks,
279 ) -> Result<Option<IDWriteFontFallback>> {
280 if fallbacks.fallback_list().is_empty() {
281 return Ok(None);
282 }
283 unsafe {
284 let builder = self.components.factory.CreateFontFallbackBuilder()?;
285 let font_set = &self.system_font_collection.GetFontSet()?;
286 for family_name in fallbacks.fallback_list() {
287 let Some(fonts) = font_set
288 .GetMatchingFonts(
289 &HSTRING::from(family_name),
290 DWRITE_FONT_WEIGHT_NORMAL,
291 DWRITE_FONT_STRETCH_NORMAL,
292 DWRITE_FONT_STYLE_NORMAL,
293 )
294 .log_err()
295 else {
296 continue;
297 };
298 if fonts.GetFontCount() == 0 {
299 log::error!("No matching font found for {}", family_name);
300 continue;
301 }
302 let font = fonts.GetFontFaceReference(0)?.CreateFontFace()?;
303 let mut count = 0;
304 font.GetUnicodeRanges(None, &mut count).ok();
305 if count == 0 {
306 continue;
307 }
308 let mut unicode_ranges = vec![DWRITE_UNICODE_RANGE::default(); count as usize];
309 let Some(_) = font
310 .GetUnicodeRanges(Some(&mut unicode_ranges), &mut count)
311 .log_err()
312 else {
313 continue;
314 };
315 let target_family_name = HSTRING::from(family_name);
316 builder.AddMapping(
317 &unicode_ranges,
318 &[target_family_name.as_ptr()],
319 None,
320 None,
321 None,
322 1.0,
323 )?;
324 }
325 let system_fallbacks = self.components.factory.GetSystemFontFallback()?;
326 builder.AddMappings(&system_fallbacks)?;
327 Ok(Some(builder.CreateFontFallback()?))
328 }
329 }
330
331 unsafe fn generate_font_features(
332 &self,
333 font_features: &FontFeatures,
334 ) -> Result<IDWriteTypography> {
335 let direct_write_features = self.components.factory.CreateTypography()?;
336 apply_font_features(&direct_write_features, font_features)?;
337 Ok(direct_write_features)
338 }
339
340 unsafe fn get_font_id_from_font_collection(
341 &mut self,
342 family_name: &str,
343 font_weight: FontWeight,
344 font_style: FontStyle,
345 font_features: &FontFeatures,
346 font_fallbacks: Option<&FontFallbacks>,
347 is_system_font: bool,
348 ) -> Option<FontId> {
349 let collection = if is_system_font {
350 &self.system_font_collection
351 } else {
352 &self.custom_font_collection
353 };
354 let fontset = collection.GetFontSet().log_err()?;
355 let font = fontset
356 .GetMatchingFonts(
357 &HSTRING::from(family_name),
358 font_weight.into(),
359 DWRITE_FONT_STRETCH_NORMAL,
360 font_style.into(),
361 )
362 .log_err()?;
363 let total_number = font.GetFontCount();
364 for index in 0..total_number {
365 let Some(font_face_ref) = font.GetFontFaceReference(index).log_err() else {
366 continue;
367 };
368 let Some(font_face) = font_face_ref.CreateFontFace().log_err() else {
369 continue;
370 };
371 let Some(identifier) = get_font_identifier(&font_face, &self.components.locale) else {
372 continue;
373 };
374 let is_emoji = font_face.IsColorFont().as_bool();
375 let Some(direct_write_features) = self.generate_font_features(font_features).log_err()
376 else {
377 continue;
378 };
379 let fallbacks = font_fallbacks
380 .and_then(|fallbacks| self.generate_font_fallbacks(fallbacks).log_err().flatten());
381 let font_info = FontInfo {
382 font_family: family_name.to_owned(),
383 font_face,
384 features: direct_write_features,
385 fallbacks,
386 is_system_font,
387 is_emoji,
388 };
389 let font_id = FontId(self.fonts.len());
390 self.fonts.push(font_info);
391 self.font_id_by_identifier.insert(identifier, font_id);
392 return Some(font_id);
393 }
394 None
395 }
396
397 unsafe fn update_system_font_collection(&mut self) {
398 let mut collection = std::mem::zeroed();
399 if self
400 .components
401 .factory
402 .GetSystemFontCollection(false, &mut collection, true)
403 .log_err()
404 .is_some()
405 {
406 self.system_font_collection = collection.unwrap();
407 }
408 }
409
410 fn select_font(&mut self, target_font: &Font) -> FontId {
411 unsafe {
412 if target_font.family == ".SystemUIFont" {
413 let family = self.system_ui_font_name.clone();
414 self.find_font_id(
415 family.as_ref(),
416 target_font.weight,
417 target_font.style,
418 &target_font.features,
419 target_font.fallbacks.as_ref(),
420 )
421 .unwrap()
422 } else {
423 self.find_font_id(
424 target_font.family.as_ref(),
425 target_font.weight,
426 target_font.style,
427 &target_font.features,
428 target_font.fallbacks.as_ref(),
429 )
430 .unwrap_or_else(|| {
431 let family = self.system_ui_font_name.clone();
432 log::error!("{} not found, use {} instead.", target_font.family, family);
433 self.get_font_id_from_font_collection(
434 family.as_ref(),
435 target_font.weight,
436 target_font.style,
437 &target_font.features,
438 target_font.fallbacks.as_ref(),
439 true,
440 )
441 .unwrap()
442 })
443 }
444 }
445 }
446
447 unsafe fn find_font_id(
448 &mut self,
449 family_name: &str,
450 weight: FontWeight,
451 style: FontStyle,
452 features: &FontFeatures,
453 fallbacks: Option<&FontFallbacks>,
454 ) -> Option<FontId> {
455 // try to find target font in custom font collection first
456 self.get_font_id_from_font_collection(
457 family_name,
458 weight,
459 style,
460 features,
461 fallbacks,
462 false,
463 )
464 .or_else(|| {
465 self.get_font_id_from_font_collection(
466 family_name,
467 weight,
468 style,
469 features,
470 fallbacks,
471 true,
472 )
473 })
474 .or_else(|| {
475 self.update_system_font_collection();
476 self.get_font_id_from_font_collection(
477 family_name,
478 weight,
479 style,
480 features,
481 fallbacks,
482 true,
483 )
484 })
485 }
486
487 fn layout_line(
488 &mut self,
489 text: &str,
490 font_size: Pixels,
491 font_runs: &[FontRun],
492 ) -> Result<LineLayout> {
493 if font_runs.is_empty() {
494 return Ok(LineLayout {
495 font_size,
496 ..Default::default()
497 });
498 }
499 unsafe {
500 let text_renderer = self.components.text_renderer.clone();
501 let text_wide = text.encode_utf16().collect_vec();
502
503 let mut utf8_offset = 0usize;
504 let mut utf16_offset = 0u32;
505 let text_layout = {
506 let first_run = &font_runs[0];
507 let font_info = &self.fonts[first_run.font_id.0];
508 let collection = if font_info.is_system_font {
509 &self.system_font_collection
510 } else {
511 &self.custom_font_collection
512 };
513 let format: IDWriteTextFormat1 = self
514 .components
515 .factory
516 .CreateTextFormat(
517 &HSTRING::from(&font_info.font_family),
518 collection,
519 font_info.font_face.GetWeight(),
520 font_info.font_face.GetStyle(),
521 DWRITE_FONT_STRETCH_NORMAL,
522 font_size.0,
523 &HSTRING::from(&self.components.locale),
524 )?
525 .cast()?;
526 if let Some(ref fallbacks) = font_info.fallbacks {
527 format.SetFontFallback(fallbacks)?;
528 }
529
530 let layout = self.components.factory.CreateTextLayout(
531 &text_wide,
532 &format,
533 f32::INFINITY,
534 f32::INFINITY,
535 )?;
536 let current_text = &text[utf8_offset..(utf8_offset + first_run.len)];
537 utf8_offset += first_run.len;
538 let current_text_utf16_length = current_text.encode_utf16().count() as u32;
539 let text_range = DWRITE_TEXT_RANGE {
540 startPosition: utf16_offset,
541 length: current_text_utf16_length,
542 };
543 layout.SetTypography(&font_info.features, text_range)?;
544 utf16_offset += current_text_utf16_length;
545
546 layout
547 };
548
549 let mut first_run = true;
550 let mut ascent = Pixels::default();
551 let mut descent = Pixels::default();
552 for run in font_runs {
553 if first_run {
554 first_run = false;
555 let mut metrics = vec![DWRITE_LINE_METRICS::default(); 4];
556 let mut line_count = 0u32;
557 text_layout.GetLineMetrics(Some(&mut metrics), &mut line_count as _)?;
558 ascent = px(metrics[0].baseline);
559 descent = px(metrics[0].height - metrics[0].baseline);
560 continue;
561 }
562 let font_info = &self.fonts[run.font_id.0];
563 let current_text = &text[utf8_offset..(utf8_offset + run.len)];
564 utf8_offset += run.len;
565 let current_text_utf16_length = current_text.encode_utf16().count() as u32;
566
567 let collection = if font_info.is_system_font {
568 &self.system_font_collection
569 } else {
570 &self.custom_font_collection
571 };
572 let text_range = DWRITE_TEXT_RANGE {
573 startPosition: utf16_offset,
574 length: current_text_utf16_length,
575 };
576 utf16_offset += current_text_utf16_length;
577 text_layout.SetFontCollection(collection, text_range)?;
578 text_layout
579 .SetFontFamilyName(&HSTRING::from(&font_info.font_family), text_range)?;
580 text_layout.SetFontSize(font_size.0, text_range)?;
581 text_layout.SetFontStyle(font_info.font_face.GetStyle(), text_range)?;
582 text_layout.SetFontWeight(font_info.font_face.GetWeight(), text_range)?;
583 text_layout.SetTypography(&font_info.features, text_range)?;
584 }
585
586 let mut runs = Vec::new();
587 let renderer_context = RendererContext {
588 text_system: self,
589 index_converter: StringIndexConverter::new(text),
590 runs: &mut runs,
591 utf16_index: 0,
592 width: 0.0,
593 };
594 text_layout.Draw(
595 Some(&renderer_context as *const _ as _),
596 &text_renderer.0,
597 0.0,
598 0.0,
599 )?;
600 let width = px(renderer_context.width);
601
602 Ok(LineLayout {
603 font_size,
604 width,
605 ascent,
606 descent,
607 runs,
608 len: text.len(),
609 })
610 }
611 }
612
613 fn font_metrics(&self, font_id: FontId) -> FontMetrics {
614 unsafe {
615 let font_info = &self.fonts[font_id.0];
616 let mut metrics = std::mem::zeroed();
617 font_info.font_face.GetMetrics(&mut metrics);
618
619 FontMetrics {
620 units_per_em: metrics.Base.designUnitsPerEm as _,
621 ascent: metrics.Base.ascent as _,
622 descent: -(metrics.Base.descent as f32),
623 line_gap: metrics.Base.lineGap as _,
624 underline_position: metrics.Base.underlinePosition as _,
625 underline_thickness: metrics.Base.underlineThickness as _,
626 cap_height: metrics.Base.capHeight as _,
627 x_height: metrics.Base.xHeight as _,
628 bounding_box: Bounds {
629 origin: Point {
630 x: metrics.glyphBoxLeft as _,
631 y: metrics.glyphBoxBottom as _,
632 },
633 size: Size {
634 width: (metrics.glyphBoxRight - metrics.glyphBoxLeft) as _,
635 height: (metrics.glyphBoxTop - metrics.glyphBoxBottom) as _,
636 },
637 },
638 }
639 }
640 }
641
642 fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
643 let render_target = &self.components.render_context.dc_target;
644 unsafe {
645 render_target.SetUnitMode(D2D1_UNIT_MODE_DIPS);
646 render_target.SetDpi(96.0 * params.scale_factor, 96.0 * params.scale_factor);
647 }
648 let font = &self.fonts[params.font_id.0];
649 let glyph_id = [params.glyph_id.0 as u16];
650 let advance = [0.0f32];
651 let offset = [DWRITE_GLYPH_OFFSET::default()];
652 let glyph_run = DWRITE_GLYPH_RUN {
653 fontFace: unsafe { std::mem::transmute_copy(&font.font_face) },
654 fontEmSize: params.font_size.0,
655 glyphCount: 1,
656 glyphIndices: glyph_id.as_ptr(),
657 glyphAdvances: advance.as_ptr(),
658 glyphOffsets: offset.as_ptr(),
659 isSideways: BOOL(0),
660 bidiLevel: 0,
661 };
662 let bounds = unsafe {
663 render_target.GetGlyphRunWorldBounds(
664 D2D_POINT_2F { x: 0.0, y: 0.0 },
665 &glyph_run,
666 DWRITE_MEASURING_MODE_NATURAL,
667 )?
668 };
669 // todo(windows)
670 // This is a walkaround, deleted when figured out.
671 let y_offset;
672 let extra_height;
673 if params.is_emoji {
674 y_offset = 0;
675 extra_height = 0;
676 } else {
677 // make some room for scaler.
678 y_offset = -1;
679 extra_height = 2;
680 }
681
682 if bounds.right < bounds.left {
683 Ok(Bounds {
684 origin: point(0.into(), 0.into()),
685 size: size(0.into(), 0.into()),
686 })
687 } else {
688 Ok(Bounds {
689 origin: point(
690 ((bounds.left * params.scale_factor).ceil() as i32).into(),
691 ((bounds.top * params.scale_factor).ceil() as i32 + y_offset).into(),
692 ),
693 size: size(
694 (((bounds.right - bounds.left) * params.scale_factor).ceil() as i32).into(),
695 (((bounds.bottom - bounds.top) * params.scale_factor).ceil() as i32
696 + extra_height)
697 .into(),
698 ),
699 })
700 }
701 }
702
703 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
704 let font_info = &self.fonts[font_id.0];
705 let codepoints = [ch as u32];
706 let mut glyph_indices = vec![0u16; 1];
707 unsafe {
708 font_info
709 .font_face
710 .GetGlyphIndices(codepoints.as_ptr(), 1, glyph_indices.as_mut_ptr())
711 .log_err()
712 }
713 .map(|_| GlyphId(glyph_indices[0] as u32))
714 }
715
716 fn rasterize_glyph(
717 &self,
718 params: &RenderGlyphParams,
719 glyph_bounds: Bounds<DevicePixels>,
720 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
721 if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
722 return Err(anyhow!("glyph bounds are empty"));
723 }
724
725 let font_info = &self.fonts[params.font_id.0];
726 let glyph_id = [params.glyph_id.0 as u16];
727 let advance = [glyph_bounds.size.width.0 as f32];
728 let offset = [DWRITE_GLYPH_OFFSET {
729 advanceOffset: -glyph_bounds.origin.x.0 as f32 / params.scale_factor,
730 ascenderOffset: glyph_bounds.origin.y.0 as f32 / params.scale_factor,
731 }];
732 let glyph_run = DWRITE_GLYPH_RUN {
733 fontFace: unsafe { std::mem::transmute_copy(&font_info.font_face) },
734 fontEmSize: params.font_size.0,
735 glyphCount: 1,
736 glyphIndices: glyph_id.as_ptr(),
737 glyphAdvances: advance.as_ptr(),
738 glyphOffsets: offset.as_ptr(),
739 isSideways: BOOL(0),
740 bidiLevel: 0,
741 };
742
743 // Add an extra pixel when the subpixel variant isn't zero to make room for anti-aliasing.
744 let mut bitmap_size = glyph_bounds.size;
745 if params.subpixel_variant.x > 0 {
746 bitmap_size.width += DevicePixels(1);
747 }
748 if params.subpixel_variant.y > 0 {
749 bitmap_size.height += DevicePixels(1);
750 }
751 let bitmap_size = bitmap_size;
752
753 let total_bytes;
754 let bitmap_format;
755 let render_target_property;
756 let bitmap_width;
757 let bitmap_height;
758 let bitmap_stride;
759 let bitmap_dpi;
760 if params.is_emoji {
761 total_bytes = bitmap_size.height.0 as usize * bitmap_size.width.0 as usize * 4;
762 bitmap_format = &GUID_WICPixelFormat32bppPBGRA;
763 render_target_property = get_render_target_property(
764 DXGI_FORMAT_B8G8R8A8_UNORM,
765 D2D1_ALPHA_MODE_PREMULTIPLIED,
766 );
767 bitmap_width = bitmap_size.width.0 as u32;
768 bitmap_height = bitmap_size.height.0 as u32;
769 bitmap_stride = bitmap_size.width.0 as u32 * 4;
770 bitmap_dpi = 96.0;
771 } else {
772 total_bytes = bitmap_size.height.0 as usize * bitmap_size.width.0 as usize;
773 bitmap_format = &GUID_WICPixelFormat8bppAlpha;
774 render_target_property =
775 get_render_target_property(DXGI_FORMAT_A8_UNORM, D2D1_ALPHA_MODE_STRAIGHT);
776 bitmap_width = bitmap_size.width.0 as u32 * 2;
777 bitmap_height = bitmap_size.height.0 as u32 * 2;
778 bitmap_stride = bitmap_size.width.0 as u32;
779 bitmap_dpi = 192.0;
780 }
781
782 let bitmap_factory = self.components.bitmap_factory.resolve()?;
783 unsafe {
784 let bitmap = bitmap_factory.CreateBitmap(
785 bitmap_width,
786 bitmap_height,
787 bitmap_format,
788 WICBitmapCacheOnLoad,
789 )?;
790 let render_target = self
791 .components
792 .d2d1_factory
793 .CreateWicBitmapRenderTarget(&bitmap, &render_target_property)?;
794 let brush = render_target.CreateSolidColorBrush(&BRUSH_COLOR, None)?;
795 let subpixel_shift = params
796 .subpixel_variant
797 .map(|v| v as f32 / SUBPIXEL_VARIANTS as f32);
798 let baseline_origin = D2D_POINT_2F {
799 x: subpixel_shift.x / params.scale_factor,
800 y: subpixel_shift.y / params.scale_factor,
801 };
802
803 // This `cast()` action here should never fail since we are running on Win10+, and
804 // ID2D1DeviceContext4 requires Win8+
805 let render_target = render_target.cast::<ID2D1DeviceContext4>().unwrap();
806 render_target.SetUnitMode(D2D1_UNIT_MODE_DIPS);
807 render_target.SetDpi(
808 bitmap_dpi * params.scale_factor,
809 bitmap_dpi * params.scale_factor,
810 );
811 render_target.SetTextRenderingParams(&self.components.render_context.params);
812 render_target.BeginDraw();
813
814 if params.is_emoji {
815 // WARN: only DWRITE_GLYPH_IMAGE_FORMATS_COLR has been tested
816 let enumerator = self.components.factory.TranslateColorGlyphRun(
817 baseline_origin,
818 &glyph_run as _,
819 None,
820 DWRITE_GLYPH_IMAGE_FORMATS_COLR
821 | DWRITE_GLYPH_IMAGE_FORMATS_SVG
822 | DWRITE_GLYPH_IMAGE_FORMATS_PNG
823 | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
824 | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8,
825 DWRITE_MEASURING_MODE_NATURAL,
826 None,
827 0,
828 )?;
829 while enumerator.MoveNext().is_ok() {
830 let Ok(color_glyph) = enumerator.GetCurrentRun() else {
831 break;
832 };
833 let color_glyph = &*color_glyph;
834 let brush_color = translate_color(&color_glyph.Base.runColor);
835 brush.SetColor(&brush_color);
836 match color_glyph.glyphImageFormat {
837 DWRITE_GLYPH_IMAGE_FORMATS_PNG
838 | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
839 | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8 => render_target
840 .DrawColorBitmapGlyphRun(
841 color_glyph.glyphImageFormat,
842 baseline_origin,
843 &color_glyph.Base.glyphRun,
844 color_glyph.measuringMode,
845 D2D1_COLOR_BITMAP_GLYPH_SNAP_OPTION_DEFAULT,
846 ),
847 DWRITE_GLYPH_IMAGE_FORMATS_SVG => render_target.DrawSvgGlyphRun(
848 baseline_origin,
849 &color_glyph.Base.glyphRun,
850 &brush,
851 None,
852 color_glyph.Base.paletteIndex as u32,
853 color_glyph.measuringMode,
854 ),
855 _ => render_target.DrawGlyphRun(
856 baseline_origin,
857 &color_glyph.Base.glyphRun,
858 Some(color_glyph.Base.glyphRunDescription as *const _),
859 &brush,
860 color_glyph.measuringMode,
861 ),
862 }
863 }
864 } else {
865 render_target.DrawGlyphRun(
866 baseline_origin,
867 &glyph_run,
868 None,
869 &brush,
870 DWRITE_MEASURING_MODE_NATURAL,
871 );
872 }
873 render_target.EndDraw(None, None)?;
874
875 let mut raw_data = vec![0u8; total_bytes];
876 if params.is_emoji {
877 bitmap.CopyPixels(std::ptr::null() as _, bitmap_stride, &mut raw_data)?;
878 // Convert from BGRA with premultiplied alpha to BGRA with straight alpha.
879 for pixel in raw_data.chunks_exact_mut(4) {
880 let a = pixel[3] as f32 / 255.;
881 pixel[0] = (pixel[0] as f32 / a) as u8;
882 pixel[1] = (pixel[1] as f32 / a) as u8;
883 pixel[2] = (pixel[2] as f32 / a) as u8;
884 }
885 } else {
886 let scaler = bitmap_factory.CreateBitmapScaler()?;
887 scaler.Initialize(
888 &bitmap,
889 bitmap_size.width.0 as u32,
890 bitmap_size.height.0 as u32,
891 WICBitmapInterpolationModeHighQualityCubic,
892 )?;
893 scaler.CopyPixels(std::ptr::null() as _, bitmap_stride, &mut raw_data)?;
894 }
895 Ok((bitmap_size, raw_data))
896 }
897 }
898
899 fn get_typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
900 unsafe {
901 let font = &self.fonts[font_id.0].font_face;
902 let glyph_indices = [glyph_id.0 as u16];
903 let mut metrics = [DWRITE_GLYPH_METRICS::default()];
904 font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
905
906 let metrics = &metrics[0];
907 let advance_width = metrics.advanceWidth as i32;
908 let advance_height = metrics.advanceHeight as i32;
909 let left_side_bearing = metrics.leftSideBearing;
910 let right_side_bearing = metrics.rightSideBearing;
911 let top_side_bearing = metrics.topSideBearing;
912 let bottom_side_bearing = metrics.bottomSideBearing;
913 let vertical_origin_y = metrics.verticalOriginY;
914
915 let y_offset = vertical_origin_y + bottom_side_bearing - advance_height;
916 let width = advance_width - (left_side_bearing + right_side_bearing);
917 let height = advance_height - (top_side_bearing + bottom_side_bearing);
918
919 Ok(Bounds {
920 origin: Point {
921 x: left_side_bearing as f32,
922 y: y_offset as f32,
923 },
924 size: Size {
925 width: width as f32,
926 height: height as f32,
927 },
928 })
929 }
930 }
931
932 fn get_advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
933 unsafe {
934 let font = &self.fonts[font_id.0].font_face;
935 let glyph_indices = [glyph_id.0 as u16];
936 let mut metrics = [DWRITE_GLYPH_METRICS::default()];
937 font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
938
939 let metrics = &metrics[0];
940
941 Ok(Size {
942 width: metrics.advanceWidth as f32,
943 height: 0.0,
944 })
945 }
946 }
947
948 fn all_font_names(&self) -> Vec<String> {
949 let mut result =
950 get_font_names_from_collection(&self.system_font_collection, &self.components.locale);
951 result.extend(get_font_names_from_collection(
952 &self.custom_font_collection,
953 &self.components.locale,
954 ));
955 result
956 }
957}
958
959impl Drop for DirectWriteState {
960 fn drop(&mut self) {
961 unsafe {
962 let _ = self
963 .components
964 .factory
965 .UnregisterFontFileLoader(&self.components.in_memory_loader);
966 }
967 }
968}
969
970struct TextRendererWrapper(pub IDWriteTextRenderer);
971
972impl TextRendererWrapper {
973 pub fn new(locale_str: &str) -> Self {
974 let inner = TextRenderer::new(locale_str);
975 TextRendererWrapper(inner.into())
976 }
977}
978
979#[implement(IDWriteTextRenderer)]
980struct TextRenderer {
981 locale: String,
982}
983
984impl TextRenderer {
985 pub fn new(locale_str: &str) -> Self {
986 TextRenderer {
987 locale: locale_str.to_owned(),
988 }
989 }
990}
991
992struct RendererContext<'t, 'a, 'b> {
993 text_system: &'t mut DirectWriteState,
994 index_converter: StringIndexConverter<'a>,
995 runs: &'b mut Vec<ShapedRun>,
996 utf16_index: usize,
997 width: f32,
998}
999
1000#[allow(non_snake_case)]
1001impl IDWritePixelSnapping_Impl for TextRenderer_Impl {
1002 fn IsPixelSnappingDisabled(
1003 &self,
1004 _clientdrawingcontext: *const ::core::ffi::c_void,
1005 ) -> windows::core::Result<BOOL> {
1006 Ok(BOOL(0))
1007 }
1008
1009 fn GetCurrentTransform(
1010 &self,
1011 _clientdrawingcontext: *const ::core::ffi::c_void,
1012 transform: *mut DWRITE_MATRIX,
1013 ) -> windows::core::Result<()> {
1014 unsafe {
1015 *transform = DWRITE_MATRIX {
1016 m11: 1.0,
1017 m12: 0.0,
1018 m21: 0.0,
1019 m22: 1.0,
1020 dx: 0.0,
1021 dy: 0.0,
1022 };
1023 }
1024 Ok(())
1025 }
1026
1027 fn GetPixelsPerDip(
1028 &self,
1029 _clientdrawingcontext: *const ::core::ffi::c_void,
1030 ) -> windows::core::Result<f32> {
1031 Ok(1.0)
1032 }
1033}
1034
1035#[allow(non_snake_case)]
1036impl IDWriteTextRenderer_Impl for TextRenderer_Impl {
1037 fn DrawGlyphRun(
1038 &self,
1039 clientdrawingcontext: *const ::core::ffi::c_void,
1040 _baselineoriginx: f32,
1041 _baselineoriginy: f32,
1042 _measuringmode: DWRITE_MEASURING_MODE,
1043 glyphrun: *const DWRITE_GLYPH_RUN,
1044 glyphrundescription: *const DWRITE_GLYPH_RUN_DESCRIPTION,
1045 _clientdrawingeffect: Option<&windows::core::IUnknown>,
1046 ) -> windows::core::Result<()> {
1047 unsafe {
1048 let glyphrun = &*glyphrun;
1049 let glyph_count = glyphrun.glyphCount as usize;
1050 if glyph_count == 0 {
1051 return Ok(());
1052 }
1053 let desc = &*glyphrundescription;
1054 let utf16_length_per_glyph = desc.stringLength as usize / glyph_count;
1055 let context =
1056 &mut *(clientdrawingcontext as *const RendererContext as *mut RendererContext);
1057
1058 if glyphrun.fontFace.is_none() {
1059 return Ok(());
1060 }
1061
1062 let font_face = glyphrun.fontFace.as_ref().unwrap();
1063 // This `cast()` action here should never fail since we are running on Win10+, and
1064 // `IDWriteFontFace3` requires Win10
1065 let font_face = &font_face.cast::<IDWriteFontFace3>().unwrap();
1066 let Some((font_identifier, font_struct, is_emoji)) =
1067 get_font_identifier_and_font_struct(font_face, &self.locale)
1068 else {
1069 return Ok(());
1070 };
1071
1072 let font_id = if let Some(id) = context
1073 .text_system
1074 .font_id_by_identifier
1075 .get(&font_identifier)
1076 {
1077 *id
1078 } else {
1079 context.text_system.select_font(&font_struct)
1080 };
1081 let mut glyphs = SmallVec::new();
1082 for index in 0..glyph_count {
1083 let id = GlyphId(*glyphrun.glyphIndices.add(index) as u32);
1084 context
1085 .index_converter
1086 .advance_to_utf16_ix(context.utf16_index);
1087 glyphs.push(ShapedGlyph {
1088 id,
1089 position: point(px(context.width), px(0.0)),
1090 index: context.index_converter.utf8_ix,
1091 is_emoji,
1092 });
1093 context.utf16_index += utf16_length_per_glyph;
1094 context.width += *glyphrun.glyphAdvances.add(index);
1095 }
1096 context.runs.push(ShapedRun { font_id, glyphs });
1097 }
1098 Ok(())
1099 }
1100
1101 fn DrawUnderline(
1102 &self,
1103 _clientdrawingcontext: *const ::core::ffi::c_void,
1104 _baselineoriginx: f32,
1105 _baselineoriginy: f32,
1106 _underline: *const DWRITE_UNDERLINE,
1107 _clientdrawingeffect: Option<&windows::core::IUnknown>,
1108 ) -> windows::core::Result<()> {
1109 Err(windows::core::Error::new(
1110 E_NOTIMPL,
1111 "DrawUnderline unimplemented",
1112 ))
1113 }
1114
1115 fn DrawStrikethrough(
1116 &self,
1117 _clientdrawingcontext: *const ::core::ffi::c_void,
1118 _baselineoriginx: f32,
1119 _baselineoriginy: f32,
1120 _strikethrough: *const DWRITE_STRIKETHROUGH,
1121 _clientdrawingeffect: Option<&windows::core::IUnknown>,
1122 ) -> windows::core::Result<()> {
1123 Err(windows::core::Error::new(
1124 E_NOTIMPL,
1125 "DrawStrikethrough unimplemented",
1126 ))
1127 }
1128
1129 fn DrawInlineObject(
1130 &self,
1131 _clientdrawingcontext: *const ::core::ffi::c_void,
1132 _originx: f32,
1133 _originy: f32,
1134 _inlineobject: Option<&IDWriteInlineObject>,
1135 _issideways: BOOL,
1136 _isrighttoleft: BOOL,
1137 _clientdrawingeffect: Option<&windows::core::IUnknown>,
1138 ) -> windows::core::Result<()> {
1139 Err(windows::core::Error::new(
1140 E_NOTIMPL,
1141 "DrawInlineObject unimplemented",
1142 ))
1143 }
1144}
1145
1146struct StringIndexConverter<'a> {
1147 text: &'a str,
1148 utf8_ix: usize,
1149 utf16_ix: usize,
1150}
1151
1152impl<'a> StringIndexConverter<'a> {
1153 fn new(text: &'a str) -> Self {
1154 Self {
1155 text,
1156 utf8_ix: 0,
1157 utf16_ix: 0,
1158 }
1159 }
1160
1161 fn advance_to_utf8_ix(&mut self, utf8_target: usize) {
1162 for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1163 if self.utf8_ix + ix >= utf8_target {
1164 self.utf8_ix += ix;
1165 return;
1166 }
1167 self.utf16_ix += c.len_utf16();
1168 }
1169 self.utf8_ix = self.text.len();
1170 }
1171
1172 fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
1173 for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1174 if self.utf16_ix >= utf16_target {
1175 self.utf8_ix += ix;
1176 return;
1177 }
1178 self.utf16_ix += c.len_utf16();
1179 }
1180 self.utf8_ix = self.text.len();
1181 }
1182}
1183
1184impl Into<DWRITE_FONT_STYLE> for FontStyle {
1185 fn into(self) -> DWRITE_FONT_STYLE {
1186 match self {
1187 FontStyle::Normal => DWRITE_FONT_STYLE_NORMAL,
1188 FontStyle::Italic => DWRITE_FONT_STYLE_ITALIC,
1189 FontStyle::Oblique => DWRITE_FONT_STYLE_OBLIQUE,
1190 }
1191 }
1192}
1193
1194impl From<DWRITE_FONT_STYLE> for FontStyle {
1195 fn from(value: DWRITE_FONT_STYLE) -> Self {
1196 match value.0 {
1197 0 => FontStyle::Normal,
1198 1 => FontStyle::Italic,
1199 2 => FontStyle::Oblique,
1200 _ => unreachable!(),
1201 }
1202 }
1203}
1204
1205impl Into<DWRITE_FONT_WEIGHT> for FontWeight {
1206 fn into(self) -> DWRITE_FONT_WEIGHT {
1207 DWRITE_FONT_WEIGHT(self.0 as i32)
1208 }
1209}
1210
1211impl From<DWRITE_FONT_WEIGHT> for FontWeight {
1212 fn from(value: DWRITE_FONT_WEIGHT) -> Self {
1213 FontWeight(value.0 as f32)
1214 }
1215}
1216
1217fn get_font_names_from_collection(
1218 collection: &IDWriteFontCollection1,
1219 locale: &str,
1220) -> Vec<String> {
1221 unsafe {
1222 let mut result = Vec::new();
1223 let family_count = collection.GetFontFamilyCount();
1224 for index in 0..family_count {
1225 let Some(font_family) = collection.GetFontFamily(index).log_err() else {
1226 continue;
1227 };
1228 let Some(localized_family_name) = font_family.GetFamilyNames().log_err() else {
1229 continue;
1230 };
1231 let Some(family_name) = get_name(localized_family_name, locale).log_err() else {
1232 continue;
1233 };
1234 result.push(family_name);
1235 }
1236
1237 result
1238 }
1239}
1240
1241fn get_font_identifier_and_font_struct(
1242 font_face: &IDWriteFontFace3,
1243 locale: &str,
1244) -> Option<(FontIdentifier, Font, bool)> {
1245 let postscript_name = get_postscript_name(font_face, locale).log_err()?;
1246 let localized_family_name = unsafe { font_face.GetFamilyNames().log_err() }?;
1247 let family_name = get_name(localized_family_name, locale).log_err()?;
1248 let weight = unsafe { font_face.GetWeight() };
1249 let style = unsafe { font_face.GetStyle() };
1250 let identifier = FontIdentifier {
1251 postscript_name,
1252 weight: weight.0,
1253 style: style.0,
1254 };
1255 let font_struct = Font {
1256 family: family_name.into(),
1257 features: FontFeatures::default(),
1258 weight: weight.into(),
1259 style: style.into(),
1260 fallbacks: None,
1261 };
1262 let is_emoji = unsafe { font_face.IsColorFont().as_bool() };
1263 Some((identifier, font_struct, is_emoji))
1264}
1265
1266#[inline]
1267fn get_font_identifier(font_face: &IDWriteFontFace3, locale: &str) -> Option<FontIdentifier> {
1268 let weight = unsafe { font_face.GetWeight().0 };
1269 let style = unsafe { font_face.GetStyle().0 };
1270 get_postscript_name(font_face, locale)
1271 .log_err()
1272 .map(|postscript_name| FontIdentifier {
1273 postscript_name,
1274 weight,
1275 style,
1276 })
1277}
1278
1279#[inline]
1280fn get_postscript_name(font_face: &IDWriteFontFace3, locale: &str) -> Result<String> {
1281 let mut info = None;
1282 let mut exists = BOOL(0);
1283 unsafe {
1284 font_face.GetInformationalStrings(
1285 DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_NAME,
1286 &mut info,
1287 &mut exists,
1288 )?
1289 };
1290 if !exists.as_bool() || info.is_none() {
1291 return Err(anyhow!("No postscript name found for font face"));
1292 }
1293
1294 get_name(info.unwrap(), locale)
1295}
1296
1297// https://learn.microsoft.com/en-us/windows/win32/api/dwrite/ne-dwrite-dwrite_font_feature_tag
1298fn apply_font_features(
1299 direct_write_features: &IDWriteTypography,
1300 features: &FontFeatures,
1301) -> Result<()> {
1302 let tag_values = features.tag_value_list();
1303 if tag_values.is_empty() {
1304 return Ok(());
1305 }
1306
1307 // All of these features are enabled by default by DirectWrite.
1308 // If you want to (and can) peek into the source of DirectWrite
1309 let mut feature_liga = make_direct_write_feature("liga", 1);
1310 let mut feature_clig = make_direct_write_feature("clig", 1);
1311 let mut feature_calt = make_direct_write_feature("calt", 1);
1312
1313 for (tag, value) in tag_values {
1314 if tag.as_str() == "liga" && *value == 0 {
1315 feature_liga.parameter = 0;
1316 continue;
1317 }
1318 if tag.as_str() == "clig" && *value == 0 {
1319 feature_clig.parameter = 0;
1320 continue;
1321 }
1322 if tag.as_str() == "calt" && *value == 0 {
1323 feature_calt.parameter = 0;
1324 continue;
1325 }
1326
1327 unsafe {
1328 direct_write_features.AddFontFeature(make_direct_write_feature(&tag, *value))?;
1329 }
1330 }
1331 unsafe {
1332 direct_write_features.AddFontFeature(feature_liga)?;
1333 direct_write_features.AddFontFeature(feature_clig)?;
1334 direct_write_features.AddFontFeature(feature_calt)?;
1335 }
1336
1337 Ok(())
1338}
1339
1340#[inline]
1341fn make_direct_write_feature(feature_name: &str, parameter: u32) -> DWRITE_FONT_FEATURE {
1342 let tag = make_direct_write_tag(feature_name);
1343 DWRITE_FONT_FEATURE {
1344 nameTag: tag,
1345 parameter,
1346 }
1347}
1348
1349#[inline]
1350fn make_open_type_tag(tag_name: &str) -> u32 {
1351 let bytes = tag_name.bytes().collect_vec();
1352 assert_eq!(bytes.len(), 4);
1353 ((bytes[3] as u32) << 24)
1354 | ((bytes[2] as u32) << 16)
1355 | ((bytes[1] as u32) << 8)
1356 | (bytes[0] as u32)
1357}
1358
1359#[inline]
1360fn make_direct_write_tag(tag_name: &str) -> DWRITE_FONT_FEATURE_TAG {
1361 DWRITE_FONT_FEATURE_TAG(make_open_type_tag(tag_name))
1362}
1363
1364#[inline]
1365fn get_name(string: IDWriteLocalizedStrings, locale: &str) -> Result<String> {
1366 let mut locale_name_index = 0u32;
1367 let mut exists = BOOL(0);
1368 unsafe {
1369 string.FindLocaleName(
1370 &HSTRING::from(locale),
1371 &mut locale_name_index,
1372 &mut exists as _,
1373 )?
1374 };
1375 if !exists.as_bool() {
1376 unsafe {
1377 string.FindLocaleName(
1378 DEFAULT_LOCALE_NAME,
1379 &mut locale_name_index as _,
1380 &mut exists as _,
1381 )?
1382 };
1383 if !exists.as_bool() {
1384 return Err(anyhow!("No localised string for {}", locale));
1385 }
1386 }
1387
1388 let name_length = unsafe { string.GetStringLength(locale_name_index) }? as usize;
1389 let mut name_vec = vec![0u16; name_length + 1];
1390 unsafe {
1391 string.GetString(locale_name_index, &mut name_vec)?;
1392 }
1393
1394 Ok(String::from_utf16_lossy(&name_vec[..name_length]))
1395}
1396
1397#[inline]
1398fn translate_color(color: &DWRITE_COLOR_F) -> D2D1_COLOR_F {
1399 D2D1_COLOR_F {
1400 r: color.r,
1401 g: color.g,
1402 b: color.b,
1403 a: color.a,
1404 }
1405}
1406
1407fn get_system_ui_font_name() -> SharedString {
1408 unsafe {
1409 let mut info: LOGFONTW = std::mem::zeroed();
1410 let font_family = if SystemParametersInfoW(
1411 SPI_GETICONTITLELOGFONT,
1412 std::mem::size_of::<LOGFONTW>() as u32,
1413 Some(&mut info as *mut _ as _),
1414 SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
1415 )
1416 .log_err()
1417 .is_none()
1418 {
1419 // https://learn.microsoft.com/en-us/windows/win32/uxguide/vis-fonts
1420 // Segoe UI is the Windows font intended for user interface text strings.
1421 "Segoe UI".into()
1422 } else {
1423 let font_name = String::from_utf16_lossy(&info.lfFaceName);
1424 font_name.trim_matches(char::from(0)).to_owned().into()
1425 };
1426 log::info!("Use {} as UI font.", font_family);
1427 font_family
1428 }
1429}
1430
1431#[inline]
1432fn get_render_target_property(
1433 pixel_format: DXGI_FORMAT,
1434 alpha_mode: D2D1_ALPHA_MODE,
1435) -> D2D1_RENDER_TARGET_PROPERTIES {
1436 D2D1_RENDER_TARGET_PROPERTIES {
1437 r#type: D2D1_RENDER_TARGET_TYPE_DEFAULT,
1438 pixelFormat: D2D1_PIXEL_FORMAT {
1439 format: pixel_format,
1440 alphaMode: alpha_mode,
1441 },
1442 dpiX: 96.0,
1443 dpiY: 96.0,
1444 usage: D2D1_RENDER_TARGET_USAGE_NONE,
1445 minLevel: D2D1_FEATURE_LEVEL_DEFAULT,
1446 }
1447}
1448
1449const DEFAULT_LOCALE_NAME: PCWSTR = windows::core::w!("en-US");
1450const BRUSH_COLOR: D2D1_COLOR_F = D2D1_COLOR_F {
1451 r: 1.0,
1452 g: 1.0,
1453 b: 1.0,
1454 a: 1.0,
1455};