use crate::{CodeData, Document, Error, ExtractOptions, Inline, MergeOptions, OutputEncoding, TagKind, Unit};
use serde::Serialize;
pub mod tokens;
pub const LOCOS: &str = "locos";
pub const LOCOS_VERSION: u32 = 1;
pub const P_INDEX: &str = "locos.p_index";
pub const STYLE: &str = "locos.style";
pub const A11Y_IMAGES: &str = "locos.a11y_images";
pub const A11Y_EMPTY_ALT: &str = "locos.a11y_empty_alt";
pub const A11Y_MISSING_ALT: &str = "locos.a11y_missing_alt";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Profile {
pub name: &'static str,
pub version: u32,
}
pub fn locos() -> Profile {
Profile { name: LOCOS, version: LOCOS_VERSION }
}
pub const LOCOS_OLDEST_VERSION: u32 = 1;
pub fn profiles() -> Vec<Profile> {
vec![locos()]
}
pub fn find(name: &str) -> Option<Profile> {
profiles().into_iter().find(|p| p.name == name)
}
pub fn resolve(spec: &str, version: Option<u32>) -> Result<Profile, Error> {
let (name, in_spec) = match spec.split_once('@') {
Some((n, v)) => {
let v: u32 = v.parse().map_err(|_| Error::UnknownProfile(spec.to_string()))?;
(n, Some(v))
}
None => (spec, None),
};
let current = find(name).ok_or_else(|| Error::UnknownProfile(spec.to_string()))?;
let want = match (in_spec, version) {
(Some(a), Some(b)) if a != b => return Err(Error::UnknownProfile(format!("{spec} (asked for version {b})"))),
(a, b) => a.or(b).unwrap_or(current.version),
};
if !current.reads(want) {
return Err(Error::ParserVersion {
found: format!("profile {name} version {want}"),
expected: format!("profile {name} versions {} to {}", current.oldest(), current.version),
});
}
Ok(Profile { name: current.name, version: want })
}
pub fn check(name: Option<&str>) -> Result<(), Error> {
match name {
Some(n) if find(n).is_none() => Err(Error::UnknownProfile(n.to_string())),
_ => Ok(()),
}
}
const LOCOS_KEEPS_ENCODING: &[&str] = &[
"ini", "strings", "dxf", "txt", "properties", "xaml", "resjson", "ttx", "txml", "txlf", "html", "xslt", "hhc", "hhk", "hhp", "rc", "plist", "csv", "tsv", "xtg",
];
impl Profile {
pub fn oldest(&self) -> u32 {
match self.name {
LOCOS => LOCOS_OLDEST_VERSION,
_ => self.version,
}
}
pub fn reads(&self, version: u32) -> bool {
let current = find(self.name).map_or(self.version, |p| p.version);
(self.oldest()..=current).contains(&version)
}
pub fn extract_options(&self) -> ExtractOptions {
ExtractOptions::new().with_profile(self.name)
}
pub fn merge_options(&self, format: &str) -> MergeOptions {
let enc = if LOCOS_KEEPS_ENCODING.contains(&format) { OutputEncoding::Keep } else { OutputEncoding::Utf8 };
MergeOptions::new().with_output_encoding(enc).with_stamp_target_always(true).with_profile(self.name)
}
}
pub fn annotate(doc: &mut Document, profile: Option<&str>) {
if profile != Some(LOCOS) {
return;
}
let format = doc.format.clone();
for u in &mut doc.units {
for c in u.codes.values_mut() {
c.clear_typing();
}
u.context.role = None;
u.context.level = None;
u.plural = None;
let p = match format.as_str() {
"icml" => u.hidden("p").map(str::to_string),
"idml" => u.id.strip_prefix('p').filter(|n| n.parse::<usize>().is_ok()).map(str::to_string),
"txml" | "txlf" => u.hidden("key").map(str::to_string),
"ttx" => u.context.key.clone().filter(|k| k.parse::<usize>().is_ok()),
_ => u.context.extra.get("p_index").map(str::to_string),
};
if let Some(p) = p {
u.context.extra.insert(P_INDEX.to_string(), p);
}
if let Some(pick) = locos_text_codes(&format) {
flatten_codes(u, pick, format != "ftl");
}
if LOCOS_NO_STYLE.contains(&format.as_str()) {
u.context.style = None;
}
if format == "eml" && matches!(u.context.style.as_deref(), Some("Subject" | "text/plain")) {
u.context.style = None;
}
if format == "dtd" {
if let Some(k) = u.context.key.clone() {
u.context.extra.insert(STYLE.to_string(), format!("dtd:{k}"));
}
}
if matches!(format.as_str(), "odt" | "ods" | "odp" | "odg") {
u.context.style = None;
match u.context.kind.as_deref() {
Some("heading") => {
u.context.extra.insert(STYLE.to_string(), "heading".to_string());
}
Some("comment") => {
u.context.extra.insert(STYLE.to_string(), "comment".to_string());
}
_ => {}
}
}
}
}
const LOCOS_NO_STYLE: &[&str] = &[
"po", "wxl", "xaml", "resx", "strings", "properties", "json", "json5", "resjson", "arb", "yaml", "txml", "txlf", "ttml", "ass", "tex", "plist", "stringsdict", "mo",
];
fn locos_text_codes(format: &str) -> Option<fn(&CodeData) -> bool> {
match format {
"po" | "mo" | "strings" | "properties" | "dtd" | "wxl" | "xaml" | "resx" | "json" | "json5" | "resjson" | "yaml" => Some(|_| true),
"arb" | "ftl" => Some(|c| c.label.as_deref() == Some("placeholder")),
_ => None,
}
}
fn flatten_codes(u: &mut Unit, pick: fn(&CodeData) -> bool, drop: bool) {
let mut gone = Vec::new();
for s in &mut u.segments {
let mut out: Vec<Inline> = Vec::with_capacity(s.source.len());
for i in std::mem::take(&mut s.source) {
let raw = match &i {
Inline::Tag { id, kind, display, .. } => match u.codes.get(id) {
Some(c) if pick(c) => {
gone.push(id.clone());
let m = match kind {
TagKind::Open => c.open.as_deref(),
TagKind::Close => c.close.as_deref(),
TagKind::Standalone => c.standalone.as_deref(),
};
Some(m.unwrap_or(display).to_string())
}
_ => None,
},
Inline::Text(_) => None,
};
let i = raw.map(Inline::Text).unwrap_or(i);
match (out.last_mut(), &i) {
(Some(Inline::Text(a)), Inline::Text(b)) => a.push_str(b),
_ => out.push(i),
}
}
s.source = out;
}
if drop {
for id in gone {
u.codes.remove(&id);
}
}
}
pub fn lang_tag(code: &str) -> Option<String> {
let tag = code.trim().replace('_', "-");
if tag.is_empty() || tag.len() > 64 {
return None;
}
let mut parts = tag.split('-');
let first = parts.next()?;
if !(2..=8).contains(&first.len()) || !first.bytes().all(|b| b.is_ascii_alphabetic()) {
return None;
}
let mut out = vec![first.to_ascii_lowercase()];
let mut ext = false;
for sub in parts {
if sub.is_empty() || sub.len() > 8 || !sub.bytes().all(|b| b.is_ascii_alphanumeric()) {
return None;
}
let alpha = sub.bytes().all(|b| b.is_ascii_alphabetic());
if sub.len() == 1 {
ext = true;
out.push(sub.to_ascii_lowercase());
} else if ext {
out.push(sub.to_ascii_lowercase());
} else if sub.len() == 4 && alpha {
let mut s = sub.to_ascii_lowercase();
s[..1].make_ascii_uppercase();
out.push(s);
} else if (sub.len() == 2 && alpha) || (sub.len() == 3 && sub.bytes().all(|b| b.is_ascii_digit())) {
out.push(sub.to_ascii_uppercase());
} else {
out.push(sub.to_ascii_lowercase());
}
}
Some(out.join("-"))
}
pub fn is_rtl(code: &str) -> bool {
const SCRIPTS: [&str; 11] = ["arab", "hebr", "syrc", "thaa", "nkoo", "adlm", "rohg", "samr", "mand", "mend", "yezi"];
const LANGS: [&str; 22] =
["ar", "arc", "azb", "ckb", "dv", "fa", "glk", "he", "iw", "ji", "ks", "lrc", "mzn", "nqo", "pnb", "prs", "ps", "sd", "syr", "ug", "ur", "yi"];
let Some(tag) = lang_tag(code) else { return false };
let parts: Vec<&str> = tag.split('-').collect();
for sub in &parts[1..] {
if sub.len() == 1 {
break;
}
if sub.len() == 4 && sub.bytes().all(|b| b.is_ascii_alphabetic()) {
return SCRIPTS.contains(&sub.to_ascii_lowercase().as_str());
}
}
LANGS.contains(&parts[0])
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct LocosUnit {
pub p_index: i64,
pub segment_id: String,
pub text: String,
pub map: tokens::LocosMap,
pub style: String,
}
pub fn locos_units(doc: &Document) -> Vec<LocosUnit> {
let segs: Vec<(&Unit, &crate::Segment)> = doc.units.iter().filter(|u| u.translate).flat_map(|u| u.segments.iter().map(move |s| (u, s))).collect();
let metas: Vec<Option<i64>> = segs.iter().map(|(u, _)| u.context.extra.get(P_INDEX).and_then(|p| p.parse().ok())).collect();
let distinct = metas.iter().flatten().collect::<std::collections::BTreeSet<_>>().len() == metas.len();
let use_meta = !segs.is_empty() && metas.iter().all(Option::is_some) && distinct;
segs.iter()
.enumerate()
.map(|(i, (u, s))| {
let (text, map) = tokens::to_locos_text_coded(&doc.format, &s.source, &u.codes);
let style = u.context.extra.get(STYLE).filter(|s| !s.is_empty()).map(str::to_string).or_else(|| u.context.style.clone()).unwrap_or_default();
let p_index = match (use_meta, metas[i]) {
(true, Some(p)) => p,
_ => i as i64,
};
LocosUnit { p_index, segment_id: s.id.clone(), text, map, style }
})
.collect()
}
pub fn locos_set_target(doc: &mut Document, seg_id: &str, target: Vec<Inline>) -> Result<(), Error> {
if LOCOS_WRITES_REPAIRED.contains(&doc.format.as_str()) {
let Some((ui, si)) = doc.locate(seg_id) else { return Err(Error::UnknownSegment(seg_id.to_string())) };
let repaired = tokens::repair_tags(&doc.units[ui].segments[si].source, target, false);
return set_like_locos(doc, seg_id, repaired);
}
if !tokens::locos_repairs_tags(&doc.format) {
return set_like_locos(doc, seg_id, target);
}
let Some((ui, si)) = doc.locate(seg_id) else { return Err(Error::UnknownSegment(seg_id.to_string())) };
let repaired = tokens::repair_tags(&doc.units[ui].segments[si].source, target.clone(), true);
set_like_locos(doc, seg_id, repaired)?;
if tokens::locos_keeps_typed_tags(&doc.format) && target.iter().any(|i| matches!(i, Inline::Tag { .. })) {
doc.units[ui].segments[si].target = crate::merge_text(target);
}
Ok(())
}
const LOCOS_WRITES_REPAIRED: &[&str] = &["sub", "xtg", "idml", "icml"];
fn set_like_locos(doc: &mut Document, seg_id: &str, target: Vec<Inline>) -> Result<(), Error> {
if target.iter().all(|i| matches!(i, Inline::Text(t) if t.is_empty())) {
return doc.set_target_empty(seg_id);
}
let blank = target.iter().all(|i| matches!(i, Inline::Text(t) if t.trim().is_empty()));
if !blank {
return doc.set_target_repeating(seg_id, target);
}
doc.set_target_repeating(seg_id, target.clone())?;
let (ui, si) = doc.locate(seg_id).ok_or_else(|| Error::UnknownSegment(seg_id.to_string()))?;
let seg = &mut doc.units[ui].segments[si];
let text: String = target.iter().map(|i| if let Inline::Text(t) = i { t.as_str() } else { "" }).collect();
seg.target = vec![Inline::Text(text)];
seg.empty_target = false;
seg.state = crate::SegState::Draft;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lang_tags_like_locos() {
for (code, want) in [("es_ES", Some("es-ES")), ("EN-us", Some("en-US")), ("zh_hant_tw", Some("zh-Hant-TW")), ("es-419", Some("es-419")), ("x", None), ("", None), ("de DE", None), ("de--DE", None), ("\"><b>", None)] {
assert_eq!(lang_tag(code).as_deref(), want, "{code}");
}
assert!(is_rtl("ar-SA") && is_rtl("ku-Arab") && is_rtl("he") && !is_rtl("ug-Latn") && !is_rtl("de") && !is_rtl("<x>"));
}
#[test]
fn resolve_names_and_versions() {
assert_eq!(resolve("locos", None).unwrap(), locos());
assert_eq!(resolve("locos@1", None).unwrap(), locos());
assert_eq!(resolve("locos", Some(LOCOS_VERSION)).unwrap(), locos());
assert_eq!(resolve("locos@1", Some(1)).unwrap().version, 1);
assert!(matches!(resolve("locos@1", Some(2)), Err(Error::UnknownProfile(_))));
assert!(matches!(resolve("locos@x", None), Err(Error::UnknownProfile(_))));
assert!(matches!(resolve("nope", None), Err(Error::UnknownProfile(_))));
assert!(matches!(resolve("locos", Some(LOCOS_VERSION + 1)), Err(Error::ParserVersion { .. })));
assert!(matches!(resolve("locos@0", None), Err(Error::ParserVersion { .. })));
assert!(locos().reads(1) && !locos().reads(0) && !locos().reads(LOCOS_VERSION + 1));
}
}