iced_af 0.4.1

The iced application framework project.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// This file is part of `iced_af` crate. For the terms of use, please see the file
// called LICENSE-BSD-3-Clause at the top level of the `iced_af` crate.

//! The localisation component of the mini application framework.
//!
//! Add new window localisation under `src/windows/` directory.

use crate::{
    application::{environment::Environment, StringGroup},
    core::{error::CoreError, traits::AnyLocalisedTrait},
};
use i18n::{
    lexer::{DataProvider, IcuDataProvider},
    localiser::{CommandRegistry, Localiser},
    provider::RepositoryDetails,
    provider_sqlite3::LocalisationProviderSqlite3,
    utility::{
        Direction, LanguageTag, LanguageTagRegistry, LocalisationData, LocalisationErrorTrait,
        PlaceholderValue, ScriptDirection,
    },
};
use iced::Alignment;
use std::collections::HashMap;

#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};

#[cfg(not(feature = "sync"))]
use std::rc::Rc as RefCount;

#[cfg(feature = "sync")]
#[cfg(target_has_atomic = "ptr")]
use std::sync::Arc as RefCount;

//
// ----- The localisation for the UI
//

/// The localised string cache for constant strings of window types.
/// 
/// Note: Instances specific localisation, such as messages, are stored instead
/// in the window's state.
pub struct StringCache {
    cache: HashMap<StringGroup, Box<dyn AnyLocalisedTrait>>,
}

impl StringCache {
    /// Creates an empty cache.
    pub fn new() -> StringCache {
        StringCache {
            cache: HashMap::<StringGroup, Box<dyn AnyLocalisedTrait>>::new(),
        }
    }

    /// Attempts to update the localised string to the selected language
    /// contained in `Localisation`.
    pub fn try_update(&mut self, localisation: &Localisation) -> Result<(), CoreError> {
        for (string_group, strings) in self.cache.iter_mut() {
            strings.try_update(localisation)?;
            trace!(
                "try_update(): Updated strings for string group ‘{:?}’: {:?}",
                string_group,
                strings
            );
        }
        Ok(())
    }

    /// Returns true if a `StringGroup` exists in the cache.
    pub fn exists(&self, string_group: &StringGroup) -> bool {
        self.cache.contains_key(string_group)
    }

    /// Insert localised strings into the cache.
    pub fn insert(
        &mut self,
        string_group: StringGroup,
        localised_strings: Box<dyn AnyLocalisedTrait>,
    ) {
        let _ = self.cache.insert(string_group, localised_strings);
    }

    /// Get a reference to the localised strings for the specified `StringGroup`.
    pub fn get(&self, string_group: &StringGroup) -> Option<&Box<dyn AnyLocalisedTrait>> {
        self.cache.get(string_group)
    }
}

/// `Localisation` is a wrapper for the `Localiser` of the
/// `i18n-rizzen-yazston` crate, with added script layout data for the current
/// language, and cache of available languages in the application's
/// localisation database. 
pub struct Localisation {
    // The i18n localiser
    localiser: Localiser,

    // Layout data for the default language. Cached copy from available_languages as there are many view() calls.
    layout_data: LayoutData,

    // Available languages according to supported scripts
    available_languages: HashMap<RefCount<LanguageTag>, (LayoutData, f32)>,
}

impl Localisation {
    /// Initialise the `Localiser`, collect available languages layout data
    pub fn try_new<T: AsRef<str>>(
        environment: &Environment,
        language: T,
    ) -> Result<Localisation, CoreError> {
        let directions = vec![
            ScriptDirection::TopToBottomLeftToRight,
            ScriptDirection::TopToBottomRightToLeft,
        ];
        let mut available_languages = HashMap::<RefCount<LanguageTag>, (LayoutData, f32)>::new();
        let language_tag_registry = RefCount::new(LanguageTagRegistry::new());
        let path = environment.application_path.join("l10n");
        let localisation_provider = Box::new(
            LocalisationProviderSqlite3::try_new(
                path, &language_tag_registry, false
            )?
        );
        let icu_data_provider = RefCount::new(IcuDataProvider::try_new(DataProvider::Internal)?);
        let command_registry = RefCount::new(CommandRegistry::new());
        let localiser = Localiser::try_new(
            &icu_data_provider,
            &language_tag_registry,
            localisation_provider,
            &command_registry,
            true,
            true,
            language.as_ref(),
        )?;
        let binding = localiser
            .localisation_provider()
            .component_details("application")?;
        debug!("Building language list");
        for language_data in binding.languages.iter() {
            match localiser.script_data_for_language_tag(language_data.0) {
                None => {
                    debug!("Language tag ‘{:?}’ is not supported for the application's user interface.", language_data.0);
                }
                Some(script_data) => {
                    for script_direction in script_data.directions {
                        for supported in directions.iter() {
                            if script_direction == *supported {
                                debug!("Adding language: ‘{:?}’", language_data.0);

                                available_languages.insert(
                                    language_data.0.clone(),
                                    (LayoutData::new(&script_direction), language_data.1.ratio),
                                );
                            }
                        }
                    }
                }
            }
        }
        let layout_data = available_languages
            .get(&localiser.default_language())
            .unwrap()
            .0
            .clone();
        Ok(Localisation {
            localiser,
            layout_data,
            available_languages,
        })
    }

    // ----- Exposed Localiser methods

    /// Obtain reference to `Localiser` language tag registry.
    pub fn language_tag_registry(&self) -> &RefCount<LanguageTagRegistry> {
        self.localiser.language_tag_registry()
    }

    /// Obtain reference to `Localiser` ICU data provider.
    pub fn icu_data_provider(&self) -> &RefCount<IcuDataProvider> {
        self.localiser.icu_data_provider()
    }

    /// Obtain reference to `Localiser` command registry.
    pub fn command_registry(&self) -> &RefCount<CommandRegistry> {
        self.localiser.command_registry()
    }

    /// Obtain reference to `Localiser` default language.
    pub fn default_language(&self) -> RefCount<LanguageTag> {
        self.localiser.default_language()
    }

    /// Obtain reference to `Localiser` repository details.
    pub fn repository_details(&self) -> Result<RefCount<RepositoryDetails>, CoreError> {
        Ok(self
            .localiser
            .localisation_provider()
            .repository_details()?)
    }

    /// Get a literal string using `Localiser` defaults.
    pub fn literal_with_defaults(
        &self,
        component: &str,
        identifier: &str,
    ) -> Result<(RefCount<String>, RefCount<LanguageTag>), CoreError> {
        Ok(self
            .localiser
            .literal_with_defaults(component, identifier)?)
    }

    /// Format a string using `Localiser` defaults.
    pub fn format_with_defaults(
        &self,
        component: &str,
        identifier: &str,
        values: &HashMap<String, PlaceholderValue>,
    ) -> Result<(RefCount<String>, RefCount<LanguageTag>), CoreError> {
        Ok(self
            .localiser
            .format_with_defaults(component, identifier, values)?)
    }

    /// Format an error into a string using `Localiser` defaults.
    pub fn format_error_with_defaults(
        &self,
        error: &impl LocalisationErrorTrait,
    ) -> Result<(RefCount<String>, RefCount<LanguageTag>), CoreError> {
        Ok(self.localiser.format_error_with_defaults(error)?)
    }

    /// Format `LocalisationData` instance into a string using `Localiser` defaults.
    pub fn format_localisation_data_with_defaults(
        &self,
        data: &LocalisationData,
    ) -> Result<(RefCount<String>, RefCount<LanguageTag>), CoreError> {
        Ok(self
            .localiser
            .format_localisation_data_with_defaults(data)?)
    }

    // ----- Localisation methods

    /// Get a reference to available languages. Also includes the layout data
    /// and ratio of translated string to development language.
    pub fn available_languages(&self) -> &HashMap<RefCount<LanguageTag>, (LayoutData, f32)> {
        &self.available_languages
    }

    /// Change the default language of the `Localiser`, and change layout data
    /// to the new language.
    pub fn change_default_language(
        &mut self,
        tag: RefCount<LanguageTag>,
    ) -> Result<bool, CoreError> {
        if tag != self.localiser.default_language() {
            let Some(layout) = self.available_languages.get(&tag) else {
                return Err(CoreError::LanguageTagNotSupported(tag.as_str().to_string()));
            };
            self.localiser.defaults(Some(tag), None, None)?;
            self.layout_data = layout.0.clone();
            return Ok(true);
        }
        Ok(false)
    }

    /// Get reference to the language layout data.
    pub fn layout_data(&self) -> &LayoutData {
        &self.layout_data
    }
}

//
// ----- Script directionality
//

/// Text flow data of scripts.
///
/// Field meaning:
///
/// * `flow_line`: The direction of the line stack goes in.
///
/// * `flow_word`: The direction of the words within the line.
///
/// * `reverse_lines`: Normally used to indicate the page elements of a [`Vec`] needs to be reversed before placement.
///
/// * `reverse_words`: Normally used to indicate the line elements of a [`Vec`] needs to be reversed before placement.
///
/// * `align_lines_start`: Align the stack of lines to the start direction. Horizontal taken as top, and vertical
/// taken as left.
///
/// * `align_lines_end`: Align the stack of lines to the end direction.
///
/// * `align_words_start`: Align the words of the lines to the start direction. Horizontal taken as left, and vertical
/// taken as top.
///
/// * `align_words_end`: Align the words of the lines to the end direction.
///
/// `iced` horizontal layout flow is top to bottom for lines/rows and left to right for words/columns. Currently `iced`
/// has not vertical layout support.
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct LayoutData {
    pub flow_line: Direction,
    pub flow_word: Direction,
    pub reverse_lines: bool,
    pub reverse_words: bool,
    pub align_lines_start: Alignment,
    pub align_lines_end: Alignment,
    pub align_words_start: Alignment,
    pub align_words_end: Alignment,
}

impl LayoutData {
    /// Create a `LayoutData` for the specified script direction.
    pub fn new(script_direction: &ScriptDirection) -> Self {
        match script_direction {
            // Most common is top to bottom line flow.
            ScriptDirection::TopToBottomLeftToRight => LayoutData {
                flow_line: Direction::TopToBottom,
                flow_word: Direction::LeftToRight,
                reverse_lines: false,
                reverse_words: false,
                align_lines_start: Alignment::Start,
                align_lines_end: Alignment::End,
                align_words_start: Alignment::Start,
                align_words_end: Alignment::End,
            },
            ScriptDirection::TopToBottomRightToLeft => LayoutData {
                flow_line: Direction::TopToBottom,
                flow_word: Direction::RightToLeft,
                reverse_lines: false,
                reverse_words: true,
                align_lines_start: Alignment::Start,
                align_lines_end: Alignment::End,
                align_words_start: Alignment::End,
                align_words_end: Alignment::Start,
            },

            // Commonly known as vertical texts, for various eastern asian scripts.
            ScriptDirection::RightToLeftTopToBottom => LayoutData {
                flow_line: Direction::RightToLeft,
                flow_word: Direction::TopToBottom,
                reverse_lines: true,
                reverse_words: false,
                align_lines_start: Alignment::End,
                align_lines_end: Alignment::Start,
                align_words_start: Alignment::Start,
                align_words_end: Alignment::End,
            },
            ScriptDirection::RightToLeftBottomToTop => LayoutData {
                flow_line: Direction::LeftToRight,
                flow_word: Direction::TopToBottom,
                reverse_lines: false,
                reverse_words: false,
                align_lines_start: Alignment::Start,
                align_lines_end: Alignment::End,
                align_words_start: Alignment::Start,
                align_words_end: Alignment::End,
            },

            // The bottom to top line flow is very rare, though some have been seen on monuments.
            // Mongolian script is such a script
            ScriptDirection::LeftToRightTopToBottom => LayoutData {
                flow_line: Direction::BottomToTop,
                flow_word: Direction::LeftToRight,
                reverse_lines: true,
                reverse_words: false,
                align_lines_start: Alignment::End,
                align_lines_end: Alignment::Start,
                align_words_start: Alignment::Start,
                align_words_end: Alignment::End,
            },
            ScriptDirection::LeftToRightBottomToTop => LayoutData {
                flow_line: Direction::BottomToTop,
                flow_word: Direction::RightToLeft,
                reverse_lines: true,
                reverse_words: true,
                align_lines_start: Alignment::End,
                align_lines_end: Alignment::Start,
                align_words_start: Alignment::End,
                align_words_end: Alignment::Start,
            },
            ScriptDirection::BottomToTopLeftToRight => LayoutData {
                flow_line: Direction::RightToLeft,
                flow_word: Direction::BottomToTop,
                reverse_lines: true,
                reverse_words: true,
                align_lines_start: Alignment::End,
                align_lines_end: Alignment::Start,
                align_words_start: Alignment::End,
                align_words_end: Alignment::Start,
            },
            ScriptDirection::BottomToTopRightToLeft => LayoutData {
                flow_line: Direction::LeftToRight,
                flow_word: Direction::BottomToTop,
                reverse_lines: false,
                reverse_words: true,
                align_lines_start: Alignment::Start,
                align_lines_end: Alignment::End,
                align_words_start: Alignment::End,
                align_words_end: Alignment::Start,
            },
        }
    }
}