File indexing completed on 2024-05-12 17:21:06

0001 /*
0002  * SPDX-FileCopyrightText: 2020-2021 Han Young <hanyoung@protonmail.com>
0003  *
0004  * SPDX-License-Identifier: GPL-3.0-or-later
0005  */
0006 
0007 #include "historymanager.h"
0008 #include <QDebug>
0009 #include <QDir>
0010 #include <QJsonArray>
0011 #include <QJsonDocument>
0012 #include <QJsonObject>
0013 #include <QStandardPaths>
0014 
0015 HistoryManager::HistoryManager()
0016 {
0017     // create cache location if it does not exist, and load cache
0018     QDir dir(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + QStringLiteral("/kalk"));
0019     if (!dir.exists()) {
0020         dir.mkpath(QStringLiteral("."));
0021     }
0022 
0023     QFile file(dir.path() + QStringLiteral("/history.json"));
0024     if (file.open(QIODevice::ReadOnly)) {
0025         QJsonDocument doc(QJsonDocument::fromJson(file.readAll()));
0026         const auto array = doc.array();
0027         m_historyList.reserve(array.size());
0028         for (const auto &record : array) {
0029             m_historyList.append(record.toString());
0030         }
0031     }
0032 }
0033 
0034 void HistoryManager::clearHistory()
0035 {
0036     m_historyList.clear();
0037     QDir dir(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + QStringLiteral("/kalk"));
0038     QFile file(dir.path() + QStringLiteral("history.json"));
0039     file.remove();
0040     Q_EMIT layoutChanged();
0041     save();
0042 }
0043 
0044 void HistoryManager::save()
0045 {
0046     QJsonDocument doc;
0047     QJsonArray array;
0048     for (const auto &record : qAsConst(m_historyList)) {
0049         array.append(record);
0050     }
0051     doc.setArray(array);
0052     QString url = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);
0053     QFile file(url + QStringLiteral("/kalk/history.json"));
0054     file.open(QIODevice::WriteOnly);
0055     file.write(doc.toJson(QJsonDocument::Compact));
0056     qDebug() << "save" << file.fileName();
0057 }