1use std::any::{Any, TypeId};
4use std::collections::{HashMap, HashSet};
5use std::fmt::{self, Debug};
6use std::ops::Deref;
7use std::rc::Rc;
8
9use waft_embedder::{Locale, TextDirection};
10use waft_foundation::{
11 App, ChangeNotifier, ChangeNotifierData, Completer, CompleterFuture,
12 DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle, IterableProperty, Ref, wait_all,
13};
14use waft_rendering::RendererBinding;
15
16use crate::binding::{WidgetsBinding, WidgetsBindingObserverObject, WidgetsBindingObserverRef};
17use crate::framework::{
18 BuildContext, GlobalKey, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget,
19 WidgetRef,
20};
21use crate::widgets::app::{
22 LocaleListResolutionCallback, LocaleResolutionCallback, basic_locale_list_resolution,
23};
24use crate::widgets::basic::{Directionality, Semantics, SizedBox};
25
26type TypeToResources = HashMap<TypeId, Rc<dyn Any>>;
30
31struct Pending {
34 delegate: LocalizationsDelegateRef,
35 future_value: CompleterFuture<Rc<dyn Any>>,
36}
37
38fn load_all(
53 app: &mut App,
54 locale: &Locale,
55 all_delegates: &[LocalizationsDelegateRef],
56) -> CompleterFuture<Rc<TypeToResources>> {
57 let mut output = TypeToResources::new();
58 let mut pending_list: Option<Vec<Pending>> = None;
59
60 let mut types = HashSet::new();
63 let mut delegates = Vec::new();
64 for delegate in all_delegates {
65 if !types.contains(&delegate.r#type()) && delegate.is_supported(locale) {
66 types.insert(delegate.r#type());
67 delegates.push(delegate);
68 }
69 }
70
71 for delegate in delegates {
72 let input_value = delegate.load(app, locale);
73 if let Some(completed_value) = input_value.peek() {
74 let r#type = delegate.r#type();
76 debug_assert!(!output.contains_key(&r#type));
77 output.insert(r#type, completed_value);
78 } else {
79 pending_list.get_or_insert_default().push(Pending {
80 delegate: delegate.clone(),
81 future_value: input_value,
82 });
83 }
84 }
85
86 let Some(pending_list) = pending_list else {
88 return CompleterFuture::ready(Rc::new(output));
89 };
90
91 let future_values: Vec<_> = pending_list
93 .iter()
94 .map(|pending| pending.future_value.clone())
95 .collect();
96 CompleterFuture::spawn(app, async move {
97 let values = wait_all(future_values).await;
98 debug_assert_eq!(values.len(), pending_list.len());
99 for (pending, value) in pending_list.iter().zip(values) {
100 let r#type = pending.delegate.r#type();
101 debug_assert!(!output.contains_key(&r#type));
102 output.insert(r#type, value);
103 }
104 Rc::new(output)
105 })
106}
107
108pub trait LocalizationsDelegate<T: ?Sized + 'static>: Debug + 'static {
121 fn is_supported(&self, locale: &Locale) -> bool;
126
127 fn load(&self, app: &mut App, locale: &Locale) -> CompleterFuture<Rc<T>>;
138
139 fn should_reload(&self, old: &Self) -> bool;
146}
147
148pub trait AnyLocalizationsDelegate: Debug {
151 fn is_supported(&self, locale: &Locale) -> bool;
153
154 fn load(&self, app: &mut App, locale: &Locale) -> CompleterFuture<Rc<dyn Any>>;
156
157 fn should_reload(&self, old: &dyn AnyLocalizationsDelegate) -> bool;
160
161 fn r#type(&self) -> TypeId;
174
175 fn runtime_type(&self) -> TypeId;
177
178 fn as_any(&self) -> &dyn Any;
180}
181
182#[derive(Clone)]
184pub struct LocalizationsDelegateRef(Rc<dyn AnyLocalizationsDelegate>);
185
186impl LocalizationsDelegateRef {
187 pub fn new<T: ?Sized + 'static>(delegate: impl LocalizationsDelegate<T>) -> Self {
189 LocalizationsDelegateRef(Rc::new(ErasedDelegate {
190 delegate,
191 resources: std::marker::PhantomData::<fn() -> Rc<T>>,
192 }))
193 }
194}
195
196impl Deref for LocalizationsDelegateRef {
197 type Target = dyn AnyLocalizationsDelegate;
198
199 fn deref(&self) -> &Self::Target {
200 &*self.0
201 }
202}
203
204impl Debug for LocalizationsDelegateRef {
205 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206 Debug::fmt(&self.0, f)
207 }
208}
209
210struct ErasedDelegate<T: ?Sized, D> {
211 delegate: D,
212 resources: std::marker::PhantomData<fn() -> Rc<T>>,
213}
214
215impl<T: ?Sized + 'static, D: LocalizationsDelegate<T>> Debug for ErasedDelegate<T, D> {
216 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217 Debug::fmt(&self.delegate, f)
218 }
219}
220
221impl<T: ?Sized + 'static, D: LocalizationsDelegate<T>> AnyLocalizationsDelegate
222 for ErasedDelegate<T, D>
223{
224 fn is_supported(&self, locale: &Locale) -> bool {
225 self.delegate.is_supported(locale)
226 }
227
228 fn load(&self, app: &mut App, locale: &Locale) -> CompleterFuture<Rc<dyn Any>> {
229 let resources = self.delegate.load(app, locale);
230 if let Some(value) = resources.peek() {
233 return CompleterFuture::ready(erase(value));
234 }
235 let completer = Completer::new();
236 let future = completer.future();
237 resources.then(app, move |app, value| completer.complete(app, erase(value)));
238 future
239 }
240
241 fn should_reload(&self, old: &dyn AnyLocalizationsDelegate) -> bool {
242 old.as_any()
243 .downcast_ref::<Self>()
244 .is_some_and(|old| self.delegate.should_reload(&old.delegate))
245 }
246
247 fn r#type(&self) -> TypeId {
248 TypeId::of::<T>()
249 }
250
251 fn runtime_type(&self) -> TypeId {
252 TypeId::of::<D>()
253 }
254
255 fn as_any(&self) -> &dyn Any {
256 self
257 }
258}
259
260fn erase<T: ?Sized + 'static>(resources: Rc<T>) -> Rc<dyn Any> {
262 Rc::new(resources)
263}
264
265pub trait WidgetsLocalizations: 'static {
279 fn text_direction(&self) -> TextDirection;
281
282 fn reorder_item_to_start(&self) -> String;
285
286 fn reorder_item_to_end(&self) -> String;
289
290 fn reorder_item_up(&self) -> String;
293
294 fn reorder_item_down(&self) -> String;
297
298 fn reorder_item_left(&self) -> String;
301
302 fn reorder_item_right(&self) -> String;
305
306 fn search_results_found(&self) -> String {
308 String::from("Search results found")
309 }
310
311 fn no_results_found(&self) -> String {
313 String::from("No results found")
314 }
315
316 fn copy_button_label(&self) -> String;
318
319 fn cut_button_label(&self) -> String;
321
322 fn paste_button_label(&self) -> String;
324
325 fn select_all_button_label(&self) -> String;
327
328 fn look_up_button_label(&self) -> String;
330
331 fn search_web_button_label(&self) -> String;
333
334 fn share_button_label(&self) -> String;
336
337 fn radio_button_unselected_label(&self) -> String;
340}
341
342impl dyn WidgetsLocalizations {
343 pub fn of(app: &mut App, context: BuildContext) -> Rc<dyn WidgetsLocalizations> {
356 Localizations::of::<dyn WidgetsLocalizations>(app, context).expect(
357 "No WidgetsLocalizations found. WidgetsLocalizations.of requires a \
358 Localizations ancestor with a WidgetsLocalizations delegate.",
359 )
360 }
361}
362
363#[derive(Debug)]
364struct WidgetsLocalizationsDelegate;
365
366impl LocalizationsDelegate<dyn WidgetsLocalizations> for WidgetsLocalizationsDelegate {
367 fn is_supported(&self, _locale: &Locale) -> bool {
368 true
369 }
370
371 fn load(
372 &self,
373 _app: &mut App,
374 locale: &Locale,
375 ) -> CompleterFuture<Rc<dyn WidgetsLocalizations>> {
376 DefaultWidgetsLocalizations::load(locale)
377 }
378
379 fn should_reload(&self, _old: &Self) -> bool {
380 false
381 }
382}
383
384#[derive(Debug, Default)]
393pub struct DefaultWidgetsLocalizations;
394
395impl DefaultWidgetsLocalizations {
396 pub const fn new() -> DefaultWidgetsLocalizations {
401 DefaultWidgetsLocalizations
402 }
403
404 pub fn load(_locale: &Locale) -> CompleterFuture<Rc<dyn WidgetsLocalizations>> {
412 CompleterFuture::ready(Rc::new(DefaultWidgetsLocalizations::new()))
413 }
414
415 pub fn delegate() -> LocalizationsDelegateRef {
420 LocalizationsDelegateRef::new(WidgetsLocalizationsDelegate)
421 }
422}
423
424impl WidgetsLocalizations for DefaultWidgetsLocalizations {
425 fn text_direction(&self) -> TextDirection {
426 TextDirection::Ltr
427 }
428
429 fn reorder_item_to_start(&self) -> String {
430 String::from("Move to the start")
431 }
432
433 fn reorder_item_to_end(&self) -> String {
434 String::from("Move to the end")
435 }
436
437 fn reorder_item_up(&self) -> String {
438 String::from("Move up")
439 }
440
441 fn reorder_item_down(&self) -> String {
442 String::from("Move down")
443 }
444
445 fn reorder_item_left(&self) -> String {
446 String::from("Move left")
447 }
448
449 fn reorder_item_right(&self) -> String {
450 String::from("Move right")
451 }
452
453 fn copy_button_label(&self) -> String {
454 String::from("Copy")
455 }
456
457 fn cut_button_label(&self) -> String {
458 String::from("Cut")
459 }
460
461 fn paste_button_label(&self) -> String {
462 String::from("Paste")
463 }
464
465 fn select_all_button_label(&self) -> String {
466 String::from("Select all")
467 }
468
469 fn look_up_button_label(&self) -> String {
470 String::from("Look Up")
471 }
472
473 fn search_web_button_label(&self) -> String {
474 String::from("Search Web")
475 }
476
477 fn share_button_label(&self) -> String {
478 String::from("Share")
479 }
480
481 fn radio_button_unselected_label(&self) -> String {
482 String::from("Not selected")
483 }
484}
485
486struct LocalizationsScope {
492 key: Option<KeyRef>,
493 locale: Locale,
494 localizations_state: Handle<LocalizationsState>,
495 type_to_resources: Rc<TypeToResources>,
496 child: WidgetRef,
497}
498
499impl Debug for LocalizationsScope {
500 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
501 f.debug_struct("LocalizationsScope")
502 .field("locale", &self.locale)
503 .finish_non_exhaustive()
504 }
505}
506
507impl InheritedWidget for LocalizationsScope {
508 fn key(&self) -> Option<&KeyRef> {
509 self.key.as_ref()
510 }
511
512 fn child(&self) -> &WidgetRef {
513 &self.child
514 }
515
516 fn update_should_notify(&self, old: &LocalizationsScope) -> bool {
517 !Rc::ptr_eq(&self.type_to_resources, &old.type_to_resources)
518 }
519}
520
521pub struct Localizations {
561 key: Option<KeyRef>,
562 locale: Locale,
563 delegates: Vec<LocalizationsDelegateRef>,
564 child: Option<WidgetRef>,
565 is_application_level: bool,
566}
567
568impl Localizations {
569 pub fn new(locale: Locale, delegates: Vec<LocalizationsDelegateRef>) -> Localizations {
573 debug_assert!(
574 delegates
575 .iter()
576 .any(|delegate| delegate.r#type() == TypeId::of::<dyn WidgetsLocalizations>()),
577 "the delegates must include a LocalizationsDelegate<dyn WidgetsLocalizations>"
578 );
579 Localizations {
580 key: None,
581 locale,
582 delegates,
583 child: None,
584 is_application_level: false,
585 }
586 }
587
588 pub fn r#override(app: &mut App, context: BuildContext) -> LocalizationsOverride {
608 LocalizationsOverride {
609 key: None,
610 locale: Localizations::locale_of(app, context),
611 delegates: Localizations::delegates_of(app, context),
612 child: None,
613 }
614 }
615
616 pub fn key(mut self, key: KeyRef) -> Localizations {
618 self.key = Some(key);
619 self
620 }
621
622 #[cfg_attr(debug_assertions, track_caller)]
624 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Localizations {
625 self.child = Some(child.into_widget());
626 self
627 }
628
629 pub fn is_application_level(mut self, is_application_level: bool) -> Localizations {
633 self.is_application_level = is_application_level;
634 self
635 }
636
637 pub fn locale_of(app: &mut App, context: BuildContext) -> Locale {
643 let state = Self::state_of(app, context).expect(
644 "Requested the Locale of a context that does not include a Localizations \
645 ancestor.\nTo request the Locale, the context used to retrieve the \
646 Localizations widget must be that of a widget that is a descendant of a \
647 Localizations widget.",
648 );
649 app.get(state).locale.clone().expect(
650 "Localizations.localeOf found a Localizations widget that had a unexpected null locale.",
651 )
652 }
653
654 pub fn maybe_locale_of(app: &mut App, context: BuildContext) -> Option<Locale> {
660 let state = Self::state_of(app, context)?;
661 app.get(state).locale.clone()
662 }
663
664 fn delegates_of(app: &mut App, context: BuildContext) -> Vec<LocalizationsDelegateRef> {
667 let state = Self::state_of(app, context).expect("a Localizations ancestor was not found");
668 state.widget(app).delegates.clone()
669 }
670
671 pub fn of<T: ?Sized + 'static>(app: &mut App, context: BuildContext) -> Option<Rc<T>> {
687 let state = Self::state_of(app, context)?;
688 state.resources_for::<T>(app)
689 }
690
691 fn state_of(app: &mut App, context: BuildContext) -> Option<Handle<LocalizationsState>> {
693 context
694 .depend_on_inherited_widget_of_exact_type::<LocalizationsScope>(app)
695 .map(|scope| scope.localizations_state)
696 }
697}
698
699impl Debug for Localizations {
700 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
701 f.debug_struct("Localizations")
702 .field("locale", &self.locale)
703 .field("delegates", &self.delegates)
704 .finish_non_exhaustive()
705 }
706}
707
708impl StatefulWidget for Localizations {
709 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
710 properties.add(DiagnosticsProperty::new("locale", self.locale.clone()));
711 properties.add(IterableProperty::<String>::new(
712 "delegates",
713 self.delegates
714 .iter()
715 .map(|delegate| format!("{delegate:?}"))
716 .collect::<Vec<String>>(),
717 ));
718 }
719
720 type State = LocalizationsState;
721
722 fn key(&self) -> Option<&KeyRef> {
723 self.key.as_ref()
724 }
725
726 fn create_state(&self) -> LocalizationsState {
727 LocalizationsState {
728 state: StateData::new(),
729 localized_resources_scope_key: GlobalKey::new(),
730 type_to_resources: Rc::new(TypeToResources::new()),
731 locale: None,
732 }
733 }
734}
735
736pub struct LocalizationsOverride {
738 key: Option<KeyRef>,
739 locale: Locale,
740 delegates: Vec<LocalizationsDelegateRef>,
741 child: Option<WidgetRef>,
742}
743
744impl LocalizationsOverride {
745 pub fn key(mut self, key: KeyRef) -> LocalizationsOverride {
747 self.key = Some(key);
748 self
749 }
750
751 pub fn locale(mut self, locale: Locale) -> LocalizationsOverride {
753 self.locale = locale;
754 self
755 }
756
757 pub fn delegates(mut self, delegates: Vec<LocalizationsDelegateRef>) -> LocalizationsOverride {
759 self.delegates.splice(0..0, delegates);
760 self
761 }
762
763 #[cfg_attr(debug_assertions, track_caller)]
765 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> LocalizationsOverride {
766 self.child = Some(child.into_widget());
767 self
768 }
769}
770
771pub struct LocalizationsOverrideKind;
773
774impl IntoWidget<LocalizationsOverrideKind> for LocalizationsOverride {
775 #[cfg_attr(debug_assertions, track_caller)]
776 fn into_widget(self) -> WidgetRef {
777 Localizations {
778 key: self.key,
779 locale: self.locale,
780 delegates: self.delegates,
781 child: self.child,
782 is_application_level: false,
783 }
784 .into_widget()
785 }
786}
787
788pub struct LocalizationsState {
790 state: StateData<Localizations>,
791 localized_resources_scope_key: GlobalKey,
792 type_to_resources: Rc<TypeToResources>,
793 locale: Option<Locale>,
794}
795
796impl LocalizationsState {
797 pub fn locale(self: Handle<Self>, app: &App) -> Option<&Locale> {
799 app.get(self).locale.as_ref()
800 }
801
802 fn set_locale(self: Handle<Self>, app: &mut App, locale: Locale) {
803 if app.get(self).locale.as_ref() == Some(&locale) {
804 return;
805 }
806 app.platform().set_application_locale(&locale);
807 app.get_mut(self).locale = Some(locale);
808 }
809
810 fn any_delegates_should_reload(self: Handle<Self>, app: &App, old: &Localizations) -> bool {
811 let delegates = &self.widget(app).delegates;
812 if delegates.len() != old.delegates.len() {
813 return true;
814 }
815 delegates
816 .iter()
817 .zip(&old.delegates)
818 .any(|(delegate, old_delegate)| {
819 delegate.runtime_type() != old_delegate.runtime_type()
820 || delegate.should_reload(&**old_delegate)
821 })
822 }
823
824 pub fn load(self: Handle<Self>, app: &mut App, locale: Locale) {
826 let delegates = self.widget(app).delegates.clone();
827 if delegates.is_empty() {
828 self.set_locale(app, locale);
829 return;
830 }
831
832 let type_to_resources_future = load_all(app, &locale, &delegates);
833
834 if let Some(type_to_resources) = type_to_resources_future.peek() {
835 app.get_mut(self).type_to_resources = type_to_resources;
837 self.set_locale(app, locale);
838 } else {
839 RendererBinding::instance(app).defer_first_frame(app);
844 type_to_resources_future.then(app, move |app, value| {
845 if self.mounted(app) {
846 self.set_state(app, |state| state.type_to_resources = value);
847 self.set_locale(app, locale);
848 }
849 RendererBinding::instance(app).allow_first_frame(app);
850 });
851 }
852 }
853
854 pub fn resources_for<T: ?Sized + 'static>(self: Handle<Self>, app: &App) -> Option<Rc<T>> {
856 app.get(self)
857 .type_to_resources
858 .get(&TypeId::of::<T>())
859 .and_then(|resources| resources.downcast_ref::<Rc<T>>())
860 .cloned()
861 }
862
863 fn text_direction(self: Handle<Self>, app: &App) -> TextDirection {
864 self.resources_for::<dyn WidgetsLocalizations>(app)
865 .expect("the delegates include one for WidgetsLocalizations")
866 .text_direction()
867 }
868}
869
870impl State for LocalizationsState {
871 type Widget = Localizations;
872 crate::state_accessors!();
873
874 fn init_state(self: Handle<Self>, app: &mut App) {
875 let locale = self.widget(app).locale.clone();
876 self.load(app, locale);
877 }
878
879 fn did_update_widget(self: Handle<Self>, app: &mut App, old: &Localizations) {
880 if self.widget(app).locale != old.locale || self.any_delegates_should_reload(app, old) {
881 let locale = self.widget(app).locale.clone();
882 self.load(app, locale);
883 }
884 }
885
886 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
887 let Some(locale) = app.get(self).locale.clone() else {
888 return SizedBox::shrink().into_widget();
889 };
890 let text_direction = self.text_direction(app);
891 let child = self
892 .widget(app)
893 .child
894 .clone()
895 .expect("a Localizations widget needs a child");
896 let widget = self.widget(app);
897 let is_application_level = widget.is_application_level;
898 let mut semantics = Semantics::new()
899 .container(!is_application_level)
900 .text_direction(text_direction);
901 if !is_application_level {
904 semantics = semantics.locale_for_subtree(widget.locale.clone());
905 }
906 let state = app.get(self);
907 semantics
908 .child(LocalizationsScope {
909 key: Some(state.localized_resources_scope_key.clone().into()),
910 locale,
911 localizations_state: self,
912 type_to_resources: Rc::clone(&state.type_to_resources),
913 child: Directionality::new(text_direction, child).into_widget(),
914 })
915 .into_widget()
916 }
917}
918
919pub struct LocalizationsResolver {
928 change_notifier: ChangeNotifierData,
929 localizations_delegates: Option<Vec<LocalizationsDelegateRef>>,
930 locale_list_resolution_callback: Option<LocaleListResolutionCallback>,
931 locale_resolution_callback: Option<LocaleResolutionCallback>,
932 supported_locales: Vec<Locale>,
933 locale: Option<Locale>,
934 resolved_locale: Option<Locale>,
935 observer: Option<WidgetsBindingObserverRef>,
938}
939
940impl LocalizationsResolver {
941 pub fn new(
944 app: &mut App,
945 locale: Option<Locale>,
946 locale_list_resolution_callback: Option<LocaleListResolutionCallback>,
947 locale_resolution_callback: Option<LocaleResolutionCallback>,
948 localizations_delegates: Option<Vec<LocalizationsDelegateRef>>,
949 supported_locales: Vec<Locale>,
950 ) -> Ref<LocalizationsResolver> {
951 let this = app.create(LocalizationsResolver {
952 change_notifier: ChangeNotifierData::default(),
953 localizations_delegates,
954 locale_list_resolution_callback,
955 locale_resolution_callback,
956 supported_locales,
957 locale,
958 resolved_locale: None,
959 observer: None,
960 });
961 let platform_locales = app.platform().locales();
962 let resolved_locale = this.resolve_locales(app, Some(&platform_locales));
963 app.get_mut(&this).resolved_locale = Some(resolved_locale);
964 let observer: WidgetsBindingObserverRef = Rc::new(this.clone());
965 WidgetsBinding::instance(app).add_observer(app, Rc::clone(&observer));
966 app.get_mut(&this).observer = Some(observer);
967 this
968 }
969
970 pub fn dispose(self: Handle<Self>, app: &mut App) {
972 if let Some(observer) = app.get_mut(self).observer.take() {
973 WidgetsBinding::instance(app).remove_observer(app, &observer);
974 }
975 ChangeNotifierData::dispose(app, self);
976 }
977
978 pub fn update(
981 self: Handle<Self>,
982 app: &mut App,
983 locale: Option<Locale>,
984 locale_list_resolution_callback: Option<LocaleListResolutionCallback>,
985 locale_resolution_callback: Option<LocaleResolutionCallback>,
986 localizations_delegates: Option<Vec<LocalizationsDelegateRef>>,
987 supported_locales: Vec<Locale>,
988 ) {
989 let this = app.get_mut(self);
990 this.locale = locale;
991 this.locale_list_resolution_callback = locale_list_resolution_callback;
992 this.locale_resolution_callback = locale_resolution_callback;
993 this.localizations_delegates = localizations_delegates;
994 if this.supported_locales != supported_locales {
995 this.supported_locales = supported_locales;
996 let platform_locales = app.platform().locales();
997 self.update_resolved_locale(app, Some(&platform_locales));
998 }
999 }
1000
1001 pub fn locale(self: Handle<Self>, app: &mut App) -> Locale {
1003 match app.get(self).locale.clone() {
1004 Some(locale) => {
1005 let supported_locales = app.get(self).supported_locales.clone();
1006 self.resolve_locales_with(app, Some(&[locale]), &supported_locales)
1007 }
1008 None => app
1009 .get(self)
1010 .resolved_locale
1011 .clone()
1012 .expect("resolved at construction"),
1013 }
1014 }
1015
1016 pub fn localizations_delegates(self: Handle<Self>, app: &App) -> Vec<LocalizationsDelegateRef> {
1019 let mut delegates = app
1020 .get(self)
1021 .localizations_delegates
1022 .clone()
1023 .unwrap_or_default();
1024 delegates.push(DefaultWidgetsLocalizations::delegate());
1025 delegates
1026 }
1027
1028 pub fn locale_list_resolution_callback(
1030 self: Handle<Self>,
1031 app: &App,
1032 ) -> Option<LocaleListResolutionCallback> {
1033 app.get(self).locale_list_resolution_callback.clone()
1034 }
1035
1036 pub fn locale_resolution_callback(
1038 self: Handle<Self>,
1039 app: &App,
1040 ) -> Option<LocaleResolutionCallback> {
1041 app.get(self).locale_resolution_callback.clone()
1042 }
1043
1044 pub fn supported_locales(self: Handle<Self>, app: &App) -> &[Locale] {
1046 &app.get(self).supported_locales
1047 }
1048
1049 fn update_resolved_locale(
1050 self: Handle<Self>,
1051 app: &mut App,
1052 preferred_locales: Option<&[Locale]>,
1053 ) {
1054 let new_locale = self.resolve_locales(app, preferred_locales);
1055 if app.get(self).resolved_locale.as_ref() != Some(&new_locale) {
1056 app.get_mut(self).resolved_locale = Some(new_locale);
1057 self.notify_listeners(app);
1058 }
1059 }
1060
1061 fn resolve_locales(
1062 self: Handle<Self>,
1063 app: &mut App,
1064 preferred_locales: Option<&[Locale]>,
1065 ) -> Locale {
1066 let supported_locales = app.get(self).supported_locales.clone();
1067 self.resolve_locales_with(app, preferred_locales, &supported_locales)
1068 }
1069
1070 fn resolve_locales_with(
1071 self: Handle<Self>,
1072 app: &mut App,
1073 preferred_locales: Option<&[Locale]>,
1074 supported_locales: &[Locale],
1075 ) -> Locale {
1076 if let Some(callback) = app.get(self).locale_list_resolution_callback.clone()
1078 && let Some(locale) = callback(preferred_locales, supported_locales)
1079 {
1080 return locale;
1081 }
1082 if let Some(callback) = app.get(self).locale_resolution_callback.clone()
1084 && let Some(locale) = callback(
1085 preferred_locales.and_then(|locales| locales.first()),
1086 supported_locales,
1087 )
1088 {
1089 return locale;
1090 }
1091 basic_locale_list_resolution(preferred_locales, supported_locales)
1093 }
1094}
1095
1096impl Debug for LocalizationsResolver {
1097 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1098 f.write_str("LocalizationsResolver")
1099 }
1100}
1101
1102impl ChangeNotifier for LocalizationsResolver {
1103 fn change_notifier_data(&self) -> &ChangeNotifierData {
1104 &self.change_notifier
1105 }
1106
1107 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1108 &mut self.change_notifier
1109 }
1110}
1111
1112impl WidgetsBindingObserverObject for LocalizationsResolver {
1113 fn did_change_locales(self: Handle<Self>, app: &mut App, locales: Option<&[Locale]>) {
1114 self.update_resolved_locale(app, locales);
1115 }
1116}
1117
1118#[cfg(test)]
1119mod tests {
1120 use std::cell::{Cell, RefCell};
1121 use waft_foundation::AppCell;
1122
1123 use super::*;
1124 use crate::test_harness::Harness;
1125 use crate::widgets::basic::Builder;
1126
1127 fn en_us() -> Locale {
1128 Locale::new("en").country_code("US")
1129 }
1130
1131 trait Greetings: 'static {
1133 fn hello(&self) -> String;
1134 }
1135
1136 struct LocaleGreetings(Locale);
1137
1138 impl Greetings for LocaleGreetings {
1139 fn hello(&self) -> String {
1140 format!("hello in {}", self.0)
1141 }
1142 }
1143
1144 #[derive(Debug)]
1145 struct GreetingsDelegate {
1146 loads: Rc<Cell<u32>>,
1147 reload: bool,
1148 }
1149
1150 impl LocalizationsDelegate<dyn Greetings> for GreetingsDelegate {
1151 fn is_supported(&self, locale: &Locale) -> bool {
1152 locale.language_code != "xx"
1153 }
1154
1155 fn load(&self, _app: &mut App, locale: &Locale) -> CompleterFuture<Rc<dyn Greetings>> {
1156 self.loads.set(self.loads.get() + 1);
1157 CompleterFuture::ready(Rc::new(LocaleGreetings(locale.clone())))
1158 }
1159
1160 fn should_reload(&self, _old: &Self) -> bool {
1161 self.reload
1162 }
1163 }
1164
1165 struct FakeLocalizationsDelegate {
1167 completer: Completer<Rc<dyn Greetings>>,
1168 }
1169
1170 impl Debug for FakeLocalizationsDelegate {
1171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1172 f.write_str("FakeLocalizationsDelegate")
1173 }
1174 }
1175
1176 impl LocalizationsDelegate<dyn Greetings> for FakeLocalizationsDelegate {
1177 fn is_supported(&self, _locale: &Locale) -> bool {
1178 true
1179 }
1180
1181 fn load(&self, _app: &mut App, _locale: &Locale) -> CompleterFuture<Rc<dyn Greetings>> {
1182 self.completer.future()
1183 }
1184
1185 fn should_reload(&self, _old: &Self) -> bool {
1186 false
1187 }
1188 }
1189
1190 #[derive(Clone, Debug, PartialEq)]
1191 struct Seen {
1192 locale: Locale,
1193 copy_label: String,
1194 greeting: Option<String>,
1195 text_direction: TextDirection,
1196 }
1197
1198 fn probe(seen: &Rc<RefCell<Vec<Seen>>>) -> Builder {
1199 let seen = Rc::clone(seen);
1200 Builder::new(move |app, context| {
1201 seen.borrow_mut().push(Seen {
1202 locale: Localizations::locale_of(app, context),
1203 copy_label: <dyn WidgetsLocalizations>::of(app, context).copy_button_label(),
1204 greeting: Localizations::of::<dyn Greetings>(app, context)
1205 .map(|greetings| greetings.hello()),
1206 text_direction: Directionality::of(app, context),
1207 });
1208 SizedBox::shrink().into_widget()
1209 })
1210 }
1211
1212 #[test]
1213 fn localizations_provides_the_locale_the_resources_and_the_directionality() {
1214 let cell = AppCell::new();
1215 let mut app = cell.borrow_mut();
1216 let seen = Rc::new(RefCell::new(Vec::new()));
1217 let harness = Harness::mount(
1218 &mut app,
1219 Localizations::new(en_us(), vec![DefaultWidgetsLocalizations::delegate()])
1220 .child(probe(&seen))
1221 .into_widget(),
1222 );
1223 harness.pump(&mut app);
1224 assert_eq!(
1225 seen.borrow().as_slice(),
1226 [Seen {
1227 locale: en_us(),
1228 copy_label: String::from("Copy"),
1229 greeting: None,
1230 text_direction: TextDirection::Ltr,
1231 }]
1232 );
1233 assert!(
1234 RendererBinding::instance(&mut app).send_frames_to_engine(&app),
1235 "a delegate that loads synchronously defers no frame"
1236 );
1237 }
1238
1239 #[test]
1240 fn locale_is_available_when_localizations_widget_stops_deferring_frames() {
1241 let cell = AppCell::new();
1242 let mut app = cell.borrow_mut();
1243 let delegate = FakeLocalizationsDelegate {
1244 completer: Completer::new(),
1245 };
1246 let completer = delegate.completer.clone();
1247 let seen = Rc::new(RefCell::new(Vec::new()));
1248 let key = GlobalKey::new();
1249 let harness = Harness::mount(
1250 &mut app,
1251 Localizations::new(
1252 Locale::new("fo"),
1253 vec![
1254 DefaultWidgetsLocalizations::delegate(),
1255 LocalizationsDelegateRef::new(delegate),
1256 ],
1257 )
1258 .key(key.clone().into())
1259 .child(probe(&seen))
1260 .into_widget(),
1261 );
1262 harness.pump(&mut app);
1263 let state = key
1264 .current_state::<LocalizationsState>(&app)
1265 .expect("the Localizations widget mounted");
1266 assert_eq!(state.locale(&app), None);
1267 assert!(seen.borrow().is_empty(), "the child is not built yet");
1268 let binding = RendererBinding::instance(&mut app);
1269 assert!(
1270 !binding.send_frames_to_engine(&app),
1271 "the first frame is deferred until the load completes"
1272 );
1273
1274 completer.complete(&mut app, Rc::new(LocaleGreetings(Locale::new("fo"))));
1275 assert_eq!(
1276 state.locale(&app),
1277 None,
1278 "the load completes on the microtask queue"
1279 );
1280 drop(app);
1281 cell.checkpoint();
1282 let mut app = cell.borrow_mut();
1283 assert_eq!(state.locale(&app), Some(&Locale::new("fo")));
1284 assert!(binding.send_frames_to_engine(&app));
1285 harness.pump(&mut app);
1286 assert_eq!(seen.borrow()[0].locale, Locale::new("fo"));
1287 assert_eq!(seen.borrow()[0].greeting.as_deref(), Some("hello in fo"));
1288 }
1289
1290 #[test]
1291 fn a_pending_load_keeps_the_old_locale_until_it_completes() {
1292 let cell = AppCell::new();
1293 let mut app = cell.borrow_mut();
1294 let seen = Rc::new(RefCell::new(Vec::new()));
1295 let probe = probe(&seen).into_widget();
1298 let harness = Harness::mount(
1299 &mut app,
1300 Localizations::new(
1301 en_us(),
1302 vec![
1303 LocalizationsDelegateRef::new(GreetingsDelegate {
1304 loads: Rc::new(Cell::new(0)),
1305 reload: false,
1306 }),
1307 DefaultWidgetsLocalizations::delegate(),
1308 ],
1309 )
1310 .child(Rc::clone(&probe))
1311 .into_widget(),
1312 );
1313 harness.pump(&mut app);
1314 assert_eq!(seen.borrow()[0].greeting.as_deref(), Some("hello in en_US"));
1315
1316 let delegate = FakeLocalizationsDelegate {
1317 completer: Completer::new(),
1318 };
1319 let completer = delegate.completer.clone();
1320 harness.set_child(
1321 &mut app,
1322 Localizations::new(
1323 Locale::new("fr"),
1324 vec![
1325 LocalizationsDelegateRef::new(delegate),
1326 DefaultWidgetsLocalizations::delegate(),
1327 ],
1328 )
1329 .child(Rc::clone(&probe))
1330 .into_widget(),
1331 );
1332 harness.pump(&mut app);
1333 assert_eq!(
1334 seen.borrow().len(),
1335 1,
1336 "the dependents keep the old resources"
1337 );
1338 let binding = RendererBinding::instance(&mut app);
1339 assert!(!binding.send_frames_to_engine(&app));
1340
1341 completer.complete(&mut app, Rc::new(LocaleGreetings(Locale::new("fr"))));
1342 drop(app);
1343 cell.checkpoint();
1344 let mut app = cell.borrow_mut();
1345 harness.pump(&mut app);
1346 assert!(binding.send_frames_to_engine(&app));
1347 assert_eq!(
1348 seen.borrow().len(),
1349 2,
1350 "the new resources rebuild the dependents"
1351 );
1352 assert_eq!(seen.borrow()[1].locale, Locale::new("fr"));
1353 assert_eq!(seen.borrow()[1].greeting.as_deref(), Some("hello in fr"));
1354 }
1355
1356 #[test]
1357 fn a_delegate_loads_once_per_locale_and_again_when_it_asks_to_reload() {
1358 let cell = AppCell::new();
1359 let mut app = cell.borrow_mut();
1360 let seen = Rc::new(RefCell::new(Vec::new()));
1361 let loads = Rc::new(Cell::new(0));
1362 let probe = probe(&seen).into_widget();
1365 let localized = |locale: Locale, reload: bool| {
1366 Localizations::new(
1367 locale,
1368 vec![
1369 LocalizationsDelegateRef::new(GreetingsDelegate {
1370 loads: Rc::clone(&loads),
1371 reload,
1372 }),
1373 DefaultWidgetsLocalizations::delegate(),
1374 ],
1375 )
1376 .child(Rc::clone(&probe))
1377 .into_widget()
1378 };
1379 let harness = Harness::mount(&mut app, localized(en_us(), false));
1380 harness.pump(&mut app);
1381 assert_eq!(loads.get(), 1);
1382 assert_eq!(seen.borrow()[0].greeting.as_deref(), Some("hello in en_US"));
1383
1384 harness.set_child(&mut app, localized(en_us(), false));
1385 harness.pump(&mut app);
1386 assert_eq!(loads.get(), 1, "the same locale and delegates load nothing");
1387 assert_eq!(seen.borrow().len(), 1, "the dependents do not rebuild");
1388
1389 harness.set_child(&mut app, localized(Locale::new("fr"), false));
1390 harness.pump(&mut app);
1391 assert_eq!(loads.get(), 2, "a new locale loads");
1392 assert_eq!(seen.borrow()[1].greeting.as_deref(), Some("hello in fr"));
1393
1394 harness.set_child(&mut app, localized(Locale::new("fr"), true));
1395 harness.pump(&mut app);
1396 assert_eq!(loads.get(), 3, "a delegate that asks to reload loads");
1397 assert_eq!(seen.borrow().len(), 3);
1398 }
1399
1400 #[test]
1401 fn an_unsupported_locale_skips_the_delegate() {
1402 let cell = AppCell::new();
1403 let mut app = cell.borrow_mut();
1404 let seen = Rc::new(RefCell::new(Vec::new()));
1405 let harness = Harness::mount(
1406 &mut app,
1407 Localizations::new(
1408 Locale::new("xx"),
1409 vec![
1410 LocalizationsDelegateRef::new(GreetingsDelegate {
1411 loads: Rc::new(Cell::new(0)),
1412 reload: false,
1413 }),
1414 DefaultWidgetsLocalizations::delegate(),
1415 ],
1416 )
1417 .child(probe(&seen))
1418 .into_widget(),
1419 );
1420 harness.pump(&mut app);
1421 assert_eq!(seen.borrow()[0].greeting, None);
1422 }
1423
1424 #[test]
1425 fn override_keeps_the_inherited_locale_and_puts_its_delegates_first() {
1426 let cell = AppCell::new();
1427 let mut app = cell.borrow_mut();
1428 let seen = Rc::new(RefCell::new(Vec::new()));
1429 let inner = {
1430 let seen = Rc::clone(&seen);
1431 Builder::new(move |app, context| {
1432 Localizations::r#override(app, context)
1433 .delegates(vec![LocalizationsDelegateRef::new(GreetingsDelegate {
1434 loads: Rc::new(Cell::new(0)),
1435 reload: false,
1436 })])
1437 .child(probe(&seen))
1438 .into_widget()
1439 })
1440 };
1441 let harness = Harness::mount(
1442 &mut app,
1443 Localizations::new(en_us(), vec![DefaultWidgetsLocalizations::delegate()])
1444 .child(inner)
1445 .into_widget(),
1446 );
1447 harness.pump(&mut app);
1448 let seen = seen.borrow();
1449 assert_eq!(seen[0].locale, en_us());
1450 assert_eq!(seen[0].greeting.as_deref(), Some("hello in en_US"));
1451 assert_eq!(seen[0].copy_label, "Copy");
1452 }
1453
1454 #[test]
1455 fn the_resolver_follows_the_platform_locales_and_notifies_on_a_change() {
1456 let cell = AppCell::new();
1457 let mut app = cell.borrow_mut();
1458 let resolver = LocalizationsResolver::new(
1459 &mut app,
1460 None,
1461 None,
1462 None,
1463 None,
1464 vec![en_us(), Locale::new("fr").country_code("FR")],
1465 );
1466 assert_eq!(
1467 resolver.locale(&mut app),
1468 en_us(),
1469 "no platform locales: the first supported"
1470 );
1471 let notified = Rc::new(Cell::new(0));
1472 app.get_mut(&resolver)
1473 .change_notifier
1474 .add_listener(waft_foundation::Listener::new({
1475 let notified = Rc::clone(¬ified);
1476 move |_app| notified.set(notified.get() + 1)
1477 }));
1478
1479 let binding = WidgetsBinding::instance(&mut app);
1480 binding.dispatch_locales_changed(&mut app, Some(&[Locale::new("fr").country_code("CA")]));
1481 assert_eq!(
1482 resolver.locale(&mut app),
1483 Locale::new("fr").country_code("FR")
1484 );
1485 assert_eq!(notified.get(), 1);
1486 binding.dispatch_locales_changed(&mut app, Some(&[Locale::new("fr").country_code("CA")]));
1487 assert_eq!(notified.get(), 1, "the same resolution does not notify");
1488
1489 resolver.update(
1490 &mut app,
1491 Some(Locale::new("en").country_code("GB")),
1492 None,
1493 None,
1494 None,
1495 vec![en_us(), Locale::new("fr").country_code("FR")],
1496 );
1497 assert_eq!(
1498 resolver.locale(&mut app),
1499 en_us(),
1500 "an app locale resolves against the supported list"
1501 );
1502 assert_eq!(resolver.localizations_delegates(&app).len(), 1);
1503
1504 resolver.dispose(&mut app);
1505 let freed = resolver.handle();
1506 drop(resolver);
1507 drop(app);
1508 cell.checkpoint();
1509 assert!(
1510 !cell.borrow().contains(freed),
1511 "the binding let go of it at dispose"
1512 );
1513 }
1514
1515 #[test]
1516 fn the_resolver_prefers_its_callbacks_over_the_basic_algorithm() {
1517 let cell = AppCell::new();
1518 let mut app = cell.borrow_mut();
1519 let list_callback: LocaleListResolutionCallback =
1520 Rc::new(|_locales, _supported| Some(Locale::new("de")));
1521 let resolver = LocalizationsResolver::new(
1522 &mut app,
1523 None,
1524 Some(list_callback),
1525 Some(Rc::new(|_locale, _supported| Some(Locale::new("it")))),
1526 None,
1527 vec![en_us()],
1528 );
1529 assert_eq!(resolver.locale(&mut app), Locale::new("de"));
1530 resolver.update(
1531 &mut app,
1532 None,
1533 Some(Rc::new(|_locales, _supported| None)),
1534 Some(Rc::new(|_locale, _supported| Some(Locale::new("it")))),
1535 None,
1536 vec![en_us()],
1537 );
1538 assert_eq!(
1539 resolver.locale(&mut app),
1540 Locale::new("de"),
1541 "update re-resolves only when the supported locales change"
1542 );
1543 resolver.update(
1544 &mut app,
1545 None,
1546 Some(Rc::new(|_locales, _supported| None)),
1547 Some(Rc::new(|_locale, _supported| Some(Locale::new("it")))),
1548 None,
1549 vec![en_us(), Locale::new("fr")],
1550 );
1551 assert_eq!(
1552 resolver.locale(&mut app),
1553 Locale::new("it"),
1554 "the list callback declines"
1555 );
1556 resolver.dispose(&mut app);
1557 }
1558
1559 #[test]
1560 fn maybe_locale_of_is_none_without_an_ancestor() {
1561 let cell = AppCell::new();
1562 let mut app = cell.borrow_mut();
1563 let seen = Rc::new(Cell::new(Some(en_us())));
1564 let harness = Harness::mount(
1565 &mut app,
1566 Builder::new({
1567 let seen = Rc::clone(&seen);
1568 move |app, context| {
1569 seen.set(Localizations::maybe_locale_of(app, context));
1570 SizedBox::shrink().into_widget()
1571 }
1572 })
1573 .into_widget(),
1574 );
1575 harness.pump(&mut app);
1576 assert_eq!(seen.take(), None);
1577 }
1578}