reintroduced epub support
This commit is contained in:
49 files changed
+5048
-205
No files matched your search
@@ -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
|
||||
@@ -23,7 +23,13 @@ HistoryModel::HistoryModel(FormatRegistry ®istry, 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,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
|
||||
+213
-59
@@ -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)
|
||||
return;
|
||||
|
||||
beginResetModel();
|
||||
m_currentChapter = index;
|
||||
m_currentChapterData = m_reader->loadChapter(index);
|
||||
m_totalPages = m_currentChapterData.chunks.size();
|
||||
m_currentPage = qMin(1, m_totalPages);
|
||||
endResetModel();
|
||||
|
||||
emit currentChapterChanged();
|
||||
emit totalPagesChanged();
|
||||
emit currentPageChanged();
|
||||
}
|
||||
|
||||
void ReadingModel::nextChapter()
|
||||
{
|
||||
if (m_isTextMode && m_currentChapter + 1 < m_chapterCount) {
|
||||
loadChapter(m_currentChapter + 1);
|
||||
saveCurrentPosition(0);
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
auto layouts = 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, 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;
|
||||
m_progress = pos.progress;
|
||||
m_pageShift = pos.pageShift;
|
||||
m_mangaRTL = pos.mangaRTL;
|
||||
restoreChunk = pos.chunkIndex;
|
||||
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_pageShift = true;
|
||||
m_mangaRTL = true;
|
||||
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
@@ -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;
|
||||
};
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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("&") + name + QLatin1Char(';');
|
||||
}
|
||||
i = j + 1;
|
||||
} else {
|
||||
out += QStringLiteral("&"); // bare ampersand
|
||||
++i;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace HtmlEntities
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
#include <QString>
|
||||
|
||||
namespace HtmlEntities {
|
||||
|
||||
// Rewrites HTML named character references (e.g. " ", "—") to
|
||||
// numeric references so the text parses as plain XML. The five XML entities
|
||||
// are kept; unknown names are escaped ("&foo;" -> "&foo;") so the parse
|
||||
// does not fail on them.
|
||||
QString toXmlSafe(const QString &html);
|
||||
|
||||
} // namespace HtmlEntities
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)
|
||||
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());
|
||||
|
||||
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 {};
|
||||
} 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;
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 ¶ms)
|
||||
: 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 ¶ms)
|
||||
{
|
||||
LayoutWorker worker(params);
|
||||
return worker.run(prepared);
|
||||
}
|
||||
|
||||
ChunkLayout layoutBlocks(const QVector<BlockItem> &blocks,
|
||||
const LayoutParams ¶ms,
|
||||
IBookImageResolver *imageResolver)
|
||||
{
|
||||
PreparedChunk prep = prepareBlocks(blocks, params.fontSize, imageResolver);
|
||||
return layoutPreparedChunk(prep, params);
|
||||
}
|
||||
|
||||
ChunkLayout layoutChunk(const QString &html,
|
||||
const LayoutParams ¶ms,
|
||||
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 ¶ms);
|
||||
|
||||
ChunkLayout layoutChunk(const QString &html,
|
||||
const LayoutParams ¶ms,
|
||||
IBookImageResolver *imageResolver = nullptr);
|
||||
|
||||
ChunkLayout layoutBlocks(const QVector<BlockItem> &blocks,
|
||||
const LayoutParams ¶ms,
|
||||
IBookImageResolver *imageResolver = nullptr);
|
||||
|
||||
} // namespace ChunkLayoutEngine
|
||||
|
||||
Q_DECLARE_METATYPE(ChunkLayout)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 ¶ms)
|
||||
{
|
||||
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 ¶ms) : 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 ¶ms)
|
||||
{
|
||||
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 ¶ms);
|
||||
|
||||
} // namespace HtmlBlockParser
|
||||
|
||||
@@ -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 ¶ms)
|
||||
: 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 ¶ms)
|
||||
{
|
||||
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
|
||||
|
||||
@@ -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 ¶ms = {});
|
||||
|
||||
} // namespace KnuthPlass
|
||||
|
||||
@@ -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},
|
||||
|
||||
@@ -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
@@ -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
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user