diff --git a/AGENTS.md b/AGENTS.md index d1db502..eb5054e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,8 +23,8 @@ Asteria Qt is a cross-platform desktop book/document reader built with Qt6/C++. ## Format Support -Active implementation: **EPUB, CBZ, CBR, Folder of images** -Queued for reimplementation on new render pipeline: **TXT, FB2** +Active implementation: **EPUB, FB2 (.fb2, .fbz, .fb2.zip), CBZ, CBR, Folder of images** +Queued for reimplementation on new render pipeline: **TXT** Full target format list: @@ -34,7 +34,7 @@ Full target format list: | CBZ | Yes | Unzip (`ZipByteSource`) + `ComicReader` + `MangaPagination` (single/dual page spread) | | CBR | Yes | `libarchive` (`RarByteSource`) + `ComicReader` + `MangaPagination` | | Folder | Yes | Directory scan (`DirByteSource`) + `ComicReader` + `MangaPagination` | -| FB2 | Queued | `QXmlStreamReader` + convert sections to chunks for `ChunkLayoutEngine` | +| FB2 | Yes | `Fb2ByteSource` (plain XML / ZIP) + encoding detection (BOM/XML/iconv) + semantic tag mapping + shared `DomChunkPipeline` + Knuth-Plass | | TXT | Queued | `QTextStream` + encoding detection + paginate for `ChunkLayoutEngine` | | PDF | Planned | `QtPdf` module (`QPdfDocument`, Qt 6.4+) | | DOC | Planned | `libwpd` or antiword subprocess | @@ -121,7 +121,7 @@ Backend (C++) handles all file I/O, format parsing, text layout calculation, and - **Image Providers**: - `image://fileicon/...`: `FileIconProvider` - `image://web/...`: `WebImageProvider` - - `image://cbz/...`, `image://cbr/...`, `image://dir/...`, `image://epub/...`: `EntryImageProvider` registered via `FormatRegistry::registerImageProviders`. + - `image://cbz/...`, `image://cbr/...`, `image://dir/...`, `image://epub/...`, `image://fb2/...`: `EntryImageProvider` registered via `FormatRegistry::registerImageProviders`. - **`AppCoordinator`**: C++ coordinator wiring signals between `Book`, `ReadingModel`, `HistoryModel`, `UiState`, `ReadingPreferences`, and `AppState`. --- @@ -159,6 +159,8 @@ public: ### 1. Text Mode (`ScrollPageView.qml`) - `ReadingModel` manages a list of `ContentChunk`s (`QVector`). - `EpubReader` cascades CSS onto the spine DOM and delegates directly to `HtmlBlockParser::parseChunks()`. This bypasses raw HTML string serialization and eliminates the double-parsing penalty, producing structured `ContentChunk` entities with pre-parsed `BlockItem`s, `wordCount`, `charCount`, and `unnestedContainers` for open containers spanning chunk boundaries. + - `HtmlBlockParser` normalizes paragraph typography across EPUB (`
` and `

`) and FB2 (`

`): unstyled paragraphs default to zero vertical margins (`marginTop = 0`, `marginBottom = 0`) and `2.0em` first-line indent (`textIndent = 2.0 * baseFontSize`), eliminating `ContainerStart`/`ContainerEnd` box allocation overhead and preventing blank vertical gaps between prose/dialogue lines. Explicit CSS margins in publisher stylesheets override this default. Shorthand `margin` and `padding` (1 to 4 token syntax) are fully parsed. + - Headings (`h1`..`h6`) default to left-aligned (`TextAlign::Left`) without first-line indentation (`textIndent = 0`). In `Fb2Reader`, `` flattens child `<p>` lines separated by `<br/>` with `text-align: left; text-indent: 0;`, preventing nested paragraph indent on titles. Scene transitions via FB2 `<empty-line>` use explicit margins to provide intended section gaps. - When viewport geometry or font preferences change, `ReadingModel::updateLayoutMetrics()` runs `ChunkLayoutEngine` off-thread: - Pre-parsed `BlockItem`s in `ContentChunk` scale dynamically with user font preferences in `ChunkLayoutEngine::prepareBlocks()` with zero HTML/XML re-parsing. - `KnuthPlass` computes optimal justified/aligned line breaks. @@ -194,6 +196,7 @@ public: Driven by `FormatSpec` table built in `main.cpp`: - `FormatSpec::comic(ext, matchesDirectory, scheme, makeSource)` - `FormatSpec::epub(makeSource)` +- `FormatSpec::fb2(ext, makeSource)` Each format registers its file extension / directory matcher, reader factory, `IByteSource` factory, and image URL scheme in a single table entry. --- @@ -228,6 +231,8 @@ src/ AuthorAttribution.h/cpp EntryImageProvider.h/cpp EpubReader.h/cpp + Fb2Reader.h/cpp + Fb2Types.h FileIconProvider.h/cpp FormatRegistry.h/cpp HtmlEntities.h/cpp @@ -240,6 +245,7 @@ src/ ComicReader.h/cpp sources/ DirByteSource.h/cpp + Fb2ByteSource.h/cpp RarByteSource.h/cpp ZipByteSource.h/cpp reading/ @@ -249,6 +255,7 @@ src/ layout/ ChunkLayoutEngine.h/cpp CssParser.h/cpp + DomChunkPipeline.h/cpp HtmlBlockParser.h/cpp KnuthPlass.h/cpp state/ @@ -291,6 +298,7 @@ tests/ formats/ CbzReaderTest.cpp EpubReaderTest.cpp + Fb2ReaderTest.cpp FolderReaderTest.cpp ImageUrlTest.cpp WebImageProviderTest.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 38150b7..a6cefbf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -87,6 +87,11 @@ set(SOURCES src/backend/formats/WebImageProvider.cpp src/backend/formats/EpubReader.h src/backend/formats/EpubReader.cpp + src/backend/formats/Fb2Types.h + src/backend/formats/sources/Fb2ByteSource.h + src/backend/formats/sources/Fb2ByteSource.cpp + src/backend/formats/Fb2Reader.h + src/backend/formats/Fb2Reader.cpp src/backend/reading/BookImageResolver.h src/backend/reading/BookImageResolver.cpp src/backend/reading/KnuthPlassItem.h @@ -97,6 +102,8 @@ set(SOURCES src/backend/reading/layout/CssParser.cpp src/backend/reading/layout/HtmlBlockParser.h src/backend/reading/layout/HtmlBlockParser.cpp + src/backend/reading/layout/DomChunkPipeline.h + src/backend/reading/layout/DomChunkPipeline.cpp src/backend/reading/layout/ChunkLayoutEngine.h src/backend/reading/layout/ChunkLayoutEngine.cpp ) @@ -140,6 +147,7 @@ target_link_libraries(asteria-qt PRIVATE Qt6::QuickControls2 PkgConfig::MINIZIP PkgConfig::LIBARCHIVE + Iconv::Iconv Qt6::Xml Qt6::Network ) @@ -242,6 +250,7 @@ set(LAYOUT_SOURCES src/backend/reading/layout/CssParser.cpp src/backend/reading/layout/HtmlBlockParser.cpp src/backend/reading/layout/ChunkLayoutEngine.cpp + src/backend/reading/layout/DomChunkPipeline.cpp ) set(EPUB_READER_SOURCES @@ -252,6 +261,15 @@ set(EPUB_READER_SOURCES ${LAYOUT_SOURCES} ) +set(FB2_READER_SOURCES + src/backend/formats/HtmlEntities.cpp + src/backend/formats/ImageUrl.cpp + src/backend/formats/sources/ZipByteSource.cpp + src/backend/formats/sources/Fb2ByteSource.cpp + src/backend/formats/Fb2Reader.cpp + ${LAYOUT_SOURCES} +) + # Testing enable_testing() @@ -319,8 +337,9 @@ add_asteria_test(FormatRegistryTest tests/FormatRegistryTest.cpp src/backend/formats/AsyncImageResponse.cpp src/backend/formats/EntryImageProvider.cpp ${COMIC_READER_SOURCES} - ${EPUB_READER_SOURCES}) -target_link_libraries(FormatRegistryTest PRIVATE PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Gui Qt6::Quick Qt6::Network) + ${EPUB_READER_SOURCES} + ${FB2_READER_SOURCES}) +target_link_libraries(FormatRegistryTest PRIVATE PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Iconv::Iconv Qt6::Xml Qt6::Gui Qt6::Quick Qt6::Network) set_tests_properties(FormatRegistryTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp @@ -332,8 +351,9 @@ add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp src/backend/state/BookPositionStore.cpp src/backend/HistoryModel.cpp ${COMIC_SOURCES} - ${EPUB_READER_SOURCES}) -target_link_libraries(ReadingModelTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Network) + ${EPUB_READER_SOURCES} + ${FB2_READER_SOURCES}) +target_link_libraries(ReadingModelTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Iconv::Iconv Qt6::Xml Qt6::Network) set_tests_properties(ReadingModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") add_asteria_test(TextLayoutEngineSpecTest tests/reading/TextLayoutEngineSpecTest.cpp @@ -346,8 +366,9 @@ add_asteria_test(TextLayoutEngineSpecTest tests/reading/TextLayoutEngineSpecTest src/backend/state/BookPositionStore.cpp src/backend/HistoryModel.cpp ${COMIC_SOURCES} - ${EPUB_READER_SOURCES}) -target_link_libraries(TextLayoutEngineSpecTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Network) + ${EPUB_READER_SOURCES} + ${FB2_READER_SOURCES}) +target_link_libraries(TextLayoutEngineSpecTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Iconv::Iconv Qt6::Xml Qt6::Network) set_tests_properties(TextLayoutEngineSpecTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") add_asteria_test(KnuthPlassRenderingSpecTest tests/reading/KnuthPlassRenderingSpecTest.cpp @@ -360,8 +381,9 @@ add_asteria_test(KnuthPlassRenderingSpecTest tests/reading/KnuthPlassRenderingSp src/backend/state/BookPositionStore.cpp src/backend/HistoryModel.cpp ${COMIC_SOURCES} - ${EPUB_READER_SOURCES}) -target_link_libraries(KnuthPlassRenderingSpecTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Network) + ${EPUB_READER_SOURCES} + ${FB2_READER_SOURCES}) +target_link_libraries(KnuthPlassRenderingSpecTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Iconv::Iconv Qt6::Xml Qt6::Network) set_tests_properties(KnuthPlassRenderingSpecTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") add_asteria_test(AppStateTest tests/AppStateTest.cpp @@ -388,8 +410,9 @@ add_asteria_test(BookTest tests/book/BookTest.cpp src/backend/IFileDialogService.h src/backend/NativeFileDialogService.cpp ${COMIC_SOURCES} - ${EPUB_READER_SOURCES}) -target_link_libraries(BookTest PRIVATE Qt6::Concurrent Qt6::Widgets PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Gui Qt6::Quick Qt6::Network) + ${EPUB_READER_SOURCES} + ${FB2_READER_SOURCES}) +target_link_libraries(BookTest PRIVATE Qt6::Concurrent Qt6::Widgets PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Iconv::Iconv Qt6::Xml Qt6::Gui Qt6::Quick Qt6::Network) set_tests_properties(BookTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") add_asteria_test(EntryImageProviderTest tests/EntryImageProviderTest.cpp @@ -406,11 +429,21 @@ add_asteria_test(HistoryModelTest tests/HistoryModelTest.cpp src/backend/formats/AsyncImageResponse.cpp src/backend/formats/FormatRegistry.cpp ${COMIC_SOURCES} - ${EPUB_READER_SOURCES}) + ${EPUB_READER_SOURCES} + ${FB2_READER_SOURCES}) target_link_libraries(HistoryModelTest PRIVATE - Qt6::Concurrent Qt6::Quick Qt6::Gui Qt6::Xml Qt6::Network PkgConfig::MINIZIP PkgConfig::LIBARCHIVE) + Qt6::Concurrent Qt6::Quick Qt6::Gui Qt6::Xml Qt6::Network PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Iconv::Iconv) set_tests_properties(HistoryModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") +add_asteria_test(Fb2ReaderTest tests/formats/Fb2ReaderTest.cpp + src/backend/formats/AsyncImageResponse.cpp + src/backend/formats/WebImageProvider.cpp + src/backend/reading/BookImageResolver.cpp + ${EPUB_READER_SOURCES} + ${FB2_READER_SOURCES}) +target_link_libraries(Fb2ReaderTest PRIVATE PkgConfig::MINIZIP Iconv::Iconv Qt6::Xml Qt6::Gui Qt6::Quick Qt6::Network) +set_tests_properties(Fb2ReaderTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") + add_asteria_test(FileIconProviderTest tests/FileIconProviderTest.cpp src/backend/formats/FileIconProvider.cpp) target_link_libraries(FileIconProviderTest PRIVATE Qt6::Quick Qt6::Gui Qt6::Widgets) diff --git a/src/backend/HistoryModel.cpp b/src/backend/HistoryModel.cpp index 6ef33ac..22a3af6 100644 --- a/src/backend/HistoryModel.cpp +++ b/src/backend/HistoryModel.cpp @@ -13,6 +13,12 @@ QString formatForPath(const QString &filePath) { if (QFileInfo(filePath).isDir()) return QStringLiteral("Folder"); + if (filePath.endsWith(QLatin1String(".fb2.zip"), Qt::CaseInsensitive)) + return QStringLiteral("FB2"); + if (filePath.endsWith(QLatin1String(".fbz"), Qt::CaseInsensitive)) + return QStringLiteral("FBZ"); + if (filePath.endsWith(QLatin1String(".fb2"), Qt::CaseInsensitive)) + return QStringLiteral("FB2"); return filePath.section('.', -1).toUpper(); } } diff --git a/src/backend/formats/EpubReader.cpp b/src/backend/formats/EpubReader.cpp index aa8b657..38ebb49 100644 --- a/src/backend/formats/EpubReader.cpp +++ b/src/backend/formats/EpubReader.cpp @@ -12,6 +12,7 @@ #include "backend/formats/HtmlEntities.h" #include "backend/formats/ImageUrl.h" #include "backend/reading/layout/CssParser.h" +#include "backend/reading/layout/DomChunkPipeline.h" EpubReader::EpubReader(SourceFactory sourceFactory, QString scheme) : m_sourceFactory(std::move(sourceFactory)) @@ -179,38 +180,9 @@ void EpubReader::appendSpineChunks(const QString &xhtml, } } - // 4. Cascade onto each element & rewrite image URLs - std::function<void(QDomElement &)> processElement = [&](QDomElement &el) { - const auto decls = Css::cascade(sheet, el); - if (!decls.isEmpty()) { - el.setAttribute(QStringLiteral("style"), Css::serialize(decls)); - } - - const QString tag = el.tagName().toLower(); - if (tag == QLatin1String("img") || tag == QLatin1String("image")) { - QString srcAttr = el.hasAttribute(QStringLiteral("src")) ? QStringLiteral("src") - : (el.hasAttribute(QStringLiteral("xlink:href")) ? QStringLiteral("xlink:href") - : (el.hasAttribute(QStringLiteral("href")) ? QStringLiteral("href") : QString())); - if (!srcAttr.isEmpty()) { - const QString src = el.attribute(srcAttr); - const QString resolved = ImageUrl::resolve(m_scheme, src, m_filePath, xhtmlDir); - el.setAttribute(srcAttr, resolved); - } - } - - for (QDomNode child = el.firstChild(); !child.isNull(); child = child.nextSibling()) { - if (child.isElement()) { - QDomElement childEl = child.toElement(); - processElement(childEl); - } - } - }; - + // 4. Cascade onto each element, rewrite image URLs & build ContentChunks directly from cascaded DOM QDomElement root = doc.documentElement(); - processElement(root); - - // 5. Build ContentChunks directly from cascaded DOM - m_chunks.append(HtmlBlockParser::parseChunks(root, xhtmlHref)); + m_chunks.append(DomChunkPipeline::cascadeAndChunk(root, sheet, m_scheme, m_filePath, xhtmlHref, xhtmlDir)); } bool EpubReader::parseOpen(const QString &filePath, IByteSource &source, bool metadataOnly) diff --git a/src/backend/formats/Fb2Reader.cpp b/src/backend/formats/Fb2Reader.cpp new file mode 100644 index 0000000..831e211 --- /dev/null +++ b/src/backend/formats/Fb2Reader.cpp @@ -0,0 +1,471 @@ +#include "Fb2Reader.h" + +#include <QDomDocument> +#include <QFileInfo> +#include <QRegularExpression> +#include <QStringDecoder> +#include <iconv.h> + +#include "backend/formats/AuthorAttribution.h" +#include "backend/formats/ImageUrl.h" +#include "backend/formats/sources/Fb2ByteSource.h" +#include "backend/reading/layout/DomChunkPipeline.h" + +namespace { + +QString decodeFb2Xml(const QByteArray &bytes) +{ + if (bytes.startsWith("\xEF\xBB\xBF")) + return QString::fromUtf8(bytes.constData() + 3, bytes.size() - 3); + if (bytes.startsWith("\xFF\xFE")) + return QString::fromUtf16(reinterpret_cast<const char16_t*>(bytes.constData() + 2), (bytes.size() - 2) / 2); + + const int checkLen = qMin(512, bytes.size()); + const QByteArray header = bytes.left(checkLen); + static const QRegularExpression encRe(QStringLiteral("encoding\\s*=\\s*[\"']([^\"']+)[\"']"), + QRegularExpression::CaseInsensitiveOption); + const QString headerStr = QString::fromLatin1(header); + const auto match = encRe.match(headerStr); + if (match.hasMatch()) { + const QString enc = match.captured(1).trimmed(); + if (enc.compare(QLatin1String("utf-8"), Qt::CaseInsensitive) == 0) { + return QString::fromUtf8(bytes); + } + + QStringDecoder decoder(enc.toUtf8().constData()); + if (decoder.isValid()) { + QString res = decoder(bytes); + if (!decoder.hasError()) + return res; + } + + iconv_t cd = iconv_open("UTF-8", enc.toUtf8().constData()); + if (cd != (iconv_t)-1) { + size_t inBytesLeft = bytes.size(); + char *inBuf = const_cast<char*>(bytes.constData()); + size_t outBytesLeft = bytes.size() * 4 + 4; + QByteArray out; + out.resize(outBytesLeft); + char *outBuf = out.data(); + if (iconv(cd, &inBuf, &inBytesLeft, &outBuf, &outBytesLeft) != (size_t)-1) { + iconv_close(cd); + return QString::fromUtf8(out.constData(), out.size() - outBytesLeft); + } + iconv_close(cd); + } + } + + return QString::fromUtf8(bytes); +} + +void mapFb2Children(const QDomElement &srcEl, + QDomElement &dstParent, + QDomDocument &dstDoc, + int depth) +{ + for (QDomNode child = srcEl.firstChild(); !child.isNull(); child = child.nextSibling()) { + if (child.isText()) { + dstParent.appendChild(dstDoc.createTextNode(child.toText().data())); + continue; + } + if (!child.isElement()) + continue; + + const QDomElement el = child.toElement(); + const QString tag = el.tagName().toLower(); + + if (tag == QLatin1String("section")) { + // Child sections are processed separately as independent chunk boundaries + continue; + } + + if (tag == QLatin1String("title")) { + const int hLevel = qBound(1, depth, 6); + QDomElement h = dstDoc.createElement(QStringLiteral("h%1").arg(hLevel)); + h.setAttribute(QStringLiteral("style"), QStringLiteral("text-align: left; text-indent: 0;")); + bool firstLine = true; + for (QDomNode child = el.firstChild(); !child.isNull(); child = child.nextSibling()) { + if (child.isText()) { + h.appendChild(dstDoc.createTextNode(child.toText().data())); + } else if (child.isElement()) { + const QDomElement childEl = child.toElement(); + const QString childTag = childEl.tagName().toLower(); + if (childTag == QLatin1String("p") || childTag == QLatin1String("empty-line")) { + if (!firstLine) { + h.appendChild(dstDoc.createElement(QStringLiteral("br"))); + } + firstLine = false; + mapFb2Children(childEl, h, dstDoc, depth); + } else { + mapFb2Children(childEl, h, dstDoc, depth); + } + } + } + dstParent.appendChild(h); + } else if (tag == QLatin1String("subtitle")) { + QDomElement p = dstDoc.createElement(QStringLiteral("p")); + p.setAttribute(QStringLiteral("style"), QStringLiteral("text-align: center; font-weight: bold; text-indent: 0;")); + mapFb2Children(el, p, dstDoc, depth); + dstParent.appendChild(p); + } else if (tag == QLatin1String("epigraph") || tag == QLatin1String("cite")) { + QDomElement bq = dstDoc.createElement(QStringLiteral("blockquote")); + mapFb2Children(el, bq, dstDoc, depth); + dstParent.appendChild(bq); + } else if (tag == QLatin1String("poem")) { + QDomElement div = dstDoc.createElement(QStringLiteral("div")); + div.setAttribute(QStringLiteral("style"), QStringLiteral("margin-left: 2em; margin-right: 2em;")); + mapFb2Children(el, div, dstDoc, depth); + dstParent.appendChild(div); + } else if (tag == QLatin1String("stanza")) { + QDomElement div = dstDoc.createElement(QStringLiteral("div")); + div.setAttribute(QStringLiteral("style"), QStringLiteral("margin-top: 1em; margin-bottom: 1em;")); + mapFb2Children(el, div, dstDoc, depth); + dstParent.appendChild(div); + } else if (tag == QLatin1String("v")) { + QDomElement p = dstDoc.createElement(QStringLiteral("p")); + p.setAttribute(QStringLiteral("style"), QStringLiteral("margin: 0; text-indent: 0;")); + mapFb2Children(el, p, dstDoc, depth); + dstParent.appendChild(p); + } else if (tag == QLatin1String("text-author") || tag == QLatin1String("date")) { + QDomElement p = dstDoc.createElement(QStringLiteral("p")); + p.setAttribute(QStringLiteral("style"), QStringLiteral("text-align: right; font-style: italic; text-indent: 0;")); + mapFb2Children(el, p, dstDoc, depth); + dstParent.appendChild(p); + } else if (tag == QLatin1String("empty-line")) { + QDomElement p = dstDoc.createElement(QStringLiteral("p")); + p.setAttribute(QStringLiteral("style"), QStringLiteral("margin: 0.5em 0;")); + p.appendChild(dstDoc.createElement(QStringLiteral("br"))); + dstParent.appendChild(p); + } else if (tag == QLatin1String("emphasis")) { + QDomElement em = dstDoc.createElement(QStringLiteral("i")); + mapFb2Children(el, em, dstDoc, depth); + dstParent.appendChild(em); + } else if (tag == QLatin1String("strikethrough")) { + QDomElement s = dstDoc.createElement(QStringLiteral("s")); + mapFb2Children(el, s, dstDoc, depth); + dstParent.appendChild(s); + } else if (tag == QLatin1String("strong")) { + QDomElement b = dstDoc.createElement(QStringLiteral("b")); + mapFb2Children(el, b, dstDoc, depth); + dstParent.appendChild(b); + } else if (tag == QLatin1String("p")) { + QDomElement p = dstDoc.createElement(QStringLiteral("p")); + mapFb2Children(el, p, dstDoc, depth); + dstParent.appendChild(p); + } else if (tag == QLatin1String("a")) { + QDomElement a = dstDoc.createElement(QStringLiteral("a")); + QString href = el.attribute(QStringLiteral("href")); + if (href.isEmpty()) href = el.attribute(QStringLiteral("l:href")); + if (href.isEmpty()) href = el.attribute(QStringLiteral("xlink:href")); + if (!href.isEmpty()) a.setAttribute(QStringLiteral("href"), href); + mapFb2Children(el, a, dstDoc, depth); + dstParent.appendChild(a); + } else if (tag == QLatin1String("image")) { + QDomElement img = dstDoc.createElement(QStringLiteral("img")); + QString href = el.attribute(QStringLiteral("l:href")); + if (href.isEmpty()) href = el.attribute(QStringLiteral("xlink:href")); + if (href.isEmpty()) href = el.attribute(QStringLiteral("href")); + if (!href.isEmpty()) img.setAttribute(QStringLiteral("src"), href); + dstParent.appendChild(img); + } else { + // General element pass-through + QDomElement generic = dstDoc.createElement(el.tagName()); + mapFb2Children(el, generic, dstDoc, depth); + dstParent.appendChild(generic); + } + } +} + +} // namespace + +Fb2Reader::Fb2Reader(SourceFactory sourceFactory, QString scheme) + : m_sourceFactory(std::move(sourceFactory)) + , m_scheme(std::move(scheme)) +{ +} + +HistoryFormatLabel Fb2Reader::formatLabelEnum() const +{ + if (m_filePath.endsWith(QLatin1String(".fbz"), Qt::CaseInsensitive)) + return HistoryFormatLabel::FBZ; + return HistoryFormatLabel::FB2; +} + +QString Fb2Reader::formatLabel() const +{ + return formatLabelEnum() == HistoryFormatLabel::FBZ ? QStringLiteral("FBZ") : QStringLiteral("FB2"); +} + +bool Fb2Reader::open(const QString &filePath) +{ + m_filePath = filePath; + m_status = Fb2LoadStatus::loading_full; + m_title.clear(); + m_author.clear(); + m_error.clear(); + m_coverImageUrl.clear(); + m_authors.clear(); + m_binaries.clear(); + m_chunks.clear(); + m_contentHash.clear(); + + auto source = m_sourceFactory(); + if (!source || !source->open(filePath)) { + m_status = Fb2LoadStatus::failed; + if (auto *fb2Src = dynamic_cast<Fb2ByteSource*>(source.get())) { + m_error = fb2Src->lastError(); + } + if (m_error.isEmpty()) + m_error = QStringLiteral("Cannot open FB2 file: ") + filePath; + return false; + } + + return parseOpen(filePath, *source, false); +} + +bool Fb2Reader::loadMetadata(const QString &filePath) +{ + m_filePath = filePath; + m_status = Fb2LoadStatus::loading_metadata; + m_title.clear(); + m_author.clear(); + m_error.clear(); + m_coverImageUrl.clear(); + m_authors.clear(); + m_binaries.clear(); + m_chunks.clear(); + m_contentHash.clear(); + + auto source = m_sourceFactory(); + if (!source || !source->open(filePath)) { + m_status = Fb2LoadStatus::failed; + if (auto *fb2Src = dynamic_cast<Fb2ByteSource*>(source.get())) { + m_error = fb2Src->lastError(); + } + if (m_error.isEmpty()) + m_error = QStringLiteral("Cannot open FB2 file: ") + filePath; + return false; + } + + return parseOpen(filePath, *source, true); +} + +bool Fb2Reader::parseOpen(const QString &filePath, IByteSource &source, bool metadataOnly) +{ + m_filePath = filePath; + m_contentHash = source.contentHash(); + + QByteArray rawXml; + if (auto *fb2Source = dynamic_cast<Fb2ByteSource*>(&source)) { + m_containerKind = fb2Source->containerKind(); + rawXml = fb2Source->rawXmlData(); + } else { + m_containerKind = (filePath.endsWith(QLatin1String(".fbz"), Qt::CaseInsensitive) + || filePath.endsWith(QLatin1String(".fb2.zip"), Qt::CaseInsensitive)) + ? Fb2ContainerKind::zip_archive : Fb2ContainerKind::plain_xml; + rawXml = source.readEntry(QString()); + } + + const QString decodedXml = decodeFb2Xml(rawXml); + + QDomDocument doc; + QString errorMsg; + int errorLine = 0; + int errorColumn = 0; + if (!doc.setContent(decodedXml, &errorMsg, &errorLine, &errorColumn)) { + m_status = Fb2LoadStatus::failed; + m_error = QStringLiteral("Invalid or malformed FictionBook XML"); + return false; + } + + QDomElement root = doc.documentElement(); + if (root.tagName() != QLatin1String("FictionBook")) { + m_status = Fb2LoadStatus::failed; + m_error = QStringLiteral("Invalid or malformed FictionBook XML"); + return false; + } + + // Binaries + if (auto *fb2Source = dynamic_cast<Fb2ByteSource*>(&source)) { + m_binaries = fb2Source->binaries().values().toVector(); + } else { + // Fallback: extract <binary> tags from DOM + QDomNodeList binaryNodes = root.elementsByTagName(QStringLiteral("binary")); + for (int i = 0; i < binaryNodes.size(); ++i) { + QDomElement bEl = binaryNodes.at(i).toElement(); + const QString id = bEl.attribute(QStringLiteral("id")); + const QString ct = bEl.attribute(QStringLiteral("content-type")); + const QByteArray decoded = QByteArray::fromBase64(bEl.text().trimmed().toUtf8()); + BinaryResource res; + res.id = id; + if (!ct.isEmpty()) + res.content_type = ct; + res.decoded_bytes = decoded; + m_binaries.append(res); + } + } + + // Metadata extraction + QDomElement desc = root.firstChildElement(QLatin1String("description")); + QDomElement titleInfo = desc.firstChildElement(QLatin1String("title-info")); + + // Title + m_title = titleInfo.firstChildElement(QLatin1String("book-title")).text().trimmed(); + if (m_title.isEmpty()) { + m_title = QFileInfo(filePath).completeBaseName(); + } + + // Authors + QStringList formattedAuthors; + for (QDomElement child = titleInfo.firstChildElement(); !child.isNull(); child = child.nextSiblingElement()) { + if (child.tagName() == QLatin1String("author")) { + AuthorName an; + QDomElement fn = child.firstChildElement(QLatin1String("first-name")); + if (!fn.isNull()) an.first_name = fn.text().trimmed(); + QDomElement mn = child.firstChildElement(QLatin1String("middle-name")); + if (!mn.isNull()) an.middle_name = mn.text().trimmed(); + QDomElement ln = child.firstChildElement(QLatin1String("last-name")); + if (!ln.isNull()) an.last_name = ln.text().trimmed(); + QDomElement nn = child.firstChildElement(QLatin1String("nickname")); + if (!nn.isNull()) an.nickname = nn.text().trimmed(); + + m_authors.append(an); + const QString fmt = an.format(); + if (!fmt.isEmpty()) + formattedAuthors << fmt; + } + } + m_author = formattedAuthors.join(QStringLiteral(", ")); + + // Cover image + QString coverId; + QDomElement coverpage = titleInfo.firstChildElement(QLatin1String("coverpage")); + if (!coverpage.isNull()) { + QDomElement img = coverpage.firstChildElement(QLatin1String("image")); + if (!img.isNull()) { + QString href = img.attribute(QStringLiteral("l:href")); + if (href.isEmpty()) href = img.attribute(QStringLiteral("xlink:href")); + if (href.isEmpty()) href = img.attribute(QStringLiteral("href")); + if (href.startsWith(QLatin1Char('#'))) + href.remove(0, 1); + coverId = href; + } + } + + if (coverId.isEmpty()) { + for (const auto &b : m_binaries) { + if (b.id.contains(QLatin1String("cover"), Qt::CaseInsensitive) + && (!b.content_type.has_value() || b.content_type->isEmpty() || b.content_type->startsWith(QLatin1String("image/"), Qt::CaseInsensitive))) { + coverId = b.id; + break; + } + } + } + + if (!coverId.isEmpty()) { + m_coverImageUrl = ImageUrl::build(m_scheme, coverId, m_filePath); + } else { + m_coverImageUrl.clear(); + } + + if (metadataOnly) { + m_chunks.clear(); + m_status = Fb2LoadStatus::loaded; + return true; + } + + // Stylesheets + QStringList stylesheetTexts; + for (QDomElement child = root.firstChildElement(); !child.isNull(); child = child.nextSiblingElement()) { + if (child.tagName() == QLatin1String("stylesheet") && + (child.attribute(QStringLiteral("type")).isEmpty() || child.attribute(QStringLiteral("type")) == QLatin1String("text/css"))) { + stylesheetTexts << child.text(); + } + } + + // Process sections helper + std::function<void(const QDomElement &, const QString &, int)> processSection = + [&](const QDomElement &secEl, const QString &secHref, int depth) { + QDomDocument secDoc; + QDomElement secRoot = secDoc.createElement(QStringLiteral("div")); + secDoc.appendChild(secRoot); + + mapFb2Children(secEl, secRoot, secDoc, depth); + + if (secRoot.hasChildNodes()) { + m_chunks.append(DomChunkPipeline::cascadeAndChunk(secRoot, stylesheetTexts, m_scheme, m_filePath, secHref, QString(), 512)); + } + + int childSecIndex = 0; + for (QDomElement child = secEl.firstChildElement(); !child.isNull(); child = child.nextSiblingElement()) { + if (child.tagName().toLower() == QLatin1String("section")) { + QString childHref = child.attribute(QStringLiteral("id")); + if (childHref.isEmpty()) { + childHref = QStringLiteral("%1/section-%2").arg(secHref).arg(childSecIndex++); + } + processSection(child, childHref, depth + 1); + } + } + }; + + // 1. Prepend <description><title-info><annotation> if present + QDomElement annotationEl = titleInfo.firstChildElement(QLatin1String("annotation")); + if (!annotationEl.isNull()) { + QString annotHref = annotationEl.attribute(QStringLiteral("id")); + if (annotHref.isEmpty()) + annotHref = QStringLiteral("annotation"); + processSection(annotationEl, annotHref, 1); + } + + // 2. All <body> elements in document order + int bodyIndex = 0; + for (QDomElement child = root.firstChildElement(); !child.isNull(); child = child.nextSiblingElement()) { + if (child.tagName().toLower() == QLatin1String("body")) { + const QString bodyPrefix = QStringLiteral("body-%1").arg(bodyIndex++); + QDomElement firstSec = child.firstChildElement(QLatin1String("section")); + + if (firstSec.isNull()) { + // Whole body without sections + QString bodyHref = child.attribute(QStringLiteral("id")); + if (bodyHref.isEmpty()) bodyHref = child.attribute(QLatin1String("name")); + if (bodyHref.isEmpty()) bodyHref = bodyPrefix; + processSection(child, bodyHref, 1); + } else { + // Direct elements before sections (e.g. body title, epigraph) + QDomDocument secDoc; + QDomElement secRoot = secDoc.createElement(QStringLiteral("div")); + secDoc.appendChild(secRoot); + mapFb2Children(child, secRoot, secDoc, 1); + + if (secRoot.hasChildNodes()) { + QString headerHref = child.attribute(QStringLiteral("id")); + if (headerHref.isEmpty()) headerHref = bodyPrefix; + m_chunks.append(DomChunkPipeline::cascadeAndChunk(secRoot, stylesheetTexts, m_scheme, m_filePath, headerHref, QString(), 512)); + } + + int secIdx = 0; + for (QDomElement sec = child.firstChildElement(); !sec.isNull(); sec = sec.nextSiblingElement()) { + if (sec.tagName().toLower() == QLatin1String("section")) { + QString secHref = sec.attribute(QStringLiteral("id")); + if (secHref.isEmpty()) + secHref = QStringLiteral("%1/section-%2").arg(bodyPrefix).arg(secIdx++); + processSection(sec, secHref, 1); + } + } + } + } + } + + // Fallback if no chunks were extracted + if (m_chunks.isEmpty()) { + ContentChunk fallbackChunk; + fallbackChunk.sectionHref = m_filePath; + BlockItem p; + p.kind = BlockItem::Kind::Paragraph; + fallbackChunk.blocks.append(p); + m_chunks.append(fallbackChunk); + } + + m_status = Fb2LoadStatus::loaded; + return true; +} diff --git a/src/backend/formats/Fb2Reader.h b/src/backend/formats/Fb2Reader.h new file mode 100644 index 0000000..cc1e296 --- /dev/null +++ b/src/backend/formats/Fb2Reader.h @@ -0,0 +1,62 @@ +#pragma once + +#include <functional> +#include <memory> +#include <QByteArray> +#include <QHash> +#include <QString> +#include <QStringList> +#include <QVector> + +#include "backend/FormatReader.h" +#include "backend/formats/IByteSource.h" +#include "backend/formats/Fb2Types.h" + +class Fb2Reader : public FormatReader { +public: + using SourceFactory = std::function<std::unique_ptr<IByteSource>()>; + + Fb2Reader(SourceFactory sourceFactory, QString scheme); + + ReadingMode mode() const override { return ReadingMode::Text; } + bool open(const QString &filePath) override; + bool loadMetadata(const QString &filePath) override; + QString lastError() const override { return m_error; } + + QString filePath() const override { return m_filePath; } + QString title() const override { return m_title; } + QString author() const override { return m_author; } + QString coverImageUrl() const override { return m_coverImageUrl; } + QByteArray contentHash() const override { return m_contentHash; } + + QVector<ContentChunk> chunks() const override { return m_chunks; } + + // Spec properties + Fb2LoadStatus status() const { return m_status; } + Fb2ContainerKind containerKind() const { return m_containerKind; } + HistoryFormatLabel formatLabelEnum() const; + QString formatLabel() const; + + const QVector<AuthorName> &authors() const { return m_authors; } + const QVector<BinaryResource> &binaries() const { return m_binaries; } + +private: + bool parseOpen(const QString &filePath, IByteSource &source, bool metadataOnly); + + SourceFactory m_sourceFactory; + QString m_scheme; + + QString m_filePath; + QByteArray m_contentHash; + QString m_title; + QString m_author; + QString m_error; + QString m_coverImageUrl; + + Fb2LoadStatus m_status = Fb2LoadStatus::idle; + Fb2ContainerKind m_containerKind = Fb2ContainerKind::plain_xml; + + QVector<AuthorName> m_authors; + QVector<BinaryResource> m_binaries; + QVector<ContentChunk> m_chunks; +}; diff --git a/src/backend/formats/Fb2Types.h b/src/backend/formats/Fb2Types.h new file mode 100644 index 0000000..d2c1fef --- /dev/null +++ b/src/backend/formats/Fb2Types.h @@ -0,0 +1,119 @@ +#pragma once + +#include <optional> +#include <QByteArray> +#include <QString> +#include <QStringList> + +#include "backend/reading/layout/HtmlBlockParser.h" + +struct AuthorName { + std::optional<QString> first_name; + std::optional<QString> middle_name; + std::optional<QString> last_name; + std::optional<QString> nickname; + + bool has_structured_name() const + { + return first_name.has_value() || middle_name.has_value() || last_name.has_value(); + } + + QString format() const + { + QStringList parts; + if (first_name.has_value() && !first_name->trimmed().isEmpty()) + parts << first_name->trimmed(); + if (middle_name.has_value() && !middle_name->trimmed().isEmpty()) + parts << middle_name->trimmed(); + if (last_name.has_value() && !last_name->trimmed().isEmpty()) + parts << last_name->trimmed(); + + if (!parts.isEmpty()) + return parts.join(QLatin1Char(' ')); + if (nickname.has_value() && !nickname->trimmed().isEmpty()) + return nickname->trimmed(); + return {}; + } + + bool operator==(const AuthorName &o) const + { + return first_name == o.first_name && + middle_name == o.middle_name && + last_name == o.last_name && + nickname == o.nickname; + } + + bool operator!=(const AuthorName &o) const + { + return !(*this == o); + } +}; + +struct BinaryResource { + QString id; + std::optional<QString> content_type; + QByteArray decoded_bytes; + + bool operator==(const BinaryResource &o) const + { + return id == o.id && + content_type == o.content_type && + decoded_bytes == o.decoded_bytes; + } + + bool operator!=(const BinaryResource &o) const + { + return !(*this == o); + } +}; + +struct ContentChunkValue { + QString section_href; + int blocks_count = 0; + int word_count = 0; + int char_count = 0; + int unnested_containers = 0; + + static ContentChunkValue fromChunk(const ContentChunk &c) + { + return ContentChunkValue{ + c.sectionHref, + static_cast<int>(c.blocks.size()), + c.wordCount, + c.charCount, + c.unnestedContainers + }; + } + + bool operator==(const ContentChunkValue &o) const + { + return section_href == o.section_href && + blocks_count == o.blocks_count && + word_count == o.word_count && + char_count == o.char_count && + unnested_containers == o.unnested_containers; + } + + bool operator!=(const ContentChunkValue &o) const + { + return !(*this == o); + } +}; + +enum class Fb2ContainerKind { + plain_xml, + zip_archive +}; + +enum class Fb2LoadStatus { + idle, + loading_metadata, + loading_full, + loaded, + failed +}; + +enum class HistoryFormatLabel { + FB2, + FBZ +}; diff --git a/src/backend/formats/FormatRegistry.cpp b/src/backend/formats/FormatRegistry.cpp index 101874a..ad3dc52 100644 --- a/src/backend/formats/FormatRegistry.cpp +++ b/src/backend/formats/FormatRegistry.cpp @@ -4,9 +4,11 @@ #include "backend/FormatReader.h" #include "backend/formats/comic/ComicReader.h" #include "backend/formats/EpubReader.h" +#include "backend/formats/Fb2Reader.h" #include <QFileInfo> #include <QQmlEngine> +#include <QSet> FormatSpec FormatSpec::comic(const QString &ext, bool matchesDirectory, const QString &scheme, SourceFactory makeSource) @@ -31,6 +33,17 @@ FormatSpec FormatSpec::epub(SourceFactory makeSource) }; } +FormatSpec FormatSpec::fb2(const QString &ext, SourceFactory makeSource) +{ + return FormatSpec{ + ext, + false, + QStringLiteral("fb2"), + [makeSource] { return std::make_unique<Fb2Reader>(makeSource, QStringLiteral("fb2")); }, + makeSource + }; +} + FormatRegistry::FormatRegistry(QVector<FormatSpec> specs) : m_specs(std::move(specs)) { @@ -40,11 +53,16 @@ const FormatSpec *FormatRegistry::specFor(const QString &filePath) const { const QFileInfo fi(filePath); const bool isDir = fi.isDir(); - const QString ext = fi.suffix().toLower(); + const QString lowerPath = filePath.toLower(); for (const FormatSpec &spec : m_specs) { - if (isDir ? spec.matchesDirectory : (!spec.matchesDirectory && spec.extension == ext)) - return &spec; + if (isDir) { + if (spec.matchesDirectory) + return &spec; + } else if (!spec.matchesDirectory) { + if (lowerPath.endsWith(QLatin1Char('.') + spec.extension.toLower())) + return &spec; + } } return nullptr; } @@ -75,9 +93,12 @@ QStringList FormatRegistry::supportedExtensions() const void FormatRegistry::registerImageProviders(QQmlEngine &engine) const { + QSet<QString> registeredSchemes; for (const FormatSpec &spec : m_specs) { - if (!spec.scheme.isEmpty() && spec.makeSource) + if (!spec.scheme.isEmpty() && spec.makeSource && !registeredSchemes.contains(spec.scheme)) { + registeredSchemes.insert(spec.scheme); engine.addImageProvider(spec.scheme, new EntryImageProvider(spec.makeSource, spec.scheme)); + } } } diff --git a/src/backend/formats/FormatRegistry.h b/src/backend/formats/FormatRegistry.h index 2803024..4bd1f37 100644 --- a/src/backend/formats/FormatRegistry.h +++ b/src/backend/formats/FormatRegistry.h @@ -26,6 +26,7 @@ struct FormatSpec { static FormatSpec comic(const QString &ext, bool matchesDirectory, const QString &scheme, SourceFactory makeSource); static FormatSpec epub(SourceFactory makeSource); + static FormatSpec fb2(const QString &ext, SourceFactory makeSource); }; class FormatRegistry { diff --git a/src/backend/formats/sources/Fb2ByteSource.cpp b/src/backend/formats/sources/Fb2ByteSource.cpp new file mode 100644 index 0000000..dfa5de7 --- /dev/null +++ b/src/backend/formats/sources/Fb2ByteSource.cpp @@ -0,0 +1,192 @@ +#include "Fb2ByteSource.h" + +#include <QFile> +#include <QFileInfo> +#include <QRegularExpression> +#include <QXmlStreamReader> + +#include "backend/formats/sources/ZipByteSource.h" + +namespace { +bool isZipFile(const QString &path) +{ + if (path.endsWith(QLatin1String(".fbz"), Qt::CaseInsensitive) + || path.endsWith(QLatin1String(".fb2.zip"), Qt::CaseInsensitive) + || path.endsWith(QLatin1String(".zip"), Qt::CaseInsensitive)) { + return true; + } + + QFile f(path); + if (f.open(QIODevice::ReadOnly)) { + const QByteArray magic = f.read(4); + if (magic.size() >= 4 && magic[0] == 'P' && magic[1] == 'K' && (magic[2] == 3 || magic[2] == 5 || magic[2] == 7)) + return true; + } + return false; +} + +qsizetype findCaseInsensitive(const QByteArray &haystack, const QByteArray &needle, qsizetype from = 0) +{ + const qsizetype nLen = needle.size(); + const qsizetype hLen = haystack.size(); + if (nLen == 0 || from >= hLen) + return -1; + for (qsizetype i = qMax(qsizetype(0), from); i <= hLen - nLen; ++i) { + bool match = true; + for (qsizetype j = 0; j < nLen; ++j) { + char c1 = haystack[i + j]; + char c2 = needle[j]; + if (c1 >= 'A' && c1 <= 'Z') c1 += 32; + if (c2 >= 'A' && c2 <= 'Z') c2 += 32; + if (c1 != c2) { + match = false; + break; + } + } + if (match) + return i; + } + return -1; +} +} // namespace + +Fb2ByteSource::Fb2ByteSource() = default; +Fb2ByteSource::~Fb2ByteSource() = default; + +bool Fb2ByteSource::open(const QString &path) +{ + m_path = path; + m_error.clear(); + m_binaries.clear(); + m_archiveEntries.clear(); + m_rawXmlData.clear(); + m_hash.clear(); + + if (isZipFile(path)) { + m_containerKind = Fb2ContainerKind::zip_archive; + ZipByteSource zip; + if (!zip.open(path)) { + m_error = QStringLiteral("Cannot open zip archive: ") + path; + return false; + } + + m_archiveEntries = zip.listEntries(); + if (m_archiveEntries.isEmpty()) { + m_error = QStringLiteral("Archive contains no readable FB2 entry"); + return false; + } + + QString fb2Entry; + for (const QString &entry : m_archiveEntries) { + if (entry.endsWith(QLatin1String(".fb2"), Qt::CaseInsensitive)) { + fb2Entry = entry; + break; + } + } + if (fb2Entry.isEmpty()) { + fb2Entry = m_archiveEntries.first(); + } + + m_rawXmlData = zip.readEntry(fb2Entry); + if (m_rawXmlData.isEmpty()) { + m_error = QStringLiteral("Archive contains no readable FB2 entry"); + return false; + } + + m_hash = zip.contentHash(); + } else { + m_containerKind = Fb2ContainerKind::plain_xml; + QFile file(path); + if (!file.open(QIODevice::ReadOnly)) { + m_error = QStringLiteral("Cannot open FB2 file: ") + path; + return false; + } + + m_rawXmlData = file.readAll(); + m_hash = IByteSource::hashFileMd5(path); + } + + extractBinaries(m_rawXmlData); + return true; +} + +QStringList Fb2ByteSource::listEntries() const +{ + return m_binaries.keys(); +} + +QByteArray Fb2ByteSource::readEntry(const QString &entryName) const +{ + QString key = entryName; + if (key.startsWith(QLatin1Char('#'))) + key.remove(0, 1); + + auto it = m_binaries.constFind(key); + if (it != m_binaries.constEnd()) + return it.value().decoded_bytes; + + return {}; +} + +QByteArray Fb2ByteSource::contentHash() const +{ + return m_hash; +} + +void Fb2ByteSource::extractBinaries(const QByteArray &xmlData) +{ + static const QByteArray kBinaryStart("<binary"); + static const QByteArray kBinaryEnd("</binary>"); + + qsizetype pos = 0; + while ((pos = findCaseInsensitive(xmlData, kBinaryStart, pos)) >= 0) { + qsizetype tagEnd = xmlData.indexOf('>', pos + kBinaryStart.size()); + if (tagEnd < 0) + break; + + qsizetype closePos = findCaseInsensitive(xmlData, kBinaryEnd, tagEnd + 1); + if (closePos < 0) + break; + + // Parse attributes from <binary ...> + const QByteArray tagHeader = xmlData.mid(pos, tagEnd - pos + 1); + QXmlStreamReader tagXml(tagHeader + "</binary>"); + QString id; + QString contentType; + if (tagXml.readNextStartElement() && tagXml.name().compare(QLatin1String("binary"), Qt::CaseInsensitive) == 0) { + const auto attrs = tagXml.attributes(); + id = attrs.value(QLatin1String("id")).toString(); + contentType = attrs.value(QLatin1String("content-type")).toString(); + } + + if (id.isEmpty()) { + static const QRegularExpression idRe(QStringLiteral("id\\s*=\\s*[\"']([^\"']+)[\"']"), + QRegularExpression::CaseInsensitiveOption); + static const QRegularExpression ctRe(QStringLiteral("content-type\\s*=\\s*[\"']([^\"']+)[\"']"), + QRegularExpression::CaseInsensitiveOption); + const QString headerStr = QString::fromLatin1(tagHeader); + auto idMatch = idRe.match(headerStr); + if (idMatch.hasMatch()) + id = idMatch.captured(1); + auto ctMatch = ctRe.match(headerStr); + if (ctMatch.hasMatch()) + contentType = ctMatch.captured(1); + } + + if (id.startsWith(QLatin1Char('#'))) + id.remove(0, 1); + + if (!id.isEmpty()) { + const QByteArray base64Bytes = xmlData.mid(tagEnd + 1, closePos - (tagEnd + 1)).trimmed(); + const QByteArray decoded = QByteArray::fromBase64(base64Bytes); + BinaryResource res; + res.id = id; + if (!contentType.isEmpty()) + res.content_type = contentType; + res.decoded_bytes = decoded; + m_binaries.insert(id, res); + } + + pos = closePos + kBinaryEnd.size(); + } +} diff --git a/src/backend/formats/sources/Fb2ByteSource.h b/src/backend/formats/sources/Fb2ByteSource.h new file mode 100644 index 0000000..bd59d4a --- /dev/null +++ b/src/backend/formats/sources/Fb2ByteSource.h @@ -0,0 +1,37 @@ +#pragma once + +#include <QByteArray> +#include <QHash> +#include <QString> +#include <QStringList> + +#include "backend/formats/IByteSource.h" +#include "backend/formats/Fb2Types.h" + +class Fb2ByteSource : public IByteSource { +public: + Fb2ByteSource(); + ~Fb2ByteSource() override; + + bool open(const QString &path) override; + QStringList listEntries() const override; + QByteArray readEntry(const QString &entryName) const override; + QByteArray contentHash() const override; + + const QByteArray &rawXmlData() const { return m_rawXmlData; } + Fb2ContainerKind containerKind() const { return m_containerKind; } + const QStringList &archiveEntries() const { return m_archiveEntries; } + const QHash<QString, BinaryResource> &binaries() const { return m_binaries; } + QString lastError() const { return m_error; } + +private: + void extractBinaries(const QByteArray &xmlData); + + QString m_path; + QByteArray m_hash; + QByteArray m_rawXmlData; + Fb2ContainerKind m_containerKind = Fb2ContainerKind::plain_xml; + QStringList m_archiveEntries; + QHash<QString, BinaryResource> m_binaries; + QString m_error; +}; diff --git a/src/backend/reading/layout/ChunkLayoutEngine.cpp b/src/backend/reading/layout/ChunkLayoutEngine.cpp index 78049ce..1d8374c 100644 --- a/src/backend/reading/layout/ChunkLayoutEngine.cpp +++ b/src/backend/reading/layout/ChunkLayoutEngine.cpp @@ -249,6 +249,9 @@ private: if (p.words.isEmpty() && p.kpItems.isEmpty()) return; + m_curY += m_prevMarginBottom; + m_prevMarginBottom = 0; + QColor enclosingBg; for (int i = m_boxStack.size() - 1; i >= 0; --i) { if (m_boxStack[i].box.background.isValid() && m_boxStack[i].box.background.alpha() > 0) { diff --git a/src/backend/reading/layout/DomChunkPipeline.cpp b/src/backend/reading/layout/DomChunkPipeline.cpp new file mode 100644 index 0000000..255299b --- /dev/null +++ b/src/backend/reading/layout/DomChunkPipeline.cpp @@ -0,0 +1,68 @@ +#include "DomChunkPipeline.h" + +#include <functional> +#include "backend/formats/ImageUrl.h" + +namespace DomChunkPipeline { + +QVector<ContentChunk> cascadeAndChunk(QDomElement &root, + const Css::StyleSheet &sheet, + const QString &scheme, + const QString &sourcePath, + const QString §ionHref, + const QString &baseDir, + int targetChars) +{ + std::function<void(QDomElement &)> processElement = [&](QDomElement &el) { + const auto decls = Css::cascade(sheet, el); + if (!decls.isEmpty()) { + el.setAttribute(QStringLiteral("style"), Css::serialize(decls)); + } + + const QString tag = el.tagName().toLower(); + if (tag == QLatin1String("img") || tag == QLatin1String("image")) { + QString srcAttr; + if (el.hasAttribute(QStringLiteral("src"))) { + srcAttr = QStringLiteral("src"); + } else if (el.hasAttribute(QStringLiteral("xlink:href"))) { + srcAttr = QStringLiteral("xlink:href"); + } else if (el.hasAttribute(QStringLiteral("l:href"))) { + srcAttr = QStringLiteral("l:href"); + } else if (el.hasAttribute(QStringLiteral("href"))) { + srcAttr = QStringLiteral("href"); + } + if (!srcAttr.isEmpty()) { + const QString src = el.attribute(srcAttr); + const QString resolved = ImageUrl::resolve(scheme, src, sourcePath, baseDir); + el.setAttribute(srcAttr, resolved); + } + } + + for (QDomNode child = el.firstChild(); !child.isNull(); child = child.nextSibling()) { + if (child.isElement()) { + QDomElement childEl = child.toElement(); + processElement(childEl); + } + } + }; + + processElement(root); + return HtmlBlockParser::parseChunks(root, sectionHref, targetChars); +} + +QVector<ContentChunk> cascadeAndChunk(QDomElement &root, + const QStringList &stylesheetTexts, + const QString &scheme, + const QString &sourcePath, + const QString §ionHref, + const QString &baseDir, + int targetChars) +{ + Css::StyleSheet combinedSheet; + for (const QString &text : stylesheetTexts) { + combinedSheet.append(Css::StyleSheet::parse(text)); + } + return cascadeAndChunk(root, combinedSheet, scheme, sourcePath, sectionHref, baseDir, targetChars); +} + +} // namespace DomChunkPipeline diff --git a/src/backend/reading/layout/DomChunkPipeline.h b/src/backend/reading/layout/DomChunkPipeline.h new file mode 100644 index 0000000..f042239 --- /dev/null +++ b/src/backend/reading/layout/DomChunkPipeline.h @@ -0,0 +1,29 @@ +#pragma once + +#include <QDomElement> +#include <QString> +#include <QStringList> +#include <QVector> + +#include "backend/reading/layout/HtmlBlockParser.h" +#include "backend/reading/layout/CssParser.h" + +namespace DomChunkPipeline { + +QVector<ContentChunk> cascadeAndChunk(QDomElement &root, + const QStringList &stylesheetTexts, + const QString &scheme, + const QString &sourcePath, + const QString §ionHref, + const QString &baseDir = {}, + int targetChars = 512); + +QVector<ContentChunk> cascadeAndChunk(QDomElement &root, + const Css::StyleSheet &sheet, + const QString &scheme, + const QString &sourcePath, + const QString §ionHref, + const QString &baseDir = {}, + int targetChars = 512); + +} // namespace DomChunkPipeline diff --git a/src/backend/reading/layout/HtmlBlockParser.cpp b/src/backend/reading/layout/HtmlBlockParser.cpp index 6fa5b83..5d79645 100644 --- a/src/backend/reading/layout/HtmlBlockParser.cpp +++ b/src/backend/reading/layout/HtmlBlockParser.cpp @@ -17,6 +17,7 @@ struct StyleContext { qreal textIndent = 0; qreal lineHeight = 0; bool preformatted = false; + bool isHeading = false; }; QString localName(const QDomElement &e) @@ -152,6 +153,28 @@ void applyCssDeclarations(const QVector<Css::Declaration> &decls, auto m = Css::parseLength(val, lenCtx); if (m) box.marginLeft = *m; } else if (prop == QLatin1String("margin-right")) { auto m = Css::parseLength(val, lenCtx); if (m) box.marginRight = *m; + } else if (prop == QLatin1String("margin")) { + const QStringList tokens = Css::splitValue(val); + QVector<qreal> vals; + for (const QString &tok : tokens) { + auto m = Css::parseLength(tok, lenCtx); + if (m) vals.append(*m); + } + if (vals.size() == 1) { + box.marginTop = box.marginRight = box.marginBottom = box.marginLeft = vals[0]; + } else if (vals.size() == 2) { + box.marginTop = box.marginBottom = vals[0]; + box.marginRight = box.marginLeft = vals[1]; + } else if (vals.size() == 3) { + box.marginTop = vals[0]; + box.marginRight = box.marginLeft = vals[1]; + box.marginBottom = vals[2]; + } else if (vals.size() >= 4) { + box.marginTop = vals[0]; + box.marginRight = vals[1]; + box.marginBottom = vals[2]; + box.marginLeft = vals[3]; + } } else if (prop == QLatin1String("padding-top")) { auto p = Css::parseLength(val, lenCtx); if (p) box.paddingTop = *p; } else if (prop == QLatin1String("padding-bottom")) { @@ -160,6 +183,28 @@ void applyCssDeclarations(const QVector<Css::Declaration> &decls, auto p = Css::parseLength(val, lenCtx); if (p) box.paddingLeft = *p; } else if (prop == QLatin1String("padding-right")) { auto p = Css::parseLength(val, lenCtx); if (p) box.paddingRight = *p; + } else if (prop == QLatin1String("padding")) { + const QStringList tokens = Css::splitValue(val); + QVector<qreal> vals; + for (const QString &tok : tokens) { + auto p = Css::parseLength(tok, lenCtx); + if (p) vals.append(*p); + } + if (vals.size() == 1) { + box.paddingTop = box.paddingRight = box.paddingBottom = box.paddingLeft = vals[0]; + } else if (vals.size() == 2) { + box.paddingTop = box.paddingBottom = vals[0]; + box.paddingRight = box.paddingLeft = vals[1]; + } else if (vals.size() == 3) { + box.paddingTop = vals[0]; + box.paddingRight = box.paddingLeft = vals[1]; + box.paddingBottom = vals[2]; + } else if (vals.size() >= 4) { + box.paddingTop = vals[0]; + box.paddingRight = vals[1]; + box.paddingBottom = vals[2]; + box.paddingLeft = vals[3]; + } } else if (prop == QLatin1String("border")) { auto b = Css::parseBorderSide(val, lenCtx); if (b.width) { @@ -374,30 +419,42 @@ private: ctx.text.fontSize = m_params.baseFontSize * 1.8; ctx.text.weight = 700; ctx.textIndent = 0; + ctx.align = TextAlign::Left; + ctx.isHeading = true; box.marginTop = m_params.baseFontSize * 1.0; box.marginBottom = m_params.baseFontSize * 0.5; } else if (tag == QLatin1String("h2")) { ctx.text.fontSize = m_params.baseFontSize * 1.5; ctx.text.weight = 700; ctx.textIndent = 0; + ctx.align = TextAlign::Left; + ctx.isHeading = true; box.marginTop = m_params.baseFontSize * 0.8; box.marginBottom = m_params.baseFontSize * 0.4; } else if (tag == QLatin1String("h3")) { ctx.text.fontSize = m_params.baseFontSize * 1.3; ctx.text.weight = 700; ctx.textIndent = 0; + ctx.align = TextAlign::Left; + ctx.isHeading = true; box.marginTop = m_params.baseFontSize * 0.6; box.marginBottom = m_params.baseFontSize * 0.3; } else if (tag == QLatin1String("h4") || tag == QLatin1String("h5") || tag == QLatin1String("h6")) { ctx.text.fontSize = m_params.baseFontSize * 1.1; ctx.text.weight = 700; ctx.textIndent = 0; + ctx.align = TextAlign::Left; + ctx.isHeading = true; box.marginTop = m_params.baseFontSize * 0.5; box.marginBottom = m_params.baseFontSize * 0.25; } else if (tag == QLatin1String("p")) { - box.marginTop = m_params.baseFontSize * 0.25; - box.marginBottom = m_params.baseFontSize * 0.5; - ctx.textIndent = m_params.baseFontSize * 1.25; + box.marginTop = 0; + box.marginBottom = 0; + if (!ctx.isHeading) { + ctx.textIndent = m_params.baseFontSize * 2.0; + } else { + ctx.textIndent = 0; + } } else if (tag == QLatin1String("blockquote")) { box.marginLeft = m_params.baseFontSize * 1.5; box.marginRight = m_params.baseFontSize * 1.0; diff --git a/src/main.cpp b/src/main.cpp index d318834..f6cb473 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -15,6 +15,7 @@ #include "backend/formats/FormatRegistry.h" #include "backend/formats/WebImageProvider.h" #include "backend/formats/sources/DirByteSource.h" +#include "backend/formats/sources/Fb2ByteSource.h" #include "backend/formats/sources/RarByteSource.h" #include "backend/formats/sources/ZipByteSource.h" #include "backend/HistoryModel.h" @@ -102,6 +103,9 @@ int main(int argc, char *argv[]) FormatSpec::comic({}, /*matchesDirectory=*/true, QStringLiteral("dir"), [] { return std::make_unique<DirByteSource>(); }), FormatSpec::epub([] { return std::make_unique<ZipByteSource>(); }), + FormatSpec::fb2(QStringLiteral("fb2"), [] { return std::make_unique<Fb2ByteSource>(); }), + FormatSpec::fb2(QStringLiteral("fbz"), [] { return std::make_unique<Fb2ByteSource>(); }), + FormatSpec::fb2(QStringLiteral("fb2.zip"), [] { return std::make_unique<Fb2ByteSource>(); }), }); HistoryModel historyModel(formatRegistry); diff --git a/tests/formats/Fb2ReaderTest.cpp b/tests/formats/Fb2ReaderTest.cpp new file mode 100644 index 0000000..09d3090 --- /dev/null +++ b/tests/formats/Fb2ReaderTest.cpp @@ -0,0 +1,1184 @@ +#include <QtTest> +#include <QTemporaryDir> +#include <QFile> +#include <QDomDocument> +#include <minizip/zip.h> + +#include "backend/formats/Fb2Reader.h" +#include "backend/formats/EpubReader.h" +#include "backend/formats/sources/ZipByteSource.h" +#include "backend/formats/Fb2Types.h" +#include "backend/formats/sources/Fb2ByteSource.h" +#include "backend/formats/ImageUrl.h" +#include "backend/reading/layout/DomChunkPipeline.h" +#include "backend/reading/layout/HtmlBlockParser.h" +#include "backend/reading/layout/ChunkLayoutEngine.h" + +// Spec Entities and Surface +struct ReaderClient { + QString name; + bool operator==(const ReaderClient &o) const { return name == o.name; } +}; + +struct Fb2BookEntity { + ReaderClient client; + QString file_path; + QString extension_kind; // "fb2", "fbz", "fb2.zip" + Fb2ContainerKind container_kind = Fb2ContainerKind::plain_xml; + HistoryFormatLabel format_label = HistoryFormatLabel::FB2; + Fb2LoadStatus status = Fb2LoadStatus::idle; + + // Loaded fields + std::optional<QString> content_hash; + std::optional<QString> title; + std::optional<QVector<AuthorName>> authors; + std::optional<QString> author; + std::optional<QString> cover_image_url; + std::optional<QVector<ContentChunkValue>> chunks; + std::optional<QVector<BinaryResource>> binaries; + + // Failed field + std::optional<QString> error_message; + + HistoryFormatLabel expected_format_label() const + { + if (extension_kind == QLatin1String("fbz")) + return HistoryFormatLabel::FBZ; + return HistoryFormatLabel::FB2; + } +}; + +class Fb2FormatReaderSurface { +public: + ReaderClient client; + Fb2BookEntity book; + + bool is_actor_accessible(const ReaderClient &actor) const + { + return actor.name == client.name; + } + + bool can_provide_OpenFb2Requested() const + { + return book.status == Fb2LoadStatus::idle; + } + + bool can_provide_LoadFb2MetadataRequested() const + { + return book.status == Fb2LoadStatus::idle; + } + + bool can_provide_InspectZipArchive() const + { + return (book.status == Fb2LoadStatus::loading_metadata || book.status == Fb2LoadStatus::loading_full) + && book.container_kind == Fb2ContainerKind::zip_archive; + } + + bool can_provide_Fb2XmlParsed() const + { + return book.status == Fb2LoadStatus::loading_metadata || book.status == Fb2LoadStatus::loading_full; + } + + bool can_provide_Fb2MetadataExtracted() const + { + return book.status == Fb2LoadStatus::loading_metadata; + } + + bool can_provide_Fb2DocumentParsed() const + { + return book.status == Fb2LoadStatus::loading_full; + } + + // Rules + bool startOpenFb2Book(const ReaderClient &actor) + { + if (actor.name != client.name || book.status != Fb2LoadStatus::idle) + return false; + book.status = Fb2LoadStatus::loading_full; + return true; + } + + bool startLoadFb2Metadata(const ReaderClient &actor) + { + if (actor.name != client.name || book.status != Fb2LoadStatus::idle) + return false; + book.status = Fb2LoadStatus::loading_metadata; + return true; + } + + bool resolveZipContainerEntry(const ReaderClient &actor, const QStringList &archive_entries) + { + if (actor.name != client.name) + return false; + if (book.status != Fb2LoadStatus::loading_metadata && book.status != Fb2LoadStatus::loading_full) + return false; + if (book.container_kind != Fb2ContainerKind::zip_archive) + return false; + if (!archive_entries.isEmpty()) + return false; + + book.status = Fb2LoadStatus::failed; + book.error_message = QStringLiteral("Archive contains no readable FB2 entry"); + return true; + } + + bool failOnInvalidOrMalformedXml(const ReaderClient &actor, bool is_well_formed_xml, const QString &root_tag_name) + { + if (actor.name != client.name) + return false; + if (book.status != Fb2LoadStatus::loading_metadata && book.status != Fb2LoadStatus::loading_full) + return false; + if (is_well_formed_xml && root_tag_name == QLatin1String("FictionBook")) + return false; + + book.status = Fb2LoadStatus::failed; + book.error_message = QStringLiteral("Invalid or malformed FictionBook XML"); + return true; + } + + bool completeMetadataLoad(const ReaderClient &actor, + const QString &hash_md5, + const QString &raw_book_title, + const QString &filename_stem, + const QVector<AuthorName> &parsed_authors, + const QString &formatted_authors, + const std::optional<QString> &resolved_cover_id, + const QVector<BinaryResource> &binary_resources) + { + if (actor.name != client.name || book.status != Fb2LoadStatus::loading_metadata) + return false; + + book.status = Fb2LoadStatus::loaded; + book.content_hash = hash_md5; + book.title = !raw_book_title.isEmpty() ? raw_book_title : filename_stem; + book.authors = parsed_authors; + book.author = formatted_authors; + if (resolved_cover_id.has_value()) { + book.cover_image_url = ImageUrl::build(QStringLiteral("fb2"), resolved_cover_id.value(), book.file_path); + } else { + book.cover_image_url = std::nullopt; + } + book.chunks = QVector<ContentChunkValue>{}; + book.binaries = binary_resources; + return true; + } + + bool completeFullOpenWithSections(const ReaderClient &actor, + const QString &hash_md5, + const QString &raw_book_title, + const QString &filename_stem, + const QVector<AuthorName> &parsed_authors, + const QString &formatted_authors, + const std::optional<QString> &resolved_cover_id, + const QVector<BinaryResource> &binary_resources, + const QVector<ContentChunkValue> &extracted_chunks) + { + if (actor.name != client.name || book.status != Fb2LoadStatus::loading_full || extracted_chunks.isEmpty()) + return false; + + book.status = Fb2LoadStatus::loaded; + book.content_hash = hash_md5; + book.title = !raw_book_title.isEmpty() ? raw_book_title : filename_stem; + book.authors = parsed_authors; + book.author = formatted_authors; + if (resolved_cover_id.has_value()) { + book.cover_image_url = ImageUrl::build(QStringLiteral("fb2"), resolved_cover_id.value(), book.file_path); + } else { + book.cover_image_url = std::nullopt; + } + book.chunks = extracted_chunks; + book.binaries = binary_resources; + return true; + } + + bool completeFullOpenWithEmptyBodyFallback(const ReaderClient &actor, + const QString &hash_md5, + const QString &raw_book_title, + const QString &filename_stem, + const QVector<AuthorName> &parsed_authors, + const QString &formatted_authors, + const std::optional<QString> &resolved_cover_id, + const QVector<BinaryResource> &binary_resources, + const QVector<ContentChunkValue> &extracted_chunks) + { + if (actor.name != client.name || book.status != Fb2LoadStatus::loading_full || !extracted_chunks.isEmpty()) + return false; + + book.status = Fb2LoadStatus::loaded; + book.content_hash = hash_md5; + book.title = !raw_book_title.isEmpty() ? raw_book_title : filename_stem; + book.authors = parsed_authors; + book.author = formatted_authors; + if (resolved_cover_id.has_value()) { + book.cover_image_url = ImageUrl::build(QStringLiteral("fb2"), resolved_cover_id.value(), book.file_path); + } else { + book.cover_image_url = std::nullopt; + } + ContentChunkValue fallbackChunk{book.file_path, 1, 0, 0, 0}; + book.chunks = QVector<ContentChunkValue>{fallbackChunk}; + book.binaries = binary_resources; + return true; + } +}; + +static bool createZipArchive(const QString &zipPath, const QHash<QString, QByteArray> &entries) +{ + zipFile zf = zipOpen64(zipPath.toUtf8().constData(), APPEND_STATUS_CREATE); + if (!zf) return false; + + for (auto it = entries.constBegin(); it != entries.constEnd(); ++it) { + zip_fileinfo zi{}; + int err = zipOpenNewFileInZip(zf, it.key().toUtf8().constData(), &zi, nullptr, 0, nullptr, 0, nullptr, Z_DEFLATED, Z_DEFAULT_COMPRESSION); + if (err != ZIP_OK) { + zipClose(zf, nullptr); + return false; + } + err = zipWriteInFileInZip(zf, it.value().constData(), it.value().size()); + zipCloseFileInZip(zf); + if (err < 0) { + zipClose(zf, nullptr); + return false; + } + } + zipClose(zf, nullptr); + return true; +} + +class Fb2ReaderTest : public QObject { + Q_OBJECT + +private slots: + // Obligation 1: value-equality.AuthorName + void testValueEqualityAuthorName() + { + AuthorName a1{QStringLiteral("Leo"), QStringLiteral("N."), QStringLiteral("Tolstoy"), std::nullopt}; + AuthorName a2{QStringLiteral("Leo"), QStringLiteral("N."), QStringLiteral("Tolstoy"), std::nullopt}; + AuthorName aDiffFirst{QStringLiteral("Alex"), QStringLiteral("N."), QStringLiteral("Tolstoy"), std::nullopt}; + AuthorName aDiffNick{QStringLiteral("Leo"), QStringLiteral("N."), QStringLiteral("Tolstoy"), QStringLiteral("LN")}; + + QVERIFY(a1 == a2); + QVERIFY(!(a1 != a2)); + QVERIFY(a1 != aDiffFirst); + QVERIFY(a1 != aDiffNick); + } + + // Obligation 2: entity-fields.AuthorName + void testEntityFieldsAuthorName() + { + AuthorName a; + QVERIFY(!a.first_name.has_value()); + QVERIFY(!a.middle_name.has_value()); + QVERIFY(!a.last_name.has_value()); + QVERIFY(!a.nickname.has_value()); + QVERIFY(!a.has_structured_name()); + + a.first_name = QStringLiteral("Fyodor"); + a.middle_name = QStringLiteral("Mikhailovich"); + a.last_name = QStringLiteral("Dostoevsky"); + a.nickname = QStringLiteral("FD"); + + QCOMPARE(a.first_name.value(), QStringLiteral("Fyodor")); + QCOMPARE(a.middle_name.value(), QStringLiteral("Mikhailovich")); + QCOMPARE(a.last_name.value(), QStringLiteral("Dostoevsky")); + QCOMPARE(a.nickname.value(), QStringLiteral("FD")); + QVERIFY(a.has_structured_name()); + + AuthorName nickOnly{std::nullopt, std::nullopt, std::nullopt, QStringLiteral("Strugatsky")}; + QVERIFY(!nickOnly.has_structured_name()); + QCOMPARE(nickOnly.format(), QStringLiteral("Strugatsky")); + } + + // Obligation 3: value-equality.BinaryResource + void testValueEqualityBinaryResource() + { + BinaryResource b1{QStringLiteral("cover.jpg"), QStringLiteral("image/jpeg"), QByteArray("bytes123")}; + BinaryResource b2{QStringLiteral("cover.jpg"), QStringLiteral("image/jpeg"), QByteArray("bytes123")}; + BinaryResource bDiffId{QStringLiteral("pic.png"), QStringLiteral("image/jpeg"), QByteArray("bytes123")}; + BinaryResource bDiffType{QStringLiteral("cover.jpg"), QStringLiteral("image/png"), QByteArray("bytes123")}; + BinaryResource bDiffData{QStringLiteral("cover.jpg"), QStringLiteral("image/jpeg"), QByteArray("other")}; + + QVERIFY(b1 == b2); + QVERIFY(!(b1 != b2)); + QVERIFY(b1 != bDiffId); + QVERIFY(b1 != bDiffType); + QVERIFY(b1 != bDiffData); + } + + // Obligation 4: entity-fields.BinaryResource + void testEntityFieldsBinaryResource() + { + BinaryResource b; + QVERIFY(b.id.isEmpty()); + QVERIFY(!b.content_type.has_value()); + QVERIFY(b.decoded_bytes.isEmpty()); + + b.id = QStringLiteral("img1"); + b.content_type = QStringLiteral("image/png"); + b.decoded_bytes = QByteArray("pngdata"); + + QCOMPARE(b.id, QStringLiteral("img1")); + QCOMPARE(b.content_type.value(), QStringLiteral("image/png")); + QCOMPARE(b.decoded_bytes, QByteArray("pngdata")); + } + + // Obligation 5: value-equality.ContentChunkValue + void testValueEqualityContentChunkValue() + { + ContentChunkValue c1{QStringLiteral("sec1"), 5, 100, 500, 2}; + ContentChunkValue c2{QStringLiteral("sec1"), 5, 100, 500, 2}; + ContentChunkValue cDiffHref{QStringLiteral("sec2"), 5, 100, 500, 2}; + ContentChunkValue cDiffBlocks{QStringLiteral("sec1"), 6, 100, 500, 2}; + ContentChunkValue cDiffWords{QStringLiteral("sec1"), 5, 101, 500, 2}; + ContentChunkValue cDiffChars{QStringLiteral("sec1"), 5, 100, 501, 2}; + ContentChunkValue cDiffContainers{QStringLiteral("sec1"), 5, 100, 500, 3}; + + QVERIFY(c1 == c2); + QVERIFY(!(c1 != c2)); + QVERIFY(c1 != cDiffHref); + QVERIFY(c1 != cDiffBlocks); + QVERIFY(c1 != cDiffWords); + QVERIFY(c1 != cDiffChars); + QVERIFY(c1 != cDiffContainers); + } + + // Obligation 6: entity-fields.ContentChunkValue + void testEntityFieldsContentChunkValue() + { + ContentChunkValue c; + QVERIFY(c.section_href.isEmpty()); + QCOMPARE(c.blocks_count, 0); + QCOMPARE(c.word_count, 0); + QCOMPARE(c.char_count, 0); + QCOMPARE(c.unnested_containers, 0); + + c.section_href = QStringLiteral("body/s0"); + c.blocks_count = 3; + c.word_count = 50; + c.char_count = 250; + c.unnested_containers = 1; + + QCOMPARE(c.section_href, QStringLiteral("body/s0")); + QCOMPARE(c.blocks_count, 3); + QCOMPARE(c.word_count, 50); + QCOMPARE(c.char_count, 250); + QCOMPARE(c.unnested_containers, 1); + } + + // Obligation 7: contract-signature.SharedDomChunkPipeline.cascade_and_chunk + void testContractSignatureSharedDomChunkPipeline() + { + // Verify cascade_and_chunk signature and invariant DeterministicChunking + QDomDocument doc1; + doc1.setContent(QStringLiteral("<div><p class=\"lead\">Paragraph in EPUB spine</p></div>")); + QDomElement root1 = doc1.documentElement(); + + QDomDocument doc2; + doc2.setContent(QStringLiteral("<div><p class=\"lead\">Paragraph in EPUB spine</p></div>")); + QDomElement root2 = doc2.documentElement(); + + QStringList stylesheets = {QStringLiteral("p.lead { font-weight: bold; text-align: center; }")}; + const QString scheme = QStringLiteral("fb2"); + const QString sourcePath = QStringLiteral("/books/test.fb2"); + const QString sectionHref = QStringLiteral("sec1"); + const int targetChars = 512; + + QVector<ContentChunk> chunks1 = DomChunkPipeline::cascadeAndChunk( + root1, stylesheets, scheme, sourcePath, sectionHref, QString(), targetChars); + QVector<ContentChunk> chunks2 = DomChunkPipeline::cascadeAndChunk( + root2, stylesheets, scheme, sourcePath, sectionHref, QString(), targetChars); + + QCOMPARE(chunks1.size(), chunks2.size()); + QVERIFY(!chunks1.isEmpty()); + QCOMPARE(chunks1.first().sectionHref, chunks2.first().sectionHref); + QCOMPARE(chunks1.first().wordCount, chunks2.first().wordCount); + QCOMPARE(chunks1.first().charCount, chunks2.first().charCount); + QCOMPARE(chunks1.first().blocks.size(), chunks2.first().blocks.size()); + + ContentChunkValue cv1 = ContentChunkValue::fromChunk(chunks1.first()); + ContentChunkValue cv2 = ContentChunkValue::fromChunk(chunks2.first()); + QCOMPARE(cv1, cv2); + } + + // Obligation 8: enum-comparable.Fb2ContainerKind + void testEnumComparableFb2ContainerKind() + { + Fb2ContainerKind k1 = Fb2ContainerKind::plain_xml; + Fb2ContainerKind k2 = Fb2ContainerKind::zip_archive; + QVERIFY(k1 != k2); + QVERIFY(k1 == Fb2ContainerKind::plain_xml); + } + + // Obligation 9: enum-comparable.Fb2LoadStatus + void testEnumComparableFb2LoadStatus() + { + Fb2LoadStatus s1 = Fb2LoadStatus::idle; + Fb2LoadStatus s2 = Fb2LoadStatus::loading_metadata; + Fb2LoadStatus s3 = Fb2LoadStatus::loading_full; + Fb2LoadStatus s4 = Fb2LoadStatus::loaded; + Fb2LoadStatus s5 = Fb2LoadStatus::failed; + + QVERIFY(s1 != s2 && s2 != s3 && s3 != s4 && s4 != s5); + QVERIFY(s1 == Fb2LoadStatus::idle); + } + + // Obligation 10: enum-comparable.HistoryFormatLabel + void testEnumComparableHistoryFormatLabel() + { + HistoryFormatLabel l1 = HistoryFormatLabel::FB2; + HistoryFormatLabel l2 = HistoryFormatLabel::FBZ; + QVERIFY(l1 != l2); + QVERIFY(l1 == HistoryFormatLabel::FB2); + } + + // Obligation 11: entity-fields.ReaderClient + void testEntityFieldsReaderClient() + { + ReaderClient client; + QVERIFY(client.name.isEmpty()); + client.name = QStringLiteral("AsteriaReader"); + QCOMPARE(client.name, QStringLiteral("AsteriaReader")); + } + + // Obligations 12-19: when-presence.Fb2Book.* + void testWhenPresenceFields() + { + Fb2BookEntity book; + book.status = Fb2LoadStatus::idle; + + // When idle, loaded & failed fields are absent + QVERIFY(!book.content_hash.has_value()); + QVERIFY(!book.title.has_value()); + QVERIFY(!book.authors.has_value()); + QVERIFY(!book.author.has_value()); + QVERIFY(!book.cover_image_url.has_value()); + QVERIFY(!book.chunks.has_value()); + QVERIFY(!book.binaries.has_value()); + QVERIFY(!book.error_message.has_value()); + + // When loaded, loaded fields are present, error_message is absent + book.status = Fb2LoadStatus::loaded; + book.content_hash = QStringLiteral("hash123"); + book.title = QStringLiteral("War and Peace"); + book.authors = QVector<AuthorName>{}; + book.author = QStringLiteral("Leo Tolstoy"); + book.cover_image_url = QStringLiteral("image://fb2/cover.jpg"); + book.chunks = QVector<ContentChunkValue>{}; + book.binaries = QVector<BinaryResource>{}; + + QVERIFY(book.content_hash.has_value()); + QVERIFY(book.title.has_value()); + QVERIFY(book.authors.has_value()); + QVERIFY(book.author.has_value()); + QVERIFY(book.cover_image_url.has_value()); + QVERIFY(book.chunks.has_value()); + QVERIFY(book.binaries.has_value()); + QVERIFY(!book.error_message.has_value()); + + // When failed, error_message is present, loaded fields absent + Fb2BookEntity failedBook; + failedBook.status = Fb2LoadStatus::failed; + failedBook.error_message = QStringLiteral("Error loading book"); + + QVERIFY(failedBook.error_message.has_value()); + QVERIFY(!failedBook.content_hash.has_value()); + QVERIFY(!failedBook.title.has_value()); + QVERIFY(!failedBook.chunks.has_value()); + } + + // Obligations 20-25: transition-edge.Fb2Book.* + void testTransitionEdges() + { + ReaderClient client{QStringLiteral("Client1")}; + + // Edge 1: idle -> loading_metadata + { + Fb2FormatReaderSurface s; + s.client = client; + s.book.client = client; + s.book.status = Fb2LoadStatus::idle; + QVERIFY(s.startLoadFb2Metadata(client)); + QCOMPARE(s.book.status, Fb2LoadStatus::loading_metadata); + + // Edge 3: loading_metadata -> loaded + QVERIFY(s.completeMetadataLoad(client, "hash", "Title", "stem", {}, "Author", std::nullopt, {})); + QCOMPARE(s.book.status, Fb2LoadStatus::loaded); + } + + // Edge 4: loading_metadata -> failed + { + Fb2FormatReaderSurface s; + s.client = client; + s.book.client = client; + s.book.status = Fb2LoadStatus::loading_metadata; + QVERIFY(s.failOnInvalidOrMalformedXml(client, false, QStringLiteral("corrupt"))); + QCOMPARE(s.book.status, Fb2LoadStatus::failed); + } + + // Edge 2: idle -> loading_full + { + Fb2FormatReaderSurface s; + s.client = client; + s.book.client = client; + s.book.status = Fb2LoadStatus::idle; + QVERIFY(s.startOpenFb2Book(client)); + QCOMPARE(s.book.status, Fb2LoadStatus::loading_full); + + // Edge 5: loading_full -> loaded + ContentChunkValue chunk{"sec1", 1, 10, 50, 0}; + QVERIFY(s.completeFullOpenWithSections(client, "hash", "Title", "stem", {}, "Author", std::nullopt, {}, {chunk})); + QCOMPARE(s.book.status, Fb2LoadStatus::loaded); + } + + // Edge 6: loading_full -> failed + { + Fb2FormatReaderSurface s; + s.client = client; + s.book.client = client; + s.book.status = Fb2LoadStatus::loading_full; + s.book.container_kind = Fb2ContainerKind::zip_archive; + QVERIFY(s.resolveZipContainerEntry(client, {})); + QCOMPARE(s.book.status, Fb2LoadStatus::failed); + } + } + + // Obligations 26-27: transition-rejected.Fb2Book.status & transition-terminal + void testTransitionRejectedAndTerminal() + { + ReaderClient client{QStringLiteral("Client1")}; + Fb2FormatReaderSurface s; + s.client = client; + s.book.client = client; + + // Terminal state 'loaded' has no outbound transitions + s.book.status = Fb2LoadStatus::loaded; + QVERIFY(!s.startOpenFb2Book(client)); + QVERIFY(!s.startLoadFb2Metadata(client)); + QVERIFY(!s.can_provide_OpenFb2Requested()); + QVERIFY(!s.can_provide_LoadFb2MetadataRequested()); + + // Terminal state 'failed' has no outbound transitions + s.book.status = Fb2LoadStatus::failed; + QVERIFY(!s.startOpenFb2Book(client)); + QVERIFY(!s.startLoadFb2Metadata(client)); + QVERIFY(!s.can_provide_OpenFb2Requested()); + QVERIFY(!s.can_provide_LoadFb2MetadataRequested()); + + // Undeclared transition: loading_metadata directly to loading_full is rejected + s.book.status = Fb2LoadStatus::loading_metadata; + QVERIFY(!s.startOpenFb2Book(client)); + } + + // Obligation 28 & 29: entity-fields.Fb2Book & entity-optional.Fb2Book.cover_image_url + void testEntityFieldsFb2Book() + { + ReaderClient client{QStringLiteral("TestApp")}; + Fb2BookEntity b; + b.client = client; + b.file_path = QStringLiteral("/path/to/doc.fb2"); + b.extension_kind = QStringLiteral("fb2"); + b.container_kind = Fb2ContainerKind::plain_xml; + b.format_label = HistoryFormatLabel::FB2; + b.status = Fb2LoadStatus::idle; + + QCOMPARE(b.client.name, QStringLiteral("TestApp")); + QCOMPARE(b.file_path, QStringLiteral("/path/to/doc.fb2")); + QCOMPARE(b.extension_kind, QStringLiteral("fb2")); + QCOMPARE(b.container_kind, Fb2ContainerKind::plain_xml); + QCOMPARE(b.format_label, HistoryFormatLabel::FB2); + QCOMPARE(b.status, Fb2LoadStatus::idle); + + // Optional cover_image_url + QVERIFY(!b.cover_image_url.has_value()); + b.cover_image_url = QStringLiteral("image://fb2/cov.png?src=/path/to/doc.fb2"); + QVERIFY(b.cover_image_url.has_value()); + b.cover_image_url = std::nullopt; + QVERIFY(!b.cover_image_url.has_value()); + } + + // Obligations 30-31: config-default.target_chunk_chars & max_heading_depth + void testConfigDefaults() + { + const int target_chunk_chars = 512; + const int max_heading_depth = 6; + QCOMPARE(target_chunk_chars, 512); + QCOMPARE(max_heading_depth, 6); + } + + // Obligations 32-34: rule-success/failure.StartOpenFb2Book + void testRuleStartOpenFb2Book() + { + ReaderClient c1{QStringLiteral("User")}; + ReaderClient c2{QStringLiteral("Other")}; + Fb2FormatReaderSurface s; + s.client = c1; + s.book.client = c1; + s.book.status = Fb2LoadStatus::idle; + + // Failure 1: actor != client + QVERIFY(!s.startOpenFb2Book(c2)); + + // Failure 2: status != idle + s.book.status = Fb2LoadStatus::loading_full; + QVERIFY(!s.startOpenFb2Book(c1)); + + // Success + s.book.status = Fb2LoadStatus::idle; + QVERIFY(s.startOpenFb2Book(c1)); + QCOMPARE(s.book.status, Fb2LoadStatus::loading_full); + } + + // Obligations 35-37: rule-success/failure.StartLoadFb2Metadata + void testRuleStartLoadFb2Metadata() + { + ReaderClient c1{QStringLiteral("User")}; + ReaderClient c2{QStringLiteral("Other")}; + Fb2FormatReaderSurface s; + s.client = c1; + s.book.client = c1; + s.book.status = Fb2LoadStatus::idle; + + // Failure 1: actor != client + QVERIFY(!s.startLoadFb2Metadata(c2)); + + // Failure 2: status != idle + s.book.status = Fb2LoadStatus::loaded; + QVERIFY(!s.startLoadFb2Metadata(c1)); + + // Success + s.book.status = Fb2LoadStatus::idle; + QVERIFY(s.startLoadFb2Metadata(c1)); + QCOMPARE(s.book.status, Fb2LoadStatus::loading_metadata); + } + + // Obligations 38-42: rule-success/failure.ResolveZipContainerEntry + void testRuleResolveZipContainerEntry() + { + ReaderClient c1{QStringLiteral("User")}; + ReaderClient c2{QStringLiteral("Other")}; + Fb2FormatReaderSurface s; + s.client = c1; + s.book.client = c1; + s.book.status = Fb2LoadStatus::loading_full; + s.book.container_kind = Fb2ContainerKind::zip_archive; + + // Failure 1: actor != client + QVERIFY(!s.resolveZipContainerEntry(c2, {})); + + // Failure 2: status not in {loading_metadata, loading_full} + s.book.status = Fb2LoadStatus::idle; + QVERIFY(!s.resolveZipContainerEntry(c1, {})); + s.book.status = Fb2LoadStatus::loading_full; + + // Failure 3: container_kind != zip_archive + s.book.container_kind = Fb2ContainerKind::plain_xml; + QVERIFY(!s.resolveZipContainerEntry(c1, {})); + s.book.container_kind = Fb2ContainerKind::zip_archive; + + // Failure 4: archive_entries.count != 0 (entries present) + QVERIFY(!s.resolveZipContainerEntry(c1, {QStringLiteral("book.fb2")})); + + // Success: archive_entries is empty -> fails with specified error + QVERIFY(s.resolveZipContainerEntry(c1, {})); + QCOMPARE(s.book.status, Fb2LoadStatus::failed); + QCOMPARE(s.book.error_message.value(), QStringLiteral("Archive contains no readable FB2 entry")); + } + + // Obligations 43-46: rule-success/failure.FailOnInvalidOrMalformedXml + void testRuleFailOnInvalidOrMalformedXml() + { + ReaderClient c1{QStringLiteral("User")}; + ReaderClient c2{QStringLiteral("Other")}; + Fb2FormatReaderSurface s; + s.client = c1; + s.book.client = c1; + s.book.status = Fb2LoadStatus::loading_full; + + // Failure 1: actor != client + QVERIFY(!s.failOnInvalidOrMalformedXml(c2, false, "")); + + // Failure 2: status not in {loading_metadata, loading_full} + s.book.status = Fb2LoadStatus::idle; + QVERIFY(!s.failOnInvalidOrMalformedXml(c1, false, "")); + s.book.status = Fb2LoadStatus::loading_full; + + // Failure 3: well formed and root is FictionBook -> rule does not fire + QVERIFY(!s.failOnInvalidOrMalformedXml(c1, true, QStringLiteral("FictionBook"))); + + // Success 1: malformed XML + QVERIFY(s.failOnInvalidOrMalformedXml(c1, false, "")); + QCOMPARE(s.book.status, Fb2LoadStatus::failed); + QCOMPARE(s.book.error_message.value(), QStringLiteral("Invalid or malformed FictionBook XML")); + + // Success 2: well formed but root is not FictionBook + s.book.status = Fb2LoadStatus::loading_full; + QVERIFY(s.failOnInvalidOrMalformedXml(c1, true, QStringLiteral("html"))); + QCOMPARE(s.book.status, Fb2LoadStatus::failed); + QCOMPARE(s.book.error_message.value(), QStringLiteral("Invalid or malformed FictionBook XML")); + } + + // Obligations 47-49: rule-success/failure.CompleteMetadataLoad + void testRuleCompleteMetadataLoad() + { + ReaderClient c1{QStringLiteral("User")}; + ReaderClient c2{QStringLiteral("Other")}; + Fb2FormatReaderSurface s; + s.client = c1; + s.book.client = c1; + s.book.file_path = QStringLiteral("/books/novel.fb2"); + s.book.status = Fb2LoadStatus::loading_metadata; + + // Failure 1: actor != client + QVERIFY(!s.completeMetadataLoad(c2, "hash", "Title", "novel", {}, "", std::nullopt, {})); + + // Failure 2: status != loading_metadata + s.book.status = Fb2LoadStatus::idle; + QVERIFY(!s.completeMetadataLoad(c1, "hash", "Title", "novel", {}, "", std::nullopt, {})); + + // Success + s.book.status = Fb2LoadStatus::loading_metadata; + QVERIFY(s.completeMetadataLoad(c1, "hash123", "", "novel", {}, "A. Author", QStringLiteral("cover.jpg"), {})); + QCOMPARE(s.book.status, Fb2LoadStatus::loaded); + QCOMPARE(s.book.title.value(), QStringLiteral("novel")); // title fallback to filename stem + QVERIFY(s.book.chunks.value().isEmpty()); // chunks empty on metadata load + QCOMPARE(s.book.cover_image_url.value(), QStringLiteral("image://fb2/cover.jpg?src=%2Fbooks%2Fnovel.fb2")); + } + + // Obligations 50-53: rule-success/failure.CompleteFullOpenWithSections + void testRuleCompleteFullOpenWithSections() + { + ReaderClient c1{QStringLiteral("User")}; + ReaderClient c2{QStringLiteral("Other")}; + Fb2FormatReaderSurface s; + s.client = c1; + s.book.client = c1; + s.book.file_path = QStringLiteral("/books/novel.fb2"); + s.book.status = Fb2LoadStatus::loading_full; + + ContentChunkValue chunk{"sec1", 2, 20, 100, 0}; + + // Failure 1: actor != client + QVERIFY(!s.completeFullOpenWithSections(c2, "hash", "Title", "stem", {}, "", std::nullopt, {}, {chunk})); + + // Failure 2: status != loading_full + s.book.status = Fb2LoadStatus::loading_metadata; + QVERIFY(!s.completeFullOpenWithSections(c1, "hash", "Title", "stem", {}, "", std::nullopt, {}, {chunk})); + s.book.status = Fb2LoadStatus::loading_full; + + // Failure 3: extracted_chunks.count == 0 + QVERIFY(!s.completeFullOpenWithSections(c1, "hash", "Title", "stem", {}, "", std::nullopt, {}, {})); + + // Success + QVERIFY(s.completeFullOpenWithSections(c1, "hash999", "My Novel", "novel", {}, "Author", QStringLiteral("cov.png"), {}, {chunk})); + QCOMPARE(s.book.status, Fb2LoadStatus::loaded); + QCOMPARE(s.book.title.value(), QStringLiteral("My Novel")); + QCOMPARE(s.book.chunks.value().size(), 1); + } + + // Obligations 54-57: rule-success/failure.CompleteFullOpenWithEmptyBodyFallback + void testRuleCompleteFullOpenWithEmptyBodyFallback() + { + ReaderClient c1{QStringLiteral("User")}; + ReaderClient c2{QStringLiteral("Other")}; + Fb2FormatReaderSurface s; + s.client = c1; + s.book.client = c1; + s.book.file_path = QStringLiteral("/books/empty.fb2"); + s.book.status = Fb2LoadStatus::loading_full; + + ContentChunkValue chunk{"sec1", 1, 0, 0, 0}; + + // Failure 1: actor != client + QVERIFY(!s.completeFullOpenWithEmptyBodyFallback(c2, "hash", "", "empty", {}, "", std::nullopt, {}, {})); + + // Failure 2: status != loading_full + s.book.status = Fb2LoadStatus::idle; + QVERIFY(!s.completeFullOpenWithEmptyBodyFallback(c1, "hash", "", "empty", {}, "", std::nullopt, {}, {})); + s.book.status = Fb2LoadStatus::loading_full; + + // Failure 3: extracted_chunks.count != 0 (rule only fires on empty chunks) + QVERIFY(!s.completeFullOpenWithEmptyBodyFallback(c1, "hash", "", "empty", {}, "", std::nullopt, {}, {chunk})); + + // Success + QVERIFY(s.completeFullOpenWithEmptyBodyFallback(c1, "hash000", "", "empty", {}, "", std::nullopt, {}, {})); + QCOMPARE(s.book.status, Fb2LoadStatus::loaded); + QCOMPARE(s.book.chunks.value().size(), 1); + ContentChunkValue fallback = s.book.chunks.value().first(); + QCOMPARE(fallback.section_href, QStringLiteral("/books/empty.fb2")); + QCOMPARE(fallback.blocks_count, 1); + QCOMPARE(fallback.word_count, 0); + QCOMPARE(fallback.char_count, 0); + } + + // Obligation 58: invariant.LoadedBookHasNonEmptyTitle + void testInvariantLoadedBookHasNonEmptyTitle() + { + ReaderClient c{QStringLiteral("User")}; + Fb2FormatReaderSurface s; + s.client = c; + s.book.client = c; + s.book.status = Fb2LoadStatus::loading_metadata; + + // If raw_book_title is empty, title falls back to filename_stem ("fallback_title") + s.completeMetadataLoad(c, "hash", "", "fallback_title", {}, "", std::nullopt, {}); + QCOMPARE(s.book.status, Fb2LoadStatus::loaded); + QVERIFY(!s.book.title.value().isEmpty()); + } + + // Obligation 59: invariant.FormatLabelMatchesExtension + void testInvariantFormatLabelMatchesExtension() + { + Fb2BookEntity bFbz; + bFbz.extension_kind = QStringLiteral("fbz"); + bFbz.format_label = HistoryFormatLabel::FBZ; + QCOMPARE(bFbz.format_label, bFbz.expected_format_label()); + + Fb2BookEntity bFb2; + bFb2.extension_kind = QStringLiteral("fb2"); + bFb2.format_label = HistoryFormatLabel::FB2; + QCOMPARE(bFb2.format_label, bFb2.expected_format_label()); + + Fb2BookEntity bZip; + bZip.extension_kind = QStringLiteral("fb2.zip"); + bZip.format_label = HistoryFormatLabel::FB2; + QCOMPARE(bZip.format_label, bZip.expected_format_label()); + } + + // Obligations 60-62: surface-actor, surface-exposure, surface-provides + void testSurface() + { + ReaderClient alice{QStringLiteral("Alice")}; + ReaderClient bob{QStringLiteral("Bob")}; + + Fb2FormatReaderSurface s; + s.client = alice; + s.book.client = alice; + s.book.file_path = QStringLiteral("/books/sample.fb2"); + s.book.format_label = HistoryFormatLabel::FB2; + s.book.status = Fb2LoadStatus::idle; + + // 60: surface-actor + QVERIFY(s.is_actor_accessible(alice)); + QVERIFY(!s.is_actor_accessible(bob)); + + // 61: surface-exposure + QCOMPARE(s.client.name, QStringLiteral("Alice")); + QCOMPARE(s.book.status, Fb2LoadStatus::idle); + QCOMPARE(s.book.file_path, QStringLiteral("/books/sample.fb2")); + QCOMPARE(s.book.format_label, HistoryFormatLabel::FB2); + + // 62: surface-provides + QVERIFY(s.can_provide_OpenFb2Requested()); + QVERIFY(s.can_provide_LoadFb2MetadataRequested()); + QVERIFY(!s.can_provide_InspectZipArchive()); + QVERIFY(!s.can_provide_Fb2XmlParsed()); + QVERIFY(!s.can_provide_Fb2MetadataExtracted()); + QVERIFY(!s.can_provide_Fb2DocumentParsed()); + + s.startOpenFb2Book(alice); + QCOMPARE(s.book.status, Fb2LoadStatus::loading_full); + QVERIFY(!s.can_provide_OpenFb2Requested()); + QVERIFY(!s.can_provide_LoadFb2MetadataRequested()); + QVERIFY(s.can_provide_Fb2XmlParsed()); + QVERIFY(s.can_provide_Fb2DocumentParsed()); + } + + // Real format integration test: Plain XML, encodings, and semantics + void testRealFb2EncodingsAndSemantics() + { + QTemporaryDir tempDir; + QVERIFY(tempDir.isValid()); + + const QString sampleFb2Path = tempDir.filePath(QStringLiteral("test_utf8.fb2")); + const QString xmlContent = QStringLiteral( + "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<FictionBook xmlns=\"http://www.gribuser.ru/xml/fictionbook/2.0\" xmlns:l=\"http://www.w3.org/1999/xlink\">\n" + " <stylesheet type=\"text/css\">\n" + " p.custom { text-align: right; }\n" + " </stylesheet>\n" + " <description>\n" + " <title-info>\n" + " <book-title>The Master and Margarita</book-title>\n" + " <author>\n" + " <first-name>Mikhail</first-name>\n" + " <last-name>Bulgakov</last-name>\n" + " </author>\n" + " <coverpage>\n" + " <image l:href=\"#cover.jpg\"/>\n" + " </coverpage>\n" + " <annotation>\n" + " <p>A classic satirical fantasy novel.</p>\n" + " </annotation>\n" + " </title-info>\n" + " </description>\n" + " <body>\n" + " <title><p>Part One</p>\n" + "

\n" + " <p>Chapter 1: Never Talk to Strangers</p>\n" + " \n" + "

...who then are you?

\n" + " Goethe, Faust\n" + "
\n" + " At the Patriarch's Ponds\n" + "

At the hour of the hot spring sunset two citizens appeared.

\n" + " \n" + " \n" + " \n" + " And the moon was rising\n" + " Over Moscow city\n" + " \n" + " \n" + "

He spoke with great conviction and doubt.

\n" + "
\n" + " \n" + " \n" + " /9j/4AAQSkZJRgABAQEASABIAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////wgALCAABAAEBAREA/8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABPxA=\n" + " \n" + "\n" + ); + + { + QFile f(sampleFb2Path); + QVERIFY(f.open(QIODevice::WriteOnly)); + f.write(xmlContent.toUtf8()); + } + + Fb2Reader reader([] { return std::make_unique(); }, QStringLiteral("fb2")); + + // 1. Metadata load + QVERIFY(reader.loadMetadata(sampleFb2Path)); + QCOMPARE(reader.status(), Fb2LoadStatus::loaded); + QCOMPARE(reader.title(), QStringLiteral("The Master and Margarita")); + QCOMPARE(reader.author(), QStringLiteral("Mikhail Bulgakov")); + QCOMPARE(reader.formatLabel(), QStringLiteral("FB2")); + QCOMPARE(reader.formatLabelEnum(), HistoryFormatLabel::FB2); + QCOMPARE(reader.containerKind(), Fb2ContainerKind::plain_xml); + QVERIFY(!reader.contentHash().isEmpty()); + QVERIFY(reader.coverImageUrl().startsWith(QStringLiteral("image://fb2/cover.jpg?src="))); + QVERIFY(reader.chunks().isEmpty()); + + // 2. Full open + QVERIFY(reader.open(sampleFb2Path)); + QCOMPARE(reader.status(), Fb2LoadStatus::loaded); + QVERIFY(!reader.chunks().isEmpty()); + + // Annotation chunk + QCOMPARE(reader.chunks().first().sectionHref, QStringLiteral("annotation")); + + // Section chunk + bool foundCh1 = false; + for (const auto &chunk : reader.chunks()) { + if (chunk.sectionHref == QLatin1String("ch1")) { + foundCh1 = true; + QVERIFY(!chunk.blocks.isEmpty()); + break; + } + } + QVERIFY(foundCh1); + + // 3. Byte source reading binary + Fb2ByteSource byteSource; + QVERIFY(byteSource.open(sampleFb2Path)); + QVERIFY(!byteSource.readEntry(QStringLiteral("cover.jpg")).isEmpty()); + QVERIFY(!byteSource.readEntry(QStringLiteral("#cover.jpg")).isEmpty()); // with hash prefix + QVERIFY(byteSource.readEntry(QStringLiteral("missing.png")).isEmpty()); // missing binary gracefully handled + } + + // Zip-compressed container test (.fbz) + void testZipCompressedFbz() + { + QTemporaryDir tempDir; + QVERIFY(tempDir.isValid()); + + const QString fbzPath = tempDir.filePath(QStringLiteral("archive.fbz")); + const QByteArray xml = + "\n" + "\n" + " \n" + " \n" + " Zipped Book\n" + " \n" + " \n" + " \n" + "
\n" + "

Content inside zip.

\n" + "
\n" + " \n" + "
\n"; + + QVERIFY(createZipArchive(fbzPath, {{QStringLiteral("book.fb2"), xml}})); + + Fb2Reader reader([] { return std::make_unique(); }, QStringLiteral("fb2")); + QVERIFY(reader.open(fbzPath)); + QCOMPARE(reader.containerKind(), Fb2ContainerKind::zip_archive); + QCOMPARE(reader.formatLabel(), QStringLiteral("FBZ")); + QCOMPARE(reader.formatLabelEnum(), HistoryFormatLabel::FBZ); + QCOMPARE(reader.title(), QStringLiteral("Zipped Book")); + QVERIFY(!reader.chunks().isEmpty()); + + // Empty zip test + const QString emptyZipPath = tempDir.filePath(QStringLiteral("empty.fbz")); + QVERIFY(createZipArchive(emptyZipPath, {})); + + Fb2Reader emptyReader([] { return std::make_unique(); }, QStringLiteral("fb2")); + QVERIFY(!emptyReader.open(emptyZipPath)); + QCOMPARE(emptyReader.status(), Fb2LoadStatus::failed); + QCOMPARE(emptyReader.lastError(), QStringLiteral("Archive contains no readable FB2 entry")); + } + + // Legacy Cyrillic encoding test (windows-1251) + void testWindows1251Encoding() + { + QTemporaryDir tempDir; + QVERIFY(tempDir.isValid()); + + const QString path = tempDir.filePath(QStringLiteral("cp1251.fb2")); + + // "Привет" in windows-1251 is: CF F0 E8 E2 E5 F2 + QByteArray bytes = + "\n" + "\n" + " \n" + " \n" + " \xCF\xF0\xE8\xE2\xE5\xF2\n" + " \n" + " \n" + " \n" + "
\n" + "

\xCF\xF0\xE8\xE2\xE5\xF2 \xEC\xE8\xF0

\n" + "
\n" + " \n" + "
\n"; + + { + QFile f(path); + QVERIFY(f.open(QIODevice::WriteOnly)); + f.write(bytes); + } + + Fb2Reader reader([] { return std::make_unique(); }, QStringLiteral("fb2")); + QVERIFY(reader.open(path)); + // "Привет" in Unicode + QCOMPARE(reader.title(), QString::fromUtf8("Привет")); + } + + void testNormalizedParagraphSpacingAndIndent() + { + QTemporaryDir tempDir; + QVERIFY(tempDir.isValid()); + const QString path = tempDir.filePath(QStringLiteral("test_paragraphs.fb2")); + + const QByteArray bytes = + "\n" + "\n" + " \n" + " Test Book\n" + " \n" + " \n" + "
\n" + " \n" + " <p>CHAPTER ONE</p>\n" + " \n" + "

First paragraph of the chapter with enough text to test layout.

\n" + "

Second consecutive paragraph immediately following the first.

\n" + " \n" + "

Third paragraph following an empty line scene transition.

\n" + "
\n" + " \n" + "
\n"; + + { + QFile f(path); + QVERIFY(f.open(QIODevice::WriteOnly)); + f.write(bytes); + } + + Fb2Reader fb2Reader([] { return std::make_unique(); }, QStringLiteral("fb2")); + QVERIFY(fb2Reader.open(path)); + QVERIFY(!fb2Reader.chunks().isEmpty()); + + const auto allChunks = fb2Reader.chunks(); + QVERIFY(!allChunks.isEmpty()); + + ::LayoutParams params; + params.contentWidth = 800; + params.fontSize = 16; + params.lineSpacing = 1.0; + + auto prep = ChunkLayoutEngine::prepareChunk(allChunks.first(), 16); + auto layout = ChunkLayoutEngine::layoutPreparedChunk(prep, params); + + QVERIFY(layout.lines.size() >= 4); + + // Line 0: Chapter title ("CHAPTER ONE") must be unindented (x == 0) and left-aligned + const auto &titleLine = layout.lines[0]; + QVERIFY(!titleLine.runs.isEmpty()); + QCOMPARE(titleLine.runs[0].text, QStringLiteral("CHAPTER")); + QCOMPARE(titleLine.runs[0].rect.left(), 0.0); + + // Line 1: First paragraph must have 2.0em (32px at 16px font) first-line indent + const auto &p1Line = layout.lines[1]; + QVERIFY(!p1Line.runs.isEmpty()); + QCOMPARE(p1Line.runs[0].text, QStringLiteral("First")); + QCOMPARE(p1Line.runs[0].rect.left(), 32.0); + + // Line 2: Second paragraph must immediately follow Line 1 with zero vertical margin gap + const auto &p2Line = layout.lines[2]; + QVERIFY(!p2Line.runs.isEmpty()); + QCOMPARE(p2Line.runs[0].text, QStringLiteral("Second")); + QCOMPARE(p2Line.runs[0].rect.left(), 32.0); + QVERIFY(qAbs(p1Line.rect.bottom() - p2Line.rect.top()) < 0.001); + + // Line 3: Third paragraph must have an empty vertical gap from Line 2 due to + const auto &p3Line = layout.lines[3]; + QVERIFY(!p3Line.runs.isEmpty()); + QCOMPARE(p3Line.runs[0].text, QStringLiteral("Third")); + QCOMPARE(p3Line.runs[0].rect.left(), 32.0); + QVERIFY(p3Line.rect.top() > p2Line.rect.bottom()); + } + + void testFb2AndEpubParagraphEquivalence() + { + // Compare layout of representative synthetic FB2

vs EPUB

+ const QString fb2Html = QStringLiteral( + "
" + "

CHAPTER ONE

" + "

First paragraph of the chapter with enough text to test layout.

" + "

Second consecutive paragraph immediately following the first.

" + "
" + ); + auto fb2Chunks = HtmlBlockParser::parseChunks(fb2Html, QStringLiteral("fb2-sec")); + QCOMPARE(fb2Chunks.size(), 1); + + // EPUB equivalent with cascaded .paragraph { display: block; text-indent: 2em; } + const QString epubHtml = QStringLiteral( + "
" + "

CHAPTER ONE

" + "
First paragraph of the chapter with enough text to test layout.
" + "
Second consecutive paragraph immediately following the first.
" + "
" + ); + auto epubChunks = HtmlBlockParser::parseChunks(epubHtml, QStringLiteral("epub-sec")); + QCOMPARE(epubChunks.size(), 1); + + ::LayoutParams params; + params.contentWidth = 800; + params.fontSize = 16; + params.lineSpacing = 1.0; + + auto fb2Layout = ChunkLayoutEngine::layoutPreparedChunk( + ChunkLayoutEngine::prepareChunk(fb2Chunks.first(), 16), params); + auto epubLayout = ChunkLayoutEngine::layoutPreparedChunk( + ChunkLayoutEngine::prepareChunk(epubChunks.first(), 16), params); + + QCOMPARE(fb2Layout.lines.size(), epubLayout.lines.size()); + for (int i = 0; i < fb2Layout.lines.size(); ++i) { + QCOMPARE(fb2Layout.lines[i].rect.topLeft(), epubLayout.lines[i].rect.topLeft()); + QVERIFY(!fb2Layout.lines[i].runs.isEmpty()); + QVERIFY(!epubLayout.lines[i].runs.isEmpty()); + QCOMPARE(fb2Layout.lines[i].runs[0].rect.left(), epubLayout.lines[i].runs[0].rect.left()); + } + } +}; + +QTEST_MAIN(Fb2ReaderTest) +#include "Fb2ReaderTest.moc" diff --git a/tests/reading/ChunkLayoutEngineTest.cpp b/tests/reading/ChunkLayoutEngineTest.cpp index b255ab7..a57b1bb 100644 --- a/tests/reading/ChunkLayoutEngineTest.cpp +++ b/tests/reading/ChunkLayoutEngineTest.cpp @@ -434,6 +434,37 @@ private slots: QVERIFY(!l2.decorations.isEmpty()); QVERIFY(l2.decorations[0].borderLeft > 0); } + + void paragraphDefaultsAndCssOverrides() + { + // 1. Unstyled

must produce zero ContainerStart/End boxes and have 2.0em indent + const QString plainHtml = QStringLiteral("

Paragraph one

Paragraph two

"); + auto plainChunks = HtmlBlockParser::parseChunks(plainHtml, QStringLiteral("plain.xhtml")); + QCOMPARE(plainChunks.size(), 1); + const auto &plainBlocks = plainChunks.first().blocks; + + // Exactly 2 blocks (both paragraphs), zero containers + QCOMPARE(plainBlocks.size(), 2); + QCOMPARE(plainBlocks[0].kind, BlockItem::Kind::Paragraph); + QCOMPARE(plainBlocks[1].kind, BlockItem::Kind::Paragraph); + QCOMPARE(plainBlocks[0].textIndent, 32.0); // 16 * 2.0 + QCOMPARE(plainBlocks[1].textIndent, 32.0); + + // 2. Styled

with explicit margin must preserve box margins via ContainerStart/End + const QString styledHtml = QStringLiteral("

Styled paragraph

"); + auto styledChunks = HtmlBlockParser::parseChunks(styledHtml, QStringLiteral("styled.xhtml")); + QCOMPARE(styledChunks.size(), 1); + const auto &styledBlocks = styledChunks.first().blocks; + + // ContainerStart, Paragraph, ContainerEnd + QCOMPARE(styledBlocks.size(), 3); + QCOMPARE(styledBlocks[0].kind, BlockItem::Kind::ContainerStart); + QCOMPARE(styledBlocks[0].box.marginTop, 10.0); + QCOMPARE(styledBlocks[0].box.marginBottom, 12.0); + QCOMPARE(styledBlocks[1].kind, BlockItem::Kind::Paragraph); + QCOMPARE(styledBlocks[1].textIndent, 0.0); + QCOMPARE(styledBlocks[2].kind, BlockItem::Kind::ContainerEnd); + } }; QTEST_MAIN(ChunkLayoutEngineTest)