sofie-engine 0.4.0

Screens: the template parser and renderer, and the component catalog.
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
406
407
use std::sync::LazyLock;

use sofie_core::{DisplayZone, Shown};
use sofie_values::{Instant, Locale, Money, Present};

use super::conventions::{self, Conventions, NEUTRAL};
use super::{CountedKeys, Message, Part, Translations, Variant, negotiate};
use crate::message::{is_exactly_one, number_of};

static PLAIN: LazyLock<Translations> =
    LazyLock::new(|| Translations::new(&["en"]).expect("the engine's own translations parse"));

#[derive(Clone, Copy, Debug)]
pub struct Language<'a> {
    translations: &'a Translations,
    index: usize,
    conventions: &'static Conventions,
    plural_rule: PluralRule,
    #[cfg(feature = "gates")]
    pub(crate) gates: crate::rendering::GatesRef<'a>,
}

/// What a language's texts and formats are made of, apart from the viewer's gates.
#[cfg(feature = "clients")]
#[derive(Clone, Copy, Debug)]
pub(crate) struct Texts {
    generation: u64,
    index: usize,
    conventions: &'static Conventions,
}

#[cfg(feature = "clients")]
impl Texts {
    pub(crate) fn is_of_same_translations(self, other: Self) -> bool {
        self.generation == other.generation
    }
}

#[cfg(feature = "clients")]
impl PartialEq for Texts {
    fn eq(&self, other: &Self) -> bool {
        self.generation == other.generation
            && self.index == other.index
            && std::ptr::eq(self.conventions, other.conventions)
    }
}

impl Translations {
    /// The principal's choice first, then `Accept-Language` by weight, then the source language.
    #[must_use]
    pub fn negotiate(
        &self,
        preferred: Option<&Locale>,
        accept_language: Option<&str>,
    ) -> Language<'_> {
        let accepted = accept_language.map(negotiate::accepted).unwrap_or_default();
        let index = preferred
            .into_iter()
            .chain(&accepted)
            .find_map(|wanted| closest(&self.languages, wanted))
            .unwrap_or(0);
        let language = self.languages[index].language();
        Language {
            translations: self,
            index,
            conventions: conventions::for_language(language),
            plural_rule: PluralRule::for_language(language),
            #[cfg(feature = "gates")]
            gates: crate::rendering::GatesRef::default(),
        }
    }
}

fn filled(message: &Message, arguments: &[(&str, String)]) -> String {
    let mut text = String::new();
    for part in message.parts() {
        match part {
            Part::Text(literal) => text.push_str(literal),
            Part::Argument(name) => {
                let value = arguments
                    .iter()
                    .find(|(argument, _)| *argument == name.as_str());
                text.push_str(value.map_or("", |(_, value)| value));
            }
        }
    }
    text
}

fn closest(declared: &[Locale], wanted: &Locale) -> Option<usize> {
    declared
        .iter()
        .position(|language| language == wanted)
        .or_else(|| {
            declared
                .iter()
                .position(|language| language.language() == wanted.language())
        })
}

impl<'a> Language<'a> {
    /// So compiling the feature in changes nothing until the app declares languages.
    #[must_use]
    pub fn plain() -> Language<'static> {
        Language {
            translations: &PLAIN,
            index: 0,
            conventions: &NEUTRAL,
            plural_rule: PluralRule::OneIsOne,
            #[cfg(feature = "gates")]
            gates: crate::rendering::GatesRef::default(),
        }
    }

    #[must_use]
    pub fn locale(self) -> &'a Locale {
        &self.translations.languages[self.index]
    }

    #[must_use]
    pub fn field_message<'m>(self, message: &'m str) -> &'m str
    where
        'a: 'm,
    {
        self.text(message, message)
    }

    /// A value refusing in its own words (`validation.invalid`) keeps them, translated if a key.
    #[must_use]
    pub fn field_error(self, key: &str, arguments: &[(&str, String)], fallback: &str) -> String {
        if key == "validation.invalid" {
            return self.field_message(fallback).to_owned();
        }
        let Some(message) = self.message(key) else {
            return fallback.to_owned();
        };
        if !is_source_wording(key, arguments, fallback) {
            return self.field_message(fallback).to_owned();
        }
        filled(message, arguments)
    }

    pub(crate) fn text<'m>(self, key: &str, fallback: &'m str) -> &'m str
    where
        'a: 'm,
    {
        self.message(key)
            .and_then(Message::plain)
            .unwrap_or(fallback)
    }

    pub(crate) fn message(self, key: &str) -> Option<&'a Message> {
        self.translations
            .entries
            .get_or_default(key, self.index)
            .map(|definition| &definition.message)
    }

    /// Another language's `one` would write its singular here, so only this language's counts.
    pub(crate) fn own_message(self, key: &str) -> Option<&'a Message> {
        self.translations
            .entries
            .get(key, self.index)
            .map(|definition| &definition.message)
    }

    /// `key.one` where the count is one, then `key.other`, then the plain key.
    pub(crate) fn counted_message(
        self,
        key: &str,
        keys: &CountedKeys,
        count: Option<Shown<'_>>,
    ) -> Option<&'a Message> {
        let one = || self.own_message(&keys.one);
        self.plural_rule
            .is_one(count)
            .then(one)
            .flatten()
            .or_else(|| self.message(&keys.other))
            .or_else(|| self.message(key))
    }

    #[cfg(feature = "clients")]
    pub(crate) fn plural_rule(self) -> PluralRule {
        self.plural_rule
    }

    pub(crate) fn enumeration(self, name: &str) -> Option<&'a [Variant]> {
        self.translations.enums.get(name).map(Vec::as_slice)
    }

    pub(crate) fn conventions(self) -> &'static Conventions {
        self.conventions
    }

    #[cfg(feature = "clients")]
    pub(crate) fn texts(self) -> Texts {
        Texts {
            generation: self.translations.generation,
            index: self.index,
            conventions: self.conventions,
        }
    }

    pub(crate) fn write_money(self, out: &mut String, amount: Money, scratch: &mut String) {
        self.conventions.write_money(out, amount, scratch);
    }

    #[must_use]
    pub fn format(self, value: &impl Present) -> String {
        let mut out = String::new();
        value.write_localized(&mut out, &self);
        out
    }
}

/// A message other than the key's own source text was chosen by its writer
/// (`plan.unique(…, "is already registered")`), so a translation of the key must not replace it;
/// an empty one asks for the key's text.
fn is_source_wording(key: &str, arguments: &[(&str, String)], fallback: &str) -> bool {
    fallback.is_empty()
        || Language::plain()
            .message(key)
            .is_none_or(|message| filled(message, arguments) == fallback)
}

pub(crate) fn write_instant(
    language: Language<'_>,
    out: &mut String,
    instant: Instant,
    scratch: &mut String,
) {
    language
        .conventions
        .write_instant(out, instant, DisplayZone::current(), scratch);
}

impl sofie_values::Conventions for Language<'_> {
    fn write_number(&self, out: &mut String, plain: &str) {
        self.conventions.write_number(out, plain);
    }

    fn write_money(&self, out: &mut String, amount: Money) {
        self.conventions
            .write_money(out, amount, &mut String::new());
    }

    fn write_date(&self, out: &mut String, iso: &str) {
        self.conventions.write_date(out, iso, &mut String::new());
    }

    fn write_variant(&self, out: &mut String, enumeration: &str, variant: &str) {
        let registered = self
            .enumeration(enumeration)
            .and_then(|variants| variants.iter().find(|known| known.name == variant));
        match registered {
            Some(known) => out.push_str(self.text(&known.key, &known.humanized)),
            None => out.push_str(variant),
        }
    }
}

/// CLDR's plural rules for whole counts, `one` and `other` only: a language's further forms fall to
/// `other`. A language none of these lists names may have a `one` the table cannot say (`sl`'s
/// 101, `fil`'s 2), so it takes `other` and is not told its `one` is never shown.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PluralRule {
    OneIsOne,
    OneIsZeroOrOne,
    OneEndsInOneNotEleven,
    OtherOnly,
}

const ONE_IS_ONE: [&str; 131] = [
    "af", "an", "ar", "asa", "ast", "az", "bal", "bem", "bez", "bg", "brx", "ca", "ce", "cgg",
    "chr", "ckb", "cs", "cy", "da", "de", "dv", "ee", "el", "en", "eo", "es", "et", "eu", "fi",
    "fo", "fur", "fy", "ga", "gl", "gsw", "ha", "haw", "he", "hu", "ia", "io", "it", "iu", "jgo",
    "ji", "jmc", "ka", "kaj", "kcg", "kk", "kkj", "kl", "ks", "ksb", "ksh", "ku", "ky", "lag",
    "lb", "lg", "lij", "mas", "mgo", "ml", "mn", "mr", "mt", "nah", "naq", "nb", "nd", "ne", "nl",
    "nn", "nnh", "no", "nr", "ny", "nyn", "om", "or", "os", "pap", "pl", "ps", "rm", "ro", "rof",
    "rwk", "saq", "sat", "sc", "scn", "sd", "sdh", "se", "seh", "sk", "sma", "smi", "smj", "smn",
    "sms", "sn", "so", "sq", "ss", "ssy", "st", "sv", "sw", "syr", "ta", "te", "teo", "tig", "tk",
    "tn", "tr", "ts", "ug", "ur", "uz", "ve", "vec", "vo", "vun", "wae", "xh", "xog", "yi",
];

const ONE_IS_ZERO_OR_ONE: [&str; 27] = [
    "ak", "am", "as", "bho", "bn", "csw", "doi", "fa", "ff", "fr", "gu", "guw", "hi", "hy", "kab",
    "kn", "ln", "mg", "nso", "pa", "pcm", "pt", "shi", "si", "ti", "wa", "zu",
];

const ONE_ENDS_IN_ONE_NOT_ELEVEN: [&str; 11] = [
    "be", "bs", "hr", "is", "lt", "lv", "mk", "ru", "sh", "sr", "uk",
];

#[cfg(feature = "parse")]
const WITHOUT_ONE: [&str; 33] = [
    "bm", "bo", "dz", "hnj", "id", "ig", "ii", "in", "ja", "jbo", "jv", "jw", "kde", "kea", "km",
    "ko", "lkt", "lo", "ms", "my", "root", "sah", "ses", "sg", "su", "th", "to", "tpi", "vi", "wo",
    "yo", "yue", "zh",
];

impl PluralRule {
    pub(crate) fn for_language(language: &str) -> Self {
        if ONE_IS_ONE.contains(&language) {
            Self::OneIsOne
        // CLDR's `pt` is Brazilian, where 0 is singular as in French.
        } else if ONE_IS_ZERO_OR_ONE.contains(&language) {
            Self::OneIsZeroOrOne
        } else if ONE_ENDS_IN_ONE_NOT_ELEVEN.contains(&language) {
            Self::OneEndsInOneNotEleven
        } else {
            Self::OtherOnly
        }
    }

    #[cfg(feature = "parse")]
    pub(crate) fn has_no_one(language: &str) -> bool {
        WITHOUT_ONE.contains(&language)
    }

    /// Anything but a number is `other`.
    #[expect(
        clippy::float_cmp,
        reason = "a whole count's remainders are whole, so exact"
    )]
    pub(crate) fn is_one(self, count: Option<Shown<'_>>) -> bool {
        let absolute = number_of(count).map(f64::abs);
        match self {
            Self::OneIsOne => is_exactly_one(count),
            Self::OneIsZeroOrOne => absolute.is_some_and(|count| count < 2.0),
            Self::OneEndsInOneNotEleven => absolute.is_some_and(|count| {
                count.fract() == 0.0 && count % 10.0 == 1.0 && count % 100.0 != 11.0
            }),
            Self::OtherOnly => false,
        }
    }

    #[cfg(feature = "clients")]
    pub(crate) fn name(self) -> &'static str {
        match self {
            Self::OneIsOne => "one-is-one",
            Self::OneIsZeroOrOne => "one-is-zero-or-one",
            Self::OneEndsInOneNotEleven => "one-ends-in-one-not-eleven",
            Self::OtherOnly => "other-only",
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn refusal(refused: sofie_core::Result<impl std::fmt::Debug>) -> sofie_core::FieldError {
        match refused {
            Err(sofie_core::Error::Invalid(mut fields)) => fields.remove(0),
            other => panic!("not refused as invalid: {other:?}"),
        }
    }

    #[test]
    fn each_value_refusal_reads_in_its_own_key_in_every_shipped_language() {
        use sofie_values::{Currency, Date, Email, Locale, Money, Slug, TimeOfDay, TimeZone, Url};

        let euro = Currency::parse("EUR").unwrap();
        let refusals = [
            refusal(Email::parse("ada lovelace@example.com")),
            refusal(Email::parse("ada(at)example.com")),
            refusal(Email::parse("a\"b@example.com")),
            refusal(Money::parse_major("1.234", euro)),
            refusal(Money::parse_major("1,5", euro)),
            refusal(Money::parse_major("1.5", Currency::parse("JPY").unwrap())),
            refusal(Currency::parse("eur")),
            refusal(Slug::parse("Not A Slug")),
            refusal(Url::parse("ftp://example.com")),
            refusal(Locale::parse("en-u")),
            refusal(Date::parse("2026-02-30")),
            refusal(TimeOfDay::parse("25:00")),
            refusal(TimeZone::parse("Mars/Olympus")),
        ];
        let translations = Translations::new(&["en", "de", "tr"]).unwrap();
        let english = translations.negotiate(None, Some("en"));
        for refused in &refusals {
            let arguments: Vec<(&str, String)> = refused
                .arguments
                .iter()
                .map(|(name, value)| (name.as_ref(), value.clone()))
                .collect();
            assert_ne!(refused.key, "validation.invalid", "{refused:?}");
            assert_eq!(
                english
                    .message(&refused.key)
                    .map(|message| filled(message, &arguments))
                    .as_ref(),
                Some(&refused.message),
                "{refused:?}"
            );
            for language in ["de", "tr"] {
                let translated = translations.negotiate(None, Some(language)).field_error(
                    &refused.key,
                    &arguments,
                    &refused.message,
                );
                assert_ne!(translated, refused.message, "{language}: {refused:?}");
            }
        }
    }
}