Skip to main content

rpfm_extensions/translator/
mod.rs

1//---------------------------------------------------------------------------//
2// Copyright (c) 2017-2026 Ismael Gutiérrez González. All rights reserved.
3//
4// This file is part of the Rusted PackFile Manager (RPFM) project,
5// which can be found here: https://github.com/Frodo45127/rpfm.
6//
7// This file is licensed under the MIT license, which can be found here:
8// https://github.com/Frodo45127/rpfm/blob/master/LICENSE.
9//---------------------------------------------------------------------------//
10
11//! Mod translation and localization support.
12//!
13//! This module provides tools for managing translations of mod content, making it
14//! easier to localize mods for different languages. It tracks translation status,
15//! detects changes in source text, and supports auto-translation from vanilla data.
16//!
17//! # Overview
18//!
19//! The translation system works by:
20//!
21//! 1. Extracting all translatable strings from a pack's Loc files
22//! 2. Storing translations in a separate JSON file alongside the pack
23//! 3. Tracking which translations need updating when source text changes
24//! 4. Auto-translating from vanilla localisation data where possible
25//!
26//! # Translation Files
27//!
28//! Translations are stored in separate JSON files. Each file contains all source
29//! strings and their translations, along with metadata about translation status.
30//!
31//! # Auto-Translation
32//!
33//! The system can automatically translate strings that exist in the game's vanilla
34//! localisation files. This is useful for mods that reference vanilla content or
35//! use similar terminology.
36//!
37//! # Workflow
38//!
39//! 1. Create a [`PackTranslation`] from a pack
40//! 2. Export to a translation file for external editing
41//! 3. Import completed translations
42//! 4. Generate the final translated Loc file for the pack
43//!
44//! # Output
45//!
46//! Translated strings are output to a Loc file that overrides the original mod's
47//! entries. The filename depends on the game:
48//!
49//! - **Warhammer 1 and newer** (except Thrones): `!!!!!!translated_locs.loc` - loads
50//!   first due to its naming, allowing translations to override the original entries
51//! - **Thrones of Britannia and older games**: `localisation.loc`
52//!
53//! # Example
54//!
55//! ```ignore
56//! use rpfm_extensions::translator::PackTranslation;
57//!
58//! // Create translation from pack
59//! let mut translation = PackTranslation::new(
60//!     &[translations_path],
61//!     &pack,
62//!     "warhammer_3",
63//!     "EN",  // Source language
64//!     "ES",  // Target language (Spanish)
65//!     &dependencies,
66//!     &english_base,
67//!     &local_fixes,
68//! )?;
69//!
70//! // Save translation file
71//! translation.save(&output_path)?;
72//!
73//! // Generate translated Loc file for the pack
74//! let loc_file = translation.generate_loc()?;
75//! ```
76
77use csv::{QuoteStyle, WriterBuilder};
78use getset::{Getters, MutGetters, Setters};
79use itertools::Itertools;
80use rayon::prelude::*;
81use serde::{Serialize as SerdeSerialize, Serializer};
82use serde_derive::{Serialize, Deserialize};
83
84use std::collections::{BTreeMap, HashMap, HashSet};
85use std::fs::{self, DirBuilder, File};
86use std::io::{BufReader, BufWriter, Read, Write};
87use std::path::{Path, PathBuf};
88
89use rpfm_lib::error::{Result, RLibError};
90use rpfm_lib::files::{Container, FileType, loc::Loc, pack::Pack, RFile, RFileDecoded, table::{DecodedData, local::TableInMemory, Table}};
91use rpfm_lib::games::GameInfo;
92use rpfm_lib::schema::*;
93use rpfm_lib::utils::files_from_subdir;
94
95use crate::dependencies::Dependencies;
96
97pub mod hub;
98#[cfg(test)] mod test;
99
100/// Filename for the generated translated Loc file.
101///
102/// The leading exclamation marks ensure this file loads before other Loc files,
103/// allowing translations to override the original mod's strings.
104pub const TRANSLATED_FILE_NAME: &str = "!!!!!!translated_locs.loc";
105
106/// Full path for the translated Loc file within a pack.
107pub const TRANSLATED_PATH: &str = "text/!!!!!!translated_locs.loc";
108
109/// Legacy path for translated Loc files (for backwards compatibility).
110pub const TRANSLATED_PATH_OLD: &str = "text/localisation.loc";
111
112/// Name of the Translation Hub's TSV with the vanilla English texts.
113pub const VANILLA_LOC_NAME_EN: &str = "vanilla_english.tsv";
114
115//-------------------------------------------------------------------------------//
116//                              Enums & Structs
117//-------------------------------------------------------------------------------//
118
119/// Translation data for an entire pack.
120///
121/// Contains all translatable strings from a pack along with their translations
122/// and metadata about translation status.
123///
124/// # Persistence and Format Versioning
125///
126/// This struct is serialized to JSON files for storage. There are currently two
127/// on-disk formats, picked by the [`version`](Self::version) field:
128///
129/// - `0` — legacy format. Per-entry `key`/`value_original`/`value_translated`/
130///   `needs_retranslation`/`removed`; no `aut`, and no `src_lang`, `authors`,
131///   `glossary` or `version` at the root. The user can opt back into this format
132///   from the translator UI to share translations with older tooling.
133/// - `1` — current format. Adds `version`, `src_lang`, `authors`, `glossary` and
134///   `aut`, and uses the shorter per-entry field names (`src`/`dst`/`retr`/`rem`/`aut`).
135///
136/// On load, files without a `version` field are treated as v0 — i.e. existing
137/// translation hubs and legacy local files keep their format unless the user
138/// explicitly upgrades them.
139///
140/// # Parent Translations
141///
142/// When a pack has dependencies, translations from parent mods are also loaded
143/// and used for auto-translation, ensuring consistent terminology across
144/// dependent mods.
145#[derive(Debug, Clone, Getters, MutGetters, Setters, Serialize, Deserialize)]
146#[getset(get = "pub", get_mut = "pub", set = "pub")]
147pub struct PackTranslation {
148
149    /// On-disk format version. See the struct-level docs for the meaning of
150    /// each value. New in-memory translations default to v1; legacy files
151    /// without this field are treated as v0.
152    #[serde(default)]
153    version: u32,
154
155    /// Target language code for translations (e.g., "ES", "DE", "FR").
156    language: String,
157
158    /// Source language code these translations are based on (e.g., "EN").
159    ///
160    /// Missing from the old format; defaults to [`DEFAULT_SRC_LANG`] when loading
161    /// legacy files.
162    #[serde(default = "default_src_lang")]
163    src_lang: String,
164
165    /// Name of the pack these translations belong to.
166    pack_name: String,
167
168    /// Names of the translators who contributed to this translation.
169    ///
170    /// Missing from the old format; defaults to an empty list when loading legacy files.
171    #[serde(default)]
172    authors: Vec<String>,
173
174    /// Per-pack glossary of preferred translations for specific source terms.
175    ///
176    /// Stored as a sorted map (source term → preferred translation) so the
177    /// JSON output is deterministic. v1+ only; dropped when saving as v0.
178    #[serde(default)]
179    glossary: BTreeMap<String, String>,
180
181    /// Map of Loc keys to their translation data.
182    ///
183    /// Keys are the original Loc entry keys from the pack.
184    #[serde(serialize_with = "ordered_map_translations")]
185    translations: HashMap<String, Translation>,
186}
187
188/// Translation entry for a single localizable string.
189///
190/// Tracks both the source and translated text, along with status flags
191/// indicating whether the translation is up-to-date, was generated
192/// automatically, or refers to a string no longer present in the pack.
193///
194/// Field names were shortened in the new format; serde aliases keep
195/// backwards-compatible deserialization of the old field names. The old
196/// per-entry `key` field is no longer stored — the map key in
197/// [`PackTranslation::translations`] is the authoritative identifier — and
198/// extra fields in legacy files are silently ignored.
199#[derive(Debug, Clone, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
200#[getset(get = "pub", get_mut = "pub", set = "pub")]
201pub struct Translation {
202
203    /// Source text in the base language (typically English).
204    ///
205    /// Used to detect when the source text changes, requiring re-translation.
206    #[serde(alias = "value_original")]
207    src: String,
208
209    /// Translated text in the target language.
210    ///
211    /// May be empty if not yet translated.
212    #[serde(alias = "value_translated")]
213    dst: String,
214
215    /// Whether this translation needs review because the source text changed
216    /// after the previous translation.
217    #[serde(alias = "needs_retranslation")]
218    retr: bool,
219
220    /// Whether this string has been removed from the source pack.
221    ///
222    /// Translations for removed strings are kept for reference but marked
223    /// as removed. If the string reappears, it will be flagged for re-translation.
224    #[serde(alias = "removed")]
225    rem: bool,
226
227    /// Whether this translation was generated automatically (e.g. from vanilla
228    /// data) and still needs manual review.
229    ///
230    /// Missing from the old format; defaults to `false` when loading legacy files.
231    #[serde(default)]
232    aut: bool,
233}
234
235/// Current on-disk format version. New translations default to this; legacy
236/// files without a `version` field are still loaded as v0 and saved back as v0
237/// unless the user opts in to the new format from the UI.
238pub const CURRENT_VERSION: u32 = 1;
239
240/// Two-letter source-language code assumed when none is recorded on disk.
241///
242/// Translations have always been authored against the English base, so legacy
243/// files (which predate the `src_lang` field) and freshly created translations
244/// both end up with this value. Uppercase to match how `language` is stored
245/// elsewhere in the translator; not the same thing as `rpfm_lib::games::ENGLISH`,
246/// which is the lowercase identifier used for game data file naming
247/// (e.g. `local_en.pack`).
248pub const DEFAULT_SRC_LANG: &str = "EN";
249
250/// Wire-format counterparts used when saving as legacy v0. We can't reuse the
251/// canonical structs because field names changed and the per-entry `key` field
252/// is no longer stored. Building these on save lets us write the old shape
253/// without polluting [`PackTranslation`] with version-specific serde glue.
254#[derive(Serialize)]
255struct PackTranslationV0Wire<'a> {
256    language: &'a str,
257    pack_name: &'a str,
258    translations: BTreeMap<String, TranslationV0Wire<'a>>,
259}
260
261#[derive(Serialize)]
262struct TranslationV0Wire<'a> {
263    key: String,
264    value_original: &'a str,
265    value_translated: &'a str,
266    needs_retranslation: bool,
267    removed: bool,
268}
269
270//-------------------------------------------------------------------------------//
271//                             Implementations
272//-------------------------------------------------------------------------------//
273
274impl Translation {
275
276    /// This function fills the translation of a line from vanilla or from other lines of the same pack, if possible.
277    ///
278    /// Lines with an empty source always end up with an empty translation, as there is nothing to translate.
279    ///
280    /// # Arguments
281    ///
282    /// * `tr_key` - Loc key of this line.
283    /// * `pack_translations` - Snapshot of every line of the pack, used to reuse translations of identical sources.
284    /// * `base_english` - Vanilla loc in the source language.
285    /// * `base_local_fixes` - Fixes for the vanilla translation, which take priority over it.
286    /// * `base_local_tr` - Vanilla loc in the target language, patched with the parent packs' translations.
287    fn auto_translate(
288        &mut self,
289        tr_key: &str,
290        pack_translations: &HashMap<String, Translation>,
291        base_english: &HashMap<String, String>,
292        base_local_fixes: &HashMap<String, String>,
293        base_local_tr: &HashMap<String, String>
294    ) {
295        if self.rem {
296            return;
297        }
298
299        // Fix incorrectly translated lines.
300        if !self.src.trim().is_empty() && self.dst.trim().is_empty() && !self.retr {
301            self.retr = true;
302        }
303
304        // Empty source: trivially "translate" by copying, dropping any stale translation. Not flagged
305        // as auto because it requires no manual review.
306        else if self.src.trim().is_empty() {
307            self.dst = self.src.to_owned();
308            self.retr = false;
309            self.aut = false;
310        }
311
312        // If the value is unchanged from english, just copy the vanilla translation. This is a patch for
313        // packs not using the optimizer, because the optimizer removes these entries.
314        else if let Some(vanilla_data) = base_english.get(tr_key) {
315            if self.src == *vanilla_data {
316                if let Some(vanilla_data) = base_local_fixes.get(tr_key).filter(|v| !v.trim().is_empty()) {
317                    self.dst = vanilla_data.to_owned();
318                    self.retr = false;
319                    self.aut = false;
320                } else if let Some(vanilla_data) = base_local_tr.get(tr_key).filter(|v| !v.trim().is_empty()) {
321                    self.dst = vanilla_data.to_owned();
322                    self.retr = false;
323                    self.aut = false;
324                }
325            }
326        }
327
328        // Reuse the translation of an identical english value with a different key. This has no context and
329        // may give wrong translations, so it's only done for lines not yet translated.
330        else if self.dst.trim().is_empty() || self.retr {
331            if let Some((key, _)) = base_english.iter().find(|(_, value)| **value == self.src) {
332                if let Some(value_tr) = base_local_fixes.get(key).filter(|v| !v.trim().is_empty()) {
333                    self.dst = value_tr.to_owned();
334                    self.retr = false;
335                    self.aut = true;
336                } else if let Some(value_tr) = base_local_tr.get(key).filter(|v| !v.trim().is_empty()) {
337                    self.dst = value_tr.to_owned();
338                    self.retr = false;
339                    self.aut = true;
340                }
341            } else if let Some((_, value_tr)) = pack_translations.iter()
342                .find(|(_, other)| other.src == self.src && !other.retr && self.retr && !other.dst.trim().is_empty()) {
343                self.dst = value_tr.dst.to_owned();
344                self.retr = false;
345                self.aut = true;
346            }
347        }
348    }
349}
350
351impl PackTranslation {
352
353    #[allow(clippy::too_many_arguments)]
354    pub fn new(paths: &[PathBuf], pack: &Pack, game_key: &str, src_lang: &str, language: &str, dependencies: &Dependencies, base_english: &HashMap<String, String>, base_local_fixes: &HashMap<String, String>) -> Result<Self> {
355        let mut translations = Self::load(paths, &pack.disk_file_name(), game_key, src_lang, language).unwrap_or_else(|_| {
356            // No existing file → new translation. `Default::default()` already gives us
357            // version=1; we stamp the language, source language and pack name on top.
358            Self {
359                language: language.to_owned(),
360                src_lang: src_lang.to_owned(),
361                pack_name: pack.disk_file_name(),
362                ..Default::default()
363            }
364        });
365
366        // Legacy files written before `src_lang` existed come through with an empty value.
367        // Stamp the caller's choice so the saved file always carries a meaningful source language.
368        if translations.src_lang.is_empty() {
369            translations.src_lang = src_lang.to_owned();
370        }
371
372        // If the pack has dependencies, we have to try to load their translations too, then patch the live dependencies with them.
373        // Otherwise, we'll have a situation where data is compared and imported from the wrong language.
374        let mut parent_tr = vec![];
375        for (_, pack_name) in pack.dependencies() {
376            if let Ok(ptr) = Self::load(paths, pack_name, game_key, src_lang, language) {
377                parent_tr.push(ptr);
378            }
379        }
380
381        // Once we got the previous translation loaded, get the files to translate from the Pack, updating our translation.
382        let mut locs = pack.files_by_type(&[FileType::Loc]);
383        let merged_loc = Self::sort_and_merge_locs_for_translation(&mut locs)?;
384        let merged_loc_data = merged_loc.data();
385        let merged_loc_hash = merged_loc_data
386            .par_iter()
387            .map(|x| (x[0].data_to_string(), x[1].data_to_string()))
388            .collect::<HashMap<_,_>>();
389
390        // Once we have the clean list of loc entries we have in our Pack, we need to update the translation with it.
391        // First we do a pass to mark all removed translations as such. This is separated from the rest because this pass is way slower than the rest.
392        for (tr_key, tr) in translations.translations_mut() {
393            let was_removed = tr.rem;
394            tr.rem = !merged_loc_hash.contains_key(&**tr_key);
395
396            // If the line has been removed, unmark it for translation.
397            // If the line has been re-added, only flag for retranslation if the original value changed or there's no translation yet.
398            if tr.rem {
399                tr.retr = false;
400            } else if was_removed {
401                if let Some(current_value) = merged_loc_hash.get(&**tr_key) {
402                    tr.retr = tr.dst.is_empty() || *current_value != tr.src;
403                }
404            }
405        }
406
407        // Next, we update the translations data with the loc data of the merged loc.
408        for row in merged_loc.data().iter() {
409            let key = row[0].data_to_string();
410            let value = row[1].data_to_string();
411
412            match translations.translations.get_mut(&*key) {
413                Some(tr) => {
414                    if value != tr.src {
415                        tr.src = value.to_string();
416                        tr.retr = true;
417                        // Source changed — any prior auto-translation is no longer trustworthy.
418                        tr.aut = false;
419                    }
420                },
421
422                None => {
423                    let tr = Translation {
424                        src: value.to_string(),
425                        dst: String::new(),
426                        retr: true,
427                        rem: false,
428                        aut: false,
429                    };
430
431                    translations.translations.insert(key.to_string(), tr);
432                }
433            }
434        }
435
436        // Lastly, we do an auto-translation pass. We have two copies of base local: one normal and one patched with parent translations.
437        // This is needed because the base localisation data doesn't have the translation data for parent mods included.
438        let mut base_local_tr = dependencies.localisation_data().clone();
439        for ptr in parent_tr {
440            for (key, val) in ptr.translations() {
441                if !*val.retr() && !val.dst().is_empty() {
442                    if let Some(ptr_val) = base_local_tr.get_mut(key) {
443                        *ptr_val = val.dst().to_string();
444                    }
445                }
446            }
447        }
448
449        let tr_copy = translations.translations().clone();
450        translations.translations_mut().par_iter_mut().for_each(|(tr_key, tr)| {
451            tr.auto_translate(tr_key, &tr_copy, base_english, base_local_fixes, &base_local_tr);
452        });
453
454        Ok(translations)
455    }
456
457    // TODO: Move this to the normal merge functions.
458    pub fn sort_and_merge_locs_for_translation(locs: &mut [&RFile]) -> Result<Loc> {
459
460        // We need them in a specific order so the file priority removes unused loc entries from the translation.
461        locs.sort_by(|a, b| a.path_in_container_raw().cmp(b.path_in_container_raw()));
462        let locs = locs.iter()
463            .filter(|file| {
464                if let Some(name) = file.file_name() {
465                    !name.is_empty() && name != TRANSLATED_FILE_NAME
466                } else {
467                    false
468                }
469            })
470            .filter_map(|file| if let Ok(RFileDecoded::Loc(loc)) = file.decoded() { Some(loc) } else { None })
471            .collect::<Vec<_>>();
472
473        // Once we merge all the locs in the correct order, remove duplicated keys except the first one.
474        let mut merged_loc = Loc::merge(&locs)?;
475        let mut keys_found = HashSet::new();
476        let mut rows_to_delete = vec![];
477        for (index, row) in merged_loc.data().iter().enumerate() {
478            if keys_found.contains(&row[0].data_to_string()) {
479                rows_to_delete.push(index);
480            } else {
481                keys_found.insert(row[0].data_to_string());
482            }
483        }
484
485        rows_to_delete.reverse();
486        for row in &rows_to_delete {
487            merged_loc.data_mut().remove(*row);
488        }
489
490        Ok(merged_loc)
491    }
492
493    /// Name of the TSV with the vanilla texts of a source language.
494    ///
495    /// # Arguments
496    ///
497    /// * `src_lang` - Source language code (e.g. "EN", "SP").
498    ///
499    /// # Returns
500    ///
501    /// [`VANILLA_LOC_NAME_EN`] for English, `vanilla_{src_lang}.tsv` for any other language.
502    pub fn vanilla_loc_file_name(src_lang: &str) -> String {
503        if src_lang.eq_ignore_ascii_case(DEFAULT_SRC_LANG) {
504            VANILLA_LOC_NAME_EN.to_owned()
505        } else {
506            format!("vanilla_{}.tsv", src_lang.to_lowercase())
507        }
508    }
509
510    /// Generates the vanilla texts TSV of a language from the game's locale packs.
511    ///
512    /// The file is kept so it can still be used after the game stops shipping that language,
513    /// and it's only regenerated when the locale packs are newer than it.
514    ///
515    /// # Arguments
516    ///
517    /// * `game` - Game the locale packs belong to.
518    /// * `game_path` - Path of the game's installation.
519    /// * `src_lang` - Language code of the locale packs to read (e.g. "SP").
520    /// * `dest_folder` - Folder where the TSV is written.
521    ///
522    /// # Returns
523    ///
524    /// `true` if the game has locale packs for the language (so the TSV is up to date), `false` otherwise.
525    ///
526    /// # Errors
527    ///
528    /// Returns an error if the game's data folder can't be read, or if the packs can't be read or the TSV written.
529    pub fn generate_vanilla_loc(game: &GameInfo, game_path: &Path, src_lang: &str, dest_folder: &Path) -> Result<bool> {
530        let packs = Self::locale_pack_paths(&game.data_path(game_path)?, src_lang)?;
531        if packs.is_empty() {
532            return Ok(false);
533        }
534
535        let dest_path = dest_folder.join(Self::vanilla_loc_file_name(src_lang));
536        if let Ok(generated) = fs::metadata(&dest_path).and_then(|meta| meta.modified()) {
537            let newest_pack = packs.iter()
538                .filter_map(|path| fs::metadata(path).and_then(|meta| meta.modified()).ok())
539                .max();
540
541            if newest_pack.is_some_and(|newest_pack| newest_pack <= generated) {
542                return Ok(true);
543            }
544        }
545
546        let mut pack = Pack::read_and_merge(&packs, game, true, false, false)?;
547        pack.files_by_type_mut(&[FileType::Loc]).par_iter_mut().for_each(|file| {
548            let _ = file.decode(&None, true, false);
549        });
550
551        let mut locs = pack.files_by_type(&[FileType::Loc]);
552        let merged_loc = Self::sort_and_merge_locs_for_translation(&mut locs)?;
553
554        // Written to a temp file first, so an interrupted write can't leave a truncated TSV that looks up to date.
555        DirBuilder::new().recursive(true).create(dest_folder)?;
556        let temp_path = dest_path.with_extension("tsv.tmp");
557        let mut writer = WriterBuilder::new()
558            .delimiter(b'\t')
559            .quote_style(QuoteStyle::Never)
560            .has_headers(false)
561            .flexible(true)
562            .from_path(&temp_path)?;
563
564        merged_loc.tsv_export(&mut writer, TRANSLATED_PATH_OLD)?;
565        drop(writer);
566        fs::rename(&temp_path, &dest_path)?;
567
568        Ok(true)
569    }
570
571    /// Paths of the game's locale packs for a language (`local_{lang}.pack`, `local_{lang}_*.pack`), sorted.
572    ///
573    /// Linux ports keep them in `localisation/{lang}/` instead of directly in the data folder.
574    fn locale_pack_paths(data_path: &Path, lang: &str) -> Result<Vec<PathBuf>> {
575        let lang = lang.to_lowercase();
576        let prefix = format!("local_{lang}");
577        let mut files = files_from_subdir(data_path, false)?;
578
579        let localisation_path = data_path.join("localisation").join(&lang);
580        if localisation_path.is_dir() {
581            files.extend(files_from_subdir(&localisation_path, false)?);
582        }
583
584        let mut paths = files.into_iter()
585            .filter(|path| {
586                let name = path.file_name().map(|name| name.to_string_lossy().to_lowercase()).unwrap_or_default();
587                name.ends_with(".pack") && name.strip_prefix(&prefix).is_some_and(|rest| rest.starts_with('.') || rest.starts_with('_'))
588            })
589            .collect::<Vec<_>>();
590
591        paths.sort();
592        Ok(paths)
593    }
594
595    /// This function applies a [PackTranslation] to a Pack.
596    pub fn apply(&self, _pack: &mut Pack) -> Result<()> {
597        todo!()
598    }
599
600    /// This function loads a [PackTranslation] to memory from either a local json file, or a remote one.
601    ///
602    /// Files written in the old format (with `key`, `value_original`, `value_translated`,
603    /// `needs_retranslation`, `removed` and without `src_lang`/`authors`/`glossary`/`aut`) are accepted
604    /// transparently via serde aliases and field defaults — no explicit version probing needed.
605    ///
606    /// On-disk layout:
607    /// - v1+ → `{game_key}/{pack_name}/{src_lang}-{language}.json`.
608    /// - v0  → `{game_key}/{pack_name}/{language}.json` (no source language in the path, since
609    ///   v0 implicitly assumed English).
610    ///
611    /// `load_json` will probe both paths in that order so users who upgrade RPFM keep finding
612    /// their existing translations even if they were saved before this refactor.
613    pub fn load(paths: &[PathBuf], pack_name: &str, game_key: &str, src_lang: &str, language: &str) -> Result<Self> {
614        for path in paths {
615            match Self::load_json(path, pack_name, game_key, src_lang, language) {
616                Ok(mut tr) => return {
617                    for trad in tr.translations_mut() {
618                        trad.1.dst = trad.1.dst.replace("\n||\n", "||");
619                        trad.1.dst = trad.1.dst.replace("\r", "\\\\r");
620                        trad.1.dst = trad.1.dst.replace("\n", "\\\\n");
621                        trad.1.dst = trad.1.dst.replace("\t", "\\\\t");
622                    }
623                    Ok(tr)
624                },
625                Err(_) => continue,
626            }
627        }
628
629        Err(RLibError::TranslatorCouldNotLoadTranslation)
630    }
631
632    fn load_json(path: &Path, pack_name: &str, game_key: &str, src_lang: &str, language: &str) -> Result<Self> {
633        // v1 layout encodes both source and target language in the filename. v0 layout, which
634        // predates non-EN sources, only used the target language. Probe v1 first; fall back to
635        // v0 only when sourcing from EN, since a v0 file can't possibly carry a non-EN source.
636        let v1_path = path.join(format!("{game_key}/{pack_name}/{src_lang}-{language}.json"));
637        let v0_path = path.join(format!("{game_key}/{pack_name}/{language}.json"));
638        let chosen = if v1_path.is_file() {
639            v1_path
640        } else if src_lang.eq_ignore_ascii_case("EN") && v0_path.is_file() {
641            v0_path
642        } else {
643            return Err(RLibError::TranslatorCouldNotLoadTranslation);
644        };
645
646        let mut file = BufReader::new(File::open(chosen)?);
647        let mut data = Vec::with_capacity(file.get_ref().metadata()?.len() as usize);
648        file.read_to_end(&mut data)?;
649
650        // Peek at the JSON to determine the version before deserialising. We need a different
651        // default for "missing version field in file" (= v0, legacy) versus "freshly created
652        // in-memory PackTranslation" (= v1, current). Serde defaults can only express one of
653        // those, so we resolve it manually here.
654        let value: serde_json::Value = serde_json::from_slice(&data)?;
655        let version = value.get("version").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
656        let mut pack_tr: Self = serde_json::from_value(value)?;
657        pack_tr.version = version;
658        Ok(pack_tr)
659    }
660
661    /// Name of the file this translation is saved as, which depends on its format version.
662    ///
663    /// # Returns
664    ///
665    /// `{src_lang}-{language}.json` for v1+, or the legacy `{language}.json` for v0.
666    pub fn file_name(&self) -> String {
667        if self.version == 0 {
668            format!("{}.json", self.language)
669        } else {
670            format!("{}-{}.json", self.src_lang, self.language)
671        }
672    }
673
674    /// This function saves a [PackTranslation] from memory to a `.json` file with the provided path.
675    ///
676    /// The on-disk format depends on [`Self::version`]: 0 writes the legacy shape, 1 (or higher)
677    /// writes the current shape. Downgrading v1 → v0 drops fields that don't exist in v0
678    /// (`src_lang`, `authors`, `glossary` and the per-entry `aut` flag).
679    ///
680    /// The filename also depends on the version: v1+ uses `{src_lang}-{language}.json` so
681    /// translations from different source languages live side-by-side; v0 keeps the legacy
682    /// `{language}.json` because the old format had no concept of source language.
683    pub fn save(&mut self, path: &Path, game_key: &str) -> Result<()> {
684        let folder = path.join(format!("{}/{}", game_key, self.pack_name));
685        let path = folder.join(self.file_name());
686
687        // Make sure the path exists to avoid problems with updating schemas.
688        DirBuilder::new().recursive(true).create(&folder)?;
689
690        // Switching between v0 and v1 moves an EN-sourced translation between the two filenames, so remove
691        // the stale one. Non-EN sources never have a v0 file, and `{language}.json` belongs to the EN one.
692        if self.src_lang.eq_ignore_ascii_case(DEFAULT_SRC_LANG) {
693            let other_filename = if self.version == 0 {
694                format!("{}-{}.json", self.src_lang, self.language)
695            } else {
696                format!("{}.json", self.language)
697            };
698
699            let other_path = folder.join(other_filename);
700            if other_path.is_file() {
701                std::fs::remove_file(&other_path)?;
702            }
703        }
704
705        let json = if self.version == 0 {
706            // Materialize the v0 wire shape from current data. The per-entry `aut` flag is
707            // dropped silently — there's no corresponding concept in v0.
708            let translations = self.translations.iter()
709                .map(|(key, tr)| (key.clone(), TranslationV0Wire {
710                    key: key.clone(),
711                    value_original: tr.src(),
712                    value_translated: tr.dst(),
713                    needs_retranslation: *tr.retr(),
714                    removed: *tr.rem(),
715                }))
716                .collect::<BTreeMap<_, _>>();
717
718            let wire = PackTranslationV0Wire {
719                language: &self.language,
720                pack_name: &self.pack_name,
721                translations,
722            };
723
724            serde_json::to_string_pretty(&wire)?
725        } else {
726            serde_json::to_string_pretty(&self)?
727        };
728
729        let mut file = BufWriter::new(File::create(&path)?);
730        file.write_all(json.as_bytes())?;
731        Ok(())
732    }
733
734    pub fn definition() -> Definition {
735        // We put the booleans first because they may act as a kind of filter.
736        Definition::new_with_fields(0, &[
737            Field { name: "key".to_string(), field_type: FieldType::StringU8, is_key: true, ..Default::default() },
738            Field { name: "retr".to_string(), field_type: FieldType::Boolean, ..Default::default() },
739            Field { name: "rem".to_string(), field_type: FieldType::Boolean, ..Default::default() },
740            Field { name: "aut".to_string(), field_type: FieldType::Boolean, ..Default::default() },
741            Field { name: "src".to_string(), field_type: FieldType::StringU8, ..Default::default() },
742            Field { name: "dst".to_string(), field_type: FieldType::StringU8, ..Default::default() },
743        ], &[], None)
744    }
745
746    pub fn from_table(&mut self, table: &TableInMemory) -> Result<()> {
747        self.translations_mut().clear();
748
749        for row in table.data().iter() {
750            let mut tr = Translation::default();
751            let mut key = String::new();
752
753            if let DecodedData::StringU8(ref data) = row[0] {
754                key = data.to_owned();
755            }
756
757            if let DecodedData::Boolean(data) = row[1] {
758                tr.set_retr(data);
759            }
760
761            if let DecodedData::Boolean(data) = row[2] {
762                tr.set_rem(data);
763            }
764
765            if let DecodedData::Boolean(data) = row[3] {
766                tr.set_aut(data);
767            }
768
769            if let DecodedData::StringU8(ref data) = row[4] {
770                tr.set_src(data.to_owned());
771            }
772
773            if let DecodedData::StringU8(ref data) = row[5] {
774                tr.set_dst(data.to_owned());
775            }
776
777            self.translations_mut().insert(key, tr);
778        }
779
780        Ok(())
781    }
782
783    pub fn to_table(&self) -> Result<TableInMemory> {
784        let definition = Self::definition();
785        let mut table = TableInMemory::new(&definition, None, "");
786
787        // Due to bugs in the table filters, we pre-sort the data by putting stuff that needs to be retranslated at the start.
788        let data = self.translations()
789            .iter()
790            .sorted_by(|(k1, _), (k2, _)| Ord::cmp(k1, k2))
791            .sorted_by(|(_, tr1), (_, tr2)| Ord::cmp(tr2.retr(), tr1.retr()))
792            .map(|(key, tr)| vec![
793                DecodedData::StringU8(key.to_owned()),
794                DecodedData::Boolean(*tr.retr()),
795                DecodedData::Boolean(*tr.rem()),
796                DecodedData::Boolean(*tr.aut()),
797                DecodedData::StringU8(tr.src().to_owned()),
798                DecodedData::StringU8(tr.dst().to_owned()),
799            ]).collect::<Vec<_>>();
800
801        table.set_data(&data)?;
802        Ok(table)
803    }
804
805    /// Definition of the per-pack glossary table, used to drive the UI table view.
806    ///
807    /// The glossary is a flat two-column table: a source term (used as the key) and the
808    /// preferred translation for it.
809    pub fn glossary_definition() -> Definition {
810        Definition::new_with_fields(0, &[
811            Field { name: "source".to_string(), field_type: FieldType::StringU8, is_key: true, ..Default::default() },
812            Field { name: "translation".to_string(), field_type: FieldType::StringU8, ..Default::default() },
813        ], &[], None)
814    }
815
816    /// Materialize the glossary as an editable [`TableInMemory`] for the UI.
817    pub fn glossary_to_table(&self) -> Result<TableInMemory> {
818        let definition = Self::glossary_definition();
819        let mut table = TableInMemory::new(&definition, None, "");
820
821        // BTreeMap iteration is already sorted, which matches what we want in the UI.
822        let data = self.glossary()
823            .iter()
824            .map(|(src, dst)| vec![
825                DecodedData::StringU8(src.to_owned()),
826                DecodedData::StringU8(dst.to_owned()),
827            ]).collect::<Vec<_>>();
828
829        table.set_data(&data)?;
830        Ok(table)
831    }
832
833    /// Replace the glossary with the contents of `table`. Empty source cells are dropped so a
834    /// trailing blank row left over from the UI doesn't end up in the saved JSON.
835    pub fn glossary_from_table(&mut self, table: &TableInMemory) -> Result<()> {
836        self.glossary_mut().clear();
837
838        for row in table.data().iter() {
839            let src = match row.first() {
840                Some(DecodedData::StringU8(s)) => s.trim().to_owned(),
841                _ => continue,
842            };
843            if src.is_empty() {
844                continue;
845            }
846            let dst = match row.get(1) {
847                Some(DecodedData::StringU8(s)) => s.to_owned(),
848                _ => String::new(),
849            };
850            self.glossary_mut().insert(src, dst);
851        }
852
853        Ok(())
854    }
855}
856
857impl Default for PackTranslation {
858    fn default() -> Self {
859        Self {
860            version: CURRENT_VERSION,
861            language: String::new(),
862            src_lang: default_src_lang(),
863            pack_name: String::new(),
864            authors: Vec::new(),
865            glossary: BTreeMap::new(),
866            translations: HashMap::new(),
867        }
868    }
869}
870
871/// Default source language used when loading translation files that don't
872/// declare one (i.e. files written before `src_lang` existed). Exists as a
873/// function rather than a `&str` because `#[serde(default = "...")]` takes a
874/// function path; the actual value lives in [`DEFAULT_SRC_LANG`].
875fn default_src_lang() -> String {
876    DEFAULT_SRC_LANG.to_owned()
877}
878
879/// Special serializer function to sort the translations HashMap before serializing.
880fn ordered_map_translations<S>(value: &HashMap<String, Translation>, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, {
881    let ordered: BTreeMap<_, _> = value.iter().collect();
882    ordered.serialize(serializer)
883}