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