import Foundation import ParcelConfig import ParcelCore import Testing @testable import ParcelUI struct LearningLocalizationTests { @Test func catalogAndRuntimeCopyMatch() throws { let catalog = try loadCatalog("UI") let runtimeURL = try #require( Bundle.module.url(forResource: "UI", withExtension: "strings", subdirectory: "en.lproj")) let runtime = try PropertyListDecoder().decode([String: String].self, from: Data(contentsOf: runtimeURL)) let pluralURL = try #require( Bundle.module.url(forResource: "UI", withExtension: "stringsdict", subdirectory: "en.lproj")) let plurals = try PropertyListDecoder().decode([String: CompiledPlural].self, from: Data(contentsOf: pluralURL)) for (key, entry) in catalog.strings { let english = try #require(entry.localizations["en"]) if english.substitutions == nil { #expect(runtime[key] == english.stringUnit?.value, "Missing compiled key: \(key)") } else { #expect(plurals[key] != nil, "Missing compiled plural: \(key)") } } } @Test( arguments: ["TourSetup", "TourDemos", "Menu", "WhatsNew", "Highlights", "Appearance"], ["en", "es", "fr", "de", "ja", "zh-Hans", "ko", "pt-BR"]) func featureCatalogsHaveCompiledLocalizedValues(table: String, locale: String) throws { let catalog = try loadCatalog(table) let runtimeURL = try #require( Bundle.module.url(forResource: table, withExtension: "strings", subdirectory: "\(locale).lproj")) let runtime = try PropertyListDecoder().decode([String: String].self, from: Data(contentsOf: runtimeURL)) for (key, entry) in catalog.strings { let localized = try #require(entry.localizations[locale]) let value = try #require(localized.stringUnit?.value) #expect(!value.isEmpty) if let substitutions = localized.substitutions { let url = try #require( Bundle.module.url(forResource: table, withExtension: "stringsdict", subdirectory: "\(locale).lproj") ) let plurals = try PropertyListDecoder().decode( [String: CompiledPlural].self, from: Data(contentsOf: url)) let expected = normalizedPluralFormat(value, arguments: substitutions.mapValues(\.argNum)) #expect(plurals[key]?.format == expected) } else { #expect(runtime[key] == value) } } } @Test(arguments: ["en", "es", "fr", "de", "ja", "zh-Hans", "ko", "pt-BR"]) func accessibilityHelperAndLoginCopyCompileInEveryLanguage(locale: String) throws { for (table, keys) in [ ( "UI", [ "↑ Drag Parcel into the list above", "Drag Parcel into the Accessibility list", "Drag the icon into the list above, or activate to reveal Parcel in Finder.", "Reveal Parcel in Finder", "Close", "The Accessibility helper could not follow System Settings.", ] ), ( "TourSetup", [ "Accessibility is on, Parcel can move and resize your windows", "Turn on Accessibility so Parcel can move and resize your windows", "Enable…", "Enable Accessibility…", "Open at login (Recommended)", "Open Login Items", "You’re ready", ] ), ("Settings", ["Open at Login", "launch at login", "login item"]), ] { let catalog = try loadCatalog(table) let url = try #require( Bundle.module.url(forResource: table, withExtension: "strings", subdirectory: "\(locale).lproj")) let runtime = try PropertyListDecoder().decode([String: String].self, from: Data(contentsOf: url)) for key in keys { let value = try #require(catalog.strings[key]?.localizations[locale]?.stringUnit?.value) #expect(!value.isEmpty) #expect(runtime[key] == value) #expect(!value.contains("\n"), "Allow copy must be one message, not a title and explanation.") } } } @Test(arguments: [ "Parcel tiles your windows automatically. No shortcuts needed.", "Accessibility is on, Parcel can move and resize your windows", "Turn on Accessibility so Parcel can move and resize your windows", "Parcel will tidy your windows and keep them arranged automatically.", "Tidy this screen, then keep windows arranged across your screens.", "Parcel moves windows only when you ask. Choose Retile in the Parcel menu to arrange them.", ]) func screenSummariesKeepTheirTwoSentenceBudget(key: String) throws { let catalog = try loadCatalog("TourSetup") let english = try #require(catalog.strings[key]?.localizations["en"]?.stringUnit?.value) #expect(english.split(whereSeparator: \.isWhitespace).count <= 20) #expect(english.filter { ".!?".contains($0) }.count <= 2) #expect(!english.contains(";")) } @Test func pluralFormatNormalizationKeepsArgumentPositions() { #expect(normalizedPluralFormat("%#@points@", arguments: ["points": 1]) == "%1$#@points@") #expect( normalizedPluralFormat("%1$@ layout, %#@windows@", arguments: ["windows": 2]) == "%1$@ layout, %2$#@windows@") #expect(normalizedPluralFormat("%2$#@points@", arguments: ["points": 1]) == "%2$#@points@") } private func normalizedPluralFormat(_ value: String, arguments: [String: Int]) -> String { arguments.reduce(value) { format, argument in format.replacingOccurrences(of: "%#@\(argument.key)@", with: "%\(argument.value)$#@\(argument.key)@") } } @Test func everyRuntimeBuiltUIKeyHasACatalogEntry() throws { let catalogs = [ "UI": try loadCatalog("UI"), "Settings": try loadCatalog("Settings"), "TourSetup": try loadCatalog("TourSetup"), "Menu": try loadCatalog("Menu"), "WhatsNew": try loadCatalog("WhatsNew"), "Support": try loadCatalog("Support"), ] let root = repository.appendingPathComponent("Sources/ParcelUI") let files = try #require(FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil)) for case let file as URL in files where file.pathExtension == "swift" { let source = try String(contentsOf: file, encoding: .utf8) for (function, table) in [ ("UIStrings.text", "UI"), ("SettingsText.string", "Settings"), ("TourText.text", "TourSetup"), ("MenuText.text", "Menu"), ("WhatsNewText.text", "WhatsNew"), ("SupportText.text", "Support"), ] { for argument in try localizationArguments(source, function: function) { let integers: Set switch file.lastPathComponent { case "SettingsText.swift": integers = ["number"] case "SettingsView.swift": integers = ["maximum", "values.windowCap"] default: integers = [] } let literals = try literalKeys(argument, integers: integers) if literals.isEmpty { switch argument.trimmingCharacters(in: .whitespacesAndNewlines) { case "tour.step.titleKey": for step in TourStep.allCases { #expect(catalogs[table]?.strings[step.titleKey] != nil) } case "setup.step.title": for step in TourSetupStep.allCases { #expect(catalogs[table]?.strings[step.title] != nil) } case "referenceTitle(row.command)" where file.lastPathComponent == "TourSetupView.swift": for key in ["Retile", "Next window", "Change layout", "Float window"] { #expect(catalogs[table]?.strings[key] != nil) } case "String.LocalizationValue(name)" where file.lastPathComponent == "WindowRulesText.swift": for app in DefaultFloatApps.all { #expect( catalogs[table]?.strings[app.name] != nil, "Missing default app name: \(app.name)") } case "title" where file.lastPathComponent == "ParcelUI.swift": for key in ["Settings…", "Quit Parcel"] { #expect(catalogs[table]?.strings[key] != nil) } default: Issue.record("Uncovered runtime key in \(file.path): \(argument)") } } for key in literals { #expect( catalogs[table]?.strings[key] != nil, "Missing \(table) catalog key in \(file.path): \(key)" ) } } } } } @Test(arguments: [0, 1, 2, 99, 100]) func windowPluralsUseCatalog(count: Int) { let snapshot = LayoutSnapshot( layout: .grid, bounds: CGRect(x: 0, y: 0, width: 100, height: 100), tiles: (0.. Catalog { try JSONDecoder().decode( Catalog.self, from: Data(contentsOf: repository.appendingPathComponent("Sources/ParcelUI/Resources/\(table).xcstrings"))) } } private func localizationArguments(_ source: String, function: String) throws -> [String] { let expression = try NSRegularExpression(pattern: NSRegularExpression.escapedPattern(for: function) + #"\s*\("#) var result: [String] = [] for match in expression.matches(in: source, range: NSRange(source.startIndex..., in: source)) { guard let range = Range(match.range, in: source) else { throw CatalogScanError.invalidRange } let start = range.upperBound var depth = 1 var quoted = false var escaped = false for index in source[start...].indices { let character = source[index] if escaped { escaped = false continue } if character == "\\" { escaped = true continue } if character == "\"" { quoted.toggle() continue } if quoted { continue } if character == "(" { depth += 1 } if character == ")" { depth -= 1 } if depth == 0 { result.append(String(source[start.. = []) throws -> [String] { let normalized = try normalizeInterpolations(argument, integers: integers) let expression = try NSRegularExpression(pattern: #""((?:\\.|[^"\\])*)""#) return try expression.matches(in: normalized, range: NSRange(normalized.startIndex..., in: normalized)).map { match in guard let range = Range(match.range, in: normalized) else { throw CatalogScanError.invalidRange } return try JSONDecoder().decode(String.self, from: Data(normalized[range].utf8)) } } private func normalizeInterpolations(_ argument: String, integers: Set) throws -> String { var normalized = "" var cursor = argument.startIndex while cursor < argument.endIndex { let character = argument[cursor] let next = argument.index(after: cursor) guard character == "\\", next < argument.endIndex else { normalized.append(character) cursor = next continue } guard argument[next] == "(" else { normalized.append(character) normalized.append(argument[next]) cursor = argument.index(after: next) continue } let start = argument.index(after: next) var end = start var depth = 1 var quoted = false var escaped = false while end < argument.endIndex { let character = argument[end] if escaped { escaped = false } else if character == "\\" { escaped = true } else if character == "\"" { quoted.toggle() } else if !quoted { if character == "(" { depth += 1 } if character == ")" { depth -= 1 } if depth == 0 { break } } end = argument.index(after: end) } guard depth == 0 else { throw CatalogScanError.unclosedInterpolation } normalized += integers.contains(String(argument[start..