1// SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd.
2//
3// SPDX-License-Identifier: GPL-3.0-or-later
4
5#include "kitmanager.h"
6#include "common/util/custompaths.h"
7#include "common/util/qtcassert.h"
8#include "persistentsettings.h"
9
10#include <QFileInfo>
11
12const char KIT_DATA_KEY[] = "Profile.";
13const char KIT_COUNT_KEY[] = "Profile.Count";
14const char KIT_DEFAULT_KEY[] = "Profile.Default";
15const char KIT_FILENAME[] = "/profiles.xml";
16
17class KitManagerPrivate
18{
19public:
20 Kit *defaultKit = nullptr;
21 bool initialized = false;
22 std::vector<std::unique_ptr<Kit>> kitList;
23 Kit selectedKit;
24 std::unique_ptr<PersistentSettingsWriter> writer;
25};
26
27static KitManagerPrivate *d = nullptr;
28
29KitManager::KitManager(QObject *parent)
30 : QObject(parent)
31{
32 d = new KitManagerPrivate;
33}
34
35//////////////////
36// find helpers
37//////////////////
38template<typename R, typename S, typename T>
39decltype(auto) equal(R (S::*function)() const, T value)
40{
41 // This should use std::equal_to<> instead of std::equal_to<T>,
42 // but that's not supported everywhere yet, since it is C++14
43 return std::bind<bool>(std::equal_to<T>(), value, std::bind(function, std::placeholders::_1));
44}
45
46void KitManager::restoreKits()
47{
48 // TODO(Mozart)
49}
50
51KitManager::KitList KitManager::restoreKits(const QString &fileName)
52{
53 KitList result;
54
55 QFileInfo info(fileName);
56 if (!info.exists())
57 return result;
58
59 PersistentSettingsReader reader;
60 if (!reader.load(fileName)) {
61 qWarning("Warning: Failed to read \"%s\", cannot restore kits!",
62 qPrintable(fileName));
63 return result;
64 }
65 QVariantMap data = reader.restoreValues();
66
67 const int count = data.value(QLatin1String(KIT_COUNT_KEY), 0).toInt();
68 for (int i = 0; i < count; ++i) {
69 const QString key = QString::fromLatin1(KIT_DATA_KEY) + QString::number(i);
70 if (!data.contains(key))
71 break;
72
73 const QVariantMap stMap = data.value(key).toMap();
74
75 auto k = std::make_unique<Kit>(stMap);
76
77 result.kits.emplace_back(std::move(k));
78 }
79 const QString id = data.value(QLatin1String(KIT_DEFAULT_KEY)).toString();
80 if (id.isEmpty())
81 return result;
82
83 std::vector<std::unique_ptr<Kit>>::iterator it;
84 for (; it != result.kits.end(); ++it) {
85 if (it->get()->id() == id) {
86 result.defaultKit = id;
87 break;
88 }
89 }
90
91 return result;
92}
93
94KitManager *KitManager::instance()
95{
96 static KitManager ins;
97 return &ins;
98}
99
100KitManager::~KitManager()
101{
102}
103
104void KitManager::setSelectedKit(Kit &kit)
105{
106 d->selectedKit = kit;
107}
108
109const Kit &KitManager::getSelectedKit()
110{
111 return d->selectedKit;
112}
113
114QString KitManager::getDefaultOutputPath() const
115{
116 return d->selectedKit.getDefaultOutput();
117}
118