1// SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd.
2//
3// SPDX-License-Identifier: GPL-3.0-or-later
4
5#include "shortcututil.h"
6
7#include <QFile>
8#include <QJsonParseError>
9#include <QJsonObject>
10#include <QJsonArray>
11#include <QMap>
12
13ShortcutUtil::ShortcutUtil(QObject *parent)
14 : QObject(parent)
15{
16
17}
18
19ShortcutUtil::~ShortcutUtil()
20{
21
22}
23
24bool ShortcutUtil::readFromJson(const QString &qsFilePath, QMap<QString, QStringList> &mapShortcutItem)
25{
26 QFile file(qsFilePath);
27 if (!file.open(QIODevice::ReadOnly))
28 return false;
29
30 QByteArray data = file.readAll();
31 file.close();
32
33 QJsonParseError parseError;
34 QJsonDocument doc = QJsonDocument::fromJson(data, &parseError);
35 if (QJsonParseError::NoError != parseError.error) {
36 return false;
37 }
38
39 if (!doc.isObject())
40 return false;
41
42 QJsonObject rootObject = doc.object();
43 mapShortcutItem.clear();
44 for (auto key : rootObject.keys()) {
45 if (!rootObject.value(key).isArray())
46 continue;
47 QJsonArray valueArray = rootObject.value(key).toArray();
48 if (valueArray.count() < 2)
49 continue;
50
51 QStringList qsListValue = {valueArray.first().toString(), valueArray.last().toString()};
52 mapShortcutItem[key] = qsListValue;
53 }
54
55 return true;
56}
57
58bool ShortcutUtil::writeToJson(const QString &qsFilePath, const QMap<QString, QStringList> &mapShortcutItem)
59{
60 QJsonObject rootObject;
61 QMap<QString, QStringList>::const_iterator iter = mapShortcutItem.begin();
62 for (; iter != mapShortcutItem.end(); ++iter)
63 {
64 QString qsID = iter.key();
65 QString qsDesc = iter.value().first();
66 QString qsShortcut = iter.value().last();
67
68 QJsonArray valueArray;
69 valueArray.append(QJsonValue(qsDesc));
70 valueArray.append(QJsonValue(qsShortcut));
71
72 rootObject.insert(qsID, valueArray);
73 }
74
75 QJsonDocument doc;
76 doc.setObject(rootObject);
77 QString jsonStr(doc.toJson(QJsonDocument::Indented));
78
79 QFile file(qsFilePath);
80 if (!file.open(QIODevice::WriteOnly))
81 return false;
82 file.write(jsonStr.toUtf8());
83 file.close();
84
85 return true;
86}
87