enshwick 1.0.0-alpha.4

The Enshwick Loader's modding API for Enshrouded: the one crate mods are written against
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! Translations: a mod ships its texts per language in one TOML file, a
//! server owner may add to them or change them, and the game shows them for
//! the player's language.
//!
//! ```toml
//! [en]
//! "locker.name" = "Locker"
//!
//! [uk]
//! "locker.name" = "Шафка"
//! ```
//!
//! `en` is the fallback for every language without a text of its own. A file
//! `mod-configs/<id>.texts.toml` in the same form overrides or adds texts.

use std::collections::BTreeMap;

use rustc_hash::FxHashMap;

use crate::content::Id;
use crate::locks::Relock;
use crate::{Host, Load, Off};

/// The language the player reads the game in, for a mod's own texts in its
/// dialogs and windows; the fallback on a server.
///
/// The fallback, too, before the client's first text.
///
/// # Examples
///
/// ```
/// use enshwick::i18n::{Texts, language};
///
/// let texts = Texts::parse("[en]\ngreeting = \"Hello\"\n[uk]\ngreeting = \"Привіт\"\n")?;
/// let greeting = texts.fill("greeting", language(), &[]);
/// assert!(!greeting.is_empty());
/// # Ok::<(), enshwick::Off>(())
/// ```
#[must_use]
pub fn language() -> Language {
    crate::host().map_or(Language::FALLBACK, |host| host.language())
}

impl Host {
    /// The language the player reads the game in; see [`language`].
    ///
    /// # Examples
    ///
    /// ```
    /// if let Some(host) = enshwick::host() {
    ///     enshwick::info!("texts in {}", host.language().code());
    /// }
    /// ```
    #[must_use]
    pub fn language(&self) -> Language {
        let language = Language((self.api().language)(self.handle()));
        if language.code().is_empty() {
            Language::FALLBACK
        } else {
            language
        }
    }
}

/// The game's own text of tag `id` in the language the player reads the
/// game in, such as an item's or a survivor's name; a text missing there
/// comes in English, as the game shows it.
///
/// `id` is a text tag's game id, [`Guid::id`](crate::content::Guid::id) of
/// the tag an item's or a template's data names. The text is read from the
/// game's archive and stays valid for the process. `None` for a tag the
/// game lacks, and always on a server, whose archive holds no texts.
///
/// # Examples
///
/// ```
/// use enshwick::i18n::game_text;
///
/// if let Some(text) = game_text(0x8f21_95d5) {
///     enshwick::info!("the game calls it {text}");
/// }
/// ```
#[must_use]
pub fn game_text(id: u32) -> Option<&'static str> {
    game_text_in(id, language())
}

/// The game's own text of tag `id` in `language`, as [`game_text`] reads
/// it; [`Language::FALLBACK`] asks for English.
///
/// # Examples
///
/// ```
/// use enshwick::i18n::{Language, game_text_in};
///
/// let name = game_text_in(0x8f21_95d5, Language::UK_UA);
/// assert!(name.is_none() || name.is_some_and(|n| !n.is_empty()));
/// ```
#[must_use]
pub fn game_text_in(id: u32, language: Language) -> Option<&'static str> {
    crate::host()?.game_text(id, language)
}

impl Host {
    /// The game's own text of tag `id` in `language`; see [`game_text_in`].
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::i18n::Language;
    ///
    /// if let Some(host) = enshwick::host() {
    ///     let _ = host.game_text(0x8f21_95d5, Language::DE_DE);
    /// }
    /// ```
    #[must_use]
    pub fn game_text(&self, id: u32, language: Language) -> Option<&'static str> {
        let api = self.api();
        let mut out = crate::abi::Str::EMPTY;
        if !(api.game_text)(self.handle(), id, language.0, &raw mut out).is_ok() {
            return None;
        }
        // SAFETY: the loader keeps the text for the life of the process.
        unsafe { out.as_str() }
    }
}

/// A game language, as the game numbers them.
///
/// # Examples
///
/// ```
/// use enshwick::i18n::Language;
///
/// assert_eq!(Language::from_code("uk"), Some(Language::UK_UA));
/// assert_eq!(Language::UK_UA.code(), "uk");
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Language(pub u32);

macro_rules! languages {
    ($($name:ident = $id:literal, $code:literal, $doc:literal;)*) => {
        impl Language {
            $(#[doc = $doc] pub const $name: Self = Self($id);)*

            /// Every language the game knows, the fallback first.
            pub const ALL: &[Self] = &[$(Self::$name),*];

            /// The language's code in text files, such as `uk` or `pt-br`.
            ///
            /// # Examples
            ///
            /// See [`Language`].
            #[must_use]
            pub const fn code(self) -> &'static str {
                match self.0 {
                    $($id => $code,)*
                    _ => "",
                }
            }

            /// The language with code `code`, ignoring case.
            ///
            /// # Examples
            ///
            /// See [`Language`].
            #[must_use]
            pub fn from_code(code: &str) -> Option<Self> {
                let code = code.to_ascii_lowercase();
                match code.as_str() {
                    $($code => Some(Self::$name),)*
                    _ => None,
                }
            }
        }
    };
}

languages! {
    FALLBACK = 0, "en", "English, and every language without a text of its own.";
    EN_US = 1, "en-us", "English (United States).";
    EN_GB = 2, "en-gb", "English (United Kingdom).";
    DE_DE = 3, "de", "German.";
    NL_NL = 4, "nl", "Dutch.";
    FR_FR = 5, "fr", "French.";
    IT_IT = 6, "it", "Italian.";
    ES_ES = 7, "es", "Spanish (Spain).";
    ES_MX = 8, "es-mx", "Spanish (Mexico).";
    RU_RU = 9, "ru", "Russian.";
    PL_PL = 10, "pl", "Polish.";
    JA_JP = 11, "ja", "Japanese.";
    ID_ID = 12, "id", "Indonesian.";
    KO_KR = 13, "ko", "Korean.";
    MS_MY = 14, "ms", "Malay.";
    PT_PT = 15, "pt", "Portuguese (Portugal).";
    PT_BR = 16, "pt-br", "Portuguese (Brazil).";
    TH_TH = 17, "th", "Thai.";
    TR_TR = 18, "tr", "Turkish.";
    VI_VN = 19, "vi", "Vietnamese.";
    ZH_CN = 20, "zh-cn", "Chinese (Simplified).";
    ZH_TW = 21, "zh-tw", "Chinese (Traditional).";
    FR_CA = 22, "fr-ca", "French (Canada).";
    ES_419 = 23, "es-419", "Spanish (Latin America).";
    BG_BG = 24, "bg", "Bulgarian.";
    CS_CZ = 25, "cs", "Czech.";
    DA_DK = 26, "da", "Danish.";
    FI_FI = 27, "fi", "Finnish.";
    EL_GR = 28, "el", "Greek.";
    HU_HU = 29, "hu", "Hungarian.";
    NO_NO = 30, "no", "Norwegian.";
    NB_NO = 31, "nb", "Norwegian (Bokmål).";
    RO_RO = 32, "ro", "Romanian.";
    SV_SE = 33, "sv", "Swedish.";
    UK_UA = 34, "uk", "Ukrainian.";
}

/// The key of the mod's own name in its texts: the Mods screen, the join
/// dialog and the status show it in the player's language, and the
/// manifest's `name` where the texts lack it.
///
/// # Examples
///
/// ```
/// use enshwick::i18n::{Language, MOD_NAME, Texts};
///
/// let texts = Texts::parse("[en]\n\"mod.name\" = \"Better Altars\"\n[uk]\n\"mod.name\" = \"Кращі олтарі\"\n")?;
/// assert_eq!(texts.get(MOD_NAME, Language::UK_UA), Some("Кращі олтарі"));
/// # Ok::<(), enshwick::Off>(())
/// ```
pub const MOD_NAME: &str = "mod.name";

/// The key of the sentence on what the mod does in its texts, shown as
/// [`MOD_NAME`] is, the manifest's `description` where the texts lack it.
///
/// # Examples
///
/// ```
/// assert_eq!(enshwick::i18n::MOD_DESCRIPTION, "mod.description");
/// ```
pub const MOD_DESCRIPTION: &str = "mod.description";

/// A mod's texts by language and key.
///
/// # Examples
///
/// ```
/// use enshwick::i18n::{Language, Texts};
///
/// let texts = Texts::parse("[en]\ngreeting = \"Hello\"\n[uk]\ngreeting = \"Привіт\"\n")?;
/// assert_eq!(texts.get("greeting", Language::UK_UA), Some("Привіт"));
/// assert_eq!(texts.get("greeting", Language::DE_DE), Some("Hello"));
/// # Ok::<(), enshwick::Off>(())
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Texts {
    by_language: FxHashMap<Language, BTreeMap<String, String>>,
}

impl Texts {
    /// Texts from TOML: a table per language code, keys to texts.
    ///
    /// # Errors
    ///
    /// [`Off`] for malformed TOML, an unknown language code or a value that
    /// is not text.
    ///
    /// # Examples
    ///
    /// See [`Texts`].
    pub fn parse(toml: &str) -> Result<Self, Off> {
        let tables: BTreeMap<String, BTreeMap<String, String>> =
            toml::from_str(toml).map_err(|e| Off::new(format!("texts: {}", e.message())))?;
        let mut texts = Self::default();
        for (code, entries) in tables {
            let language = Language::from_code(&code)
                .ok_or_else(|| Off::new(format!("texts: unknown language {code:?}")))?;
            texts
                .by_language
                .entry(language)
                .or_default()
                .extend(entries);
        }
        Ok(texts)
    }

    /// Adds `other`'s texts over these.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::i18n::{Language, Texts};
    ///
    /// let mut texts = Texts::parse("[en]\na = \"A\"\n")?;
    /// texts.merge(Texts::parse("[en]\na = \"B\"\n")?);
    /// assert_eq!(texts.get("a", Language::FALLBACK), Some("B"));
    /// # Ok::<(), enshwick::Off>(())
    /// ```
    pub fn merge(&mut self, other: Self) {
        for (language, entries) in other.by_language {
            self.by_language
                .entry(language)
                .or_default()
                .extend(entries);
        }
    }

    /// The text of `key` in `language`, else in English.
    ///
    /// # Examples
    ///
    /// See [`Texts`].
    #[must_use]
    pub fn get(&self, key: &str, language: Language) -> Option<&str> {
        let find = |language| {
            self.by_language
                .get(&language)
                .and_then(|entries| entries.get(key))
                .map(String::as_str)
        };
        find(language).or_else(|| find(Language::FALLBACK))
    }

    /// The text of `key` in `language` with each `{name}` in it replaced by
    /// the value `args` pairs with `name`; the key itself when no language
    /// has a text for it, so a missing text shows rather than vanishes.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::i18n::{Language, Texts};
    ///
    /// let texts = Texts::parse("[en]\nupdate = \"{name}: {from} to {to}\"\n")?;
    /// let line = texts.fill("update", Language::UK_UA, &[("name", "Lanterns"), ("from", "0.1.0"), ("to", "0.2.0")]);
    /// assert_eq!(line, "Lanterns: 0.1.0 to 0.2.0");
    /// assert_eq!(texts.fill("missing", Language::FALLBACK, &[]), "missing");
    /// # Ok::<(), enshwick::Off>(())
    /// ```
    #[must_use]
    pub fn fill(&self, key: &str, language: Language, args: &[(&str, &str)]) -> String {
        let text = self.get(key, language).unwrap_or(key);
        let mut out = String::with_capacity(text.len());
        let mut rest = text;
        while let Some(open) = rest.find('{') {
            out.push_str(&rest[..open]);
            let after = &rest[open + 1..];
            let value = after.find('}').and_then(|close| {
                let name = &after[..close];
                args.iter()
                    .find(|(arg, _)| *arg == name)
                    .map(|(_, value)| (*value, close))
            });
            if let Some((value, close)) = value {
                out.push_str(value);
                rest = &after[close + 1..];
            } else {
                out.push('{');
                rest = after;
            }
        }
        out.push_str(rest);
        out
    }

    /// The texts as TOML, a table per language code, as [`Texts::parse`]
    /// reads them.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::i18n::Texts;
    ///
    /// let texts = Texts::parse("[uk]\ngreeting = \"Привіт\"\n")?;
    /// assert_eq!(Texts::parse(&texts.to_toml())?, texts);
    /// # Ok::<(), enshwick::Off>(())
    /// ```
    #[must_use]
    pub fn to_toml(&self) -> String {
        let tables: BTreeMap<&str, &BTreeMap<String, String>> = self
            .by_language
            .iter()
            .map(|(language, entries)| (language.code(), entries))
            .collect();
        toml::to_string(&tables).unwrap_or_default()
    }

    /// Every language with a text for `key`, and the text, in no set order.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::i18n::Texts;
    ///
    /// let texts = Texts::parse("[en]\ngreeting = \"Hello\"\n[uk]\ngreeting = \"Привіт\"\n")?;
    /// let mut all: Vec<&str> = texts.translations("greeting").map(|(_, text)| text).collect();
    /// all.sort_unstable();
    /// assert_eq!(all, ["Hello", "Привіт"]);
    /// # Ok::<(), enshwick::Off>(())
    /// ```
    pub fn translations<'a>(
        &'a self,
        key: &'a str,
    ) -> impl Iterator<Item = (Language, &'a str)> + 'a {
        self.by_language
            .iter()
            .filter_map(move |(&language, entries)| {
                entries.get(key).map(|t| (language, t.as_str()))
            })
    }

    /// Every language with texts of its own, in the order of
    /// [`Language::ALL`]: the set a test of the texts iterates, so a new
    /// language is a new table in the file and no change to the test.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::i18n::{Language, Texts};
    ///
    /// let texts = Texts::parse("[uk]\na = \"А\"\n[en]\na = \"A\"\n")?;
    /// let languages: Vec<Language> = texts.languages().collect();
    /// assert_eq!(languages, [Language::FALLBACK, Language::UK_UA]);
    /// # Ok::<(), enshwick::Off>(())
    /// ```
    pub fn languages(&self) -> impl Iterator<Item = Language> + '_ {
        Language::ALL
            .iter()
            .copied()
            .filter(|language| self.by_language.contains_key(language))
    }

    /// Each language paired with each key another language has a text for
    /// and it lacks, sorted by language as [`languages`](Self::languages)
    /// gives them, then by key; empty when every language has every text.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::i18n::{Language, Texts};
    ///
    /// let texts = Texts::parse("[en]\na = \"A\"\nb = \"B\"\n[uk]\na = \"А\"\n")?;
    /// assert_eq!(texts.untranslated(), [(Language::UK_UA, "b")]);
    /// # Ok::<(), enshwick::Off>(())
    /// ```
    #[must_use]
    pub fn untranslated(&self) -> Vec<(Language, &str)> {
        let keys: std::collections::BTreeSet<&str> = self
            .by_language
            .values()
            .flat_map(|entries| entries.keys().map(String::as_str))
            .collect();
        self.languages()
            .flat_map(|language| {
                let entries = &self.by_language[&language];
                keys.iter()
                    .filter(|key| !entries.contains_key(**key))
                    .map(move |&key| (language, key))
            })
            .collect()
    }
}

/// The texts each mod, or each content pack in the loader's copy of the
/// API, handed the loader so far.
static HANDED: crate::fresh::Fresh<std::sync::Mutex<Vec<(crate::abi::ModHandle, Texts)>>> =
    crate::fresh::Fresh::new();

impl Load<'_> {
    /// The mod's texts: `embedded`, usually `include_str!("texts.toml")`,
    /// with `mod-configs/<id>.texts.toml` over it when the server has one.
    /// The loader keeps them too, to label the mod's settings on the Mods
    /// screen: `config.<field>` (or the field's `text` key) for a row,
    /// `<key>.doc` for its description and `<key>.<choice>` for a choice.
    ///
    /// # Errors
    ///
    /// [`Off`] when either file is malformed.
    ///
    /// # Examples
    ///
    /// ```
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     let texts = load.texts("[en]\n\"locker.name\" = \"Locker\"\n")?;
    ///     let _ = texts;
    ///     Ok(())
    /// }
    /// ```
    pub fn texts(&mut self, embedded: &str) -> Result<Texts, Off> {
        let mut texts = Texts::parse(embedded)?;
        let data = self.data_dir()?;
        // `<game>/mod-data/<id>` beside `<game>/mod-configs/`.
        let overrides = data
            .file_name()
            .zip(data.parent().and_then(std::path::Path::parent))
            .map(|(id, game)| {
                game.join("mod-configs")
                    .join(format!("{}.texts.toml", id.to_string_lossy()))
            });
        if let Some(path) = overrides {
            match std::fs::read_to_string(&path) {
                Ok(text) => texts.merge(
                    Texts::parse(&text)
                        .map_err(|off| Off::new(format!("{}: {off}", path.display())))?,
                ),
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
                // Such as a file saved as UTF-16 or in a code page.
                Err(error) => return Err(Off::new(format!("{}: {error}", path.display()))),
            }
        }
        let api = self.host().api();
        // The loader keeps the last texts it was given, so it gets all
        // of this mod's, a pack's added to the mod's own.
        let me = self.host().handle();
        let mut handed = HANDED.get_or_init(std::sync::Mutex::default).relock();
        let all = if let Some((_, kept)) = handed.iter_mut().find(|(owner, _)| *owner == me) {
            kept.merge(texts.clone());
            kept.to_toml()
        } else {
            handed.push((me, texts.clone()));
            texts.to_toml()
        };
        let _kept = (api.texts)(me, crate::abi::Str::new(&all));

        Ok(texts)
    }

    /// Gives each game tag the translations of its key, for every language
    /// that has one: `(key, tag)` pairs, such as an item's name tag, each
    /// tag the mod's own content id.
    ///
    /// # Errors
    ///
    /// [`Off`] when the loader refuses a tag's id (see [`Load::declare`]) or
    /// a key has no text at all.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::content::Id;
    ///
    /// const LOCKER_NAME: Id = Id::new("you.lockers:locker.name");
    ///
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     let texts = load.texts("[en]\n\"locker.name\" = \"Locker\"\n[uk]\n\"locker.name\" = \"Шафка\"\n")?;
    ///     load.add_texts(&texts, &[("locker.name", LOCKER_NAME)])
    /// }
    /// ```
    pub fn add_texts(&mut self, texts: &Texts, tags: &[(&str, Id)]) -> Result<(), Off> {
        for &(key, tag) in tags {
            let tag = self.declare(tag)?;
            let mut any = false;
            for (language, text) in texts.translations(key) {
                self.add_text(tag, language, text)?;
                any = true;
            }
            if !any {
                return Err(Off::new(format!("texts: no text for {key:?}")));
            }
        }
        Ok(())
    }
}

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

    #[test]
    fn every_language_round_trips_through_its_code() {
        for &language in Language::ALL {
            assert_eq!(Language::from_code(language.code()), Some(language));
        }
        assert_eq!(Language::from_code("PT-BR"), Some(Language::PT_BR));
        assert_eq!(Language::from_code("xx"), None);
    }

    #[test]
    fn placeholders_take_their_values_and_others_stay() {
        let texts =
            Texts::parse("[en]\na = \"{x} and {y} and {unknown} and {\"\n[uk]\na = \"{y}, {x}\"\n")
                .unwrap();
        let args = [("x", "1"), ("y", "{x}")];
        assert_eq!(
            texts.fill("a", Language::FALLBACK, &args),
            "1 and {x} and {unknown} and {"
        );
        assert_eq!(texts.fill("a", Language::UK_UA, &args), "{x}, 1");
    }

    #[test]
    fn unknown_languages_and_non_text_values_are_errors() {
        assert!(Texts::parse("[xx]\na = \"b\"\n").is_err());
        assert!(Texts::parse("[en]\na = 1\n").is_err());
    }
}