Skip to main content

bilingua_model/
lib.rs

1//! Bilingua document model: what every file parser extracts and what it writes back.
2//!
3//! A parser (`Filter`) turns a source file into a [`Document`]: translatable [`Unit`]s (a paragraph, a cell, a
4//! string) and a [`Skeleton`] that holds everything else byte for byte. Each unit holds one or more
5//! [`Segment`]s (one before segmentation; sentences after `bilingua-seg` splits it). Formatting inside the text
6//! is kept as inline [`Inline::Tag`] codes whose original markup lives in [`Unit::codes`], so a writer can put
7//! it back exactly.
8//!
9//! JSON shape: `Inline` and `TagKind` serialise exactly like `catcore::Inline` and `catcore::TagKind`
10//! (`{"text": ".."}` / `{"tag": {"id", "kind": "open|close|standalone", "display"}}`), so one editor UI shows
11//! bilingual files (catcore) and source files (Bilingua) the same way. Every field added since is optional and
12//! left out of the JSON when empty: a tag's `free` flag, a segment's `origin`, a unit's `notes` and `lock_reason`,
13//! a skeleton's `parser`.
14//!
15//! Bilingual files (XLIFF and the like) use the same model: a segment may carry a target, a state and an origin
16//! (with a match percentage), and a unit may carry notes and a lock reason. Monolingual formats leave them empty.
17//!
18//! [`profile`] holds what one consumer needs and no other (the Localization OS profile, and
19//! [`profile::tokens`], which converts inline codes to and from LocOS's text tokens, one token per tag).
20
21#![warn(missing_docs)]
22#![deny(unsafe_code)]
23
24use serde::{Deserialize, Serialize};
25use std::collections::BTreeMap;
26
27pub mod b64;
28/// CLDR plural categories per language, shared by the format crates (not part of the semver API).
29#[doc(hidden)]
30pub mod cldr;
31pub mod codepage;
32pub mod enc;
33pub mod garble;
34pub mod guard;
35/// The gettext plural rules of Localization OS, shared by the mo and po crates (not part of the semver API).
36#[doc(hidden)]
37pub mod plural_table;
38pub mod profile;
39mod pytables;
40pub mod pytext;
41pub mod smallmap;
42/// A scanning-step counter for tests that show a parser is linear without timing it (not part of the semver API).
43#[doc(hidden)]
44pub mod work;
45
46// Unit model step 6 (BILI-119a): plural groups and the shared ICU parser.
47pub mod icu;
48mod plural;
49pub use plural::{PluralKind, PluralSlot};
50
51pub use encoding_rs;
52pub use guard::{LimitError, LimitKind, Limits};
53pub use smallmap::{SmallMap, TextMap};
54pub use pytext::{py_is_word_char, py_is_word_start_char, py_isdecimal_char, py_isalnum_char, py_isalpha_char, py_isspace_char, py_has_alnum, py_has_alpha, py_isalnum, py_isalpha, py_isspace, py_lstrip, py_rstrip, py_strip};
55
56/// What a builder takes for an optional text field: `"de-DE"`, a `String`, or an `Option` of either (`None`
57/// clears the field). `impl Into<Option<String>>` would refuse a plain `&str`, so the builders take this instead.
58///
59/// The trait is sealed: Bilingua implements it for `&str`, `String`, `&String` and their `Option`s, and may add
60/// more types in a 1.x release; other crates cannot implement it.
61pub trait IntoOptionString: sealed::Sealed {
62    /// The value as an optional `String`.
63    fn into_option_string(self) -> Option<String>;
64}
65
66mod sealed {
67    pub trait Sealed {}
68    impl Sealed for &str {}
69    impl Sealed for String {}
70    impl Sealed for &String {}
71    impl Sealed for Option<String> {}
72    impl Sealed for Option<&str> {}
73    impl Sealed for Option<&String> {}
74}
75
76impl IntoOptionString for &str {
77    fn into_option_string(self) -> Option<String> {
78        Some(self.to_string())
79    }
80}
81impl IntoOptionString for String {
82    fn into_option_string(self) -> Option<String> {
83        Some(self)
84    }
85}
86impl IntoOptionString for &String {
87    fn into_option_string(self) -> Option<String> {
88        Some(self.clone())
89    }
90}
91impl IntoOptionString for Option<String> {
92    fn into_option_string(self) -> Option<String> {
93        self
94    }
95}
96impl IntoOptionString for Option<&str> {
97    fn into_option_string(self) -> Option<String> {
98        self.map(str::to_string)
99    }
100}
101impl IntoOptionString for Option<&String> {
102    fn into_option_string(self) -> Option<String> {
103        self.cloned()
104    }
105}
106
107/// One piece of segment content, in logical order.
108///
109/// The enum is closed (text or a code), matching catcore's JSON. The `Tag` variant is `#[non_exhaustive]`: build it
110/// with [`Inline::tag`] or [`Inline::free_tag`] (and [`Inline::with_free`]), and match it with `..`, so a code can
111/// carry more in a 1.x release.
112#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
113#[serde(rename_all = "lowercase")]
114pub enum Inline {
115    /// Plain text.
116    Text(String),
117    /// An inline code. `free` is true for a standalone code that names its argument (`%1$s`, `{name}`, `{0}`, an
118    /// XLIFF `<x id>` or `<ph id>`): a translation may move it, because the writer finds it again by `id`. It is
119    /// false for markup and for unnumbered placeholders (`%s`), whose order is the argument order. Only a
120    /// standalone code can be free.
121    #[non_exhaustive]
122    Tag {
123        /// The code's id: the key of its original markup in [`Unit::codes`]. An open and its close share it.
124        id: String,
125        /// Open, close or standalone.
126        kind: TagKind,
127        /// What an editor shows for the code (`<b>`, `{name}`).
128        display: String,
129        /// The code may move freely in the target (see above).
130        #[serde(default, skip_serializing_if = "is_false")]
131        free: bool,
132    },
133}
134
135fn is_false(b: &bool) -> bool {
136    !*b
137}
138
139impl Inline {
140    /// A text piece.
141    pub fn text(s: impl Into<String>) -> Inline {
142        Inline::Text(s.into())
143    }
144    /// A code that is not free (markup, or an unnumbered placeholder).
145    pub fn tag(id: impl Into<String>, kind: TagKind, display: impl Into<String>) -> Inline {
146        Inline::Tag { id: id.into(), kind, display: display.into(), free: false }
147    }
148    /// A standalone code that may move freely in the target (see [`Inline::Tag`]).
149    pub fn free_tag(id: impl Into<String>, display: impl Into<String>) -> Inline {
150        Inline::Tag { id: id.into(), kind: TagKind::Standalone, display: display.into(), free: true }
151    }
152    /// True for a free-order standalone code.
153    pub fn is_free(&self) -> bool {
154        matches!(self, Inline::Tag { free: true, .. })
155    }
156    /// Sets the free flag of a standalone code (`Inline::tag(id, kind, display).with_free(f)`). Only a standalone
157    /// code can be free: on an open or close code, and on text, the flag stays false.
158    pub fn with_free(mut self, value: bool) -> Inline {
159        if let Inline::Tag { kind, free, .. } = &mut self {
160            *free = value && *kind == TagKind::Standalone;
161        }
162        self
163    }
164}
165
166/// The kind of an inline code. Closed: a code opens, closes or stands alone.
167#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
168#[serde(rename_all = "lowercase")]
169pub enum TagKind {
170    /// Opens a pair (`<b>`).
171    Open,
172    /// Closes a pair (`</b>`).
173    Close,
174    /// Stands alone (`<br/>`, `{name}`, `%s`).
175    Standalone,
176}
177
178/// The original markup of one inline code, kept so the writer can reproduce it.
179/// A paired code fills `open` and `close`; a standalone code fills `standalone`. Build it with
180/// [`CodeData::paired`], [`CodeData::standalone`] or [`CodeData::new`] and the `with_*` methods.
181#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
182#[non_exhaustive]
183pub struct CodeData {
184    /// The opening markup of a paired code.
185    pub open: Option<String>,
186    /// The closing markup of a paired code.
187    pub close: Option<String>,
188    /// The markup of a standalone code.
189    pub standalone: Option<String>,
190    /// Human label for the tag chip, e.g. "bold", "link".
191    pub label: Option<String>,
192    /// What the code is (bold, link, field...), when the format knows (BILI-118). JSON key `type`, left out when
193    /// unset. Extractors fill it; writers never read it. Unset under the LocOS profile.
194    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
195    pub ty: Option<CodeType>,
196    /// Facts about the code, keyed per type (see [`CodeType::attr_keys`]): `href` and `title` for a link, ...
197    /// Left out of the JSON when empty. Unset under the LocOS profile.
198    #[serde(default, skip_serializing_if = "TextMap::is_empty")]
199    pub attrs: TextMap,
200}
201
202impl CodeData {
203    /// No markup and no label.
204    pub fn new() -> CodeData {
205        CodeData::default()
206    }
207    /// A paired code's markup.
208    pub fn paired(open: impl Into<String>, close: impl Into<String>) -> CodeData {
209        let (open, close): (String, String) = (open.into(), close.into());
210        CodeData::new().with_open(open).with_close(close)
211    }
212    /// A standalone code's markup.
213    pub fn standalone(markup: impl Into<String>) -> CodeData {
214        let markup: String = markup.into();
215        CodeData::new().with_standalone(markup)
216    }
217    /// Sets (or with `None` clears) the opening markup.
218    pub fn with_open(mut self, open: impl IntoOptionString) -> CodeData {
219        self.open = open.into_option_string();
220        self
221    }
222    /// Sets (or clears) the closing markup.
223    pub fn with_close(mut self, close: impl IntoOptionString) -> CodeData {
224        self.close = close.into_option_string();
225        self
226    }
227    /// Sets (or clears) the standalone markup.
228    pub fn with_standalone(mut self, standalone: impl IntoOptionString) -> CodeData {
229        self.standalone = standalone.into_option_string();
230        self
231    }
232    /// Sets (or clears) the chip label.
233    pub fn with_label(mut self, label: impl IntoOptionString) -> CodeData {
234        self.label = label.into_option_string();
235        self
236    }
237    /// The opening markup of a paired code. (`open_markup`, not `open`, to match [`CodeData::standalone_markup`],
238    /// whose plain name is taken by the [`CodeData::standalone`] constructor.)
239    pub fn open_markup(&self) -> Option<&str> {
240        self.open.as_deref()
241    }
242    /// The closing markup of a paired code.
243    pub fn close_markup(&self) -> Option<&str> {
244        self.close.as_deref()
245    }
246    /// The markup of a standalone code.
247    pub fn standalone_markup(&self) -> Option<&str> {
248        self.standalone.as_deref()
249    }
250    /// The chip label.
251    pub fn label(&self) -> Option<&str> {
252        self.label.as_deref()
253    }
254    /// Sets (or with `None` clears) the opening markup in place.
255    pub fn set_open(&mut self, open: impl IntoOptionString) {
256        self.open = open.into_option_string();
257    }
258    /// Sets (or clears) the closing markup in place.
259    pub fn set_close(&mut self, close: impl IntoOptionString) {
260        self.close = close.into_option_string();
261    }
262    /// Sets (or clears) the standalone markup in place.
263    pub fn set_standalone(&mut self, standalone: impl IntoOptionString) {
264        self.standalone = standalone.into_option_string();
265    }
266    /// Sets (or clears) the chip label in place.
267    pub fn set_label(&mut self, label: impl IntoOptionString) {
268        self.label = label.into_option_string();
269    }
270}
271
272// --- BILI-118: typed inline codes (unit model step 5) ---------------------------------------------------
273
274impl CodeData {
275    /// Sets (or clears) the code type.
276    pub fn with_code_type(mut self, ty: Option<CodeType>) -> CodeData {
277        self.ty = ty;
278        self
279    }
280    /// Sets one attribute (`href`, `field`, ...); an empty value is not stored.
281    pub fn with_attr(mut self, key: &str, value: impl Into<Box<str>>) -> CodeData {
282        self.set_attr(key, value);
283        self
284    }
285    /// What the code is, when the format knows.
286    pub fn code_type(&self) -> Option<CodeType> {
287        self.ty
288    }
289    /// Sets (or with `None` clears) the code type in place.
290    pub fn set_code_type(&mut self, ty: Option<CodeType>) {
291        self.ty = ty;
292    }
293    /// The code's attributes (keys per [`CodeType::attr_keys`]).
294    pub fn attrs(&self) -> &TextMap {
295        &self.attrs
296    }
297    /// The code's attributes, for changing.
298    pub fn attrs_mut(&mut self) -> &mut TextMap {
299        &mut self.attrs
300    }
301    /// One attribute's value.
302    pub fn attr(&self, key: &str) -> Option<&str> {
303        self.attrs.get(key)
304    }
305    /// Sets one attribute in place; an empty value removes it instead.
306    pub fn set_attr(&mut self, key: &str, value: impl Into<Box<str>>) {
307        let value: Box<str> = value.into();
308        if value.is_empty() {
309            self.attrs.remove(key);
310        } else {
311            self.attrs.insert(key, value);
312        }
313    }
314    /// Clears the type and the attributes (what the LocOS profile does to every code).
315    pub fn clear_typing(&mut self) {
316        self.ty = None;
317        self.attrs.clear();
318    }
319}
320
321/// What an inline code is, for chips and QA ("bold", "link to x.com"). Closed list with a catch-all: match with a
322/// wildcard arm; a JSON value this release does not know reads as `Other`. Serialised lowercase.
323#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
324#[serde(rename_all = "lowercase")]
325#[non_exhaustive]
326pub enum CodeType {
327    /// Bold or strong.
328    Bold,
329    /// Italic or emphasis.
330    Italic,
331    /// Underline.
332    Underline,
333    /// Strike-through.
334    Strike,
335    /// Superscript.
336    Superscript,
337    /// Subscript.
338    Subscript,
339    /// Inline code or a monospace span.
340    Code,
341    /// A named character style (attr `style`).
342    Style,
343    /// A hyperlink (attrs `href`, `title`).
344    Link,
345    /// An inline image (attrs `src`, `alt`).
346    Image,
347    /// A line break.
348    Linebreak,
349    /// A tab.
350    Tab,
351    /// A field (attr `field`: PAGE, DATE, TOC...).
352    Field,
353    /// A footnote or endnote reference.
354    Footnoteref,
355    /// A placeholder (attr `name`).
356    Placeholder,
357    /// Anything else. An unknown type in a JSON file also reads as `Other`.
358    #[serde(other)]
359    Other,
360}
361
362impl CodeType {
363    /// The JSON name (`"bold"`, `"link"`, ...).
364    pub fn as_str(self) -> &'static str {
365        match self {
366            CodeType::Bold => "bold",
367            CodeType::Italic => "italic",
368            CodeType::Underline => "underline",
369            CodeType::Strike => "strike",
370            CodeType::Superscript => "superscript",
371            CodeType::Subscript => "subscript",
372            CodeType::Code => "code",
373            CodeType::Style => "style",
374            CodeType::Link => "link",
375            CodeType::Image => "image",
376            CodeType::Linebreak => "linebreak",
377            CodeType::Tab => "tab",
378            CodeType::Field => "field",
379            CodeType::Footnoteref => "footnoteref",
380            CodeType::Placeholder => "placeholder",
381            CodeType::Other => "other",
382        }
383    }
384    /// The type for a JSON name; an unknown name is `Other`.
385    pub fn from_name(name: &str) -> CodeType {
386        CodeType::ALL.iter().copied().find(|t| t.as_str() == name).unwrap_or(CodeType::Other)
387    }
388    /// Every type, in declaration order.
389    pub const ALL: [CodeType; 16] = [
390        CodeType::Bold,
391        CodeType::Italic,
392        CodeType::Underline,
393        CodeType::Strike,
394        CodeType::Superscript,
395        CodeType::Subscript,
396        CodeType::Code,
397        CodeType::Style,
398        CodeType::Link,
399        CodeType::Image,
400        CodeType::Linebreak,
401        CodeType::Tab,
402        CodeType::Field,
403        CodeType::Footnoteref,
404        CodeType::Placeholder,
405        CodeType::Other,
406    ];
407    /// The `attrs` keys this type may carry: `href`, `title` (link); `field` (field); `src`, `alt` (image);
408    /// `style` (style); `name` (placeholder); none for the others.
409    pub fn attr_keys(self) -> &'static [&'static str] {
410        match self {
411            CodeType::Link => &["href", "title"],
412            CodeType::Field => &["field"],
413            CodeType::Image => &["src", "alt"],
414            CodeType::Style => &["style"],
415            CodeType::Placeholder => &["name"],
416            _ => &[],
417        }
418    }
419}
420
421impl std::fmt::Display for CodeType {
422    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
423        f.write_str(self.as_str())
424    }
425}
426
427/// The original markup of a unit's inline codes, by code id: a compact sorted map (see [`SmallMap`]).
428/// The type of [`Unit::codes`]; what [`Unit::set_codes`] and [`Unit::with_codes`] take.
429pub type Codes = SmallMap<CodeData>;
430
431/// Where a segment is in its life, from untouched to signed off. Monolingual files only use `New`, `Draft`,
432/// `Translated` and `Confirmed`; bilingual files and review workflows use the rest.
433#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
434#[non_exhaustive]
435pub enum SegState {
436    /// No target yet.
437    #[default]
438    #[serde(rename = "new")]
439    New,
440    /// A target exists but nobody accepted it (machine output, TM match, work in progress).
441    #[serde(rename = "draft")]
442    Draft,
443    /// The translator accepted the target.
444    #[serde(rename = "translated")]
445    Translated,
446    /// Confirmed or approved by the translator (XLIFF 2 `final`, Trados `ApprovedTranslation`).
447    #[serde(rename = "confirmed")]
448    Confirmed,
449    /// A reviewer checked it.
450    #[serde(rename = "reviewed")]
451    Reviewed,
452    /// Final approval (XLIFF 1.2 `signed-off`).
453    #[serde(rename = "signed-off")]
454    SignedOff,
455    /// A reviewer sent it back; it needs work again.
456    #[serde(rename = "rejected")]
457    Rejected,
458    /// Frozen: nobody edits it (context match, project lock).
459    #[serde(rename = "locked")]
460    Locked,
461}
462
463impl SegState {
464    /// Position in the life cycle, used when segments are joined (the joined segment is as far along as its
465    /// least advanced part). `Rejected` ranks just above `New`: it has a target but needs work.
466    pub fn rank(self) -> u8 {
467        match self {
468            SegState::New => 0,
469            SegState::Rejected => 1,
470            SegState::Draft => 2,
471            SegState::Translated => 3,
472            SegState::Confirmed => 4,
473            SegState::Reviewed => 5,
474            SegState::SignedOff => 6,
475            SegState::Locked => 7,
476        }
477    }
478
479    /// Inverse of [`SegState::rank`]; anything above the top rank is `Locked`.
480    pub fn from_rank(r: u8) -> SegState {
481        match r {
482            0 => SegState::New,
483            1 => SegState::Rejected,
484            2 => SegState::Draft,
485            3 => SegState::Translated,
486            4 => SegState::Confirmed,
487            5 => SegState::Reviewed,
488            6 => SegState::SignedOff,
489            _ => SegState::Locked,
490        }
491    }
492
493    /// True when a person accepted the target (translated or further along).
494    pub fn is_accepted(self) -> bool {
495        self.rank() >= SegState::Translated.rank()
496    }
497}
498
499/// Where a segment's target came from. Match with a wildcard arm: a 1.x release may add kinds (a JSON file with
500/// a kind this release does not know reads as `Other`).
501#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
502#[serde(rename_all = "lowercase")]
503#[non_exhaustive]
504pub enum OriginKind {
505    /// Translation memory.
506    Tm,
507    /// Machine translation engine.
508    Mt,
509    /// Language model translation or post-edit.
510    Ai,
511    /// Typed by a person.
512    Human,
513    /// Anything else; `Origin::name` says more. An unknown kind in a JSON file also reads as `Other`.
514    #[default]
515    #[serde(other)]
516    Other,
517}
518
519/// How a target came to be, with the match percentage when it came from memory. Build it with [`Origin::new`].
520#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
521#[non_exhaustive]
522pub struct Origin {
523    /// Memory, machine, AI, person or other.
524    pub kind: OriginKind,
525    /// Engine, memory or person: "Acme TM", "engine-2", "ana". Free text.
526    #[serde(default, skip_serializing_if = "Option::is_none")]
527    pub name: Option<String>,
528    /// Match percentage as the file states it (0 to 100; some tools write 101 for a context match).
529    #[serde(default, skip_serializing_if = "Option::is_none")]
530    pub match_pct: Option<u8>,
531}
532
533impl Origin {
534    /// An origin of this kind, with no name and no match percentage.
535    pub fn new(kind: OriginKind) -> Origin {
536        Origin { kind, name: None, match_pct: None }
537    }
538    /// Sets the match percentage.
539    pub fn with_match(mut self, pct: u8) -> Origin {
540        self.match_pct = Some(pct);
541        self
542    }
543    /// Sets (or with `None` clears) the match percentage.
544    pub fn with_match_pct(mut self, pct: Option<u8>) -> Origin {
545        self.match_pct = pct;
546        self
547    }
548    /// Sets (or with `None` clears) the engine, memory or person name.
549    pub fn with_name(mut self, name: impl IntoOptionString) -> Origin {
550        self.name = name.into_option_string();
551        self
552    }
553}
554
555/// One translatable piece of a unit: its source, and its target once there is one. Build it with
556/// [`Segment::new`] and the `with_*` methods.
557#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
558#[non_exhaustive]
559pub struct Segment {
560    /// Unique within the document: `<unit id>` when the unit has one segment, else `<unit id>#<n>` (1-based).
561    pub id: String,
562    /// The source text with its inline codes.
563    pub source: Vec<Inline>,
564    /// Empty = untranslated, unless `empty_target` says the translation is empty on purpose (see below).
565    #[serde(default)]
566    pub target: Vec<Inline>,
567    /// Where the segment is in its life (new, draft, translated, ...).
568    #[serde(default)]
569    pub state: SegState,
570    /// Where the target came from. `None` for monolingual files and for targets nobody labelled.
571    #[serde(default, skip_serializing_if = "Option::is_none")]
572    pub origin: Option<Origin>,
573    /// Translated to nothing on purpose. The empty-translation rule: a segment with an empty `target` is
574    /// untranslated and the writer keeps its source text, unless `empty_target` is true; then the segment counts as
575    /// translated ([`Segment::has_target`]) and the writer writes nothing for it. [`Document::set_target_empty`]
576    /// sets it; [`Document::set_target`] with any target clears it. Left out of the JSON when false. (Localization
577    /// OS writes an empty target as an empty value or paragraph: its adapter sets this flag for an empty LocOS
578    /// target.)
579    #[serde(default, skip_serializing_if = "is_false")]
580    pub empty_target: bool,
581}
582
583impl Segment {
584    /// An untranslated segment (no target, state `New`, no origin).
585    pub fn new(id: impl Into<String>, source: Vec<Inline>) -> Segment {
586        Segment { id: id.into(), source, target: vec![], state: SegState::New, origin: None, empty_target: false }
587    }
588    /// True when the segment is translated: it has a target, or it was translated to nothing on purpose.
589    pub fn has_target(&self) -> bool {
590        !self.target.is_empty() || self.empty_target
591    }
592    /// The text to write: the target, nothing for an empty translation, or the source when untranslated.
593    pub fn output(&self) -> &[Inline] {
594        if self.has_target() {
595            &self.target
596        } else {
597            &self.source
598        }
599    }
600    /// Marks (or unmarks) the segment as translated to nothing on purpose; marking clears the target.
601    pub fn with_empty_target(mut self, empty_target: bool) -> Segment {
602        self.empty_target = empty_target;
603        if empty_target {
604            self.target.clear();
605        }
606        self
607    }
608    /// Sets the target as it is (no tag check: use [`Document::set_target`] for edits).
609    pub fn with_target(mut self, target: Vec<Inline>) -> Segment {
610        self.target = target;
611        self
612    }
613    /// Sets the state.
614    pub fn with_state(mut self, state: SegState) -> Segment {
615        self.state = state;
616        self
617    }
618    /// Sets (or with `None` clears) where the target came from.
619    pub fn with_origin(mut self, origin: impl Into<Option<Origin>>) -> Segment {
620        self.origin = origin.into();
621        self
622    }
623}
624
625/// A comment on a unit: a translator query, a developer instruction, a reviewer remark. Build it with
626/// [`Note::new`].
627#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
628#[non_exhaustive]
629pub struct Note {
630    /// Who wrote it, when the file says.
631    #[serde(default, skip_serializing_if = "Option::is_none")]
632    pub author: Option<String>,
633    /// The comment.
634    pub text: String,
635    /// Kind as the file has it: "comment", "instruction", "developer", "reviewer", ... Free text.
636    #[serde(default, skip_serializing_if = "Option::is_none")]
637    pub kind: Option<String>,
638}
639
640impl Note {
641    /// A note with this text, no author and no kind.
642    pub fn new(text: impl Into<String>) -> Note {
643        Note { author: None, text: text.into(), kind: None }
644    }
645    /// Sets (or with `None` clears) the author.
646    pub fn with_author(mut self, author: impl IntoOptionString) -> Note {
647        self.author = author.into_option_string();
648        self
649    }
650    /// Sets (or clears) the kind ("comment", "developer", ...).
651    pub fn with_kind(mut self, kind: impl IntoOptionString) -> Note {
652        self.kind = kind.into_option_string();
653        self
654    }
655}
656
657/// What helps a translator, an AI lane or a preview understand a unit. Build it with [`UnitContext::new`] and the
658/// `with_*` methods; `extra` takes anything without a field of its own.
659#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
660#[non_exhaustive]
661pub struct UnitContext {
662    /// What the unit is: "heading", "paragraph", "list-item", "cell", "button", "title", "alt", "key",
663    /// "subtitle", ... Free text; parsers use the most specific word they know.
664    pub kind: Option<String>,
665    /// Style or element name as the file has it, e.g. "Heading 2", "h2", "td".
666    pub style: Option<String>,
667    /// Resource key or path for key/value formats (JSON pointer, PO msgctxt + msgid, subtitle number).
668    pub key: Option<String>,
669    /// Nearest heading text above the unit, when the format has headings.
670    pub heading: Option<String>,
671    /// Location in the original, readable: `word/document.xml paragraph 12`, `/html/body/main/p[3]`.
672    pub location: Option<String>,
673    /// Maximum length in characters, when the file states one.
674    pub max_len: Option<usize>,
675    /// Comments or notes attached in the file (translator comments, PO comments, DOCX comments).
676    #[serde(default)]
677    pub notes: Vec<String>,
678    /// Subtitle timing and similar extras the editor may show.
679    #[serde(default)]
680    pub extra: TextMap,
681    /// The unit's structural role in the document (a heading, a header, a speaker note, ...), when the format
682    /// knows it. Left out of JSON when unset. Not filled under the `locos` profile.
683    #[serde(default, skip_serializing_if = "Option::is_none")]
684    pub role: Option<Role>,
685    /// The outline level for [`Role::Heading`] (1 for a top-level heading). Left out of JSON when unset.
686    #[serde(default, skip_serializing_if = "Option::is_none")]
687    pub level: Option<u8>,
688}
689
690/// A unit's structural role ([`UnitContext::role`]). JSON: the lowercase name. A value this release does not know
691/// (written by a newer one) reads as [`Role::Other`].
692#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
693#[serde(rename_all = "lowercase")]
694#[non_exhaustive]
695pub enum Role {
696    /// A heading; [`UnitContext::level`] holds its level.
697    Heading,
698    /// The document title.
699    Title,
700    /// The document subtitle.
701    Subtitle,
702    /// A slide's title.
703    SlideTitle,
704    /// Page header text.
705    Header,
706    /// Page footer text.
707    Footer,
708    /// Footnote text.
709    Footnote,
710    /// Endnote text.
711    Endnote,
712    /// Speaker notes.
713    Notes,
714    /// Comment (annotation) text.
715    Comment,
716    /// A table or figure caption.
717    Caption,
718    /// A sheet's name.
719    SheetName,
720    /// A role from a newer release, or one without a name here.
721    #[serde(other)]
722    Other,
723}
724
725impl Role {
726    /// The JSON name (`"heading"`, `"slidetitle"`, ...).
727    pub fn as_str(self) -> &'static str {
728        match self {
729            Role::Heading => "heading",
730            Role::Title => "title",
731            Role::Subtitle => "subtitle",
732            Role::SlideTitle => "slidetitle",
733            Role::Header => "header",
734            Role::Footer => "footer",
735            Role::Footnote => "footnote",
736            Role::Endnote => "endnote",
737            Role::Notes => "notes",
738            Role::Comment => "comment",
739            Role::Caption => "caption",
740            Role::SheetName => "sheetname",
741            Role::Other => "other",
742        }
743    }
744}
745
746impl std::fmt::Display for Role {
747    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
748        f.write_str(self.as_str())
749    }
750}
751
752impl UnitContext {
753    /// Sets (or with `None` clears) the structural role.
754    pub fn with_role(mut self, role: impl Into<Option<Role>>) -> UnitContext {
755        self.role = role.into();
756        self
757    }
758    /// Sets (or clears) the heading level.
759    pub fn with_level(mut self, level: impl Into<Option<u8>>) -> UnitContext {
760        self.level = level.into();
761        self
762    }
763    /// The structural role, when known.
764    pub fn role(&self) -> Option<Role> {
765        self.role
766    }
767    /// The heading level, when known.
768    pub fn level(&self) -> Option<u8> {
769        self.level
770    }
771    /// Sets (or with `None` clears) the structural role, in place.
772    pub fn set_role(&mut self, role: impl Into<Option<Role>>) {
773        self.role = role.into();
774    }
775    /// Sets (or clears) the heading level, in place.
776    pub fn set_level(&mut self, level: impl Into<Option<u8>>) {
777        self.level = level.into();
778    }
779    /// Sets the role [`Role::Heading`] and its level in one call (a level of 0 is stored as unset).
780    pub fn set_heading_role(&mut self, level: u8) {
781        self.role = Some(Role::Heading);
782        self.level = (level > 0).then_some(level);
783    }
784}
785
786impl UnitContext {
787    /// An empty context.
788    pub fn new() -> UnitContext {
789        UnitContext::default()
790    }
791    /// Sets (or with `None` clears) what the unit is ("heading", "cell", ...).
792    pub fn with_kind(mut self, kind: impl IntoOptionString) -> UnitContext {
793        self.kind = kind.into_option_string();
794        self
795    }
796    /// Sets (or clears) the style or element name.
797    pub fn with_style(mut self, style: impl IntoOptionString) -> UnitContext {
798        self.style = style.into_option_string();
799        self
800    }
801    /// Sets (or clears) the resource key or path.
802    pub fn with_key(mut self, key: impl IntoOptionString) -> UnitContext {
803        self.key = key.into_option_string();
804        self
805    }
806    /// Sets (or clears) the nearest heading.
807    pub fn with_heading(mut self, heading: impl IntoOptionString) -> UnitContext {
808        self.heading = heading.into_option_string();
809        self
810    }
811    /// Sets (or clears) the readable location.
812    pub fn with_location(mut self, location: impl IntoOptionString) -> UnitContext {
813        self.location = location.into_option_string();
814        self
815    }
816    /// Sets (or clears) the maximum length in characters.
817    pub fn with_max_len(mut self, max_len: Option<usize>) -> UnitContext {
818        self.max_len = max_len;
819        self
820    }
821    /// Replaces the notes.
822    pub fn with_notes(mut self, notes: Vec<String>) -> UnitContext {
823        self.notes = notes;
824        self
825    }
826    /// Replaces the extras (a [`TextMap`], or a `BTreeMap<String, String>`).
827    pub fn with_extra(mut self, extra: impl Into<TextMap>) -> UnitContext {
828        self.set_extra(extra);
829        self
830    }
831
832    /// What the unit is ("heading", "cell", ...).
833    pub fn kind(&self) -> Option<&str> {
834        self.kind.as_deref()
835    }
836    /// The style or element name.
837    pub fn style(&self) -> Option<&str> {
838        self.style.as_deref()
839    }
840    /// The resource key or path.
841    pub fn key(&self) -> Option<&str> {
842        self.key.as_deref()
843    }
844    /// The nearest heading.
845    pub fn heading(&self) -> Option<&str> {
846        self.heading.as_deref()
847    }
848    /// The readable location.
849    pub fn location(&self) -> Option<&str> {
850        self.location.as_deref()
851    }
852    /// Sets (or with `None` clears) what the unit is, in place.
853    pub fn set_kind(&mut self, kind: impl IntoOptionString) {
854        self.kind = kind.into_option_string();
855    }
856    /// Sets (or clears) the style or element name, in place.
857    pub fn set_style(&mut self, style: impl IntoOptionString) {
858        self.style = style.into_option_string();
859    }
860    /// Sets (or clears) the resource key or path, in place.
861    pub fn set_key(&mut self, key: impl IntoOptionString) {
862        self.key = key.into_option_string();
863    }
864    /// Sets (or clears) the nearest heading, in place.
865    pub fn set_heading(&mut self, heading: impl IntoOptionString) {
866        self.heading = heading.into_option_string();
867    }
868    /// Sets (or clears) the readable location, in place.
869    pub fn set_location(&mut self, location: impl IntoOptionString) {
870        self.location = location.into_option_string();
871    }
872
873    /// The extras, read-only.
874    pub fn extra(&self) -> &TextMap {
875        &self.extra
876    }
877    /// The extras, to change in place.
878    pub fn extra_mut(&mut self) -> &mut TextMap {
879        &mut self.extra
880    }
881    /// Replaces the extras (a [`TextMap`], or a `BTreeMap<String, String>`).
882    pub fn set_extra(&mut self, extra: impl Into<TextMap>) {
883        self.extra = extra.into();
884    }
885}
886
887/// One translatable unit of the file (a paragraph, a cell, a string): its segments, the original markup of its
888/// inline codes and its context. Build it with [`Unit::new`] or [`Unit::from_segments`] and the `with_*` methods.
889#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
890#[serde(from = "UnitRepr")]
891#[non_exhaustive]
892pub struct Unit {
893    /// Unique within the document, stable for the same input file.
894    pub id: String,
895    /// One segment before sentence splitting; one per sentence after.
896    pub segments: Vec<Segment>,
897    /// Text between segments as it appeared in the source (spaces after a full stop). Always
898    /// `segments.len() - 1` entries; the writer joins segment targets with these.
899    #[serde(default)]
900    pub separators: Vec<String>,
901    /// Original markup per inline code id.
902    #[serde(default)]
903    pub codes: Codes,
904    /// What helps a translator understand the unit.
905    #[serde(default)]
906    pub context: UnitContext,
907    /// False for content shown for context only (locked).
908    #[serde(default = "yes")]
909    pub translate: bool,
910    /// Comments attached to the unit in a bilingual file. (Source files keep theirs in `context.notes`.)
911    #[serde(default, skip_serializing_if = "Vec::is_empty")]
912    pub notes: Vec<Note>,
913    /// Why the unit is locked ("context match", "locked by the project"). Free text, usually with
914    /// `translate == false`.
915    #[serde(default, skip_serializing_if = "Option::is_none")]
916    pub lock_reason: Option<String>,
917    /// What the parser needs to write the unit back and nobody else sees: the value as written in the file, its
918    /// white space, a layout flag. Keyed by a short name the parser picks ("raw", "lead"). It is not an inline code,
919    /// so editors, the LocOS token map and tag checks never see it. Left out of the JSON when empty. (Parsers used
920    /// to keep this in `codes` under `~` names; such codes in an old JSON document are moved here when it is read.)
921    #[serde(default, skip_serializing_if = "TextMap::is_empty")]
922    pub hidden: TextMap,
923    /// The plural group this unit is one form of (see [`PluralSlot`]); `None` for most units and under the LocOS
924    /// profile. Left out of the JSON when unset. No writer reads it.
925    #[serde(default, skip_serializing_if = "Option::is_none")]
926    pub plural: Option<Box<PluralSlot>>,
927}
928
929fn yes() -> bool {
930    true
931}
932
933/// The JSON form of a [`Unit`] as read: the same fields, with old `~` codes moved into `hidden`.
934#[derive(Deserialize)]
935struct UnitRepr {
936    id: String,
937    segments: Vec<Segment>,
938    #[serde(default)]
939    separators: Vec<String>,
940    #[serde(default)]
941    codes: Codes,
942    #[serde(default)]
943    context: UnitContext,
944    #[serde(default = "yes")]
945    translate: bool,
946    #[serde(default)]
947    notes: Vec<Note>,
948    #[serde(default)]
949    lock_reason: Option<String>,
950    #[serde(default)]
951    hidden: TextMap,
952    #[serde(default)]
953    plural: Option<Box<PluralSlot>>,
954}
955
956impl From<UnitRepr> for Unit {
957    fn from(r: UnitRepr) -> Unit {
958        let mut hidden = r.hidden;
959        let mut codes = r.codes;
960        // an old parser's hidden value: a `~` code with no open or close markup, whose `standalone` (or, for a
961        // flag, `label`) held it. Most documents have none, so the map is only rebuilt when one is there.
962        let old = |k: &str, c: &CodeData| k.starts_with('~') && c.open.is_none() && c.close.is_none();
963        if codes.iter().any(|(k, c)| old(k, c)) {
964            let mut kept = Vec::with_capacity(codes.len());
965            for (k, c) in codes {
966                if old(&k, &c) {
967                    let name = &k[1..];
968                    if !hidden.contains_key(name) {
969                        hidden.insert(name, c.standalone.or(c.label).unwrap_or_default());
970                    }
971                } else {
972                    kept.push((k, c));
973                }
974            }
975            codes = kept.into_iter().collect();
976        }
977        Unit {
978            id: r.id,
979            segments: r.segments,
980            separators: r.separators,
981            codes,
982            context: r.context,
983            translate: r.translate,
984            notes: r.notes,
985            lock_reason: r.lock_reason,
986            hidden,
987            plural: r.plural,
988        }
989    }
990}
991
992impl Unit {
993    /// A unit with one segment holding `source`.
994    pub fn new(id: impl Into<String>, source: Vec<Inline>) -> Unit {
995        let id = id.into();
996        let seg = Segment::new(id.clone(), source);
997        Unit::from_segments(id, vec![seg])
998    }
999
1000    /// A unit made of the given segments (their ids are kept as they are). Separators start empty, one per gap.
1001    pub fn from_segments(id: impl Into<String>, segments: Vec<Segment>) -> Unit {
1002        Unit {
1003            separators: vec![String::new(); segments.len().saturating_sub(1)],
1004            segments,
1005            id: id.into(),
1006            codes: Codes::new(),
1007            context: UnitContext::default(),
1008            translate: true,
1009            notes: vec![],
1010            lock_reason: None,
1011            hidden: TextMap::new(),
1012            plural: None,
1013        }
1014    }
1015    /// A hidden value (see [`Unit::hidden`]).
1016    pub fn hidden(&self, key: &str) -> Option<&str> {
1017        self.hidden.get(key)
1018    }
1019    /// Sets a hidden value.
1020    pub fn set_hidden(&mut self, key: impl Into<String>, value: impl Into<String>) {
1021        self.hidden.insert(key.into(), value.into());
1022    }
1023    /// True when the hidden value is set (a flag).
1024    pub fn has_hidden(&self, key: &str) -> bool {
1025        self.hidden.contains_key(key)
1026    }
1027    /// Sets a hidden value (builder form of [`Unit::set_hidden`]).
1028    pub fn with_hidden(mut self, key: impl Into<String>, value: impl Into<String>) -> Unit {
1029        self.set_hidden(key, value);
1030        self
1031    }
1032    /// Every hidden value, read-only.
1033    pub fn hidden_map(&self) -> &TextMap {
1034        &self.hidden
1035    }
1036    /// Every hidden value, to change in place.
1037    pub fn hidden_map_mut(&mut self) -> &mut TextMap {
1038        &mut self.hidden
1039    }
1040    /// Replaces the hidden values (a [`TextMap`], or a `BTreeMap<String, String>`).
1041    pub fn set_hidden_map(&mut self, hidden: impl Into<TextMap>) {
1042        self.hidden = hidden.into();
1043    }
1044
1045    /// The original markup of the inline codes, read-only. Prefer it to the field.
1046    pub fn codes(&self) -> &Codes {
1047        &self.codes
1048    }
1049    /// The original markup of the inline codes, to change in place (see [`Unit::codes`]).
1050    pub fn codes_mut(&mut self) -> &mut Codes {
1051        &mut self.codes
1052    }
1053    /// Replaces the original markup of the inline codes (a [`Codes`], or a `BTreeMap<String, CodeData>`).
1054    pub fn set_codes(&mut self, codes: impl Into<Codes>) {
1055        self.codes = codes.into();
1056    }
1057    /// Replaces the separators (one per gap between segments).
1058    pub fn with_separators(mut self, separators: Vec<String>) -> Unit {
1059        self.separators = separators;
1060        self
1061    }
1062    /// Replaces the original markup of the inline codes (a [`Codes`], or a `BTreeMap<String, CodeData>`).
1063    pub fn with_codes(mut self, codes: impl Into<Codes>) -> Unit {
1064        self.set_codes(codes);
1065        self
1066    }
1067    /// Adds (or replaces) the original markup of one inline code.
1068    pub fn with_code(mut self, id: impl Into<String>, code: CodeData) -> Unit {
1069        self.codes.insert(id.into(), code);
1070        self
1071    }
1072    /// Sets the context.
1073    pub fn with_context(mut self, context: UnitContext) -> Unit {
1074        self.context = context;
1075        self
1076    }
1077    /// Sets whether the unit is translatable (`false`: shown for context only).
1078    pub fn with_translate(mut self, translate: bool) -> Unit {
1079        self.translate = translate;
1080        self
1081    }
1082    /// Replaces the bilingual-file notes.
1083    pub fn with_notes(mut self, notes: Vec<Note>) -> Unit {
1084        self.notes = notes;
1085        self
1086    }
1087    /// Sets (or with `None` clears) why the unit is locked.
1088    pub fn with_lock_reason(mut self, reason: impl IntoOptionString) -> Unit {
1089        self.lock_reason = reason.into_option_string();
1090        self
1091    }
1092
1093    /// The whole unit's source, segments joined with their separators.
1094    pub fn source(&self) -> Vec<Inline> {
1095        self.join(|s| &s.source)
1096    }
1097
1098    /// The text to write for this unit: each segment's target, or its source when the segment is untranslated
1099    /// (as every CAT tool does), or nothing for a segment translated to empty ([`Segment::empty_target`]).
1100    pub fn output(&self) -> Vec<Inline> {
1101        self.join(|s| if s.has_target() { &s.target } else { &s.source })
1102    }
1103
1104    /// True when some segment of a translatable unit is translated (has a target or an empty translation).
1105    pub fn is_translated(&self) -> bool {
1106        self.translate && self.segments.iter().any(Segment::has_target)
1107    }
1108
1109    fn join<'a>(&'a self, pick: impl Fn(&'a Segment) -> &'a Vec<Inline>) -> Vec<Inline> {
1110        let mut out = Vec::new();
1111        for (i, seg) in self.segments.iter().enumerate() {
1112            if i > 0 {
1113                if let Some(sep) = self.separators.get(i - 1) {
1114                    if !sep.is_empty() {
1115                        out.push(Inline::Text(sep.clone()));
1116                    }
1117                }
1118            }
1119            out.extend(pick(seg).iter().cloned());
1120        }
1121        merge_text(out)
1122    }
1123}
1124
1125// Unit model step 6: the plural slot.
1126impl Unit {
1127    /// The plural group this unit is one form of, if any.
1128    pub fn plural(&self) -> Option<&PluralSlot> {
1129        self.plural.as_deref()
1130    }
1131    /// The plural slot, to change in place.
1132    pub fn plural_mut(&mut self) -> Option<&mut PluralSlot> {
1133        self.plural.as_deref_mut()
1134    }
1135    /// Sets (or with `None` clears) the plural slot.
1136    pub fn set_plural(&mut self, plural: impl Into<Option<PluralSlot>>) {
1137        self.plural = plural.into().map(Box::new);
1138    }
1139    /// Sets the plural slot (builder form of [`Unit::set_plural`]).
1140    pub fn with_plural(mut self, plural: impl Into<Option<PluralSlot>>) -> Unit {
1141        self.set_plural(plural);
1142        self
1143    }
1144}
1145
1146/// Joins neighbouring `Text` pieces.
1147pub fn merge_text(v: Vec<Inline>) -> Vec<Inline> {
1148    let mut out: Vec<Inline> = Vec::with_capacity(v.len());
1149    for i in v {
1150        match (out.last_mut(), i) {
1151            (Some(Inline::Text(a)), Inline::Text(b)) => a.push_str(&b),
1152            (_, Inline::Text(t)) if t.is_empty() => {}
1153            (_, x) => out.push(x),
1154        }
1155    }
1156    out
1157}
1158
1159/// Plain text with the tags removed.
1160pub fn plain_text(v: &[Inline]) -> String {
1161    v.iter()
1162        .filter_map(|i| match i {
1163            Inline::Text(t) => Some(t.as_str()),
1164            _ => None,
1165        })
1166        .collect()
1167}
1168
1169/// One piece of a text skeleton: literal output, or the place where a unit's text goes. Closed: anything else a
1170/// format needs lives in its own parts' text or in [`Unit::hidden`].
1171#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1172#[serde(rename_all = "lowercase")]
1173pub enum SkelPart {
1174    /// Literal output.
1175    Raw(String),
1176    /// Index into `Document::units`. The parser decides how the unit's inlines are rendered (escaping, codes).
1177    Unit(usize),
1178}
1179
1180/// The content of one zip entry in a skeleton. Closed: copied bytes or rebuilt text.
1181#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1182#[serde(rename_all = "lowercase")]
1183pub enum ZipData {
1184    /// Copied unchanged. In JSON this is a base64 string; the old array-of-integers form still reads.
1185    Raw(#[serde(with = "b64")] Vec<u8>),
1186    /// A text entry rebuilt from parts.
1187    Parts(Vec<SkelPart>),
1188}
1189
1190/// One entry of a zip skeleton, in the archive's order. Build it with [`ZipEntry::new`] or [`ZipEntry::raw`].
1191#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1192#[non_exhaustive]
1193pub struct ZipEntry {
1194    /// The member name in the archive.
1195    pub name: String,
1196    /// Its content.
1197    pub data: ZipData,
1198}
1199
1200impl ZipEntry {
1201    /// An entry with this name and content.
1202    pub fn new(name: impl Into<String>, data: ZipData) -> ZipEntry {
1203        ZipEntry { name: name.into(), data }
1204    }
1205    /// An entry copied unchanged.
1206    pub fn raw(name: impl Into<String>, bytes: Vec<u8>) -> ZipEntry {
1207        ZipEntry::new(name, ZipData::Raw(bytes))
1208    }
1209}
1210
1211/// Which parser made a skeleton: the crate name, its version (for information) and the skeleton schema number.
1212/// The schema is an integer each format crate bumps only when its skeleton layout changes, so a new crate release
1213/// that did not touch the layout still merges old skeletons (see [`check_parser`]).
1214#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1215#[non_exhaustive]
1216pub struct ParserInfo {
1217    /// The producing crate, e.g. "bilingua-docx".
1218    pub name: String,
1219    /// Its semver version, e.g. "0.1.0". Informational only; never compared.
1220    pub version: String,
1221    /// The skeleton schema number. Absent in stamps written before schemas existed, which read as schema 1.
1222    #[serde(default = "legacy_schema")]
1223    pub schema: u32,
1224}
1225
1226fn legacy_schema() -> u32 {
1227    1
1228}
1229
1230impl ParserInfo {
1231    /// A stamp for this crate name, version and skeleton schema (usually written `parser_info!()`).
1232    pub fn new(name: impl Into<String>, version: impl Into<String>, schema: u32) -> ParserInfo {
1233        ParserInfo { name: name.into(), version: version.into(), schema }
1234    }
1235
1236    /// True when a skeleton made by `self` can be read by `current`: same crate and a schema no newer than the
1237    /// current one.
1238    pub fn compatible_with(&self, current: &ParserInfo) -> bool {
1239        self.name == current.name && self.schema <= current.schema
1240    }
1241}
1242
1243/// The producing parser of the running crate: `parser_info!()` expands to a [`ParserInfo`] with the calling
1244/// crate's name, version and `crate::SKELETON_SCHEMA`. Every format crate defines that constant
1245/// (`pub const SKELETON_SCHEMA: u32 = 1;`) and bumps it only when its skeleton changes.
1246/// `parser_info!(n)` stamps an explicit schema instead.
1247// `crate::SKELETON_SCHEMA` must resolve in the calling crate: that is the point.
1248#[allow(clippy::crate_in_macro_def)]
1249#[macro_export]
1250macro_rules! parser_info {
1251    () => {
1252        $crate::parser_info!(crate::SKELETON_SCHEMA)
1253    };
1254    ($schema:expr) => {
1255        $crate::ParserInfo::new(env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"), $schema)
1256    };
1257}
1258
1259/// Refuses a document whose skeleton came from another crate or from a newer schema than `current`. Older
1260/// schemas and skeletons with no record (written before stamps existed) are accepted; a crate that stops
1261/// reading some old schema uses [`check_parser_min`].
1262pub fn check_parser(doc: &Document, current: &ParserInfo) -> Result<(), Error> {
1263    check_parser_min(doc, current, 1)
1264}
1265
1266/// Like [`check_parser`], but also refuses schemas older than `oldest`, the oldest one the crate still reads.
1267pub fn check_parser_min(doc: &Document, current: &ParserInfo, oldest: u32) -> Result<(), Error> {
1268    match doc.skeleton.parser() {
1269        Some(found) if !found.compatible_with(current) || found.schema < oldest => Err(Error::ParserVersion {
1270            found: format!("{} {} (skeleton schema {})", found.name, found.version, found.schema),
1271            expected: if found.name != current.name {
1272                current.name.clone()
1273            } else if found.schema > current.schema {
1274                format!("{} {} (reads skeleton schema {} and older)", current.name, current.version, current.schema)
1275            } else {
1276                format!("{} {} (reads skeleton schema {} to {})", current.name, current.version, oldest, current.schema)
1277            },
1278        }),
1279        _ => Ok(()),
1280    }
1281}
1282
1283/// Everything in the file that is not translatable text. New kinds of skeleton come as new variants (match with a
1284/// wildcard arm); the fields of each variant are fixed for 1.x (a format records more in its parts, in the
1285/// `encoding` tag's `;name=value` items, or in [`Unit::hidden`]).
1286#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1287#[serde(rename_all = "lowercase")]
1288#[non_exhaustive]
1289pub enum Skeleton {
1290    /// A text file: parts in order. `encoding` is what the writer must produce ("utf-8", "utf-8-bom", ...).
1291    Text {
1292        /// The parts in order.
1293        parts: Vec<SkelPart>,
1294        /// The encoding tag (the envelope of [`enc::decode_text`]: `"utf-8"`, `"windows-1252;nl=crlf"`, ...).
1295        encoding: String,
1296        /// The parser that made it.
1297        #[serde(default, skip_serializing_if = "Option::is_none")]
1298        parser: Option<ParserInfo>,
1299    },
1300    /// A zip container (DOCX, XLSX, PPTX, ODF, IDML): entries in their original order.
1301    Zip {
1302        /// The entries in archive order.
1303        entries: Vec<ZipEntry>,
1304        /// The parser that made it.
1305        #[serde(default, skip_serializing_if = "Option::is_none")]
1306        parser: Option<ParserInfo>,
1307    },
1308    /// A binary file kept whole (a compiled MO catalog): the writer rebuilds the file from these bytes and the
1309    /// units. In JSON the bytes are a base64 string.
1310    Binary {
1311        /// The original file.
1312        #[serde(with = "b64")]
1313        data: Vec<u8>,
1314        /// The parser that made it.
1315        #[serde(default, skip_serializing_if = "Option::is_none")]
1316        parser: Option<ParserInfo>,
1317    },
1318}
1319
1320impl Default for Skeleton {
1321    /// An empty UTF-8 text skeleton.
1322    fn default() -> Self {
1323        Skeleton::Text { parts: Vec::new(), encoding: "utf-8".into(), parser: None }
1324    }
1325}
1326
1327impl Skeleton {
1328    /// A text skeleton stamped with the producing parser.
1329    pub fn text(parts: Vec<SkelPart>, encoding: impl Into<String>, parser: ParserInfo) -> Skeleton {
1330        Skeleton::Text { parts, encoding: encoding.into(), parser: Some(parser) }
1331    }
1332    /// A zip skeleton stamped with the producing parser.
1333    pub fn zip(entries: Vec<ZipEntry>, parser: ParserInfo) -> Skeleton {
1334        Skeleton::Zip { entries, parser: Some(parser) }
1335    }
1336    /// A binary skeleton stamped with the producing parser.
1337    pub fn binary(data: Vec<u8>, parser: ParserInfo) -> Skeleton {
1338        Skeleton::Binary { data, parser: Some(parser) }
1339    }
1340    /// The parser that made this skeleton, if recorded.
1341    pub fn parser(&self) -> Option<&ParserInfo> {
1342        match self {
1343            Skeleton::Text { parser, .. } | Skeleton::Zip { parser, .. } | Skeleton::Binary { parser, .. } => parser.as_ref(),
1344        }
1345    }
1346}
1347
1348/// How finely units are split into segments.
1349#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1350#[serde(rename_all = "lowercase")]
1351#[non_exhaustive]
1352pub enum Granularity {
1353    /// SRX sentence segmentation (the classic CAT default).
1354    #[default]
1355    Sentence,
1356    /// One segment per unit (paragraph, cell, string).
1357    Paragraph,
1358    /// One segment per unit, flagged so AI lanes translate the whole document in one pass. The editor still
1359    /// edits per unit.
1360    Document,
1361}
1362
1363/// An extracted file: its units and its skeleton. Build it with [`Document::new`] and the `with_*` methods; edit
1364/// targets with [`Document::set_target`] and friends, which check the tags. `Default` is an empty document of no
1365/// format (no writer accepts it).
1366#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1367#[non_exhaustive]
1368pub struct Document {
1369    /// Parser id, e.g. "html", "docx", "json".
1370    pub format: String,
1371    /// Original file name, when known.
1372    pub name: Option<String>,
1373    /// The source language (a BCP 47 tag, `en`, `de-DE`), when known.
1374    pub source_lang: Option<String>,
1375    /// The target language, when known.
1376    pub target_lang: Option<String>,
1377    /// How finely the units are segmented.
1378    pub granularity: Granularity,
1379    /// The translatable units, in file order.
1380    pub units: Vec<Unit>,
1381    /// Everything else in the file.
1382    pub skeleton: Skeleton,
1383    /// Things the reader noticed but did not refuse the file for (text that looks garbled in the code page it was
1384    /// read with, ...). Left out of the JSON when empty.
1385    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1386    pub warnings: Vec<Warning>,
1387    /// The encoding a text file was decoded from when it was not UTF-8 (`utf-16le`, `windows-1252`, `shift_jis`,
1388    /// ...); `None` for UTF-8 (with or without BOM) and for zip and binary files. The `bilingua` facade fills it
1389    /// from the skeleton; left out of the JSON when unset.
1390    #[serde(default, skip_serializing_if = "Option::is_none")]
1391    pub source_encoding: Option<String>,
1392    /// Segment id to position, built on the first [`Document::set_target`] and checked on every use.
1393    #[serde(skip)]
1394    seg_index: SegIndex,
1395}
1396
1397/// The lookup behind [`Document::set_target`]. It is a cache: it never takes part in equality, serialisation or
1398/// the document's identity, and a stale entry is detected and rebuilt, never trusted.
1399#[derive(Default)]
1400struct SegIndex(Option<std::collections::HashMap<String, (usize, usize)>>);
1401
1402/// A clone starts without the cache (it is rebuilt on its first use), so cloning a document costs no more than
1403/// before the index existed.
1404impl Clone for SegIndex {
1405    fn clone(&self) -> SegIndex {
1406        SegIndex(None)
1407    }
1408}
1409
1410/// The cache never shows in a document's `Debug` output beyond its name, so the output does not change with it.
1411impl std::fmt::Debug for SegIndex {
1412    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1413        f.write_str("SegIndex")
1414    }
1415}
1416
1417impl PartialEq for SegIndex {
1418    fn eq(&self, _: &SegIndex) -> bool {
1419        true
1420    }
1421}
1422
1423impl Eq for SegIndex {}
1424
1425// Unit model step 6: plural categories of the target.
1426impl Document {
1427    /// The categories the target language uses for `kind`, in CLDR order and always with `other` (`one`, `few`,
1428    /// `many`, `other` for Polish cardinals), read from `target_lang` through the shared CLDR table (the Babel data
1429    /// Localization OS uses; aliases such as `deu` and `iw` resolve). `None` for a select, without a target
1430    /// language, or for one the table does not know. Units hold no copy of them.
1431    pub fn plural_categories(&self, kind: PluralKind) -> Option<Vec<&'static str>> {
1432        plural::categories(self.target_lang.as_deref(), kind)
1433    }
1434}
1435
1436/// A notice about a file that was read anyway: it never stops a merge. `kind` is a stable word for programs
1437/// ("text_encoding"); `message` is plain text safe to show the person who uploaded the file.
1438#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1439#[non_exhaustive]
1440pub struct Warning {
1441    /// A stable word for programs (`text_encoding`).
1442    pub kind: String,
1443    /// Which part of the file the notice is about ("text encoding", an entry name, ...).
1444    #[serde(default, skip_serializing_if = "String::is_empty")]
1445    pub part: String,
1446    /// Plain text for the person who uploaded the file.
1447    pub message: String,
1448}
1449
1450impl Warning {
1451    /// A warning of this kind about this part.
1452    pub fn new(kind: impl Into<String>, part: impl Into<String>, message: impl Into<String>) -> Warning {
1453        Warning { kind: kind.into(), part: part.into(), message: message.into() }
1454    }
1455}
1456
1457impl Document {
1458    /// A document of `format` (the filter id) with its units and skeleton; no name, no languages, sentence
1459    /// granularity, no warnings.
1460    pub fn new(format: impl Into<String>, units: Vec<Unit>, skeleton: Skeleton) -> Document {
1461        Document { format: format.into(), name: None, source_lang: None, target_lang: None, granularity: Granularity::default(), units, skeleton, warnings: vec![], source_encoding: None, seg_index: SegIndex::default() }
1462    }
1463    /// Takes the languages and the granularity from the options the file was opened with (what every parser does).
1464    pub fn with_options(mut self, opts: &ExtractOptions) -> Document {
1465        self.source_lang = opts.source_lang.clone();
1466        self.target_lang = opts.target_lang.clone();
1467        self.granularity = opts.granularity;
1468        self
1469    }
1470    /// Sets (or with `None` clears) the file name.
1471    pub fn with_name(mut self, name: impl IntoOptionString) -> Document {
1472        self.name = name.into_option_string();
1473        self
1474    }
1475    /// Sets (or clears) the source language.
1476    pub fn with_source_lang(mut self, lang: impl IntoOptionString) -> Document {
1477        self.source_lang = lang.into_option_string();
1478        self
1479    }
1480    /// Sets (or clears) the target language.
1481    pub fn with_target_lang(mut self, lang: impl IntoOptionString) -> Document {
1482        self.target_lang = lang.into_option_string();
1483        self
1484    }
1485    /// Sets the granularity.
1486    pub fn with_granularity(mut self, granularity: Granularity) -> Document {
1487        self.granularity = granularity;
1488        self
1489    }
1490    /// The encoding of a text skeleton (or of a LocOS-profile markdown, po or subtitle skeleton), when it is not
1491    /// UTF-8: the base of its tag (`utf-16le-bom` and `utf-16le`
1492    /// both give `utf-16le`). `None` for UTF-8, binary plists, zip and binary skeletons.
1493    pub fn detected_source_encoding(&self) -> Option<String> {
1494        let encoding = match &self.skeleton {
1495            Skeleton::Text { encoding, .. } => encoding.as_str(),
1496            // the LocOS-profile text formats keep the decoded file under a first line with the skeleton tag
1497            Skeleton::Binary { data, .. } if matches!(self.format.as_str(), "markdown" | "po" | "srt" | "vtt") => enc::locos_skeleton_parts(data)?.0,
1498            _ => return None,
1499        };
1500        let base = encoding.split(';').next().unwrap_or("").to_ascii_lowercase();
1501        let base = base.strip_suffix("-bom").or_else(|| base.strip_suffix("-nobom")).unwrap_or(&base).to_string();
1502        (!matches!(base.as_str(), "" | "utf-8" | "utf8" | "bplist")).then_some(base)
1503    }
1504    /// Replaces the warnings.
1505    pub fn with_warnings(mut self, warnings: Vec<Warning>) -> Document {
1506        self.warnings = warnings;
1507        self
1508    }
1509
1510    /// Every segment with its unit, in order.
1511    pub fn segments(&self) -> impl Iterator<Item = (&Unit, &Segment)> {
1512        self.units.iter().flat_map(|u| u.segments.iter().map(move |s| (u, s)))
1513    }
1514
1515    /// The number of segments.
1516    pub fn segment_count(&self) -> usize {
1517        self.units.iter().map(|u| u.segments.len()).sum()
1518    }
1519
1520    /// The segment with this id and its unit.
1521    pub fn find(&self, seg_id: &str) -> Option<(&Unit, &Segment)> {
1522        self.segments().find(|(_, s)| s.id == seg_id)
1523    }
1524
1525    /// Sets a segment's target. Rejects unknown segments, untranslatable units, segments in state
1526    /// [`SegState::Locked`], and tags the source lacks or repeats. A missing tag is allowed (the writer leaves it out), as in catcore.
1527    ///
1528    /// The first call builds an index of segment ids (one pass over the document); later calls find the segment
1529    /// through it, so setting every segment of a 12 000 unit file is linear, not quadratic. The index is checked
1530    /// on each use and rebuilt when the units were edited since (a segment added, removed or renamed through the
1531    /// public fields); for many segments at once [`Document::set_targets`] is still the lighter call. When two
1532    /// segments share an id, the first one in the document wins as long as the units are not edited between
1533    /// calls.
1534    pub fn set_target(&mut self, seg_id: &str, target: Vec<Inline>) -> Result<(), Error> {
1535        let at = self.locate(seg_id).ok_or_else(|| Error::UnknownSegment(seg_id.to_string()))?;
1536        self.apply_target(at, seg_id, target, false)
1537    }
1538
1539    /// [`Document::set_target`] that lets a translation repeat a standalone placeholder tag (the `#` of an ICU
1540    /// plural, Chrome `$x$`, go `{{..}}`), as Localization OS does; paired tags still keep the exactly-once rule.
1541    pub fn set_target_repeating(&mut self, seg_id: &str, target: Vec<Inline>) -> Result<(), Error> {
1542        let at = self.locate(seg_id).ok_or_else(|| Error::UnknownSegment(seg_id.to_string()))?;
1543        self.apply_target(at, seg_id, target, true)
1544    }
1545
1546    /// Position (unit, segment) of the segment with this id, through the cached index.
1547    pub(crate) fn locate(&mut self, seg_id: &str) -> Option<(usize, usize)> {
1548        let valid = |units: &[Unit], (ui, si): (usize, usize)| units.get(ui).and_then(|u| u.segments.get(si)).is_some_and(|s| s.id == seg_id);
1549        if let Some(at) = self.seg_index.0.as_ref().and_then(|m| m.get(seg_id)).copied() {
1550            if valid(&self.units, at) {
1551                return Some(at);
1552            }
1553        }
1554        // A miss or a stale hit: the index may be out of date, so rebuild it once and look again.
1555        let fresh = self.segment_index();
1556        let at = fresh.get(seg_id).copied();
1557        self.seg_index = SegIndex(Some(fresh));
1558        at
1559    }
1560
1561    /// Sets many targets in one pass: one id index is built for the whole call, so 100 000 segments take
1562    /// milliseconds where 100 000 [`Document::set_target`] calls scan the document each time. Items are applied in
1563    /// order with the same rules as `set_target`; the first error stops the call and is returned, items before it
1564    /// stay applied. When an id appears more than once, the segment is set by each item in turn (the last wins).
1565    pub fn set_targets<I, S>(&mut self, items: I) -> Result<(), Error>
1566    where
1567        I: IntoIterator<Item = (S, Vec<Inline>)>,
1568        S: AsRef<str>,
1569    {
1570        let index = self.segment_index();
1571        for (id, target) in items {
1572            let id = id.as_ref();
1573            let at = *index.get(id).ok_or_else(|| Error::UnknownSegment(id.to_string()))?;
1574            self.apply_target(at, id, target, false)?;
1575        }
1576        Ok(())
1577    }
1578
1579    /// Sets many states in one pass (see [`Document::set_targets`]).
1580    pub fn set_states<I, S>(&mut self, items: I) -> Result<(), Error>
1581    where
1582        I: IntoIterator<Item = (S, SegState)>,
1583        S: AsRef<str>,
1584    {
1585        let index = self.segment_index();
1586        for (id, state) in items {
1587            let id = id.as_ref();
1588            let (ui, si) = *index.get(id).ok_or_else(|| Error::UnknownSegment(id.to_string()))?;
1589            self.units[ui].segments[si].state = state;
1590        }
1591        Ok(())
1592    }
1593
1594    /// Segment id to (unit index, segment index); the first segment with an id wins, as in `set_target`.
1595    fn segment_index(&self) -> std::collections::HashMap<String, (usize, usize)> {
1596        let mut m = std::collections::HashMap::with_capacity(self.segment_count());
1597        for (ui, u) in self.units.iter().enumerate() {
1598            for (si, s) in u.segments.iter().enumerate() {
1599                m.entry(s.id.clone()).or_insert((ui, si));
1600            }
1601        }
1602        m
1603    }
1604
1605    fn apply_target(&mut self, (ui, si): (usize, usize), seg_id: &str, target: Vec<Inline>, repeat_standalone: bool) -> Result<(), Error> {
1606        let unit = &mut self.units[ui];
1607        if !unit.translate {
1608            return Err(Error::Locked(seg_id.to_string()));
1609        }
1610        let seg = &mut unit.segments[si];
1611        if seg.state == SegState::Locked {
1612            return Err(Error::Locked(seg_id.to_string()));
1613        }
1614        check_tags(&seg.source, &target, repeat_standalone)?;
1615        // The free flag belongs to the source code: a target tag takes it from the source tag with its id, so a
1616        // caller (an editor, a LocOS adapter) that does not know the flag cannot drop or invent it.
1617        let target = merge_text(
1618            target
1619                .into_iter()
1620                .map(|i| match i {
1621                    Inline::Tag { id, kind, display, .. } => {
1622                        let free = kind == TagKind::Standalone
1623                            && seg.source.iter().any(|s| matches!(s, Inline::Tag { id: sid, kind: TagKind::Standalone, free: true, .. } if *sid == id));
1624                        Inline::Tag { id, kind, display, free }
1625                    }
1626                    t => t,
1627                })
1628                .collect(),
1629        );
1630        let empty = plain_text(&target).trim().is_empty() && !target.iter().any(|i| matches!(i, Inline::Tag { .. }));
1631        seg.target = if empty { vec![] } else { target };
1632        seg.empty_target = false;
1633        seg.state = if seg.target.is_empty() { SegState::New } else { SegState::Draft };
1634        Ok(())
1635    }
1636
1637    /// Marks a segment as translated to nothing on purpose (see [`Segment::empty_target`]): the writer writes an
1638    /// empty value for it. State `Draft`, as for any new target. Rejects unknown segments, untranslatable units
1639    /// and locked segments.
1640    pub fn set_target_empty(&mut self, seg_id: &str) -> Result<(), Error> {
1641        let (ui, si) = self.locate(seg_id).ok_or_else(|| Error::UnknownSegment(seg_id.to_string()))?;
1642        let unit = &mut self.units[ui];
1643        if !unit.translate {
1644            return Err(Error::Locked(seg_id.to_string()));
1645        }
1646        let seg = &mut unit.segments[si];
1647        if seg.state == SegState::Locked {
1648            return Err(Error::Locked(seg_id.to_string()));
1649        }
1650        seg.target.clear();
1651        seg.empty_target = true;
1652        seg.state = SegState::Draft;
1653        Ok(())
1654    }
1655
1656    /// Sets a segment's state (for many, [`Document::set_states`]).
1657    ///
1658    /// Like `set_target`, the first segment with the id wins as long as the units are not edited between calls.
1659    pub fn set_state(&mut self, seg_id: &str, state: SegState) -> Result<(), Error> {
1660        // through the cached index, as set_target: a scan per call made a whole-document pass quadratic (BILI-112)
1661        let (ui, si) = self.locate(seg_id).ok_or_else(|| Error::UnknownSegment(seg_id.to_string()))?;
1662        self.units[ui].segments[si].state = state;
1663        Ok(())
1664    }
1665}
1666
1667/// The merge-time tag check ([`guard::check_targets`]). Each target tag must be a tag of the segment's source (same
1668/// id and kind) or have its markup in the unit's `codes` (a reader that maps a stored translation's placeholders to
1669/// the unit's codes, as PO and MO do for a plural form, gives such tags). With `counts`, a paired tag of the
1670/// source may appear no more often than there.
1671pub(crate) fn check_target_tags(source: &[Inline], target: &[Inline], codes: &Codes, counts: bool) -> Result<(), Error> {
1672    let mut allowed: BTreeMap<(&str, TagKind), usize> = BTreeMap::new();
1673    for i in source {
1674        if let Inline::Tag { id, kind, .. } = i {
1675            *allowed.entry((id.as_str(), *kind)).or_default() += 1;
1676        }
1677    }
1678    let mut used: BTreeMap<(&str, TagKind), usize> = BTreeMap::new();
1679    for i in target {
1680        if let Inline::Tag { id, kind, .. } = i {
1681            match allowed.get(&(id.as_str(), *kind)) {
1682                Some(max) => {
1683                    let n = used.entry((id.as_str(), *kind)).or_default();
1684                    *n += 1;
1685                    if counts && *n > *max && *kind != TagKind::Standalone {
1686                        return Err(Error::DuplicatedTag(id.clone()));
1687                    }
1688                }
1689                None if codes.contains_key(id) => {}
1690                None => return Err(Error::InventedTag(id.clone())),
1691            }
1692        }
1693    }
1694    Ok(())
1695}
1696
1697fn check_tags(source: &[Inline], target: &[Inline], repeat_standalone: bool) -> Result<(), Error> {
1698    let mut allowed: BTreeMap<(&str, TagKind), usize> = BTreeMap::new();
1699    for i in source {
1700        if let Inline::Tag { id, kind, .. } = i {
1701            *allowed.entry((id.as_str(), *kind)).or_default() += 1;
1702        }
1703    }
1704    let mut used: BTreeMap<(&str, TagKind), usize> = BTreeMap::new();
1705    for i in target {
1706        if let Inline::Tag { id, kind, .. } = i {
1707            let n = used.entry((id.as_str(), *kind)).or_default();
1708            *n += 1;
1709            match allowed.get(&(id.as_str(), *kind)) {
1710                None => return Err(Error::InventedTag(id.clone())),
1711                Some(max) if *n > *max && !(repeat_standalone && *kind == TagKind::Standalone) => return Err(Error::DuplicatedTag(id.clone())),
1712                _ => {}
1713            }
1714        }
1715    }
1716    Ok(())
1717}
1718
1719/// Options for [`Filter::extract`]. Build them with [`ExtractOptions::new`] and the `with_*` methods
1720/// (`ExtractOptions::new().with_target_lang("de-DE")`); new options are added without breaking callers.
1721#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1722#[non_exhaustive]
1723pub struct ExtractOptions {
1724    /// The source language (a BCP 47 tag, `en`, `de-DE`), when known.
1725    pub source_lang: Option<String>,
1726    /// The target language, when known.
1727    pub target_lang: Option<String>,
1728    /// Parsers always extract one segment per unit; `bilingua-seg` applies the granularity afterwards.
1729    pub granularity: Granularity,
1730    /// Extract text the format marks as not translatable as locked units (for context), instead of skipping it.
1731    pub include_locked: bool,
1732    /// Safety limits for this call; `None` uses [`Limits::default`] (Localization OS's numbers).
1733    #[serde(default, skip_serializing_if = "Option::is_none")]
1734    pub limits: Option<Limits>,
1735    /// Options only one format knows, as `"<format>.<name>"` to a text value (`"ftl.translate_terms"` to
1736    /// `"true"`). Each filter declares its keys and their kind ([`Filter::format_option_keys`]); the `bilingua`
1737    /// facade refuses a key no filter declares, or a value of the wrong kind, with [`Error::FormatOption`].
1738    /// Booleans are `true`/`false`/`1`/`0`/`yes`/`no`/`on`/`off`; integers are decimal.
1739    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1740    pub format_options: BTreeMap<String, String>,
1741    /// A behaviour profile ([`profile`]): `Some("locos")` for the Localization OS adapter. `None`: Bilingua's own
1742    /// behaviour. The `bilingua` facade refuses a name it does not know.
1743    #[serde(default, skip_serializing_if = "Option::is_none")]
1744    pub profile: Option<String>,
1745}
1746
1747impl ExtractOptions {
1748    /// Switches a profile on (`"locos"`), or off with `None`.
1749    pub fn with_profile(mut self, profile: impl IntoOptionString) -> ExtractOptions {
1750        self.profile = profile.into_option_string();
1751        self
1752    }
1753    /// True when this profile is on.
1754    pub fn is_profile(&self, name: &str) -> bool {
1755        self.profile.as_deref() == Some(name)
1756    }
1757    /// The defaults: no languages, sentence granularity, locked text skipped, Localization OS's limits.
1758    pub fn new() -> ExtractOptions {
1759        ExtractOptions::default()
1760    }
1761    /// Sets (or with `None` clears) the source language; it picks the sentence rules.
1762    pub fn with_source_lang(mut self, lang: impl IntoOptionString) -> ExtractOptions {
1763        self.source_lang = lang.into_option_string();
1764        self
1765    }
1766    /// Sets (or clears) the target language.
1767    pub fn with_target_lang(mut self, lang: impl IntoOptionString) -> ExtractOptions {
1768        self.target_lang = lang.into_option_string();
1769        self
1770    }
1771    /// Sets the granularity.
1772    pub fn with_granularity(mut self, granularity: Granularity) -> ExtractOptions {
1773        self.granularity = granularity;
1774        self
1775    }
1776    /// Extracts locked text as locked units, for context.
1777    pub fn with_include_locked(mut self, include_locked: bool) -> ExtractOptions {
1778        self.include_locked = include_locked;
1779        self
1780    }
1781    /// Limits for this call (`Limits` or `Option<Limits>`; `None` is the defaults).
1782    pub fn with_limits(mut self, limits: impl Into<Option<Limits>>) -> ExtractOptions {
1783        self.limits = limits.into();
1784        self
1785    }
1786    /// Sets one format option (`"<format>.<name>"`); the value is text (`true`, `42`, `name=Name`).
1787    pub fn with_format_option(mut self, key: impl Into<String>, value: impl ToString) -> ExtractOptions {
1788        self.format_options.insert(key.into(), value.to_string());
1789        self
1790    }
1791    /// Replaces all format options.
1792    pub fn with_format_options(mut self, options: BTreeMap<String, String>) -> ExtractOptions {
1793        self.format_options = options;
1794        self
1795    }
1796
1797    /// A format option as text, if set.
1798    pub fn format_option(&self, key: &str) -> Option<&str> {
1799        self.format_options.get(key).map(String::as_str)
1800    }
1801
1802    /// A format option as a boolean (`true`, `1`, `yes`, `on` are true; `false`, `0`, `no`, `off` are false; any
1803    /// other text or no entry gives `None`).
1804    pub fn format_flag(&self, key: &str) -> Option<bool> {
1805        match self.format_option(key)?.trim().to_ascii_lowercase().as_str() {
1806            "true" | "1" | "yes" | "on" => Some(true),
1807            "false" | "0" | "no" | "off" => Some(false),
1808            _ => None,
1809        }
1810    }
1811
1812    /// A format option as an integer (`None` when unset or not a decimal integer).
1813    pub fn format_int(&self, key: &str) -> Option<i64> {
1814        self.format_option(key)?.trim().parse().ok()
1815    }
1816
1817    /// The limits in force: the caller's, or the defaults.
1818    pub fn limits(&self) -> Limits {
1819        // clamped, so a caller's huge number (2^62 units from a CLI flag or a Python dict) cannot overflow the
1820        // budgets formats derive from a limit (`40 * max_units`)
1821        self.limits.unwrap_or_default().clamped()
1822    }
1823}
1824
1825/// The kind of value a format option takes.
1826#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1827#[non_exhaustive]
1828pub enum OptionKind {
1829    /// `true`/`false` (also `1`/`0`, `yes`/`no`, `on`/`off`).
1830    Bool,
1831    /// A decimal integer.
1832    Int,
1833    /// Any text.
1834    Text,
1835}
1836
1837/// One option a format understands in `ExtractOptions::format_options`: its full key (`"csv.columns"`), the kind
1838/// of value, and a line of help for tools that list the options.
1839#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1840#[non_exhaustive]
1841pub struct FormatOptionKey {
1842    /// The full key, `<family>.<name>`.
1843    pub key: &'static str,
1844    /// The kind of value.
1845    pub kind: OptionKind,
1846    /// One line of help.
1847    pub help: &'static str,
1848}
1849
1850impl FormatOptionKey {
1851    /// A key of this kind.
1852    pub const fn new(key: &'static str, kind: OptionKind, help: &'static str) -> FormatOptionKey {
1853        FormatOptionKey { key, kind, help }
1854    }
1855    /// A boolean key.
1856    pub const fn bool(key: &'static str, help: &'static str) -> FormatOptionKey {
1857        FormatOptionKey::new(key, OptionKind::Bool, help)
1858    }
1859    /// An integer key.
1860    pub const fn int(key: &'static str, help: &'static str) -> FormatOptionKey {
1861        FormatOptionKey::new(key, OptionKind::Int, help)
1862    }
1863    /// A text key.
1864    pub const fn text(key: &'static str, help: &'static str) -> FormatOptionKey {
1865        FormatOptionKey::new(key, OptionKind::Text, help)
1866    }
1867
1868    /// Refuses a value that is not of this key's kind.
1869    pub fn check(&self, value: &str) -> Result<(), Error> {
1870        let v = value.trim();
1871        let ok = match self.kind {
1872            OptionKind::Bool => matches!(v.to_ascii_lowercase().as_str(), "true" | "1" | "yes" | "on" | "false" | "0" | "no" | "off"),
1873            OptionKind::Int => v.parse::<i64>().is_ok(),
1874            OptionKind::Text => true,
1875        };
1876        if ok {
1877            Ok(())
1878        } else {
1879            let want = match self.kind {
1880                OptionKind::Bool => "true or false",
1881                OptionKind::Int => "an integer",
1882                OptionKind::Text => "text",
1883            };
1884            Err(Error::FormatOption { key: self.key.to_string(), msg: format!("the value {value:?} is not {want}") })
1885        }
1886    }
1887}
1888
1889/// Checks every `format_options` entry against the keys the filters declare: an unknown key or a value of the
1890/// wrong kind is an [`Error::FormatOption`]. The `bilingua` facade calls this with every filter's keys, so an
1891/// option meant for another format (the adapter sends `docx.translate_comments` with every file) is accepted.
1892pub fn check_format_options(opts: &ExtractOptions, known: &[FormatOptionKey]) -> Result<(), Error> {
1893    check_option_map(&opts.format_options, known)
1894}
1895
1896/// [`check_format_options`] for any map of options (`MergeOptions::format_options` too).
1897pub fn check_option_map(options: &BTreeMap<String, String>, known: &[FormatOptionKey]) -> Result<(), Error> {
1898    for (k, v) in options {
1899        match known.iter().find(|f| f.key == k) {
1900            Some(f) => f.check(v)?,
1901            None => {
1902                let family = k.split('.').next().unwrap_or("");
1903                let same: Vec<&str> = known.iter().filter(|f| f.key.split('.').next() == Some(family)).map(|f| f.key).collect();
1904                let msg = if same.is_empty() { "no format has this option".to_string() } else { format!("unknown option; {family} knows {}", same.join(", ")) };
1905                return Err(Error::FormatOption { key: k.clone(), msg });
1906            }
1907        }
1908    }
1909    Ok(())
1910}
1911
1912/// The check every filter makes when it is called directly (not through the `bilingua` facade), first thing in
1913/// `extract` (with `&opts.format_options`) and in `merge_with` (with its `MergeOptions::format_options`): an option
1914/// in one of the filter's own families (its id, and the `<family>.` prefix of every key it declares) that it does
1915/// not declare is refused (a misspelt `csv.colums` would otherwise be ignored), and so is a value of the wrong kind
1916/// for a key it declares. Keys of other formats are left alone: one option map may be meant for many formats, and
1917/// only the facade, which knows every filter's keys, can tell a good foreign key from a misspelt one.
1918pub fn check_own_options<F: Filter + ?Sized>(filter: &F, options: &BTreeMap<String, String>) -> Result<(), Error> {
1919    if options.is_empty() {
1920        return Ok(());
1921    }
1922    let keys = filter.format_option_keys();
1923    let id = filter.id();
1924    let family = |k: &str| k.split('.').next().unwrap_or("").to_string();
1925    for (k, v) in options {
1926        let fam = family(k);
1927        if fam != id && !keys.iter().any(|f| family(f.key) == fam) {
1928            continue;
1929        }
1930        match keys.iter().find(|f| f.key == k) {
1931            Some(f) => f.check(v)?,
1932            None => {
1933                let mine: Vec<&str> = keys.iter().map(|f| f.key).collect();
1934                let msg = if mine.is_empty() { format!("{id} has no options") } else { format!("unknown option; {id} knows {}", mine.join(", ")) };
1935                return Err(Error::FormatOption { key: k.clone(), msg });
1936            }
1937        }
1938    }
1939    Ok(())
1940}
1941
1942/// How a merge writes text files.
1943#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1944#[non_exhaustive]
1945pub enum OutputEncoding {
1946    /// The file's own encoding, BOM and line endings (the default; an untouched merge is byte-identical).
1947    #[default]
1948    #[serde(rename = "keep")]
1949    Keep,
1950    /// Always UTF-8 (Localization OS behaviour). An XML, HTML or PO charset declaration is rewritten to say UTF-8,
1951    /// so the file stays truthful; a UTF-8 BOM the file had is kept, a UTF-16 BOM is dropped.
1952    #[serde(rename = "utf-8", alias = "utf8")]
1953    Utf8,
1954}
1955
1956/// Options for [`Filter::merge_with`]. The default is what [`Filter::merge`] does. They live here, once, and
1957/// every format that stamps a language, fills plurals or writes text honours them:
1958///
1959/// - `output_encoding`: [`OutputEncoding::Keep`] or [`OutputEncoding::Utf8`] (through `enc::encode_text_with`, so
1960///   every text format that keeps its encoding in the skeleton gets it).
1961/// - `stamp_target_always`: by default a merge in which nothing is translated returns the original bytes (no target
1962///   language stamp, no plural fill, no format conversion). With `true` the target language is stamped and
1963///   missing plural forms are filled even then, as Localization OS does. It only has an effect when
1964///   `Document::target_lang` is set.
1965#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1966#[serde(default, deny_unknown_fields)]
1967#[non_exhaustive]
1968pub struct MergeOptions {
1969    /// Keep the file's encoding, or write UTF-8.
1970    pub output_encoding: OutputEncoding,
1971    /// Stamp the target language and fill plurals even when nothing is translated.
1972    pub stamp_target_always: bool,
1973    /// The profile the document is written for (see [`ExtractOptions::profile`]); format crates may switch on it.
1974    #[serde(skip_serializing_if = "Option::is_none")]
1975    pub profile: Option<String>,
1976    /// Merge-time format options, as for [`ExtractOptions::format_options`] (checked against the same keys).
1977    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
1978    pub format_options: BTreeMap<String, String>,
1979    /// Safety limits for a merge that reads a stored package again (EPUB, MadCap Flare); `None` uses
1980    /// [`Limits::default`]. They are the caller's policy: a merge never takes limits from the document, so a file
1981    /// extracted under raised limits is merged under the same ones only when the caller passes them here again.
1982    #[serde(skip_serializing_if = "Option::is_none")]
1983    pub limits: Option<Limits>,
1984}
1985
1986impl MergeOptions {
1987    /// The defaults: keep the file's encoding, no stamp when nothing is translated (what [`Filter::merge`] does).
1988    pub fn new() -> MergeOptions {
1989        MergeOptions::default()
1990    }
1991    /// Sets the output encoding.
1992    pub fn with_output_encoding(mut self, output_encoding: OutputEncoding) -> MergeOptions {
1993        self.output_encoding = output_encoding;
1994        self
1995    }
1996    /// Sets the stamp rule.
1997    pub fn with_stamp_target_always(mut self, stamp_target_always: bool) -> MergeOptions {
1998        self.stamp_target_always = stamp_target_always;
1999        self
2000    }
2001    /// Switches a profile on (`"locos"`), or off with `None`.
2002    pub fn with_profile(mut self, profile: impl IntoOptionString) -> MergeOptions {
2003        self.profile = profile.into_option_string();
2004        self
2005    }
2006    /// True when this profile is on.
2007    pub fn is_profile(&self, name: &str) -> bool {
2008        self.profile.as_deref() == Some(name)
2009    }
2010    /// Sets the safety limits for this merge, or `None` for [`Limits::default`].
2011    pub fn with_limits(mut self, limits: impl Into<Option<Limits>>) -> MergeOptions {
2012        self.limits = limits.into();
2013        self
2014    }
2015    /// The limits in force: the caller's, or the defaults.
2016    pub fn limits(&self) -> Limits {
2017        // clamped, so a caller's huge number (2^62 units from a CLI flag or a Python dict) cannot overflow the
2018        // budgets formats derive from a limit (`40 * max_units`)
2019        self.limits.unwrap_or_default().clamped()
2020    }
2021    /// Sets one format option (`"<format>.<name>"`).
2022    pub fn with_format_option(mut self, key: impl Into<String>, value: impl ToString) -> MergeOptions {
2023        self.format_options.insert(key.into(), value.to_string());
2024        self
2025    }
2026    /// Replaces all format options.
2027    pub fn with_format_options(mut self, options: BTreeMap<String, String>) -> MergeOptions {
2028        self.format_options = options;
2029        self
2030    }
2031
2032    /// True when the document has at least one segment with a target.
2033    pub fn any_translated(doc: &Document) -> bool {
2034        doc.segments().any(|(_, s)| s.has_target())
2035    }
2036
2037    /// Should a format stamp the target language and fill plurals for this document? `target_lang` must be set (and
2038    /// not blank) and something translated, or `stamp_target_always`. "Translated" is [`MergeOptions::any_translated`];
2039    /// a format with its own notion of a change uses [`MergeOptions::stamp_lang`].
2040    pub fn should_stamp(&self, doc: &Document) -> bool {
2041        self.stamp_lang(doc, Self::any_translated(doc)).is_some()
2042    }
2043
2044    /// Can this text be a language code in any spelling a format writes (`de-DE`, `zh_Hant`, `sr@latin`,
2045    /// `de_DE.UTF-8`)? ASCII letters, digits, `-`, `_`, `@` and `.`, at most 64 bytes. The target language is free
2046    /// text (a host setting, or the `trgLang` of a returned XLIFF), and several formats write it into a header
2047    /// line or a key; anything else, a line break above all, is never stamped.
2048    pub fn plausible_lang(code: &str) -> bool {
2049        !code.is_empty() && code.len() <= 64 && code.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'@' | b'.'))
2050    }
2051
2052    /// The one stamp rule every format uses: the document's `target_lang` (trimmed, and only when it can be a
2053    /// language code, see [`MergeOptions::plausible_lang`]) when `translated` (the format's own "something was
2054    /// written" test) or `stamp_target_always`, else `None`.
2055    pub fn stamp_lang<'a>(&self, doc: &'a Document, translated: bool) -> Option<&'a str> {
2056        doc.target_lang.as_deref().map(str::trim).filter(|t| Self::plausible_lang(t)).filter(|_| translated || self.stamp_target_always)
2057    }
2058}
2059
2060#[derive(Debug, thiserror::Error)]
2061#[non_exhaustive]
2062/// Every Bilingua failure. Match with a wildcard arm: a 1.x release may add variants.
2063pub enum Error {
2064    #[error("not a {format} file: {msg}")]
2065    /// The bytes are not a file of this format.
2066    Parse {
2067        /// The format id.
2068        format: String,
2069        /// What is wrong.
2070        msg: String,
2071    },
2072    #[error("unsupported: {0}")]
2073    /// No parser for the file, or a feature the format crate does not have.
2074    Unsupported(String),
2075    #[error("unknown segment {0}")]
2076    /// No segment has this id.
2077    UnknownSegment(String),
2078    #[error("segment {0} is locked")]
2079    /// The segment is locked, or belongs to a locked unit.
2080    Locked(String),
2081    #[error("tag {0} is not in the source")]
2082    /// The target uses a tag the source does not have.
2083    InventedTag(String),
2084    #[error("tag {0} appears more often than in the source")]
2085    /// The target uses a tag more often than the source.
2086    DuplicatedTag(String),
2087    #[error("this skeleton was made by {found}, but this is {expected}; open the file again with the current parser")]
2088    /// The skeleton comes from another parser or a newer skeleton schema.
2089    ParserVersion {
2090        /// The parser that made the skeleton.
2091        found: String,
2092        /// The parser that tried to read it.
2093        expected: String,
2094    },
2095    #[error("cannot write: {0}")]
2096    /// The skeleton is broken or does not belong to this document.
2097    Write(String),
2098    /// The translation cannot be written in this format: it does not fit (a caption too long), a character has no
2099    /// code in the file's code table, or the text would read back as structure (every letter swallowed by a
2100    /// placeholder). The document itself is fine; the translator has to change the text. `unit` names the unit when
2101    /// one is to blame; `reason` is plain text (LocOS's message where LocOS has one), safe to show the translator, and
2102    /// is also the whole `Display` text.
2103    /// `Write` stays for a broken or foreign skeleton.
2104    #[error("{reason}")]
2105    Unwritable {
2106        /// The unit to blame, when there is one.
2107        unit: Option<String>,
2108        /// Why, safe to show the translator.
2109        reason: String,
2110    },
2111    /// The target language changed after extract: `unit` was added at extract for a plural category of another
2112    /// target language (Polish `many` in a document now merged for Slovenian), so writing it would put one
2113    /// language's form under another's category. Extract the file again for this target (0.10).
2114    #[error("unit {unit} is a plural form added for another target language; extract the file again for this target")]
2115    TargetChanged {
2116        /// The first such unit.
2117        unit: String,
2118    },
2119    /// The file is over a safety limit or holds something unsafe (a zip bomb, an XML entity bomb, too many
2120    /// units). The message is short, names the limit and is safe to show the person who uploaded the file.
2121    #[error("{0}")]
2122    Limit(LimitError),
2123    /// The bytes cannot be read as text in any encoding Bilingua knows.
2124    #[error("{0}")]
2125    Encoding(String),
2126    /// A `format_options` key no format declares, or a value of the wrong kind.
2127    #[error("format option {key}: {msg}")]
2128    FormatOption {
2129        /// The key.
2130        key: String,
2131        /// What is wrong with it.
2132        msg: String,
2133    },
2134    /// A profile name Bilingua does not know (see [`profile::profiles`]).
2135    #[error("unknown profile {0:?}")]
2136    UnknownProfile(String),
2137    #[error(transparent)]
2138    /// An I/O error from a reader (Bilingua itself reads no files).
2139    Io(#[from] std::io::Error),
2140}
2141
2142/// A file parser. Implementations live in one crate per format (`bilingua-html`, `bilingua-docx`, ...).
2143///
2144/// The trait is open: another crate may implement it for a format of its own. It implements `id`, `extensions`,
2145/// `sniff`, `extract` and `merge_with`; the rest have defaults, and a 1.x release adds methods only with defaults.
2146/// Such a filter is called directly (and segmented with `bilingua_seg::segment`): the `bilingua` facade's
2147/// `filters()` list is Bilingua's own formats. What a writer needs is public: [`Document::new`], [`Unit::new`],
2148/// [`Skeleton::text`] and friends, [`parser_info!`] with a `SKELETON_SCHEMA` constant, [`check_parser`], the
2149/// [`enc`] codecs and the [`guard`] limits. Start `extract` and `merge_with` with [`check_own_options`].
2150pub trait Filter: Send + Sync {
2151    /// Short id, e.g. "html".
2152    fn id(&self) -> &'static str;
2153    /// Lowercase extensions without the dot, e.g. `["html", "htm"]`.
2154    fn extensions(&self) -> &'static [&'static str];
2155    /// True when the bytes look like this format (used when the extension is missing or ambiguous).
2156    fn sniff(&self, bytes: &[u8]) -> bool;
2157    /// True when the format carries source and target (PO, XLIFF and the like): its extract may fill segment
2158    /// targets and states. False for source files.
2159    fn bilingual(&self) -> bool {
2160        false
2161    }
2162    /// The `ExtractOptions::format_options` keys this filter reads (`"csv.columns"`, ...), each with the
2163    /// `<family>.` prefix of its format. The facade refuses keys no filter declares; the filter itself refuses
2164    /// undeclared keys of its own families ([`check_own_options`]). Default: none.
2165    fn format_option_keys(&self) -> &'static [FormatOptionKey] {
2166        &[]
2167    }
2168    /// Source file to document. One segment per unit; no sentence splitting here.
2169    fn extract(&self, bytes: &[u8], opts: &ExtractOptions) -> Result<Document, Error>;
2170    /// Document back to a file in the original format, targets in place of sources, with [`MergeOptions`]. Every
2171    /// format honours both options: `output_encoding` (keep the file's encoding, or write UTF-8) and
2172    /// `stamp_target_always` (stamp the target language and fill plurals even when nothing is translated; the
2173    /// rule is [`MergeOptions::should_stamp`]).
2174    fn merge_with(&self, doc: &Document, opts: &MergeOptions) -> Result<Vec<u8>, Error>;
2175    /// [`Filter::merge_with`] with the default options: the file's own encoding, and no stamp when nothing is
2176    /// translated (an untouched merge gives the original bytes).
2177    fn merge(&self, doc: &Document) -> Result<Vec<u8>, Error> {
2178        self.merge_with(doc, &MergeOptions::default())
2179    }
2180    /// For formats a browser can show: the translated document as HTML in which every segment's text sits in
2181    /// `<span data-bl-seg="SEGMENT_ID">..</span>`, so a live preview can patch one segment without reloading.
2182    /// Scripts must be stripped. `None` when the format has no preview.
2183    fn preview(&self, _doc: &Document) -> Option<String> {
2184        None
2185    }
2186    /// The inner HTML of one segment's span in `preview()` (its current target, or source when empty), so a
2187    /// live preview can patch that span in place. `None` when the format has no preview or the id is unknown.
2188    fn render_segment(&self, _doc: &Document, _seg_id: &str) -> Option<String> {
2189        None
2190    }
2191}
2192
2193#[cfg(test)]
2194mod tests {
2195    use super::*;
2196
2197    #[test]
2198    fn json_shape_matches_catcore() {
2199        let v = vec![Inline::text("Hi "), Inline::tag("1", TagKind::Open, "<b>")];
2200        let j = serde_json::to_string(&v).unwrap();
2201        assert_eq!(j, r#"[{"text":"Hi "},{"tag":{"id":"1","kind":"open","display":"<b>"}}]"#);
2202    }
2203
2204    #[test]
2205    fn output_joins_segments_and_falls_back_to_source() {
2206        let mut u = Unit::new("p1", vec![]);
2207        u.segments = vec![
2208            Segment { id: "p1#1".into(), source: vec![Inline::text("One.")], target: vec![Inline::text("Uno.")], state: SegState::Draft, origin: None, empty_target: false },
2209            Segment { id: "p1#2".into(), source: vec![Inline::text("Two.")], target: vec![], state: SegState::New, origin: None, empty_target: false },
2210        ];
2211        u.separators = vec![" ".into()];
2212        assert_eq!(u.output(), vec![Inline::text("Uno. Two.")]);
2213        assert_eq!(plain_text(&u.source()), "One. Two.");
2214    }
2215
2216    #[test]
2217    fn set_target_takes_the_free_flag_from_the_source() {
2218        let mut d = Document {
2219            format: "test".into(),
2220            name: None,
2221            source_lang: None,
2222            target_lang: None,
2223            granularity: Granularity::Paragraph,
2224            units: vec![Unit::new("u1", vec![Inline::text("Hi "), Inline::free_tag("1", "{name}"), Inline::tag("2", TagKind::Standalone, "%s")])],
2225            skeleton: Skeleton::Text { parts: vec![SkelPart::Unit(0)], encoding: "utf-8".into(), parser: None },
2226            warnings: vec![],
2227            source_encoding: None,
2228            seg_index: SegIndex::default(),
2229        };
2230        // An editor that does not know the flag sends both codes as not free, and claims the %s is free.
2231        let t = vec![
2232            Inline::Tag { id: "2".into(), kind: TagKind::Standalone, display: "%s".into(), free: true },
2233            Inline::text(" hola "),
2234            Inline::tag("1", TagKind::Standalone, "{name}"),
2235        ];
2236        d.set_target("u1", t).unwrap();
2237        let got: Vec<bool> = d.units[0].segments[0].target.iter().filter(|i| matches!(i, Inline::Tag { .. })).map(Inline::is_free).collect();
2238        assert_eq!(got, vec![false, true]);
2239    }
2240
2241    #[test]
2242    fn set_target_checks_tags() {
2243        let mut d = Document {
2244            format: "test".into(),
2245            name: None,
2246            source_lang: None,
2247            target_lang: None,
2248            granularity: Granularity::Paragraph,
2249            units: vec![Unit::new("u1", vec![Inline::tag("1", TagKind::Open, "<b>"), Inline::text("x"), Inline::tag("1", TagKind::Close, "</b>")])],
2250            skeleton: Skeleton::Text { parts: vec![SkelPart::Unit(0)], encoding: "utf-8".into(), parser: None },
2251            warnings: vec![],
2252            source_encoding: None,
2253            seg_index: SegIndex::default(),
2254        };
2255        assert!(d.set_target("u1", vec![Inline::text("y")]).is_ok());
2256        assert!(matches!(d.set_target("u1", vec![Inline::tag("2", TagKind::Open, "<i>")]), Err(Error::InventedTag(_))));
2257        assert!(matches!(
2258            d.set_target("u1", vec![Inline::tag("1", TagKind::Open, ""), Inline::tag("1", TagKind::Open, "")]),
2259            Err(Error::DuplicatedTag(_))
2260        ));
2261        assert_eq!(d.find("u1").unwrap().1.state, SegState::Draft);
2262    }
2263
2264    fn big_doc(n: usize) -> Document {
2265        Document {
2266            format: "test".into(),
2267            units: (0..n).map(|i| Unit::new(format!("u{i}"), vec![Inline::text(format!("Source {i}"))])).collect(),
2268            skeleton: Skeleton::Text { parts: vec![], encoding: "utf-8".into(), parser: None },
2269            ..Default::default()
2270        }
2271    }
2272
2273    #[test]
2274    fn set_targets_sets_many_and_matches_set_target() {
2275        let mut a = big_doc(50);
2276        let mut b = big_doc(50);
2277        a.units[7].translate = false;
2278        b.units[7].translate = false;
2279        for i in (0..50).filter(|i| *i != 7) {
2280            a.set_target(&format!("u{i}"), vec![Inline::text(format!("T{i}"))]).unwrap();
2281        }
2282        b.set_targets((0..50).filter(|i| *i != 7).map(|i| (format!("u{i}"), vec![Inline::text(format!("T{i}"))]))).unwrap();
2283        assert_eq!(a, b);
2284        assert_eq!(b.find("u49").unwrap().1.state, SegState::Draft);
2285    }
2286
2287    #[test]
2288    fn set_target_index_follows_edits_and_stays_out_of_equality() {
2289        let mut d = big_doc(20);
2290        d.set_target("u5", vec![Inline::text("a")]).unwrap();
2291        // the cached index does not make two equal documents unequal, and does not reach the JSON
2292        let e: Document = serde_json::from_str(&serde_json::to_string(&d).unwrap()).unwrap();
2293        assert_eq!(d, e);
2294        assert!(!serde_json::to_string(&d).unwrap().contains("seg_index"));
2295        // units removed, inserted and renamed through the public fields since the index was built
2296        let moved = d.units.remove(2);
2297        d.set_target("u6", vec![Inline::text("b")]).unwrap();
2298        assert_eq!(d.find("u6").unwrap().1.target, vec![Inline::text("b")]);
2299        assert!(matches!(d.set_target("u2", vec![]), Err(Error::UnknownSegment(_))));
2300        d.units.insert(0, moved);
2301        d.set_target("u2", vec![Inline::text("c")]).unwrap();
2302        assert_eq!(d.units[0].segments[0].target, vec![Inline::text("c")]);
2303        d.units[3].segments[0].id = "renamed".into();
2304        d.set_target("renamed", vec![Inline::text("d")]).unwrap();
2305        assert!(d.find("renamed").unwrap().1.has_target());
2306        // a clone and the JSON round trip set targets the same way
2307        let mut c: Document = serde_json::from_str(&serde_json::to_string(&d).unwrap()).unwrap();
2308        c.set_target("u9", vec![Inline::text("x")]).unwrap();
2309        assert_eq!(c.find("u9").unwrap().1.target, vec![Inline::text("x")]);
2310    }
2311
2312    #[test]
2313    fn set_target_index_keeps_first_duplicate_send_sync_and_debug() {
2314        fn send_sync<T: Send + Sync>() {}
2315        send_sync::<Document>();
2316        let mut d = big_doc(6);
2317        d.units[4].segments[0].id = "u1".into();
2318        let before = format!("{d:?}");
2319        d.set_target("u1", vec![Inline::text("a")]).unwrap();
2320        d.set_target("u1", vec![Inline::text("b")]).unwrap();
2321        // the first segment with the id wins, as the old scan did; the later twin is untouched
2322        assert_eq!(d.units[1].segments[0].target, vec![Inline::text("b")]);
2323        assert!(!d.units[4].segments[0].has_target());
2324        // the cache does not show in Debug, and a clone (which starts without it) sets targets the same way
2325        let mut fresh = big_doc(6);
2326        fresh.units[4].segments[0].id = "u1".into();
2327        assert_eq!(before, format!("{fresh:?}"));
2328        let mut c = d.clone();
2329        c.set_target("u3", vec![Inline::text("z")]).unwrap();
2330        assert_eq!(c.find("u3").unwrap().1.target, vec![Inline::text("z")]);
2331        assert_eq!(format!("{:?}", d.clone()), format!("{d:?}"));
2332    }
2333
2334    #[test]
2335    fn set_targets_errors_like_set_target_and_keeps_earlier_items() {
2336        let mut d = big_doc(3);
2337        d.units[1].translate = false;
2338        let r = d.set_targets(vec![("u0", vec![Inline::text("a")]), ("u1", vec![Inline::text("b")]), ("u2", vec![Inline::text("c")])]);
2339        assert!(matches!(r, Err(Error::Locked(_))));
2340        assert_eq!(d.units[0].segments[0].target, vec![Inline::text("a")]);
2341        assert!(d.units[2].segments[0].target.is_empty());
2342        assert!(matches!(d.set_targets(vec![("nope", vec![])]), Err(Error::UnknownSegment(_))));
2343        let r = d.set_targets(vec![("u0", vec![Inline::tag("9", TagKind::Open, "<i>")])]);
2344        assert!(matches!(r, Err(Error::InventedTag(_))));
2345        // an empty target clears the segment, as set_target does
2346        d.set_targets(vec![("u0", vec![Inline::text("  ")])]).unwrap();
2347        assert_eq!(d.units[0].segments[0].state, SegState::New);
2348    }
2349
2350    #[test]
2351    fn set_states_batch() {
2352        let mut d = big_doc(4);
2353        d.set_states((0..4).map(|i| (format!("u{i}"), SegState::Confirmed))).unwrap();
2354        assert!(d.segments().all(|(_, s)| s.state == SegState::Confirmed));
2355        assert!(matches!(d.set_states(vec![("zzz", SegState::New)]), Err(Error::UnknownSegment(_))));
2356    }
2357
2358    #[test]
2359    fn set_targets_100k_is_fast() {
2360        let n = 100_000;
2361        let mut d = big_doc(n);
2362        let t = std::time::Instant::now();
2363        d.set_targets((0..n).map(|i| (format!("u{i}"), vec![Inline::text("x")]))).unwrap();
2364        d.set_states((0..n).map(|i| (format!("u{i}"), SegState::Translated))).unwrap();
2365        let took = t.elapsed();
2366        // well under a second in release; a debug build gets a loose bound that still rules out a quadratic scan
2367        let limit = if cfg!(debug_assertions) { 10_000 } else { 1_000 };
2368        assert!(took.as_millis() < limit, "100k targets took {took:?}");
2369        assert_eq!(d.units[n - 1].segments[0].state, SegState::Translated);
2370    }
2371}