feat: EPUB阅读器搜索、注释、CFI模块及大书远距跳转优化

- 实现EPUB阅读器搜索功能及选中注释功能
- 优化CFI模块,修复代码审查发现的11个问题
- 实现大书远距目录跳转与后台补全优化方案
- 优化设置面板与章节运行时联动
- 重构及大量改进优化
This commit is contained in:
shenlei
2026-06-22 20:26:34 +08:00
parent f50495ad91
commit c65c190b71
178 changed files with 11380 additions and 6728 deletions
@@ -1,16 +1,18 @@
import Foundation
/// Builds diagnostics and human-readable summaries for a text book build.
struct RDEPUBBuildDiagnosticsReporter {
func phase7SemanticSummary(
title: String?,
diagnostics: [RDEPUBTextChapterPaginationDiagnostic]
) -> String? {
guard !diagnostics.isEmpty else { return nil }
let blockKinds = uniqueValues(from: diagnostics.flatMap(\.blockKinds))
let semanticHints = uniqueValues(from: diagnostics.flatMap(\.semanticHints))
let attachmentPlacements = uniqueValues(from: diagnostics.flatMap(\.attachmentPlacements))
let note = diagnostics
.flatMap(\.sampleNotes)
.first(where: { $0.contains("semantic") || $0.contains("attachment") || $0.contains("block kinds") })
@@ -22,6 +24,7 @@ struct RDEPUBBuildDiagnosticsReporter {
semanticHints.isEmpty ? nil : "hints [\(semanticHints.map(\.rawValue).joined(separator: ","))]",
attachmentPlacements.isEmpty ? nil : "placements [\(attachmentPlacements.map(\.rawValue).joined(separator: ","))]"
].compactMap { $0 }
if let note {
parts.append(note)
}
@@ -38,11 +41,14 @@ struct RDEPUBBuildDiagnosticsReporter {
title: title,
pageCount: pages.count,
breakReasons: pages.map(\.metadata.breakReason),
attachmentPageCount: pages.filter { !$0.metadata.attachmentKinds.isEmpty }.count,
blockAdjustedPageCount: pages.filter { $0.metadata.breakReason == .blockBoundary || $0.metadata.breakReason == .attachmentBoundary }.count,
blockKinds: uniqueValues(from: pages.flatMap(\.metadata.blockKinds)),
semanticHints: uniqueValues(from: pages.flatMap(\.metadata.semanticHints)),
attachmentPlacements: uniqueValues(from: pages.flatMap(\.metadata.attachmentPlacements)),
sampleNotes: Array(pages.flatMap(\.metadata.diagnostics).prefix(4))
)
}
@@ -1,12 +1,13 @@
import Foundation
/// Normalizes suspicious trailing or whitespace-only page frames after pagination.
struct RDEPUBChapterTailNormalizer {
func normalize(
_ frames: [RDEPUBTextLayoutFrame],
content: NSAttributedString,
href: String
) -> [RDEPUBTextLayoutFrame] {
guard frames.count > 1 else { return frames }
var normalized = frames
@@ -16,10 +17,12 @@ struct RDEPUBChapterTailNormalizer {
for frame in normalized {
if shouldDropWhitespaceOnlyFrame(frame, in: content) {
let note = "normalized: dropped whitespace-only intermediate page \(NSStringFromRange(frame.contentRange))"
if var previous = compacted.popLast() {
previous.diagnostics.append(note)
compacted.append(previous)
} else {
#if DEBUG
print("[EPUB][Pagination] href=\(href) dropped leading/intermediate whitespace frame \(NSStringFromRange(frame.contentRange))")
#endif
@@ -73,6 +76,7 @@ struct RDEPUBChapterTailNormalizer {
previousFrame: RDEPUBTextLayoutFrame,
in content: NSAttributedString
) -> Bool {
guard trailingFrame.contentRange.length > 0,
NSMaxRange(previousFrame.contentRange) == trailingFrame.contentRange.location else {
return false
@@ -80,6 +84,7 @@ struct RDEPUBChapterTailNormalizer {
let visibleCount = visibleCharacterCount(in: content, range: trailingFrame.contentRange)
let trailingAttachmentCount = attachmentCount(in: content, range: trailingFrame.contentRange)
guard visibleCount <= 2,
trailingFrame.contentRange.length <= 2,
visibleCount > 0 || trailingAttachmentCount > 0 else {
@@ -94,6 +99,7 @@ struct RDEPUBChapterTailNormalizer {
_ previousFrame: RDEPUBTextLayoutFrame,
with trailingFrame: RDEPUBTextLayoutFrame
) -> RDEPUBTextLayoutFrame {
let mergedRange = NSRange(
location: previousFrame.contentRange.location,
length: NSMaxRange(trailingFrame.contentRange) - previousFrame.contentRange.location
@@ -109,6 +115,7 @@ struct RDEPUBChapterTailNormalizer {
semanticHints: uniqueValues(from: previousFrame.semanticHints + trailingFrame.semanticHints),
attachmentPlacements: uniqueValues(from: previousFrame.attachmentPlacements + trailingFrame.attachmentPlacements),
trailingFragmentID: trailingFrame.trailingFragmentID ?? previousFrame.trailingFragmentID,
diagnostics: previousFrame.diagnostics
+ trailingFrame.diagnostics
+ ["normalized: merged short trailing page \(NSStringFromRange(trailingFrame.contentRange)) into previous page"]
@@ -121,6 +128,7 @@ struct RDEPUBChapterTailNormalizer {
) -> Int {
guard range.length > 0 else { return 0 }
let string = content.attributedSubstring(from: range).string
let filteredScalars = string.unicodeScalars.filter { scalar in
!CharacterSet.whitespacesAndNewlines.contains(scalar)
&& !CharacterSet.controlCharacters.contains(scalar)
@@ -1,8 +1,9 @@
import UIKit
/// Keeps pagination cache key generation and cache IO in one BuildPipeline role.
struct RDEPUBPaginationCacheCoordinator {
private let cache: RDEPUBTextBookCache?
private let layoutConfig: RDEPUBTextLayoutConfig
init(cache: RDEPUBTextBookCache?, layoutConfig: RDEPUBTextLayoutConfig) {
@@ -32,11 +33,13 @@ struct RDEPUBPaginationCacheCoordinator {
func save(chapters: [RDEPUBTextChapter], key: String?) {
guard let key else { return }
let paginationCache = chapters.map { chapter in
RDEPUBTextChapterPaginationCache(
href: chapter.href,
pageRanges: chapter.pages.map(\.contentRange),
breakReasons: chapter.pages.map(\.metadata.breakReason),
semanticHints: Array(Set(chapter.pages.flatMap(\.metadata.semanticHints)))
)
}
@@ -1,6 +1,5 @@
import UIKit
/// EPUB EPUB publication `RDEPUBTextBook`
public final class RDEPUBTextBookBuilder {
private let renderer: RDEPUBTextRenderer
private let cache: RDEPUBTextBookCache?
@@ -12,20 +11,14 @@ public final class RDEPUBTextBookBuilder {
private let cacheCoordinator: RDEPUBPaginationCacheCoordinator
private let diagnosticsReporter: RDEPUBBuildDiagnosticsReporter
///
public private(set) var lastBuildResourceDiagnostics: [RDEPUBTextResourceReferenceDiagnostic] = []
///
public private(set) var lastBuildPaginationDiagnostics: [RDEPUBTextChapterPaginationDiagnostic] = []
///
public private(set) var lastBuildPerformanceSamples: [RDEPUBTextPerformanceSample] = []
/// /
public private(set) var lastBuildCacheStats: (hits: Int, misses: Int) = (0, 0)
///
/// - Parameters:
/// - renderer:
/// - cache:
/// - layoutConfig:
public init(
renderer: RDEPUBTextRenderer,
cache: RDEPUBTextBookCache? = nil,
@@ -42,7 +35,6 @@ public final class RDEPUBTextBookBuilder {
self.diagnosticsReporter = RDEPUBBuildDiagnosticsReporter()
}
/// 使 DTCoreText
public convenience init() {
self.init(renderer: RDEPUBDTCoreTextRenderer())
}
@@ -51,7 +43,6 @@ public final class RDEPUBTextBookBuilder {
ProcessInfo.processInfo.arguments.contains("--demo-pagination-debug")
}
/// Phase 7
public func phase7SemanticSummary(title: String? = nil) -> String? {
diagnosticsReporter.phase7SemanticSummary(
title: title,
@@ -59,16 +50,6 @@ public final class RDEPUBTextBookBuilder {
)
}
/// EPUB publication
///
///
/// 1.
/// 2. spine 线 HTML
/// 3. HTML NSAttributedString
/// 4. /
/// 5. 使 CoreText
/// 6.
/// 7. RDEPUBTextBook
public func build(
parser: RDEPUBParser,
publication: RDEPUBPublication,
@@ -88,7 +69,6 @@ public final class RDEPUBTextBookBuilder {
let buildStart = CFAbsoluteTimeGetCurrent()
// WXRead
let bookID = publication.metadata.identifier ?? publication.metadata.title
let cacheKey = cacheCoordinator.cacheKey(bookID: bookID, pageSize: pageSize, style: style)
let cachedPagination = cacheCoordinator.load(key: cacheKey)
@@ -134,7 +114,6 @@ public final class RDEPUBTextBookBuilder {
sampler.totalBuildDuration = CFAbsoluteTimeGetCurrent() - buildStart
//
cacheCoordinator.save(chapters: chapters, key: cacheKey)
#if DEBUG
@@ -145,7 +124,6 @@ public final class RDEPUBTextBookBuilder {
return book
}
/// spine
public func buildChapter(
parser: RDEPUBParser,
publication: RDEPUBPublication,
@@ -192,6 +170,7 @@ public final class RDEPUBTextBookBuilder {
let request = RDEPUBTextTypesetterPipeline().makeRequest(
from: RDEPUBTypesettingInput(
href: item.href,
spineIndex: spineIndex,
title: chapterTitle,
rawHTML: rawHTML,
baseURL: parser.fileURL(forRelativePath: item.href)?.deletingLastPathComponent(),
@@ -281,11 +260,13 @@ public final class RDEPUBTextBookBuilder {
}
let paginateDuration = CFAbsoluteTimeGetCurrent() - paginateStart
let normalizedFrames = tailNormalizer.normalize(
layoutFrames,
content: content,
href: item.href
)
let effectiveFrames = normalizedFrames.isEmpty && content.length > 0
? [
RDEPUBTextLayoutFrame(
@@ -339,6 +320,12 @@ public final class RDEPUBTextBookBuilder {
title: chapterTitle,
attributedContent: chapterAttributedContent,
fragmentOffsets: rendered.fragmentOffsets,
cfiMap: RDEPUBCFITextNodeMapBuilder.makeMap(
href: item.href,
rawHTML: rawHTML,
chapterText: chapterAttributedContent.string,
fragmentOffsets: rendered.fragmentOffsets
),
pageBreakReasons: pages.map(\.metadata.breakReason),
pages: pages
)
@@ -365,9 +352,6 @@ public final class RDEPUBTextBookBuilder {
)
}
// MARK: -
/// 退 spine item title href
private func resolvedChapterTitle(for item: RDEPUBSpineItem, toc: [EPUBTableOfContentsItem]) -> String {
if let title = flattenedTOCItems(from: toc).first(where: { tocItem in
tocItem.href.components(separatedBy: "#").first == item.href
@@ -378,16 +362,12 @@ public final class RDEPUBTextBookBuilder {
return trimmedTitle.isEmpty ? item.href : trimmedTitle
}
///
private func flattenedTOCItems(from items: [EPUBTableOfContentsItem]) -> [EPUBTableOfContentsItem] {
items.flatMap { item in
[item] + flattenedTOCItems(from: item.children)
}
}
// MARK: -
/// /
private func shouldSkipChapter(item: RDEPUBSpineItem, content: NSAttributedString, text: String) -> Bool {
let lowercasedHref = item.href.lowercased()
var hasAttachment = false
@@ -404,9 +384,6 @@ public final class RDEPUBTextBookBuilder {
return false
}
// MARK: -
///
private func attachmentCount(in content: NSAttributedString) -> Int {
guard content.length > 0 else { return 0 }
var count = 0
@@ -418,7 +395,6 @@ public final class RDEPUBTextBookBuilder {
return count
}
/// NSRange
private func attachmentRanges(in content: NSAttributedString) -> [NSRange] {
guard content.length > 0 else { return [] }
var ranges: [NSRange] = []
@@ -430,9 +406,6 @@ public final class RDEPUBTextBookBuilder {
return ranges
}
// MARK: -
/// href cover
private func isAttachmentOnlyCoverChapter(
item: RDEPUBSpineItem,
content: NSAttributedString,
@@ -445,6 +418,7 @@ public final class RDEPUBTextBookBuilder {
}
private func debugPreview(for content: NSAttributedString, limit: Int) -> String {
let collapsed = content.string
.replacingOccurrences(of: "\n", with: " ")
.replacingOccurrences(of: "\r", with: " ")
@@ -1,19 +1,14 @@
import Foundation
import CryptoKit
// MARK: - WXRead
///
///
/// WXRead WRChapterPageCount NSRange +
/// NSAttributedString HTML CoreText
public struct RDEPUBTextChapterPaginationCache: Equatable {
///
public var href: String
///
public var pageRanges: [NSRange]
///
public var breakReasons: [RDEPUBTextPageBreakReason]
public var semanticHints: [RDEPUBTextSemanticHint]
public init(
@@ -29,11 +24,8 @@ public struct RDEPUBTextChapterPaginationCache: Equatable {
}
}
// MARK: - NSCoding 使
/// NSKeyedArchiver
///
final class PaginationCacheArchive: NSObject, NSSecureCoding {
static var supportsSecureCoding: Bool { true }
let chapters: [ChapterPaginationArchive]
@@ -52,20 +44,20 @@ final class PaginationCacheArchive: NSObject, NSSecureCoding {
}
}
/// NSRange location/length 便 NSSecureCoding
final class ChapterPaginationArchive: NSObject, NSSecureCoding {
static var supportsSecureCoding: Bool { true }
let href: String
/// rangeLengths
let rangeLocations: [NSNumber]
///
let rangeLengths: [NSNumber]
///
let breakReasons: [String]
///
let semanticHints: [String]
///
init(from cache: RDEPUBTextChapterPaginationCache) {
self.href = cache.href
self.rangeLocations = cache.pageRanges.map { NSNumber(value: $0.location) }
@@ -97,7 +89,6 @@ final class ChapterPaginationArchive: NSObject, NSSecureCoding {
self.semanticHints = semanticHints
}
///
func toCache() -> RDEPUBTextChapterPaginationCache {
let pageRanges = zip(rangeLocations, rangeLengths).map { loc, len in
NSRange(location: loc.intValue, length: len.intValue)
@@ -111,28 +102,14 @@ final class ChapterPaginationArchive: NSObject, NSSecureCoding {
}
}
// MARK: -
/// WXRead WRChapterPageCount
///
///
/// - = SHA256(ID + + + + + schema)
/// - = NSRange + NSKeyedArchiver
/// - HTML CoreText
/// - 线 serial DispatchQueue
public final class RDEPUBTextBookCache {
///
//
public var schemaVersion: Int = 6
/// 线
private let queue = DispatchQueue(label: "com.rdreader.textbookcache", qos: .utility)
///
private let cacheDirectory: URL
///
/// - Parameter subdirectory: Caches
public init(subdirectory: String = "RDEPUBTextBookCache") {
let baseURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?
.appendingPathComponent(subdirectory, isDirectory: true)
@@ -141,13 +118,6 @@ public final class RDEPUBTextBookCache {
try? FileManager.default.createDirectory(at: cacheDirectory, withIntermediateDirectories: true)
}
// MARK: -
// WRChapterPageCount.currentCacheKeyWithBookId
// bookID + fontSize + lineHeightMultiple + contentInsets + pageSize
/// SHA256 + ".cache"
///
///
public func cacheKey(
bookID: String,
fontSize: CGFloat,
@@ -162,10 +132,6 @@ public final class RDEPUBTextBookCache {
return hex + ".cache"
}
// MARK: - /
/// href
/// nil
public func load(key: String) -> [String: RDEPUBTextChapterPaginationCache]? {
queue.sync {
let fileURL = cacheDirectory.appendingPathComponent(key)
@@ -203,7 +169,6 @@ public final class RDEPUBTextBookCache {
}
}
///
public func save(_ chapters: [RDEPUBTextChapterPaginationCache], key: String) {
queue.sync {
let fileURL = cacheDirectory.appendingPathComponent(key)
@@ -223,9 +188,6 @@ public final class RDEPUBTextBookCache {
}
}
// MARK: -
///
public func invalidateAll() {
queue.sync {
let fileManager = FileManager.default
@@ -1,93 +1,99 @@
import UIKit
// MARK: -
///
/// /
public struct RDEPUBTextChapterPaginationDiagnostic: Equatable {
public var href: String
public var title: String
public var pageCount: Int
///
public var breakReasons: [RDEPUBTextPageBreakReason]
///
public var attachmentPageCount: Int
/// /
public var blockAdjustedPageCount: Int
public var blockKinds: [RDEPUBTextBlockKind]
public var semanticHints: [RDEPUBTextSemanticHint]
public var attachmentPlacements: [RDEPUBTextAttachmentPlacement]
/// 4
public var sampleNotes: [String]
}
// MARK: -
///
public struct RDEPUBTextChapterBuildResult {
public var chapter: RDEPUBTextChapter
public var resourceDiagnostics: [RDEPUBTextResourceReferenceDiagnostic]
public var paginationDiagnostic: RDEPUBTextChapterPaginationDiagnostic
public var performanceSample: RDEPUBTextPerformanceSample
public var cacheHit: Bool
}
// MARK: -
///
///
/// `RDEPUBTextPage` `RDEPUBTextLayoutFrame`
/// `contentRange`
public struct RDEPUBTextPage: Equatable {
/// 0
public var absolutePageIndex: Int
public var chapterIndex: Int
public var spineIndex: Int
public var href: String
public var chapterTitle: String
/// 0
public var pageIndexInChapter: Int
public var totalPagesInChapter: Int
///
public var chapterContent: NSAttributedString
///
public var content: NSAttributedString
///
public var contentRange: NSRange
public var pageStartOffset: Int
public var pageEndOffset: Int
///
public var metadata: RDEPUBTextPageMetadata
}
// MARK: -
///
public struct RDEPUBTextChapter: Equatable {
public var chapterIndex: Int
public var spineIndex: Int
public var href: String
public var title: String
///
public var attributedContent: NSAttributedString
/// fragment ID
public var fragmentOffsets: [String: Int]
public var cfiMap: RDEPUBCFIMap?
public var pageBreakReasons: [RDEPUBTextPageBreakReason]
public var pages: [RDEPUBTextPage]
}
// MARK: -
/// EPUB
///
/// EPUBTextRendering `RDEPUBTextBookBuilder.build()`
/// `chapterData(for:)` `chapterData(atChapterIndex:)` `RDEPUBChapterData`
public struct RDEPUBTextBook {
public var chapters: [RDEPUBTextChapter]
public var pages: [RDEPUBTextPage]
/// fileIndex/row/column
public let indexTable: RDEPUBTextIndexTable
/// WXRead <-> <->
public var positionConverter: RDEPUBTextPositionConverter {
RDEPUBTextPositionConverter(book: self)
}
@@ -102,31 +108,26 @@ public struct RDEPUBTextBook {
lhs.chapters == rhs.chapters && lhs.pages == rhs.pages
}
/// href 访
public func chapterData(for href: String) -> RDEPUBChapterData? {
guard let chapter = chapters.first(where: { $0.href == href }) else { return nil }
return RDEPUBChapterData(chapter: chapter, indexTable: indexTable)
}
/// spine 访
public func chapterData(forSpineIndex spineIndex: Int) -> RDEPUBChapterData? {
guard let chapter = chapters.first(where: { $0.spineIndex == spineIndex }) else { return nil }
return RDEPUBChapterData(chapter: chapter, indexTable: indexTable)
}
/// 访
public func chapterData(atChapterIndex index: Int) -> RDEPUBChapterData? {
guard chapters.indices.contains(index) else { return nil }
return RDEPUBChapterData(chapter: chapters[index], indexTable: indexTable)
}
/// 1 访
public func chapterData(forPageNumber pageNumber: Int) -> RDEPUBChapterData? {
guard let page = page(at: pageNumber) else { return nil }
return chapterData(forSpineIndex: page.spineIndex)
}
/// 访
public func chapterData(
for location: RDEPUBLocation,
resolver: RDEPUBResourceResolver,
@@ -138,7 +139,6 @@ public struct RDEPUBTextBook {
return chapterData(for: normalizedLocation.href)
}
/// WXRead
public var chapterInfos: [EPUBChapterInfo] {
chapters.map { chapter in
EPUBChapterInfo(
@@ -149,7 +149,6 @@ public struct RDEPUBTextBook {
}
}
/// 1
public func page(at pageNumber: Int) -> RDEPUBTextPage? {
guard pageNumber > 0, pages.indices.contains(pageNumber - 1) else {
return nil
@@ -157,12 +156,6 @@ public struct RDEPUBTextBook {
return pages[pageNumber - 1]
}
/// 1
///
///
/// 1. rangeAnchor
/// 2. fragment ID
/// 3. navigationProgression 退
public func pageNumber(for location: RDEPUBLocation, resolver: RDEPUBResourceResolver, bookIdentifier: String?) -> Int? {
guard let normalizedLocation = resolver.normalizedLocation(location, bookIdentifier: bookIdentifier),
let chapterData = chapterData(for: normalizedLocation.href) else {
@@ -182,7 +175,6 @@ public struct RDEPUBTextBook {
return chapterData.pageNumber(for: normalizedLocation)
}
/// RDEPUBLocation
public func location(forPageNumber pageNumber: Int, bookIdentifier: String?) -> RDEPUBLocation? {
guard let chapterData = chapterData(forPageNumber: pageNumber),
let page = page(at: pageNumber) else {
@@ -1,10 +1,8 @@
// RDEPUBTextBuildPipelineInterfaces.swift
// EPUB 线线
import UIKit
/// EPUB EPUB
protocol RDEPUBTextBookBuilding {
func build(
parser: RDEPUBParser,
publication: RDEPUBPublication,
@@ -13,41 +11,25 @@ protocol RDEPUBTextBookBuilding {
) throws -> RDEPUBTextBook
}
/// 线
struct RDEPUBChapterRenderPipeline {
private let renderer: RDEPUBTextRenderer
/// 线
/// - Parameter renderer:
init(renderer: RDEPUBTextRenderer) {
self.renderer = renderer
}
///
/// - Parameter request:
/// - Returns:
func render(_ request: RDEPUBTextChapterRenderRequest) throws -> RDEPUBRenderedChapterContent {
try renderer.renderChapter(request: request)
}
}
/// 线
struct RDEPUBChapterPaginationPipeline {
private let frameFactory: RDEPUBPageFrameBuilding
/// 线
/// - Parameter frameFactory: 使 CoreText
init(frameFactory: RDEPUBPageFrameBuilding = RDEPUBCoreTextPageFrameFactory()) {
self.frameFactory = frameFactory
}
///
/// - Parameters:
/// - content:
/// - pageSize:
/// - config:
/// - fragmentOffsets: fragment
/// - Returns:
func frames(
for content: NSAttributedString,
pageSize: CGSize,
@@ -1,20 +1,17 @@
import Foundation
// MARK: -
///
public struct RDEPUBTextPerformanceSample: Equatable {
///
public var chapterHref: String
/// HTML
public var renderDuration: TimeInterval
/// CoreText
public var paginateDuration: TimeInterval
///
public var pageCount: Int
///
public var attributedStringLength: Int
///
public var cacheHit: Bool
public init(
@@ -34,21 +31,14 @@ public struct RDEPUBTextPerformanceSample: Equatable {
}
}
// MARK: -
///
///
/// `RDEPUBTextBookBuilder` 使
///
public final class RDEPUBTextPerformanceSampler {
///
public private(set) var samples: [RDEPUBTextPerformanceSample] = []
///
public var totalBuildDuration: TimeInterval = 0
public init() {}
///
public func record(_ sample: RDEPUBTextPerformanceSample) {
samples.append(sample)
#if DEBUG
@@ -56,7 +46,6 @@ public final class RDEPUBTextPerformanceSampler {
#endif
}
/// /
public func summary() -> String {
let totalRender = samples.reduce(0) { $0 + $1.renderDuration }
let totalPaginate = samples.reduce(0) { $0 + $1.paginateDuration }
@@ -64,13 +53,11 @@ public final class RDEPUBTextPerformanceSampler {
return "[PERF] chapters=\(samples.count) render=\(formatMS(totalRender)) paginate=\(formatMS(totalPaginate)) total=\(formatMS(totalBuildDuration)) cacheHits=\(hitCount)/\(samples.count)"
}
///
public func reset() {
samples.removeAll()
totalBuildDuration = 0
}
///
private func formatMS(_ duration: TimeInterval) -> String {
String(format: "%.0fms", duration * 1000)
}
@@ -5,24 +5,20 @@ import UIKit
import DTCoreText
#endif
///
///
///
/// 1. avoidPageBreakInside WXRead 退
/// 2. keepWithNext
/// 3. pageBreakBefore/After
/// 4. pageRelate
/// 5.
/// 6. CoreText
struct RDEPUBChapterPageCounter {
private let factory: RDEPUBCoreTextPageFrameFactory
private let attributedString: NSAttributedString
private let pageSize: CGSize
private let config: RDEPUBTextLayoutConfig
private let pageBreakPolicy: RDEPUBPageBreakPolicy
private let framesetter: CTFramesetter
/// DTCoreText
private let dtLayoutRect: CGRect
init(factory: RDEPUBCoreTextPageFrameFactory) {
@@ -35,7 +31,6 @@ struct RDEPUBChapterPageCounter {
self.dtLayoutRect = factory.config.contentRect(fallback: factory.pageSize)
}
///
func layoutFrames(fragmentOffsets: [String: Int] = [:]) -> [RDEPUBTextLayoutFrame] {
guard attributedString.length > 0, pageSize.width > 0, pageSize.height > 0 else {
return []
@@ -48,8 +43,6 @@ struct RDEPUBChapterPageCounter {
#endif
}
// MARK: - CoreText 退
private func layoutFramesUsingCoreText(fragmentOffsets: [String: Int]) -> [RDEPUBTextLayoutFrame] {
guard attributedString.length > 0, pageSize.width > 0, pageSize.height > 0 else {
return []
@@ -129,9 +122,8 @@ struct RDEPUBChapterPageCounter {
return frames
}
// MARK: - DTCoreText
#if canImport(DTCoreText)
private func layoutFramesUsingDTCoreText(fragmentOffsets: [String: Int]) -> [RDEPUBTextLayoutFrame] {
guard config.numberOfColumns == 1 else {
return layoutFramesUsingCoreText(fragmentOffsets: fragmentOffsets)
@@ -252,9 +244,6 @@ struct RDEPUBChapterPageCounter {
}
#endif
// MARK: - WXRead
/// CoreText frame path
private func proposedVisibleRange(
from frame: CTFrame,
start location: Int,
@@ -5,13 +5,14 @@ import UIKit
import DTCoreText
#endif
/// CoreText
///
/// RDEPUBChapterPageCounter RDEPUBPageBreakPolicy
struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
let attributedString: NSAttributedString
let pageSize: CGSize
let config: RDEPUBTextLayoutConfig
private let pageBreakPolicy: RDEPUBPageBreakPolicy
init(attributedString: NSAttributedString, pageSize: CGSize, config: RDEPUBTextLayoutConfig = .default) {
@@ -21,13 +22,10 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
self.pageBreakPolicy = RDEPUBPageBreakPolicy(attributedString: attributedString)
}
/// 便使
init() {
self.init(attributedString: NSAttributedString(), pageSize: .zero, config: .default)
}
// MARK: - RDEPUBPageFrameBuilding
func makeFrames(
attributedString: NSAttributedString,
pageSize: CGSize,
@@ -39,9 +37,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
return counter.layoutFrames(fragmentOffsets: fragmentOffsets)
}
// MARK: -
/// CGPath CTFramesetterCreateFrame
static func makeLayoutPath(pageSize: CGSize, config: RDEPUBTextLayoutConfig) -> CGPath {
let columnRects = config.columnRects(fallback: pageSize)
guard columnRects.count > 1 else {
@@ -55,9 +50,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
return path
}
// MARK: -
/// CTFrame avoidPageBreakInside
func trimmedRangeForAvoidPageBreakInside(
from frame: CTFrame,
proposed: NSRange
@@ -74,7 +66,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
return trimmedRangeForAvoidPageBreakInside(proposed: proposed, lineRanges: lineRanges)
}
/// CoreText keepWithNext
func trimmedRangeForKeepWithNext(
from frame: CTFrame,
proposed: NSRange
@@ -88,7 +79,7 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
}
#if canImport(DTCoreText)
/// DTCoreText avoidPageBreakInside
func trimmedRangeForAvoidPageBreakInside(
from layoutFrame: DTCoreTextLayoutFrame,
proposed: NSRange
@@ -102,7 +93,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
return trimmedRangeForAvoidPageBreakInside(proposed: proposed, lineRanges: lineRanges)
}
/// DTCoreText keepWithNext
func trimmedRangeForKeepWithNext(
from layoutFrame: DTCoreTextLayoutFrame,
proposed: NSRange
@@ -115,7 +105,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
}
#endif
/// avoidPageBreakInside
func trimmedRangeForAvoidPageBreakInside(
proposed: NSRange,
lineRanges: [NSRange]
@@ -155,7 +144,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
return NSRange(location: proposed.location, length: adjustedLength)
}
/// keepWithNext
func trimmedRangeForKeepWithNext(
proposed: NSRange,
lineRanges: [NSRange]
@@ -195,7 +183,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
return NSRange(location: proposed.location, length: adjustedLength)
}
/// avoidWidows / avoidOrphans
func trimmedRangeForWidowAndOrphanControl(
proposed: NSRange,
lineRanges: [NSRange]
@@ -227,9 +214,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
return adjusted
}
// MARK: -
/// CTFrame
static func lineRanges(from frame: CTFrame) -> [NSRange] {
let lines = CTFrameGetLines(frame) as! [CTLine]
return lines.map {
@@ -239,7 +223,7 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
}
#if canImport(DTCoreText)
/// DTCoreTextLayoutFrame
static func lineRanges(from layoutFrame: DTCoreTextLayoutFrame) -> [NSRange] {
guard let lines = layoutFrame.lines as? [DTCoreTextLayoutLine] else {
return []
@@ -248,9 +232,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
}
#endif
// MARK: -
///
func blockRange(at location: Int) -> NSRange? {
guard location >= 0, location < attributedString.length else { return nil }
let attributes = attributedString.attributes(at: location, effectiveRange: nil)
@@ -260,7 +241,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
return nil
}
///
func blockKind(at location: Int) -> RDEPUBTextBlockKind? {
guard location >= 0, location < attributedString.length else { return nil }
let attributes = attributedString.attributes(at: location, effectiveRange: nil)
@@ -268,7 +248,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
return RDEPUBTextBlockKind(rawValue: rawValue)
}
///
func attachmentPlacement(at location: Int) -> RDEPUBTextAttachmentPlacement? {
guard location >= 0, location < attributedString.length else { return nil }
let attributes = attributedString.attributes(at: location, effectiveRange: nil)
@@ -276,7 +255,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
return RDEPUBTextAttachmentPlacement(rawValue: rawValue)
}
///
func paragraphRange(containing location: Int) -> NSRange {
let source = attributedString.string as NSString
guard source.length > 0 else { return NSRange(location: 0, length: 0) }
@@ -284,7 +262,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
return source.paragraphRange(for: NSRange(location: safeLocation, length: 0))
}
///
func attachmentRanges(in range: NSRange) -> [NSRange] {
guard let safeRange = clampedRange(range), safeRange.length > 0 else {
return []
@@ -297,7 +274,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
return results
}
///
func semanticHints(at location: Int) -> [RDEPUBTextSemanticHint] {
guard location >= 0, location < attributedString.length else { return [] }
let attributes = attributedString.attributes(at: location, effectiveRange: nil)
@@ -307,8 +283,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
.compactMap { RDEPUBTextSemanticHint(rawValue: String($0)) }
}
// MARK: - Widow / Orphan
private func trimmedRangeAvoidingWidow(
proposed: NSRange,
lineRanges: [NSRange]
@@ -408,7 +382,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
return lineCount
}
///
func attachmentKinds(in range: NSRange) -> [RDEPUBTextAttachmentKind] {
guard let safeRange = clampedRange(range), safeRange.length > 0 else {
return []
@@ -425,7 +398,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
return kinds
}
///
func blockKinds(in range: NSRange) -> [RDEPUBTextBlockKind] {
guard let safeRange = clampedRange(range), safeRange.length > 0 else {
return []
@@ -442,7 +414,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
return kinds
}
///
func semanticHints(in range: NSRange) -> [RDEPUBTextSemanticHint] {
guard let safeRange = clampedRange(range), safeRange.length > 0 else {
return []
@@ -457,7 +428,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
return hints
}
///
func attachmentPlacements(in range: NSRange) -> [RDEPUBTextAttachmentPlacement] {
guard let safeRange = clampedRange(range), safeRange.length > 0 else {
return []
@@ -474,7 +444,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
return placements
}
/// attributedString
func clampedRange(_ range: NSRange) -> NSRange? {
guard range.location >= 0, range.length >= 0 else { return nil }
guard attributedString.length > 0 else {
@@ -486,7 +455,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
return NSRange(location: range.location, length: min(range.length, maxLength))
}
/// fragment ID
func nearestTrailingFragmentID(
endingAt location: Int,
fragmentOffsets: [String: Int]
@@ -497,9 +465,6 @@ struct RDEPUBCoreTextPageFrameFactory: RDEPUBPageFrameBuilding {
.key
}
// MARK: -
///
func diagnostics(
reason: RDEPUBTextPageBreakReason,
range: NSRange,
@@ -1,19 +1,14 @@
import Foundation
import UIKit
///
///
/// CoreText frame attributed string
struct RDEPUBPageBreakPolicy {
private let attributedString: NSAttributedString
init(attributedString: NSAttributedString) {
self.attributedString = attributedString
}
// MARK: -
/// avoidPageBreakInside
func lineIsInAvoidPageBreakInsideBlock(_ lineRange: NSRange) -> Bool {
guard let probeRange = clampedProbeRange(for: lineRange) else {
return false
@@ -35,7 +30,6 @@ struct RDEPUBPageBreakPolicy {
return found
}
/// keepWithNext
func lineIsInKeepWithNextBlock(_ lineRange: NSRange) -> Bool {
guard let probeRange = clampedProbeRange(for: lineRange) else {
return false
@@ -54,14 +48,6 @@ struct RDEPUBPageBreakPolicy {
return found
}
// MARK: -
/// CoreText/DTCoreText
///
///
/// 1. chapterEnd
/// 2. pageRelate
/// 3. 使
func adjustedRange(
from proposedRange: NSRange,
totalLength: Int,
@@ -111,8 +97,6 @@ struct RDEPUBPageBreakPolicy {
let currentSemanticHints = proposedSemanticHints
let currentAttachmentPlacements = proposedAttachmentPlacements
// WXRead CTFrame pageRelate
//
if let pageRelateBoundary = preferredPageRelateBoundary(
after: proposedRange,
minimumEnd: proposedRange.location + 1,
@@ -142,7 +126,6 @@ struct RDEPUBPageBreakPolicy {
)
}
//
return (
range: proposedRange,
breakReason: .frameLimit,
@@ -164,9 +147,6 @@ struct RDEPUBPageBreakPolicy {
)
}
// MARK: -
/// pageRelate
func preferredPageRelateBoundary(
after range: NSRange,
minimumEnd: Int,
@@ -192,8 +172,6 @@ struct RDEPUBPageBreakPolicy {
return lastLineStart
}
// MARK: -
private func shouldTreatAvoidHintAsBlockProtection(_ attributes: [NSAttributedString.Key: Any]) -> Bool {
guard let rawValue = attributes[.rdPageSemanticHints] as? String else {
return false
@@ -1,33 +1,27 @@
import Foundation
/// CoreText
///
/// `RDEPUBTextLayouter`
/// `RDEPUBTextBookBuilder` `RDEPUBTextLayoutFrame`
/// `RDEPUBTextPage` `RDEPUBTextBook`
struct RDEPUBTextLayoutFrame: Equatable {
///
var contentRange: NSRange
///
var breakReason: RDEPUBTextPageBreakReason
/// HTML
var blockRange: NSRange?
///
var attachmentRanges: [NSRange]
///
var attachmentKinds: [RDEPUBTextAttachmentKind]
/// HTML
var blockKinds: [RDEPUBTextBlockKind]
///
var semanticHints: [RDEPUBTextSemanticHint]
/// 线
var attachmentPlacements: [RDEPUBTextAttachmentPlacement]
/// fragment ID
var trailingFragmentID: String?
///
var diagnostics: [String]
///
var metadata: RDEPUBTextPageMetadata {
RDEPUBTextPageMetadata(
breakReason: breakReason,
@@ -5,12 +5,6 @@ import UIKit
import DTCoreText
#endif
/// CoreText Facade
///
///
/// - RDEPUBCoreTextPageFrameFactory
/// - RDEPUBPageBreakPolicy keepWithNext
/// - RDEPUBChapterPageCounter
struct RDEPUBTextLayouter {
private let counter: RDEPUBChapterPageCounter
@@ -19,7 +13,6 @@ struct RDEPUBTextLayouter {
self.counter = RDEPUBChapterPageCounter(factory: factory)
}
///
func layoutFrames(fragmentOffsets: [String: Int] = [:]) -> [RDEPUBTextLayoutFrame] {
counter.layoutFrames(fragmentOffsets: fragmentOffsets)
}
@@ -1,30 +1,18 @@
// RDEPUBTextPaginationInterfaces.swift
// EPUB
import Foundation
import UIKit
// MARK: -
///
struct RDEPUBPageBreakDecision {
///
var range: NSRange
///
var reason: RDEPUBTextPageBreakReason
///
var diagnostics: [String]
}
///
protocol RDEPUBChapterPageCounting {
///
/// - Parameters:
/// - attributedString:
/// - pageSize:
/// - config:
/// - fragmentOffsets: fragment
/// - Returns:
func pageRanges(
for attributedString: NSAttributedString,
pageSize: CGSize,
@@ -33,15 +21,8 @@ protocol RDEPUBChapterPageCounting {
) -> [RDEPUBPageBreakDecision]
}
///
protocol RDEPUBPageFrameBuilding {
///
/// - Parameters:
/// - attributedString:
/// - pageSize:
/// - config:
/// - fragmentOffsets: fragment
/// - Returns:
func makeFrames(
attributedString: NSAttributedString,
pageSize: CGSize,
@@ -1,18 +1,8 @@
import CoreText
import UIKit
// MARK: - NSAttributedString
/// NSAttributedString 便 CoreText
extension NSAttributedString {
///
///
/// `RDEPUBTextBookBuilder` `RDPlainTextBookBuilder`
/// - Parameters:
/// - size:
/// - fragmentOffsets: fragment ID
/// - config: avoidPageBreakInside
/// - Returns:
func rd_paginatedFrames(
size: CGSize,
fragmentOffsets: [String: Int] = [:],
@@ -23,17 +13,13 @@ extension NSAttributedString {
return counter.layoutFrames(fragmentOffsets: fragmentOffsets)
}
/// NSRange
func ss_pageRanges(size: CGSize) -> [NSRange] {
rd_paginatedFrames(size: size).map(\.contentRange)
}
}
// MARK: - UIColor CSS
/// UIColor CSS CSS
extension UIColor {
/// UIColor CSS rgba()
var ss_cssString: String {
var red: CGFloat = 0
var green: CGFloat = 0
@@ -1,14 +1,9 @@
import UIKit
/// 访便
///
/// `RDEPUBTextChapter` `indexTable`
/// fragment API
/// `RDEPUBTextBook.chapterData(for:)` `chapterData(atChapterIndex:)`
public final class RDEPUBChapterData {
///
public let chapter: RDEPUBTextChapter
/// fileIndex/row/column
public let indexTable: RDEPUBTextIndexTable
public init(chapter: RDEPUBTextChapter, indexTable: RDEPUBTextIndexTable) {
@@ -16,88 +11,66 @@ public final class RDEPUBChapterData {
self.indexTable = indexTable
}
// MARK: - 便 chapter
///
public var chapterIndex: Int { chapter.chapterIndex }
/// spine
public var spineIndex: Int { chapter.spineIndex }
/// "OEBPS/chapter1.xhtml"
public var href: String { chapter.href }
///
public var title: String { chapter.title }
///
public var attributedContent: NSAttributedString { chapter.attributedContent }
///
public var pages: [RDEPUBTextPage] { chapter.pages }
///
public var pageCount: Int { chapter.pages.count }
/// fragment ID
public var fragmentOffsets: [String: Int] { chapter.fragmentOffsets }
/// /
public var chapterInfo: EPUBChapterInfo {
EPUBChapterInfo(spineIndex: spineIndex, title: title, pageCount: pageCount)
}
///
public var absolutePageRange: ClosedRange<Int>? {
guard let firstPage = pages.first, let lastPage = pages.last else { return nil }
return firstPage.absolutePageIndex...lastPage.absolutePageIndex
}
// MARK: -
///
/// - Parameter absoluteOffset:
/// - Returns: nil
public func page(containing absoluteOffset: Int) -> RDEPUBTextPage? {
chapter.pages.first { NSLocationInRange(absoluteOffset, $0.contentRange) }
}
/// 0
public func pageNumber(containing absoluteOffset: Int) -> Int? {
page(containing: absoluteOffset)?.absolutePageIndex
}
///
public func page(atAbsolutePageIndex absolutePageIndex: Int) -> RDEPUBTextPage? {
chapter.pages.first { $0.absolutePageIndex == absolutePageIndex }
}
/// 1
public func page(atPageNumber pageNumber: Int) -> RDEPUBTextPage? {
guard pageNumber > 0, pages.indices.contains(pageNumber - 1) else { return nil }
return pages[pageNumber - 1]
}
// MARK: -
/// fileIndex/row/column
public func anchor(forAbsoluteIndex index: Int) -> RDEPUBTextAnchor {
indexTable.anchor(forAbsoluteIndex: index, in: chapter)
}
///
public func anchor(forGlobalIndex index: Int) -> RDEPUBTextAnchor? {
indexTable.anchor(forGlobalIndex: index)
}
///
public func rangeAnchor(for absoluteRange: NSRange) -> RDEPUBTextRangeAnchor {
let start = anchor(forAbsoluteIndex: absoluteRange.location)
let end = anchor(forAbsoluteIndex: absoluteRange.location + absoluteRange.length)
return RDEPUBTextRangeAnchor(start: start, end: end)
}
///
public func globalRange(for rangeAnchor: RDEPUBTextRangeAnchor) -> NSRange {
indexTable.globalRange(for: rangeAnchor)
}
/// /
/// - Parameters:
/// - absoluteRange:
/// - bookIdentifier:
/// - Returns: nil
public func selection(from absoluteRange: NSRange, bookIdentifier: String?) -> RDEPUBSelection? {
guard page(containing: absoluteRange.location) != nil else { return nil }
let location = self.location(for: absoluteRange, bookIdentifier: bookIdentifier)
@@ -115,7 +88,6 @@ public final class RDEPUBChapterData {
)
}
/// RDEPUBLocation
public func location(for absoluteRange: NSRange, bookIdentifier: String?) -> RDEPUBLocation {
indexTable.location(
for: rangeAnchor(for: absoluteRange),
@@ -124,32 +96,31 @@ public final class RDEPUBChapterData {
)
}
/// RDEPUBLocation
public func location(forPage page: RDEPUBTextPage, bookIdentifier: String?) -> RDEPUBLocation {
location(for: page.contentRange, bookIdentifier: bookIdentifier)
}
///
public func page(for location: RDEPUBLocation) -> RDEPUBTextPage? {
guard let range = absoluteRange(for: location) else { return nil }
return page(containing: range.location)
}
///
public func page(for searchMatch: RDEPUBSearchMatch) -> RDEPUBTextPage? {
guard let range = absoluteRange(for: searchMatch) else { return nil }
return page(containing: range.location)
}
// MARK: - Location
///
///
///
/// 1. rangeAnchor
/// 2. fragment ID
/// 3. navigationProgression退
public func absoluteRange(for location: RDEPUBLocation) -> NSRange? {
if let cfiRange = RDEPUBCFICompatibility.parseRangeLossy(location.rangeCFI),
let rangeAnchor = indexTable.rangeAnchor(for: cfiRange) {
return indexTable.chapterRange(for: rangeAnchor)
}
if let cfi = RDEPUBCFICompatibility.parseLossy(location.cfi),
let anchor = indexTable.anchor(for: cfi) {
return NSRange(location: indexTable.chapterOffset(for: anchor), length: 1)
}
if let rangeAnchor = location.rangeAnchor {
return indexTable.chapterRange(for: rangeAnchor)
}
@@ -164,16 +135,35 @@ public final class RDEPUBChapterData {
return NSRange(location: offset, length: 1)
}
///
public func absoluteRange(for highlight: RDEPUBHighlight) -> NSRange? {
if let cfiRange = RDEPUBCFICompatibility.parseRangeLossy(highlight.location.rangeCFI),
let rangeAnchor = indexTable.rangeAnchor(for: cfiRange) {
return indexTable.chapterRange(for: rangeAnchor)
}
if let endpointRange = chapterRange(fromLocationCFIEndpoints: highlight.location) {
return endpointRange
}
if let rangeAnchor = highlight.location.rangeAnchor {
return indexTable.chapterRange(for: rangeAnchor)
}
return RDEPUBTextOffsetRangeInfo.decode(from: highlight.rangeInfo)?.nsRange
}
///
public func absoluteRange(for searchMatch: RDEPUBSearchMatch) -> NSRange? {
if let cfiRange = RDEPUBCFICompatibility.parseRangeLossy(searchMatch.rangeCFI),
let rangeAnchor = indexTable.rangeAnchor(for: cfiRange) {
return indexTable.chapterRange(for: rangeAnchor)
}
if let cfi = RDEPUBCFICompatibility.parseLossy(searchMatch.cfi),
let anchor = indexTable.anchor(for: cfi) {
let location = indexTable.chapterOffset(for: anchor)
return NSRange(
location: location,
length: recoveredSearchRangeLength(for: searchMatch, cfi: cfi, startOffset: location)
)
}
if let location = searchMatch.rangeLocation {
return NSRange(location: location, length: max(searchMatch.rangeLength, 1))
}
@@ -183,8 +173,17 @@ public final class RDEPUBChapterData {
return nil
}
///
public func globalRange(for location: RDEPUBLocation) -> NSRange? {
if let cfiRange = RDEPUBCFICompatibility.parseRangeLossy(location.rangeCFI),
let rangeAnchor = indexTable.rangeAnchor(for: cfiRange) {
return indexTable.globalRange(for: rangeAnchor)
}
if let cfi = RDEPUBCFICompatibility.parseLossy(location.cfi),
let anchor = indexTable.anchor(for: cfi) {
return NSRange(location: indexTable.globalIndex(for: anchor), length: 1)
}
if let rangeAnchor = location.rangeAnchor {
return indexTable.globalRange(for: rangeAnchor)
}
@@ -195,8 +194,16 @@ public final class RDEPUBChapterData {
return NSRange(location: chapterStart + chapterRange.location, length: chapterRange.length)
}
///
public func globalRange(for highlight: RDEPUBHighlight) -> NSRange? {
if let cfiRange = RDEPUBCFICompatibility.parseRangeLossy(highlight.location.rangeCFI),
let rangeAnchor = indexTable.rangeAnchor(for: cfiRange) {
return indexTable.globalRange(for: rangeAnchor)
}
if let endpointRange = globalRange(fromLocationCFIEndpoints: highlight.location) {
return endpointRange
}
if let rangeAnchor = highlight.location.rangeAnchor {
return indexTable.globalRange(for: rangeAnchor)
}
@@ -207,8 +214,19 @@ public final class RDEPUBChapterData {
return NSRange(location: chapterStart + chapterRange.location, length: chapterRange.length)
}
///
public func globalRange(for searchMatch: RDEPUBSearchMatch) -> NSRange? {
if let cfiRange = RDEPUBCFICompatibility.parseRangeLossy(searchMatch.rangeCFI),
let rangeAnchor = indexTable.rangeAnchor(for: cfiRange) {
return indexTable.globalRange(for: rangeAnchor)
}
if let cfi = RDEPUBCFICompatibility.parseLossy(searchMatch.cfi),
let anchor = indexTable.anchor(for: cfi) {
let chapterLocation = indexTable.chapterOffset(for: anchor)
return NSRange(
location: indexTable.globalIndex(for: anchor),
length: recoveredSearchRangeLength(for: searchMatch, cfi: cfi, startOffset: chapterLocation)
)
}
if let rangeAnchor = searchMatch.rangeAnchor {
return indexTable.globalRange(for: rangeAnchor)
}
@@ -219,13 +237,14 @@ public final class RDEPUBChapterData {
return NSRange(location: chapterStart + chapterRange.location, length: chapterRange.length)
}
// MARK: - /
///
public func highlights(on page: RDEPUBTextPage, from allHighlights: [RDEPUBHighlight]) -> [RDEPUBHighlight] {
let pageRange = absoluteOffsetRange(for: page)
return allHighlights.filter { highlight in
guard highlight.location.href == chapter.href else { return false }
if let cfiRange = RDEPUBCFICompatibility.parseRangeLossy(highlight.location.rangeCFI),
let rangeAnchor = indexTable.rangeAnchor(for: cfiRange) {
return NSIntersectionRange(indexTable.chapterRange(for: rangeAnchor), page.contentRange).length > 0
}
if let anchor = highlight.location.rangeAnchor?.start {
return pageRange.contains(absoluteOffset(for: anchor))
}
@@ -236,7 +255,6 @@ public final class RDEPUBChapterData {
}
}
///
public func searchMatches(on page: RDEPUBTextPage, from matches: [RDEPUBSearchMatch]) -> [RDEPUBSearchMatch] {
return matches.filter { match in
guard match.href == chapter.href else { return false }
@@ -247,26 +265,20 @@ public final class RDEPUBChapterData {
}
}
/// `searchMatches(on:from:)` /WXRead
public func searchResults(on page: RDEPUBTextPage, from matches: [RDEPUBSearchMatch]) -> [RDEPUBSearchMatch] {
searchMatches(on: page, from: matches)
}
/// 1
public func pageNumber(for location: RDEPUBLocation) -> Int? {
guard let page = page(for: location) else { return nil }
return page.absolutePageIndex + 1
}
/// 1
public func pageNumber(for searchMatch: RDEPUBSearchMatch) -> Int? {
guard let page = page(for: searchMatch) else { return nil }
return page.absolutePageIndex + 1
}
// MARK: -
/// TOC
public func contains(
tableOfContentsItem item: EPUBTableOfContentsItem,
normalizer: (String) -> String?
@@ -278,7 +290,6 @@ public final class RDEPUBChapterData {
return chapterHref == itemHref
}
///
public func tableOfContentsItems(
from items: [EPUBTableOfContentsItem],
normalizer: (String) -> String?
@@ -289,7 +300,6 @@ public final class RDEPUBChapterData {
}
}
///
public func primaryTableOfContentsItem(
from items: [EPUBTableOfContentsItem],
normalizer: (String) -> String?
@@ -297,10 +307,6 @@ public final class RDEPUBChapterData {
tableOfContentsItems(from: items, normalizer: normalizer).first
}
// MARK: - WXRead WRChapterData.addHighlightInRange:key:itemId:color:
/// /线 NSAttributedString
/// CoreText WXRead com.weread.highlight / com.weread.underline
public func applyHighlights(
to content: NSMutableAttributedString,
page: RDEPUBTextPage,
@@ -324,17 +330,51 @@ public final class RDEPUBChapterData {
}
}
// MARK: -
/// [start, end+1)
private func absoluteOffsetRange(for page: RDEPUBTextPage) -> Range<Int> {
let lowerBound = page.pageStartOffset
let upperBound = page.pageEndOffset + 1
return lowerBound..<max(upperBound, lowerBound)
}
/// 退 chapterOffset
private func absoluteOffset(for anchor: RDEPUBTextAnchor) -> Int {
indexTable.chapterOffset(for: anchor)
}
private func chapterRange(fromLocationCFIEndpoints location: RDEPUBLocation) -> NSRange? {
guard let startCFI = RDEPUBCFICompatibility.parseLossy(location.cfi),
let endCFI = RDEPUBCFICompatibility.parseLossy(location.lastCFI ?? location.cfi),
let startAnchor = indexTable.anchor(for: startCFI),
let endAnchor = indexTable.anchor(for: endCFI),
startAnchor.fileIndex == endAnchor.fileIndex else {
return nil
}
let start = indexTable.chapterOffset(for: startAnchor)
let end = indexTable.chapterOffset(for: endAnchor)
return NSRange(location: min(start, end), length: max(abs(end - start), 1))
}
private func globalRange(fromLocationCFIEndpoints location: RDEPUBLocation) -> NSRange? {
guard let startCFI = RDEPUBCFICompatibility.parseLossy(location.cfi),
let endCFI = RDEPUBCFICompatibility.parseLossy(location.lastCFI ?? location.cfi),
let startAnchor = indexTable.anchor(for: startCFI),
let endAnchor = indexTable.anchor(for: endCFI),
startAnchor.fileIndex == endAnchor.fileIndex else {
return nil
}
let start = indexTable.globalIndex(for: startAnchor)
let end = indexTable.globalIndex(for: endAnchor)
return NSRange(location: min(start, end), length: max(abs(end - start), 1))
}
private func recoveredSearchRangeLength(
for searchMatch: RDEPUBSearchMatch,
cfi: RDEPUBCFI,
startOffset: Int
) -> Int {
let exactLength = cfi.textAssertion?.exact?.utf16.count ?? 0
let fallbackLength = max(searchMatch.rangeLength, 1)
let candidateLength = exactLength > 0 ? exactLength : fallbackLength
let remainingLength = max(attributedContent.length - startOffset, 1)
return min(max(candidateLength, 1), remainingLength)
}
}
@@ -4,18 +4,9 @@ import UIKit
import DTCoreText
#endif
/// DTCoreText EPUB HTML NSAttributedString
///
/// `RDEPUBTextRenderer`
/// HTML DTCoreText NSAttributedString fragment /
///
/// DTCoreText HTML
/// `willFlushCallback` DOM
/// DTCoreText 退
public struct RDEPUBDTCoreTextRenderer: RDEPUBTextRenderer {
public init() {}
/// DTCoreText
public static var isAvailable: Bool {
#if canImport(DTCoreText)
return true
@@ -24,7 +15,6 @@ public struct RDEPUBDTCoreTextRenderer: RDEPUBTextRenderer {
#endif
}
/// HTML NSAttributedString fragment
public func renderChapter(
request: RDEPUBTextChapterRenderRequest
) throws -> RDEPUBRenderedChapterContent {
@@ -56,7 +46,6 @@ public struct RDEPUBDTCoreTextRenderer: RDEPUBTextRenderer {
#endif
}
/// 便 HTML
public func renderChapter(
html: String,
baseURL: URL?,
@@ -65,6 +54,7 @@ public struct RDEPUBDTCoreTextRenderer: RDEPUBTextRenderer {
let request = RDEPUBTextTypesetterPipeline().makeRequest(
from: RDEPUBTypesettingInput(
href: "",
spineIndex: nil,
title: "",
rawHTML: html,
baseURL: baseURL,
@@ -75,7 +65,6 @@ public struct RDEPUBDTCoreTextRenderer: RDEPUBTextRenderer {
return try renderChapter(request: request)
}
/// 退 DTCoreText HTML
private func fallbackRenderedContent(request: RDEPUBTextChapterRenderRequest) -> RDEPUBRenderedChapterContent {
let attributedString = RDEPUBTextRendererSupport.fallbackAttributedString(for: request.context.html, style: request.style)
RDEPUBSemanticMarkerInjector.applyPaginationSemantics(in: attributedString)
@@ -93,7 +82,7 @@ public struct RDEPUBDTCoreTextRenderer: RDEPUBTextRenderer {
}
#if canImport(DTCoreText)
/// 使 DTCoreText HTML Data
private func makeAttributedString(from data: Data, request: RDEPUBTextChapterRenderRequest) -> NSAttributedString? {
let builder = DTHTMLAttributedStringBuilder(
html: data,
@@ -111,7 +100,6 @@ public struct RDEPUBDTCoreTextRenderer: RDEPUBTextRenderer {
return builder?.generatedAttributedString()
}
/// DTCoreText
private func dtOptions(request: RDEPUBTextChapterRenderRequest) -> [AnyHashable: Any] {
let style = request.style
let maxImageSize = resolvedMaxImageSize(for: request)
@@ -1,84 +1,46 @@
// RDEPUBTextPositionConverter.swift
// EPUB
import Foundation
/// WXRead `WREpubPositionConverter`
///
///
/// - `(fileIndex, row, column)`
/// -
/// -
/// - / `RDEPUBLocation`
public struct RDEPUBTextPositionConverter {
/// EPUB
public let book: RDEPUBTextBook
/// EPUB
/// - Parameter book: EPUB
public init(book: RDEPUBTextBook) {
self.book = book
}
///
public var totalCharacterCount: Int {
book.indexTable.totalCharacterCount
}
///
/// - Parameter anchor:
/// - Returns:
public func globalIndex(for anchor: RDEPUBTextAnchor) -> Int {
book.indexTable.globalIndex(for: anchor)
}
///
/// - Parameter rangeAnchor:
/// - Returns: `NSRange`
public func globalRange(for rangeAnchor: RDEPUBTextRangeAnchor) -> NSRange {
book.indexTable.globalRange(for: rangeAnchor)
}
///
/// - Parameter index:
/// - Returns: `nil`
public func fileIndex(forCharacterPosition index: Int) -> Int? {
book.indexTable.fileIndex(forCharacterPosition: index)
}
///
/// - Parameters:
/// - fileIndex:
/// - index:
/// - Returns: `nil`
public func localOffsetInFile(at fileIndex: Int, forGlobalPosition index: Int) -> Int? {
book.indexTable.localOffsetInFile(at: fileIndex, forGlobalPosition: index)
}
///
/// - Parameter index:
/// - Returns: `nil`
public func anchor(forCharacterPosition index: Int) -> RDEPUBTextAnchor? {
book.indexTable.anchor(forGlobalIndex: index)
}
/// `RDEPUBLocation`
/// - Parameter location: EPUB
/// - Returns: `nil`
public func anchor(for location: RDEPUBLocation) -> RDEPUBTextAnchor? {
book.indexTable.anchor(for: location)
}
/// 1
/// - Parameter anchor:
/// - Returns: `nil`
public func pageNumber(for anchor: RDEPUBTextAnchor) -> Int? {
book.indexTable.pageNumber(for: anchor, in: book).map { $0 + 1 }
}
/// 1
/// - Parameter index:
/// - Returns: `nil`
public func pageNumber(forCharacterPosition index: Int) -> Int? {
guard let anchor = anchor(forCharacterPosition: index) else {
return nil
@@ -86,11 +48,6 @@ public struct RDEPUBTextPositionConverter {
return pageNumber(for: anchor)
}
/// `RDEPUBLocation`
/// - Parameters:
/// - anchor:
/// - bookIdentifier: location `bookId`
/// - Returns: `RDEPUBLocation` `nil`
public func location(
for anchor: RDEPUBTextAnchor,
bookIdentifier: String?
@@ -101,11 +58,6 @@ public struct RDEPUBTextPositionConverter {
return book.indexTable.location(for: anchor, in: chapter, bookIdentifier: bookIdentifier)
}
/// `RDEPUBLocation`
/// - Parameters:
/// - rangeAnchor:
/// - bookIdentifier: location `bookId`
/// - Returns: `RDEPUBLocation` `nil`
public func location(
for rangeAnchor: RDEPUBTextRangeAnchor,
bookIdentifier: String?
@@ -1,71 +1,54 @@
import UIKit
// MARK: -
/// EPUBTextRendering 使 NSAttributedString
/// `RDEPUBTextRendererSupport`
/// `RDEPUBTextLayouter`
public extension NSAttributedString.Key {
/// NSString NSRange
static let rdPageBlockRange = NSAttributedString.Key("com.rdreader.epub.pageBlockRange")
///
static let rdPageBlockIndex = NSAttributedString.Key("com.rdreader.epub.pageBlockIndex")
/// fragment ID
static let rdPageFragmentID = NSAttributedString.Key("com.rdreader.epub.pageFragmentID")
/// /
static let rdPageAttachmentKind = NSAttributedString.Key("com.rdreader.epub.pageAttachmentKind")
/// ///
static let rdPageBlockKind = NSAttributedString.Key("com.rdreader.epub.pageBlockKind")
///
static let rdPageSemanticHints = NSAttributedString.Key("com.rdreader.epub.pageSemanticHints")
/// /线/
static let rdPageAttachmentPlacement = NSAttributedString.Key("com.rdreader.epub.pageAttachmentPlacement")
}
// MARK: -
/// HTML
public enum RDEPUBTextBlockKind: String, Codable, Equatable, CaseIterable {
case paragraph // <p>
case list // <ul>, <ol>, <li>
case table // <table>
case code // <pre>, <code>
case blockquote // <blockquote>
case attachment // figure
case generic // <div>, <h1>-<h6>
case paragraph
case list
case table
case code
case blockquote
case attachment
case generic
}
// MARK: -
/// /
public enum RDEPUBTextSemanticHint: String, Codable, Equatable, CaseIterable {
case avoidPageBreakInside //
case keepWithNext //
case pageBreakBefore //
case pageBreakAfter //
case pageRelate //
case avoidPageBreakInside
case keepWithNext
case pageBreakBefore
case pageBreakAfter
case pageRelate
}
// MARK: -
///
public enum RDEPUBTextAttachmentPlacement: String, Codable, Equatable {
case inline //
case baseline // 线
case centered //
case inline
case baseline
case centered
}
// MARK: -
///
public struct RDEPUBTextRenderStyle {
/// EPUB
public var font: UIFont
/// pt
public var lineSpacing: CGFloat
/// nil 使 EPUB
public var textColor: UIColor?
/// nil
public var backgroundColor: UIColor?
public init(font: UIFont, lineSpacing: CGFloat, textColor: UIColor? = nil, backgroundColor: UIColor? = nil) {
@@ -76,31 +59,28 @@ public struct RDEPUBTextRenderStyle {
}
}
// MARK: -
///
public struct RDEPUBTextLayoutConfig: Equatable {
/// 0 退 pageSize.width
public var frameWidth: CGFloat
/// 0 退 pageSize.height
public var frameHeight: CGFloat
/// WXRead WRCoreTextLayoutConfig.edgeInsets
public var edgeInsets: UIEdgeInsets
/// WXRead numberOfColumns
public var numberOfColumns: Int
/// WXRead columnGap
public var columnGap: CGFloat
///
public var avoidOrphans: Bool
///
public var avoidWidows: Bool
/// avoidPageBreakInside WXRead 退
public var avoidPageBreakInsideEnabled: Bool
/// WXRead hyphenation
public var hyphenation: Bool
///
public var imageMaxHeightRatio: CGFloat
/// pageSize viewport
public var fallbackViewportSize: CGSize
public init(
@@ -129,10 +109,8 @@ public struct RDEPUBTextLayoutConfig: Equatable {
self.fallbackViewportSize = fallbackViewportSize
}
///
public static let `default` = RDEPUBTextLayoutConfig()
/// pageSize
public func resolvedFrameSize(fallback pageSize: CGSize) -> CGSize {
CGSize(
width: max(frameWidth > 0 ? frameWidth : pageSize.width, 1),
@@ -140,13 +118,11 @@ public struct RDEPUBTextLayoutConfig: Equatable {
)
}
/// WXRead frame + edgeInsets
public func contentRect(fallback pageSize: CGSize) -> CGRect {
let size = resolvedFrameSize(fallback: pageSize)
return CGRect(origin: .zero, size: size).inset(by: edgeInsets)
}
///
public func columnRects(fallback pageSize: CGSize) -> [CGRect] {
let rect = contentRect(fallback: pageSize)
let columns = max(1, numberOfColumns)
@@ -161,7 +137,6 @@ public struct RDEPUBTextLayoutConfig: Equatable {
}
}
/// /使
public var cacheSignature: String {
[
String(format: "%.3f", frameWidth),
@@ -183,18 +158,14 @@ public struct RDEPUBTextLayoutConfig: Equatable {
}
}
// MARK: - CSS
/// CSS
public enum RDEPUBTextStyleSheetLayerKind: String, CaseIterable, Equatable {
case `default` // marginpadding
case replace //
case dark //
case epub // EPUB
case user //
case `default`
case replace
case dark
case epub
case user
}
/// CSS CSS
public struct RDEPUBTextStyleSheetLayer: Equatable {
public var kind: RDEPUBTextStyleSheetLayerKind
public var css: String
@@ -205,9 +176,6 @@ public struct RDEPUBTextStyleSheetLayer: Equatable {
}
}
/// CSS CSS
///
/// CSS default replace dark epub user
public struct RDEPUBTextStyleSheetPackage: Equatable {
public var layers: [RDEPUBTextStyleSheetLayer]
@@ -215,7 +183,6 @@ public struct RDEPUBTextStyleSheetPackage: Equatable {
self.layers = layers
}
/// CSS
public var combinedCSS: String {
layers
.filter { !$0.css.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
@@ -226,15 +193,11 @@ public struct RDEPUBTextStyleSheetPackage: Equatable {
}
}
// MARK: -
///
public enum RDEPUBTextResourceReferenceKind: String, Equatable {
case stylesheet
case image
}
/// EPUB
public struct RDEPUBTextResourceReferenceDiagnostic: Equatable {
public var kind: RDEPUBTextResourceReferenceKind
public var chapterHref: String
@@ -260,9 +223,6 @@ public struct RDEPUBTextResourceReferenceDiagnostic: Equatable {
}
}
// MARK: -
/// HTML
public struct RDEPUBTextChapterContext: Equatable {
public var href: String
public var title: String
@@ -270,6 +230,7 @@ public struct RDEPUBTextChapterContext: Equatable {
public var baseURL: URL?
public var stylesheet: RDEPUBTextStyleSheetPackage
public var resourceDiagnostics: [RDEPUBTextResourceReferenceDiagnostic]
public var styleCompatibilityReport: RDEPUBCSSCompatibilityReport
public init(
href: String,
@@ -277,7 +238,8 @@ public struct RDEPUBTextChapterContext: Equatable {
html: String,
baseURL: URL?,
stylesheet: RDEPUBTextStyleSheetPackage,
resourceDiagnostics: [RDEPUBTextResourceReferenceDiagnostic]
resourceDiagnostics: [RDEPUBTextResourceReferenceDiagnostic],
styleCompatibilityReport: RDEPUBCSSCompatibilityReport = RDEPUBCSSCompatibilityReport()
) {
self.href = href
self.title = title
@@ -285,16 +247,16 @@ public struct RDEPUBTextChapterContext: Equatable {
self.baseURL = baseURL
self.stylesheet = stylesheet
self.resourceDiagnostics = resourceDiagnostics
self.styleCompatibilityReport = styleCompatibilityReport
}
}
/// `RDEPUBTextRenderer`
public struct RDEPUBTextChapterRenderRequest {
public var context: RDEPUBTextChapterContext
public var style: RDEPUBTextRenderStyle
/// page size
public var pageSize: CGSize?
/// WXRead
public var layoutConfig: RDEPUBTextLayoutConfig?
public init(
@@ -310,15 +272,12 @@ public struct RDEPUBTextChapterRenderRequest {
}
}
// MARK: -
/// fragment
public struct RDEPUBRenderedChapterContent {
///
public var attributedString: NSAttributedString
/// fragment ID
public var fragmentOffsets: [String: Int]
///
public var resourceDiagnostics: [RDEPUBTextResourceReferenceDiagnostic]
public init(
@@ -332,18 +291,12 @@ public struct RDEPUBRenderedChapterContent {
}
}
// MARK: -
/// EPUB HTML NSAttributedString
///
/// `RDEPUBDTCoreTextRenderer` DTCoreText
public protocol RDEPUBTextRenderer {
///
func renderChapter(
request: RDEPUBTextChapterRenderRequest
) throws -> RDEPUBRenderedChapterContent
/// 便 HTML
func renderChapter(
html: String,
baseURL: URL?,
@@ -351,7 +304,6 @@ public protocol RDEPUBTextRenderer {
) throws -> RDEPUBRenderedChapterContent
}
/// 便
public extension RDEPUBTextRenderer {
func renderChapter(
html: String,
@@ -370,12 +322,9 @@ public extension RDEPUBTextRenderer {
}
}
// MARK: -
/// EPUB
public enum RDEPUBTextRenderingError: LocalizedError {
case htmlEncodingFailed // HTML Data
case htmlImportFailed // HTML
case htmlEncodingFailed
case htmlImportFailed
public var errorDescription: String? {
switch self {
@@ -1,10 +1,5 @@
import Foundation
/// EPUB
///
/// `RDEPUBSearchEngine`
/// 使
///
final class RDEPUBTextSearchEngine: RDEPUBSearchEngine {
private let textBook: RDEPUBTextBook
private let publication: RDEPUBPublication
@@ -14,14 +9,6 @@ final class RDEPUBTextSearchEngine: RDEPUBSearchEngine {
self.publication = publication
}
///
///
///
/// 1.
/// 2.
/// 3. progression
/// 4. 12
/// 5. /
func search(keyword: String) -> [RDEPUBSearchMatch] {
let normalizedKeyword = keyword.trimmingCharacters(in: .whitespacesAndNewlines)
guard !normalizedKeyword.isEmpty else {
@@ -49,6 +36,7 @@ final class RDEPUBTextSearchEngine: RDEPUBSearchEngine {
let progressionDenominator = max(fullLength - 1, 1)
let progression = Double(foundRange.location) / Double(progressionDenominator)
let rangeAnchor = chapterData.rangeAnchor(for: foundRange)
matches.append(
RDEPUBSearchMatch(
href: normalizedHref,
@@ -57,7 +45,9 @@ final class RDEPUBTextSearchEngine: RDEPUBSearchEngine {
localMatchIndex: localMatchIndex,
rangeLocation: foundRange.location,
rangeLength: foundRange.length,
rangeAnchor: chapterData.rangeAnchor(for: foundRange)
rangeAnchor: rangeAnchor,
cfi: chapterData.indexTable.cfi(for: rangeAnchor.start)?.rawValue,
rangeCFI: chapterData.indexTable.cfiRange(for: rangeAnchor)?.rawValue
)
)
@@ -73,7 +63,6 @@ final class RDEPUBTextSearchEngine: RDEPUBSearchEngine {
return matches
}
/// 12
private func previewText(in text: NSString, matchRange: NSRange) -> String {
let previewRadius = 12
let start = max(matchRange.location - previewRadius, 0)
@@ -82,13 +71,16 @@ final class RDEPUBTextSearchEngine: RDEPUBSearchEngine {
return text.substring(with: range).trimmingCharacters(in: .whitespacesAndNewlines)
}
/// publication txt
static func searchWithoutPublication(textBook: RDEPUBTextBook, keyword: String) -> [RDEPUBSearchMatch] {
let normalizedKeyword = keyword.trimmingCharacters(in: .whitespacesAndNewlines)
guard !normalizedKeyword.isEmpty else { return [] }
var matches: [RDEPUBSearchMatch] = []
for chapter in textBook.chapters {
let chapterData = RDEPUBChapterData(
chapter: chapter,
indexTable: RDEPUBTextIndexTable(chapters: [chapter])
)
let source = chapter.attributedContent.string as NSString
let fullLength = source.length
guard fullLength > 0 else { continue }
@@ -102,6 +94,9 @@ final class RDEPUBTextSearchEngine: RDEPUBSearchEngine {
let progressionDenominator = max(fullLength - 1, 1)
let progression = Double(foundRange.location) / Double(progressionDenominator)
let rangeAnchor = chapterData.rangeAnchor(for: foundRange)
let cfi = chapterData.indexTable.cfi(for: rangeAnchor.start)
let cfiRange = chapterData.indexTable.cfiRange(for: rangeAnchor)
let previewRadius = 12
let previewStart = max(foundRange.location - previewRadius, 0)
let previewEnd = min(foundRange.location + foundRange.length + previewRadius, fullLength)
@@ -116,7 +111,9 @@ final class RDEPUBTextSearchEngine: RDEPUBSearchEngine {
localMatchIndex: localMatchIndex,
rangeLocation: foundRange.location,
rangeLength: foundRange.length,
rangeAnchor: nil
rangeAnchor: rangeAnchor,
cfi: cfi?.rawValue ?? cfiRange?.start.rawValue,
rangeCFI: cfiRange?.rawValue
)
)
@@ -1,16 +1,5 @@
import UIKit
/// TXT RDEPUBTextBook EPUB 线
///
/// .txt EPUB
/// 使 EPUBReader
///
///
/// 1. UTF-8 GB18030 GBK
/// 2.
/// 3. HTML
/// 4. DTCoreText
/// 5. CoreText RDEPUBTextBook
public final class RDPlainTextBookBuilder {
private let renderer: RDEPUBTextRenderer
private let layoutConfig: RDEPUBTextLayoutConfig
@@ -23,13 +12,6 @@ public final class RDPlainTextBookBuilder {
self.layoutConfig = layoutConfig
}
///
///
/// - Parameters:
/// - textFileURL: URL
/// - pageSize:
/// - style:
/// - Returns:
public func build(
textFileURL: URL,
pageSize: CGSize,
@@ -109,6 +91,7 @@ public final class RDPlainTextBookBuilder {
title: spec.title ?? "\(index + 1)",
attributedContent: chapterAttributedContent,
fragmentOffsets: [:],
cfiMap: nil,
pageBreakReasons: pages.map { $0.metadata.breakReason },
pages: pages
)
@@ -119,16 +102,11 @@ public final class RDPlainTextBookBuilder {
return RDEPUBTextBook(chapters: chapters, pages: flatPages)
}
// MARK: -
/// +
private struct ChapterSpec {
let title: String?
let content: String
}
/// "X///"
///
private func splitChapters(from text: String) -> [ChapterSpec] {
let pattern = #"^(第[零一二三四五六七八九十百千万\d]+[章节回卷].*)$"#
guard let regex = try? NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines]) else {
@@ -154,25 +132,18 @@ public final class RDPlainTextBookBuilder {
}
}
//
if specs.isEmpty {
return [ChapterSpec(title: nil, content: text)]
}
return specs
}
// MARK: - HTML
/// HTML `<p>`
private func wrapTextAsHTML(_ text: String) -> String {
let paragraphs = text.components(separatedBy: "\n").filter { !$0.isEmpty }
let body = paragraphs.map { "<p>\($0)</p>" }.joined(separator: "\n")
return "<html><body>\(body)</body></html>"
}
// MARK: -
/// UTF-8 GB18030 GBK
private func rd_decodeTextFile(url: URL) -> String {
if let content = try? NSString(contentsOf: url, encoding: String.Encoding.utf8.rawValue) as String {
return content
@@ -0,0 +1,136 @@
import Foundation
struct RDEPUBCSSCompatibilityLayer {
var policy = RDEPUBStyleCompatibilityPolicy()
func sanitize(_ css: String) -> RDEPUBCSSCompatibilityResult {
var rewritten = css
var normalized: [String] = []
var unsupported: [String] = []
if policy.normalizeLineHeight {
let result = clampNumericProperty(
in: rewritten,
property: "line-height",
minValue: 0.9,
maxValue: 2.4
)
rewritten = result.css
normalized += result.normalizedRules
}
if policy.normalizeTextIndent {
let result = clampLengthProperty(
in: rewritten,
property: "text-indent",
maxAbsolutePX: 64
)
rewritten = result.css
normalized += result.normalizedRules
}
if !policy.allowPublisherMargins {
let result = clampLengthProperty(
in: rewritten,
property: "margin",
maxAbsolutePX: 64
)
rewritten = result.css
normalized += result.normalizedRules
}
if policy.fallbackUnsupportedWritingModes,
rewritten.range(of: "writing-mode", options: [.caseInsensitive]) != nil {
unsupported.append("writing-mode")
rewritten += "\n\nhtml, body { writing-mode: horizontal-tb !important; }"
normalized.append("writing-mode")
}
if policy.clampImagesToViewport {
rewritten += """
img, svg, table, video, canvas {
max-width: 100% !important;
height: auto !important;
box-sizing: border-box !important;
}
table {
overflow-wrap: anywhere;
border-collapse: collapse;
}
"""
normalized.append("media-size-clamp")
}
return RDEPUBCSSCompatibilityResult(
css: rewritten,
report: RDEPUBCSSCompatibilityReport(
unsupportedRules: unsupported,
normalizedRules: normalized,
fontFailures: []
)
)
}
private func clampNumericProperty(
in css: String,
property: String,
minValue: Double,
maxValue: Double
) -> (css: String, normalizedRules: [String]) {
guard let regex = try? NSRegularExpression(
pattern: #"(?i)\b"# + NSRegularExpression.escapedPattern(for: property) + #"\s*:\s*([0-9]*\.?[0-9]+)\s*;"#
) else {
return (css, [])
}
let nsCSS = css as NSString
var rewritten = css
var normalized: [String] = []
for match in regex.matches(in: css, range: NSRange(location: 0, length: nsCSS.length)).reversed() {
guard match.numberOfRanges > 1 else { continue }
let rawValue = nsCSS.substring(with: match.range(at: 1))
guard let value = Double(rawValue), value < minValue || value > maxValue else { continue }
let clamped = min(max(value, minValue), maxValue)
if let range = Range(match.range, in: rewritten) {
rewritten.replaceSubrange(range, with: "\(property): \(String(format: "%.3f", clamped));")
normalized.append(property)
}
}
return (rewritten, normalized)
}
private func clampLengthProperty(
in css: String,
property: String,
maxAbsolutePX: Double
) -> (css: String, normalizedRules: [String]) {
guard let regex = try? NSRegularExpression(
pattern: #"(?i)\b"# + NSRegularExpression.escapedPattern(for: property) + #"\s*:\s*(-?[0-9]*\.?[0-9]+)px\s*;"#
) else {
return (css, [])
}
let nsCSS = css as NSString
var rewritten = css
var normalized: [String] = []
for match in regex.matches(in: css, range: NSRange(location: 0, length: nsCSS.length)).reversed() {
guard match.numberOfRanges > 1 else { continue }
let rawValue = nsCSS.substring(with: match.range(at: 1))
guard let value = Double(rawValue), abs(value) > maxAbsolutePX else { continue }
let clamped = value < 0 ? -maxAbsolutePX : maxAbsolutePX
if let range = Range(match.range, in: rewritten) {
rewritten.replaceSubrange(range, with: "\(property): \(String(format: "%.0f", clamped))px;")
normalized.append(property)
}
}
return (rewritten, normalized)
}
}
@@ -0,0 +1,21 @@
import UIKit
struct RDEPUBFontFallbackResolver {
static func fallbackChain(requestedFamily: String?, embeddedFamily: String?) -> RDEPUBFontFallbackChain {
let preferredCJK = ["PingFang SC", "Heiti SC", "Songti SC"]
let preferredLatin = ["Times New Roman", "Georgia", "Helvetica Neue"]
return RDEPUBFontFallbackChain(
requestedFamily: requestedFamily,
embeddedFamily: embeddedFamily,
systemFallbacks: preferredCJK + preferredLatin,
finalFallback: UIFont.systemFont(ofSize: UIFont.systemFontSize).familyName
)
}
static func resolveFont(sourceFont: UIFont?, baseFont: UIFont) -> UIFont {
RDEPUBFontNormalizer.normalizedFont(from: sourceFont, baseFont: baseFont)
}
}
@@ -0,0 +1,101 @@
import Foundation
public struct RDEPUBStyleCompatibilityPolicy: Equatable {
public var allowPublisherFonts: Bool
public var allowPublisherMargins: Bool
public var normalizeLineHeight: Bool
public var normalizeTextIndent: Bool
public var clampImagesToViewport: Bool
public var fallbackUnsupportedWritingModes: Bool
public init(
allowPublisherFonts: Bool = true,
allowPublisherMargins: Bool = true,
normalizeLineHeight: Bool = true,
normalizeTextIndent: Bool = true,
clampImagesToViewport: Bool = true,
fallbackUnsupportedWritingModes: Bool = true
) {
self.allowPublisherFonts = allowPublisherFonts
self.allowPublisherMargins = allowPublisherMargins
self.normalizeLineHeight = normalizeLineHeight
self.normalizeTextIndent = normalizeTextIndent
self.clampImagesToViewport = clampImagesToViewport
self.fallbackUnsupportedWritingModes = fallbackUnsupportedWritingModes
}
}
public struct RDEPUBFontFallbackChain: Codable, Equatable {
public var requestedFamily: String?
public var embeddedFamily: String?
public var systemFallbacks: [String]
public var finalFallback: String
public init(
requestedFamily: String? = nil,
embeddedFamily: String? = nil,
systemFallbacks: [String] = ["PingFang SC", "Heiti SC", "Times New Roman"],
finalFallback: String = ".AppleSystemUIFont"
) {
self.requestedFamily = requestedFamily
self.embeddedFamily = embeddedFamily
self.systemFallbacks = systemFallbacks
self.finalFallback = finalFallback
}
}
public struct RDEPUBEmbeddedFontDescriptor: Codable, Equatable {
public var family: String?
public var href: String
public var format: String?
public var weight: Int?
public var style: String?
}
public struct RDEPUBFontRegistrationResult: Codable, Equatable {
public var descriptor: RDEPUBEmbeddedFontDescriptor
public var fileURL: URL?
public var didRegister: Bool
public var errorDescription: String?
}
public struct RDEPUBCSSCompatibilityReport: Codable, Equatable {
public var unsupportedRules: [String]
public var normalizedRules: [String]
public var fontFailures: [String]
public init(unsupportedRules: [String] = [], normalizedRules: [String] = [], fontFailures: [String] = []) {
self.unsupportedRules = unsupportedRules
self.normalizedRules = normalizedRules
self.fontFailures = fontFailures
}
}
struct RDEPUBCSSCompatibilityResult {
var css: String
var report: RDEPUBCSSCompatibilityReport
}
@@ -4,14 +4,14 @@ import UIKit
import DTCoreText
#endif
///
struct RDEPUBAttachmentNormalizer {
///
private static var didLogFootnoteAttachment = false
///
private static var didLogCoverAttachment = false
#if canImport(DTCoreText)
func normalize(
_ attachment: DTTextAttachment,
fontPointSize: CGFloat,
@@ -25,23 +25,28 @@ struct RDEPUBAttachmentNormalizer {
}
#endif
// MARK: - DTCoreText
#if canImport(DTCoreText)
/// DTTextAttachment
static func normalizeAttachmentLayoutForWXRead(
_ attachment: DTTextAttachment,
fontPointSize: CGFloat,
maxImageSize: CGSize? = nil
) {
let pointSize = max(fontPointSize, 1)
let originalSize = attachment.originalSize
if isFootnoteAttachment(attachment) {
let targetWidth = max(round(pointSize), 1)
let aspectRatio = originalSize.height > 0 ? originalSize.width / originalSize.height : 1
let targetHeight = max(round(targetWidth / max(aspectRatio, 0.1)), 1)
attachment.displaySize = CGSize(width: targetWidth, height: targetHeight)
attachment.verticalAlignment = .baseline
if !didLogFootnoteAttachment {
@@ -54,16 +59,20 @@ struct RDEPUBAttachmentNormalizer {
}
if isCoverAttachment(attachment) {
let maxSize = maxImageSize ?? defaultMaxImageSize(fontPointSize: pointSize)
if originalSize.width > 0, originalSize.height > 0 {
let scale = min(maxSize.width / originalSize.width, maxSize.height / originalSize.height)
attachment.displaySize = CGSize(
width: round(originalSize.width * scale),
height: round(originalSize.height * scale)
)
} else {
attachment.displaySize = maxSize
}
attachment.verticalAlignment = .baseline
if !didLogCoverAttachment {
@@ -76,9 +85,11 @@ struct RDEPUBAttachmentNormalizer {
}
var resolvedSize = attachment.displaySize
if resolvedSize.width <= 0 || resolvedSize.height <= 0 {
resolvedSize = originalSize
}
if resolvedSize.width <= 0 || resolvedSize.height <= 0 {
resolvedSize = CGSize(width: pointSize, height: pointSize)
}
@@ -87,6 +98,7 @@ struct RDEPUBAttachmentNormalizer {
resolvedSize.width > 0,
resolvedSize.height > 0,
(resolvedSize.width > maxImageSize.width || resolvedSize.height > maxImageSize.height) {
let scale = min(maxImageSize.width / resolvedSize.width, maxImageSize.height / resolvedSize.height)
resolvedSize = CGSize(
width: round(resolvedSize.width * scale),
@@ -95,26 +107,31 @@ struct RDEPUBAttachmentNormalizer {
}
attachment.displaySize = CGSize(width: round(resolvedSize.width), height: round(resolvedSize.height))
attachment.verticalAlignment = .center
}
/// DTCoreText willFlushCallback
static func prepareHTMLElementForReaderRendering(
_ element: DTHTMLElement,
style: RDEPUBTextRenderStyle,
maxImageSize: CGSize? = nil
) {
guard let attachment = element.textAttachment else { return }
let pointSize = max(element.fontDescriptor.pointSize, style.font.pointSize)
let fallbackSize = CGSize(
width: defaultMaxImageSize(fontPointSize: pointSize).width,
height: defaultMaxImageSize(fontPointSize: pointSize).height
)
normalizeAttachmentLayoutForWXRead(
attachment,
fontPointSize: pointSize,
maxImageSize: maxImageSize ?? fallbackSize
)
if isFootnoteAttachment(attachment) {
element.displayStyle = .inline
} else if isCoverAttachment(attachment) {
@@ -123,23 +140,31 @@ struct RDEPUBAttachmentNormalizer {
}
private static func isFootnoteAttachment(_ attachment: DTTextAttachment) -> Bool {
let lowercasedClasses = ((attachment.attributes["class"] as? String) ?? "").lowercased()
let lowercasedPath = attachment.contentURL?.lastPathComponent.lowercased()
?? ((attachment.attributes["src"] as? String) ?? "").lowercased()
return lowercasedClasses.contains("qqreader-footnote") || lowercasedPath == "note.png"
}
private static func isCoverAttachment(_ attachment: DTTextAttachment) -> Bool {
let lowercasedClasses = ((attachment.attributes["class"] as? String) ?? "").lowercased()
let lowercasedPath = attachment.contentURL?.lastPathComponent.lowercased()
?? ((attachment.attributes["src"] as? String) ?? "").lowercased()
return lowercasedClasses.contains("rd-front-cover-image") || lowercasedPath == "cover.jpg"
}
private static func defaultMaxImageSize(fontPointSize: CGFloat) -> CGSize {
let referenceViewport = CGSize(width: 375, height: 667)
let horizontalInset = max(round(fontPointSize), 16)
let verticalInset = max(round(fontPointSize * 1.5), 28)
return CGSize(
width: max(round(referenceViewport.width - horizontalInset * 2), 1),
height: max(round((referenceViewport.height - verticalInset * 2) * 0.85), 1)
@@ -147,16 +172,15 @@ struct RDEPUBAttachmentNormalizer {
}
#endif
// MARK: -
/// NSAttributedString
static func normalizeAttachmentDisplayIfNeeded(
in attributes: inout [NSAttributedString.Key: Any],
font: UIFont
) {
guard let attachment = attributes[.attachment] else { return }
#if canImport(DTCoreText)
if let textAttachment = attachment as? DTTextAttachment {
normalizeAttachmentLayoutForWXRead(textAttachment, fontPointSize: font.pointSize)
attributes[.attachment] = textAttachment
@@ -165,15 +189,17 @@ struct RDEPUBAttachmentNormalizer {
#endif
if let textAttachment = attachment as? NSTextAttachment, textAttachment.bounds.height <= 0 {
let targetHeight = max(round(font.pointSize * 0.86), 1)
textAttachment.bounds = CGRect(x: 0, y: 0, width: targetHeight, height: targetHeight)
attributes[.attachment] = textAttachment
}
}
///
static func attachmentKind(for attributes: [NSAttributedString.Key: Any]) -> RDEPUBTextAttachmentKind? {
if let attachment = attributes[.attachment] as? NSTextAttachment {
if attachment.image != nil || attachment.fileType?.lowercased().contains("image") == true {
return .image
}
@@ -182,6 +208,7 @@ struct RDEPUBAttachmentNormalizer {
for value in attributes.values {
let typeName = String(describing: type(of: value)).lowercased()
if typeName.contains("attachment") {
return typeName.contains("image") ? .image : .generic
}
@@ -0,0 +1,59 @@
import Foundation
struct RDEPUBCFIMarkerInjector: RDEPUBTypesettingStage {
func process(_ html: String, context: RDEPUBTypesettingInput) -> String {
guard let regex = try? NSRegularExpression(
pattern: #"<([A-Za-z][A-Za-z0-9:_-]*)([^>]*\s(?:id|xml:id)\s*=\s*['"]([^'"]+)['"][^>]*)>"#,
options: [.caseInsensitive]
) else {
return html
}
let nsHTML = html as NSString
let matches = regex.matches(in: html, range: NSRange(location: 0, length: nsHTML.length))
guard !matches.isEmpty else { return html }
var rewritten = html
for match in matches.reversed() {
guard match.numberOfRanges > 3,
let fullRange = Range(match.range(at: 0), in: rewritten),
let tagNameRange = Range(match.range(at: 1), in: html),
let attributesRange = Range(match.range(at: 2), in: html),
let fragmentRange = Range(match.range(at: 3), in: html) else {
continue
}
let tagName = String(html[tagNameRange])
let attributes = String(html[attributesRange])
let fragmentID = String(html[fragmentRange])
guard attributes.range(of: "data-rd-cfi-marker", options: [.caseInsensitive]) == nil else {
continue
}
let marker = RDEPUBCFIGenerator.makeOffsetCFI(
href: context.href,
fileIndex: context.spineIndex ?? 0,
chapterOffset: 0,
fragmentID: fragmentID
).rawValue
let replacement = "<\(tagName)\(attributes) data-rd-cfi-marker=\"\(Self.escapeAttribute(marker))\">"
rewritten.replaceSubrange(fullRange, with: replacement)
}
return rewritten
}
private static func escapeAttribute(_ value: String) -> String {
value
.replacingOccurrences(of: "&", with: "&amp;")
.replacingOccurrences(of: "\"", with: "&quot;")
.replacingOccurrences(of: "<", with: "&lt;")
.replacingOccurrences(of: ">", with: "&gt;")
}
}
@@ -1,16 +1,18 @@
import UIKit
import CoreText
/// EPUB
struct RDEPUBFontNormalizer {
/// CTFontManager
private static var registeredFontPaths = Set<String>()
@discardableResult
func registerEmbeddedFonts(
html: String,
inlinedCSS: String,
input: RDEPUBTypesettingInput
) {
) -> [RDEPUBFontRegistrationResult] {
Self.registerEmbeddedFonts(
in: inlinedCSS + "\n" + Self.inlineStyleCSS(in: html),
chapterHref: input.href,
@@ -18,70 +20,119 @@ struct RDEPUBFontNormalizer {
)
}
// MARK: -
/// CSS @font-face
@discardableResult
static func registerEmbeddedFonts(
in css: String,
chapterHref: String,
resourceResolver: RDEPUBResourceResolver?
) {
) -> [RDEPUBFontRegistrationResult] {
guard let resourceResolver,
let faceRegex = try? NSRegularExpression(pattern: #"@font-face\s*\{([\s\S]*?)\}"#, options: [.caseInsensitive]),
let urlRegex = try? NSRegularExpression(pattern: #"url\(([^)]+)\)"#, options: [.caseInsensitive]) else {
return
return []
}
var results: [RDEPUBFontRegistrationResult] = []
let nsCSS = css as NSString
for faceMatch in faceRegex.matches(in: css, range: NSRange(location: 0, length: nsCSS.length)) {
guard faceMatch.numberOfRanges > 1 else { continue }
let block = nsCSS.substring(with: faceMatch.range(at: 1))
let nsBlock = block as NSString
let family = declarationValue(named: "font-family", in: block)?
.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
let weight = declarationValue(named: "font-weight", in: block).flatMap(Int.init)
let style = declarationValue(named: "font-style", in: block)
for urlMatch in urlRegex.matches(in: block, range: NSRange(location: 0, length: nsBlock.length)) {
guard urlMatch.numberOfRanges > 1 else { continue }
let rawReference = nsBlock.substring(with: urlMatch.range(at: 1))
.trimmingCharacters(in: CharacterSet(charactersIn: "\"' \n\r\t"))
let descriptor = RDEPUBEmbeddedFontDescriptor(
family: family,
href: rawReference,
format: nil,
weight: weight,
style: style
)
guard !rawReference.isEmpty,
!rawReference.hasPrefix("data:"),
!rawReference.hasPrefix("http://"),
!rawReference.hasPrefix("https://"),
!rawReference.hasPrefix("http:"),
!rawReference.hasPrefix("https:"),
let fileURL = resourceResolver.fileURL(forReference: rawReference, relativeToHref: chapterHref) else {
results.append(
RDEPUBFontRegistrationResult(
descriptor: descriptor,
fileURL: nil,
didRegister: false,
errorDescription: "Font URL could not be resolved"
)
)
continue
}
registerFontIfNeeded(at: fileURL)
let didRegister = registerFontIfNeeded(at: fileURL)
results.append(
RDEPUBFontRegistrationResult(
descriptor: descriptor,
fileURL: fileURL,
didRegister: didRegister,
errorDescription: didRegister ? nil : "Font was already registered or registration failed"
)
)
}
}
return results
}
/// CTFontManager
/// - Parameter fileURL: URL
static func registerFontIfNeeded(at fileURL: URL) {
@discardableResult
static func registerFontIfNeeded(at fileURL: URL) -> Bool {
let standardizedPath = fileURL.standardizedFileURL.path
guard !registeredFontPaths.contains(standardizedPath) else { return }
CTFontManagerRegisterFontsForURL(fileURL as CFURL, .process, nil)
registeredFontPaths.insert(standardizedPath)
guard !registeredFontPaths.contains(standardizedPath) else { return true }
let registered = CTFontManagerRegisterFontsForURL(fileURL as CFURL, .process, nil)
if registered {
registeredFontPaths.insert(standardizedPath)
}
return registered
}
// MARK: -
/// EPUB /
static func normalizedFont(from sourceFont: UIFont?, baseFont: UIFont) -> UIFont {
guard let sourceFont else {
return baseFont
}
let traits = sourceFont.fontDescriptor.symbolicTraits.intersection([.traitBold, .traitItalic])
if let descriptor = baseFont.fontDescriptor.withSymbolicTraits(traits) {
return UIFont(descriptor: descriptor, size: baseFont.pointSize)
}
return baseFont
}
/// HTML <style> CSS
static func inlineStyleCSS(in html: String) -> String {
guard let regex = try? NSRegularExpression(pattern: #"<style\b[^>]*>([\s\S]*?)</style>"#, options: [.caseInsensitive]) else {
return ""
}
let nsHTML = html as NSString
return regex.matches(in: html, range: NSRange(location: 0, length: nsHTML.length))
.compactMap { match in
guard match.numberOfRanges > 1 else { return nil }
@@ -89,4 +140,21 @@ struct RDEPUBFontNormalizer {
}
.joined(separator: "\n")
}
private static func declarationValue(named name: String, in block: String) -> String? {
guard let regex = try? NSRegularExpression(
pattern: #"(?i)\b"# + NSRegularExpression.escapedPattern(for: name) + #"\s*:\s*([^;]+)"#
) else {
return nil
}
let nsBlock = block as NSString
guard let match = regex.firstMatch(in: block, range: NSRange(location: 0, length: nsBlock.length)),
match.numberOfRanges > 1 else {
return nil
}
return nsBlock.substring(with: match.range(at: 1)).trimmingCharacters(in: .whitespacesAndNewlines)
}
}
@@ -1,26 +1,16 @@
/// RDEPUBFragmentMarkerInjector - Fragment
import Foundation
/// Fragment HTML fragment
///
///
/// 1. `process` HTML `id` `${id=xxx}`
/// 2. `extractOffsets` NSAttributedString
struct RDEPUBFragmentMarkerInjector: RDEPUBTypesettingStage {
/// HTML id fragment 使
func process(_ html: String, context: RDEPUBTypesettingInput) -> String {
Self.injectFragmentMarkers(into: html)
}
/// `${id=xxx}` fragment ID
func extractOffsets(from attributedString: NSMutableAttributedString) -> [String: Int] {
Self.extractFragmentOffsets(from: attributedString)
}
// MARK: - Fragment
/// HTML id fragment
/// `<tag id="xxx" ...>` `${id=xxx}<tag id="xxx" ...>`
static func injectFragmentMarkers(into html: String) -> String {
guard let regex = try? NSRegularExpression(pattern: #"(<[^>]+\sid="([^"]+)"[^>]*>)"#, options: [.caseInsensitive]) else {
return html
@@ -33,32 +23,43 @@ struct RDEPUBFragmentMarkerInjector: RDEPUBTypesettingStage {
)
}
// MARK: - Fragment 偏移量提取
/// 从渲染后的富文本中提取 fragment 偏移量映射。
/// 扫描 `${id=xxx}` 标记,记录偏移量,然后删除标记文本。
static func extractFragmentOffsets(from attributedString: NSMutableAttributedString) -> [String: Int] {
let markerPattern = #"\$\{id=([^}]+)\}"#
guard let regex = try? NSRegularExpression(pattern: markerPattern, options: []) else {
return [:]
}
let mutableString = NSMutableString(string: attributedString.string)
var fragmentOffsets: [String: Int] = [:]
var searchRange = NSRange(location: 0, length: mutableString.length)
var offsetAdjustment = 0
while let match = regex.firstMatch(in: mutableString as String, options: [], range: searchRange) {
let fullMatch = mutableString.substring(with: match.range) as NSString
let fragmentID = fullMatch
.replacingOccurrences(of: #"\$\{id="#, with: "", options: .regularExpression, range: NSRange(location: 0, length: fullMatch.length))
.replacingOccurrences(of: #"\}"#, with: "", options: .regularExpression)
let adjustedLocation = max(0, match.range.location + offsetAdjustment)
fragmentOffsets[fragmentID] = adjustedLocation
attributedString.deleteCharacters(in: match.range)
mutableString.deleteCharacters(in: match.range)
offsetAdjustment -= match.range.length
searchRange = NSRange(location: match.range.location, length: mutableString.length - match.range.location)
}
@@ -1,25 +1,18 @@
import Foundation
/// HTML HTML
struct RDEPUBHTMLNormalizer: RDEPUBTypesettingStage {
/// HTML
/// - Parameters:
/// - html: HTML
/// - context:
/// - Returns: HTML
func process(_ html: String, context: RDEPUBTypesettingInput) -> String {
Self.normalizeHTML(html)
}
// MARK: - HTML
/// CR HTML
static func normalizeHTML(_ html: String) -> String {
var cleanedHTML = html
let replacements: [(pattern: String, template: String)] = [
(#"<hr\s+lang="zh-CN">分页符</hr>"#, ""),
(#"\r"#, "\n"),
(#"\n+"#, "\n")
(#"<hr\s+lang="zh-CN">分页符</hr>"#, ""),
(#"\r"#, "\n"),
(#"\n+"#, "\n")
]
for replacement in replacements {
@@ -37,9 +30,6 @@ struct RDEPUBHTMLNormalizer: RDEPUBTypesettingStage {
return cleanedHTML
}
// MARK: - HTML
/// bodyPic div img h1+img HTML
private static func normalizeAttachmentHTMLMarkers(in html: String) -> String {
var normalized = html
@@ -51,10 +41,12 @@ struct RDEPUBHTMLNormalizer: RDEPUBTypesettingStage {
using: bodyPicContainerRegex,
in: normalized
) { tag in
guard let imageTagRegex = try? NSRegularExpression(pattern: #"<img\b[^>]*>"#, options: [.caseInsensitive]) else {
return tag
}
return replaceMatches(
using: imageTagRegex,
in: tag
@@ -75,6 +67,7 @@ struct RDEPUBHTMLNormalizer: RDEPUBTypesettingStage {
}
}
if let footnoteRegex = try? NSRegularExpression(
pattern: #"<img\b([^>]*class\s*=\s*["'][^"']*\bqqreader-footnote\b[^"']*["'][^>]*)>"#,
options: [.caseInsensitive]
@@ -83,6 +76,7 @@ struct RDEPUBHTMLNormalizer: RDEPUBTypesettingStage {
using: footnoteRegex,
in: normalized
) { tag in
mergeHTMLAttributes(
into: tag,
requiredClass: nil,
@@ -96,6 +90,7 @@ struct RDEPUBHTMLNormalizer: RDEPUBTypesettingStage {
}
}
if let coverRegex = try? NSRegularExpression(
pattern: #"<h1\b([^>]*class\s*=\s*["'][^"']*\bfrontCover\b[^"']*["'][^>]*)>\s*(<img\b[^>]*>)\s*</h1>"#,
options: [.caseInsensitive]
@@ -104,6 +99,7 @@ struct RDEPUBHTMLNormalizer: RDEPUBTypesettingStage {
using: coverRegex,
in: normalized
) { tag in
guard let imageTagRegex = try? NSRegularExpression(pattern: #"<img\b[^>]*>"#, options: [.caseInsensitive]),
let imageMatch = imageTagRegex.firstMatch(
in: tag,
@@ -133,15 +129,13 @@ struct RDEPUBHTMLNormalizer: RDEPUBTypesettingStage {
return normalized
}
// MARK: - HTML
/// transform
static func replaceMatches(
using regex: NSRegularExpression,
in source: String,
transform: (String) -> String
) -> String {
let nsSource = source as NSString
let matches = regex.matches(in: source, options: [], range: NSRange(location: 0, length: nsSource.length))
guard !matches.isEmpty else { return source }
@@ -154,7 +148,6 @@ struct RDEPUBHTMLNormalizer: RDEPUBTypesettingStage {
return rewritten
}
/// HTML class style
static func mergeHTMLAttributes(
into tag: String,
requiredClass: String?,
@@ -194,7 +187,6 @@ struct RDEPUBHTMLNormalizer: RDEPUBTypesettingStage {
return rewritten
}
/// `<base>`
static func injectBaseHref(into html: String, baseURL: URL?) -> String {
guard let baseURL else {
return html
@@ -213,7 +205,6 @@ struct RDEPUBHTMLNormalizer: RDEPUBTypesettingStage {
return "<head>\n\(baseTag)\n</head>\n" + html
}
/// CGSize
static func string(from size: CGSize) -> String {
"{\(Int(round(size.width))), \(Int(round(size.height)))}"
}
@@ -1,17 +1,16 @@
import Foundation
/// HTML
struct RDEPUBRenderDiagnosticsCollector {
///
private static let stylesheetLinkPattern = #"<link\b[^>]*rel\s*=\s*["'][^"']*stylesheet[^"']*["'][^>]*href\s*=\s*["']([^"']+)["'][^>]*>"#
/// 图片源地址正则
private static let imageSourcePattern = #"<img\b[^>]*src\s*=\s*["']([^"']+)["'][^>]*>"#
/// HTML
/// - Parameters:
/// - html: HTML
/// - input:
/// - Returns:
func collect(
in html: String,
input: RDEPUBTypesettingInput
@@ -24,9 +23,9 @@ struct RDEPUBRenderDiagnosticsCollector {
)
}
// MARK: -
/// HTML <img>
static func collectImageDiagnostics(
in html: String,
chapterHref: String,
@@ -50,9 +49,9 @@ struct RDEPUBRenderDiagnosticsCollector {
}
}
// MARK: -
/// `<link rel=stylesheet>` CSS
static func inlineLinkedStyleSheets(
in html: String,
chapterHref: String,
@@ -69,10 +68,14 @@ struct RDEPUBRenderDiagnosticsCollector {
return (html, "", [])
}
var rewrittenHTML = html
var inlinedCSSBlocks: [String] = []
var diagnostics: [RDEPUBTextResourceReferenceDiagnostic] = []
for match in matches.reversed() {
guard match.numberOfRanges > 1 else { continue }
let href = nsHTML.substring(with: match.range(at: 1))
@@ -103,9 +106,9 @@ struct RDEPUBRenderDiagnosticsCollector {
return (rewrittenHTML, inlinedCSSBlocks.reversed().joined(separator: "\n\n"), diagnostics.reversed())
}
// MARK: - CSS URL
/// CSS url()
static func rewriteCSSResourceURLs(
in css: String,
styleSheetFileURL: URL
@@ -121,18 +124,25 @@ struct RDEPUBRenderDiagnosticsCollector {
}
var rewrittenCSS = css
for match in matches.reversed() {
guard match.numberOfRanges > 1 else { continue }
let rawValue = nsCSS.substring(with: match.range(at: 1))
.trimmingCharacters(in: .whitespacesAndNewlines)
.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
guard !rawValue.isEmpty else { continue }
if rawValue.hasPrefix("data:") || rawValue.hasPrefix("http://") || rawValue.hasPrefix("https://") || rawValue.hasPrefix("file://") || rawValue.hasPrefix("#") {
if rawValue.hasPrefix("data:")
|| rawValue.hasPrefix("http:")
|| rawValue.hasPrefix("https:") {
continue
}
guard let resolvedURL = URL(string: rawValue, relativeTo: styleSheetFileURL.deletingLastPathComponent())?.standardizedFileURL else {
continue
}
let replacement = "url(\"\(resolvedURL.absoluteString)\")"
if let range = Range(match.range, in: rewrittenCSS) {
rewrittenCSS.replaceSubrange(range, with: replacement)
@@ -141,8 +151,6 @@ struct RDEPUBRenderDiagnosticsCollector {
return rewrittenCSS
}
// MARK: -
static func resolveReference(
_ reference: String,
kind: RDEPUBTextResourceReferenceKind,
@@ -150,11 +158,16 @@ struct RDEPUBRenderDiagnosticsCollector {
baseURL: URL?,
resourceResolver: RDEPUBResourceResolver?
) -> (normalizedHref: String?, resolvedFileURL: URL?, diagnostic: RDEPUBTextResourceReferenceDiagnostic) {
let trimmedReference = reference.trimmingCharacters(in: .whitespacesAndNewlines)
let normalizedHref = resourceResolver?.normalizedHref(trimmedReference, relativeToHref: chapterHref)
let resolvedFileURL = resourceResolver?.fileURL(forReference: trimmedReference, relativeToHref: chapterHref)
?? URL(string: trimmedReference, relativeTo: baseURL)?.standardizedFileURL
let existsOnDisk = resolvedFileURL.map { FileManager.default.fileExists(atPath: $0.path) } ?? false
let diagnostic = RDEPUBTextResourceReferenceDiagnostic(
kind: kind,
chapterHref: chapterHref,
@@ -1,29 +1,19 @@
/// RDEPUBSemanticMarkerInjector -
import Foundation
import UIKit
/// HTML
///
///
/// 1. HTML `process` `${rd-sem-start/end}`
/// 2. `apply` NSAttributedString
struct RDEPUBSemanticMarkerInjector: RDEPUBTypesettingStage {
/// ${rd-sem-start:...} / ${rd-sem-end:...}
private static let semanticMarkerPattern = #"\$\{rd-sem-(start|end):([^}]+)\}"#
/// HTML `${rd-sem-start/end}`
func process(_ html: String, context: RDEPUBTypesettingInput) -> String {
Self.injectPaginationSemanticMarkers(into: html)
}
/// NSAttributedString
func apply(to attributedString: NSMutableAttributedString) {
Self.applyPaginationSemantics(in: attributedString)
}
// MARK: - HTML
/// HTML ${rd-sem-start/end}
static func injectPaginationSemanticMarkers(into html: String) -> String {
guard let regex = try? NSRegularExpression(pattern: #"<[^>]+>"#, options: [.caseInsensitive]) else {
return html
@@ -36,8 +26,11 @@ struct RDEPUBSemanticMarkerInjector: RDEPUBTypesettingStage {
}
var output = ""
var cursor = 0
var openTagStack: [(name: String, id: String)] = []
var nextMarkerID = 0
for match in matches {
@@ -47,9 +40,11 @@ struct RDEPUBSemanticMarkerInjector: RDEPUBTypesettingStage {
let tag = nsHTML.substring(with: tagRange)
let loweredTag = tag.lowercased()
let tagName = htmlTagName(from: loweredTag)
if loweredTag.hasPrefix("</"), let tagName {
if let index = openTagStack.lastIndex(where: { $0.name == tagName }) {
let markerID = openTagStack.remove(at: index).id
output += semanticEndMarker(id: markerID)
@@ -57,16 +52,20 @@ struct RDEPUBSemanticMarkerInjector: RDEPUBTypesettingStage {
output += tag
} else if let tagName,
let semantics = paginationSemantics(forTagName: tagName, rawTag: tag) {
nextMarkerID += 1
let markerID = String(nextMarkerID)
let startMarker = semanticStartMarker(id: markerID, semantics: semantics)
if isVoidHTMLTag(tagName) || loweredTag.hasSuffix("/>") {
output += startMarker + tag + semanticEndMarker(id: markerID)
} else {
openTagStack.append((name: tagName, id: markerID))
output += tag + startMarker
}
} else {
output += tag
}
@@ -77,30 +76,34 @@ struct RDEPUBSemanticMarkerInjector: RDEPUBTypesettingStage {
return output
}
// MARK: -
/// HTML NSAttributedString
static func applyPaginationSemantics(in attributedString: NSMutableAttributedString) {
guard let regex = try? NSRegularExpression(pattern: semanticMarkerPattern, options: []) else {
return
}
let mutableString = NSMutableString(string: attributedString.string)
var searchRange = NSRange(location: 0, length: mutableString.length)
var openRanges: [String: (location: Int, semantics: RDPaginationSemantics)] = [:]
while let match = regex.firstMatch(in: mutableString as String, options: [], range: searchRange) {
let kind = mutableString.substring(with: match.range(at: 1))
let payload = mutableString.substring(with: match.range(at: 2))
let markerLocation = match.range.location
attributedString.deleteCharacters(in: match.range)
mutableString.deleteCharacters(in: match.range)
if kind == "start" {
let semantics = parseSemanticMarkerPayload(payload)
openRanges[semantics.id] = (markerLocation, semantics)
} else {
let markerID = parseSemanticEndID(payload)
if let markerID, let opened = openRanges.removeValue(forKey: markerID) {
let length = max(markerLocation - opened.location, 0)
@@ -114,8 +117,6 @@ struct RDEPUBSemanticMarkerInjector: RDEPUBTypesettingStage {
}
}
// MARK: -
static func htmlTagName(from loweredTag: String) -> String? {
let trimmed = loweredTag.trimmingCharacters(in: .whitespacesAndNewlines)
guard trimmed.hasPrefix("<") else { return nil }
@@ -297,7 +298,6 @@ struct RDEPUBSemanticMarkerInjector: RDEPUBTypesettingStage {
attributedString.addAttributes(attributes, range: range)
}
///
static func normalizeBlockKind(for attributes: [NSAttributedString.Key: Any]) -> RDEPUBTextBlockKind? {
if let rawValue = attributes[.rdPageBlockKind] as? String,
let blockKind = RDEPUBTextBlockKind(rawValue: rawValue) {
@@ -306,7 +306,6 @@ struct RDEPUBSemanticMarkerInjector: RDEPUBTypesettingStage {
return nil
}
///
static func normalizeSemanticHints(for attributes: [NSAttributedString.Key: Any]) -> [RDEPUBTextSemanticHint]? {
if let rawValue = attributes[.rdPageSemanticHints] as? String {
let hints = rawValue
@@ -317,7 +316,6 @@ struct RDEPUBSemanticMarkerInjector: RDEPUBTypesettingStage {
return nil
}
///
static func normalizeAttachmentPlacement(for attributes: [NSAttributedString.Key: Any]) -> RDEPUBTextAttachmentPlacement? {
if let rawValue = attributes[.rdPageAttachmentPlacement] as? String,
let placement = RDEPUBTextAttachmentPlacement(rawValue: rawValue) {
@@ -329,9 +327,6 @@ struct RDEPUBSemanticMarkerInjector: RDEPUBTypesettingStage {
return nil
}
// MARK: -
/// HTML
struct RDPaginationSemantics {
var id: String
var blockKind: RDEPUBTextBlockKind?
@@ -1,24 +1,20 @@
import UIKit
/// HTMLCSS
struct RDEPUBStyleSheetComposition {
/// HTML
var html: String
/// CSS default/replace/dark/epub/user
var layers: [RDEPUBTextStyleSheetLayer]
/// CSS
var inlinedCSS: String
///
var diagnostics: [RDEPUBTextResourceReferenceDiagnostic]
var compatibilityReport: RDEPUBCSSCompatibilityReport
}
/// EPUB CSS HTML
struct RDEPUBStyleSheetComposer {
/// CSS HTML
/// - Parameters:
/// - html: HTML
/// - input:
/// - Returns: HTMLCSS
func compose(html: String, input: RDEPUBTypesettingInput) -> RDEPUBStyleSheetComposition {
let stylesheetHrefReplacements = RDEPUBRenderDiagnosticsCollector.inlineLinkedStyleSheets(
in: html,
@@ -26,9 +22,10 @@ struct RDEPUBStyleSheetComposer {
baseURL: input.baseURL,
resourceResolver: input.resourceResolver
)
let compatibility = RDEPUBCSSCompatibilityLayer().sanitize(stylesheetHrefReplacements.inlinedCSS)
let layers = Self.makeStyleSheetLayers(
style: input.style,
epubCSS: stylesheetHrefReplacements.inlinedCSS,
epubCSS: compatibility.css,
contentLanguageCode: input.contentLanguageCode,
sourceHTML: input.rawHTML
)
@@ -61,14 +58,12 @@ struct RDEPUBStyleSheetComposer {
return RDEPUBStyleSheetComposition(
html: composedHTML,
layers: layers,
inlinedCSS: stylesheetHrefReplacements.inlinedCSS,
diagnostics: stylesheetHrefReplacements.diagnostics
inlinedCSS: compatibility.css,
diagnostics: stylesheetHrefReplacements.diagnostics,
compatibilityReport: compatibility.report
)
}
// MARK: - CSS
/// CSS default/replace/dark/epub/user
static func makeStyleSheetLayers(
style: RDEPUBTextRenderStyle,
epubCSS: String,
@@ -93,17 +88,13 @@ struct RDEPUBStyleSheetComposer {
return layers
}
// MARK: - Style
/// `<style>`
enum StyleInjectionPosition {
/// `<head>`
case headStart
/// `</head>`
case headEnd
}
/// HTML <style>
static func injectStyleTag(
into html: String,
styleID: String,
@@ -133,8 +124,6 @@ struct RDEPUBStyleSheetComposer {
return styleTag + "\n" + html
}
// MARK: - CSS
private static func defaultCSS() -> String {
RDEPUBAssetRepository.string(for: .wxReadDefaultCSS)
}
@@ -186,8 +175,6 @@ struct RDEPUBStyleSheetComposer {
return luminance < 0.5
}
// MARK: -
private static func prefersLatinLanguageCSS(
languageCode: String?,
sourceHTML: String
@@ -5,25 +5,8 @@ import CoreText
import DTCoreText
#endif
/// Facade stage HTML
///
/// 线 stage
/// `RDEPUBDTCoreTextRenderer` stage
enum RDEPUBTextRendererSupport {
// MARK: - 线
/// HTML
///
///
/// 1. HTMLNormalizer.normalizeHTML
/// 2. SemanticMarkerInjector.injectPaginationSemanticMarkers
/// 3. DiagnosticsCollector.inlineLinkedStyleSheets
/// 4. StyleSheetComposer.makeStyleSheetLayers + injectStyleTag
/// 5. FontNormalizer.registerEmbeddedFonts
/// 6. HTMLNormalizer.injectBaseHref
/// 7. FragmentMarkerInjector.injectFragmentMarkers
/// 8. DiagnosticsCollector.collectImageDiagnostics
static func makeChapterRenderRequest(
href: String,
title: String,
@@ -35,27 +18,33 @@ enum RDEPUBTextRendererSupport {
pageSize: CGSize? = nil,
layoutConfig: RDEPUBTextLayoutConfig? = nil
) -> RDEPUBTextChapterRenderRequest {
let normalizedHTML = RDEPUBSemanticMarkerInjector.injectPaginationSemanticMarkers(
into: RDEPUBHTMLNormalizer.normalizeHTML(rawHTML)
)
let stylesheetHrefReplacements = RDEPUBRenderDiagnosticsCollector.inlineLinkedStyleSheets(
in: normalizedHTML,
chapterHref: href,
baseURL: baseURL,
resourceResolver: resourceResolver
)
let layers = RDEPUBStyleSheetComposer.makeStyleSheetLayers(
style: style,
epubCSS: stylesheetHrefReplacements.inlinedCSS,
contentLanguageCode: contentLanguageCode,
sourceHTML: rawHTML
)
RDEPUBFontNormalizer.registerEmbeddedFonts(
in: stylesheetHrefReplacements.inlinedCSS + "\n" + RDEPUBFontNormalizer.inlineStyleCSS(in: normalizedHTML),
chapterHref: href,
resourceResolver: resourceResolver
)
let htmlWithBase = RDEPUBHTMLNormalizer.injectBaseHref(into: stylesheetHrefReplacements.html, baseURL: baseURL)
let htmlWithDefaultLayers = RDEPUBStyleSheetComposer.injectStyleTag(
into: htmlWithBase,
styleID: "rd-native-default-replace-dark",
@@ -65,19 +54,23 @@ enum RDEPUBTextRendererSupport {
.joined(separator: "\n\n"),
position: .headStart
)
let htmlWithEPUBLayer = RDEPUBStyleSheetComposer.injectStyleTag(
into: htmlWithDefaultLayers,
styleID: "rd-native-epub",
css: layers.first(where: { $0.kind == .epub })?.css ?? "",
position: .headEnd
)
let composedHTML = RDEPUBStyleSheetComposer.injectStyleTag(
into: htmlWithEPUBLayer,
styleID: "rd-native-user",
css: layers.first(where: { $0.kind == .user })?.css ?? "",
position: .headEnd
)
let markedHTML = RDEPUBFragmentMarkerInjector.injectFragmentMarkers(into: composedHTML)
let resourceDiagnostics = stylesheetHrefReplacements.diagnostics + RDEPUBRenderDiagnosticsCollector.collectImageDiagnostics(
in: markedHTML,
chapterHref: href,
@@ -101,59 +94,70 @@ enum RDEPUBTextRendererSupport {
)
}
// MARK: - RDEPUBDTCoreTextRenderer
///
static func normalizeReadingAttributes(
in attributedString: NSMutableAttributedString,
style: RDEPUBTextRenderStyle,
layoutConfig: RDEPUBTextLayoutConfig = .default
) {
let fullRange = NSRange(location: 0, length: attributedString.length)
var blockIndex = 0
let sourceText = attributedString.string as NSString
attributedString.enumerateAttributes(in: fullRange) { attributes, range, _ in
let sourceFont = attributes[.font] as? UIFont
let normalizedFont = RDEPUBFontNormalizer.normalizedFont(from: sourceFont, baseFont: style.font)
let paragraph = (attributes[.paragraphStyle] as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? paragraphStyle(lineSpacing: style.lineSpacing)
paragraph.lineSpacing = style.lineSpacing
paragraph.paragraphSpacing = max(paragraph.paragraphSpacing, style.lineSpacing / 2)
paragraph.hyphenationFactor = layoutConfig.hyphenation ? 1.0 : 0.0
var updatedAttributes = attributes
updatedAttributes[.font] = normalizedFont
updatedAttributes[.paragraphStyle] = paragraph
if let textColor = style.textColor {
updatedAttributes[.foregroundColor] = textColor
}
RDEPUBAttachmentNormalizer.normalizeAttachmentDisplayIfNeeded(in: &updatedAttributes, font: normalizedFont)
let semanticBlockRange = (attributes[.rdPageBlockRange] as? String)
.flatMap(NSRangeFromString)
.flatMap { $0.length > 0 ? $0 : nil }
let paragraphRange = sourceText.length > 0
? sourceText.paragraphRange(for: NSRange(location: min(range.location, max(sourceText.length - 1, 0)), length: 0))
: range
updatedAttributes[.rdPageBlockRange] = NSStringFromRange(semanticBlockRange ?? paragraphRange)
updatedAttributes[.rdPageBlockIndex] = blockIndex
if let attachmentKind = RDEPUBAttachmentNormalizer.attachmentKind(for: attributes) {
updatedAttributes[.rdPageAttachmentKind] = attachmentKind.rawValue
}
if let placement = RDEPUBSemanticMarkerInjector.normalizeAttachmentPlacement(for: attributes) {
updatedAttributes[.rdPageAttachmentPlacement] = placement.rawValue
}
if let blockKind = RDEPUBSemanticMarkerInjector.normalizeBlockKind(for: attributes) {
updatedAttributes[.rdPageBlockKind] = blockKind.rawValue
}
if let hints = RDEPUBSemanticMarkerInjector.normalizeSemanticHints(for: attributes), !hints.isEmpty {
updatedAttributes[.rdPageSemanticHints] = hints.map(\.rawValue).joined(separator: ",")
}
attributedString.setAttributes(updatedAttributes, range: range)
blockIndex += 1
}
}
/// 退 DTCoreText HTML
static func fallbackAttributedString(for html: String, style: RDEPUBTextRenderStyle) -> NSMutableAttributedString {
let fallbackAttributes: [NSAttributedString.Key: Any] = [
.font: style.font,
.paragraphStyle: paragraphStyle(lineSpacing: style.lineSpacing),
@@ -162,7 +166,6 @@ enum RDEPUBTextRendererSupport {
return NSMutableAttributedString(string: html, attributes: fallbackAttributes)
}
///
static func paragraphStyle(lineSpacing: CGFloat) -> NSMutableParagraphStyle {
let style = NSMutableParagraphStyle()
style.lineSpacing = lineSpacing
@@ -1,69 +1,77 @@
import UIKit
/// HTML
struct RDEPUBTypesettingInput {
///
var href: String
///
var spineIndex: Int?
var title: String
/// HTML
var rawHTML: String
/// HTML URL
var baseURL: URL?
///
var style: RDEPUBTextRenderStyle
///
var resourceResolver: RDEPUBResourceResolver?
/// zh-CN
var contentLanguageCode: String?
///
var pageSize: CGSize?
///
var layoutConfig: RDEPUBTextLayoutConfig?
}
///
struct RDEPUBTypesettingOutput {
///
var request: RDEPUBTextChapterRenderRequest
///
var diagnostics: [RDEPUBTextResourceReferenceDiagnostic]
var styleCompatibilityReport: RDEPUBCSSCompatibilityReport
}
/// HTML 线
protocol RDEPUBTypesettingStage {
/// HTML
/// - Parameters:
/// - html: HTML
/// - context:
/// - Returns: HTML
func process(_ html: String, context: RDEPUBTypesettingInput) -> String
}
/// 线 HTML
struct RDEPUBTextTypesetterPipeline {
///
/// - Parameter input:
/// - Returns:
func makeRequest(from input: RDEPUBTypesettingInput) -> RDEPUBTypesettingOutput {
let htmlNormalizer = RDEPUBHTMLNormalizer()
let semanticMarkerInjector = RDEPUBSemanticMarkerInjector()
let cfiMarkerInjector = RDEPUBCFIMarkerInjector()
let styleSheetComposer = RDEPUBStyleSheetComposer()
let fontNormalizer = RDEPUBFontNormalizer()
let fragmentMarkerInjector = RDEPUBFragmentMarkerInjector()
let diagnosticsCollector = RDEPUBRenderDiagnosticsCollector()
let normalizedHTML = semanticMarkerInjector.process(
htmlNormalizer.process(input.rawHTML, context: input),
let normalizedHTML = cfiMarkerInjector.process(
semanticMarkerInjector.process(
htmlNormalizer.process(input.rawHTML, context: input),
context: input
),
context: input
)
let styleSheetComposition = styleSheetComposer.compose(html: normalizedHTML, input: input)
fontNormalizer.registerEmbeddedFonts(
let fontResults = fontNormalizer.registerEmbeddedFonts(
html: normalizedHTML,
inlinedCSS: styleSheetComposition.inlinedCSS,
input: input
)
let compatibilityReport = Self.mergedCompatibilityReport(
styleSheetComposition.compatibilityReport,
fontResults: fontResults
)
let markedHTML = fragmentMarkerInjector.process(styleSheetComposition.html, context: input)
let diagnostics = styleSheetComposition.diagnostics + diagnosticsCollector.collect(in: markedHTML, input: input)
let context = RDEPUBTextChapterContext(
@@ -72,7 +80,8 @@ struct RDEPUBTextTypesetterPipeline {
html: markedHTML,
baseURL: input.baseURL,
stylesheet: RDEPUBTextStyleSheetPackage(layers: styleSheetComposition.layers),
resourceDiagnostics: diagnostics
resourceDiagnostics: diagnostics,
styleCompatibilityReport: compatibilityReport
)
let request = RDEPUBTextChapterRenderRequest(
context: context,
@@ -82,7 +91,27 @@ struct RDEPUBTextTypesetterPipeline {
)
return RDEPUBTypesettingOutput(
request: request,
diagnostics: diagnostics
diagnostics: diagnostics,
styleCompatibilityReport: compatibilityReport
)
}
private static func mergedCompatibilityReport(
_ report: RDEPUBCSSCompatibilityReport,
fontResults: [RDEPUBFontRegistrationResult]
) -> RDEPUBCSSCompatibilityReport {
let fontFailures = fontResults.compactMap { result -> String? in
guard result.didRegister == false else { return nil }
let family = result.descriptor.family ?? "unknown-family"
let href = result.descriptor.href
let reason = result.errorDescription ?? "Font registration failed"
return "\(family) <\(href)>: \(reason)"
}
return RDEPUBCSSCompatibilityReport(
unsupportedRules: report.unsupportedRules,
normalizedRules: report.normalizedRules,
fontFailures: report.fontFailures + fontFailures
)
}
}