diff --git a/CMakeLists.txt b/CMakeLists.txt index 766bfec..138e00c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -71,6 +71,10 @@ set(SOURCES src/backend/formats/EpubReader.cpp src/backend/formats/EpubImageProvider.h src/backend/formats/EpubImageProvider.cpp + src/backend/formats/Fb2Reader.h + src/backend/formats/Fb2Reader.cpp + src/backend/formats/Fb2ImageProvider.h + src/backend/formats/Fb2ImageProvider.cpp src/backend/formats/WebImageProvider.h src/backend/formats/WebImageProvider.cpp src/backend/formats/ImageProviderFactory.h @@ -232,10 +236,15 @@ 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(Fb2ReaderTest tests/formats/Fb2ReaderTest.cpp + src/backend/formats/Fb2Reader.cpp) +target_link_libraries(Fb2ReaderTest PRIVATE Qt6::Xml) + add_asteria_test(ReaderFactoryTest tests/ReaderFactoryTest.cpp src/backend/formats/ReaderFactory.cpp src/backend/formats/TxtReader.cpp - src/backend/formats/EpubReader.cpp) + src/backend/formats/EpubReader.cpp + src/backend/formats/Fb2Reader.cpp) target_link_libraries(ReaderFactoryTest PRIVATE PkgConfig::MINIZIP Qt6::Xml) add_asteria_test(ChunkMeasurerTest tests/ChunkMeasurerTest.cpp @@ -249,6 +258,7 @@ add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp src/backend/ReadingModel.cpp src/backend/ChunkMeasurer.cpp src/backend/formats/EpubImageProvider.cpp + src/backend/formats/Fb2ImageProvider.cpp src/backend/formats/WebImageProvider.cpp src/backend/formats/ImageProviderFactory.cpp src/backend/AppState.cpp @@ -257,7 +267,8 @@ add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp src/backend/HistoryModel.cpp src/backend/formats/ReaderFactory.cpp src/backend/formats/TxtReader.cpp - src/backend/formats/EpubReader.cpp) + src/backend/formats/EpubReader.cpp + src/backend/formats/Fb2Reader.cpp) target_link_libraries(ReadingModelTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick Qt6::Network PkgConfig::MINIZIP Qt6::Xml) set_tests_properties(ReadingModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") @@ -286,7 +297,8 @@ add_asteria_test(BookTest tests/book/BookTest.cpp src/backend/IFileDialogService.cpp src/backend/NativeFileDialogService.cpp src/backend/formats/TxtReader.cpp - src/backend/formats/EpubReader.cpp) + src/backend/formats/EpubReader.cpp + src/backend/formats/Fb2Reader.cpp) target_link_libraries(BookTest PRIVATE Qt6::Concurrent Qt6::Widgets PkgConfig::MINIZIP Qt6::Xml) set_tests_properties(BookTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") @@ -298,10 +310,12 @@ set_tests_properties(EpubImageProviderTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFO add_asteria_test(HistoryBookModelTest tests/HistoryBookModelTest.cpp src/backend/HistoryBookModel.cpp src/backend/formats/EpubImageProvider.cpp + src/backend/formats/Fb2ImageProvider.cpp src/backend/formats/ImageProviderFactory.cpp src/backend/formats/ReaderFactory.cpp src/backend/formats/TxtReader.cpp - src/backend/formats/EpubReader.cpp) + src/backend/formats/EpubReader.cpp + src/backend/formats/Fb2Reader.cpp) target_link_libraries(HistoryBookModelTest PRIVATE Qt6::Concurrent Qt6::Quick Qt6::Gui Qt6::Xml PkgConfig::MINIZIP) set_tests_properties(HistoryBookModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") diff --git a/src/backend/formats/Fb2ImageProvider.cpp b/src/backend/formats/Fb2ImageProvider.cpp new file mode 100644 index 0000000..66e5e91 --- /dev/null +++ b/src/backend/formats/Fb2ImageProvider.cpp @@ -0,0 +1,204 @@ +#include "Fb2ImageProvider.h" + +#include +#include +#include +#include +#include +#include +#include + +// --------------------------------------------------------------------------- +// Fb2ImageResponse +// --------------------------------------------------------------------------- + +Fb2ImageResponse::Fb2ImageResponse(const QString &fb2Path, const QString &id, + int displayWidth, const QSize &requestedSize) + : m_fb2Path(fb2Path) + , m_id(id) + , m_displayWidth(displayWidth) + , m_requestedSize(requestedSize) +{ + setAutoDelete(false); +} + +QQuickTextureFactory *Fb2ImageResponse::textureFactory() const +{ + if (m_image.isNull()) + return nullptr; + return QQuickTextureFactory::textureFactoryForImage(m_image); +} + +void Fb2ImageResponse::cancel() +{ + m_cancelled.storeRelaxed(1); +} + +void Fb2ImageResponse::run() +{ + if (m_cancelled.loadRelaxed()) + return; + + m_image = Fb2ImageProvider::loadImageFromFb2(m_fb2Path, m_id, m_displayWidth, m_requestedSize); + + if (m_cancelled.loadRelaxed()) + return; + + emit finished(); +} + +// --------------------------------------------------------------------------- +// Fb2ImageProvider +// --------------------------------------------------------------------------- + +QImage Fb2ImageProvider::loadImageFromFb2(const QString &fb2Path, const QString &id, + int displayWidth, const QSize &requestedSize) +{ + if (fb2Path.isEmpty() || id.isEmpty()) + return {}; + + QFile f(fb2Path); + if (!f.open(QIODevice::ReadOnly)) + return {}; + + QXmlStreamReader xml(&f); + while (!xml.atEnd()) { + xml.readNext(); + if (!xml.isStartElement() || xml.name() != QLatin1String("binary")) + continue; + if (xml.attributes().value(QLatin1String("id")) != id) + continue; + + // Accumulate text (base64 data may span multiple character events) + QString base64; + while (!xml.atEnd()) { + xml.readNext(); + if (xml.isCharacters()) + base64 += xml.text(); + else + break; + } + + const QByteArray data = QByteArray::fromBase64(base64.toLatin1()); + QImage image; + if (!image.loadFromData(data)) + return {}; + + if (requestedSize.width() > 0 || requestedSize.height() > 0) { + int targetW = requestedSize.width() > 0 ? requestedSize.width() : -1; + int targetH = requestedSize.height() > 0 ? requestedSize.height() : -1; + if (displayWidth > 0 && targetW > 0 && targetW > displayWidth) + targetW = displayWidth; + if (targetW > 0 && targetH > 0) + image = image.scaled(QSize(targetW, targetH), Qt::KeepAspectRatio, Qt::SmoothTransformation); + else if (targetW > 0) + image = image.scaledToWidth(targetW, Qt::SmoothTransformation); + else + image = image.scaledToHeight(targetH, Qt::SmoothTransformation); + } else if (displayWidth > 0 && image.width() > displayWidth) { + image = image.scaledToWidth(displayWidth, Qt::SmoothTransformation); + } + + return image; + } + + return {}; +} + +QQuickImageResponse *Fb2ImageProvider::requestImageResponse(const QString &id, + const QSize &requestedSize) +{ + QString fb2Path; + int displayWidth; + { + QMutexLocker lock(&m_mutex); + fb2Path = m_fb2Path; + displayWidth = m_displayWidth; + } + + // id may have "?fb2=" appended + QString binaryId = id; + const int qmark = id.indexOf(QLatin1Char('?')); + if (qmark >= 0) { + binaryId = id.left(qmark); + const QString query = id.mid(qmark + 1); + const QLatin1String key("fb2="); + if (query.startsWith(key)) + fb2Path = QUrl::fromPercentEncoding(query.mid(key.size()).toUtf8()); + } + + auto *response = new Fb2ImageResponse(fb2Path, binaryId, displayWidth, requestedSize); + QThreadPool::globalInstance()->start(response); + return response; +} + +QImage Fb2ImageProvider::load(const QUrl &url, int maxWidth) const +{ + if (url.scheme() != QLatin1String("image")) + return {}; + + QString binaryId = url.path(); + if (binaryId.startsWith(QLatin1Char('/'))) + binaryId = binaryId.mid(1); + if (binaryId.isEmpty()) + return {}; + + QString fb2Path; + if (url.hasQuery()) { + const QString q = url.query(); + const QLatin1String key("fb2="); + if (q.startsWith(key)) + fb2Path = QUrl::fromPercentEncoding(q.mid(key.size()).toUtf8()); + } + if (fb2Path.isEmpty()) { + QMutexLocker lock(&m_mutex); + fb2Path = m_fb2Path; + } + + return loadImageFromFb2(fb2Path, binaryId, maxWidth, {}); +} + +std::unique_ptr Fb2ImageProvider::clone() const +{ + QString fb2Path; + { + QMutexLocker lock(&m_mutex); + fb2Path = m_fb2Path; + } + auto c = std::make_unique(); + c->setFilePath(fb2Path); + return c; +} + +void Fb2ImageProvider::setFilePath(const QString &filePath) +{ + QMutexLocker lock(&m_mutex); + m_fb2Path = filePath; +} + +QString Fb2ImageProvider::coverImageUrl(const QString &coverPath) const +{ + QString fb2Path; + { QMutexLocker lock(&m_mutex); fb2Path = m_fb2Path; } + return QStringLiteral("image://fb2/") + coverPath + + QStringLiteral("?fb2=") + + QString::fromUtf8(QUrl::toPercentEncoding(fb2Path)); +} + +QString Fb2ImageProvider::scheme() const +{ + return QStringLiteral("fb2"); +} + +void Fb2ImageProvider::setDisplayWidth(int width) +{ + QMutexLocker lock(&m_mutex); + m_displayWidth = width; +} + +void Fb2ImageProvider::clear() +{ + QMutexLocker lock(&m_mutex); + m_fb2Path.clear(); + m_displayWidth = 0; +} diff --git a/src/backend/formats/Fb2ImageProvider.h b/src/backend/formats/Fb2ImageProvider.h new file mode 100644 index 0000000..1a84445 --- /dev/null +++ b/src/backend/formats/Fb2ImageProvider.h @@ -0,0 +1,50 @@ +#pragma once + +#include +#include +#include + +#include "backend/IImageLoader.h" +#include "backend/IImageProvider.h" + +class Fb2ImageResponse : public QQuickImageResponse, public QRunnable { + // NO Q_OBJECT — already inherited from QQuickImageResponse +public: + Fb2ImageResponse(const QString &fb2Path, const QString &id, + int displayWidth, const QSize &requestedSize); + + QQuickTextureFactory *textureFactory() const override; + void cancel() override; + void run() override; + +private: + const QString m_fb2Path; + const QString m_id; + const int m_displayWidth; + const QSize m_requestedSize; + QAtomicInt m_cancelled{0}; + QImage m_image; +}; + +class Fb2ImageProvider : public IImageProvider, public IImageLoader { +public: + QQuickImageResponse *requestImageResponse(const QString &id, + const QSize &requestedSize) override; + + void setFilePath(const QString &filePath) override; + void setDisplayWidth(int width) override; + void clear() override; + QString coverImageUrl(const QString &coverPath) const override; + QString scheme() const override; + + QImage load(const QUrl &url, int maxWidth) const override; + std::unique_ptr clone() const override; + + static QImage loadImageFromFb2(const QString &fb2Path, const QString &id, + int displayWidth, const QSize &requestedSize); + +private: + mutable QMutex m_mutex; + QString m_fb2Path; + int m_displayWidth = 0; +}; diff --git a/src/backend/formats/Fb2Reader.cpp b/src/backend/formats/Fb2Reader.cpp new file mode 100644 index 0000000..4595ff9 --- /dev/null +++ b/src/backend/formats/Fb2Reader.cpp @@ -0,0 +1,355 @@ +#include "Fb2Reader.h" + +#include +#include +#include +#include +#include + +#include +#include +#include + +static constexpr int kChunkSize = 4096; + +static QString decodeWithIconv(const QByteArray &raw, const char *charset) +{ + iconv_t cd = iconv_open("UTF-8", charset); + if (cd == reinterpret_cast(-1)) + return {}; + QByteArray out(raw.size() * 4, '\0'); + char *inBuf = const_cast(raw.constData()); + size_t inLeft = raw.size(); + char *outBuf = out.data(); + size_t outLeft = out.size(); + const size_t r = iconv(cd, &inBuf, &inLeft, &outBuf, &outLeft); + iconv_close(cd); + if (r == static_cast(-1)) + return {}; + out.resize(out.size() - outLeft); + return QString::fromUtf8(out); +} + +// Decode FB2 bytes to a Unicode string. +// Uses the XML encoding declaration as the authoritative charset source +// (uchardet is unreliable on files with large binary sections or sparse text). +// QStringConverter / iconv handle the actual conversion. +static QString decodeRawBytes(const QByteArray &raw) +{ + // Extract encoding name from XML declaration (first ~200 bytes) + QByteArray enc; + const int pos = raw.indexOf("encoding="); + if (pos >= 0 && pos < 200) { + const int qs = pos + 9; + if (qs < raw.size()) { + const char q = raw[qs]; + if (q == '"' || q == '\'') { + const int qe = raw.indexOf(q, qs + 1); + if (qe > qs) + enc = raw.mid(qs + 1, qe - qs - 1).toLower(); + } + } + } + + if (enc.isEmpty() || enc == "utf-8" || enc == "utf8") + return QString::fromUtf8(raw); + + // Try Qt's built-in converters first, fall back to iconv for exotic charsets + auto qtEncoding = QStringConverter::encodingForName(enc.constData()); + if (qtEncoding) { + QTextStream stream(raw); + stream.setEncoding(qtEncoding.value()); + const QString decoded = stream.readAll(); + if (!decoded.isEmpty()) + return decoded; + } + + const QString decoded = decodeWithIconv(raw, enc.constData()); + if (!decoded.isEmpty()) + return decoded; + + // Last resort: uchardet-based detection + uchardet_t ud = uchardet_new(); + if (uchardet_handle_data(ud, raw.constData(), raw.size()) == 0) { + uchardet_data_end(ud); + const char *charset = uchardet_get_charset(ud); + if (charset && charset[0] != '\0') { + const QString s = decodeWithIconv(raw, charset); + uchardet_delete(ud); + if (!s.isEmpty()) + return s; + } + } + uchardet_delete(ud); + return QString::fromUtf8(raw); +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +static QDomElement firstChildByTag(const QDomElement &parent, const QString &tag) +{ + for (QDomNode n = parent.firstChild(); !n.isNull(); n = n.nextSibling()) { + QDomElement el = n.toElement(); + if (!el.isNull() && el.tagName() == tag) + return el; + } + return {}; +} + +// Converts a single FB2 DOM node to an HTML string. Handles inline and block elements. +static QString nodeToHtml(const QDomNode &node) +{ + if (node.isText()) + return node.nodeValue().toHtmlEscaped(); + + if (!node.isElement()) + return {}; + + const QDomElement el = node.toElement(); + const QString tag = el.tagName(); + + // Build inner HTML from children + QString inner; + for (QDomNode child = el.firstChild(); !child.isNull(); child = child.nextSibling()) + inner += nodeToHtml(child); + + if (tag == QLatin1String("p") || tag == QLatin1String("v")) { + if (inner.trimmed().isEmpty()) + return {}; + return QStringLiteral("

") + inner + QStringLiteral("

\n"); + } + if (tag == QLatin1String("title")) + return inner.trimmed().isEmpty() ? QString{} : QStringLiteral("

") + inner + QStringLiteral("

\n"); + if (tag == QLatin1String("subtitle")) + return inner.trimmed().isEmpty() ? QString{} : QStringLiteral("

") + inner + QStringLiteral("

\n"); + if (tag == QLatin1String("emphasis")) + return QStringLiteral("") + inner + QStringLiteral(""); + if (tag == QLatin1String("strong")) + return QStringLiteral("") + inner + QStringLiteral(""); + if (tag == QLatin1String("epigraph") || tag == QLatin1String("poem") || tag == QLatin1String("cite")) + return inner.trimmed().isEmpty() ? QString{} : QStringLiteral("
") + inner + QStringLiteral("
\n"); + if (tag == QLatin1String("section") || tag == QLatin1String("stanza")) + return inner; + if (tag == QLatin1String("image")) { + QString href = el.attribute(QStringLiteral("l:href")); + if (href.startsWith(QLatin1Char('#'))) + href = href.mid(1); + if (!href.isEmpty()) + return QStringLiteral("\n"); + return {}; + } + if (tag == QLatin1String("a")) { + const QString href = el.attribute(QStringLiteral("l:href")); + if (!href.isEmpty() && !href.startsWith(QLatin1Char('#'))) + return QStringLiteral("") + inner + QStringLiteral(""); + return inner; + } + return inner; +} + +// --------------------------------------------------------------------------- +// Metadata parsing +// --------------------------------------------------------------------------- + +struct Fb2Metadata { + QString title, author, coverBinaryId; +}; + +static Fb2Metadata parseDescription(const QDomElement &desc) +{ + Fb2Metadata meta; + const QDomElement titleInfo = firstChildByTag(desc, QStringLiteral("title-info")); + if (titleInfo.isNull()) + return meta; + + const QDomElement bookTitle = firstChildByTag(titleInfo, QStringLiteral("book-title")); + if (!bookTitle.isNull()) + meta.title = bookTitle.text().simplified(); + + const QDomElement author = firstChildByTag(titleInfo, QStringLiteral("author")); + if (!author.isNull()) { + const QString first = firstChildByTag(author, QStringLiteral("first-name")).text().simplified(); + const QString last = firstChildByTag(author, QStringLiteral("last-name")).text().simplified(); + if (!first.isEmpty() && !last.isEmpty()) + meta.author = first + QLatin1Char(' ') + last; + else + meta.author = first + last; + } + + const QDomElement coverpage = firstChildByTag(titleInfo, QStringLiteral("coverpage")); + if (!coverpage.isNull()) { + const QDomElement img = firstChildByTag(coverpage, QStringLiteral("image")); + if (!img.isNull()) { + QString href = img.attribute(QStringLiteral("l:href")); + if (href.startsWith(QLatin1Char('#'))) + href = href.mid(1); + meta.coverBinaryId = href; + } + } + + return meta; +} + +// --------------------------------------------------------------------------- +// FormatReader interface +// --------------------------------------------------------------------------- + +bool Fb2Reader::open(const QString &filePath) +{ + m_title.clear(); + m_author.clear(); + m_error.clear(); + m_coverBinaryId.clear(); + m_chapterHtmlNodes.clear(); + m_chapterTitles.clear(); + m_toc.clear(); + m_contentHash.clear(); + + std::ifstream f(filePath.toUtf8().constData(), std::ios::binary | std::ios::ate); + if (!f) { + m_error = QStringLiteral("Cannot open file: ") + filePath; + return false; + } + const auto size = f.tellg(); + f.seekg(0); + QByteArray raw(static_cast(size), '\0'); + f.read(raw.data(), size); + + m_contentHash = QCryptographicHash::hash(raw, QCryptographicHash::Md5); + + QDomDocument doc; + const auto result = doc.setContent(decodeRawBytes(raw), QDomDocument::ParseOption::Default); + if (!result) { + m_error = QStringLiteral("Failed to parse FB2 XML: ") + result.errorMessage; + return false; + } + + const QDomElement root = doc.documentElement(); + + // Metadata + const QDomElement desc = firstChildByTag(root, QStringLiteral("description")); + if (!desc.isNull()) { + const Fb2Metadata meta = parseDescription(desc); + m_title = meta.title; + m_author = meta.author; + m_coverBinaryId = meta.coverBinaryId; + } + + if (m_title.isEmpty()) + m_title = QFileInfo(filePath).completeBaseName(); + + // Body sections + for (QDomNode bodyNode = root.firstChild(); !bodyNode.isNull(); bodyNode = bodyNode.nextSibling()) { + const QDomElement body = bodyNode.toElement(); + if (body.isNull() || body.tagName() != QLatin1String("body")) + continue; + // Skip named bodies (e.g. notes) + if (!body.attribute(QStringLiteral("name")).isEmpty()) + continue; + + for (QDomNode secNode = body.firstChild(); !secNode.isNull(); secNode = secNode.nextSibling()) { + const QDomElement section = secNode.toElement(); + if (section.isNull() || section.tagName() != QLatin1String("section")) + continue; + + // Extract section title + const QDomElement titleEl = firstChildByTag(section, QStringLiteral("title")); + QString sectionTitle = titleEl.isNull() ? QString{} : titleEl.text().simplified(); + if (sectionTitle.isEmpty()) + sectionTitle = QStringLiteral("Chapter %1").arg(m_chapterHtmlNodes.size() + 1); + m_chapterTitles.append(sectionTitle); + + // Convert section children to HTML node list + QStringList htmlNodes; + for (QDomNode child = section.firstChild(); !child.isNull(); child = child.nextSibling()) { + const QString html = nodeToHtml(child); + if (!html.isEmpty()) + htmlNodes.append(html); + } + m_chapterHtmlNodes.append(htmlNodes); + + TocEntry entry; + entry.title = sectionTitle; + entry.chapterIndex = m_chapterHtmlNodes.size() - 1; + entry.depth = 0; + m_toc.append(entry); + } + break; // only process first unnamed body + } + + m_filePath = filePath; + return true; +} + +bool Fb2Reader::loadMetadata(const QString &filePath) +{ + m_title.clear(); + m_author.clear(); + m_error.clear(); + m_coverBinaryId.clear(); + + std::ifstream f(filePath.toUtf8().constData(), std::ios::binary | std::ios::ate); + if (!f) { + m_error = QStringLiteral("Cannot open file: ") + filePath; + return false; + } + const auto size = f.tellg(); + f.seekg(0); + QByteArray raw(static_cast(size), '\0'); + f.read(raw.data(), size); + + QDomDocument doc; + const auto result = doc.setContent(decodeRawBytes(raw), QDomDocument::ParseOption::Default); + if (!result) { + m_error = QStringLiteral("Failed to parse FB2 XML: ") + result.errorMessage; + return false; + } + + const QDomElement root = doc.documentElement(); + const QDomElement desc = firstChildByTag(root, QStringLiteral("description")); + if (!desc.isNull()) { + const Fb2Metadata meta = parseDescription(desc); + m_title = meta.title; + m_author = meta.author; + m_coverBinaryId = meta.coverBinaryId; + } + + if (m_title.isEmpty()) + m_title = QFileInfo(filePath).completeBaseName(); + + return true; +} + +QString Fb2Reader::lastError() { return m_error; } +QString Fb2Reader::title() { return m_title; } +QString Fb2Reader::author() { return m_author; } +QString Fb2Reader::coverImagePath() { return m_coverBinaryId; } +int Fb2Reader::chapterCount() { return m_chapterHtmlNodes.size(); } +QList Fb2Reader::tableOfContents() { return m_toc; } +QString Fb2Reader::filePath() { return m_filePath; } +QByteArray Fb2Reader::contentHash() { return m_contentHash; } +QString Fb2Reader::fileType() const { return QStringLiteral("fb2"); } + +Chapter Fb2Reader::loadChapter(int index) +{ + if (index < 0 || index >= m_chapterHtmlNodes.size()) + return Chapter{index, {}, {}}; + + const QStringList &nodes = m_chapterHtmlNodes[index]; + QStringList chunks; + QString current; + + for (const QString &node : nodes) { + if (!current.isEmpty() && current.size() + node.size() > kChunkSize) { + chunks.append(current); + current.clear(); + } + current += node; + } + if (!current.isEmpty()) + chunks.append(current); + + return Chapter{index, m_chapterTitles[index], chunks}; +} diff --git a/src/backend/formats/Fb2Reader.h b/src/backend/formats/Fb2Reader.h new file mode 100644 index 0000000..6351f01 --- /dev/null +++ b/src/backend/formats/Fb2Reader.h @@ -0,0 +1,35 @@ +#ifndef FB2READER_H +#define FB2READER_H + +#include "backend/FormatReader.h" +#include +#include + +class Fb2Reader : public FormatReader { +public: + bool open(const QString &filePath) override; + bool loadMetadata(const QString &filePath) override; + QString lastError() override; + int chapterCount() override; + Chapter loadChapter(int index) override; + QList tableOfContents() override; + QString filePath() override; + QString title() override; + QString author() override; + QString coverImagePath() override; + QByteArray contentHash() override; + QString fileType() const override; + +private: + QString m_filePath; + QByteArray m_contentHash; + QString m_title; + QString m_author; + QString m_error; + QString m_coverBinaryId; + QList m_chapterHtmlNodes; + QStringList m_chapterTitles; + QList m_toc; +}; + +#endif // FB2READER_H diff --git a/src/backend/formats/ImageLoaderFactory.cpp b/src/backend/formats/ImageLoaderFactory.cpp index 5f96286..8546352 100644 --- a/src/backend/formats/ImageLoaderFactory.cpp +++ b/src/backend/formats/ImageLoaderFactory.cpp @@ -1,5 +1,6 @@ #include "ImageLoaderFactory.h" #include "EpubImageProvider.h" +#include "Fb2ImageProvider.h" #include "WebImageProvider.h" #include @@ -47,5 +48,10 @@ std::unique_ptr ImageLoaderFactory::create(const QString &filePath return composite; } + if (ext == QLatin1String("fb2")) { + auto loader = std::make_unique(); + loader->setFilePath(filePath); + return loader; + } return nullptr; } diff --git a/src/backend/formats/ImageProviderFactory.cpp b/src/backend/formats/ImageProviderFactory.cpp index f69a15d..f41101e 100644 --- a/src/backend/formats/ImageProviderFactory.cpp +++ b/src/backend/formats/ImageProviderFactory.cpp @@ -1,5 +1,6 @@ #include "ImageProviderFactory.h" #include "EpubImageProvider.h" +#include "Fb2ImageProvider.h" #include IImageProvider *ImageProviderFactory::create(const QString &filePath) @@ -7,5 +8,7 @@ IImageProvider *ImageProviderFactory::create(const QString &filePath) const QString ext = QFileInfo(filePath).suffix().toLower(); if (ext == QLatin1String("epub")) return new EpubImageProvider(); + if (ext == QLatin1String("fb2")) + return new Fb2ImageProvider(); return nullptr; } diff --git a/src/main.cpp b/src/main.cpp index 4f18cb1..a67f9b4 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -23,6 +23,8 @@ #include "backend/book/Book.h" #include "backend/formats/TxtReader.h" #include "backend/formats/EpubReader.h" +#include "backend/formats/Fb2Reader.h" +#include "backend/formats/Fb2ImageProvider.h" #include "backend/state/BookPositionStore.h" #include "backend/state/ReadingPreferences.h" #include "backend/state/UiState.h" @@ -103,6 +105,7 @@ int main(int argc, char *argv[]) ReaderFactory readerFactory({ [] { return std::make_unique(); }, [] { return std::make_unique(); }, + [] { return std::make_unique(); }, }); HistoryModel historyModel(readerFactory); @@ -140,6 +143,7 @@ int main(int argc, char *argv[]) QQmlApplicationEngine engine; engine.addImageProvider(QStringLiteral("web"), new WebImageProvider()); engine.addImageProvider(QStringLiteral("epub"), new EpubImageProvider()); + engine.addImageProvider(QStringLiteral("fb2"), new Fb2ImageProvider()); engine.addImageProvider(QStringLiteral("fileicon"), new FileIconProvider()); engine.rootContext()->setContextProperty(QStringLiteral("isDebugBuild"), #ifdef QT_DEBUG diff --git a/tests/formats/Fb2ReaderTest.cpp b/tests/formats/Fb2ReaderTest.cpp new file mode 100644 index 0000000..7f7538a --- /dev/null +++ b/tests/formats/Fb2ReaderTest.cpp @@ -0,0 +1,384 @@ +#include +#include +#include +#include + +#include "backend/formats/Fb2Reader.h" + +// --------------------------------------------------------------------------- +// Minimal FB2 fixture builder +// --------------------------------------------------------------------------- + +static const char kFb2Header[] = + "" + ""; + +static const char kFb2Footer[] = ""; + +static QString writeTempFb2(const QByteArray &content) +{ + QTemporaryFile tmp; + tmp.setFileTemplate(QDir::tempPath() + "/fb2_test_XXXXXX.fb2"); + tmp.setAutoRemove(false); + if (!tmp.open()) return {}; + tmp.write(content); + tmp.flush(); + return tmp.fileName(); +} + +static QString buildSampleFb2() +{ + QByteArray xml = kFb2Header; + xml += + "" + " " + " Test Book" + " " + " Test" + " Author" + " " + " " + "" + "" + "
" + " <p>Chapter One</p>" + "

First paragraph of chapter one.

" + "

Second paragraph of chapter one.

" + "
" + "
" + " <p>Chapter Two</p>" + "

This is chapter two content.

" + "
" + ""; + xml += kFb2Footer; + return writeTempFb2(xml); +} + +static QString buildFb2WithCover() +{ + QByteArray xml = kFb2Header; + xml += + "" + " " + " Cover Book" + " " + " Cover" + " Tester" + " " + " " + " " + " " + " " + "" + "" + "
" + " <p>Only Chapter</p>" + "

Some content.

" + "
" + "" + "AAAA"; + xml += kFb2Footer; + return writeTempFb2(xml); +} + +static QString buildLargeFb2() +{ + QByteArray xml = kFb2Header; + xml += + "" + " " + " Large Book" + " " + "" + "" + "
" + " <p>Big Chapter</p>"; + for (int i = 0; i < 60; ++i) { + xml += QString("

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

") + .arg(i + 1).toUtf8(); + } + xml += "
"; + xml += kFb2Footer; + return writeTempFb2(xml); +} + +static QString buildFb2Windows1251() +{ + // Minimal FB2 with windows-1251 encoding declaration and Cyrillic content. + // The bytes below are the windows-1251 encoding of "Тестовая книга" (Test book) + // and "Иван Иванов" (Ivan Ivanov), hand-encoded. + // + // We build the ASCII-safe portions as normal strings, embed raw Cyrillic bytes, + // and declare encoding="windows-1251" so the reader must transcode it. + QByteArray xml = + "" + "" + "" + ""; + // "Книга" in windows-1251: К=CA, н=ED, и=E8, г=E3, а=E0 + xml += QByteArray("\xCA\xED\xE8\xE3\xE0"); + xml += + "" + "" + "
" + "<p>Глава</p>" + "

"; + // "Привет" in windows-1251: П=CF, р=F0, и=E8, в=E2, е=E5, т=F2 + xml += QByteArray("\xCF\xF0\xE8\xE2\xE5\xF2"); + xml += "

"; + return writeTempFb2(xml); +} + +static QString buildFb2WithImage() +{ + QByteArray xml = kFb2Header; + xml += + "" + " " + " Image Book" + " " + "" + "" + "
" + " <p>Chapter With Image</p>" + "

Text before image.

" + " " + "

Text after image.

" + "
" + "" + "AAAA"; + xml += kFb2Footer; + return writeTempFb2(xml); +} + +// --------------------------------------------------------------------------- +// Test class +// --------------------------------------------------------------------------- + +class Fb2ReaderTest : public QObject { + Q_OBJECT + +private: + QString m_samplePath; + QString m_coverPath; + QString m_largePath; + QString m_imagePath; + QString m_cp1251Path; + +private slots: + void initTestCase() + { + m_samplePath = buildSampleFb2(); + m_coverPath = buildFb2WithCover(); + m_largePath = buildLargeFb2(); + m_imagePath = buildFb2WithImage(); + m_cp1251Path = buildFb2Windows1251(); + QVERIFY2(!m_samplePath.isEmpty(), "Failed to build sample FB2"); + QVERIFY2(!m_coverPath.isEmpty(), "Failed to build cover FB2"); + QVERIFY2(!m_largePath.isEmpty(), "Failed to build large FB2"); + QVERIFY2(!m_imagePath.isEmpty(), "Failed to build image FB2"); + QVERIFY2(!m_cp1251Path.isEmpty(), "Failed to build windows-1251 FB2"); + } + + void cleanupTestCase() + { + QFile::remove(m_samplePath); + QFile::remove(m_coverPath); + QFile::remove(m_largePath); + QFile::remove(m_imagePath); + QFile::remove(m_cp1251Path); + } + + // --- Error handling --- + + void openNonexistentFile() + { + Fb2Reader reader; + QVERIFY(!reader.open(QStringLiteral("/tmp/does_not_exist_xyzzy.fb2"))); + QVERIFY(!reader.lastError().isEmpty()); + } + + void openInvalidXml() + { + const QString path = writeTempFb2(" 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); + } + + // --- Chunking --- + + void largeChapterProducesMultipleChunks() + { + Fb2Reader reader; + QVERIFY(reader.open(m_largePath)); + const Chapter ch = reader.loadChapter(0); + QVERIFY(ch.contentChunks.size() > 1); + } + + // --- Cover image --- + + void coverImagePathExtracted() + { + Fb2Reader reader; + QVERIFY(reader.open(m_coverPath)); + QCOMPARE(reader.coverImagePath(), QStringLiteral("cover_img")); + } + + void coverImagePathEmptyWhenNoCover() + { + Fb2Reader reader; + QVERIFY(reader.open(m_samplePath)); + QVERIFY(reader.coverImagePath().isEmpty()); + } + + // --- Image tag rewriting --- + + void imageTagsRewrittenToProviderUrls() + { + Fb2Reader reader; + QVERIFY(reader.open(m_imagePath)); + const Chapter ch = reader.loadChapter(0); + QVERIFY(!ch.contentChunks.isEmpty()); + const QString combined = ch.contentChunks.join('\n'); + QVERIFY2(combined.contains(QStringLiteral("image://fb2/inline_img")), + qPrintable(QStringLiteral("Expected image://fb2/inline_img in: ") + combined)); + } + + // --- loadMetadata --- + + void loadMetadataOnlyParsesDescription() + { + Fb2Reader reader; + QVERIFY(reader.loadMetadata(m_samplePath)); + QCOMPARE(reader.title(), QStringLiteral("Test Book")); + QCOMPARE(reader.author(), QStringLiteral("Test Author")); + QCOMPARE(reader.chapterCount(), 0); // chapters not parsed + } + + // --- Content hash --- + + void contentHashNonEmptyAfterOpen() + { + Fb2Reader reader; + QVERIFY(reader.open(m_samplePath)); + QVERIFY(!reader.contentHash().isEmpty()); + } + + void contentHashEmptyAfterLoadMetadataOnly() + { + Fb2Reader reader; + QVERIFY(reader.loadMetadata(m_samplePath)); + QVERIFY(reader.contentHash().isEmpty()); + } + + // --- Encoding --- + + void windows1251FileOpensSuccessfully() + { + Fb2Reader reader; + QVERIFY2(reader.open(m_cp1251Path), + qPrintable(QStringLiteral("open() failed: ") + reader.lastError())); + } + + void windows1251TitleDecodedCorrectly() + { + Fb2Reader reader; + QVERIFY(reader.open(m_cp1251Path)); + // "Книга" in Unicode + QCOMPARE(reader.title(), QStringLiteral("\u041A\u043D\u0438\u0433\u0430")); + } + + void windows1251ContentDecodedCorrectly() + { + Fb2Reader reader; + QVERIFY(reader.open(m_cp1251Path)); + QCOMPARE(reader.chapterCount(), 1); + const Chapter ch = reader.loadChapter(0); + const QString combined = ch.contentChunks.join('\n'); + // "Привет" in Unicode + QVERIFY(combined.contains(QStringLiteral("\u041F\u0440\u0438\u0432\u0435\u0442"))); + } +}; + +QTEST_MAIN(Fb2ReaderTest) +#include "Fb2ReaderTest.moc"