aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/qbsprojectmanager/qbsprofilemanager.cpp
blob: 953768661d0d9439304b00308b7b1fc7ccff1dd1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "qbsprofilemanager.h"

#include "defaultpropertyprovider.h"
#include "qbsproject.h"
#include "qbsprojectmanagerconstants.h"
#include "qbsprojectmanagerplugin.h"
#include "qbsprojectmanagertr.h"
#include "qbssettings.h"

#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/projectexplorer.h>
#include <qmljstools/qmljstoolsconstants.h>
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitinformation.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>

#include <QCryptographicHash>
#include <QJSEngine>
#include <QRegularExpression>
#include <QVariantMap>

namespace QbsProjectManager {

static QList<PropertyProvider *> g_propertyProviders;

PropertyProvider::PropertyProvider()
{
    g_propertyProviders.append(this);
}

PropertyProvider::~PropertyProvider()
{
    g_propertyProviders.removeOne(this);
}

namespace Internal {

static QString toJSLiteral(const bool b)
{
    return QLatin1String(b ? "true" : "false");
}

static QString toJSLiteral(const QString &str)
{
    QString js = str;
    js.replace(QRegularExpression("([\\\\\"])"), "\\\\1");
    js.prepend('"');
    js.append('"');
    return js;
}

QString toJSLiteral(const QVariant &val)
{
    if (!val.isValid())
        return QString("undefined");
    if (val.type() == QVariant::List || val.type() == QVariant::StringList) {
        QString res;
        const auto list = val.toList();
        for (const QVariant &child : list) {
            if (!res.isEmpty() ) res.append(", ");
            res.append(toJSLiteral(child));
        }
        res.prepend('[');
        res.append(']');
        return res;
    }
    if (val.type() == QVariant::Map) {
        const QVariantMap &vm = val.toMap();
        QString str("{");
        for (auto it = vm.begin(); it != vm.end(); ++it) {
            if (it != vm.begin())
                str += ',';
            str += toJSLiteral(it.key()) + ':' + toJSLiteral(it.value());
        }
        str += '}';
        return str;
    }
    if (val.type() == QVariant::Bool)
        return toJSLiteral(val.toBool());
    if (val.canConvert(QVariant::String))
        return toJSLiteral(val.toString());
    return QString::fromLatin1("Unconvertible type %1").arg(QLatin1String(val.typeName()));
}


static QbsProfileManager *m_instance = nullptr;

static QString kitNameKeyInQbsSettings(const ProjectExplorer::Kit *kit)
{
    return "preferences.qtcreator.kit." + kit->id().toString();
}

QbsProfileManager::QbsProfileManager() : m_defaultPropertyProvider(new DefaultPropertyProvider)
{
    m_instance = this;

    setObjectName(QLatin1String("QbsProjectManager"));
    connect(ProjectExplorer::KitManager::instance(), &ProjectExplorer::KitManager::kitsLoaded, this,
            [this] { m_kitsToBeSetupForQbs = ProjectExplorer::KitManager::kits(); } );
    connect(ProjectExplorer::KitManager::instance(), &ProjectExplorer::KitManager::kitAdded, this,
            &QbsProfileManager::addProfileFromKit);
    connect(ProjectExplorer::KitManager::instance(), &ProjectExplorer::KitManager::kitUpdated, this,
            &QbsProfileManager::handleKitUpdate);
    connect(ProjectExplorer::KitManager::instance(), &ProjectExplorer::KitManager::kitRemoved, this,
            &QbsProfileManager::handleKitRemoval);
    connect(&QbsSettings::instance(), &QbsSettings::settingsChanged,
            this, &QbsProfileManager::updateAllProfiles);
}

QbsProfileManager::~QbsProfileManager()
{
    delete m_defaultPropertyProvider;
    m_instance = nullptr;
}

QbsProfileManager *QbsProfileManager::instance()
{
    return m_instance;
}

QString QbsProfileManager::ensureProfileForKit(const ProjectExplorer::Kit *k)
{
    if (!k)
        return QString();
    updateProfileIfNecessary(k);
    return profileNameForKit(k);
}

void QbsProfileManager::updateProfileIfNecessary(const ProjectExplorer::Kit *kit)
{
    // kit in list <=> profile update is necessary
    // Note that the const_cast is safe, as we do not call any non-const methods on the object.
    if (m_instance->m_kitsToBeSetupForQbs.removeOne(const_cast<ProjectExplorer::Kit *>(kit)))
        m_instance->addProfileFromKit(kit);
}

void QbsProfileManager::updateAllProfiles()
{
    for (const auto * const kit : ProjectExplorer::KitManager::kits())
        addProfileFromKit(kit);
}

void QbsProfileManager::addProfileFromKit(const ProjectExplorer::Kit *k)
{
    const QString name = profileNameForKit(k);
    runQbsConfig(QbsConfigOp::Unset, "profiles." + name);
    runQbsConfig(QbsConfigOp::Set, kitNameKeyInQbsSettings(k), name);

    // set up properties:
    QVariantMap data = m_defaultPropertyProvider->properties(k, QVariantMap());
    for (PropertyProvider *provider : std::as_const(g_propertyProviders)) {
        if (provider->canHandle(k))
            data = provider->properties(k, data);
    }
    if (const QtSupport::QtVersion * const qt = QtSupport::QtKitAspect::qtVersion(k))
        data.insert("moduleProviders.Qt.qmakeFilePaths", qt->qmakeFilePath().toString());

    if (QbsSettings::qbsVersion() < QVersionNumber({1, 20})) {
        const QString keyPrefix = "profiles." + name + ".";
        for (auto it = data.begin(); it != data.end(); ++it)
            runQbsConfig(QbsConfigOp::Set, keyPrefix + it.key(), it.value());
    } else {
        runQbsConfig(QbsConfigOp::AddProfile, name, data);
    }
    emit qbsProfilesUpdated();
}

void QbsProfileManager::handleKitUpdate(ProjectExplorer::Kit *kit)
{
    m_kitsToBeSetupForQbs.removeOne(kit);
    addProfileFromKit(kit);
}

void QbsProfileManager::handleKitRemoval(ProjectExplorer::Kit *kit)
{
    m_kitsToBeSetupForQbs.removeOne(kit);
    runQbsConfig(QbsConfigOp::Unset, kitNameKeyInQbsSettings(kit));
    runQbsConfig(QbsConfigOp::Unset, "profiles." + profileNameForKit(kit));
    emit qbsProfilesUpdated();
}

QString QbsProfileManager::profileNameForKit(const ProjectExplorer::Kit *kit)
{
    if (!kit)
        return QString();
    return QString::fromLatin1("qtc_%1_%2").arg(kit->fileSystemFriendlyName().left(8),
            QString::fromLatin1(QCryptographicHash::hash(
                                    kit->id().name(), QCryptographicHash::Sha1).toHex().left(8)));
}

QString QbsProfileManager::runQbsConfig(QbsConfigOp op, const QString &key, const QVariant &value)
{
    QStringList args;
    if (QbsSettings::useCreatorSettingsDirForQbs())
        args << "--settings-dir" << QbsSettings::qbsSettingsBaseDir();
    switch (op) {
    case QbsConfigOp::Get:
        args << key;
        break;
    case QbsConfigOp::Set:
        args << key << toJSLiteral(value);
        break;
    case QbsConfigOp::Unset:
        args << "--unset" << key;
        break;
    case QbsConfigOp::AddProfile: {
        args << "--add-profile" << key;
        const QVariantMap props = value.toMap();
        for (auto it = props.begin(); it != props.end(); ++it)
            args << it.key() << toJSLiteral(it.value());
        if (props.isEmpty()) // Make sure we still create a profile for "empty" kits.
            args << "qbs.optimization" << toJSLiteral(QString("none"));
        break;
    }
    }
    const Utils::FilePath qbsConfigExe = QbsSettings::qbsConfigFilePath();
    if (qbsConfigExe.isEmpty() || !qbsConfigExe.exists())
        return {};
    Utils::Process qbsConfig;
    qbsConfig.setCommand({qbsConfigExe, args});
    qbsConfig.start();
    if (!qbsConfig.waitForFinished(5000)) {
        Core::MessageManager::writeFlashing(
            Tr::tr("Failed to run qbs config: %1").arg(qbsConfig.errorString()));
    } else if (qbsConfig.exitCode() != 0) {
        Core::MessageManager::writeFlashing(
            Tr::tr("Failed to run qbs config: %1")
                .arg(QString::fromLocal8Bit(qbsConfig.readAllRawStandardError())));
    }
    return QString::fromLocal8Bit(qbsConfig.readAllRawStandardOutput()).trimmed();
}

QVariant fromJSLiteral(const QString &str)
{
    QJSEngine engine;
    QJSValue sv = engine.evaluate("(function(){return " + str + ";})()");
    return sv.isError() ? str : sv.toVariant();
}

} // namespace Internal
} // namespace QbsProjectManager