diff --git a/CMakeLists.txt b/CMakeLists.txt index 97d509a..06331c6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -18,6 +18,7 @@ find_package(Qt6 REQUIRED COMPONENTS Svg QuickControls2 Test + Xml ) find_package(Qt6 OPTIONAL_COMPONENTS Pdf DBus) @@ -25,6 +26,7 @@ find_package(Qt6 OPTIONAL_COMPONENTS Pdf DBus) find_package(PkgConfig REQUIRED) pkg_check_modules(UCHARDET REQUIRED IMPORTED_TARGET uchardet) find_package(Iconv REQUIRED) +pkg_check_modules(MINIZIP REQUIRED IMPORTED_TARGET minizip) # Source files set(SOURCES @@ -40,6 +42,8 @@ set(SOURCES src/backend/BookController.cpp src/backend/formats/TxtReader.h 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 Iconv::Iconv) +target_link_libraries(asteria-qt PRIVATE PkgConfig::MINIZIP Qt6::Xml) # Set resource aliases so src/qml/* maps to qrc:/Asteria/* 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 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 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 src/backend/ReadingModel.cpp) @@ -166,11 +177,12 @@ add_asteria_test(BookControllerTest tests/BookControllerTest.cpp src/backend/BookController.cpp src/backend/ReaderFactory.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 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") if(Qt6DBus_FOUND) diff --git a/src/backend/ReaderFactory.cpp b/src/backend/ReaderFactory.cpp index 4fc8749..081fde8 100644 --- a/src/backend/ReaderFactory.cpp +++ b/src/backend/ReaderFactory.cpp @@ -1,6 +1,7 @@ #include "ReaderFactory.h" #include "FormatReader.h" #include "formats/TxtReader.h" +#include "formats/EpubReader.h" #include @@ -10,6 +11,8 @@ std::unique_ptr ReaderFactory::create(const QString &filePath) if (ext == QLatin1String("txt")) return std::make_unique(); + if (ext == QLatin1String("epub")) + return std::make_unique(); return nullptr; } diff --git a/src/backend/formats/EpubReader.cpp b/src/backend/formats/EpubReader.cpp new file mode 100644 index 0000000..bf3ef8c --- /dev/null +++ b/src/backend/formats/EpubReader.cpp @@ -0,0 +1,333 @@ +#include "EpubReader.h" + +#include +#include +#include +#include + +#include + +// --------------------------------------------------------------------------- +// 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 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 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 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 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("

") + text.toHtmlEscaped() + QStringLiteral("

\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 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])}; +} diff --git a/src/backend/formats/EpubReader.h b/src/backend/formats/EpubReader.h new file mode 100644 index 0000000..a41cb0e --- /dev/null +++ b/src/backend/formats/EpubReader.h @@ -0,0 +1,35 @@ +#ifndef EPUBREADER_H +#define EPUBREADER_H + +#include "backend/FormatReader.h" +#include +#include +#include +#include + +class EpubReader : public FormatReader { +public: + bool open(const QString &filePath) override; + QString lastError() override; + int chapterCount() override; + Chapter loadChapter(int index) override; + QList 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 m_spineRawContent; + QList 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 diff --git a/src/qml/components/Footer.qml b/src/qml/components/Footer.qml index c906a13..339a07a 100644 --- a/src/qml/components/Footer.qml +++ b/src/qml/components/Footer.qml @@ -1,4 +1,5 @@ import QtQuick +import QtQuick.Controls import Asteria Rectangle { @@ -12,9 +13,33 @@ Rectangle { anchors.top: parent.top } - Text { + // Prev chapter button + Button { + id: prevBtn 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 ? "Chapter " + (readingModel.currentChapter + 1) + " / " + readingModel.totalChapters : "" @@ -23,6 +48,29 @@ Rectangle { 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 { anchors.right: parent.right anchors.rightMargin: 16 diff --git a/src/qml/components/PageView.qml b/src/qml/components/PageView.qml index 57e40b8..5971be2 100644 --- a/src/qml/components/PageView.qml +++ b/src/qml/components/PageView.qml @@ -3,6 +3,11 @@ import QtQuick.Controls import Asteria Rectangle { + focus: true + + Keys.onLeftPressed: readingModel.previousChapter() + Keys.onRightPressed: readingModel.nextChapter() + gradient: Gradient { GradientStop { position: 0.0; color: Theme.gradientTop } GradientStop { position: 1.0; color: Theme.gradientBottom } diff --git a/src/qml/components/SideBar.qml b/src/qml/components/SideBar.qml index 8957e6d..cbe83f7 100644 --- a/src/qml/components/SideBar.qml +++ b/src/qml/components/SideBar.qml @@ -49,6 +49,7 @@ Rectangle { } Column { + id: navColumn y: Theme.headerHeight width: Theme.sidebarWidth @@ -96,4 +97,72 @@ Rectangle { 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() + } + } + } + } + } } diff --git a/src/qml/pages/ReaderPage.qml b/src/qml/pages/ReaderPage.qml index 9c14960..bb11147 100644 --- a/src/qml/pages/ReaderPage.qml +++ b/src/qml/pages/ReaderPage.qml @@ -3,4 +3,5 @@ import Asteria PageView { anchors.fill: parent + focus: visible } diff --git a/tests/formats/EpubReaderTest.cpp b/tests/formats/EpubReaderTest.cpp new file mode 100644 index 0000000..5be8892 --- /dev/null +++ b/tests/formats/EpubReaderTest.cpp @@ -0,0 +1,367 @@ +#include +#include +#include +#include + +#include + +#include "backend/formats/EpubReader.h" + +// --------------------------------------------------------------------------- +// Minimal EPUB fixture builder (uses minizip directly) +// --------------------------------------------------------------------------- + +static const char kMimetype[] = "application/epub+zip"; + +static const char kContainer[] = + "" + "" + " " + " " + " " + ""; + +static const char kOpf[] = + "" + "" + " " + " Test Book" + " Test Author" + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + ""; + +static const char kNcx[] = + "" + "" + " " + " " + " Chapter One" + " " + " " + " " + " Chapter Two" + " " + " " + " " + ""; + +static const char kChapter1[] = + "" + "" + "" + " Chapter One" + " " + "

Chapter One

" + "

First paragraph of chapter one.

" + "

Second paragraph of chapter one.

" + " " + ""; + +static const char kChapter2[] = + "" + "" + " Chapter Two" + " " + "

This is chapter two content.

" + " " + ""; + +// 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[] = + "" + "" + " " + " No TOC Book" + " Nobody" + " " + " " + " " + " " + " " + " " + " " + ""; + + 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

elements). +static QString buildEpubLargeChapter() +{ + QString body; + for (int i = 0; i < 60; ++i) + body += QString("

Paragraph %1: The quick brown fox jumped over the lazy dog repeatedly.

\n").arg(i + 1); + + QByteArray chapterXhtml = + "" + "" + "Big" + "" + body.toUtf8() + "" + ""; + + static const char opfLarge[] = + "" + "" + " " + " Large" + " Writer" + " " + " " + " " + " " + " " + " " + " " + ""; + + 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 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("