initial epub support

This commit is contained in:
Agel committed 2026-03-19 23:27:01 +01:00
1 parent 53d6d541a7
commit f328e7dab0
9 files changed
+878 -5

No files matched your search

+333
View File
@@ -0,0 +1,333 @@
#include "EpubReader.h"
#include <QDomDocument>
#include <QFileInfo>
#include <QTextStream>
#include <QXmlStreamReader>
#include <minizip/unzip.h>
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
// Read a single file from an open unzFile handle by name.
// Returns empty QByteArray on failure.
static QByteArray readZipEntry(unzFile zf, const char *entryName)
{
if (unzLocateFile(zf, entryName, 0) != UNZ_OK)
return {};
if (unzOpenCurrentFile(zf) != UNZ_OK)
return {};
QByteArray result;
char buf[4096];
int bytesRead;
while ((bytesRead = unzReadCurrentFile(zf, buf, sizeof(buf))) > 0)
result.append(buf, bytesRead);
unzCloseCurrentFile(zf);
return (bytesRead == 0) ? result : QByteArray{};
}
// Serialize a QDomNode to a string (no XML declaration, no extra indentation).
static QString serializeNode(const QDomNode &node)
{
QString out;
QTextStream stream(&out);
node.save(stream, 0 /*indent*/);
return out;
}
// ---------------------------------------------------------------------------
// EpubReader::open
// ---------------------------------------------------------------------------
bool EpubReader::open(const QString &filePath)
{
// Reset state
m_title.clear();
m_author.clear();
m_error.clear();
m_opfDir.clear();
m_spineHrefs.clear();
m_spineRawContent.clear();
m_toc.clear();
unzFile zf = unzOpen(filePath.toUtf8().constData());
if (!zf) {
m_error = QStringLiteral("Cannot open as ZIP archive: ") + filePath;
return false;
}
// Ensure the handle is closed on all exit paths
auto guard = [&](void *) { unzClose(zf); };
std::unique_ptr<void, decltype(guard)> closeGuard(zf, guard);
// 1. Parse META-INF/container.xml
QByteArray containerData = readZipEntry(zf, "META-INF/container.xml");
if (containerData.isEmpty()) {
m_error = QStringLiteral("Invalid EPUB: missing META-INF/container.xml");
return false;
}
QString opfPath;
if (!parseContainer(containerData, opfPath)) {
m_error = QStringLiteral("Invalid EPUB: cannot parse container.xml");
return false;
}
// 2. Determine OPF base directory
const int lastSlash = opfPath.lastIndexOf(QLatin1Char('/'));
m_opfDir = (lastSlash >= 0) ? opfPath.left(lastSlash + 1) : QString();
// 3. Parse OPF
QByteArray opfData = readZipEntry(zf, opfPath.toUtf8().constData());
if (opfData.isEmpty()) {
m_error = QStringLiteral("Invalid EPUB: cannot read OPF file: ") + opfPath;
return false;
}
QString ncxHref;
if (!parseOpf(opfData, ncxHref)) {
m_error = QStringLiteral("Invalid EPUB: cannot parse OPF file");
return false;
}
// 4. Read each spine item's raw XHTML
for (const QString &href : m_spineHrefs)
m_spineRawContent.append(readZipEntry(zf, href.toUtf8().constData()));
// 5. Parse NCX if available
if (!ncxHref.isEmpty()) {
QByteArray ncxData = readZipEntry(zf, ncxHref.toUtf8().constData());
if (!ncxData.isEmpty())
parseNcx(ncxData);
}
return true;
}
// ---------------------------------------------------------------------------
// parseContainer: extract the OPF rootfile full-path
// ---------------------------------------------------------------------------
bool EpubReader::parseContainer(const QByteArray &data, QString &opfPath)
{
QXmlStreamReader xml(data);
while (!xml.atEnd()) {
xml.readNext();
if (xml.isStartElement() && xml.name() == QLatin1String("rootfile")) {
opfPath = xml.attributes().value(QLatin1String("full-path")).toString();
if (!opfPath.isEmpty())
return true;
}
}
return false;
}
// ---------------------------------------------------------------------------
// parseOpf: extract metadata, manifest, and spine
// ---------------------------------------------------------------------------
bool EpubReader::parseOpf(const QByteArray &data, QString &ncxHref)
{
QXmlStreamReader xml(data);
QHash<QString, QString> manifest; // id -> relative href
QString ncxId;
static const QLatin1String kDcNs("http://purl.org/dc/elements/1.1/");
while (!xml.atEnd()) {
xml.readNext();
if (!xml.isStartElement())
continue;
const QStringView name = xml.name();
const QStringView ns = xml.namespaceUri();
if (name == QLatin1String("title") && ns == kDcNs) {
if (m_title.isEmpty())
m_title = xml.readElementText().trimmed();
} else if (name == QLatin1String("creator") && ns == kDcNs) {
if (m_author.isEmpty())
m_author = xml.readElementText().trimmed();
} else if (name == QLatin1String("item")) {
const QString id = xml.attributes().value(QLatin1String("id")).toString();
const QString href = xml.attributes().value(QLatin1String("href")).toString();
if (!id.isEmpty() && !href.isEmpty())
manifest.insert(id, href);
} else if (name == QLatin1String("spine")) {
ncxId = xml.attributes().value(QLatin1String("toc")).toString();
} else if (name == QLatin1String("itemref")) {
const QString idref = xml.attributes().value(QLatin1String("idref")).toString();
if (manifest.contains(idref))
m_spineHrefs.append(m_opfDir + manifest.value(idref));
}
}
if (!ncxId.isEmpty() && manifest.contains(ncxId))
ncxHref = m_opfDir + manifest.value(ncxId);
return !xml.hasError();
}
// ---------------------------------------------------------------------------
// parseNcx: build TOC from navMap
// ---------------------------------------------------------------------------
void EpubReader::parseNcx(const QByteArray &data)
{
QXmlStreamReader xml(data);
int depth = 0;
QString currentLabel;
QString currentSrc;
bool insideNavLabel = false;
bool insideText = false;
// Map both full path and filename-only -> spine index
QHash<QString, int> hrefToIndex;
for (int i = 0; i < m_spineHrefs.size(); ++i) {
hrefToIndex.insert(m_spineHrefs[i], i);
hrefToIndex.insert(QFileInfo(m_spineHrefs[i]).fileName(), i);
}
while (!xml.atEnd()) {
xml.readNext();
if (xml.isStartElement()) {
const QStringView name = xml.name();
if (name == QLatin1String("navPoint")) {
++depth;
currentLabel.clear();
currentSrc.clear();
} else if (name == QLatin1String("navLabel")) {
insideNavLabel = true;
} else if (insideNavLabel && name == QLatin1String("text")) {
insideText = true;
} else if (name == QLatin1String("content")) {
QString src = xml.attributes().value(QLatin1String("src")).toString();
const int hashPos = src.indexOf(QLatin1Char('#'));
if (hashPos >= 0)
src = src.left(hashPos);
currentSrc = src;
}
} else if (xml.isCharacters() && insideText) {
currentLabel += xml.text();
} else if (xml.isEndElement()) {
const QStringView name = xml.name();
if (name == QLatin1String("text") && insideText) {
insideText = false;
} else if (name == QLatin1String("navLabel")) {
insideNavLabel = false;
} else if (name == QLatin1String("navPoint")) {
int chapterIdx = -1;
if (!currentSrc.isEmpty()) {
const QString fullHref = m_opfDir + currentSrc;
if (hrefToIndex.contains(fullHref))
chapterIdx = hrefToIndex.value(fullHref);
else if (hrefToIndex.contains(currentSrc))
chapterIdx = hrefToIndex.value(currentSrc);
}
if (chapterIdx >= 0 && !currentLabel.trimmed().isEmpty()) {
TocEntry entry;
entry.title = currentLabel.trimmed();
entry.chapterIndex = chapterIdx;
entry.depth = depth - 1;
m_toc.append(entry);
}
--depth;
currentLabel.clear();
currentSrc.clear();
}
}
}
}
// ---------------------------------------------------------------------------
// chunkXhtml: DOM-based chunking of a spine XHTML item
// ---------------------------------------------------------------------------
QStringList EpubReader::chunkXhtml(const QByteArray &data)
{
if (data.isEmpty())
return {};
QDomDocument doc;
const auto parseResult = doc.setContent(data, QDomDocument::ParseOption::Default);
if (!parseResult) {
// Malformed XHTML fallback: return raw as a single chunk
return {QString::fromUtf8(data)};
}
// Find <body> element (may have namespace prefix in some EPUBs)
QDomElement body;
const QDomNodeList bodies = doc.elementsByTagName(QStringLiteral("body"));
if (!bodies.isEmpty())
body = bodies.at(0).toElement();
if (body.isNull())
return {};
static constexpr int kChunkSize = 4096;
QStringList chunks;
QString current;
QDomNode node = body.firstChild();
while (!node.isNull()) {
QString serialized;
if (node.isElement()) {
serialized = serializeNode(node);
} else if (node.isText()) {
const QString text = node.nodeValue().trimmed();
if (!text.isEmpty())
serialized = QStringLiteral("<p>") + text.toHtmlEscaped() + QStringLiteral("</p>\n");
}
if (!serialized.isEmpty()) {
if (!current.isEmpty() && current.size() + serialized.size() > kChunkSize) {
chunks.append(current);
current.clear();
}
current += serialized;
}
node = node.nextSibling();
}
if (!current.isEmpty())
chunks.append(current);
return chunks;
}
// ---------------------------------------------------------------------------
// FormatReader interface
// ---------------------------------------------------------------------------
QString EpubReader::lastError() { return m_error; }
QString EpubReader::title() { return m_title; }
QString EpubReader::author() { return m_author; }
int EpubReader::chapterCount() { return m_spineHrefs.size(); }
QList<TocEntry> EpubReader::tableOfContents() { return m_toc; }
Chapter EpubReader::loadChapter(int index)
{
if (index < 0 || index >= m_spineRawContent.size())
return Chapter{index, {}, {}};
QString chTitle;
for (const TocEntry &e : m_toc) {
if (e.chapterIndex == index) {
chTitle = e.title;
break;
}
}
if (chTitle.isEmpty() && index < m_spineHrefs.size())
chTitle = QFileInfo(m_spineHrefs[index]).completeBaseName();
return Chapter{index, chTitle, chunkXhtml(m_spineRawContent[index])};
}
+35
View File
@@ -0,0 +1,35 @@
#ifndef EPUBREADER_H
#define EPUBREADER_H
#include "backend/FormatReader.h"
#include <QByteArray>
#include <QHash>
#include <QList>
#include <QStringList>
class EpubReader : public FormatReader {
public:
bool open(const QString &filePath) override;
QString lastError() override;
int chapterCount() override;
Chapter loadChapter(int index) override;
QList<TocEntry> tableOfContents() override;
QString title() override;
QString author() override;
private:
QString m_title;
QString m_author;
QString m_error;
QString m_opfDir;
QStringList m_spineHrefs;
QList<QByteArray> m_spineRawContent;
QList<TocEntry> m_toc;
bool parseContainer(const QByteArray &data, QString &opfPath);
bool parseOpf(const QByteArray &data, QString &ncxHref);
void parseNcx(const QByteArray &data);
static QStringList chunkXhtml(const QByteArray &data);
};
#endif // EPUBREADER_H