fix history sort

This commit is contained in:
Agel committed 2026-10-30 12:39:30 +01:00
1 parent c25e8ddb90
commit 511472bc73
4 files changed
+293 -30

No files matched your search

+2 -1
View File
@@ -113,7 +113,7 @@ Backend (C++) handles all file I/O, format parsing, text layout calculation, and
| `readingModel` (`ReadingModel`) | `QAbstractListModel` exposing chunks (`ContentRole`, `LayoutRole`, `PixelHeightRole`), layout updates, reading mode (`isTextMode`, `isMangaMode`), manga page pairs, and per-book toggles (`pageShift`, `mangaRTL`, `useBookColours`). |
| `readingPreferences` (`ReadingPreferences`) | Font size, line spacing, horizontal margin, vertical margin (`QSettings`). |
| `uiState` (`UiState`) | Current theme, last page, sidebar open state, reader bars visibility (`barsVisible`), last file path, custom theme colors, window geometry. |
| `historyModel` (`HistoryModel`) | `QAbstractListModel` of recent books with async metadata extraction and reading progress. |
| `historyModel` (`HistoryModel`) | `QAbstractListModel` of recent books with async metadata extraction and reading progress. Entries store strongly-typed `QDateTime lastOpened`, immediately drop bogus/unparseable dates on deserialization, and are maintained strictly in descending chronological order (`lastOpened desc`). |
| `isDebugBuild` | Boolean constant indicating debug build. |
### Additional Registered Types & Providers
@@ -191,6 +191,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`.
- **Restoration Flow**:
+112 -23
View File
@@ -6,7 +6,9 @@
#include <QDateTime>
#include <QFileInfo>
#include <QPointer>
#include <QSet>
#include <QtConcurrent>
#include <algorithm>
namespace {
QString formatForPath(const QString &filePath)
@@ -21,6 +23,19 @@ QString formatForPath(const QString &filePath)
return QStringLiteral("FB2");
return filePath.section('.', -1).toUpper();
}
QDateTime parseDateTime(const QString &str)
{
if (str.isEmpty())
return {};
QDateTime dt = QDateTime::fromString(str, Qt::ISODate);
if (!dt.isValid()) {
const QDate d = QDate::fromString(str, Qt::ISODate);
if (d.isValid())
dt = d.startOfDay();
}
return dt;
}
}
HistoryModel::HistoryModel(FormatRegistry &registry, QObject *parent)
@@ -62,7 +77,7 @@ QVariant HistoryModel::data(const QModelIndex &index, int role) const
case ProgressRole:
return entry.progress;
case LastOpenedRole:
return entry.lastOpened;
return entry.lastOpened.isValid() ? entry.lastOpened.toString(Qt::ISODate) : QString();
case CoverImageUrlRole:
return entry.coverImageUrl;
default:
@@ -81,10 +96,18 @@ bool HistoryModel::setData(const QModelIndex &index, const QVariant &value, int
entry.progress = value.toDouble();
emit dataChanged(index, index, {ProgressRole});
return true;
case LastOpenedRole:
entry.lastOpened = value.toString();
emit dataChanged(index, index, {LastOpenedRole});
case LastOpenedRole: {
QDateTime dt;
if (value.canConvert<QDateTime>()) {
dt = value.toDateTime();
} else {
dt = parseDateTime(value.toString());
}
if (!dt.isValid())
return false;
addOrUpdateBook(entry.filePath, entry.progress, dt);
return true;
}
default:
return false;
}
@@ -105,14 +128,46 @@ QHash<int, QByteArray> HistoryModel::roleNames() const
void HistoryModel::load(AppState &state)
{
clear();
for (const QVariantMap &item : state.loadArray(QStringLiteral("history"))) {
const QList<QVariantMap> rawItems = state.loadArray(QStringLiteral("history"));
QList<HistoryEntry> loadedEntries;
loadedEntries.reserve(rawItems.size());
QSet<QString> seenPaths;
for (const QVariantMap &item : rawItems) {
const QString fp = item.value(QStringLiteral("filePath")).toString();
if (fp.isEmpty()) continue;
if (fp.isEmpty() || seenPaths.contains(fp))
continue;
const QString loStr = item.value(QStringLiteral("lastOpened")).toString();
const QDateTime lastOpened = parseDateTime(loStr);
if (!lastOpened.isValid())
continue; // bogus date: immediately dropped
seenPaths.insert(fp);
double progress = item.value(QStringLiteral("progress"), 0.0).toDouble();
progress = qBound(0.0, progress, 1.0);
const QString lo = item.value(QStringLiteral("lastOpened")).toString();
addOrUpdateBook(fp, progress, lo);
HistoryEntry entry;
entry.filePath = fp;
entry.progress = progress;
entry.lastOpened = lastOpened;
entry.format = formatForPath(fp);
loadedEntries.append(entry);
}
std::stable_sort(loadedEntries.begin(), loadedEntries.end(),
[](const HistoryEntry &a, const HistoryEntry &b) {
return a.lastOpened > b.lastOpened;
});
beginResetModel();
m_entries = std::move(loadedEntries);
endResetModel();
emit countChanged();
for (const auto &entry : m_entries) {
requestMetadata(entry.filePath);
}
}
@@ -124,28 +179,50 @@ void HistoryModel::save(AppState &state) const
items.append({
{QStringLiteral("filePath"), entry.filePath},
{QStringLiteral("progress"), entry.progress},
{QStringLiteral("lastOpened"), entry.lastOpened},
{QStringLiteral("lastOpened"), entry.lastOpened.toString(Qt::ISODate)},
});
}
state.saveArray(QStringLiteral("history"), items);
}
void HistoryModel::addOrUpdateBook(const QString &filePath, double progress, const QString &lastOpened)
void HistoryModel::addOrUpdateBook(const QString &filePath, double progress, const QDateTime &lastOpened)
{
if (filePath.isEmpty() || !lastOpened.isValid())
return; // bogus date: immediately dropped
int existingIndex = -1;
for (int i = 0; i < m_entries.size(); ++i) {
if (m_entries[i].filePath == filePath) {
m_entries[i].progress = progress;
m_entries[i].lastOpened = lastOpened;
existingIndex = i;
break;
}
}
if (i != 0) {
beginMoveRows(QModelIndex(), i, i, QModelIndex(), 0);
m_entries.move(i, 0);
if (existingIndex != -1) {
m_entries[existingIndex].progress = progress;
m_entries[existingIndex].lastOpened = lastOpened;
int targetIndex = 0;
for (int i = 0; i < m_entries.size(); ++i) {
if (i == existingIndex)
continue;
if (lastOpened > m_entries[i].lastOpened)
break;
++targetIndex;
}
if (existingIndex != targetIndex) {
if (existingIndex < targetIndex) {
beginMoveRows(QModelIndex(), existingIndex, existingIndex, QModelIndex(), targetIndex + 1);
} else {
beginMoveRows(QModelIndex(), existingIndex, existingIndex, QModelIndex(), targetIndex);
}
m_entries.move(existingIndex, targetIndex);
endMoveRows();
}
emit dataChanged(createIndex(0, 0), createIndex(0, 0), {ProgressRole, LastOpenedRole});
emit dataChanged(createIndex(targetIndex, 0), createIndex(targetIndex, 0), {ProgressRole, LastOpenedRole});
return;
}
}
HistoryEntry entry;
entry.filePath = filePath;
@@ -153,14 +230,27 @@ void HistoryModel::addOrUpdateBook(const QString &filePath, double progress, con
entry.lastOpened = lastOpened;
entry.format = formatForPath(filePath);
beginInsertRows(QModelIndex(), 0, 0);
m_entries.prepend(entry);
int targetIndex = 0;
while (targetIndex < m_entries.size() && !(lastOpened > m_entries[targetIndex].lastOpened)) {
++targetIndex;
}
beginInsertRows(QModelIndex(), targetIndex, targetIndex);
m_entries.insert(targetIndex, entry);
endInsertRows();
emit countChanged();
requestMetadata(filePath);
}
void HistoryModel::addOrUpdateBook(const QString &filePath, double progress, const QString &lastOpened)
{
const QDateTime dt = parseDateTime(lastOpened);
if (!dt.isValid())
return; // bogus date: immediately dropped
addOrUpdateBook(filePath, progress, dt);
}
void HistoryModel::addOrUpdateBook(const QString &filePath, double progress)
{
double resolvedProgress = progress;
@@ -174,8 +264,7 @@ void HistoryModel::addOrUpdateBook(const QString &filePath, double progress)
if (resolvedProgress < 0.0)
resolvedProgress = 0.0;
}
addOrUpdateBook(filePath, resolvedProgress,
QDateTime::currentDateTime().toString(Qt::ISODate));
addOrUpdateBook(filePath, resolvedProgress, QDateTime::currentDateTime());
}
void HistoryModel::removeBook(const QString &filePath)
@@ -214,7 +303,7 @@ double HistoryModel::progress(int index) const
return m_entries.at(index).progress;
}
QString HistoryModel::lastOpened(int index) const
QDateTime HistoryModel::lastOpened(int index) const
{
if (index < 0 || index >= m_entries.size()) return {};
return m_entries.at(index).lastOpened;
+4 -2
View File
@@ -2,6 +2,7 @@
#define HISTORYMODEL_H
#include <QAbstractListModel>
#include <QDateTime>
#include <QFuture>
#include <QHash>
#include <QList>
@@ -13,7 +14,7 @@ class FormatRegistry;
struct HistoryEntry {
QString filePath;
double progress = 0.0;
QString lastOpened;
QDateTime lastOpened;
QString title;
QString author;
QString format;
@@ -50,6 +51,7 @@ public:
void load(AppState &state);
void save(AppState &state) const;
Q_INVOKABLE void addOrUpdateBook(const QString &filePath, double progress, const QDateTime &lastOpened);
Q_INVOKABLE void addOrUpdateBook(const QString &filePath, double progress, const QString &lastOpened);
Q_INVOKABLE void addOrUpdateBook(const QString &filePath, double progress);
Q_INVOKABLE void removeBook(const QString &filePath);
@@ -57,7 +59,7 @@ public:
QString filePath(int index) const;
double progress(int index) const;
QString lastOpened(int index) const;
QDateTime lastOpened(int index) const;
signals:
void countChanged();
+175 -4
View File
@@ -93,7 +93,7 @@ private slots:
HistoryModel model(registry);
QSignalSpy countSpy(&model, &HistoryModel::countChanged);
model.addOrUpdateBook(QStringLiteral("/path/to/book.cbz"), 0.42, QStringLiteral("2026-01-01"));
model.addOrUpdateBook(QStringLiteral("/path/to/book.cbz"), 0.42, QStringLiteral("2026-01-01T12:00:00"));
QCOMPARE(countSpy.count(), 1);
QCOMPARE(model.rowCount(), 1);
@@ -101,8 +101,9 @@ private slots:
const QModelIndex idx = model.index(0, 0);
QCOMPARE(model.data(idx, HistoryModel::FilePathRole).toString(), QStringLiteral("/path/to/book.cbz"));
QCOMPARE(model.data(idx, HistoryModel::ProgressRole).toDouble(), 0.42);
QCOMPARE(model.data(idx, HistoryModel::LastOpenedRole).toString(), QStringLiteral("2026-01-01"));
QCOMPARE(model.data(idx, HistoryModel::LastOpenedRole).toString(), QStringLiteral("2026-01-01T12:00:00"));
QCOMPARE(model.data(idx, HistoryModel::FormatRole).toString(), QStringLiteral("CBZ"));
QCOMPARE(model.lastOpened(0), QDateTime::fromString(QStringLiteral("2026-01-01T12:00:00"), Qt::ISODate));
}
void loadMetadataPopulatesTitleAndCoverUrl()
@@ -155,7 +156,7 @@ private slots:
{
HistoryModel model(registry);
model.addOrUpdateBook(QStringLiteral("/path/to/book.cbz"), 0.75, QStringLiteral("2026-10-25"));
model.addOrUpdateBook(QStringLiteral("/path/to/book.cbz"), 0.75, QStringLiteral("2026-10-25T14:00:00"));
model.save(appState);
}
@@ -165,9 +166,179 @@ private slots:
QCOMPARE(model2.rowCount(), 1);
QCOMPARE(model2.filePath(0), QStringLiteral("/path/to/book.cbz"));
QCOMPARE(model2.progress(0), 0.75);
QCOMPARE(model2.lastOpened(0), QStringLiteral("2026-10-25"));
QCOMPARE(model2.lastOpened(0), QDateTime::fromString(QStringLiteral("2026-10-25T14:00:00"), Qt::ISODate));
}
}
void bogusDateDroppedOnLoad()
{
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/hist-bogus-XXXXXX.ini"));
(void)f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState appState(s);
appState.saveArray(QStringLiteral("history"), {
{
{QStringLiteral("filePath"), QStringLiteral("/path/valid1.cbz")},
{QStringLiteral("progress"), 0.1},
{QStringLiteral("lastOpened"), QStringLiteral("2026-10-20T10:00:00")},
},
{
{QStringLiteral("filePath"), QStringLiteral("/path/bogus_empty.cbz")},
{QStringLiteral("progress"), 0.2},
{QStringLiteral("lastOpened"), QStringLiteral("")},
},
{
{QStringLiteral("filePath"), QStringLiteral("/path/valid2.cbz")},
{QStringLiteral("progress"), 0.3},
{QStringLiteral("lastOpened"), QStringLiteral("2026-10-25T15:30:00")},
},
{
{QStringLiteral("filePath"), QStringLiteral("/path/bogus_text.cbz")},
{QStringLiteral("progress"), 0.4},
{QStringLiteral("lastOpened"), QStringLiteral("not-a-valid-date")},
},
{
{QStringLiteral("filePath"), QStringLiteral("/path/bogus_invalid_date.cbz")},
{QStringLiteral("progress"), 0.5},
{QStringLiteral("lastOpened"), QStringLiteral("2026-02-31T00:00:00")},
},
{
{QStringLiteral("filePath"), QStringLiteral("")},
{QStringLiteral("progress"), 0.6},
{QStringLiteral("lastOpened"), QStringLiteral("2026-10-30T10:00:00")},
},
});
FormatRegistry registry = makeRegistry();
HistoryModel model(registry);
model.load(appState);
QCOMPARE(model.rowCount(), 2);
QCOMPARE(model.filePath(0), QStringLiteral("/path/valid2.cbz"));
QCOMPARE(model.filePath(1), QStringLiteral("/path/valid1.cbz"));
}
void bogusDateDroppedOnAddOrUpdate()
{
FormatRegistry registry = makeRegistry();
HistoryModel model(registry);
model.addOrUpdateBook(QStringLiteral("/path/bad1.cbz"), 0.5, QDateTime());
QCOMPARE(model.rowCount(), 0);
model.addOrUpdateBook(QStringLiteral("/path/bad2.cbz"), 0.5, QStringLiteral("corrupted-date"));
QCOMPARE(model.rowCount(), 0);
model.addOrUpdateBook(QString(), 0.5, QDateTime::currentDateTime());
QCOMPARE(model.rowCount(), 0);
const QDateTime dt = QDateTime::fromString(QStringLiteral("2026-10-25T12:00:00"), Qt::ISODate);
model.addOrUpdateBook(QStringLiteral("/path/good.cbz"), 0.5, dt);
QCOMPARE(model.rowCount(), 1);
model.addOrUpdateBook(QStringLiteral("/path/good.cbz"), 0.8, QStringLiteral("garbage"));
QCOMPARE(model.lastOpened(0), dt);
QCOMPARE(model.progress(0), 0.5);
}
void loadSortsEntriesByLastOpenedDesc()
{
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/hist-sort-XXXXXX.ini"));
(void)f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState appState(s);
appState.saveArray(QStringLiteral("history"), {
{
{QStringLiteral("filePath"), QStringLiteral("/path/oldest.cbz")},
{QStringLiteral("progress"), 0.1},
{QStringLiteral("lastOpened"), QStringLiteral("2026-01-01T10:00:00")},
},
{
{QStringLiteral("filePath"), QStringLiteral("/path/newest.cbz")},
{QStringLiteral("progress"), 0.5},
{QStringLiteral("lastOpened"), QStringLiteral("2026-10-30T10:00:00")},
},
{
{QStringLiteral("filePath"), QStringLiteral("/path/middle.cbz")},
{QStringLiteral("progress"), 0.3},
{QStringLiteral("lastOpened"), QStringLiteral("2026-06-15T10:00:00")},
},
});
FormatRegistry registry = makeRegistry();
HistoryModel model(registry);
model.load(appState);
QCOMPARE(model.rowCount(), 3);
QCOMPARE(model.filePath(0), QStringLiteral("/path/newest.cbz"));
QCOMPARE(model.filePath(1), QStringLiteral("/path/middle.cbz"));
QCOMPARE(model.filePath(2), QStringLiteral("/path/oldest.cbz"));
}
void saveAndLoadPreservesChronologicalOrder()
{
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/hist-pres-XXXXXX.ini"));
(void)f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState appState(s);
FormatRegistry registry = makeRegistry();
{
HistoryModel model(registry);
model.addOrUpdateBook(QStringLiteral("/path/a.cbz"), 0.1, QStringLiteral("2026-10-10T10:00:00"));
model.addOrUpdateBook(QStringLiteral("/path/b.cbz"), 0.2, QStringLiteral("2026-10-20T10:00:00"));
model.addOrUpdateBook(QStringLiteral("/path/c.cbz"), 0.3, QStringLiteral("2026-10-30T10:00:00"));
QCOMPARE(model.filePath(0), QStringLiteral("/path/c.cbz"));
QCOMPARE(model.filePath(1), QStringLiteral("/path/b.cbz"));
QCOMPARE(model.filePath(2), QStringLiteral("/path/a.cbz"));
model.save(appState);
}
{
HistoryModel model2(registry);
model2.load(appState);
QCOMPARE(model2.rowCount(), 3);
QCOMPARE(model2.filePath(0), QStringLiteral("/path/c.cbz"));
QCOMPARE(model2.filePath(1), QStringLiteral("/path/b.cbz"));
QCOMPARE(model2.filePath(2), QStringLiteral("/path/a.cbz"));
}
}
void addOrUpdateMaintainsChronologicalOrder()
{
FormatRegistry registry = makeRegistry();
HistoryModel model(registry);
model.addOrUpdateBook(QStringLiteral("/path/1.cbz"), 0.1, QStringLiteral("2026-05-01T12:00:00"));
model.addOrUpdateBook(QStringLiteral("/path/2.cbz"), 0.2, QStringLiteral("2026-01-01T12:00:00"));
model.addOrUpdateBook(QStringLiteral("/path/3.cbz"), 0.3, QStringLiteral("2026-03-01T12:00:00"));
QCOMPARE(model.rowCount(), 3);
QCOMPARE(model.filePath(0), QStringLiteral("/path/1.cbz"));
QCOMPARE(model.filePath(1), QStringLiteral("/path/3.cbz"));
QCOMPARE(model.filePath(2), QStringLiteral("/path/2.cbz"));
// Update book 2 (Jan) to June (newest) -> moves to index 0
model.addOrUpdateBook(QStringLiteral("/path/2.cbz"), 0.5, QStringLiteral("2026-06-01T12:00:00"));
QCOMPARE(model.filePath(0), QStringLiteral("/path/2.cbz"));
QCOMPARE(model.filePath(1), QStringLiteral("/path/1.cbz"));
QCOMPARE(model.filePath(2), QStringLiteral("/path/3.cbz"));
// Update book 2 (now index 0) to February (between Jan and Mar) -> moves to index 2
model.addOrUpdateBook(QStringLiteral("/path/2.cbz"), 0.6, QStringLiteral("2026-02-01T12:00:00"));
QCOMPARE(model.filePath(0), QStringLiteral("/path/1.cbz"));
QCOMPARE(model.filePath(1), QStringLiteral("/path/3.cbz"));
QCOMPARE(model.filePath(2), QStringLiteral("/path/2.cbz"));
}
};
QTEST_MAIN(HistoryModelTest)