Skip to main content

waft_widgets/widgets/
localizations.rs

1//! Flutter `widgets/localizations.dart`.
2
3use 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
26/// The resources every delegate loaded, keyed by the delegate's [`type`](AnyLocalizationsDelegate::type).
27///
28/// Each value holds the `Rc<T>` a [`LocalizationsDelegate<T>`] produced.
29type TypeToResources = HashMap<TypeId, Rc<dyn Any>>;
30
31// Used by load_all() to record LocalizationsDelegate.load() futures we're
32// waiting for.
33struct Pending {
34    delegate: LocalizationsDelegateRef,
35    future_value: CompleterFuture<Rc<dyn Any>>,
36}
37
38// A utility function used by Localizations to generate one future
39// that completes when all of the LocalizationsDelegate.load() futures
40// complete. The returned map is indexed by each delegate's type.
41//
42// The input future values must have distinct types.
43//
44// The returned future will resolve when all of the input map's
45// future values have resolved. If all of the input map's values are
46// already complete (Dart's SynchronousFutures) then a complete future
47// is returned immediately.
48//
49// This is more complicated than just applying wait_all to input
50// because some of the input.values may be already complete. We don't want
51// to wait_all for those.
52fn 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    // Only load the first delegate for each delegate type that supports
61    // locale.languageCode.
62    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            // inputValue was a SynchronousFuture
75            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    // All of the delegate.load() values were synchronous futures, we're done.
87    let Some(pending_list) = pending_list else {
88        return CompleterFuture::ready(Rc::new(output));
89    };
90
91    // Some of delegate.load() values were asynchronous futures. Wait for them.
92    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
108// ---------------------------------------------------------------------------------------------
109// LocalizationsDelegate
110
111/// A factory for a set of localized resources of type `T`, to be loaded by a
112/// [`Localizations`] widget.
113///
114/// Typical applications have one [`Localizations`] widget which is created by the
115/// `WidgetsApp` and configured with the app's `localizationsDelegates` parameter (a list
116/// of delegates). The delegate's [`type`](AnyLocalizationsDelegate::type) is used to
117/// identify the object created by an individual delegate's [`load`](Self::load) method.
118///
119/// An example of a class used as the value of `T` here would be `MaterialLocalizations`.
120pub trait LocalizationsDelegate<T: ?Sized + 'static>: Debug + 'static {
121    /// Whether resources for the given locale can be loaded by this delegate.
122    ///
123    /// Return true if the instance of `T` loaded by this delegate's [`load`](Self::load)
124    /// method supports the given `locale`'s language.
125    fn is_supported(&self, locale: &Locale) -> bool;
126
127    /// Start loading the resources for `locale`. The returned future completes
128    /// when the resources have finished loading.
129    ///
130    /// It's assumed that this method will return an object that contains a
131    /// collection of related resources (typically defined with one method per
132    /// resource). The object will be retrieved with [`Localizations::of`].
133    ///
134    /// A delegate whose resources are at hand returns [`CompleterFuture::ready`], Dart's
135    /// `SynchronousFuture`: the [`Localizations`] widget then builds at once instead of
136    /// deferring the first frame until the future completes.
137    fn load(&self, app: &mut App, locale: &Locale) -> CompleterFuture<Rc<T>>;
138
139    /// Returns true if the resources for this delegate should be loaded
140    /// again by calling the [`load`](Self::load) method.
141    ///
142    /// This method is called whenever its [`Localizations`] widget is
143    /// rebuilt. If it returns true then dependent widgets will be rebuilt
144    /// after [`load`](Self::load) has completed.
145    fn should_reload(&self, old: &Self) -> bool;
146}
147
148/// The erased form of a [`LocalizationsDelegate`]: the delegate as a [`Localizations`]
149/// widget holds it, without its resource type.
150pub trait AnyLocalizationsDelegate: Debug {
151    /// See [`LocalizationsDelegate::is_supported`].
152    fn is_supported(&self, locale: &Locale) -> bool;
153
154    /// See [`LocalizationsDelegate::load`]; the value holds the `Rc<T>`.
155    fn load(&self, app: &mut App, locale: &Locale) -> CompleterFuture<Rc<dyn Any>>;
156
157    /// See [`LocalizationsDelegate::should_reload`]; false when `old` is a delegate of
158    /// another type.
159    fn should_reload(&self, old: &dyn AnyLocalizationsDelegate) -> bool;
160
161    /// The type of the object returned by the [`load`](Self::load) method, T by default.
162    ///
163    /// This type is used to retrieve the object "loaded" by this
164    /// [`LocalizationsDelegate`] from the [`Localizations`] inherited widget.
165    /// For example the object loaded by `LocalizationsDelegate<Foo>` would
166    /// be retrieved with:
167    ///
168    /// ```text
169    /// Localizations::of::<Foo>(app, context)
170    /// ```
171    ///
172    /// It's rarely necessary to override this getter.
173    fn r#type(&self) -> TypeId;
174
175    /// The delegate's own type, Dart's `runtimeType`.
176    fn runtime_type(&self) -> TypeId;
177
178    /// The delegate as `Any`, for [`should_reload`](Self::should_reload).
179    fn as_any(&self) -> &dyn Any;
180}
181
182/// A shared, erased [`LocalizationsDelegate`].
183#[derive(Clone)]
184pub struct LocalizationsDelegateRef(Rc<dyn AnyLocalizationsDelegate>);
185
186impl LocalizationsDelegateRef {
187    /// Erases `delegate`.
188    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        // A complete future stays complete, so `load_all` still tells a synchronous delegate
231        // apart; a pending one is forwarded when it completes.
232        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
260/// The `Rc<T>` as [`TypeToResources`] stores it.
261fn erase<T: ?Sized + 'static>(resources: Rc<T>) -> Rc<dyn Any> {
262    Rc::new(resources)
263}
264
265// ---------------------------------------------------------------------------------------------
266// WidgetsLocalizations
267
268/// Interface for localized resource values for the lowest levels of the Flutter
269/// framework.
270///
271/// This class also maps locales to a specific [`Directionality`] using the
272/// [`text_direction`](Self::text_direction) property.
273///
274/// See also:
275///
276///  * [`DefaultWidgetsLocalizations`], which implements this interface and
277///    supports a variety of locales.
278pub trait WidgetsLocalizations: 'static {
279    /// The reading direction for text in this locale.
280    fn text_direction(&self) -> TextDirection;
281
282    /// The semantics label used for `SliverReorderableList` to reorder an item in the
283    /// list to the start of the list.
284    fn reorder_item_to_start(&self) -> String;
285
286    /// The semantics label used for `SliverReorderableList` to reorder an item in the
287    /// list to the end of the list.
288    fn reorder_item_to_end(&self) -> String;
289
290    /// The semantics label used for `SliverReorderableList` to reorder an item in the
291    /// list one space up the list.
292    fn reorder_item_up(&self) -> String;
293
294    /// The semantics label used for `SliverReorderableList` to reorder an item in the
295    /// list one space down the list.
296    fn reorder_item_down(&self) -> String;
297
298    /// The semantics label used for `SliverReorderableList` to reorder an item in the
299    /// list one space left in the list.
300    fn reorder_item_left(&self) -> String;
301
302    /// The semantics label used for `SliverReorderableList` to reorder an item in the
303    /// list one space right in the list.
304    fn reorder_item_right(&self) -> String;
305
306    /// Label for "search results found" announcement.
307    fn search_results_found(&self) -> String {
308        String::from("Search results found")
309    }
310
311    /// Label for "no results found" announcement.
312    fn no_results_found(&self) -> String {
313        String::from("No results found")
314    }
315
316    /// The label for the copy button on the text selection toolbar.
317    fn copy_button_label(&self) -> String;
318
319    /// The label for the cut button on the text selection toolbar.
320    fn cut_button_label(&self) -> String;
321
322    /// The label for the paste button on the text selection toolbar.
323    fn paste_button_label(&self) -> String;
324
325    /// The label for the select all button on the text selection toolbar.
326    fn select_all_button_label(&self) -> String;
327
328    /// The label for the look up button on the text selection toolbar.
329    fn look_up_button_label(&self) -> String;
330
331    /// The label for the search web button on the text selection toolbar.
332    fn search_web_button_label(&self) -> String;
333
334    /// The label for the share button on the text selection toolbar.
335    fn share_button_label(&self) -> String;
336
337    /// The semantics label used for a `RadioGroup` widget when the radio button is
338    /// unselected.
339    fn radio_button_unselected_label(&self) -> String;
340}
341
342impl dyn WidgetsLocalizations {
343    /// The `WidgetsLocalizations` from the closest [`Localizations`] instance
344    /// that encloses the given context.
345    ///
346    /// This method is just a convenient shorthand for:
347    /// `Localizations::of::<dyn WidgetsLocalizations>(app, context)`.
348    ///
349    /// References to the localized resources defined by this class are typically
350    /// written in terms of this method. For example:
351    ///
352    /// ```text
353    /// <dyn WidgetsLocalizations>::of(app, context).reorder_item_up()
354    /// ```
355    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/// US English localizations for the widgets library.
385///
386/// See also:
387///
388///  * `GlobalWidgetsLocalizations`, which provides widgets localizations for
389///    many languages.
390///  * `WidgetsApp.localizationsDelegates`, which automatically includes
391///    [`DefaultWidgetsLocalizations::delegate`] by default.
392#[derive(Debug, Default)]
393pub struct DefaultWidgetsLocalizations;
394
395impl DefaultWidgetsLocalizations {
396    /// Construct an object that defines the localized values for the widgets
397    /// library for US English (only).
398    ///
399    /// [`delegate`](Self::delegate) is the delegate.
400    pub const fn new() -> DefaultWidgetsLocalizations {
401        DefaultWidgetsLocalizations
402    }
403
404    /// Creates an object that provides US English resource values for the
405    /// lowest levels of the widgets library.
406    ///
407    /// The `locale` parameter is ignored.
408    ///
409    /// This method is typically used to create a [`LocalizationsDelegate`].
410    /// The `WidgetsApp` does so by default.
411    pub fn load(_locale: &Locale) -> CompleterFuture<Rc<dyn WidgetsLocalizations>> {
412        CompleterFuture::ready(Rc::new(DefaultWidgetsLocalizations::new()))
413    }
414
415    /// A [`LocalizationsDelegate`] that uses [`DefaultWidgetsLocalizations::load`]
416    /// to create an instance of this class.
417    ///
418    /// `WidgetsApp` automatically adds this value to `WidgetsApp.localizationsDelegates`.
419    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
486// ---------------------------------------------------------------------------------------------
487// _LocalizationsScope
488
489/// Dart's `_LocalizationsScope`: the inherited widget that [`Localizations`] rebuilds its
490/// dependents through.
491struct 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
521// ---------------------------------------------------------------------------------------------
522// Localizations
523
524/// Defines the [`Locale`] for its `child` and the localized resources that the
525/// child depends on.
526///
527/// ## Defining localized resources
528///
529/// This class is effectively an [`InheritedWidget`]. If it's rebuilt with
530/// a new `locale` or a different list of `delegates` or any of its
531/// delegates' [`LocalizationsDelegate::should_reload`] methods returns true,
532/// then widgets that have created a dependency on this widget will be
533/// rebuilt after the resources for the new locale have been loaded.
534///
535/// The [`Localizations`] widget also instantiates [`Directionality`] in order to
536/// support the appropriate [`Directionality::of`] for its localized `child`.
537///
538/// Each [`LocalizationsDelegate`] in `delegates` produces a collection of localized
539/// resources, an object of type `T`, one of which is retrieved with [`Localizations::of`].
540///
541/// `WidgetsApp` creates a [`Localizations`] widget so most apps will not need to create one.
542/// The widget app's [`Localizations`] delegates can be initialized with
543/// `WidgetsApp.localizationsDelegates`. The `MaterialApp` class also provides a
544/// `localizationsDelegates` parameter that's just passed along to the `WidgetsApp`.
545///
546/// ## Loading localized resources
547///
548/// Localized resources are loaded by the list of [`LocalizationsDelegate`]
549/// `delegates`. Each delegate is essentially a factory for a collection
550/// of localized resources. There are multiple delegates because there are
551/// multiple sources for localizations within an app.
552///
553/// If [`Localizations`] were to be rebuilt with a new `locale` then
554/// the widget subtree that corresponds to [`BuildContext`] `context` would
555/// be rebuilt after the corresponding resources had been loaded.
556///
557/// ## Localizations widgets
558///
559/// The delegates are the primary parameter.
560pub 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    /// Create a widget from which localizations (like translated strings) can be obtained.
570    ///
571    /// The delegates must include one for [`WidgetsLocalizations`].
572    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    /// Overrides the inherited [`Locale`] or [`LocalizationsDelegate`]s for `child`.
589    ///
590    /// This factory constructor is used for the (rare) situation where part of an app
591    /// should be localized for a different locale than the one defined for the device,
592    /// or if its localizations should come from a different list of
593    /// [`LocalizationsDelegate`]s than the list defined by `WidgetsApp.localizationsDelegates`.
594    ///
595    /// For example you could specify that `my_widget` was only to be localized for
596    /// the US English locale:
597    ///
598    /// ```text
599    /// Localizations::r#override(app, context)
600    ///     .locale(Locale::new("en").country_code("US"))
601    ///     .child(my_widget)
602    /// ```
603    ///
604    /// The `locale` and `delegates` parameters default to the [`Localizations::locale_of`]
605    /// and [`Localizations`] delegates values from the enclosing [`Localizations`] widget.
606    /// The given `delegates` are consulted before the inherited ones.
607    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    /// Dart `Localizations(key:)`.
617    pub fn key(mut self, key: KeyRef) -> Localizations {
618        self.key = Some(key);
619        self
620    }
621
622    /// The widget below this widget in the tree.
623    #[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    /// Whether this widget is at the application level.
630    ///
631    /// `WidgetsApp` sets this to true.
632    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    /// The locale of the Localizations widget for the widget tree that
638    /// corresponds to [`BuildContext`] `context`.
639    ///
640    /// If no [`Localizations`] widget is in scope then the [`Localizations::locale_of`]
641    /// method will throw an exception.
642    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    /// The locale of the Localizations widget for the widget tree that
655    /// corresponds to [`BuildContext`] `context`.
656    ///
657    /// If no [`Localizations`] widget is in scope then this function will return
658    /// null.
659    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    // There doesn't appear to be a need to make this public. It's only used
665    // by Localizations.override.
666    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    /// Returns the localized resources object of the given `type` for the widget
672    /// tree that corresponds to the given `context`.
673    ///
674    /// Returns null if no resources object of the given `type` exists within
675    /// the given `context`.
676    ///
677    /// This method is typically used by a static factory method on the `type`
678    /// class. For example Flutter's `MaterialLocalizations` class looks up Material
679    /// resources with a method defined like this:
680    ///
681    /// ```text
682    /// pub fn of(app: &mut App, context: BuildContext) -> Rc<dyn MaterialLocalizations> {
683    ///     Localizations::of::<dyn MaterialLocalizations>(app, context).expect(..)
684    /// }
685    /// ```
686    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    /// The state behind the nearest `_LocalizationsScope`, registering the dependency.
692    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
736/// Dart's `Localizations.override` factory, before its optional arguments are known.
737pub struct LocalizationsOverride {
738    key: Option<KeyRef>,
739    locale: Locale,
740    delegates: Vec<LocalizationsDelegateRef>,
741    child: Option<WidgetRef>,
742}
743
744impl LocalizationsOverride {
745    /// Dart `Localizations.override(key:)`.
746    pub fn key(mut self, key: KeyRef) -> LocalizationsOverride {
747        self.key = Some(key);
748        self
749    }
750
751    /// Dart `Localizations.override(locale:)`.
752    pub fn locale(mut self, locale: Locale) -> LocalizationsOverride {
753        self.locale = locale;
754        self
755    }
756
757    /// Dart `Localizations.override(delegates:)`: consulted before the inherited delegates.
758    pub fn delegates(mut self, delegates: Vec<LocalizationsDelegateRef>) -> LocalizationsOverride {
759        self.delegates.splice(0..0, delegates);
760        self
761    }
762
763    /// Dart `Localizations.override(child:)`.
764    #[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
771/// The kind tag of [`IntoWidget`] for a [`LocalizationsOverride`].
772pub 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
788/// Dart's `_LocalizationsState`.
789pub 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    /// The locale the resources were loaded for; `None` until the first load.
798    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    /// Loads the resources for `locale` from the widget's delegates.
825    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            // All of the delegates' resources loaded synchronously.
836            app.get_mut(self).type_to_resources = type_to_resources;
837            self.set_locale(app, locale);
838        } else {
839            // - Don't rebuild the dependent widgets until the resources for the new locale
840            // have finished loading. Until then the old locale will continue to be used.
841            // - If we're running at app startup time then defer reporting the first
842            // "useful" frame until after the async load has completed.
843            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    /// The resources a [`LocalizationsDelegate<T>`] loaded, if one did.
855    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 this is not application level, we need to explicit mark the
902        // semantics subtree with the locale.
903        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
919// ---------------------------------------------------------------------------------------------
920// LocalizationsResolver
921
922/// Resolves the locale for an app based on the locale it is being run in, the locale the
923/// app has been configured with, and the locales the app supports.
924///
925/// Registers itself as a binding observer (Dart's `WidgetsBindingObserver` mixin) so that
926/// [`did_change_locales`](WidgetsBindingObserverObject::did_change_locales) re-resolves.
927pub 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    /// What the binding observes, kept to remove it. It keeps this object, as Dart's binding
936    /// keeps its observer, until `dispose` removes it.
937    observer: Option<WidgetsBindingObserverRef>,
938}
939
940impl LocalizationsResolver {
941    /// Creates a resolver (Dart's constructor: `supportedLocales` is required; the rest are
942    /// its optional named arguments, in the order [`update`](Self::update) takes them).
943    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    /// Unregisters from the binding and disposes the notifier.
971    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    /// Updates the resolver with the given configuration, re-resolving the locale when
979    /// `supported_locales` changed.
980    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    /// The currently resolved locale.
1002    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    /// The delegates for the app's localizations, with
1017    /// [`DefaultWidgetsLocalizations::delegate`] appended.
1018    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    /// The callback that resolves from the full list of preferred locales.
1029    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    /// The callback that resolves from the single default locale.
1037    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    /// The locales the app supports.
1045    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        // Attempt to use localeListResolutionCallback.
1077        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        // localeListResolutionCallback failed, falling back to localeResolutionCallback.
1083        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        // Both callbacks failed, falling back to default algorithm.
1092        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    /// A resource type of its own, so `Localizations::of` has two types to tell apart.
1132    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    /// Dart's `FakeLocalizationsDelegate`: loads whenever the test completes its completer.
1166    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        // One probe widget: an identical child is not rebuilt, so only the scope's
1296        // notification can rebuild it.
1297        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        // One probe widget: an identical child is not rebuilt, so only the scope's
1363        // notification can rebuild it.
1364        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(&notified);
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}