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 let p = match format.as_str() {
168 "icml" => u.hidden("p").map(str::to_string),
169 "idml" => u.id.strip_prefix('p').filter(|n| n.parse::<usize>().is_ok()).map(str::to_string),
170 // TXML: the position among every `<segment>` of a translatable or localizable block, protected ones
171 // counted (LocOS `wordfast.walk_txml`); TXLF: the cat_xliff slot key. Both are the crate's `key` code.
172 "txml" | "txlf" => u.hidden("key").map(str::to_string),
173 // TTX: the position among every `<Tu>` (LocOS `ttx_filter.walk`), the crate's context key
174 "ttx" => u.context.key.clone().filter(|k| k.parse::<usize>().is_ok()),
175 // the formats that record LocOS's own index (odf, Qt ts, wxl)
176 _ => u.context.extra.get("p_index").cloned(),
177 };
178 if let Some(p) = p {
179 u.context.extra.insert(P_INDEX.to_string(), p);
180 }
181 // Track D, X3: the inline codes LocOS keeps as plain text in the unit become that text again
182 if let Some(pick) = locos_text_codes(&format) {
183 // FTL keeps the codes: its writer finds the placeables in the translation again, as LocOS's does
184 flatten_codes(u, pick, format != "ftl");
185 }
186 // LocOS's style for the unit: the adapter takes `locos.style`, else `context.style`
187 if LOCOS_NO_STYLE.contains(&format.as_str()) {
188 u.context.style = None;
189 }
190 // e-mail (`email_filter`): the Subject and the plain-text paragraphs have no style; an HTML part keeps the
191 // html filter's own (`a11y:img-alt`, ...)
192 if format == "eml" && matches!(u.context.style.as_deref(), Some("Subject" | "text/plain")) {
193 u.context.style = None;
194 }
195 if format == "dtd" {
196 if let Some(k) = u.context.key.clone() {
197 u.context.extra.insert(STYLE.to_string(), format!("dtd:{k}"));
198 }
199 }
200 // ODF (`odf_filter.parse`): `heading` for a `text:h`, `comment` for a comment paragraph
201 // (`office_comments.COMMENT_STYLE`), nothing for every other paragraph (not its automatic or named style)
202 if matches!(format.as_str(), "odt" | "ods" | "odp" | "odg") {
203 u.context.style = None;
204 match u.context.kind.as_deref() {
205 Some("heading") => {
206 u.context.extra.insert(STYLE.to_string(), "heading".to_string());
207 }
208 Some("comment") => {
209 u.context.extra.insert(STYLE.to_string(), "comment".to_string());
210 }
211 _ => {}
212 }
213 }
214 }
215}
216
217/// Formats whose LocOS units carry no style (`""`) where Bilingua sets `context.style`.
218/// TTML: LocOS's units have no style (`ttml_filter`), where Bilingua keeps the caption's `style` attribute.
219/// Wave 6 (B-SIDE ass-2,
220/// tex-2, pl-1, mo-2): LocOS `ass_filter`, `latex_filter`, `apple_filter` (plist, stringsdict) and the PO filter
221/// behind `mo_filter` give every unit an empty style.
222const LOCOS_NO_STYLE: &[&str] = &[
223 "po", "wxl", "xaml", "resx", "strings", "properties", "json", "json5", "resjson", "arb", "yaml", "txml", "txlf", "ttml", "ass", "tex", "plist", "stringsdict", "mo",
224];
225
226/// For the formats whose LocOS filter keeps (some) inline codes as plain unit text, which codes: every code in the
227/// key/value formats (placeholders such as `%@`, `{0}`, `[ProductName]`, and JSON's HTML), only `placeholder` codes
228/// in ARB (LocOS keeps its ICU plural and select arguments as tokens) and FTL (its placeables). YAML: every code
229/// (LocOS's yaml filter has no inline map at all).
230fn locos_text_codes(format: &str) -> Option<fn(&CodeData) -> bool> {
231 match format {
232 // yaml: LocOS `yaml_filter` offers the plain value (no inline map): Rails `%{name}`, `{name}`, HTML, `%d`
233 // mo (B-SIDE W6 mo-1): LocOS reads an MO through its PO filter, whose placeholders are tokens only for entries
234 // flagged c-format / python-format, and an MO has no flags
235 "po" | "mo" | "strings" | "properties" | "dtd" | "wxl" | "xaml" | "resx" | "json" | "json5" | "resjson" | "yaml" => Some(|_| true),
236 "arb" | "ftl" => Some(|c| c.label.as_deref() == Some("placeholder")),
237 _ => None,
238 }
239}
240
241/// Replaces the tags `pick` selects in every segment's source by the markup they stand for (the code's own
242/// open, close or standalone text, else the tag's display), joining the text runs, and drops their codes unless
243/// `drop` is false.
244fn flatten_codes(u: &mut Unit, pick: fn(&CodeData) -> bool, drop: bool) {
245 let mut gone = Vec::new();
246 for s in &mut u.segments {
247 let mut out: Vec<Inline> = Vec::with_capacity(s.source.len());
248 for i in std::mem::take(&mut s.source) {
249 let raw = match &i {
250 Inline::Tag { id, kind, display, .. } => match u.codes.get(id) {
251 Some(c) if pick(c) => {
252 gone.push(id.clone());
253 let m = match kind {
254 TagKind::Open => c.open.as_deref(),
255 TagKind::Close => c.close.as_deref(),
256 TagKind::Standalone => c.standalone.as_deref(),
257 };
258 Some(m.unwrap_or(display).to_string())
259 }
260 _ => None,
261 },
262 Inline::Text(_) => None,
263 };
264 let i = raw.map(Inline::Text).unwrap_or(i);
265 match (out.last_mut(), &i) {
266 (Some(Inline::Text(a)), Inline::Text(b)) => a.push_str(b),
267 _ => out.push(i),
268 }
269 }
270 s.source = out;
271 }
272 if drop {
273 for id in gone {
274 u.codes.remove(&id);
275 }
276 }
277}
278
279/// The language tag Localization OS declares for a target locale (its `languages_catalog.html_lang`): underscores
280/// become hyphens and the case is canonical (`es_ES` gives `es-ES`, `zh_hant_tw` gives `zh-Hant-TW`); `None` for
281/// a blank or malformed code (spaces, quotes, an empty subtag, more than 64 characters).
282pub fn lang_tag(code: &str) -> Option<String> {
283 let tag = code.trim().replace('_', "-");
284 if tag.is_empty() || tag.len() > 64 {
285 return None;
286 }
287 let mut parts = tag.split('-');
288 let first = parts.next()?;
289 if !(2..=8).contains(&first.len()) || !first.bytes().all(|b| b.is_ascii_alphabetic()) {
290 return None;
291 }
292 let mut out = vec![first.to_ascii_lowercase()];
293 let mut ext = false;
294 for sub in parts {
295 if sub.is_empty() || sub.len() > 8 || !sub.bytes().all(|b| b.is_ascii_alphanumeric()) {
296 return None;
297 }
298 let alpha = sub.bytes().all(|b| b.is_ascii_alphabetic());
299 if sub.len() == 1 {
300 ext = true;
301 out.push(sub.to_ascii_lowercase());
302 } else if ext {
303 out.push(sub.to_ascii_lowercase());
304 } else if sub.len() == 4 && alpha {
305 let mut s = sub.to_ascii_lowercase();
306 s[..1].make_ascii_uppercase();
307 out.push(s);
308 } else if (sub.len() == 2 && alpha) || (sub.len() == 3 && sub.bytes().all(|b| b.is_ascii_digit())) {
309 out.push(sub.to_ascii_uppercase());
310 } else {
311 out.push(sub.to_ascii_lowercase());
312 }
313 }
314 Some(out.join("-"))
315}
316
317/// True when Localization OS writes `code` right to left (its `text_direction`): a script subtag decides
318/// (`ku-Arab` yes, `ug-Latn` no), else the base language (`ar`, `he`, `fa-IR`, `ur`). False for a code
319/// [`lang_tag`] refuses.
320pub fn is_rtl(code: &str) -> bool {
321 const SCRIPTS: [&str; 11] = ["arab", "hebr", "syrc", "thaa", "nkoo", "adlm", "rohg", "samr", "mand", "mend", "yezi"];
322 const LANGS: [&str; 22] =
323 ["ar", "arc", "azb", "ckb", "dv", "fa", "glk", "he", "iw", "ji", "ks", "lrc", "mzn", "nqo", "pnb", "prs", "ps", "sd", "syr", "ug", "ur", "yi"];
324 let Some(tag) = lang_tag(code) else { return false };
325 let parts: Vec<&str> = tag.split('-').collect();
326 for sub in &parts[1..] {
327 if sub.len() == 1 {
328 break;
329 }
330 if sub.len() == 4 && sub.bytes().all(|b| b.is_ascii_alphabetic()) {
331 return SCRIPTS.contains(&sub.to_ascii_lowercase().as_str());
332 }
333 }
334 LANGS.contains(&parts[0])
335}
336
337/// One translatable segment as the Localization OS adapter numbers it ([`locos_units`]).
338#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
339#[non_exhaustive]
340pub struct LocosUnit {
341 /// LocOS's paragraph index (`TextUnit.p_index`).
342 pub p_index: i64,
343 /// The Bilingua segment id the index stands for (what [`locos_set_target`] takes).
344 pub segment_id: String,
345 /// The segment's source as LocOS text, tokens included ([`tokens::to_locos_text_coded`]).
346 pub text: String,
347 /// The side map of the tokens in `text`, for [`tokens::from_locos_text`].
348 pub map: tokens::LocosMap,
349 /// LocOS's style for the unit: `locos.style`, else `context.style`, else empty.
350 pub style: String,
351}
352
353/// The translatable segments of a document extracted under the LocOS profile at paragraph granularity, numbered the
354/// way Localization OS numbers its units: `p_index` is `context.extra[P_INDEX]` when every segment's unit has one
355/// and they are all distinct, else the position among the translatable segments; the text is the segment's source
356/// with its codes as LocOS tokens, numbered by the format's LocOS rule.
357pub fn locos_units(doc: &Document) -> Vec<LocosUnit> {
358 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();
359 let metas: Vec<Option<i64>> = segs.iter().map(|(u, _)| u.context.extra.get(P_INDEX).and_then(|p| p.parse().ok())).collect();
360 let distinct = metas.iter().flatten().collect::<std::collections::BTreeSet<_>>().len() == metas.len();
361 let use_meta = !segs.is_empty() && metas.iter().all(Option::is_some) && distinct;
362 segs.iter()
363 .enumerate()
364 .map(|(i, (u, s))| {
365 let (text, map) = tokens::to_locos_text_coded(&doc.format, &s.source, &u.codes);
366 let style = u.context.extra.get(STYLE).filter(|s| !s.is_empty()).cloned().or_else(|| u.context.style.clone()).unwrap_or_default();
367 let p_index = match (use_meta, metas[i]) {
368 (true, Some(p)) => p,
369 _ => i as i64,
370 };
371 LocosUnit { p_index, segment_id: s.id.clone(), text, map, style }
372 })
373 .collect()
374}
375
376/// Sets a target the way Localization OS means it: an empty LocOS target is a translation to nothing (written as
377/// an empty value, [`Document::set_target_empty`]); one of white space only is written as that white space (LocOS
378/// writes it, and the adapter's JSON document carries it, where [`Document::set_target`] would read it as no
379/// translation); anything else is [`Document::set_target`], except that a translation may repeat a standalone
380/// placeholder tag (`#` in ICU, Chrome `$x$`, go `{{..}}`: LocOS accepts it, where `set_target` refuses it as
381/// "tag appears more often"); paired tags keep the exactly-once rule and a tag the source lacks is still refused.
382/// For the formats whose LocOS writer repairs a translation's tags ([`tokens::locos_repairs_tags`]: the XLIFF
383/// family, TXML, TTX, the XLIFF packages, and since W5 the XML formats and MDX) a target may hold any tag of the
384/// source more often than the source, or unbalanced: LocOS's rule (`cat_xliff._render`, the `xml_its` render): a code
385/// written more often than the source has it loses the extra tags (its text stays), a close that closes nothing is
386/// dropped, a pair left open is closed at the end ([`tokens::repair_locos_text_for`] lists each repair); MDX writes
387/// a repeated tag again, as LocOS's `_rematerialize` does. A tag the source lacks is still refused.
388/// MicroDVD `.sub` and XPress Tags take the same repairs, applied to the target before it is set.
389pub fn locos_set_target(doc: &mut Document, seg_id: &str, target: Vec<Inline>) -> Result<(), Error> {
390 if LOCOS_WRITES_REPAIRED.contains(&doc.format.as_str()) {
391 let Some((ui, si)) = doc.locate(seg_id) else { return Err(Error::UnknownSegment(seg_id.to_string())) };
392 // pairs only: a repeated standalone placeholder is still written each time
393 let repaired = tokens::repair_tags(&doc.units[ui].segments[si].source, target, false);
394 return set_like_locos(doc, seg_id, repaired);
395 }
396 if !tokens::locos_repairs_tags(&doc.format) {
397 return set_like_locos(doc, seg_id, target);
398 }
399 let Some((ui, si)) = doc.locate(seg_id) else { return Err(Error::UnknownSegment(seg_id.to_string())) };
400 let repaired = tokens::repair_tags(&doc.units[ui].segments[si].source, target.clone(), true);
401 set_like_locos(doc, seg_id, repaired)?;
402 // the CAT writers apply the rule themselves after stripping the target's edges (as LocOS's do), and MDX writes
403 // each tag as typed, so there the target keeps every tag as it came, repeated or unbalanced; the repaired copy
404 // only had to pass the checks. The XML writers (W5) get the repaired target.
405 if tokens::locos_keeps_typed_tags(&doc.format) && target.iter().any(|i| matches!(i, Inline::Tag { .. })) {
406 doc.units[ui].segments[si].target = crate::merge_text(target);
407 }
408 Ok(())
409}
410
411/// Formats whose LocOS writer writes a translation that repeats a style pair, the repeat without its tags (its
412/// text stays), where `set_target` refuses it as "tag appears more often" (B-SIDE W6 st-2, xtg-2): MicroDVD
413/// `subtitle_text_filter`, XPress Tags `quark_tags_filter`, and InDesign IDML and InCopy ICML (`idml_filter`: a repeated
414/// token is dropped, its text stays). The target is repaired by the CAT writers' rule
415/// ([`tokens::repair_tags`]: at most as often as the source, a stray close dropped, an open pair closed at the end)
416/// and set as repaired.
417const LOCOS_WRITES_REPAIRED: &[&str] = &["sub", "xtg", "idml", "icml"];
418
419/// The body of [`locos_set_target`] once the tags are repaired.
420fn set_like_locos(doc: &mut Document, seg_id: &str, target: Vec<Inline>) -> Result<(), Error> {
421 if target.iter().all(|i| matches!(i, Inline::Text(t) if t.is_empty())) {
422 return doc.set_target_empty(seg_id);
423 }
424 let blank = target.iter().all(|i| matches!(i, Inline::Text(t) if t.trim().is_empty()));
425 if !blank {
426 return doc.set_target_repeating(seg_id, target);
427 }
428 // validated as any target (unknown segment, locked unit), then kept as it is
429 doc.set_target_repeating(seg_id, target.clone())?;
430 let (ui, si) = doc.locate(seg_id).ok_or_else(|| Error::UnknownSegment(seg_id.to_string()))?;
431 let seg = &mut doc.units[ui].segments[si];
432 let text: String = target.iter().map(|i| if let Inline::Text(t) = i { t.as_str() } else { "" }).collect();
433 seg.target = vec![Inline::Text(text)];
434 seg.empty_target = false;
435 seg.state = crate::SegState::Draft;
436 Ok(())
437}
438
439#[cfg(test)]
440mod tests {
441 use super::*;
442
443 #[test]
444 fn lang_tags_like_locos() {
445 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)] {
446 assert_eq!(lang_tag(code).as_deref(), want, "{code}");
447 }
448 assert!(is_rtl("ar-SA") && is_rtl("ku-Arab") && is_rtl("he") && !is_rtl("ug-Latn") && !is_rtl("de") && !is_rtl("<x>"));
449 }
450
451 #[test]
452 fn resolve_names_and_versions() {
453 assert_eq!(resolve("locos", None).unwrap(), locos());
454 assert_eq!(resolve("locos@1", None).unwrap(), locos());
455 assert_eq!(resolve("locos", Some(LOCOS_VERSION)).unwrap(), locos());
456 assert_eq!(resolve("locos@1", Some(1)).unwrap().version, 1);
457 assert!(matches!(resolve("locos@1", Some(2)), Err(Error::UnknownProfile(_))));
458 assert!(matches!(resolve("locos@x", None), Err(Error::UnknownProfile(_))));
459 assert!(matches!(resolve("nope", None), Err(Error::UnknownProfile(_))));
460 assert!(matches!(resolve("locos", Some(LOCOS_VERSION + 1)), Err(Error::ParserVersion { .. })));
461 assert!(matches!(resolve("locos@0", None), Err(Error::ParserVersion { .. })));
462 assert!(locos().reads(1) && !locos().reads(0) && !locos().reads(LOCOS_VERSION + 1));
463 }
464}