Files
hfut-bishe/client/gui/main_window/RecentProjectHistory.cpp
2026-04-07 20:55:30 +08:00

101 lines
2.6 KiB
C++

#include "main_window/RecentProjectHistory.h"
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonValue>
#include <QDebug>
#include <QStandardPaths>
QString RecentProjectHistory::cacheFilePath() {
const QString base = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation);
return QDir(base).filePath(QStringLiteral("landscape_tool/recent_projects.cache"));
}
QString RecentProjectHistory::normalizePath(const QString& path) {
if (path.isEmpty()) {
return QString();
}
const QFileInfo fi(path);
const QString c = fi.canonicalFilePath();
return c.isEmpty() ? QDir::cleanPath(fi.absoluteFilePath()) : c;
}
QStringList RecentProjectHistory::dedupeNewestFirst(const QStringList& paths) {
QStringList out;
out.reserve(paths.size());
for (const QString& p : paths) {
const QString n = normalizePath(p);
if (n.isEmpty()) {
continue;
}
if (out.contains(n)) {
continue;
}
out.append(n);
if (out.size() >= kMaxEntries) {
break;
}
}
return out;
}
QStringList RecentProjectHistory::load() const {
const QString filePath = cacheFilePath();
QFile f(filePath);
if (!f.open(QIODevice::ReadOnly)) {
return {};
}
const QJsonDocument doc = QJsonDocument::fromJson(f.readAll());
if (!doc.isArray()) {
return {};
}
QStringList paths;
for (const QJsonValue& v : doc.array()) {
if (v.isString()) {
paths.append(v.toString());
}
}
return dedupeNewestFirst(paths);
}
bool RecentProjectHistory::save(const QStringList& paths) const {
const QString filePath = cacheFilePath();
const QFileInfo fi(filePath);
QDir().mkpath(fi.absolutePath());
QJsonArray arr;
for (const QString& p : dedupeNewestFirst(paths)) {
arr.append(p);
}
const QJsonDocument doc(arr);
QFile f(filePath);
if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
qWarning() << "RecentProjectHistory: cannot write" << filePath;
return false;
}
f.write(doc.toJson(QJsonDocument::Compact));
return true;
}
void RecentProjectHistory::addAndSave(const QString& projectDir) {
const QString n = normalizePath(projectDir);
if (n.isEmpty()) {
return;
}
QStringList paths = load();
paths.removeAll(n);
paths.prepend(n);
save(paths);
}
void RecentProjectHistory::removeAndSave(const QString& projectDir) {
const QString n = normalizePath(projectDir);
QStringList paths = load();
paths.removeAll(n);
save(paths);
}