Repository Public License
1// ORIX Convert — App/Sources/App/L10n.swift2// Description: String lookup. L() reads the app's string catalog (Localizable); LE() translates English strings that3// come from engines (option labels, limitations, warnings) through the "Engines" catalog, falling back4// to the English text. Formatting helpers for sizes, durations and counts are locale-aware.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import Foundation78/// Localized app string. The key is the English text.9nonisolated func L(_ key: String) -> String {10 Bundle.main.localizedString(forKey: key, value: key, table: nil)11}1213/// Localized app string with `%@` / `%lld` arguments.14nonisolated func L(_ key: String, _ arguments: any CVarArg...) -> String {15 String(format: Bundle.main.localizedString(forKey: key, value: key, table: nil), locale: Locale.current, arguments: arguments)16}1718/// Localized engine-provided string. Exact catalog match first, then the harvested patterns for interpolated19/// messages (see EngineStrings), then the English text unchanged.20nonisolated func LE(_ english: String) -> String {21 EngineStrings.shared.translate(english)22}2324/// Localized value reported by an engine (an inspection field value, a fact): only an exact catalog match is used25/// ("yes", "none", "present (never executed)"), never a pattern — the value may be the user's own data (a title, a26/// name) and must then stay as it is.27nonisolated func LEValue(_ english: String) -> String {28 EngineStrings.shared.exact(english) ?? english29}3031/// Looks up engine strings in `Engines.strings` (compiled from Engines.xcstrings).32nonisolated final class EngineStrings: Sendable {33 static let shared = EngineStrings()3435 private struct Pattern: Sendable {36 let regex: NSRegularExpression37 let translation: String38 }3940 private let patterns: [Pattern]41 private let isEnglish: Bool42 /// The bundle whose `Engines` table is read: the main bundle, or one `.lproj` of it when a language is forced.43 private let bundle: Bundle44 private static let selector = try? NSRegularExpression(pattern: #"\{(\d+)\|([^|{}]*)\|([^|{}]*)\}"#)4546 /// `language` forces a localization of the app whatever the user's language (the self-test reads the French47 /// table this way); `nil` follows the app's preferred localization.48 init(language forced: String? = nil) {49 let language = forced ?? Bundle.main.preferredLocalizations.first ?? "en"50 isEnglish = language.hasPrefix("en")51 if let forced, let path = Bundle.main.path(forResource: forced, ofType: "lproj"), let localized = Bundle(path: path) { bundle = localized } else { bundle = .main }52 var compiled: [Pattern] = []53 if !isEnglish, let url = Bundle.main.url(forResource: "EnginePatterns", withExtension: "json"),54 let data = try? Data(contentsOf: url), let table = try? JSONDecoder().decode([String: String].self, from: data) {55 // Longest keys first so the most specific pattern wins. A capture may be empty: engines build plurals56 // with interpolations such as "page\(n == 1 ? "" : "s")".57 // The most specific pattern wins: most literal text first (not the longest key — "%@ image%@: %@." must58 // not beat "Limitation: %@"). A capture may be empty: engines build plurals with interpolations such as59 // "page\(n == 1 ? "" : "s")". A capture that decides a plural choice ({N|…|…}) is a number or a short60 // plural mark, never a sentence: this keeps generic patterns from swallowing unrelated messages.61 func literal(_ key: String) -> Int { key.replacingOccurrences(of: "%@", with: "").count }62 let ordered = table.sorted { a, b in63 let la = literal(a.key), lb = literal(b.key)64 return la != lb ? la > lb : a.key < b.key65 }66 for (key, translation) in ordered {67 var deciding = Set<Int>()68 if let selector = Self.selector {69 for match in selector.matches(in: translation, options: [], range: NSRange(translation.startIndex..., in: translation)) {70 if let range = Range(match.range(at: 1), in: translation), let index = Int(translation[range]) { deciding.insert(index) }71 }72 }73 let parts = key.components(separatedBy: "%@")74 var pattern = "^"75 for (index, part) in parts.enumerated() {76 pattern += NSRegularExpression.escapedPattern(for: part)77 if index < parts.count - 1 {78 pattern += deciding.contains(index + 1) ? #"((?:[0-9][0-9 \u00A0\u202F,.]*)|(?:[a-z ]{0,9}))"# : "(.*?)"79 }80 }81 if let regex = try? NSRegularExpression(pattern: pattern + "$", options: [.dotMatchesLineSeparators]) {82 compiled.append(Pattern(regex: regex, translation: translation))83 }84 }85 }86 patterns = compiled87 }8889 func translate(_ english: String) -> String { translate(english, depth: 0) }9091 /// The exact catalog translation of `english`, `nil` when there is none (or in English).92 func exact(_ english: String) -> String? {93 if isEnglish || english.isEmpty { return nil }94 let found = bundle.localizedString(forKey: english, value: "\u{1}", table: "Engines")95 return found == "\u{1}" ? nil : found96 }9798 /// Whether a captured value stands for "one" in French: a number below 2 (0 and 1 are singular), or — when the99 /// capture is the English plural mark itself — the singular form ("", "y", "is", "was", "has", "does").100 static func isSingular(_ capture: String) -> Bool {101 let trimmed = capture.trimmingCharacters(in: .whitespaces)102 let digits = trimmed.replacingOccurrences(of: ",", with: "").replacingOccurrences(of: "\u{00A0}", with: "").replacingOccurrences(of: "\u{202F}", with: "").replacingOccurrences(of: " ", with: "")103 if let number = Double(digits) { return abs(number) < 2 }104 return ["", "y", "is", "was", "has", "does", "it", "this"].contains(trimmed.lowercased())105 }106107 /// Exact match, then patterns. Captured values are themselves looked up (one level), so a translated wrapper108 /// such as "The file is protected. %@" also translates the sentence it wraps. A translation may reorder its109 /// arguments with %1$@, %2$@… (and leave out a capture that is only an English plural mark), and choose between110 /// a singular and a plural wording with {N|singular|plural}, decided by capture N (`isSingular`).111 private func translate(_ english: String, depth: Int) -> String {112 if isEnglish || english.isEmpty { return english }113 let exact = bundle.localizedString(forKey: english, value: "\u{1}", table: "Engines")114 if exact != "\u{1}" { return exact }115 guard depth < 2 else { return english }116 let range = NSRange(english.startIndex..., in: english)117 for pattern in patterns {118 guard let match = pattern.regex.firstMatch(in: english, options: [], range: range) else { continue }119 let raw: [String] = (1..<match.numberOfRanges).map { index in Range(match.range(at: index), in: english).map { String(english[$0]) } ?? "" }120 let captures = raw.map { translate($0, depth: depth + 1) }121 var out = pattern.translation122 // Plural choices first (they never contain a placeholder of their own that depends on order).123 if let selector = Self.selector {124 while let found = selector.firstMatch(in: out, options: [], range: NSRange(out.startIndex..., in: out)),125 let whole = Range(found.range, in: out), let number = Range(found.range(at: 1), in: out),126 let one = Range(found.range(at: 2), in: out), let many = Range(found.range(at: 3), in: out) {127 let index = (Int(out[number]) ?? 0) - 1128 let singular = raw.indices.contains(index) ? Self.isSingular(raw[index]) : false129 out.replaceSubrange(whole, with: String(singular ? out[one] : out[many]))130 }131 }132 // Positional and sequential placeholders are filled in one pass, so that a captured value which itself133 // contains "%@" is never taken for a placeholder.134 var result = ""135 var next = 0136 var rest = Substring(out)137 while let percent = rest.firstIndex(of: "%") {138 result += rest[..<percent]139 let after = rest[rest.index(after: percent)...]140 if after.hasPrefix("@") {141 if next < captures.count { result += captures[next] }142 next += 1143 rest = after.dropFirst()144 } else if let dollar = after.firstIndex(of: "$"), let index = Int(after[..<dollar]), after[after.index(after: dollar)...].hasPrefix("@") {145 if captures.indices.contains(index - 1) { result += captures[index - 1] }146 rest = after[after.index(after: dollar)...].dropFirst()147 } else {148 result += "%"149 rest = after150 }151 }152 result += rest153 return result154 }155 return english156 }157}158159/// Locale-aware formatting used across the app.160nonisolated enum Fmt {161 static func bytes(_ value: Int64?) -> String {162 guard let value else { return "—" }163 return value.formatted(.byteCount(style: .file))164 }165166 static func count(_ value: Int) -> String { value.formatted(.number) }167168 static func percent(_ fraction: Double) -> String {169 fraction.formatted(.percent.precision(.fractionLength(0)))170 }171172 /// "1 min 12 s", "0.4 s".173 static func duration(_ seconds: Double?) -> String {174 guard let seconds, seconds.isFinite, seconds >= 0 else { return "—" }175 if seconds < 0.1 { return "< " + Measurement(value: 0.1, unit: UnitDuration.seconds).formatted(.measurement(width: .narrow, usage: .asProvided)) }176 if seconds < 10 {177 return Measurement(value: (seconds * 10).rounded() / 10, unit: UnitDuration.seconds).formatted(.measurement(width: .narrow, usage: .asProvided))178 }179 return Duration.seconds(seconds.rounded()).formatted(.units(allowed: [.hours, .minutes, .seconds], width: .narrow, maximumUnitCount: 2))180 }181182 static func date(_ date: Date) -> String {183 date.formatted(date: .abbreviated, time: .shortened)184 }185186 static func time(_ date: Date) -> String {187 date.formatted(.dateTime.hour().minute().second().secondFraction(.fractional(2)))188 }189190 /// "+12 %" / "−48 %" change from `before` to `after`; `nil` when it cannot be computed.191 static func change(before: Int64?, after: Int64?) -> String? {192 guard let before, let after, before > 0 else { return nil }193 let ratio = Double(after - before) / Double(before)194 return ratio.formatted(.percent.precision(.fractionLength(0)).sign(strategy: .always(includingZero: false)))195 }196}197