Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ All notable changes to this project will be documented in this file. Take a look

### Changed

#### Shared

* `Language` is now parsed from its BCP 47 tag, [see the migration guide](docs/Migration%20Guide.md#language).

#### Navigator

* Upgraded Readium CSS to version 2.0.5 in the EPUB navigator, which changes several EPUB preferences, [see the migration guide](docs/Migration%20Guide.md#upgrade-to-readium-css-v2).
Expand Down Expand Up @@ -94,7 +98,7 @@ All notable changes to this project will be documented in this file. Take a look
* `AudioNavigatorDelegate.navigator(_:shouldPlayNextResource:)` is no longer called after the last resource. Use the new `MediaPlaybackState.ended` to detect the end of the publication, [see the migration guide](docs/Migration%20Guide.md#end-of-the-publication).
* The `PublicationSpeechSynthesizer` picks up its configuration differently:
* Changing `config` while playing restarts the current utterance with the new configuration, instead of applying it from the next utterance.
* An utterance whose language has no voice in `Configuration.voices` is spoken with the best voice of its base language, instead of the default voice of the engine, [see the migration guide](docs/Migration%20Guide.md#text-to-speech-voices).
* An utterance whose language has no voice in `Configuration.voices` is spoken with the best voice of its primary language, instead of the default voice of the engine, [see the migration guide](docs/Migration%20Guide.md#text-to-speech-voices).

#### Streamer

Expand Down
2 changes: 1 addition & 1 deletion Sources/Navigator/EPUB/CSS/ReadiumCSS.swift
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ extension ReadiumCSS: HTMLInjectable {
!bodyLang.isEmpty
{
return [
.langAttribute(on: .html, language: Language(code: .bcp47(bodyLang))),
.langAttribute(on: .html, language: Language(bodyLang)),
]
} else {
return [
Expand Down
4 changes: 2 additions & 2 deletions Sources/Navigator/TTS/AVTTSEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ private extension TTSVoice {
init(voice: AVSpeechSynthesisVoice) {
self.init(
id: ID(voice.identifier),
language: Language(code: .bcp47(voice.language)),
language: Language(voice.language),
name: voice.name,
gender: Gender(voice: voice),
quality: Quality(voice: voice)
Expand Down Expand Up @@ -398,7 +398,7 @@ private extension TTSVoice.Quality {

private extension AVSpeechSynthesisVoice {
convenience init?(language: Language) {
self.init(language: language.code.bcp47)
self.init(language: language.tag)
}
}

Expand Down
14 changes: 7 additions & 7 deletions Sources/Navigator/TTS/PublicationSpeechSynthesizer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -254,14 +254,14 @@ public final class PublicationSpeechSynthesizer: Loggable {
/// it in a voice picker.
///
/// This is the voice of `config.voices` matching `language` and its
/// region first, then its base language, e.g. `en-US` then `en`. The
/// region first, then its primary language, e.g. `en-US` then `en`. The
/// voices which are not installed are skipped. Without a match, this is
/// the first voice of the base language ordered by
/// the first voice of the primary language ordered by
/// ``TTSVoice/sorted(preferredRegions:displayLocale:)``.
///
/// Returns `nil` when the engine picks the voice itself: with
/// `config.prefersAssistiveTechnologyVoice`, or when no voice is
/// installed for the base language.
/// installed for the primary language.
public func voice(for language: Language) -> TTSVoice? {
guard !config.prefersAssistiveTechnologyVoice else {
return nil
Expand Down Expand Up @@ -455,19 +455,19 @@ public final class PublicationSpeechSynthesizer: Loggable {
}

/// Returns the installed voice of `config.voices` for `language`, matching
/// its region first, then its base language.
/// its region first, then its primary language.
private func configuredVoice(for language: Language) -> TTSVoice? {
[language, language.removingRegion()]
[language, language.primaryLanguage]
.compactMap { config.voices[$0] }
.lazy
.compactMap { self.voice(withID: $0) }
.first
}

/// Returns the first voice of the base language of `language`, ordered by
/// Returns the first voice of the primary language of `language`, ordered by
/// `sorted()`.
private func defaultVoice(for language: Language) -> TTSVoice? {
let language = language.removingRegion()
let language = language.primaryLanguage
if let voice = defaultVoices[language] {
return voice
}
Expand Down
110 changes: 56 additions & 54 deletions Sources/Navigator/TTS/TTSVoice.swift
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,14 @@ public extension [TTSVoice] {
/// If the input language includes a region (e.g., "en-US"), only voices
/// with that exact language and region combination will be returned.
/// If the input language has no region (e.g., "en"), all voices matching
/// the base language will be returned, regardless of their region.
/// the primary language will be returned, regardless of their region.
func filterByLanguage(_ language: Language) -> [TTSVoice] {
if language.region != nil {
// Exact match: language code and region must both match
return filter { $0.language == language }
} else {
// Base language match: filter by language code only, ignoring region
return filter { $0.language.removingRegion() == language }
// Primary language match: filter by language code only, ignoring region
return filter { $0.language.primaryLanguage == language }
}
}

Expand All @@ -106,12 +106,14 @@ public extension [TTSVoice] {
/// 2. Order by voice quality from highest to lowest.
/// 3. Order by voice gender: female > male > unspecified.
/// 4. Order by voice name alphabetically.
///
/// - Parameter preferredRegions: Regions to list first, e.g. `GB` or `419`.
func sorted(
preferredRegions: [Language.Region]? = nil,
displayLocale: Locale = .current
) -> [TTSVoice] {
let languagesAndRegions: [(language: Language, region: Language.Region?)] =
map { ($0.language.removingRegion(), $0.language.region) }
map { ($0.language.primaryLanguage, $0.language.region) }

let regionsByLanguage: [Language: Set<Language.Region>] =
Dictionary(grouping: languagesAndRegions, by: \.language)
Expand All @@ -137,7 +139,7 @@ public extension [TTSVoice] {

// 3. Add remaining regions ordered by localized name.
ordered.append(contentsOf: regions.sorted {
($0.localizedName(in: displayLocale) ?? $0.code) < ($1.localizedName(in: displayLocale) ?? $1.code)
($0.localizedName(in: displayLocale) ?? $0.rawValue) < ($1.localizedName(in: displayLocale) ?? $1.rawValue)
})

ordered = ordered.removingDuplicates()
Expand All @@ -156,7 +158,7 @@ public extension [TTSVoice] {
gender: Int,
name: String
) {
let language = voice.language.removingRegion()
let language = voice.language.primaryLanguage

let regionPriority: Int =
if
Expand All @@ -169,7 +171,7 @@ public extension [TTSVoice] {
}

return (
language: language.localizedLanguage(in: displayLocale) ?? voice.language.code.bcp47,
language: language.localizedLanguage(in: displayLocale) ?? voice.language.tag,
region: regionPriority,
quality: voice.quality.flatMap { qualityPriorities[$0] } ?? .max,
gender: genderPriorities[voice.gender] ?? .max,
Expand Down Expand Up @@ -206,58 +208,58 @@ public extension [TTSVoice] {
private extension Locale {
static var preferredRegions: [ReadiumShared.Language.Region] {
preferredLanguages
.compactMap { ReadiumShared.Language(code: .bcp47($0)).region }
.compactMap { ReadiumShared.Language($0).region }
}
}

// Default region per base language.
// Default region per primary language.
// Source: https://github.com/HadrienGardeur/web-speech-recommended-voices
private let defaultRegionByLanguage: [Language.Code: Language.Region] = [
.bcp47("ar"): "SA",
.bcp47("bg"): "BG",
.bcp47("bho"): "IN",
.bcp47("bn"): "IN",
.bcp47("ca"): "ES",
.bcp47("cmn"): "CN",
.bcp47("cs"): "CZ",
.bcp47("da"): "DK",
.bcp47("de"): "DE",
.bcp47("el"): "GR",
.bcp47("en"): "US",
.bcp47("es"): "ES",
.bcp47("eu"): "ES",
.bcp47("fa"): "IR",
.bcp47("fi"): "FI",
.bcp47("fr"): "FR",
.bcp47("gl"): "ES",
.bcp47("he"): "IL",
.bcp47("hi"): "IN",
.bcp47("hr"): "HR",
.bcp47("hu"): "HU",
.bcp47("id"): "ID",
.bcp47("it"): "IT",
.bcp47("ja"): "JP",
.bcp47("kn"): "IN",
.bcp47("ko"): "KR",
.bcp47("mr"): "IN",
.bcp47("ms"): "MY",
.bcp47("nb"): "NO",
.bcp47("nl"): "NL",
.bcp47("pl"): "PL",
.bcp47("pt"): "BR",
.bcp47("ro"): "RO",
.bcp47("ru"): "RU",
.bcp47("sk"): "SK",
.bcp47("sl"): "SI",
.bcp47("sv"): "SE",
.bcp47("ta"): "IN",
.bcp47("te"): "IN",
.bcp47("th"): "TH",
.bcp47("tr"): "TR",
.bcp47("uk"): "UA",
.bcp47("vi"): "VN",
.bcp47("wuu"): "CN",
.bcp47("yue"): "HK",
"ar": "SA",
"bg": "BG",
"bho": "IN",
"bn": "IN",
"ca": "ES",
"cmn": "CN",
"cs": "CZ",
"da": "DK",
"de": "DE",
"el": "GR",
"en": "US",
"es": "ES",
"eu": "ES",
"fa": "IR",
"fi": "FI",
"fr": "FR",
"gl": "ES",
"he": "IL",
"hi": "IN",
"hr": "HR",
"hu": "HU",
"id": "ID",
"it": "IT",
"ja": "JP",
"kn": "IN",
"ko": "KR",
"mr": "IN",
"ms": "MY",
"nb": "NO",
"nl": "NL",
"pl": "PL",
"pt": "BR",
"ro": "RO",
"ru": "RU",
"sk": "SK",
"sl": "SI",
"sv": "SE",
"ta": "IN",
"te": "IN",
"th": "TH",
"tr": "TR",
"uk": "UA",
"vi": "VN",
"wuu": "CN",
"yue": "HK",
]

/// Quality order priority: higher to lower
Expand Down
24 changes: 14 additions & 10 deletions Sources/Navigator/Toolkit/Extensions/Language.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,23 @@ import Foundation
import ReadiumShared

extension Language {
/// Whether publications in this language are read from right to left by
/// default.
///
/// This is the case of Arabic, Persian and Hebrew whatever their region
/// or script, and of Traditional Chinese tagged exactly `zh-Hant` or
/// `zh-TW`, which is laid out vertically.
///
/// See https://github.com/readium/css/blob/develop/docs/CSS16-internationalization.md#missing-page-progression-direction
var isRTL: Bool {
let c = code.bcp47.lowercased()
return c == "ar"
|| c == "fa"
|| c == "he"
|| c == "zh-hant"
|| c == "zh-tw"
tag == "zh-Hant" || tag == "zh-TW" || ["ar", "fa", "he"].contains(code)
}

/// Whether this is a Chinese, Japanese or Korean language, which can be
/// laid out horizontally or vertically.
///
/// See https://github.com/readium/css/blob/develop/css/dist/ReadMe.md#cjk
var isCJK: Bool {
let c = code.bcp47.lowercased()
return c == "ja"
|| c == "ko"
|| removingRegion().code.bcp47.lowercased() == "zh"
["zh", "ja", "ko"].contains(code)
}
}
2 changes: 1 addition & 1 deletion Sources/Navigator/Toolkit/HTMLInjection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ extension HTMLInjection {
}

static func langAttribute(on target: HTMLElement, language: Language) -> HTMLInjection {
.attribute("xml:lang", on: target, value: language.code.bcp47)
.attribute("xml:lang", on: target, value: language.tag)
}

static func styleAttribute(on target: HTMLElement, css: String) -> HTMLInjection {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ public struct GuidedNavigationObject: Hashable, Sendable, JSONValueDecodable {
self.init(
plain: plain,
ssml: ssml,
language: obj["language"]?.string.map { Language(code: .bcp47($0)) }
language: obj["language"]?.string.map { Language($0) }
)
} else {
warnings?.log("Invalid Guided Navigation Text", model: Self.self, source: json, severity: .moderate)
Expand Down
4 changes: 2 additions & 2 deletions Sources/Shared/Publication/Metadata.swift
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public struct Metadata: Hashable, Sendable, Loggable, WarningLogger, JSONValueDe
self.modified = modified
self.published = published
self.languages = languages
language = languages.first.map { Language(code: .bcp47($0)) }
language = languages.first.map { Language($0) }
self.sortAs = sortAs
self.subjects = subjects
self.authors = authors
Expand Down Expand Up @@ -166,7 +166,7 @@ public struct Metadata: Hashable, Sendable, Loggable, WarningLogger, JSONValueDe
modified = jsonObject.pop("modified")?.date
published = jsonObject.pop("published")?.date
languages = jsonObject.pop("language")?.decode(allowingSingle: true) ?? []
language = languages.first.map { Language(code: .bcp47($0)) }
language = languages.first.map { Language($0) }
sortAs = jsonObject.pop("sortAs")?.string
subjects = jsonObject.pop("subject")?.decode(allowingSingle: true, warnings: warnings) ?? []
authors = jsonObject.pop("author")?.decode(allowingSingle: true, warnings: warnings) ?? []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ public actor HTMLResourceContentIterator: ContentIterator {
return
}

let language = try node.language().map { Language(code: .bcp47($0)) }
let language = try node.language().map { Language($0) }
if currentLanguage != language {
flushSegment()
currentLanguage = language
Expand Down
Loading
Loading