fb2 support
This commit is contained in:
18 files changed
+2351
-53
No files matched your search
@@ -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<ContentChunk>`).
|
||||
- `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 (`<div class="paragraph">` and `<p>`) and FB2 (`<p>`): 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`, `<title>` 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
|
||||
|
||||
+45
-12
@@ -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)
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
};
|
||||
@@ -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
|
||||
};
|
||||
@@ -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))
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
};
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -434,6 +434,37 @@ private slots:
|
||||
QVERIFY(!l2.decorations.isEmpty());
|
||||
QVERIFY(l2.decorations[0].borderLeft > 0);
|
||||
}
|
||||
|
||||
void paragraphDefaultsAndCssOverrides()
|
||||
{
|
||||
// 1. Unstyled <p> must produce zero ContainerStart/End boxes and have 2.0em indent
|
||||
const QString plainHtml = QStringLiteral("<div><p>Paragraph one</p><p>Paragraph two</p></div>");
|
||||
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 <p> with explicit margin must preserve box margins via ContainerStart/End
|
||||
const QString styledHtml = QStringLiteral("<div><p style=\"margin-top: 10px; margin-bottom: 12px; text-indent: 0;\">Styled paragraph</p></div>");
|
||||
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)
|
||||
|
||||
Reference in new issue
Block a user