From 5d96fbb0bb7dba707b9d24fbbaa0e1606f5e6462 Mon Sep 17 00:00:00 2001 From: Agel Date: Fri, 13 Nov 2026 09:45:09 +0100 Subject: [PATCH] Remove Book and Close Book menu items and auto-close on navigation Simplify sidebar navigation by removing the conditional Book and Close Book items so users no longer need to manage a book left open in the background. Because there is no longer a Book item to return to the reader, navigating away from the reader to History or Custom Theme now flushes any pending scroll position and closes the active or in-flight book. Opening the Settings popup still keeps the book open behind the overlay, and clicking Files keeps the current book open until a file is actually selected so cancelling the file dialog preserves the current reading session. This also fixes book-lifecycle edge cases exposed by closing on navigation: - Cancel in-flight async loads in Book::close() and clear loading state so closing mid-load does not jump back to the reader or stall the spinner. - Emit willCloseBook before resetting the reader so AppCoordinator snapshots final progress into HistoryModel and immediately clears UiState.lastFilePath. - Mark Book as loading before clearing the outgoing reader when opening a new file to prevent HistoryPage from flashing between books, and fall back to History on load errors. - Reset ScrollPageView and MangaPageView state when a book closes, and always navigate to the reader on restoreReady so CLI-opened files are not hidden behind a previously saved History page. - Add coverage in BookTest and AppCoordinatorTest and document the behavior in AGENTS.md. --- AGENTS.md | 3 +- CMakeLists.txt | 20 ++++ src/backend/AppCoordinator.cpp | 8 +- src/backend/AppCoordinator.h | 2 +- src/backend/book/Book.cpp | 31 ++++-- src/backend/book/Book.h | 2 + src/qml/Main.qml | 28 +++--- src/qml/components/MangaPageView.qml | 12 ++- src/qml/components/ScrollPageView.qml | 15 ++- src/qml/components/SideBar.qml | 15 --- tests/AppCoordinatorTest.cpp | 134 ++++++++++++++++++++++++++ tests/book/BookTest.cpp | 76 +++++++++++++++ 12 files changed, 300 insertions(+), 46 deletions(-) create mode 100644 tests/AppCoordinatorTest.cpp diff --git a/AGENTS.md b/AGENTS.md index 55cf4a5..0f74182 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -231,7 +231,7 @@ public: ## Position Restoration & State Persistence - **History Persistence & Ordering**: `AppState` persists the history list. On deserialization (`HistoryModel::load`), timestamps are converted to strongly-typed `QDateTime`, and bogus or unparseable timestamps are immediately dropped. Loaded entries are sorted in descending chronological order (`lastOpened desc`). Runtime updates (`addOrUpdateBook`) preserve this descending chronological order without inversions. - **Position Persistence**: `BookPositionStore` persists `BookPosition` (`chunkIndex`, `intraOffset`, `progress`, `pageShift`, `mangaRTL`, `useBookColours`) indexed by file content MD5 (`contentHash()`), ensuring state survives file renames or moves. -- **UI State Persistence**: `UiState` persists `themeName`, `lastPage`, `sidebarOpen`, `barsVisible`, `lastFilePath`, `customTheme`, and window geometry. Distraction-free chrome toggling via spacebar toggles `barsVisible` without destroying the persistent `sidebarOpen` user preference; effective sidebar visibility in reader mode is gated by `(!inReader || barsVisible) && uiState.sidebarOpen`. +- **UI State Persistence**: `UiState` persists `themeName`, `lastPage`, `sidebarOpen`, `barsVisible`, `lastFilePath`, `customTheme`, and window geometry. Distraction-free chrome toggling via spacebar toggles `barsVisible` without destroying the persistent `sidebarOpen` user preference; effective sidebar visibility in reader mode is gated by `(!inReader || barsVisible) && uiState.sidebarOpen`. Navigating away from the reader to `History` or `Custom Theme` (or opening a new file) closes the active/loading book via `Book.close()` (cancelling in-flight loads, snapshotting progress into `HistoryModel`, resetting `ReadingModel`, and clearing `UiState.lastFilePath`), while opening the `Settings` popup keeps the current book open. - **Restoration Flow**: - Text mode: `ReadingModel` computes layout for the saved anchor chunk first, then emits `restoreReady(chunkIndex, intraOffset)`. `ScrollPageView` positions the `ListView` at `chunkIndex` and applies `intraOffset`. - Comic mode: `restoreReady(chunkIndex)` triggers `MangaPageView.showPair(pairIndexForChunk(chunkIndex))`. @@ -339,6 +339,7 @@ src/ specs/ knuth-plass-rendering.allium tests/ + AppCoordinatorTest.cpp AppStateTest.cpp EntryImageProviderTest.cpp FileIconProviderTest.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index f2131e9..ee5609d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -438,6 +438,26 @@ set_tests_properties(TxtReaderTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offsc add_asteria_test(AppStateTest tests/AppStateTest.cpp src/backend/AppState.cpp) +add_asteria_test(AppCoordinatorTest tests/AppCoordinatorTest.cpp + src/backend/AppCoordinator.cpp + src/backend/AppState.cpp + src/backend/HistoryModel.cpp + src/backend/ReadingModel.cpp + src/backend/reading/MangaPagination.cpp + src/backend/state/BookPositionStore.cpp + src/backend/state/ReadingPreferences.cpp + src/backend/state/UiState.cpp + src/backend/book/Book.cpp + src/backend/formats/FormatRegistry.cpp + src/backend/formats/AsyncImageResponse.cpp + src/backend/IFileDialogService.h + ${COMIC_SOURCES} + ${EPUB_READER_SOURCES} + ${FB2_READER_SOURCES} + ${TXT_READER_SOURCES}) +target_link_libraries(AppCoordinatorTest PRIVATE Qt6::Concurrent Qt6::Gui Qt6::Quick Qt6::Xml Qt6::Network PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Iconv::Iconv) +set_tests_properties(AppCoordinatorTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") + add_asteria_test(ReadingPreferencesTest tests/state/ReadingPreferencesTest.cpp src/backend/AppState.cpp src/backend/state/ReadingPreferences.cpp) diff --git a/src/backend/AppCoordinator.cpp b/src/backend/AppCoordinator.cpp index 31862c7..40789e3 100644 --- a/src/backend/AppCoordinator.cpp +++ b/src/backend/AppCoordinator.cpp @@ -27,7 +27,8 @@ AppCoordinator::AppCoordinator(Book &book, , m_appState(appState) , m_settings(settings) { - connect(&m_book, &Book::willOpenNewBook, this, &AppCoordinator::onWillOpenNewBook); + connect(&m_book, &Book::willOpenNewBook, this, &AppCoordinator::snapshotOutgoingBook); + connect(&m_book, &Book::willCloseBook, this, &AppCoordinator::snapshotOutgoingBook); connect(&m_readingModel, &ReadingModel::positionSaved, this, &AppCoordinator::onPositionSaved); connect(&m_book, &Book::bookChanged, this, &AppCoordinator::onBookChanged); @@ -35,8 +36,8 @@ AppCoordinator::AppCoordinator(Book &book, this, &AppCoordinator::onAboutToQuit); } -// Before a new book open: snapshot the outgoing book's progress into the library. -void AppCoordinator::onWillOpenNewBook() +// Before closing or opening a new book: snapshot the outgoing book's progress into the library. +void AppCoordinator::snapshotOutgoingBook() { if (m_book.hasBook()) m_historyModel.addOrUpdateBook(m_book.filePath(), m_readingModel.progress()); @@ -54,6 +55,7 @@ void AppCoordinator::onBookChanged() { if (!m_book.hasBook()) { m_readingModel.setReader(nullptr); + m_uiState.setLastFilePath(QString()); return; } diff --git a/src/backend/AppCoordinator.h b/src/backend/AppCoordinator.h index 06017e6..70b39b4 100644 --- a/src/backend/AppCoordinator.h +++ b/src/backend/AppCoordinator.h @@ -26,7 +26,7 @@ public: private slots: void onBookChanged(); - void onWillOpenNewBook(); + void snapshotOutgoingBook(); void onPositionSaved(); void onAboutToQuit(); diff --git a/src/backend/book/Book.cpp b/src/backend/book/Book.cpp index 2805d16..d21bd6a 100644 --- a/src/backend/book/Book.cpp +++ b/src/backend/book/Book.cpp @@ -66,16 +66,23 @@ void Book::openImpl(const QString &filePath) if (m_reader) emit willOpenNewBook(); - close(); - - m_loading = true; - emit loadingChanged(); - - m_errorMessage.clear(); - emit errorMessageChanged(); - const int generation = ++m_openGeneration; + if (!m_loading) { + m_loading = true; + emit loadingChanged(); + } + + if (!m_errorMessage.isEmpty()) { + m_errorMessage.clear(); + emit errorMessageChanged(); + } + + if (m_reader) { + m_reader.reset(); + emit bookChanged(); + } + m_openFuture = QtConcurrent::run([this, effectivePath, generation]() { const auto reportError = [this, generation, effectivePath](const QString &err) { QMetaObject::invokeMethod(this, [this, generation, effectivePath, err]() { @@ -115,7 +122,15 @@ void Book::openImpl(const QString &filePath) void Book::close() { + ++m_openGeneration; + + if (m_loading) { + m_loading = false; + emit loadingChanged(); + } + if (!m_reader) return; + emit willCloseBook(); m_reader.reset(); emit bookChanged(); } diff --git a/src/backend/book/Book.h b/src/backend/book/Book.h index ff1bf00..4e4f1fd 100644 --- a/src/backend/book/Book.h +++ b/src/backend/book/Book.h @@ -49,6 +49,8 @@ public: signals: // Emitted just before replacing the current reader with a new one. void willOpenNewBook(); + // Emitted just before closing the current reader. + void willCloseBook(); void bookChanged(); void loadingChanged(); diff --git a/src/qml/Main.qml b/src/qml/Main.qml index 7e5ece9..b68e353 100644 --- a/src/qml/Main.qml +++ b/src/qml/Main.qml @@ -57,17 +57,22 @@ ApplicationWindow { Connections { target: Book function onLoadingChanged() { - if (Book.loading) root._bookInitializing = true + if (Book.loading) + root._bookInitializing = true + else if (!Book.hasBook) + root._bookInitializing = false } function onErrorMessageChanged() { if (Book.errorMessage !== "") { root._bookInitializing = false root._startupRestore = false UiState.barsVisible = true + if (!Book.hasBook && root.currentPage === "reader") + root.currentPage = "history" } } function onBookChanged() { - if (!Book.hasBook) { + if (!Book.hasBook && !Book.loading) { UiState.barsVisible = true if (root.currentPage === "reader") root.currentPage = "history" @@ -106,15 +111,16 @@ ApplicationWindow { root.settingsOpen = true } else { root.settingsOpen = false + if (root.currentPage === "reader" && ReadingModel.isTextMode && readerPage.scrollView) + readerPage.scrollView.syncScrollPosition() + if (Book.hasBook || Book.loading) + Book.close() root.currentPage = page } } onOpenFile: { Book.browseAndOpen() } - onCloseBook: { - Book.close() - } } Column { @@ -201,16 +207,8 @@ ApplicationWindow { function onRestoreReady(chunkIndex) { if (!Book.hasBook) return root._bookInitializing = false - if (root._startupRestore) { - root._startupRestore = false - const savedPage = UiState.lastPage - if (savedPage === "history") - root.currentPage = savedPage - else - root.currentPage = "reader" - } else { - root.currentPage = "reader" - } + root._startupRestore = false + root.currentPage = "reader" } } diff --git a/src/qml/components/MangaPageView.qml b/src/qml/components/MangaPageView.qml index 9a25dcb..a950aa8 100644 --- a/src/qml/components/MangaPageView.qml +++ b/src/qml/components/MangaPageView.qml @@ -213,10 +213,20 @@ Rectangle { } } + function resetViewState() { + clickDebounce.stop() + root.contentReady = false + pageArea.pair = [] + root.currentPair = 0 + } + Connections { target: Book function onLoadingChanged() { - if (Book.loading) root.contentReady = false + if (Book.loading) root.resetViewState() + } + function onBookChanged() { + if (!Book.hasBook) root.resetViewState() } } } diff --git a/src/qml/components/ScrollPageView.qml b/src/qml/components/ScrollPageView.qml index ed9dbe0..0225df5 100644 --- a/src/qml/components/ScrollPageView.qml +++ b/src/qml/components/ScrollPageView.qml @@ -241,12 +241,23 @@ Rectangle { } } + function resetViewState() { + restoreTimer.stop(); + scrollAnimation.stop(); + root.contentReady = false; + root.restoreReady = false; + } + Connections { target: Book function onLoadingChanged() { if (Book.loading) { - root.contentReady = false; - root.restoreReady = false; + root.resetViewState(); + } + } + function onBookChanged() { + if (!Book.hasBook) { + root.resetViewState(); } } } diff --git a/src/qml/components/SideBar.qml b/src/qml/components/SideBar.qml index e973d2f..dca72a0 100644 --- a/src/qml/components/SideBar.qml +++ b/src/qml/components/SideBar.qml @@ -9,7 +9,6 @@ Rectangle { signal closeDrawer() signal navigateTo(string page) signal openFile() - signal closeBook() width: root.sidebarOpen ? ThemeManager.sidebarWidth : 0 clip: true @@ -53,13 +52,6 @@ Rectangle { y: ThemeManager.headerHeight width: ThemeManager.sidebarWidth - SideBarButton { - visible: Book.hasBook - iconText: "\ue86d" - title: "Book" - onClicked: root.navigateTo("reader") - } - SideBarButton { iconText: "\ue02f" title: "History" @@ -72,13 +64,6 @@ Rectangle { onClicked: root.openFile() } - SideBarButton { - visible: Book.hasBook - iconText: "\ue5cd" - title: "Close Book" - onClicked: root.closeBook() - } - // Divider Rectangle { width: parent.width diff --git a/tests/AppCoordinatorTest.cpp b/tests/AppCoordinatorTest.cpp new file mode 100644 index 0000000..844afd2 --- /dev/null +++ b/tests/AppCoordinatorTest.cpp @@ -0,0 +1,134 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "backend/AppCoordinator.h" +#include "backend/AppState.h" +#include "backend/HistoryModel.h" +#include "backend/IFileDialogService.h" +#include "backend/ReadingModel.h" +#include "backend/book/Book.h" +#include "backend/formats/FormatRegistry.h" +#include "backend/formats/sources/DirByteSource.h" +#include "backend/state/BookPositionStore.h" +#include "backend/state/ReadingPreferences.h" +#include "backend/state/UiState.h" + +class FakeDialogService : public IFileDialogService { + Q_OBJECT +public: + explicit FakeDialogService(QObject *parent = nullptr) : IFileDialogService(parent) {} + void open(const QStringList &) override {} +}; + +class AppCoordinatorTest : public QObject { + Q_OBJECT + +private: + static QString createSampleComic(QTemporaryDir &tmp, int pages = 4) + { + if (!tmp.isValid()) return {}; + for (int i = 1; i <= pages; ++i) { + QImage img(8, 8, QImage::Format_RGB888); + img.fill(Qt::blue); + img.save(tmp.filePath(QStringLiteral("page%1.png").arg(i, 2, 10, QLatin1Char('0'))), "PNG"); + } + return tmp.path(); + } + + struct Ctx { + QTemporaryFile settingsFile; + std::unique_ptr settings; + std::unique_ptr appState; + std::unique_ptr prefs; + std::unique_ptr uiState; + std::unique_ptr positions; + std::unique_ptr registry; + std::unique_ptr history; + std::unique_ptr dialog; + std::unique_ptr book; + std::unique_ptr readingModel; + std::unique_ptr coordinator; + + Ctx() + { + settingsFile.setFileTemplate(QDir::tempPath() + QStringLiteral("/coord-XXXXXX.ini")); + (void)settingsFile.open(); + settingsFile.close(); + + settings = std::make_unique(settingsFile.fileName(), QSettings::IniFormat); + appState = std::make_unique(*settings); + prefs = std::make_unique(*appState); + uiState = std::make_unique(*appState); + positions = std::make_unique(*appState); + registry = std::make_unique(QList{ + FormatSpec::comic({}, /*matchesDirectory=*/true, QStringLiteral("dir"), + [] { return std::make_unique(); }), + FormatSpec::txt(QStringLiteral("txt")), + }); + history = std::make_unique(*registry); + dialog = std::make_unique(); + book = std::make_unique(*dialog, *registry); + readingModel = std::make_unique(*positions); + coordinator = std::make_unique( + *book, *readingModel, *history, *uiState, *prefs, *appState, *settings); + } + }; + +private slots: + void closeBookSnapshotsHistoryAndClearsLastFilePath() + { + QTemporaryDir tmp; + const QString path = createSampleComic(tmp); + QVERIFY(!path.isEmpty()); + + Ctx ctx; + ctx.book->openFromPath(path); + QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000); + + QCOMPARE(ctx.uiState->lastFilePath(), path); + QCOMPARE(ctx.history->rowCount(), 1); + + ctx.readingModel->setScrollInfo(2, 0.75); + ctx.book->close(); + + QVERIFY(!ctx.book->hasBook()); + QCOMPARE(ctx.uiState->lastFilePath(), QString()); + QCOMPARE(ctx.readingModel->progress(), 0.0); + QCOMPARE(ctx.readingModel->totalPages(), 0); + QCOMPARE(ctx.history->rowCount(), 1); + QCOMPARE(ctx.history->filePath(0), path); + QVERIFY(qFuzzyCompare(ctx.history->progress(0), 0.75)); + } + + void openingNewBookSnapshotsPreviousAndSwitchesLastFilePath() + { + QTemporaryDir tmp1; + QTemporaryDir tmp2; + const QString path1 = createSampleComic(tmp1); + const QString path2 = createSampleComic(tmp2); + QVERIFY(!path1.isEmpty()); + QVERIFY(!path2.isEmpty()); + + Ctx ctx; + ctx.book->openFromPath(path1); + QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000); + ctx.readingModel->setScrollInfo(1, 0.5); + + ctx.book->openFromPath(path2); + QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook() && ctx.book->filePath() == path2, 5000); + + QCOMPARE(ctx.uiState->lastFilePath(), path2); + QCOMPARE(ctx.history->rowCount(), 2); + QCOMPARE(ctx.history->filePath(0), path2); + QCOMPARE(ctx.history->filePath(1), path1); + QVERIFY(qFuzzyCompare(ctx.history->progress(1), 0.5)); + } +}; + +QTEST_MAIN(AppCoordinatorTest) +#include "AppCoordinatorTest.moc" diff --git a/tests/book/BookTest.cpp b/tests/book/BookTest.cpp index 765caec..76abf55 100644 --- a/tests/book/BookTest.cpp +++ b/tests/book/BookTest.cpp @@ -127,6 +127,82 @@ private slots: QCOMPARE(bookChanged.count(), 1); } + void closeBookEmitsWillCloseBookBeforeReset() + { + QTemporaryDir tmp; + const QString path = createSampleComic(tmp); + QVERIFY(!path.isEmpty()); + + Ctx ctx; + ctx.book->openFromPath(path); + QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000); + + bool hadBookDuringWillClose = false; + QString filePathDuringWillClose; + connect(ctx.book, &Book::willCloseBook, this, [&]() { + hadBookDuringWillClose = ctx.book->hasBook(); + filePathDuringWillClose = ctx.book->filePath(); + }); + + QSignalSpy willClose(ctx.book, &Book::willCloseBook); + ctx.book->close(); + + QCOMPARE(willClose.count(), 1); + QVERIFY(hadBookDuringWillClose); + QCOMPARE(filePathDuringWillClose, path); + QVERIFY(!ctx.book->hasBook()); + + // Closing again when already closed is a no-op. + ctx.book->close(); + QCOMPARE(willClose.count(), 1); + } + + void closeBookCancelsInFlightOpen() + { + QTemporaryDir tmp; + const QString path = createSampleComic(tmp); + QVERIFY(!path.isEmpty()); + + Ctx ctx; + QSignalSpy bookChanged(ctx.book, &Book::bookChanged); + ctx.book->openFromPath(path); + QVERIFY(ctx.book->loading()); + + ctx.book->close(); + QVERIFY(!ctx.book->loading()); + QVERIFY(!ctx.book->hasBook()); + + // Give the background thread time to finish; cancelled load must not install the reader. + QTest::qWait(200); + QCoreApplication::processEvents(); + QVERIFY(!ctx.book->hasBook()); + QVERIFY(!ctx.book->loading()); + QCOMPARE(bookChanged.count(), 0); + } + + void openNewBookSetsLoadingBeforeClosingPrevious() + { + QTemporaryDir tmp; + const QString path = createSampleComic(tmp); + QVERIFY(!path.isEmpty()); + + Ctx ctx; + ctx.book->openFromPath(path); + QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000); + + bool wasLoadingWhenOldBookCleared = false; + connect(ctx.book, &Book::bookChanged, this, [&]() { + if (!ctx.book->hasBook()) + wasLoadingWhenOldBookCleared = ctx.book->loading(); + }); + + QSignalSpy willOpen(ctx.book, &Book::willOpenNewBook); + ctx.book->openFromPath(path); + QCOMPARE(willOpen.count(), 1); + QVERIFY(wasLoadingWhenOldBookCleared); + QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000); + } + void willOpenNewBookFiredBeforeSwap() { QTemporaryDir tmp;