From e17def3588980ddbc33c09ba827b6159d03bb808 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Menu?= Date: Wed, 25 Nov 2026 19:18:21 +0100 Subject: [PATCH 1/2] Make the navigator preferences no longer Codable --- CHANGELOG.md | 6 + .../Preferences/AudioPreferences.swift | 48 ++- .../Preferences/EPUBPreferences+Legacy.swift | 238 ++++++++--- .../EPUB/Preferences/EPUBPreferences.swift | 209 ---------- .../PDF/Preferences/PDFPreferences.swift | 113 ++++-- .../Navigator/Preferences/Configurable.swift | 12 +- .../Preferences/LenientDecoding.swift | 17 + Sources/Navigator/Preferences/Types.swift | 20 +- TestApp/Sources/Data/Book.swift | 32 +- TestApp/Sources/Data/Database.swift | 2 +- .../Sources/Data/UserPreferencesStore.swift | 168 -------- TestApp/Sources/Data/UserSettingsStore.swift | 86 ++++ .../Reader/Audiobook/AudiobookModule.swift | 15 +- .../Audiobook/AudiobookViewController.swift | 10 +- .../Common/Preferences/UserPreferences.swift | 26 +- .../Common/Preferences/UserSettings.swift | 290 ++++++++++++++ TestApp/Sources/Reader/EPUB/EPUBModule.swift | 15 +- .../Reader/EPUB/EPUBViewController.swift | 10 +- TestApp/Sources/Reader/PDF/PDFModule.swift | 15 +- .../Reader/PDF/PDFViewController.swift | 10 +- .../Preferences/EPUBPreferencesTests.swift | 378 +++--------------- .../Preferences/LegacyPreferencesTests.swift | 152 +++++++ docs/Guides/Navigator/Preferences.md | 59 +-- docs/Migration Guide.md | 62 ++- 24 files changed, 1075 insertions(+), 918 deletions(-) create mode 100644 Sources/Navigator/Preferences/LenientDecoding.swift delete mode 100644 TestApp/Sources/Data/UserPreferencesStore.swift create mode 100644 TestApp/Sources/Data/UserSettingsStore.swift create mode 100644 TestApp/Sources/Reader/Common/Preferences/UserSettings.swift create mode 100644 Tests/NavigatorTests/Preferences/LegacyPreferencesTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 8226eaa5f1..bd12a18745 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,12 @@ All notable changes to this project will be documented in this file. Take a look * Removed the OpenDyslexic, AccessibleDfA and iA Writer Duospace fonts bundled with the toolkit, [see the migration guide](docs/Migration%20Guide.md#bundled-fonts). * SVG documents in the reading order of an EPUB are now rendered as fixed-layout pages, even in a reflowable publication. +### Removed + +#### Navigator + +* The `Preferences` types and their values are no longer `Codable`. Persist your own settings model and derive the preferences from it instead, [see the migration guide](docs/Migration%20Guide.md#preferences-are-no-longer-codable). + ### Fixed #### Navigator diff --git a/Sources/Navigator/Audiobook/Preferences/AudioPreferences.swift b/Sources/Navigator/Audiobook/Preferences/AudioPreferences.swift index 6ee201d4ac..bc984d7e55 100644 --- a/Sources/Navigator/Audiobook/Preferences/AudioPreferences.swift +++ b/Sources/Navigator/Audiobook/Preferences/AudioPreferences.swift @@ -32,23 +32,45 @@ public struct AudioPreferences: ConfigurablePreferences, Sendable { self.volume = volume self.speed = speed } +} + +public extension AudioPreferences { + @available(*, unavailable, message: "Store the publication-specific settings in your own settings model, see the migration guide") + func filterSharedPreferences() -> AudioPreferences { + fatalError() + } - public func merging(_ other: AudioPreferences) -> AudioPreferences { - AudioPreferences( - volume: other.volume ?? volume, - speed: other.speed ?? speed - ) + @available(*, unavailable, message: "Store the publication-specific settings in your own settings model, see the migration guide") + func filterPublicationPreferences() -> AudioPreferences { + fatalError() } +} + +/// Decodes the `AudioPreferences` persisted with Readium 3.x, to migrate them +/// to your own settings model. +/// +/// This is a snapshot of the 3.x `AudioPreferences`, with the values as they +/// were saved. The decoding is lenient: an invalid value drops only its +/// preference. The values are not checked against the ranges supported by +/// `AudioPreferences`. +/// +/// It will be removed in a future major version. +public struct LegacyAudioPreferences: Decodable, Hashable, Sendable { + /// Volume of playback, from 0.0 to 1.0. + public let volume: Double? + /// Speed of playback. Normal is 1.0. + public let speed: Double? +} - /// Returns a new `AudioPreferences` with the publication-specific preferences - /// removed. - public func filterSharedPreferences() -> AudioPreferences { - self +public extension LegacyAudioPreferences { + private enum CodingKeys: String, CodingKey { + case volume + case speed } - /// Returns a new `AudioPreferences` keeping only the publication-specific - /// preferences. - public func filterPublicationPreferences() -> AudioPreferences { - AudioPreferences() + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + volume = container.decodeLeniently(Double.self, forKey: .volume) + speed = container.decodeLeniently(Double.self, forKey: .speed) } } diff --git a/Sources/Navigator/EPUB/Preferences/EPUBPreferences+Legacy.swift b/Sources/Navigator/EPUB/Preferences/EPUBPreferences+Legacy.swift index d436afa52c..15027f95dd 100644 --- a/Sources/Navigator/EPUB/Preferences/EPUBPreferences+Legacy.swift +++ b/Sources/Navigator/EPUB/Preferences/EPUBPreferences+Legacy.swift @@ -160,49 +160,189 @@ private enum ReadiumCSSName: String { case backgroundColor = "--USER__backgroundColor" } -// MARK: - Preferences serialized without a version (3.x) +// MARK: - Preferences serialized with Readium 3.x + +/// Decodes the `EPUBPreferences` persisted with Readium 3.x, to migrate them +/// to your own settings model. +/// +/// This is a snapshot of the 3.x `EPUBPreferences`, with the values as they +/// were saved. The decoding is lenient: an invalid value drops only its +/// preference. See the migration guide for the equivalent of the removed +/// preferences, such as `theme` or `publisherStyles`. +/// +/// It will be removed in a future major version. +public struct LegacyEPUBPreferences: Decodable, Hashable, Sendable { + /// Default page background color, as a packed RGB integer. + public let backgroundColor: Int? + /// Number of reflowable columns to display. + public let columnCount: ColumnCount? + /// Method for fitting the content of fixed-layout resources within the + /// viewport. + public let fit: Fit? + /// Default typeface for the text. + public let fontFamily: String? + /// Base text font size. + public let fontSize: Double? + /// Default boldness for the text. + public let fontWeight: Double? + /// Enable hyphenation. + public let hyphens: Bool? + /// Filter applied to images in dark theme. + public let imageFilter: ImageFilter? + /// Language of the publication content, as a BCP 47 tag. + public let language: String? + /// Space between letters. + public let letterSpacing: Double? + /// Enable ligatures in Arabic. + public let ligatures: Bool? + /// Leading line height. + public let lineHeight: Double? + /// Indicates whether the first page should be displayed alone and + /// centered instead of alongside the second page. + public let offsetFirstPage: Bool? + /// Factor applied to horizontal margins. + public let pageMargins: Double? + /// Text indentation for paragraphs. + public let paragraphIndent: Double? + /// Vertical margins for paragraphs. + public let paragraphSpacing: Double? + /// Indicates whether the original publisher styles should be observed. + /// + /// Many settings required this to be off. + public let publisherStyles: Bool? + /// Direction of the reading progression across resources. + public let readingProgression: ReadingProgression? + /// Indicates if the overflow of resources should be handled using + /// scrolling instead of synthetic pagination. + public let scroll: Bool? + /// Indicates if the fixed-layout publication should be rendered with a + /// synthetic spread (dual-page). + public let spread: Spread? + /// Page text alignment. + public let textAlign: TextAlignment? + /// Default page text color, as a packed RGB integer. + public let textColor: Int? + /// Normalize text styles to increase accessibility. + public let textNormalization: Bool? + /// Reader theme. + public let theme: Theme? + /// Scale applied to all element font sizes. + public let typeScale: Double? + /// Indicates whether the text should be laid out vertically. + public let verticalText: Bool? + /// Space between words. + public let wordSpacing: Double? + + public enum ColumnCount: String, Decodable, Hashable, Sendable { + case auto + case one = "1" + case two = "2" + } -extension EPUBPreferences { - /// Keys of the preferences serialized without a version, which changed - /// or were removed. - private enum LegacyCodingKeys: String, CodingKey { + public enum Fit: String, Decodable, Hashable, Sendable { + case auto + case page + case width + } + + public enum ImageFilter: String, Decodable, Hashable, Sendable { + case darken + case invert + } + + public enum ReadingProgression: String, Decodable, Hashable, Sendable { + case ltr + case rtl + } + + public enum Spread: String, Decodable, Hashable, Sendable { + case auto + case never + case always + } + + public enum TextAlignment: String, Decodable, Hashable, Sendable { + case center + case justify + case start + case end + case left + case right + } + + public enum Theme: String, Decodable, Hashable, Sendable { + case light + case dark + case sepia + } +} + +public extension LegacyEPUBPreferences { + private enum CodingKeys: String, CodingKey { + case backgroundColor case columnCount + case fit + case fontFamily + case fontSize + case fontWeight + case hyphens case imageFilter + case language + case letterSpacing + case ligatures + case lineHeight + case offsetFirstPage + case pageMargins + case paragraphIndent + case paragraphSpacing case publisherStyles + case readingProgression + case scroll + case spread + case textAlign + case textColor + case textNormalization case theme + case typeScale + case verticalText + case wordSpacing } - /// Migrates the preferences serialized without a version, before the - /// Readium CSS v2 upgrade. - /// - /// The `typeScale` preference is dropped. - mutating func migrateUnversioned(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: LegacyCodingKeys.self) - - // `columnCount` was an enum of `auto`, `1` and `2`. - if let columnCount = container.decodeLeniently(String.self, forKey: .columnCount) { - self.columnCount = Self.validColumnCount(Int(columnCount)) - } - - // `theme` was an enum of `light`, `dark` and `sepia`, and - // `imageFilter` an enum of `darken` and `invert`. - let theme = container.decodeLeniently(String.self, forKey: .theme) - .flatMap(LegacyTheme.init(rawValue:)) - if let theme = theme { - applyLegacyTheme( - theme, - imageFilter: container.decodeLeniently(String.self, forKey: .imageFilter) - ) - } - - // These preferences were ignored while the publisher styles were - // enabled. An unset `publisherStyles` is ambiguous, as apps could - // change its default value, so they are kept in this case. - if container.decodeLeniently(Bool.self, forKey: .publisherStyles) == true { - clearPublisherStylesOverrides() - } + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + backgroundColor = container.decodeLeniently(Int.self, forKey: .backgroundColor) + columnCount = container.decodeLeniently(ColumnCount.self, forKey: .columnCount) + fit = container.decodeLeniently(Fit.self, forKey: .fit) + fontFamily = container.decodeLeniently(String.self, forKey: .fontFamily) + fontSize = container.decodeLeniently(Double.self, forKey: .fontSize) + fontWeight = container.decodeLeniently(Double.self, forKey: .fontWeight) + hyphens = container.decodeLeniently(Bool.self, forKey: .hyphens) + imageFilter = container.decodeLeniently(ImageFilter.self, forKey: .imageFilter) + language = container.decodeLeniently(String.self, forKey: .language) + letterSpacing = container.decodeLeniently(Double.self, forKey: .letterSpacing) + ligatures = container.decodeLeniently(Bool.self, forKey: .ligatures) + lineHeight = container.decodeLeniently(Double.self, forKey: .lineHeight) + offsetFirstPage = container.decodeLeniently(Bool.self, forKey: .offsetFirstPage) + pageMargins = container.decodeLeniently(Double.self, forKey: .pageMargins) + paragraphIndent = container.decodeLeniently(Double.self, forKey: .paragraphIndent) + paragraphSpacing = container.decodeLeniently(Double.self, forKey: .paragraphSpacing) + publisherStyles = container.decodeLeniently(Bool.self, forKey: .publisherStyles) + readingProgression = container.decodeLeniently(ReadingProgression.self, forKey: .readingProgression) + scroll = container.decodeLeniently(Bool.self, forKey: .scroll) + spread = container.decodeLeniently(Spread.self, forKey: .spread) + textAlign = container.decodeLeniently(TextAlignment.self, forKey: .textAlign) + textColor = container.decodeLeniently(Int.self, forKey: .textColor) + textNormalization = container.decodeLeniently(Bool.self, forKey: .textNormalization) + theme = container.decodeLeniently(Theme.self, forKey: .theme) + typeScale = container.decodeLeniently(Double.self, forKey: .typeScale) + verticalText = container.decodeLeniently(Bool.self, forKey: .verticalText) + wordSpacing = container.decodeLeniently(Double.self, forKey: .wordSpacing) } +} +// MARK: - Legacy settings migration (2.x) + +extension EPUBPreferences { /// Clears the preferences which were ignored while the legacy publisher /// styles were enabled. mutating func clearPublisherStylesOverrides() { @@ -241,10 +381,7 @@ extension EPUBPreferences { /// /// The colors already set are kept, as they took precedence over the /// theme. The light theme has no colors, it was the default rendering. - /// - /// - Parameter imageFilter: Legacy image filter (`darken` or `invert`), - /// which was applied only with the dark theme. - mutating func applyLegacyTheme(_ theme: LegacyTheme, imageFilter: String? = nil) { + mutating func applyLegacyTheme(_ theme: LegacyTheme) { switch theme { case .light: break @@ -254,19 +391,8 @@ extension EPUBPreferences { backgroundColor = backgroundColor ?? nightBackgroundColor linkColor = linkColor ?? nightLinkColor visitedColor = visitedColor ?? nightVisitedColor - - // The dark theme inverted the gaiji, unless the images were - // darkened. - switch imageFilter { - case "darken": - // The `darken` filter was `brightness(80%)`. - darkenImages = 0.2 - case "invert": - invertImages = true - invertGaiji = true - default: - invertGaiji = true - } + // The dark theme inverted the gaiji. + invertGaiji = true case .sepia: // The link colors of the sepia theme were the default ones. @@ -298,6 +424,16 @@ public extension EPUBPreferences { var theme: Theme? { fatalError() } + + @available(*, unavailable, message: "Store the publication-specific settings in your own settings model, see the migration guide") + func filterSharedPreferences() -> EPUBPreferences { + fatalError() + } + + @available(*, unavailable, message: "Store the publication-specific settings in your own settings model, see the migration guide") + func filterPublicationPreferences() -> EPUBPreferences { + fatalError() + } } // MARK: - Removed settings diff --git a/Sources/Navigator/EPUB/Preferences/EPUBPreferences.swift b/Sources/Navigator/EPUB/Preferences/EPUBPreferences.swift index d2473715fd..55c9d5c726 100644 --- a/Sources/Navigator/EPUB/Preferences/EPUBPreferences.swift +++ b/Sources/Navigator/EPUB/Preferences/EPUBPreferences.swift @@ -227,69 +227,6 @@ public struct EPUBPreferences: ConfigurablePreferences, Sendable { self.visitedColor = visitedColor self.wordSpacing = wordSpacing.map { max($0, 0) } } - - public func merging(_ other: EPUBPreferences) -> EPUBPreferences { - EPUBPreferences( - backgroundColor: other.backgroundColor ?? backgroundColor, - blendImages: other.blendImages ?? blendImages, - columnCount: other.columnCount ?? columnCount, - darkenImages: other.darkenImages ?? darkenImages, - fit: other.fit ?? fit, - fontFamily: other.fontFamily ?? fontFamily, - fontSize: other.fontSize ?? fontSize, - fontWeight: other.fontWeight ?? fontWeight, - fontWidth: other.fontWidth ?? fontWidth, - hyphens: other.hyphens ?? hyphens, - invertGaiji: other.invertGaiji ?? invertGaiji, - invertImages: other.invertImages ?? invertImages, - language: other.language ?? language, - letterSpacing: other.letterSpacing ?? letterSpacing, - ligatures: other.ligatures ?? ligatures, - lineHeight: other.lineHeight ?? lineHeight, - linkColor: other.linkColor ?? linkColor, - maximalLineLength: other.maximalLineLength ?? maximalLineLength, - minimalLineLength: other.minimalLineLength ?? minimalLineLength, - noRuby: other.noRuby ?? noRuby, - offsetFirstPage: other.offsetFirstPage ?? offsetFirstPage, - optimalLineLength: other.optimalLineLength ?? optimalLineLength, - pageMargins: other.pageMargins ?? pageMargins, - paragraphIndent: other.paragraphIndent ?? paragraphIndent, - paragraphSpacing: other.paragraphSpacing ?? paragraphSpacing, - readingProgression: other.readingProgression ?? readingProgression, - scroll: other.scroll ?? scroll, - spread: other.spread ?? spread, - textAlign: other.textAlign ?? textAlign, - textColor: other.textColor ?? textColor, - textNormalization: other.textNormalization ?? textNormalization, - verticalText: other.verticalText ?? verticalText, - visitedColor: other.visitedColor ?? visitedColor, - wordSpacing: other.wordSpacing ?? wordSpacing - ) - } - - /// Returns a new `EPUBPreferences` with the publication-specific preferences - /// removed. - public func filterSharedPreferences() -> EPUBPreferences { - var prefs = self - prefs.language = nil - prefs.offsetFirstPage = nil - prefs.readingProgression = nil - prefs.spread = nil - prefs.verticalText = nil - return prefs - } - - /// Returns a new `EPUBPreferences` keeping only the publication-specific - /// preferences. - public func filterPublicationPreferences() -> EPUBPreferences { - EPUBPreferences( - language: language, - offsetFirstPage: offsetFirstPage, - readingProgression: readingProgression, - spread: spread, - verticalText: verticalText - ) - } } /// Limits of the preferences, shared with `EPUBDefaults`, `EPUBSettings` and @@ -304,149 +241,3 @@ extension EPUBPreferences { value.takeIf { $0 >= 1 } } } - -// MARK: - Codable - -public extension EPUBPreferences { - /// Version of the serialization format, written in the `version` key. - /// - /// Preferences serialized before the Readium CSS v2 upgrade (toolkit 3.x) - /// have no version. - internal static let codingVersion = 4 - - // New properties must be added here, in `init(from:)` and in - // `encode(to:)`, and to the round-trip fixture in `EPUBPreferencesTests`. - private enum CodingKeys: String, CodingKey { - case version - case backgroundColor - case blendImages - case columnCount - case darkenImages - case fit - case fontFamily - case fontSize - case fontWeight - case fontWidth - case hyphens - case invertGaiji - case invertImages - case language - case letterSpacing - case ligatures - case lineHeight - case linkColor - case maximalLineLength - case minimalLineLength - case noRuby - case offsetFirstPage - case optimalLineLength - case pageMargins - case paragraphIndent - case paragraphSpacing - case readingProgression - case scroll - case spread - case textAlign - case textColor - case textNormalization - case verticalText - case visitedColor - case wordSpacing - } - - /// Decodes the preferences leniently: an invalid value drops only its - /// preference. - /// - /// Preferences serialized without a version are migrated from the - /// previous format, see `EPUBPreferences+Legacy.swift`. - init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - self.init( - backgroundColor: container.decodeLeniently(Color.self, forKey: .backgroundColor), - blendImages: container.decodeLeniently(Bool.self, forKey: .blendImages), - columnCount: container.decodeLeniently(Int.self, forKey: .columnCount), - darkenImages: container.decodeLeniently(Double.self, forKey: .darkenImages), - fit: container.decodeLeniently(Fit.self, forKey: .fit), - fontFamily: container.decodeLeniently(FontFamily.self, forKey: .fontFamily), - fontSize: container.decodeLeniently(Double.self, forKey: .fontSize), - fontWeight: container.decodeLeniently(Double.self, forKey: .fontWeight), - fontWidth: container.decodeLeniently(Double.self, forKey: .fontWidth), - hyphens: container.decodeLeniently(Bool.self, forKey: .hyphens), - invertGaiji: container.decodeLeniently(Bool.self, forKey: .invertGaiji), - invertImages: container.decodeLeniently(Bool.self, forKey: .invertImages), - language: container.decodeLeniently(Language.self, forKey: .language), - letterSpacing: container.decodeLeniently(Double.self, forKey: .letterSpacing), - ligatures: container.decodeLeniently(Bool.self, forKey: .ligatures), - lineHeight: container.decodeLeniently(Double.self, forKey: .lineHeight), - linkColor: container.decodeLeniently(Color.self, forKey: .linkColor), - maximalLineLength: container.decodeLeniently(Double.self, forKey: .maximalLineLength), - minimalLineLength: container.decodeLeniently(Double.self, forKey: .minimalLineLength), - noRuby: container.decodeLeniently(Bool.self, forKey: .noRuby), - offsetFirstPage: container.decodeLeniently(Bool.self, forKey: .offsetFirstPage), - optimalLineLength: container.decodeLeniently(Double.self, forKey: .optimalLineLength), - pageMargins: container.decodeLeniently(Double.self, forKey: .pageMargins), - paragraphIndent: container.decodeLeniently(Double.self, forKey: .paragraphIndent), - paragraphSpacing: container.decodeLeniently(Double.self, forKey: .paragraphSpacing), - readingProgression: container.decodeLeniently(ReadingProgression.self, forKey: .readingProgression), - scroll: container.decodeLeniently(Bool.self, forKey: .scroll), - spread: container.decodeLeniently(Spread.self, forKey: .spread), - textAlign: container.decodeLeniently(TextAlignment.self, forKey: .textAlign), - textColor: container.decodeLeniently(Color.self, forKey: .textColor), - textNormalization: container.decodeLeniently(Bool.self, forKey: .textNormalization), - verticalText: container.decodeLeniently(Bool.self, forKey: .verticalText), - visitedColor: container.decodeLeniently(Color.self, forKey: .visitedColor), - wordSpacing: container.decodeLeniently(Double.self, forKey: .wordSpacing) - ) - - if container.decodeLeniently(Int.self, forKey: .version) == nil { - try migrateUnversioned(from: decoder) - } - } - - func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(Self.codingVersion, forKey: .version) - try container.encodeIfPresent(backgroundColor, forKey: .backgroundColor) - try container.encodeIfPresent(blendImages, forKey: .blendImages) - try container.encodeIfPresent(columnCount, forKey: .columnCount) - try container.encodeIfPresent(darkenImages, forKey: .darkenImages) - try container.encodeIfPresent(fit, forKey: .fit) - try container.encodeIfPresent(fontFamily, forKey: .fontFamily) - try container.encodeIfPresent(fontSize, forKey: .fontSize) - try container.encodeIfPresent(fontWeight, forKey: .fontWeight) - try container.encodeIfPresent(fontWidth, forKey: .fontWidth) - try container.encodeIfPresent(hyphens, forKey: .hyphens) - try container.encodeIfPresent(invertGaiji, forKey: .invertGaiji) - try container.encodeIfPresent(invertImages, forKey: .invertImages) - try container.encodeIfPresent(language, forKey: .language) - try container.encodeIfPresent(letterSpacing, forKey: .letterSpacing) - try container.encodeIfPresent(ligatures, forKey: .ligatures) - try container.encodeIfPresent(lineHeight, forKey: .lineHeight) - try container.encodeIfPresent(linkColor, forKey: .linkColor) - try container.encodeIfPresent(maximalLineLength, forKey: .maximalLineLength) - try container.encodeIfPresent(minimalLineLength, forKey: .minimalLineLength) - try container.encodeIfPresent(noRuby, forKey: .noRuby) - try container.encodeIfPresent(offsetFirstPage, forKey: .offsetFirstPage) - try container.encodeIfPresent(optimalLineLength, forKey: .optimalLineLength) - try container.encodeIfPresent(pageMargins, forKey: .pageMargins) - try container.encodeIfPresent(paragraphIndent, forKey: .paragraphIndent) - try container.encodeIfPresent(paragraphSpacing, forKey: .paragraphSpacing) - try container.encodeIfPresent(readingProgression, forKey: .readingProgression) - try container.encodeIfPresent(scroll, forKey: .scroll) - try container.encodeIfPresent(spread, forKey: .spread) - try container.encodeIfPresent(textAlign, forKey: .textAlign) - try container.encodeIfPresent(textColor, forKey: .textColor) - try container.encodeIfPresent(textNormalization, forKey: .textNormalization) - try container.encodeIfPresent(verticalText, forKey: .verticalText) - try container.encodeIfPresent(visitedColor, forKey: .visitedColor) - try container.encodeIfPresent(wordSpacing, forKey: .wordSpacing) - } -} - -extension KeyedDecodingContainer { - /// Decodes the value for `key`, or returns `nil` if it is missing or - /// invalid. - func decodeLeniently(_ type: T.Type, forKey key: Key) -> T? { - try? decodeIfPresent(type, forKey: key) - } -} diff --git a/Sources/Navigator/PDF/Preferences/PDFPreferences.swift b/Sources/Navigator/PDF/Preferences/PDFPreferences.swift index 2e98862bfa..98264dfaee 100644 --- a/Sources/Navigator/PDF/Preferences/PDFPreferences.swift +++ b/Sources/Navigator/PDF/Preferences/PDFPreferences.swift @@ -66,36 +66,97 @@ public struct PDFPreferences: ConfigurablePreferences, Sendable { self.spread = spread self.visibleScrollbar = visibleScrollbar } +} + +public extension PDFPreferences { + @available(*, unavailable, message: "Store the publication-specific settings in your own settings model, see the migration guide") + func filterSharedPreferences() -> PDFPreferences { + fatalError() + } - public func merging(_ other: PDFPreferences) -> PDFPreferences { - PDFPreferences( - backgroundColor: other.backgroundColor ?? backgroundColor, - fit: other.fit ?? fit, - offsetFirstPage: other.offsetFirstPage ?? offsetFirstPage, - pageSpacing: other.pageSpacing ?? pageSpacing, - readingProgression: other.readingProgression ?? readingProgression, - scroll: other.scroll ?? scroll, - scrollAxis: other.scrollAxis ?? scrollAxis, - spread: other.spread ?? spread, - visibleScrollbar: other.visibleScrollbar ?? visibleScrollbar - ) + @available(*, unavailable, message: "Store the publication-specific settings in your own settings model, see the migration guide") + func filterPublicationPreferences() -> PDFPreferences { + fatalError() } +} + +/// Decodes the `PDFPreferences` persisted with Readium 3.x, to migrate them +/// to your own settings model. +/// +/// This is a snapshot of the 3.x `PDFPreferences`, with the values as they +/// were saved. The decoding is lenient: an invalid value drops only its +/// preference. +/// +/// It will be removed in a future major version. +public struct LegacyPDFPreferences: Decodable, Hashable, Sendable { + /// Background color behind the document pages, as a packed RGB integer. + public let backgroundColor: Int? + /// Method for fitting the pages within the viewport. + public let fit: Fit? + /// Indicates whether the first page should be displayed alone instead of + /// alongside the second page. + public let offsetFirstPage: Bool? + /// Spacing between pages in points. + public let pageSpacing: Double? + /// Direction of the horizontal progression across pages. + public let readingProgression: ReadingProgression? + /// Indicates if pages should be handled using scrolling instead of + /// pagination. + public let scroll: Bool? + /// Indicates the axis along which pages should be laid out in scroll mode. + public let scrollAxis: Axis? + /// Indicates if the publication should be rendered with a synthetic spread + /// (dual-page). + public let spread: Spread? + /// Indicates whether the scrollbar should be visible while scrolling. + public let visibleScrollbar: Bool? + + public enum Axis: String, Decodable, Hashable, Sendable { + case horizontal + case vertical + } + + public enum Fit: String, Decodable, Hashable, Sendable { + case auto + case page + case width + } + + public enum ReadingProgression: String, Decodable, Hashable, Sendable { + case ltr + case rtl + } + + public enum Spread: String, Decodable, Hashable, Sendable { + case auto + case never + case always + } +} - /// Returns a new `PDFPreferences` with the publication-specific preferences - /// removed. - public func filterSharedPreferences() -> PDFPreferences { - var prefs = self - prefs.offsetFirstPage = nil - prefs.readingProgression = nil - return prefs +public extension LegacyPDFPreferences { + private enum CodingKeys: String, CodingKey { + case backgroundColor + case fit + case offsetFirstPage + case pageSpacing + case readingProgression + case scroll + case scrollAxis + case spread + case visibleScrollbar } - /// Returns a new `PDFPreferences` keeping only the publication-specific - /// preferences. - public func filterPublicationPreferences() -> PDFPreferences { - PDFPreferences( - offsetFirstPage: offsetFirstPage, - readingProgression: readingProgression - ) + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + backgroundColor = container.decodeLeniently(Int.self, forKey: .backgroundColor) + fit = container.decodeLeniently(Fit.self, forKey: .fit) + offsetFirstPage = container.decodeLeniently(Bool.self, forKey: .offsetFirstPage) + pageSpacing = container.decodeLeniently(Double.self, forKey: .pageSpacing) + readingProgression = container.decodeLeniently(ReadingProgression.self, forKey: .readingProgression) + scroll = container.decodeLeniently(Bool.self, forKey: .scroll) + scrollAxis = container.decodeLeniently(Axis.self, forKey: .scrollAxis) + spread = container.decodeLeniently(Spread.self, forKey: .spread) + visibleScrollbar = container.decodeLeniently(Bool.self, forKey: .visibleScrollbar) } } diff --git a/Sources/Navigator/Preferences/Configurable.swift b/Sources/Navigator/Preferences/Configurable.swift index cf5dc6b897..6c18a11f54 100644 --- a/Sources/Navigator/Preferences/Configurable.swift +++ b/Sources/Navigator/Preferences/Configurable.swift @@ -32,14 +32,16 @@ public protocol Configurable { public protocol ConfigurableSettings: Hashable {} /// Marker interface for the `Preferences` properties holder. -public protocol ConfigurablePreferences: Codable, Hashable { +public protocol ConfigurablePreferences: Hashable { /// Empty set of preferences. static var empty: Self { get } +} - /// Creates a new instance of `Self` after merging the values of `other`. - /// - /// In case of conflict, `other` takes precedence. - func merging(_ other: Self) -> Self +public extension ConfigurablePreferences { + @available(*, unavailable, message: "Store your own settings model and derive the preferences from it, see the migration guide") + func merging(_ other: Self) -> Self { + fatalError() + } } public extension Configurable { diff --git a/Sources/Navigator/Preferences/LenientDecoding.swift b/Sources/Navigator/Preferences/LenientDecoding.swift new file mode 100644 index 0000000000..c7346f9114 --- /dev/null +++ b/Sources/Navigator/Preferences/LenientDecoding.swift @@ -0,0 +1,17 @@ +// +// Copyright 2026 Readium Foundation. All rights reserved. +// Use of this source code is governed by the BSD-style license +// available in the top-level LICENSE file of the project. +// + +import Foundation + +/// Helpers to decode the preferences persisted with Readium 3.x, where an +/// invalid value drops only its preference. +extension KeyedDecodingContainer { + /// Decodes the value for `key`, or returns `nil` if it is missing or + /// invalid. + func decodeLeniently(_ type: T.Type, forKey key: Key) -> T? { + try? decodeIfPresent(type, forKey: key) + } +} diff --git a/Sources/Navigator/Preferences/Types.swift b/Sources/Navigator/Preferences/Types.swift index 4b4197d56b..60227e6f9a 100644 --- a/Sources/Navigator/Preferences/Types.swift +++ b/Sources/Navigator/Preferences/Types.swift @@ -9,13 +9,13 @@ import ReadiumShared import UIKit /// Layout axis. -public enum Axis: String, Codable, Hashable, Sendable { +public enum Axis: String, Hashable, Sendable { case horizontal case vertical } /// Synthetic spread policy. -public enum Spread: String, Codable, Hashable, Sendable { +public enum Spread: String, Hashable, Sendable { /// The publication should be displayed in a spread if the screen is large /// enough. case auto @@ -26,7 +26,7 @@ public enum Spread: String, Codable, Hashable, Sendable { } /// Direction of the reading progression across resources. -public enum ReadingProgression: String, Codable, Hashable, Sendable { +public enum ReadingProgression: String, Hashable, Sendable { case ltr case rtl @@ -49,7 +49,7 @@ extension ReadiumShared.ReadingProgression { } /// Method for fitting the content within the viewport. -public enum Fit: String, Codable, Hashable, Sendable { +public enum Fit: String, Hashable, Sendable { /// Use the best fitting strategy depending on the current settings and /// content. case auto @@ -60,27 +60,27 @@ public enum Fit: String, Codable, Hashable, Sendable { } @available(*, unavailable, message: "Use the textColor, backgroundColor, linkColor and visitedColor preferences instead") -public enum Theme: String, Codable, Hashable, Sendable { +public enum Theme: String, Hashable, Sendable { case light case dark case sepia } @available(*, unavailable, message: "Use an Int? instead, where nil means an automatic number of columns") -public enum ColumnCount: String, Codable, Hashable, Sendable { +public enum ColumnCount: String, Hashable, Sendable { case auto case one = "1" case two = "2" } @available(*, unavailable, message: "Use darkenImages or invertImages instead") -public enum ImageFilter: String, Codable, Hashable, Sendable { +public enum ImageFilter: String, Hashable, Sendable { case darken case invert } /// Text alignment in a reflowable document. -public enum TextAlignment: String, Codable, Hashable, Sendable { +public enum TextAlignment: String, Hashable, Sendable { /// Align the text in the center of the page. case center /// Stretch lines of text that end with a soft line break to fill the width @@ -97,7 +97,7 @@ public enum TextAlignment: String, Codable, Hashable, Sendable { } /// Represents a color stored as a packed int. -public struct Color: RawRepresentable, Codable, Hashable, Sendable { +public struct Color: RawRepresentable, Hashable, Sendable { /// Packed int representation. public var rawValue: Int @@ -173,7 +173,7 @@ public struct Color: RawRepresentable, Codable, Hashable, Sendable { /// /// For a list of vetted font families, see /// https://readium.org/readium-css/docs/CSS10-libre_fonts. -public struct FontFamily: RawRepresentable, ExpressibleByStringLiteral, Codable, Hashable, Sendable { +public struct FontFamily: RawRepresentable, ExpressibleByStringLiteral, Hashable, Sendable { // Generic font families // See https://www.w3.org/TR/css-fonts-4/#generic-font-families diff --git a/TestApp/Sources/Data/Book.swift b/TestApp/Sources/Data/Book.swift index 902f3cabe9..79544a3eb9 100644 --- a/TestApp/Sources/Data/Book.swift +++ b/TestApp/Sources/Data/Book.swift @@ -35,9 +35,9 @@ nonisolated struct Book: Codable { var progression: Double /// Date of creation. var created: Date - /// JSON of user preferences specific to this publication (e.g. language, - /// reading progression, spreads). - var preferencesJSON: String? + /// JSON of the user settings specific to this publication (e.g. + /// language, reading progression, spreads). + var settingsJSON: String? var mediaType: MediaType { MediaType(type) ?? .binary @@ -52,8 +52,7 @@ nonisolated struct Book: Codable { url: AnyURL, coverPath: String? = nil, locator: Locator? = nil, - created: Date = Date(), - preferencesJSON: String? = nil + created: Date = Date() ) { self.id = id self.identifier = identifier @@ -65,29 +64,23 @@ nonisolated struct Book: Codable { self.locator = locator progression = locator?.locations.totalProgression ?? 0 self.created = created - self.preferencesJSON = preferencesJSON } var cover: FileURL? { coverPath.map { Paths.covers.appendingPath($0, isDirectory: false) } } - func preferences() throws -> P? { - guard let data = preferencesJSON.flatMap({ $0.data(using: .utf8) }) else { + func settings() throws -> S? { + guard let data = settingsJSON.flatMap({ $0.data(using: .utf8) }) else { return nil } - return try JSONDecoder().decode(P.self, from: data) - } - - mutating func setPreferences(_ preferences: P) throws { - let data = try JSONEncoder().encode(preferences) - preferencesJSON = String(data: data, encoding: .utf8) + return try JSONDecoder().decode(S.self, from: data) } } nonisolated extension Book: TableRecord, FetchableRecord, PersistableRecord { enum Columns: String, ColumnExpression { - case id, identifier, title, type, url, coverPath, locator, progression, created, preferencesJSON + case id, identifier, title, type, url, coverPath, locator, progression, created, settingsJSON } } @@ -142,10 +135,11 @@ final class BookRepository { } } - func savePreferences(_ preferences: Preferences, of id: Book.Id) async throws { - // Encoded eagerly, as `preferences` is not `Sendable` and cannot be + /// Saves the book-specific `settings`. + func saveSettings(_ settings: Settings, of id: Book.Id) async throws { + // Encoded eagerly, as `settings` is not `Sendable` and cannot be // captured in the database closure. - let data = try JSONEncoder().encode(preferences) + let data = try JSONEncoder().encode(settings) let json = String(data: data, encoding: .utf8) try await db.write { db in @@ -153,7 +147,7 @@ final class BookRepository { return } - book.preferencesJSON = json + book.settingsJSON = json try book.save(db) } } diff --git a/TestApp/Sources/Data/Database.swift b/TestApp/Sources/Data/Database.swift index ddae7d9e4d..b00aea67b6 100644 --- a/TestApp/Sources/Data/Database.swift +++ b/TestApp/Sources/Data/Database.swift @@ -32,7 +32,7 @@ final nonisolated class Database { t.column("locator", .text) t.column("progression", .integer).notNull().defaults(to: 0) t.column("created", .datetime).notNull() - t.column("preferencesJSON", .text) + t.column("settingsJSON", .text) } try db.create(table: "bookmark") { t in diff --git a/TestApp/Sources/Data/UserPreferencesStore.swift b/TestApp/Sources/Data/UserPreferencesStore.swift deleted file mode 100644 index 089c7dfd48..0000000000 --- a/TestApp/Sources/Data/UserPreferencesStore.swift +++ /dev/null @@ -1,168 +0,0 @@ -// -// Copyright 2026 Readium Foundation. All rights reserved. -// Use of this source code is governed by the BSD-style license -// available in the top-level LICENSE file of the project. -// - -import Combine -import Foundation -import ReadiumNavigator - -/// A persistent store for a set of user preferences of type `Preferences`. -protocol UserPreferencesStore { - associatedtype Preferences: ConfigurablePreferences - - /// Returns the latest preferences of the given book ID. - func preferences(for bookId: Book.Id) async throws -> Preferences - - /// Sets the latest preferences of the given book ID. - func savePreferences(_ preferences: Preferences, of bookId: Book.Id) async throws - - /// Observes the preferences of the given book ID. - func preferencesPublisher(for bookId: Book.Id) -> AnyPublisher -} - -/// A `UserPreferencesStore` which splits user preferences and store them in -/// separate stores. -/// -/// - publication-specific preferences are stored in the `books` database table -/// - shared (navigator-specific) preferences are stored in the `UserDefaults`. -final class CompositeUserPreferencesStore: UserPreferencesStore { - private let publicationStore: AnyUserPreferencesStore - private let sharedStore: AnyUserPreferencesStore - private let publicationFilter: (Preferences) -> Preferences - private let sharedFilter: (Preferences) -> Preferences - - init( - publicationStore: S1, - sharedStore: S2, - publicationFilter: @escaping (Preferences) -> Preferences, - sharedFilter: @escaping (Preferences) -> Preferences - ) where S1.Preferences == Preferences, S2.Preferences == Preferences { - self.publicationStore = publicationStore.eraseToAnyPreferencesStore() - self.sharedStore = sharedStore.eraseToAnyPreferencesStore() - self.publicationFilter = publicationFilter - self.sharedFilter = sharedFilter - } - - func preferences(for bookId: Book.Id) async throws -> Preferences { - try await sharedStore.preferences(for: bookId).merging(publicationStore.preferences(for: bookId)) - } - - func savePreferences(_ preferences: Preferences, of bookId: Book.Id) async throws { - try await publicationStore.savePreferences(publicationFilter(preferences), of: bookId) - try await sharedStore.savePreferences(sharedFilter(preferences), of: bookId) - } - - func preferencesPublisher(for bookId: Book.Id) -> AnyPublisher { - publicationStore.preferencesPublisher(for: bookId) - .combineLatest(sharedStore.preferencesPublisher(for: bookId)) { p, s in - s.merging(p) - } - .eraseToAnyPublisher() - } -} - -/// A `UserPreferencesStore` that stores the preferences in the `books` -/// database table. -final class DatabaseUserPreferencesStore: UserPreferencesStore { - private let books: BookRepository - - init(books: BookRepository) { - self.books = books - } - - func savePreferences(_ preferences: Preferences, of bookId: Book.Id) async throws { - try await books.savePreferences(preferences, of: bookId) - } - - func preferences(for bookId: Book.Id) async throws -> Preferences { - try await books.get(bookId)?.preferences() - ?? .empty - } - - func preferencesPublisher(for bookId: Book.Id) -> AnyPublisher { - books.observe(bookId) - .tryMap { book in - try (book?.preferences() as Preferences?) ?? .empty - } - .removeDuplicates() - .assertNoFailure() - .eraseToAnyPublisher() - } -} - -/// A `UserPreferencesStore` that stores the preferences in the standard -/// UserDefaults. -final class UserDefaultsUserPreferencesStore: UserPreferencesStore { - private let userDefaults: UserDefaults - private let key: String = .init(reflecting: Preferences.self) - - init(userDefaults: UserDefaults = .standard) { - self.userDefaults = userDefaults - } - - @MainActor - func preferences(for bookId: Book.Id) async throws -> Preferences { - guard let data = userDefaults.userPreferences[key] else { - return .empty - } - return try JSONDecoder().decode(Preferences.self, from: data) - } - - @MainActor - func savePreferences(_ preferences: Preferences, of bookId: Book.Id) async throws { - let data = try JSONEncoder().encode(preferences) - var userPrefs = userDefaults.userPreferences - userPrefs[key] = data - userDefaults.userPreferences = userPrefs - } - - func preferencesPublisher(for bookId: Book.Id) -> AnyPublisher { - userDefaults.publisher(for: \.userPreferences) - .tryCompactMap { [self] dict in - try dict[key].flatMap { try JSONDecoder().decode(Preferences.self, from: $0) } - } - .assertNoFailure() - .eraseToAnyPublisher() - } -} - -private extension UserDefaults { - @objc dynamic var userPreferences: [String: Data] { - get { object(forKey: "userPreferences") as? [String: Data] ?? [:] } - set { set(newValue, forKey: "userPreferences") } - } -} - -extension UserPreferencesStore { - /// Wraps this `UserPreferencesStore` with a type eraser. - public func eraseToAnyPreferencesStore() -> AnyUserPreferencesStore { - AnyUserPreferencesStore(self) - } -} - -/// A type-erasing `UserPreferencesStore` object. -struct AnyUserPreferencesStore: UserPreferencesStore { - private let _preferences: (Book.Id) async throws -> Preferences - private let _savePreferences: (Preferences, Book.Id) async throws -> Void - private let _preferencesPublisher: (Book.Id) -> AnyPublisher - - init(_ preferencesStore: P) where P.Preferences == Preferences { - _preferences = preferencesStore.preferences - _savePreferences = preferencesStore.savePreferences - _preferencesPublisher = preferencesStore.preferencesPublisher - } - - func preferences(for bookId: Book.Id) async throws -> Preferences { - try await _preferences(bookId) - } - - func savePreferences(_ preferences: Preferences, of bookId: Book.Id) async throws { - try await _savePreferences(preferences, bookId) - } - - func preferencesPublisher(for bookId: Book.Id) -> AnyPublisher { - _preferencesPublisher(bookId) - } -} diff --git a/TestApp/Sources/Data/UserSettingsStore.swift b/TestApp/Sources/Data/UserSettingsStore.swift new file mode 100644 index 0000000000..2fa7bcf652 --- /dev/null +++ b/TestApp/Sources/Data/UserSettingsStore.swift @@ -0,0 +1,86 @@ +// +// Copyright 2026 Readium Foundation. All rights reserved. +// Use of this source code is governed by the BSD-style license +// available in the top-level LICENSE file of the project. +// + +import Combine +import Foundation +import ReadiumNavigator + +/// A persistent store for the `UserSettings` of a reader. +/// +/// The settings are split and stored in separate places: +/// - the book-specific settings are stored in the `book` database table, +/// - the shared settings are stored in the `UserDefaults`. +final class UserSettingsStore { + private let books: BookRepository + private let userDefaults: UserDefaults + + init(books: BookRepository, userDefaults: UserDefaults = .standard) { + self.books = books + self.userDefaults = userDefaults + } + + /// Returns the latest settings of the given book ID. + func settings(for bookId: Book.Id) async throws -> Settings { + try await Settings( + book: bookSettings(for: bookId), + shared: sharedSettings() + ) + } + + /// Saves the settings of the given book ID. + func saveSettings(_ settings: Settings, of bookId: Book.Id) async throws { + try await books.saveSettings(settings.book, of: bookId) + try saveSharedSettings(settings.shared) + } + + /// Observes the settings of the given book ID. + func settingsPublisher(for bookId: Book.Id) -> AnyPublisher { + let bookSettings = books.observe(bookId) + .tryMap { book in + try book?.settings() ?? Settings.BookSettings() + } + + let sharedSettings = userDefaults.publisher(for: \.userSettings) + .tryMap { dict in + try Self.decodeSharedSettings(from: dict) ?? Settings.SharedSettings() + } + + return bookSettings.combineLatest(sharedSettings) { book, shared in + Settings(book: book, shared: shared) + } + .removeDuplicates() + .assertNoFailure() + .eraseToAnyPublisher() + } + + private func bookSettings(for bookId: Book.Id) async throws -> Settings.BookSettings { + try await books.get(bookId)?.settings() ?? Settings.BookSettings() + } + + private func sharedSettings() throws -> Settings.SharedSettings { + try Self.decodeSharedSettings(from: userDefaults.userSettings) ?? Settings.SharedSettings() + } + + private func saveSharedSettings(_ settings: Settings.SharedSettings) throws { + var dict = userDefaults.userSettings + dict[Settings.storageKey] = try JSONEncoder().encode(settings) + userDefaults.userSettings = dict + } + + private static func decodeSharedSettings(from dict: [String: Data]) throws -> Settings.SharedSettings? { + try dict[Settings.storageKey].map { + try JSONDecoder().decode(Settings.SharedSettings.self, from: $0) + } + } +} + +private extension UserDefaults { + /// Shared settings of each format, by `UserSettings.storageKey`. + @objc dynamic var userSettings: [String: Data] { + get { object(forKey: "userSettings") as? [String: Data] ?? [:] } + set { set(newValue, forKey: "userSettings") } + } +} diff --git a/TestApp/Sources/Reader/Audiobook/AudiobookModule.swift b/TestApp/Sources/Reader/Audiobook/AudiobookModule.swift index e8ac883f46..ac9326e3b4 100644 --- a/TestApp/Sources/Reader/Audiobook/AudiobookModule.swift +++ b/TestApp/Sources/Reader/Audiobook/AudiobookModule.swift @@ -30,26 +30,17 @@ final class AudiobookModule: ReaderFormatModule { highlights: HighlightRepository, readium: Readium ) async throws -> UIViewController { - let preferencesStore = makePreferencesStore(books: books) + let settingsStore = UserSettingsStore(books: books) let viewController = try await AudiobookViewController( publication: publication, locator: locator, bookId: bookId, books: books, bookmarks: bookmarks, - initialPreferences: preferencesStore.preferences(for: bookId), - preferencesStore: preferencesStore + initialPreferences: settingsStore.settings(for: bookId).preferences(), + settingsStore: settingsStore ) viewController.moduleDelegate = delegate return viewController } - - func makePreferencesStore(books: BookRepository) -> AnyUserPreferencesStore { - CompositeUserPreferencesStore( - publicationStore: DatabaseUserPreferencesStore(books: books), - sharedStore: UserDefaultsUserPreferencesStore(), - publicationFilter: { $0.filterPublicationPreferences() }, - sharedFilter: { $0.filterSharedPreferences() } - ).eraseToAnyPreferencesStore() - } } diff --git a/TestApp/Sources/Reader/Audiobook/AudiobookViewController.swift b/TestApp/Sources/Reader/Audiobook/AudiobookViewController.swift index 76f64e4301..3010413653 100644 --- a/TestApp/Sources/Reader/Audiobook/AudiobookViewController.swift +++ b/TestApp/Sources/Reader/Audiobook/AudiobookViewController.swift @@ -14,7 +14,7 @@ import UIKit class AudiobookViewController: ReaderViewController, AudioNavigatorDelegate { private let model: AudiobookViewModel - private let preferencesStore: AnyUserPreferencesStore + private let settingsStore: UserSettingsStore init( publication: Publication, @@ -23,9 +23,9 @@ class AudiobookViewController: ReaderViewController, AudioNaviga books: BookRepository, bookmarks: BookmarkRepository, initialPreferences: AudioPreferences, - preferencesStore: AnyUserPreferencesStore + settingsStore: UserSettingsStore ) { - self.preferencesStore = preferencesStore + self.settingsStore = settingsStore let navigator = AudioNavigator( publication: publication, @@ -81,9 +81,9 @@ class AudiobookViewController: ReaderViewController, AudioNaviga let userPrefs = await UserPreferences( model: UserPreferencesViewModel( bookId: bookId, - preferences: try! preferencesStore.preferences(for: bookId), + preferences: try! settingsStore.settings(for: bookId).preferences(), configurable: navigator, - store: preferencesStore + store: settingsStore ), onClose: { [weak self = self] in self?.dismiss(animated: true) diff --git a/TestApp/Sources/Reader/Common/Preferences/UserPreferences.swift b/TestApp/Sources/Reader/Common/Preferences/UserPreferences.swift index 06657fa7a0..a02b7fb21e 100644 --- a/TestApp/Sources/Reader/Common/Preferences/UserPreferences.swift +++ b/TestApp/Sources/Reader/Common/Preferences/UserPreferences.swift @@ -18,23 +18,24 @@ final class UserPreferencesViewModel< >: ObservableObject where E.Preferences == P { @Published private(set) var editor: E - private let bookId: Book.Id private let configurable: AnyConfigurable - private let store: AnyUserPreferencesStore

+ private let savePreferences: (P) async throws -> Void private var subscriptions = Set() - init( + init( bookId: Book.Id, preferences: P, configurable: C, - store: ST - ) where C.Settings == S, C.Preferences == P, C.Editor == E, ST.Preferences == P { + store: UserSettingsStore + ) where C.Settings == S, C.Preferences == P, C.Editor == E, US.Preferences == P { editor = configurable.editor(of: preferences) - self.bookId = bookId self.configurable = configurable.eraseToAnyConfigurable() - self.store = store.eraseToAnyPreferencesStore() + savePreferences = { preferences in + try await store.saveSettings(US(preferences), of: bookId) + } - let preferences = store.preferencesPublisher(for: bookId) + let preferences = store.settingsPublisher(for: bookId) + .map { $0.preferences() } .receive(on: DispatchQueue.main) preferences @@ -60,7 +61,7 @@ final class UserPreferencesViewModel< func commit() { Task { - try! await store.savePreferences(editor.preferences, of: bookId) + try! await savePreferences(editor.preferences) } } } @@ -1057,7 +1058,7 @@ extension Preference { /// /// The Readium toolkit has no themes: a theme is only a set of color /// preferences applied together. `nil` keeps the color of the publication. -struct ReaderTheme: Hashable { +nonisolated struct ReaderTheme: Hashable { typealias Color = ReadiumNavigator.Color var name: String @@ -1066,6 +1067,11 @@ struct ReaderTheme: Hashable { var linkColor: Color? var visitedColor: Color? + /// Colors of the theme, to compare themes regardless of their name. + var colors: [Color?] { + [textColor, backgroundColor, linkColor, visitedColor] + } + static let light = ReaderTheme(name: "Light") static let sepia = ReaderTheme( diff --git a/TestApp/Sources/Reader/Common/Preferences/UserSettings.swift b/TestApp/Sources/Reader/Common/Preferences/UserSettings.swift new file mode 100644 index 0000000000..35e9d88512 --- /dev/null +++ b/TestApp/Sources/Reader/Common/Preferences/UserSettings.swift @@ -0,0 +1,290 @@ +// +// Copyright 2026 Readium Foundation. All rights reserved. +// Use of this source code is governed by the BSD-style license +// available in the top-level LICENSE file of the project. +// + +import Foundation +import ReadiumNavigator +import ReadiumShared + +/// User settings of a reader, owned and persisted by the Test App. +/// +/// The navigator preferences are derived from them with `preferences()` +/// before being submitted. The settings are split into a part specific to +/// each book and a part shared by all the books of the same format. +nonisolated protocol UserSettings: Hashable, Sendable { + associatedtype Preferences: ConfigurablePreferences + associatedtype BookSettings: UserSettingsPart + associatedtype SharedSettings: UserSettingsPart + + /// Key of the shared settings in the `UserDefaults`. + static var storageKey: String { get } + + var book: BookSettings { get } + var shared: SharedSettings { get } + + init(book: BookSettings, shared: SharedSettings) + + /// Creates the settings from navigator preferences, for example the ones + /// produced by a preferences editor. + init(_ preferences: Preferences) + + /// Returns the navigator preferences to submit. + func preferences() -> Preferences +} + +/// A part of `UserSettings`, persisted as JSON. +nonisolated protocol UserSettingsPart: Codable, Hashable, Sendable { + init() +} + +// MARK: - EPUB + +nonisolated struct EPUBUserSettings: UserSettings { + static let storageKey = "epub" + + nonisolated struct BookSettings: UserSettingsPart { + var language: String? + var offsetFirstPage: Bool? + var readingProgression: String? + var spread: String? + var verticalText: Bool? + } + + nonisolated struct SharedSettings: UserSettingsPart { + var theme: Theme = .publisher + var blendImages: Bool? + var columnCount: Int? + var darkenImages: Double? + var fit: String? + var fontFamily: String? + var fontSize: Double? + var fontWeight: Double? + var fontWidth: Double? + var hyphens: Bool? + var invertGaiji: Bool? + var invertImages: Bool? + var letterSpacing: Double? + var ligatures: Bool? + var lineHeight: Double? + var maximalLineLength: Double? + var minimalLineLength: Double? + var noRuby: Bool? + var optimalLineLength: Double? + var pageMargins: Double? + var paragraphIndent: Double? + var paragraphSpacing: Double? + var scroll: Bool? + var textAlign: String? + var textNormalization: Bool? + var wordSpacing: Double? + } + + /// Colors of the publication, applied together. + nonisolated enum Theme: Codable, Hashable, Sendable { + /// Keeps the colors of the publication. + case publisher + case sepia + case dark + /// Colors which match no other theme, as packed integers. + case custom(text: Int?, background: Int?, link: Int?, visited: Int?) + + /// Returns the theme matching the given colors. + init(text: Color?, background: Color?, link: Color?, visited: Color?) { + let custom = Theme.custom(text: text?.rawValue, background: background?.rawValue, link: link?.rawValue, visited: visited?.rawValue) + self = [.publisher, .sepia, .dark].first { $0.readerTheme.colors == custom.readerTheme.colors } ?? custom + } + + var readerTheme: ReaderTheme { + switch self { + case .publisher: + return .light + case .sepia: + return .sepia + case .dark: + return .dark + case let .custom(text, background, link, visited): + return ReaderTheme( + name: "Custom", + textColor: text.map(Color.init(rawValue:)), + backgroundColor: background.map(Color.init(rawValue:)), + linkColor: link.map(Color.init(rawValue:)), + visitedColor: visited.map(Color.init(rawValue:)) + ) + } + } + } + + var book: BookSettings + var shared: SharedSettings +} + +nonisolated extension EPUBUserSettings { + init(_ preferences: EPUBPreferences) { + book = BookSettings( + language: preferences.language?.tag, + offsetFirstPage: preferences.offsetFirstPage, + readingProgression: preferences.readingProgression?.rawValue, + spread: preferences.spread?.rawValue, + verticalText: preferences.verticalText + ) + shared = SharedSettings( + theme: Theme( + text: preferences.textColor, + background: preferences.backgroundColor, + link: preferences.linkColor, + visited: preferences.visitedColor + ), + blendImages: preferences.blendImages, + columnCount: preferences.columnCount, + darkenImages: preferences.darkenImages, + fit: preferences.fit?.rawValue, + fontFamily: preferences.fontFamily?.rawValue, + fontSize: preferences.fontSize, + fontWeight: preferences.fontWeight, + fontWidth: preferences.fontWidth, + hyphens: preferences.hyphens, + invertGaiji: preferences.invertGaiji, + invertImages: preferences.invertImages, + letterSpacing: preferences.letterSpacing, + ligatures: preferences.ligatures, + lineHeight: preferences.lineHeight, + maximalLineLength: preferences.maximalLineLength, + minimalLineLength: preferences.minimalLineLength, + noRuby: preferences.noRuby, + optimalLineLength: preferences.optimalLineLength, + pageMargins: preferences.pageMargins, + paragraphIndent: preferences.paragraphIndent, + paragraphSpacing: preferences.paragraphSpacing, + scroll: preferences.scroll, + textAlign: preferences.textAlign?.rawValue, + textNormalization: preferences.textNormalization, + wordSpacing: preferences.wordSpacing + ) + } + + func preferences() -> EPUBPreferences { + let colors = shared.theme.readerTheme + return EPUBPreferences( + backgroundColor: colors.backgroundColor, + blendImages: shared.blendImages, + columnCount: shared.columnCount, + darkenImages: shared.darkenImages, + fit: shared.fit.flatMap(Fit.init(rawValue:)), + fontFamily: shared.fontFamily.map(FontFamily.init(rawValue:)), + fontSize: shared.fontSize, + fontWeight: shared.fontWeight, + fontWidth: shared.fontWidth, + hyphens: shared.hyphens, + invertGaiji: shared.invertGaiji, + invertImages: shared.invertImages, + language: book.language.map { Language($0) }, + letterSpacing: shared.letterSpacing, + ligatures: shared.ligatures, + lineHeight: shared.lineHeight, + linkColor: colors.linkColor, + maximalLineLength: shared.maximalLineLength, + minimalLineLength: shared.minimalLineLength, + noRuby: shared.noRuby, + offsetFirstPage: book.offsetFirstPage, + optimalLineLength: shared.optimalLineLength, + pageMargins: shared.pageMargins, + paragraphIndent: shared.paragraphIndent, + paragraphSpacing: shared.paragraphSpacing, + readingProgression: book.readingProgression.flatMap(ReadingProgression.init(rawValue:)), + scroll: shared.scroll, + spread: book.spread.flatMap(Spread.init(rawValue:)), + textAlign: shared.textAlign.flatMap(TextAlignment.init(rawValue:)), + textColor: colors.textColor, + textNormalization: shared.textNormalization, + verticalText: book.verticalText, + visitedColor: colors.visitedColor, + wordSpacing: shared.wordSpacing + ) + } +} + +// MARK: - PDF + +nonisolated struct PDFUserSettings: UserSettings { + static let storageKey = "pdf" + + nonisolated struct BookSettings: UserSettingsPart { + var offsetFirstPage: Bool? + var readingProgression: String? + } + + nonisolated struct SharedSettings: UserSettingsPart { + var backgroundColor: Int? + var fit: String? + var pageSpacing: Double? + var scroll: Bool? + var scrollAxis: String? + var spread: String? + var visibleScrollbar: Bool? + } + + var book: BookSettings + var shared: SharedSettings +} + +nonisolated extension PDFUserSettings { + init(_ preferences: PDFPreferences) { + book = BookSettings( + offsetFirstPage: preferences.offsetFirstPage, + readingProgression: preferences.readingProgression?.rawValue + ) + shared = SharedSettings( + backgroundColor: preferences.backgroundColor?.rawValue, + fit: preferences.fit?.rawValue, + pageSpacing: preferences.pageSpacing, + scroll: preferences.scroll, + scrollAxis: preferences.scrollAxis?.rawValue, + spread: preferences.spread?.rawValue, + visibleScrollbar: preferences.visibleScrollbar + ) + } + + func preferences() -> PDFPreferences { + PDFPreferences( + backgroundColor: shared.backgroundColor.map(Color.init(rawValue:)), + fit: shared.fit.flatMap(Fit.init(rawValue:)), + offsetFirstPage: book.offsetFirstPage, + pageSpacing: shared.pageSpacing, + readingProgression: book.readingProgression.flatMap(ReadingProgression.init(rawValue:)), + scroll: shared.scroll, + scrollAxis: shared.scrollAxis.flatMap(Axis.init(rawValue:)), + spread: shared.spread.flatMap(Spread.init(rawValue:)), + visibleScrollbar: shared.visibleScrollbar + ) + } +} + +// MARK: - Audio + +nonisolated struct AudioUserSettings: UserSettings { + static let storageKey = "audio" + + /// The audio navigator has no book-specific preferences. + nonisolated struct BookSettings: UserSettingsPart {} + + nonisolated struct SharedSettings: UserSettingsPart { + var volume: Double? + var speed: Double? + } + + var book: BookSettings + var shared: SharedSettings +} + +nonisolated extension AudioUserSettings { + init(_ preferences: AudioPreferences) { + book = BookSettings() + shared = SharedSettings(volume: preferences.volume, speed: preferences.speed) + } + + func preferences() -> AudioPreferences { + AudioPreferences(volume: shared.volume, speed: shared.speed) + } +} diff --git a/TestApp/Sources/Reader/EPUB/EPUBModule.swift b/TestApp/Sources/Reader/EPUB/EPUBModule.swift index 9fe245c2d8..f69e895ba2 100644 --- a/TestApp/Sources/Reader/EPUB/EPUBModule.swift +++ b/TestApp/Sources/Reader/EPUB/EPUBModule.swift @@ -30,7 +30,7 @@ final class EPUBModule: ReaderFormatModule { highlights: HighlightRepository, readium: Readium ) async throws -> UIViewController { - let preferencesStore = makePreferencesStore(books: books) + let settingsStore = UserSettingsStore(books: books) let epubViewController = try await EPUBViewController( publication: publication, locator: locator, @@ -38,19 +38,10 @@ final class EPUBModule: ReaderFormatModule { books: books, bookmarks: bookmarks, highlights: highlights, - initialPreferences: preferencesStore.preferences(for: bookId), - preferencesStore: preferencesStore + initialPreferences: settingsStore.settings(for: bookId).preferences(), + settingsStore: settingsStore ) epubViewController.moduleDelegate = delegate return epubViewController } - - func makePreferencesStore(books: BookRepository) -> AnyUserPreferencesStore { - CompositeUserPreferencesStore( - publicationStore: DatabaseUserPreferencesStore(books: books), - sharedStore: UserDefaultsUserPreferencesStore(), - publicationFilter: { $0.filterPublicationPreferences() }, - sharedFilter: { $0.filterSharedPreferences() } - ).eraseToAnyPreferencesStore() - } } diff --git a/TestApp/Sources/Reader/EPUB/EPUBViewController.swift b/TestApp/Sources/Reader/EPUB/EPUBViewController.swift index 340dac2a02..658909adfb 100644 --- a/TestApp/Sources/Reader/EPUB/EPUBViewController.swift +++ b/TestApp/Sources/Reader/EPUB/EPUBViewController.swift @@ -17,7 +17,7 @@ public extension FontFamily { } class EPUBViewController: VisualReaderViewController { - private let preferencesStore: AnyUserPreferencesStore + private let settingsStore: UserSettingsStore init( publication: Publication, @@ -27,7 +27,7 @@ class EPUBViewController: VisualReaderViewController + settingsStore: UserSettingsStore ) throws { var templates = HTMLDecorationTemplate.defaultTemplates() templates[.pageList] = .pageList @@ -63,7 +63,7 @@ class EPUBViewController: VisualReaderViewController UIViewController { - let preferencesStore = makePreferencesStore(books: books) + let settingsStore = UserSettingsStore(books: books) let viewController = try await PDFViewController( publication: publication, locator: locator, @@ -38,19 +38,10 @@ final class PDFModule: ReaderFormatModule { books: books, bookmarks: bookmarks, highlights: highlights, - initialPreferences: preferencesStore.preferences(for: bookId), - preferencesStore: preferencesStore + initialPreferences: settingsStore.settings(for: bookId).preferences(), + settingsStore: settingsStore ) viewController.moduleDelegate = delegate return viewController } - - func makePreferencesStore(books: BookRepository) -> AnyUserPreferencesStore { - CompositeUserPreferencesStore( - publicationStore: DatabaseUserPreferencesStore(books: books), - sharedStore: UserDefaultsUserPreferencesStore(), - publicationFilter: { $0.filterPublicationPreferences() }, - sharedFilter: { $0.filterSharedPreferences() } - ).eraseToAnyPreferencesStore() - } } diff --git a/TestApp/Sources/Reader/PDF/PDFViewController.swift b/TestApp/Sources/Reader/PDF/PDFViewController.swift index 6de8632014..20be0be053 100644 --- a/TestApp/Sources/Reader/PDF/PDFViewController.swift +++ b/TestApp/Sources/Reader/PDF/PDFViewController.swift @@ -11,7 +11,7 @@ import SwiftUI import UIKit final class PDFViewController: VisualReaderViewController { - private let preferencesStore: AnyUserPreferencesStore + private let settingsStore: UserSettingsStore init( publication: Publication, @@ -21,9 +21,9 @@ final class PDFViewController: VisualReaderViewController + settingsStore: UserSettingsStore ) throws { - self.preferencesStore = preferencesStore + self.settingsStore = settingsStore let navigator = try PDFNavigatorViewController( publication: publication, @@ -43,9 +43,9 @@ final class PDFViewController: VisualReaderViewController String { - let publisherStyles = publisherStyles.map { #""publisherStyles": \#($0),"# } ?? "" - return #""" - { - \#(publisherStyles) - "columnCount": "2", - "fontSize": 1.2, - "hyphens": true, - "letterSpacing": 0.1, - "ligatures": false, - "lineHeight": 2.0, - "paragraphIndent": 1.0, - "paragraphSpacing": 0.5, - "textAlign": "justify", - "theme": "dark", - "typeScale": 1.2, - "wordSpacing": 0.2 - } - """# - } - - private func decode(_ json: String) throws -> EPUBPreferences { - try JSONDecoder().decode(EPUBPreferences.self, from: Data(json.utf8)) - } - } - /// These tests write to `UserDefaults.standard`, so they must not run /// concurrently. @Suite("Legacy preferences", .serialized) struct Legacy { @@ -1456,88 +1225,7 @@ enum EPUBPreferencesTests { } } -/// Every preference set to a distinct non-default value. -private let allPreferences = EPUBPreferences( - backgroundColor: Color(hex: "#FF0000"), - blendImages: true, - columnCount: 2, - darkenImages: 0.3, - fit: .width, - fontFamily: "Literata", - fontSize: 1.4, - fontWeight: 1.75, - fontWidth: 1.7, - hyphens: true, - invertGaiji: true, - invertImages: false, - language: Language("fr"), - letterSpacing: 0.1, - ligatures: false, - lineHeight: 1.6, - linkColor: Color(hex: "#0000FF"), - maximalLineLength: 1.3, - minimalLineLength: 0.8, - noRuby: true, - offsetFirstPage: true, - optimalLineLength: 1.2, - pageMargins: 1.5, - paragraphIndent: 1.1, - paragraphSpacing: 0.5, - readingProgression: .rtl, - scroll: true, - spread: .always, - textAlign: .justify, - textColor: Color(hex: "#00FF00"), - textNormalization: true, - verticalText: true, - visitedColor: Color(hex: "#FF00FF"), - wordSpacing: 0.2 -) - -/// `allPreferences` serialized, which pins the name of every coding key. The -/// colors are serialized as their raw value. -private let allPreferencesJSON = """ -{ - "version": 4, - "backgroundColor": 16711680, - "blendImages": true, - "columnCount": 2, - "darkenImages": 0.3, - "fit": "width", - "fontFamily": "Literata", - "fontSize": 1.4, - "fontWeight": 1.75, - "fontWidth": 1.7, - "hyphens": true, - "invertGaiji": true, - "invertImages": false, - "language": "fr", - "letterSpacing": 0.1, - "ligatures": false, - "lineHeight": 1.6, - "linkColor": 255, - "maximalLineLength": 1.3, - "minimalLineLength": 0.8, - "noRuby": true, - "offsetFirstPage": true, - "optimalLineLength": 1.2, - "pageMargins": 1.5, - "paragraphIndent": 1.1, - "paragraphSpacing": 0.5, - "readingProgression": "rtl", - "scroll": true, - "spread": "always", - "textAlign": "justify", - "textColor": 65280, - "textNormalization": true, - "verticalText": true, - "visitedColor": 16711935, - "wordSpacing": 0.2 -} -""" - -/// Every preference set to a value different from the ones of -/// `allPreferences` and `allDefaults`. +/// Every preference set to a value different from the ones of `allDefaults`. private let otherPreferences = EPUBPreferences( backgroundColor: Color(hex: "#00FFFF"), blendImages: false, @@ -1786,3 +1474,45 @@ private func cssProperties( ("wordSpacing", editor.wordSpacing.isEffective), ] } + +private extension EPUBPreferences { + /// Returns a copy of the preferences, created with the initializer. + func reinitialized() -> EPUBPreferences { + EPUBPreferences( + backgroundColor: backgroundColor, + blendImages: blendImages, + columnCount: columnCount, + darkenImages: darkenImages, + fit: fit, + fontFamily: fontFamily, + fontSize: fontSize, + fontWeight: fontWeight, + fontWidth: fontWidth, + hyphens: hyphens, + invertGaiji: invertGaiji, + invertImages: invertImages, + language: language, + letterSpacing: letterSpacing, + ligatures: ligatures, + lineHeight: lineHeight, + linkColor: linkColor, + maximalLineLength: maximalLineLength, + minimalLineLength: minimalLineLength, + noRuby: noRuby, + offsetFirstPage: offsetFirstPage, + optimalLineLength: optimalLineLength, + pageMargins: pageMargins, + paragraphIndent: paragraphIndent, + paragraphSpacing: paragraphSpacing, + readingProgression: readingProgression, + scroll: scroll, + spread: spread, + textAlign: textAlign, + textColor: textColor, + textNormalization: textNormalization, + verticalText: verticalText, + visitedColor: visitedColor, + wordSpacing: wordSpacing + ) + } +} diff --git a/Tests/NavigatorTests/Preferences/LegacyPreferencesTests.swift b/Tests/NavigatorTests/Preferences/LegacyPreferencesTests.swift new file mode 100644 index 0000000000..f3f718ea25 --- /dev/null +++ b/Tests/NavigatorTests/Preferences/LegacyPreferencesTests.swift @@ -0,0 +1,152 @@ +// +// Copyright 2026 Readium Foundation. All rights reserved. +// Use of this source code is governed by the BSD-style license +// available in the top-level LICENSE file of the project. +// + +import Foundation +@testable import ReadiumNavigator +import Testing + +enum LegacyPreferencesTests { + @Suite("LegacyEPUBPreferences") struct EPUB { + @Test("decodes every 3.x preference from its own key") + func decodesCodingKeys() throws { + let prefs = try decode(LegacyEPUBPreferences.self, """ + { + "backgroundColor": 16711680, + "columnCount": "2", + "fit": "width", + "fontFamily": "Literata", + "fontSize": 1.4, + "fontWeight": 1.75, + "hyphens": true, + "imageFilter": "invert", + "language": "fr", + "letterSpacing": 0.1, + "ligatures": false, + "lineHeight": 1.6, + "offsetFirstPage": true, + "pageMargins": 1.5, + "paragraphIndent": 1.1, + "paragraphSpacing": 0.5, + "publisherStyles": false, + "readingProgression": "rtl", + "scroll": true, + "spread": "always", + "textAlign": "justify", + "textColor": 65280, + "textNormalization": true, + "theme": "sepia", + "typeScale": 1.2, + "verticalText": true, + "wordSpacing": 0.2 + } + """) + #expect(prefs == LegacyEPUBPreferences( + backgroundColor: 0xFF0000, + columnCount: .two, + fit: .width, + fontFamily: "Literata", + fontSize: 1.4, + fontWeight: 1.75, + hyphens: true, + imageFilter: .invert, + language: "fr", + letterSpacing: 0.1, + ligatures: false, + lineHeight: 1.6, + offsetFirstPage: true, + pageMargins: 1.5, + paragraphIndent: 1.1, + paragraphSpacing: 0.5, + publisherStyles: false, + readingProgression: .rtl, + scroll: true, + spread: .always, + textAlign: .justify, + textColor: 0x00FF00, + textNormalization: true, + theme: .sepia, + typeScale: 1.2, + verticalText: true, + wordSpacing: 0.2 + )) + } + + @Test("an invalid value drops only its preference") + func invalidValue() throws { + let prefs = try decode(LegacyEPUBPreferences.self, #"{"fontSize": "big", "textColor": "red", "theme": "night", "columnCount": 2, "lineHeight": 1.5}"#) + #expect(try prefs == decode(LegacyEPUBPreferences.self, #"{"lineHeight": 1.5}"#)) + } + } + + @Suite("LegacyPDFPreferences") struct PDF { + @Test("decodes every 3.x preference from its own key") + func decodesCodingKeys() throws { + let prefs = try decode(LegacyPDFPreferences.self, """ + { + "backgroundColor": 16711680, + "fit": "width", + "offsetFirstPage": true, + "pageSpacing": 12.5, + "readingProgression": "rtl", + "scroll": true, + "scrollAxis": "horizontal", + "spread": "always", + "visibleScrollbar": false + } + """) + #expect(prefs == LegacyPDFPreferences( + backgroundColor: 0xFF0000, + fit: .width, + offsetFirstPage: true, + pageSpacing: 12.5, + readingProgression: .rtl, + scroll: true, + scrollAxis: .horizontal, + spread: .always, + visibleScrollbar: false + )) + } + + @Test("an invalid value drops only its preference") + func invalidValue() throws { + let prefs = try decode(LegacyPDFPreferences.self, #"{"fit": "unknown", "scrollAxis": 1, "backgroundColor": "red", "scroll": true}"#) + #expect(try prefs == decode(LegacyPDFPreferences.self, #"{"scroll": true}"#)) + } + } + + @Suite("LegacyAudioPreferences") struct Audio { + @Test("decodes every 3.x preference from its own key") + func decodesCodingKeys() throws { + let prefs = try decode(LegacyAudioPreferences.self, #"{"volume": 0.5, "speed": 1.5}"#) + #expect(prefs == LegacyAudioPreferences(volume: 0.5, speed: 1.5)) + } + + @Test("an invalid value drops only its preference") + func invalidValue() throws { + let prefs = try decode(LegacyAudioPreferences.self, #"{"volume": "loud", "speed": 2}"#) + #expect(prefs == LegacyAudioPreferences(volume: nil, speed: 2)) + } + + @Test("keeps the values out of the ranges supported by AudioPreferences") + func outOfRange() throws { + let prefs = try decode(LegacyAudioPreferences.self, #"{"volume": 1.5, "speed": -1}"#) + #expect(prefs == LegacyAudioPreferences(volume: 1.5, speed: -1)) + } + } + + @Suite("Legacy preferences") struct All { + @Test("a payload which is not an object fails to decode", arguments: [#"[]"#, #""dark""#, "1"]) + func notAnObject(json: String) { + #expect(throws: DecodingError.self) { try decode(LegacyEPUBPreferences.self, json) } + #expect(throws: DecodingError.self) { try decode(LegacyPDFPreferences.self, json) } + #expect(throws: DecodingError.self) { try decode(LegacyAudioPreferences.self, json) } + } + } +} + +private func decode(_ type: L.Type, _ json: String) throws -> L { + try JSONDecoder().decode(L.self, from: Data(json.utf8)) +} diff --git a/docs/Guides/Navigator/Preferences.md b/docs/Guides/Navigator/Preferences.md index fcb82c5a7f..c676b1911a 100644 --- a/docs/Guides/Navigator/Preferences.md +++ b/docs/Guides/Navigator/Preferences.md @@ -382,42 +382,53 @@ pickerRow( ## Save and restore the user preferences -Having a user settings screen is not useful if you cannot save and restore the selected preferences for future sessions. All `Preferences` types implement the `Codable` protocol and can be serialized to and from JSON. +The `Preferences` types are not `Codable`: they are low-level navigator inputs rarely map 1-1 to the settings of your user interface. Instead, your app owns a settings model, persisted the way you want, from which it derives the `Preferences` before submitting them to the navigator. ```swift -let jsonData = try JSONEncoder().encode(preferences) -``` +struct ReaderSettings: Codable { + enum Theme: String, Codable { + case light, sepia, dark + } -When you are ready to restore the user preferences, construct a new `Preferences` object from the JSON data. + var theme: Theme = .light + var fontSize: Double? + var scroll: Bool? -```swift -let preferences = try JSONDecoder().decode(EPUBPreferences.self, from: jsonData) -``` + func preferences() -> EPUBPreferences { + EPUBPreferences( + backgroundColor: theme == .dark ? Color(hex: "#000000") : nil, + fontSize: fontSize, + scroll: scroll, + textColor: theme == .dark ? Color(hex: "#FEFEFE") : nil + ) + } +} -In the Test App, `UserPreferencesViewModel` delegates the preferences persistence to a `UserPreferencesStore`. The preferences are observed from the store to automatically submit updated preferences to the navigator and refresh the user interface. +let jsonData = try JSONEncoder().encode(settings) -### Splitting and merging preferences +// Later, when opening a publication: +let settings = try JSONDecoder().decode(ReaderSettings.self, from: jsonData) +navigator.submitPreferences(settings.preferences()) +``` -The way you store user preferences can affect the available features. You could have, for example: +Your model decides what is persisted: a theme or a dual-page toggle can drive several preferences, and you are free to rename, add or drop settings without depending on the toolkit's serialization format. -* A unique set of preferences for each publication. -* Preferences shared between publications with the same profile or media type (EPUB, PDF, etc.). -* Global preferences shared with all publications (e.g. colors). -* Several user setting profiles/themes that the user can switch between and modify independently. -* Some settings that are not stored as JSON and will need to be reconstructed (e.g. the publication language). +### Preferences specific to a publication -To assist you, the toolkit provides suggested filters for each `Preferences` type, to extract the preferences intrinsic to a publication. +The way you store user settings can affect the available features. You could have, for example: -```swift -let publicationPrefs = preferences.filterPublicationPreferences() -let sharedPrefs = preferences.filterSharedPreferences() +* A unique set of settings for each publication. +* Settings shared between publications with the same profile or media type (EPUB, PDF, etc.). +* Global settings shared with all publications (e.g. colors). +* Several user setting profiles/themes that the user can switch between and modify independently. -// You can reconstruct the original preferences by combining the filtered ones. -let combinedPrefs = publicationPrefs.merging(sharedPrefs) -``` +Some preferences are closely tied to a specific publication and should never be shared between multiple publications. It is recommended that you store them separately per book: -> [!TIP] -> Some preferences are closely tied to a specific publication and should never be shared between multiple publications, such as the language. It is recommended that you store these preferences separately per book, which is what the suggested filters will do if you use them. +| Navigator | Preferences specific to a publication | +|-----------|-------------------------------------------------------------------------------| +| EPUB | `language`, `offsetFirstPage`, `readingProgression`, `spread`, `verticalText` | +| PDF | `offsetFirstPage`, `readingProgression` | +| Audio | None | ## Appendix: Preference constraints diff --git a/docs/Migration Guide.md b/docs/Migration Guide.md index e815100ae5..7e724d205a 100644 --- a/docs/Migration Guide.md +++ b/docs/Migration Guide.md @@ -22,6 +22,53 @@ All migration steps necessary in reading apps to upgrade to major versions of th +synthesizer.config.voices[voice.language.primaryLanguage] = voice.id ``` +### Preferences are no longer `Codable` + +`EPUBPreferences`, `PDFPreferences`, `AudioPreferences` and their value types (`Color`, `FontFamily`, `Fit`, `Spread`, etc.) are no longer `Codable`. Persisting the navigator preferences made them a storage format, which broke whenever a preference changed in Readium, and they rarely map 1-1 to the settings shown to your users (a theme, a dual-page toggle). + +Your app now owns its settings model, which it persists the way it wants, and derives the preferences from it before submitting them to the navigator. + +```swift +struct ReaderSettings: Codable { + var fontSize: Double? + var scroll: Bool? + var language: String? + + func preferences() -> EPUBPreferences { + EPUBPreferences( + fontSize: fontSize, + language: language.map { Language($0) }, + scroll: scroll + ) + } +} +``` + +`ConfigurablePreferences.merging(_:)` and the `filterPublicationPreferences()` / `filterSharedPreferences()` methods of the `Preferences` types are removed. Store the preferences specific to a publication in your own model, [see the user guide](Guides/Navigator/Preferences.md#preferences-specific-to-a-publication) for the list. + +#### Migrating the saved preferences + +If you were directly persisting the preferences from Readium 3.x, you will need to migrate them to your own alternative model. + +To read the preferences persisted with Readium 3.x, decode them once with `LegacyEPUBPreferences`, `LegacyPDFPreferences` or `LegacyAudioPreferences`. Then map them to your model, save it and delete the old data. + +These types are snapshots of the 3.x `Preferences`: they hold the values as they were saved, including the removed preferences such as `theme` or `publisherStyles`, with their own nested types. See [Saved preferences](#saved-preferences) for the equivalent of the removed EPUB preferences. + +```swift +if let data = UserDefaults.standard.data(forKey: "epubPreferences") { + let legacy = try JSONDecoder().decode(LegacyEPUBPreferences.self, from: data) + let settings = ReaderSettings( + fontSize: legacy.fontSize, + scroll: legacy.scroll, + language: legacy.language + ) + try save(settings) + UserDefaults.standard.removeObject(forKey: "epubPreferences") +} +``` + +The `Legacy*Preferences` types will be removed in a future major version. + ### Upgrade to Readium CSS v2 The EPUB navigator now uses Readium CSS v2. Several EPUB preferences are replaced or removed. @@ -172,15 +219,16 @@ See [the EPUB fonts guide](Guides/Navigator/EPUB%20Fonts.md) for more details. #### Saved preferences -`EPUBPreferences` saved as JSON with a previous version of the toolkit are migrated when decoded, so you don't need to migrate them yourself. +When you map the `LegacyEPUBPreferences` saved with Readium 3.x to your model ([see above](#migrating-the-saved-preferences)), these are the equivalents of the removed preferences, to keep the rendering they had: + +* `columnCount`: `.auto` becomes `nil`, `.one` and `.two` become `1` and `2`. +* `imageFilter`: with the dark theme, `.darken` becomes `darkenImages = 0.2` and `.invert` becomes `invertImages = true`. With another theme, drop the filter, as it was not applied. +* `theme`: `.dark` and `.sepia` become the colors listed [above](#themes), and `.light` leaves the colors unset. The `textColor` and `backgroundColor` saved along with the theme took precedence over its colors. `.dark` also inverted the gaiji (`invertGaiji = true`), unless `imageFilter` was `.darken`. +* `publisherStyles`: when `true`, drop the preferences it disabled (`hyphens`, `letterSpacing`, `ligatures`, `lineHeight`, `paragraphIndent`, `paragraphSpacing`, `textAlign` and `wordSpacing`), as they now apply as soon as they are set. When `false` or missing, keep them. If your app kept the default `EPUBDefaults.publisherStyles` (`true`), these preferences saved without an explicit `publisherStyles` were ignored and will now be applied. +* `typeScale` has no equivalent. -* `columnCount`: `"auto"` becomes `nil`, `"1"` and `"2"` become `1` and `2`. -* `imageFilter`: with the dark theme, `"darken"` becomes `darkenImages = 0.2` and `"invert"` becomes `invertImages = true`. With another theme, the filter is dropped, as it was not applied. -* `theme`: `"dark"` and `"sepia"` become the colors listed [above](#themes), and `"light"` is dropped. The colors which were saved along with the theme are kept, the theme only fills the missing ones. `"dark"` also sets `invertGaiji = true`, unless `imageFilter` is `"darken"`. -* `publisherStyles`: when `true`, the preferences it disabled (`hyphens`, `letterSpacing`, `ligatures`, `lineHeight`, `paragraphIndent`, `paragraphSpacing`, `textAlign` and `wordSpacing`) are dropped, as they now apply as soon as they are set. When `false` or missing, they are kept. If your app kept the default `EPUBDefaults.publisherStyles` (`true`), these preferences saved without an explicit `publisherStyles` were ignored and will now be applied. -* `typeScale` is dropped. +The colors are packed RGB integers, which you can convert with `Color(rawValue:)`. The decoding is lenient: an invalid value drops only its preference, instead of failing to decode all of them. -The decoding is also more lenient: an invalid value drops only its preference, instead of failing to decode all of them. ## 4.0.0-alpha.3 From bbaeed6b5f005df4c6f40da77974d91d191eecc9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Menu?= Date: Wed, 25 Nov 2026 21:22:07 +0100 Subject: [PATCH 2/2] Fixes --- docs/Guides/Navigator/Preferences.md | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/docs/Guides/Navigator/Preferences.md b/docs/Guides/Navigator/Preferences.md index c676b1911a..c2df5ac0eb 100644 --- a/docs/Guides/Navigator/Preferences.md +++ b/docs/Guides/Navigator/Preferences.md @@ -382,7 +382,7 @@ pickerRow( ## Save and restore the user preferences -The `Preferences` types are not `Codable`: they are low-level navigator inputs rarely map 1-1 to the settings of your user interface. Instead, your app owns a settings model, persisted the way you want, from which it derives the `Preferences` before submitting them to the navigator. +The `Preferences` types are not `Codable`: they are low-level navigator inputs which rarely map 1-1 to the settings of your user interface. Instead, your app owns a settings model, persisted the way you want, from which it derives the `Preferences` before submitting them to the navigator. ```swift struct ReaderSettings: Codable { @@ -395,20 +395,29 @@ struct ReaderSettings: Codable { var scroll: Bool? func preferences() -> EPUBPreferences { - EPUBPreferences( - backgroundColor: theme == .dark ? Color(hex: "#000000") : nil, + let (textColor, backgroundColor): (Color?, Color?) = switch theme { + case .light: (nil, nil) + case .sepia: (Color(hex: "#121212"), Color(hex: "#FAF4E8")) + case .dark: (Color(hex: "#FEFEFE"), Color(hex: "#000000")) + } + + return EPUBPreferences( + backgroundColor: backgroundColor, fontSize: fontSize, scroll: scroll, - textColor: theme == .dark ? Color(hex: "#FEFEFE") : nil + textColor: textColor ) } } +// Save the settings chosen by the user. +var settings = ReaderSettings() +settings.theme = .sepia let jsonData = try JSONEncoder().encode(settings) // Later, when opening a publication: -let settings = try JSONDecoder().decode(ReaderSettings.self, from: jsonData) -navigator.submitPreferences(settings.preferences()) +let restoredSettings = try JSONDecoder().decode(ReaderSettings.self, from: jsonData) +navigator.submitPreferences(restoredSettings.preferences()) ``` Your model decides what is persisted: a theme or a dual-page toggle can drive several preferences, and you are free to rename, add or drop settings without depending on the toolkit's serialization format.