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.
This commit is contained in:
Agel committed 2026-11-13 09:45:09 +01:00
1 parent 5940d86ed2
commit 5d96fbb0bb
12 files changed
+300 -46

No files matched your search

+2 -1
View File
@@ -231,7 +231,7 @@ public:
## Position Restoration & State Persistence ## 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. - **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. - **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**: - **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`. - 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))`. - Comic mode: `restoreReady(chunkIndex)` triggers `MangaPageView.showPair(pairIndexForChunk(chunkIndex))`.
@@ -339,6 +339,7 @@ src/
specs/ specs/
knuth-plass-rendering.allium knuth-plass-rendering.allium
tests/ tests/
AppCoordinatorTest.cpp
AppStateTest.cpp AppStateTest.cpp
EntryImageProviderTest.cpp EntryImageProviderTest.cpp
FileIconProviderTest.cpp FileIconProviderTest.cpp
+20
View File
@@ -438,6 +438,26 @@ set_tests_properties(TxtReaderTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offsc
add_asteria_test(AppStateTest tests/AppStateTest.cpp add_asteria_test(AppStateTest tests/AppStateTest.cpp
src/backend/AppState.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 add_asteria_test(ReadingPreferencesTest tests/state/ReadingPreferencesTest.cpp
src/backend/AppState.cpp src/backend/AppState.cpp
src/backend/state/ReadingPreferences.cpp) src/backend/state/ReadingPreferences.cpp)
+5 -3
View File
@@ -27,7 +27,8 @@ AppCoordinator::AppCoordinator(Book &book,
, m_appState(appState) , m_appState(appState)
, m_settings(settings) , 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_readingModel, &ReadingModel::positionSaved, this, &AppCoordinator::onPositionSaved);
connect(&m_book, &Book::bookChanged, this, &AppCoordinator::onBookChanged); connect(&m_book, &Book::bookChanged, this, &AppCoordinator::onBookChanged);
@@ -35,8 +36,8 @@ AppCoordinator::AppCoordinator(Book &book,
this, &AppCoordinator::onAboutToQuit); this, &AppCoordinator::onAboutToQuit);
} }
// Before a new book open: snapshot the outgoing book's progress into the library. // Before closing or opening a new book: snapshot the outgoing book's progress into the library.
void AppCoordinator::onWillOpenNewBook() void AppCoordinator::snapshotOutgoingBook()
{ {
if (m_book.hasBook()) if (m_book.hasBook())
m_historyModel.addOrUpdateBook(m_book.filePath(), m_readingModel.progress()); m_historyModel.addOrUpdateBook(m_book.filePath(), m_readingModel.progress());
@@ -54,6 +55,7 @@ void AppCoordinator::onBookChanged()
{ {
if (!m_book.hasBook()) { if (!m_book.hasBook()) {
m_readingModel.setReader(nullptr); m_readingModel.setReader(nullptr);
m_uiState.setLastFilePath(QString());
return; return;
} }
+1 -1
View File
@@ -26,7 +26,7 @@ public:
private slots: private slots:
void onBookChanged(); void onBookChanged();
void onWillOpenNewBook(); void snapshotOutgoingBook();
void onPositionSaved(); void onPositionSaved();
void onAboutToQuit(); void onAboutToQuit();
+23 -8
View File
@@ -66,16 +66,23 @@ void Book::openImpl(const QString &filePath)
if (m_reader) if (m_reader)
emit willOpenNewBook(); emit willOpenNewBook();
close();
m_loading = true;
emit loadingChanged();
m_errorMessage.clear();
emit errorMessageChanged();
const int generation = ++m_openGeneration; 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]() { m_openFuture = QtConcurrent::run([this, effectivePath, generation]() {
const auto reportError = [this, generation, effectivePath](const QString &err) { const auto reportError = [this, generation, effectivePath](const QString &err) {
QMetaObject::invokeMethod(this, [this, generation, effectivePath, err]() { QMetaObject::invokeMethod(this, [this, generation, effectivePath, err]() {
@@ -115,7 +122,15 @@ void Book::openImpl(const QString &filePath)
void Book::close() void Book::close()
{ {
++m_openGeneration;
if (m_loading) {
m_loading = false;
emit loadingChanged();
}
if (!m_reader) return; if (!m_reader) return;
emit willCloseBook();
m_reader.reset(); m_reader.reset();
emit bookChanged(); emit bookChanged();
} }
+2
View File
@@ -49,6 +49,8 @@ public:
signals: signals:
// Emitted just before replacing the current reader with a new one. // Emitted just before replacing the current reader with a new one.
void willOpenNewBook(); void willOpenNewBook();
// Emitted just before closing the current reader.
void willCloseBook();
void bookChanged(); void bookChanged();
void loadingChanged(); void loadingChanged();
+13 -15
View File
@@ -57,17 +57,22 @@ ApplicationWindow {
Connections { Connections {
target: Book target: Book
function onLoadingChanged() { function onLoadingChanged() {
if (Book.loading) root._bookInitializing = true if (Book.loading)
root._bookInitializing = true
else if (!Book.hasBook)
root._bookInitializing = false
} }
function onErrorMessageChanged() { function onErrorMessageChanged() {
if (Book.errorMessage !== "") { if (Book.errorMessage !== "") {
root._bookInitializing = false root._bookInitializing = false
root._startupRestore = false root._startupRestore = false
UiState.barsVisible = true UiState.barsVisible = true
if (!Book.hasBook && root.currentPage === "reader")
root.currentPage = "history"
} }
} }
function onBookChanged() { function onBookChanged() {
if (!Book.hasBook) { if (!Book.hasBook && !Book.loading) {
UiState.barsVisible = true UiState.barsVisible = true
if (root.currentPage === "reader") if (root.currentPage === "reader")
root.currentPage = "history" root.currentPage = "history"
@@ -106,15 +111,16 @@ ApplicationWindow {
root.settingsOpen = true root.settingsOpen = true
} else { } else {
root.settingsOpen = false root.settingsOpen = false
if (root.currentPage === "reader" && ReadingModel.isTextMode && readerPage.scrollView)
readerPage.scrollView.syncScrollPosition()
if (Book.hasBook || Book.loading)
Book.close()
root.currentPage = page root.currentPage = page
} }
} }
onOpenFile: { onOpenFile: {
Book.browseAndOpen() Book.browseAndOpen()
} }
onCloseBook: {
Book.close()
}
} }
Column { Column {
@@ -201,16 +207,8 @@ ApplicationWindow {
function onRestoreReady(chunkIndex) { function onRestoreReady(chunkIndex) {
if (!Book.hasBook) return if (!Book.hasBook) return
root._bookInitializing = false root._bookInitializing = false
if (root._startupRestore) { root._startupRestore = false
root._startupRestore = false root.currentPage = "reader"
const savedPage = UiState.lastPage
if (savedPage === "history")
root.currentPage = savedPage
else
root.currentPage = "reader"
} else {
root.currentPage = "reader"
}
} }
} }
+11 -1
View File
@@ -213,10 +213,20 @@ Rectangle {
} }
} }
function resetViewState() {
clickDebounce.stop()
root.contentReady = false
pageArea.pair = []
root.currentPair = 0
}
Connections { Connections {
target: Book target: Book
function onLoadingChanged() { function onLoadingChanged() {
if (Book.loading) root.contentReady = false if (Book.loading) root.resetViewState()
}
function onBookChanged() {
if (!Book.hasBook) root.resetViewState()
} }
} }
} }
+13 -2
View File
@@ -241,12 +241,23 @@ Rectangle {
} }
} }
function resetViewState() {
restoreTimer.stop();
scrollAnimation.stop();
root.contentReady = false;
root.restoreReady = false;
}
Connections { Connections {
target: Book target: Book
function onLoadingChanged() { function onLoadingChanged() {
if (Book.loading) { if (Book.loading) {
root.contentReady = false; root.resetViewState();
root.restoreReady = false; }
}
function onBookChanged() {
if (!Book.hasBook) {
root.resetViewState();
} }
} }
} }
-15
View File
@@ -9,7 +9,6 @@ Rectangle {
signal closeDrawer() signal closeDrawer()
signal navigateTo(string page) signal navigateTo(string page)
signal openFile() signal openFile()
signal closeBook()
width: root.sidebarOpen ? ThemeManager.sidebarWidth : 0 width: root.sidebarOpen ? ThemeManager.sidebarWidth : 0
clip: true clip: true
@@ -53,13 +52,6 @@ Rectangle {
y: ThemeManager.headerHeight y: ThemeManager.headerHeight
width: ThemeManager.sidebarWidth width: ThemeManager.sidebarWidth
SideBarButton {
visible: Book.hasBook
iconText: "\ue86d"
title: "Book"
onClicked: root.navigateTo("reader")
}
SideBarButton { SideBarButton {
iconText: "\ue02f" iconText: "\ue02f"
title: "History" title: "History"
@@ -72,13 +64,6 @@ Rectangle {
onClicked: root.openFile() onClicked: root.openFile()
} }
SideBarButton {
visible: Book.hasBook
iconText: "\ue5cd"
title: "Close Book"
onClicked: root.closeBook()
}
// Divider // Divider
Rectangle { Rectangle {
width: parent.width width: parent.width
+134
View File
@@ -0,0 +1,134 @@
#include <QtTest>
#include <QDir>
#include <QFile>
#include <QImage>
#include <QSettings>
#include <QTemporaryDir>
#include <QTemporaryFile>
#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<QSettings> settings;
std::unique_ptr<AppState> appState;
std::unique_ptr<ReadingPreferences> prefs;
std::unique_ptr<UiState> uiState;
std::unique_ptr<BookPositionStore> positions;
std::unique_ptr<FormatRegistry> registry;
std::unique_ptr<HistoryModel> history;
std::unique_ptr<FakeDialogService> dialog;
std::unique_ptr<Book> book;
std::unique_ptr<ReadingModel> readingModel;
std::unique_ptr<AppCoordinator> coordinator;
Ctx()
{
settingsFile.setFileTemplate(QDir::tempPath() + QStringLiteral("/coord-XXXXXX.ini"));
(void)settingsFile.open();
settingsFile.close();
settings = std::make_unique<QSettings>(settingsFile.fileName(), QSettings::IniFormat);
appState = std::make_unique<AppState>(*settings);
prefs = std::make_unique<ReadingPreferences>(*appState);
uiState = std::make_unique<UiState>(*appState);
positions = std::make_unique<BookPositionStore>(*appState);
registry = std::make_unique<FormatRegistry>(QList<FormatSpec>{
FormatSpec::comic({}, /*matchesDirectory=*/true, QStringLiteral("dir"),
[] { return std::make_unique<DirByteSource>(); }),
FormatSpec::txt(QStringLiteral("txt")),
});
history = std::make_unique<HistoryModel>(*registry);
dialog = std::make_unique<FakeDialogService>();
book = std::make_unique<Book>(*dialog, *registry);
readingModel = std::make_unique<ReadingModel>(*positions);
coordinator = std::make_unique<AppCoordinator>(
*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"
+76
View File
@@ -127,6 +127,82 @@ private slots:
QCOMPARE(bookChanged.count(), 1); 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() void willOpenNewBookFiredBeforeSwap()
{ {
QTemporaryDir tmp; QTemporaryDir tmp;