add library with reading history, progress tracking, and view persistence

This commit is contained in:
Agel committed 2026-03-20 11:20:16 +01:00
1 parent c62733bc26
commit c4046d8533
15 files changed
+685 -40

No files matched your search

+3
View File
@@ -101,6 +101,7 @@ set_source_files_properties(src/qml/components/SideBarButton.qml PROPERTIES QT_R
set_source_files_properties(src/qml/pages/StarterPage.qml PROPERTIES QT_RESOURCE_ALIAS pages/StarterPage.qml)
set_source_files_properties(src/qml/pages/ReaderPage.qml PROPERTIES QT_RESOURCE_ALIAS pages/ReaderPage.qml)
set_source_files_properties(src/qml/pages/SettingsPage.qml PROPERTIES QT_RESOURCE_ALIAS pages/SettingsPage.qml)
set_source_files_properties(src/qml/pages/LibraryPage.qml PROPERTIES QT_RESOURCE_ALIAS pages/LibraryPage.qml)
# QML module
qt_policy(SET QTP0004 NEW)
@@ -120,6 +121,7 @@ qt_add_qml_module(asteria-qt
src/qml/pages/StarterPage.qml
src/qml/pages/ReaderPage.qml
src/qml/pages/SettingsPage.qml
src/qml/pages/LibraryPage.qml
RESOURCES
src/assets/moon1.svg
src/assets/MaterialIconsOutlined-Regular.otf
@@ -179,6 +181,7 @@ set_tests_properties(ReadingModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=of
add_asteria_test(BookControllerTest tests/BookControllerTest.cpp
src/backend/BookController.cpp
src/backend/AppState.cpp
src/backend/ReaderFactory.cpp
src/backend/ReadingModel.cpp
src/backend/formats/TxtReader.cpp
+123
View File
@@ -1,5 +1,13 @@
#include "AppState.h"
#include <QSettings>
#include <QCryptographicHash>
#include <QDateTime>
static QString bookSettingsKey(const QString &filePath)
{
QByteArray hash = QCryptographicHash::hash(filePath.toUtf8(), QCryptographicHash::Md5).toHex();
return QStringLiteral("bookmarks/") + QString::fromLatin1(hash);
}
AppState::AppState(QObject *parent)
: QObject(parent)
@@ -111,6 +119,117 @@ QUrl AppState::lastFileUrl() const
return QUrl::fromLocalFile(m_lastFilePath);
}
void AppState::saveBookPosition(const QString &filePath, int chapter, int scrollIndex, qreal scrollOffset)
{
QSettings s;
QString key = bookSettingsKey(filePath);
s.setValue(key + QStringLiteral("/chapter"), chapter);
s.setValue(key + QStringLiteral("/scrollIndex"), scrollIndex);
s.setValue(key + QStringLiteral("/scrollOffset"), scrollOffset);
}
QVariantMap AppState::loadBookPosition(const QString &filePath) const
{
QSettings s;
QString key = bookSettingsKey(filePath);
QVariantMap result;
result[QStringLiteral("chapter")] = s.value(key + QStringLiteral("/chapter"), 0).toInt();
result[QStringLiteral("scrollIndex")] = s.value(key + QStringLiteral("/scrollIndex"), 0).toInt();
result[QStringLiteral("scrollOffset")] = s.value(key + QStringLiteral("/scrollOffset"), 0.0).toDouble();
return result;
}
QString AppState::lastPage() const { return m_lastPage; }
void AppState::setLastPage(const QString &page)
{
if (m_lastPage == page)
return;
m_lastPage = page;
emit lastPageChanged();
}
void AppState::addOrUpdateLibraryBook(const QString &filePath, const QString &title, const QString &author, double progress)
{
QString lastOpened = QDateTime::currentDateTime().toString(Qt::ISODate);
for (int i = 0; i < m_libraryBooks.size(); i++) {
QVariantMap book = m_libraryBooks[i].toMap();
if (book[QStringLiteral("filePath")].toString() == filePath) {
book[QStringLiteral("title")] = title;
book[QStringLiteral("author")] = author;
book[QStringLiteral("lastOpened")] = lastOpened;
if (progress >= 0.0)
book[QStringLiteral("progress")] = progress;
m_libraryBooks[i] = book;
// Move to front (most recently opened)
m_libraryBooks.move(i, 0);
saveLibraryBooks();
emit libraryBooksChanged();
return;
}
}
QVariantMap newBook;
newBook[QStringLiteral("filePath")] = filePath;
newBook[QStringLiteral("title")] = title;
newBook[QStringLiteral("author")] = author;
newBook[QStringLiteral("progress")] = qMax(progress, 0.0);
newBook[QStringLiteral("lastOpened")] = lastOpened;
m_libraryBooks.prepend(newBook);
saveLibraryBooks();
emit libraryBooksChanged();
}
void AppState::removeLibraryBook(const QString &filePath)
{
for (int i = 0; i < m_libraryBooks.size(); i++) {
if (m_libraryBooks[i].toMap()[QStringLiteral("filePath")].toString() == filePath) {
m_libraryBooks.removeAt(i);
saveLibraryBooks();
emit libraryBooksChanged();
return;
}
}
}
QVariantList AppState::libraryBooks() const
{
return m_libraryBooks;
}
void AppState::loadLibraryBooks()
{
QSettings s;
int size = s.beginReadArray(QStringLiteral("library"));
m_libraryBooks.clear();
for (int i = 0; i < size; i++) {
s.setArrayIndex(i);
QVariantMap book;
book[QStringLiteral("filePath")] = s.value(QStringLiteral("filePath")).toString();
book[QStringLiteral("title")] = s.value(QStringLiteral("title")).toString();
book[QStringLiteral("author")] = s.value(QStringLiteral("author")).toString();
book[QStringLiteral("progress")] = s.value(QStringLiteral("progress"), 0.0).toDouble();
book[QStringLiteral("lastOpened")] = s.value(QStringLiteral("lastOpened")).toString();
m_libraryBooks.append(book);
}
s.endArray();
}
void AppState::saveLibraryBooks()
{
QSettings s;
s.beginWriteArray(QStringLiteral("library"), m_libraryBooks.size());
for (int i = 0; i < m_libraryBooks.size(); i++) {
s.setArrayIndex(i);
QVariantMap book = m_libraryBooks[i].toMap();
s.setValue(QStringLiteral("filePath"), book[QStringLiteral("filePath")]);
s.setValue(QStringLiteral("title"), book[QStringLiteral("title")]);
s.setValue(QStringLiteral("author"), book[QStringLiteral("author")]);
s.setValue(QStringLiteral("progress"), book[QStringLiteral("progress")]);
s.setValue(QStringLiteral("lastOpened"), book[QStringLiteral("lastOpened")]);
}
s.endArray();
}
void AppState::save()
{
QSettings s;
@@ -119,11 +238,13 @@ void AppState::save()
s.setValue(QStringLiteral("session/lastScrollPosition"), m_lastScrollPosition);
s.setValue(QStringLiteral("session/lastScrollIndex"), m_lastScrollIndex);
s.setValue(QStringLiteral("session/lastScrollOffset"), m_lastScrollOffset);
s.setValue(QStringLiteral("session/lastPage"), m_lastPage);
s.setValue(QStringLiteral("preferences/pageFlipMode"), m_pageFlipMode);
s.setValue(QStringLiteral("window/width"), m_windowWidth);
s.setValue(QStringLiteral("window/height"), m_windowHeight);
s.setValue(QStringLiteral("window/x"), m_windowX);
s.setValue(QStringLiteral("window/y"), m_windowY);
saveLibraryBooks();
}
void AppState::restore()
@@ -134,11 +255,13 @@ void AppState::restore()
m_lastScrollPosition = s.value(QStringLiteral("session/lastScrollPosition"), 0.0).toDouble();
m_lastScrollIndex = s.value(QStringLiteral("session/lastScrollIndex"), 0).toInt();
m_lastScrollOffset = s.value(QStringLiteral("session/lastScrollOffset"), 0.0).toDouble();
m_lastPage = s.value(QStringLiteral("session/lastPage"), QStringLiteral("starter")).toString();
m_pageFlipMode = s.value(QStringLiteral("preferences/pageFlipMode"), QStringLiteral("scroll")).toString();
m_windowWidth = s.value(QStringLiteral("window/width"), 1024).toInt();
m_windowHeight = s.value(QStringLiteral("window/height"), 768).toInt();
m_windowX = s.value(QStringLiteral("window/x"), -1).toInt();
m_windowY = s.value(QStringLiteral("window/y"), -1).toInt();
loadLibraryBooks();
emit stateRestored();
}
+20
View File
@@ -4,6 +4,8 @@
#include <QObject>
#include <QString>
#include <QUrl>
#include <QVariantMap>
#include <QVariantList>
class AppState : public QObject {
Q_OBJECT
@@ -17,6 +19,8 @@ class AppState : public QObject {
Q_PROPERTY(int windowHeight READ windowHeight WRITE setWindowHeight NOTIFY windowHeightChanged)
Q_PROPERTY(int windowX READ windowX WRITE setWindowX NOTIFY windowXChanged)
Q_PROPERTY(int windowY READ windowY WRITE setWindowY NOTIFY windowYChanged)
Q_PROPERTY(QVariantList libraryBooks READ libraryBooks NOTIFY libraryBooksChanged)
Q_PROPERTY(QString lastPage READ lastPage WRITE setLastPage NOTIFY lastPageChanged)
public:
explicit AppState(QObject *parent = nullptr);
@@ -53,6 +57,16 @@ public:
Q_INVOKABLE QUrl lastFileUrl() const;
Q_INVOKABLE void saveBookPosition(const QString &filePath, int chapter, int scrollIndex, qreal scrollOffset);
Q_INVOKABLE QVariantMap loadBookPosition(const QString &filePath) const;
QString lastPage() const;
void setLastPage(const QString &page);
Q_INVOKABLE void addOrUpdateLibraryBook(const QString &filePath, const QString &title, const QString &author, double progress);
Q_INVOKABLE void removeLibraryBook(const QString &filePath);
Q_INVOKABLE QVariantList libraryBooks() const;
Q_INVOKABLE void save();
Q_INVOKABLE void restore();
@@ -68,8 +82,12 @@ signals:
void windowHeightChanged();
void windowXChanged();
void windowYChanged();
void libraryBooksChanged();
void lastPageChanged();
private:
void loadLibraryBooks();
void saveLibraryBooks();
QString m_lastFilePath;
int m_lastChapter = 0;
qreal m_lastScrollPosition = 0.0;
@@ -80,6 +98,8 @@ private:
int m_windowHeight = 768;
int m_windowX = -1;
int m_windowY = -1;
QVariantList m_libraryBooks;
QString m_lastPage = QStringLiteral("starter");
};
#endif // APPSTATE_H
+41
View File
@@ -1,4 +1,5 @@
#include "BookController.h"
#include "AppState.h"
#include "ReaderFactory.h"
#include "ReadingModel.h"
#include <QFileDialog>
@@ -114,10 +115,31 @@ void BookController::setReadingModel(ReadingModel *model)
m_readingModel = model;
}
void BookController::setAppState(AppState *state)
{
m_appState = state;
}
void BookController::openBookFromPath(const QString &filePath)
{
openBook(QUrl::fromLocalFile(filePath));
}
void BookController::openBook(const QUrl &fileUrl)
{
QString filePath = fileUrl.toLocalFile();
if (m_reader && m_appState && m_readingModel) {
m_appState->saveBookPosition(m_currentFilePath,
m_readingModel->currentChapter(),
m_appState->lastScrollIndex(),
m_appState->lastScrollOffset());
m_appState->addOrUpdateLibraryBook(m_currentFilePath, m_bookTitle, m_bookAuthor,
m_readingModel->progress());
}
if (m_reader)
closeBook();
m_loading = true;
emit loadingChanged();
@@ -151,6 +173,9 @@ void BookController::openBook(const QUrl &fileUrl)
if (m_readingModel)
m_readingModel->setReader(m_reader.get());
if (m_appState)
m_appState->addOrUpdateLibraryBook(m_currentFilePath, m_bookTitle, m_bookAuthor, -1.0);
m_loading = false;
emit loadingChanged();
emit bookChanged();
@@ -278,6 +303,14 @@ void BookController::browseAndOpenFallback()
void BookController::closeBook()
{
if (m_reader && m_appState && m_readingModel && !m_currentFilePath.isEmpty()) {
m_appState->saveBookPosition(m_currentFilePath,
m_readingModel->currentChapter(),
m_appState->lastScrollIndex(),
m_appState->lastScrollOffset());
m_appState->addOrUpdateLibraryBook(m_currentFilePath, m_bookTitle, m_bookAuthor,
m_readingModel->progress());
}
m_reader.reset();
m_bookTitle.clear();
m_bookAuthor.clear();
@@ -288,3 +321,11 @@ void BookController::closeBook()
emit bookChanged();
}
void BookController::clearError()
{
if (m_errorMessage.isEmpty())
return;
m_errorMessage.clear();
emit errorMessageChanged();
}
+5
View File
@@ -9,6 +9,7 @@
#include "FormatReader.h"
class AppState;
class ReadingModel;
class BookController : public QObject {
@@ -33,10 +34,13 @@ public:
QString currentFilePath() const;
void setReadingModel(ReadingModel *model);
void setAppState(AppState *state);
Q_INVOKABLE void openBook(const QUrl &fileUrl);
Q_INVOKABLE void openBookFromPath(const QString &filePath);
Q_INVOKABLE void browseAndOpen();
Q_INVOKABLE void closeBook();
Q_INVOKABLE void clearError();
signals:
void bookReady();
@@ -55,6 +59,7 @@ private:
std::unique_ptr<FormatReader> m_reader;
ReadingModel *m_readingModel = nullptr;
AppState *m_appState = nullptr;
QString m_bookTitle;
QString m_bookAuthor;
QString m_currentFilePath;
+4 -1
View File
@@ -58,7 +58,10 @@ double ReadingModel::progress() const
{
if (m_totalChapters == 0)
return 0.0;
return static_cast<double>(m_currentChapter + 1) / m_totalChapters;
double chapterFraction = 0.0;
if (m_totalContentHeight > 0)
chapterFraction = qBound(0.0, m_absoluteScrollY / m_totalContentHeight, 1.0);
return (m_currentChapter + chapterFraction) / m_totalChapters;
}
int ReadingModel::currentPage() const
+11
View File
@@ -31,6 +31,7 @@ int main(int argc, char *argv[])
AppState appState;
appState.restore();
bookController.setAppState(&appState);
QQmlApplicationEngine engine;
@@ -48,6 +49,16 @@ int main(int argc, char *argv[])
if (bookController.hasBook()) {
appState.setLastFilePath(bookController.currentFilePath());
appState.setLastChapter(readingModel.currentChapter());
appState.saveBookPosition(bookController.currentFilePath(),
readingModel.currentChapter(),
appState.lastScrollIndex(),
appState.lastScrollOffset());
appState.addOrUpdateLibraryBook(bookController.currentFilePath(),
bookController.bookTitle(),
bookController.bookAuthor(),
readingModel.progress());
} else {
appState.setLastFilePath(QString());
}
appState.save();
});
+20 -1
View File
@@ -19,6 +19,8 @@ ApplicationWindow {
property string currentPage: "starter"
property string pageFlipMode: appState.pageFlipMode
onCurrentPageChanged: appState.lastPage = currentPage
Component.onCompleted: {
width = appState.windowWidth
height = appState.windowHeight
@@ -28,6 +30,9 @@ ApplicationWindow {
}
if (appState.lastFilePath !== "")
bookController.openBook(appState.lastFileUrl())
var savedPage = appState.lastPage
if (savedPage === "library" || savedPage === "settings")
window.currentPage = savedPage
}
Timer {
@@ -57,10 +62,15 @@ ApplicationWindow {
onCloseDrawer: window.sidebarOpen = false
onNavigateTo: function(page) {
window.currentPage = page
window.sidebarOpen = false
}
onOpenFile: {
bookController.browseAndOpen()
}
onCloseBook: {
bookController.closeBook()
window.sidebarOpen = false
}
}
Column {
@@ -82,7 +92,7 @@ ApplicationWindow {
StarterPage {
anchors.fill: parent
visible: window.currentPage !== "reader" && window.currentPage !== "settings"
visible: window.currentPage === "starter"
}
ReaderPage {
@@ -94,6 +104,11 @@ ApplicationWindow {
anchors.fill: parent
visible: window.currentPage === "settings"
}
LibraryPage {
anchors.fill: parent
visible: window.currentPage === "library"
}
}
Loader {
@@ -115,5 +130,9 @@ ApplicationWindow {
function onBookReady() {
window.currentPage = "reader"
}
function onBookChanged() {
if (!bookController.hasBook && window.currentPage === "reader")
window.currentPage = "starter"
}
}
}
+39 -24
View File
@@ -12,36 +12,51 @@ Rectangle {
onClicked: {} // Block clicks through overlay
}
Column {
Rectangle {
anchors.centerIn: parent
spacing: 20
width: Math.min(overlay.width * 0.7, 440)
height: dialogColumn.implicitHeight + 48
color: Theme.surface
radius: 8
Text {
anchors.horizontalCenter: parent.horizontalCenter
text: bookController.errorMessage
font.pixelSize: 15
color: Theme.readingText
horizontalAlignment: Text.AlignHCenter
wrapMode: Text.Wrap
width: Math.min(overlay.width * 0.6, 400)
}
Column {
id: dialogColumn
anchors {
top: parent.top
left: parent.left
right: parent.right
topMargin: 24
leftMargin: 24
rightMargin: 24
}
spacing: 20
Button {
anchors.horizontalCenter: parent.horizontalCenter
text: "Ok"
contentItem: Text {
text: parent.text
font.pixelSize: 14
color: "#ffffff"
Text {
width: parent.width
text: bookController.errorMessage
font.pixelSize: 15
color: Theme.readingText
horizontalAlignment: Text.AlignHCenter
wrapMode: Text.Wrap
}
background: Rectangle {
implicitWidth: 80
implicitHeight: 36
radius: 4
color: parent.hovered ? Qt.lighter(Theme.primaryAccent, 1.15) : Theme.primaryAccent
Button {
anchors.horizontalCenter: parent.horizontalCenter
text: "Ok"
contentItem: Text {
text: parent.text
font.pixelSize: 14
color: "#ffffff"
horizontalAlignment: Text.AlignHCenter
}
background: Rectangle {
implicitWidth: 80
implicitHeight: 36
radius: 4
color: parent.hovered ? Qt.lighter(Theme.primaryAccent, 1.15) : Theme.primaryAccent
}
onClicked: bookController.clearError()
}
onClicked: bookController.errorMessage = ""
}
}
}
+17 -10
View File
@@ -77,23 +77,30 @@ Rectangle {
var idx = chunkListView.indexAt(0, chunkListView.contentY)
appState.lastScrollIndex = idx
var item = chunkListView.itemAtIndex(idx)
appState.lastScrollOffset = item ? chunkListView.contentY - item.y : 0
var offset = item ? chunkListView.contentY - item.y : 0
appState.lastScrollOffset = offset
appState.lastScrollPosition = chunkListView.contentY
if (bookController.hasBook)
appState.saveBookPosition(bookController.currentFilePath,
readingModel.currentChapter, idx, offset)
}
}
Connections {
target: bookController
function onBookReady() {
if (bookController.currentFilePath === appState.lastFilePath) {
readingModel.goToChapter(appState.lastChapter)
if (appState.lastScrollIndex > 0)
Qt.callLater(function() {
chunkListView.positionViewAtIndex(
appState.lastScrollIndex, ListView.Beginning)
chunkListView.contentY += appState.lastScrollOffset
})
}
var pos = appState.loadBookPosition(bookController.currentFilePath)
var savedChapter = pos["chapter"]
var savedScrollIndex = pos["scrollIndex"]
var savedScrollOffset = pos["scrollOffset"]
if (savedChapter > 0)
readingModel.goToChapter(savedChapter)
if (savedScrollIndex > 0)
Qt.callLater(function() {
chunkListView.positionViewAtIndex(savedScrollIndex, ListView.Beginning)
chunkListView.contentY += savedScrollOffset
})
Qt.callLater(function() {
readingModel.setViewportSize(chunkListView.width, chunkListView.height)
})
+14
View File
@@ -13,6 +13,7 @@ Rectangle {
signal closeDrawer()
signal navigateTo(string page)
signal openFile()
signal closeBook()
Behavior on width {
NumberAnimation {
@@ -59,12 +60,25 @@ Rectangle {
onClicked: sidebar.navigateTo("reader")
}
SideBarButton {
iconText: "\ue02f"
title: "Library"
onClicked: sidebar.navigateTo("library")
}
SideBarButton {
iconText: "\ue30a"
title: "Files"
onClicked: sidebar.openFile()
}
SideBarButton {
visible: bookController.hasBook
iconText: "\ue5cd"
title: "Close Book"
onClicked: sidebar.closeBook()
}
// Divider
Rectangle {
width: parent.width
+96
View File
@@ -0,0 +1,96 @@
import QtQuick
import QtQuick.Controls
import Asteria
Rectangle {
color: Theme.backgroundDefault
Text {
visible: appState.libraryBooks.length === 0
anchors.centerIn: parent
text: "No books read yet.\nOpen a book to start your library."
horizontalAlignment: Text.AlignHCenter
color: Theme.dimText
font.pixelSize: 14
lineHeight: 1.6
}
ListView {
visible: appState.libraryBooks.length > 0
anchors.fill: parent
anchors.margins: 16
spacing: 8
clip: true
model: appState.libraryBooks
delegate: Rectangle {
id: bookRow
width: ListView.view.width
height: bookInfoCol.implicitHeight + 24
color: Theme.surface
radius: 4
Row {
anchors.fill: parent
anchors.leftMargin: 14
anchors.rightMargin: 14
anchors.topMargin: 12
anchors.bottomMargin: 12
spacing: 8
Column {
id: bookInfoCol
width: parent.width - removeBtn.width - parent.spacing
anchors.verticalCenter: parent.verticalCenter
spacing: 3
Text {
width: parent.width
text: modelData.title || "Unknown Title"
color: Theme.uiText
font.pixelSize: 14
font.bold: true
elide: Text.ElideRight
}
Text {
visible: modelData.author !== ""
width: parent.width
text: modelData.author
color: Theme.dimText
font.pixelSize: 12
elide: Text.ElideRight
}
Text {
text: Math.round(modelData.progress * 100) + "%"
color: Theme.buttonAccent
font.pixelSize: 12
}
}
Button {
id: removeBtn
anchors.verticalCenter: parent.verticalCenter
flat: true
contentItem: Text {
text: "\ue872"
font.family: "Material Icons Outlined"
font.pixelSize: 20
color: Theme.dimText
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
background: Item {}
onClicked: appState.removeLibraryBook(modelData.filePath)
}
}
MouseArea {
anchors.fill: parent
z: -1
onClicked: bookController.openBookFromPath(modelData.filePath)
}
}
}
}
+241
View File
@@ -161,6 +161,54 @@ private slots:
QCOMPARE(spyY.count(), 1);
}
void saveAndLoadBookPosition()
{
AppState state;
state.saveBookPosition(QStringLiteral("/books/a.epub"), 3, 42, 123.5);
QVariantMap pos = state.loadBookPosition(QStringLiteral("/books/a.epub"));
QCOMPARE(pos["chapter"].toInt(), 3);
QCOMPARE(pos["scrollIndex"].toInt(), 42);
QCOMPARE(pos["scrollOffset"].toDouble(), 123.5);
}
void loadBookPositionForUnknownBook()
{
AppState state;
QVariantMap pos = state.loadBookPosition(QStringLiteral("/books/unknown.epub"));
QCOMPARE(pos["chapter"].toInt(), 0);
QCOMPARE(pos["scrollIndex"].toInt(), 0);
QCOMPARE(pos["scrollOffset"].toDouble(), 0.0);
}
void saveBookPositionForMultipleBooks()
{
AppState state;
state.saveBookPosition(QStringLiteral("/books/a.epub"), 1, 10, 50.0);
state.saveBookPosition(QStringLiteral("/books/b.epub"), 5, 99, 200.5);
QVariantMap posA = state.loadBookPosition(QStringLiteral("/books/a.epub"));
QVariantMap posB = state.loadBookPosition(QStringLiteral("/books/b.epub"));
QCOMPARE(posA["chapter"].toInt(), 1);
QCOMPARE(posA["scrollIndex"].toInt(), 10);
QCOMPARE(posB["chapter"].toInt(), 5);
QCOMPARE(posB["scrollIndex"].toInt(), 99);
QCOMPARE(posB["scrollOffset"].toDouble(), 200.5);
}
void saveBookPositionOverwritesPrevious()
{
AppState state;
state.saveBookPosition(QStringLiteral("/books/a.epub"), 1, 10, 50.0);
state.saveBookPosition(QStringLiteral("/books/a.epub"), 7, 33, 88.0);
QVariantMap pos = state.loadBookPosition(QStringLiteral("/books/a.epub"));
QCOMPARE(pos["chapter"].toInt(), 7);
QCOMPARE(pos["scrollIndex"].toInt(), 33);
QCOMPARE(pos["scrollOffset"].toDouble(), 88.0);
}
void restoreEmitsSingleSignal()
{
AppState state;
@@ -191,6 +239,199 @@ private slots:
QCOMPARE(spyX.count(), 0);
QCOMPARE(spyY.count(), 0);
}
// Library tests
void saveAndRestoreLastPage()
{
{
AppState state;
state.setLastPage(QStringLiteral("library"));
state.save();
}
AppState state2;
state2.restore();
QCOMPARE(state2.lastPage(), QStringLiteral("library"));
}
void lastPageDefaultsToStarter()
{
AppState state;
QCOMPARE(state.lastPage(), QStringLiteral("starter"));
}
void libraryBooksInitiallyEmpty()
{
AppState state;
QVERIFY(state.libraryBooks().isEmpty());
}
void addLibraryBookAddsEntry()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.0);
QVariantList books = state.libraryBooks();
QCOMPARE(books.size(), 1);
QVariantMap book = books.first().toMap();
QCOMPARE(book[QStringLiteral("filePath")].toString(), QStringLiteral("/books/a.epub"));
QCOMPARE(book[QStringLiteral("title")].toString(), QStringLiteral("Title A"));
QCOMPARE(book[QStringLiteral("author")].toString(), QStringLiteral("Author A"));
QCOMPARE(book[QStringLiteral("progress")].toDouble(), 0.0);
}
void addLibraryBookPersistsThroughSaveRestore()
{
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.5);
state.save();
}
AppState state2;
state2.restore();
QVariantList books = state2.libraryBooks();
QCOMPARE(books.size(), 1);
QVariantMap book = books.first().toMap();
QCOMPARE(book[QStringLiteral("filePath")].toString(), QStringLiteral("/books/a.epub"));
QCOMPARE(book[QStringLiteral("title")].toString(), QStringLiteral("Title A"));
QCOMPARE(book[QStringLiteral("progress")].toDouble(), 0.5);
}
void addLibraryBookUpdatesMetadata()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Old Title"),
QStringLiteral("Old Author"), 0.3);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("New Title"),
QStringLiteral("New Author"), 0.3);
QVariantList books = state.libraryBooks();
QCOMPARE(books.size(), 1);
QVariantMap book = books.first().toMap();
QCOMPARE(book[QStringLiteral("title")].toString(), QStringLiteral("New Title"));
QCOMPARE(book[QStringLiteral("author")].toString(), QStringLiteral("New Author"));
}
void addLibraryBookOverwritesProgress()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.6);
// Lower value should overwrite (always update, no max logic)
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.2);
QVariantList books = state.libraryBooks();
QCOMPARE(books.size(), 1);
QCOMPARE(books.first().toMap()[QStringLiteral("progress")].toDouble(), 0.2);
}
void addLibraryBookSentinelPreservesProgress()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.5);
// -1.0 sentinel: update metadata but don't touch progress
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("New Title"),
QStringLiteral("Author A"), -1.0);
QVariantList books = state.libraryBooks();
QCOMPARE(books.size(), 1);
QVariantMap book = books.first().toMap();
QCOMPARE(book[QStringLiteral("progress")].toDouble(), 0.5);
QCOMPARE(book[QStringLiteral("title")].toString(), QStringLiteral("New Title"));
}
void addNewLibraryBookWithSentinelStartsAtZero()
{
AppState state;
// New book added with sentinel should start at 0%
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), -1.0);
QVariantList books = state.libraryBooks();
QCOMPARE(books.size(), 1);
QCOMPARE(books.first().toMap()[QStringLiteral("progress")].toDouble(), 0.0);
}
void removeLibraryBookRemovesEntry()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.5);
state.addOrUpdateLibraryBook(QStringLiteral("/books/b.epub"),
QStringLiteral("Title B"),
QStringLiteral("Author B"), 0.3);
state.removeLibraryBook(QStringLiteral("/books/a.epub"));
QVariantList books = state.libraryBooks();
QCOMPARE(books.size(), 1);
QCOMPARE(books.first().toMap()[QStringLiteral("filePath")].toString(),
QStringLiteral("/books/b.epub"));
}
void removeNonexistentLibraryBookIsNoop()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.5);
state.removeLibraryBook(QStringLiteral("/books/nonexistent.epub"));
QCOMPARE(state.libraryBooks().size(), 1);
}
void libraryBooksChangedSignalOnAdd()
{
AppState state;
QSignalSpy spy(&state, &AppState::libraryBooksChanged);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.0);
QCOMPARE(spy.count(), 1);
}
void libraryBooksChangedSignalOnRemove()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.0);
QSignalSpy spy(&state, &AppState::libraryBooksChanged);
state.removeLibraryBook(QStringLiteral("/books/a.epub"));
QCOMPARE(spy.count(), 1);
}
void multipleLibraryBooksAreStoredInOrder()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.1);
state.addOrUpdateLibraryBook(QStringLiteral("/books/b.epub"),
QStringLiteral("Title B"),
QStringLiteral("Author B"), 0.2);
QVariantList books = state.libraryBooks();
QCOMPARE(books.size(), 2);
// Most recently added/updated comes first
QCOMPARE(books.at(0).toMap()[QStringLiteral("filePath")].toString(),
QStringLiteral("/books/b.epub"));
QCOMPARE(books.at(1).toMap()[QStringLiteral("filePath")].toString(),
QStringLiteral("/books/a.epub"));
}
};
QTEST_MAIN(AppStateTest)
+47
View File
@@ -1,8 +1,10 @@
#include <QtTest>
#include <QSignalSpy>
#include <QUrl>
#include <QSettings>
#include "backend/BookController.h"
#include "backend/ReadingModel.h"
#include "backend/AppState.h"
class BookControllerTest : public QObject {
Q_OBJECT
@@ -14,6 +16,16 @@ private:
}
private slots:
void initTestCase()
{
QCoreApplication::setOrganizationName(QStringLiteral("AsteriaTest"));
QCoreApplication::setApplicationName(QStringLiteral("BookControllerTest"));
}
void cleanup()
{
QSettings().clear();
}
void openValidBook()
{
BookController ctrl;
@@ -109,6 +121,41 @@ private slots:
ctrl.closeBook();
QVERIFY(ctrl.currentFilePath().isEmpty());
}
void clearErrorResetsMessage()
{
BookController ctrl;
ctrl.openBook(QUrl::fromLocalFile("/tmp/file.xyz"));
QVERIFY(!ctrl.errorMessage().isEmpty());
QSignalSpy spy(&ctrl, &BookController::errorMessageChanged);
ctrl.clearError();
QVERIFY(ctrl.errorMessage().isEmpty());
QCOMPARE(spy.count(), 1);
}
void openBookSavesPositionOfPrevious()
{
AppState appState;
ReadingModel model;
BookController ctrl;
ctrl.setReadingModel(&model);
ctrl.setAppState(&appState);
ctrl.openBook(QUrl::fromLocalFile(fixturePath("sample.txt")));
QVERIFY(ctrl.hasBook());
QString firstPath = ctrl.currentFilePath();
// Attempt to open a second book — position of first book should be saved
// regardless of whether the second open succeeds
ctrl.openBook(QUrl::fromLocalFile("/tmp/file.xyz"));
// Position for sample.txt should have been saved (chapter 0 at minimum)
QVariantMap pos = appState.loadBookPosition(firstPath);
QVERIFY(pos.contains("chapter"));
QCOMPARE(pos["chapter"].toInt(), 0);
}
};
QTEST_MAIN(BookControllerTest)
+4 -4
View File
@@ -186,12 +186,12 @@ private slots:
FakeReader reader;
model.setReader(&reader);
// Chapter 0 of 3 → 1/3
QCOMPARE(model.progress(), 1.0 / 3.0);
// Chapter 0 of 3, no scroll → 0/3 = 0.0
QCOMPARE(model.progress(), 0.0);
model.goToChapter(2);
// Chapter 2 of 3 → 3/3 = 1.0
QCOMPARE(model.progress(), 1.0);
// Chapter 2 of 3, no scroll → 2/3
QCOMPARE(model.progress(), 2.0 / 3.0);
}
void setReaderNull()