1#![warn(missing_docs)]
22#![deny(unsafe_code)]
23
24use serde::{Deserialize, Serialize};
25use std::collections::BTreeMap;
26
27pub mod b64;
28#[doc(hidden)]
30pub mod cldr;
31pub mod codepage;
32pub mod enc;
33pub mod garble;
34pub mod guard;
35#[doc(hidden)]
37pub mod plural_table;
38pub mod profile;
39mod pytables;
40pub mod pytext;
41pub mod smallmap;
42#[doc(hidden)]
44pub mod work;
45
46pub 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
56pub trait IntoOptionString: sealed::Sealed {
62 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
113#[serde(rename_all = "lowercase")]
114pub enum Inline {
115 Text(String),
117 #[non_exhaustive]
122 Tag {
123 id: String,
125 kind: TagKind,
127 display: String,
129 #[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 pub fn text(s: impl Into<String>) -> Inline {
142 Inline::Text(s.into())
143 }
144 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 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 pub fn is_free(&self) -> bool {
154 matches!(self, Inline::Tag { free: true, .. })
155 }
156 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
168#[serde(rename_all = "lowercase")]
169pub enum TagKind {
170 Open,
172 Close,
174 Standalone,
176}
177
178#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
182#[non_exhaustive]
183pub struct CodeData {
184 pub open: Option<String>,
186 pub close: Option<String>,
188 pub standalone: Option<String>,
190 pub label: Option<String>,
192 #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
195 pub ty: Option<CodeType>,
196 #[serde(default, skip_serializing_if = "TextMap::is_empty")]
199 pub attrs: TextMap,
200}
201
202impl CodeData {
203 pub fn new() -> CodeData {
205 CodeData::default()
206 }
207 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 pub fn standalone(markup: impl Into<String>) -> CodeData {
214 let markup: String = markup.into();
215 CodeData::new().with_standalone(markup)
216 }
217 pub fn with_open(mut self, open: impl IntoOptionString) -> CodeData {
219 self.open = open.into_option_string();
220 self
221 }
222 pub fn with_close(mut self, close: impl IntoOptionString) -> CodeData {
224 self.close = close.into_option_string();
225 self
226 }
227 pub fn with_standalone(mut self, standalone: impl IntoOptionString) -> CodeData {
229 self.standalone = standalone.into_option_string();
230 self
231 }
232 pub fn with_label(mut self, label: impl IntoOptionString) -> CodeData {
234 self.label = label.into_option_string();
235 self
236 }
237 pub fn open_markup(&self) -> Option<&str> {
240 self.open.as_deref()
241 }
242 pub fn close_markup(&self) -> Option<&str> {
244 self.close.as_deref()
245 }
246 pub fn standalone_markup(&self) -> Option<&str> {
248 self.standalone.as_deref()
249 }
250 pub fn label(&self) -> Option<&str> {
252 self.label.as_deref()
253 }
254 pub fn set_open(&mut self, open: impl IntoOptionString) {
256 self.open = open.into_option_string();
257 }
258 pub fn set_close(&mut self, close: impl IntoOptionString) {
260 self.close = close.into_option_string();
261 }
262 pub fn set_standalone(&mut self, standalone: impl IntoOptionString) {
264 self.standalone = standalone.into_option_string();
265 }
266 pub fn set_label(&mut self, label: impl IntoOptionString) {
268 self.label = label.into_option_string();
269 }
270}
271
272impl CodeData {
275 pub fn with_code_type(mut self, ty: Option<CodeType>) -> CodeData {
277 self.ty = ty;
278 self
279 }
280 pub fn with_attr(mut self, key: &str, value: impl Into<Box<str>>) -> CodeData {
282 self.set_attr(key, value);
283 self
284 }
285 pub fn code_type(&self) -> Option<CodeType> {
287 self.ty
288 }
289 pub fn set_code_type(&mut self, ty: Option<CodeType>) {
291 self.ty = ty;
292 }
293 pub fn attrs(&self) -> &TextMap {
295 &self.attrs
296 }
297 pub fn attrs_mut(&mut self) -> &mut TextMap {
299 &mut self.attrs
300 }
301 pub fn attr(&self, key: &str) -> Option<&str> {
303 self.attrs.get(key)
304 }
305 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 pub fn clear_typing(&mut self) {
316 self.ty = None;
317 self.attrs.clear();
318 }
319}
320
321#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
324#[serde(rename_all = "lowercase")]
325#[non_exhaustive]
326pub enum CodeType {
327 Bold,
329 Italic,
331 Underline,
333 Strike,
335 Superscript,
337 Subscript,
339 Code,
341 Style,
343 Link,
345 Image,
347 Linebreak,
349 Tab,
351 Field,
353 Footnoteref,
355 Placeholder,
357 #[serde(other)]
359 Other,
360}
361
362impl CodeType {
363 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 pub fn from_name(name: &str) -> CodeType {
386 CodeType::ALL.iter().copied().find(|t| t.as_str() == name).unwrap_or(CodeType::Other)
387 }
388 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 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
427pub type Codes = SmallMap<CodeData>;
430
431#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
434#[non_exhaustive]
435pub enum SegState {
436 #[default]
438 #[serde(rename = "new")]
439 New,
440 #[serde(rename = "draft")]
442 Draft,
443 #[serde(rename = "translated")]
445 Translated,
446 #[serde(rename = "confirmed")]
448 Confirmed,
449 #[serde(rename = "reviewed")]
451 Reviewed,
452 #[serde(rename = "signed-off")]
454 SignedOff,
455 #[serde(rename = "rejected")]
457 Rejected,
458 #[serde(rename = "locked")]
460 Locked,
461}
462
463impl SegState {
464 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 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 pub fn is_accepted(self) -> bool {
495 self.rank() >= SegState::Translated.rank()
496 }
497}
498
499#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
502#[serde(rename_all = "lowercase")]
503#[non_exhaustive]
504pub enum OriginKind {
505 Tm,
507 Mt,
509 Ai,
511 Human,
513 #[default]
515 #[serde(other)]
516 Other,
517}
518
519#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
521#[non_exhaustive]
522pub struct Origin {
523 pub kind: OriginKind,
525 #[serde(default, skip_serializing_if = "Option::is_none")]
527 pub name: Option<String>,
528 #[serde(default, skip_serializing_if = "Option::is_none")]
530 pub match_pct: Option<u8>,
531}
532
533impl Origin {
534 pub fn new(kind: OriginKind) -> Origin {
536 Origin { kind, name: None, match_pct: None }
537 }
538 pub fn with_match(mut self, pct: u8) -> Origin {
540 self.match_pct = Some(pct);
541 self
542 }
543 pub fn with_match_pct(mut self, pct: Option<u8>) -> Origin {
545 self.match_pct = pct;
546 self
547 }
548 pub fn with_name(mut self, name: impl IntoOptionString) -> Origin {
550 self.name = name.into_option_string();
551 self
552 }
553}
554
555#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
558#[non_exhaustive]
559pub struct Segment {
560 pub id: String,
562 pub source: Vec<Inline>,
564 #[serde(default)]
566 pub target: Vec<Inline>,
567 #[serde(default)]
569 pub state: SegState,
570 #[serde(default, skip_serializing_if = "Option::is_none")]
572 pub origin: Option<Origin>,
573 #[serde(default, skip_serializing_if = "is_false")]
580 pub empty_target: bool,
581}
582
583impl Segment {
584 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 pub fn has_target(&self) -> bool {
590 !self.target.is_empty() || self.empty_target
591 }
592 pub fn output(&self) -> &[Inline] {
594 if self.has_target() {
595 &self.target
596 } else {
597 &self.source
598 }
599 }
600 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 pub fn with_target(mut self, target: Vec<Inline>) -> Segment {
610 self.target = target;
611 self
612 }
613 pub fn with_state(mut self, state: SegState) -> Segment {
615 self.state = state;
616 self
617 }
618 pub fn with_origin(mut self, origin: impl Into<Option<Origin>>) -> Segment {
620 self.origin = origin.into();
621 self
622 }
623}
624
625#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
628#[non_exhaustive]
629pub struct Note {
630 #[serde(default, skip_serializing_if = "Option::is_none")]
632 pub author: Option<String>,
633 pub text: String,
635 #[serde(default, skip_serializing_if = "Option::is_none")]
637 pub kind: Option<String>,
638}
639
640impl Note {
641 pub fn new(text: impl Into<String>) -> Note {
643 Note { author: None, text: text.into(), kind: None }
644 }
645 pub fn with_author(mut self, author: impl IntoOptionString) -> Note {
647 self.author = author.into_option_string();
648 self
649 }
650 pub fn with_kind(mut self, kind: impl IntoOptionString) -> Note {
652 self.kind = kind.into_option_string();
653 self
654 }
655}
656
657#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
660#[non_exhaustive]
661pub struct UnitContext {
662 pub kind: Option<String>,
665 pub style: Option<String>,
667 pub key: Option<String>,
669 pub heading: Option<String>,
671 pub location: Option<String>,
673 pub max_len: Option<usize>,
675 #[serde(default)]
677 pub notes: Vec<String>,
678 #[serde(default)]
680 pub extra: TextMap,
681 #[serde(default, skip_serializing_if = "Option::is_none")]
684 pub role: Option<Role>,
685 #[serde(default, skip_serializing_if = "Option::is_none")]
687 pub level: Option<u8>,
688}
689
690#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
693#[serde(rename_all = "lowercase")]
694#[non_exhaustive]
695pub enum Role {
696 Heading,
698 Title,
700 Subtitle,
702 SlideTitle,
704 Header,
706 Footer,
708 Footnote,
710 Endnote,
712 Notes,
714 Comment,
716 Caption,
718 SheetName,
720 #[serde(other)]
722 Other,
723}
724
725impl Role {
726 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 pub fn with_role(mut self, role: impl Into<Option<Role>>) -> UnitContext {
755 self.role = role.into();
756 self
757 }
758 pub fn with_level(mut self, level: impl Into<Option<u8>>) -> UnitContext {
760 self.level = level.into();
761 self
762 }
763 pub fn role(&self) -> Option<Role> {
765 self.role
766 }
767 pub fn level(&self) -> Option<u8> {
769 self.level
770 }
771 pub fn set_role(&mut self, role: impl Into<Option<Role>>) {
773 self.role = role.into();
774 }
775 pub fn set_level(&mut self, level: impl Into<Option<u8>>) {
777 self.level = level.into();
778 }
779 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 pub fn new() -> UnitContext {
789 UnitContext::default()
790 }
791 pub fn with_kind(mut self, kind: impl IntoOptionString) -> UnitContext {
793 self.kind = kind.into_option_string();
794 self
795 }
796 pub fn with_style(mut self, style: impl IntoOptionString) -> UnitContext {
798 self.style = style.into_option_string();
799 self
800 }
801 pub fn with_key(mut self, key: impl IntoOptionString) -> UnitContext {
803 self.key = key.into_option_string();
804 self
805 }
806 pub fn with_heading(mut self, heading: impl IntoOptionString) -> UnitContext {
808 self.heading = heading.into_option_string();
809 self
810 }
811 pub fn with_location(mut self, location: impl IntoOptionString) -> UnitContext {
813 self.location = location.into_option_string();
814 self
815 }
816 pub fn with_max_len(mut self, max_len: Option<usize>) -> UnitContext {
818 self.max_len = max_len;
819 self
820 }
821 pub fn with_notes(mut self, notes: Vec<String>) -> UnitContext {
823 self.notes = notes;
824 self
825 }
826 pub fn with_extra(mut self, extra: impl Into<TextMap>) -> UnitContext {
828 self.set_extra(extra);
829 self
830 }
831
832 pub fn kind(&self) -> Option<&str> {
834 self.kind.as_deref()
835 }
836 pub fn style(&self) -> Option<&str> {
838 self.style.as_deref()
839 }
840 pub fn key(&self) -> Option<&str> {
842 self.key.as_deref()
843 }
844 pub fn heading(&self) -> Option<&str> {
846 self.heading.as_deref()
847 }
848 pub fn location(&self) -> Option<&str> {
850 self.location.as_deref()
851 }
852 pub fn set_kind(&mut self, kind: impl IntoOptionString) {
854 self.kind = kind.into_option_string();
855 }
856 pub fn set_style(&mut self, style: impl IntoOptionString) {
858 self.style = style.into_option_string();
859 }
860 pub fn set_key(&mut self, key: impl IntoOptionString) {
862 self.key = key.into_option_string();
863 }
864 pub fn set_heading(&mut self, heading: impl IntoOptionString) {
866 self.heading = heading.into_option_string();
867 }
868 pub fn set_location(&mut self, location: impl IntoOptionString) {
870 self.location = location.into_option_string();
871 }
872
873 pub fn extra(&self) -> &TextMap {
875 &self.extra
876 }
877 pub fn extra_mut(&mut self) -> &mut TextMap {
879 &mut self.extra
880 }
881 pub fn set_extra(&mut self, extra: impl Into<TextMap>) {
883 self.extra = extra.into();
884 }
885}
886
887#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
890#[serde(from = "UnitRepr")]
891#[non_exhaustive]
892pub struct Unit {
893 pub id: String,
895 pub segments: Vec<Segment>,
897 #[serde(default)]
900 pub separators: Vec<String>,
901 #[serde(default)]
903 pub codes: Codes,
904 #[serde(default)]
906 pub context: UnitContext,
907 #[serde(default = "yes")]
909 pub translate: bool,
910 #[serde(default, skip_serializing_if = "Vec::is_empty")]
912 pub notes: Vec<Note>,
913 #[serde(default, skip_serializing_if = "Option::is_none")]
916 pub lock_reason: Option<String>,
917 #[serde(default, skip_serializing_if = "TextMap::is_empty")]
922 pub hidden: TextMap,
923 #[serde(default, skip_serializing_if = "Option::is_none")]
926 pub plural: Option<Box<PluralSlot>>,
927}
928
929fn yes() -> bool {
930 true
931}
932
933#[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 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 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 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 pub fn hidden(&self, key: &str) -> Option<&str> {
1017 self.hidden.get(key)
1018 }
1019 pub fn set_hidden(&mut self, key: impl Into<String>, value: impl Into<String>) {
1021 self.hidden.insert(key.into(), value.into());
1022 }
1023 pub fn has_hidden(&self, key: &str) -> bool {
1025 self.hidden.contains_key(key)
1026 }
1027 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 pub fn hidden_map(&self) -> &TextMap {
1034 &self.hidden
1035 }
1036 pub fn hidden_map_mut(&mut self) -> &mut TextMap {
1038 &mut self.hidden
1039 }
1040 pub fn set_hidden_map(&mut self, hidden: impl Into<TextMap>) {
1042 self.hidden = hidden.into();
1043 }
1044
1045 pub fn codes(&self) -> &Codes {
1047 &self.codes
1048 }
1049 pub fn codes_mut(&mut self) -> &mut Codes {
1051 &mut self.codes
1052 }
1053 pub fn set_codes(&mut self, codes: impl Into<Codes>) {
1055 self.codes = codes.into();
1056 }
1057 pub fn with_separators(mut self, separators: Vec<String>) -> Unit {
1059 self.separators = separators;
1060 self
1061 }
1062 pub fn with_codes(mut self, codes: impl Into<Codes>) -> Unit {
1064 self.set_codes(codes);
1065 self
1066 }
1067 pub fn with_code(mut self, id: impl Into<String>, code: CodeData) -> Unit {
1069 self.codes.insert(id.into(), code);
1070 self
1071 }
1072 pub fn with_context(mut self, context: UnitContext) -> Unit {
1074 self.context = context;
1075 self
1076 }
1077 pub fn with_translate(mut self, translate: bool) -> Unit {
1079 self.translate = translate;
1080 self
1081 }
1082 pub fn with_notes(mut self, notes: Vec<Note>) -> Unit {
1084 self.notes = notes;
1085 self
1086 }
1087 pub fn with_lock_reason(mut self, reason: impl IntoOptionString) -> Unit {
1089 self.lock_reason = reason.into_option_string();
1090 self
1091 }
1092
1093 pub fn source(&self) -> Vec<Inline> {
1095 self.join(|s| &s.source)
1096 }
1097
1098 pub fn output(&self) -> Vec<Inline> {
1101 self.join(|s| if s.has_target() { &s.target } else { &s.source })
1102 }
1103
1104 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
1125impl Unit {
1127 pub fn plural(&self) -> Option<&PluralSlot> {
1129 self.plural.as_deref()
1130 }
1131 pub fn plural_mut(&mut self) -> Option<&mut PluralSlot> {
1133 self.plural.as_deref_mut()
1134 }
1135 pub fn set_plural(&mut self, plural: impl Into<Option<PluralSlot>>) {
1137 self.plural = plural.into().map(Box::new);
1138 }
1139 pub fn with_plural(mut self, plural: impl Into<Option<PluralSlot>>) -> Unit {
1141 self.set_plural(plural);
1142 self
1143 }
1144}
1145
1146pub 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
1159pub 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1172#[serde(rename_all = "lowercase")]
1173pub enum SkelPart {
1174 Raw(String),
1176 Unit(usize),
1178}
1179
1180#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1182#[serde(rename_all = "lowercase")]
1183pub enum ZipData {
1184 Raw(#[serde(with = "b64")] Vec<u8>),
1186 Parts(Vec<SkelPart>),
1188}
1189
1190#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1192#[non_exhaustive]
1193pub struct ZipEntry {
1194 pub name: String,
1196 pub data: ZipData,
1198}
1199
1200impl ZipEntry {
1201 pub fn new(name: impl Into<String>, data: ZipData) -> ZipEntry {
1203 ZipEntry { name: name.into(), data }
1204 }
1205 pub fn raw(name: impl Into<String>, bytes: Vec<u8>) -> ZipEntry {
1207 ZipEntry::new(name, ZipData::Raw(bytes))
1208 }
1209}
1210
1211#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1215#[non_exhaustive]
1216pub struct ParserInfo {
1217 pub name: String,
1219 pub version: String,
1221 #[serde(default = "legacy_schema")]
1223 pub schema: u32,
1224}
1225
1226fn legacy_schema() -> u32 {
1227 1
1228}
1229
1230impl ParserInfo {
1231 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 pub fn compatible_with(&self, current: &ParserInfo) -> bool {
1239 self.name == current.name && self.schema <= current.schema
1240 }
1241}
1242
1243#[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
1259pub fn check_parser(doc: &Document, current: &ParserInfo) -> Result<(), Error> {
1263 check_parser_min(doc, current, 1)
1264}
1265
1266pub 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1287#[serde(rename_all = "lowercase")]
1288#[non_exhaustive]
1289pub enum Skeleton {
1290 Text {
1292 parts: Vec<SkelPart>,
1294 encoding: String,
1296 #[serde(default, skip_serializing_if = "Option::is_none")]
1298 parser: Option<ParserInfo>,
1299 },
1300 Zip {
1302 entries: Vec<ZipEntry>,
1304 #[serde(default, skip_serializing_if = "Option::is_none")]
1306 parser: Option<ParserInfo>,
1307 },
1308 Binary {
1311 #[serde(with = "b64")]
1313 data: Vec<u8>,
1314 #[serde(default, skip_serializing_if = "Option::is_none")]
1316 parser: Option<ParserInfo>,
1317 },
1318}
1319
1320impl Default for Skeleton {
1321 fn default() -> Self {
1323 Skeleton::Text { parts: Vec::new(), encoding: "utf-8".into(), parser: None }
1324 }
1325}
1326
1327impl Skeleton {
1328 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 pub fn zip(entries: Vec<ZipEntry>, parser: ParserInfo) -> Skeleton {
1334 Skeleton::Zip { entries, parser: Some(parser) }
1335 }
1336 pub fn binary(data: Vec<u8>, parser: ParserInfo) -> Skeleton {
1338 Skeleton::Binary { data, parser: Some(parser) }
1339 }
1340 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1350#[serde(rename_all = "lowercase")]
1351#[non_exhaustive]
1352pub enum Granularity {
1353 #[default]
1355 Sentence,
1356 Paragraph,
1358 Document,
1361}
1362
1363#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1367#[non_exhaustive]
1368pub struct Document {
1369 pub format: String,
1371 pub name: Option<String>,
1373 pub source_lang: Option<String>,
1375 pub target_lang: Option<String>,
1377 pub granularity: Granularity,
1379 pub units: Vec<Unit>,
1381 pub skeleton: Skeleton,
1383 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1386 pub warnings: Vec<Warning>,
1387 #[serde(default, skip_serializing_if = "Option::is_none")]
1391 pub source_encoding: Option<String>,
1392 #[serde(skip)]
1394 seg_index: SegIndex,
1395}
1396
1397#[derive(Default)]
1400struct SegIndex(Option<std::collections::HashMap<String, (usize, usize)>>);
1401
1402impl Clone for SegIndex {
1405 fn clone(&self) -> SegIndex {
1406 SegIndex(None)
1407 }
1408}
1409
1410impl 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
1425impl Document {
1427 pub fn plural_categories(&self, kind: PluralKind) -> Option<Vec<&'static str>> {
1432 plural::categories(self.target_lang.as_deref(), kind)
1433 }
1434}
1435
1436#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1439#[non_exhaustive]
1440pub struct Warning {
1441 pub kind: String,
1443 #[serde(default, skip_serializing_if = "String::is_empty")]
1445 pub part: String,
1446 pub message: String,
1448}
1449
1450impl Warning {
1451 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 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 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 pub fn with_name(mut self, name: impl IntoOptionString) -> Document {
1472 self.name = name.into_option_string();
1473 self
1474 }
1475 pub fn with_source_lang(mut self, lang: impl IntoOptionString) -> Document {
1477 self.source_lang = lang.into_option_string();
1478 self
1479 }
1480 pub fn with_target_lang(mut self, lang: impl IntoOptionString) -> Document {
1482 self.target_lang = lang.into_option_string();
1483 self
1484 }
1485 pub fn with_granularity(mut self, granularity: Granularity) -> Document {
1487 self.granularity = granularity;
1488 self
1489 }
1490 pub fn detected_source_encoding(&self) -> Option<String> {
1494 let encoding = match &self.skeleton {
1495 Skeleton::Text { encoding, .. } => encoding.as_str(),
1496 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 pub fn with_warnings(mut self, warnings: Vec<Warning>) -> Document {
1506 self.warnings = warnings;
1507 self
1508 }
1509
1510 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 pub fn segment_count(&self) -> usize {
1517 self.units.iter().map(|u| u.segments.len()).sum()
1518 }
1519
1520 pub fn find(&self, seg_id: &str) -> Option<(&Unit, &Segment)> {
1522 self.segments().find(|(_, s)| s.id == seg_id)
1523 }
1524
1525 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 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 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 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 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 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 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 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 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 pub fn set_state(&mut self, seg_id: &str, state: SegState) -> Result<(), Error> {
1660 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
1667pub(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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1722#[non_exhaustive]
1723pub struct ExtractOptions {
1724 pub source_lang: Option<String>,
1726 pub target_lang: Option<String>,
1728 pub granularity: Granularity,
1730 pub include_locked: bool,
1732 #[serde(default, skip_serializing_if = "Option::is_none")]
1734 pub limits: Option<Limits>,
1735 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1740 pub format_options: BTreeMap<String, String>,
1741 #[serde(default, skip_serializing_if = "Option::is_none")]
1744 pub profile: Option<String>,
1745}
1746
1747impl ExtractOptions {
1748 pub fn with_profile(mut self, profile: impl IntoOptionString) -> ExtractOptions {
1750 self.profile = profile.into_option_string();
1751 self
1752 }
1753 pub fn is_profile(&self, name: &str) -> bool {
1755 self.profile.as_deref() == Some(name)
1756 }
1757 pub fn new() -> ExtractOptions {
1759 ExtractOptions::default()
1760 }
1761 pub fn with_source_lang(mut self, lang: impl IntoOptionString) -> ExtractOptions {
1763 self.source_lang = lang.into_option_string();
1764 self
1765 }
1766 pub fn with_target_lang(mut self, lang: impl IntoOptionString) -> ExtractOptions {
1768 self.target_lang = lang.into_option_string();
1769 self
1770 }
1771 pub fn with_granularity(mut self, granularity: Granularity) -> ExtractOptions {
1773 self.granularity = granularity;
1774 self
1775 }
1776 pub fn with_include_locked(mut self, include_locked: bool) -> ExtractOptions {
1778 self.include_locked = include_locked;
1779 self
1780 }
1781 pub fn with_limits(mut self, limits: impl Into<Option<Limits>>) -> ExtractOptions {
1783 self.limits = limits.into();
1784 self
1785 }
1786 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 pub fn with_format_options(mut self, options: BTreeMap<String, String>) -> ExtractOptions {
1793 self.format_options = options;
1794 self
1795 }
1796
1797 pub fn format_option(&self, key: &str) -> Option<&str> {
1799 self.format_options.get(key).map(String::as_str)
1800 }
1801
1802 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 pub fn format_int(&self, key: &str) -> Option<i64> {
1814 self.format_option(key)?.trim().parse().ok()
1815 }
1816
1817 pub fn limits(&self) -> Limits {
1819 self.limits.unwrap_or_default().clamped()
1822 }
1823}
1824
1825#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1827#[non_exhaustive]
1828pub enum OptionKind {
1829 Bool,
1831 Int,
1833 Text,
1835}
1836
1837#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1840#[non_exhaustive]
1841pub struct FormatOptionKey {
1842 pub key: &'static str,
1844 pub kind: OptionKind,
1846 pub help: &'static str,
1848}
1849
1850impl FormatOptionKey {
1851 pub const fn new(key: &'static str, kind: OptionKind, help: &'static str) -> FormatOptionKey {
1853 FormatOptionKey { key, kind, help }
1854 }
1855 pub const fn bool(key: &'static str, help: &'static str) -> FormatOptionKey {
1857 FormatOptionKey::new(key, OptionKind::Bool, help)
1858 }
1859 pub const fn int(key: &'static str, help: &'static str) -> FormatOptionKey {
1861 FormatOptionKey::new(key, OptionKind::Int, help)
1862 }
1863 pub const fn text(key: &'static str, help: &'static str) -> FormatOptionKey {
1865 FormatOptionKey::new(key, OptionKind::Text, help)
1866 }
1867
1868 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
1889pub fn check_format_options(opts: &ExtractOptions, known: &[FormatOptionKey]) -> Result<(), Error> {
1893 check_option_map(&opts.format_options, known)
1894}
1895
1896pub 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
1912pub 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1944#[non_exhaustive]
1945pub enum OutputEncoding {
1946 #[default]
1948 #[serde(rename = "keep")]
1949 Keep,
1950 #[serde(rename = "utf-8", alias = "utf8")]
1953 Utf8,
1954}
1955
1956#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1966#[serde(default, deny_unknown_fields)]
1967#[non_exhaustive]
1968pub struct MergeOptions {
1969 pub output_encoding: OutputEncoding,
1971 pub stamp_target_always: bool,
1973 #[serde(skip_serializing_if = "Option::is_none")]
1975 pub profile: Option<String>,
1976 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
1978 pub format_options: BTreeMap<String, String>,
1979 #[serde(skip_serializing_if = "Option::is_none")]
1983 pub limits: Option<Limits>,
1984}
1985
1986impl MergeOptions {
1987 pub fn new() -> MergeOptions {
1989 MergeOptions::default()
1990 }
1991 pub fn with_output_encoding(mut self, output_encoding: OutputEncoding) -> MergeOptions {
1993 self.output_encoding = output_encoding;
1994 self
1995 }
1996 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 pub fn with_profile(mut self, profile: impl IntoOptionString) -> MergeOptions {
2003 self.profile = profile.into_option_string();
2004 self
2005 }
2006 pub fn is_profile(&self, name: &str) -> bool {
2008 self.profile.as_deref() == Some(name)
2009 }
2010 pub fn with_limits(mut self, limits: impl Into<Option<Limits>>) -> MergeOptions {
2012 self.limits = limits.into();
2013 self
2014 }
2015 pub fn limits(&self) -> Limits {
2017 self.limits.unwrap_or_default().clamped()
2020 }
2021 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 pub fn with_format_options(mut self, options: BTreeMap<String, String>) -> MergeOptions {
2028 self.format_options = options;
2029 self
2030 }
2031
2032 pub fn any_translated(doc: &Document) -> bool {
2034 doc.segments().any(|(_, s)| s.has_target())
2035 }
2036
2037 pub fn should_stamp(&self, doc: &Document) -> bool {
2041 self.stamp_lang(doc, Self::any_translated(doc)).is_some()
2042 }
2043
2044 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 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]
2062pub enum Error {
2064 #[error("not a {format} file: {msg}")]
2065 Parse {
2067 format: String,
2069 msg: String,
2071 },
2072 #[error("unsupported: {0}")]
2073 Unsupported(String),
2075 #[error("unknown segment {0}")]
2076 UnknownSegment(String),
2078 #[error("segment {0} is locked")]
2079 Locked(String),
2081 #[error("tag {0} is not in the source")]
2082 InventedTag(String),
2084 #[error("tag {0} appears more often than in the source")]
2085 DuplicatedTag(String),
2087 #[error("this skeleton was made by {found}, but this is {expected}; open the file again with the current parser")]
2088 ParserVersion {
2090 found: String,
2092 expected: String,
2094 },
2095 #[error("cannot write: {0}")]
2096 Write(String),
2098 #[error("{reason}")]
2105 Unwritable {
2106 unit: Option<String>,
2108 reason: String,
2110 },
2111 #[error("unit {unit} is a plural form added for another target language; extract the file again for this target")]
2115 TargetChanged {
2116 unit: String,
2118 },
2119 #[error("{0}")]
2122 Limit(LimitError),
2123 #[error("{0}")]
2125 Encoding(String),
2126 #[error("format option {key}: {msg}")]
2128 FormatOption {
2129 key: String,
2131 msg: String,
2133 },
2134 #[error("unknown profile {0:?}")]
2136 UnknownProfile(String),
2137 #[error(transparent)]
2138 Io(#[from] std::io::Error),
2140}
2141
2142pub trait Filter: Send + Sync {
2151 fn id(&self) -> &'static str;
2153 fn extensions(&self) -> &'static [&'static str];
2155 fn sniff(&self, bytes: &[u8]) -> bool;
2157 fn bilingual(&self) -> bool {
2160 false
2161 }
2162 fn format_option_keys(&self) -> &'static [FormatOptionKey] {
2166 &[]
2167 }
2168 fn extract(&self, bytes: &[u8], opts: &ExtractOptions) -> Result<Document, Error>;
2170 fn merge_with(&self, doc: &Document, opts: &MergeOptions) -> Result<Vec<u8>, Error>;
2175 fn merge(&self, doc: &Document) -> Result<Vec<u8>, Error> {
2178 self.merge_with(doc, &MergeOptions::default())
2179 }
2180 fn preview(&self, _doc: &Document) -> Option<String> {
2184 None
2185 }
2186 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 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 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 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 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 assert_eq!(d.units[1].segments[0].target, vec![Inline::text("b")]);
2323 assert!(!d.units[4].segments[0].has_target());
2324 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 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 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}