Initial FB2 support

This commit is contained in:
Agel committed 2026-04-17 16:59:36 +02:00
1 parent 04bf291229
commit 7fdd56a7f5
9 files changed
+1059 -4

No files matched your search

+18 -4
View File
@@ -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")
+204
View File
@@ -0,0 +1,204 @@
#include "Fb2ImageProvider.h"
#include <QFile>
#include <QImage>
#include <QMutexLocker>
#include <QQuickTextureFactory>
#include <QThreadPool>
#include <QUrl>
#include <QXmlStreamReader>
// ---------------------------------------------------------------------------
// 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=<encoded-path>" 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<IImageLoader> Fb2ImageProvider::clone() const
{
QString fb2Path;
{
QMutexLocker lock(&m_mutex);
fb2Path = m_fb2Path;
}
auto c = std::make_unique<Fb2ImageProvider>();
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;
}
+50
View File
@@ -0,0 +1,50 @@
#pragma once
#include <QMutex>
#include <QRunnable>
#include <QString>
#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<IImageLoader> 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;
};
+355
View File
@@ -0,0 +1,355 @@
#include "Fb2Reader.h"
#include <QCryptographicHash>
#include <QDomDocument>
#include <QFileInfo>
#include <QStringConverter>
#include <QTextStream>
#include <uchardet/uchardet.h>
#include <iconv.h>
#include <fstream>
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<iconv_t>(-1))
return {};
QByteArray out(raw.size() * 4, '\0');
char *inBuf = const_cast<char *>(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<size_t>(-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("<p>") + inner + QStringLiteral("</p>\n");
}
if (tag == QLatin1String("title"))
return inner.trimmed().isEmpty() ? QString{} : QStringLiteral("<h2>") + inner + QStringLiteral("</h2>\n");
if (tag == QLatin1String("subtitle"))
return inner.trimmed().isEmpty() ? QString{} : QStringLiteral("<h3>") + inner + QStringLiteral("</h3>\n");
if (tag == QLatin1String("emphasis"))
return QStringLiteral("<em>") + inner + QStringLiteral("</em>");
if (tag == QLatin1String("strong"))
return QStringLiteral("<strong>") + inner + QStringLiteral("</strong>");
if (tag == QLatin1String("epigraph") || tag == QLatin1String("poem") || tag == QLatin1String("cite"))
return inner.trimmed().isEmpty() ? QString{} : QStringLiteral("<blockquote>") + inner + QStringLiteral("</blockquote>\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("<img src=\"image://fb2/") + href + QStringLiteral("\"/>\n");
return {};
}
if (tag == QLatin1String("a")) {
const QString href = el.attribute(QStringLiteral("l:href"));
if (!href.isEmpty() && !href.startsWith(QLatin1Char('#')))
return QStringLiteral("<a href=\"") + href.toHtmlEscaped() + QStringLiteral("\">") + inner + QStringLiteral("</a>");
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<int>(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<int>(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<TocEntry> 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};
}
+35
View File
@@ -0,0 +1,35 @@
#ifndef FB2READER_H
#define FB2READER_H
#include "backend/FormatReader.h"
#include <QByteArray>
#include <QList>
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<TocEntry> 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<QStringList> m_chapterHtmlNodes;
QStringList m_chapterTitles;
QList<TocEntry> m_toc;
};
#endif // FB2READER_H
@@ -1,5 +1,6 @@
#include "ImageLoaderFactory.h"
#include "EpubImageProvider.h"
#include "Fb2ImageProvider.h"
#include "WebImageProvider.h"
#include <QFileInfo>
@@ -47,5 +48,10 @@ std::unique_ptr<IImageLoader> ImageLoaderFactory::create(const QString &filePath
return composite;
}
if (ext == QLatin1String("fb2")) {
auto loader = std::make_unique<Fb2ImageProvider>();
loader->setFilePath(filePath);
return loader;
}
return nullptr;
}
@@ -1,5 +1,6 @@
#include "ImageProviderFactory.h"
#include "EpubImageProvider.h"
#include "Fb2ImageProvider.h"
#include <QFileInfo>
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;
}
+4
View File
@@ -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<TxtReader>(); },
[] { return std::make_unique<EpubReader>(); },
[] { return std::make_unique<Fb2Reader>(); },
});
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
+384
View File
@@ -0,0 +1,384 @@
#include <QtTest/QtTest>
#include <QDir>
#include <QFile>
#include <QTemporaryFile>
#include "backend/formats/Fb2Reader.h"
// ---------------------------------------------------------------------------
// Minimal FB2 fixture builder
// ---------------------------------------------------------------------------
static const char kFb2Header[] =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<FictionBook xmlns=\"http://www.gribuser.ru/xml/fictionbook/2.0\""
" xmlns:l=\"http://www.w3.org/1999/xlink\">";
static const char kFb2Footer[] = "</FictionBook>";
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 +=
"<description>"
" <title-info>"
" <book-title>Test Book</book-title>"
" <author>"
" <first-name>Test</first-name>"
" <last-name>Author</last-name>"
" </author>"
" </title-info>"
"</description>"
"<body>"
" <section>"
" <title><p>Chapter One</p></title>"
" <p>First paragraph of chapter one.</p>"
" <p>Second paragraph of chapter one.</p>"
" </section>"
" <section>"
" <title><p>Chapter Two</p></title>"
" <p>This is chapter two content.</p>"
" </section>"
"</body>";
xml += kFb2Footer;
return writeTempFb2(xml);
}
static QString buildFb2WithCover()
{
QByteArray xml = kFb2Header;
xml +=
"<description>"
" <title-info>"
" <book-title>Cover Book</book-title>"
" <author>"
" <first-name>Cover</first-name>"
" <last-name>Tester</last-name>"
" </author>"
" <coverpage>"
" <image l:href=\"#cover_img\"/>"
" </coverpage>"
" </title-info>"
"</description>"
"<body>"
" <section>"
" <title><p>Only Chapter</p></title>"
" <p>Some content.</p>"
" </section>"
"</body>"
"<binary id=\"cover_img\" content-type=\"image/png\">AAAA</binary>";
xml += kFb2Footer;
return writeTempFb2(xml);
}
static QString buildLargeFb2()
{
QByteArray xml = kFb2Header;
xml +=
"<description>"
" <title-info>"
" <book-title>Large Book</book-title>"
" </title-info>"
"</description>"
"<body>"
" <section>"
" <title><p>Big Chapter</p></title>";
for (int i = 0; i < 60; ++i) {
xml += QString("<p>Paragraph %1: The quick brown fox jumped over the lazy dog repeatedly.</p>")
.arg(i + 1).toUtf8();
}
xml += " </section></body>";
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 =
"<?xml version=\"1.0\" encoding=\"windows-1251\"?>"
"<FictionBook xmlns=\"http://www.gribuser.ru/xml/fictionbook/2.0\""
" xmlns:l=\"http://www.w3.org/1999/xlink\">"
"<description><title-info>"
"<book-title>";
// "Книга" in windows-1251: К=CA, н=ED, и=E8, г=E3, а=E0
xml += QByteArray("\xCA\xED\xE8\xE3\xE0");
xml +=
"</book-title>"
"</title-info></description>"
"<body><section>"
"<title><p>Глава</p></title>"
"<p>";
// "Привет" in windows-1251: П=CF, р=F0, и=E8, в=E2, е=E5, т=F2
xml += QByteArray("\xCF\xF0\xE8\xE2\xE5\xF2");
xml += "</p></section></body></FictionBook>";
return writeTempFb2(xml);
}
static QString buildFb2WithImage()
{
QByteArray xml = kFb2Header;
xml +=
"<description>"
" <title-info>"
" <book-title>Image Book</book-title>"
" </title-info>"
"</description>"
"<body>"
" <section>"
" <title><p>Chapter With Image</p></title>"
" <p>Text before image.</p>"
" <image l:href=\"#inline_img\"/>"
" <p>Text after image.</p>"
" </section>"
"</body>"
"<binary id=\"inline_img\" content-type=\"image/png\">AAAA</binary>";
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("<not valid xml <<<");
Fb2Reader reader;
QVERIFY(!reader.open(path));
QVERIFY(!reader.lastError().isEmpty());
QFile::remove(path);
}
// --- Metadata ---
void titleExtracted()
{
Fb2Reader reader;
QVERIFY(reader.open(m_samplePath));
QCOMPARE(reader.title(), QStringLiteral("Test Book"));
}
void authorExtracted()
{
Fb2Reader reader;
QVERIFY(reader.open(m_samplePath));
QCOMPARE(reader.author(), QStringLiteral("Test Author"));
}
void fileTypeIsFb2()
{
Fb2Reader reader;
QCOMPARE(reader.fileType(), QStringLiteral("fb2"));
}
// --- Chapters ---
void chapterCountMatchesBodySections()
{
Fb2Reader reader;
QVERIFY(reader.open(m_samplePath));
QCOMPARE(reader.chapterCount(), 2);
}
void loadChapterContent()
{
Fb2Reader reader;
QVERIFY(reader.open(m_samplePath));
const Chapter ch = reader.loadChapter(0);
QCOMPARE(ch.index, 0);
QVERIFY(!ch.contentChunks.isEmpty());
const QString combined = ch.contentChunks.join('\n');
QVERIFY(combined.contains(QStringLiteral("First paragraph")));
}
void loadChapterTwo()
{
Fb2Reader reader;
QVERIFY(reader.open(m_samplePath));
const Chapter ch = reader.loadChapter(1);
QCOMPARE(ch.index, 1);
QVERIFY(!ch.contentChunks.isEmpty());
const QString combined = ch.contentChunks.join('\n');
QVERIFY(combined.contains(QStringLiteral("chapter two")));
}
void loadChapterOutOfRange()
{
Fb2Reader reader;
QVERIFY(reader.open(m_samplePath));
const Chapter ch = reader.loadChapter(99);
QVERIFY(ch.contentChunks.isEmpty());
}
// --- TOC ---
void tableOfContentsBuilt()
{
Fb2Reader reader;
QVERIFY(reader.open(m_samplePath));
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);
}
// --- 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"