Epub阅读器0.0.1
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
import Foundation
|
||||
|
||||
enum RDEPUBAsset: String {
|
||||
case bridgeScript = "epub-bridge"
|
||||
case fixedLayoutTemplate = "epub-fixed-layout"
|
||||
|
||||
var fileExtension: String {
|
||||
switch self {
|
||||
case .bridgeScript:
|
||||
return "js"
|
||||
case .fixedLayoutTemplate:
|
||||
return "html"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum RDEPUBAssetRepository {
|
||||
static func string(for asset: RDEPUBAsset, replacements: [String: String] = [:]) -> String {
|
||||
guard let url = resourceBundle.url(forResource: asset.rawValue, withExtension: asset.fileExtension),
|
||||
var content = try? String(contentsOf: url, encoding: .utf8) else {
|
||||
assertionFailure("Missing EPUB asset: \(asset.rawValue).\(asset.fileExtension)")
|
||||
return ""
|
||||
}
|
||||
|
||||
for (token, value) in replacements {
|
||||
content = content.replacingOccurrences(of: "{{\(token)}}", with: value)
|
||||
}
|
||||
return content
|
||||
}
|
||||
|
||||
private static var resourceBundle: Bundle {
|
||||
if let bundle = resolvedBundle {
|
||||
return bundle
|
||||
}
|
||||
return Bundle(for: RDEPUBAssetBundleToken.self)
|
||||
}
|
||||
|
||||
private static var resolvedBundle: Bundle? = {
|
||||
let hostBundles = [Bundle(for: RDEPUBAssetBundleToken.self), Bundle.main] + Bundle.allFrameworks + Bundle.allBundles
|
||||
for hostBundle in hostBundles {
|
||||
if let url = hostBundle.url(forResource: "RDReaderViewAssets", withExtension: "bundle"),
|
||||
let bundle = Bundle(url: url) {
|
||||
return bundle
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}()
|
||||
}
|
||||
|
||||
private final class RDEPUBAssetBundleToken {}
|
||||
@@ -0,0 +1,49 @@
|
||||
import Foundation
|
||||
|
||||
enum RDEPUBFixedLayoutTemplate {
|
||||
static func html(for request: RDEPUBFixedRenderRequest, publication: RDEPUBPublication) -> String {
|
||||
let panes = request.spread.resources.enumerated().compactMap { index, resource -> String? in
|
||||
guard let url = publication.resourceResolver.resourceURL(forRelativePath: resource.href)?.absoluteString else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let pageType: String
|
||||
if request.spread.resources.count == 1 {
|
||||
pageType = "single"
|
||||
} else if request.spread.resources.count == 2 {
|
||||
pageType = index == 0 ? "left" : "right"
|
||||
} else {
|
||||
pageType = "center"
|
||||
}
|
||||
|
||||
return """
|
||||
<div class=\"ss-fixed-viewport\" data-page-type=\"\(pageType)\">
|
||||
<iframe class=\"ss-fixed-page\" data-page-type=\"\(pageType)\" scrolling=\"no\" src=\"\(url)\"></iframe>
|
||||
</div>
|
||||
"""
|
||||
}.joined()
|
||||
|
||||
let background = request.backgroundColorCSS ?? "#FFFFFF"
|
||||
let viewportWidth = max(1, Int((request.viewportSize.width - request.contentInset.left - request.contentInset.right).rounded(.down)))
|
||||
let viewportHeight = max(1, Int((request.viewportSize.height - request.contentInset.top - request.contentInset.bottom).rounded(.down)))
|
||||
let insetTop = Int(request.contentInset.top.rounded(.down))
|
||||
let insetRight = Int(request.contentInset.right.rounded(.down))
|
||||
let insetBottom = Int(request.contentInset.bottom.rounded(.down))
|
||||
let insetLeft = Int(request.contentInset.left.rounded(.down))
|
||||
return RDEPUBAssetRepository.string(
|
||||
for: .fixedLayoutTemplate,
|
||||
replacements: [
|
||||
"BACKGROUND": background,
|
||||
"INSET_TOP": String(insetTop),
|
||||
"INSET_RIGHT": String(insetRight),
|
||||
"INSET_BOTTOM": String(insetBottom),
|
||||
"INSET_LEFT": String(insetLeft),
|
||||
"VIEWPORT_WIDTH": String(viewportWidth),
|
||||
"VIEWPORT_HEIGHT": String(viewportHeight),
|
||||
"PANES": panes,
|
||||
"FIT_MODE": request.fit.rawValue,
|
||||
"FIXED_LAYOUT_READY_MESSAGE": RDEPUBJavaScriptBridgeMessage.fixedLayoutReady.rawValue
|
||||
]
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
import Foundation
|
||||
|
||||
enum RDEPUBJavaScriptBridgeMessage: String, CaseIterable {
|
||||
case progressionChanged = "ssReaderProgressionChanged"
|
||||
case selectionChanged = "ssReaderSelectionChanged"
|
||||
case internalLink = "ssReaderInternalLink"
|
||||
case externalLink = "ssReaderExternalLink"
|
||||
case javaScriptError = "ssReaderJSError"
|
||||
case fixedLayoutReady = "ssReaderFixedLayoutReady"
|
||||
}
|
||||
|
||||
enum RDEPUBJavaScriptBridge {
|
||||
static var messageNames: [String] {
|
||||
RDEPUBJavaScriptBridgeMessage.allCases.map(\.rawValue)
|
||||
}
|
||||
|
||||
static var userScript: String {
|
||||
RDEPUBAssetRepository.string(
|
||||
for: .bridgeScript,
|
||||
replacements: [
|
||||
"PROGRESSION_CHANGED_MESSAGE": RDEPUBJavaScriptBridgeMessage.progressionChanged.rawValue,
|
||||
"SELECTION_CHANGED_MESSAGE": RDEPUBJavaScriptBridgeMessage.selectionChanged.rawValue,
|
||||
"INTERNAL_LINK_MESSAGE": RDEPUBJavaScriptBridgeMessage.internalLink.rawValue,
|
||||
"EXTERNAL_LINK_MESSAGE": RDEPUBJavaScriptBridgeMessage.externalLink.rawValue,
|
||||
"JAVASCRIPT_ERROR_MESSAGE": RDEPUBJavaScriptBridgeMessage.javaScriptError.rawValue,
|
||||
"FIXED_LAYOUT_READY_MESSAGE": RDEPUBJavaScriptBridgeMessage.fixedLayoutReady.rawValue
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
static func applyPresentationScript(for request: RDEPUBReflowableRenderRequest) -> String {
|
||||
let style = escapedJavaScriptTemplateLiteral(RDEPUBStyleSheetBuilder.renderCSS(for: request.presentation))
|
||||
let pageStride = max(1, request.presentation.viewportSize.width)
|
||||
let searchScript = applySearchScript(for: request.searchPresentation)
|
||||
|
||||
return """
|
||||
(function() {
|
||||
if (!window.RDReaderBridge) { return false; }
|
||||
window.RDReaderBridge.applyPagination(`\(style)`);
|
||||
window.RDReaderBridge.setPageMetrics(\(request.totalPagesInChapter), \(pageStride));
|
||||
window.RDReaderBridge.clearHighlights();
|
||||
window.RDReaderBridge.setHighlights(\(jsonString(from: highlightsPayload(request.highlights), fallback: "[]")));
|
||||
if (\(jsonString(from: targetLocationPayload(request.targetLocation), fallback: "null")) !== null) {
|
||||
window.RDReaderBridge.scrollToLocation(\(jsonString(from: targetLocationPayload(request.targetLocation), fallback: "null")), \(request.pageIndex));
|
||||
} else {
|
||||
window.RDReaderBridge.scrollToPage(\(request.pageIndex));
|
||||
}
|
||||
window.RDReaderBridge.reportProgression();
|
||||
return true;
|
||||
})();
|
||||
\(searchScript)
|
||||
"""
|
||||
}
|
||||
|
||||
static func applySearchScript(for presentation: RDEPUBSearchPresentation?) -> String {
|
||||
let payload = jsonString(from: searchPayload(presentation), fallback: "null")
|
||||
return """
|
||||
(function() {
|
||||
var payload = \(payload);
|
||||
function normalizeHref(rawHref) {
|
||||
if (!rawHref) { return ''; }
|
||||
var value = String(rawHref);
|
||||
value = value.replace(/^.*?:\\/\\/[^/]+\\//, '');
|
||||
value = value.split('#')[0];
|
||||
value = value.replace(/^\\/+/, '');
|
||||
try {
|
||||
value = decodeURIComponent(value);
|
||||
} catch (error) {
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function ensureStyle(doc) {
|
||||
if (!doc || !doc.head || doc.getElementById('ss-reader-search-style')) { return; }
|
||||
var style = doc.createElement('style');
|
||||
style.id = 'ss-reader-search-style';
|
||||
style.textContent = '.ss-reader-search-mark{background:rgba(248,225,108,0.55);color:inherit;border-radius:2px;padding:0;}.ss-reader-search-mark-active{background:rgba(255,159,67,0.75);color:inherit;border-radius:2px;padding:0;}';
|
||||
doc.head.appendChild(style);
|
||||
}
|
||||
|
||||
function clearMarks(doc) {
|
||||
if (!doc || !doc.body) { return; }
|
||||
var marks = doc.querySelectorAll('span.ss-reader-search-mark, span.ss-reader-search-mark-active');
|
||||
marks.forEach(function(mark) {
|
||||
var textNode = doc.createTextNode(mark.textContent || '');
|
||||
if (mark.parentNode) {
|
||||
mark.parentNode.replaceChild(textNode, mark);
|
||||
}
|
||||
});
|
||||
doc.body.normalize();
|
||||
}
|
||||
|
||||
function searchableDocuments(rootDoc) {
|
||||
var items = [];
|
||||
if (!rootDoc) { return items; }
|
||||
items.push({ doc: rootDoc, href: normalizeHref(rootDoc.location && rootDoc.location.href) });
|
||||
var frames = rootDoc.querySelectorAll ? rootDoc.querySelectorAll('iframe') : [];
|
||||
frames.forEach(function(frame) {
|
||||
try {
|
||||
if (frame.contentDocument) {
|
||||
items.push({
|
||||
doc: frame.contentDocument,
|
||||
href: normalizeHref(frame.contentWindow && frame.contentWindow.location && frame.contentWindow.location.href)
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
}
|
||||
});
|
||||
return items;
|
||||
}
|
||||
|
||||
function textNodes(doc) {
|
||||
if (!doc || !doc.body) { return []; }
|
||||
var walker = doc.createTreeWalker(doc.body, NodeFilter.SHOW_TEXT, {
|
||||
acceptNode: function(node) {
|
||||
if (!node || !node.nodeValue || !node.nodeValue.trim()) {
|
||||
return NodeFilter.FILTER_REJECT;
|
||||
}
|
||||
var parent = node.parentNode;
|
||||
if (!parent || !parent.nodeName) {
|
||||
return NodeFilter.FILTER_REJECT;
|
||||
}
|
||||
var name = parent.nodeName.toLowerCase();
|
||||
if (['script', 'style', 'noscript'].indexOf(name) >= 0) {
|
||||
return NodeFilter.FILTER_REJECT;
|
||||
}
|
||||
if (parent.classList && (parent.classList.contains('ss-reader-search-mark') || parent.classList.contains('ss-reader-search-mark-active'))) {
|
||||
return NodeFilter.FILTER_REJECT;
|
||||
}
|
||||
return NodeFilter.FILTER_ACCEPT;
|
||||
}
|
||||
});
|
||||
|
||||
var nodes = [];
|
||||
while (walker.nextNode()) {
|
||||
nodes.push(walker.currentNode);
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
|
||||
function applyToDocument(doc, resourceState, keyword) {
|
||||
clearMarks(doc);
|
||||
ensureStyle(doc);
|
||||
if (!doc || !doc.body || !resourceState || !keyword || resourceState.matchCount <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
var lowerKeyword = String(keyword).toLowerCase();
|
||||
var activeIndex = typeof resourceState.activeLocalMatchIndex === 'number' ? resourceState.activeLocalMatchIndex : null;
|
||||
var currentLocalIndex = 0;
|
||||
var activeElement = null;
|
||||
|
||||
textNodes(doc).forEach(function(node) {
|
||||
var source = node.nodeValue || '';
|
||||
var lowerSource = source.toLowerCase();
|
||||
var cursor = 0;
|
||||
var replaced = false;
|
||||
var fragment = doc.createDocumentFragment();
|
||||
|
||||
while (cursor < source.length) {
|
||||
var foundIndex = lowerSource.indexOf(lowerKeyword, cursor);
|
||||
if (foundIndex < 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
replaced = true;
|
||||
if (foundIndex > cursor) {
|
||||
fragment.appendChild(doc.createTextNode(source.slice(cursor, foundIndex)));
|
||||
}
|
||||
|
||||
var mark = doc.createElement('span');
|
||||
mark.className = currentLocalIndex === activeIndex ? 'ss-reader-search-mark-active' : 'ss-reader-search-mark';
|
||||
mark.textContent = source.slice(foundIndex, foundIndex + keyword.length);
|
||||
fragment.appendChild(mark);
|
||||
if (currentLocalIndex === activeIndex) {
|
||||
activeElement = mark;
|
||||
}
|
||||
|
||||
currentLocalIndex += 1;
|
||||
cursor = foundIndex + keyword.length;
|
||||
}
|
||||
|
||||
if (!replaced) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (cursor < source.length) {
|
||||
fragment.appendChild(doc.createTextNode(source.slice(cursor)));
|
||||
}
|
||||
if (node.parentNode) {
|
||||
node.parentNode.replaceChild(fragment, node);
|
||||
}
|
||||
});
|
||||
|
||||
if (activeElement && activeElement.scrollIntoView) {
|
||||
activeElement.scrollIntoView({ block: 'center', inline: 'center', behavior: 'auto' });
|
||||
}
|
||||
}
|
||||
|
||||
var docs = searchableDocuments(document);
|
||||
var states = new Map();
|
||||
if (payload && Array.isArray(payload.resources)) {
|
||||
payload.resources.forEach(function(resource) {
|
||||
states.set(normalizeHref(resource.href), resource);
|
||||
});
|
||||
}
|
||||
|
||||
docs.forEach(function(item) {
|
||||
applyToDocument(item.doc, states.get(item.href), payload && payload.keyword ? payload.keyword : '');
|
||||
});
|
||||
return true;
|
||||
})();
|
||||
"""
|
||||
}
|
||||
|
||||
private static func escapedJavaScriptTemplateLiteral(_ string: String) -> String {
|
||||
string
|
||||
.replacingOccurrences(of: "\\", with: "\\\\")
|
||||
.replacingOccurrences(of: "`", with: "\\`")
|
||||
}
|
||||
|
||||
private static func highlightsPayload(_ highlights: [RDEPUBHighlight]) -> [[String: String]] {
|
||||
highlights.compactMap { highlight in
|
||||
guard let rangeInfo = highlight.rangeInfo, !rangeInfo.isEmpty else { return nil }
|
||||
return [
|
||||
"id": highlight.id,
|
||||
"rangeInfo": rangeInfo,
|
||||
"color": highlight.color,
|
||||
"style": highlight.style.rawValue
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
private static func targetLocationPayload(_ location: RDEPUBLocation?) -> [String: Any]? {
|
||||
guard let location else { return nil }
|
||||
return [
|
||||
"progression": location.progression,
|
||||
"lastProgression": location.lastProgression ?? location.progression,
|
||||
"fragment": location.fragment as Any
|
||||
]
|
||||
}
|
||||
|
||||
private static func searchPayload(_ presentation: RDEPUBSearchPresentation?) -> [String: Any]? {
|
||||
guard let presentation else { return nil }
|
||||
return [
|
||||
"keyword": presentation.keyword,
|
||||
"resources": presentation.resources.map { resource in
|
||||
[
|
||||
"href": resource.href,
|
||||
"matchCount": resource.matchCount,
|
||||
"activeLocalMatchIndex": resource.activeLocalMatchIndex as Any
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
private static func jsonString(from object: Any?, fallback: String) -> String {
|
||||
guard let object else { return fallback }
|
||||
guard JSONSerialization.isValidJSONObject(object),
|
||||
let data = try? JSONSerialization.data(withJSONObject: object, options: []),
|
||||
let string = String(data: data, encoding: .utf8) else {
|
||||
return fallback
|
||||
}
|
||||
return string
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import Foundation
|
||||
|
||||
public enum RDEPUBLayout: String, Codable {
|
||||
case reflowable
|
||||
case fixed
|
||||
}
|
||||
|
||||
public enum RDEPUBReadingProfile: String, Codable {
|
||||
case webInteractive
|
||||
case webFixedLayout
|
||||
case textReflowable
|
||||
}
|
||||
|
||||
public enum RDEPUBReadingProgression: String, Codable {
|
||||
case ltr
|
||||
case rtl
|
||||
case auto
|
||||
}
|
||||
|
||||
public enum RDEPUBPageSpread: String, Codable {
|
||||
case left
|
||||
case right
|
||||
case center
|
||||
}
|
||||
|
||||
public struct RDEPUBMetadata: Codable, Equatable {
|
||||
public var identifier: String?
|
||||
public var title: String
|
||||
public var author: String?
|
||||
public var language: String?
|
||||
public var version: String?
|
||||
public var layout: RDEPUBLayout
|
||||
public var spread: String?
|
||||
public var readingProgression: RDEPUBReadingProgression
|
||||
|
||||
public init(
|
||||
identifier: String? = nil,
|
||||
title: String = "",
|
||||
author: String? = nil,
|
||||
language: String? = nil,
|
||||
version: String? = nil,
|
||||
layout: RDEPUBLayout = .reflowable,
|
||||
spread: String? = nil,
|
||||
readingProgression: RDEPUBReadingProgression = .auto
|
||||
) {
|
||||
self.identifier = identifier
|
||||
self.title = title
|
||||
self.author = author
|
||||
self.language = language
|
||||
self.version = version
|
||||
self.layout = layout
|
||||
self.spread = spread
|
||||
self.readingProgression = readingProgression
|
||||
}
|
||||
}
|
||||
|
||||
public struct RDEPUBManifestItem: Codable, Equatable {
|
||||
public var id: String
|
||||
public var href: String
|
||||
public var mediaType: String
|
||||
public var properties: [String]
|
||||
public var fallback: String?
|
||||
public var mediaOverlay: String?
|
||||
public var title: String?
|
||||
|
||||
public init(
|
||||
id: String,
|
||||
href: String,
|
||||
mediaType: String,
|
||||
properties: [String] = [],
|
||||
fallback: String? = nil,
|
||||
mediaOverlay: String? = nil,
|
||||
title: String? = nil
|
||||
) {
|
||||
self.id = id
|
||||
self.href = href
|
||||
self.mediaType = mediaType
|
||||
self.properties = properties
|
||||
self.fallback = fallback
|
||||
self.mediaOverlay = mediaOverlay
|
||||
self.title = title
|
||||
}
|
||||
|
||||
public var isNavigationDocument: Bool {
|
||||
properties.contains("nav")
|
||||
}
|
||||
|
||||
public var isNCX: Bool {
|
||||
mediaType == "application/x-dtbncx+xml"
|
||||
}
|
||||
}
|
||||
|
||||
public struct RDEPUBSpineItem: Codable, Equatable {
|
||||
public var idref: String
|
||||
public var href: String
|
||||
public var mediaType: String
|
||||
public var title: String
|
||||
public var linear: Bool
|
||||
public var properties: [String]
|
||||
public var pageSpread: RDEPUBPageSpread?
|
||||
public var layout: RDEPUBLayout?
|
||||
|
||||
public init(
|
||||
idref: String,
|
||||
href: String,
|
||||
mediaType: String,
|
||||
title: String,
|
||||
linear: Bool = true,
|
||||
properties: [String] = [],
|
||||
pageSpread: RDEPUBPageSpread? = nil,
|
||||
layout: RDEPUBLayout? = nil
|
||||
) {
|
||||
self.idref = idref
|
||||
self.href = href
|
||||
self.mediaType = mediaType
|
||||
self.title = title
|
||||
self.linear = linear
|
||||
self.properties = properties
|
||||
self.pageSpread = pageSpread
|
||||
self.layout = layout
|
||||
}
|
||||
}
|
||||
|
||||
public struct EPUBTableOfContentsItem: Codable, Equatable {
|
||||
public var title: String
|
||||
public var href: String
|
||||
public var children: [EPUBTableOfContentsItem]
|
||||
|
||||
public init(title: String, href: String, children: [EPUBTableOfContentsItem] = []) {
|
||||
self.title = title
|
||||
self.href = href
|
||||
self.children = children
|
||||
}
|
||||
}
|
||||
|
||||
public enum RDEPUBParserError: LocalizedError {
|
||||
case archiveOpenFailed(URL)
|
||||
case missingContainerXML
|
||||
case missingRootFile
|
||||
case invalidRootFilePath(String)
|
||||
case invalidXML(URL)
|
||||
case missingManifestItem(idref: String)
|
||||
case emptySpine
|
||||
|
||||
public var errorDescription: String? {
|
||||
switch self {
|
||||
case .archiveOpenFailed(let url):
|
||||
return "无法打开 EPUB 压缩包: \(url.lastPathComponent)"
|
||||
case .missingContainerXML:
|
||||
return "EPUB 缺少 META-INF/container.xml"
|
||||
case .missingRootFile:
|
||||
return "container.xml 中未找到 rootfile"
|
||||
case .invalidRootFilePath(let path):
|
||||
return "OPF 路径无效: \(path)"
|
||||
case .invalidXML(let url):
|
||||
return "XML 解析失败: \(url.lastPathComponent)"
|
||||
case .missingManifestItem(let idref):
|
||||
return "spine itemref 找不到对应 manifest 项: \(idref)"
|
||||
case .emptySpine:
|
||||
return "OPF spine 为空"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import UIKit
|
||||
|
||||
public struct RDEPUBNavigatorLayoutContext: Equatable {
|
||||
public var containerSize: CGSize
|
||||
public var pagesPerScreen: Int
|
||||
public var safeAreaInsets: UIEdgeInsets
|
||||
public var userInterfaceIdiom: UIUserInterfaceIdiom
|
||||
public var reflowableContentInsets: UIEdgeInsets
|
||||
|
||||
public init(
|
||||
containerSize: CGSize,
|
||||
pagesPerScreen: Int = 1,
|
||||
safeAreaInsets: UIEdgeInsets = .zero,
|
||||
userInterfaceIdiom: UIUserInterfaceIdiom = .phone,
|
||||
reflowableContentInsets: UIEdgeInsets = UIEdgeInsets(top: 40, left: 16, bottom: 40, right: 16)
|
||||
) {
|
||||
self.containerSize = containerSize
|
||||
self.pagesPerScreen = max(1, pagesPerScreen)
|
||||
self.safeAreaInsets = safeAreaInsets
|
||||
self.userInterfaceIdiom = userInterfaceIdiom
|
||||
self.reflowableContentInsets = reflowableContentInsets
|
||||
}
|
||||
|
||||
public var viewportSize: CGSize {
|
||||
let width: CGFloat
|
||||
if pagesPerScreen > 1 {
|
||||
width = containerSize.width / CGFloat(pagesPerScreen)
|
||||
} else {
|
||||
width = containerSize.width
|
||||
}
|
||||
return CGSize(width: width, height: containerSize.height)
|
||||
}
|
||||
|
||||
public var fixedContentInset: UIEdgeInsets {
|
||||
var insets = safeAreaInsets
|
||||
if userInterfaceIdiom != .phone {
|
||||
insets = .zero
|
||||
}
|
||||
|
||||
let horizontalInsets = max(insets.left, insets.right)
|
||||
insets.left = horizontalInsets
|
||||
insets.right = horizontalInsets
|
||||
return insets
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import Foundation
|
||||
|
||||
public enum RDEPUBNavigatorState: String, Codable {
|
||||
case initializing
|
||||
case loading
|
||||
case idle
|
||||
case jumping
|
||||
case moving
|
||||
case repaginating
|
||||
|
||||
public var isStableForSnapshotApplication: Bool {
|
||||
self == .idle
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
import UIKit
|
||||
import WebKit
|
||||
|
||||
public final class RDEPUBPaginator: NSObject {
|
||||
private var parser: RDEPUBParser?
|
||||
private weak var hostingView: UIView?
|
||||
private var presentation = RDEPUBPresentationStyle(
|
||||
viewportSize: .zero,
|
||||
contentInsets: .zero,
|
||||
fontSize: 16,
|
||||
lineHeightMultiple: 1.5
|
||||
)
|
||||
private var completion: (([Int]) -> Void)?
|
||||
private var singlePageCountCompletion: ((Int) -> Void)?
|
||||
private var pageCounts: [Int] = []
|
||||
private var measurementIndices: [Int] = []
|
||||
private var currentMeasurementOffset = 0
|
||||
private var pendingMeasurementValue = 1
|
||||
private var measurementPass = 0
|
||||
private var activeSessionID = UUID()
|
||||
private let debugScope = "PaginatorWebView"
|
||||
|
||||
private lazy var webView: WKWebView = {
|
||||
let configuration = WKWebViewConfiguration()
|
||||
configuration.websiteDataStore = .nonPersistent()
|
||||
let webView = WKWebView(frame: .zero, configuration: configuration)
|
||||
webView.navigationDelegate = self
|
||||
webView.isOpaque = false
|
||||
webView.backgroundColor = .clear
|
||||
webView.scrollView.isScrollEnabled = false
|
||||
webView.scrollView.bounces = false
|
||||
webView.scrollView.showsHorizontalScrollIndicator = false
|
||||
webView.scrollView.showsVerticalScrollIndicator = false
|
||||
webView.isUserInteractionEnabled = false
|
||||
if #available(iOS 16.4, *) {
|
||||
webView.isInspectable = true
|
||||
} else {
|
||||
// Fallback on earlier versions
|
||||
}
|
||||
RDEPUBWebViewDebug.log("PaginatorWebView", message: "configured webView=\(RDEPUBWebViewDebug.webViewID(webView))")
|
||||
return webView
|
||||
}()
|
||||
|
||||
public override init() {
|
||||
super.init()
|
||||
}
|
||||
|
||||
deinit {
|
||||
cleanupMeasurementState()
|
||||
webView.navigationDelegate = nil
|
||||
webView.stopLoading()
|
||||
webView.removeFromSuperview()
|
||||
}
|
||||
|
||||
public func calculate(
|
||||
parser: RDEPUBParser,
|
||||
hostingView: UIView,
|
||||
presentation: RDEPUBPresentationStyle,
|
||||
completion: @escaping ([Int]) -> Void
|
||||
) {
|
||||
self.parser = parser
|
||||
self.hostingView = hostingView
|
||||
self.presentation = presentation
|
||||
self.completion = completion
|
||||
self.singlePageCountCompletion = nil
|
||||
self.pageCounts = Array(repeating: 1, count: parser.spine.count)
|
||||
self.measurementIndices = Array(parser.spine.indices)
|
||||
self.currentMeasurementOffset = 0
|
||||
self.activeSessionID = UUID()
|
||||
RDEPUBWebViewDebug.log(debugScope, message: "calculate session=\(activeSessionID) spineCount=\(parser.spine.count)")
|
||||
|
||||
guard parser.metadata.layout != .fixed else {
|
||||
completion(self.pageCounts)
|
||||
return
|
||||
}
|
||||
|
||||
webView.navigationDelegate = self
|
||||
if webView.superview == nil {
|
||||
hostingView.addSubview(webView)
|
||||
}
|
||||
webView.frame = CGRect(origin: .zero, size: presentation.viewportSize)
|
||||
measureNextSpineItem()
|
||||
}
|
||||
|
||||
public func calculate(
|
||||
parser: RDEPUBParser,
|
||||
hostingView: UIView,
|
||||
viewportSize: CGSize,
|
||||
padding: UIEdgeInsets,
|
||||
fontSize: CGFloat,
|
||||
lineHeightMultiple: CGFloat,
|
||||
completion: @escaping ([Int]) -> Void
|
||||
) {
|
||||
calculate(
|
||||
parser: parser,
|
||||
hostingView: hostingView,
|
||||
presentation: RDEPUBPresentationStyle(
|
||||
viewportSize: viewportSize,
|
||||
contentInsets: padding,
|
||||
fontSize: fontSize,
|
||||
lineHeightMultiple: lineHeightMultiple
|
||||
),
|
||||
completion: completion
|
||||
)
|
||||
}
|
||||
|
||||
public func calculateSingleSpinePageCount(
|
||||
parser: RDEPUBParser,
|
||||
spineIndex: Int,
|
||||
hostingView: UIView,
|
||||
presentation: RDEPUBPresentationStyle,
|
||||
completion: @escaping (Int) -> Void
|
||||
) {
|
||||
self.parser = parser
|
||||
self.hostingView = hostingView
|
||||
self.presentation = presentation
|
||||
self.completion = nil
|
||||
self.singlePageCountCompletion = completion
|
||||
self.pageCounts = Array(repeating: 1, count: parser.spine.count)
|
||||
self.measurementIndices = parser.spine.indices.contains(spineIndex) ? [spineIndex] : []
|
||||
self.currentMeasurementOffset = 0
|
||||
self.activeSessionID = UUID()
|
||||
RDEPUBWebViewDebug.log(debugScope, message: "calculateSingle session=\(activeSessionID) spineIndex=\(spineIndex)")
|
||||
|
||||
guard parser.metadata.layout != .fixed, !measurementIndices.isEmpty else {
|
||||
completion(1)
|
||||
return
|
||||
}
|
||||
|
||||
webView.navigationDelegate = self
|
||||
if webView.superview == nil {
|
||||
hostingView.addSubview(webView)
|
||||
}
|
||||
webView.frame = CGRect(origin: .zero, size: presentation.viewportSize)
|
||||
measureNextSpineItem()
|
||||
}
|
||||
|
||||
public func calculateSingleSpinePageCount(
|
||||
parser: RDEPUBParser,
|
||||
spineIndex: Int,
|
||||
hostingView: UIView,
|
||||
viewportSize: CGSize,
|
||||
padding: UIEdgeInsets,
|
||||
fontSize: CGFloat,
|
||||
lineHeightMultiple: CGFloat,
|
||||
completion: @escaping (Int) -> Void
|
||||
) {
|
||||
calculateSingleSpinePageCount(
|
||||
parser: parser,
|
||||
spineIndex: spineIndex,
|
||||
hostingView: hostingView,
|
||||
presentation: RDEPUBPresentationStyle(
|
||||
viewportSize: viewportSize,
|
||||
contentInsets: padding,
|
||||
fontSize: fontSize,
|
||||
lineHeightMultiple: lineHeightMultiple
|
||||
),
|
||||
completion: completion
|
||||
)
|
||||
}
|
||||
|
||||
public static func injectPaginationCSS(
|
||||
into html: String,
|
||||
viewportSize: CGSize,
|
||||
padding: UIEdgeInsets,
|
||||
fontSize: CGFloat,
|
||||
lineHeightMultiple: CGFloat,
|
||||
themeBackgroundColor: String? = nil,
|
||||
themeTextColor: String? = nil
|
||||
) -> String {
|
||||
RDEPUBStyleSheetBuilder.injectPaginationCSS(
|
||||
into: html,
|
||||
presentation: RDEPUBPresentationStyle(
|
||||
viewportSize: viewportSize,
|
||||
contentInsets: padding,
|
||||
fontSize: fontSize,
|
||||
lineHeightMultiple: lineHeightMultiple,
|
||||
themeBackgroundColor: themeBackgroundColor,
|
||||
themeTextColor: themeTextColor
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private func measureNextSpineItem() {
|
||||
guard let parser else {
|
||||
finishIfNeeded()
|
||||
return
|
||||
}
|
||||
|
||||
guard currentMeasurementOffset < measurementIndices.count else {
|
||||
finishIfNeeded()
|
||||
return
|
||||
}
|
||||
|
||||
let currentSpineIndex = measurementIndices[currentMeasurementOffset]
|
||||
|
||||
let item = parser.spine[currentSpineIndex]
|
||||
guard isRenderablePage(item: item),
|
||||
let opfDirectoryURL = parser.opfDirectoryURL else {
|
||||
pageCounts[currentSpineIndex] = 1
|
||||
currentMeasurementOffset += 1
|
||||
measureNextSpineItem()
|
||||
return
|
||||
}
|
||||
|
||||
let fileURL = opfDirectoryURL.appendingPathComponent(item.href)
|
||||
guard FileManager.default.fileExists(atPath: fileURL.path) else {
|
||||
pageCounts[currentSpineIndex] = 1
|
||||
currentMeasurementOffset += 1
|
||||
measureNextSpineItem()
|
||||
return
|
||||
}
|
||||
|
||||
pendingMeasurementValue = 1
|
||||
measurementPass = 0
|
||||
let readAccessURL = parser.extractionRootURL ?? opfDirectoryURL
|
||||
RDEPUBWebViewDebug.logNavigationEvent(debugScope, webView: webView, event: "measure-load", url: fileURL)
|
||||
webView.loadFileURL(fileURL, allowingReadAccessTo: readAccessURL)
|
||||
}
|
||||
|
||||
private func currentSpineIndexForMeasurement() -> Int? {
|
||||
measurementIndices[safe: currentMeasurementOffset]
|
||||
}
|
||||
|
||||
private func finishIfNeeded() {
|
||||
if let singlePageCountCompletion {
|
||||
let measuredSpineIndex = measurementIndices.first ?? 0
|
||||
singlePageCountCompletion(max(1, pageCounts[safe: measuredSpineIndex] ?? 1))
|
||||
self.singlePageCountCompletion = nil
|
||||
cleanupMeasurementState()
|
||||
return
|
||||
}
|
||||
guard let completion else { return }
|
||||
completion(pageCounts)
|
||||
self.completion = nil
|
||||
cleanupMeasurementState()
|
||||
}
|
||||
|
||||
private func cleanupMeasurementState() {
|
||||
parser = nil
|
||||
hostingView = nil
|
||||
completion = nil
|
||||
singlePageCountCompletion = nil
|
||||
measurementIndices = []
|
||||
currentMeasurementOffset = 0
|
||||
pendingMeasurementValue = 1
|
||||
measurementPass = 0
|
||||
activeSessionID = UUID()
|
||||
webView.stopLoading()
|
||||
webView.navigationDelegate = nil
|
||||
webView.removeFromSuperview()
|
||||
}
|
||||
|
||||
private func isRenderablePage(item: RDEPUBSpineItem) -> Bool {
|
||||
let mediaType = item.mediaType.lowercased()
|
||||
return mediaType.contains("html") || mediaType.contains("xhtml") || mediaType.contains("xml")
|
||||
}
|
||||
|
||||
private func scheduleMeasurementPass() {
|
||||
let sessionID = activeSessionID
|
||||
let delays: [TimeInterval] = [0.0, 0.08, 0.18]
|
||||
guard measurementPass < delays.count else {
|
||||
guard sessionID == activeSessionID,
|
||||
let currentSpineIndex = currentSpineIndexForMeasurement() else {
|
||||
return
|
||||
}
|
||||
pageCounts[currentSpineIndex] = max(1, pendingMeasurementValue)
|
||||
currentMeasurementOffset += 1
|
||||
measureNextSpineItem()
|
||||
return
|
||||
}
|
||||
|
||||
let delay = delays[measurementPass]
|
||||
measurementPass += 1
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in
|
||||
guard let self, self.activeSessionID == sessionID else { return }
|
||||
self.measureCurrentDocument(sessionID: sessionID)
|
||||
}
|
||||
}
|
||||
|
||||
private func measureCurrentDocument(sessionID: UUID) {
|
||||
let script = RDEPUBStyleSheetBuilder.measurementScript(for: presentation)
|
||||
RDEPUBWebViewDebug.logJavaScript(debugScope, webView: webView, action: "measure", details: "session=\(sessionID) pass=\(measurementPass)")
|
||||
|
||||
webView.evaluateJavaScript(script) { [weak self] value, _ in
|
||||
guard let self else { return }
|
||||
guard self.activeSessionID == sessionID,
|
||||
self.currentSpineIndexForMeasurement() != nil else {
|
||||
return
|
||||
}
|
||||
if let number = value as? NSNumber {
|
||||
self.pendingMeasurementValue = max(self.pendingMeasurementValue, number.intValue)
|
||||
} else if let intValue = value as? Int {
|
||||
self.pendingMeasurementValue = max(self.pendingMeasurementValue, intValue)
|
||||
}
|
||||
RDEPUBWebViewDebug.log(self.debugScope, message: "measurement value=\(self.pendingMeasurementValue) session=\(sessionID)")
|
||||
self.scheduleMeasurementPass()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension RDEPUBPaginator: WKNavigationDelegate {
|
||||
public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
|
||||
RDEPUBWebViewDebug.logNavigationEvent(debugScope, webView: webView, event: "didStart", url: webView.url)
|
||||
}
|
||||
|
||||
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
|
||||
RDEPUBWebViewDebug.logNavigationEvent(debugScope, webView: webView, event: "didFinish", url: webView.url)
|
||||
guard currentSpineIndexForMeasurement() != nil else { return }
|
||||
scheduleMeasurementPass()
|
||||
}
|
||||
|
||||
public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
|
||||
RDEPUBWebViewDebug.logNavigationEvent(debugScope, webView: webView, event: "didFail", url: webView.url, error: error)
|
||||
let currentSpineIndex = measurementIndices[safe: currentMeasurementOffset] ?? 0
|
||||
pageCounts[currentSpineIndex] = 1
|
||||
currentMeasurementOffset += 1
|
||||
measureNextSpineItem()
|
||||
}
|
||||
|
||||
public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
|
||||
RDEPUBWebViewDebug.logNavigationEvent(debugScope, webView: webView, event: "didFailProvisional", url: webView.url, error: error)
|
||||
let currentSpineIndex = measurementIndices[safe: currentMeasurementOffset] ?? 0
|
||||
pageCounts[currentSpineIndex] = 1
|
||||
currentMeasurementOffset += 1
|
||||
measureNextSpineItem()
|
||||
}
|
||||
|
||||
public func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
|
||||
RDEPUBWebViewDebug.logNavigationEvent(debugScope, webView: webView, event: "processTerminated", url: webView.url)
|
||||
}
|
||||
}
|
||||
|
||||
private extension Array {
|
||||
subscript(safe index: Int) -> Element? {
|
||||
indices.contains(index) ? self[index] : nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import Foundation
|
||||
import ZIPFoundation
|
||||
|
||||
extension RDEPUBParser {
|
||||
func parseContainerRootFile(at containerURL: URL) throws -> String {
|
||||
guard let parser = XMLParser(contentsOf: containerURL) else {
|
||||
throw RDEPUBParserError.invalidXML(containerURL)
|
||||
}
|
||||
|
||||
let delegate = ContainerXMLParserDelegate()
|
||||
parser.shouldProcessNamespaces = false
|
||||
parser.delegate = delegate
|
||||
|
||||
guard parser.parse() else {
|
||||
throw parser.parserError ?? RDEPUBParserError.invalidXML(containerURL)
|
||||
}
|
||||
|
||||
guard let rootFilePath = delegate.rootFilePath, !rootFilePath.isEmpty else {
|
||||
throw RDEPUBParserError.missingRootFile
|
||||
}
|
||||
|
||||
return rootFilePath
|
||||
}
|
||||
|
||||
func extractArchiveIfNeeded(epubURL: URL) throws -> URL {
|
||||
let fileManager = FileManager.default
|
||||
let extractionURL = temporaryExtractionDirectory(for: epubURL)
|
||||
|
||||
if fileManager.fileExists(atPath: extractionURL.path) {
|
||||
return extractionURL
|
||||
}
|
||||
|
||||
guard let archive = Archive(url: epubURL, accessMode: .read) else {
|
||||
throw RDEPUBParserError.archiveOpenFailed(epubURL)
|
||||
}
|
||||
|
||||
try fileManager.createDirectory(at: extractionURL, withIntermediateDirectories: true)
|
||||
|
||||
for entry in archive {
|
||||
let destinationURL = extractionURL.appendingPathComponent(entry.path)
|
||||
switch entry.type {
|
||||
case .directory:
|
||||
try fileManager.createDirectory(at: destinationURL, withIntermediateDirectories: true)
|
||||
case .file:
|
||||
try fileManager.createDirectory(at: destinationURL.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
_ = try archive.extract(entry, to: destinationURL)
|
||||
case .symlink:
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
return extractionURL
|
||||
}
|
||||
|
||||
func temporaryExtractionDirectory(for epubURL: URL) -> URL {
|
||||
let baseURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?
|
||||
.appendingPathComponent("ssreaderview-epub", isDirectory: true)
|
||||
?? FileManager.default.temporaryDirectory.appendingPathComponent("ssreaderview-epub", isDirectory: true)
|
||||
let fileAttributes = try? FileManager.default.attributesOfItem(atPath: epubURL.path)
|
||||
let fileSize = (fileAttributes?[.size] as? NSNumber)?.stringValue ?? "0"
|
||||
let modifiedAt = (fileAttributes?[.modificationDate] as? Date)?.timeIntervalSince1970 ?? 0
|
||||
let slug = epubURL.deletingPathExtension().lastPathComponent
|
||||
.replacingOccurrences(of: " ", with: "-")
|
||||
let signature = String(format: "%.0f", modifiedAt)
|
||||
return baseURL.appendingPathComponent("\(slug)-\(fileSize)-\(signature)", isDirectory: true)
|
||||
}
|
||||
|
||||
func reset() {
|
||||
extractionRootURL = nil
|
||||
opfURL = nil
|
||||
resetPublicationState()
|
||||
}
|
||||
|
||||
func resetPublicationState() {
|
||||
metadata = RDEPUBMetadata()
|
||||
manifest = [:]
|
||||
spine = []
|
||||
tableOfContents = []
|
||||
}
|
||||
}
|
||||
|
||||
private final class ContainerXMLParserDelegate: NSObject, XMLParserDelegate {
|
||||
private(set) var rootFilePath: String?
|
||||
|
||||
func parser(
|
||||
_ parser: XMLParser,
|
||||
didStartElement elementName: String,
|
||||
namespaceURI: String?,
|
||||
qualifiedName qName: String?,
|
||||
attributes attributeDict: [String: String] = [:]
|
||||
) {
|
||||
let name = XMLName.localName(from: qName ?? elementName)
|
||||
guard name == "rootfile", rootFilePath == nil else {
|
||||
return
|
||||
}
|
||||
rootFilePath = attributeDict["full-path"]?.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
import Foundation
|
||||
|
||||
extension RDEPUBParser {
|
||||
func buildSpine(from packageDocument: OPFPackageDocument, opfURL: URL) throws -> [RDEPUBSpineItem] {
|
||||
let opfDirectoryURL = opfURL.deletingLastPathComponent()
|
||||
let publicationLayout = packageDocument.metadata.layout
|
||||
|
||||
let spineItems = try packageDocument.spineReferences.map { reference in
|
||||
guard let manifestItem = packageDocument.manifestByID[reference.idref] else {
|
||||
throw RDEPUBParserError.missingManifestItem(idref: reference.idref)
|
||||
}
|
||||
|
||||
let normalizedHref = normalize(href: manifestItem.href, relativeTo: opfDirectoryURL)
|
||||
let title = manifestItem.title?.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let fallbackTitle = normalizedHref
|
||||
.split(separator: "/")
|
||||
.last
|
||||
.map(String.init)
|
||||
.map { $0.replacingOccurrences(of: ".xhtml", with: "") }
|
||||
.map { $0.replacingOccurrences(of: ".html", with: "") }
|
||||
.flatMap { $0.isEmpty ? nil : $0 }
|
||||
?? reference.idref
|
||||
|
||||
let effectiveLayout: RDEPUBLayout?
|
||||
if reference.properties.contains("rendition:layout-pre-paginated") || manifestItem.properties.contains("rendition:layout-pre-paginated") {
|
||||
effectiveLayout = .fixed
|
||||
} else if reference.properties.contains("rendition:layout-reflowable") || manifestItem.properties.contains("rendition:layout-reflowable") {
|
||||
effectiveLayout = .reflowable
|
||||
} else {
|
||||
effectiveLayout = publicationLayout == .fixed ? .fixed : nil
|
||||
}
|
||||
|
||||
return RDEPUBSpineItem(
|
||||
idref: reference.idref,
|
||||
href: normalizedHref,
|
||||
mediaType: manifestItem.mediaType,
|
||||
title: title?.isEmpty == false ? title! : fallbackTitle,
|
||||
linear: reference.linear,
|
||||
properties: reference.properties,
|
||||
pageSpread: reference.pageSpread,
|
||||
layout: effectiveLayout
|
||||
)
|
||||
}
|
||||
|
||||
guard !spineItems.isEmpty else {
|
||||
throw RDEPUBParserError.emptySpine
|
||||
}
|
||||
|
||||
return spineItems
|
||||
}
|
||||
}
|
||||
|
||||
struct OPFPackageDocument {
|
||||
var metadata: RDEPUBMetadata
|
||||
var manifest: [RDEPUBManifestItem]
|
||||
var manifestByID: [String: RDEPUBManifestItem]
|
||||
var spineReferences: [OPFSpineReference]
|
||||
var ncxItem: RDEPUBManifestItem?
|
||||
var navigationItem: RDEPUBManifestItem?
|
||||
}
|
||||
|
||||
struct OPFSpineReference {
|
||||
var idref: String
|
||||
var linear: Bool
|
||||
var properties: [String]
|
||||
var pageSpread: RDEPUBPageSpread?
|
||||
}
|
||||
|
||||
final class OPFPackageParserDelegate: NSObject, XMLParserDelegate {
|
||||
private var metadata = RDEPUBMetadata()
|
||||
private var manifestItems: [RDEPUBManifestItem] = []
|
||||
private var spineReferences: [OPFSpineReference] = []
|
||||
private let xmlContext = XMLParserContext()
|
||||
private var uniqueIdentifierID: String?
|
||||
private var currentIdentifierElementID: String?
|
||||
private var currentMetaProperty: String?
|
||||
private var identifierByID: [String: String] = [:]
|
||||
private var manifestTitleByID: [String: String] = [:]
|
||||
private var currentMetaRefinesID: String?
|
||||
private var ncxID: String?
|
||||
|
||||
func packageDocument() -> OPFPackageDocument {
|
||||
if metadata.identifier == nil, let fallbackIdentifier = identifierByID.values.first {
|
||||
metadata.identifier = fallbackIdentifier
|
||||
}
|
||||
metadata.title = metadata.title.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
metadata.author = metadata.author?.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
metadata.language = metadata.language?.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
|
||||
let manifest = manifestItems.map { item in
|
||||
var updatedItem = item
|
||||
updatedItem.title = manifestTitleByID[item.id]
|
||||
return updatedItem
|
||||
}
|
||||
|
||||
return OPFPackageDocument(
|
||||
metadata: metadata,
|
||||
manifest: manifest,
|
||||
manifestByID: Dictionary(uniqueKeysWithValues: manifest.map { ($0.id, $0) }),
|
||||
spineReferences: spineReferences,
|
||||
ncxItem: manifest.first(where: { $0.id == ncxID || $0.isNCX }),
|
||||
navigationItem: manifest.first(where: { $0.isNavigationDocument })
|
||||
)
|
||||
}
|
||||
|
||||
func parser(
|
||||
_ parser: XMLParser,
|
||||
didStartElement elementName: String,
|
||||
namespaceURI: String?,
|
||||
qualifiedName qName: String?,
|
||||
attributes attributeDict: [String: String] = [:]
|
||||
) {
|
||||
let name = xmlContext.startElement(named: qName ?? elementName)
|
||||
|
||||
switch name {
|
||||
case "package":
|
||||
metadata.version = attributeDict["version"]
|
||||
uniqueIdentifierID = attributeDict["unique-identifier"]
|
||||
case "identifier":
|
||||
if currentSection == .metadata {
|
||||
currentIdentifierElementID = attributeDict["id"]
|
||||
}
|
||||
case "item":
|
||||
guard currentSection == .manifest,
|
||||
let id = attributeDict["id"],
|
||||
let href = attributeDict["href"],
|
||||
let mediaType = attributeDict["media-type"] else {
|
||||
return
|
||||
}
|
||||
manifestItems.append(
|
||||
RDEPUBManifestItem(
|
||||
id: id,
|
||||
href: href,
|
||||
mediaType: mediaType,
|
||||
properties: XMLName.tokenize(attributeDict["properties"]),
|
||||
fallback: attributeDict["fallback"],
|
||||
mediaOverlay: attributeDict["media-overlay"]
|
||||
)
|
||||
)
|
||||
case "itemref":
|
||||
guard currentSection == .spine, let idref = attributeDict["idref"] else {
|
||||
return
|
||||
}
|
||||
spineReferences.append(
|
||||
OPFSpineReference(
|
||||
idref: idref,
|
||||
linear: (attributeDict["linear"]?.lowercased() ?? "yes") != "no",
|
||||
properties: XMLName.tokenize(attributeDict["properties"]),
|
||||
pageSpread: pageSpread(from: attributeDict)
|
||||
)
|
||||
)
|
||||
case "meta":
|
||||
currentMetaProperty = attributeDict["property"] ?? attributeDict["name"]
|
||||
currentMetaRefinesID = attributeDict["refines"].flatMap(XMLName.refinedID(from:))
|
||||
if let property = currentMetaProperty?.lowercased(),
|
||||
property == "rendition:layout",
|
||||
let value = attributeDict["content"] {
|
||||
metadata.layout = layout(from: value)
|
||||
}
|
||||
if let property = currentMetaProperty?.lowercased(),
|
||||
property == "rendition:spread" {
|
||||
metadata.spread = attributeDict["content"]
|
||||
}
|
||||
if let property = currentMetaProperty?.lowercased(),
|
||||
property == "title",
|
||||
let refinesID = currentMetaRefinesID,
|
||||
let value = attributeDict["content"],
|
||||
!value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
|
||||
manifestTitleByID[refinesID] = value.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
if name == "spine" {
|
||||
if let direction = attributeDict["page-progression-direction"]?.lowercased() {
|
||||
metadata.readingProgression = direction == "ltr" ? .ltr : (direction == "rtl" ? .rtl : .auto)
|
||||
}
|
||||
ncxID = attributeDict["toc"]
|
||||
}
|
||||
}
|
||||
|
||||
func parser(_ parser: XMLParser, foundCharacters string: String) {
|
||||
xmlContext.appendCharacters(string)
|
||||
}
|
||||
|
||||
func parser(
|
||||
_ parser: XMLParser,
|
||||
didEndElement elementName: String,
|
||||
namespaceURI: String?,
|
||||
qualifiedName qName: String?
|
||||
) {
|
||||
let name = XMLName.localName(from: qName ?? elementName)
|
||||
let text = xmlContext.trimmedCharacters
|
||||
|
||||
switch (currentSection, name) {
|
||||
case (.metadata, "identifier"):
|
||||
if let identifierID = currentIdentifierElementID, !text.isEmpty {
|
||||
identifierByID[identifierID] = text
|
||||
if identifierID == uniqueIdentifierID {
|
||||
metadata.identifier = text
|
||||
}
|
||||
} else if metadata.identifier == nil, !text.isEmpty {
|
||||
metadata.identifier = text
|
||||
}
|
||||
currentIdentifierElementID = nil
|
||||
case (.metadata, "title"):
|
||||
if metadata.title.isEmpty, !text.isEmpty {
|
||||
metadata.title = text
|
||||
}
|
||||
case (.metadata, "creator"):
|
||||
if metadata.author == nil, !text.isEmpty {
|
||||
metadata.author = text
|
||||
}
|
||||
case (.metadata, "language"):
|
||||
if metadata.language == nil, !text.isEmpty {
|
||||
metadata.language = text
|
||||
}
|
||||
case (.metadata, "meta"):
|
||||
applyMetaValue(text)
|
||||
currentMetaProperty = nil
|
||||
currentMetaRefinesID = nil
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
xmlContext.endElement()
|
||||
}
|
||||
|
||||
private var currentSection: XMLSection {
|
||||
if xmlContext.containsElement(named: "manifest") {
|
||||
return .manifest
|
||||
}
|
||||
if xmlContext.containsElement(named: "spine") {
|
||||
return .spine
|
||||
}
|
||||
if xmlContext.containsElement(named: "metadata") {
|
||||
return .metadata
|
||||
}
|
||||
return .other
|
||||
}
|
||||
|
||||
private func applyMetaValue(_ value: String) {
|
||||
let normalizedValue = value.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !normalizedValue.isEmpty, let property = currentMetaProperty?.lowercased() else {
|
||||
return
|
||||
}
|
||||
|
||||
switch property {
|
||||
case "rendition:layout":
|
||||
metadata.layout = layout(from: normalizedValue)
|
||||
case "rendition:spread":
|
||||
metadata.spread = normalizedValue
|
||||
case "dcterms:identifier", "identifier":
|
||||
if metadata.identifier == nil {
|
||||
metadata.identifier = normalizedValue
|
||||
}
|
||||
case "title":
|
||||
if let refinesID = currentMetaRefinesID {
|
||||
manifestTitleByID[refinesID] = normalizedValue
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
private func pageSpread(from attributes: [String: String]) -> RDEPUBPageSpread? {
|
||||
if let properties = attributes["properties"]?.lowercased() {
|
||||
if properties.contains("page-spread-left") {
|
||||
return .left
|
||||
}
|
||||
if properties.contains("page-spread-right") {
|
||||
return .right
|
||||
}
|
||||
if properties.contains("page-spread-center") {
|
||||
return .center
|
||||
}
|
||||
}
|
||||
|
||||
if let legacySpread = attributes["page-spread"]?.lowercased() {
|
||||
switch legacySpread {
|
||||
case "left":
|
||||
return .left
|
||||
case "right":
|
||||
return .right
|
||||
case "center":
|
||||
return .center
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
private func layout(from rawValue: String) -> RDEPUBLayout {
|
||||
rawValue.lowercased().contains("pre-paginated") ? .fixed : .reflowable
|
||||
}
|
||||
}
|
||||
|
||||
enum XMLSection {
|
||||
case metadata
|
||||
case manifest
|
||||
case spine
|
||||
case other
|
||||
}
|
||||
|
||||
enum XMLName {
|
||||
static func localName(from rawName: String) -> String {
|
||||
rawName.split(separator: ":").last.map(String.init) ?? rawName
|
||||
}
|
||||
|
||||
static func tokenize(_ rawValue: String?) -> [String] {
|
||||
guard let rawValue else { return [] }
|
||||
return rawValue
|
||||
.split(whereSeparator: { $0 == " " || $0 == "\n" || $0 == "\t" || $0 == "\r" })
|
||||
.map(String.init)
|
||||
}
|
||||
|
||||
static func refinedID(from rawValue: String) -> String? {
|
||||
let trimmed = rawValue.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard trimmed.hasPrefix("#") else {
|
||||
return nil
|
||||
}
|
||||
return String(trimmed.dropFirst())
|
||||
}
|
||||
}
|
||||
|
||||
final class XMLParserContext {
|
||||
private var elementStack: [String] = []
|
||||
private var currentCharacters = ""
|
||||
|
||||
var trimmedCharacters: String {
|
||||
currentCharacters.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
|
||||
func startElement(named rawName: String) -> String {
|
||||
let name = XMLName.localName(from: rawName)
|
||||
elementStack.append(name)
|
||||
currentCharacters = ""
|
||||
return name
|
||||
}
|
||||
|
||||
func appendCharacters(_ string: String) {
|
||||
currentCharacters += string
|
||||
}
|
||||
|
||||
func endElement() {
|
||||
if !elementStack.isEmpty {
|
||||
_ = elementStack.removeLast()
|
||||
}
|
||||
currentCharacters = ""
|
||||
}
|
||||
|
||||
func containsElement(named name: String) -> Bool {
|
||||
elementStack.contains(name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import Foundation
|
||||
|
||||
extension RDEPUBParser {
|
||||
public func readingProfile() -> RDEPUBReadingProfile {
|
||||
if metadata.layout == .fixed {
|
||||
return .webFixedLayout
|
||||
}
|
||||
return hasInteractiveContent() ? .webInteractive : .textReflowable
|
||||
}
|
||||
|
||||
public func hasInteractiveContent() -> Bool {
|
||||
let interactiveMediaTypes = [
|
||||
"application/javascript",
|
||||
"text/javascript",
|
||||
"application/ecmascript"
|
||||
]
|
||||
if manifest.values.contains(where: { item in
|
||||
interactiveMediaTypes.contains(item.mediaType.lowercased()) || item.properties.contains("scripted")
|
||||
}) {
|
||||
return true
|
||||
}
|
||||
|
||||
let interactivePattern = #"<(script|iframe|video|audio|canvas|svg|form)\b|\bon(load|click|touchstart|touchend|mouseover)=|hype_generated_script|swiper|webview"#
|
||||
for item in spine where item.linear && (item.mediaType.contains("html") || item.mediaType.contains("xhtml")) {
|
||||
guard let html = htmlString(forRelativePath: item.href) else {
|
||||
continue
|
||||
}
|
||||
if html.range(of: interactivePattern, options: [.regularExpression, .caseInsensitive]) != nil {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import Foundation
|
||||
import UIKit
|
||||
|
||||
extension RDEPUBParser {
|
||||
public func manifestItem(for id: String) -> RDEPUBManifestItem? {
|
||||
manifest[id]
|
||||
}
|
||||
|
||||
public func manifestItem(forHref href: String) -> RDEPUBManifestItem? {
|
||||
let target = href.components(separatedBy: "#").first ?? href
|
||||
return manifest.values.first { item in
|
||||
normalize(href: item.href, relativeTo: opfDirectoryURL ?? URL(fileURLWithPath: "/")) == target
|
||||
}
|
||||
}
|
||||
|
||||
public func href(forSpineIndex index: Int) -> String? {
|
||||
guard spine.indices.contains(index) else { return nil }
|
||||
return spine[index].href
|
||||
}
|
||||
|
||||
public func fileURL(forRelativePath relativePath: String) -> URL? {
|
||||
guard let opfDirectoryURL else { return nil }
|
||||
let path = relativePath.components(separatedBy: "#").first ?? relativePath
|
||||
guard !path.isEmpty else { return nil }
|
||||
let resolvedURL = URL(fileURLWithPath: path, relativeTo: opfDirectoryURL).standardizedFileURL
|
||||
guard let rootURL = extractionRootURL?.standardizedFileURL else {
|
||||
return resolvedURL
|
||||
}
|
||||
guard resolvedURL.path.hasPrefix(rootURL.path) else {
|
||||
return nil
|
||||
}
|
||||
return resolvedURL
|
||||
}
|
||||
|
||||
public func resourceURL(forRelativePath relativePath: String) -> URL? {
|
||||
let normalizedPath = relativePath.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
|
||||
guard !normalizedPath.isEmpty else { return nil }
|
||||
guard let encodedPath = normalizedPath.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
|
||||
return nil
|
||||
}
|
||||
var components = URLComponents()
|
||||
components.scheme = RDEPUBResourceURLSchemeHandler.scheme
|
||||
components.host = RDEPUBResourceURLSchemeHandler.host
|
||||
components.percentEncodedPath = "/" + encodedPath
|
||||
return components.url
|
||||
}
|
||||
|
||||
public func fileURL(forResourceURL resourceURL: URL) -> URL? {
|
||||
guard resourceURL.scheme == RDEPUBResourceURLSchemeHandler.scheme,
|
||||
resourceURL.host == RDEPUBResourceURLSchemeHandler.host else {
|
||||
return nil
|
||||
}
|
||||
let relativePath = resourceURL.path.removingPercentEncoding?.trimmingCharacters(in: CharacterSet(charactersIn: "/")) ?? ""
|
||||
return fileURL(forRelativePath: relativePath)
|
||||
}
|
||||
|
||||
public func coverImage() -> UIImage? {
|
||||
let coverCandidates = manifest.values.filter { item in
|
||||
item.properties.contains("cover-image") || item.id.lowercased().contains("cover")
|
||||
}
|
||||
for item in coverCandidates {
|
||||
if let fileURL = fileURL(forRelativePath: item.href),
|
||||
let image = UIImage(contentsOfFile: fileURL.path) {
|
||||
return image
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
public func htmlString(forSpineIndex index: Int) -> String? {
|
||||
guard spine.indices.contains(index) else {
|
||||
return nil
|
||||
}
|
||||
return htmlString(forRelativePath: spine[index].href)
|
||||
}
|
||||
|
||||
public func htmlString(forRelativePath relativePath: String) -> String? {
|
||||
guard let fileURL = fileURL(forRelativePath: relativePath) else {
|
||||
return nil
|
||||
}
|
||||
return try? String(contentsOf: fileURL)
|
||||
}
|
||||
|
||||
func normalize(href: String, relativeTo directoryURL: URL) -> String {
|
||||
guard let resolvedURL = URL(string: href, relativeTo: directoryURL)?.standardizedFileURL else {
|
||||
return href
|
||||
}
|
||||
let prefix = directoryURL.standardizedFileURL.path + "/"
|
||||
if resolvedURL.path.hasPrefix(prefix) {
|
||||
return String(resolvedURL.path.dropFirst(prefix.count))
|
||||
}
|
||||
return href
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
import Foundation
|
||||
|
||||
extension RDEPUBParser {
|
||||
func parseTOC(from packageDocument: OPFPackageDocument, opfURL: URL) -> [EPUBTableOfContentsItem] {
|
||||
let opfDirectoryURL = opfURL.deletingLastPathComponent()
|
||||
|
||||
if let ncxItem = packageDocument.ncxItem ?? packageDocument.manifest.first(where: { $0.isNCX }) {
|
||||
let ncxURL = opfDirectoryURL.appendingPathComponent(ncxItem.href)
|
||||
let items = parseNCXDocumentItems(at: ncxURL)
|
||||
if !items.isEmpty {
|
||||
return items
|
||||
}
|
||||
}
|
||||
|
||||
if let navItem = packageDocument.navigationItem {
|
||||
let navURL = opfDirectoryURL.appendingPathComponent(navItem.href)
|
||||
let items = parseNavDocumentItems(at: navURL, baseURL: navURL.deletingLastPathComponent())
|
||||
if !items.isEmpty {
|
||||
return items
|
||||
}
|
||||
}
|
||||
|
||||
return spine.map { EPUBTableOfContentsItem(title: $0.title, href: $0.href) }
|
||||
}
|
||||
|
||||
func parseNCXDocumentItems(at ncxURL: URL) -> [EPUBTableOfContentsItem] {
|
||||
guard FileManager.default.fileExists(atPath: ncxURL.path),
|
||||
let parser = XMLParser(contentsOf: ncxURL) else {
|
||||
return []
|
||||
}
|
||||
|
||||
let delegate = NCXParserDelegate(baseURL: ncxURL.deletingLastPathComponent()) { [weak self] href, baseURL in
|
||||
self?.normalizeTOCHref(href, relativeTo: baseURL)
|
||||
}
|
||||
parser.shouldProcessNamespaces = false
|
||||
parser.delegate = delegate
|
||||
guard parser.parse() else {
|
||||
return []
|
||||
}
|
||||
return delegate.items
|
||||
}
|
||||
|
||||
func parseNavDocumentItems(at navURL: URL, baseURL: URL) -> [EPUBTableOfContentsItem] {
|
||||
guard FileManager.default.fileExists(atPath: navURL.path),
|
||||
let parser = XMLParser(contentsOf: navURL) else {
|
||||
return []
|
||||
}
|
||||
|
||||
let delegate = NavDocumentParserDelegate(baseURL: baseURL) { [weak self] href, currentBaseURL in
|
||||
self?.normalizeTOCHref(href, relativeTo: currentBaseURL)
|
||||
}
|
||||
parser.shouldProcessNamespaces = false
|
||||
parser.delegate = delegate
|
||||
guard parser.parse() else {
|
||||
return []
|
||||
}
|
||||
return delegate.items
|
||||
}
|
||||
|
||||
func normalizeTOCHref(_ href: String, relativeTo baseURL: URL) -> String? {
|
||||
let components = href.split(separator: "#", maxSplits: 1, omittingEmptySubsequences: false)
|
||||
let pathPart = components.first.map(String.init) ?? href
|
||||
let fragment = components.count > 1 ? String(components[1]) : nil
|
||||
|
||||
let normalizedPath: String
|
||||
if pathPart.isEmpty {
|
||||
normalizedPath = ""
|
||||
} else {
|
||||
normalizedPath = normalize(href: pathPart, relativeTo: baseURL)
|
||||
}
|
||||
|
||||
if let fragment, !fragment.isEmpty {
|
||||
if normalizedPath.isEmpty {
|
||||
return "#\(fragment)"
|
||||
}
|
||||
return "\(normalizedPath)#\(fragment)"
|
||||
}
|
||||
|
||||
return normalizedPath.isEmpty ? nil : normalizedPath
|
||||
}
|
||||
}
|
||||
|
||||
private final class TOCNode {
|
||||
var title = ""
|
||||
var href: String?
|
||||
var children: [TOCNode] = []
|
||||
|
||||
func asItem() -> EPUBTableOfContentsItem? {
|
||||
let trimmedTitle = title.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard let href, !href.isEmpty else {
|
||||
return nil
|
||||
}
|
||||
return EPUBTableOfContentsItem(
|
||||
title: trimmedTitle.isEmpty ? href : trimmedTitle,
|
||||
href: href,
|
||||
children: children.compactMap { $0.asItem() }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private final class TOCTreeBuilder {
|
||||
private var nodeStack: [TOCNode] = []
|
||||
private var rootNodes: [TOCNode] = []
|
||||
|
||||
var items: [EPUBTableOfContentsItem] {
|
||||
rootNodes.compactMap { $0.asItem() }
|
||||
}
|
||||
|
||||
func beginNode() {
|
||||
nodeStack.append(TOCNode())
|
||||
}
|
||||
|
||||
func updateCurrentHref(_ href: String?) {
|
||||
nodeStack.last?.href = href
|
||||
}
|
||||
|
||||
func appendCurrentTitle(_ text: String) {
|
||||
nodeStack.last?.title += text
|
||||
}
|
||||
|
||||
func endNode() {
|
||||
guard let node = nodeStack.popLast() else {
|
||||
return
|
||||
}
|
||||
if let parent = nodeStack.last {
|
||||
parent.children.append(node)
|
||||
} else {
|
||||
rootNodes.append(node)
|
||||
}
|
||||
}
|
||||
|
||||
func reset() {
|
||||
nodeStack.removeAll()
|
||||
}
|
||||
}
|
||||
|
||||
private final class NCXParserDelegate: NSObject, XMLParserDelegate {
|
||||
private let baseURL: URL
|
||||
private let hrefNormalizer: (String, URL) -> String?
|
||||
private let treeBuilder = TOCTreeBuilder()
|
||||
private var readingLabelText = false
|
||||
|
||||
init(baseURL: URL, hrefNormalizer: @escaping (String, URL) -> String?) {
|
||||
self.baseURL = baseURL
|
||||
self.hrefNormalizer = hrefNormalizer
|
||||
}
|
||||
|
||||
var items: [EPUBTableOfContentsItem] {
|
||||
treeBuilder.items
|
||||
}
|
||||
|
||||
func parser(
|
||||
_ parser: XMLParser,
|
||||
didStartElement elementName: String,
|
||||
namespaceURI: String?,
|
||||
qualifiedName qName: String?,
|
||||
attributes attributeDict: [String: String] = [:]
|
||||
) {
|
||||
let name = XMLName.localName(from: qName ?? elementName)
|
||||
|
||||
switch name {
|
||||
case "navPoint":
|
||||
treeBuilder.beginNode()
|
||||
case "content":
|
||||
guard let src = attributeDict["src"] else {
|
||||
return
|
||||
}
|
||||
treeBuilder.updateCurrentHref(hrefNormalizer(src, baseURL))
|
||||
case "text":
|
||||
readingLabelText = true
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
func parser(_ parser: XMLParser, foundCharacters string: String) {
|
||||
if readingLabelText {
|
||||
treeBuilder.appendCurrentTitle(string)
|
||||
}
|
||||
}
|
||||
|
||||
func parser(
|
||||
_ parser: XMLParser,
|
||||
didEndElement elementName: String,
|
||||
namespaceURI: String?,
|
||||
qualifiedName qName: String?
|
||||
) {
|
||||
let name = XMLName.localName(from: qName ?? elementName)
|
||||
|
||||
switch name {
|
||||
case "text":
|
||||
readingLabelText = false
|
||||
case "navPoint":
|
||||
treeBuilder.endNode()
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final class NavDocumentParserDelegate: NSObject, XMLParserDelegate {
|
||||
private let baseURL: URL
|
||||
private let hrefNormalizer: (String, URL) -> String?
|
||||
private var insideTOCNav = false
|
||||
private var listDepth = 0
|
||||
private let treeBuilder = TOCTreeBuilder()
|
||||
private var collectingAnchorText = false
|
||||
|
||||
init(baseURL: URL, hrefNormalizer: @escaping (String, URL) -> String?) {
|
||||
self.baseURL = baseURL
|
||||
self.hrefNormalizer = hrefNormalizer
|
||||
}
|
||||
|
||||
var items: [EPUBTableOfContentsItem] {
|
||||
treeBuilder.items
|
||||
}
|
||||
|
||||
func parser(
|
||||
_ parser: XMLParser,
|
||||
didStartElement elementName: String,
|
||||
namespaceURI: String?,
|
||||
qualifiedName qName: String?,
|
||||
attributes attributeDict: [String: String] = [:]
|
||||
) {
|
||||
let name = XMLName.localName(from: qName ?? elementName)
|
||||
|
||||
switch name {
|
||||
case "nav":
|
||||
insideTOCNav = isTOCNav(attributes: attributeDict)
|
||||
case "ol":
|
||||
if insideTOCNav {
|
||||
listDepth += 1
|
||||
}
|
||||
case "li":
|
||||
if insideTOCNav, listDepth > 0 {
|
||||
treeBuilder.beginNode()
|
||||
}
|
||||
case "a":
|
||||
guard insideTOCNav else {
|
||||
return
|
||||
}
|
||||
collectingAnchorText = true
|
||||
if let href = attributeDict["href"] {
|
||||
treeBuilder.updateCurrentHref(hrefNormalizer(href, baseURL))
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
func parser(_ parser: XMLParser, foundCharacters string: String) {
|
||||
if collectingAnchorText {
|
||||
treeBuilder.appendCurrentTitle(string)
|
||||
}
|
||||
}
|
||||
|
||||
func parser(
|
||||
_ parser: XMLParser,
|
||||
didEndElement elementName: String,
|
||||
namespaceURI: String?,
|
||||
qualifiedName qName: String?
|
||||
) {
|
||||
let name = XMLName.localName(from: qName ?? elementName)
|
||||
|
||||
switch name {
|
||||
case "a":
|
||||
collectingAnchorText = false
|
||||
case "li":
|
||||
guard insideTOCNav else {
|
||||
break
|
||||
}
|
||||
treeBuilder.endNode()
|
||||
case "ol":
|
||||
if insideTOCNav {
|
||||
listDepth = max(0, listDepth - 1)
|
||||
}
|
||||
case "nav":
|
||||
insideTOCNav = false
|
||||
listDepth = 0
|
||||
treeBuilder.reset()
|
||||
collectingAnchorText = false
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
private func isTOCNav(attributes: [String: String]) -> Bool {
|
||||
if let epubType = attributes["epub:type"]?.lowercased(), epubType.contains("toc") {
|
||||
return true
|
||||
}
|
||||
if let type = attributes["type"]?.lowercased(), type.contains("toc") {
|
||||
return true
|
||||
}
|
||||
if let role = attributes["role"]?.lowercased(), role.contains("doc-toc") {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import Foundation
|
||||
|
||||
public final class RDEPUBParser {
|
||||
public internal(set) var metadata = RDEPUBMetadata()
|
||||
public internal(set) var manifest: [String: RDEPUBManifestItem] = [:]
|
||||
public internal(set) var spine: [RDEPUBSpineItem] = []
|
||||
public internal(set) var tableOfContents: [EPUBTableOfContentsItem] = []
|
||||
public internal(set) var extractionRootURL: URL?
|
||||
public internal(set) var opfURL: URL?
|
||||
|
||||
public var opfDirectoryURL: URL? {
|
||||
opfURL?.deletingLastPathComponent()
|
||||
}
|
||||
|
||||
public init() {}
|
||||
|
||||
public func makePublication() -> RDEPUBPublication {
|
||||
RDEPUBPublication(parser: self)
|
||||
}
|
||||
|
||||
public func parse(epubURL: URL) throws {
|
||||
reset()
|
||||
|
||||
let extractionURL = try extractArchiveIfNeeded(epubURL: epubURL)
|
||||
extractionRootURL = extractionURL
|
||||
|
||||
let containerURL = extractionURL.appendingPathComponent("META-INF/container.xml")
|
||||
guard FileManager.default.fileExists(atPath: containerURL.path) else {
|
||||
throw RDEPUBParserError.missingContainerXML
|
||||
}
|
||||
|
||||
let rootFilePath = try parseContainerRootFile(at: containerURL)
|
||||
let packageURL = extractionURL.appendingPathComponent(rootFilePath)
|
||||
guard FileManager.default.fileExists(atPath: packageURL.path) else {
|
||||
throw RDEPUBParserError.invalidRootFilePath(rootFilePath)
|
||||
}
|
||||
|
||||
try parseOPF(at: packageURL)
|
||||
}
|
||||
|
||||
public func parseOPF(at opfURL: URL) throws {
|
||||
resetPublicationState()
|
||||
|
||||
guard let parser = XMLParser(contentsOf: opfURL) else {
|
||||
throw RDEPUBParserError.invalidXML(opfURL)
|
||||
}
|
||||
|
||||
let delegate = OPFPackageParserDelegate()
|
||||
parser.shouldProcessNamespaces = false
|
||||
parser.delegate = delegate
|
||||
|
||||
guard parser.parse() else {
|
||||
throw parser.parserError ?? RDEPUBParserError.invalidXML(opfURL)
|
||||
}
|
||||
|
||||
let packageDocument = delegate.packageDocument()
|
||||
self.opfURL = opfURL
|
||||
self.metadata = packageDocument.metadata
|
||||
self.manifest = Dictionary(uniqueKeysWithValues: packageDocument.manifest.map { ($0.id, $0) })
|
||||
self.spine = try buildSpine(from: packageDocument, opfURL: opfURL)
|
||||
self.tableOfContents = parseTOC(from: packageDocument, opfURL: opfURL)
|
||||
}
|
||||
|
||||
public func parseTOC() -> [EPUBTableOfContentsItem] {
|
||||
tableOfContents
|
||||
}
|
||||
|
||||
public func parseNavDocument(_ navURL: URL, baseURL: URL? = nil) -> [EPUBTableOfContentsItem] {
|
||||
parseNavDocumentItems(at: navURL, baseURL: baseURL ?? navURL.deletingLastPathComponent())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import UIKit
|
||||
|
||||
public struct RDEPUBPreferences: Equatable {
|
||||
public var fontSize: CGFloat
|
||||
public var lineHeightMultiple: CGFloat
|
||||
public var reflowableContentInsets: UIEdgeInsets
|
||||
public var fixedContentInset: UIEdgeInsets
|
||||
public var themeBackgroundColor: String?
|
||||
public var themeTextColor: String?
|
||||
public var fixedBackgroundColor: String?
|
||||
public var fixedLayoutFit: RDEPUBFixedLayoutFit
|
||||
public var fixedLayoutSpreadMode: RDEPUBFixedLayoutSpreadMode
|
||||
|
||||
public init(
|
||||
fontSize: CGFloat,
|
||||
lineHeightMultiple: CGFloat,
|
||||
reflowableContentInsets: UIEdgeInsets,
|
||||
fixedContentInset: UIEdgeInsets,
|
||||
themeBackgroundColor: String? = nil,
|
||||
themeTextColor: String? = nil,
|
||||
fixedBackgroundColor: String? = nil,
|
||||
fixedLayoutFit: RDEPUBFixedLayoutFit = .page,
|
||||
fixedLayoutSpreadMode: RDEPUBFixedLayoutSpreadMode = .automatic
|
||||
) {
|
||||
self.fontSize = fontSize
|
||||
self.lineHeightMultiple = lineHeightMultiple
|
||||
self.reflowableContentInsets = reflowableContentInsets
|
||||
self.fixedContentInset = fixedContentInset
|
||||
self.themeBackgroundColor = themeBackgroundColor
|
||||
self.themeTextColor = themeTextColor
|
||||
self.fixedBackgroundColor = fixedBackgroundColor
|
||||
self.fixedLayoutFit = fixedLayoutFit
|
||||
self.fixedLayoutSpreadMode = fixedLayoutSpreadMode
|
||||
}
|
||||
|
||||
public func presentationStyle(viewportSize: CGSize) -> RDEPUBPresentationStyle {
|
||||
RDEPUBPresentationStyle(
|
||||
viewportSize: viewportSize,
|
||||
contentInsets: reflowableContentInsets,
|
||||
fontSize: fontSize,
|
||||
lineHeightMultiple: lineHeightMultiple,
|
||||
themeBackgroundColor: themeBackgroundColor,
|
||||
themeTextColor: themeTextColor
|
||||
)
|
||||
}
|
||||
|
||||
public func renderRequest(
|
||||
for page: EPUBPage,
|
||||
publication: RDEPUBPublication,
|
||||
viewportSize: CGSize,
|
||||
targetLocation: RDEPUBLocation? = nil,
|
||||
highlights: [RDEPUBHighlight] = [],
|
||||
searchPresentation: RDEPUBSearchPresentation? = nil
|
||||
) -> RDEPUBRenderRequest? {
|
||||
if publication.layout == .fixed, let fixedSpread = page.fixedSpread {
|
||||
return .fixed(
|
||||
RDEPUBFixedRenderRequest(
|
||||
spread: fixedSpread,
|
||||
viewportSize: viewportSize,
|
||||
contentInset: fixedContentInset,
|
||||
backgroundColorCSS: fixedBackgroundColor,
|
||||
fit: fixedLayoutFit,
|
||||
searchPresentation: searchPresentation
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
guard publication.spine.indices.contains(page.spineIndex) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return .reflowable(
|
||||
RDEPUBReflowableRenderRequest(
|
||||
spineIndex: page.spineIndex,
|
||||
href: publication.spine[page.spineIndex].href,
|
||||
pageIndex: page.pageIndexInChapter,
|
||||
totalPagesInChapter: page.totalPagesInChapter,
|
||||
presentation: presentationStyle(viewportSize: viewportSize),
|
||||
targetLocation: targetLocation,
|
||||
highlights: highlights,
|
||||
searchPresentation: searchPresentation
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import Foundation
|
||||
|
||||
public final class RDEPUBPublication {
|
||||
public let parser: RDEPUBParser
|
||||
public let resourceResolver: RDEPUBResourceResolver
|
||||
|
||||
public init(parser: RDEPUBParser) {
|
||||
self.parser = parser
|
||||
self.resourceResolver = RDEPUBResourceResolver(parser: parser)
|
||||
}
|
||||
|
||||
public var metadata: RDEPUBMetadata {
|
||||
parser.metadata
|
||||
}
|
||||
|
||||
public var manifest: [String: RDEPUBManifestItem] {
|
||||
parser.manifest
|
||||
}
|
||||
|
||||
public var spine: [RDEPUBSpineItem] {
|
||||
parser.spine
|
||||
}
|
||||
|
||||
public var tableOfContents: [EPUBTableOfContentsItem] {
|
||||
parser.tableOfContents
|
||||
}
|
||||
|
||||
public var layout: RDEPUBLayout {
|
||||
metadata.layout
|
||||
}
|
||||
|
||||
public var readingProfile: RDEPUBReadingProfile {
|
||||
parser.readingProfile()
|
||||
}
|
||||
|
||||
public var readingProgression: RDEPUBReadingProgression {
|
||||
metadata.readingProgression
|
||||
}
|
||||
|
||||
public var bookIdentifier: String? {
|
||||
metadata.identifier
|
||||
}
|
||||
|
||||
public func fixedLayoutSpreadEnabled(for preferences: RDEPUBPreferences, viewportSize: CGSize) -> Bool {
|
||||
guard layout == .fixed else {
|
||||
return false
|
||||
}
|
||||
guard metadata.spread?.lowercased() != "none" else {
|
||||
return false
|
||||
}
|
||||
|
||||
switch preferences.fixedLayoutSpreadMode {
|
||||
case .never:
|
||||
return false
|
||||
case .always:
|
||||
return spine.count > 1
|
||||
case .automatic:
|
||||
return viewportSize.width > viewportSize.height
|
||||
}
|
||||
}
|
||||
|
||||
public func makeFixedSpreads(preferences: RDEPUBPreferences, viewportSize: CGSize) -> [EPUBFixedSpread] {
|
||||
EPUBFixedSpread.makeSpreads(
|
||||
spine: spine,
|
||||
spreadEnabled: fixedLayoutSpreadEnabled(for: preferences, viewportSize: viewportSize)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,411 @@
|
||||
import Foundation
|
||||
|
||||
public struct RDEPUBLocation: Codable, Equatable {
|
||||
public var bookIdentifier: String?
|
||||
public var href: String
|
||||
public var progression: Double
|
||||
public var lastProgression: Double?
|
||||
public var fragment: String?
|
||||
|
||||
public init(
|
||||
bookIdentifier: String? = nil,
|
||||
href: String,
|
||||
progression: Double,
|
||||
lastProgression: Double? = nil,
|
||||
fragment: String? = nil
|
||||
) {
|
||||
self.bookIdentifier = bookIdentifier
|
||||
self.href = href
|
||||
self.progression = Self.clamp(progression)
|
||||
self.lastProgression = lastProgression.map(Self.clamp)
|
||||
self.fragment = fragment?.nilIfEmpty
|
||||
}
|
||||
|
||||
public var navigationProgression: Double {
|
||||
let end = lastProgression ?? progression
|
||||
if end.isNaN || end.isInfinite {
|
||||
return progression
|
||||
}
|
||||
return Self.clamp((progression + end) / 2.0)
|
||||
}
|
||||
|
||||
private static func clamp(_ value: Double) -> Double {
|
||||
guard value.isFinite else { return 0 }
|
||||
return min(1, max(0, value))
|
||||
}
|
||||
}
|
||||
|
||||
public struct RDEPUBViewportResource: Codable, Equatable {
|
||||
public var href: String
|
||||
public var spineIndex: Int
|
||||
public var progression: Double
|
||||
public var lastProgression: Double?
|
||||
public var fragment: String?
|
||||
|
||||
public init(
|
||||
href: String,
|
||||
spineIndex: Int,
|
||||
progression: Double,
|
||||
lastProgression: Double? = nil,
|
||||
fragment: String? = nil
|
||||
) {
|
||||
self.href = href
|
||||
self.spineIndex = spineIndex
|
||||
self.progression = progression
|
||||
self.lastProgression = lastProgression
|
||||
self.fragment = fragment
|
||||
}
|
||||
}
|
||||
|
||||
public struct RDEPUBViewport: Codable, Equatable {
|
||||
public var resources: [RDEPUBViewportResource]
|
||||
public var visiblePageNumber: Int
|
||||
public var chapterIndex: Int?
|
||||
public var isFixedLayout: Bool
|
||||
|
||||
public init(
|
||||
resources: [RDEPUBViewportResource],
|
||||
visiblePageNumber: Int,
|
||||
chapterIndex: Int? = nil,
|
||||
isFixedLayout: Bool
|
||||
) {
|
||||
self.resources = resources
|
||||
self.visiblePageNumber = visiblePageNumber
|
||||
self.chapterIndex = chapterIndex
|
||||
self.isFixedLayout = isFixedLayout
|
||||
}
|
||||
}
|
||||
|
||||
public struct RDEPUBReadingContext: Codable, Equatable {
|
||||
public var location: RDEPUBLocation
|
||||
public var viewport: RDEPUBViewport
|
||||
public var pageNumber: Int
|
||||
public var chapterIndex: Int?
|
||||
|
||||
public init(
|
||||
location: RDEPUBLocation,
|
||||
viewport: RDEPUBViewport,
|
||||
pageNumber: Int,
|
||||
chapterIndex: Int? = nil
|
||||
) {
|
||||
self.location = location
|
||||
self.viewport = viewport
|
||||
self.pageNumber = pageNumber
|
||||
self.chapterIndex = chapterIndex
|
||||
}
|
||||
}
|
||||
|
||||
public struct RDEPUBSelection: Codable, Equatable {
|
||||
public var bookIdentifier: String?
|
||||
public var location: RDEPUBLocation
|
||||
public var text: String
|
||||
public var rangeInfo: String?
|
||||
public var createdAt: Date
|
||||
|
||||
public init(
|
||||
bookIdentifier: String? = nil,
|
||||
location: RDEPUBLocation,
|
||||
text: String,
|
||||
rangeInfo: String? = nil,
|
||||
createdAt: Date = Date()
|
||||
) {
|
||||
self.bookIdentifier = bookIdentifier
|
||||
self.location = location
|
||||
self.text = text
|
||||
self.rangeInfo = rangeInfo?.nilIfEmpty
|
||||
self.createdAt = createdAt
|
||||
}
|
||||
|
||||
public var isEmpty: Bool {
|
||||
text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || rangeInfo?.isEmpty != false
|
||||
}
|
||||
}
|
||||
|
||||
public enum RDEPUBHighlightStyle: String, Codable {
|
||||
case highlight
|
||||
case underline
|
||||
}
|
||||
|
||||
public enum RDEPUBAnnotationMenuAction: Equatable {
|
||||
case copy
|
||||
case highlight
|
||||
case annotate
|
||||
}
|
||||
|
||||
public struct RDEPUBTextOffsetRangeInfo: Codable, Equatable {
|
||||
public var kind: String
|
||||
public var href: String
|
||||
public var start: Int
|
||||
public var end: Int
|
||||
|
||||
public init(href: String, start: Int, end: Int) {
|
||||
self.kind = "text-offset"
|
||||
self.href = href
|
||||
self.start = start
|
||||
self.end = end
|
||||
}
|
||||
|
||||
public var nsRange: NSRange? {
|
||||
guard end > start else { return nil }
|
||||
return NSRange(location: start, length: end - start)
|
||||
}
|
||||
|
||||
public func jsonString() -> String? {
|
||||
guard let data = try? JSONEncoder().encode(self) else { return nil }
|
||||
return String(data: data, encoding: .utf8)
|
||||
}
|
||||
|
||||
public static func decode(from string: String?) -> RDEPUBTextOffsetRangeInfo? {
|
||||
guard let string,
|
||||
let data = string.data(using: .utf8),
|
||||
let rangeInfo = try? JSONDecoder().decode(RDEPUBTextOffsetRangeInfo.self, from: data),
|
||||
rangeInfo.kind == "text-offset",
|
||||
rangeInfo.end > rangeInfo.start else {
|
||||
return nil
|
||||
}
|
||||
return rangeInfo
|
||||
}
|
||||
}
|
||||
|
||||
public struct RDEPUBHighlight: Codable, Equatable {
|
||||
public var id: String
|
||||
public var bookIdentifier: String?
|
||||
public var location: RDEPUBLocation
|
||||
public var text: String
|
||||
public var rangeInfo: String?
|
||||
public var style: RDEPUBHighlightStyle
|
||||
public var color: String
|
||||
public var note: String?
|
||||
public var createdAt: Date
|
||||
|
||||
public init(
|
||||
id: String = UUID().uuidString,
|
||||
bookIdentifier: String? = nil,
|
||||
location: RDEPUBLocation,
|
||||
text: String,
|
||||
rangeInfo: String? = nil,
|
||||
style: RDEPUBHighlightStyle = .highlight,
|
||||
color: String = "#F8E16C",
|
||||
note: String? = nil,
|
||||
createdAt: Date = Date()
|
||||
) {
|
||||
self.id = id
|
||||
self.bookIdentifier = bookIdentifier
|
||||
self.location = location
|
||||
self.text = text
|
||||
self.rangeInfo = rangeInfo?.nilIfEmpty
|
||||
self.style = style
|
||||
self.color = color
|
||||
self.note = note?.nilIfEmpty
|
||||
self.createdAt = createdAt
|
||||
}
|
||||
|
||||
public var hasNote: Bool {
|
||||
note?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case id
|
||||
case bookIdentifier
|
||||
case location
|
||||
case text
|
||||
case rangeInfo
|
||||
case style
|
||||
case color
|
||||
case note
|
||||
case createdAt
|
||||
}
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
id = try container.decode(String.self, forKey: .id)
|
||||
bookIdentifier = try container.decodeIfPresent(String.self, forKey: .bookIdentifier)
|
||||
location = try container.decode(RDEPUBLocation.self, forKey: .location)
|
||||
text = try container.decode(String.self, forKey: .text)
|
||||
rangeInfo = try container.decodeIfPresent(String.self, forKey: .rangeInfo)?.nilIfEmpty
|
||||
if let rawStyle = try container.decodeIfPresent(String.self, forKey: .style),
|
||||
let decodedStyle = RDEPUBHighlightStyle(rawValue: rawStyle) {
|
||||
style = decodedStyle
|
||||
} else {
|
||||
style = .highlight
|
||||
}
|
||||
color = try container.decodeIfPresent(String.self, forKey: .color) ?? "#F8E16C"
|
||||
note = try container.decodeIfPresent(String.self, forKey: .note)?.nilIfEmpty
|
||||
createdAt = try container.decodeIfPresent(Date.self, forKey: .createdAt) ?? Date()
|
||||
}
|
||||
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(id, forKey: .id)
|
||||
try container.encodeIfPresent(bookIdentifier, forKey: .bookIdentifier)
|
||||
try container.encode(location, forKey: .location)
|
||||
try container.encode(text, forKey: .text)
|
||||
try container.encodeIfPresent(rangeInfo, forKey: .rangeInfo)
|
||||
try container.encode(style, forKey: .style)
|
||||
try container.encode(color, forKey: .color)
|
||||
try container.encodeIfPresent(note, forKey: .note)
|
||||
try container.encode(createdAt, forKey: .createdAt)
|
||||
}
|
||||
}
|
||||
|
||||
public struct RDEPUBBookmark: Codable, Equatable {
|
||||
public var id: String
|
||||
public var bookIdentifier: String?
|
||||
public var location: RDEPUBLocation
|
||||
public var chapterTitle: String?
|
||||
public var note: String?
|
||||
public var createdAt: Date
|
||||
|
||||
public init(
|
||||
id: String = UUID().uuidString,
|
||||
bookIdentifier: String? = nil,
|
||||
location: RDEPUBLocation,
|
||||
chapterTitle: String? = nil,
|
||||
note: String? = nil,
|
||||
createdAt: Date = Date()
|
||||
) {
|
||||
self.id = id
|
||||
self.bookIdentifier = bookIdentifier
|
||||
self.location = location
|
||||
self.chapterTitle = chapterTitle?.nilIfEmpty
|
||||
self.note = note?.nilIfEmpty
|
||||
self.createdAt = createdAt
|
||||
}
|
||||
|
||||
public var hasNote: Bool {
|
||||
note?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false
|
||||
}
|
||||
}
|
||||
|
||||
public struct EPUBChapterInfo: Codable, Equatable {
|
||||
public var spineIndex: Int
|
||||
public var title: String
|
||||
public var pageCount: Int
|
||||
|
||||
public init(spineIndex: Int, title: String, pageCount: Int) {
|
||||
self.spineIndex = spineIndex
|
||||
self.title = title
|
||||
self.pageCount = pageCount
|
||||
}
|
||||
}
|
||||
|
||||
public struct EPUBPage: Codable, Equatable {
|
||||
public var spineIndex: Int
|
||||
public var chapterIndex: Int
|
||||
public var pageIndexInChapter: Int
|
||||
public var totalPagesInChapter: Int
|
||||
public var chapterTitle: String
|
||||
public var fixedSpread: EPUBFixedSpread?
|
||||
|
||||
public init(
|
||||
spineIndex: Int,
|
||||
chapterIndex: Int,
|
||||
pageIndexInChapter: Int,
|
||||
totalPagesInChapter: Int,
|
||||
chapterTitle: String,
|
||||
fixedSpread: EPUBFixedSpread?
|
||||
) {
|
||||
self.spineIndex = spineIndex
|
||||
self.chapterIndex = chapterIndex
|
||||
self.pageIndexInChapter = pageIndexInChapter
|
||||
self.totalPagesInChapter = totalPagesInChapter
|
||||
self.chapterTitle = chapterTitle
|
||||
self.fixedSpread = fixedSpread
|
||||
}
|
||||
}
|
||||
|
||||
public struct EPUBFixedSpreadResource: Codable, Equatable {
|
||||
public var spineIndex: Int
|
||||
public var href: String
|
||||
public var title: String
|
||||
public var pageSpread: RDEPUBPageSpread?
|
||||
|
||||
public init(spineIndex: Int, href: String, title: String, pageSpread: RDEPUBPageSpread? = nil) {
|
||||
self.spineIndex = spineIndex
|
||||
self.href = href
|
||||
self.title = title
|
||||
self.pageSpread = pageSpread
|
||||
}
|
||||
}
|
||||
|
||||
public struct EPUBFixedSpread: Codable, Equatable {
|
||||
public var resources: [EPUBFixedSpreadResource]
|
||||
|
||||
public init(resources: [EPUBFixedSpreadResource]) {
|
||||
self.resources = resources
|
||||
}
|
||||
|
||||
public var primaryResource: EPUBFixedSpreadResource {
|
||||
resources.first ?? EPUBFixedSpreadResource(spineIndex: 0, href: "", title: "")
|
||||
}
|
||||
|
||||
public func contains(normalizedHref: String, normalizer: (String) -> String?) -> Bool {
|
||||
resources.contains { resource in
|
||||
normalizer(resource.href) == normalizedHref
|
||||
}
|
||||
}
|
||||
|
||||
public static func makeSpreads(spine: [RDEPUBSpineItem], spreadEnabled: Bool) -> [EPUBFixedSpread] {
|
||||
let resources = spine.enumerated().map { index, item in
|
||||
EPUBFixedSpreadResource(
|
||||
spineIndex: index,
|
||||
href: item.href,
|
||||
title: item.title,
|
||||
pageSpread: item.pageSpread
|
||||
)
|
||||
}
|
||||
|
||||
guard spreadEnabled, resources.count > 1 else {
|
||||
return resources.map { EPUBFixedSpread(resources: [$0]) }
|
||||
}
|
||||
|
||||
var spreads: [EPUBFixedSpread] = []
|
||||
var cursor = 0
|
||||
|
||||
while cursor < resources.count {
|
||||
let current = resources[cursor]
|
||||
|
||||
guard cursor + 1 < resources.count else {
|
||||
spreads.append(EPUBFixedSpread(resources: [current]))
|
||||
break
|
||||
}
|
||||
|
||||
let next = resources[cursor + 1]
|
||||
if shouldPair(current: current, next: next) {
|
||||
spreads.append(EPUBFixedSpread(resources: [current, next]))
|
||||
cursor += 2
|
||||
} else {
|
||||
spreads.append(EPUBFixedSpread(resources: [current]))
|
||||
cursor += 1
|
||||
}
|
||||
}
|
||||
|
||||
return spreads
|
||||
}
|
||||
|
||||
public static func makeSpreads(parser: RDEPUBParser, spreadEnabled: Bool) -> [EPUBFixedSpread] {
|
||||
makeSpreads(spine: parser.spine, spreadEnabled: spreadEnabled)
|
||||
}
|
||||
|
||||
private static func shouldPair(current: EPUBFixedSpreadResource, next: EPUBFixedSpreadResource) -> Bool {
|
||||
if current.pageSpread == .center || next.pageSpread == .center {
|
||||
return false
|
||||
}
|
||||
|
||||
switch (current.pageSpread, next.pageSpread) {
|
||||
case (.left, .right), (.right, .left):
|
||||
return true
|
||||
case (.left, .left), (.right, .right):
|
||||
return false
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension String {
|
||||
var nilIfEmpty: String? {
|
||||
let trimmed = trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return trimmed.isEmpty ? nil : trimmed
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
import Foundation
|
||||
|
||||
public final class RDEPUBReadingSession {
|
||||
public typealias PaginationSnapshot = (pages: [EPUBPage], chapters: [EPUBChapterInfo])
|
||||
|
||||
public let publication: RDEPUBPublication
|
||||
|
||||
public private(set) var navigatorState: RDEPUBNavigatorState = .initializing
|
||||
public private(set) var activePages: [EPUBPage] = []
|
||||
public private(set) var activeChapters: [EPUBChapterInfo] = []
|
||||
public private(set) var stagedPages: [EPUBPage]?
|
||||
public private(set) var stagedChapters: [EPUBChapterInfo]?
|
||||
public private(set) var stagedRestoreLocation: RDEPUBLocation?
|
||||
public private(set) var pendingNavigationLocation: RDEPUBLocation?
|
||||
public private(set) var pendingNavigationPageNum: Int?
|
||||
public private(set) var currentViewport: RDEPUBViewport?
|
||||
public private(set) var currentReadingContext: RDEPUBReadingContext?
|
||||
|
||||
public init(publication: RDEPUBPublication) {
|
||||
self.publication = publication
|
||||
}
|
||||
|
||||
public var resourceResolver: RDEPUBResourceResolver {
|
||||
publication.resourceResolver
|
||||
}
|
||||
|
||||
public func transition(to state: RDEPUBNavigatorState) {
|
||||
navigatorState = state
|
||||
}
|
||||
|
||||
public func resetRuntimeState() {
|
||||
navigatorState = .initializing
|
||||
activePages = []
|
||||
activeChapters = []
|
||||
clearPendingNavigation()
|
||||
clearStagedSnapshot()
|
||||
currentViewport = nil
|
||||
currentReadingContext = nil
|
||||
}
|
||||
|
||||
public func setActiveSnapshot(_ snapshot: PaginationSnapshot) {
|
||||
activePages = snapshot.pages
|
||||
activeChapters = snapshot.chapters
|
||||
}
|
||||
|
||||
public func stageSnapshot(_ snapshot: PaginationSnapshot, restoreLocation: RDEPUBLocation?) {
|
||||
stagedPages = snapshot.pages
|
||||
stagedChapters = snapshot.chapters
|
||||
stagedRestoreLocation = restoreLocation
|
||||
}
|
||||
|
||||
public func stagedSnapshot() -> PaginationSnapshot? {
|
||||
guard let stagedPages, let stagedChapters else {
|
||||
return nil
|
||||
}
|
||||
return (stagedPages, stagedChapters)
|
||||
}
|
||||
|
||||
public func consumeStagedSnapshotIfAllowed() -> (snapshot: PaginationSnapshot, restoreLocation: RDEPUBLocation?)? {
|
||||
guard navigatorState.isStableForSnapshotApplication,
|
||||
let stagedPages,
|
||||
let stagedChapters else {
|
||||
return nil
|
||||
}
|
||||
let restoreLocation = stagedRestoreLocation
|
||||
clearStagedSnapshot()
|
||||
return ((stagedPages, stagedChapters), restoreLocation)
|
||||
}
|
||||
|
||||
public func clearStagedSnapshot() {
|
||||
stagedPages = nil
|
||||
stagedChapters = nil
|
||||
stagedRestoreLocation = nil
|
||||
}
|
||||
|
||||
public func clearPendingNavigation() {
|
||||
pendingNavigationLocation = nil
|
||||
pendingNavigationPageNum = nil
|
||||
}
|
||||
|
||||
public func pendingLocation(forPageNumber pageNumber: Int, spineIndex: Int?) -> RDEPUBLocation? {
|
||||
guard pendingNavigationPageNum == pageNumber,
|
||||
let pendingNavigationLocation else {
|
||||
return nil
|
||||
}
|
||||
guard let spineIndex else {
|
||||
return pendingNavigationLocation
|
||||
}
|
||||
let pageHref = resourceResolver.href(forSpineIndex: spineIndex)
|
||||
guard resourceResolver.normalizedHref(pageHref ?? "") == resourceResolver.normalizedHref(pendingNavigationLocation.href) else {
|
||||
return nil
|
||||
}
|
||||
return pendingNavigationLocation
|
||||
}
|
||||
|
||||
public func pageContains(spineIndex: Int, in page: EPUBPage) -> Bool {
|
||||
if let fixedSpread = page.fixedSpread {
|
||||
return fixedSpread.resources.contains(where: { $0.spineIndex == spineIndex })
|
||||
}
|
||||
return page.spineIndex == spineIndex
|
||||
}
|
||||
|
||||
public func fallbackLocation(for page: EPUBPage, bookIdentifier: String?) -> RDEPUBLocation? {
|
||||
if let fixedSpread = page.fixedSpread {
|
||||
return RDEPUBLocation(
|
||||
bookIdentifier: bookIdentifier,
|
||||
href: fixedSpread.primaryResource.href,
|
||||
progression: 0,
|
||||
lastProgression: 1
|
||||
)
|
||||
}
|
||||
|
||||
guard let href = resourceResolver.href(forSpineIndex: page.spineIndex) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let progression: Double
|
||||
if page.totalPagesInChapter <= 1 {
|
||||
progression = 0
|
||||
} else {
|
||||
progression = Double(page.pageIndexInChapter) / Double(page.totalPagesInChapter - 1)
|
||||
}
|
||||
|
||||
return RDEPUBLocation(
|
||||
bookIdentifier: bookIdentifier,
|
||||
href: href,
|
||||
progression: progression,
|
||||
lastProgression: progression
|
||||
)
|
||||
}
|
||||
|
||||
public func currentVisibleLocation(currentPageNumber: Int, bookIdentifier: String?) -> RDEPUBLocation? {
|
||||
guard currentPageNumber > 0,
|
||||
activePages.indices.contains(currentPageNumber - 1) else {
|
||||
return nil
|
||||
}
|
||||
return fallbackLocation(for: activePages[currentPageNumber - 1], bookIdentifier: bookIdentifier)
|
||||
}
|
||||
|
||||
public func initialSpineIndex(for location: RDEPUBLocation?) -> Int {
|
||||
guard let location,
|
||||
let normalizedHref = resourceResolver.normalizedHref(location.href),
|
||||
let spineIndex = publication.spine.firstIndex(where: { resourceResolver.normalizedHref($0.href) == normalizedHref }) else {
|
||||
return 0
|
||||
}
|
||||
return spineIndex
|
||||
}
|
||||
|
||||
public func pageIndex(for location: RDEPUBLocation, bookIdentifier: String?) -> Int? {
|
||||
guard location.bookIdentifier == nil || location.bookIdentifier == bookIdentifier else {
|
||||
return nil
|
||||
}
|
||||
guard let targetHref = resourceResolver.normalizedHref(location.href) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
if publication.layout == .fixed {
|
||||
return activePages.firstIndex(where: { page in
|
||||
if let fixedSpread = page.fixedSpread {
|
||||
return fixedSpread.contains(normalizedHref: targetHref, normalizer: { self.resourceResolver.normalizedHref($0) })
|
||||
}
|
||||
guard let href = self.resourceResolver.href(forSpineIndex: page.spineIndex) else {
|
||||
return false
|
||||
}
|
||||
return self.resourceResolver.normalizedHref(href) == targetHref
|
||||
})
|
||||
}
|
||||
|
||||
guard let spineIndex = publication.spine.firstIndex(where: { resourceResolver.normalizedHref($0.href) == targetHref }) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let candidates = activePages.enumerated().filter { $0.element.spineIndex == spineIndex }
|
||||
guard !candidates.isEmpty else {
|
||||
return nil
|
||||
}
|
||||
if candidates.count == 1 {
|
||||
return candidates[0].offset
|
||||
}
|
||||
|
||||
let navigationProgression = location.navigationProgression
|
||||
let localIndex = min(
|
||||
candidates.count - 1,
|
||||
max(0, Int(round(navigationProgression * Double(candidates.count - 1))))
|
||||
)
|
||||
return candidates[localIndex].offset
|
||||
}
|
||||
|
||||
public func queueNavigation(
|
||||
to location: RDEPUBLocation,
|
||||
relativeToSpineIndex spineIndex: Int? = nil,
|
||||
bookIdentifier: String?
|
||||
) -> Int? {
|
||||
guard let normalizedLocation = resourceResolver.normalizedLocation(
|
||||
location,
|
||||
relativeToSpineIndex: spineIndex,
|
||||
bookIdentifier: bookIdentifier
|
||||
), let pageIndex = pageIndex(for: normalizedLocation, bookIdentifier: bookIdentifier) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
pendingNavigationLocation = normalizedLocation.fragment == nil ? nil : normalizedLocation
|
||||
pendingNavigationPageNum = normalizedLocation.fragment == nil ? nil : pageIndex + 1
|
||||
transition(to: .jumping)
|
||||
return pageIndex + 1
|
||||
}
|
||||
|
||||
public func updateReadingContext(
|
||||
pageNumber: Int,
|
||||
location: RDEPUBLocation,
|
||||
spineIndex: Int,
|
||||
chapterIndex: Int?,
|
||||
bookIdentifier: String?
|
||||
) {
|
||||
let normalizedLocation = resourceResolver.normalizedLocation(
|
||||
location,
|
||||
relativeToSpineIndex: spineIndex,
|
||||
bookIdentifier: bookIdentifier
|
||||
) ?? RDEPUBLocation(
|
||||
bookIdentifier: bookIdentifier,
|
||||
href: location.href,
|
||||
progression: location.progression,
|
||||
lastProgression: location.lastProgression,
|
||||
fragment: location.fragment
|
||||
)
|
||||
|
||||
let resource = RDEPUBViewportResource(
|
||||
href: normalizedLocation.href,
|
||||
spineIndex: spineIndex,
|
||||
progression: normalizedLocation.progression,
|
||||
lastProgression: normalizedLocation.lastProgression,
|
||||
fragment: normalizedLocation.fragment
|
||||
)
|
||||
let viewport = RDEPUBViewport(
|
||||
resources: [resource],
|
||||
visiblePageNumber: pageNumber,
|
||||
chapterIndex: chapterIndex,
|
||||
isFixedLayout: publication.layout == .fixed
|
||||
)
|
||||
currentViewport = viewport
|
||||
currentReadingContext = RDEPUBReadingContext(
|
||||
location: normalizedLocation,
|
||||
viewport: viewport,
|
||||
pageNumber: pageNumber,
|
||||
chapterIndex: chapterIndex
|
||||
)
|
||||
|
||||
if pendingNavigationPageNum == pageNumber {
|
||||
clearPendingNavigation()
|
||||
}
|
||||
if navigatorState == .jumping || navigatorState == .moving {
|
||||
transition(to: .idle)
|
||||
}
|
||||
}
|
||||
|
||||
public func currentReadingLocation(bookIdentifier: String?) -> RDEPUBLocation? {
|
||||
currentReadingContext?.location ?? currentVisibleLocation(currentPageNumber: currentViewport?.visiblePageNumber ?? 0, bookIdentifier: bookIdentifier)
|
||||
}
|
||||
|
||||
public func makePaginationSnapshot(
|
||||
pageCounts: [Int],
|
||||
preferences: RDEPUBPreferences,
|
||||
layoutContext: RDEPUBNavigatorLayoutContext
|
||||
) -> PaginationSnapshot {
|
||||
if publication.layout == .fixed {
|
||||
let spreads = publication.makeFixedSpreads(
|
||||
preferences: preferences,
|
||||
viewportSize: layoutContext.viewportSize
|
||||
)
|
||||
|
||||
let chapters = spreads.enumerated().map { spreadIndex, spread in
|
||||
EPUBChapterInfo(
|
||||
spineIndex: spread.primaryResource.spineIndex,
|
||||
title: spread.primaryResource.title,
|
||||
pageCount: 1
|
||||
)
|
||||
}
|
||||
|
||||
let pages = spreads.enumerated().map { spreadIndex, spread in
|
||||
EPUBPage(
|
||||
spineIndex: spread.primaryResource.spineIndex,
|
||||
chapterIndex: spreadIndex,
|
||||
pageIndexInChapter: 0,
|
||||
totalPagesInChapter: 1,
|
||||
chapterTitle: spread.primaryResource.title,
|
||||
fixedSpread: spread
|
||||
)
|
||||
}
|
||||
|
||||
return (pages, chapters)
|
||||
}
|
||||
|
||||
var pages: [EPUBPage] = []
|
||||
var chapters: [EPUBChapterInfo] = []
|
||||
|
||||
for (spineIndex, pageCount) in pageCounts.enumerated() {
|
||||
guard pageCount > 0, spineIndex < publication.spine.count else { continue }
|
||||
|
||||
let chapterIndex = chapters.count
|
||||
let title = publication.spine[spineIndex].title
|
||||
|
||||
chapters.append(
|
||||
EPUBChapterInfo(
|
||||
spineIndex: spineIndex,
|
||||
title: title,
|
||||
pageCount: pageCount
|
||||
)
|
||||
)
|
||||
|
||||
for pageIndex in 0..<pageCount {
|
||||
pages.append(
|
||||
EPUBPage(
|
||||
spineIndex: spineIndex,
|
||||
chapterIndex: chapterIndex,
|
||||
pageIndexInChapter: pageIndex,
|
||||
totalPagesInChapter: pageCount,
|
||||
chapterTitle: title,
|
||||
fixedSpread: nil
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return (pages, chapters)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import UIKit
|
||||
|
||||
public enum RDEPUBFixedLayoutFit: String, Codable {
|
||||
case auto
|
||||
case page
|
||||
case width
|
||||
}
|
||||
|
||||
public enum RDEPUBFixedLayoutSpreadMode: String, Codable {
|
||||
case automatic
|
||||
case always
|
||||
case never
|
||||
}
|
||||
|
||||
public struct RDEPUBPresentationStyle: Equatable {
|
||||
public var viewportSize: CGSize
|
||||
public var contentInsets: UIEdgeInsets
|
||||
public var fontSize: CGFloat
|
||||
public var lineHeightMultiple: CGFloat
|
||||
public var themeBackgroundColor: String?
|
||||
public var themeTextColor: String?
|
||||
|
||||
public init(
|
||||
viewportSize: CGSize,
|
||||
contentInsets: UIEdgeInsets,
|
||||
fontSize: CGFloat,
|
||||
lineHeightMultiple: CGFloat,
|
||||
themeBackgroundColor: String? = nil,
|
||||
themeTextColor: String? = nil
|
||||
) {
|
||||
self.viewportSize = viewportSize
|
||||
self.contentInsets = contentInsets
|
||||
self.fontSize = fontSize
|
||||
self.lineHeightMultiple = lineHeightMultiple
|
||||
self.themeBackgroundColor = themeBackgroundColor
|
||||
self.themeTextColor = themeTextColor
|
||||
}
|
||||
}
|
||||
|
||||
public struct RDEPUBReflowableRenderRequest: Equatable {
|
||||
public var spineIndex: Int
|
||||
public var href: String
|
||||
public var pageIndex: Int
|
||||
public var totalPagesInChapter: Int
|
||||
public var presentation: RDEPUBPresentationStyle
|
||||
public var targetLocation: RDEPUBLocation?
|
||||
public var highlights: [RDEPUBHighlight]
|
||||
public var searchPresentation: RDEPUBSearchPresentation?
|
||||
|
||||
public init(
|
||||
spineIndex: Int,
|
||||
href: String,
|
||||
pageIndex: Int,
|
||||
totalPagesInChapter: Int,
|
||||
presentation: RDEPUBPresentationStyle,
|
||||
targetLocation: RDEPUBLocation? = nil,
|
||||
highlights: [RDEPUBHighlight] = [],
|
||||
searchPresentation: RDEPUBSearchPresentation? = nil
|
||||
) {
|
||||
self.spineIndex = spineIndex
|
||||
self.href = href
|
||||
self.pageIndex = pageIndex
|
||||
self.totalPagesInChapter = totalPagesInChapter
|
||||
self.presentation = presentation
|
||||
self.targetLocation = targetLocation
|
||||
self.highlights = highlights
|
||||
self.searchPresentation = searchPresentation
|
||||
}
|
||||
}
|
||||
|
||||
public struct RDEPUBFixedRenderRequest: Equatable {
|
||||
public var spread: EPUBFixedSpread
|
||||
public var viewportSize: CGSize
|
||||
public var contentInset: UIEdgeInsets
|
||||
public var backgroundColorCSS: String?
|
||||
public var fit: RDEPUBFixedLayoutFit
|
||||
public var searchPresentation: RDEPUBSearchPresentation?
|
||||
|
||||
public init(
|
||||
spread: EPUBFixedSpread,
|
||||
viewportSize: CGSize,
|
||||
contentInset: UIEdgeInsets,
|
||||
backgroundColorCSS: String? = nil,
|
||||
fit: RDEPUBFixedLayoutFit = .page,
|
||||
searchPresentation: RDEPUBSearchPresentation? = nil
|
||||
) {
|
||||
self.spread = spread
|
||||
self.viewportSize = viewportSize
|
||||
self.contentInset = contentInset
|
||||
self.backgroundColorCSS = backgroundColorCSS
|
||||
self.fit = fit
|
||||
self.searchPresentation = searchPresentation
|
||||
}
|
||||
}
|
||||
|
||||
public enum RDEPUBRenderRequest: Equatable {
|
||||
case reflowable(RDEPUBReflowableRenderRequest)
|
||||
case fixed(RDEPUBFixedRenderRequest)
|
||||
|
||||
public var isFixedLayout: Bool {
|
||||
if case .fixed = self {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
public var primarySpineIndex: Int {
|
||||
switch self {
|
||||
case .reflowable(let request):
|
||||
return request.spineIndex
|
||||
case .fixed(let request):
|
||||
return request.spread.primaryResource.spineIndex
|
||||
}
|
||||
}
|
||||
|
||||
public var primaryHref: String {
|
||||
switch self {
|
||||
case .reflowable(let request):
|
||||
return request.href
|
||||
case .fixed(let request):
|
||||
return request.spread.primaryResource.href
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import Foundation
|
||||
|
||||
public final class RDEPUBResourceResolver {
|
||||
private let parser: RDEPUBParser
|
||||
|
||||
public init(parser: RDEPUBParser) {
|
||||
self.parser = parser
|
||||
}
|
||||
|
||||
public var opfDirectoryURL: URL? {
|
||||
parser.opfDirectoryURL
|
||||
}
|
||||
|
||||
public func fileURL(forRelativePath relativePath: String) -> URL? {
|
||||
parser.fileURL(forRelativePath: relativePath)
|
||||
}
|
||||
|
||||
public func resourceURL(forRelativePath relativePath: String) -> URL? {
|
||||
parser.resourceURL(forRelativePath: relativePath)
|
||||
}
|
||||
|
||||
public func fileURL(forResourceURL resourceURL: URL) -> URL? {
|
||||
parser.fileURL(forResourceURL: resourceURL)
|
||||
}
|
||||
|
||||
public func normalizedHref(_ href: String, relativeToSpineIndex spineIndex: Int? = nil) -> String? {
|
||||
guard let opfDirectoryURL else {
|
||||
return href.components(separatedBy: "#").first
|
||||
}
|
||||
|
||||
let pathPart = href.components(separatedBy: "#").first ?? href
|
||||
if pathPart.isEmpty {
|
||||
guard let spineIndex, parser.spine.indices.contains(spineIndex) else {
|
||||
return nil
|
||||
}
|
||||
return parser.spine[spineIndex].href.components(separatedBy: "#").first
|
||||
}
|
||||
|
||||
let baseURL: URL
|
||||
if let spineIndex, parser.spine.indices.contains(spineIndex) {
|
||||
baseURL = opfDirectoryURL
|
||||
.appendingPathComponent(parser.spine[spineIndex].href)
|
||||
.deletingLastPathComponent()
|
||||
} else {
|
||||
baseURL = opfDirectoryURL
|
||||
}
|
||||
|
||||
guard let resolvedURL = URL(string: pathPart, relativeTo: baseURL)?.standardizedFileURL else {
|
||||
return pathPart
|
||||
}
|
||||
|
||||
let opfPath = opfDirectoryURL.standardizedFileURL.path + "/"
|
||||
let resolvedPath = resolvedURL.path
|
||||
if resolvedPath.hasPrefix(opfPath) {
|
||||
return String(resolvedPath.dropFirst(opfPath.count))
|
||||
}
|
||||
return pathPart
|
||||
}
|
||||
|
||||
public func normalizedLocation(
|
||||
_ location: RDEPUBLocation,
|
||||
relativeToSpineIndex spineIndex: Int? = nil,
|
||||
bookIdentifier: String?
|
||||
) -> RDEPUBLocation? {
|
||||
let rawHref = location.href
|
||||
let hrefParts = rawHref.split(separator: "#", maxSplits: 1, omittingEmptySubsequences: false)
|
||||
let pathPart = hrefParts.first.map(String.init) ?? rawHref
|
||||
let fragment = location.fragment ?? (hrefParts.count > 1 ? String(hrefParts[1]) : nil)
|
||||
|
||||
let normalizedTargetHref: String
|
||||
if pathPart.isEmpty {
|
||||
guard let spineIndex, parser.spine.indices.contains(spineIndex) else {
|
||||
return nil
|
||||
}
|
||||
normalizedTargetHref = parser.spine[spineIndex].href.components(separatedBy: "#").first ?? parser.spine[spineIndex].href
|
||||
} else {
|
||||
guard let href = normalizedHref(pathPart, relativeToSpineIndex: spineIndex) else {
|
||||
return nil
|
||||
}
|
||||
normalizedTargetHref = href
|
||||
}
|
||||
|
||||
return RDEPUBLocation(
|
||||
bookIdentifier: bookIdentifier,
|
||||
href: normalizedTargetHref,
|
||||
progression: location.progression,
|
||||
lastProgression: location.lastProgression,
|
||||
fragment: fragment
|
||||
)
|
||||
}
|
||||
|
||||
public func spineIndex(forNormalizedHref normalizedHref: String) -> Int? {
|
||||
parser.spine.firstIndex { item in
|
||||
self.normalizedHref(item.href) == normalizedHref
|
||||
}
|
||||
}
|
||||
|
||||
public func spineIndex(for location: RDEPUBLocation) -> Int? {
|
||||
guard let normalizedHref = normalizedHref(location.href) else {
|
||||
return nil
|
||||
}
|
||||
return spineIndex(forNormalizedHref: normalizedHref)
|
||||
}
|
||||
|
||||
public func href(forSpineIndex spineIndex: Int) -> String? {
|
||||
guard parser.spine.indices.contains(spineIndex) else {
|
||||
return nil
|
||||
}
|
||||
return parser.spine[spineIndex].href
|
||||
}
|
||||
|
||||
public func title(forSpineIndex spineIndex: Int) -> String? {
|
||||
guard parser.spine.indices.contains(spineIndex) else {
|
||||
return nil
|
||||
}
|
||||
return parser.spine[spineIndex].title
|
||||
}
|
||||
|
||||
public func manifestItem(forHref href: String) -> RDEPUBManifestItem? {
|
||||
let targetHref = normalizedHref(href) ?? href.components(separatedBy: "#").first ?? href
|
||||
return parser.manifest.values.first {
|
||||
normalizedHref($0.href) == targetHref
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import Foundation
|
||||
import WebKit
|
||||
|
||||
public final class RDEPUBResourceURLSchemeHandler: NSObject, WKURLSchemeHandler {
|
||||
public static let scheme = "ss-reader"
|
||||
public static let host = "book"
|
||||
|
||||
private weak var parser: RDEPUBParser?
|
||||
private let fileManager = FileManager.default
|
||||
private let syncQueue = DispatchQueue(label: "com.ssreaderview.epub.scheme-handler")
|
||||
private var activeTasks: [ObjectIdentifier: Bool] = [:]
|
||||
|
||||
public init(parser: RDEPUBParser) {
|
||||
self.parser = parser
|
||||
super.init()
|
||||
}
|
||||
|
||||
public func webView(_ webView: WKWebView, start urlSchemeTask: any WKURLSchemeTask) {
|
||||
let taskID = ObjectIdentifier(urlSchemeTask as AnyObject)
|
||||
syncQueue.sync {
|
||||
activeTasks[taskID] = true
|
||||
}
|
||||
|
||||
let requestURL = urlSchemeTask.request.url
|
||||
RDEPUBWebViewDebug.logSchemeTask("ResourceScheme", requestURL: requestURL, event: "start")
|
||||
|
||||
guard let parser,
|
||||
let requestURL,
|
||||
let fileURL = parser.fileURL(forResourceURL: requestURL),
|
||||
fileManager.fileExists(atPath: fileURL.path) else {
|
||||
if let requestURL, Self.isOptionalResource(requestURL) {
|
||||
RDEPUBWebViewDebug.logSchemeTask("ResourceScheme", requestURL: requestURL, event: "missing-optional-resource")
|
||||
let response = URLResponse(
|
||||
url: requestURL,
|
||||
mimeType: Self.mimeType(for: requestURL.pathExtension),
|
||||
expectedContentLength: 0,
|
||||
textEncodingName: Self.textEncodingName(for: requestURL.pathExtension)
|
||||
)
|
||||
urlSchemeTask.didReceive(response)
|
||||
urlSchemeTask.didReceive(Data())
|
||||
urlSchemeTask.didFinish()
|
||||
} else {
|
||||
RDEPUBWebViewDebug.logSchemeTask("ResourceScheme", requestURL: requestURL, event: "missing-file")
|
||||
urlSchemeTask.didFailWithError(NSError(domain: NSURLErrorDomain, code: NSURLErrorFileDoesNotExist))
|
||||
}
|
||||
clearTask(taskID)
|
||||
return
|
||||
}
|
||||
|
||||
RDEPUBWebViewDebug.logSchemeTask("ResourceScheme", requestURL: requestURL, fileURL: fileURL, event: "resolved")
|
||||
|
||||
do {
|
||||
let data = try Data(contentsOf: fileURL)
|
||||
guard isTaskActive(taskID) else { return }
|
||||
|
||||
let response = URLResponse(
|
||||
url: requestURL,
|
||||
mimeType: Self.mimeType(for: fileURL.pathExtension),
|
||||
expectedContentLength: data.count,
|
||||
textEncodingName: Self.textEncodingName(for: fileURL.pathExtension)
|
||||
)
|
||||
urlSchemeTask.didReceive(response)
|
||||
urlSchemeTask.didReceive(data)
|
||||
urlSchemeTask.didFinish()
|
||||
RDEPUBWebViewDebug.logSchemeTask("ResourceScheme", requestURL: requestURL, fileURL: fileURL, event: "finished")
|
||||
} catch {
|
||||
guard isTaskActive(taskID) else { return }
|
||||
RDEPUBWebViewDebug.logSchemeTask("ResourceScheme", requestURL: requestURL, fileURL: fileURL, event: "failed", error: error)
|
||||
urlSchemeTask.didFailWithError(error)
|
||||
}
|
||||
|
||||
clearTask(taskID)
|
||||
}
|
||||
|
||||
public func webView(_ webView: WKWebView, stop urlSchemeTask: any WKURLSchemeTask) {
|
||||
RDEPUBWebViewDebug.logSchemeTask("ResourceScheme", requestURL: urlSchemeTask.request.url, event: "stop")
|
||||
clearTask(ObjectIdentifier(urlSchemeTask as AnyObject))
|
||||
}
|
||||
|
||||
private func clearTask(_ id: ObjectIdentifier) {
|
||||
syncQueue.sync {
|
||||
activeTasks[id] = nil
|
||||
}
|
||||
}
|
||||
|
||||
private func isTaskActive(_ id: ObjectIdentifier) -> Bool {
|
||||
syncQueue.sync {
|
||||
activeTasks[id] == true
|
||||
}
|
||||
}
|
||||
|
||||
private static func mimeType(for pathExtension: String) -> String {
|
||||
switch pathExtension.lowercased() {
|
||||
case "html", "htm":
|
||||
return "text/html"
|
||||
case "xhtml":
|
||||
return "application/xhtml+xml"
|
||||
case "css":
|
||||
return "text/css"
|
||||
case "js":
|
||||
return "application/javascript"
|
||||
case "xml", "opf", "ncx":
|
||||
return "application/xml"
|
||||
case "svg":
|
||||
return "image/svg+xml"
|
||||
case "jpg", "jpeg":
|
||||
return "image/jpeg"
|
||||
case "png":
|
||||
return "image/png"
|
||||
case "gif":
|
||||
return "image/gif"
|
||||
case "webp":
|
||||
return "image/webp"
|
||||
case "ttf":
|
||||
return "font/ttf"
|
||||
case "otf":
|
||||
return "font/otf"
|
||||
case "woff":
|
||||
return "font/woff"
|
||||
case "woff2":
|
||||
return "font/woff2"
|
||||
case "mp3":
|
||||
return "audio/mpeg"
|
||||
case "mp4":
|
||||
return "video/mp4"
|
||||
default:
|
||||
return "application/octet-stream"
|
||||
}
|
||||
}
|
||||
|
||||
private static func textEncodingName(for pathExtension: String) -> String? {
|
||||
switch pathExtension.lowercased() {
|
||||
case "html", "htm", "xhtml", "css", "js", "xml", "opf", "ncx", "txt":
|
||||
return "utf-8"
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
private static func isOptionalResource(_ url: URL) -> Bool {
|
||||
switch url.pathExtension.lowercased() {
|
||||
case "ttf", "otf", "woff", "woff2", "css", "js", "jpg", "jpeg", "png", "gif", "webp", "svg":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import Foundation
|
||||
import UIKit
|
||||
|
||||
protocol RDEPUBSearchEngine {
|
||||
func search(keyword: String) -> [RDEPUBSearchMatch]
|
||||
}
|
||||
|
||||
final class RDEPUBHTMLSearchEngine: RDEPUBSearchEngine {
|
||||
private let parser: RDEPUBParser
|
||||
private let publication: RDEPUBPublication
|
||||
|
||||
init(parser: RDEPUBParser, publication: RDEPUBPublication) {
|
||||
self.parser = parser
|
||||
self.publication = publication
|
||||
}
|
||||
|
||||
func search(keyword: String) -> [RDEPUBSearchMatch] {
|
||||
let normalizedKeyword = keyword.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !normalizedKeyword.isEmpty else {
|
||||
return []
|
||||
}
|
||||
|
||||
var searchMatches: [RDEPUBSearchMatch] = []
|
||||
for item in publication.spine where item.linear {
|
||||
guard item.mediaType.contains("html") || item.mediaType.contains("xhtml"),
|
||||
let html = parser.htmlString(forRelativePath: item.href) else {
|
||||
continue
|
||||
}
|
||||
|
||||
let plainText = plainText(fromHTML: html, baseURL: parser.fileURL(forRelativePath: item.href)?.deletingLastPathComponent())
|
||||
let normalizedHref = publication.resourceResolver.normalizedHref(item.href) ?? item.href
|
||||
searchMatches.append(contentsOf: matches(in: plainText, href: normalizedHref, keyword: normalizedKeyword))
|
||||
}
|
||||
|
||||
return searchMatches
|
||||
}
|
||||
|
||||
private func plainText(fromHTML html: String, baseURL: URL?) -> String {
|
||||
guard let data = html.data(using: .utf8) else {
|
||||
return fallbackPlainText(fromHTML: html)
|
||||
}
|
||||
|
||||
var options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
|
||||
.documentType: NSAttributedString.DocumentType.html,
|
||||
.characterEncoding: String.Encoding.utf8.rawValue
|
||||
]
|
||||
if let baseURL {
|
||||
options[NSAttributedString.DocumentReadingOptionKey(rawValue: "NSBaseURLDocumentOption")] = baseURL
|
||||
}
|
||||
|
||||
if let attributed = try? NSAttributedString(data: data, options: options, documentAttributes: nil) {
|
||||
return attributed.string
|
||||
}
|
||||
return fallbackPlainText(fromHTML: html)
|
||||
}
|
||||
|
||||
private func fallbackPlainText(fromHTML html: String) -> String {
|
||||
let stripped = html.replacingOccurrences(of: "<[^>]+>", with: " ", options: .regularExpression)
|
||||
return stripped
|
||||
.replacingOccurrences(of: " ", with: " ")
|
||||
.replacingOccurrences(of: "&", with: "&")
|
||||
.replacingOccurrences(of: "<", with: "<")
|
||||
.replacingOccurrences(of: ">", with: ">")
|
||||
.replacingOccurrences(of: "'", with: "'")
|
||||
.replacingOccurrences(of: """, with: "\"")
|
||||
}
|
||||
|
||||
private func matches(in text: String, href: String, keyword: String) -> [RDEPUBSearchMatch] {
|
||||
let source = text as NSString
|
||||
let fullLength = source.length
|
||||
guard fullLength > 0 else {
|
||||
return []
|
||||
}
|
||||
|
||||
var results: [RDEPUBSearchMatch] = []
|
||||
var localMatchIndex = 0
|
||||
var searchRange = NSRange(location: 0, length: fullLength)
|
||||
|
||||
while searchRange.length > 0 {
|
||||
let foundRange = source.range(of: keyword, options: [.caseInsensitive], range: searchRange)
|
||||
guard foundRange.location != NSNotFound else {
|
||||
break
|
||||
}
|
||||
|
||||
let progressionDenominator = max(fullLength - 1, 1)
|
||||
let progression = Double(foundRange.location) / Double(progressionDenominator)
|
||||
results.append(
|
||||
RDEPUBSearchMatch(
|
||||
href: href,
|
||||
progression: progression,
|
||||
previewText: previewText(in: source, matchRange: foundRange),
|
||||
localMatchIndex: localMatchIndex,
|
||||
rangeLocation: foundRange.location,
|
||||
rangeLength: foundRange.length
|
||||
)
|
||||
)
|
||||
|
||||
localMatchIndex += 1
|
||||
let nextLocation = foundRange.location + max(foundRange.length, 1)
|
||||
if nextLocation >= fullLength {
|
||||
break
|
||||
}
|
||||
searchRange = NSRange(location: nextLocation, length: fullLength - nextLocation)
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
private func previewText(in text: NSString, matchRange: NSRange) -> String {
|
||||
let previewRadius = 12
|
||||
let start = max(matchRange.location - previewRadius, 0)
|
||||
let end = min(matchRange.location + matchRange.length + previewRadius, text.length)
|
||||
let range = NSRange(location: start, length: max(end - start, 0))
|
||||
return text.substring(with: range).trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import Foundation
|
||||
|
||||
public struct RDEPUBSearchMatch: Codable, Equatable {
|
||||
public var href: String
|
||||
public var progression: Double
|
||||
public var previewText: String
|
||||
public var localMatchIndex: Int
|
||||
public var rangeLocation: Int?
|
||||
public var rangeLength: Int
|
||||
|
||||
public init(
|
||||
href: String,
|
||||
progression: Double,
|
||||
previewText: String,
|
||||
localMatchIndex: Int,
|
||||
rangeLocation: Int? = nil,
|
||||
rangeLength: Int
|
||||
) {
|
||||
self.href = href
|
||||
self.progression = progression
|
||||
self.previewText = previewText
|
||||
self.localMatchIndex = localMatchIndex
|
||||
self.rangeLocation = rangeLocation
|
||||
self.rangeLength = rangeLength
|
||||
}
|
||||
}
|
||||
|
||||
public struct RDEPUBSearchResult: Codable, Equatable {
|
||||
public var keyword: String
|
||||
public var totalMatchCount: Int
|
||||
public var currentMatchIndex: Int?
|
||||
public var currentMatch: RDEPUBSearchMatch?
|
||||
|
||||
public init(
|
||||
keyword: String,
|
||||
totalMatchCount: Int,
|
||||
currentMatchIndex: Int?,
|
||||
currentMatch: RDEPUBSearchMatch?
|
||||
) {
|
||||
self.keyword = keyword
|
||||
self.totalMatchCount = totalMatchCount
|
||||
self.currentMatchIndex = currentMatchIndex
|
||||
self.currentMatch = currentMatch
|
||||
}
|
||||
}
|
||||
|
||||
public struct RDEPUBSearchState: Codable, Equatable {
|
||||
public var keyword: String
|
||||
public var matches: [RDEPUBSearchMatch]
|
||||
public var currentMatchIndex: Int?
|
||||
|
||||
public init(keyword: String, matches: [RDEPUBSearchMatch], currentMatchIndex: Int? = nil) {
|
||||
self.keyword = keyword
|
||||
self.matches = matches
|
||||
self.currentMatchIndex = currentMatchIndex
|
||||
}
|
||||
|
||||
public var currentMatch: RDEPUBSearchMatch? {
|
||||
guard let currentMatchIndex,
|
||||
matches.indices.contains(currentMatchIndex) else {
|
||||
return nil
|
||||
}
|
||||
return matches[currentMatchIndex]
|
||||
}
|
||||
|
||||
public var result: RDEPUBSearchResult {
|
||||
RDEPUBSearchResult(
|
||||
keyword: keyword,
|
||||
totalMatchCount: matches.count,
|
||||
currentMatchIndex: currentMatchIndex.map { $0 + 1 },
|
||||
currentMatch: currentMatch
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
public struct RDEPUBSearchPresentationResource: Codable, Equatable {
|
||||
public var href: String
|
||||
public var matchCount: Int
|
||||
public var activeLocalMatchIndex: Int?
|
||||
|
||||
public init(href: String, matchCount: Int, activeLocalMatchIndex: Int? = nil) {
|
||||
self.href = href
|
||||
self.matchCount = matchCount
|
||||
self.activeLocalMatchIndex = activeLocalMatchIndex
|
||||
}
|
||||
}
|
||||
|
||||
public struct RDEPUBSearchPresentation: Codable, Equatable {
|
||||
public var keyword: String
|
||||
public var resources: [RDEPUBSearchPresentationResource]
|
||||
|
||||
public init(keyword: String, resources: [RDEPUBSearchPresentationResource]) {
|
||||
self.keyword = keyword
|
||||
self.resources = resources
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import Foundation
|
||||
|
||||
public enum RDEPUBStyleSheetBuilder {
|
||||
public static func injectPaginationCSS(
|
||||
into html: String,
|
||||
presentation: RDEPUBPresentationStyle
|
||||
) -> String {
|
||||
let styleTag = "<style id=\"ss-reader-pagination\">\(measurementCSS(for: presentation))</style>"
|
||||
if html.range(of: "</head>", options: .caseInsensitive) != nil {
|
||||
return html.replacingOccurrences(of: "</head>", with: styleTag + "</head>", options: .caseInsensitive)
|
||||
}
|
||||
if html.range(of: "<body", options: .caseInsensitive) != nil {
|
||||
return html.replacingOccurrences(of: "<body", with: styleTag + "<body", options: .caseInsensitive)
|
||||
}
|
||||
return styleTag + html
|
||||
}
|
||||
|
||||
public static func renderCSS(for presentation: RDEPUBPresentationStyle) -> String {
|
||||
let values = cssValues(for: presentation)
|
||||
let backgroundCSS = presentation.themeBackgroundColor.map { "background: \($0) !important;" } ?? ""
|
||||
let textCSS = presentation.themeTextColor.map { "color: \($0) !important;" } ?? ""
|
||||
|
||||
return """
|
||||
html {
|
||||
margin: 0 !important;
|
||||
padding: 0 !important;
|
||||
width: \(values.viewportWidth)px !important;
|
||||
height: \(values.viewportHeight)px !important;
|
||||
min-height: \(values.viewportHeight)px !important;
|
||||
overflow-x: hidden !important;
|
||||
overflow-y: hidden !important;
|
||||
}
|
||||
body {
|
||||
margin: 0 !important;
|
||||
padding: 0 !important;
|
||||
box-sizing: border-box !important;
|
||||
position: relative !important;
|
||||
width: \(values.viewportWidth)px !important;
|
||||
height: \(values.viewportHeight)px !important;
|
||||
min-height: \(values.viewportHeight)px !important;
|
||||
overflow: hidden !important;
|
||||
background: transparent !important;
|
||||
}
|
||||
#ss-reader-viewport {
|
||||
position: relative !important;
|
||||
width: \(values.viewportWidth)px !important;
|
||||
height: \(values.viewportHeight)px !important;
|
||||
min-height: \(values.viewportHeight)px !important;
|
||||
overflow: hidden !important;
|
||||
background: transparent !important;
|
||||
}
|
||||
#ss-reader-content {
|
||||
position: relative !important;
|
||||
box-sizing: border-box !important;
|
||||
width: \(values.viewportWidth)px !important;
|
||||
height: \(values.viewportHeight)px !important;
|
||||
min-height: \(values.viewportHeight)px !important;
|
||||
overflow: visible !important;
|
||||
padding: \(values.paddingTop)px \(values.paddingRight)px \(values.paddingBottom)px \(values.paddingLeft)px !important;
|
||||
font-size: \(values.fontSize)px !important;
|
||||
line-height: \(values.lineHeight) !important;
|
||||
-webkit-column-width: \(values.contentWidth)px !important;
|
||||
column-width: \(values.contentWidth)px !important;
|
||||
-webkit-column-gap: \(values.columnGap)px !important;
|
||||
column-gap: \(values.columnGap)px !important;
|
||||
-webkit-column-fill: auto !important;
|
||||
column-fill: auto !important;
|
||||
transform-origin: top left !important;
|
||||
will-change: transform !important;
|
||||
\(backgroundCSS)
|
||||
\(textCSS)
|
||||
}
|
||||
#ss-reader-content img, #ss-reader-content svg, #ss-reader-content video, #ss-reader-content canvas, #ss-reader-content iframe {
|
||||
max-width: 100% !important;
|
||||
height: auto !important;
|
||||
break-inside: avoid-column !important;
|
||||
-webkit-column-break-inside: avoid !important;
|
||||
}
|
||||
#ss-reader-content mark.ss-reader-highlight {
|
||||
padding: 0;
|
||||
border-radius: 2px;
|
||||
color: inherit !important;
|
||||
}
|
||||
#ss-reader-content mark.ss-reader-highlight-highlight {
|
||||
text-decoration: none !important;
|
||||
color: inherit !important;
|
||||
}
|
||||
#ss-reader-content mark.ss-reader-highlight-underline {
|
||||
background: transparent !important;
|
||||
color: inherit !important;
|
||||
text-decoration-line: underline !important;
|
||||
text-decoration-thickness: 2px !important;
|
||||
text-decoration-skip-ink: auto !important;
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
public static func measurementCSS(for presentation: RDEPUBPresentationStyle) -> String {
|
||||
let values = cssValues(for: presentation)
|
||||
let backgroundCSS = presentation.themeBackgroundColor.map { "background: \($0) !important;" } ?? ""
|
||||
let textCSS = presentation.themeTextColor.map { "color: \($0) !important;" } ?? ""
|
||||
|
||||
return """
|
||||
html {
|
||||
margin: 0 !important;
|
||||
padding: 0 !important;
|
||||
width: \(values.viewportWidth)px !important;
|
||||
height: \(values.viewportHeight)px !important;
|
||||
min-height: \(values.viewportHeight)px !important;
|
||||
overflow: hidden !important;
|
||||
}
|
||||
body {
|
||||
margin: 0 !important;
|
||||
box-sizing: border-box !important;
|
||||
position: relative !important;
|
||||
width: \(values.viewportWidth)px !important;
|
||||
height: \(values.viewportHeight)px !important;
|
||||
min-height: \(values.viewportHeight)px !important;
|
||||
overflow: visible !important;
|
||||
padding: \(values.paddingTop)px \(values.paddingRight)px \(values.paddingBottom)px \(values.paddingLeft)px !important;
|
||||
font-size: \(values.fontSize)px !important;
|
||||
line-height: \(values.lineHeight) !important;
|
||||
-webkit-column-width: \(values.contentWidth)px !important;
|
||||
column-width: \(values.contentWidth)px !important;
|
||||
-webkit-column-gap: \(values.columnGap)px !important;
|
||||
column-gap: \(values.columnGap)px !important;
|
||||
-webkit-column-fill: auto !important;
|
||||
column-fill: auto !important;
|
||||
transform-origin: top left !important;
|
||||
\(backgroundCSS)
|
||||
\(textCSS)
|
||||
}
|
||||
img, svg, video, canvas, iframe {
|
||||
max-width: 100% !important;
|
||||
height: auto !important;
|
||||
break-inside: avoid-column !important;
|
||||
-webkit-column-break-inside: avoid !important;
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
public static func measurementScript(for presentation: RDEPUBPresentationStyle) -> String {
|
||||
let style = measurementCSS(for: presentation)
|
||||
.replacingOccurrences(of: "\\", with: "\\\\")
|
||||
.replacingOccurrences(of: "`", with: "\\`")
|
||||
|
||||
let viewportWidth = Double(max(1, presentation.viewportSize.width))
|
||||
let viewportWidthJS = String(format: "%.3f", viewportWidth)
|
||||
|
||||
return """
|
||||
(function() {
|
||||
var style = document.getElementById('ss-reader-pagination');
|
||||
if (!style) {
|
||||
style = document.createElement('style');
|
||||
style.id = 'ss-reader-pagination';
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
style.textContent = `\(style)`;
|
||||
var scrollingElement = document.scrollingElement || document.documentElement || document.body;
|
||||
var totalWidth = Math.max(
|
||||
scrollingElement ? scrollingElement.scrollWidth : 0,
|
||||
scrollingElement ? scrollingElement.offsetWidth : 0,
|
||||
document.body ? document.body.scrollWidth : 0,
|
||||
document.body ? document.body.offsetWidth : 0,
|
||||
document.documentElement ? document.documentElement.scrollWidth : 0,
|
||||
document.documentElement ? document.documentElement.offsetWidth : 0
|
||||
);
|
||||
return Math.max(1, Math.ceil(totalWidth / \(viewportWidthJS)));
|
||||
})();
|
||||
"""
|
||||
}
|
||||
|
||||
private static func cssValues(for presentation: RDEPUBPresentationStyle) -> (
|
||||
viewportWidth: String,
|
||||
viewportHeight: String,
|
||||
contentWidth: String,
|
||||
columnGap: String,
|
||||
paddingTop: String,
|
||||
paddingRight: String,
|
||||
paddingBottom: String,
|
||||
paddingLeft: String,
|
||||
fontSize: String,
|
||||
lineHeight: String
|
||||
) {
|
||||
let viewportWidth = max(1, presentation.viewportSize.width)
|
||||
let viewportHeight = max(1, presentation.viewportSize.height)
|
||||
let contentInsets = presentation.contentInsets
|
||||
let contentWidth = max(1, viewportWidth - contentInsets.left - contentInsets.right)
|
||||
let columnGap = max(0, contentInsets.left + contentInsets.right)
|
||||
|
||||
return (
|
||||
viewportWidth: String(format: "%.3f", viewportWidth),
|
||||
viewportHeight: String(format: "%.3f", viewportHeight),
|
||||
contentWidth: String(format: "%.3f", contentWidth),
|
||||
columnGap: String(format: "%.3f", columnGap),
|
||||
paddingTop: String(format: "%.3f", contentInsets.top),
|
||||
paddingRight: String(format: "%.3f", contentInsets.right),
|
||||
paddingBottom: String(format: "%.3f", contentInsets.bottom),
|
||||
paddingLeft: String(format: "%.3f", contentInsets.left),
|
||||
fontSize: String(format: "%.3f", presentation.fontSize),
|
||||
lineHeight: String(format: "%.3f", max(1, presentation.lineHeightMultiple))
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import UIKit
|
||||
import WebKit
|
||||
|
||||
extension RDEPUBWebView {
|
||||
func configureWebViewIfNeeded(publication: RDEPUBPublication) {
|
||||
let parser = publication.parser
|
||||
let publicationKey = parser.opfURL?.path ?? parser.extractionRootURL?.path ?? UUID().uuidString
|
||||
if publicationKey == configuredPublicationKey, webView != nil {
|
||||
return
|
||||
}
|
||||
|
||||
teardownWebView()
|
||||
|
||||
let userContentController = WKUserContentController()
|
||||
RDEPUBJavaScriptBridge.messageNames.forEach {
|
||||
userContentController.add(self, name: $0)
|
||||
}
|
||||
userContentController.addUserScript(
|
||||
WKUserScript(
|
||||
source: RDEPUBJavaScriptBridge.userScript,
|
||||
injectionTime: .atDocumentEnd,
|
||||
forMainFrameOnly: true
|
||||
)
|
||||
)
|
||||
|
||||
let configuration = WKWebViewConfiguration()
|
||||
configuration.websiteDataStore = .nonPersistent()
|
||||
configuration.userContentController = userContentController
|
||||
let schemeHandler = RDEPUBResourceURLSchemeHandler(parser: parser)
|
||||
configuration.setURLSchemeHandler(schemeHandler, forURLScheme: RDEPUBResourceURLSchemeHandler.scheme)
|
||||
|
||||
let webView = RDEPUBAnnotationWebView(frame: bounds, configuration: configuration)
|
||||
webView.onSelectionAction = { [weak self] action in
|
||||
guard let self else { return }
|
||||
self.handleSelectionMenuAction(action)
|
||||
}
|
||||
UIMenuController.shared.menuItems = [
|
||||
UIMenuItem(title: "拷贝", action: #selector(RDEPUBAnnotationWebView.rd_copy(_:))),
|
||||
UIMenuItem(title: "高亮", action: #selector(RDEPUBAnnotationWebView.rd_highlight(_:))),
|
||||
UIMenuItem(title: "批注", action: #selector(RDEPUBAnnotationWebView.rd_annotate(_:)))
|
||||
]
|
||||
webView.navigationDelegate = self
|
||||
webView.scrollView.isScrollEnabled = false
|
||||
webView.scrollView.showsHorizontalScrollIndicator = false
|
||||
webView.scrollView.showsVerticalScrollIndicator = false
|
||||
webView.scrollView.bounces = false
|
||||
webView.scrollView.alwaysBounceHorizontal = false
|
||||
webView.scrollView.alwaysBounceVertical = false
|
||||
webView.scrollView.clipsToBounds = true
|
||||
webView.scrollView.panGestureRecognizer.isEnabled = false
|
||||
webView.scrollView.pinchGestureRecognizer?.isEnabled = false
|
||||
webView.isOpaque = false
|
||||
webView.backgroundColor = .clear
|
||||
webView.clipsToBounds = true
|
||||
if #available(iOS 16.4, *) {
|
||||
webView.isInspectable = true
|
||||
}
|
||||
|
||||
addSubview(webView)
|
||||
webView.frame = bounds
|
||||
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
|
||||
self.schemeHandler = schemeHandler
|
||||
self.webView = webView
|
||||
self.configuredPublicationKey = publicationKey
|
||||
RDEPUBWebViewDebug.log(debugScope, message: "configured webView=\(RDEPUBWebViewDebug.webViewID(webView)) publicationKey=\(publicationKey)")
|
||||
}
|
||||
|
||||
func handleSelectionMenuAction(_ action: RDEPUBAnnotationMenuAction) {
|
||||
delegate?.epubWebView(self, didRequestSelectionAction: action)
|
||||
clearWebSelection()
|
||||
}
|
||||
|
||||
func clearWebSelection() {
|
||||
webView?.evaluateJavaScript("window.getSelection && window.getSelection().removeAllRanges();")
|
||||
}
|
||||
|
||||
func teardownWebView() {
|
||||
cancelFixedLayoutReadyFallback()
|
||||
if let webView {
|
||||
RDEPUBWebViewDebug.log(debugScope, message: "teardown webView=\(RDEPUBWebViewDebug.webViewID(webView))")
|
||||
}
|
||||
webView?.navigationDelegate = nil
|
||||
if let userContentController = webView?.configuration.userContentController {
|
||||
RDEPUBJavaScriptBridge.messageNames.forEach {
|
||||
userContentController.removeScriptMessageHandler(forName: $0)
|
||||
}
|
||||
}
|
||||
(webView as? RDEPUBAnnotationWebView)?.onSelectionAction = nil
|
||||
webView?.removeFromSuperview()
|
||||
webView = nil
|
||||
schemeHandler = nil
|
||||
configuredPublicationKey = nil
|
||||
currentLoadSignature = nil
|
||||
}
|
||||
}
|
||||
|
||||
extension UIColor {
|
||||
var ss_hexString: String {
|
||||
var red: CGFloat = 0
|
||||
var green: CGFloat = 0
|
||||
var blue: CGFloat = 0
|
||||
var alpha: CGFloat = 0
|
||||
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
|
||||
return String(format: "#%02X%02X%02X", Int(red * 255), Int(green * 255), Int(blue * 255))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import UIKit
|
||||
import WebKit
|
||||
|
||||
extension RDEPUBWebView {
|
||||
public func loadFixedSpread(
|
||||
parser: RDEPUBParser,
|
||||
spread: EPUBFixedSpread,
|
||||
viewportSize: CGSize,
|
||||
contentInset: UIEdgeInsets,
|
||||
backgroundColor: UIColor?
|
||||
) {
|
||||
let request = RDEPUBRenderRequest.fixed(
|
||||
RDEPUBFixedRenderRequest(
|
||||
spread: spread,
|
||||
viewportSize: viewportSize,
|
||||
contentInset: contentInset,
|
||||
backgroundColorCSS: backgroundColor?.ss_hexString,
|
||||
fit: .page,
|
||||
searchPresentation: nil
|
||||
)
|
||||
)
|
||||
load(publication: parser.makePublication(), request: request)
|
||||
}
|
||||
|
||||
func handleFixedLayoutLoad(
|
||||
publication: RDEPUBPublication,
|
||||
request: RDEPUBFixedRenderRequest,
|
||||
loadSignature: String,
|
||||
in webView: WKWebView
|
||||
) {
|
||||
currentPageIndex = 0
|
||||
currentTotalPagesInChapter = 1
|
||||
viewportSize = request.viewportSize
|
||||
currentPadding = request.contentInset
|
||||
currentFontSize = 16
|
||||
currentLineHeightMultiple = 1.5
|
||||
currentThemeBackgroundColor = request.backgroundColorCSS
|
||||
currentThemeTextColor = nil
|
||||
targetLocation = nil
|
||||
pendingHighlights = []
|
||||
fixedSpread = request.spread
|
||||
isFixedLayout = true
|
||||
pendingProgressionRequest = false
|
||||
currentLoadSignature = loadSignature
|
||||
scheduleFixedLayoutReadyFallback()
|
||||
|
||||
let html = RDEPUBFixedLayoutTemplate.html(for: request, publication: publication)
|
||||
RDEPUBWebViewDebug.log(debugScope, message: "load fixed spread resources=\(request.spread.resources.map(\.href).joined(separator: ",")) fit=\(request.fit.rawValue)")
|
||||
webView.loadHTMLString(
|
||||
html,
|
||||
baseURL: URL(string: "\(RDEPUBResourceURLSchemeHandler.scheme)://\(RDEPUBResourceURLSchemeHandler.host)/")
|
||||
)
|
||||
}
|
||||
|
||||
func fixedLayoutLoadSignature(publicationKey: String, request: RDEPUBFixedRenderRequest) -> String {
|
||||
[
|
||||
publicationKey,
|
||||
"fixed",
|
||||
request.spread.resources.map(\.href).joined(separator: "|"),
|
||||
String(format: "%.2f", request.viewportSize.width),
|
||||
String(format: "%.2f", request.viewportSize.height),
|
||||
String(format: "%.2f", request.contentInset.top),
|
||||
String(format: "%.2f", request.contentInset.left),
|
||||
String(format: "%.2f", request.contentInset.bottom),
|
||||
String(format: "%.2f", request.contentInset.right),
|
||||
request.backgroundColorCSS ?? "",
|
||||
request.fit.rawValue
|
||||
].joined(separator: "#")
|
||||
}
|
||||
|
||||
func scheduleFixedLayoutReadyFallback() {
|
||||
let workItem = DispatchWorkItem { [weak self] in
|
||||
RDEPUBWebViewDebug.log(self?.debugScope ?? "ReaderWebView", message: "fixed ready fallback fired")
|
||||
self?.applySearchDecorationsIfNeeded {
|
||||
self?.rendered()
|
||||
}
|
||||
}
|
||||
fixedLayoutReadyWorkItem = workItem
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: workItem)
|
||||
}
|
||||
|
||||
func cancelFixedLayoutReadyFallback() {
|
||||
fixedLayoutReadyWorkItem?.cancel()
|
||||
fixedLayoutReadyWorkItem = nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import Foundation
|
||||
import WebKit
|
||||
|
||||
extension RDEPUBWebView {
|
||||
func internalLocation(from url: URL) -> RDEPUBLocation? {
|
||||
let href = url.path.removingPercentEncoding?.trimmingCharacters(in: CharacterSet(charactersIn: "/")) ?? ""
|
||||
let fragment = url.fragment
|
||||
guard !href.isEmpty || fragment != nil else { return nil }
|
||||
return RDEPUBLocation(href: href, progression: 0, fragment: fragment)
|
||||
}
|
||||
|
||||
func currentLocation(from body: [String: Any]) -> RDEPUBLocation {
|
||||
let progression = (body["progression"] as? NSNumber)?.doubleValue ?? 0
|
||||
let lastProgression = (body["lastProgression"] as? NSNumber)?.doubleValue
|
||||
let fragment = body["fragment"] as? String
|
||||
return RDEPUBLocation(href: currentHref, progression: progression, lastProgression: lastProgression, fragment: fragment)
|
||||
}
|
||||
}
|
||||
|
||||
extension RDEPUBWebView: WKNavigationDelegate {
|
||||
public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
|
||||
RDEPUBWebViewDebug.logNavigationEvent(debugScope, webView: webView, event: "didStart", url: webView.url)
|
||||
}
|
||||
|
||||
public func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
|
||||
RDEPUBWebViewDebug.logNavigationEvent(debugScope, webView: webView, event: "didCommit", url: webView.url)
|
||||
}
|
||||
|
||||
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
|
||||
RDEPUBWebViewDebug.logNavigationEvent(debugScope, webView: webView, event: "didFinish", url: webView.url)
|
||||
applyPresentation()
|
||||
}
|
||||
|
||||
public func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
|
||||
RDEPUBWebViewDebug.logNavigationEvent(debugScope, webView: webView, event: "processTerminated", url: webView.url)
|
||||
}
|
||||
|
||||
public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
|
||||
RDEPUBWebViewDebug.logNavigationEvent(debugScope, webView: webView, event: "didFail", url: webView.url, error: error)
|
||||
}
|
||||
|
||||
public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
|
||||
RDEPUBWebViewDebug.logNavigationEvent(debugScope, webView: webView, event: "didFailProvisional", url: webView.url, error: error)
|
||||
}
|
||||
|
||||
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
|
||||
RDEPUBWebViewDebug.logNavigationEvent(debugScope, webView: webView, event: "decidePolicy", url: navigationAction.request.url)
|
||||
guard navigationAction.navigationType == .linkActivated,
|
||||
let url = navigationAction.request.url else {
|
||||
decisionHandler(.allow)
|
||||
return
|
||||
}
|
||||
|
||||
if url.scheme == RDEPUBResourceURLSchemeHandler.scheme,
|
||||
let location = internalLocation(from: url) {
|
||||
delegate?.epubWebView(self, didActivateInternalLink: location, fromSpineIndex: currentSpineIndex)
|
||||
decisionHandler(.cancel)
|
||||
return
|
||||
}
|
||||
|
||||
if let scheme = url.scheme?.lowercased(), ["http", "https", "mailto", "tel"].contains(scheme) {
|
||||
delegate?.epubWebView(self, didActivateExternalLink: url)
|
||||
decisionHandler(.cancel)
|
||||
return
|
||||
}
|
||||
|
||||
decisionHandler(.allow)
|
||||
}
|
||||
}
|
||||
|
||||
extension RDEPUBWebView: WKScriptMessageHandler {
|
||||
public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
|
||||
RDEPUBWebViewDebug.logMessage(debugScope, webView: message.webView, name: message.name, body: message.body)
|
||||
switch message.name {
|
||||
case RDEPUBJavaScriptBridgeMessage.progressionChanged.rawValue:
|
||||
guard let body = message.body as? [String: Any] else { return }
|
||||
delegate?.epubWebView(self, didUpdateLocation: currentLocation(from: body), spineIndex: currentSpineIndex)
|
||||
case RDEPUBJavaScriptBridgeMessage.selectionChanged.rawValue:
|
||||
if let body = message.body as? [String: Any],
|
||||
let text = body["text"] as? String,
|
||||
let rangeInfo = body["rangeInfo"] as? String {
|
||||
let location = currentLocation(from: body)
|
||||
let selection = RDEPUBSelection(location: location, text: text, rangeInfo: rangeInfo)
|
||||
delegate?.epubWebView(self, didChangeSelection: selection, spineIndex: currentSpineIndex)
|
||||
} else {
|
||||
delegate?.epubWebView(self, didChangeSelection: nil, spineIndex: currentSpineIndex)
|
||||
}
|
||||
case RDEPUBJavaScriptBridgeMessage.internalLink.rawValue:
|
||||
guard let body = message.body as? [String: Any],
|
||||
let href = body["href"] as? String else { return }
|
||||
let location = RDEPUBLocation(href: href, progression: 0)
|
||||
delegate?.epubWebView(self, didActivateInternalLink: location, fromSpineIndex: currentSpineIndex)
|
||||
case RDEPUBJavaScriptBridgeMessage.externalLink.rawValue:
|
||||
guard let body = message.body as? [String: Any],
|
||||
let urlString = body["url"] as? String,
|
||||
let url = URL(string: urlString) else { return }
|
||||
delegate?.epubWebView(self, didActivateExternalLink: url)
|
||||
case RDEPUBJavaScriptBridgeMessage.javaScriptError.rawValue:
|
||||
delegate?.epubWebView(self, didLogJavaScriptError: "\(message.body)")
|
||||
case RDEPUBJavaScriptBridgeMessage.fixedLayoutReady.rawValue:
|
||||
applySearchDecorationsIfNeeded {
|
||||
self.rendered()
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import UIKit
|
||||
import WebKit
|
||||
|
||||
extension RDEPUBWebView {
|
||||
public func loadPage(
|
||||
parser: RDEPUBParser,
|
||||
spineIndex: Int,
|
||||
pageIndex: Int,
|
||||
totalPagesInChapter: Int,
|
||||
viewportSize: CGSize,
|
||||
padding: UIEdgeInsets,
|
||||
fontSize: CGFloat,
|
||||
lineHeightMultiple: CGFloat,
|
||||
themeBackgroundColor: String?,
|
||||
themeTextColor: String?,
|
||||
targetLocation: RDEPUBLocation?,
|
||||
highlights: [RDEPUBHighlight]
|
||||
) {
|
||||
let href = parser.spine.indices.contains(spineIndex) ? parser.spine[spineIndex].href : ""
|
||||
let request = RDEPUBRenderRequest.reflowable(
|
||||
RDEPUBReflowableRenderRequest(
|
||||
spineIndex: spineIndex,
|
||||
href: href,
|
||||
pageIndex: pageIndex,
|
||||
totalPagesInChapter: totalPagesInChapter,
|
||||
presentation: RDEPUBPresentationStyle(
|
||||
viewportSize: viewportSize,
|
||||
contentInsets: padding,
|
||||
fontSize: fontSize,
|
||||
lineHeightMultiple: lineHeightMultiple,
|
||||
themeBackgroundColor: themeBackgroundColor,
|
||||
themeTextColor: themeTextColor
|
||||
),
|
||||
targetLocation: targetLocation,
|
||||
highlights: highlights,
|
||||
searchPresentation: nil
|
||||
)
|
||||
)
|
||||
load(publication: parser.makePublication(), request: request)
|
||||
}
|
||||
|
||||
func handleReflowableLoad(
|
||||
publication: RDEPUBPublication,
|
||||
request: RDEPUBReflowableRenderRequest,
|
||||
loadSignature: String,
|
||||
in webView: WKWebView
|
||||
) {
|
||||
guard publication.spine.indices.contains(request.spineIndex),
|
||||
let requestURL = publication.resourceResolver.resourceURL(forRelativePath: request.href) else {
|
||||
return
|
||||
}
|
||||
|
||||
currentPageIndex = request.pageIndex
|
||||
currentTotalPagesInChapter = max(1, request.totalPagesInChapter)
|
||||
viewportSize = request.presentation.viewportSize
|
||||
currentPadding = request.presentation.contentInsets
|
||||
currentFontSize = request.presentation.fontSize
|
||||
currentLineHeightMultiple = request.presentation.lineHeightMultiple
|
||||
currentThemeBackgroundColor = request.presentation.themeBackgroundColor
|
||||
currentThemeTextColor = request.presentation.themeTextColor
|
||||
targetLocation = request.targetLocation
|
||||
pendingHighlights = request.highlights
|
||||
fixedSpread = nil
|
||||
isFixedLayout = false
|
||||
pendingProgressionRequest = true
|
||||
|
||||
if currentLoadSignature == loadSignature {
|
||||
if didRenderCurrentRequest || webView.isLoading {
|
||||
let reason = didRenderCurrentRequest ? "already-rendered" : "still-loading"
|
||||
RDEPUBWebViewDebug.log(debugScope, message: "skip duplicate request href=\(request.href) page=\(request.pageIndex) reason=\(reason)")
|
||||
return
|
||||
}
|
||||
|
||||
if webView.url == requestURL {
|
||||
RDEPUBWebViewDebug.log(debugScope, message: "reuse existing document href=\(request.href) page=\(request.pageIndex)")
|
||||
applyPresentation()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
currentLoadSignature = loadSignature
|
||||
RDEPUBWebViewDebug.logNavigationEvent(debugScope, webView: webView, event: "load-request", url: requestURL)
|
||||
webView.load(URLRequest(url: requestURL))
|
||||
}
|
||||
|
||||
func reflowableLoadSignature(publicationKey: String, request: RDEPUBReflowableRenderRequest) -> String {
|
||||
let targetSignature = [
|
||||
request.targetLocation?.href ?? "",
|
||||
String(request.targetLocation?.progression ?? 0),
|
||||
String(request.targetLocation?.lastProgression ?? 0),
|
||||
request.targetLocation?.fragment ?? ""
|
||||
].joined(separator: "|")
|
||||
let highlightSignature = request.highlights
|
||||
.map { [$0.id, $0.rangeInfo ?? "", $0.color, $0.style.rawValue].joined(separator: "|") }
|
||||
.joined(separator: ",")
|
||||
let presentation = request.presentation
|
||||
return [
|
||||
publicationKey,
|
||||
"reflowable",
|
||||
String(request.spineIndex),
|
||||
request.href,
|
||||
String(request.pageIndex),
|
||||
String(request.totalPagesInChapter),
|
||||
String(format: "%.2f", presentation.viewportSize.width),
|
||||
String(format: "%.2f", presentation.viewportSize.height),
|
||||
String(format: "%.2f", presentation.contentInsets.top),
|
||||
String(format: "%.2f", presentation.contentInsets.left),
|
||||
String(format: "%.2f", presentation.contentInsets.bottom),
|
||||
String(format: "%.2f", presentation.contentInsets.right),
|
||||
String(format: "%.2f", presentation.fontSize),
|
||||
String(format: "%.2f", presentation.lineHeightMultiple),
|
||||
presentation.themeBackgroundColor ?? "",
|
||||
presentation.themeTextColor ?? "",
|
||||
targetSignature,
|
||||
highlightSignature
|
||||
].joined(separator: "#")
|
||||
}
|
||||
|
||||
func applyPresentation() {
|
||||
guard let webView, let currentRenderRequest else { return }
|
||||
guard case .reflowable(let request) = currentRenderRequest else {
|
||||
return
|
||||
}
|
||||
|
||||
let script = RDEPUBJavaScriptBridge.applyPresentationScript(for: request)
|
||||
RDEPUBWebViewDebug.logJavaScript(
|
||||
debugScope,
|
||||
webView: webView,
|
||||
action: "applyPresentation",
|
||||
details: "spine=\(request.spineIndex) page=\(request.pageIndex) total=\(request.totalPagesInChapter)"
|
||||
)
|
||||
|
||||
webView.evaluateJavaScript(script) { [weak self] _, error in
|
||||
guard let self else { return }
|
||||
if let error {
|
||||
RDEPUBWebViewDebug.logJavaScript(self.debugScope, webView: webView, action: "applyPresentationFailed", details: error.localizedDescription)
|
||||
self.delegate?.epubWebView(self, didLogJavaScriptError: error.localizedDescription)
|
||||
return
|
||||
}
|
||||
self.applySearchDecorationsIfNeeded {
|
||||
self.rendered()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import WebKit
|
||||
|
||||
extension RDEPUBWebView {
|
||||
func applySearchDecorationsIfNeeded(completion: (() -> Void)? = nil) {
|
||||
guard let webView else {
|
||||
completion?()
|
||||
return
|
||||
}
|
||||
|
||||
let presentation: RDEPUBSearchPresentation?
|
||||
switch currentRenderRequest {
|
||||
case .reflowable(let request):
|
||||
presentation = request.searchPresentation
|
||||
case .fixed(let request):
|
||||
presentation = request.searchPresentation
|
||||
case .none:
|
||||
presentation = nil
|
||||
}
|
||||
|
||||
let script = RDEPUBJavaScriptBridge.applySearchScript(for: presentation)
|
||||
webView.evaluateJavaScript(script) { [weak self] _, error in
|
||||
guard let self else {
|
||||
completion?()
|
||||
return
|
||||
}
|
||||
if let error {
|
||||
self.delegate?.epubWebView(self, didLogJavaScriptError: error.localizedDescription)
|
||||
}
|
||||
completion?()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import UIKit
|
||||
import WebKit
|
||||
|
||||
public protocol RDEPUBWebViewDelegate: AnyObject {
|
||||
func epubWebView(_ webView: RDEPUBWebView, didUpdateLocation location: RDEPUBLocation, spineIndex: Int)
|
||||
func epubWebView(_ webView: RDEPUBWebView, didChangeSelection selection: RDEPUBSelection?, spineIndex: Int)
|
||||
func epubWebView(_ webView: RDEPUBWebView, didRequestSelectionAction action: RDEPUBAnnotationMenuAction)
|
||||
func epubWebView(_ webView: RDEPUBWebView, didActivateInternalLink location: RDEPUBLocation, fromSpineIndex: Int)
|
||||
func epubWebView(_ webView: RDEPUBWebView, didActivateExternalLink url: URL)
|
||||
func epubWebView(_ webView: RDEPUBWebView, didLogJavaScriptError message: String)
|
||||
func epubWebViewDidFinishRendering(_ webView: RDEPUBWebView)
|
||||
}
|
||||
|
||||
public extension RDEPUBWebViewDelegate {
|
||||
func epubWebView(_ webView: RDEPUBWebView, didRequestSelectionAction action: RDEPUBAnnotationMenuAction) {}
|
||||
}
|
||||
|
||||
final class RDEPUBAnnotationWebView: WKWebView {
|
||||
var onSelectionAction: ((RDEPUBAnnotationMenuAction) -> Void)?
|
||||
|
||||
override var canBecomeFirstResponder: Bool {
|
||||
true
|
||||
}
|
||||
|
||||
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
|
||||
switch action {
|
||||
case #selector(rd_copy(_:)),
|
||||
#selector(rd_highlight(_:)),
|
||||
#selector(rd_annotate(_:)):
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@objc func rd_copy(_ sender: Any?) {
|
||||
onSelectionAction?(.copy)
|
||||
}
|
||||
|
||||
@objc func rd_highlight(_ sender: Any?) {
|
||||
onSelectionAction?(.highlight)
|
||||
}
|
||||
|
||||
@objc func rd_annotate(_ sender: Any?) {
|
||||
onSelectionAction?(.annotate)
|
||||
}
|
||||
}
|
||||
|
||||
public final class RDEPUBWebView: UIView {
|
||||
public weak var delegate: RDEPUBWebViewDelegate?
|
||||
public var onRendered: (() -> Void)?
|
||||
|
||||
var publication: RDEPUBPublication?
|
||||
var currentRenderRequest: RDEPUBRenderRequest?
|
||||
var webView: WKWebView?
|
||||
var schemeHandler: RDEPUBResourceURLSchemeHandler?
|
||||
var configuredPublicationKey: String?
|
||||
var currentLoadSignature: String?
|
||||
var currentSpineIndex = 0
|
||||
var currentHref = ""
|
||||
var currentPageIndex = 0
|
||||
var currentTotalPagesInChapter = 1
|
||||
var viewportSize: CGSize = .zero
|
||||
var currentPadding: UIEdgeInsets = .zero
|
||||
var currentFontSize: CGFloat = 16
|
||||
var currentLineHeightMultiple: CGFloat = 1.5
|
||||
var currentThemeBackgroundColor: String?
|
||||
var currentThemeTextColor: String?
|
||||
var targetLocation: RDEPUBLocation?
|
||||
var pendingHighlights: [RDEPUBHighlight] = []
|
||||
var fixedSpread: EPUBFixedSpread?
|
||||
var isFixedLayout = false
|
||||
var pendingProgressionRequest = false
|
||||
var fixedLayoutReadyWorkItem: DispatchWorkItem?
|
||||
var didRenderCurrentRequest = false
|
||||
let debugScope = "ReaderWebView"
|
||||
|
||||
public override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
backgroundColor = .clear
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
deinit {
|
||||
teardownWebView()
|
||||
}
|
||||
|
||||
public override func layoutSubviews() {
|
||||
super.layoutSubviews()
|
||||
webView?.frame = bounds
|
||||
}
|
||||
|
||||
public func reset() {
|
||||
delegate = nil
|
||||
onRendered = nil
|
||||
publication = nil
|
||||
currentRenderRequest = nil
|
||||
currentSpineIndex = 0
|
||||
currentHref = ""
|
||||
currentPageIndex = 0
|
||||
currentTotalPagesInChapter = 1
|
||||
viewportSize = .zero
|
||||
currentPadding = .zero
|
||||
currentFontSize = 16
|
||||
currentLineHeightMultiple = 1.5
|
||||
currentThemeBackgroundColor = nil
|
||||
currentThemeTextColor = nil
|
||||
targetLocation = nil
|
||||
pendingHighlights = []
|
||||
fixedSpread = nil
|
||||
isFixedLayout = false
|
||||
pendingProgressionRequest = false
|
||||
didRenderCurrentRequest = false
|
||||
teardownWebView()
|
||||
}
|
||||
|
||||
public func load(publication: RDEPUBPublication, request: RDEPUBRenderRequest) {
|
||||
configureWebViewIfNeeded(publication: publication)
|
||||
guard let webView else { return }
|
||||
|
||||
self.publication = publication
|
||||
self.currentRenderRequest = request
|
||||
self.currentSpineIndex = request.primarySpineIndex
|
||||
self.currentHref = request.primaryHref
|
||||
self.didRenderCurrentRequest = false
|
||||
cancelFixedLayoutReadyFallback()
|
||||
|
||||
let publicationKey = publication.parser.opfURL?.path ?? publication.parser.extractionRootURL?.path ?? ""
|
||||
let loadSignature = pageLoadSignature(publicationKey: publicationKey, request: request)
|
||||
RDEPUBWebViewDebug.log(
|
||||
debugScope,
|
||||
message: "load request=\(request.isFixedLayout ? "fixed" : "reflowable") signature=\(loadSignature) webView=\(RDEPUBWebViewDebug.webViewID(webView))"
|
||||
)
|
||||
|
||||
switch request {
|
||||
case .reflowable(let reflowableRequest):
|
||||
handleReflowableLoad(publication: publication, request: reflowableRequest, loadSignature: loadSignature, in: webView)
|
||||
case .fixed(let fixedRequest):
|
||||
handleFixedLayoutLoad(publication: publication, request: fixedRequest, loadSignature: loadSignature, in: webView)
|
||||
}
|
||||
}
|
||||
|
||||
func pageLoadSignature(
|
||||
publicationKey: String,
|
||||
request: RDEPUBRenderRequest
|
||||
) -> String {
|
||||
switch request {
|
||||
case .reflowable(let request):
|
||||
return reflowableLoadSignature(publicationKey: publicationKey, request: request)
|
||||
case .fixed(let request):
|
||||
return fixedLayoutLoadSignature(publicationKey: publicationKey, request: request)
|
||||
}
|
||||
}
|
||||
|
||||
func rendered() {
|
||||
guard !didRenderCurrentRequest else { return }
|
||||
didRenderCurrentRequest = true
|
||||
cancelFixedLayoutReadyFallback()
|
||||
RDEPUBWebViewDebug.log(debugScope, message: "rendered spine=\(currentSpineIndex) href=\(currentHref) fixed=\(isFixedLayout)")
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in
|
||||
guard let self else { return }
|
||||
self.delegate?.epubWebViewDidFinishRendering(self)
|
||||
self.onRendered?()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import Foundation
|
||||
import WebKit
|
||||
|
||||
enum RDEPUBWebViewDebug {
|
||||
static var isEnabled: Bool = {
|
||||
if let configured = UserDefaults.standard.object(forKey: "RDEPUBWebViewDebugEnabled") as? Bool {
|
||||
return configured
|
||||
}
|
||||
#if DEBUG
|
||||
return true
|
||||
#else
|
||||
return false
|
||||
#endif
|
||||
}()
|
||||
|
||||
static func webViewID(_ webView: WKWebView?) -> String {
|
||||
guard let webView else { return "nil-webview" }
|
||||
return String(ObjectIdentifier(webView).hashValue, radix: 16)
|
||||
}
|
||||
|
||||
static func log(_ scope: String, message: String) {
|
||||
guard isEnabled else { return }
|
||||
print("[RDReaderWK][\(scope)] \(message)")
|
||||
}
|
||||
|
||||
static func logNavigationEvent(_ scope: String, webView: WKWebView?, event: String, url: URL? = nil, error: Error? = nil) {
|
||||
guard isEnabled else { return }
|
||||
let webViewToken = webViewID(webView)
|
||||
let urlText = summarizedURL(url)
|
||||
if let error {
|
||||
log(scope, message: "webView=\(webViewToken) event=\(event) url=\(urlText) error=\(error.localizedDescription)")
|
||||
} else {
|
||||
log(scope, message: "webView=\(webViewToken) event=\(event) url=\(urlText)")
|
||||
}
|
||||
}
|
||||
|
||||
static func logJavaScript(_ scope: String, webView: WKWebView?, action: String, details: String) {
|
||||
guard isEnabled else { return }
|
||||
log(scope, message: "webView=\(webViewID(webView)) js=\(action) \(details)")
|
||||
}
|
||||
|
||||
static func logMessage(_ scope: String, webView: WKWebView?, name: String, body: Any) {
|
||||
guard isEnabled else { return }
|
||||
log(scope, message: "webView=\(webViewID(webView)) message=\(name) body=\(String(describing: body))")
|
||||
}
|
||||
|
||||
static func logSchemeTask(_ scope: String, requestURL: URL?, fileURL: URL? = nil, event: String, error: Error? = nil) {
|
||||
guard isEnabled else { return }
|
||||
let requestText = summarizedURL(requestURL)
|
||||
let fileText = summarizedURL(fileURL)
|
||||
if let error {
|
||||
log(scope, message: "scheme=\(event) request=\(requestText) file=\(fileText) error=\(error.localizedDescription)")
|
||||
} else {
|
||||
log(scope, message: "scheme=\(event) request=\(requestText) file=\(fileText)")
|
||||
}
|
||||
}
|
||||
|
||||
static func summarizedURL(_ url: URL?) -> String {
|
||||
guard let url else { return "nil" }
|
||||
if let scheme = url.scheme, scheme == RDEPUBResourceURLSchemeHandler.scheme {
|
||||
return url.absoluteString
|
||||
}
|
||||
let path = url.path
|
||||
if path.isEmpty {
|
||||
return url.absoluteString
|
||||
}
|
||||
return url.lastPathComponent.isEmpty ? path : url.lastPathComponent
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user