diff --git a/CMakeLists.txt b/CMakeLists.txt index 71063c0..383f5e9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -161,6 +161,8 @@ set_source_files_properties(src/qml/ThemeManager.qml PROPERTIES QT_RESOURCE_ALIA set_source_files_properties(src/qml/components/Header.qml PROPERTIES QT_RESOURCE_ALIAS components/Header.qml) set_source_files_properties(src/qml/components/SideBar.qml PROPERTIES QT_RESOURCE_ALIAS components/SideBar.qml) set_source_files_properties(src/qml/components/PageView.qml PROPERTIES QT_RESOURCE_ALIAS components/PageView.qml) +set_source_files_properties(src/qml/components/ScrollPageView.qml PROPERTIES QT_RESOURCE_ALIAS components/ScrollPageView.qml) +set_source_files_properties(src/qml/components/MangaPageView.qml PROPERTIES QT_RESOURCE_ALIAS components/MangaPageView.qml) set_source_files_properties(src/qml/components/Footer.qml PROPERTIES QT_RESOURCE_ALIAS components/Footer.qml) set_source_files_properties(src/qml/components/ErrorPopup.qml PROPERTIES QT_RESOURCE_ALIAS components/ErrorPopup.qml) set_source_files_properties(src/qml/components/SideBarButton.qml PROPERTIES QT_RESOURCE_ALIAS components/SideBarButton.qml) @@ -184,6 +186,8 @@ qt_add_qml_module(asteria-qt src/qml/components/Header.qml src/qml/components/SideBar.qml src/qml/components/PageView.qml + src/qml/components/ScrollPageView.qml + src/qml/components/MangaPageView.qml src/qml/components/Footer.qml src/qml/components/ErrorPopup.qml src/qml/components/SideBarButton.qml @@ -254,7 +258,7 @@ add_asteria_test(ReaderFactoryTest tests/ReaderFactoryTest.cpp src/backend/formats/EpubReader.cpp src/backend/formats/Fb2Reader.cpp src/backend/formats/CbzReader.cpp) -target_link_libraries(ReaderFactoryTest PRIVATE PkgConfig::MINIZIP Qt6::Xml) +target_link_libraries(ReaderFactoryTest PRIVATE PkgConfig::MINIZIP Qt6::Xml Qt6::Gui) add_asteria_test(ChunkMeasurerTest tests/ChunkMeasurerTest.cpp src/backend/ChunkMeasurer.cpp diff --git a/src/backend/FormatReader.h b/src/backend/FormatReader.h index 8d80145..ec163a9 100644 --- a/src/backend/FormatReader.h +++ b/src/backend/FormatReader.h @@ -4,6 +4,8 @@ #include #include #include +#include +#include struct TocEntry { QString title; @@ -19,6 +21,8 @@ struct Chapter { class FormatReader { public: + enum class RenderingMode { Scroll, Manga }; + virtual ~FormatReader() = default; virtual bool open(const QString &filePath) = 0; @@ -37,6 +41,12 @@ public: // Returns the lowercase file extension this reader handles (e.g. "txt", "epub"). 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 chapterPageSizes(int chapterIndex) const { Q_UNUSED(chapterIndex); return {}; } }; #endif // FORMATREADER_H diff --git a/src/backend/ReadingModel.cpp b/src/backend/ReadingModel.cpp index 85f0fb9..4c7d632 100644 --- a/src/backend/ReadingModel.cpp +++ b/src/backend/ReadingModel.cpp @@ -3,6 +3,7 @@ #include "IChunkMeasurer.h" #include "IImageLoader.h" #include "ChunkMeasurer.h" +#include #include #include #include @@ -34,6 +35,7 @@ QVariant ReadingModel::data(const QModelIndex &index, int role) const { case ContentRole: return c.html; case PixelHeightRole: return c.pixelHeight; case ChapterRole: return c.chapterIndex; + case NaturalSizeRole: return c.naturalSize; default: return {}; } } @@ -43,6 +45,7 @@ QHash ReadingModel::roleNames() const { {ContentRole, "content"}, {PixelHeightRole, "pixelHeight"}, {ChapterRole, "chapter"}, + {NaturalSizeRole, "naturalSize"}, }; } @@ -58,6 +61,10 @@ int ReadingModel::totalChapters() const { return m_totalChapters; } bool ReadingModel::hasChapters() const { return m_totalChapters > 1; } bool ReadingModel::measuring() const { return m_measuring; } qreal ReadingModel::totalPixelHeight() const { return m_totalPixelHeight; } +int ReadingModel::totalPagePairs() const { return m_pagePairs.size(); } +bool ReadingModel::isMangaMode() const { return m_isMangaMode; } +bool ReadingModel::pageShift() const { return m_pageShift; } +bool ReadingModel::mangaRTL() const { return m_mangaRTL; } double ReadingModel::progress() const { @@ -85,6 +92,16 @@ void ReadingModel::measure(const bool isNew) { if (!m_reader) return; + if (m_isMangaMode) { + // No measurement needed — images are sized by the view to fit the viewport. + // Queue the emission so QML's Loader has time to create MangaPageView before + // restoreReady arrives (in scroll mode the async measurement provides this gap). + QMetaObject::invokeMethod(this, [this, isNew] { + emitRestoreReady(isNew); + }, Qt::QueuedConnection); + return; + } + m_totalPixelHeight = 0; QStringList htmls; @@ -95,6 +112,13 @@ void ReadingModel::measure(const bool isNew) runMeasurement(htmls, isNew); } +void ReadingModel::emitRestoreReady(const bool isNew) +{ + if (!isNew) return; + const auto pos = m_positions.load(m_reader->contentHash()); + emit restoreReady(pos.chunkIndex, pos.intraOffset); +} + void ReadingModel::runMeasurement(const QStringList &htmls, const bool isNew) { if (m_measureFuture.isRunning()) @@ -127,10 +151,7 @@ void ReadingModel::runMeasurement(const QStringList &htmls, const bool isNew) createIndex(m_chunks.size() - 1, 0), {PixelHeightRole}); - if (isNew) { - const auto pos = m_positions.load(m_reader->contentHash()); - emit restoreReady(pos.chunkIndex, pos.intraOffset); - } + emitRestoreReady(isNew); }, Qt::QueuedConnection); }); } @@ -139,7 +160,7 @@ void ReadingModel::setContentWidth(int width) { if (width == m_contentWidth) return; m_contentWidth = width; - if (m_reader) measure(false); + if (m_reader && !m_isMangaMode) measure(false); } void ReadingModel::setFontParams(int fontSize, qreal lineSpacing) @@ -147,7 +168,7 @@ void ReadingModel::setFontParams(int fontSize, qreal lineSpacing) if (fontSize == m_fontSize && qFuzzyCompare(lineSpacing, m_lineSpacing)) return; m_fontSize = fontSize; m_lineSpacing = lineSpacing; - if (m_reader) measure(false); + if (m_reader && !m_isMangaMode) measure(false); } void ReadingModel::setImageLoader(std::unique_ptr loader) @@ -157,6 +178,9 @@ void ReadingModel::setImageLoader(std::unique_ptr loader) void ReadingModel::recalculateCurrentPage() { + // In manga mode currentPage/totalPages track pair index/count (updated by MangaPageView). + if (m_isMangaMode) return; + int page = 0; if (!m_chunks.isEmpty()) { page = qBound(0.0, m_yOffset / m_totalPixelHeight, 1.0) * m_chunks.size() * page_ratio; @@ -167,6 +191,148 @@ void ReadingModel::recalculateCurrentPage() emit currentPageChanged(); } +void ReadingModel::rebuildPagePairs() +{ + const int oldPairs = m_pagePairs.size(); + m_pagePairs.clear(); + + if (!m_isMangaMode || m_chunks.isEmpty()) { + if (m_pagePairs.size() != oldPairs) emit totalPagePairsChanged(); + return; + } + + if (!m_mangaLandscape) { + // Portrait: every chunk is its own solo pair. + m_pagePairs.reserve(m_chunks.size()); + for (int i = 0; i < m_chunks.size(); ++i) + m_pagePairs.append({i, -1}); + } else { + // Landscape: cover alone, optional shift page alone, then portrait-pair the rest. + m_pagePairs.append({0, -1}); // cover always solo + int i = 1; + if (m_pageShift && i < m_chunks.size()) { + m_pagePairs.append({i, -1}); // page 1 solo when shift is ON + ++i; + } + while (i < m_chunks.size()) { + const QSize sz = m_chunks[i].naturalSize; + const bool isLandscape = sz.isValid() && sz.width() > sz.height(); + if (isLandscape) { + m_pagePairs.append({i, -1}); + ++i; + } else { + // Try to pair with next portrait page. + const int next = i + 1; + if (next < m_chunks.size()) { + const QSize nextSz = m_chunks[next].naturalSize; + const bool nextLandscape = nextSz.isValid() && nextSz.width() > nextSz.height(); + if (!nextLandscape) { + m_pagePairs.append({i, next}); + i += 2; + continue; + } + } + m_pagePairs.append({i, -1}); + ++i; + } + } + } + + if (m_pagePairs.size() != oldPairs) emit totalPagePairsChanged(); + + // Sync totalPages/currentPage to pair count in manga mode. + if (const int pairs = m_pagePairs.size(); m_totalPages != pairs) { + m_totalPages = pairs; + emit totalPagesChanged(); + } + if (m_currentPage == 0 && !m_pagePairs.isEmpty()) { + m_currentPage = 1; + emit currentPageChanged(); + } +} + +QVariantList ReadingModel::pagePair(int pairIndex) const +{ + if (pairIndex < 0 || pairIndex >= m_pagePairs.size()) return {}; + const auto &p = m_pagePairs.at(pairIndex); + QVariantList list; + list.append(p.first); + if (p.second >= 0) + list.append(p.second); + return list; +} + +int ReadingModel::pairIndexForChunk(int chunkIndex) const +{ + for (int i = 0; i < m_pagePairs.size(); ++i) { + if (m_pagePairs[i].first == chunkIndex || m_pagePairs[i].second == chunkIndex) + return i; + } + return 0; +} + +QString ReadingModel::imageUrlForChunk(int chunkIndex) const +{ + if (chunkIndex < 0 || chunkIndex >= m_chunks.size()) return {}; + const QString &html = m_chunks.at(chunkIndex).html; + // Extract src="..." from the img tag. + static const QRegularExpression re(QStringLiteral("]*src=\"([^\"]+)\"")); + const auto match = re.match(html); + if (match.hasMatch()) + return match.captured(1); + return {}; +} + +void ReadingModel::setMangaLandscape(bool landscape) +{ + if (m_mangaLandscape == landscape) return; + m_mangaLandscape = landscape; + if (m_isMangaMode) rebuildPagePairs(); +} + +void ReadingModel::setPageShift(bool shift, int currentPairIndex) +{ + if (m_pageShift == shift) return; + + // Pick an anchor chunk that keeps an image on screen across the rebuild AND keeps + // back-and-forth toggling stable (no cumulative drift): + // - turning shift ON: anchor on the higher-index chunk (.second). + // - turning shift OFF: anchor on the lower-index chunk (.first). + // For solo pairs (cover, wide spread) fall back to .first. + int currentChunk = 0; + if (currentPairIndex >= 0 && currentPairIndex < m_pagePairs.size()) { + const auto &pair = m_pagePairs.at(currentPairIndex); + currentChunk = (shift && pair.second >= 0) ? pair.second : pair.first; + } + + 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, 0, m_mangaRTL, m_pageShift); + + emit pageShiftChanged(); + // Tell MangaPageView the exact pair to jump to so it re-evaluates its display binding. + emit pagePairsRebuilt(newPair); +} + +void ReadingModel::setMangaRTL(bool rtl) +{ + if (m_mangaRTL == rtl) return; + m_mangaRTL = rtl; + if (m_reader) + m_positions.save(m_reader->contentHash(), 0, 0, m_mangaRTL, m_pageShift); + emit mangaRTLChanged(); +} + void ReadingModel::loadAllChapters() { beginResetModel(); @@ -181,34 +347,43 @@ void ReadingModel::loadAllChapters() if (m_totalPages != 0) { m_totalPages = 0; emit totalPagesChanged(); } if (m_reader) { - if (!m_coverImageUrl.isEmpty()) { + // In manga mode the format's first chunk is already the cover — no extra cover injection. + if (!m_isMangaMode && !m_coverImageUrl.isEmpty()) { QString coverHtml = QStringLiteral("
") + QStringLiteral("
"); - m_chunks.push_back({coverHtml, 0, -1, -1}); // chunkInChapter=-1 = cover sentinel + m_chunks.push_back({coverHtml, 0, -1, -1, QSize()}); // chunkInChapter=-1 = cover sentinel m_chapterStartIndices.append(1); // chapter 0 starts after cover } else { m_chapterStartIndices.append(0); } for (int i = 0; i < m_totalChapters; ++i) { auto chapter = m_reader->loadChapter(i); + const QVector 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) - m_chunks.push_back({html, i, j++, -1}); + for (const auto &html : chapter.contentChunks) { + const QSize sz = (j < sizes.size()) ? sizes[j] : QSize(); + m_chunks.push_back({html, i, j, -1, sz}); + ++j; + } } } endResetModel(); - if (const int pages = m_chunks.size() * page_ratio; m_totalPages != pages) { - m_totalPages = pages; - emit totalPagesChanged(); - } - if (const int page = m_chunks.isEmpty() ? 0 : 1; m_currentPage != page) { - m_currentPage = page; - emit currentPageChanged(); + if (m_isMangaMode) { + rebuildPagePairs(); + } else { + if (const int pages = m_chunks.size() * page_ratio; m_totalPages != pages) { + m_totalPages = pages; + emit totalPagesChanged(); + } + if (const int page = m_chunks.isEmpty() ? 0 : 1; m_currentPage != page) { + m_currentPage = page; + emit currentPageChanged(); + } } } @@ -218,6 +393,21 @@ void ReadingModel::setReader(FormatReader *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. + if (m_isMangaMode && reader) { + const auto pos = m_positions.load(reader->contentHash()); + m_pageShift = pos.pageShift; + m_mangaRTL = pos.mangaRTL; + } else { + m_pageShift = true; + m_mangaRTL = true; + } + loadAllChapters(); emit totalChaptersChanged(); diff --git a/src/backend/ReadingModel.h b/src/backend/ReadingModel.h index 1d9d934..2cc9246 100644 --- a/src/backend/ReadingModel.h +++ b/src/backend/ReadingModel.h @@ -3,7 +3,10 @@ #include #include +#include +#include #include +#include #include #include "IImageLoader.h" #include "state/BookPositionStore.h" @@ -15,6 +18,7 @@ struct ContentChunk { int chapterIndex = 0; // which chapter owns this chunk int chunkInChapter = 0; // 0-based index within chapter (-1 for cover) int pixelHeight = -1; // -1 = not yet measured + QSize naturalSize; // image pixel dimensions (null for text chunks) }; class ReadingModel : public QAbstractListModel { @@ -28,12 +32,17 @@ class ReadingModel : public QAbstractListModel { Q_PROPERTY(bool hasChapters READ hasChapters NOTIFY totalChaptersChanged) Q_PROPERTY(bool measuring READ measuring NOTIFY measuringChanged) Q_PROPERTY(qreal totalPixelHeight READ totalPixelHeight NOTIFY totalPixelHeightChanged) + 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) public: enum Roles { ContentRole = Qt::UserRole + 1, PixelHeightRole = Qt::UserRole + 2, ChapterRole = Qt::UserRole + 3, + NaturalSizeRole = Qt::UserRole + 4, }; explicit ReadingModel(BookPositionStore &positions, QObject *parent = nullptr); @@ -52,6 +61,10 @@ public: bool hasChapters() const; bool measuring() const; qreal totalPixelHeight() const; + int totalPagePairs() const; + bool isMangaMode() const; + bool pageShift() const; + bool mangaRTL() const; void setReader(FormatReader *reader); void setCoverImageUrl(const QString &coverImageUrl); @@ -63,6 +76,19 @@ public: 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; + Q_INVOKABLE QString imageUrlForChunk(int chunkIndex) const; + + // Called from MangaPageView when window orientation changes + Q_INVOKABLE void setMangaLandscape(bool landscape); + + // Per-book page-shift toggle: when ON, page 1 is shown alone after the cover. + // currentPairIndex must be the pair the view is currently displaying. + Q_INVOKABLE void setPageShift(bool shift, int currentPairIndex = 0); + Q_INVOKABLE void setMangaRTL(bool rtl); + // Measurement Q_INVOKABLE void measure(bool isNew); @@ -78,6 +104,12 @@ signals: void totalPixelHeightChanged(); 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, int intraChunkOffset); @@ -87,7 +119,9 @@ private: void loadAllChapters(); void recalculateCurrentPage(); + void rebuildPagePairs(); void runMeasurement(const QStringList &htmls, bool isNew); + void emitRestoreReady(bool isNew); FormatReader *m_reader = nullptr; QString m_coverImageUrl; @@ -96,11 +130,19 @@ private: int m_currentPage = 0; int m_totalPages = 0; bool m_measuring = false; + bool m_isMangaMode = false; + bool m_mangaLandscape = false; + bool m_pageShift = true; + bool m_mangaRTL = true; QVector m_chunks; QVector m_chapterStartIndices; QVector m_chapterTitles; + // Manga page pairs: each QPair holds (leftChunkIdx, rightChunkIdx) where rightChunkIdx + // may be -1 for solo pages. In RTL mode the "left" slot is the later page visually. + QVector> m_pagePairs; + qreal m_totalPixelHeight = 0.0; qreal m_yOffset = 0.0; int m_contentWidth = 0; diff --git a/src/backend/book/Book.cpp b/src/backend/book/Book.cpp index 8d822ac..c13e228 100644 --- a/src/backend/book/Book.cpp +++ b/src/backend/book/Book.cpp @@ -26,6 +26,7 @@ bool Book::hasBook() const { return m_reader != nullptr; } bool Book::loading() const { return m_loading; } QString Book::errorMessage() const { return m_errorMessage; } QString Book::coverImageUrl() const { return m_coverImageUrl; } +QString Book::renderingMode() const { return m_renderingMode; } QString Book::title() const { return m_reader ? m_reader->title() : QString(); } QString Book::author() const { return m_reader ? m_reader->author() : QString(); } @@ -113,8 +114,15 @@ void Book::openImpl(const QString &filePath) m_reader = std::move(*readerBox); m_coverImageUrl.clear(); m_loading = false; + + const QString newMode = (m_reader->preferredRenderingMode() == FormatReader::RenderingMode::Manga) + ? QStringLiteral("manga") : QStringLiteral("scroll"); + const bool modeChanged = (newMode != m_renderingMode); + m_renderingMode = newMode; + emit loadingChanged(); emit bookChanged(); + if (modeChanged) emit renderingModeChanged(); }, Qt::QueuedConnection); }); } @@ -124,7 +132,10 @@ void Book::close() if (!m_reader) return; m_reader.reset(); m_coverImageUrl.clear(); + const bool modeChanged = (m_renderingMode != QStringLiteral("scroll")); + m_renderingMode = QStringLiteral("scroll"); emit bookChanged(); + if (modeChanged) emit renderingModeChanged(); } void Book::clearError() @@ -134,10 +145,10 @@ void Book::clearError() emit errorMessageChanged(); } -void Book::saveCurrentPosition(int chunkIndex, int intraOffset) +void Book::saveCurrentPosition(int chunkIndex, int intraOffset, bool pageShift) { if (!m_reader) return; - m_positions.save(m_reader->contentHash(), chunkIndex, intraOffset); + m_positions.save(m_reader->contentHash(), chunkIndex, intraOffset, pageShift); emit positionSaved(); } diff --git a/src/backend/book/Book.h b/src/backend/book/Book.h index 6f90128..3b8fc2b 100644 --- a/src/backend/book/Book.h +++ b/src/backend/book/Book.h @@ -15,14 +15,15 @@ class Book : public QObject { Q_OBJECT - Q_PROPERTY(bool hasBook READ hasBook NOTIFY bookChanged) - Q_PROPERTY(bool loading READ loading NOTIFY loadingChanged) - Q_PROPERTY(QString title READ title NOTIFY bookChanged) - 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 toc READ toc NOTIFY bookChanged) - Q_PROPERTY(QString errorMessage READ errorMessage NOTIFY errorMessageChanged) + Q_PROPERTY(bool hasBook READ hasBook NOTIFY bookChanged) + Q_PROPERTY(bool loading READ loading NOTIFY loadingChanged) + Q_PROPERTY(QString title READ title NOTIFY bookChanged) + 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 toc READ toc NOTIFY bookChanged) + Q_PROPERTY(QString errorMessage READ errorMessage NOTIFY errorMessageChanged) + Q_PROPERTY(QString renderingMode READ renderingMode NOTIFY renderingModeChanged) public: Book(IFileDialogService &dialog, BookPositionStore &positions, @@ -30,14 +31,15 @@ public: QObject *parent = nullptr); ~Book() override; - bool hasBook() const; - bool loading() const; - QString title() const; - QString author() const; - QString filePath() const; - QString coverImageUrl() const; - QList toc() const; - QString errorMessage() const; + bool hasBook() const; + bool loading() const; + QString title() const; + QString author() const; + QString filePath() const; + QString coverImageUrl() const; + QList toc() const; + QString errorMessage() const; + QString renderingMode() const; // Called by main.cpp's bookChanged lambda after the image provider resolves the cover URL. void setCoverImageUrl(const QString &url); @@ -52,7 +54,7 @@ public: Q_INVOKABLE void clearError(); // Save current scroll position. Called from QML's scroll tracker; forwards to BookPositionStore. - Q_INVOKABLE void saveCurrentPosition(int chunkIndex, int intraOffset); + Q_INVOKABLE void saveCurrentPosition(int chunkIndex, int intraOffset, bool pageShift = false); // Called from QML's PageView when its width changes. Propagates to image provider + ReadingModel // via the contentWidthChanged signal (wired in main.cpp). @@ -67,6 +69,7 @@ signals: void bookChanged(); void loadingChanged(); void errorMessageChanged(); + void renderingModeChanged(); void contentWidthChanged(int width); private: @@ -78,9 +81,10 @@ private: std::unique_ptr m_reader; QString m_coverImageUrl; QString m_errorMessage; - bool m_loading = false; + QString m_renderingMode = QStringLiteral("scroll"); + bool m_loading = false; int m_openGeneration = 0; - int m_contentWidth = 0; + int m_contentWidth = 0; QFuture m_openFuture; }; diff --git a/src/backend/formats/CbzReader.cpp b/src/backend/formats/CbzReader.cpp index 3e6b0c3..1388454 100644 --- a/src/backend/formats/CbzReader.cpp +++ b/src/backend/formats/CbzReader.cpp @@ -2,9 +2,11 @@ #include "backend/ZipUtils.h" +#include #include #include #include +#include #include #include @@ -77,6 +79,7 @@ bool CbzReader::parseArchive(const QString &filePath) const QStringList allEntries = ZipUtils::listZipEntries(zf); + QStringList imageEntries; for (const QString &entry : allEntries) { if (entry.startsWith(QLatin1String("__MACOSX/"))) continue; @@ -85,16 +88,31 @@ bool CbzReader::parseArchive(const QString &filePath) if (baseName.startsWith(QLatin1Char('.'))) continue; if (kImageExtensions.contains(QFileInfo(entry).suffix().toLower())) - m_pageEntries.append(entry); + imageEntries.append(entry); + } + imageEntries.sort(); + + // Read image header for each page to get natural dimensions (header-only, no pixel decode). + m_pageEntries.reserve(imageEntries.size()); + for (const QString &entry : imageEntries) { + QSize naturalSize; + const QByteArray data = ZipUtils::readZipEntry(zf, entry.toUtf8().constData()); + if (!data.isEmpty()) { + QBuffer buf; + buf.setData(data); + buf.open(QIODevice::ReadOnly); + QImageReader reader(&buf); + naturalSize = reader.size(); + } + m_pageEntries.append({entry, naturalSize}); } - m_pageEntries.sort(); if (m_pageEntries.isEmpty()) { m_error = QStringLiteral("No images found in archive: ") + filePath; return false; } - m_coverEntry = m_pageEntries.first(); + m_coverEntry = m_pageEntries.first().entry; // Look for ComicInfo.xml (case-insensitive, archive-root only) for (const QString &entry : allEntries) { @@ -104,7 +122,7 @@ bool CbzReader::parseArchive(const QString &filePath) int coverIndex = -1; parseComicInfo(comicInfoData, m_title, m_author, coverIndex); if (coverIndex >= 0 && coverIndex < m_pageEntries.size()) - m_coverEntry = m_pageEntries[coverIndex]; + m_coverEntry = m_pageEntries[coverIndex].entry; } break; } @@ -155,13 +173,24 @@ Chapter CbzReader::loadChapter(int index) QStringList chunks; chunks.reserve(m_pageEntries.size()); - for (const QString &entry : m_pageEntries) { + for (const PageEntry &page : m_pageEntries) { chunks.append(QStringLiteral("

" - "

").arg(entry)); + "

").arg(page.entry)); } return Chapter{0, m_title, chunks}; } +QVector CbzReader::chapterPageSizes(int chapterIndex) const +{ + if (chapterIndex != 0 || m_pageEntries.isEmpty()) + return {}; + QVector sizes; + sizes.reserve(m_pageEntries.size()); + for (const PageEntry &page : m_pageEntries) + sizes.append(page.naturalSize); + return sizes; +} + QString CbzReader::lastError() { return m_error; } QString CbzReader::title() { return m_title; } QString CbzReader::author() { return m_author; } diff --git a/src/backend/formats/CbzReader.h b/src/backend/formats/CbzReader.h index 474e3a1..732bfdc 100644 --- a/src/backend/formats/CbzReader.h +++ b/src/backend/formats/CbzReader.h @@ -4,7 +4,9 @@ #include "backend/FormatReader.h" #include #include +#include #include +#include class CbzReader : public FormatReader { public: @@ -21,7 +23,15 @@ public: QByteArray contentHash() override; QString fileType() const override; + RenderingMode preferredRenderingMode() const override { return RenderingMode::Manga; } + QVector chapterPageSizes(int chapterIndex) const override; + private: + struct PageEntry { + QString entry; + QSize naturalSize; + }; + bool parseArchive(const QString &filePath); QString m_filePath; @@ -29,7 +39,7 @@ private: QString m_title; QString m_author; QString m_error; - QStringList m_pageEntries; + QVector m_pageEntries; QString m_coverEntry; }; diff --git a/src/backend/state/BookPositionStore.cpp b/src/backend/state/BookPositionStore.cpp index 3964b07..7c2aad6 100644 --- a/src/backend/state/BookPositionStore.cpp +++ b/src/backend/state/BookPositionStore.cpp @@ -13,16 +13,20 @@ BookPosition BookPositionStore::load(const QByteArray &contentMd5) BookPosition pos; pos.chunkIndex = d.value(QStringLiteral("chunkIndex"), 0).toInt(); pos.intraOffset = d.value(QStringLiteral("intraOffset"), 0).toInt(); + pos.pageShift = d.value(QStringLiteral("pageShift"), true).toBool(); + pos.mangaRTL = d.value(QStringLiteral("mangaRTL"), true).toBool(); return pos; } -void BookPositionStore::save(const QByteArray &contentMd5, int chunkIndex, int intraOffset) +void BookPositionStore::save(const QByteArray &contentMd5, int chunkIndex, int intraOffset, bool mangaRTL, bool pageShift) { if (contentMd5.isEmpty()) return; m_state.saveSection(sectionKey(contentMd5), { {QStringLiteral("chunkIndex"), chunkIndex}, {QStringLiteral("intraOffset"), intraOffset}, + {QStringLiteral("pageShift"), pageShift}, + {QStringLiteral("mangaRTL"), mangaRTL}, }); } diff --git a/src/backend/state/BookPositionStore.h b/src/backend/state/BookPositionStore.h index 8750fc2..d186ebb 100644 --- a/src/backend/state/BookPositionStore.h +++ b/src/backend/state/BookPositionStore.h @@ -5,8 +5,10 @@ #include "backend/AppState.h" struct BookPosition { - int chunkIndex = 0; - int intraOffset = 0; + int chunkIndex = 0; + int intraOffset = 0; + bool pageShift = true; // manga page-shift; default ON + bool mangaRTL = true; // manga reading direction; default RTL }; class BookPositionStore { @@ -17,7 +19,7 @@ public: BookPosition load(const QByteArray &contentMd5); // Save the current position for a book identified by MD5 of its contents. - void save(const QByteArray &contentMd5, int chunkIndex, int intraOffset); + void save(const QByteArray &contentMd5, int chunkIndex, int intraOffset, bool mangaRTL = true, bool pageShift = true); private: AppState &m_state; diff --git a/src/qml/Main.qml b/src/qml/Main.qml index f2ff2ee..88d72f7 100644 --- a/src/qml/Main.qml +++ b/src/qml/Main.qml @@ -183,6 +183,9 @@ ApplicationWindow { target: readingModel function onRestoreReady(chunkIndex, intraOffset) { if (!book.hasBook) return + // Reset loading overlay — in manga mode measuring is skipped so measuringChanged + // never fires; restoreReady is the definitive "ready" signal for all modes. + window._bookInitializing = false if (window._startupRestore) { window._startupRestore = false var savedPage = uiState.lastPage @@ -219,7 +222,7 @@ ApplicationWindow { sequence: "Up" context: Qt.ApplicationShortcut onActivated: { - if (currentPage === "reader" && readerPage?.pageView) { + if (currentPage === "reader" && readerPage?.pageView && !readingModel.isMangaMode) { readerPage.pageView.handleScrollUp(); } } @@ -228,11 +231,31 @@ ApplicationWindow { sequence: "Down" context: Qt.ApplicationShortcut onActivated: { - if (currentPage === "reader" && readerPage?.pageView) { + if (currentPage === "reader" && readerPage?.pageView && !readingModel.isMangaMode) { readerPage.pageView.handleScrollDown(); } } } + Shortcut { + sequence: "Left" + context: Qt.ApplicationShortcut + onActivated: { + if (currentPage === "reader" && readerPage?.pageView && readingModel.isMangaMode) { + readingModel.mangaRTL ? readerPage.pageView.handleScrollDown() + : readerPage.pageView.handleScrollUp(); + } + } + } + Shortcut { + sequence: "Right" + context: Qt.ApplicationShortcut + onActivated: { + if (currentPage === "reader" && readerPage?.pageView && readingModel.isMangaMode) { + readingModel.mangaRTL ? readerPage.pageView.handleScrollUp() + : readerPage.pageView.handleScrollDown(); + } + } + } Shortcut { sequence: "PgUp" context: Qt.ApplicationShortcut @@ -278,6 +301,22 @@ ApplicationWindow { } } } + Shortcut { + sequence: "M" + context: Qt.ApplicationShortcut + onActivated: { + if (currentPage === "reader" && readingModel.isMangaMode) + readingModel.setMangaRTL(!readingModel.mangaRTL) + } + } + Shortcut { + sequence: "S" + context: Qt.ApplicationShortcut + onActivated: { + if (currentPage === "reader" && readingModel.isMangaMode) + readingModel.setPageShift(!readingModel.pageShift, readerPage.pageView.currentMangaPair) + } + } Timer { running: true diff --git a/src/qml/components/Footer.qml b/src/qml/components/Footer.qml index 257e0e2..3e3563e 100644 --- a/src/qml/components/Footer.qml +++ b/src/qml/components/Footer.qml @@ -13,13 +13,13 @@ Rectangle { anchors.top: parent.top } - // Measuring spinner + // Measuring spinner (hidden during manga mode — measurement is skipped for image formats) Text { anchors.left: parent.left anchors.leftMargin: 16 anchors.verticalCenter: parent.verticalCenter visible: typeof readingModel !== "undefined" && readingModel.measuring - text: "\ue863" + text: "" font.family: "Material Icons Outlined" font.pixelSize: 14 color: ThemeManager.currentTheme.dimText @@ -32,6 +32,64 @@ Rectangle { } } + // RTL reading direction toggle (manga mode only). + Button { + anchors.left: parent.left + anchors.leftMargin: 16 + anchors.verticalCenter: parent.verticalCenter + visible: typeof readingModel !== "undefined" && readingModel.isMangaMode + flat: true + padding: 0 + implicitWidth: 24 + implicitHeight: 24 + contentItem: Text { + text: "" + font.family: "Material Icons Outlined" + font.pixelSize: 16 + color: (typeof readingModel !== "undefined" && readingModel.mangaRTL) + ? ThemeManager.currentTheme.buttonAccent + : ThemeManager.currentTheme.dimText + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + } + background: Item {} + onClicked: readingModel.setMangaRTL(!readingModel.mangaRTL) + ToolTip.visible: hovered + ToolTip.delay: 500 + ToolTip.text: "Right-to-left reading (M)" + } + + // Page-shift toggle (manga mode only). Shifts page 1 to be displayed alone after the cover. + Button { + anchors.left: parent.left + anchors.leftMargin: 44 + anchors.verticalCenter: parent.verticalCenter + visible: typeof readingModel !== "undefined" && readingModel.isMangaMode + flat: true + padding: 0 + implicitWidth: 24 + implicitHeight: 24 + contentItem: Text { + text: "" + font.family: "Material Icons Outlined" + font.pixelSize: 16 + color: (typeof readingModel !== "undefined" && readingModel.pageShift) + ? ThemeManager.currentTheme.buttonAccent + : ThemeManager.currentTheme.dimText + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + } + background: Item {} + onClicked: { + // currentPair lives on MangaPageView; reach it via the PageView router alias. + const pairIdx = readerPage.pageView.currentMangaPair + readingModel.setPageShift(!readingModel.pageShift, pairIdx) + } + ToolTip.visible: hovered + ToolTip.delay: 500 + ToolTip.text: "Page shift (S)" + } + // Prev chapter button Button { id: prevBtn @@ -44,7 +102,7 @@ Rectangle { implicitWidth: 20 implicitHeight: 20 contentItem: Text { - text: "\ue5cb" + text: "" font.family: "Material Icons Outlined" font.pixelSize: 16 color: prevBtn.enabled ? ThemeManager.currentTheme.dimText : ThemeManager.currentTheme.actionDisabled @@ -53,6 +111,9 @@ Rectangle { } background: Item {} onClicked: readingModel.previousChapter() + ToolTip.visible: hovered + ToolTip.delay: 500 + ToolTip.text: "Previous chapter" } Text { @@ -79,7 +140,7 @@ Rectangle { implicitWidth: 20 implicitHeight: 20 contentItem: Text { - text: "\ue5cc" + text: "" font.family: "Material Icons Outlined" font.pixelSize: 16 color: nextBtn.enabled ? ThemeManager.currentTheme.dimText : ThemeManager.currentTheme.actionDisabled @@ -88,6 +149,9 @@ Rectangle { } background: Item {} onClicked: readingModel.nextChapter() + ToolTip.visible: hovered + ToolTip.delay: 500 + ToolTip.text: "Next chapter" } Text { diff --git a/src/qml/components/MangaPageView.qml b/src/qml/components/MangaPageView.qml new file mode 100644 index 0000000..c001672 --- /dev/null +++ b/src/qml/components/MangaPageView.qml @@ -0,0 +1,228 @@ +import QtQuick +import QtQuick.Controls +import Asteria + +Rectangle { + id: root + focus: true + + // Keep the same public interface as ScrollPageView so PageView router delegates uniformly. + property bool contentReady: false + property bool resizing: false + property bool restoreReady: false + property int initialIndex: -1 + property int initialOffset: -1 + + property int currentPair: 0 + + readonly property bool landscape: width > height + + gradient: Gradient { + GradientStop { position: 0.0; color: ThemeManager.currentTheme.gradientTop } + GradientStop { position: 1.0; color: ThemeManager.currentTheme.gradientBottom } + } + + // Keyboard navigation — same names as ScrollPageView so PageView can forward blindly. + function handlePageDown() { nextPair() } + function handlePageUp() { previousPair() } + function handleScrollDown() { nextPair() } + function handleScrollUp() { previousPair() } + + function nextPair() { + if (currentPair < readingModel.totalPagePairs - 1) { + currentPair++ + onPairChanged() + } + } + + function previousPair() { + if (currentPair > 0) { + currentPair-- + onPairChanged() + } + } + + function onPairChanged() { + const pair = readingModel.pagePair(currentPair) + if (pair.length === 0) return + const firstChunk = pair[0] + // Keep scroll model in sync so Footer page counter and chapter tracking work. + readingModel.setScrollInfo(firstChunk, currentPair / Math.max(1, readingModel.totalPagePairs - 1)) + book.saveCurrentPosition(firstChunk, 0, readingModel.pageShift) + // Sync currentPage for footer display. + // totalPages is already set to totalPagePairs by the model in manga mode. + } + + // Notify model when orientation changes (triggers pair rebuild). + onLandscapeChanged: landscapeDebounce.restart() + + Timer { + id: landscapeDebounce + interval: 150 + repeat: false + onTriggered: readingModel.setMangaLandscape(landscape) + } + + // Initialise landscape state once visible. + Component.onCompleted: readingModel.setMangaLandscape(landscape) + + // Page display area. + Item { + id: pageArea + anchors.fill: parent + anchors.margins: readingPreferences.verticalMargin + + // Build display pair: for RTL mode pages are reversed (higher index on the left). + property var pair: contentReady ? readingModel.pagePair(currentPair) : [] + + property int leftChunk: { + if (pair.length === 0) return -1 + if (pair.length === 1) return pair[0] + return readingModel.mangaRTL ? pair[1] : pair[0] + } + property int rightChunk: { + if (pair.length < 2) return -1 + return readingModel.mangaRTL ? pair[0] : pair[1] + } + + property bool hasTwoPages: pair.length === 2 + + Behavior on opacity { NumberAnimation { duration: 120 } } + + // Left (or solo) page. + Image { + id: leftImg + visible: pageArea.leftChunk >= 0 + x: 0 + y: 0 + width: pageArea.hasTwoPages ? parent.width / 2 : parent.width + height: parent.height + fillMode: Image.PreserveAspectFit + // When paired, pin content to the spine (right edge) so there's no gap between pages. + horizontalAlignment: pageArea.hasTwoPages ? Image.AlignRight : Image.AlignHCenter + asynchronous: true + cache: true + source: pageArea.leftChunk >= 0 ? readingModel.imageUrlForChunk(pageArea.leftChunk) : "" + } + + // Right page (landscape two-page spread only). + Image { + id: rightImg + visible: pageArea.rightChunk >= 0 + x: parent.width / 2 + y: 0 + width: parent.width / 2 + height: parent.height + fillMode: Image.PreserveAspectFit + // Pin content to the spine (left edge) so it meets the left page with no gap. + horizontalAlignment: Image.AlignLeft + asynchronous: true + cache: true + source: pageArea.rightChunk >= 0 ? readingModel.imageUrlForChunk(pageArea.rightChunk) : "" + } + + // Loading indicator while images load. + BusyIndicator { + anchors.centerIn: parent + running: (leftImg.status === Image.Loading) || (rightImg.visible && rightImg.status === Image.Loading) + visible: running + z: 5 + } + } + + // Swipe / tap input. + MouseArea { + id: inputArea + anchors.fill: parent + z: 10 + + property real pressX: 0 + property real startPressX: 0 + property bool dragging: false + + onPressed: function(mouse) { + pressX = mouse.x + startPressX = mouse.x + dragging = false + } + + onPositionChanged: function(mouse) { + if (Math.abs(mouse.x - startPressX) > 8) + dragging = true + } + + onReleased: function(mouse) { + const dx = mouse.x - startPressX + if (Math.abs(dx) > root.width * 0.12) { + // Swipe gesture. + if (readingModel.mangaRTL) { + if (dx < 0) nextPair(); else previousPair() + } else { + if (dx > 0) nextPair(); else previousPair() + } + return + } + if (dragging) return + // Tap zones — only if not a swipe. + clickDebounce.clickX = mouse.x + clickDebounce.restart() + } + + onDoubleClicked: { + clickDebounce.stop() + window.visibility = (window.visibility === Window.FullScreen) ? Window.Windowed : Window.FullScreen + } + } + + Timer { + id: clickDebounce + interval: 150 + property real clickX: 0 + onTriggered: { + const third = root.width / 3 + if (clickX < third) { + // Left third tap. + if (readingModel.mangaRTL) nextPair(); else previousPair() + } else if (clickX > root.width - third) { + // Right third tap. + if (readingModel.mangaRTL) previousPair(); else nextPair() + } else { + // Middle — toggle bars. + window.barsVisible = !window.barsVisible + window.sidebarOpen = !window.sidebarOpen + } + } + } + + // Restore position when a new book is loaded. + Connections { + target: readingModel + function onRestoreReady(chunkIndex, intraOffset) { + contentReady = true + const pair = readingModel.pairIndexForChunk(chunkIndex) + currentPair = pair + restoreReady = true + onPairChanged() + } + function onTotalPagePairsChanged() { + // Re-clamp after pair rebuild (resize / orientation flip). + currentPair = Math.min(currentPair, Math.max(0, readingModel.totalPagePairs - 1)) + } + function onPagePairsRebuilt(newPairIndex) { + // setPageShift rebuilt the pairs — the pair-content binding needs to re-evaluate + // even when newPairIndex equals the existing currentPair (toggling shift can leave + // the index unchanged while pair contents change). Two writes force two change + // notifications; the binding is read once after the function returns with the + // final value, so the -1 intermediate is never displayed. + currentPair = -1 + currentPair = newPairIndex + } + } + + Connections { + target: book + function onLoadingChanged() { + if (book.loading) contentReady = false + } + } +} diff --git a/src/qml/components/PageView.qml b/src/qml/components/PageView.qml index cb6a954..8962330 100644 --- a/src/qml/components/PageView.qml +++ b/src/qml/components/PageView.qml @@ -2,219 +2,44 @@ import QtQuick import QtQuick.Controls import Asteria -Rectangle { +Item { + id: root focus: true + // Mirror the public properties ScrollPageView exposes so callers stay unchanged. property bool contentReady: false property bool resizing: false property bool restoreReady: false property int initialIndex: -1 property int initialOffset: -1 - // Animation for smooth scrolling - property Animation scrollAnimation: PropertyAnimation { - target: chunkListView - property: "contentY" - duration: 200 - easing.type: Easing.InOutQuad - } - - // Public methods for global keyboard navigation - function handlePageUp() { - var scrollAmount = chunkListView.height * 0.95; - var targetY = Math.max(0, chunkListView.contentY - scrollAmount); - animateScrollTo(targetY); - } - - function handlePageDown() { - var scrollAmount = chunkListView.height * 0.95; - var maxY = Math.max(0, chunkListView.contentHeight - chunkListView.height); - var targetY = Math.min(maxY, chunkListView.contentY + scrollAmount); - animateScrollTo(targetY); - } - - function handleScrollUp() { - var lineHeight = readingPreferences.fontSize * readingPreferences.lineSpacing; - var scrollAmount = lineHeight * 3; - var targetY = Math.max(0, chunkListView.contentY - scrollAmount); - animateScrollTo(targetY); - } - - function handleScrollDown() { - var lineHeight = readingPreferences.fontSize * readingPreferences.lineSpacing; - var scrollAmount = lineHeight * 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(); - } - - gradient: Gradient { - GradientStop { position: 0.0; color: ThemeManager.currentTheme.gradientTop } - GradientStop { position: 1.0; color: ThemeManager.currentTheme.gradientBottom } - } + // Current pair index in the active MangaPageView; -1 when in scroll mode. + readonly property int currentMangaPair: (loader.item && loader.item.hasOwnProperty("currentPair")) + ? loader.item.currentPair : -1 + // Delegate all navigation calls to whichever view is active. + function handlePageUp() { if (loader.item) loader.item.handlePageUp() } + function handlePageDown() { if (loader.item) loader.item.handlePageDown() } + function handleScrollUp() { if (loader.item) loader.item.handleScrollUp() } + function handleScrollDown() { if (loader.item) loader.item.handleScrollDown() } function updateContentWidth() { - book.setContentWidth(chunkListView.width - 18 - 2 * readingPreferences.horizontalMargin) + if (loader.item && typeof loader.item.updateContentWidth === "function") + loader.item.updateContentWidth() } - Component.onCompleted: updateContentWidth() - onWidthChanged: { - resizing = true; - remeasureTimer.restart() - } - - Timer { - id: remeasureTimer - interval: 150 - repeat: false - onTriggered: { - updateContentWidth() - resizing = false; - } - } - - ListView { - id: chunkListView + Loader { + id: loader anchors.fill: parent - anchors.topMargin: readingPreferences.verticalMargin - anchors.bottomMargin: readingPreferences.verticalMargin - model: contentReady ? readingModel : null - cacheBuffer: 20 - clip: true - maximumFlickVelocity: 99999 - - delegate: Item { - id: chunkDelegate - readonly property int chunkIdx: model.index - width: chunkListView.width - height: resizing || readingModel.measuring ? contentText.implicitHeight : model.pixelHeight - - Text { - visible: isDebugBuild - leftPadding: 0 - text: model.index - color: "#FFFFFF" - height: 0 - } - Text { - id: contentText - width: parent.width - 18 // subtract scrollbar - leftPadding: readingPreferences.horizontalMargin - rightPadding: readingPreferences.horizontalMargin - wrapMode: Text.WrapAtWordBoundaryOrAnywhere - textFormat: Text.RichText - font.pixelSize: readingPreferences.fontSize - lineHeight: readingPreferences.lineSpacing - color: ThemeManager.currentTheme.readingText - text: model.content - visible: model.content !== "" - onImplicitHeightChanged: { - if (model.pixelHeight > 0 && implicitHeight > 0) { - var diff = model.pixelHeight - implicitHeight - if (Math.abs(diff) > 1) { - console.warn("Chunk", model.index, - "height mismatch: measured=" + model.pixelHeight, - "actual=" + Math.round(implicitHeight), - "diff=" + Math.round(diff)) - } - } - } - } - } - - onContentYChanged: { - scrollTrackTimer.restart() - } - - ScrollBar.vertical: ScrollBar { - policy: ScrollBar.AsNeeded - padding: 0 - contentItem: Rectangle { - implicitWidth: 18 - radius: 3 - color: ThemeManager.currentTheme.scrollbarThumb - } - background: Rectangle { - implicitWidth: 18 - color: ThemeManager.currentTheme.scrollbarTrack - } - } - - MouseArea { - anchors.fill: parent - anchors.rightMargin: 18 - 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.barsVisible = !window.barsVisible - window.sidebarOpen = !window.sidebarOpen - } - } + sourceComponent: book.renderingMode === "manga" ? mangaViewComp : scrollViewComp } - - Timer { - id: scrollTrackTimer - interval: 300 - repeat: false - onTriggered: { - if (book.hasBook && contentReady && restoreReady) { - var topIdx = chunkListView.indexAt(0, chunkListView.contentY) - if (topIdx < 0) topIdx = 0 - var topItem = chunkListView.itemAtIndex(topIdx) - var intraOffset = topItem ? (chunkListView.contentY - topItem.y) : 0 - readingModel.setScrollInfo(topIdx, chunkListView.visibleArea.yPosition) - book.saveCurrentPosition(topIdx, intraOffset) - } - } + Component { + id: scrollViewComp + ScrollPageView { anchors.fill: parent; focus: true } } - Connections { - target: book - function onLoadingChanged() { - if (book.loading) - contentReady = false - } + Component { + id: mangaViewComp + MangaPageView { anchors.fill: parent; focus: true } } - - Connections { - target: readingModel - function onRestoreReady(chunkIndex, intraOffset) { - contentReady = true - initialIndex = chunkIndex - initialOffset = intraOffset - restoreTimer.start() - } - function onScrollToChunkRequested(chunkIndex) { - chunkListView.positionViewAtIndex(chunkIndex, ListView.Beginning) - } - } - - Timer { - id: restoreTimer - interval: 1 - repeat: false - onTriggered: { - console.info("Restoring contentHeight:", chunkListView.contentHeight, "originY:", chunkListView.originY, "chunkIndex:", initialIndex, "intraOffset:", initialOffset) - chunkListView.positionViewAtIndex(initialIndex, ListView.Beginning) - chunkListView.contentY += initialOffset - restoreReady = true - } - } - } diff --git a/src/qml/components/ScrollPageView.qml b/src/qml/components/ScrollPageView.qml new file mode 100644 index 0000000..cb6a954 --- /dev/null +++ b/src/qml/components/ScrollPageView.qml @@ -0,0 +1,220 @@ +import QtQuick +import QtQuick.Controls +import Asteria + +Rectangle { + focus: true + + property bool contentReady: false + property bool resizing: false + property bool restoreReady: false + property int initialIndex: -1 + property int initialOffset: -1 + + // Animation for smooth scrolling + property Animation scrollAnimation: PropertyAnimation { + target: chunkListView + property: "contentY" + duration: 200 + easing.type: Easing.InOutQuad + } + + // Public methods for global keyboard navigation + function handlePageUp() { + var scrollAmount = chunkListView.height * 0.95; + var targetY = Math.max(0, chunkListView.contentY - scrollAmount); + animateScrollTo(targetY); + } + + function handlePageDown() { + var scrollAmount = chunkListView.height * 0.95; + var maxY = Math.max(0, chunkListView.contentHeight - chunkListView.height); + var targetY = Math.min(maxY, chunkListView.contentY + scrollAmount); + animateScrollTo(targetY); + } + + function handleScrollUp() { + var lineHeight = readingPreferences.fontSize * readingPreferences.lineSpacing; + var scrollAmount = lineHeight * 3; + var targetY = Math.max(0, chunkListView.contentY - scrollAmount); + animateScrollTo(targetY); + } + + function handleScrollDown() { + var lineHeight = readingPreferences.fontSize * readingPreferences.lineSpacing; + var scrollAmount = lineHeight * 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(); + } + + gradient: Gradient { + GradientStop { position: 0.0; color: ThemeManager.currentTheme.gradientTop } + GradientStop { position: 1.0; color: ThemeManager.currentTheme.gradientBottom } + } + + function updateContentWidth() { + book.setContentWidth(chunkListView.width - 18 - 2 * readingPreferences.horizontalMargin) + } + + Component.onCompleted: updateContentWidth() + onWidthChanged: { + resizing = true; + remeasureTimer.restart() + } + + Timer { + id: remeasureTimer + interval: 150 + repeat: false + onTriggered: { + updateContentWidth() + resizing = false; + } + } + + ListView { + id: chunkListView + anchors.fill: parent + anchors.topMargin: readingPreferences.verticalMargin + anchors.bottomMargin: readingPreferences.verticalMargin + model: contentReady ? readingModel : null + cacheBuffer: 20 + clip: true + maximumFlickVelocity: 99999 + + delegate: Item { + id: chunkDelegate + readonly property int chunkIdx: model.index + width: chunkListView.width + height: resizing || readingModel.measuring ? contentText.implicitHeight : model.pixelHeight + + Text { + visible: isDebugBuild + leftPadding: 0 + text: model.index + color: "#FFFFFF" + height: 0 + } + Text { + id: contentText + width: parent.width - 18 // subtract scrollbar + leftPadding: readingPreferences.horizontalMargin + rightPadding: readingPreferences.horizontalMargin + wrapMode: Text.WrapAtWordBoundaryOrAnywhere + textFormat: Text.RichText + font.pixelSize: readingPreferences.fontSize + lineHeight: readingPreferences.lineSpacing + color: ThemeManager.currentTheme.readingText + text: model.content + visible: model.content !== "" + onImplicitHeightChanged: { + if (model.pixelHeight > 0 && implicitHeight > 0) { + var diff = model.pixelHeight - implicitHeight + if (Math.abs(diff) > 1) { + console.warn("Chunk", model.index, + "height mismatch: measured=" + model.pixelHeight, + "actual=" + Math.round(implicitHeight), + "diff=" + Math.round(diff)) + } + } + } + } + } + + onContentYChanged: { + scrollTrackTimer.restart() + } + + ScrollBar.vertical: ScrollBar { + policy: ScrollBar.AsNeeded + padding: 0 + contentItem: Rectangle { + implicitWidth: 18 + radius: 3 + color: ThemeManager.currentTheme.scrollbarThumb + } + background: Rectangle { + implicitWidth: 18 + color: ThemeManager.currentTheme.scrollbarTrack + } + } + + MouseArea { + anchors.fill: parent + anchors.rightMargin: 18 + 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.barsVisible = !window.barsVisible + window.sidebarOpen = !window.sidebarOpen + } + } + } + + + Timer { + id: scrollTrackTimer + interval: 300 + repeat: false + onTriggered: { + if (book.hasBook && contentReady && restoreReady) { + var topIdx = chunkListView.indexAt(0, chunkListView.contentY) + if (topIdx < 0) topIdx = 0 + var topItem = chunkListView.itemAtIndex(topIdx) + var intraOffset = topItem ? (chunkListView.contentY - topItem.y) : 0 + readingModel.setScrollInfo(topIdx, chunkListView.visibleArea.yPosition) + book.saveCurrentPosition(topIdx, intraOffset) + } + } + } + + Connections { + target: book + function onLoadingChanged() { + if (book.loading) + contentReady = false + } + } + + Connections { + target: readingModel + function onRestoreReady(chunkIndex, intraOffset) { + contentReady = true + initialIndex = chunkIndex + initialOffset = intraOffset + restoreTimer.start() + } + function onScrollToChunkRequested(chunkIndex) { + chunkListView.positionViewAtIndex(chunkIndex, ListView.Beginning) + } + } + + Timer { + id: restoreTimer + interval: 1 + repeat: false + onTriggered: { + console.info("Restoring contentHeight:", chunkListView.contentHeight, "originY:", chunkListView.originY, "chunkIndex:", initialIndex, "intraOffset:", initialOffset) + chunkListView.positionViewAtIndex(initialIndex, ListView.Beginning) + chunkListView.contentY += initialOffset + restoreReady = true + } + } + +}