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

+15 -3
View File
@@ -18,6 +18,7 @@ find_package(Qt6 REQUIRED COMPONENTS
Svg Svg
QuickControls2 QuickControls2
Test Test
Xml
) )
find_package(Qt6 OPTIONAL_COMPONENTS Pdf DBus) find_package(Qt6 OPTIONAL_COMPONENTS Pdf DBus)
@@ -25,6 +26,7 @@ find_package(Qt6 OPTIONAL_COMPONENTS Pdf DBus)
find_package(PkgConfig REQUIRED) find_package(PkgConfig REQUIRED)
pkg_check_modules(UCHARDET REQUIRED IMPORTED_TARGET uchardet) pkg_check_modules(UCHARDET REQUIRED IMPORTED_TARGET uchardet)
find_package(Iconv REQUIRED) find_package(Iconv REQUIRED)
pkg_check_modules(MINIZIP REQUIRED IMPORTED_TARGET minizip)
# Source files # Source files
set(SOURCES set(SOURCES
@@ -40,6 +42,8 @@ set(SOURCES
src/backend/BookController.cpp src/backend/BookController.cpp
src/backend/formats/TxtReader.h src/backend/formats/TxtReader.h
src/backend/formats/TxtReader.cpp src/backend/formats/TxtReader.cpp
src/backend/formats/EpubReader.h
src/backend/formats/EpubReader.cpp
) )
@@ -82,6 +86,7 @@ endif()
target_link_libraries(asteria-qt PRIVATE PkgConfig::UCHARDET) target_link_libraries(asteria-qt PRIVATE PkgConfig::UCHARDET)
target_link_libraries(asteria-qt PRIVATE Iconv::Iconv) target_link_libraries(asteria-qt PRIVATE Iconv::Iconv)
target_link_libraries(asteria-qt PRIVATE PkgConfig::MINIZIP Qt6::Xml)
# Set resource aliases so src/qml/* maps to qrc:/Asteria/* # Set resource aliases so src/qml/* maps to qrc:/Asteria/*
set_source_files_properties(src/qml/Main.qml PROPERTIES QT_RESOURCE_ALIAS Main.qml) set_source_files_properties(src/qml/Main.qml PROPERTIES QT_RESOURCE_ALIAS Main.qml)
@@ -153,9 +158,15 @@ endfunction()
add_asteria_test(TxtReaderTest tests/formats/TxtReaderTest.cpp add_asteria_test(TxtReaderTest tests/formats/TxtReaderTest.cpp
src/backend/formats/TxtReader.cpp) src/backend/formats/TxtReader.cpp)
add_asteria_test(EpubReaderTest tests/formats/EpubReaderTest.cpp
src/backend/formats/EpubReader.cpp)
target_link_libraries(EpubReaderTest PRIVATE PkgConfig::MINIZIP Qt6::Xml)
add_asteria_test(ReaderFactoryTest tests/ReaderFactoryTest.cpp add_asteria_test(ReaderFactoryTest tests/ReaderFactoryTest.cpp
src/backend/ReaderFactory.cpp src/backend/ReaderFactory.cpp
src/backend/formats/TxtReader.cpp) src/backend/formats/TxtReader.cpp
src/backend/formats/EpubReader.cpp)
target_link_libraries(ReaderFactoryTest PRIVATE PkgConfig::MINIZIP Qt6::Xml)
add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp
src/backend/ReadingModel.cpp) src/backend/ReadingModel.cpp)
@@ -166,11 +177,12 @@ add_asteria_test(BookControllerTest tests/BookControllerTest.cpp
src/backend/BookController.cpp src/backend/BookController.cpp
src/backend/ReaderFactory.cpp src/backend/ReaderFactory.cpp
src/backend/ReadingModel.cpp src/backend/ReadingModel.cpp
src/backend/formats/TxtReader.cpp) src/backend/formats/TxtReader.cpp
src/backend/formats/EpubReader.cpp)
add_asteria_test(AppStateTest tests/AppStateTest.cpp add_asteria_test(AppStateTest tests/AppStateTest.cpp
src/backend/AppState.cpp) src/backend/AppState.cpp)
target_link_libraries(BookControllerTest PRIVATE Qt6::Widgets) target_link_libraries(BookControllerTest PRIVATE Qt6::Widgets PkgConfig::MINIZIP Qt6::Xml)
set_tests_properties(BookControllerTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") set_tests_properties(BookControllerTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
if(Qt6DBus_FOUND) if(Qt6DBus_FOUND)
+3
View File
@@ -1,6 +1,7 @@
#include "ReaderFactory.h" #include "ReaderFactory.h"
#include "FormatReader.h" #include "FormatReader.h"
#include "formats/TxtReader.h" #include "formats/TxtReader.h"
#include "formats/EpubReader.h"
#include <QFileInfo> #include <QFileInfo>
@@ -10,6 +11,8 @@ std::unique_ptr<FormatReader> ReaderFactory::create(const QString &filePath)
if (ext == QLatin1String("txt")) if (ext == QLatin1String("txt"))
return std::make_unique<TxtReader>(); return std::make_unique<TxtReader>();
if (ext == QLatin1String("epub"))
return std::make_unique<EpubReader>();
return nullptr; return nullptr;
} }
+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
+50 -2
View File
@@ -1,4 +1,5 @@
import QtQuick import QtQuick
import QtQuick.Controls
import Asteria import Asteria
Rectangle { Rectangle {
@@ -12,9 +13,33 @@ Rectangle {
anchors.top: parent.top anchors.top: parent.top
} }
Text { // Prev chapter button
Button {
id: prevBtn
anchors.verticalCenter: parent.verticalCenter anchors.verticalCenter: parent.verticalCenter
x: parent.width * 0.5 x: parent.width * 0.5 - chapterText.implicitWidth / 2 - width - 4
visible: bookController.hasBook && readingModel.hasChapters
enabled: readingModel.currentChapter > 0
flat: true
padding: 0
implicitWidth: 20
implicitHeight: 20
contentItem: Text {
text: "\ue5cb"
font.family: "Material Icons Outlined"
font.pixelSize: 16
color: prevBtn.enabled ? Theme.dimText : Theme.actionDisabled
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
background: Item {}
onClicked: readingModel.previousChapter()
}
Text {
id: chapterText
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenter: parent.horizontalCenter
text: bookController.hasBook && readingModel.hasChapters text: bookController.hasBook && readingModel.hasChapters
? "Chapter " + (readingModel.currentChapter + 1) + " / " + readingModel.totalChapters ? "Chapter " + (readingModel.currentChapter + 1) + " / " + readingModel.totalChapters
: "" : ""
@@ -23,6 +48,29 @@ Rectangle {
color: Theme.dimText color: Theme.dimText
} }
// Next chapter button
Button {
id: nextBtn
anchors.verticalCenter: parent.verticalCenter
x: parent.width * 0.5 + chapterText.implicitWidth / 2 + 4
visible: bookController.hasBook && readingModel.hasChapters
enabled: readingModel.currentChapter < readingModel.totalChapters - 1
flat: true
padding: 0
implicitWidth: 20
implicitHeight: 20
contentItem: Text {
text: "\ue5cc"
font.family: "Material Icons Outlined"
font.pixelSize: 16
color: nextBtn.enabled ? Theme.dimText : Theme.actionDisabled
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
background: Item {}
onClicked: readingModel.nextChapter()
}
Text { Text {
anchors.right: parent.right anchors.right: parent.right
anchors.rightMargin: 16 anchors.rightMargin: 16
+5
View File
@@ -3,6 +3,11 @@ import QtQuick.Controls
import Asteria import Asteria
Rectangle { Rectangle {
focus: true
Keys.onLeftPressed: readingModel.previousChapter()
Keys.onRightPressed: readingModel.nextChapter()
gradient: Gradient { gradient: Gradient {
GradientStop { position: 0.0; color: Theme.gradientTop } GradientStop { position: 0.0; color: Theme.gradientTop }
GradientStop { position: 1.0; color: Theme.gradientBottom } GradientStop { position: 1.0; color: Theme.gradientBottom }
+69
View File
@@ -49,6 +49,7 @@ Rectangle {
} }
Column { Column {
id: navColumn
y: Theme.headerHeight y: Theme.headerHeight
width: Theme.sidebarWidth width: Theme.sidebarWidth
@@ -96,4 +97,72 @@ Rectangle {
onClicked: sidebar.navigateTo("settings") onClicked: sidebar.navigateTo("settings")
} }
} }
// TOC section — shown when the current book has a table of contents
Item {
visible: bookController.hasBook && bookController.toc.length > 0
anchors.top: navColumn.bottom
anchors.bottom: parent.bottom
width: parent.width
Rectangle {
id: tocDivider
width: parent.width
height: 1
color: Theme.divider
}
Text {
id: tocLabel
anchors.top: tocDivider.bottom
anchors.topMargin: 8
anchors.left: parent.left
anchors.leftMargin: 16
text: "Contents"
font.pixelSize: 10
font.bold: true
color: Theme.dimText
font.letterSpacing: 1
}
ListView {
anchors.top: tocLabel.bottom
anchors.topMargin: 4
anchors.bottom: parent.bottom
width: parent.width
clip: true
model: bookController.toc
delegate: Rectangle {
width: ListView.view.width
height: tocEntryText.implicitHeight + 10
color: readingModel.currentChapter === modelData.chapterIndex
? Qt.rgba(1, 1, 1, 0.05)
: "transparent"
Text {
id: tocEntryText
anchors.verticalCenter: parent.verticalCenter
x: 16 + modelData.depth * 12
width: parent.width - x - 8
text: modelData.title
font.pixelSize: 13
color: readingModel.currentChapter === modelData.chapterIndex
? Theme.sidebarButtonText
: Theme.uiText
elide: Text.ElideRight
wrapMode: Text.NoWrap
}
MouseArea {
anchors.fill: parent
onClicked: {
readingModel.goToChapter(modelData.chapterIndex)
sidebar.navigateTo("reader")
sidebar.closeDrawer()
}
}
}
}
}
} }
+1
View File
@@ -3,4 +3,5 @@ import Asteria
PageView { PageView {
anchors.fill: parent anchors.fill: parent
focus: visible
} }
+367
View File
@@ -0,0 +1,367 @@
#include <QtTest/QtTest>
#include <QDir>
#include <QFile>
#include <QTemporaryFile>
#include <minizip/zip.h>
#include "backend/formats/EpubReader.h"
// ---------------------------------------------------------------------------
// Minimal EPUB fixture builder (uses minizip directly)
// ---------------------------------------------------------------------------
static const char kMimetype[] = "application/epub+zip";
static const char kContainer[] =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">"
" <rootfiles>"
" <rootfile full-path=\"OEBPS/content.opf\""
" media-type=\"application/oebps-package+xml\"/>"
" </rootfiles>"
"</container>";
static const char kOpf[] =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"2.0\" unique-identifier=\"BookId\">"
" <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">"
" <dc:title>Test Book</dc:title>"
" <dc:creator>Test Author</dc:creator>"
" </metadata>"
" <manifest>"
" <item id=\"ncx\" href=\"toc.ncx\" media-type=\"application/x-dtbncx+xml\"/>"
" <item id=\"ch1\" href=\"chapter1.xhtml\" media-type=\"application/xhtml+xml\"/>"
" <item id=\"ch2\" href=\"chapter2.xhtml\" media-type=\"application/xhtml+xml\"/>"
" </manifest>"
" <spine toc=\"ncx\">"
" <itemref idref=\"ch1\"/>"
" <itemref idref=\"ch2\"/>"
" </spine>"
"</package>";
static const char kNcx[] =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<ncx xmlns=\"http://www.daisy.org/z3986/2005/ncx/\" version=\"2005-1\">"
" <navMap>"
" <navPoint id=\"np1\" playOrder=\"1\">"
" <navLabel><text>Chapter One</text></navLabel>"
" <content src=\"chapter1.xhtml\"/>"
" </navPoint>"
" <navPoint id=\"np2\" playOrder=\"2\">"
" <navLabel><text>Chapter Two</text></navLabel>"
" <content src=\"chapter2.xhtml\"/>"
" </navPoint>"
" </navMap>"
"</ncx>";
static const char kChapter1[] =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">"
"<html xmlns=\"http://www.w3.org/1999/xhtml\">"
" <head><title>Chapter One</title></head>"
" <body>"
" <h1>Chapter One</h1>"
" <p>First paragraph of chapter one.</p>"
" <p>Second paragraph of chapter one.</p>"
" </body>"
"</html>";
static const char kChapter2[] =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<html xmlns=\"http://www.w3.org/1999/xhtml\">"
" <head><title>Chapter Two</title></head>"
" <body>"
" <p>This is chapter two content.</p>"
" </body>"
"</html>";
// Add one entry to an open zipFile handle.
static bool addEntry(zipFile zf, const char *name, const QByteArray &data, bool store = false)
{
zip_fileinfo fi{};
int method = store ? Z_NO_COMPRESSION : Z_DEFLATED;
int level = store ? 0 : Z_DEFAULT_COMPRESSION;
if (zipOpenNewFileInZip(zf, name, &fi,
nullptr, 0, nullptr, 0, nullptr,
method, level) != ZIP_OK)
return false;
if (zipWriteInFileInZip(zf, data.constData(), (unsigned)data.size()) != ZIP_OK) {
zipCloseFileInZip(zf);
return false;
}
return zipCloseFileInZip(zf) == ZIP_OK;
}
// Build a minimal two-chapter EPUB and return its file path (caller deletes).
static QString buildSampleEpub()
{
QTemporaryFile tmp;
tmp.setFileTemplate(QDir::tempPath() + "/epub_test_XXXXXX.epub");
tmp.setAutoRemove(false);
if (!tmp.open()) return {};
const QString path = tmp.fileName();
tmp.close();
zipFile zf = zipOpen(path.toUtf8().constData(), APPEND_STATUS_CREATE);
if (!zf) return {};
bool ok = true;
ok = ok && addEntry(zf, "mimetype", QByteArray(kMimetype), /*store=*/true);
ok = ok && addEntry(zf, "META-INF/container.xml", QByteArray(kContainer));
ok = ok && addEntry(zf, "OEBPS/content.opf", QByteArray(kOpf));
ok = ok && addEntry(zf, "OEBPS/toc.ncx", QByteArray(kNcx));
ok = ok && addEntry(zf, "OEBPS/chapter1.xhtml", QByteArray(kChapter1));
ok = ok && addEntry(zf, "OEBPS/chapter2.xhtml", QByteArray(kChapter2));
zipClose(zf, nullptr);
return ok ? path : QString{};
}
// Build an EPUB without an NCX.
static QString buildEpubNoNcx()
{
static const char opfNoNcx[] =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"2.0\">"
" <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">"
" <dc:title>No TOC Book</dc:title>"
" <dc:creator>Nobody</dc:creator>"
" </metadata>"
" <manifest>"
" <item id=\"ch1\" href=\"chapter1.xhtml\" media-type=\"application/xhtml+xml\"/>"
" </manifest>"
" <spine>"
" <itemref idref=\"ch1\"/>"
" </spine>"
"</package>";
QTemporaryFile tmp;
tmp.setFileTemplate(QDir::tempPath() + "/epub_notoc_XXXXXX.epub");
tmp.setAutoRemove(false);
if (!tmp.open()) return {};
const QString path = tmp.fileName();
tmp.close();
zipFile zf = zipOpen(path.toUtf8().constData(), APPEND_STATUS_CREATE);
if (!zf) return {};
bool ok = true;
ok = ok && addEntry(zf, "mimetype", QByteArray(kMimetype), true);
ok = ok && addEntry(zf, "META-INF/container.xml", QByteArray(kContainer));
ok = ok && addEntry(zf, "OEBPS/content.opf", QByteArray(opfNoNcx));
ok = ok && addEntry(zf, "OEBPS/chapter1.xhtml", QByteArray(kChapter1));
zipClose(zf, nullptr);
return ok ? path : QString{};
}
// Build an EPUB with one large chapter (>4096 chars of <p> elements).
static QString buildEpubLargeChapter()
{
QString body;
for (int i = 0; i < 60; ++i)
body += QString("<p>Paragraph %1: The quick brown fox jumped over the lazy dog repeatedly.</p>\n").arg(i + 1);
QByteArray chapterXhtml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<html xmlns=\"http://www.w3.org/1999/xhtml\">"
"<head><title>Big</title></head>"
"<body>" + body.toUtf8() + "</body>"
"</html>";
static const char opfLarge[] =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"2.0\">"
" <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">"
" <dc:title>Large</dc:title>"
" <dc:creator>Writer</dc:creator>"
" </metadata>"
" <manifest>"
" <item id=\"ch1\" href=\"chapter1.xhtml\" media-type=\"application/xhtml+xml\"/>"
" </manifest>"
" <spine>"
" <itemref idref=\"ch1\"/>"
" </spine>"
"</package>";
QTemporaryFile tmp;
tmp.setFileTemplate(QDir::tempPath() + "/epub_large_XXXXXX.epub");
tmp.setAutoRemove(false);
if (!tmp.open()) return {};
const QString path = tmp.fileName();
tmp.close();
zipFile zf = zipOpen(path.toUtf8().constData(), APPEND_STATUS_CREATE);
if (!zf) return {};
bool ok = true;
ok = ok && addEntry(zf, "mimetype", QByteArray(kMimetype), true);
ok = ok && addEntry(zf, "META-INF/container.xml", QByteArray(kContainer));
ok = ok && addEntry(zf, "OEBPS/content.opf", QByteArray(opfLarge));
ok = ok && addEntry(zf, "OEBPS/chapter1.xhtml", chapterXhtml);
zipClose(zf, nullptr);
return ok ? path : QString{};
}
// ---------------------------------------------------------------------------
// Test class
// ---------------------------------------------------------------------------
class EpubReaderTest : public QObject {
Q_OBJECT
private:
QString m_epubPath;
QString m_noNcxPath;
QString m_largePath;
private slots:
void initTestCase()
{
m_epubPath = buildSampleEpub();
m_noNcxPath = buildEpubNoNcx();
m_largePath = buildEpubLargeChapter();
QVERIFY2(!m_epubPath.isEmpty(), "Failed to build sample EPUB fixture");
QVERIFY2(!m_noNcxPath.isEmpty(), "Failed to build no-NCX EPUB fixture");
QVERIFY2(!m_largePath.isEmpty(), "Failed to build large chapter EPUB fixture");
}
void cleanupTestCase()
{
QFile::remove(m_epubPath);
QFile::remove(m_noNcxPath);
QFile::remove(m_largePath);
}
// --- Phase 2: error handling ---
void openNonexistentFile()
{
EpubReader reader;
QVERIFY(!reader.open("/tmp/does_not_exist_xyzzy.epub"));
QVERIFY(!reader.lastError().isEmpty());
}
void openInvalidZip()
{
QTemporaryFile tmp;
QVERIFY(tmp.open());
tmp.write("This is not a zip file.\n");
tmp.flush();
EpubReader reader;
QVERIFY(!reader.open(tmp.fileName()));
QVERIFY(!reader.lastError().isEmpty());
}
// --- Phase 3: metadata ---
void openValidEpub()
{
EpubReader reader;
QVERIFY(reader.open(m_epubPath));
}
void titleExtracted()
{
EpubReader reader;
QVERIFY(reader.open(m_epubPath));
QCOMPARE(reader.title(), QStringLiteral("Test Book"));
}
void authorExtracted()
{
EpubReader reader;
QVERIFY(reader.open(m_epubPath));
QCOMPARE(reader.author(), QStringLiteral("Test Author"));
}
// --- Phase 4: chapters ---
void chapterCountMatchesSpine()
{
EpubReader reader;
QVERIFY(reader.open(m_epubPath));
QCOMPARE(reader.chapterCount(), 2);
}
void loadChapterContent()
{
EpubReader reader;
QVERIFY(reader.open(m_epubPath));
Chapter ch = reader.loadChapter(0);
QCOMPARE(ch.index, 0);
QVERIFY(!ch.contentChunks.isEmpty());
const QString combined = ch.contentChunks.join('\n');
QVERIFY(combined.contains("First paragraph"));
}
void loadChapterTwo()
{
EpubReader reader;
QVERIFY(reader.open(m_epubPath));
Chapter ch = reader.loadChapter(1);
QCOMPARE(ch.index, 1);
QVERIFY(!ch.contentChunks.isEmpty());
const QString combined = ch.contentChunks.join('\n');
QVERIFY(combined.contains("chapter two"));
}
void loadChapterOutOfRange()
{
EpubReader reader;
QVERIFY(reader.open(m_epubPath));
Chapter ch = reader.loadChapter(99);
QVERIFY(ch.contentChunks.isEmpty());
}
// --- Phase 5: TOC ---
void tableOfContentsFromNcx()
{
EpubReader reader;
QVERIFY(reader.open(m_epubPath));
const QList<TocEntry> toc = reader.tableOfContents();
QCOMPARE(toc.size(), 2);
QCOMPARE(toc[0].title, QStringLiteral("Chapter One"));
QCOMPARE(toc[0].chapterIndex, 0);
QCOMPARE(toc[0].depth, 0);
QCOMPARE(toc[1].title, QStringLiteral("Chapter Two"));
QCOMPARE(toc[1].chapterIndex, 1);
}
void epubWithNoNcx()
{
EpubReader reader;
QVERIFY(reader.open(m_noNcxPath));
QVERIFY(reader.tableOfContents().isEmpty());
QCOMPARE(reader.chapterCount(), 1);
}
// --- Phase 6: chunking ---
void largeChapterProducesMultipleChunks()
{
EpubReader reader;
QVERIFY(reader.open(m_largePath));
const Chapter ch = reader.loadChapter(0);
QVERIFY(ch.contentChunks.size() > 1);
}
void chunksAreStandaloneHtml()
{
EpubReader reader;
QVERIFY(reader.open(m_largePath));
const Chapter ch = reader.loadChapter(0);
for (const QString &chunk : ch.contentChunks) {
const bool hasBlock = chunk.contains("<p") || chunk.contains("<h1") ||
chunk.contains("<h2") || chunk.contains("<div");
QVERIFY2(hasBlock, "Chunk lacks any block element");
}
}
};
QTEST_MAIN(EpubReaderTest)
#include "EpubReaderTest.moc"