old render cleanup part 2

This commit is contained in:
Agel committed 2026-10-25 15:10:38 +01:00
1 parent acc7e71e7b
commit cef762c3ee
40 files changed
+329 -3643

No files matched your search

+6 -24
View File
@@ -2,35 +2,22 @@
#define FORMATREADER_H
#include <QByteArray>
#include <QString>
#include <QList>
#include <QSize>
#include <QString>
#include <QVector>
struct TocEntry {
QString title;
int chapterIndex;
int depth; // 0 = top level
};
struct Chapter {
int index;
QString title;
QStringList contentChunks;
struct PageInfo {
QString imageUrl;
QSize naturalSize;
};
class FormatReader {
public:
enum class RenderingMode { Scroll, Manga };
virtual ~FormatReader() = default;
virtual bool open(const QString &filePath) = 0;
virtual bool loadMetadata(const QString &filePath) = 0;
virtual QString lastError() = 0;
virtual int chapterCount() = 0;
virtual Chapter loadChapter(int index) = 0;
virtual QList<TocEntry> tableOfContents() = 0;
virtual QString filePath() = 0;
virtual QString title() = 0;
virtual QString author() = 0;
@@ -38,15 +25,10 @@ public:
// MD5 of file contents, computed once during open(). Used as a stable key for
// per-book state (bookmarks, etc.) that survives file renames.
virtual QByteArray contentHash() = 0;
// Returns the lowercase file extension this reader handles (e.g. "txt", "epub").
// Returns the lowercase file extension this reader handles (e.g. "cbz", "cbr").
virtual QString fileType() const = 0;
// Rendering mode this format prefers. Defaults to Scroll; image-only formats override to Manga.
virtual RenderingMode preferredRenderingMode() const { return RenderingMode::Scroll; }
// Natural pixel sizes for each chunk in a chapter, parallel to loadChapter().contentChunks.
// Empty by default; image-based readers override to provide aspect ratios for page pairing.
virtual QVector<QSize> chapterPageSizes(int chapterIndex) const { Q_UNUSED(chapterIndex); return {}; }
virtual QVector<PageInfo> pages() const = 0;
};
#endif // FORMATREADER_H
+22 -119
View File
@@ -1,6 +1,4 @@
#include "ReadingModel.h"
#include "FormatReader.h"
#include <QRegularExpression>
#include <algorithm>
ReadingModel::ReadingModel(BookPositionStore &positions, QObject *parent)
@@ -11,18 +9,7 @@ ReadingModel::ReadingModel(BookPositionStore &positions, QObject *parent)
ReadingModel::~ReadingModel() = default;
QString ReadingModel::chapterTitle() const
{
if (m_currentChapter < 0 || m_currentChapter >= m_chapterTitles.size())
return {};
return m_chapterTitles.at(m_currentChapter);
}
int ReadingModel::currentChapter() const { return m_currentChapter; }
int ReadingModel::totalChapters() const { return m_totalChapters; }
bool ReadingModel::hasChapters() const { return m_totalChapters > 1; }
int ReadingModel::totalPagePairs() const { return m_pagination.count(); }
bool ReadingModel::isMangaMode() const { return m_isMangaMode; }
bool ReadingModel::pageShift() const { return m_pageShift; }
bool ReadingModel::mangaRTL() const { return m_mangaRTL; }
@@ -38,19 +25,10 @@ void ReadingModel::setScrollInfo(const int topChunkIndex, const qreal proportion
{
m_yOffset = proportion;
// Derive current chapter
const auto it = std::upper_bound(m_chapterStartIndices.begin(), m_chapterStartIndices.end(), topChunkIndex);
if (const int chapter = std::max(0, static_cast<int>(std::distance(m_chapterStartIndices.begin(), it)) - 1); chapter != m_currentChapter) {
m_currentChapter = chapter;
emit chapterChanged();
}
if (m_isMangaMode) {
const int page = pairIndexForChunk(topChunkIndex) + 1;
if (m_currentPage != page) {
m_currentPage = page;
emit currentPageChanged();
}
const int page = pairIndexForChunk(topChunkIndex) + 1;
if (m_currentPage != page) {
m_currentPage = page;
emit currentPageChanged();
}
}
@@ -58,21 +36,24 @@ void ReadingModel::rebuildPagePairs()
{
const int oldPairs = m_pagination.count();
if (!m_isMangaMode || m_chunks.isEmpty()) {
if (m_pages.isEmpty()) {
m_pagination.clear();
if (m_pagination.count() != oldPairs) emit totalPagePairsChanged();
if (m_totalPages != 0) {
m_totalPages = 0;
emit totalPagesChanged();
}
return;
}
QVector<QSize> sizes;
sizes.reserve(m_chunks.size());
for (const auto &c : m_chunks)
sizes.append(c.naturalSize);
sizes.reserve(m_pages.size());
for (const auto &p : m_pages)
sizes.append(p.naturalSize);
m_pagination.rebuild(sizes, m_mangaLandscape, m_pageShift);
if (m_pagination.count() != oldPairs) emit totalPagePairsChanged();
// Sync totalPages/currentPage to pair count in manga mode.
if (const int pairs = m_pagination.count(); m_totalPages != pairs) {
m_totalPages = pairs;
emit totalPagesChanged();
@@ -101,41 +82,36 @@ int ReadingModel::pairIndexForChunk(int chunkIndex) const
QString ReadingModel::imageUrlForChunk(int chunkIndex) const
{
if (chunkIndex < 0 || chunkIndex >= m_chunks.size()) return {};
return m_chunks.at(chunkIndex).imageUrl;
if (chunkIndex < 0 || chunkIndex >= m_pages.size()) return {};
return m_pages.at(chunkIndex).imageUrl;
}
void ReadingModel::setMangaLandscape(bool landscape)
{
if (m_mangaLandscape == landscape) return;
m_mangaLandscape = landscape;
if (m_isMangaMode) rebuildPagePairs();
rebuildPagePairs();
}
void ReadingModel::setPageShift(bool shift, int currentPairIndex)
{
if (m_pageShift == shift) return;
// Anchor on a chunk that keeps an image on screen across the rebuild and
// keeps back-and-forth toggling stable (see MangaPagination for the rule).
const int currentChunk = m_pagination.anchorChunkForShiftToggle(currentPairIndex, shift);
m_pageShift = shift;
rebuildPagePairs();
// Re-locate the pair that contains the chunk we were on.
const int newPair = pairIndexForChunk(currentChunk);
if (m_currentPage != newPair + 1) {
m_currentPage = newPair + 1;
emit currentPageChanged();
}
// Persist immediately.
if (m_reader)
m_positions.save(m_reader->contentHash(), currentChunk, m_mangaRTL, m_pageShift);
emit pageShiftChanged();
// Tell MangaPageView the exact pair to jump to so it re-evaluates its display binding.
emit pagePairsRebuilt(newPair);
}
@@ -150,87 +126,35 @@ void ReadingModel::setMangaRTL(bool rtl)
emit mangaRTLChanged();
}
// Extract src="..." from a chunk's img tag, done once at load time.
static QString extractImageUrl(const QString &html)
void ReadingModel::loadPages()
{
static const QRegularExpression re(QStringLiteral("<img\\s[^>]*src=\"([^\"]+)\""));
const auto match = re.match(html);
return match.hasMatch() ? match.captured(1) : QString();
}
void ReadingModel::loadAllChapters()
{
m_chunks.clear();
m_chapterStartIndices.clear();
m_chapterTitles.clear();
m_currentChapter = 0;
m_pages.clear();
if (m_currentPage != 0) { m_currentPage = 0; emit currentPageChanged(); }
if (m_totalPages != 0) { m_totalPages = 0; emit totalPagesChanged(); }
if (m_reader) {
m_chapterStartIndices.append(0);
for (int i = 0; i < m_totalChapters; ++i) {
auto chapter = m_reader->loadChapter(i);
const QVector<QSize> sizes = m_reader->chapterPageSizes(i);
if (i > 0)
m_chapterStartIndices.append(m_chunks.size());
m_chapterTitles.append(chapter.title);
int j = 0;
for (const auto &html : chapter.contentChunks) {
const QSize sz = (j < sizes.size()) ? sizes[j] : QSize();
m_chunks.push_back({i, sz, extractImageUrl(html)});
++j;
}
}
m_pages = m_reader->pages();
}
if (m_isMangaMode) {
rebuildPagePairs();
} else {
if (m_totalPages != m_chunks.size()) {
m_totalPages = m_chunks.size();
emit totalPagesChanged();
}
if (const int page = m_chunks.isEmpty() ? 0 : 1; m_currentPage != page) {
m_currentPage = page;
emit currentPageChanged();
}
}
rebuildPagePairs();
}
void ReadingModel::setReader(FormatReader *reader)
{
m_reader = reader;
m_currentChapter = 0;
m_totalChapters = reader ? reader->chapterCount() : 0;
const bool wasManga = m_isMangaMode;
m_isMangaMode = reader && reader->preferredRenderingMode() == FormatReader::RenderingMode::Manga;
if (m_isMangaMode != wasManga)
emit isMangaModeChanged();
// Load per-book pageShift and mangaRTL before loadAllChapters so rebuildPagePairs uses the saved values.
int restoreChunk = 0;
if (reader) {
const auto pos = m_positions.load(reader->contentHash());
restoreChunk = pos.chunkIndex;
if (m_isMangaMode) {
m_pageShift = pos.pageShift;
m_mangaRTL = pos.mangaRTL;
} else {
m_pageShift = true;
m_mangaRTL = true;
}
m_pageShift = pos.pageShift;
m_mangaRTL = pos.mangaRTL;
} else {
m_pageShift = true;
m_mangaRTL = true;
}
loadAllChapters();
emit totalChaptersChanged();
emit chapterChanged();
loadPages();
if (m_reader) {
QMetaObject::invokeMethod(this, [this, restoreChunk] {
@@ -238,24 +162,3 @@ void ReadingModel::setReader(FormatReader *reader)
}, Qt::QueuedConnection);
}
}
void ReadingModel::nextChapter()
{
if (!m_reader || m_currentChapter >= m_totalChapters - 1)
return;
emit scrollToChunkRequested(m_chapterStartIndices.at(m_currentChapter + 1));
}
void ReadingModel::previousChapter()
{
if (!m_reader || m_currentChapter <= 0)
return;
emit scrollToChunkRequested(m_chapterStartIndices.at(m_currentChapter - 1));
}
void ReadingModel::goToChapter(int index)
{
if (!m_reader || index < 0 || index >= m_totalChapters)
return;
emit scrollToChunkRequested(m_chapterStartIndices.at(index));
}
+3 -34
View File
@@ -6,28 +6,16 @@
#include <QString>
#include <QVariantList>
#include <QVector>
#include "backend/FormatReader.h"
#include "reading/MangaPagination.h"
#include "state/BookPositionStore.h"
class FormatReader;
struct ContentChunk {
int chapterIndex = 0;
QSize naturalSize;
QString imageUrl;
};
class ReadingModel : public QObject {
Q_OBJECT
Q_PROPERTY(QString chapterTitle READ chapterTitle NOTIFY chapterChanged)
Q_PROPERTY(int currentChapter READ currentChapter NOTIFY chapterChanged)
Q_PROPERTY(int totalChapters READ totalChapters NOTIFY totalChaptersChanged)
Q_PROPERTY(double progress READ progress NOTIFY currentPageChanged)
Q_PROPERTY(int currentPage READ currentPage NOTIFY currentPageChanged)
Q_PROPERTY(int totalPages READ totalPages NOTIFY totalPagesChanged)
Q_PROPERTY(bool hasChapters READ hasChapters NOTIFY totalChaptersChanged)
Q_PROPERTY(int totalPagePairs READ totalPagePairs NOTIFY totalPagePairsChanged)
Q_PROPERTY(bool isMangaMode READ isMangaMode NOTIFY isMangaModeChanged)
Q_PROPERTY(bool pageShift READ pageShift NOTIFY pageShiftChanged)
Q_PROPERTY(bool mangaRTL READ mangaRTL NOTIFY mangaRTLChanged)
@@ -35,15 +23,10 @@ public:
explicit ReadingModel(BookPositionStore &positions, QObject *parent = nullptr);
~ReadingModel() override;
QString chapterTitle() const;
int currentChapter() const;
int totalChapters() const;
double progress() const;
int currentPage() const;
int totalPages() const;
bool hasChapters() const;
int totalPagePairs() const;
bool isMangaMode() const;
bool pageShift() const;
bool mangaRTL() const;
@@ -52,10 +35,6 @@ public:
// Called from QML on every page navigation
Q_INVOKABLE void setScrollInfo(int topChunkIndex, qreal proportion);
Q_INVOKABLE void nextChapter();
Q_INVOKABLE void previousChapter();
Q_INVOKABLE void goToChapter(int index);
// Manga page-pair API
Q_INVOKABLE QVariantList pagePair(int pairIndex) const;
Q_INVOKABLE int pairIndexForChunk(int chunkIndex) const;
@@ -70,38 +49,28 @@ public:
Q_INVOKABLE void setMangaRTL(bool rtl);
signals:
void chapterChanged();
void totalChaptersChanged();
void currentPageChanged();
void totalPagesChanged();
void totalPagePairsChanged();
void isMangaModeChanged();
void pageShiftChanged();
void mangaRTLChanged();
// Fired after setPageShift rebuilds pairs; carries the new pair index to display.
void pagePairsRebuilt(int newPairIndex);
void scrollToChunkRequested(int chunkIndex);
void restoreReady(int chunkIndex);
private:
void loadAllChapters();
void loadPages();
void rebuildPagePairs();
FormatReader *m_reader = nullptr;
int m_currentChapter = 0;
int m_totalChapters = 0;
int m_currentPage = 0;
int m_totalPages = 0;
bool m_isMangaMode = false;
bool m_mangaLandscape = false;
bool m_pageShift = true;
bool m_mangaRTL = true;
QVector<ContentChunk> m_chunks;
QVector<int> m_chapterStartIndices;
QVector<QString> m_chapterTitles;
QVector<PageInfo> m_pages;
MangaPagination m_pagination;
qreal m_yOffset = 0.0;
-5
View File
@@ -34,11 +34,6 @@ QString Book::title() const { return m_reader ? m_reader->title() : QString();
QString Book::author() const { return m_reader ? m_reader->author() : QString(); }
QString Book::filePath() const { return m_reader ? m_reader->filePath() : QString(); }
QList<TocEntry> Book::toc() const
{
return m_reader ? m_reader->tableOfContents() : QList<TocEntry>{};
}
FormatReader *Book::reader() const
{
return m_reader.get();
-2
View File
@@ -21,7 +21,6 @@ class Book : public QObject {
Q_PROPERTY(QString author READ author NOTIFY bookChanged)
Q_PROPERTY(QString filePath READ filePath NOTIFY bookChanged)
Q_PROPERTY(QString coverImageUrl READ coverImageUrl NOTIFY bookChanged)
Q_PROPERTY(QList<TocEntry> toc READ toc NOTIFY bookChanged)
Q_PROPERTY(QString errorMessage READ errorMessage NOTIFY errorMessageChanged)
public:
Book(IFileDialogService &dialog,
@@ -36,7 +35,6 @@ public:
QString author() const;
QString filePath() const;
QString coverImageUrl() const;
QList<TocEntry> toc() const;
QString errorMessage() const;
// Called by AppCoordinator::onBookChanged after the image provider resolves the cover URL.
-430
View File
@@ -1,430 +0,0 @@
#include "EpubReader.h"
#include <QCryptographicHash>
#include <QDir>
#include <QDomDocument>
#include <QFile>
#include <QFileInfo>
#include <QTextStream>
#include <QUrl>
#include <QXmlStreamReader>
#include "backend/ZipUtils.h"
using ZipUtils::readZipEntry;
// Serialize a QDomNode to a string (no XML declaration, no extra indentation).
static QString serializeNode(const QDomNode &node)
{
QString out;
QTextStream stream(&out);
node.save(stream, 0 /*indent*/);
return out;
}
// ---------------------------------------------------------------------------
// EpubReader::open
// ---------------------------------------------------------------------------
bool EpubReader::open(const QString &filePath)
{
// Reset state
m_title.clear();
m_author.clear();
m_error.clear();
m_opfDir.clear();
m_coverImagePath.clear();
m_spineHrefs.clear();
m_spineRawContent.clear();
m_toc.clear();
m_contentHash.clear();
// Compute content hash from raw file bytes before ZIP parsing
{
QFile f(filePath);
if (f.open(QIODevice::ReadOnly))
m_contentHash = QCryptographicHash::hash(f.readAll(), QCryptographicHash::Md5);
}
unzFile zf = unzOpen(filePath.toUtf8().constData());
if (!zf) {
m_error = QStringLiteral("Cannot open as ZIP archive: ") + filePath;
return false;
}
// Ensure the handle is closed on all exit paths
auto guard = [&](void *) { unzClose(zf); };
std::unique_ptr<void, decltype(guard)> closeGuard(zf, guard);
// 1. Parse META-INF/container.xml
QByteArray containerData = readZipEntry(zf, "META-INF/container.xml");
if (containerData.isEmpty()) {
m_error = QStringLiteral("Invalid EPUB: missing META-INF/container.xml");
return false;
}
QString opfPath;
if (!parseContainer(containerData, opfPath)) {
m_error = QStringLiteral("Invalid EPUB: cannot parse container.xml");
return false;
}
// 2. Determine OPF base directory
const int lastSlash = opfPath.lastIndexOf(QLatin1Char('/'));
m_opfDir = (lastSlash >= 0) ? opfPath.left(lastSlash + 1) : QString();
// 3. Parse OPF
QByteArray opfData = readZipEntry(zf, opfPath.toUtf8().constData());
if (opfData.isEmpty()) {
m_error = QStringLiteral("Invalid EPUB: cannot read OPF file: ") + opfPath;
return false;
}
QString ncxHref;
if (!parseOpf(opfData, ncxHref)) {
m_error = QStringLiteral("Invalid EPUB: cannot parse OPF file");
return false;
}
// 4. Read each spine item's raw XHTML
for (const QString &href : m_spineHrefs)
m_spineRawContent.append(readZipEntry(zf, href.toUtf8().constData()));
// 5. Parse NCX if available
if (!ncxHref.isEmpty()) {
QByteArray ncxData = readZipEntry(zf, ncxHref.toUtf8().constData());
if (!ncxData.isEmpty())
parseNcx(ncxData);
}
m_filePath = filePath;
return true;
}
// ---------------------------------------------------------------------------
// parseContainer: extract the OPF rootfile full-path
// ---------------------------------------------------------------------------
bool EpubReader::parseContainer(const QByteArray &data, QString &opfPath)
{
QXmlStreamReader xml(data);
while (!xml.atEnd()) {
xml.readNext();
if (xml.isStartElement() && xml.name() == QLatin1String("rootfile")) {
opfPath = xml.attributes().value(QLatin1String("full-path")).toString();
if (!opfPath.isEmpty())
return true;
}
}
return false;
}
// ---------------------------------------------------------------------------
// parseOpf: extract metadata, manifest, and spine
// ---------------------------------------------------------------------------
bool EpubReader::parseOpf(const QByteArray &data, QString &ncxHref)
{
QXmlStreamReader xml(data);
QHash<QString, QString> manifest; // id -> relative href
QString ncxId;
QString coverId; // ID of the cover image item
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) {
if (m_title.isEmpty())
m_title = xml.readElementText().trimmed();
} else if (name == QLatin1String("creator") && ns == kDcNs) {
if (m_author.isEmpty())
m_author = xml.readElementText().trimmed();
} else if (name == QLatin1String("meta")) {
// Check for cover image metadata
const QString metaName = xml.attributes().value(QLatin1String("name")).toString();
const QString metaContent = xml.attributes().value(QLatin1String("content")).toString();
if (metaName == QLatin1String("cover") && !metaContent.isEmpty()) {
coverId = metaContent;
}
} else if (name == QLatin1String("item")) {
const QString id = xml.attributes().value(QLatin1String("id")).toString();
const QString href = xml.attributes().value(QLatin1String("href")).toString();
const QString properties = xml.attributes().value(QLatin1String("properties")).toString();
if (!id.isEmpty() && !href.isEmpty())
manifest.insert(id, href);
// Check if this item is the cover image
if (properties.contains(QLatin1String("cover-image"))) {
coverId = id;
}
} else if (name == QLatin1String("spine")) {
ncxId = xml.attributes().value(QLatin1String("toc")).toString();
} else if (name == QLatin1String("itemref")) {
const QString idref = xml.attributes().value(QLatin1String("idref")).toString();
if (manifest.contains(idref))
m_spineHrefs.append(m_opfDir + manifest.value(idref));
}
}
// Resolve cover image path if we found a cover ID
if (!coverId.isEmpty() && manifest.contains(coverId)) {
m_coverImagePath = m_opfDir + manifest.value(coverId);
}
if (!ncxId.isEmpty() && manifest.contains(ncxId))
ncxHref = m_opfDir + manifest.value(ncxId);
return !xml.hasError();
}
// ---------------------------------------------------------------------------
// parseNcx: build TOC from navMap
// ---------------------------------------------------------------------------
void EpubReader::parseNcx(const QByteArray &data)
{
QXmlStreamReader xml(data);
int depth = 0;
QString currentLabel;
QString currentSrc;
bool insideNavLabel = false;
bool insideText = false;
// Map both full path and filename-only -> spine index
QHash<QString, int> hrefToIndex;
for (int i = 0; i < m_spineHrefs.size(); ++i) {
hrefToIndex.insert(m_spineHrefs[i], i);
hrefToIndex.insert(QFileInfo(m_spineHrefs[i]).fileName(), i);
}
while (!xml.atEnd()) {
xml.readNext();
if (xml.isStartElement()) {
const QStringView name = xml.name();
if (name == QLatin1String("navPoint")) {
++depth;
currentLabel.clear();
currentSrc.clear();
} else if (name == QLatin1String("navLabel")) {
insideNavLabel = true;
} else if (insideNavLabel && name == QLatin1String("text")) {
insideText = true;
} else if (name == QLatin1String("content")) {
QString src = xml.attributes().value(QLatin1String("src")).toString();
const int hashPos = src.indexOf(QLatin1Char('#'));
if (hashPos >= 0)
src = src.left(hashPos);
currentSrc = src;
}
} else if (xml.isCharacters() && insideText) {
currentLabel += xml.text();
} else if (xml.isEndElement()) {
const QStringView name = xml.name();
if (name == QLatin1String("text") && insideText) {
insideText = false;
} else if (name == QLatin1String("navLabel")) {
insideNavLabel = false;
} else if (name == QLatin1String("navPoint")) {
int chapterIdx = -1;
if (!currentSrc.isEmpty()) {
const QString fullHref = m_opfDir + currentSrc;
if (hrefToIndex.contains(fullHref))
chapterIdx = hrefToIndex.value(fullHref);
else if (hrefToIndex.contains(currentSrc))
chapterIdx = hrefToIndex.value(currentSrc);
}
if (chapterIdx >= 0 && !currentLabel.trimmed().isEmpty()) {
TocEntry entry;
entry.title = currentLabel.trimmed();
entry.chapterIndex = chapterIdx;
entry.depth = depth - 1;
m_toc.append(entry);
}
--depth;
currentLabel.clear();
currentSrc.clear();
}
}
}
}
// ---------------------------------------------------------------------------
// chunkXhtml: DOM-based chunking of a spine XHTML item
// ---------------------------------------------------------------------------
QStringList EpubReader::chunkXhtml(const QByteArray &data, const QString &xhtmlHref)
{
if (data.isEmpty())
return {};
QDomDocument doc;
const auto parseResult = doc.setContent(data, QDomDocument::ParseOption::Default);
if (!parseResult) {
// Malformed XHTML fallback: return raw as a single chunk
return {QString::fromUtf8(data)};
}
// Rewrite <img src="..."> to image://epub/ URLs so Qt can load them from the provider
const int slashPos = xhtmlHref.lastIndexOf(QLatin1Char('/'));
const QString xhtmlDir = (slashPos >= 0) ? xhtmlHref.left(slashPos + 1) : QString();
const QDomNodeList imgs = doc.elementsByTagName(QStringLiteral("img"));
for (int i = 0; i < imgs.size(); ++i) {
QDomElement img = imgs.at(i).toElement();
if (img.isNull())
continue;
QString src = img.attribute(QStringLiteral("src"));
if (src.isEmpty() || src.startsWith(QStringLiteral("image://")))
continue;
src = QUrl::fromPercentEncoding(src.toUtf8());
if (src.startsWith(QLatin1String("http://")) || src.startsWith(QLatin1String("https://"))) {
img.setAttribute(QStringLiteral("src"), QStringLiteral("image://web/") + src);
} else {
const QString resolved = QDir::cleanPath(xhtmlDir + src);
img.setAttribute(QStringLiteral("src"),
QStringLiteral("image://epub/") + resolved);
}
}
// Find <body> element (may have namespace prefix in some EPUBs)
QDomElement body;
const QDomNodeList bodies = doc.elementsByTagName(QStringLiteral("body"));
if (!bodies.isEmpty())
body = bodies.at(0).toElement();
if (body.isNull())
return {};
static constexpr int kChunkSize = 4096;
QStringList chunks;
QString current;
QDomNode node = body.firstChild();
while (!node.isNull()) {
QString serialized;
if (node.isElement()) {
serialized = serializeNode(node);
} else if (node.isText()) {
const QString text = node.nodeValue().trimmed();
if (!text.isEmpty())
serialized = QStringLiteral("<p>") + text.toHtmlEscaped() + QStringLiteral("</p>\n");
}
if (!serialized.isEmpty()) {
if (!current.isEmpty() && current.size() + serialized.size() > kChunkSize) {
chunks.append(current);
current.clear();
}
current += serialized;
}
node = node.nextSibling();
}
if (!current.isEmpty())
chunks.append(current);
return chunks;
}
// ---------------------------------------------------------------------------
// FormatReader interface
// ---------------------------------------------------------------------------
bool EpubReader::loadMetadata(const QString &filePath)
{
// Reset state
m_title.clear();
m_author.clear();
m_error.clear();
m_opfDir.clear();
m_coverImagePath.clear();
m_spineHrefs.clear();
unzFile zf = unzOpen(filePath.toUtf8().constData());
if (!zf) {
m_error = QStringLiteral("Cannot open as ZIP archive: ") + filePath;
return false;
}
// Ensure the handle is closed on all exit paths
auto guard = [&](void *) { unzClose(zf); };
std::unique_ptr<void, decltype(guard)> closeGuard(zf, guard);
// 1. Parse META-INF/container.xml
QByteArray containerData = readZipEntry(zf, "META-INF/container.xml");
if (containerData.isEmpty()) {
m_error = QStringLiteral("Invalid EPUB: missing META-INF/container.xml");
return false;
}
QString opfPath;
if (!parseContainer(containerData, opfPath)) {
m_error = QStringLiteral("Invalid EPUB: cannot parse container.xml");
return false;
}
// 2. Determine OPF base directory
const int lastSlash = opfPath.lastIndexOf(QLatin1Char('/'));
m_opfDir = (lastSlash >= 0) ? opfPath.left(lastSlash + 1) : QString();
// 3. Parse OPF (only metadata and manifest for cover image)
QByteArray opfData = readZipEntry(zf, opfPath.toUtf8().constData());
if (opfData.isEmpty()) {
m_error = QStringLiteral("Invalid EPUB: cannot read OPF file: ") + opfPath;
return false;
}
QString ncxHref;
if (!parseOpf(opfData, ncxHref)) {
m_error = QStringLiteral("Invalid EPUB: cannot parse OPF file");
return false;
}
return true;
}
QString EpubReader::lastError() { return m_error; }
QString EpubReader::title() { return m_title; }
QString EpubReader::author() { return m_author; }
QString EpubReader::coverImagePath() { return m_coverImagePath; }
int EpubReader::chapterCount() { return m_spineHrefs.size(); }
QList<TocEntry> EpubReader::tableOfContents() { return m_toc; }
QString EpubReader::filePath()
{
return m_filePath;
}
QByteArray EpubReader::contentHash()
{
return m_contentHash;
}
Chapter EpubReader::loadChapter(int index)
{
if (index < 0 || index >= m_spineRawContent.size())
return Chapter{index, {}, {}};
QString chTitle;
for (const TocEntry &e : m_toc) {
if (e.chapterIndex == index) {
chTitle = e.title;
break;
}
}
if (chTitle.isEmpty() && index < m_spineHrefs.size())
chTitle = QFileInfo(m_spineHrefs[index]).completeBaseName();
return Chapter{index, chTitle, chunkXhtml(m_spineRawContent[index], m_spineHrefs[index])};
}
QString EpubReader::fileType() const { return QStringLiteral("epub"); }
-42
View File
@@ -1,42 +0,0 @@
#ifndef EPUBREADER_H
#define EPUBREADER_H
#include "backend/FormatReader.h"
#include <QByteArray>
#include <QHash>
#include <QList>
class EpubReader : public FormatReader {
public:
bool open(const QString &filePath) override;
bool loadMetadata(const QString &filePath) override;
QString lastError() override;
int chapterCount() override;
Chapter loadChapter(int index) override;
QList<TocEntry> tableOfContents() override;
QString filePath() override;
QString title() override;
QString author() override;
QString coverImagePath() override;
QByteArray contentHash() override;
QString fileType() const override;
private:
QString m_filePath;
QByteArray m_contentHash;
QString m_title;
QString m_author;
QString m_error;
QString m_opfDir;
QString m_coverImagePath;
QStringList m_spineHrefs;
QList<QByteArray> m_spineRawContent;
QList<TocEntry> m_toc;
bool parseContainer(const QByteArray &data, QString &opfPath);
bool parseOpf(const QByteArray &data, QString &ncxHref);
void parseNcx(const QByteArray &data);
static QStringList chunkXhtml(const QByteArray &data, const QString &xhtmlHref);
};
#endif // EPUBREADER_H
-366
View File
@@ -1,366 +0,0 @@
#include "Fb2Reader.h"
#include "ImageUrl.h"
#include <QCryptographicHash>
#include <QDomDocument>
#include <QFileInfo>
#include <QStringConverter>
#include <QTextStream>
#include <QUrl>
#include <uchardet/uchardet.h>
#include <iconv.h>
#include <fstream>
static constexpr int kChunkSize = 4096;
static QString decodeWithIconv(const QByteArray &raw, const char *charset)
{
iconv_t cd = iconv_open("UTF-8", charset);
if (cd == reinterpret_cast<iconv_t>(-1))
return {};
QByteArray out(raw.size() * 4, '\0');
char *inBuf = const_cast<char *>(raw.constData());
size_t inLeft = raw.size();
char *outBuf = out.data();
size_t outLeft = out.size();
const size_t r = iconv(cd, &inBuf, &inLeft, &outBuf, &outLeft);
iconv_close(cd);
if (r == static_cast<size_t>(-1))
return {};
out.resize(out.size() - outLeft);
return QString::fromUtf8(out);
}
// Decode FB2 bytes to a Unicode string.
// Uses the XML encoding declaration as the authoritative charset source
// (uchardet is unreliable on files with large binary sections or sparse text).
// QStringConverter / iconv handle the actual conversion.
QString Fb2Reader::decodeRawBytes(const QByteArray &raw)
{
// Extract encoding name from XML declaration (first ~200 bytes)
QByteArray enc;
const int pos = raw.indexOf("encoding=");
if (pos >= 0 && pos < 200) {
const int qs = pos + 9;
if (qs < raw.size()) {
const char q = raw[qs];
if (q == '"' || q == '\'') {
const int qe = raw.indexOf(q, qs + 1);
if (qe > qs)
enc = raw.mid(qs + 1, qe - qs - 1).toLower();
}
}
}
if (enc.isEmpty() || enc == "utf-8" || enc == "utf8")
return QString::fromUtf8(raw);
// Try Qt's built-in converters first, fall back to iconv for exotic charsets
auto qtEncoding = QStringConverter::encodingForName(enc.constData());
if (qtEncoding) {
QTextStream stream(raw);
stream.setEncoding(qtEncoding.value());
const QString decoded = stream.readAll();
if (!decoded.isEmpty())
return decoded;
}
const QString decoded = decodeWithIconv(raw, enc.constData());
if (!decoded.isEmpty())
return decoded;
// Last resort: uchardet-based detection
uchardet_t ud = uchardet_new();
if (uchardet_handle_data(ud, raw.constData(), raw.size()) == 0) {
uchardet_data_end(ud);
const char *charset = uchardet_get_charset(ud);
if (charset && charset[0] != '\0') {
const QString s = decodeWithIconv(raw, charset);
uchardet_delete(ud);
if (!s.isEmpty())
return s;
}
}
uchardet_delete(ud);
return QString::fromUtf8(raw);
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
static QDomElement firstChildByTag(const QDomElement &parent, const QString &tag)
{
for (QDomNode n = parent.firstChild(); !n.isNull(); n = n.nextSibling()) {
QDomElement el = n.toElement();
if (!el.isNull() && el.tagName() == tag)
return el;
}
return {};
}
// Converts a single FB2 DOM node to an HTML string. Handles inline and block elements.
// fb2UrlSuffix is appended to image URLs, e.g. "?fb2=<encoded_path>" for self-contained loading.
static QString nodeToHtml(const QDomNode &node, const QString &fb2UrlSuffix = {})
{
if (node.isText())
return node.nodeValue().toHtmlEscaped();
if (!node.isElement())
return {};
const QDomElement el = node.toElement();
const QString tag = el.tagName();
// Build inner HTML from children
QString inner;
for (QDomNode child = el.firstChild(); !child.isNull(); child = child.nextSibling())
inner += nodeToHtml(child, fb2UrlSuffix);
if (tag == QLatin1String("p") || tag == QLatin1String("v")) {
if (inner.trimmed().isEmpty())
return {};
return QStringLiteral("<p>") + inner + QStringLiteral("</p>\n");
}
if (tag == QLatin1String("title"))
return inner.trimmed().isEmpty() ? QString{} : QStringLiteral("<h2>") + inner + QStringLiteral("</h2>\n");
if (tag == QLatin1String("subtitle"))
return inner.trimmed().isEmpty() ? QString{} : QStringLiteral("<h3>") + inner + QStringLiteral("</h3>\n");
if (tag == QLatin1String("emphasis"))
return QStringLiteral("<em>") + inner + QStringLiteral("</em>");
if (tag == QLatin1String("strong"))
return QStringLiteral("<strong>") + inner + QStringLiteral("</strong>");
if (tag == QLatin1String("epigraph") || tag == QLatin1String("poem") || tag == QLatin1String("cite"))
return inner.trimmed().isEmpty() ? QString{} : QStringLiteral("<blockquote>") + inner + QStringLiteral("</blockquote>\n");
if (tag == QLatin1String("section") || tag == QLatin1String("stanza"))
return inner;
if (tag == QLatin1String("image")) {
QString href = el.attribute(QStringLiteral("l:href"));
if (href.isEmpty())
href = el.attribute(QStringLiteral("xlink:href"));
if (href.startsWith(QLatin1Char('#')))
href = href.mid(1);
if (!href.isEmpty())
return QStringLiteral("<img src=\"image://fb2/") + href + fb2UrlSuffix + QStringLiteral("\"/>\n");
return {};
}
if (tag == QLatin1String("a")) {
const QString href = el.attribute(QStringLiteral("l:href"));
if (!href.isEmpty() && !href.startsWith(QLatin1Char('#')))
return QStringLiteral("<a href=\"") + href.toHtmlEscaped() + QStringLiteral("\">") + inner + QStringLiteral("</a>");
return inner;
}
return inner;
}
// ---------------------------------------------------------------------------
// Metadata parsing
// ---------------------------------------------------------------------------
struct Fb2Metadata {
QString title, author, coverBinaryId;
};
static Fb2Metadata parseDescription(const QDomElement &desc)
{
Fb2Metadata meta;
const QDomElement titleInfo = firstChildByTag(desc, QStringLiteral("title-info"));
if (titleInfo.isNull())
return meta;
const QDomElement bookTitle = firstChildByTag(titleInfo, QStringLiteral("book-title"));
if (!bookTitle.isNull())
meta.title = bookTitle.text().simplified();
const QDomElement author = firstChildByTag(titleInfo, QStringLiteral("author"));
if (!author.isNull()) {
const QString first = firstChildByTag(author, QStringLiteral("first-name")).text().simplified();
const QString last = firstChildByTag(author, QStringLiteral("last-name")).text().simplified();
if (!first.isEmpty() && !last.isEmpty())
meta.author = first + QLatin1Char(' ') + last;
else
meta.author = first + last;
}
const QDomElement coverpage = firstChildByTag(titleInfo, QStringLiteral("coverpage"));
if (!coverpage.isNull()) {
const QDomElement img = firstChildByTag(coverpage, QStringLiteral("image"));
if (!img.isNull()) {
QString href = img.attribute(QStringLiteral("l:href"));
if (href.isEmpty())
href = img.attribute(QStringLiteral("xlink:href"));
if (href.startsWith(QLatin1Char('#')))
href = href.mid(1);
meta.coverBinaryId = href;
}
}
return meta;
}
// ---------------------------------------------------------------------------
// FormatReader interface
// ---------------------------------------------------------------------------
bool Fb2Reader::open(const QString &filePath)
{
m_title.clear();
m_author.clear();
m_error.clear();
m_coverBinaryId.clear();
m_chapterHtmlNodes.clear();
m_chapterTitles.clear();
m_toc.clear();
m_contentHash.clear();
std::ifstream f(filePath.toUtf8().constData(), std::ios::binary | std::ios::ate);
if (!f) {
m_error = QStringLiteral("Cannot open file: ") + filePath;
return false;
}
const auto size = f.tellg();
f.seekg(0);
QByteArray raw(static_cast<int>(size), '\0');
f.read(raw.data(), size);
m_contentHash = QCryptographicHash::hash(raw, QCryptographicHash::Md5);
QDomDocument doc;
const auto result = doc.setContent(decodeRawBytes(raw), QDomDocument::ParseOption::Default);
if (!result) {
m_error = QStringLiteral("Failed to parse FB2 XML: ") + result.errorMessage;
return false;
}
const QDomElement root = doc.documentElement();
// Metadata
const QDomElement desc = firstChildByTag(root, QStringLiteral("description"));
if (!desc.isNull()) {
const Fb2Metadata meta = parseDescription(desc);
m_title = meta.title;
m_author = meta.author;
m_coverBinaryId = meta.coverBinaryId;
}
if (m_title.isEmpty())
m_title = QFileInfo(filePath).completeBaseName();
// Pre-compute URL suffix so body image URLs embed the file path (self-contained, encoding-safe).
const QString urlSuffix = ImageUrl::querySuffix(filePath);
// Body sections
for (QDomNode bodyNode = root.firstChild(); !bodyNode.isNull(); bodyNode = bodyNode.nextSibling()) {
const QDomElement body = bodyNode.toElement();
if (body.isNull() || body.tagName() != QLatin1String("body"))
continue;
// Skip named bodies (e.g. notes)
if (!body.attribute(QStringLiteral("name")).isEmpty())
continue;
for (QDomNode secNode = body.firstChild(); !secNode.isNull(); secNode = secNode.nextSibling()) {
const QDomElement section = secNode.toElement();
if (section.isNull() || section.tagName() != QLatin1String("section"))
continue;
// Extract section title
const QDomElement titleEl = firstChildByTag(section, QStringLiteral("title"));
QString sectionTitle = titleEl.isNull() ? QString{} : titleEl.text().simplified();
if (sectionTitle.isEmpty())
sectionTitle = QStringLiteral("Chapter %1").arg(m_chapterHtmlNodes.size() + 1);
m_chapterTitles.append(sectionTitle);
// Convert section children to HTML node list
QStringList htmlNodes;
for (QDomNode child = section.firstChild(); !child.isNull(); child = child.nextSibling()) {
const QString html = nodeToHtml(child, urlSuffix);
if (!html.isEmpty())
htmlNodes.append(html);
}
m_chapterHtmlNodes.append(htmlNodes);
TocEntry entry;
entry.title = sectionTitle;
entry.chapterIndex = m_chapterHtmlNodes.size() - 1;
entry.depth = 0;
m_toc.append(entry);
}
break; // only process first unnamed body
}
m_filePath = filePath;
return true;
}
bool Fb2Reader::loadMetadata(const QString &filePath)
{
m_title.clear();
m_author.clear();
m_error.clear();
m_coverBinaryId.clear();
std::ifstream f(filePath.toUtf8().constData(), std::ios::binary | std::ios::ate);
if (!f) {
m_error = QStringLiteral("Cannot open file: ") + filePath;
return false;
}
const auto size = f.tellg();
f.seekg(0);
QByteArray raw(static_cast<int>(size), '\0');
f.read(raw.data(), size);
QDomDocument doc;
const auto result = doc.setContent(decodeRawBytes(raw), QDomDocument::ParseOption::Default);
if (!result) {
m_error = QStringLiteral("Failed to parse FB2 XML: ") + result.errorMessage;
return false;
}
const QDomElement root = doc.documentElement();
const QDomElement desc = firstChildByTag(root, QStringLiteral("description"));
if (!desc.isNull()) {
const Fb2Metadata meta = parseDescription(desc);
m_title = meta.title;
m_author = meta.author;
m_coverBinaryId = meta.coverBinaryId;
}
if (m_title.isEmpty())
m_title = QFileInfo(filePath).completeBaseName();
return true;
}
QString Fb2Reader::lastError() { return m_error; }
QString Fb2Reader::title() { return m_title; }
QString Fb2Reader::author() { return m_author; }
QString Fb2Reader::coverImagePath() { return m_coverBinaryId; }
int Fb2Reader::chapterCount() { return m_chapterHtmlNodes.size(); }
QList<TocEntry> Fb2Reader::tableOfContents() { return m_toc; }
QString Fb2Reader::filePath() { return m_filePath; }
QByteArray Fb2Reader::contentHash() { return m_contentHash; }
QString Fb2Reader::fileType() const { return QStringLiteral("fb2"); }
Chapter Fb2Reader::loadChapter(int index)
{
if (index < 0 || index >= m_chapterHtmlNodes.size())
return Chapter{index, {}, {}};
const QStringList &nodes = m_chapterHtmlNodes[index];
QStringList chunks;
QString current;
for (const QString &node : nodes) {
if (!current.isEmpty() && current.size() + node.size() > kChunkSize) {
chunks.append(current);
current.clear();
}
current += node;
}
if (!current.isEmpty())
chunks.append(current);
return Chapter{index, m_chapterTitles[index], chunks};
}
-37
View File
@@ -1,37 +0,0 @@
#ifndef FB2READER_H
#define FB2READER_H
#include "backend/FormatReader.h"
#include <QByteArray>
#include <QList>
class Fb2Reader : public FormatReader {
public:
static QString decodeRawBytes(const QByteArray &raw);
bool open(const QString &filePath) override;
bool loadMetadata(const QString &filePath) override;
QString lastError() override;
int chapterCount() override;
Chapter loadChapter(int index) override;
QList<TocEntry> tableOfContents() override;
QString filePath() override;
QString title() override;
QString author() override;
QString coverImagePath() override;
QByteArray contentHash() override;
QString fileType() const override;
private:
QString m_filePath;
QByteArray m_contentHash;
QString m_title;
QString m_author;
QString m_error;
QString m_coverBinaryId;
QList<QStringList> m_chapterHtmlNodes;
QStringList m_chapterTitles;
QList<TocEntry> m_toc;
};
#endif // FB2READER_H
-1
View File
@@ -1,7 +1,6 @@
#include "FormatRegistry.h"
#include "EntryImageProvider.h"
#include "WebImageProvider.h"
#include "backend/FormatReader.h"
#include <QFileInfo>
+7 -22
View File
@@ -2,9 +2,16 @@
#include <QLatin1Char>
#include <QLatin1String>
#include <QUrl>
namespace {
const QLatin1String kSrcKey("src=");
QString querySuffix(const QString &sourcePath)
{
return QStringLiteral("?src=")
+ QString::fromUtf8(QUrl::toPercentEncoding(sourcePath));
}
}
namespace ImageUrl {
@@ -19,12 +26,6 @@ QString build(const QString &scheme, const QString &entry, const QString &source
return build(scheme, entry) + querySuffix(sourcePath);
}
QString querySuffix(const QString &sourcePath)
{
return QStringLiteral("?src=")
+ QString::fromUtf8(QUrl::toPercentEncoding(sourcePath));
}
Parsed parseProviderId(const QString &id)
{
Parsed result;
@@ -41,20 +42,4 @@ Parsed parseProviderId(const QString &id)
return result;
}
Parsed parseImageUrl(const QUrl &url)
{
Parsed result;
result.entry = url.path();
if (result.entry.startsWith(QLatin1Char('/')))
result.entry = result.entry.mid(1);
if (url.hasQuery()) {
const QString query = url.query();
if (query.startsWith(kSrcKey))
result.sourcePath = QUrl::fromPercentEncoding(query.mid(kSrcKey.size()).toUtf8());
}
return result;
}
} // namespace ImageUrl
-7
View File
@@ -1,7 +1,6 @@
#pragma once
#include <QString>
#include <QUrl>
// Single authority for the image-provider URL grammar:
// image://<scheme>/<entry>[?src=<percent-encoded-source-path>]
@@ -12,9 +11,6 @@ namespace ImageUrl {
QString build(const QString &scheme, const QString &entry);
QString build(const QString &scheme, const QString &entry, const QString &sourcePath);
// "?src=<percent-encoded-source-path>" — for appending to an existing URL.
QString querySuffix(const QString &sourcePath);
struct Parsed {
QString entry;
QString sourcePath; // empty = use the provider's current file
@@ -24,7 +20,4 @@ struct Parsed {
// entry arrives percent-encoded).
Parsed parseProviderId(const QString &id);
// Parse a full image:// URL (IImageLoader::load path).
Parsed parseImageUrl(const QUrl &url);
} // namespace ImageUrl
-218
View File
@@ -1,218 +0,0 @@
#include "TxtReader.h"
#include <QCryptographicHash>
#include <QFileInfo>
#include <QRegularExpression>
#include <QTextStream>
#include <uchardet/uchardet.h>
#include <iconv.h>
#include <fstream>
static constexpr int kChunkSize = 4096;
static QString decodeWithIconv(const QByteArray &raw, const char *charset)
{
iconv_t cd = iconv_open("UTF-8", charset);
if (cd == reinterpret_cast<iconv_t>(-1))
return {};
// Worst case: each byte becomes 4 UTF-8 bytes
QByteArray out(raw.size() * 4, '\0');
char *inBuf = const_cast<char *>(raw.constData());
size_t inLeft = raw.size();
char *outBuf = out.data();
size_t outLeft = out.size();
size_t result = iconv(cd, &inBuf, &inLeft, &outBuf, &outLeft);
iconv_close(cd);
if (result == static_cast<size_t>(-1))
return {};
out.resize(out.size() - outLeft);
return QString::fromUtf8(out);
}
// Convert a raw text fragment into HTML paragraphs.
// Splits on blank lines (\n\n+) to create <p> blocks;
// single newlines within a block become <br>.
static QString textToHtml(const QString &text)
{
QString html;
const QStringList blocks = text.split(QRegularExpression("\\n\\n+"));
for (const QString &block : blocks) {
QString escaped = block.toHtmlEscaped().trimmed();
if (escaped.isEmpty())
continue;
escaped.replace('\n', QStringLiteral("<br>\n"));
html += QStringLiteral("<p>") + escaped + QStringLiteral("</p>\n");
}
return html;
}
// Split raw text into chunks of approximately kChunkSize characters,
// preferring to split at \n boundaries, falling back to whitespace.
static QStringList splitRawText(const QString &content)
{
QStringList rawChunks;
int pos = 0;
const int len = content.size();
while (pos < len) {
if (len - pos <= kChunkSize) {
rawChunks.append(content.mid(pos));
break;
}
int end = pos + kChunkSize;
// Look backward for a newline to split at
int splitAt = -1;
for (int i = end; i > pos; --i) {
if (content.at(i) == '\n') {
splitAt = i + 1; // include the newline in the current chunk
break;
}
}
// No newline found — fall back to whitespace
if (splitAt < 0) {
for (int i = end; i > pos; --i) {
if (content.at(i).isSpace()) {
splitAt = i + 1;
break;
}
}
}
// No whitespace either — hard split
if (splitAt < 0)
splitAt = end;
rawChunks.append(content.mid(pos, splitAt - pos));
pos = splitAt;
}
return rawChunks;
}
bool TxtReader::open(const QString &filePath)
{
// Use std::ifstream to bypass Qt's CFStringGetFileSystemRepresentation() on macOS,
// which re-normalizes paths to NFD and breaks NFC filenames on SMB/ZFS mounts.
std::ifstream f(filePath.toUtf8().constData(), std::ios::binary | std::ios::ate);
if (!f) {
m_error = QStringLiteral("Cannot open file: ") + filePath;
return false;
}
const auto size = f.tellg();
f.seekg(0);
QByteArray raw(static_cast<int>(size), '\0');
f.read(raw.data(), size);
m_contentHash = QCryptographicHash::hash(raw, QCryptographicHash::Md5);
uchardet_t ud = uchardet_new();
if (uchardet_handle_data(ud, raw.constData(), raw.size()) == 0) {
uchardet_data_end(ud);
const char *charset = uchardet_get_charset(ud);
if (charset && charset[0] != '\0') {
auto qtEncoding = QStringConverter::encodingForName(charset);
if (qtEncoding) {
QTextStream stream(raw);
stream.setEncoding(qtEncoding.value());
m_content = stream.readAll();
} else {
m_content = decodeWithIconv(raw, charset);
}
uchardet_delete(ud);
if (!m_content.isEmpty()) {
m_title = QFileInfo(filePath).completeBaseName();
m_filePath = filePath;
return true;
}
}
}
uchardet_delete(ud);
// Default: UTF-8
m_content = QString::fromUtf8(raw);
m_title = QFileInfo(filePath).completeBaseName();
m_filePath = filePath;
return true;
}
bool TxtReader::loadMetadata(const QString &filePath)
{
if (!std::ifstream(filePath.toUtf8().constData())) {
m_error = QStringLiteral("File not found: ") + filePath;
return false;
}
// For TXT files, we only need the filename for title
m_title = QFileInfo(filePath).completeBaseName();
m_author.clear(); // No author info in plain text files
return true;
}
QString TxtReader::lastError()
{
return m_error;
}
int TxtReader::chapterCount()
{
return m_content.isEmpty() ? 0 : 1;
}
Chapter TxtReader::loadChapter(int index)
{
if (index != 0 || m_content.isEmpty())
return Chapter{index, {}, {}};
QStringList rawChunks = splitRawText(m_content);
QStringList htmlChunks;
htmlChunks.reserve(rawChunks.size());
for (const QString &raw : rawChunks) {
QString html = textToHtml(raw);
if (!html.isEmpty())
htmlChunks.append(html);
}
return Chapter{0, m_title, htmlChunks};
}
QList<TocEntry> TxtReader::tableOfContents()
{
return {};
}
QString TxtReader::filePath()
{
return m_filePath;
}
QString TxtReader::title()
{
return m_title;
}
QString TxtReader::author()
{
return {};
}
QString TxtReader::coverImagePath()
{
return {};
}
QByteArray TxtReader::contentHash()
{
return m_contentHash;
}
QString TxtReader::fileType() const { return QStringLiteral("txt"); }
-30
View File
@@ -1,30 +0,0 @@
#ifndef TXTREADER_H
#define TXTREADER_H
#include "backend/FormatReader.h"
class TxtReader : public FormatReader {
public:
bool open(const QString &filePath) override;
bool loadMetadata(const QString &filePath) override;
QString lastError() override;
int chapterCount() override;
Chapter loadChapter(int index) override;
QList<TocEntry> tableOfContents() override;
QString filePath() override;
QString title() override;
QString author() override;
QString coverImagePath() override;
QByteArray contentHash() override;
QString fileType() const override;
private:
QString m_content;
QString m_filePath;
QString m_title;
QString m_author;
QString m_error;
QByteArray m_contentHash;
};
#endif // TXTREADER_H
-122
View File
@@ -1,122 +0,0 @@
#include "WebImageProvider.h"
#include <QCryptographicHash>
#include <QDir>
#include <QEventLoop>
#include <QFile>
#include <QFileInfo>
#include <QImage>
#include <QMutexLocker>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QStandardPaths>
#include <QThreadPool>
#include "AsyncImageResponse.h"
#include "ImageScaling.h"
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
QString WebImageProvider::cacheDir()
{
return QStandardPaths::writableLocation(QStandardPaths::CacheLocation)
+ QStringLiteral("/web-images");
}
QString WebImageProvider::cacheFilePath(const QString &urlString)
{
const QByteArray hash =
QCryptographicHash::hash(urlString.toUtf8(), QCryptographicHash::Sha256).toHex();
const QString ext = QFileInfo(QUrl(urlString).path()).suffix();
return cacheDir() + QLatin1Char('/') + QString::fromLatin1(hash)
+ (ext.isEmpty() ? QString() : QLatin1Char('.') + ext);
}
// ---------------------------------------------------------------------------
// WebImageProvider
// ---------------------------------------------------------------------------
QImage WebImageProvider::loadWebImage(const QString &urlString,
const QSize &requestedSize)
{
if (urlString.isEmpty())
return {};
// Check cache first
const QString cachePath = cacheFilePath(urlString);
if (QFile::exists(cachePath)) {
QImage image;
if (image.load(cachePath))
return scaleToFit(image, requestedSize);
}
// Download — blocking, safe to call from any thread via a local event loop
QNetworkAccessManager nam;
QNetworkRequest request{QUrl(urlString)};
request.setHeader(QNetworkRequest::UserAgentHeader, QStringLiteral("Asteria/1.0"));
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
QNetworkRequest::NoLessSafeRedirectPolicy);
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();
if (data.isEmpty())
return {};
// Persist to cache
QDir().mkpath(cacheDir());
QFile f(cachePath);
if (f.open(QIODevice::WriteOnly)) {
f.write(data);
f.close();
}
QImage image;
if (!image.loadFromData(data))
return {};
return scaleToFit(image, requestedSize);
}
// ---------------------------------------------------------------------------
// WebImageProvider — IImageProvider
// ---------------------------------------------------------------------------
QQuickImageResponse *WebImageProvider::requestImageResponse(const QString &id,
const QSize &requestedSize)
{
// Warmup request: pre-creates QQuickPixmapReader on the main thread at
// startup so the render thread never creates it first (which would trigger
// a "Cannot create children for a parent in a different thread" warning).
// Return an empty response immediately — no network request needed.
if (id == QLatin1String("__warmup__")) {
auto *response = new AsyncImageResponse([] { return QImage(); });
QMetaObject::invokeMethod(response, "finished", Qt::QueuedConnection);
return response;
}
auto *response = new AsyncImageResponse([id, requestedSize] {
return loadWebImage(id, requestedSize);
});
QThreadPool::globalInstance()->start(response);
return response;
}
QString WebImageProvider::scheme() const
{
return QStringLiteral("web");
}
-24
View File
@@ -1,24 +0,0 @@
#pragma once
#include <QSize>
#include <QString>
#include "backend/IImageProvider.h"
class WebImageProvider : public IImageProvider {
public:
QQuickImageResponse *requestImageResponse(const QString &id,
const QSize &requestedSize) override;
void setFilePath(const QString &) override {}
void clear() override {}
QString coverImageUrl(const QString &) const override { return {}; }
QString scheme() const override;
// Download (or load from disk cache) a web image. Thread-safe, may block.
static QImage loadWebImage(const QString &urlString,
const QSize &requestedSize);
static QString cacheDir();
static QString cacheFilePath(const QString &urlString);
};
+5 -24
View File
@@ -164,39 +164,20 @@ bool ComicReader::loadMetadata(const QString &filePath)
return parseSource(filePath);
}
Chapter ComicReader::loadChapter(int index)
QVector<PageInfo> ComicReader::pages() const
{
if (index != 0 || m_pageEntries.isEmpty())
return Chapter{index, {}, {}};
QStringList chunks;
chunks.reserve(m_pageEntries.size());
QVector<PageInfo> result;
result.reserve(m_pageEntries.size());
for (const PageEntry &page : m_pageEntries) {
chunks.append(QStringLiteral("<p style=\"text-align:center;margin:0\">"
"<img src=\"%1\"/></p>")
.arg(ImageUrl::build(m_scheme, page.entry)));
result.append({ImageUrl::build(m_scheme, page.entry), page.naturalSize});
}
return Chapter{0, m_title, chunks};
}
QVector<QSize> ComicReader::chapterPageSizes(int chapterIndex) const
{
if (chapterIndex != 0 || m_pageEntries.isEmpty())
return {};
QVector<QSize> sizes;
sizes.reserve(m_pageEntries.size());
for (const PageEntry &page : m_pageEntries)
sizes.append(page.naturalSize);
return sizes;
return result;
}
QString ComicReader::lastError() { return m_error; }
QString ComicReader::title() { return m_title; }
QString ComicReader::author() { return m_author; }
QString ComicReader::coverImagePath() { return m_coverEntry; }
int ComicReader::chapterCount() { return m_pageEntries.isEmpty() ? 0 : 1; }
QString ComicReader::filePath() { return m_filePath; }
QByteArray ComicReader::contentHash() { return m_contentHash; }
QString ComicReader::fileType() const { return m_fileType; }
QList<TocEntry> ComicReader::tableOfContents() { return {}; }
+2 -7
View File
@@ -6,9 +6,8 @@
#include <functional>
#include <memory>
#include <QByteArray>
#include <QList>
#include <QSize>
#include <QStringList>
#include <QString>
#include <QVector>
class ComicReader : public FormatReader {
@@ -20,9 +19,6 @@ public:
bool open(const QString &filePath) override;
bool loadMetadata(const QString &filePath) override;
QString lastError() override;
int chapterCount() override;
Chapter loadChapter(int index) override;
QList<TocEntry> tableOfContents() override;
QString filePath() override;
QString title() override;
QString author() override;
@@ -30,8 +26,7 @@ public:
QByteArray contentHash() override;
QString fileType() const override;
RenderingMode preferredRenderingMode() const override { return RenderingMode::Manga; }
QVector<QSize> chapterPageSizes(int chapterIndex) const override;
QVector<PageInfo> pages() const override;
private:
struct PageEntry {
@@ -1,88 +0,0 @@
#include "Fb2ByteSource.h"
#include "backend/formats/Fb2Reader.h"
#include <QCryptographicHash>
#include <QFile>
#include <QFileInfo>
#include <QXmlStreamReader>
bool Fb2ByteSource::open(const QString &path)
{
m_path.clear();
m_hash.clear();
if (!QFileInfo::exists(path))
return false;
m_path = path;
return true;
}
QByteArray Fb2ByteSource::rawBytes() const
{
if (m_path.isEmpty())
return {};
QFile f(m_path);
if (!f.open(QIODevice::ReadOnly))
return {};
return f.readAll();
}
QStringList Fb2ByteSource::listEntries() const
{
const QByteArray raw = rawBytes();
if (raw.isEmpty())
return {};
QStringList ids;
// Decode first so parsing works for encodings Qt 6 does not natively
// detect (e.g. Windows-1251); see Fb2Reader::decodeRawBytes.
QXmlStreamReader xml(Fb2Reader::decodeRawBytes(raw));
while (!xml.atEnd()) {
xml.readNext();
if (xml.isStartElement() && xml.name() == QLatin1String("binary"))
ids.append(xml.attributes().value(QLatin1String("id")).toString());
}
return ids;
}
QByteArray Fb2ByteSource::readEntry(const QString &binaryId) const
{
if (binaryId.isEmpty())
return {};
const QByteArray raw = rawBytes();
if (raw.isEmpty())
return {};
QXmlStreamReader xml(Fb2Reader::decodeRawBytes(raw));
while (!xml.atEnd()) {
xml.readNext();
if (!xml.isStartElement() || xml.name() != QLatin1String("binary"))
continue;
if (xml.attributes().value(QLatin1String("id")) != binaryId)
continue;
// Accumulate text (base64 data may span multiple character events)
QString base64;
while (!xml.atEnd()) {
xml.readNext();
if (xml.isCharacters())
base64 += xml.text();
else
break;
}
return QByteArray::fromBase64(base64.toLatin1());
}
return {};
}
QByteArray Fb2ByteSource::contentHash() const
{
if (m_hash.isEmpty() && !m_path.isEmpty()) {
const QByteArray raw = rawBytes();
if (!raw.isEmpty())
m_hash = QCryptographicHash::hash(raw, QCryptographicHash::Md5);
}
return m_hash;
}
@@ -1,20 +0,0 @@
#pragma once
#include "backend/formats/IByteSource.h"
// Byte source over an FB2 document: entries are the ids of its base64
// <binary> elements. Parsing is deferred to the calls that need it so that
// open() stays cheap for per-request provider use.
class Fb2ByteSource : public IByteSource {
public:
bool open(const QString &path) override;
QStringList listEntries() const override;
QByteArray readEntry(const QString &binaryId) const override;
QByteArray contentHash() const override;
private:
QByteArray rawBytes() const;
QString m_path;
mutable QByteArray m_hash;
};
-14
View File
@@ -13,18 +13,13 @@
#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/Fb2ByteSource.h"
#include "backend/formats/sources/RarByteSource.h"
#include "backend/formats/sources/ZipByteSource.h"
#include "backend/HistoryModel.h"
#include "backend/ReadingModel.h"
#include "backend/NativeFileDialogService.h"
#include "backend/book/Book.h"
#include "backend/formats/TxtReader.h"
#include "backend/formats/EpubReader.h"
#include "backend/formats/Fb2Reader.h"
#include "backend/formats/comic/CbzReader.h"
#include "backend/formats/comic/CbrReader.h"
#include "backend/formats/comic/FolderReader.h"
@@ -107,14 +102,6 @@ int main(int argc, char *argv[])
// The format table: one row declares everything a format needs.
FormatRegistry formatRegistry({
{QStringLiteral("txt"), false, {},
[] { return std::make_unique<TxtReader>(); }, nullptr},
{QStringLiteral("epub"), false, QStringLiteral("epub"),
[] { return std::make_unique<EpubReader>(); },
[] { return std::make_unique<ZipByteSource>(); }},
{QStringLiteral("fb2"), false, QStringLiteral("fb2"),
[] { return std::make_unique<Fb2Reader>(); },
[] { return std::make_unique<Fb2ByteSource>(); }},
{QStringLiteral("cbz"), false, QStringLiteral("cbz"),
[] { return std::make_unique<CbzReader>(); },
[] { return std::make_unique<ZipByteSource>(); }},
@@ -159,7 +146,6 @@ int main(int argc, char *argv[])
// --- QML engine ---
QQmlApplicationEngine engine;
engine.addImageProvider(QStringLiteral("web"), new WebImageProvider());
engine.addImageProvider(QStringLiteral("fileicon"), new FileIconProvider());
formatRegistry.registerImageProviders(engine);
engine.rootContext()->setContextProperty(QStringLiteral("isDebugBuild"),
+7 -7
View File
@@ -166,7 +166,7 @@ ApplicationWindow {
anchors.fill: parent
z: 3000
}
// Pre-warms QQuickPixmapReader on the main thread so the render thread
// never creates it first (which logs a QObject parent-thread warning).
Image { width: 0; height: 0; visible: false; source: "image://web/__warmup__" }
@@ -213,9 +213,9 @@ ApplicationWindow {
sequence: "Left"
context: Qt.ApplicationShortcut
onActivated: {
if (currentPage === "reader" && readerPage?.pageView && readingModel.isMangaMode) {
if (currentPage === "reader" && readerPage?.pageView) {
readingModel.mangaRTL ? readerPage.pageView.handleScrollDown()
: readerPage.pageView.handleScrollUp();
: readerPage.pageView.handleScrollUp();
}
}
}
@@ -223,9 +223,9 @@ ApplicationWindow {
sequence: "Right"
context: Qt.ApplicationShortcut
onActivated: {
if (currentPage === "reader" && readerPage?.pageView && readingModel.isMangaMode) {
if (currentPage === "reader" && readerPage?.pageView) {
readingModel.mangaRTL ? readerPage.pageView.handleScrollUp()
: readerPage.pageView.handleScrollDown();
: readerPage.pageView.handleScrollDown();
}
}
}
@@ -278,7 +278,7 @@ ApplicationWindow {
sequence: "M"
context: Qt.ApplicationShortcut
onActivated: {
if (currentPage === "reader" && readingModel.isMangaMode)
if (currentPage === "reader")
readingModel.setMangaRTL(!readingModel.mangaRTL)
}
}
@@ -286,7 +286,7 @@ ApplicationWindow {
sequence: "S"
context: Qt.ApplicationShortcut
onActivated: {
if (currentPage === "reader" && readingModel.isMangaMode)
if (currentPage === "reader")
readingModel.setPageShift(!readingModel.pageShift, readerPage.pageView.currentPair)
}
}
+2 -48
View File
@@ -13,12 +13,11 @@ Rectangle {
anchors.top: parent.top
}
// RTL reading direction toggle (manga mode only).
// RTL reading direction toggle.
FlatIconButton {
anchors.left: parent.left
anchors.leftMargin: 16
anchors.verticalCenter: parent.verticalCenter
visible: readingModel.isMangaMode
padding: 0
implicitWidth: 24
implicitHeight: 24
@@ -29,12 +28,11 @@ Rectangle {
onClicked: readingModel.setMangaRTL(!readingModel.mangaRTL)
}
// Page-shift toggle (manga mode only). Shifts page 1 to be displayed alone after the cover.
// Page-shift toggle. Shifts page 1 to be displayed alone after the cover.
FlatIconButton {
anchors.left: parent.left
anchors.leftMargin: 44
anchors.verticalCenter: parent.verticalCenter
visible: readingModel.isMangaMode
padding: 0
implicitWidth: 24
implicitHeight: 24
@@ -48,50 +46,6 @@ Rectangle {
}
}
// Prev chapter button
FlatIconButton {
id: prevBtn
anchors.verticalCenter: parent.verticalCenter
x: parent.width * 0.5 - chapterText.implicitWidth / 2 - width - 4
visible: book.hasBook && readingModel.hasChapters
enabled: readingModel.currentChapter > 0
padding: 0
implicitWidth: 20
implicitHeight: 20
iconText: ""
iconColor: prevBtn.enabled ? ThemeManager.currentTheme.dimText : ThemeManager.currentTheme.actionDisabled
tooltip: "Previous chapter"
onClicked: readingModel.previousChapter()
}
Text {
id: chapterText
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenter: parent.horizontalCenter
text: book.hasBook && readingModel.hasChapters
? "Chapter " + (readingModel.currentChapter + 1) + " / " + readingModel.totalChapters
: ""
font.pixelSize: 11
font.bold: true
color: ThemeManager.currentTheme.dimText
}
// Next chapter button
FlatIconButton {
id: nextBtn
anchors.verticalCenter: parent.verticalCenter
x: parent.width * 0.5 + chapterText.implicitWidth / 2 + 4
visible: book.hasBook && readingModel.hasChapters
enabled: readingModel.currentChapter < readingModel.totalChapters - 1
padding: 0
implicitWidth: 20
implicitHeight: 20
iconText: ""
iconColor: nextBtn.enabled ? ThemeManager.currentTheme.dimText : ThemeManager.currentTheme.actionDisabled
tooltip: "Next chapter"
onClicked: readingModel.nextChapter()
}
Text {
anchors.right: parent.right
anchors.rightMargin: 16
-3
View File
@@ -194,9 +194,6 @@ Rectangle {
contentReady = true
showPair(readingModel.pairIndexForChunk(chunkIndex))
}
function onScrollToChunkRequested(chunkIndex) {
showPair(readingModel.pairIndexForChunk(chunkIndex))
}
function onTotalPagePairsChanged() {
// Re-clamp after pair rebuild (resize / orientation flip).
showPair(Math.min(currentPair, Math.max(0, readingModel.totalPagePairs - 1)))
-66
View File
@@ -118,70 +118,4 @@ Rectangle {
onClicked: sidebar.navigateTo("settings")
}
}
// TOC section — shown when the current book has a table of contents
Item {
visible: book.hasBook && book.toc.length > 0
anchors.top: navColumn.bottom
anchors.bottom: parent.bottom
width: parent.width
Rectangle {
id: tocDivider
width: parent.width
height: 1
color: ThemeManager.currentTheme.divider
}
Text {
id: tocLabel
anchors.top: tocDivider.bottom
anchors.topMargin: 8
anchors.left: parent.left
anchors.leftMargin: 16
text: "Contents"
font.pixelSize: 10
font.bold: true
color: ThemeManager.currentTheme.dimText
font.letterSpacing: 1
}
ListView {
anchors.top: tocLabel.bottom
anchors.topMargin: 4
anchors.bottom: parent.bottom
width: parent.width
clip: true
model: book.toc
delegate: Rectangle {
width: ListView.view.width
height: tocEntryText.implicitHeight + 10
color: readingModel.currentChapter === modelData.chapterIndex
? Qt.rgba(1, 1, 1, 0.05)
: "transparent"
Text {
id: tocEntryText
anchors.verticalCenter: parent.verticalCenter
x: 16 + modelData.depth * 12
width: parent.width - x - 8
text: modelData.title
font.pixelSize: 13
color: readingModel.currentChapter === modelData.chapterIndex
? ThemeManager.currentTheme.sidebarButtonText
: ThemeManager.currentTheme.uiText
elide: Text.ElideRight
wrapMode: Text.NoWrap
}
MouseArea {
anchors.fill: parent
onClicked: {
readingModel.goToChapter(modelData.chapterIndex)
}
}
}
}
}
}