epub问题修改

This commit is contained in:
shen
2026-05-26 23:27:52 +08:00
parent 22adb76332
commit ea21c6a831
8 changed files with 257 additions and 144 deletions
@@ -223,6 +223,10 @@ public final class RDEPUBTextBookBuilder {
self.init(renderer: RDEPUBDTCoreTextRenderer())
}
private var isPaginationDebugEnabled: Bool {
ProcessInfo.processInfo.arguments.contains("--demo-pagination-debug")
}
/// Phase 7
public func phase7SemanticSummary(title: String? = nil) -> String? {
guard !lastBuildPaginationDiagnostics.isEmpty else { return nil }
@@ -263,6 +267,9 @@ public final class RDEPUBTextBookBuilder {
pageSize: CGSize,
style: RDEPUBTextRenderStyle
) throws -> RDEPUBTextBook {
if isPaginationDebugEnabled {
print("[PaginationDebug] build pageSize=\(NSCoder.string(for: pageSize)) layoutInsets=\(NSCoder.string(for: layoutConfig.edgeInsets))")
}
var chapters: [RDEPUBTextChapter] = []
var flatPages: [RDEPUBTextPage] = []
lastBuildResourceDiagnostics = []
@@ -437,6 +444,18 @@ public final class RDEPUBTextBookBuilder {
)
}
if isPaginationDebugEnabled,
item.href.contains("Chapter_3.xhtml") {
print("[PaginationDebug] href=\(item.href) pages=\(pages.count)")
for page in pages {
let preview = debugPreview(for: page.content, limit: 36)
print("[PaginationDebug] absPage=\(page.absolutePageIndex + 1) localPage=\(page.pageIndexInChapter + 1) range=\(NSStringFromRange(page.contentRange)) break=\(page.metadata.breakReason.rawValue) preview=\(preview)")
for note in page.metadata.diagnostics.prefix(4) {
print("[PaginationDebug] note=\(note)")
}
}
}
chapters.append(
RDEPUBTextChapter(
chapterIndex: chapterIndex,
@@ -575,11 +594,26 @@ public final class RDEPUBTextBookBuilder {
return attachmentCount(in: content) > 0 && trimmed.count <= 1
}
private func debugPreview(for content: NSAttributedString, limit: Int) -> String {
let collapsed = content.string
.replacingOccurrences(of: "\n", with: " ")
.replacingOccurrences(of: "\r", with: " ")
.replacingOccurrences(of: "\t", with: " ")
.trimmingCharacters(in: .whitespacesAndNewlines)
guard !collapsed.isEmpty else { return "<empty>" }
if collapsed.count <= limit {
return collapsed
}
let head = collapsed.prefix(limit)
return "\(head)"
}
// MARK: -
///
/// 1.
/// 2. 2
///
/// 1.
/// 2.
/// 3. 2
private func normalizeTrailingFrames(
_ frames: [RDEPUBTextLayoutFrame],
content: NSAttributedString,
@@ -589,9 +623,28 @@ public final class RDEPUBTextBookBuilder {
var normalized = frames
// /
//
var compacted: [RDEPUBTextLayoutFrame] = []
compacted.reserveCapacity(normalized.count)
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 {
print("[EPUB][Pagination] href=\(href) dropped leading/intermediate whitespace frame \(NSStringFromRange(frame.contentRange))")
}
continue
}
compacted.append(frame)
}
normalized = compacted
//
while let lastFrame = normalized.last,
shouldDropWhitespaceOnlyTrailingFrame(lastFrame, in: content) {
shouldDropWhitespaceOnlyFrame(lastFrame, in: content) {
normalized.removeLast()
let note = "normalized: dropped whitespace-only trailing page \(NSStringFromRange(lastFrame.contentRange))"
if var previousFrame = normalized.popLast() {
@@ -617,7 +670,7 @@ public final class RDEPUBTextBookBuilder {
}
///
private func shouldDropWhitespaceOnlyTrailingFrame(
private func shouldDropWhitespaceOnlyFrame(
_ frame: RDEPUBTextLayoutFrame,
in content: NSAttributedString
) -> Bool {
@@ -737,7 +790,7 @@ public final class RDEPUBTextBookBuilder {
bookID: bookID,
fontSize: style.font.pointSize,
lineHeightMultiple: style.lineSpacing,
contentInsets: .zero,
contentInsets: layoutConfig.edgeInsets,
pageSize: pageSize,
layoutConfigSignature: layoutConfig.cacheSignature
)
@@ -123,7 +123,8 @@ final class ChapterPaginationArchive: NSObject, NSSecureCoding {
public final class RDEPUBTextBookCache {
///
public var schemaVersion: Int = 4
//
public var schemaVersion: Int = 6
/// 线
private let queue = DispatchQueue(label: "com.rdreader.textbookcache", qos: .utility)
@@ -67,23 +67,42 @@ struct RDEPUBTextLayouter {
var frames: [RDEPUBTextLayoutFrame] = []
var location = 0
let resolvedSize = config.resolvedFrameSize(fallback: pageSize)
let usableWidth = resolvedSize.width - config.edgeInsets.left - config.edgeInsets.right
let usableHeight = resolvedSize.height - config.edgeInsets.top - config.edgeInsets.bottom
guard usableWidth > 0, usableHeight > 0 else {
return []
}
while location < attributedString.length {
let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(location, 0), path, nil)
let visibleRange = CTFrameGetVisibleStringRange(frame)
guard visibleRange.length > 0 else {
let framePath = CGMutablePath()
// WXRead WRChapterPageCount
// CoreText 使 bottom inset y UIKit top inset
let pageRect = CGRect(
x: config.edgeInsets.left,
y: config.edgeInsets.bottom,
width: usableWidth,
height: usableHeight
)
framePath.addRect(pageRect)
let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(location, 0), framePath, nil)
let proposedRange = proposedRangeUsingWXReadPageCount(
from: frame,
start: location,
usableHeight: usableHeight,
totalLength: attributedString.length
)
guard proposedRange.length > 0 else {
break
}
let proposedRange = NSRange(location: location, length: visibleRange.length)
// avoidPageBreakInside WXRead
let avoidAdjusted = trimmedRangeForAvoidPageBreakInside(from: frame, proposed: proposedRange)
let lineAdjusted = trimmedRangeForKeepWithNext(from: frame, proposed: avoidAdjusted)
let lineRanges = lineRanges(from: frame)
let adjusted = adjustedRange(
from: lineAdjusted,
from: avoidAdjusted,
totalLength: attributedString.length,
lineRanges: lineRanges
)
@@ -108,7 +127,7 @@ struct RDEPUBTextLayouter {
let nextLocation = adjusted.range.location + adjusted.range.length
guard nextLocation > location else {
location += max(visibleRange.length, 1)
location += max(proposedRange.length, 1)
continue
}
location = nextLocation
@@ -155,7 +174,12 @@ struct RDEPUBTextLayouter {
totalLength: attributedString.length,
lineRanges: lineRanges
)
let verifiedRange = verifiedDisplayRange(for: adjusted.range)
let verifiedRange: NSRange
if adjusted.breakReason == .attachmentBoundary {
verifiedRange = verifiedDisplayRange(for: adjusted.range)
} else {
verifiedRange = adjusted.range
}
let trailingFragmentID = nearestTrailingFragmentID(
endingAt: verifiedRange.location + verifiedRange.length,
fragmentOffsets: fragmentOffsets
@@ -191,27 +215,28 @@ struct RDEPUBTextLayouter {
}
private func verifiedDisplayRange(for range: NSRange) -> NSRange {
guard range.length > 0,
!attachmentRanges(in: range).isEmpty else {
guard let clampedRange = clampedRange(range),
clampedRange.length > 0,
!attachmentRanges(in: clampedRange).isEmpty else {
return range
}
let pageContent = attributedString.attributedSubstring(from: range)
let pageContent = attributedString.attributedSubstring(from: clampedRange)
guard let layouter = DTCoreTextLayouter(attributedString: pageContent) else {
return range
return clampedRange
}
layouter.shouldCacheLayoutFrames = false
guard let layoutFrame = layouter.layoutFrame(with: dtLayoutRect, range: NSRange(location: 0, length: 0)) else {
return range
return clampedRange
}
let visibleRange = layoutFrame.visibleStringRange()
guard visibleRange.length > 0, visibleRange.length < range.length else {
return range
guard visibleRange.length > 0, visibleRange.length < clampedRange.length else {
return clampedRange
}
return NSRange(location: range.location, length: visibleRange.length)
return NSRange(location: clampedRange.location, length: visibleRange.length)
}
#endif
@@ -281,10 +306,6 @@ struct RDEPUBTextLayouter {
)
}
// 55%
let minLength = max(Int(Double(proposedRange.length) * 0.55), 1)
let minimumEnd = proposedRange.location + minLength
let currentBlockRange = blockRange(at: max(proposedRange.location, pageEnd - 1))
let currentAttachmentRanges = attachmentRanges(in: proposedRange)
let currentAttachmentKinds = attachmentKinds(in: proposedRange)
@@ -292,38 +313,12 @@ struct RDEPUBTextLayouter {
let currentSemanticHints = proposedSemanticHints
let currentAttachmentPlacements = proposedAttachmentPlacements
// 1. pageBreakBefore/After
if let semanticBoundary = preferredSemanticBoundary(
in: proposedRange,
minimumEnd: minimumEnd
) {
let adjustedRange = NSRange(location: proposedRange.location, length: semanticBoundary.location - proposedRange.location)
return (
range: adjustedRange,
breakReason: .semanticBoundary,
blockRange: currentBlockRange,
attachmentRanges: currentAttachmentRanges,
attachmentKinds: currentAttachmentKinds,
blockKinds: currentBlockKinds,
semanticHints: currentSemanticHints,
attachmentPlacements: currentAttachmentPlacements,
diagnostics: diagnostics(
reason: .semanticBoundary,
range: adjustedRange,
attachmentRanges: currentAttachmentRanges,
blockRange: currentBlockRange,
blockKinds: currentBlockKinds,
semanticHints: currentSemanticHints,
attachmentPlacements: currentAttachmentPlacements,
trigger: semanticBoundary.trigger
)
)
}
// 2. pageRelate
// WXRead CTFrame pageRelate
// keepWithNext/attachmentBoundary/
//
if let pageRelateBoundary = preferredPageRelateBoundary(
after: proposedRange,
minimumEnd: minimumEnd,
minimumEnd: proposedRange.location + 1,
lineRanges: lineRanges
) {
let adjustedRange = NSRange(location: proposedRange.location, length: pageRelateBoundary - proposedRange.location)
@@ -349,33 +344,6 @@ struct RDEPUBTextLayouter {
)
}
// 3.
if let attachmentBoundary = preferredAttachmentBoundary(
in: proposedRange,
minimumEnd: minimumEnd
) {
let adjustedRange = NSRange(location: proposedRange.location, length: attachmentBoundary - proposedRange.location)
return (
range: adjustedRange,
breakReason: .attachmentBoundary,
blockRange: currentBlockRange,
attachmentRanges: currentAttachmentRanges,
attachmentKinds: currentAttachmentKinds,
blockKinds: currentBlockKinds,
semanticHints: currentSemanticHints,
attachmentPlacements: currentAttachmentPlacements,
diagnostics: diagnostics(
reason: .attachmentBoundary,
range: adjustedRange,
attachmentRanges: currentAttachmentRanges,
blockRange: currentBlockRange,
blockKinds: currentBlockKinds,
semanticHints: currentSemanticHints,
attachmentPlacements: currentAttachmentPlacements
)
)
}
// 4.
return (
range: proposedRange,
@@ -407,8 +375,11 @@ struct RDEPUBTextLayouter {
in range: NSRange,
minimumEnd: Int
) -> (location: Int, trigger: String)? {
guard let safeRange = clampedRange(range), safeRange.length > 0 else {
return nil
}
var boundary: (location: Int, trigger: String)?
attributedString.enumerateAttribute(.rdPageSemanticHints, in: range) { value, attributeRange, stop in
attributedString.enumerateAttribute(.rdPageSemanticHints, in: safeRange) { value, attributeRange, stop in
guard let rawValue = value as? String else { return }
let hints = rawValue
.split(separator: ",")
@@ -416,7 +387,7 @@ struct RDEPUBTextLayouter {
guard !hints.isEmpty else { return }
if hints.contains(.pageBreakBefore),
attributeRange.location > range.location,
attributeRange.location > safeRange.location,
attributeRange.location >= minimumEnd {
boundary = (attributeRange.location, RDEPUBTextSemanticHint.pageBreakBefore.rawValue)
stop.pointee = true
@@ -426,7 +397,7 @@ struct RDEPUBTextLayouter {
let attributeEnd = attributeRange.location + attributeRange.length
if hints.contains(.pageBreakAfter),
attributeEnd > minimumEnd,
attributeEnd < range.location + range.length {
attributeEnd < safeRange.location + safeRange.length {
boundary = (attributeEnd, RDEPUBTextSemanticHint.pageBreakAfter.rawValue)
stop.pointee = true
return
@@ -438,8 +409,11 @@ struct RDEPUBTextLayouter {
/// .attachment .centered
///
private func preferredAttachmentBoundary(in range: NSRange, minimumEnd: Int) -> Int? {
guard let safeRange = clampedRange(range), safeRange.length > 0 else {
return nil
}
var boundary: Int?
attributedString.enumerateAttribute(.rdPageAttachmentKind, in: range) { value, attributeRange, stop in
attributedString.enumerateAttribute(.rdPageAttachmentKind, in: safeRange) { value, attributeRange, stop in
guard value != nil else { return }
let location = attributeRange.location
@@ -448,11 +422,21 @@ struct RDEPUBTextLayouter {
// WXRead
//
let isBlockLevelAttachment = blockKind == .attachment || placement == .centered
//
// /线 note.png
let isBlockLevelAttachment: Bool
switch placement {
case .centered:
isBlockLevelAttachment = true
case .inline, .baseline:
isBlockLevelAttachment = false
case nil:
isBlockLevelAttachment = blockKind == .attachment
}
guard isBlockLevelAttachment else { return }
let boundaryRange = blockRange(at: location) ?? paragraphRange(containing: location)
if boundaryRange.location > range.location, boundaryRange.location >= minimumEnd {
if boundaryRange.location > safeRange.location, boundaryRange.location >= minimumEnd {
boundary = boundaryRange.location
stop.pointee = true
}
@@ -523,8 +507,11 @@ struct RDEPUBTextLayouter {
///
private func attachmentRanges(in range: NSRange) -> [NSRange] {
guard let safeRange = clampedRange(range), safeRange.length > 0 else {
return []
}
var results: [NSRange] = []
attributedString.enumerateAttribute(.rdPageAttachmentKind, in: range) { value, attributeRange, _ in
attributedString.enumerateAttribute(.rdPageAttachmentKind, in: safeRange) { value, attributeRange, _ in
guard value != nil else { return }
results.append(attributeRange)
}
@@ -543,8 +530,11 @@ struct RDEPUBTextLayouter {
///
private func attachmentKinds(in range: NSRange) -> [RDEPUBTextAttachmentKind] {
guard let safeRange = clampedRange(range), safeRange.length > 0 else {
return []
}
var kinds: [RDEPUBTextAttachmentKind] = []
attributedString.enumerateAttribute(.rdPageAttachmentKind, in: range) { value, _, _ in
attributedString.enumerateAttribute(.rdPageAttachmentKind, in: safeRange) { value, _, _ in
guard let rawValue = value as? String,
let kind = RDEPUBTextAttachmentKind(rawValue: rawValue),
!kinds.contains(kind) else {
@@ -557,8 +547,11 @@ struct RDEPUBTextLayouter {
///
private func blockKinds(in range: NSRange) -> [RDEPUBTextBlockKind] {
guard let safeRange = clampedRange(range), safeRange.length > 0 else {
return []
}
var kinds: [RDEPUBTextBlockKind] = []
attributedString.enumerateAttribute(.rdPageBlockKind, in: range) { value, _, _ in
attributedString.enumerateAttribute(.rdPageBlockKind, in: safeRange) { value, _, _ in
guard let rawValue = value as? String,
let kind = RDEPUBTextBlockKind(rawValue: rawValue),
!kinds.contains(kind) else {
@@ -571,8 +564,11 @@ struct RDEPUBTextLayouter {
///
private func semanticHints(in range: NSRange) -> [RDEPUBTextSemanticHint] {
guard let safeRange = clampedRange(range), safeRange.length > 0 else {
return []
}
var hints: [RDEPUBTextSemanticHint] = []
attributedString.enumerateAttribute(.rdPageSemanticHints, in: range) { value, _, _ in
attributedString.enumerateAttribute(.rdPageSemanticHints, in: safeRange) { value, _, _ in
guard let rawValue = value as? String else { return }
for hint in rawValue.split(separator: ",").compactMap({ RDEPUBTextSemanticHint(rawValue: String($0)) }) where !hints.contains(hint) {
hints.append(hint)
@@ -583,8 +579,11 @@ struct RDEPUBTextLayouter {
///
private func attachmentPlacements(in range: NSRange) -> [RDEPUBTextAttachmentPlacement] {
guard let safeRange = clampedRange(range), safeRange.length > 0 else {
return []
}
var placements: [RDEPUBTextAttachmentPlacement] = []
attributedString.enumerateAttribute(.rdPageAttachmentPlacement, in: range) { value, _, _ in
attributedString.enumerateAttribute(.rdPageAttachmentPlacement, in: safeRange) { value, _, _ in
guard let rawValue = value as? String,
let placement = RDEPUBTextAttachmentPlacement(rawValue: rawValue),
!placements.contains(placement) else {
@@ -595,6 +594,22 @@ struct RDEPUBTextLayouter {
return placements
}
/// attributedString
private func clampedRange(_ range: NSRange) -> NSRange? {
guard range.location >= 0, range.length >= 0 else { return nil }
guard attributedString.length > 0 else {
return range.location == 0 ? NSRange(location: 0, length: 0) : nil
}
guard range.location < attributedString.length else { return nil }
let maxLength = attributedString.length - range.location
return NSRange(location: range.location, length: min(range.length, maxLength))
}
private func clampedProbeRange(for lineRange: NSRange) -> NSRange? {
clampedRange(NSRange(location: lineRange.location, length: max(lineRange.length, 1)))
}
/// fragment ID
private func nearestTrailingFragmentID(
endingAt location: Int,
@@ -770,10 +785,15 @@ struct RDEPUBTextLayouter {
/// avoidPageBreakInside
private func lineIsInAvoidPageBreakInsideBlock(_ lineRange: NSRange) -> Bool {
guard let probeRange = clampedProbeRange(for: lineRange) else {
return false
}
var found = false
let probeRange = NSRange(location: lineRange.location, length: max(lineRange.length, 1))
attributedString.enumerateAttribute(.rdPageSemanticHints, in: probeRange) { value, _, stop in
guard let rawValue = value as? String else { return }
attributedString.enumerateAttributes(in: probeRange) { attributes, _, stop in
guard shouldTreatAvoidHintAsBlockProtection(attributes) else {
return
}
guard let rawValue = attributes[.rdPageSemanticHints] as? String else { return }
let hints = rawValue
.split(separator: ",")
.compactMap { RDEPUBTextSemanticHint(rawValue: String($0)) }
@@ -785,10 +805,37 @@ struct RDEPUBTextLayouter {
return found
}
/// avoidPageBreakInside
/// note.png `img`
private func shouldTreatAvoidHintAsBlockProtection(_ attributes: [NSAttributedString.Key: Any]) -> Bool {
guard let rawValue = attributes[.rdPageSemanticHints] as? String else {
return false
}
let hints = rawValue
.split(separator: ",")
.compactMap { RDEPUBTextSemanticHint(rawValue: String($0)) }
guard hints.contains(.avoidPageBreakInside) else {
return false
}
let placement = (attributes[.rdPageAttachmentPlacement] as? String)
.flatMap(RDEPUBTextAttachmentPlacement.init(rawValue:))
let blockKind = (attributes[.rdPageBlockKind] as? String)
.flatMap(RDEPUBTextBlockKind.init(rawValue:))
if blockKind == .attachment, placement != .centered {
return false
}
return true
}
/// keepWithNext
private func lineIsInKeepWithNextBlock(_ lineRange: NSRange) -> Bool {
guard let probeRange = clampedProbeRange(for: lineRange) else {
return false
}
var found = false
let probeRange = NSRange(location: lineRange.location, length: max(lineRange.length, 1))
attributedString.enumerateAttribute(.rdPageSemanticHints, in: probeRange) { value, _, stop in
guard let rawValue = value as? String else { return }
let hints = rawValue
@@ -811,6 +858,47 @@ struct RDEPUBTextLayouter {
}
}
/// WXRead `WRChapterPageCount.recalculatePageRangesForAttributedString`
/// 1. CTFrame
/// 2. origin
/// 3. `lineY - ascent > usableHeight`
/// 4.
private func proposedRangeUsingWXReadPageCount(
from frame: CTFrame,
start location: Int,
usableHeight: CGFloat,
totalLength: Int
) -> NSRange {
let lines = CTFrameGetLines(frame) as! [CTLine]
guard !lines.isEmpty else {
return NSRange(location: location, length: 0)
}
var origins = [CGPoint](repeating: .zero, count: lines.count)
CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), &origins)
var pageCharCount = 0
for (index, line) in lines.enumerated() {
let lineRange = CTLineGetStringRange(line)
let lineY = origins[index].y
var ascent: CGFloat = 0
var descent: CGFloat = 0
CTLineGetTypographicBounds(line, &ascent, &descent, nil)
if lineY - ascent > usableHeight {
break
}
pageCharCount += lineRange.length
}
if pageCharCount == 0 {
pageCharCount = 1
}
return NSRange(location: location, length: min(pageCharCount, totalLength - location))
}
#if canImport(DTCoreText)
/// DTCoreTextLayoutFrame
private func lineRanges(from layoutFrame: DTCoreTextLayoutFrame) -> [NSRange] {