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