目前阅读稳定版本,需要修改图片阅读方式

This commit is contained in:
shen
2026-05-23 15:50:53 +08:00
parent d7339aa255
commit 3e2669d8a8
7 changed files with 450 additions and 9 deletions
@@ -1,9 +1,15 @@
import UIKit
#if canImport(DTCoreText)
import DTCoreText
#endif
enum RDEPUBTextRendererSupport {
private static let stylesheetLinkPattern = #"<link\b[^>]*rel\s*=\s*["'][^"']*stylesheet[^"']*["'][^>]*href\s*=\s*["']([^"']+)["'][^>]*>"#
private static let imageSourcePattern = #"<img\b[^>]*src\s*=\s*["']([^"']+)["'][^>]*>"#
private static let semanticMarkerPattern = #"\$\{rd-sem-(start|end):([^}]+)\}"#
private static var didLogFootnoteAttachment = false
private static var didLogCoverAttachment = false
static func injectFragmentMarkers(into html: String) -> String {
guard let regex = try? NSRegularExpression(pattern: #"(<[^>]+\sid="([^"]+)"[^>]*>)"#, options: [.caseInsensitive]) else {
@@ -84,16 +90,18 @@ enum RDEPUBTextRendererSupport {
var blockIndex = 0
attributedString.enumerateAttributes(in: fullRange) { attributes, range, _ in
let sourceFont = attributes[.font] as? UIFont
let normalizedFont = 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)
var updatedAttributes = attributes
updatedAttributes[.font] = normalizedFont(from: sourceFont, baseFont: style.font)
updatedAttributes[.font] = normalizedFont
updatedAttributes[.paragraphStyle] = paragraph
if let textColor = style.textColor {
updatedAttributes[.foregroundColor] = textColor
}
normalizeAttachmentDisplayIfNeeded(in: &updatedAttributes, font: normalizedFont)
updatedAttributes[.rdPageBlockRange] = NSStringFromRange(range)
updatedAttributes[.rdPageBlockIndex] = blockIndex
if let attachmentKind = attachmentKind(for: attributes) {
@@ -201,9 +209,59 @@ enum RDEPUBTextRendererSupport {
}
}
cleanedHTML = normalizeAttachmentHTMLMarkers(in: cleanedHTML)
return cleanedHTML
}
#if canImport(DTCoreText)
static func prepareHTMLElementForReaderRendering(
_ element: DTHTMLElement,
style: RDEPUBTextRenderStyle
) {
guard let attachment = element.textAttachment else { return }
let lowercasedClasses = (((attachment.attributes["class"] as? String) ?? (element.attributes["class"] as? String) ?? "")).lowercased()
let lowercasedPath = attachment.contentURL?.lastPathComponent.lowercased()
?? ((attachment.attributes["src"] as? String) ?? (element.attributes["src"] as? String) ?? "").lowercased()
let pointSize = max(element.fontDescriptor.pointSize, style.font.pointSize)
if lowercasedClasses.contains("qqreader-footnote") || lowercasedPath == "note.png" {
let targetHeight = max(round(pointSize * 0.54), 1)
let originalSize = attachment.originalSize
let aspectRatio = originalSize.height > 0 ? originalSize.width / originalSize.height : 1
let targetWidth = max(round(targetHeight * max(aspectRatio, 0.1)), 1)
attachment.displaySize = CGSize(width: targetWidth, height: targetHeight)
attachment.verticalAlignment = .center
element.displayStyle = .inline
if !didLogFootnoteAttachment {
didLogFootnoteAttachment = true
print("[EPUB][Attachment] footnote classes=\(lowercasedClasses) path=\(lowercasedPath) original=\(string(from: originalSize)) display=\(string(from: attachment.displaySize)) font=\(pointSize)")
}
return
}
if lowercasedClasses.contains("rd-front-cover-image") || lowercasedPath == "cover.jpg" {
let maxSize = UIScreen.main.bounds.insetBy(dx: 20, dy: 28).size
let originalSize = attachment.originalSize
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 = CGSize(width: round(maxSize.width), height: round(maxSize.height))
}
attachment.verticalAlignment = .baseline
element.displayStyle = .block
if !didLogCoverAttachment {
didLogCoverAttachment = true
print("[EPUB][Attachment] cover classes=\(lowercasedClasses) path=\(lowercasedPath) original=\(string(from: originalSize)) display=\(string(from: attachment.displaySize))")
}
}
}
#endif
private static func makeStyleSheetLayers(
style: RDEPUBTextRenderStyle,
epubCSS: String
@@ -244,10 +302,32 @@ enum RDEPUBTextRendererSupport {
private static func replaceCSS() -> String {
"""
img, svg, video, canvas {
display: block;
max-width: 100%;
height: auto;
}
.frontCover,
.bodyPic,
.qrbodyPic,
figure {
text-align: center;
text-indent: 0;
}
.frontCover img,
.rd-front-cover-image,
.bodyPic img,
.qrbodyPic img,
figure img {
display: block;
margin-left: auto;
margin-right: auto;
}
.qqreader-footnote,
.s-pic,
.h-pic,
.g-pic {
display: inline;
vertical-align: middle;
}
h1, h2, h3, h4, h5, h6 {
page-break-after: avoid;
break-after: avoid;
@@ -262,6 +342,168 @@ enum RDEPUBTextRendererSupport {
"""
}
private static func normalizeAttachmentHTMLMarkers(in html: String) -> String {
var normalized = html
if let footnoteRegex = try? NSRegularExpression(
pattern: #"<img\b([^>]*class\s*=\s*["'][^"']*\bqqreader-footnote\b[^"']*["'][^>]*)>"#,
options: [.caseInsensitive]
) {
normalized = replaceMatches(
using: footnoteRegex,
in: normalized
) { tag in
mergeHTMLAttributes(
into: tag,
requiredClass: nil,
styleFragments: [
"width:1em",
"height:1em",
"vertical-align:middle",
"display:inline-block"
]
)
}
}
if let coverRegex = try? NSRegularExpression(
pattern: #"<h1\b([^>]*class\s*=\s*["'][^"']*\bfrontCover\b[^"']*["'][^>]*)>\s*(<img\b[^>]*>)\s*</h1>"#,
options: [.caseInsensitive]
) {
normalized = replaceMatches(
using: coverRegex,
in: normalized
) { tag in
guard let imageTagRegex = try? NSRegularExpression(pattern: #"<img\b[^>]*>"#, options: [.caseInsensitive]),
let imageMatch = imageTagRegex.firstMatch(
in: tag,
options: [],
range: NSRange(location: 0, length: (tag as NSString).length)
),
let imageRange = Range(imageMatch.range, in: tag) else {
return tag
}
let imageTag = String(tag[imageRange])
let normalizedImageTag = mergeHTMLAttributes(
into: imageTag,
requiredClass: "rd-front-cover-image",
styleFragments: [
"display:block",
"width:100%",
"height:auto",
"margin-left:auto",
"margin-right:auto"
]
)
return tag.replacingCharacters(in: imageRange, with: normalizedImageTag)
}
}
return normalized
}
private 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 }
var rewritten = source
for match in matches.reversed() {
guard let range = Range(match.range, in: rewritten) else { continue }
let original = String(rewritten[range])
rewritten.replaceSubrange(range, with: transform(original))
}
return rewritten
}
private static func string(from size: CGSize) -> String {
"{\(Int(round(size.width))), \(Int(round(size.height)))}"
}
private static func mergeHTMLAttributes(
into tag: String,
requiredClass: String?,
styleFragments: [String]
) -> String {
var rewritten = tag
if let requiredClass {
if let classRegex = try? NSRegularExpression(pattern: #"class\s*=\s*["']([^"']*)["']"#, options: [.caseInsensitive]),
let match = classRegex.firstMatch(in: rewritten, options: [], range: NSRange(location: 0, length: (rewritten as NSString).length)),
match.numberOfRanges > 1 {
let existingClasses = (rewritten as NSString).substring(with: match.range(at: 1))
if !existingClasses.localizedCaseInsensitiveContains(requiredClass) {
let replacement = #"class="\#(existingClasses) \#(requiredClass)""#
if let range = Range(match.range, in: rewritten) {
rewritten.replaceSubrange(range, with: replacement)
}
}
} else if let closing = rewritten.lastIndex(of: ">") {
rewritten.insert(contentsOf: #" class="\#(requiredClass)""#, at: closing)
}
}
let styleValue = styleFragments.joined(separator: ";") + ";"
if let styleRegex = try? NSRegularExpression(pattern: #"style\s*=\s*["']([^"']*)["']"#, options: [.caseInsensitive]),
let match = styleRegex.firstMatch(in: rewritten, options: [], range: NSRange(location: 0, length: (rewritten as NSString).length)),
match.numberOfRanges > 1 {
let existing = (rewritten as NSString).substring(with: match.range(at: 1)).trimmingCharacters(in: .whitespacesAndNewlines)
let merged = existing.isEmpty ? styleValue : existing + (existing.hasSuffix(";") ? "" : ";") + styleValue
let replacement = #"style="\#(merged)""#
if let range = Range(match.range, in: rewritten) {
rewritten.replaceSubrange(range, with: replacement)
}
} else if let closing = rewritten.lastIndex(of: ">") {
rewritten.insert(contentsOf: #" style="\#(styleValue)""#, at: closing)
}
return rewritten
}
private 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 {
let lowercasedClasses = ((textAttachment.attributes["class"] as? String) ?? "").lowercased()
let lowercasedPath = textAttachment.contentURL?.lastPathComponent.lowercased() ?? ""
if lowercasedClasses.contains("qqreader-footnote") || lowercasedPath == "note.png" {
let targetHeight = max(round(font.pointSize * 0.14), 1)
let originalSize = textAttachment.originalSize
let aspectRatio = originalSize.height > 0 ? originalSize.width / originalSize.height : 1
let targetWidth = max(round(targetHeight * max(aspectRatio, 0.1)), 1)
textAttachment.displaySize = CGSize(width: targetWidth, height: round(targetHeight))
textAttachment.verticalAlignment = .center
} else if lowercasedClasses.contains("rd-front-cover-image") {
let originalSize = textAttachment.originalSize
let maxWidth = max(UIScreen.main.bounds.width - 48, font.lineHeight * 8)
if originalSize.width > 0, originalSize.height > 0 {
let scaledHeight = round(originalSize.height * (maxWidth / originalSize.width))
textAttachment.displaySize = CGSize(width: round(maxWidth), height: scaledHeight)
} else {
textAttachment.displaySize = CGSize(width: round(maxWidth), height: round(maxWidth * 1.4))
}
textAttachment.verticalAlignment = .baseline
}
attributes[.attachment] = textAttachment
return
}
#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
}
}
private static func darkCSS(style: RDEPUBTextRenderStyle) -> String {
let background = style.backgroundColor?.ss_cssString ?? "rgba(0, 0, 0, 1.000)"
let text = style.textColor?.ss_cssString ?? "rgba(255, 255, 255, 1.000)"