reintroduced epub support

This commit is contained in:
Agel committed 2026-10-25 19:59:23 +01:00
1 parent 49a959a89d
commit d14170a68f
49 files changed
+5036 -193

No files matched your search

+1 -3
View File
@@ -163,7 +163,7 @@ When `CMakeLists.txt` gains a new `find_package` or `pkg_check_modules` dependen
### Content Model
All format readers produce normalized HTML content organized into chapters. Each chapter's content is split into chunks (a `QStringList`) at the reader level, where the format structure is known. This enables virtualized rendering via `ListView` in QML. The content model is defined in `FormatReader.h`:
All format readers produce normalized content organized into chapters. Each chapter's content is represented as chunks (a `QStringList` of standalone fragments) to enable virtualized rendering via `ListView` in QML. The content model is defined in `FormatReader.h`:
```cpp
struct TocEntry {
@@ -189,8 +189,6 @@ struct Chapter {
Chapter mapping by format: TXT = 1 chapter (whole file). FB2 = `<section>` elements. EPUB = spine items. CBZ = 1 chapter (whole archive). PDF = outline entries or individual pages.
**Chunking:** Each format reader splits content into chunks natively — chunking at the reader level is trivial and reliable compared to splitting arbitrary HTML. TxtReader splits raw text at ~4096 character boundaries (preferring `\n`, falling back to whitespace), then converts each chunk to HTML independently. Each chunk is a standalone HTML fragment (contains its own `<p>` tags).
**ReadingModel** is a `QAbstractListModel` exposing chunks via `ContentRole`. `PageView.qml` renders chunks in a `ListView` with `cacheBuffer` for seamless scrolling — no visible seams between chunks.
**Progress tracking** to track reading position ONLY ListView y offset must be used. Current page / progress percentage must be calculated using this and total height only.
+79 -8
View File
@@ -19,6 +19,7 @@ find_package(Qt6 REQUIRED COMPONENTS
QuickControls2
Test
Xml
Network
)
find_package(Qt6 OPTIONAL_COMPONENTS DBus)
@@ -79,6 +80,24 @@ set(SOURCES
src/backend/formats/FormatRegistry.cpp
src/backend/formats/FileIconProvider.h
src/backend/formats/FileIconProvider.cpp
src/backend/formats/HtmlEntities.h
src/backend/formats/HtmlEntities.cpp
src/backend/formats/WebImageProvider.h
src/backend/formats/WebImageProvider.cpp
src/backend/formats/EpubReader.h
src/backend/formats/EpubReader.cpp
src/backend/reading/BookImageResolver.h
src/backend/reading/BookImageResolver.cpp
src/backend/reading/KnuthPlassItem.h
src/backend/reading/KnuthPlassItem.cpp
src/backend/reading/layout/KnuthPlass.h
src/backend/reading/layout/KnuthPlass.cpp
src/backend/reading/layout/CssParser.h
src/backend/reading/layout/CssParser.cpp
src/backend/reading/layout/HtmlBlockParser.h
src/backend/reading/layout/HtmlBlockParser.cpp
src/backend/reading/layout/ChunkLayoutEngine.h
src/backend/reading/layout/ChunkLayoutEngine.cpp
)
if(WIN32)
@@ -121,6 +140,7 @@ target_link_libraries(asteria-qt PRIVATE
PkgConfig::MINIZIP
PkgConfig::LIBARCHIVE
Qt6::Xml
Qt6::Network
)
if(Qt6DBus_FOUND)
@@ -142,6 +162,7 @@ set_source_files_properties(src/qml/ThemeManager.qml PROPERTIES QT_RESOURCE_ALIA
set_source_files_properties(src/qml/components/Header.qml PROPERTIES QT_RESOURCE_ALIAS components/Header.qml)
set_source_files_properties(src/qml/components/SideBar.qml PROPERTIES QT_RESOURCE_ALIAS components/SideBar.qml)
set_source_files_properties(src/qml/components/MangaPageView.qml PROPERTIES QT_RESOURCE_ALIAS components/MangaPageView.qml)
set_source_files_properties(src/qml/components/ScrollPageView.qml PROPERTIES QT_RESOURCE_ALIAS components/ScrollPageView.qml)
set_source_files_properties(src/qml/components/Footer.qml PROPERTIES QT_RESOURCE_ALIAS components/Footer.qml)
set_source_files_properties(src/qml/components/ErrorPopup.qml PROPERTIES QT_RESOURCE_ALIAS components/ErrorPopup.qml)
set_source_files_properties(src/qml/components/SideBarButton.qml PROPERTIES QT_RESOURCE_ALIAS components/SideBarButton.qml)
@@ -167,6 +188,7 @@ qt_add_qml_module(asteria-qt
src/qml/components/Header.qml
src/qml/components/SideBar.qml
src/qml/components/MangaPageView.qml
src/qml/components/ScrollPageView.qml
src/qml/components/Footer.qml
src/qml/components/ErrorPopup.qml
src/qml/components/SideBarButton.qml
@@ -212,6 +234,21 @@ set(COMIC_SOURCES
${COMIC_READER_SOURCES}
src/backend/formats/EntryImageProvider.cpp)
set(LAYOUT_SOURCES
src/backend/reading/layout/KnuthPlass.cpp
src/backend/reading/layout/CssParser.cpp
src/backend/reading/layout/HtmlBlockParser.cpp
src/backend/reading/layout/ChunkLayoutEngine.cpp
)
set(EPUB_READER_SOURCES
src/backend/formats/HtmlEntities.cpp
src/backend/formats/WebImageProvider.cpp
src/backend/reading/BookImageResolver.cpp
src/backend/formats/EpubReader.cpp
${LAYOUT_SOURCES}
)
# Testing
enable_testing()
@@ -232,6 +269,36 @@ add_asteria_test(ImageUrlTest tests/formats/ImageUrlTest.cpp
add_asteria_test(MangaPaginationTest tests/reading/MangaPaginationTest.cpp
src/backend/reading/MangaPagination.cpp)
add_asteria_test(KnuthPlassTest tests/reading/KnuthPlassTest.cpp
src/backend/reading/layout/KnuthPlass.cpp)
add_asteria_test(CssParserTest tests/reading/CssParserTest.cpp
src/backend/reading/layout/CssParser.cpp)
target_link_libraries(CssParserTest PRIVATE Qt6::Gui Qt6::Xml)
add_asteria_test(ChunkLayoutEngineTest tests/reading/ChunkLayoutEngineTest.cpp
src/backend/reading/BookImageResolver.cpp
src/backend/formats/AsyncImageResponse.cpp
src/backend/formats/WebImageProvider.cpp
src/backend/formats/HtmlEntities.cpp
src/backend/formats/ImageUrl.cpp
${LAYOUT_SOURCES})
target_link_libraries(ChunkLayoutEngineTest PRIVATE Qt6::Gui Qt6::Xml Qt6::Quick Qt6::Network)
set_tests_properties(ChunkLayoutEngineTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
add_asteria_test(WebImageProviderTest tests/formats/WebImageProviderTest.cpp
src/backend/formats/AsyncImageResponse.cpp
src/backend/formats/WebImageProvider.cpp)
target_link_libraries(WebImageProviderTest PRIVATE Qt6::Quick Qt6::Gui Qt6::Network)
set_tests_properties(WebImageProviderTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
add_asteria_test(EpubReaderTest tests/formats/EpubReaderTest.cpp
src/backend/formats/AsyncImageResponse.cpp
src/backend/formats/ImageUrl.cpp
${EPUB_READER_SOURCES})
target_link_libraries(EpubReaderTest PRIVATE Qt6::Xml Qt6::Gui Qt6::Quick Qt6::Network)
set_tests_properties(EpubReaderTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
add_asteria_test(CbzReaderTest tests/formats/CbzReaderTest.cpp ${COMIC_READER_SOURCES})
target_link_libraries(CbzReaderTest PRIVATE PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Gui)
@@ -243,8 +310,9 @@ add_asteria_test(FormatRegistryTest tests/FormatRegistryTest.cpp
src/backend/formats/FormatRegistry.cpp
src/backend/formats/AsyncImageResponse.cpp
src/backend/formats/EntryImageProvider.cpp
${COMIC_READER_SOURCES})
target_link_libraries(FormatRegistryTest PRIVATE PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Gui Qt6::Quick)
${COMIC_READER_SOURCES}
${EPUB_READER_SOURCES})
target_link_libraries(FormatRegistryTest PRIVATE PkgConfig::MINIZIP PkgConfig::LIBARCHIVE 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
@@ -255,8 +323,9 @@ add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp
src/backend/AppState.cpp
src/backend/state/BookPositionStore.cpp
src/backend/HistoryModel.cpp
${COMIC_SOURCES})
target_link_libraries(ReadingModelTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml)
${COMIC_SOURCES}
${EPUB_READER_SOURCES})
target_link_libraries(ReadingModelTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Network)
set_tests_properties(ReadingModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
add_asteria_test(AppStateTest tests/AppStateTest.cpp
@@ -282,8 +351,9 @@ add_asteria_test(BookTest tests/book/BookTest.cpp
src/backend/formats/AsyncImageResponse.cpp
src/backend/IFileDialogService.h
src/backend/NativeFileDialogService.cpp
${COMIC_SOURCES})
target_link_libraries(BookTest PRIVATE Qt6::Concurrent Qt6::Widgets PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Gui Qt6::Quick)
${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)
set_tests_properties(BookTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
add_asteria_test(EntryImageProviderTest tests/EntryImageProviderTest.cpp
@@ -299,9 +369,10 @@ add_asteria_test(HistoryModelTest tests/HistoryModelTest.cpp
src/backend/AppState.cpp
src/backend/formats/AsyncImageResponse.cpp
src/backend/formats/FormatRegistry.cpp
${COMIC_SOURCES})
${COMIC_SOURCES}
${EPUB_READER_SOURCES})
target_link_libraries(HistoryModelTest PRIVATE
Qt6::Concurrent Qt6::Quick Qt6::Gui Qt6::Xml PkgConfig::MINIZIP PkgConfig::LIBARCHIVE)
Qt6::Concurrent Qt6::Quick Qt6::Gui Qt6::Xml Qt6::Network PkgConfig::MINIZIP PkgConfig::LIBARCHIVE)
set_tests_properties(HistoryModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
add_asteria_test(FileIconProviderTest tests/FileIconProviderTest.cpp
+2 -15
View File
@@ -17,18 +17,6 @@ struct PageInfo {
QSize naturalSize;
};
struct TocEntry {
QString title;
int chapterIndex = 0;
int depth = 0;
};
struct Chapter {
int index = 0;
QString title;
QStringList chunks; // Standalone HTML/text fragments for virtualized rendering
};
class FormatReader {
public:
virtual ~FormatReader() = default;
@@ -50,9 +38,8 @@ public:
virtual QVector<PageInfo> pages() const { return {}; }
// Text mode (default empty for comic readers)
virtual int chapterCount() const { return 0; }
virtual Chapter loadChapter(int index) const { Q_UNUSED(index); return {}; }
virtual QVector<TocEntry> tableOfContents() const { return {}; }
// Returns standalone HTML fragments representing the entire book for continuous scrolling.
virtual QStringList chunks() const { return {}; }
};
#endif // FORMATREADER_H
+9 -3
View File
@@ -23,7 +23,13 @@ HistoryModel::HistoryModel(FormatRegistry &registry, QObject *parent)
{
}
HistoryModel::~HistoryModel() = default;
HistoryModel::~HistoryModel()
{
for (auto &f : m_metadataFutures) {
if (f.isRunning())
f.waitForFinished();
}
}
int HistoryModel::rowCount(const QModelIndex &parent) const
{
@@ -213,7 +219,7 @@ void HistoryModel::requestMetadata(const QString &filePath)
FormatRegistry *registry = &m_registry;
QPointer<HistoryModel> self(this);
(void)QtConcurrent::run([self, filePath, registry]() {
m_metadataFutures.append(QtConcurrent::run([self, filePath, registry]() {
auto reader = registry->createReader(filePath);
QString title;
QString author;
@@ -244,5 +250,5 @@ void HistoryModel::requestMetadata(const QString &filePath)
}
}
}, Qt::QueuedConnection);
});
}));
}
+2
View File
@@ -2,6 +2,7 @@
#define HISTORYMODEL_H
#include <QAbstractListModel>
#include <QFuture>
#include <QHash>
#include <QList>
#include <QString>
@@ -66,6 +67,7 @@ private:
QList<HistoryEntry> m_entries;
FormatRegistry &m_registry;
QList<QFuture<void>> m_metadataFutures;
};
#endif // HISTORYMODEL_H
+202 -48
View File
@@ -1,42 +1,65 @@
#include "ReadingModel.h"
#include <algorithm>
#include <numeric>
#include <QPointer>
#include <QtConcurrent>
ReadingModel::ReadingModel(BookPositionStore &positions, QObject *parent)
: QAbstractListModel(parent)
, m_positions(positions)
{
m_remainingLayoutTimer = new QTimer(this);
m_remainingLayoutTimer->setSingleShot(true);
m_remainingLayoutTimer->setInterval(100);
connect(m_remainingLayoutTimer, &QTimer::timeout, this, &ReadingModel::runRemainingLayout);
}
ReadingModel::~ReadingModel() = default;
ReadingModel::~ReadingModel()
{
if (m_remainingLayoutTimer) {
m_remainingLayoutTimer->stop();
}
++m_layoutGeneration;
if (m_layoutFuture.isRunning()) {
m_layoutFuture.waitForFinished();
}
}
int ReadingModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid() || !m_isTextMode)
return 0;
return m_currentChapterData.chunks.size();
return m_chunks.size();
}
QVariant ReadingModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || !m_isTextMode || index.row() < 0 || index.row() >= m_currentChapterData.chunks.size())
if (!index.isValid() || !m_isTextMode || index.row() < 0 || index.row() >= m_chunks.size())
return {};
if (role == ContentRole)
return m_currentChapterData.chunks.at(index.row());
return m_chunks.at(index.row());
if (role == LayoutRole && index.row() < m_chunkLayouts.size())
return QVariant::fromValue(m_chunkLayouts.at(index.row()));
if (role == PixelHeightRole && index.row() < m_chunkLayouts.size())
return m_chunkLayouts.at(index.row()).totalHeight;
return {};
}
QHash<int, QByteArray> ReadingModel::roleNames() const
{
return {{ContentRole, "content"}};
return {
{ContentRole, "content"},
{LayoutRole, "layout"},
{PixelHeightRole, "pixelHeight"}
};
}
bool ReadingModel::isTextMode() const { return m_isTextMode; }
bool ReadingModel::isMangaMode() const { return !m_isTextMode; }
bool ReadingModel::measuring() const { return m_measuring; }
int ReadingModel::totalPagePairs() const { return m_pagination.count(); }
bool ReadingModel::pageShift() const { return m_pageShift; }
bool ReadingModel::mangaRTL() const { return m_mangaRTL; }
int ReadingModel::currentChapter() const { return m_currentChapter; }
int ReadingModel::chapterCount() const { return m_chapterCount; }
QString ReadingModel::chapterTitle() const { return m_currentChapterData.title; }
double ReadingModel::progress() const
{
@@ -46,8 +69,108 @@ double ReadingModel::progress() const
int ReadingModel::currentPage() const { return m_currentPage; }
int ReadingModel::totalPages() const { return m_totalPages; }
void ReadingModel::setImageResolver(IBookImageResolver *resolver)
{
m_imageResolver = resolver;
}
void ReadingModel::updateLayoutMetrics(int contentWidth, int fontSize, qreal lineSpacing, int anchorChunk)
{
if (contentWidth <= 0 || fontSize <= 0 || lineSpacing <= 0)
return;
if (m_layoutContentWidth == contentWidth && m_layoutFontSize == fontSize
&& qFuzzyCompare(m_layoutLineSpacing, lineSpacing))
return;
const bool fontSizeChanged = (m_layoutFontSize != fontSize);
m_layoutContentWidth = contentWidth;
m_layoutFontSize = fontSize;
m_layoutLineSpacing = lineSpacing;
if (!m_isTextMode || m_chunks.isEmpty())
return;
const int targetChunk = (anchorChunk >= 0) ? anchorChunk : (m_currentPage > 0 ? (m_currentPage - 1) : 0);
if (fontSizeChanged || m_preparedChunks.size() != m_chunks.size()) {
if (m_remainingLayoutTimer)
m_remainingLayoutTimer->stop();
startLayoutMeasurement(targetChunk, m_intraOffset);
return;
}
// FAST PATH: Font size unchanged, only width or line spacing changed.
// 1. Immediately layout visible chunk window synchronously (<0.2ms) so display reflows in real time without lag.
LayoutParams params;
params.contentWidth = m_layoutContentWidth;
params.fontSize = m_layoutFontSize;
params.lineSpacing = m_layoutLineSpacing;
const int startIdx = std::max(0, targetChunk - 2);
const int endIdx = std::min(int(m_preparedChunks.size() - 1), targetChunk + 4);
if (m_chunkLayouts.size() != m_preparedChunks.size()) {
m_chunkLayouts.resize(m_preparedChunks.size());
}
for (int i = startIdx; i <= endIdx; ++i) {
m_chunkLayouts[i] = ChunkLayoutEngine::layoutPreparedChunk(m_preparedChunks[i], params);
}
if (startIdx <= endIdx) {
emit dataChanged(index(startIdx, 0), index(endIdx, 0), {LayoutRole, PixelHeightRole});
}
// 2. Debounce background layout for off-screen chunks so mouse drag stays at 60fps without thread pool saturation.
if (m_remainingLayoutTimer) {
m_remainingLayoutTimer->start();
} else {
runRemainingLayout();
}
}
void ReadingModel::runRemainingLayout()
{
if (!m_isTextMode || m_preparedChunks.isEmpty())
return;
const int generation = ++m_layoutGeneration;
const auto prepared = m_preparedChunks;
LayoutParams params;
params.contentWidth = m_layoutContentWidth;
params.fontSize = m_layoutFontSize;
params.lineSpacing = m_layoutLineSpacing;
QPointer<ReadingModel> self(this);
m_layoutFuture = QtConcurrent::run([self, generation, prepared, params]() {
QVector<ChunkLayout> newLayouts = QtConcurrent::blockingMapped(
prepared,
[params](const ChunkLayoutEngine::PreparedChunk &prep) {
return ChunkLayoutEngine::layoutPreparedChunk(prep, params);
});
if (!self || self->m_layoutGeneration != generation)
return;
QMetaObject::invokeMethod(self.data(), [self, generation, newLayouts = std::move(newLayouts)]() mutable {
if (!self || generation != self->m_layoutGeneration)
return;
self->m_chunkLayouts = std::move(newLayouts);
if (!self->m_chunkLayouts.isEmpty()) {
emit self->dataChanged(self->index(0, 0), self->index(self->m_chunkLayouts.size() - 1, 0), {LayoutRole, PixelHeightRole});
}
}, Qt::QueuedConnection);
});
}
void ReadingModel::setScrollInfo(const int topChunkIndex, const qreal proportion)
{
setScrollPosition(topChunkIndex, 0.0, proportion);
}
void ReadingModel::setScrollPosition(int topChunkIndex, qreal intraOffset, qreal proportion)
{
m_intraOffset = intraOffset;
const qreal clamped = qBound(0.0, proportion, 1.0);
if (!qFuzzyCompare(m_progress, clamped)) {
m_progress = clamped;
@@ -68,15 +191,15 @@ void ReadingModel::setScrollInfo(const int topChunkIndex, const qreal proportion
}
}
saveCurrentPosition(topChunkIndex);
saveCurrentPosition(topChunkIndex, intraOffset);
}
void ReadingModel::saveCurrentPosition(int chunkIndex)
void ReadingModel::saveCurrentPosition(int chunkIndex, qreal intraOffset)
{
if (!m_reader) return;
BookPosition pos;
pos.chapterIndex = m_currentChapter;
pos.chunkIndex = chunkIndex;
pos.intraOffset = intraOffset;
pos.progress = m_progress;
pos.pageShift = m_pageShift;
pos.mangaRTL = m_mangaRTL;
@@ -84,40 +207,64 @@ void ReadingModel::saveCurrentPosition(int chunkIndex)
emit positionSaved();
}
void ReadingModel::loadChapter(int index)
void ReadingModel::startLayoutMeasurement(int restoreChunk, qreal restoreIntraOffset)
{
if (!m_reader || !m_isTextMode)
if (m_remainingLayoutTimer)
m_remainingLayoutTimer->stop();
if (!m_isTextMode || m_chunks.isEmpty()) {
m_preparedChunks.clear();
m_chunkLayouts.clear();
if (m_measuring) {
m_measuring = false;
emit measuringChanged();
}
return;
if (index < 0 || index >= m_chapterCount)
}
m_measuring = true;
emit measuringChanged();
const int generation = ++m_layoutGeneration;
const auto chunks = m_chunks;
LayoutParams params;
params.contentWidth = m_layoutContentWidth;
params.fontSize = m_layoutFontSize;
params.lineSpacing = m_layoutLineSpacing;
auto *resolver = m_imageResolver;
QPointer<ReadingModel> self(this);
m_layoutFuture = QtConcurrent::run([self, generation, chunks, params, resolver, restoreChunk, restoreIntraOffset]() {
auto prepared = QtConcurrent::blockingMapped(chunks, [params, resolver](const QString &chunkHtml) {
return ChunkLayoutEngine::prepareChunk(chunkHtml, params.fontSize, resolver);
});
if (!self || self->m_layoutGeneration != generation)
return;
beginResetModel();
m_currentChapter = index;
m_currentChapterData = m_reader->loadChapter(index);
m_totalPages = m_currentChapterData.chunks.size();
m_currentPage = qMin(1, m_totalPages);
endResetModel();
auto layouts = QtConcurrent::blockingMapped(prepared, [params](const ChunkLayoutEngine::PreparedChunk &prep) {
return ChunkLayoutEngine::layoutPreparedChunk(prep, params);
});
emit currentChapterChanged();
emit totalPagesChanged();
emit currentPageChanged();
}
if (!self || self->m_layoutGeneration != generation)
return;
void ReadingModel::nextChapter()
{
if (m_isTextMode && m_currentChapter + 1 < m_chapterCount) {
loadChapter(m_currentChapter + 1);
saveCurrentPosition(0);
QMetaObject::invokeMethod(self.data(), [self, generation, prepared = std::move(prepared), layouts = std::move(layouts), restoreChunk, restoreIntraOffset]() mutable {
if (!self || generation != self->m_layoutGeneration)
return;
self->m_preparedChunks = std::move(prepared);
self->m_chunkLayouts = std::move(layouts);
self->m_measuring = false;
emit self->measuringChanged();
if (!self->m_chunkLayouts.isEmpty()) {
emit self->dataChanged(self->index(0, 0), self->index(self->m_chunkLayouts.size() - 1, 0), {LayoutRole, PixelHeightRole});
}
emit self->restoreReady(restoreChunk, restoreIntraOffset);
}, Qt::QueuedConnection);
});
}
void ReadingModel::previousChapter()
{
if (m_isTextMode && m_currentChapter > 0) {
loadChapter(m_currentChapter - 1);
saveCurrentPosition(0);
}
}
void ReadingModel::rebuildPagePairs()
{
@@ -230,7 +377,9 @@ void ReadingModel::setReader(FormatReader *reader)
m_reader = reader;
beginResetModel();
m_currentChapterData = {};
m_chunks.clear();
m_preparedChunks.clear();
m_chunkLayouts.clear();
endResetModel();
const bool oldTextMode = m_isTextMode;
@@ -239,38 +388,43 @@ void ReadingModel::setReader(FormatReader *reader)
emit modeChanged();
int restoreChunk = 0;
int restoreChapter = 0;
qreal restoreIntraOffset = 0.0;
if (reader) {
const auto pos = m_positions.load(reader->contentHash());
restoreChunk = pos.chunkIndex;
restoreChapter = pos.chapterIndex;
restoreIntraOffset = pos.intraOffset;
m_intraOffset = pos.intraOffset;
m_progress = pos.progress;
m_pageShift = pos.pageShift;
m_mangaRTL = pos.mangaRTL;
emit progressChanged();
} else {
m_progress = 0.0;
m_intraOffset = 0.0;
m_pageShift = true;
m_mangaRTL = true;
emit progressChanged();
}
if (m_isTextMode && m_reader) {
m_chapterCount = m_reader->chapterCount();
emit chapterCountChanged();
loadChapter(qBound(0, restoreChapter, qMax(0, m_chapterCount - 1)));
beginResetModel();
m_chunks = m_reader->chunks();
m_totalPages = m_chunks.size();
m_currentPage = m_totalPages > 0 ? qBound(1, restoreChunk + 1, m_totalPages) : 0;
endResetModel();
emit totalPagesChanged();
emit currentPageChanged();
startLayoutMeasurement(restoreChunk, restoreIntraOffset);
} else {
m_chapterCount = 0;
m_currentChapter = 0;
emit chapterCountChanged();
emit currentChapterChanged();
loadPages();
}
if (m_reader) {
if (m_reader && !m_isTextMode) {
QMetaObject::invokeMethod(this, [this, restoreChunk] {
emit restoreReady(restoreChunk);
emit restoreReady(restoreChunk, 0.0);
}, Qt::QueuedConnection);
}
}
+34 -19
View File
@@ -2,30 +2,35 @@
#define READINGMODEL_H
#include <QAbstractListModel>
#include <QFuture>
#include <QSize>
#include <QString>
#include <QTimer>
#include <QVariantList>
#include <QVector>
#include "backend/FormatReader.h"
#include "backend/reading/BookImageResolver.h"
#include "backend/reading/layout/ChunkLayoutEngine.h"
#include "reading/MangaPagination.h"
#include "state/BookPositionStore.h"
class ReadingModel : public QAbstractListModel {
Q_OBJECT
Q_PROPERTY(bool isTextMode READ isTextMode NOTIFY modeChanged)
Q_PROPERTY(bool isMangaMode READ isMangaMode NOTIFY modeChanged)
Q_PROPERTY(bool measuring READ measuring NOTIFY measuringChanged)
Q_PROPERTY(double progress READ progress NOTIFY progressChanged)
Q_PROPERTY(int currentPage READ currentPage NOTIFY currentPageChanged)
Q_PROPERTY(int totalPages READ totalPages NOTIFY totalPagesChanged)
Q_PROPERTY(int currentChapter READ currentChapter NOTIFY currentChapterChanged)
Q_PROPERTY(int chapterCount READ chapterCount NOTIFY chapterCountChanged)
Q_PROPERTY(QString chapterTitle READ chapterTitle NOTIFY currentChapterChanged)
Q_PROPERTY(int totalPagePairs READ totalPagePairs NOTIFY totalPagePairsChanged)
Q_PROPERTY(bool pageShift READ pageShift NOTIFY pageShiftChanged)
Q_PROPERTY(bool mangaRTL READ mangaRTL NOTIFY mangaRTLChanged)
public:
enum ReadingRoles {
ContentRole = Qt::UserRole + 1
ContentRole = Qt::UserRole + 1,
LayoutRole,
PixelHeightRole
};
Q_ENUM(ReadingRoles)
@@ -37,25 +42,24 @@ public:
QHash<int, QByteArray> roleNames() const override;
bool isTextMode() const;
bool isMangaMode() const;
bool measuring() const;
double progress() const;
int currentPage() const;
int totalPages() const;
int currentChapter() const;
int chapterCount() const;
QString chapterTitle() const;
int totalPagePairs() const;
bool pageShift() const;
bool mangaRTL() const;
void setReader(FormatReader *reader);
void setImageResolver(IBookImageResolver *resolver);
// Text layout metrics
Q_INVOKABLE void updateLayoutMetrics(int contentWidth, int fontSize, qreal lineSpacing, int anchorChunk = -1);
// Called on navigation
Q_INVOKABLE void setScrollInfo(int topChunkIndex, qreal proportion);
// Text chapter navigation
Q_INVOKABLE void loadChapter(int index);
Q_INVOKABLE void nextChapter();
Q_INVOKABLE void previousChapter();
Q_INVOKABLE void setScrollPosition(int topChunkIndex, qreal intraOffset, qreal proportion);
// Manga page-pair API
Q_INVOKABLE QVariantList pagePair(int pairIndex) const;
@@ -71,30 +75,40 @@ public:
signals:
void modeChanged();
void measuringChanged();
void progressChanged();
void currentPageChanged();
void totalPagesChanged();
void currentChapterChanged();
void chapterCountChanged();
void totalPagePairsChanged();
void pageShiftChanged();
void mangaRTLChanged();
void pagePairsRebuilt(int newPairIndex);
void restoreReady(int chunkIndex);
void restoreReady(int chunkIndex, qreal intraOffset = 0.0);
void positionSaved();
private:
void loadPages();
void rebuildPagePairs();
void saveCurrentPosition(int chunkIndex);
void startLayoutMeasurement(int restoreChunk = 0, qreal restoreIntraOffset = 0.0);
void runRemainingLayout();
void saveCurrentPosition(int chunkIndex, qreal intraOffset = 0.0);
FormatReader *m_reader = nullptr;
IBookImageResolver *m_imageResolver = nullptr;
bool m_isTextMode = false;
bool m_measuring = false;
int m_currentPage = 0;
int m_totalPages = 0;
int m_currentChapter = 0;
int m_chapterCount = 0;
Chapter m_currentChapterData;
QStringList m_chunks;
QVector<ChunkLayoutEngine::PreparedChunk> m_preparedChunks;
QVector<ChunkLayout> m_chunkLayouts;
int m_layoutContentWidth = 600;
int m_layoutFontSize = 16;
qreal m_layoutLineSpacing = 1.0;
int m_layoutGeneration = 0;
QFuture<void> m_layoutFuture;
QTimer *m_remainingLayoutTimer = nullptr;
bool m_mangaLandscape = false;
bool m_pageShift = true;
@@ -103,6 +117,7 @@ private:
QVector<PageInfo> m_pages;
MangaPagination m_pagination;
qreal m_progress = 0.0;
qreal m_intraOffset = 0.0;
BookPositionStore &m_positions;
};
-17
View File
@@ -32,23 +32,6 @@ QString Book::author() const { return m_reader ? m_reader->author() : QString();
QString Book::filePath() const { return m_reader ? m_reader->filePath() : QString(); }
QString Book::coverImageUrl() const { return m_reader ? m_reader->coverImageUrl() : QString(); }
QVariantList Book::tableOfContents() const
{
if (!m_reader)
return {};
const auto toc = m_reader->tableOfContents();
QVariantList list;
list.reserve(toc.size());
for (const auto &entry : toc) {
list.append(QVariantMap{
{QStringLiteral("title"), entry.title},
{QStringLiteral("chapterIndex"), entry.chapterIndex},
{QStringLiteral("depth"), entry.depth}
});
}
return list;
}
FormatReader *Book::reader() const
{
return m_reader.get();
-2
View File
@@ -22,7 +22,6 @@ class Book : public QObject {
Q_PROPERTY(QString filePath READ filePath NOTIFY bookChanged)
Q_PROPERTY(QString coverImageUrl READ coverImageUrl NOTIFY bookChanged)
Q_PROPERTY(QString errorMessage READ errorMessage NOTIFY errorMessageChanged)
Q_PROPERTY(QVariantList tableOfContents READ tableOfContents NOTIFY bookChanged)
public:
Book(IFileDialogService &dialog,
@@ -37,7 +36,6 @@ public:
QString filePath() const;
QString coverImageUrl() const;
QString errorMessage() const;
QVariantList tableOfContents() const;
// Access the underlying reader (e.g. to push into ReadingModel).
FormatReader *reader() const;
+340
View File
@@ -0,0 +1,340 @@
#include "EpubReader.h"
#include <QDir>
#include <QDomDocument>
#include <QFontDatabase>
#include <QFileInfo>
#include <QSet>
#include <QTextStream>
#include <QUrl>
#include <QXmlStreamReader>
#include "backend/formats/HtmlEntities.h"
#include "backend/formats/ImageUrl.h"
#include "backend/reading/layout/CssParser.h"
EpubReader::EpubReader(SourceFactory sourceFactory, QString scheme)
: m_sourceFactory(std::move(sourceFactory))
, m_scheme(std::move(scheme))
{
}
QString EpubReader::coverImageUrl() const
{
if (m_coverEntry.isEmpty())
return {};
return ImageUrl::build(m_scheme, m_coverEntry, m_filePath);
}
bool EpubReader::parseContainer(const QByteArray &data, QString &outOpfPath)
{
QXmlStreamReader xml(data);
while (!xml.atEnd()) {
xml.readNext();
if (xml.isStartElement() && xml.name() == QLatin1String("rootfile")) {
outOpfPath = xml.attributes().value(QLatin1String("full-path")).toString();
if (!outOpfPath.isEmpty())
return true;
}
}
return false;
}
bool EpubReader::parseOpf(const QByteArray &data, IByteSource &source, bool metadataOnly)
{
QXmlStreamReader xml(data);
QString coverId;
static const QLatin1String kDcNs("http://purl.org/dc/elements/1.1/");
while (!xml.atEnd()) {
xml.readNext();
if (!xml.isStartElement())
continue;
const QStringView name = xml.name();
const QStringView ns = xml.namespaceUri();
if (name == QLatin1String("title") && (ns == kDcNs || ns.isEmpty())) {
if (m_title.isEmpty())
m_title = xml.readElementText().trimmed();
} else if (name == QLatin1String("creator") && (ns == kDcNs || ns.isEmpty())) {
if (m_author.isEmpty())
m_author = xml.readElementText().trimmed();
} else if (name == QLatin1String("meta")) {
const auto attrs = xml.attributes();
if (attrs.value(QLatin1String("name")) == QLatin1String("cover"))
coverId = attrs.value(QLatin1String("content")).toString();
else if (attrs.value(QLatin1String("content")) == QLatin1String("cover"))
coverId = attrs.value(QLatin1String("name")).toString();
} else if (name == QLatin1String("item")) {
const auto attrs = xml.attributes();
const QString id = attrs.value(QLatin1String("id")).toString();
const QString rawHref = attrs.value(QLatin1String("href")).toString();
const QString href = QUrl::fromPercentEncoding(rawHref.toUtf8());
const QString mediaType = attrs.value(QLatin1String("media-type")).toString().toLower();
const QString props = attrs.value(QLatin1String("properties")).toString();
if (!id.isEmpty() && !href.isEmpty()) {
m_manifest.insert(id, {href, mediaType, props});
if (props.contains(QLatin1String("cover-image")))
coverId = id;
// Load embedded fonts
if (!metadataOnly && (mediaType.startsWith(QLatin1String("font/"))
|| mediaType.startsWith(QLatin1String("application/font"))
|| mediaType.startsWith(QLatin1String("application/x-font"))
|| mediaType == QLatin1String("application/vnd.ms-opentype"))) {
const QString fontPath = QDir::cleanPath(m_opfDir + href);
const QByteArray fontData = source.readEntry(fontPath);
if (!fontData.isEmpty()) {
QFontDatabase::addApplicationFontFromData(fontData);
}
}
}
} else if (name == QLatin1String("itemref")) {
const auto attrs = xml.attributes();
const QString idref = attrs.value(QLatin1String("idref")).toString();
if (m_manifest.contains(idref)) {
const QString resolved = QDir::cleanPath(m_opfDir + m_manifest[idref].href);
m_spineHrefs.append(resolved);
}
}
}
if (!coverId.isEmpty() && m_manifest.contains(coverId)) {
m_coverEntry = QDir::cleanPath(m_opfDir + m_manifest[coverId].href);
} else {
// Fallback: look for item with id cover/cover-image and image media type
for (auto it = m_manifest.begin(); it != m_manifest.end(); ++it) {
if (it.key().contains(QLatin1String("cover"), Qt::CaseInsensitive)
&& it.value().mediaType.startsWith(QLatin1String("image/"))) {
m_coverEntry = QDir::cleanPath(m_opfDir + it.value().href);
break;
}
}
}
return true;
}
void EpubReader::appendSpineChunks(const QString &xhtml,
const QString &xhtmlHref,
IByteSource &source,
QHash<QString, Css::StyleSheet> &cssCache,
QSet<QString> &loadedFonts)
{
const QString safeXml = HtmlEntities::toXmlSafe(xhtml);
QDomDocument doc;
if (!doc.setContent(safeXml)) {
m_chunks.append(xhtml);
return;
}
const int lastSlash = xhtmlHref.lastIndexOf(QLatin1Char('/'));
const QString xhtmlDir = (lastSlash >= 0) ? xhtmlHref.left(lastSlash + 1) : QString();
Css::StyleSheet sheet;
// 1. External stylesheets <link rel="stylesheet" href="..."/>
QDomNodeList links = doc.elementsByTagName(QStringLiteral("link"));
for (int i = 0; i < links.size(); ++i) {
QDomElement linkEl = links.at(i).toElement();
if (linkEl.attribute(QStringLiteral("rel")).toLower() == QLatin1String("stylesheet")) {
QString href = linkEl.attribute(QStringLiteral("href"));
href = QUrl::fromPercentEncoding(href.toUtf8());
const QString cssPath = QDir::cleanPath(xhtmlDir + href);
auto it = cssCache.constFind(cssPath);
if (it != cssCache.constEnd()) {
sheet.append(it.value());
} else {
const QByteArray cssData = source.readEntry(cssPath);
if (!cssData.isEmpty()) {
Css::StyleSheet parsedSheet = Css::StyleSheet::parse(QString::fromUtf8(cssData));
sheet.append(parsedSheet);
cssCache.insert(cssPath, parsedSheet);
}
}
}
}
// 2. Embedded <style> blocks
QDomNodeList styles = doc.elementsByTagName(QStringLiteral("style"));
for (int i = 0; i < styles.size(); ++i) {
sheet.append(Css::StyleSheet::parse(styles.at(i).toElement().text()));
}
// 3. Resolve CSS fonts if any
for (const auto &ff : sheet.fontFaces) {
if (!ff.src.isEmpty()) {
const QString fontPath = QDir::cleanPath(xhtmlDir + ff.src);
if (!loadedFonts.contains(fontPath)) {
loadedFonts.insert(fontPath);
const QByteArray fData = source.readEntry(fontPath);
if (!fData.isEmpty()) {
QFontDatabase::addApplicationFontFromData(fData);
}
}
}
}
// 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);
}
}
};
QDomElement root = doc.documentElement();
processElement(root);
// 5. Chunk <body> directly from modified DOM
QDomNodeList bodies = doc.elementsByTagName(QStringLiteral("body"));
if (bodies.isEmpty()) {
QString serialized;
QTextStream ts(&serialized);
doc.save(ts, 0);
m_chunks.append(serialized);
return;
}
QDomElement body = bodies.at(0).toElement();
QString currentChunk;
static constexpr int kChunkTargetSize = 4096;
for (QDomNode node = body.firstChild(); !node.isNull(); node = node.nextSibling()) {
QString serialized;
QTextStream ts(&serialized);
node.save(ts, 0);
if (!currentChunk.isEmpty() && (currentChunk.size() + serialized.size() > kChunkTargetSize)) {
m_chunks.append(currentChunk);
currentChunk.clear();
}
currentChunk += serialized;
}
if (!currentChunk.isEmpty())
m_chunks.append(currentChunk);
}
bool EpubReader::parseOpen(const QString &filePath, IByteSource &source, bool metadataOnly)
{
m_filePath = filePath;
// 1. container.xml
const QByteArray containerData = source.readEntry(QStringLiteral("META-INF/container.xml"));
if (containerData.isEmpty()) {
m_error = QStringLiteral("Missing or invalid META-INF/container.xml");
return false;
}
QString opfPath;
if (!parseContainer(containerData, opfPath)) {
m_error = QStringLiteral("Could not find OPF rootfile path in container.xml");
return false;
}
const int lastSlash = opfPath.lastIndexOf(QLatin1Char('/'));
m_opfDir = (lastSlash >= 0) ? opfPath.left(lastSlash + 1) : QString();
// 2. OPF
const QByteArray opfData = source.readEntry(opfPath);
if (opfData.isEmpty()) {
m_error = QStringLiteral("Cannot read OPF file: ") + opfPath;
return false;
}
if (!parseOpf(opfData, source, metadataOnly)) {
m_error = QStringLiteral("Error parsing OPF package");
return false;
}
if (m_title.isEmpty())
m_title = QFileInfo(filePath).completeBaseName();
if (!metadataOnly) {
QHash<QString, Css::StyleSheet> cssCache;
QSet<QString> loadedFonts;
m_chunks.clear();
for (const QString &href : m_spineHrefs) {
const QByteArray xhtmlData = source.readEntry(href);
if (!xhtmlData.isEmpty()) {
appendSpineChunks(QString::fromUtf8(xhtmlData), href, source, cssCache, loadedFonts);
}
}
if (m_chunks.isEmpty()) {
m_chunks.append(QStringLiteral("<p></p>"));
}
}
m_filePath = filePath;
return true;
}
bool EpubReader::open(const QString &filePath)
{
m_title.clear();
m_author.clear();
m_error.clear();
m_opfDir.clear();
m_coverEntry.clear();
m_manifest.clear();
m_spineHrefs.clear();
m_chunks.clear();
m_contentHash.clear();
m_filePath.clear();
auto source = m_sourceFactory();
if (!source || !source->open(filePath)) {
m_error = QStringLiteral("Cannot open EPUB file: ") + filePath;
return false;
}
m_contentHash = source->contentHash();
return parseOpen(filePath, *source, false);
}
bool EpubReader::loadMetadata(const QString &filePath)
{
m_title.clear();
m_author.clear();
m_error.clear();
m_opfDir.clear();
m_coverEntry.clear();
m_manifest.clear();
m_spineHrefs.clear();
m_chunks.clear();
m_contentHash.clear();
m_filePath.clear();
auto source = m_sourceFactory();
if (!source || !source->open(filePath)) {
m_error = QStringLiteral("Cannot open EPUB file: ") + filePath;
return false;
}
return parseOpen(filePath, *source, true);
}
+66
View File
@@ -0,0 +1,66 @@
#pragma once
#include <functional>
#include <memory>
#include <QByteArray>
#include <QHash>
#include <QSet>
#include <QString>
#include <QStringList>
#include <QVector>
#include "backend/FormatReader.h"
#include "backend/formats/IByteSource.h"
#include "backend/reading/layout/CssParser.h"
class EpubReader : public FormatReader {
public:
using SourceFactory = std::function<std::unique_ptr<IByteSource>()>;
EpubReader(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;
QByteArray contentHash() const override { return m_contentHash; }
QStringList chunks() const override { return m_chunks; }
private:
struct ManifestItem {
QString href;
QString mediaType;
QString properties;
};
bool parseOpen(const QString &filePath, IByteSource &source, bool metadataOnly);
bool parseContainer(const QByteArray &data, QString &outOpfPath);
bool parseOpf(const QByteArray &data, IByteSource &source, bool metadataOnly);
void appendSpineChunks(const QString &xhtml,
const QString &xhtmlHref,
IByteSource &source,
QHash<QString, Css::StyleSheet> &cssCache,
QSet<QString> &loadedFonts);
SourceFactory m_sourceFactory;
QString m_scheme;
QString m_filePath;
QByteArray m_contentHash;
QString m_title;
QString m_author;
QString m_error;
QString m_opfDir;
QString m_coverEntry;
QHash<QString, ManifestItem> m_manifest; // id -> item
QStringList m_spineHrefs; // ordered spine relative hrefs
QStringList m_chunks;
};
+21
View File
@@ -3,6 +3,7 @@
#include "EntryImageProvider.h"
#include "backend/FormatReader.h"
#include "backend/formats/comic/ComicReader.h"
#include "backend/formats/EpubReader.h"
#include <QFileInfo>
#include <QQmlEngine>
@@ -19,6 +20,17 @@ FormatSpec FormatSpec::comic(const QString &ext, bool matchesDirectory, const QS
};
}
FormatSpec FormatSpec::epub(SourceFactory makeSource)
{
return FormatSpec{
QStringLiteral("epub"),
false,
QStringLiteral("epub"),
[makeSource] { return std::make_unique<EpubReader>(makeSource, QStringLiteral("epub")); },
makeSource
};
}
FormatRegistry::FormatRegistry(QVector<FormatSpec> specs)
: m_specs(std::move(specs))
{
@@ -43,6 +55,15 @@ std::unique_ptr<FormatReader> FormatRegistry::createReader(const QString &filePa
return spec ? spec->makeReader() : nullptr;
}
std::unique_ptr<IByteSource> FormatRegistry::createByteSourceForScheme(const QString &scheme) const
{
for (const FormatSpec &spec : m_specs) {
if (spec.scheme == scheme && spec.makeSource)
return spec.makeSource();
}
return nullptr;
}
QStringList FormatRegistry::supportedExtensions() const
{
QStringList out;
+2
View File
@@ -25,6 +25,7 @@ struct FormatSpec {
static FormatSpec comic(const QString &ext, bool matchesDirectory, const QString &scheme,
SourceFactory makeSource);
static FormatSpec epub(SourceFactory makeSource);
};
class FormatRegistry {
@@ -32,6 +33,7 @@ public:
explicit FormatRegistry(QVector<FormatSpec> specs);
std::unique_ptr<FormatReader> createReader(const QString &filePath) const;
std::unique_ptr<IByteSource> createByteSourceForScheme(const QString &scheme) const;
QStringList supportedExtensions() const;
// Register one provider per scheme with the QML engine (engine takes ownership).
+101
View File
@@ -0,0 +1,101 @@
#include "HtmlEntities.h"
#include <QHash>
namespace HtmlEntities {
namespace {
const QHash<QString, int> &entityTable()
{
static const QHash<QString, int> table = [] {
QHash<QString, int> t;
static const char *const latin1[] = {
"nbsp", "iexcl", "cent", "pound", "curren", "yen", "brvbar", "sect", "uml", "copy",
"ordf", "laquo", "not", "shy", "reg", "macr", "deg", "plusmn", "sup2", "sup3",
"acute", "micro", "para", "middot", "cedil", "sup1", "ordm", "raquo", "frac14", "frac12",
"frac34", "iquest", "Agrave", "Aacute", "Acirc", "Atilde", "Auml", "Aring", "AElig", "Ccedil",
"Egrave", "Eacute", "Ecirc", "Euml", "Igrave", "Iacute", "Icirc", "Iuml", "ETH", "Ntilde",
"Ograve", "Oacute", "Ocirc", "Otilde", "Ouml", "times", "Oslash", "Ugrave", "Uacute", "Ucirc",
"Uuml", "Yacute", "THORN", "szlig", "agrave", "aacute", "acirc", "atilde", "auml", "aring",
"aelig", "ccedil", "egrave", "eacute", "ecirc", "euml", "igrave", "iacute", "icirc", "iuml",
"eth", "ntilde", "ograve", "oacute", "ocirc", "otilde", "ouml", "divide", "oslash", "ugrave",
"uacute", "ucirc", "uuml", "yacute", "thorn", "yuml",
};
for (int i = 0; i < int(sizeof(latin1) / sizeof(latin1[0])); ++i)
t.insert(QString::fromLatin1(latin1[i]), 160 + i);
static const struct { const char *name; int code; } others[] = {
{"OElig", 338}, {"oelig", 339}, {"Scaron", 352}, {"scaron", 353}, {"Yuml", 376},
{"fnof", 402}, {"circ", 710}, {"tilde", 732}, {"ensp", 8194}, {"emsp", 8195},
{"thinsp", 8201}, {"zwnj", 8204}, {"zwj", 8205}, {"lrm", 8206}, {"rlm", 8207},
{"ndash", 8211}, {"mdash", 8212}, {"lsquo", 8216}, {"rsquo", 8217}, {"sbquo", 8218},
{"ldquo", 8220}, {"rdquo", 8221}, {"bdquo", 8222}, {"dagger", 8224}, {"Dagger", 8225},
{"bull", 8226}, {"hellip", 8230}, {"permil", 8240}, {"prime", 8242}, {"Prime", 8243},
{"lsaquo", 8249}, {"rsaquo", 8250}, {"oline", 8254}, {"euro", 8364}, {"trade", 8482},
{"larr", 8592}, {"uarr", 8593}, {"rarr", 8594}, {"darr", 8595}, {"harr", 8596},
{"minus", 8722}, {"infin", 8734}, {"asymp", 8776}, {"ne", 8800}, {"le", 8804},
{"ge", 8805}, {"alpha", 945}, {"beta", 946}, {"gamma", 947}, {"delta", 948},
{"epsilon", 949}, {"theta", 952}, {"lambda", 955}, {"mu", 956}, {"pi", 960},
{"sigma", 963}, {"tau", 964}, {"phi", 966}, {"omega", 969}, {"Omega", 937},
};
for (const auto &e : others)
t.insert(QString::fromLatin1(e.name), e.code);
return t;
}();
return table;
}
bool isXmlEntity(QStringView name)
{
return name == QLatin1String("amp") || name == QLatin1String("lt") || name == QLatin1String("gt")
|| name == QLatin1String("quot") || name == QLatin1String("apos");
}
} // namespace
QString toXmlSafe(const QString &html)
{
if (!html.contains(QLatin1Char('&')))
return html;
QString out;
out.reserve(html.size() + 16);
const int n = html.size();
int i = 0;
while (i < n) {
const QChar c = html[i];
if (c != QLatin1Char('&')) {
out += c;
++i;
continue;
}
// Numeric references pass through unchanged.
if (i + 1 < n && html[i + 1] == QLatin1Char('#')) {
out += c;
++i;
continue;
}
int j = i + 1;
while (j < n && j - i <= 32 && html[j].isLetterOrNumber())
++j;
const QStringView name = QStringView(html).mid(i + 1, j - i - 1);
if (j < n && html[j] == QLatin1Char(';') && !name.isEmpty()) {
if (isXmlEntity(name)) {
out += QStringView(html).mid(i, j - i + 1);
} else if (const auto it = entityTable().constFind(name.toString()); it != entityTable().cend()) {
out += QStringLiteral("&#") + QString::number(it.value()) + QLatin1Char(';');
} else {
out += QStringLiteral("&amp;") + name + QLatin1Char(';');
}
i = j + 1;
} else {
out += QStringLiteral("&amp;"); // bare ampersand
++i;
}
}
return out;
}
} // namespace HtmlEntities
+14
View File
@@ -0,0 +1,14 @@
#pragma once
#include <QString>
namespace HtmlEntities {
// Rewrites HTML named character references (e.g. "&nbsp;", "&mdash;") to
// numeric references so the text parses as plain XML. The five XML entities
// are kept; unknown names are escaped ("&foo;" -> "&amp;foo;") so the parse
// does not fail on them.
QString toXmlSafe(const QString &html);
} // namespace HtmlEntities
+217
View File
@@ -0,0 +1,217 @@
#include "WebImageProvider.h"
#include <QCryptographicHash>
#include <QDir>
#include <QEventLoop>
#include <QFile>
#include <QFileInfo>
#include <QMutexLocker>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QSaveFile>
#include <QStandardPaths>
#include <QThreadPool>
#include <QUrl>
#include "AsyncImageResponse.h"
#include "ImageScaling.h"
// ---------------------------------------------------------------------------
// DiskWebImageStorage
// ---------------------------------------------------------------------------
DiskWebImageStorage::DiskWebImageStorage()
: DiskWebImageStorage(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral("/web-images"))
{
}
DiskWebImageStorage::DiskWebImageStorage(QString baseDir)
: m_baseDir(std::move(baseDir))
{
if (!m_baseDir.isEmpty()) {
QDir().mkpath(m_baseDir);
}
}
QString DiskWebImageStorage::filePathForKey(const QString &key) const
{
return m_baseDir + QLatin1Char('/') + key;
}
bool DiskWebImageStorage::contains(const QString &key) const
{
QMutexLocker lock(&m_mutex);
return QFile::exists(filePathForKey(key));
}
QByteArray DiskWebImageStorage::read(const QString &key) const
{
QMutexLocker lock(&m_mutex);
QFile f(filePathForKey(key));
if (f.open(QIODevice::ReadOnly))
return f.readAll();
return {};
}
bool DiskWebImageStorage::write(const QString &key, const QByteArray &data)
{
QMutexLocker lock(&m_mutex);
if (m_baseDir.isEmpty() || data.isEmpty())
return false;
QDir().mkpath(m_baseDir);
QSaveFile f(filePathForKey(key));
if (!f.open(QIODevice::WriteOnly))
return false;
f.write(data);
return f.commit();
}
// ---------------------------------------------------------------------------
// Default Network Fetcher
// ---------------------------------------------------------------------------
static QByteArray defaultHttpFetch(const QString &urlString)
{
QUrl url(urlString);
if (!url.isValid() || (url.scheme() != QLatin1String("http") && url.scheme() != QLatin1String("https")))
return {};
QNetworkAccessManager nam;
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::UserAgentHeader, QStringLiteral("Asteria/1.0"));
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
request.setTransferTimeout(5000);
QNetworkReply *reply = nam.get(request);
QEventLoop loop;
QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
if (reply->error() != QNetworkReply::NoError) {
reply->deleteLater();
return {};
}
const QByteArray data = reply->readAll();
reply->deleteLater();
return data;
}
// ---------------------------------------------------------------------------
// WebImageProvider
// ---------------------------------------------------------------------------
WebImageProvider::WebImageProvider()
: WebImageProvider(std::make_shared<DiskWebImageStorage>(), defaultHttpFetch)
{
}
WebImageProvider::WebImageProvider(std::shared_ptr<IWebImageStorage> storage,
HttpFetcher fetcher)
: m_storage(std::move(storage))
, m_fetcher(fetcher ? std::move(fetcher) : defaultHttpFetch)
{
}
WebImageProvider *WebImageProvider::defaultInstance()
{
static WebImageProvider s_instance;
return &s_instance;
}
void WebImageProvider::setStorage(std::shared_ptr<IWebImageStorage> storage)
{
QMutexLocker lock(&m_imageMutex);
m_storage = std::move(storage);
m_memoryCache.clear();
}
void WebImageProvider::setFetcher(HttpFetcher fetcher)
{
QMutexLocker lock(&m_imageMutex);
m_fetcher = fetcher ? std::move(fetcher) : defaultHttpFetch;
}
QString WebImageProvider::cacheKey(const QString &url)
{
const QByteArray hash = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Sha256).toHex();
const QString ext = QFileInfo(QUrl(url).path()).suffix().toLower();
if (!ext.isEmpty() && (ext == QLatin1String("png") || ext == QLatin1String("jpg")
|| ext == QLatin1String("jpeg") || ext == QLatin1String("gif")
|| ext == QLatin1String("webp") || ext == QLatin1String("svg"))) {
return QString::fromLatin1(hash) + QLatin1Char('.') + ext;
}
return QString::fromLatin1(hash);
}
QImage WebImageProvider::fetchImage(const QString &urlString, const QSize &requestedSize)
{
if (urlString.isEmpty())
return {};
// 1. In-memory cache
{
QMutexLocker lock(&m_imageMutex);
auto it = m_memoryCache.find(urlString);
if (it != m_memoryCache.end())
return scaleToFit(*it, requestedSize);
}
const QString key = cacheKey(urlString);
// 2. Persistent storage (disk or mock)
if (m_storage && m_storage->contains(key)) {
const QByteArray data = m_storage->read(key);
if (!data.isEmpty()) {
QImage img;
if (img.loadFromData(data)) {
QMutexLocker lock(&m_imageMutex);
m_memoryCache.insert(urlString, img);
return scaleToFit(img, requestedSize);
}
}
}
// 3. Network fetch
if (!m_fetcher)
return {};
const QByteArray fetched = m_fetcher(urlString);
if (fetched.isEmpty())
return {};
QImage img;
if (!img.loadFromData(fetched))
return {};
// Store
if (m_storage) {
m_storage->write(key, fetched);
}
{
QMutexLocker lock(&m_imageMutex);
m_memoryCache.insert(urlString, img);
}
return scaleToFit(img, requestedSize);
}
QQuickImageResponse *WebImageProvider::requestImageResponse(const QString &id,
const QSize &requestedSize)
{
if (id == QLatin1String("__warmup__")) {
auto *response = new AsyncImageResponse([] { return QImage(); });
QMetaObject::invokeMethod(response, "finished", Qt::QueuedConnection);
return response;
}
auto *response = new AsyncImageResponse([this, id, requestedSize]() -> QImage {
return fetchImage(id, requestedSize);
});
QThreadPool::globalInstance()->start(response);
return response;
}
+67
View File
@@ -0,0 +1,67 @@
#pragma once
#include <QByteArray>
#include <QImage>
#include <QMutex>
#include <QQuickAsyncImageProvider>
#include <QString>
#include <functional>
#include <memory>
class IWebImageStorage {
public:
virtual ~IWebImageStorage() = default;
virtual bool contains(const QString &key) const = 0;
virtual QByteArray read(const QString &key) const = 0;
virtual bool write(const QString &key, const QByteArray &data) = 0;
};
class DiskWebImageStorage : public IWebImageStorage {
public:
DiskWebImageStorage();
explicit DiskWebImageStorage(QString baseDir);
bool contains(const QString &key) const override;
QByteArray read(const QString &key) const override;
bool write(const QString &key, const QByteArray &data) override;
QString cacheDir() const { return m_baseDir; }
private:
QString filePathForKey(const QString &key) const;
QString m_baseDir;
mutable QMutex m_mutex;
};
class WebImageProvider : public QQuickAsyncImageProvider {
public:
using HttpFetcher = std::function<QByteArray(const QString &url)>;
WebImageProvider();
explicit WebImageProvider(std::shared_ptr<IWebImageStorage> storage,
HttpFetcher fetcher = nullptr);
QQuickImageResponse *requestImageResponse(const QString &id,
const QSize &requestedSize) override;
QString scheme() const { return QStringLiteral("web"); }
static QString cacheKey(const QString &url);
// Synchronous download or cache lookup (safe across threads)
QImage fetchImage(const QString &url, const QSize &requestedSize = {});
// Set custom storage & fetcher (e.g. for unit tests)
void setStorage(std::shared_ptr<IWebImageStorage> storage);
void setFetcher(HttpFetcher fetcher);
// Global default instance for non-QML direct resolution
static WebImageProvider *defaultInstance();
private:
std::shared_ptr<IWebImageStorage> m_storage;
HttpFetcher m_fetcher;
mutable QMutex m_imageMutex;
QHash<QString, QImage> m_memoryCache;
};
+57 -7
View File
@@ -2,7 +2,6 @@
#include <algorithm>
#include <QBuffer>
#include <QCollator>
#include <QFileInfo>
#include <QImageReader>
#include <QXmlStreamReader>
@@ -55,17 +54,68 @@ static void parseComicInfo(const QByteArray &data,
outAuthor = writer;
}
static int naturalCompare(QStringView a, QStringView b)
{
int i = 0, j = 0;
const int lenA = a.size();
const int lenB = b.size();
while (i < lenA && j < lenB) {
const QChar ca = a[i];
const QChar cb = b[j];
if (ca.isDigit() && cb.isDigit()) {
const int startA = i;
while (i < lenA && a[i] == QLatin1Char('0'))
++i;
const int startB = j;
while (j < lenB && b[j] == QLatin1Char('0'))
++j;
const int numStartA = i;
while (i < lenA && a[i].isDigit())
++i;
const int numStartB = j;
while (j < lenB && b[j].isDigit())
++j;
const int numLenA = i - numStartA;
const int numLenB = j - numStartB;
if (numLenA != numLenB)
return (numLenA < numLenB) ? -1 : 1;
for (int kA = numStartA, kB = numStartB; kA < i; ++kA, ++kB) {
if (a[kA] != b[kB])
return (a[kA] < b[kB]) ? -1 : 1;
}
const int zerosA = numStartA - startA;
const int zerosB = numStartB - startB;
if (zerosA != zerosB)
return (zerosA < zerosB) ? -1 : 1;
} else {
const QChar la = ca.toLower();
const QChar lb = cb.toLower();
if (la != lb)
return (la < lb) ? -1 : 1;
++i;
++j;
}
}
if (i < lenA) return 1;
if (j < lenB) return -1;
return 0;
}
static void naturalSortEntries(QStringList &entries)
{
if (entries.size() <= 1)
return;
QCollator collator{QLocale(QLocale::English)};
collator.setNumericMode(true);
collator.setCaseSensitivity(Qt::CaseInsensitive);
std::sort(entries.begin(), entries.end(), [&collator](const QString &a, const QString &b) {
const int cmp = collator.compare(a, b);
std::sort(entries.begin(), entries.end(), [](const QString &a, const QString &b) {
const int cmp = naturalCompare(a, b);
if (cmp != 0)
return cmp < 0;
return a < b;
+79 -28
View File
@@ -1,20 +1,19 @@
#include "ZipByteSource.h"
#include <minizip/unzip.h>
#include <QMutexLocker>
#include <memory>
namespace {
QByteArray readZipEntry(unzFile zf, const char *entryName)
QByteArray readCurrentZipEntry(unzFile zf)
{
if (unzLocateFile(zf, entryName, 0) != UNZ_OK)
return {};
if (unzOpenCurrentFile(zf) != UNZ_OK)
return {};
QByteArray result;
char buf[4096];
int bytesRead;
char buf[16384];
int bytesRead = 0;
while ((bytesRead = unzReadCurrentFile(zf, buf, sizeof(buf))) > 0)
result.append(buf, bytesRead);
@@ -22,27 +21,56 @@ QByteArray readZipEntry(unzFile zf, const char *entryName)
return (bytesRead == 0) ? result : QByteArray{};
}
QStringList listZipEntries(unzFile zf)
} // namespace
ZipByteSource::ZipByteSource() = default;
ZipByteSource::~ZipByteSource()
{
QStringList entries;
if (unzGoToFirstFile(zf) != UNZ_OK)
return entries;
do {
char name[4096];
unz_file_info64 info{};
if (unzGetCurrentFileInfo64(zf, &info, name, static_cast<uLong>(sizeof(name) - 1),
nullptr, 0, nullptr, 0) == UNZ_OK) {
name[sizeof(name) - 1] = '\0';
entries.append(QString::fromUtf8(name));
}
} while (unzGoToNextFile(zf) == UNZ_OK);
return entries;
closeArchive();
}
} // namespace
ZipByteSource::ZipByteSource(ZipByteSource &&other) noexcept
{
QMutexLocker locker(&other.m_mutex);
m_path = std::move(other.m_path);
m_hash = std::move(other.m_hash);
m_entries = std::move(other.m_entries);
m_entryPositions = std::move(other.m_entryPositions);
m_zf = other.m_zf;
other.m_zf = nullptr;
}
ZipByteSource &ZipByteSource::operator=(ZipByteSource &&other) noexcept
{
if (this != &other) {
closeArchive();
QMutexLocker locker(&other.m_mutex);
m_path = std::move(other.m_path);
m_hash = std::move(other.m_hash);
m_entries = std::move(other.m_entries);
m_entryPositions = std::move(other.m_entryPositions);
m_zf = other.m_zf;
other.m_zf = nullptr;
}
return *this;
}
void ZipByteSource::closeArchive()
{
QMutexLocker locker(&m_mutex);
if (m_zf) {
unzClose(static_cast<unzFile>(m_zf));
m_zf = nullptr;
}
m_entryPositions.clear();
}
bool ZipByteSource::open(const QString &path)
{
closeArchive();
QMutexLocker locker(&m_mutex);
m_path.clear();
m_hash.clear();
m_entries.clear();
@@ -50,9 +78,24 @@ bool ZipByteSource::open(const QString &path)
unzFile zf = unzOpen(path.toUtf8().constData());
if (!zf)
return false;
m_entries = listZipEntries(zf);
unzClose(zf);
if (unzGoToFirstFile(zf) == UNZ_OK) {
do {
char name[4096];
unz_file_info64 info{};
unz64_file_pos pos{};
unzGetFilePos64(zf, &pos);
if (unzGetCurrentFileInfo64(zf, &info, name, static_cast<uLong>(sizeof(name) - 1),
nullptr, 0, nullptr, 0) == UNZ_OK) {
name[sizeof(name) - 1] = '\0';
const QString entryName = QString::fromUtf8(name);
m_entries.append(entryName);
m_entryPositions.insert(entryName, pos);
}
} while (unzGoToNextFile(zf) == UNZ_OK);
}
m_zf = zf;
m_path = path;
return true;
}
@@ -64,14 +107,22 @@ QStringList ZipByteSource::listEntries() const
QByteArray ZipByteSource::readEntry(const QString &entryName) const
{
if (m_path.isEmpty() || entryName.isEmpty())
QMutexLocker locker(&m_mutex);
if (!m_zf || entryName.isEmpty())
return {};
unzFile zf = unzOpen(m_path.toUtf8().constData());
if (!zf)
unzFile zf = static_cast<unzFile>(m_zf);
auto it = m_entryPositions.constFind(entryName);
if (it != m_entryPositions.constEnd()) {
unz64_file_pos pos = it.value();
if (unzGoToFilePos64(zf, &pos) != UNZ_OK)
return {};
auto closeGuard = [](void *p) { unzClose(static_cast<unzFile>(p)); };
std::unique_ptr<void, decltype(closeGuard)> guard(zf, closeGuard);
return readZipEntry(zf, entryName.toUtf8().constData());
} else {
if (unzLocateFile(zf, entryName.toUtf8().constData(), 0) != UNZ_OK)
return {};
}
return readCurrentZipEntry(zf);
}
QByteArray ZipByteSource::contentHash() const
@@ -1,16 +1,32 @@
#pragma once
#include <QHash>
#include <QMutex>
#include <minizip/unzip.h>
#include "backend/formats/IByteSource.h"
class ZipByteSource : public IByteSource {
public:
ZipByteSource();
~ZipByteSource() override;
ZipByteSource(const ZipByteSource &) = delete;
ZipByteSource &operator=(const ZipByteSource &) = delete;
ZipByteSource(ZipByteSource &&other) noexcept;
ZipByteSource &operator=(ZipByteSource &&other) noexcept;
bool open(const QString &path) override;
QStringList listEntries() const override;
QByteArray readEntry(const QString &entryName) const override;
QByteArray contentHash() const override;
private:
void closeArchive();
QString m_path;
mutable QByteArray m_hash;
QStringList m_entries;
QHash<QString, unz64_file_pos> m_entryPositions;
void *m_zf = nullptr;
mutable QMutex m_mutex;
};
+199
View File
@@ -0,0 +1,199 @@
#include "BookImageResolver.h"
#include <QBuffer>
#include <QImageReader>
#include <QMutexLocker>
#include <QUrl>
#include "backend/formats/IByteSource.h"
#include "backend/formats/ImageUrl.h"
#include "backend/formats/WebImageProvider.h"
BookImageResolver::BookImageResolver()
: BookImageResolver(SourceFactory(nullptr), nullptr)
{
}
BookImageResolver::BookImageResolver(SourceFactory sourceFactory,
WebImageProvider *webProvider)
: m_sourceFactory(std::move(sourceFactory))
, m_webProvider(webProvider)
{
}
BookImageResolver::BookImageResolver(SchemeSourceFactory schemeSourceFactory,
WebImageProvider *webProvider)
: m_schemeSourceFactory(std::move(schemeSourceFactory))
, m_webProvider(webProvider)
{
}
void BookImageResolver::setSourceFactory(SourceFactory factory)
{
QMutexLocker lock(&m_cacheMutex);
m_sourceFactory = std::move(factory);
m_schemeSourceFactory = nullptr;
m_activeScheme.clear();
m_activeSourcePath.clear();
m_activeSource.reset();
m_cache.clear();
m_sizeCache.clear();
}
void BookImageResolver::setSchemeSourceFactory(SchemeSourceFactory factory)
{
QMutexLocker lock(&m_cacheMutex);
m_schemeSourceFactory = std::move(factory);
m_sourceFactory = nullptr;
m_activeScheme.clear();
m_activeSourcePath.clear();
m_activeSource.reset();
m_cache.clear();
m_sizeCache.clear();
}
void BookImageResolver::setWebProvider(WebImageProvider *provider)
{
QMutexLocker lock(&m_cacheMutex);
m_webProvider = provider;
}
void BookImageResolver::clearCache()
{
QMutexLocker lock(&m_cacheMutex);
m_activeScheme.clear();
m_activeSourcePath.clear();
m_activeSource.reset();
m_cache.clear();
m_sizeCache.clear();
}
QByteArray BookImageResolver::fetchEntryBytes(const QString &imageUrl)
{
if (!imageUrl.startsWith(QLatin1String("image://")))
return {};
const int slashIdx = imageUrl.indexOf(QLatin1Char('/'), 8);
if (slashIdx < 0)
return {};
const QString scheme = imageUrl.mid(8, slashIdx - 8);
if (scheme == QLatin1String("web") || scheme == QLatin1String("fileicon"))
return {};
const QString id = imageUrl.mid(slashIdx + 1);
const ImageUrl::Parsed parsed = ImageUrl::parseProviderId(id);
QMutexLocker lock(&m_cacheMutex);
const QString targetPath = !parsed.sourcePath.isEmpty() ? parsed.sourcePath : m_activeSourcePath;
if (targetPath.isEmpty() || parsed.entry.isEmpty())
return {};
if (m_activeScheme != scheme || m_activeSourcePath != targetPath || !m_activeSource) {
if (m_schemeSourceFactory) {
m_activeSource = m_schemeSourceFactory(scheme);
} else if (m_sourceFactory) {
m_activeSource = m_sourceFactory();
} else {
m_activeSource.reset();
}
if (m_activeSource && m_activeSource->open(targetPath)) {
m_activeScheme = scheme;
m_activeSourcePath = targetPath;
} else {
m_activeSource.reset();
m_activeScheme.clear();
m_activeSourcePath.clear();
}
}
if (m_activeSource) {
return m_activeSource->readEntry(parsed.entry);
}
return {};
}
QSizeF BookImageResolver::imageSize(const QString &imageUrl)
{
if (imageUrl.isEmpty())
return {};
{
QMutexLocker lock(&m_cacheMutex);
auto it = m_sizeCache.find(imageUrl);
if (it != m_sizeCache.end())
return *it;
auto imgIt = m_cache.find(imageUrl);
if (imgIt != m_cache.end())
return imgIt->size();
}
// Fast path: sniff header dimensions using QImageReader without full decompression
const QByteArray bytes = fetchEntryBytes(imageUrl);
if (!bytes.isEmpty()) {
QBuffer buffer;
buffer.setData(bytes);
buffer.open(QIODevice::ReadOnly);
QImageReader reader(&buffer);
const QSize sz = reader.size();
if (sz.isValid() && sz.width() > 0 && sz.height() > 0) {
const QSizeF sizeF(sz.width(), sz.height());
QMutexLocker lock(&m_cacheMutex);
m_sizeCache.insert(imageUrl, sizeF);
return sizeF;
}
}
// Fall back to resolving full image
const QImage img = resolveImage(imageUrl);
if (!img.isNull()) {
const QSizeF sizeF(img.width(), img.height());
QMutexLocker lock(&m_cacheMutex);
m_sizeCache.insert(imageUrl, sizeF);
return sizeF;
}
return {};
}
QImage BookImageResolver::resolveImage(const QString &imageUrl)
{
if (imageUrl.isEmpty())
return {};
{
QMutexLocker lock(&m_cacheMutex);
auto it = m_cache.find(imageUrl);
if (it != m_cache.end())
return *it;
}
QImage result;
if (imageUrl.startsWith(QLatin1String("image://web/"))) {
const QString actualUrl = imageUrl.mid(12);
WebImageProvider *p = m_webProvider ? m_webProvider : WebImageProvider::defaultInstance();
if (p)
result = p->fetchImage(actualUrl);
} else if (imageUrl.startsWith(QLatin1String("http://")) || imageUrl.startsWith(QLatin1String("https://"))) {
WebImageProvider *p = m_webProvider ? m_webProvider : WebImageProvider::defaultInstance();
if (p)
result = p->fetchImage(imageUrl);
} else if (imageUrl.startsWith(QLatin1String("image://"))) {
const QByteArray data = fetchEntryBytes(imageUrl);
if (!data.isEmpty()) {
result.loadFromData(data);
}
}
if (!result.isNull()) {
QMutexLocker lock(&m_cacheMutex);
m_cache.insert(imageUrl, result);
m_sizeCache.insert(imageUrl, result.size());
}
return result;
}
+54
View File
@@ -0,0 +1,54 @@
#pragma once
#include <QHash>
#include <QImage>
#include <QMutex>
#include <QSizeF>
#include <QString>
#include <functional>
#include <memory>
class IByteSource;
class WebImageProvider;
class IBookImageResolver {
public:
virtual ~IBookImageResolver() = default;
virtual QImage resolveImage(const QString &imageUrl) = 0;
virtual QSizeF imageSize(const QString &imageUrl) = 0;
};
class BookImageResolver : public IBookImageResolver {
public:
using SourceFactory = std::function<std::unique_ptr<IByteSource>()>;
using SchemeSourceFactory = std::function<std::unique_ptr<IByteSource>(const QString &scheme)>;
BookImageResolver();
explicit BookImageResolver(SourceFactory sourceFactory,
WebImageProvider *webProvider = nullptr);
explicit BookImageResolver(SchemeSourceFactory schemeSourceFactory,
WebImageProvider *webProvider = nullptr);
QImage resolveImage(const QString &imageUrl) override;
QSizeF imageSize(const QString &imageUrl) override;
void setSourceFactory(SourceFactory factory);
void setSchemeSourceFactory(SchemeSourceFactory factory);
void setWebProvider(WebImageProvider *provider);
void clearCache();
private:
QByteArray fetchEntryBytes(const QString &imageUrl);
SourceFactory m_sourceFactory;
SchemeSourceFactory m_schemeSourceFactory;
WebImageProvider *m_webProvider = nullptr;
mutable QMutex m_cacheMutex;
QHash<QString, QImage> m_cache;
QHash<QString, QSizeF> m_sizeCache;
QString m_activeScheme;
QString m_activeSourcePath;
std::unique_ptr<IByteSource> m_activeSource;
};
+182
View File
@@ -0,0 +1,182 @@
#include "KnuthPlassItem.h"
#include <QPainter>
#include "BookImageResolver.h"
BookImageResolver *KnuthPlassItem::s_imageResolver = nullptr;
KnuthPlassItem::KnuthPlassItem(QQuickItem *parent)
: QQuickPaintedItem(parent)
{
setAntialiasing(true);
setRenderTarget(QQuickPaintedItem::Image);
}
void KnuthPlassItem::setImageResolver(BookImageResolver *resolver)
{
s_imageResolver = resolver;
}
void KnuthPlassItem::setLayout(const QVariant &val)
{
m_layoutVariant = val;
if (val.canConvert<ChunkLayout>()) {
m_layout = val.value<ChunkLayout>();
} else {
m_layout = {};
}
setImplicitHeight(m_layout.totalHeight);
emit layoutChanged();
update();
}
void KnuthPlassItem::setTextColor(const QColor &c)
{
if (m_textColor != c) {
m_textColor = c;
emit colorsChanged();
update();
}
}
void KnuthPlassItem::setLinkColor(const QColor &c)
{
if (m_linkColor != c) {
m_linkColor = c;
emit colorsChanged();
update();
}
}
void KnuthPlassItem::setDimColor(const QColor &c)
{
if (m_dimColor != c) {
m_dimColor = c;
emit colorsChanged();
update();
}
}
void KnuthPlassItem::setHorizontalMargin(qreal m)
{
if (!qFuzzyCompare(m_horizontalMargin, m)) {
m_horizontalMargin = m;
emit horizontalMarginChanged();
update();
}
}
void KnuthPlassItem::geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry)
{
QQuickPaintedItem::geometryChange(newGeometry, oldGeometry);
if (newGeometry.size() != oldGeometry.size()) {
update();
}
}
void KnuthPlassItem::paint(QPainter *painter)
{
if (!painter)
return;
painter->setRenderHint(QPainter::Antialiasing, true);
painter->setRenderHint(QPainter::TextAntialiasing, true);
painter->setRenderHint(QPainter::SmoothPixmapTransform, true);
const qreal offX = m_horizontalMargin;
// 1. Draw block decorations (backgrounds & borders)
for (const auto &dec : m_layout.decorations) {
QRectF r = dec.rect;
r.translate(offX, 0);
if (dec.background.isValid()) {
painter->fillRect(r, dec.background);
}
QColor borderColor = dec.borderColor.isValid() ? dec.borderColor : m_dimColor;
if (dec.borderLeft > 0) {
painter->fillRect(QRectF(r.left(), r.top(), dec.borderLeft, r.height()), borderColor);
}
if (dec.borderTop > 0) {
painter->fillRect(QRectF(r.left(), r.top(), r.width(), dec.borderTop), borderColor);
}
if (dec.borderBottom > 0) {
painter->fillRect(QRectF(r.left(), r.bottom() - dec.borderBottom, r.width(), dec.borderBottom), borderColor);
}
}
// 2. Draw horizontal rules (<hr>)
for (const auto &rule : m_layout.rules) {
QRectF r = rule.rect;
r.translate(offX, 0);
painter->fillRect(r, rule.color.isValid() ? rule.color : m_dimColor);
}
// 3. Draw text runs
QFont currentFont;
QColor currentPenColor;
bool hasFont = false;
bool hasPen = false;
for (const auto &line : m_layout.lines) {
for (const auto &run : line.runs) {
QRectF r = run.rect;
r.translate(offX, 0);
// Highlight background
if (run.background.isValid()) {
painter->fillRect(r, run.background);
}
// Word text
QColor fg = run.color.isValid() ? run.color : (run.link ? m_linkColor : m_textColor);
if (!hasPen || currentPenColor != fg) {
painter->setPen(fg);
currentPenColor = fg;
hasPen = true;
}
if (!hasFont || currentFont != run.font) {
painter->setFont(run.font);
currentFont = run.font;
hasFont = true;
}
painter->drawText(QPointF(r.left(), run.baselineY), run.text);
// Text decorations
if (run.underline) {
qreal lineY = run.baselineY + 2.0;
painter->drawLine(QPointF(r.left(), lineY), QPointF(r.right(), lineY));
}
if (run.strikeOut) {
qreal lineY = run.baselineY - (run.font.pixelSize() * 0.35);
painter->drawLine(QPointF(r.left(), lineY), QPointF(r.right(), lineY));
}
if (run.overline) {
qreal lineY = run.baselineY - (run.font.pixelSize() * 0.85);
painter->drawLine(QPointF(r.left(), lineY), QPointF(r.right(), lineY));
}
}
}
// 4. Draw images
for (const auto &imgItem : m_layout.images) {
QRectF r = imgItem.targetRect;
r.translate(offX, 0);
QImage img;
if (s_imageResolver) {
img = s_imageResolver->resolveImage(imgItem.url);
}
if (!img.isNull()) {
painter->drawImage(r, img);
} else {
// Placeholder rect
painter->setPen(m_dimColor);
painter->drawRect(r);
}
}
}
+61
View File
@@ -0,0 +1,61 @@
#pragma once
#include <QColor>
#include <QPainter>
#include <QQuickPaintedItem>
#include <QVariant>
#include "layout/ChunkLayoutEngine.h"
class BookImageResolver;
class KnuthPlassItem : public QQuickPaintedItem {
Q_OBJECT
Q_PROPERTY(QVariant layout READ layout WRITE setLayout NOTIFY layoutChanged)
Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor NOTIFY colorsChanged)
Q_PROPERTY(QColor linkColor READ linkColor WRITE setLinkColor NOTIFY colorsChanged)
Q_PROPERTY(QColor dimColor READ dimColor WRITE setDimColor NOTIFY colorsChanged)
Q_PROPERTY(qreal horizontalMargin READ horizontalMargin WRITE setHorizontalMargin NOTIFY horizontalMarginChanged)
public:
explicit KnuthPlassItem(QQuickItem *parent = nullptr);
QVariant layout() const { return m_layoutVariant; }
void setLayout(const QVariant &val);
QColor textColor() const { return m_textColor; }
void setTextColor(const QColor &c);
QColor linkColor() const { return m_linkColor; }
void setLinkColor(const QColor &c);
QColor dimColor() const { return m_dimColor; }
void setDimColor(const QColor &c);
qreal horizontalMargin() const { return m_horizontalMargin; }
void setHorizontalMargin(qreal m);
void paint(QPainter *painter) override;
static void setImageResolver(BookImageResolver *resolver);
protected:
void geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry) override;
signals:
void layoutChanged();
void colorsChanged();
void horizontalMarginChanged();
private:
QVariant m_layoutVariant;
ChunkLayout m_layout;
QColor m_textColor = QColor(196, 200, 216); // Theme.readingText default
QColor m_linkColor = QColor(87, 133, 193); // Theme.buttonAccent default
QColor m_dimColor = QColor(113, 115, 140); // Theme.dimText default
qreal m_horizontalMargin = 0;
static BookImageResolver *s_imageResolver;
};
@@ -0,0 +1,659 @@
#include "ChunkLayoutEngine.h"
#include <QFontDatabase>
#include <QFontMetricsF>
#include <QHash>
#include <algorithm>
#include <cmath>
#include "backend/reading/BookImageResolver.h"
#include "KnuthPlass.h"
namespace ChunkLayoutEngine {
namespace {
QFont resolveFont(const TextStyle &style, qreal baseFontSize, const QString &baseFontFamily)
{
QFont font;
if (!style.fontFamilies.isEmpty()) {
const QString &fam = style.fontFamilies.first();
if (fam.compare(QLatin1String("serif"), Qt::CaseInsensitive) == 0) {
font.setStyleHint(QFont::Serif);
font.setFamily(QStringLiteral("Times New Roman"));
} else if (fam.compare(QLatin1String("sans-serif"), Qt::CaseInsensitive) == 0) {
font.setStyleHint(QFont::SansSerif);
font.setFamily(QStringLiteral("Helvetica"));
} else if (fam.compare(QLatin1String("monospace"), Qt::CaseInsensitive) == 0) {
font.setStyleHint(QFont::Monospace);
font.setFamily(QStringLiteral("Courier"));
} else {
font.setFamily(fam);
}
} else if (!baseFontFamily.isEmpty()) {
font.setFamily(baseFontFamily);
}
qreal targetSize = style.fontSize > 0 ? style.fontSize : baseFontSize;
font.setPointSizeF(targetSize * 0.75);
font.setPixelSize(static_cast<int>(std::round(targetSize)));
font.setWeight(static_cast<QFont::Weight>(style.weight));
font.setItalic(style.italic);
font.setCapitalization(style.smallCaps ? QFont::SmallCaps : QFont::MixedCase);
if (style.letterSpacing != 0) {
font.setLetterSpacing(QFont::AbsoluteSpacing, style.letterSpacing);
}
font.setUnderline(style.underline);
font.setStrikeOut(style.strikeOut);
font.setOverline(style.overline);
return font;
}
QString transformText(const QString &text, TextTransform transform)
{
switch (transform) {
case TextTransform::Uppercase: return text.toUpper();
case TextTransform::Lowercase: return text.toLower();
case TextTransform::Capitalize: {
QString res = text;
bool inWord = false;
for (int i = 0; i < res.size(); ++i) {
if (res[i].isLetter()) {
if (!inWord) {
res[i] = res[i].toUpper();
inWord = true;
}
} else {
inWord = false;
}
}
return res;
}
case TextTransform::None:
default:
return text;
}
}
struct WordMetrics {
qreal width = 0;
qreal ascent = 0;
qreal descent = 0;
};
struct ActiveBox {
BoxStyle box;
qreal startY = 0;
qreal left = 0;
qreal right = 0;
};
class LayoutWorker {
public:
explicit LayoutWorker(const LayoutParams &params)
: m_params(params)
{
}
ChunkLayout run(const PreparedChunk &prepared)
{
m_curY = 0;
m_prevMarginBottom = 0;
m_layout.contentWidth = m_params.contentWidth;
for (const auto &b : prepared.blocks) {
switch (b.kind) {
case PreparedBlock::Kind::ContainerStart:
handleContainerStart(b.box);
break;
case PreparedBlock::Kind::ContainerEnd:
handleContainerEnd(b.box);
break;
case PreparedBlock::Kind::Rule:
handleRule(b.ruleColor);
break;
case PreparedBlock::Kind::ImageBlock:
handleImageBlock(b.imageBlock);
break;
case PreparedBlock::Kind::Paragraph:
handleParagraph(b.paragraph);
break;
}
}
m_layout.totalHeight = m_curY;
return m_layout;
}
private:
void handleContainerStart(const BoxStyle &box)
{
qreal collapsedMargin = std::max(m_prevMarginBottom, box.marginTop);
m_curY += collapsedMargin;
m_prevMarginBottom = 0;
ActiveBox ab;
ab.box = box;
ab.startY = m_curY;
ab.left = currentLeft() + box.marginLeft;
ab.right = currentRight() + box.marginRight;
m_curY += box.borderTop + box.paddingTop;
m_boxStack.append(ab);
}
void handleContainerEnd(const BoxStyle &box)
{
if (m_boxStack.isEmpty())
return;
ActiveBox ab = m_boxStack.takeLast();
m_curY += box.paddingBottom + box.borderBottom;
PositionedDecoration dec;
dec.rect = QRectF(ab.left, ab.startY,
std::max(0.0, m_params.contentWidth - ab.left - ab.right),
m_curY - ab.startY);
dec.background = box.background;
dec.borderColor = box.borderColor;
dec.borderLeft = box.borderLeft;
dec.borderTop = box.borderTop;
dec.borderBottom = box.borderBottom;
if (dec.background.isValid() || dec.borderLeft > 0 || dec.borderTop > 0 || dec.borderBottom > 0) {
m_layout.decorations.append(dec);
}
m_prevMarginBottom = box.marginBottom;
}
void handleRule(const QColor &color)
{
m_curY += std::max(m_prevMarginBottom, 8.0);
PositionedRule r;
qreal left = currentLeft();
qreal right = currentRight();
r.rect = QRectF(left, m_curY, std::max(10.0, m_params.contentWidth - left - right), 1.0);
r.color = color;
m_layout.rules.append(r);
m_curY += 1.0;
m_prevMarginBottom = 8.0;
}
qreal currentLeft() const
{
qreal l = 0;
for (const auto &b : m_boxStack) {
l += b.box.marginLeft + b.box.borderLeft + b.box.paddingLeft;
}
return l;
}
qreal currentRight() const
{
qreal r = 0;
for (const auto &b : m_boxStack) {
r += b.box.marginRight + b.box.borderRight + b.box.paddingRight;
}
return r;
}
void handleImageBlock(const PreparedImageBlock &item)
{
qreal left = currentLeft();
qreal right = currentRight();
qreal availWidth = std::max(50.0, m_params.contentWidth - left - right);
qreal natW = item.naturalSize.width() > 0 ? item.naturalSize.width() : 100.0;
qreal natH = item.naturalSize.height() > 0 ? item.naturalSize.height() : 100.0;
qreal targetW = natW;
qreal targetH = natH;
if (item.cssWidth > 0) {
targetW = item.cssWidth;
targetH = (item.cssHeight > 0) ? item.cssHeight : (targetW * (natH / natW));
} else if (item.cssHeight > 0) {
targetH = item.cssHeight;
targetW = targetH * (natW / natH);
}
if (item.cssMaxWidth > 0 && targetW > item.cssMaxWidth) {
qreal scale = item.cssMaxWidth / targetW;
targetW *= scale;
targetH *= scale;
}
if (targetW > availWidth) {
qreal scale = availWidth / targetW;
targetW *= scale;
targetH *= scale;
}
qreal imgX = left + std::max(0.0, (availWidth - targetW) / 2.0);
m_curY += 8.0;
PositionedImage posImg;
posImg.url = item.imageUrl;
posImg.targetRect = QRectF(imgX, m_curY, targetW, targetH);
m_layout.images.append(posImg);
m_curY += targetH + 8.0;
m_prevMarginBottom = 0;
}
void handleParagraph(const PreparedParagraph &p)
{
if (p.words.isEmpty() && p.kpItems.isEmpty())
return;
qreal left = currentLeft();
qreal right = currentRight();
qreal availWidth = std::max(50.0, m_params.contentWidth - left - right);
// Check if any word exceeds line width (emergency letter split fallback)
QVector<PreparedWord> activeWords = p.words;
QVector<KnuthPlass::Item> kpItems = p.kpItems;
bool hasOversized = false;
for (const auto &w : p.words) {
if (w.width > availWidth && w.text.size() > 1) {
hasOversized = true;
break;
}
}
if (hasOversized) {
activeWords.clear();
kpItems.clear();
if (p.textIndent > 0) {
kpItems.append(KnuthPlass::Item::box(p.textIndent, -1));
}
for (const auto &it : p.kpItems) {
if (it.type == KnuthPlass::ItemType::Box && it.tag >= 0 && it.tag < p.words.size()) {
const auto &tok = p.words[it.tag];
if (tok.width > availWidth && tok.text.size() > 1) {
QFontMetricsF fm(tok.font);
for (int chIdx = 0; chIdx < tok.text.size(); ++chIdx) {
PreparedWord chTok = tok;
chTok.text = tok.text.mid(chIdx, 1);
chTok.width = fm.horizontalAdvance(chTok.text);
int subTokIdx = activeWords.size();
activeWords.append(chTok);
kpItems.append(KnuthPlass::Item::box(chTok.width, subTokIdx));
if (chIdx < tok.text.size() - 1) {
kpItems.append(KnuthPlass::Item::penaltyItem(0, 100.0, false, -1));
}
}
} else {
int tokIdx = activeWords.size();
activeWords.append(tok);
kpItems.append(KnuthPlass::Item::box(tok.width, tokIdx));
}
} else {
kpItems.append(it);
}
}
}
const auto lines = KnuthPlass::breakLines(kpItems, availWidth);
if (lines.isEmpty())
return;
qreal lineMultiplier = p.lineHeight > 0 ? p.lineHeight : m_params.lineSpacing;
for (int lIdx = 0; lIdx < lines.size(); ++lIdx) {
const auto &line = lines[lIdx];
const bool isLastLine = (lIdx == lines.size() - 1);
qreal maxAscent = p.fontSize * 0.8;
qreal maxDescent = p.fontSize * 0.2;
for (int itIdx = line.start; itIdx < line.end && itIdx < kpItems.size(); ++itIdx) {
const auto &it = kpItems[itIdx];
if (it.type == KnuthPlass::ItemType::Box && it.tag >= 0 && it.tag < activeWords.size()) {
const auto &tok = activeWords[it.tag];
maxAscent = std::max(maxAscent, tok.ascent);
maxDescent = std::max(maxDescent, tok.descent);
}
}
qreal lineHeight = (maxAscent + maxDescent) * lineMultiplier;
qreal baselineY = m_curY + maxAscent + (lineHeight - (maxAscent + maxDescent)) / 2.0;
qreal contentW = 0;
for (int itIdx = line.start; itIdx < line.end && itIdx < kpItems.size(); ++itIdx) {
const auto &it = kpItems[itIdx];
if (it.type == KnuthPlass::ItemType::Box) {
contentW += it.width;
} else if (it.type == KnuthPlass::ItemType::Glue) {
if (isLastLine || p.align != TextAlign::Justify) {
contentW += it.width;
} else {
qreal adj = (line.ratio >= 0) ? (line.ratio * it.stretch) : (line.ratio * it.shrink);
contentW += std::max(0.0, it.width + adj);
}
}
}
if (line.hyphenated) {
contentW += 8.0;
}
qreal startX = left;
if (p.align == TextAlign::Center) {
startX += std::max(0.0, (availWidth - contentW) / 2.0);
} else if (p.align == TextAlign::Right) {
startX += std::max(0.0, availWidth - contentW);
}
qreal curX = startX;
PositionedLine pLine;
pLine.rect = QRectF(left, m_curY, availWidth, lineHeight);
pLine.baselineY = baselineY;
if (lIdx == 0 && !p.marker.isEmpty()) {
PositionedWordRun mRun;
mRun.text = p.marker;
mRun.font = resolveFont(p.markerStyle, m_params.fontSize, m_params.baseFontFamily);
QFontMetricsF mFm(mRun.font);
qreal mW = mFm.horizontalAdvance(mRun.text);
mRun.rect = QRectF(startX - mW - 4.0, m_curY, mW, lineHeight);
mRun.baselineY = baselineY;
mRun.color = p.markerStyle.color;
pLine.runs.append(mRun);
}
for (int itIdx = line.start; itIdx < line.end && itIdx < kpItems.size(); ++itIdx) {
const auto &it = kpItems[itIdx];
if (it.type == KnuthPlass::ItemType::Box) {
if (it.tag >= 0 && it.tag < activeWords.size()) {
const auto &tok = activeWords[it.tag];
if (!tok.imageUrl.isEmpty()) {
PositionedImage img;
img.url = tok.imageUrl;
img.targetRect = QRectF(curX, baselineY - tok.ascent, tok.width, tok.ascent);
m_layout.images.append(img);
} else {
PositionedWordRun run;
run.text = tok.text;
run.font = tok.font;
run.color = tok.style.color;
run.background = tok.style.background;
run.link = tok.style.link;
run.underline = tok.style.underline;
run.strikeOut = tok.style.strikeOut;
run.overline = tok.style.overline;
run.rect = QRectF(curX, m_curY, tok.width, lineHeight);
run.baselineY = baselineY - tok.style.baselineShift;
pLine.runs.append(run);
}
}
curX += it.width;
} else if (it.type == KnuthPlass::ItemType::Glue) {
qreal spaceW = it.width;
if (!isLastLine && p.align == TextAlign::Justify) {
qreal adj = (line.ratio >= 0) ? (line.ratio * it.stretch) : (line.ratio * it.shrink);
spaceW = std::max(0.0, it.width + adj);
}
curX += spaceW;
}
}
if (line.hyphenated) {
PositionedWordRun hyRun;
hyRun.text = QStringLiteral("-");
if (!pLine.runs.isEmpty()) {
hyRun.font = pLine.runs.last().font;
hyRun.color = pLine.runs.last().color;
}
QFontMetricsF hFm(hyRun.font);
qreal hW = hFm.horizontalAdvance(hyRun.text);
hyRun.rect = QRectF(curX, m_curY, hW, lineHeight);
hyRun.baselineY = baselineY;
pLine.runs.append(hyRun);
}
m_layout.lines.append(pLine);
m_curY += lineHeight;
}
m_prevMarginBottom = 0;
}
const LayoutParams &m_params;
ChunkLayout m_layout;
qreal m_curY = 0;
qreal m_prevMarginBottom = 0;
QVector<ActiveBox> m_boxStack;
};
bool isPureImageBlock(const QVector<InlineItem> &inlines, int &outImageIdx)
{
outImageIdx = -1;
for (int i = 0; i < inlines.size(); ++i) {
const auto &item = inlines[i];
if (item.kind == InlineItem::Kind::Image) {
if (outImageIdx >= 0) return false;
outImageIdx = i;
} else if (item.kind == InlineItem::Kind::Text) {
if (!item.text.trimmed().isEmpty()) return false;
} else if (item.kind == InlineItem::Kind::LineBreak) {
// ignore breaks
} else {
return false;
}
}
return outImageIdx >= 0;
}
} // namespace
PreparedChunk prepareBlocks(const QVector<BlockItem> &blocks,
qreal baseFontSize,
IBookImageResolver *imageResolver)
{
PreparedChunk prepared;
prepared.blocks.reserve(blocks.size());
// Word metrics cache across the chunk
QHash<QString, WordMetrics> metricsCache;
for (const auto &b : blocks) {
PreparedBlock pb;
switch (b.kind) {
case BlockItem::Kind::ContainerStart:
pb.kind = PreparedBlock::Kind::ContainerStart;
pb.box = b.box;
prepared.blocks.append(pb);
break;
case BlockItem::Kind::ContainerEnd:
pb.kind = PreparedBlock::Kind::ContainerEnd;
pb.box = b.box;
prepared.blocks.append(pb);
break;
case BlockItem::Kind::Rule:
pb.kind = PreparedBlock::Kind::Rule;
pb.ruleColor = b.ruleColor;
prepared.blocks.append(pb);
break;
case BlockItem::Kind::Paragraph: {
int pureImageIdx = -1;
if (isPureImageBlock(b.inlines, pureImageIdx)) {
const auto &imgInline = b.inlines[pureImageIdx];
pb.kind = PreparedBlock::Kind::ImageBlock;
pb.imageBlock.imageUrl = imgInline.imageUrl;
pb.imageBlock.cssWidth = imgInline.cssWidth;
pb.imageBlock.cssHeight = imgInline.cssHeight;
pb.imageBlock.cssMaxWidth = imgInline.cssMaxWidth;
if (imageResolver) {
QSizeF sz = imageResolver->imageSize(pb.imageBlock.imageUrl);
if (sz.isValid() && sz.width() > 0 && sz.height() > 0) {
pb.imageBlock.naturalSize = sz;
}
}
prepared.blocks.append(pb);
} else {
pb.kind = PreparedBlock::Kind::Paragraph;
pb.paragraph.align = b.align;
pb.paragraph.textIndent = b.textIndent;
pb.paragraph.lineHeight = b.lineHeight;
pb.paragraph.fontSize = b.fontSize;
pb.paragraph.marker = b.marker;
pb.paragraph.markerStyle = b.markerStyle;
if (b.textIndent > 0) {
pb.paragraph.kpItems.append(KnuthPlass::Item::box(b.textIndent, -1));
}
for (const auto &item : b.inlines) {
if (item.kind == InlineItem::Kind::LineBreak) {
pb.paragraph.kpItems.append(KnuthPlass::Item::penaltyItem(0, -KnuthPlass::kInfinity, false));
continue;
}
if (item.kind == InlineItem::Kind::Image) {
qreal w = 24.0, h = 24.0;
if (imageResolver) {
QSizeF sz = imageResolver->imageSize(item.imageUrl);
if (sz.isValid() && sz.width() > 0 && sz.height() > 0) {
w = sz.width();
h = sz.height();
}
}
if (item.cssWidth > 0) {
qreal aspect = w > 0 ? (h / w) : 1.0;
w = item.cssWidth;
h = item.cssHeight > 0 ? item.cssHeight : (w * aspect);
}
PreparedWord tok;
tok.imageUrl = item.imageUrl;
tok.style = item.style;
tok.width = w;
tok.ascent = h;
tok.descent = 0;
int tokIdx = pb.paragraph.words.size();
pb.paragraph.words.append(tok);
pb.paragraph.kpItems.append(KnuthPlass::Item::box(w, tokIdx));
continue;
}
QFont font = resolveFont(item.style, baseFontSize, QString());
QFontMetricsF fm(font);
qreal spaceW = fm.horizontalAdvance(QLatin1Char(' '));
qreal hyphenW = fm.horizontalAdvance(QLatin1Char('-'));
QString rawText = transformText(item.text, item.style.transform);
const QStringList words = rawText.split(QLatin1Char(' '), Qt::SkipEmptyParts);
for (int wIdx = 0; wIdx < words.size(); ++wIdx) {
const QString &wStr = words[wIdx];
if (wStr.contains(QChar(0x00AD))) {
const QStringList parts = wStr.split(QChar(0x00AD), Qt::SkipEmptyParts);
for (int pIdx = 0; pIdx < parts.size(); ++pIdx) {
PreparedWord tok;
tok.text = parts[pIdx];
tok.style = item.style;
tok.font = font;
QString cacheKey = font.key() + QLatin1Char('|') + tok.text;
auto it = metricsCache.constFind(cacheKey);
if (it != metricsCache.constEnd()) {
tok.width = it->width;
tok.ascent = it->ascent;
tok.descent = it->descent;
} else {
tok.width = fm.horizontalAdvance(tok.text);
tok.ascent = fm.ascent();
tok.descent = fm.descent();
metricsCache.insert(cacheKey, {tok.width, tok.ascent, tok.descent});
}
int tokIdx = pb.paragraph.words.size();
pb.paragraph.words.append(tok);
pb.paragraph.kpItems.append(KnuthPlass::Item::box(tok.width, tokIdx));
if (pIdx < parts.size() - 1) {
pb.paragraph.kpItems.append(KnuthPlass::Item::penaltyItem(hyphenW, 50.0, true, -1));
}
}
} else {
PreparedWord tok;
tok.text = wStr;
tok.style = item.style;
tok.font = font;
QString cacheKey = font.key() + QLatin1Char('|') + tok.text;
auto it = metricsCache.constFind(cacheKey);
if (it != metricsCache.constEnd()) {
tok.width = it->width;
tok.ascent = it->ascent;
tok.descent = it->descent;
} else {
tok.width = fm.horizontalAdvance(tok.text);
tok.ascent = fm.ascent();
tok.descent = fm.descent();
metricsCache.insert(cacheKey, {tok.width, tok.ascent, tok.descent});
}
int tokIdx = pb.paragraph.words.size();
pb.paragraph.words.append(tok);
pb.paragraph.kpItems.append(KnuthPlass::Item::box(tok.width, tokIdx));
}
if (wIdx < words.size() - 1 || rawText.endsWith(QLatin1Char(' '))) {
qreal stretch = spaceW * 0.5;
qreal shrink = spaceW * 0.333;
pb.paragraph.kpItems.append(KnuthPlass::Item::glue(spaceW, stretch, shrink, -1));
}
}
}
KnuthPlass::finishParagraph(pb.paragraph.kpItems);
prepared.blocks.append(pb);
}
break;
}
}
}
return prepared;
}
PreparedChunk prepareChunk(const QString &html,
qreal baseFontSize,
IBookImageResolver *imageResolver)
{
ParseParams pp;
pp.baseFontSize = baseFontSize;
pp.contentWidth = 600;
const auto blocks = HtmlBlockParser::parse(html, pp);
return prepareBlocks(blocks, baseFontSize, imageResolver);
}
ChunkLayout layoutPreparedChunk(const PreparedChunk &prepared,
const LayoutParams &params)
{
LayoutWorker worker(params);
return worker.run(prepared);
}
ChunkLayout layoutBlocks(const QVector<BlockItem> &blocks,
const LayoutParams &params,
IBookImageResolver *imageResolver)
{
PreparedChunk prep = prepareBlocks(blocks, params.fontSize, imageResolver);
return layoutPreparedChunk(prep, params);
}
ChunkLayout layoutChunk(const QString &html,
const LayoutParams &params,
IBookImageResolver *imageResolver)
{
PreparedChunk prep = prepareChunk(html, params.fontSize, imageResolver);
return layoutPreparedChunk(prep, params);
}
} // namespace ChunkLayoutEngine
@@ -0,0 +1,135 @@
#pragma once
#include <QColor>
#include <QFont>
#include <QMetaType>
#include <QRectF>
#include <QString>
#include <QVector>
#include "HtmlBlockParser.h"
#include "KnuthPlass.h"
class IBookImageResolver;
struct PositionedWordRun {
QString text;
QRectF rect;
qreal baselineY = 0;
QFont font;
QColor color;
QColor background;
bool link = false;
bool underline = false;
bool strikeOut = false;
bool overline = false;
};
struct PositionedLine {
QRectF rect;
qreal baselineY = 0;
QVector<PositionedWordRun> runs;
};
struct PositionedImage {
QString url;
QRectF targetRect;
};
struct PositionedRule {
QRectF rect;
QColor color;
};
struct PositionedDecoration {
QRectF rect;
QColor background;
QColor borderColor;
qreal borderLeft = 0;
qreal borderTop = 0;
qreal borderBottom = 0;
};
struct ChunkLayout {
QVector<PositionedLine> lines;
QVector<PositionedImage> images;
QVector<PositionedRule> rules;
QVector<PositionedDecoration> decorations;
qreal totalHeight = 0;
qreal contentWidth = 0;
};
struct LayoutParams {
qreal contentWidth = 600;
qreal fontSize = 16;
qreal lineSpacing = 1.0;
QString baseFontFamily;
};
namespace ChunkLayoutEngine {
struct PreparedWord {
QString text;
QString imageUrl;
TextStyle style;
QFont font;
qreal width = 0;
qreal ascent = 0;
qreal descent = 0;
};
struct PreparedParagraph {
TextAlign align = TextAlign::Justify;
qreal textIndent = 0;
qreal lineHeight = 0;
qreal fontSize = 16;
QString marker;
TextStyle markerStyle;
QVector<PreparedWord> words;
QVector<KnuthPlass::Item> kpItems;
};
struct PreparedImageBlock {
QString imageUrl;
QSizeF naturalSize;
qreal cssWidth = -1;
qreal cssHeight = -1;
qreal cssMaxWidth = -1;
};
struct PreparedBlock {
enum class Kind { ContainerStart, ContainerEnd, Paragraph, ImageBlock, Rule };
Kind kind = Kind::Paragraph;
BoxStyle box;
PreparedParagraph paragraph;
PreparedImageBlock imageBlock;
QColor ruleColor;
};
struct PreparedChunk {
QVector<PreparedBlock> blocks;
};
PreparedChunk prepareChunk(const QString &html,
qreal baseFontSize,
IBookImageResolver *imageResolver = nullptr);
PreparedChunk prepareBlocks(const QVector<BlockItem> &blocks,
qreal baseFontSize,
IBookImageResolver *imageResolver = nullptr);
ChunkLayout layoutPreparedChunk(const PreparedChunk &prepared,
const LayoutParams &params);
ChunkLayout layoutChunk(const QString &html,
const LayoutParams &params,
IBookImageResolver *imageResolver = nullptr);
ChunkLayout layoutBlocks(const QVector<BlockItem> &blocks,
const LayoutParams &params,
IBookImageResolver *imageResolver = nullptr);
} // namespace ChunkLayoutEngine
Q_DECLARE_METATYPE(ChunkLayout)
+431
View File
@@ -0,0 +1,431 @@
#include "CssParser.h"
#include <QDomElement>
#include <QRegularExpression>
#include <algorithm>
namespace Css {
namespace {
QString stripComments(const QString &css)
{
QString out;
out.reserve(css.size());
int i = 0;
const int n = css.size();
while (i < n) {
if (i + 1 < n && css[i] == QLatin1Char('/') && css[i + 1] == QLatin1Char('*')) {
const int end = css.indexOf(QLatin1String("*/"), i + 2);
if (end < 0)
break;
i = end + 2;
continue;
}
out += css[i++];
}
return out;
}
// Index of the '}' matching the '{' at `open`, or -1.
int matchingBrace(const QString &s, int open)
{
int depth = 0;
QChar quote;
for (int i = open; i < s.size(); ++i) {
const QChar c = s[i];
if (!quote.isNull()) {
if (c == quote) quote = QChar();
continue;
}
if (c == QLatin1Char('"') || c == QLatin1Char('\'')) quote = c;
else if (c == QLatin1Char('{')) ++depth;
else if (c == QLatin1Char('}') && --depth == 0) return i;
}
return -1;
}
QString unquote(QString s)
{
s = s.trimmed();
if (s.size() >= 2 && (s.front() == QLatin1Char('"') || s.front() == QLatin1Char('\'')) && s.back() == s.front())
s = s.mid(1, s.size() - 2);
return s;
}
QString localTagName(const QDomElement &e)
{
QString tag = e.tagName();
const int colon = tag.indexOf(QLatin1Char(':'));
if (colon >= 0)
tag = tag.mid(colon + 1);
return tag.toLower();
}
bool matchesCompound(const Compound &c, const QDomElement &e)
{
if (!c.tag.isEmpty() && c.tag != localTagName(e))
return false;
if (!c.id.isEmpty() && e.attribute(QStringLiteral("id")) != c.id)
return false;
if (!c.classes.isEmpty()) {
const QStringList cls = e.attribute(QStringLiteral("class")).split(QLatin1Char(' '), Qt::SkipEmptyParts);
for (const QString &want : c.classes)
if (!cls.contains(want))
return false;
}
return true;
}
bool matchesFrom(const Selector &s, int partIdx, const QDomElement &e)
{
if (!matchesCompound(s.parts[partIdx], e))
return false;
if (partIdx == 0)
return true;
const QChar comb = s.combinators[partIdx - 1];
QDomNode p = e.parentNode();
if (comb == QLatin1Char('>')) {
return p.isElement() && matchesFrom(s, partIdx - 1, p.toElement());
}
for (; p.isElement(); p = p.parentNode()) {
if (matchesFrom(s, partIdx - 1, p.toElement()))
return true;
}
return false;
}
std::optional<Compound> parseCompound(QStringView text)
{
Compound c;
int i = 0;
const int n = text.size();
auto isIdent = [](QChar ch) { return ch.isLetterOrNumber() || ch == QLatin1Char('-') || ch == QLatin1Char('_'); };
while (i < n && (isIdent(text[i]) || text[i] == QLatin1Char('*') || text[i] == QLatin1Char('|')))
++i;
QString tag = text.left(i).toString().toLower();
const int bar = tag.indexOf(QLatin1Char('|'));
if (bar >= 0)
tag = tag.mid(bar + 1);
c.tag = (tag == QLatin1String("*")) ? QString() : tag;
while (i < n) {
const QChar kind = text[i++];
const int start = i;
while (i < n && isIdent(text[i]))
++i;
const QString name = text.mid(start, i - start).toString();
if (name.isEmpty())
return std::nullopt;
if (kind == QLatin1Char('.')) c.classes << name;
else if (kind == QLatin1Char('#')) c.id = name;
else return std::nullopt;
}
return c;
}
} // namespace
QVector<Declaration> parseDeclarations(QStringView block)
{
QVector<Declaration> out;
int depth = 0;
QChar quote;
int start = 0;
auto flush = [&](int end) {
const QStringView decl = block.mid(start, end - start).trimmed();
start = end + 1;
const int colon = decl.indexOf(QLatin1Char(':'));
if (colon <= 0)
return;
Declaration d;
d.property = decl.left(colon).trimmed().toString().toLower();
QString value = decl.mid(colon + 1).trimmed().toString();
static const QRegularExpression kImportant(QStringLiteral("!\\s*important\\s*$"),
QRegularExpression::CaseInsensitiveOption);
const auto m = kImportant.match(value);
if (m.hasMatch()) {
d.important = true;
value = value.left(m.capturedStart()).trimmed();
}
d.value = value;
if (!d.property.isEmpty() && !d.value.isEmpty())
out.append(d);
};
for (int i = 0; i < block.size(); ++i) {
const QChar c = block[i];
if (!quote.isNull()) {
if (c == quote) quote = QChar();
continue;
}
if (c == QLatin1Char('"') || c == QLatin1Char('\'')) quote = c;
else if (c == QLatin1Char('(')) ++depth;
else if (c == QLatin1Char(')')) depth = std::max(0, depth - 1);
else if (c == QLatin1Char(';') && depth == 0) flush(i);
}
flush(block.size());
return out;
}
std::optional<Selector> parseSelector(QStringView text)
{
const QString s = text.trimmed().toString();
if (s.isEmpty())
return std::nullopt;
for (QChar bad : {QLatin1Char(':'), QLatin1Char('['), QLatin1Char('+'), QLatin1Char('~')})
if (s.contains(bad))
return std::nullopt;
// Normalise child combinators so tokens are whitespace separated.
QString normalized = s;
normalized.replace(QLatin1Char('>'), QStringLiteral(" > "));
const QStringList tokens = normalized.split(QRegularExpression(QStringLiteral("\\s+")), Qt::SkipEmptyParts);
Selector sel;
QChar pending = QLatin1Char(' ');
for (const QString &tok : tokens) {
if (tok == QLatin1String(">")) {
if (sel.parts.isEmpty())
return std::nullopt;
pending = QLatin1Char('>');
continue;
}
auto compound = parseCompound(tok);
if (!compound)
return std::nullopt;
if (!sel.parts.isEmpty())
sel.combinators.append(pending);
pending = QLatin1Char(' ');
sel.specificity += (compound->id.isEmpty() ? 0 : 100)
+ 10 * compound->classes.size()
+ (compound->tag.isEmpty() ? 0 : 1);
sel.parts.append(*compound);
}
if (sel.parts.isEmpty() || sel.combinators.size() != sel.parts.size() - 1)
return std::nullopt;
return sel;
}
StyleSheet StyleSheet::parse(const QString &cssIn)
{
StyleSheet sheet;
const QString css = stripComments(cssIn);
int i = 0;
const int n = css.size();
while (i < n) {
while (i < n && css[i].isSpace())
++i;
if (i >= n)
break;
if (css[i] == QLatin1Char('@')) {
const int brace = css.indexOf(QLatin1Char('{'), i);
const int semi = css.indexOf(QLatin1Char(';'), i);
if (semi >= 0 && (brace < 0 || semi < brace)) { // @import, @charset, @namespace
i = semi + 1;
continue;
}
if (brace < 0)
break;
const int close = matchingBrace(css, brace);
if (close < 0)
break;
const QString keyword = css.mid(i + 1, brace - i - 1).trimmed().toLower();
if (keyword == QLatin1String("font-face")) {
FontFace face;
for (const Declaration &d : parseDeclarations(QStringView(css).mid(brace + 1, close - brace - 1))) {
if (d.property == QLatin1String("font-family")) {
face.family = unquote(d.value);
} else if (d.property == QLatin1String("src")) {
static const QRegularExpression kUrl(QStringLiteral("url\\(\\s*(['\"]?)([^'\")]+)\\1\\s*\\)"));
const auto m = kUrl.match(d.value);
if (m.hasMatch() && face.src.isEmpty())
face.src = m.captured(2).trimmed();
} else if (d.property == QLatin1String("font-weight")) {
face.weight = d.value;
} else if (d.property == QLatin1String("font-style")) {
face.style = d.value;
}
}
if (!face.family.isEmpty() && !face.src.isEmpty())
sheet.fontFaces.append(face);
}
// Other at-rules (@media, @page, @supports...) are skipped.
i = close + 1;
continue;
}
const int brace = css.indexOf(QLatin1Char('{'), i);
if (brace < 0)
break;
const int close = matchingBrace(css, brace);
if (close < 0)
break;
const QString selectorText = css.mid(i, brace - i);
const QVector<Declaration> decls = parseDeclarations(QStringView(css).mid(brace + 1, close - brace - 1));
if (!decls.isEmpty()) {
for (const QString &part : selectorText.split(QLatin1Char(','))) {
if (auto sel = parseSelector(part)) {
Rule rule;
rule.selector = *sel;
rule.declarations = decls;
rule.order = sheet.rules.size();
sheet.rules.append(rule);
}
}
}
i = close + 1;
}
return sheet;
}
void StyleSheet::append(const StyleSheet &other)
{
const int base = rules.size();
for (Rule r : other.rules) {
r.order += base;
rules.append(r);
}
fontFaces += other.fontFaces;
}
bool matches(const Selector &selector, const QDomElement &element)
{
if (selector.parts.isEmpty() || element.isNull())
return false;
return matchesFrom(selector, selector.parts.size() - 1, element);
}
QVector<Declaration> cascade(const StyleSheet &sheet, const QDomElement &element)
{
QVector<const Rule *> matched;
for (const Rule &r : sheet.rules)
if (matches(r.selector, element))
matched.append(&r);
std::stable_sort(matched.begin(), matched.end(), [](const Rule *a, const Rule *b) {
if (a->selector.specificity != b->selector.specificity)
return a->selector.specificity < b->selector.specificity;
return a->order < b->order;
});
const QVector<Declaration> inlineDecls = parseDeclarations(element.attribute(QStringLiteral("style")));
QVector<Declaration> out;
for (const Rule *r : std::as_const(matched))
for (const Declaration &d : r->declarations)
if (!d.important) out.append(d);
for (const Declaration &d : inlineDecls)
if (!d.important) out.append(d);
for (const Rule *r : std::as_const(matched))
for (const Declaration &d : r->declarations)
if (d.important) out.append(d);
for (const Declaration &d : inlineDecls)
if (d.important) out.append(d);
return out;
}
QString serialize(const QVector<Declaration> &declarations)
{
QString out;
for (const Declaration &d : declarations) {
if (!out.isEmpty())
out += QLatin1Char(';');
out += d.property + QLatin1Char(':') + d.value;
}
return out;
}
std::optional<qreal> parseLength(QStringView valueIn, const LengthContext &ctx)
{
const QString value = valueIn.trimmed().toString().toLower();
if (value.isEmpty())
return std::nullopt;
static const QRegularExpression kNum(QStringLiteral("^([+-]?(?:\\d+\\.?\\d*|\\.\\d+))([a-z%]*)$"));
const auto m = kNum.match(value);
if (!m.hasMatch())
return std::nullopt;
const qreal num = m.captured(1).toDouble();
const QString unit = m.captured(2);
if (unit.isEmpty())
return num * ctx.absoluteScale;
if (unit == QLatin1String("em")) return num * ctx.em;
if (unit == QLatin1String("rem")) return num * ctx.rem;
if (unit == QLatin1String("ex") || unit == QLatin1String("ch")) return num * ctx.em * 0.5;
if (unit == QLatin1String("%")) return num * ctx.percentBase / 100.0;
if (unit == QLatin1String("px")) return num * ctx.absoluteScale;
if (unit == QLatin1String("pt")) return num * 4.0 / 3.0 * ctx.absoluteScale;
if (unit == QLatin1String("pc")) return num * 16.0 * ctx.absoluteScale;
if (unit == QLatin1String("in")) return num * 96.0 * ctx.absoluteScale;
if (unit == QLatin1String("cm")) return num * 96.0 / 2.54 * ctx.absoluteScale;
if (unit == QLatin1String("mm")) return num * 96.0 / 25.4 * ctx.absoluteScale;
return std::nullopt;
}
QColor parseColor(QStringView valueIn)
{
const QString value = valueIn.trimmed().toString().toLower();
if (value.isEmpty() || value == QLatin1String("inherit") || value == QLatin1String("currentcolor")
|| value == QLatin1String("initial") || value == QLatin1String("unset"))
return {};
if (value == QLatin1String("transparent"))
return QColor(Qt::transparent);
static const QRegularExpression kFunc(QStringLiteral("^(rgba?|hsla?)\\(([^)]*)\\)$"));
const auto m = kFunc.match(value);
if (m.hasMatch()) {
QStringList parts = m.captured(2).split(QRegularExpression(QStringLiteral("[\\s,/]+")), Qt::SkipEmptyParts);
if (parts.size() < 3)
return {};
auto channel = [](const QString &p, qreal scale) {
return p.endsWith(QLatin1Char('%')) ? p.chopped(1).toDouble() / 100.0 * scale : p.toDouble();
};
qreal alpha = 1.0;
if (parts.size() >= 4)
alpha = parts[3].endsWith(QLatin1Char('%')) ? parts[3].chopped(1).toDouble() / 100.0 : parts[3].toDouble();
QColor c;
if (m.captured(1).startsWith(QLatin1String("rgb"))) {
c = QColor::fromRgbF(float(std::clamp(channel(parts[0], 255) / 255.0, 0.0, 1.0)),
float(std::clamp(channel(parts[1], 255) / 255.0, 0.0, 1.0)),
float(std::clamp(channel(parts[2], 255) / 255.0, 0.0, 1.0)));
} else {
const qreal h = std::fmod(parts[0].toDouble(), 360.0) / 360.0;
c = QColor::fromHslF(float(h < 0 ? h + 1 : h),
float(std::clamp(channel(parts[1], 1), 0.0, 1.0)),
float(std::clamp(channel(parts[2], 1), 0.0, 1.0)));
}
c.setAlphaF(float(std::clamp(alpha, 0.0, 1.0)));
return c;
}
const QColor c = QColor::fromString(value);
return c.isValid() ? c : QColor();
}
QStringList splitValue(QStringView value)
{
QStringList out;
QString cur;
int depth = 0;
for (QChar c : value) {
if (c == QLatin1Char('(')) ++depth;
if (c == QLatin1Char(')')) depth = std::max(0, depth - 1);
if (c.isSpace() && depth == 0) {
if (!cur.isEmpty()) out << cur;
cur.clear();
} else {
cur += c;
}
}
if (!cur.isEmpty()) out << cur;
return out;
}
QStringList splitCommaList(QStringView value)
{
QStringList out;
for (const QString &item : value.toString().split(QLatin1Char(','))) {
const QString u = unquote(item);
if (!u.isEmpty()) out << u;
}
return out;
}
} // namespace Css
+84
View File
@@ -0,0 +1,84 @@
#pragma once
#include <QColor>
#include <QString>
#include <QStringList>
#include <QVector>
#include <optional>
class QDomElement;
// Minimal CSS engine for EPUB styling: stylesheet parsing, selector matching
// (type, class, id, compound, descendant and child combinators), cascade, and
// value parsing. Unsupported selectors (pseudo-classes, attribute selectors,
// sibling combinators) are skipped rather than mis-applied.
namespace Css {
struct Declaration {
QString property; // lowercase
QString value; // trimmed, without !important
bool important = false;
};
struct Compound {
QString tag; // lowercase; empty = any
QString id;
QStringList classes;
};
struct Selector {
QVector<Compound> parts; // left to right
QVector<QChar> combinators; // combinators[i] joins parts[i] and parts[i+1]: ' ' or '>'
int specificity = 0;
};
struct Rule {
Selector selector;
QVector<Declaration> declarations;
int order = 0;
};
struct FontFace {
QString family;
QString src; // first url(...) value, unresolved
QString weight;
QString style;
};
struct StyleSheet {
QVector<Rule> rules;
QVector<FontFace> fontFaces;
static StyleSheet parse(const QString &css);
void append(const StyleSheet &other);
};
QVector<Declaration> parseDeclarations(QStringView block);
std::optional<Selector> parseSelector(QStringView text);
bool matches(const Selector &selector, const QDomElement &element);
// Cascade result for one element, in application order (later wins):
// stylesheet normal, inline normal, stylesheet !important, inline !important.
QVector<Declaration> cascade(const StyleSheet &sheet, const QDomElement &element);
QString serialize(const QVector<Declaration> &declarations);
// --- Values -----------------------------------------------------------------
struct LengthContext {
qreal em = 16; // current font size in px
qreal rem = 16; // root (user preference) font size in px
qreal percentBase = 0; // what 100% resolves to
qreal absoluteScale = 1; // scale applied to absolute units (px, pt...) to follow the user's font size
};
std::optional<qreal> parseLength(QStringView value, const LengthContext &ctx);
QColor parseColor(QStringView value);
// Splits a value on top-level whitespace (keeps "rgb(1, 2, 3)" together).
QStringList splitValue(QStringView value);
// Splits a comma-separated list on top-level commas, unquoting each item.
QStringList splitCommaList(QStringView value);
} // namespace Css
@@ -0,0 +1,502 @@
#include "HtmlBlockParser.h"
#include <QDomDocument>
#include <QRegularExpression>
#include <algorithm>
#include "CssParser.h"
#include "backend/formats/HtmlEntities.h"
namespace HtmlBlockParser {
namespace {
struct StyleContext {
TextStyle text;
TextAlign align = TextAlign::Justify;
qreal textIndent = 0;
qreal lineHeight = 0;
bool preformatted = false;
};
QString localName(const QDomElement &e)
{
QString name = e.tagName();
const int idx = name.indexOf(QLatin1Char(':'));
if (idx >= 0)
name = name.mid(idx + 1);
return name.toLower();
}
bool isBlockTag(const QString &tag)
{
static const QStringList kBlocks = {
QStringLiteral("p"), QStringLiteral("div"),
QStringLiteral("h1"), QStringLiteral("h2"),
QStringLiteral("h3"), QStringLiteral("h4"),
QStringLiteral("h5"), QStringLiteral("h6"),
QStringLiteral("blockquote"), QStringLiteral("pre"),
QStringLiteral("ul"), QStringLiteral("ol"),
QStringLiteral("li"), QStringLiteral("dl"),
QStringLiteral("dt"), QStringLiteral("dd"),
QStringLiteral("hr"), QStringLiteral("figure"),
QStringLiteral("svg"), QStringLiteral("figcaption"),
QStringLiteral("section"), QStringLiteral("article"),
QStringLiteral("header"), QStringLiteral("footer"), QStringLiteral("aside"),
QStringLiteral("body")
};
return kBlocks.contains(tag);
}
void applyCssDeclarations(const QVector<Css::Declaration> &decls,
StyleContext &ctx,
BoxStyle &box,
const ParseParams &params)
{
Css::LengthContext lenCtx;
lenCtx.em = ctx.text.fontSize;
lenCtx.rem = params.baseFontSize;
lenCtx.percentBase = params.contentWidth;
lenCtx.absoluteScale = params.baseFontSize / 16.0;
for (const auto &d : decls) {
const QString &prop = d.property;
const QString &val = d.value;
if (prop == QLatin1String("font-family")) {
ctx.text.fontFamilies = Css::splitCommaList(val);
} else if (prop == QLatin1String("font-size")) {
if (val == QLatin1String("xx-small")) ctx.text.fontSize = params.baseFontSize * 0.6;
else if (val == QLatin1String("x-small")) ctx.text.fontSize = params.baseFontSize * 0.75;
else if (val == QLatin1String("small")) ctx.text.fontSize = params.baseFontSize * 0.875;
else if (val == QLatin1String("medium")) ctx.text.fontSize = params.baseFontSize;
else if (val == QLatin1String("large")) ctx.text.fontSize = params.baseFontSize * 1.15;
else if (val == QLatin1String("x-large")) ctx.text.fontSize = params.baseFontSize * 1.5;
else if (val == QLatin1String("xx-large")) ctx.text.fontSize = params.baseFontSize * 2.0;
else if (val == QLatin1String("smaller")) ctx.text.fontSize *= 0.85;
else if (val == QLatin1String("larger")) ctx.text.fontSize *= 1.2;
else {
auto sz = Css::parseLength(val, lenCtx);
if (sz && *sz > 0)
ctx.text.fontSize = *sz;
}
lenCtx.em = ctx.text.fontSize;
} else if (prop == QLatin1String("font-weight")) {
if (val == QLatin1String("bold") || val == QLatin1String("bolder")) ctx.text.weight = 700;
else if (val == QLatin1String("normal") || val == QLatin1String("lighter")) ctx.text.weight = 400;
else {
bool ok;
int w = val.toInt(&ok);
if (ok && w >= 100 && w <= 900)
ctx.text.weight = w;
}
} else if (prop == QLatin1String("font-style")) {
ctx.text.italic = (val == QLatin1String("italic") || val == QLatin1String("oblique"));
} else if (prop == QLatin1String("font-variant")) {
ctx.text.smallCaps = (val == QLatin1String("small-caps"));
} else if (prop == QLatin1String("text-transform")) {
if (val == QLatin1String("uppercase")) ctx.text.transform = TextTransform::Uppercase;
else if (val == QLatin1String("lowercase")) ctx.text.transform = TextTransform::Lowercase;
else if (val == QLatin1String("capitalize")) ctx.text.transform = TextTransform::Capitalize;
else ctx.text.transform = TextTransform::None;
} else if (prop == QLatin1String("letter-spacing")) {
auto ls = Css::parseLength(val, lenCtx);
if (ls) ctx.text.letterSpacing = *ls;
} else if (prop == QLatin1String("text-decoration") || prop == QLatin1String("text-decoration-line")) {
ctx.text.underline = val.contains(QLatin1String("underline"));
ctx.text.strikeOut = val.contains(QLatin1String("line-through"));
ctx.text.overline = val.contains(QLatin1String("overline"));
} else if (prop == QLatin1String("color")) {
QColor c = Css::parseColor(val);
if (c.isValid()) ctx.text.color = c;
} else if (prop == QLatin1String("background-color") || prop == QLatin1String("background")) {
QColor c = Css::parseColor(val);
if (c.isValid()) ctx.text.background = c;
} else if (prop == QLatin1String("text-align")) {
if (val == QLatin1String("left") || val == QLatin1String("start")) ctx.align = TextAlign::Left;
else if (val == QLatin1String("center")) ctx.align = TextAlign::Center;
else if (val == QLatin1String("right") || val == QLatin1String("end")) ctx.align = TextAlign::Right;
else if (val == QLatin1String("justify")) ctx.align = TextAlign::Justify;
} else if (prop == QLatin1String("text-indent")) {
auto ind = Css::parseLength(val, lenCtx);
if (ind) ctx.textIndent = *ind;
} else if (prop == QLatin1String("line-height")) {
bool ok;
qreal lh = val.toDouble(&ok);
if (ok && lh > 0) {
ctx.lineHeight = lh;
} else {
auto len = Css::parseLength(val, lenCtx);
if (len && *len > 0 && ctx.text.fontSize > 0)
ctx.lineHeight = *len / ctx.text.fontSize;
}
} else if (prop == QLatin1String("margin-top")) {
auto m = Css::parseLength(val, lenCtx); if (m) box.marginTop = *m;
} else if (prop == QLatin1String("margin-bottom")) {
auto m = Css::parseLength(val, lenCtx); if (m) box.marginBottom = *m;
} else if (prop == QLatin1String("margin-left")) {
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("padding-top")) {
auto p = Css::parseLength(val, lenCtx); if (p) box.paddingTop = *p;
} else if (prop == QLatin1String("padding-bottom")) {
auto p = Css::parseLength(val, lenCtx); if (p) box.paddingBottom = *p;
} else if (prop == QLatin1String("padding-left")) {
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("border-left") || prop == QLatin1String("border-left-width")) {
auto w = Css::parseLength(val, lenCtx); if (w) box.borderLeft = *w;
} else if (prop == QLatin1String("border-top") || prop == QLatin1String("border-top-width")) {
auto w = Css::parseLength(val, lenCtx); if (w) box.borderTop = *w;
} else if (prop == QLatin1String("border-bottom") || prop == QLatin1String("border-bottom-width")) {
auto w = Css::parseLength(val, lenCtx); if (w) box.borderBottom = *w;
} else if (prop == QLatin1String("border-color") || prop == QLatin1String("border-left-color")) {
QColor c = Css::parseColor(val);
if (c.isValid()) box.borderColor = c;
}
}
}
class Builder {
public:
Builder(const ParseParams &params) : m_params(params)
{
StyleContext root;
root.text.fontSize = params.baseFontSize;
m_stack.append(root);
}
QVector<BlockItem> build(const QDomElement &root)
{
walk(root);
finishCurrentParagraph();
return m_blocks;
}
private:
void finishCurrentParagraph()
{
if (m_currentInlines.isEmpty())
return;
BlockItem p;
p.kind = BlockItem::Kind::Paragraph;
p.align = m_currentAlign;
p.textIndent = m_currentIndent;
p.lineHeight = m_currentLineHeight;
p.fontSize = m_currentBlockFontSize;
p.preformatted = m_currentPreformatted;
p.marker = m_currentMarker;
p.markerStyle = m_currentMarkerStyle;
p.inlines = std::move(m_currentInlines);
m_blocks.append(p);
m_currentInlines.clear();
m_currentMarker.clear();
m_currentIndent = 0;
}
void startParagraph(const StyleContext &ctx, const QString &marker = {}, const TextStyle &markerStyle = {})
{
finishCurrentParagraph();
m_currentAlign = ctx.align;
m_currentIndent = ctx.textIndent;
m_currentLineHeight = ctx.lineHeight;
m_currentBlockFontSize = ctx.text.fontSize;
m_currentPreformatted = ctx.preformatted;
m_currentMarker = marker;
m_currentMarkerStyle = markerStyle;
}
void appendText(const QString &text, const TextStyle &style, bool pre)
{
if (text.isEmpty())
return;
if (m_currentInlines.isEmpty()) {
startParagraph(m_stack.last());
}
QString processed = text;
if (!pre) {
// Collapse whitespaces
static const QRegularExpression kSpaces(QStringLiteral("\\s+"));
processed.replace(kSpaces, QStringLiteral(" "));
if (m_currentInlines.isEmpty() && processed == QLatin1String(" "))
return;
}
if (processed.isEmpty())
return;
InlineItem item;
item.kind = InlineItem::Kind::Text;
item.text = processed;
item.style = style;
m_currentInlines.append(item);
}
void walk(const QDomNode &node)
{
if (node.isText()) {
const StyleContext &ctx = m_stack.last();
appendText(node.nodeValue(), ctx.text, ctx.preformatted);
return;
}
if (!node.isElement())
return;
const QDomElement el = node.toElement();
const QString tag = localName(el);
if (tag == QLatin1String("head") || tag == QLatin1String("style") || tag == QLatin1String("script"))
return;
StyleContext ctx = m_stack.last();
BoxStyle box;
// Default HTML semantics
if (tag == QLatin1String("h1")) {
ctx.text.fontSize = m_params.baseFontSize * 1.8;
ctx.text.weight = 700;
ctx.textIndent = 0;
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;
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;
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;
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;
} else if (tag == QLatin1String("blockquote")) {
box.marginLeft = m_params.baseFontSize * 1.5;
box.marginRight = m_params.baseFontSize * 1.0;
box.marginTop = m_params.baseFontSize * 0.5;
box.marginBottom = m_params.baseFontSize * 0.5;
box.borderLeft = 3;
box.paddingLeft = m_params.baseFontSize * 0.75;
ctx.text.italic = true;
} else if (tag == QLatin1String("pre")) {
ctx.text.fontFamilies = {QStringLiteral("monospace")};
ctx.preformatted = true;
box.marginTop = m_params.baseFontSize * 0.5;
box.marginBottom = m_params.baseFontSize * 0.5;
} else if (tag == QLatin1String("b") || tag == QLatin1String("strong")) {
ctx.text.weight = 700;
} else if (tag == QLatin1String("i") || tag == QLatin1String("em") || tag == QLatin1String("cite")) {
ctx.text.italic = true;
} else if (tag == QLatin1String("u") || tag == QLatin1String("ins")) {
ctx.text.underline = true;
} else if (tag == QLatin1String("s") || tag == QLatin1String("strike") || tag == QLatin1String("del")) {
ctx.text.strikeOut = true;
} else if (tag == QLatin1String("sub")) {
ctx.text.fontSize *= 0.75;
ctx.text.baselineShift = -ctx.text.fontSize * 0.35;
} else if (tag == QLatin1String("sup")) {
ctx.text.fontSize *= 0.75;
ctx.text.baselineShift = ctx.text.fontSize * 0.45;
} else if (tag == QLatin1String("small")) {
ctx.text.fontSize *= 0.85;
} else if (tag == QLatin1String("code") || tag == QLatin1String("tt") || tag == QLatin1String("kbd")) {
ctx.text.fontFamilies = {QStringLiteral("monospace")};
ctx.text.background = QColor(255, 255, 255, 20);
} else if (tag == QLatin1String("a")) {
ctx.text.underline = true;
ctx.text.link = true;
} else if (tag == QLatin1String("hr")) {
finishCurrentParagraph();
BlockItem r;
r.kind = BlockItem::Kind::Rule;
m_blocks.append(r);
return;
} else if (tag == QLatin1String("br")) {
InlineItem br;
br.kind = InlineItem::Kind::LineBreak;
m_currentInlines.append(br);
return;
} else if (tag == QLatin1String("img") || tag == QLatin1String("image")) {
handleImage(el, ctx);
return;
}
// Apply HTML attribute alignments
if (el.hasAttribute(QStringLiteral("align"))) {
const QString a = el.attribute(QStringLiteral("align")).toLower();
if (a == QLatin1String("center")) ctx.align = TextAlign::Center;
else if (a == QLatin1String("right")) ctx.align = TextAlign::Right;
else if (a == QLatin1String("justify")) ctx.align = TextAlign::Justify;
else if (a == QLatin1String("left")) ctx.align = TextAlign::Left;
}
// Apply CSS declarations from cascaded style attribute
if (el.hasAttribute(QStringLiteral("style"))) {
const auto decls = Css::parseDeclarations(el.attribute(QStringLiteral("style")));
applyCssDeclarations(decls, ctx, box, m_params);
}
const bool isBlock = isBlockTag(tag);
const bool hasBox = (box.marginTop > 0 || box.marginBottom > 0 || box.marginLeft > 0 || box.marginRight > 0
|| box.paddingTop > 0 || box.paddingBottom > 0 || box.paddingLeft > 0 || box.paddingRight > 0
|| box.borderLeft > 0 || box.borderTop > 0 || box.borderBottom > 0);
if (isBlock) {
finishCurrentParagraph();
if (hasBox) {
BlockItem start;
start.kind = BlockItem::Kind::ContainerStart;
start.box = box;
m_blocks.append(start);
}
}
QString marker;
TextStyle markerStyle;
if (tag == QLatin1String("li")) {
marker = QStringLiteral("• ");
markerStyle = ctx.text;
} else if (tag == QLatin1String("dt")) {
ctx.text.weight = 700;
ctx.textIndent = 0;
} else if (tag == QLatin1String("dd")) {
box.marginLeft = m_params.baseFontSize * 1.5;
ctx.textIndent = 0;
}
if (isBlock) {
startParagraph(ctx, marker, markerStyle);
}
m_stack.append(ctx);
for (QDomNode child = el.firstChild(); !child.isNull(); child = child.nextSibling()) {
walk(child);
}
m_stack.removeLast();
if (isBlock) {
finishCurrentParagraph();
if (hasBox) {
BlockItem end;
end.kind = BlockItem::Kind::ContainerEnd;
end.box = box;
m_blocks.append(end);
}
}
}
void handleImage(const QDomElement &el, const StyleContext &ctx)
{
QString src = el.attribute(QStringLiteral("src"));
if (src.isEmpty())
src = el.attribute(QStringLiteral("xlink:href"));
if (src.isEmpty())
src = el.attribute(QStringLiteral("href"));
if (src.isEmpty())
return;
InlineItem item;
item.kind = InlineItem::Kind::Image;
item.imageUrl = src;
Css::LengthContext lenCtx;
lenCtx.em = ctx.text.fontSize;
lenCtx.rem = m_params.baseFontSize;
lenCtx.percentBase = m_params.contentWidth;
lenCtx.absoluteScale = m_params.baseFontSize / 16.0;
if (el.hasAttribute(QStringLiteral("width"))) {
auto w = Css::parseLength(el.attribute(QStringLiteral("width")), lenCtx);
if (w) item.cssWidth = *w;
}
if (el.hasAttribute(QStringLiteral("height"))) {
auto h = Css::parseLength(el.attribute(QStringLiteral("height")), lenCtx);
if (h) item.cssHeight = *h;
}
if (el.hasAttribute(QStringLiteral("style"))) {
const auto decls = Css::parseDeclarations(el.attribute(QStringLiteral("style")));
for (const auto &d : decls) {
if (d.property == QLatin1String("width")) {
auto w = Css::parseLength(d.value, lenCtx); if (w) item.cssWidth = *w;
} else if (d.property == QLatin1String("height")) {
auto h = Css::parseLength(d.value, lenCtx); if (h) item.cssHeight = *h;
} else if (d.property == QLatin1String("max-width")) {
auto mw = Css::parseLength(d.value, lenCtx); if (mw) item.cssMaxWidth = *mw;
}
}
}
if (m_currentInlines.isEmpty()) {
startParagraph(ctx);
}
m_currentInlines.append(item);
}
const ParseParams &m_params;
QVector<StyleContext> m_stack;
QVector<BlockItem> m_blocks;
QVector<InlineItem> m_currentInlines;
TextAlign m_currentAlign = TextAlign::Justify;
qreal m_currentIndent = 0;
qreal m_currentLineHeight = 0;
qreal m_currentBlockFontSize = 16;
bool m_currentPreformatted = false;
QString m_currentMarker;
TextStyle m_currentMarkerStyle;
};
} // namespace
QVector<BlockItem> parse(const QString &html, const ParseParams &params)
{
if (html.trimmed().isEmpty())
return {};
QString wrapped = html.trimmed();
if (!wrapped.startsWith(QLatin1String("<")))
wrapped = QStringLiteral("<p>") + wrapped + QStringLiteral("</p>");
if (!wrapped.contains(QLatin1String("<body")))
wrapped = QStringLiteral("<body>") + wrapped + QStringLiteral("</body>");
const QString safeXml = HtmlEntities::toXmlSafe(wrapped);
QDomDocument doc;
QString errorMsg;
int errorLine = 0, errorColumn = 0;
if (!doc.setContent(safeXml, false, &errorMsg, &errorLine, &errorColumn)) {
// Fallback: return as a simple paragraph
BlockItem b;
b.kind = BlockItem::Kind::Paragraph;
InlineItem textItem;
textItem.kind = InlineItem::Kind::Text;
textItem.text = html;
b.inlines.append(textItem);
return {b};
}
Builder builder(params);
return builder.build(doc.documentElement());
}
} // namespace HtmlBlockParser
@@ -0,0 +1,107 @@
#pragma once
#include <QColor>
#include <QString>
#include <QStringList>
#include <QVector>
// Intermediate representation between HTML chunks and the Knuth-Plass layout.
// All lengths are resolved to pixels for the LayoutParams used at parse time.
enum class TextAlign { Justify, Left, Center, Right };
enum class TextTransform { None, Uppercase, Lowercase, Capitalize };
struct TextStyle {
QStringList fontFamilies; // preferred families in order (may contain generic names); empty = default
qreal fontSize = 16; // px
int weight = 400; // CSS weight 100..900
bool italic = false;
bool smallCaps = false;
TextTransform transform = TextTransform::None;
qreal letterSpacing = 0; // px
bool underline = false;
bool strikeOut = false;
bool overline = false;
bool link = false;
QColor color; // invalid = theme default
QColor background; // invalid = none
qreal baselineShift = 0; // px, positive = raised (superscript)
bool operator==(const TextStyle &o) const {
return fontFamilies == o.fontFamilies
&& qFuzzyCompare(fontSize, o.fontSize)
&& weight == o.weight
&& italic == o.italic
&& smallCaps == o.smallCaps
&& transform == o.transform
&& qFuzzyCompare(letterSpacing, o.letterSpacing)
&& underline == o.underline
&& strikeOut == o.strikeOut
&& overline == o.overline
&& link == o.link
&& color == o.color
&& background == o.background
&& qFuzzyCompare(baselineShift, o.baselineShift);
}
};
struct InlineItem {
enum class Kind { Text, Image, LineBreak };
Kind kind = Kind::Text;
QString text; // whitespace already collapsed unless preformatted
TextStyle style;
QString imageUrl;
qreal cssWidth = -1; // px, -1 = auto
qreal cssHeight = -1;
qreal cssMaxWidth = -1;
};
struct BoxStyle {
qreal marginTop = 0, marginBottom = 0, marginLeft = 0, marginRight = 0;
qreal paddingTop = 0, paddingBottom = 0, paddingLeft = 0, paddingRight = 0;
qreal borderTop = 0, borderBottom = 0, borderLeft = 0, borderRight = 0;
QColor borderColor; // invalid = theme dim colour
QColor background; // invalid = none
// Boxes with a visible top edge stop margins collapsing through them.
bool blocksTopCollapse() const
{
return paddingTop > 0 || borderTop > 0 || borderLeft > 0 || borderRight > 0 || background.isValid();
}
bool blocksBottomCollapse() const
{
return paddingBottom > 0 || borderBottom > 0 || borderLeft > 0 || borderRight > 0 || background.isValid();
}
};
struct BlockItem {
enum class Kind { ContainerStart, ContainerEnd, Paragraph, Rule };
Kind kind = Kind::Paragraph;
BoxStyle box; // ContainerStart / ContainerEnd (same values on both)
// Paragraph properties
TextAlign align = TextAlign::Justify;
qreal textIndent = 0; // px, first line only
qreal lineHeight = 0; // multiplier of fontSize; 0 = LayoutParams default
qreal fontSize = 16; // block font size (minimum line height basis)
bool preformatted = false;
QString marker; // list marker drawn left of the first line
TextStyle markerStyle;
QVector<InlineItem> inlines;
QColor ruleColor; // Rule only; invalid = theme dim colour
};
struct ParseParams {
qreal baseFontSize = 16; // user preference, px
qreal contentWidth = 600; // px, resolves percentage lengths
};
namespace HtmlBlockParser {
// Parses one standalone HTML chunk (an XHTML fragment whose elements carry
// their cascaded CSS in `style` attributes) into a flat block list.
QVector<BlockItem> parse(const QString &html, const ParseParams &params);
} // namespace HtmlBlockParser
+261
View File
@@ -0,0 +1,261 @@
#include "KnuthPlass.h"
#include <QtGlobal>
#include <cmath>
namespace KnuthPlass {
namespace {
struct Node {
int position = -1; // breakpoint item index (-1 = paragraph start)
int start = 0; // first item index of the line that follows this break
int line = 0;
int fitness = 1;
qreal totalDemerits = 0;
int previous = -1; // arena index of the previous node in the best chain
};
struct Candidate {
qreal demerits = std::numeric_limits<qreal>::infinity();
int from = -1;
};
inline bool isForced(const Item &it)
{
return it.type == ItemType::Penalty && it.penalty <= -kInfinity;
}
inline int fitnessClass(qreal r)
{
if (r < -0.5) return 0;
if (r <= 0.5) return 1;
if (r <= 1.0) return 2;
return 3;
}
class Solver {
public:
Solver(const QVector<Item> &items, qreal lineWidth, const Params &params)
: m_items(items), m_lineWidth(lineWidth), m_params(params)
{
const int n = items.size();
m_sumW.resize(n + 1);
m_sumY.resize(n + 1);
m_sumZ.resize(n + 1);
m_sumW[0] = m_sumY[0] = m_sumZ[0] = 0;
for (int i = 0; i < n; ++i) {
const Item &it = items[i];
const bool counts = it.type != ItemType::Penalty;
m_sumW[i + 1] = m_sumW[i] + (counts ? it.width : 0);
m_sumY[i + 1] = m_sumY[i] + (it.type == ItemType::Glue ? it.stretch : 0);
m_sumZ[i + 1] = m_sumZ[i] + (it.type == ItemType::Glue ? it.shrink : 0);
}
}
qreal ratio(int start, int breakIdx) const
{
const Item &b = m_items[breakIdx];
qreal w = m_sumW[breakIdx] - m_sumW[start];
if (b.type == ItemType::Penalty)
w += b.width;
if (w < m_lineWidth) {
const qreal y = m_sumY[breakIdx] - m_sumY[start];
if (y >= 100000.0)
return 0.0;
return y > 0 ? (m_lineWidth - w) / y : kInfinity;
}
if (w > m_lineWidth) {
const qreal z = m_sumZ[breakIdx] - m_sumZ[start];
return z > 0 ? (m_lineWidth - w) / z : -kInfinity;
}
return 0;
}
// First item of the line that starts after a break at `breakIdx`:
// glue and non-forced penalties following a break are discarded.
int startAfter(int breakIdx) const
{
int j = breakIdx + 1;
while (j < m_items.size()) {
const Item &it = m_items[j];
if (it.type == ItemType::Box || isForced(it))
break;
++j;
}
return j;
}
bool isLegalBreak(int i) const
{
const Item &it = m_items[i];
if (it.type == ItemType::Penalty)
return it.penalty < kInfinity;
if (it.type == ItemType::Glue)
return i > 0 && m_items[i - 1].type == ItemType::Box;
return false;
}
// Returns the arena index of the best final node, or -1 when this pass failed.
int run(qreal tolerance, bool rescue)
{
m_nodes.clear();
m_active.clear();
m_nodes.reserve(m_items.size() / 4 + 8);
m_nodes.append(Node{});
m_active.append(0);
const int n = m_items.size();
QVector<int> keep;
keep.reserve(64);
for (int b = 0; b < n; ++b) {
if (!isLegalBreak(b))
continue;
const Item &brk = m_items[b];
const bool forced = isForced(brk);
Candidate best[4];
int lastDeactivated = -1;
keep.clear();
for (int idx : std::as_const(m_active)) {
const Node &a = m_nodes[idx];
const qreal r = ratio(a.start, b);
if (r < -1 || forced)
lastDeactivated = idx;
else
keep.append(idx);
if (r < -1 || r > tolerance)
continue;
const qreal badness = std::min(100.0 * std::pow(std::abs(r), 3), kInfinity);
qreal d = m_params.linePenalty + badness;
d *= d;
if (brk.type == ItemType::Penalty) {
if (brk.penalty >= 0)
d += brk.penalty * brk.penalty;
else if (brk.penalty > -kInfinity)
d -= brk.penalty * brk.penalty;
}
if (brk.type == ItemType::Penalty && brk.flagged && a.position >= 0) {
const Item &prev = m_items[a.position];
if (prev.type == ItemType::Penalty && prev.flagged)
d += m_params.flaggedDemerits;
}
const int fit = fitnessClass(r);
if (a.position >= 0 && std::abs(fit - a.fitness) > 1)
d += m_params.fitnessDemerits;
const qreal total = a.totalDemerits + d;
if (total < best[fit].demerits) {
best[fit].demerits = total;
best[fit].from = idx;
}
}
m_active.swap(keep);
bool added = false;
const int start = startAfter(b);
for (int fit = 0; fit < 4; ++fit) {
if (best[fit].from < 0)
continue;
Node node;
node.position = b;
node.start = start;
node.line = m_nodes[best[fit].from].line + 1;
node.fitness = fit;
node.totalDemerits = best[fit].demerits;
node.previous = best[fit].from;
m_nodes.append(node);
m_active.append(m_nodes.size() - 1);
added = true;
}
if (m_active.isEmpty() && !added) {
if (!rescue || lastDeactivated < 0)
return -1;
// Last resort: accept an overfull line rather than failing.
Node node;
node.position = b;
node.start = start;
node.line = m_nodes[lastDeactivated].line + 1;
node.fitness = 0;
node.totalDemerits = m_nodes[lastDeactivated].totalDemerits + kInfinity * kInfinity;
node.previous = lastDeactivated;
m_nodes.append(node);
m_active.append(m_nodes.size() - 1);
}
}
int bestIdx = -1;
for (int idx : std::as_const(m_active)) {
if (m_nodes[idx].position != n - 1)
continue;
if (bestIdx < 0 || m_nodes[idx].totalDemerits < m_nodes[bestIdx].totalDemerits)
bestIdx = idx;
}
return bestIdx;
}
QVector<Line> lines(int finalNode) const
{
QVector<Line> out;
for (int idx = finalNode; idx > 0; idx = m_nodes[idx].previous) {
const Node &node = m_nodes[idx];
const Node &prev = m_nodes[node.previous];
const Item &brk = m_items[node.position];
Line line;
line.start = prev.start;
line.end = node.position;
line.ratio = ratio(prev.start, node.position);
line.hyphenated = brk.type == ItemType::Penalty && brk.flagged && brk.width > 0;
out.append(line);
}
std::reverse(out.begin(), out.end());
return out;
}
private:
const QVector<Item> &m_items;
qreal m_lineWidth;
Params m_params;
QVector<qreal> m_sumW, m_sumY, m_sumZ;
QVector<Node> m_nodes;
QVector<int> m_active;
};
} // namespace
void finishParagraph(QVector<Item> &items)
{
// A trailing glue would otherwise become a legal break before the end.
while (!items.isEmpty() && items.last().type == ItemType::Glue)
items.removeLast();
items.append(Item::penaltyItem(0, kInfinity, false));
items.append(Item::glue(0, kInfiniteStretch, 0));
items.append(Item::penaltyItem(0, -kInfinity, false));
}
QVector<Line> breakLines(const QVector<Item> &items, qreal lineWidth, const Params &params)
{
if (items.isEmpty())
return {};
Q_ASSERT(isForced(items.last()));
Solver solver(items, std::max<qreal>(1.0, lineWidth), params);
int finalNode = solver.run(params.tolerance, false);
if (finalNode < 0)
finalNode = solver.run(params.looseTolerance, false);
if (finalNode < 0)
finalNode = solver.run(std::numeric_limits<qreal>::infinity(), true);
if (finalNode < 0)
return {};
return solver.lines(finalNode);
}
} // namespace KnuthPlass
+65
View File
@@ -0,0 +1,65 @@
#pragma once
#include <QVector>
#include <limits>
// Knuth-Plass optimal paragraph line breaking (Knuth & Plass, "Breaking
// Paragraphs into Lines", 1981). Pure computation: no Qt GUI dependency.
//
// Optimisations over the textbook formulation:
// * Prefix sums of width/stretch/shrink give O(1) line measurements between
// any active node and a candidate breakpoint.
// * Break nodes live in one contiguous arena addressed by index, so the inner
// loop performs no heap allocation per node.
namespace KnuthPlass {
constexpr qreal kInfinity = 10000.0; // penalty >= kInfinity forbids a break, <= -kInfinity forces it
constexpr qreal kInfiniteStretch = 1e7; // "fil" stretch used by the paragraph-finishing glue
enum class ItemType { Box, Glue, Penalty };
struct Item {
ItemType type = ItemType::Box;
qreal width = 0;
qreal stretch = 0; // glue only
qreal shrink = 0; // glue only
qreal penalty = 0; // penalty only
bool flagged = false; // penalty only: a hyphenation break
int tag = -1; // opaque caller data (e.g. index of the token this item represents)
static Item box(qreal w, int tag = -1) { Item i; i.type = ItemType::Box; i.width = w; i.tag = tag; return i; }
static Item glue(qreal w, qreal stretch, qreal shrink, int tag = -1)
{
Item i; i.type = ItemType::Glue; i.width = w; i.stretch = stretch; i.shrink = shrink; i.tag = tag; return i;
}
static Item penaltyItem(qreal w, qreal p, bool flagged, int tag = -1)
{
Item i; i.type = ItemType::Penalty; i.width = w; i.penalty = p; i.flagged = flagged; i.tag = tag; return i;
}
};
struct Params {
qreal tolerance = 2.0; // maximum adjustment ratio accepted on the first pass
qreal looseTolerance = 10.0; // second pass when the first finds no feasible solution
qreal linePenalty = 10.0;
qreal flaggedDemerits = 100.0; // consecutive hyphenated lines
qreal fitnessDemerits = 100.0; // adjacent lines differ by more than one fitness class
};
struct Line {
int start = 0; // index of the first item rendered on this line
int end = 0; // index of the breakpoint item (exclusive for rendering, except a penalty's width)
qreal ratio = 0; // adjustment ratio applied to the glue of this line
bool hyphenated = false; // ended at a flagged penalty with width (draw a hyphen)
};
// Appends the standard paragraph ending: finishing glue + forced break.
void finishParagraph(QVector<Item> &items);
// Break the item list into lines of the given width. The list must end with a
// forced break (use finishParagraph). Always returns a solution: when no
// feasible set of breaks exists, overfull lines are produced as a last resort.
QVector<Line> breakLines(const QVector<Item> &items, qreal lineWidth, const Params &params = {});
} // namespace KnuthPlass
+2 -2
View File
@@ -11,8 +11,8 @@ BookPosition BookPositionStore::load(const QByteArray &contentMd5)
return {};
const QVariantMap d = m_state.loadSection(sectionKey(contentMd5));
BookPosition pos;
pos.chapterIndex = d.value(QStringLiteral("chapterIndex"), 0).toInt();
pos.chunkIndex = d.value(QStringLiteral("chunkIndex"), 0).toInt();
pos.intraOffset = d.value(QStringLiteral("intraOffset"), 0.0).toReal();
pos.progress = d.value(QStringLiteral("progress"), 0.0).toReal();
pos.pageShift = d.value(QStringLiteral("pageShift"), true).toBool();
pos.mangaRTL = d.value(QStringLiteral("mangaRTL"), true).toBool();
@@ -24,8 +24,8 @@ void BookPositionStore::save(const QByteArray &contentMd5, const BookPosition &p
if (contentMd5.isEmpty())
return;
m_state.saveSection(sectionKey(contentMd5), {
{QStringLiteral("chapterIndex"), pos.chapterIndex},
{QStringLiteral("chunkIndex"), pos.chunkIndex},
{QStringLiteral("intraOffset"), pos.intraOffset},
{QStringLiteral("progress"), pos.progress},
{QStringLiteral("pageShift"), pos.pageShift},
{QStringLiteral("mangaRTL"), pos.mangaRTL},
+1 -1
View File
@@ -5,8 +5,8 @@
#include "backend/AppState.h"
struct BookPosition {
int chapterIndex = 0; // Text mode: current chapter (0 for single-chapter / comic)
int chunkIndex = 0; // Comic mode: page index; Text mode: top chunk index
qreal intraOffset = 0.0; // Text mode: intra-chunk pixel scroll offset
qreal progress = 0.0; // Normalized [0..1] scroll/reading progress
bool pageShift = true; // Comic mode only
bool mangaRTL = true; // Comic mode only
+19 -1
View File
@@ -13,11 +13,14 @@
#include "backend/AppState.h"
#include "backend/formats/FileIconProvider.h"
#include "backend/formats/FormatRegistry.h"
#include "backend/formats/WebImageProvider.h"
#include "backend/formats/sources/DirByteSource.h"
#include "backend/formats/sources/RarByteSource.h"
#include "backend/formats/sources/ZipByteSource.h"
#include "backend/HistoryModel.h"
#include "backend/ReadingModel.h"
#include "backend/reading/BookImageResolver.h"
#include "backend/reading/KnuthPlassItem.h"
#include "backend/NativeFileDialogService.h"
#include "backend/book/Book.h"
#include "backend/state/BookPositionStore.h"
@@ -105,6 +108,7 @@ int main(int argc, char *argv[])
[] { return std::make_unique<RarByteSource>(); }),
FormatSpec::comic({}, /*matchesDirectory=*/true, QStringLiteral("dir"),
[] { return std::make_unique<DirByteSource>(); }),
FormatSpec::epub([] { return std::make_unique<ZipByteSource>(); }),
});
HistoryModel historyModel(formatRegistry);
@@ -131,9 +135,21 @@ int main(int argc, char *argv[])
Book book(*fileDialogService, formatRegistry);
ReadingModel readingModel(bookPositions);
auto webStorage = std::make_shared<DiskWebImageStorage>();
auto *webProvider = new WebImageProvider(webStorage);
BookImageResolver imageResolver([&formatRegistry](const QString &scheme) {
return formatRegistry.createByteSourceForScheme(scheme);
}, webProvider);
KnuthPlassItem::setImageResolver(&imageResolver);
readingModel.setImageResolver(&imageResolver);
qRegisterMetaType<ChunkLayout>("ChunkLayout");
// --- QML engine ---
QQmlApplicationEngine engine;
qmlRegisterType<KnuthPlassItem>("Asteria", 1, 0, "KnuthPlassItem");
engine.addImageProvider(QStringLiteral("fileicon"), new FileIconProvider());
engine.addImageProvider(QStringLiteral("web"), webProvider);
formatRegistry.registerImageProviders(engine);
engine.rootContext()->setContextProperty(QStringLiteral("isDebugBuild"),
#ifdef QT_DEBUG
@@ -176,5 +192,7 @@ int main(int argc, char *argv[])
qInfo("Rendering API: %s", apiName);
}
return QApplication::exec();
const int ret = QApplication::exec();
imageResolver.setWebProvider(nullptr);
return ret;
}
+23 -1
View File
@@ -22,10 +22,23 @@ ApplicationWindow {
property string currentPage: "starter"
property bool settingsOpen: false
property bool barsVisible: true
property bool _savedSidebarOpen: false
// Set to true on the first book open at startup so we restore the last page.
property bool _startupRestore: false
property bool _bookInitializing: false
function toggleChrome() {
var anyVisible = barsVisible || sidebarOpen
if (anyVisible) {
_savedSidebarOpen = sidebarOpen
barsVisible = false
uiState.sidebarOpen = false
} else {
barsVisible = true
uiState.sidebarOpen = _savedSidebarOpen
}
}
onCurrentPageChanged: uiState.lastPage = currentPage
Component.onCompleted: {
@@ -230,7 +243,7 @@ ApplicationWindow {
}
}
Shortcut {
sequences: ["PgDown", "Next", "Space"]
sequences: ["PgDown", "Next"]
context: Qt.ApplicationShortcut
onActivated: {
if (currentPage === "reader" && readerPage?.pageView) {
@@ -238,6 +251,15 @@ ApplicationWindow {
}
}
}
Shortcut {
sequence: "Space"
context: Qt.ApplicationShortcut
onActivated: {
if (currentPage === "reader") {
window.toggleChrome();
}
}
}
Shortcut {
sequence: "M"
context: Qt.ApplicationShortcut
+20 -1
View File
@@ -13,6 +13,25 @@ Rectangle {
anchors.top: parent.top
}
// Measuring spinner
Text {
anchors.left: parent.left
anchors.leftMargin: 16
anchors.verticalCenter: parent.verticalCenter
visible: readingModel.measuring
text: "\ue863"
font.family: "Material Icons Outlined"
font.pixelSize: 16
color: ThemeManager.currentTheme.dimText
RotationAnimator on rotation {
from: 0; to: 360
duration: 1000
loops: Animation.Infinite
running: parent.visible
}
}
// RTL reading direction toggle.
FlatIconButton {
visible: !readingModel.isTextMode
@@ -43,7 +62,7 @@ Rectangle {
: ThemeManager.currentTheme.dimText
tooltip: "Page shift (S)"
onClicked: {
const pairIdx = readerPage.pageView.currentPair
const pairIdx = readerPage.mangaView.currentPair
readingModel.setPageShift(!readingModel.pageShift, pairIdx)
}
}
+2 -3
View File
@@ -179,9 +179,8 @@ Rectangle {
// Right third tap.
if (readingModel.mangaRTL) previousPair(); else nextPair()
} else {
// Middle — toggle bars.
window.barsVisible = !window.barsVisible
uiState.sidebarOpen = !uiState.sidebarOpen
// Middle — toggle chrome.
window.toggleChrome()
}
}
}
+221
View File
@@ -0,0 +1,221 @@
import QtQuick
import QtQuick.Controls
import Asteria
Rectangle {
id: root
focus: true
readonly property int scrollbarWidth: 16
property bool contentReady: false
property bool restoreReady: false
property int initialIndex: 0
property real initialOffset: 0
gradient: Gradient {
GradientStop { position: 0.0; color: ThemeManager.currentTheme.gradientTop }
GradientStop { position: 1.0; color: ThemeManager.currentTheme.gradientBottom }
}
// Keyboard navigation
function handlePageUp() {
var scrollAmount = chunkListView.height * 0.9;
var targetY = Math.max(0, chunkListView.contentY - scrollAmount);
animateScrollTo(targetY);
}
function handlePageDown() {
var scrollAmount = chunkListView.height * 0.9;
var maxY = Math.max(0, chunkListView.contentHeight - chunkListView.height);
var targetY = Math.min(maxY, chunkListView.contentY + scrollAmount);
animateScrollTo(targetY);
}
function handleScrollUp() {
var scrollAmount = readingPreferences.fontSize * readingPreferences.lineSpacing * 3;
var targetY = Math.max(0, chunkListView.contentY - scrollAmount);
animateScrollTo(targetY);
}
function handleScrollDown() {
var scrollAmount = readingPreferences.fontSize * readingPreferences.lineSpacing * 3;
var maxY = Math.max(0, chunkListView.contentHeight - chunkListView.height);
var targetY = Math.min(maxY, chunkListView.contentY + scrollAmount);
animateScrollTo(targetY);
}
function animateScrollTo(targetY) {
scrollAnimation.stop();
scrollAnimation.to = targetY;
scrollAnimation.start();
}
PropertyAnimation {
id: scrollAnimation
target: chunkListView
property: "contentY"
duration: 180
easing.type: Easing.OutQuad
}
function updateContentMetrics() {
if (chunkListView.width > 0) {
var availW = chunkListView.width - scrollbarWidth - 2 * readingPreferences.horizontalMargin;
var topIdx = -1;
var intraRatio = 0.0;
if (contentReady && restoreReady) {
var probeX = chunkListView.width / 2;
var probeY = chunkListView.contentY + 10;
topIdx = chunkListView.indexAt(probeX, probeY);
if (topIdx < 0) {
topIdx = (readingModel.currentPage > 0) ? (readingModel.currentPage - 1) : 0;
}
var topItem = chunkListView.itemAtIndex(topIdx);
if (topItem && topItem.height > 0) {
intraRatio = Math.max(0.0, Math.min(1.0, (chunkListView.contentY - topItem.y) / topItem.height));
}
}
readingModel.updateLayoutMetrics(Math.max(100, Math.floor(availW)),
readingPreferences.fontSize,
readingPreferences.lineSpacing,
topIdx);
if (contentReady && restoreReady && topIdx >= 0) {
var newTopItem = chunkListView.itemAtIndex(topIdx);
if (newTopItem && newTopItem.height > 0) {
chunkListView.contentY = newTopItem.y + intraRatio * newTopItem.height;
}
}
}
}
Component.onCompleted: updateContentMetrics()
onWidthChanged: updateContentMetrics()
Connections {
target: readingPreferences
function onFontSizeChanged() { updateContentMetrics() }
function onLineSpacingChanged() { updateContentMetrics() }
function onHorizontalMarginChanged() { updateContentMetrics() }
}
ListView {
id: chunkListView
anchors.fill: parent
anchors.topMargin: readingPreferences.verticalMargin
anchors.bottomMargin: readingPreferences.verticalMargin
model: contentReady ? readingModel : null
cacheBuffer: 600
clip: true
maximumFlickVelocity: 99999
delegate: Item {
id: chunkDelegate
width: chunkListView.width
height: model.pixelHeight > 0 ? model.pixelHeight : 30
KnuthPlassItem {
width: parent.width
height: parent.height
layout: model.layout
textColor: ThemeManager.currentTheme.readingText
linkColor: ThemeManager.currentTheme.buttonAccent
dimColor: ThemeManager.currentTheme.dimText
horizontalMargin: readingPreferences.horizontalMargin
}
}
onContentYChanged: {
if (contentReady && restoreReady) {
scrollTrackTimer.restart();
}
}
ScrollBar.vertical: ScrollBar {
id: vScrollBar
policy: ScrollBar.AsNeeded
padding: 0
contentItem: Rectangle {
implicitWidth: scrollbarWidth
radius: 3
color: ThemeManager.currentTheme.scrollbarThumb
}
background: Rectangle {
implicitWidth: scrollbarWidth
color: ThemeManager.currentTheme.scrollbarTrack
}
}
MouseArea {
anchors.fill: parent
anchors.rightMargin: scrollbarWidth
z: 1
onClicked: clickDebounce.restart()
onDoubleClicked: {
clickDebounce.stop()
window.visibility = (window.visibility === Window.FullScreen) ? Window.Windowed : Window.FullScreen
}
}
Timer {
id: clickDebounce
interval: 150
onTriggered: window.toggleChrome()
}
}
Timer {
id: scrollTrackTimer
interval: 150
repeat: false
onTriggered: {
if (contentReady && restoreReady && readingModel.isTextMode) {
var probeX = chunkListView.width / 2;
var probeY = chunkListView.contentY + 10;
var topIdx = chunkListView.indexAt(probeX, probeY);
if (topIdx < 0) {
topIdx = (readingModel.currentPage > 0) ? (readingModel.currentPage - 1) : 0;
}
var topItem = chunkListView.itemAtIndex(topIdx);
var intraOffset = topItem ? (chunkListView.contentY - topItem.y) : 0;
var maxScroll = Math.max(1, chunkListView.contentHeight - chunkListView.height);
var prop = Math.min(1.0, Math.max(0.0, chunkListView.contentY / maxScroll));
readingModel.setScrollPosition(topIdx, intraOffset, prop);
}
}
}
Connections {
target: readingModel
function onRestoreReady(chunkIndex, intraOffset) {
contentReady = true;
initialIndex = chunkIndex;
initialOffset = (intraOffset !== undefined) ? intraOffset : 0;
restoreTimer.start();
}
}
Timer {
id: restoreTimer
interval: 10
repeat: false
onTriggered: {
chunkListView.positionViewAtIndex(initialIndex, ListView.Beginning);
chunkListView.contentY += initialOffset;
restoreReady = true;
}
}
Connections {
target: book
function onLoadingChanged() {
if (book.loading) {
contentReady = false;
restoreReady = false;
}
}
}
}
+11 -1
View File
@@ -3,7 +3,10 @@ import Asteria
Item {
id: readerPage
property alias pageView: internalPageView
property alias mangaView: internalPageView
property alias scrollView: scrollPageView
readonly property var pageView: readingModel.isTextMode ? scrollPageView : internalPageView
MangaPageView {
id: internalPageView
@@ -11,4 +14,11 @@ Item {
visible: !readingModel.isTextMode
focus: visible
}
ScrollPageView {
id: scrollPageView
anchors.fill: parent
visible: readingModel.isTextMode
focus: visible
}
}
+18 -1
View File
@@ -16,6 +16,7 @@ static FormatRegistry makeRegistry()
[] { return std::make_unique<RarByteSource>(); }),
FormatSpec::comic({}, /*matchesDirectory=*/true, QStringLiteral("dir"),
[] { return std::make_unique<DirByteSource>(); }),
FormatSpec::epub([] { return std::make_unique<ZipByteSource>(); }),
});
}
@@ -43,6 +44,20 @@ private slots:
QVERIFY(registry.createReader("file.cbr") != nullptr);
}
void createEpubReader()
{
auto registry = makeRegistry();
auto reader = registry.createReader("file.epub");
QVERIFY(reader != nullptr);
QCOMPARE(reader->mode(), ReadingMode::Text);
}
void createEpubReaderUpperCase()
{
auto registry = makeRegistry();
QVERIFY(registry.createReader("file.EPUB") != nullptr);
}
void createUnknownFormat()
{
auto registry = makeRegistry();
@@ -77,8 +92,9 @@ private slots:
const QStringList exts = registry.supportedExtensions();
QVERIFY(exts.contains(QStringLiteral("cbz")));
QVERIFY(exts.contains(QStringLiteral("cbr")));
QVERIFY(exts.contains(QStringLiteral("epub")));
// The directory row contributes no extension
QCOMPARE(exts.size(), 2);
QCOMPARE(exts.size(), 3);
}
void registerImageProvidersRegistersSchemes()
@@ -90,6 +106,7 @@ private slots:
QVERIFY(engine.imageProvider(QStringLiteral("cbz")) != nullptr);
QVERIFY(engine.imageProvider(QStringLiteral("cbr")) != nullptr);
QVERIFY(engine.imageProvider(QStringLiteral("dir")) != nullptr);
QVERIFY(engine.imageProvider(QStringLiteral("epub")) != nullptr);
QVERIFY(engine.imageProvider(QStringLiteral("unknown")) == nullptr);
}
};
+16 -28
View File
@@ -41,16 +41,13 @@ public:
QByteArray contentHash() const override { return QByteArray("texthash"); }
bool loadMetadata(const QString &) override { return true; }
int chapterCount() const override { return 2; }
Chapter loadChapter(int index) const override
QStringList chunks() const override
{
if (index == 0)
return {0, QStringLiteral("Chapter 1"), {QStringLiteral("<p>Chunk 1</p>"), QStringLiteral("<p>Chunk 2</p>")}};
return {1, QStringLiteral("Chapter 2"), {QStringLiteral("<p>Chunk 3</p>")}};
}
QVector<TocEntry> tableOfContents() const override
{
return {{QStringLiteral("Chapter 1"), 0, 0}, {QStringLiteral("Chapter 2"), 1, 0}};
return {
QStringLiteral("<p>Chunk 1</p>"),
QStringLiteral("<p>Chunk 2</p>"),
QStringLiteral("<p>Chunk 3</p>")
};
}
};
@@ -167,7 +164,7 @@ private slots:
QVERIFY(!model.mangaRTL());
}
void textModeChaptersAndChunks()
void textModeContinuousChunks()
{
Ctx ctx; ReadingModel model(*ctx.store);
FakeTextReader reader;
@@ -178,31 +175,22 @@ private slots:
QCOMPARE(modeSpy.count(), 1);
QVERIFY(model.isTextMode());
QCOMPARE(model.chapterCount(), 2);
QCOMPARE(model.currentChapter(), 0);
QCOMPARE(model.chapterTitle(), QStringLiteral("Chapter 1"));
QCOMPARE(model.rowCount(), 2);
QCOMPARE(model.rowCount(), 3);
QCOMPARE(model.data(model.index(0, 0), ReadingModel::ContentRole).toString(),
QStringLiteral("<p>Chunk 1</p>"));
QCOMPARE(model.data(model.index(1, 0), ReadingModel::ContentRole).toString(),
QStringLiteral("<p>Chunk 2</p>"));
QCOMPARE(model.data(model.index(2, 0), ReadingModel::ContentRole).toString(),
QStringLiteral("<p>Chunk 3</p>"));
QTRY_COMPARE(restoreSpy.count(), 1);
// Next chapter navigation
QSignalSpy chapterSpy(&model, &ReadingModel::currentChapterChanged);
model.nextChapter();
QCOMPARE(chapterSpy.count(), 1);
QCOMPARE(model.currentChapter(), 1);
QCOMPARE(model.chapterTitle(), QStringLiteral("Chapter 2"));
QCOMPARE(model.rowCount(), 1);
QCOMPARE(model.data(model.index(0, 0), ReadingModel::ContentRole).toString(),
QStringLiteral("<p>Chunk 3</p>"));
// Previous chapter navigation
model.previousChapter();
QCOMPARE(model.currentChapter(), 0);
QCOMPARE(model.rowCount(), 2);
// Test resize fast path
QSignalSpy dataSpy(&model, &ReadingModel::dataChanged);
model.updateLayoutMetrics(800, 16, 1.2);
QVERIFY(dataSpy.count() >= 1);
QCOMPARE(model.rowCount(), 3);
QCOMPARE(model.data(model.index(0, 0), ReadingModel::LayoutRole).value<ChunkLayout>().contentWidth, 800);
}
void setReaderNullResetsState()
-1
View File
@@ -63,7 +63,6 @@ private slots:
QCOMPARE(ctx.book->filePath(), QString());
QCOMPARE(ctx.book->coverImageUrl(),QString());
QCOMPARE(ctx.book->errorMessage(), QString());
QVERIFY(ctx.book->tableOfContents().isEmpty());
}
void openValidFile()
+195
View File
@@ -0,0 +1,195 @@
#include <QtTest>
#include "backend/formats/EpubReader.h"
#include "backend/formats/IByteSource.h"
#include "backend/formats/ImageUrl.h"
class InMemoryByteSource : public IByteSource {
public:
bool open(const QString &path) override {
m_path = path;
return m_openResult;
}
QStringList listEntries() const override { return m_entries.keys(); }
QByteArray readEntry(const QString &name) const override { return m_entries.value(name); }
QByteArray contentHash() const override { return QByteArray("testhash123"); }
bool m_openResult = true;
QString m_path;
QHash<QString, QByteArray> m_entries;
};
class EpubReaderTest : public QObject {
Q_OBJECT
private slots:
void openFailsIfSourceFails()
{
auto factory = [] {
auto src = std::make_unique<InMemoryByteSource>();
src->m_openResult = false;
return src;
};
EpubReader reader(factory, QStringLiteral("epub"));
QVERIFY(!reader.open(QStringLiteral("/path/to/missing.epub")));
QVERIFY(!reader.lastError().isEmpty());
}
void openFailsIfContainerMissing()
{
auto factory = [] {
auto src = std::make_unique<InMemoryByteSource>();
return src;
};
EpubReader reader(factory, QStringLiteral("epub"));
QVERIFY(!reader.open(QStringLiteral("/path/to/bad.epub")));
QVERIFY(reader.lastError().contains(QStringLiteral("container.xml")));
}
void openEpub2WithMetadataCoverAndNcx()
{
auto src = std::make_unique<InMemoryByteSource>();
// 1. container.xml
src->m_entries.insert(QStringLiteral("META-INF/container.xml"),
"<container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">\n"
" <rootfiles>\n"
" <rootfile full-path=\"OEBPS/content.opf\" media-type=\"application/oebps-package+xml\"/>\n"
" </rootfiles>\n"
"</container>");
// 2. content.opf
src->m_entries.insert(QStringLiteral("OEBPS/content.opf"),
"<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"2.0\">\n"
" <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"
" <dc:title>Test EPUB Title</dc:title>\n"
" <dc:creator>Test Author</dc:creator>\n"
" <meta name=\"cover\" content=\"cover-img\"/>\n"
" </metadata>\n"
" <manifest>\n"
" <item id=\"cover-img\" href=\"images/cover.jpg\" media-type=\"image/jpeg\"/>\n"
" <item id=\"style\" href=\"css/style.css\" media-type=\"text/css\"/>\n"
" <item id=\"ch1\" href=\"text/ch1.xhtml\" media-type=\"application/xhtml+xml\"/>\n"
" <item id=\"ncx\" href=\"toc.ncx\" media-type=\"application/x-dtbncx+xml\"/>\n"
" </manifest>\n"
" <spine toc=\"ncx\">\n"
" <itemref idref=\"ch1\"/>\n"
" </spine>\n"
"</package>");
// 3. toc.ncx
src->m_entries.insert(QStringLiteral("OEBPS/toc.ncx"),
"<ncx xmlns=\"http://www.daisy.org/z3986/2005/ncx/\" version=\"2005-1\">\n"
" <navMap>\n"
" <navPoint id=\"np1\" playOrder=\"1\">\n"
" <navLabel><text>Chapter 1: The Beginning</text></navLabel>\n"
" <content src=\"text/ch1.xhtml\"/>\n"
" </navPoint>\n"
" </navMap>\n"
"</ncx>");
// 4. css
src->m_entries.insert(QStringLiteral("OEBPS/css/style.css"),
"p { color: red; }\n"
".quote { font-style: italic; }\n");
// 5. chapter 1 xhtml
src->m_entries.insert(QStringLiteral("OEBPS/text/ch1.xhtml"),
"<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
"<head>\n"
" <link rel=\"stylesheet\" href=\"../css/style.css\"/>\n"
"</head>\n"
"<body>\n"
" <h1>Heading</h1>\n"
" <p class=\"quote\">A stylish quote with an embedded image: <img src=\"../images/fig1.png\"/></p>\n"
" <p>External image: <img src=\"https://example.com/pic.jpg\"/></p>\n"
"</body>\n"
"</html>");
auto sharedEntries = std::make_shared<QHash<QString, QByteArray>>(src->m_entries);
auto factory = [sharedEntries]() {
auto s = std::make_unique<InMemoryByteSource>();
s->m_entries = *sharedEntries;
return s;
};
EpubReader reader(factory, QStringLiteral("epub"));
QVERIFY(reader.open(QStringLiteral("/virtual/book.epub")));
QCOMPARE(reader.title(), QStringLiteral("Test EPUB Title"));
QCOMPARE(reader.author(), QStringLiteral("Test Author"));
QCOMPARE(reader.coverImageUrl(), ImageUrl::build(QStringLiteral("epub"),
QStringLiteral("OEBPS/images/cover.jpg"),
QStringLiteral("/virtual/book.epub")));
QVERIFY(!reader.chunks().isEmpty());
QString fullHtml = reader.chunks().join(QString());
// Verify CSS styling inlined
QVERIFY(fullHtml.contains(QStringLiteral("color:red")) || fullHtml.contains(QStringLiteral("italic")));
// Verify embedded image resolved to image://epub/ with source path
QVERIFY(fullHtml.contains(QStringLiteral("image://epub/OEBPS/images/fig1.png")));
QVERIFY(fullHtml.contains(QStringLiteral("src=%2Fvirtual%2Fbook.epub")) || fullHtml.contains(QStringLiteral("src=/virtual/book.epub")));
// Verify web image resolved to image://web/
QVERIFY(fullHtml.contains(QStringLiteral("image://web/https://example.com/pic.jpg")));
}
void openEpub3WithNavDocument()
{
auto src = std::make_unique<InMemoryByteSource>();
src->m_entries.insert(QStringLiteral("META-INF/container.xml"),
"<container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">\n"
" <rootfiles>\n"
" <rootfile full-path=\"EPUB/package.opf\" media-type=\"application/oebps-package+xml\"/>\n"
" </rootfiles>\n"
"</container>");
src->m_entries.insert(QStringLiteral("EPUB/package.opf"),
"<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"3.0\">\n"
" <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"
" <dc:title>EPUB 3 Sample</dc:title>\n"
" </metadata>\n"
" <manifest>\n"
" <item id=\"cover\" href=\"cover.png\" media-type=\"image/png\" properties=\"cover-image\"/>\n"
" <item id=\"nav\" href=\"nav.xhtml\" media-type=\"application/xhtml+xml\" properties=\"nav\"/>\n"
" <item id=\"c1\" href=\"ch1.xhtml\" media-type=\"application/xhtml+xml\"/>\n"
" </manifest>\n"
" <spine>\n"
" <itemref idref=\"c1\"/>\n"
" </spine>\n"
"</package>");
src->m_entries.insert(QStringLiteral("EPUB/nav.xhtml"),
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
"<body>\n"
" <nav epub:type=\"toc\">\n"
" <ol>\n"
" <li><a href=\"ch1.xhtml\">First Section</a></li>\n"
" </ol>\n"
" </nav>\n"
"</body>\n"
"</html>");
src->m_entries.insert(QStringLiteral("EPUB/ch1.xhtml"),
"<html xmlns=\"http://www.w3.org/1999/xhtml\"><body><p>Hello EPUB 3</p></body></html>");
auto sharedEntries = std::make_shared<QHash<QString, QByteArray>>(src->m_entries);
auto factory = [sharedEntries]() {
auto s = std::make_unique<InMemoryByteSource>();
s->m_entries = *sharedEntries;
return s;
};
EpubReader reader(factory, QStringLiteral("epub"));
QVERIFY(reader.open(QStringLiteral("/virtual/epub3.epub")));
QCOMPARE(reader.title(), QStringLiteral("EPUB 3 Sample"));
QCOMPARE(reader.coverImageUrl(), ImageUrl::build(QStringLiteral("epub"),
QStringLiteral("EPUB/cover.png"),
QStringLiteral("/virtual/epub3.epub")));
QVERIFY(!reader.chunks().isEmpty());
QVERIFY(reader.chunks().first().contains(QStringLiteral("Hello EPUB 3")));
}
};
QTEST_MAIN(EpubReaderTest)
#include "EpubReaderTest.moc"
+114
View File
@@ -0,0 +1,114 @@
#include <QtTest>
#include <QBuffer>
#include <QHash>
#include "backend/formats/WebImageProvider.h"
class MockWebStorage : public IWebImageStorage {
public:
bool contains(const QString &key) const override {
return m_store.contains(key);
}
QByteArray read(const QString &key) const override {
return m_store.value(key);
}
bool write(const QString &key, const QByteArray &data) override {
m_store.insert(key, data);
return true;
}
QHash<QString, QByteArray> m_store;
};
static QByteArray createSamplePng()
{
QImage img(100, 100, QImage::Format_RGB32);
img.fill(Qt::red);
QByteArray bytes;
QBuffer buf(&bytes);
buf.open(QIODevice::WriteOnly);
img.save(&buf, "PNG");
return bytes;
}
class WebImageProviderTest : public QObject {
Q_OBJECT
private slots:
void cacheKeyFormat()
{
QString k1 = WebImageProvider::cacheKey(QStringLiteral("https://example.com/photo.jpg"));
QVERIFY(k1.endsWith(QStringLiteral(".jpg")));
QString k2 = WebImageProvider::cacheKey(QStringLiteral("https://example.com/vector.svg"));
QVERIFY(k2.endsWith(QStringLiteral(".svg")));
QString k3 = WebImageProvider::cacheKey(QStringLiteral("https://example.com/noext"));
QVERIFY(!k3.contains(QLatin1Char('.')));
}
void fetchFromNetworkAndStore()
{
auto storage = std::make_shared<MockWebStorage>();
int fetchCount = 0;
const QByteArray sampleData = createSamplePng();
WebImageProvider::HttpFetcher fetcher = [&](const QString &url) -> QByteArray {
Q_UNUSED(url);
++fetchCount;
return sampleData;
};
WebImageProvider provider(storage, fetcher);
const QString url = QStringLiteral("https://example.com/test.png");
QImage img = provider.fetchImage(url);
QVERIFY(!img.isNull());
QCOMPARE(img.size(), QSize(100, 100));
QCOMPARE(fetchCount, 1);
QVERIFY(storage->contains(WebImageProvider::cacheKey(url)));
// Second fetch hits memory cache -> fetchCount remains 1
QImage img2 = provider.fetchImage(url);
QVERIFY(!img2.isNull());
QCOMPARE(fetchCount, 1);
}
void cacheHitFromStorageWithoutNetwork()
{
auto storage = std::make_shared<MockWebStorage>();
const QString url = QStringLiteral("https://example.com/cached.png");
const QString key = WebImageProvider::cacheKey(url);
storage->write(key, createSamplePng());
int fetchCount = 0;
WebImageProvider::HttpFetcher fetcher = [&](const QString &) -> QByteArray {
++fetchCount;
return {};
};
WebImageProvider provider(storage, fetcher);
QImage img = provider.fetchImage(url);
QVERIFY(!img.isNull());
QCOMPARE(fetchCount, 0); // never hit network!
}
void warmupReturnsNullImmediately()
{
int fetchCount = 0;
WebImageProvider::HttpFetcher fetcher = [&](const QString &) -> QByteArray {
++fetchCount;
return {};
};
WebImageProvider provider(std::make_shared<MockWebStorage>(), fetcher);
auto *resp = provider.requestImageResponse(QStringLiteral("__warmup__"), {});
QVERIFY(resp != nullptr);
QCOMPARE(fetchCount, 0);
delete resp;
}
};
QTEST_MAIN(WebImageProviderTest)
#include "WebImageProviderTest.moc"
+172
View File
@@ -0,0 +1,172 @@
#include <QtTest>
#include "backend/reading/BookImageResolver.h"
#include "backend/reading/layout/ChunkLayoutEngine.h"
class MockImageResolver : public IBookImageResolver {
public:
QImage resolveImage(const QString &url) override
{
if (url == QLatin1String("image://epub/fig1.png") || url == QLatin1String("image://web/https://example.com/pic.jpg")) {
QImage img(200, 100, QImage::Format_RGB32);
img.fill(Qt::blue);
return img;
}
return {};
}
QSizeF imageSize(const QString &url) override
{
if (url == QLatin1String("image://epub/fig1.png") || url == QLatin1String("image://web/https://example.com/pic.jpg")) {
return QSizeF(200, 100);
}
return {};
}
};
class ChunkLayoutEngineTest : public QObject {
Q_OBJECT
private slots:
void paragraphLayout()
{
const QString html = QStringLiteral("<p>This is a test paragraph with several words that will fit nicely.</p>");
LayoutParams params;
params.contentWidth = 400;
params.fontSize = 16;
params.lineSpacing = 1.2;
auto layout = ChunkLayoutEngine::layoutChunk(html, params);
QVERIFY(!layout.lines.isEmpty());
QVERIFY(layout.totalHeight > 0);
QVERIFY(layout.lines[0].runs.size() >= 1);
}
void headingsAndRules()
{
const QString html = QStringLiteral("<h1>Title</h1><hr/><p>Body text</p>");
LayoutParams params;
params.contentWidth = 400;
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutChunk(html, params);
QVERIFY(layout.lines.size() >= 2);
QCOMPARE(layout.rules.size(), 1);
QVERIFY(layout.totalHeight > 30);
}
void textAlignment()
{
const QString html = QStringLiteral("<p style=\"text-align: center\">Centered line</p>");
LayoutParams params;
params.contentWidth = 400;
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutChunk(html, params);
QVERIFY(!layout.lines.isEmpty());
const auto &run = layout.lines[0].runs.first();
// Since it's centered in 400px width, start x should be > 0
QVERIFY(run.rect.left() > 10.0);
}
void blockquoteDecoration()
{
const QString html = QStringLiteral("<blockquote><p>Quote text</p></blockquote>");
LayoutParams params;
params.contentWidth = 400;
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutChunk(html, params);
QVERIFY(!layout.decorations.isEmpty());
QVERIFY(layout.decorations[0].borderLeft > 0);
}
void imageBlockLayout()
{
MockImageResolver resolver;
const QString html = QStringLiteral("<p><img src=\"image://epub/fig1.png\" width=\"150\"/></p>");
LayoutParams params;
params.contentWidth = 400;
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutChunk(html, params, &resolver);
QCOMPARE(layout.images.size(), 1);
QCOMPARE(layout.images[0].url, QStringLiteral("image://epub/fig1.png"));
QCOMPARE(layout.images[0].targetRect.width(), 150.0);
QCOMPARE(layout.images[0].targetRect.height(), 75.0); // 200x100 aspect ratio -> 150x75
}
void imageWithWhitespaceAroundIt()
{
MockImageResolver resolver;
const QString html = QStringLiteral("<p>\n <img src=\"image://epub/fig1.png\" width=\"150\"/>\n</p>");
LayoutParams params;
params.contentWidth = 400;
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutChunk(html, params, &resolver);
QCOMPARE(layout.images.size(), 1);
QCOMPARE(layout.images[0].url, QStringLiteral("image://epub/fig1.png"));
QCOMPARE(layout.images[0].targetRect.width(), 150.0);
}
void svgImageElement()
{
MockImageResolver resolver;
const QString html = QStringLiteral("<svg width=\"200\" height=\"100\"><image xlink:href=\"image://epub/fig1.png\" width=\"150\"/></svg>");
LayoutParams params;
params.contentWidth = 400;
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutChunk(html, params, &resolver);
QCOMPARE(layout.images.size(), 1);
QCOMPARE(layout.images[0].url, QStringLiteral("image://epub/fig1.png"));
}
void inlineImageInParagraph()
{
MockImageResolver resolver;
const QString html = QStringLiteral("<p>Before <img src=\"image://epub/fig1.png\" width=\"40\" height=\"20\"/> after</p>");
LayoutParams params;
params.contentWidth = 400;
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutChunk(html, params, &resolver);
QCOMPARE(layout.images.size(), 1);
QCOMPARE(layout.images[0].url, QStringLiteral("image://epub/fig1.png"));
QVERIFY(!layout.lines.isEmpty());
}
void preparedChunkFastResize()
{
const QString html = QStringLiteral("<p>This is a long paragraph designed to be laid out at different widths to test rapid reflow.</p>");
auto prepared = ChunkLayoutEngine::prepareChunk(html, 16);
QVERIFY(!prepared.blocks.isEmpty());
LayoutParams p1;
p1.contentWidth = 300;
p1.fontSize = 16;
p1.lineSpacing = 1.0;
auto l1 = ChunkLayoutEngine::layoutPreparedChunk(prepared, p1);
LayoutParams p2;
p2.contentWidth = 600;
p2.fontSize = 16;
p2.lineSpacing = 1.0;
auto l2 = ChunkLayoutEngine::layoutPreparedChunk(prepared, p2);
QVERIFY(l1.lines.size() >= l2.lines.size());
QCOMPARE(l1.contentWidth, 300.0);
QCOMPARE(l2.contentWidth, 600.0);
}
};
QTEST_MAIN(ChunkLayoutEngineTest)
#include "ChunkLayoutEngineTest.moc"
+86
View File
@@ -0,0 +1,86 @@
#include <QtTest>
#include <QDomDocument>
#include "backend/reading/layout/CssParser.h"
class CssParserTest : public QObject {
Q_OBJECT
private slots:
void parseLengthUnits()
{
Css::LengthContext ctx;
ctx.em = 20.0;
ctx.rem = 16.0;
ctx.percentBase = 500.0;
ctx.absoluteScale = 1.0;
auto l1 = Css::parseLength(QStringLiteral("2em"), ctx);
QVERIFY(l1.has_value());
QCOMPARE(*l1, 40.0);
auto l2 = Css::parseLength(QStringLiteral("1.5rem"), ctx);
QVERIFY(l2.has_value());
QCOMPARE(*l2, 24.0);
auto l3 = Css::parseLength(QStringLiteral("50%"), ctx);
QVERIFY(l3.has_value());
QCOMPARE(*l3, 250.0);
auto l4 = Css::parseLength(QStringLiteral("10px"), ctx);
QVERIFY(l4.has_value());
QCOMPARE(*l4, 10.0);
auto l5 = Css::parseLength(QStringLiteral("0"), ctx);
QVERIFY(l5.has_value());
QCOMPARE(*l5, 0.0);
}
void parseColors()
{
QColor c1 = Css::parseColor(QStringLiteral("#ff0000"));
QCOMPARE(c1, QColor(255, 0, 0));
QColor c2 = Css::parseColor(QStringLiteral("rgb(0, 128, 255)"));
QCOMPARE(c2, QColor(0, 128, 255));
QColor c3 = Css::parseColor(QStringLiteral("rgba(0, 0, 0, 0.5)"));
QCOMPARE(c3.alpha(), 128); // 0.5 * 255 rounded = 128
QColor c4 = Css::parseColor(QStringLiteral("transparent"));
QCOMPARE(c4, QColor(Qt::transparent));
QColor c5 = Css::parseColor(QStringLiteral("red"));
QCOMPARE(c5, QColor(Qt::red));
}
void stylesheetParsingAndCascade()
{
const QString css = QStringLiteral(
"p { color: black; font-size: 16px; }\n"
".highlight { color: yellow; }\n"
"#special { color: red !important; }\n"
"div > p.highlight { font-weight: bold; }\n"
"@font-face { font-family: 'MyFont'; src: url('myfont.otf'); }\n"
);
auto sheet = Css::StyleSheet::parse(css);
QCOMPARE(sheet.fontFaces.size(), 1);
QCOMPARE(sheet.fontFaces[0].family, QStringLiteral("MyFont"));
QCOMPARE(sheet.fontFaces[0].src, QStringLiteral("myfont.otf"));
QDomDocument doc;
doc.setContent(QStringLiteral("<div><p id=\"special\" class=\"highlight\" style=\"color: green\">Hello</p></div>"));
QDomElement p = doc.elementsByTagName(QStringLiteral("p")).at(0).toElement();
auto decls = Css::cascade(sheet, p);
QString serialized = Css::serialize(decls);
// font-weight: bold should match div > p.highlight
QVERIFY(serialized.contains(QStringLiteral("font-weight:bold")));
// color: red should win because it is !important in #special, beating inline style="color: green"
QVERIFY(serialized.contains(QStringLiteral("color:red")));
}
};
QTEST_MAIN(CssParserTest)
#include "CssParserTest.moc"
+87
View File
@@ -0,0 +1,87 @@
#include <QtTest>
#include "backend/reading/layout/KnuthPlass.h"
class KnuthPlassTest : public QObject {
Q_OBJECT
private slots:
void emptyItemsReturnsEmpty()
{
QVector<KnuthPlass::Item> items;
auto lines = KnuthPlass::breakLines(items, 100);
QVERIFY(lines.isEmpty());
}
void singleLineParagraph()
{
// "Hello world"
// Box(30), Glue(10, 5, 3), Box(30), finishParagraph
QVector<KnuthPlass::Item> items;
items.append(KnuthPlass::Item::box(30, 0));
items.append(KnuthPlass::Item::glue(10, 5, 3, -1));
items.append(KnuthPlass::Item::box(30, 1));
KnuthPlass::finishParagraph(items);
auto lines = KnuthPlass::breakLines(items, 100);
QCOMPARE(lines.size(), 1);
QCOMPARE(lines[0].start, 0);
// The last line of a paragraph has infinite stretch in finishing glue -> ratio is 0
QCOMPARE(lines[0].ratio, 0.0);
QVERIFY(!lines[0].hyphenated);
}
void multiLineJustification()
{
// 4 words of width 40, glue width 10, stretch 5, shrink 3
// Line width 95 -> line 1: 2 words (40 + 10 + 40 = 90) + glue needs to stretch by 5 (ratio = 1.0)
QVector<KnuthPlass::Item> items;
items.append(KnuthPlass::Item::box(40, 0));
items.append(KnuthPlass::Item::glue(10, 5, 3, -1));
items.append(KnuthPlass::Item::box(40, 1));
items.append(KnuthPlass::Item::glue(10, 5, 3, -1));
items.append(KnuthPlass::Item::box(40, 2));
items.append(KnuthPlass::Item::glue(10, 5, 3, -1));
items.append(KnuthPlass::Item::box(40, 3));
KnuthPlass::finishParagraph(items);
auto lines = KnuthPlass::breakLines(items, 95);
QCOMPARE(lines.size(), 2);
QCOMPARE(lines[0].start, 0);
QCOMPARE(lines[0].ratio, 1.0); // 95 - 90 = 5 stretch, 5 / 5 = 1.0
QCOMPARE(lines[1].ratio, 0.0); // paragraph end line
}
void softHyphenBreak()
{
// Word 1 (width 50), Glue(10), Word 2 part A (30), soft-hyphen penalty (width 8, penalty 50, flagged), Word 2 part B (30)
// Line width 98: 50 + 10 + 30 + 8 = 98 -> exactly breaks at hyphen!
QVector<KnuthPlass::Item> items;
items.append(KnuthPlass::Item::box(50, 0));
items.append(KnuthPlass::Item::glue(10, 5, 3, -1));
items.append(KnuthPlass::Item::box(30, 1));
items.append(KnuthPlass::Item::penaltyItem(8, 50, true, -1));
items.append(KnuthPlass::Item::box(30, 2));
KnuthPlass::finishParagraph(items);
auto lines = KnuthPlass::breakLines(items, 98);
QCOMPARE(lines.size(), 2);
QVERIFY(lines[0].hyphenated);
QCOMPARE(lines[1].start, 4); // starts at Word 2 part B
}
void overlongLineRescue()
{
// A single box wider than target line width should not crash or return empty;
// it falls back to emergency pass.
QVector<KnuthPlass::Item> items;
items.append(KnuthPlass::Item::box(200, 0));
KnuthPlass::finishParagraph(items);
auto lines = KnuthPlass::breakLines(items, 100);
QCOMPARE(lines.size(), 1);
}
};
QTEST_MAIN(KnuthPlassTest)
#include "KnuthPlassTest.moc"
-3
View File
@@ -21,7 +21,6 @@ private slots:
BookPositionStore store(appState);
const BookPosition pos = store.load(QByteArray("nonexistent"));
QCOMPARE(pos.chapterIndex, 0);
QCOMPARE(pos.chunkIndex, 0);
QCOMPARE(pos.progress, 0.0);
QCOMPARE(pos.pageShift, true);
@@ -39,7 +38,6 @@ private slots:
const QByteArray hash = QByteArray("abc123deadbeef");
BookPosition toSave;
toSave.chapterIndex = 2;
toSave.chunkIndex = 7;
toSave.progress = 0.65;
toSave.mangaRTL = false;
@@ -47,7 +45,6 @@ private slots:
store.save(hash, toSave);
const BookPosition pos = store.load(hash);
QCOMPARE(pos.chapterIndex, 2);
QCOMPARE(pos.chunkIndex, 7);
QCOMPARE(pos.progress, 0.65);
QCOMPARE(pos.mangaRTL, false);