1use waft_embedder::{
6 BlendMode, FontVariation, FontWeight, Matrix4, Paint, Shadow, TextDirection,
7 TextLeadingDistribution,
8};
9use waft_foundation::{
10 App, DiagnosticPropertiesBuilder, DiagnosticsProperty, DoubleProperty, EnumProperty,
11 StringProperty,
12};
13use waft_painting::{
14 AlignmentGeometry, AnyColor, ColorProperty, K_DEFAULT_FONT_SIZE, TextOverflow, TextSpan,
15 TextStyle,
16};
17
18use crate::framework::{BuildContext, IntoWidget, KeyRef, StatelessWidget, WidgetRef};
19use crate::widgets::basic::{
20 Center, Directionality, ExcludeSemantics, Semantics, SizedBox, Transform,
21};
22use crate::widgets::icon_data::IconData;
23use crate::widgets::icon_theme::IconTheme;
24use crate::widgets::icon_theme_data::describe_shadows;
25use crate::widgets::media_query::MediaQuery;
26use crate::widgets::text::RichText;
27
28#[derive(Debug)]
59pub struct Icon {
60 pub key: Option<KeyRef>,
61 pub icon: Option<IconData>,
66 pub size: Option<f64>,
77 pub fill: Option<f64>,
93 pub weight: Option<f64>,
106 pub grade: Option<f64>,
127 pub optical_size: Option<f64>,
144 pub color: Option<AnyColor>,
152 pub shadows: Option<Vec<Shadow>>,
162 pub semantic_label: Option<String>,
171 pub text_direction: Option<TextDirection>,
187 pub apply_text_scaling: Option<bool>,
196 pub blend_mode: Option<BlendMode>,
200 pub font_weight: Option<FontWeight>,
202}
203
204impl Icon {
205 pub fn new(icon: Option<IconData>) -> Icon {
207 Icon {
208 key: None,
209 icon,
210 size: None,
211 fill: None,
212 weight: None,
213 grade: None,
214 optical_size: None,
215 color: None,
216 shadows: None,
217 semantic_label: None,
218 text_direction: None,
219 apply_text_scaling: None,
220 blend_mode: None,
221 font_weight: None,
222 }
223 }
224
225 pub fn key(mut self, key: KeyRef) -> Icon {
227 self.key = Some(key);
228 self
229 }
230
231 pub fn size(mut self, size: f64) -> Icon {
233 self.size = Some(size);
234 self
235 }
236
237 pub fn fill(mut self, fill: f64) -> Icon {
239 debug_assert!((0.0..=1.0).contains(&fill));
240 self.fill = Some(fill);
241 self
242 }
243
244 pub fn weight(mut self, weight: f64) -> Icon {
246 debug_assert!(weight > 0.0);
247 self.weight = Some(weight);
248 self
249 }
250
251 pub fn grade(mut self, grade: f64) -> Icon {
253 self.grade = Some(grade);
254 self
255 }
256
257 pub fn optical_size(mut self, optical_size: f64) -> Icon {
259 debug_assert!(optical_size > 0.0);
260 self.optical_size = Some(optical_size);
261 self
262 }
263
264 pub fn color(mut self, color: impl Into<AnyColor>) -> Icon {
266 self.color = Some(color.into());
267 self
268 }
269
270 pub fn shadows(mut self, shadows: Vec<Shadow>) -> Icon {
272 self.shadows = Some(shadows);
273 self
274 }
275
276 pub fn semantic_label(mut self, semantic_label: impl Into<String>) -> Icon {
278 self.semantic_label = Some(semantic_label.into());
279 self
280 }
281
282 fn semantics(&self) -> Semantics {
284 let semantics = Semantics::new();
285 match &self.semantic_label {
286 Some(semantic_label) => semantics.label(semantic_label.clone()),
287 None => semantics,
288 }
289 }
290
291 pub fn text_direction(mut self, text_direction: TextDirection) -> Icon {
293 self.text_direction = Some(text_direction);
294 self
295 }
296
297 pub fn apply_text_scaling(mut self, apply_text_scaling: bool) -> Icon {
299 self.apply_text_scaling = Some(apply_text_scaling);
300 self
301 }
302
303 pub fn blend_mode(mut self, blend_mode: BlendMode) -> Icon {
305 self.blend_mode = Some(blend_mode);
306 self
307 }
308
309 pub fn font_weight(mut self, font_weight: FontWeight) -> Icon {
311 self.font_weight = Some(font_weight);
312 self
313 }
314
315 fn font_style(&self, icon: &IconData, resolved: ResolvedIcon) -> TextStyle {
318 let axes = [
319 ("FILL", resolved.fill),
320 ("wght", resolved.weight),
321 ("GRAD", resolved.grade),
322 ("opsz", resolved.optical_size),
323 ];
324 let font_variations = axes
325 .into_iter()
326 .filter_map(|(axis, value)| value.map(|value| FontVariation::new(axis, value)))
327 .collect();
328 let mut style = TextStyle::new()
329 .font_variations(font_variations)
330 .inherit(false)
331 .font_size(resolved.size)
332 .height(1.0)
335 .leading_distribution(TextLeadingDistribution::Even);
336 if let Some(color) = resolved.color {
337 style = style.color(color);
338 }
339 if let Some(font_family) = &icon.font_family {
340 style = style.font_family(font_family.clone());
341 }
342 if let Some(font_weight) = self.font_weight {
343 style = style.font_weight(font_weight);
344 }
345 if let Some(font_package) = &icon.font_package {
346 style = style.package(font_package.clone());
347 }
348 if let Some(font_family_fallback) = &icon.font_family_fallback {
349 style = style.font_family_fallback(font_family_fallback.clone());
350 }
351 if let Some(shadows) = resolved.shadows {
352 style = style.shadows(shadows);
353 }
354 if let Some(foreground) = resolved.foreground {
355 style = style.foreground(foreground);
356 }
357 style
358 }
359}
360
361struct ResolvedIcon {
364 size: f64,
365 fill: Option<f64>,
366 weight: Option<f64>,
367 grade: Option<f64>,
368 optical_size: Option<f64>,
369 shadows: Option<Vec<Shadow>>,
370 color: Option<AnyColor>,
371 foreground: Option<Paint>,
372}
373
374impl PartialEq for Icon {
377 fn eq(&self, other: &Icon) -> bool {
378 std::ptr::eq(self, other)
379 }
380}
381
382impl StatelessWidget for Icon {
383 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
384 properties.add(
385 DiagnosticsProperty::<String>::new(
386 "icon",
387 self.icon.as_ref().map(|icon| format!("{icon:?}")),
388 )
389 .if_null("<empty>")
390 .with_show_name(false),
391 );
392 properties.add(DoubleProperty::new("size", self.size).default_value(None));
393 properties.add(DoubleProperty::new("fill", self.fill).default_value(None));
394 properties.add(DoubleProperty::new("weight", self.weight).default_value(None));
395 properties.add(DoubleProperty::new("grade", self.grade).default_value(None));
396 properties.add(DoubleProperty::new("opticalSize", self.optical_size).default_value(None));
397 properties.add(
398 ColorProperty::new("color", self.color.as_ref().map(|color| color.color()))
399 .default_value(None),
400 );
401 properties.add(
402 DiagnosticsProperty::<String>::new(
403 "shadows",
404 self.shadows.as_deref().map(describe_shadows),
405 )
406 .default_value(None),
407 );
408 properties.add(
409 StringProperty::new("semanticLabel", self.semantic_label.clone()).default_value(None),
410 );
411 properties.add(
412 EnumProperty::<TextDirection>::new("textDirection", self.text_direction)
413 .default_value(None),
414 );
415 properties.add(
416 DiagnosticsProperty::<bool>::new("applyTextScaling", self.apply_text_scaling)
417 .default_value(None),
418 );
419 }
420
421 fn key(&self) -> Option<&KeyRef> {
422 self.key.as_ref()
423 }
424
425 fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
426 let text_direction = self
427 .text_direction
428 .unwrap_or_else(|| Directionality::of(app, context));
429
430 let icon_theme = IconTheme::of(app, context);
431
432 let apply_text_scaling = self
433 .apply_text_scaling
434 .or(icon_theme.apply_text_scaling)
435 .unwrap_or(false);
436
437 let tentative_icon_size = self.size.or(icon_theme.size).unwrap_or(K_DEFAULT_FONT_SIZE);
438
439 let icon_size = if apply_text_scaling {
440 MediaQuery::text_scaler_of(app, context).scale(tentative_icon_size)
441 } else {
442 tentative_icon_size
443 };
444
445 let icon_fill = self.fill.or(icon_theme.fill);
446 let icon_weight = self.weight.or(icon_theme.weight);
447 let icon_grade = self.grade.or(icon_theme.grade);
448 let icon_optical_size = self.optical_size.or(icon_theme.optical_size);
449 let icon_shadows = self.shadows.clone().or(icon_theme.shadows.clone());
450
451 let Some(icon) = &self.icon else {
452 return self
453 .semantics()
454 .child(SizedBox::new().width(icon_size).height(icon_size))
455 .into_widget();
456 };
457
458 let icon_opacity = icon_theme.opacity.unwrap_or(1.0);
459 let mut icon_color = Some(self.color.clone().unwrap_or_else(|| {
460 icon_theme
461 .color
462 .clone()
463 .expect("IconTheme::of returns a concrete theme")
464 }));
465 let mut foreground = None;
466 if icon_opacity != 1.0 {
467 let color = icon_color.as_ref().expect("the color is resolved above");
468 #[allow(deprecated)]
471 let faded = color.with_opacity(color.opacity() * icon_opacity);
472 icon_color = Some(faded.into());
473 }
474 if let Some(blend_mode) = self.blend_mode {
475 foreground = Some(Paint {
476 blend_mode,
477 color: icon_color
478 .as_ref()
479 .expect("the color is resolved above")
480 .color()
481 .into(),
482 ..Paint::default()
483 });
484 icon_color = None;
486 }
487
488 let font_style = self.font_style(
489 icon,
490 ResolvedIcon {
491 size: icon_size,
492 fill: icon_fill,
493 weight: icon_weight,
494 grade: icon_grade,
495 optical_size: icon_optical_size,
496 shadows: icon_shadows,
497 color: icon_color,
498 foreground,
499 },
500 );
501
502 let code_point = char::from_u32(icon.code_point)
503 .expect("an IconData code point is a Unicode scalar value");
504 let mut icon_widget = RichText::new(
505 TextSpan::new()
506 .text(code_point.to_string())
507 .style(font_style)
508 .into_span(),
509 )
510 .overflow(TextOverflow::Visible)
512 .text_direction(text_direction)
514 .into_widget();
515
516 if icon.match_text_direction {
517 match text_direction {
518 TextDirection::Rtl => {
519 icon_widget = Transform::new(Matrix4::scale(-1.0, 1.0))
520 .alignment(AlignmentGeometry::CENTER)
521 .transform_hit_tests(false)
522 .child(icon_widget)
523 .into_widget();
524 }
525 TextDirection::Ltr => {}
526 }
527 }
528
529 self.semantics()
530 .child(
531 ExcludeSemantics::new().child(
532 SizedBox::new()
533 .width(icon_size)
534 .height(icon_size)
535 .child(Center::new().child(icon_widget)),
536 ),
537 )
538 .into_widget()
539 }
540}
541
542#[cfg(test)]
543mod tests {
544 use waft_embedder::Color;
545 use waft_embedder::Size;
546 use waft_foundation::AppCell;
547 use waft_painting::{PaintingBinding, TextScaler};
548 use waft_rendering::{
549 AnyRenderBox, BoxConstraints, RenderBox, RenderConstrainedBox, RenderConstrainedBoxBase,
550 RenderExcludeSemantics, RenderHandle, RenderObject, RenderObjectWithChildMixin,
551 RenderParagraph, RenderPositionedBox, RenderSemanticsAnnotations, RenderTransform,
552 SemanticsAnnotationsMixin,
553 };
554
555 use super::*;
556 use crate::test_harness::Harness;
557 use crate::widgets::icon_theme_data::IconThemeData;
558 use crate::widgets::media_query::{MediaQuery, MediaQueryData};
559
560 fn install_fonts(app: &mut App) {
562 let binding = PaintingBinding::instance(app);
563 if !binding.has_fonts(app) {
564 binding.install_fonts(app, |fonts| {
565 fonts.add_source(valo_system_fonts::SystemFonts::load());
566 });
567 }
568 }
569
570 fn glyph() -> IconData {
571 IconData::new(0xe900)
572 .font_family("TestIcons")
573 .font_package("test_icons")
574 }
575
576 fn typed_child<P, C: RenderObject>(parent: RenderHandle<P>, app: &App) -> RenderHandle<C>
577 where
578 P: RenderObject + RenderObjectWithChildMixin<ChildType = AnyRenderBox>,
579 {
580 parent
581 .child(app)
582 .expect("a child")
583 .as_object()
584 .downcast::<C>(app)
585 .expect("the expected render object")
586 }
587
588 fn semantics_under_root(
590 harness: &Harness,
591 app: &App,
592 ) -> RenderHandle<RenderSemanticsAnnotations> {
593 harness
594 .render_root(app)
595 .child(app)
596 .expect("a child")
597 .as_object()
598 .downcast::<RenderSemanticsAnnotations>(app)
599 .expect("Icon builds a Semantics")
600 }
601
602 fn square_under_root(harness: &Harness, app: &App) -> RenderHandle<RenderConstrainedBox> {
604 let semantics = semantics_under_root(harness, app);
605 let child = semantics.child(app).expect("a child").as_object();
606 match child.downcast::<RenderExcludeSemantics>(app) {
607 Some(exclude) => typed_child(exclude, app),
608 None => child
609 .downcast::<RenderConstrainedBox>(app)
610 .expect("Icon builds a SizedBox"),
611 }
612 }
613
614 fn mount(
616 app: &mut App,
617 text_direction: TextDirection,
618 theme: IconThemeData,
619 icon: Icon,
620 ) -> Harness {
621 install_fonts(app);
622 let harness = Harness::mount(
623 app,
624 Directionality::new(text_direction, IconTheme::new(theme, icon)).into_widget(),
625 );
626 harness.pump(app);
627 harness
628 }
629
630 #[test]
631 fn an_icon_builds_a_centred_glyph_in_a_square_of_its_size() {
632 let cell = AppCell::new();
633 let mut app = cell.borrow_mut();
634 let theme = IconThemeData::fallback().color(Color::from_argb(255, 255, 0, 0));
635 let harness = mount(
636 &mut app,
637 TextDirection::Ltr,
638 theme,
639 Icon::new(Some(glyph())).size(30.0),
640 );
641
642 let square = square_under_root(&harness, &app);
643 assert_eq!(
644 square.additional_constraints(&app),
645 BoxConstraints::tight_for(Some(30.0), Some(30.0))
646 );
647 assert_eq!(square.size(&app), Size::new(30.0, 30.0));
648
649 let center = typed_child::<_, RenderPositionedBox>(square, &app);
650 let paragraph = typed_child::<_, RenderParagraph>(center, &app);
651 assert_eq!(
652 paragraph.text(&app).to_plain_text(true, true),
653 "\u{e900}",
654 "the code point is the glyph's text"
655 );
656 let style = paragraph
657 .text(&app)
658 .style()
659 .cloned()
660 .expect("Icon always styles its span");
661 assert!(!style.inherit);
662 assert_eq!(style.font_size, Some(30.0));
663 assert_eq!(style.height, Some(1.0));
664 assert_eq!(
665 style.font_family.as_deref(),
666 Some("packages/test_icons/TestIcons"),
667 "the icon's font package prefixes its family"
668 );
669 assert_eq!(
670 style.color.as_ref().map(AnyColor::color),
671 Some(Color::from_argb(255, 255, 0, 0)),
672 "the ambient IconTheme's color"
673 );
674 assert_eq!(style.font_variations.as_deref().map(<[_]>::len), Some(4));
675 assert!(style.foreground.is_none());
676 }
677
678 #[test]
679 fn an_icon_defaults_its_size_and_axes_to_the_ambient_theme() {
680 let cell = AppCell::new();
681 let mut app = cell.borrow_mut();
682 let theme = IconThemeData::fallback().size(18.0).weight(700.0);
683 let harness = mount(
684 &mut app,
685 TextDirection::Ltr,
686 theme,
687 Icon::new(Some(glyph())),
688 );
689 let square = square_under_root(&harness, &app);
690 assert_eq!(square.size(&app), Size::new(18.0, 18.0));
691
692 let center = typed_child::<_, RenderPositionedBox>(square, &app);
693 let paragraph = typed_child::<_, RenderParagraph>(center, &app);
694 let style = paragraph
695 .text(&app)
696 .style()
697 .cloned()
698 .expect("Icon always styles its span");
699 assert_eq!(style.font_size, Some(18.0));
700 let weight = style
701 .font_variations
702 .as_ref()
703 .expect("the axes are always written")
704 .iter()
705 .find(|variation| variation.axis == "wght")
706 .expect("the theme's weight");
707 assert_eq!(weight.value, 700.0);
708 }
709
710 #[test]
712 fn an_icon_labels_its_semantics_and_excludes_its_glyph() {
713 let cell = AppCell::new();
714 let mut app = cell.borrow_mut();
715 let harness = mount(
716 &mut app,
717 TextDirection::Ltr,
718 IconThemeData::fallback(),
719 Icon::new(Some(glyph())).semantic_label("a label"),
720 );
721 let semantics = semantics_under_root(&harness, &app);
722 assert_eq!(semantics.properties(&app).label.as_deref(), Some("a label"));
723 let exclude = semantics
724 .child(&app)
725 .expect("a child")
726 .as_object()
727 .downcast::<RenderExcludeSemantics>(&app)
728 .expect("the glyph sits in an ExcludeSemantics");
729 assert!(exclude.excluding(&app));
730 }
731
732 #[test]
734 fn an_icon_without_an_icon_data_still_labels_its_semantics() {
735 let cell = AppCell::new();
736 let mut app = cell.borrow_mut();
737 let harness = mount(
738 &mut app,
739 TextDirection::Ltr,
740 IconThemeData::fallback(),
741 Icon::new(None).semantic_label("a label"),
742 );
743 let semantics = semantics_under_root(&harness, &app);
744 assert_eq!(semantics.properties(&app).label.as_deref(), Some("a label"));
745 assert!(
746 semantics
747 .child(&app)
748 .expect("a child")
749 .as_object()
750 .downcast::<RenderConstrainedBox>(&app)
751 .is_some(),
752 "no ExcludeSemantics without a glyph"
753 );
754 }
755
756 #[test]
757 fn an_icon_without_an_icon_data_is_an_empty_square() {
758 let cell = AppCell::new();
759 let mut app = cell.borrow_mut();
760 let harness = mount(
761 &mut app,
762 TextDirection::Ltr,
763 IconThemeData::fallback(),
764 Icon::new(None).size(42.0),
765 );
766 let square = square_under_root(&harness, &app);
767 assert_eq!(square.size(&app), Size::new(42.0, 42.0));
768 assert!(square.child(&app).is_none(), "no glyph is built");
769 }
770
771 #[test]
772 fn a_direction_matching_icon_is_mirrored_in_rtl() {
773 let cell = AppCell::new();
774 let mut app = cell.borrow_mut();
775 let mirrored = glyph().match_text_direction(true);
776 let cell_ltr = AppCell::new();
777 let mut app_ltr = cell_ltr.borrow_mut();
778 let ltr = mount(
779 &mut app_ltr,
780 TextDirection::Ltr,
781 IconThemeData::fallback(),
782 Icon::new(Some(mirrored.clone())),
783 );
784 let square = square_under_root(<r, &app_ltr);
785 let center = typed_child::<_, RenderPositionedBox>(square, &app_ltr);
786 assert!(
787 center
788 .child(&app_ltr)
789 .expect("a child")
790 .as_object()
791 .downcast::<RenderParagraph>(&app_ltr)
792 .is_some(),
793 "no transform in left-to-right"
794 );
795
796 let rtl = mount(
797 &mut app,
798 TextDirection::Rtl,
799 IconThemeData::fallback(),
800 Icon::new(Some(mirrored)),
801 );
802 let square = square_under_root(&rtl, &app);
803 let center = typed_child::<_, RenderPositionedBox>(square, &app);
804 let transform = typed_child::<_, RenderTransform>(center, &app);
805 assert!(!transform.transform_hit_tests(&app));
806 assert_eq!(transform.alignment(&app), Some(AlignmentGeometry::CENTER));
807 typed_child::<_, RenderParagraph>(transform, &app);
808 }
809
810 #[test]
811 fn apply_text_scaling_scales_the_square_with_the_media_query() {
812 let cell = AppCell::new();
813 let mut app = cell.borrow_mut();
814 install_fonts(&mut app);
815 let media = MediaQueryData::new().text_scaler(TextScaler::linear(2.0));
816 let harness = Harness::mount(
817 &mut app,
818 Directionality::new(
819 TextDirection::Ltr,
820 MediaQuery::new(
821 media,
822 IconTheme::new(
823 IconThemeData::fallback().size(10.0),
824 Icon::new(Some(glyph())).apply_text_scaling(true),
825 ),
826 )
827 .into_widget(),
828 )
829 .into_widget(),
830 );
831 harness.pump(&mut app);
832 let square = square_under_root(&harness, &app);
833 assert_eq!(
834 square.size(&app),
835 Size::new(20.0, 20.0),
836 "the text scaler doubles the icon's size"
837 );
838 }
839
840 #[test]
841 fn a_blend_mode_moves_the_color_into_a_foreground_paint() {
842 let cell = AppCell::new();
843 let mut app = cell.borrow_mut();
844 let theme = IconThemeData::fallback().color(Color::from_argb(255, 0, 0, 255));
845 let harness = mount(
846 &mut app,
847 TextDirection::Ltr,
848 theme,
849 Icon::new(Some(glyph())).blend_mode(BlendMode::Multiply),
850 );
851 let square = square_under_root(&harness, &app);
852 let center = typed_child::<_, RenderPositionedBox>(square, &app);
853 let paragraph = typed_child::<_, RenderParagraph>(center, &app);
854 let style = paragraph
855 .text(&app)
856 .style()
857 .cloned()
858 .expect("Icon always styles its span");
859 assert!(
860 style.color.is_none(),
861 "a color and a foreground are exclusive"
862 );
863 let foreground = style.foreground.expect("the blend mode makes a paint");
864 assert_eq!(foreground.blend_mode, BlendMode::Multiply);
865 assert_eq!(foreground.color, Color::from_argb(255, 0, 0, 255).into());
866 }
867
868 #[test]
869 fn the_theme_s_opacity_fades_the_glyph_color() {
870 let cell = AppCell::new();
871 let mut app = cell.borrow_mut();
872 let theme = IconThemeData::fallback()
873 .color(Color::from_argb(255, 0, 0, 255))
874 .opacity(0.5);
875 let harness = mount(
876 &mut app,
877 TextDirection::Ltr,
878 theme,
879 Icon::new(Some(glyph())),
880 );
881 let square = square_under_root(&harness, &app);
882 let center = typed_child::<_, RenderPositionedBox>(square, &app);
883 let paragraph = typed_child::<_, RenderParagraph>(center, &app);
884 let style = paragraph
885 .text(&app)
886 .style()
887 .cloned()
888 .expect("Icon always styles its span");
889 assert_eq!(
890 style.color.as_ref().map(AnyColor::color),
891 Some(Color::from_argb(128, 0, 0, 255))
892 );
893 }
894}