Skip to main content

bilingua_model/profile/
mod.rs

1//! Profiles: named sets of choices one consumer of Bilingua needs, kept out of the general API. There is one,
2//! [`locos`]: what the Localization OS adapter needs to give LocOS the files and ids it had before Bilingua.
3//!
4//! A caller switches a profile on with `ExtractOptions::with_profile("locos")` (and `MergeOptions` from
5//! [`Profile::merge_options`]); the `bilingua` facade refuses a name [`find`] does not know. Format crates may switch
6//! behaviour on [`ExtractOptions::is_profile`] / [`MergeOptions::is_profile`] (Track D adds the per-format LocOS
7//! behaviours that way); [`annotate`] adds what the profile promises to every unit after extraction.
8//!
9//! [`tokens`] converts inline codes to and from the text tokens Localization OS uses, one token per tag.
10
11use crate::{CodeData, Document, Error, ExtractOptions, Inline, MergeOptions, OutputEncoding, TagKind, Unit};
12use serde::Serialize;
13
14pub mod tokens;
15
16/// The Localization OS profile's name.
17pub const LOCOS: &str = "locos";
18/// Its version: bumped when what the profile produces changes, so the adapter can tell stored documents apart.
19pub const LOCOS_VERSION: u32 = 1;
20/// `UnitContext::extra` key with the unit's LocOS paragraph index (`p_index`), set under the LocOS profile by the
21/// formats that have one. Left unset where Bilingua cannot give LocOS's number yet (the adapter then numbers by
22/// position).
23pub const P_INDEX: &str = "locos.p_index";
24/// `UnitContext::extra` key with the unit's LocOS style (`a11y:*`, `meta:*`, ...), set under the LocOS profile by
25/// the formats that have one; unset otherwise.
26pub const STYLE: &str = "locos.style";
27/// `UnitContext::extra` key, LocOS profile: how many images LocOS's accessibility scan anchors at this unit
28/// (LocOS `skeleton["a11y_images"]["images"]` is the sum over the units). Unset: none.
29pub const A11Y_IMAGES: &str = "locos.a11y_images";
30/// `UnitContext::extra` key, LocOS profile: the images anchored at this unit whose alt text is empty, one `where`
31/// (the image's file name) per line, in file order (LocOS `missing_alt` entries of kind `empty`). Unset: none.
32pub const A11Y_EMPTY_ALT: &str = "locos.a11y_empty_alt";
33/// `UnitContext::extra` key, LocOS profile: every missing-alt finding anchored at this unit, of both kinds, as a JSON
34/// list of `{"kind": "missing" | "empty", "where": <image name>}` in file order (LocOS `missing_alt` entries; their
35/// `unit` is this unit's `p_index`). Set by DOCX; unset: none.
36pub const A11Y_MISSING_ALT: &str = "locos.a11y_missing_alt";
37
38/// A named profile and its version.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40#[non_exhaustive]
41pub struct Profile {
42    /// Its name (`"locos"`).
43    pub name: &'static str,
44    /// Its version.
45    pub version: u32,
46}
47
48/// The Localization OS profile.
49pub fn locos() -> Profile {
50    Profile { name: LOCOS, version: LOCOS_VERSION }
51}
52
53/// The oldest version of the LocOS profile this release can still produce on request. A release that bumps
54/// [`LOCOS_VERSION`] keeps the old behaviour reachable (`resolve("locos@1")`), the way LocOS keeps its own walk and
55/// reading stamps, so a document stored under the old version still rebuilds; it raises this only when an old version
56/// cannot be replayed any more, and the adapter then asks for a re-import.
57pub const LOCOS_OLDEST_VERSION: u32 = 1;
58
59/// Every profile Bilingua knows.
60pub fn profiles() -> Vec<Profile> {
61    vec![locos()]
62}
63
64/// The profile with this name.
65pub fn find(name: &str) -> Option<Profile> {
66    profiles().into_iter().find(|p| p.name == name)
67}
68
69/// The profile a caller asks for, at a version: `spec` is a name (`"locos"`) or a name and a version
70/// (`"locos@1"`); `version`, when given, must agree with a version in `spec`. No version means the current one. An
71/// unknown name is `Error::UnknownProfile`; a version this release cannot produce (newer than the current one, or
72/// older than the oldest it replays) is `Error::ParserVersion`, so the caller can ask for a re-import.
73pub fn resolve(spec: &str, version: Option<u32>) -> Result<Profile, Error> {
74    let (name, in_spec) = match spec.split_once('@') {
75        Some((n, v)) => {
76            let v: u32 = v.parse().map_err(|_| Error::UnknownProfile(spec.to_string()))?;
77            (n, Some(v))
78        }
79        None => (spec, None),
80    };
81    let current = find(name).ok_or_else(|| Error::UnknownProfile(spec.to_string()))?;
82    let want = match (in_spec, version) {
83        (Some(a), Some(b)) if a != b => return Err(Error::UnknownProfile(format!("{spec} (asked for version {b})"))),
84        (a, b) => a.or(b).unwrap_or(current.version),
85    };
86    if !current.reads(want) {
87        return Err(Error::ParserVersion {
88            found: format!("profile {name} version {want}"),
89            expected: format!("profile {name} versions {} to {}", current.oldest(), current.version),
90        });
91    }
92    Ok(Profile { name: current.name, version: want })
93}
94
95/// Refuses a profile name Bilingua does not know (`Error::UnknownProfile`); `None` is fine.
96pub fn check(name: Option<&str>) -> Result<(), Error> {
97    match name {
98        Some(n) if find(n).is_none() => Err(Error::UnknownProfile(n.to_string())),
99        _ => Ok(()),
100    }
101}
102
103/// Formats whose files Localization OS writes back in their own encoding (UTF-16 included) rather than as UTF-8:
104/// ini, strings and dxf; plain text (LocOS `encode_like`: its BOM, UTF-16, or Windows-1252 when the text fits);
105/// properties (an ISO-8859-1 file stays ISO-8859-1, `\uXXXX` for the rest). The LocOS PO and subtitle writers keep
106/// the file's encoding themselves. XAML (LocOS `xaml_filter`: a UTF-16 file keeps its BOM and UTF-16, a declared
107/// legacy charset stays, with a character reference for what it cannot hold) and resjson (`resjson_filter`: the
108/// UTF-16 BOM and code units kept) too, and the CAT XML files whose LocOS writer splices the translation into the
109/// file's own text and encodes it back in the file's codec (`ttx_filter.build_ttx`, `wordfast.build_txml`,
110/// `cat_xliff.build_units` for TXLF): a UTF-16 TTX, TXML or TXLF stays UTF-16 with its BOM. W5: HTML (LocOS
111/// `encode_like`: a page in a declared legacy code page goes back in it, its meta charset too, when every character
112/// fits, else UTF-8), XSLT (`xslt_filter`: its UTF-16 or legacy codec, a character reference for what it cannot hold)
113/// and the HTML Help files (`htmlhelp_filter`: the source's ANSI code page, a localized build the target's, a
114/// character neither holds refused).
115/// Wave 6 (B-SIDE rc-1,
116/// pl-2, csv-1, csv-2, xtg-1): rc (`rc_filter._encode`: UTF-16 kept, an ANSI or declared page kept when the text
117/// fits, else UTF-8 with its `#pragma code_page` set to 65001), plist (`apple_filter`: a UTF-16 plist stays UTF-16),
118/// csv and tsv (`csv_filter`: the code page when every character fits, else UTF-8 with a BOM; UTF-16 kept) and
119/// XPress Tags (`quark_tags_filter`: UTF-16 and the legacy pages kept, else UTF-8 with `<e9>`).
120const LOCOS_KEEPS_ENCODING: &[&str] = &[
121    "ini", "strings", "dxf", "txt", "properties", "xaml", "resjson", "ttx", "txml", "txlf", "html", "xslt", "hhc", "hhk", "hhp", "rc", "plist", "csv", "tsv", "xtg",
122];
123
124impl Profile {
125    /// The oldest version of this profile the release can still produce.
126    pub fn oldest(&self) -> u32 {
127        match self.name {
128            LOCOS => LOCOS_OLDEST_VERSION,
129            _ => self.version,
130        }
131    }
132
133    /// True when this release can produce version `version` of the profile (the current one or an older one it
134    /// still replays).
135    pub fn reads(&self, version: u32) -> bool {
136        let current = find(self.name).map_or(self.version, |p| p.version);
137        (self.oldest()..=current).contains(&version)
138    }
139
140    /// Extraction options with this profile switched on.
141    pub fn extract_options(&self) -> ExtractOptions {
142        ExtractOptions::new().with_profile(self.name)
143    }
144
145    /// The merge options this profile uses for a document of `format` (a filter id). Localization OS: UTF-8 out,
146    /// except for the formats it writes in their own encoding (ini, strings, dxf, txt, properties, xaml, resjson, ttx,
147    /// txml, txlf, html, xslt, hhc, hhk, hhp, rc, plist, csv, tsv and xtg: `Keep`), and the target language
148    /// stamped and plurals filled even when nothing is translated (lead decision 11-04).
149    pub fn merge_options(&self, format: &str) -> MergeOptions {
150        let enc = if LOCOS_KEEPS_ENCODING.contains(&format) { OutputEncoding::Keep } else { OutputEncoding::Utf8 };
151        MergeOptions::new().with_output_encoding(enc).with_stamp_target_always(true).with_profile(self.name)
152    }
153}
154
155/// What the profile adds to an extracted document: under the LocOS profile, `context.extra[P_INDEX]` on every unit
156/// whose format knows LocOS's paragraph index (odf, Qt ts and wxl from their `p_index`, icml from its paragraph
157/// index, idml from its `p<n>` unit ids); the inline codes LocOS keeps as unit text turned back into that text (key
158/// and value formats, JSON, PO, ARB placeholders, FTL placeables); `context.style` cleared where LocOS has none and
159/// `locos.style` set where it has one (dtd; ODF `heading` and `comment`, its paragraph styles cleared). Nothing for
160/// other profiles. The `bilingua` facade calls this.
161pub fn annotate(doc: &mut Document, profile: Option<&str>) {
162    if profile != Some(LOCOS) {
163        return;
164    }
165    let format = doc.format.clone();
166    for u in &mut doc.units {
167        // BILI-118 (unit model step 5): code types and attrs stay off under the LocOS profile, so its dicts keep
168        // today's shape (design section 4, rule 7)
169        for c in u.codes.values_mut() {
170            c.clear_typing();
171        }
172        // structure roles (unit model step 4) are not part of what LocOS reads: the format crates leave them unset
173        // under the profile, and this keeps any that slipped through out of LocOS's dicts
174        u.context.role = None;
175        u.context.level = None;
176        // plural groups (unit model step 6) likewise: no crate fills them under the profile; any that slipped
177        // through stay out of LocOS's dicts
178        u.plural = None;
179        let p = match format.as_str() {
180            "icml" => u.hidden("p").map(str::to_string),
181            "idml" => u.id.strip_prefix('p').filter(|n| n.parse::<usize>().is_ok()).map(str::to_string),
182            // TXML: the position among every `<segment>` of a translatable or localizable block, protected ones
183            // counted (LocOS `wordfast.walk_txml`); TXLF: the cat_xliff slot key. Both are the crate's `key` code.
184            "txml" | "txlf" => u.hidden("key").map(str::to_string),
185            // TTX: the position among every `<Tu>` (LocOS `ttx_filter.walk`), the crate's context key
186            "ttx" => u.context.key.clone().filter(|k| k.parse::<usize>().is_ok()),
187            // the formats that record LocOS's own index (odf, Qt ts, wxl)
188            _ => u.context.extra.get("p_index").map(str::to_string),
189        };
190        if let Some(p) = p {
191            u.context.extra.insert(P_INDEX.to_string(), p);
192        }
193        // Track D, X3: the inline codes LocOS keeps as plain text in the unit become that text again
194        if let Some(pick) = locos_text_codes(&format) {
195            // FTL keeps the codes: its writer finds the placeables in the translation again, as LocOS's does
196            flatten_codes(u, pick, format != "ftl");
197        }
198        // LocOS's style for the unit: the adapter takes `locos.style`, else `context.style`
199        if LOCOS_NO_STYLE.contains(&format.as_str()) {
200            u.context.style = None;
201        }
202        // e-mail (`email_filter`): the Subject and the plain-text paragraphs have no style; an HTML part keeps the
203        // html filter's own (`a11y:img-alt`, ...)
204        if format == "eml" && matches!(u.context.style.as_deref(), Some("Subject" | "text/plain")) {
205            u.context.style = None;
206        }
207        if format == "dtd" {
208            if let Some(k) = u.context.key.clone() {
209                u.context.extra.insert(STYLE.to_string(), format!("dtd:{k}"));
210            }
211        }
212        // ODF (`odf_filter.parse`): `heading` for a `text:h`, `comment` for a comment paragraph
213        // (`office_comments.COMMENT_STYLE`), nothing for every other paragraph (not its automatic or named style)
214        if matches!(format.as_str(), "odt" | "ods" | "odp" | "odg") {
215            u.context.style = None;
216            match u.context.kind.as_deref() {
217                Some("heading") => {
218                    u.context.extra.insert(STYLE.to_string(), "heading".to_string());
219                }
220                Some("comment") => {
221                    u.context.extra.insert(STYLE.to_string(), "comment".to_string());
222                }
223                _ => {}
224            }
225        }
226    }
227}
228
229/// Formats whose LocOS units carry no style (`""`) where Bilingua sets `context.style`.
230/// TTML: LocOS's units have no style (`ttml_filter`), where Bilingua keeps the caption's `style` attribute.
231/// Wave 6 (B-SIDE ass-2,
232/// tex-2, pl-1, mo-2): LocOS `ass_filter`, `latex_filter`, `apple_filter` (plist, stringsdict) and the PO filter
233/// behind `mo_filter` give every unit an empty style.
234const LOCOS_NO_STYLE: &[&str] = &[
235    "po", "wxl", "xaml", "resx", "strings", "properties", "json", "json5", "resjson", "arb", "yaml", "txml", "txlf", "ttml", "ass", "tex", "plist", "stringsdict", "mo",
236];
237
238/// For the formats whose LocOS filter keeps (some) inline codes as plain unit text, which codes: every code in the
239/// key/value formats (placeholders such as `%@`, `{0}`, `[ProductName]`, and JSON's HTML), only `placeholder` codes
240/// in ARB (LocOS keeps its ICU plural and select arguments as tokens) and FTL (its placeables). YAML: every code
241/// (LocOS's yaml filter has no inline map at all).
242fn locos_text_codes(format: &str) -> Option<fn(&CodeData) -> bool> {
243    match format {
244        // yaml: LocOS `yaml_filter` offers the plain value (no inline map): Rails `%{name}`, `{name}`, HTML, `%d`
245        // mo (B-SIDE W6 mo-1): LocOS reads an MO through its PO filter, whose placeholders are tokens only for entries
246        // flagged c-format / python-format, and an MO has no flags
247        "po" | "mo" | "strings" | "properties" | "dtd" | "wxl" | "xaml" | "resx" | "json" | "json5" | "resjson" | "yaml" => Some(|_| true),
248        "arb" | "ftl" => Some(|c| c.label.as_deref() == Some("placeholder")),
249        _ => None,
250    }
251}
252
253/// Replaces the tags `pick` selects in every segment's source by the markup they stand for (the code's own
254/// open, close or standalone text, else the tag's display), joining the text runs, and drops their codes unless
255/// `drop` is false.
256fn flatten_codes(u: &mut Unit, pick: fn(&CodeData) -> bool, drop: bool) {
257    let mut gone = Vec::new();
258    for s in &mut u.segments {
259        let mut out: Vec<Inline> = Vec::with_capacity(s.source.len());
260        for i in std::mem::take(&mut s.source) {
261            let raw = match &i {
262                Inline::Tag { id, kind, display, .. } => match u.codes.get(id) {
263                    Some(c) if pick(c) => {
264                        gone.push(id.clone());
265                        let m = match kind {
266                            TagKind::Open => c.open.as_deref(),
267                            TagKind::Close => c.close.as_deref(),
268                            TagKind::Standalone => c.standalone.as_deref(),
269                        };
270                        Some(m.unwrap_or(display).to_string())
271                    }
272                    _ => None,
273                },
274                Inline::Text(_) => None,
275            };
276            let i = raw.map(Inline::Text).unwrap_or(i);
277            match (out.last_mut(), &i) {
278                (Some(Inline::Text(a)), Inline::Text(b)) => a.push_str(b),
279                _ => out.push(i),
280            }
281        }
282        s.source = out;
283    }
284    if drop {
285        for id in gone {
286            u.codes.remove(&id);
287        }
288    }
289}
290
291/// The language tag Localization OS declares for a target locale (its `languages_catalog.html_lang`): underscores
292/// become hyphens and the case is canonical (`es_ES` gives `es-ES`, `zh_hant_tw` gives `zh-Hant-TW`); `None` for
293/// a blank or malformed code (spaces, quotes, an empty subtag, more than 64 characters).
294pub fn lang_tag(code: &str) -> Option<String> {
295    let tag = code.trim().replace('_', "-");
296    if tag.is_empty() || tag.len() > 64 {
297        return None;
298    }
299    let mut parts = tag.split('-');
300    let first = parts.next()?;
301    if !(2..=8).contains(&first.len()) || !first.bytes().all(|b| b.is_ascii_alphabetic()) {
302        return None;
303    }
304    let mut out = vec![first.to_ascii_lowercase()];
305    let mut ext = false;
306    for sub in parts {
307        if sub.is_empty() || sub.len() > 8 || !sub.bytes().all(|b| b.is_ascii_alphanumeric()) {
308            return None;
309        }
310        let alpha = sub.bytes().all(|b| b.is_ascii_alphabetic());
311        if sub.len() == 1 {
312            ext = true;
313            out.push(sub.to_ascii_lowercase());
314        } else if ext {
315            out.push(sub.to_ascii_lowercase());
316        } else if sub.len() == 4 && alpha {
317            let mut s = sub.to_ascii_lowercase();
318            s[..1].make_ascii_uppercase();
319            out.push(s);
320        } else if (sub.len() == 2 && alpha) || (sub.len() == 3 && sub.bytes().all(|b| b.is_ascii_digit())) {
321            out.push(sub.to_ascii_uppercase());
322        } else {
323            out.push(sub.to_ascii_lowercase());
324        }
325    }
326    Some(out.join("-"))
327}
328
329/// True when Localization OS writes `code` right to left (its `text_direction`): a script subtag decides
330/// (`ku-Arab` yes, `ug-Latn` no), else the base language (`ar`, `he`, `fa-IR`, `ur`). False for a code
331/// [`lang_tag`] refuses.
332pub fn is_rtl(code: &str) -> bool {
333    const SCRIPTS: [&str; 11] = ["arab", "hebr", "syrc", "thaa", "nkoo", "adlm", "rohg", "samr", "mand", "mend", "yezi"];
334    const LANGS: [&str; 22] =
335        ["ar", "arc", "azb", "ckb", "dv", "fa", "glk", "he", "iw", "ji", "ks", "lrc", "mzn", "nqo", "pnb", "prs", "ps", "sd", "syr", "ug", "ur", "yi"];
336    let Some(tag) = lang_tag(code) else { return false };
337    let parts: Vec<&str> = tag.split('-').collect();
338    for sub in &parts[1..] {
339        if sub.len() == 1 {
340            break;
341        }
342        if sub.len() == 4 && sub.bytes().all(|b| b.is_ascii_alphabetic()) {
343            return SCRIPTS.contains(&sub.to_ascii_lowercase().as_str());
344        }
345    }
346    LANGS.contains(&parts[0])
347}
348
349/// One translatable segment as the Localization OS adapter numbers it ([`locos_units`]).
350#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
351#[non_exhaustive]
352pub struct LocosUnit {
353    /// LocOS's paragraph index (`TextUnit.p_index`).
354    pub p_index: i64,
355    /// The Bilingua segment id the index stands for (what [`locos_set_target`] takes).
356    pub segment_id: String,
357    /// The segment's source as LocOS text, tokens included ([`tokens::to_locos_text_coded`]).
358    pub text: String,
359    /// The side map of the tokens in `text`, for [`tokens::from_locos_text`].
360    pub map: tokens::LocosMap,
361    /// LocOS's style for the unit: `locos.style`, else `context.style`, else empty.
362    pub style: String,
363}
364
365/// The translatable segments of a document extracted under the LocOS profile at paragraph granularity, numbered the
366/// way Localization OS numbers its units: `p_index` is `context.extra[P_INDEX]` when every segment's unit has one
367/// and they are all distinct, else the position among the translatable segments; the text is the segment's source
368/// with its codes as LocOS tokens, numbered by the format's LocOS rule.
369pub fn locos_units(doc: &Document) -> Vec<LocosUnit> {
370    let segs: Vec<(&Unit, &crate::Segment)> = doc.units.iter().filter(|u| u.translate).flat_map(|u| u.segments.iter().map(move |s| (u, s))).collect();
371    let metas: Vec<Option<i64>> = segs.iter().map(|(u, _)| u.context.extra.get(P_INDEX).and_then(|p| p.parse().ok())).collect();
372    let distinct = metas.iter().flatten().collect::<std::collections::BTreeSet<_>>().len() == metas.len();
373    let use_meta = !segs.is_empty() && metas.iter().all(Option::is_some) && distinct;
374    segs.iter()
375        .enumerate()
376        .map(|(i, (u, s))| {
377            let (text, map) = tokens::to_locos_text_coded(&doc.format, &s.source, &u.codes);
378            let style = u.context.extra.get(STYLE).filter(|s| !s.is_empty()).map(str::to_string).or_else(|| u.context.style.clone()).unwrap_or_default();
379            let p_index = match (use_meta, metas[i]) {
380                (true, Some(p)) => p,
381                _ => i as i64,
382            };
383            LocosUnit { p_index, segment_id: s.id.clone(), text, map, style }
384        })
385        .collect()
386}
387
388/// Sets a target the way Localization OS means it: an empty LocOS target is a translation to nothing (written as
389/// an empty value, [`Document::set_target_empty`]); one of white space only is written as that white space (LocOS
390/// writes it, and the adapter's JSON document carries it, where [`Document::set_target`] would read it as no
391/// translation); anything else is [`Document::set_target`], except that a translation may repeat a standalone
392/// placeholder tag (`#` in ICU, Chrome `$x$`, go `{{..}}`: LocOS accepts it, where `set_target` refuses it as
393/// "tag appears more often"); paired tags keep the exactly-once rule and a tag the source lacks is still refused.
394/// For the formats whose LocOS writer repairs a translation's tags ([`tokens::locos_repairs_tags`]: the XLIFF
395/// family, TXML, TTX, the XLIFF packages, and since W5 the XML formats and MDX) a target may hold any tag of the
396/// source more often than the source, or unbalanced: LocOS's rule (`cat_xliff._render`, the `xml_its` render): a code
397/// written more often than the source has it loses the extra tags (its text stays), a close that closes nothing is
398/// dropped, a pair left open is closed at the end ([`tokens::repair_locos_text_for`] lists each repair); MDX writes
399/// a repeated tag again, as LocOS's `_rematerialize` does. A tag the source lacks is still refused.
400/// MicroDVD `.sub` and XPress Tags take the same repairs, applied to the target before it is set.
401pub fn locos_set_target(doc: &mut Document, seg_id: &str, target: Vec<Inline>) -> Result<(), Error> {
402    if LOCOS_WRITES_REPAIRED.contains(&doc.format.as_str()) {
403        let Some((ui, si)) = doc.locate(seg_id) else { return Err(Error::UnknownSegment(seg_id.to_string())) };
404        // pairs only: a repeated standalone placeholder is still written each time
405        let repaired = tokens::repair_tags(&doc.units[ui].segments[si].source, target, false);
406        return set_like_locos(doc, seg_id, repaired);
407    }
408    if !tokens::locos_repairs_tags(&doc.format) {
409        return set_like_locos(doc, seg_id, target);
410    }
411    let Some((ui, si)) = doc.locate(seg_id) else { return Err(Error::UnknownSegment(seg_id.to_string())) };
412    let repaired = tokens::repair_tags(&doc.units[ui].segments[si].source, target.clone(), true);
413    set_like_locos(doc, seg_id, repaired)?;
414    // the CAT writers apply the rule themselves after stripping the target's edges (as LocOS's do), and MDX writes
415    // each tag as typed, so there the target keeps every tag as it came, repeated or unbalanced; the repaired copy
416    // only had to pass the checks. The XML writers (W5) get the repaired target.
417    if tokens::locos_keeps_typed_tags(&doc.format) && target.iter().any(|i| matches!(i, Inline::Tag { .. })) {
418        doc.units[ui].segments[si].target = crate::merge_text(target);
419    }
420    Ok(())
421}
422
423/// Formats whose LocOS writer writes a translation that repeats a style pair, the repeat without its tags (its
424/// text stays), where `set_target` refuses it as "tag appears more often" (B-SIDE W6 st-2, xtg-2): MicroDVD
425/// `subtitle_text_filter`, XPress Tags `quark_tags_filter`, and InDesign IDML and InCopy ICML (`idml_filter`: a repeated
426/// token is dropped, its text stays). The target is repaired by the CAT writers' rule
427/// ([`tokens::repair_tags`]: at most as often as the source, a stray close dropped, an open pair closed at the end)
428/// and set as repaired.
429const LOCOS_WRITES_REPAIRED: &[&str] = &["sub", "xtg", "idml", "icml"];
430
431/// The body of [`locos_set_target`] once the tags are repaired.
432fn set_like_locos(doc: &mut Document, seg_id: &str, target: Vec<Inline>) -> Result<(), Error> {
433    if target.iter().all(|i| matches!(i, Inline::Text(t) if t.is_empty())) {
434        return doc.set_target_empty(seg_id);
435    }
436    let blank = target.iter().all(|i| matches!(i, Inline::Text(t) if t.trim().is_empty()));
437    if !blank {
438        return doc.set_target_repeating(seg_id, target);
439    }
440    // validated as any target (unknown segment, locked unit), then kept as it is
441    doc.set_target_repeating(seg_id, target.clone())?;
442    let (ui, si) = doc.locate(seg_id).ok_or_else(|| Error::UnknownSegment(seg_id.to_string()))?;
443    let seg = &mut doc.units[ui].segments[si];
444    let text: String = target.iter().map(|i| if let Inline::Text(t) = i { t.as_str() } else { "" }).collect();
445    seg.target = vec![Inline::Text(text)];
446    seg.empty_target = false;
447    seg.state = crate::SegState::Draft;
448    Ok(())
449}
450
451#[cfg(test)]
452mod tests {
453    use super::*;
454
455    #[test]
456    fn lang_tags_like_locos() {
457        for (code, want) in [("es_ES", Some("es-ES")), ("EN-us", Some("en-US")), ("zh_hant_tw", Some("zh-Hant-TW")), ("es-419", Some("es-419")), ("x", None), ("", None), ("de DE", None), ("de--DE", None), ("\"><b>", None)] {
458            assert_eq!(lang_tag(code).as_deref(), want, "{code}");
459        }
460        assert!(is_rtl("ar-SA") && is_rtl("ku-Arab") && is_rtl("he") && !is_rtl("ug-Latn") && !is_rtl("de") && !is_rtl("<x>"));
461    }
462
463    #[test]
464    fn resolve_names_and_versions() {
465        assert_eq!(resolve("locos", None).unwrap(), locos());
466        assert_eq!(resolve("locos@1", None).unwrap(), locos());
467        assert_eq!(resolve("locos", Some(LOCOS_VERSION)).unwrap(), locos());
468        assert_eq!(resolve("locos@1", Some(1)).unwrap().version, 1);
469        assert!(matches!(resolve("locos@1", Some(2)), Err(Error::UnknownProfile(_))));
470        assert!(matches!(resolve("locos@x", None), Err(Error::UnknownProfile(_))));
471        assert!(matches!(resolve("nope", None), Err(Error::UnknownProfile(_))));
472        assert!(matches!(resolve("locos", Some(LOCOS_VERSION + 1)), Err(Error::ParserVersion { .. })));
473        assert!(matches!(resolve("locos@0", None), Err(Error::ParserVersion { .. })));
474        assert!(locos().reads(1) && !locos().reads(0) && !locos().reads(LOCOS_VERSION + 1));
475    }
476}