aboutsummaryrefslogtreecommitdiffstats
path: root/src/usagestatisticplugin.cpp
blob: b5fd66c7affb7ef692ad63bd83c5a1b7a87b72a8 (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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "usagestatisticplugin.h"
#include "coreplugin/actionmanager/actionmanager.h"

#ifdef BUILD_DESIGNSTUDIO
#include "qdseventshandler.h"
#endif

#include <extensionsystem/pluginmanager.h>
#include <extensionsystem/pluginspec.h>
#include <utils/algorithm.h>
#include <utils/appinfo.h>
#include <utils/aspects.h>
#include <utils/infobar.h>
#include <utils/layoutbuilder.h>
#include <utils/link.h>
#include <utils/theme/theme.h>

#include <coreplugin/dialogs/ioptionspage.h>
#include <coreplugin/helpmanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/modemanager.h>

#include <projectexplorer/buildsystem.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectmanager.h>

#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitaspect.h>

#include <QCryptographicHash>
#include <QGuiApplication>
#include <QInsightConfiguration>
#include <QInsightTracker>
#include <QMetaEnum>
#include <QTimer>

using namespace Core;
using namespace ExtensionSystem;
using namespace ProjectExplorer;
using namespace QtSupport;
using namespace Utils;

Q_LOGGING_CATEGORY(statLog, "qtc.usagestatistic", QtWarningMsg);

const char kSettingsPageId[] = "UsageStatistic.PreferencesPage";

namespace UsageStatistic::Internal {

static UsageStatisticPlugin *m_instance = nullptr;

class ModeChanges : public QObject
{
    Q_OBJECT
public:
    ModeChanges(QInsightTracker *tracker)
    {
        const auto id = [](const Id &modeId) -> QString {
            return ":MODE:" + QString::fromUtf8(modeId.name());
        };
        connect(ModeManager::instance(), &ModeManager::currentModeChanged, this, [=](const Id &modeId) {
            tracker->transition(id(modeId));
        });
        // initialize with current mode
        tracker->transition(id(ModeManager::currentModeId()));
    }
};

class UILanguage : public QObject
{
    Q_OBJECT
public:
    UILanguage(QInsightTracker *tracker)
    {
        tracker->interaction(":CONFIG:UILanguage", ICore::userInterfaceLanguage(), 0);
        const QStringList languages = QLocale::system().uiLanguages();
        tracker->interaction(":CONFIG:SystemLanguage",
                             languages.isEmpty() ? QString("Unknown") : languages.first(),
                             0);
    }
};

class Theme : public QObject
{
    Q_OBJECT
public:
    Theme(QInsightTracker *tracker)
    {
        tracker->interaction(":CONFIG:Theme",
                             creatorTheme() ? creatorTheme()->id() : QString("Unknown"),
                             0);
        const QString systemTheme = QString::fromUtf8(QMetaEnum::fromType<Qt::ColorScheme>().valueToKey(
                                                          int(Utils::Theme::systemColorScheme())))
                                        .toLower();
        tracker->interaction(":CONFIG:SystemTheme", systemTheme, 0);
    }
};

class QtModules : public QObject
{
    Q_OBJECT
public:
    QtModules(QInsightTracker *tracker)
    {
        connect(ProjectManager::instance(),
                &ProjectManager::projectAdded,
                this,
                [this, tracker](Project *project) {
                    connect(project, &Project::anyParsingFinished, this, [project, tracker] {
                        if (!project->activeBuildSystem())
                            return;
                        if (!project->activeBuildSystem()->kit())
                            return;
                        QtVersion *qtVersion = QtKitAspect::qtVersion(
                            project->activeBuildSystem()->kit());
                        if (!qtVersion)
                            return;
                        const FilePath qtLibPath = qtVersion->libraryPath();
                        using ModuleHash = QHash<QString, Utils::Link>;
                        const ModuleHash all = project->activeBuildSystem()
                                                   ->additionalData("FoundPackages")
                                                   .value<ModuleHash>();
                        QStringList qtPackages;
                        for (auto it = all.begin(); it != all.end(); ++it) {
                            const QString name = it.key();
                            const FilePath cmakePath = it.value().targetFilePath;
                            if (name.size() > 4 && name.startsWith("Qt") && name[2].isDigit()
                                && name[3].isUpper() && !name.endsWith("plugin", Qt::CaseInsensitive)
                                && cmakePath.isChildOf(qtLibPath))
                                qtPackages.append(name);
                        }
                        if (qtPackages.isEmpty())
                            return;
                        const QString projectID = QString::fromLatin1(
                            QCryptographicHash::hash(project->projectFilePath().toFSPathString().toUtf8(),
                                                     QCryptographicHash::Sha1)
                                .toHex());
                        const QString json = "{\"projectid\":\"" + projectID + "\",\"qtmodules\":[\""
                                             + qtPackages.join("\",\"") + "\"]}";
                        tracker->interaction("QtModules", json, 0);
                    });
                });
    }
};

class Settings : public AspectContainer
{
public:
    Settings()
    {
        setAutoApply(false);
        setSettingsGroup("UsageStatistic");
        trackingEnabled.setDefaultValue(false);
        trackingEnabled.setSettingsKey("TrackingEnabled");
        trackingEnabled.setLabel(UsageStatisticPlugin::tr("Send pseudonymous usage statistics"),
                                 BoolAspect::LabelPlacement::AtCheckBox);
    }

    Utils::BoolAspect trackingEnabled{this};
};

static Settings &theSettings()
{
    static Settings settings;
    return settings;
}

class SettingsWidget : public IOptionsPageWidget
{
public:
    SettingsWidget()
    {
        Settings &s = theSettings();

        using namespace Layouting;
        const QString helpUrl = ICore::isQtDesignStudio() ?
                          QString("qtdesignstudio/doc/studio-collecting-usage-statistics.html\">")
                        : QString("qtcreator/doc/creator-how-to-collect-usage-statistics.html\">");

        auto moreInformationLabel = new QLabel("<a href=\"qthelp://org.qt-project."
                                               + helpUrl
                                               + UsageStatisticPlugin::tr("More information")
                                               + "</a>");
        connect(moreInformationLabel, &QLabel::linkActivated, [this](const QString &link) {
            HelpManager::showHelpUrl(link, HelpManager::ExternalHelpAlways);
        });
        // clang-format off
        Column {
            s.trackingEnabled,
            Group {
                Column {
                    Label {
                        text(UsageStatisticPlugin::tr("%1 collects pseudonymous information about "
                             "your system and the way you use the application. The data is "
                             "associated with a pseudonymous user ID generated only for this "
                             "purpose. The data will be shared with services managed by "
                             "The Qt Company. It does however not contain individual content "
                             "created by you, and will be used by The Qt Company strictly for the "
                             "purposes of improving their products.")
                                .arg(QGuiApplication::applicationDisplayName())),
                        wordWrap(true)
                    },
                    moreInformationLabel,
                    st
                }
            }
        }.attachTo(this);
        // clang-format on

        setOnApply([] {
            theSettings().apply();
            theSettings().writeToSettingsImmediatly(); // write the updated "TrackingEnabled" value to the .ini
            m_instance->configureInsight();
        });
        setOnCancel([] { theSettings().cancel(); });
        setOnFinish([] { theSettings().finish(); });
    }
};

class SettingsPage final : public Core::IOptionsPage
{
public:
    SettingsPage()
    {
        setId(kSettingsPageId);
        setCategory("Telemetry");
        setDisplayName(UsageStatisticPlugin::tr("Usage Statistics"));
        setWidgetCreator([] { return new SettingsWidget; });
    }
};

static void setupSettingsPage()
{
    static SettingsPage settings;
}

UsageStatisticPlugin::UsageStatisticPlugin()
{
    m_instance = this;
    Core::IOptionsPage::registerCategory(
        "Telemetry",
        UsageStatisticPlugin::tr("Telemetry"),
        ":/usagestatistic/images/settingscategory_usagestatistic.png");
}

UsageStatisticPlugin::~UsageStatisticPlugin() = default;

void UsageStatisticPlugin::initialize()
{
    setupSettingsPage();
    theSettings().readSettings();
}

void UsageStatisticPlugin::extensionsInitialized()
{
}

bool UsageStatisticPlugin::delayedInitialize()
{
    if (theSettings().trackingEnabled.value())
        configureInsight();

    showInfoBar();

    return true;
}

ExtensionSystem::IPlugin::ShutdownFlag UsageStatisticPlugin::aboutToShutdown()
{
    theSettings().writeSettings();

    return SynchronousShutdown;
}

static constexpr int submissionInterval()
{
    using namespace std::literals;
    return std::chrono::hours(1) / 1s;
}

void UsageStatisticPlugin::configureInsight()
{
    qCDebug(statLog) << "Configuring insight, enabled:" << theSettings().trackingEnabled.value();
    if (theSettings().trackingEnabled.value()) {
        if (!m_tracker || !m_tracker->isEnabled()) {
            // silence qt.insight.*.info logging category if logging for usagestatistic is not enabled
            // the issue here is, that qt.insight.*.info is enabled by default and spams terminals
            static std::optional<QLoggingCategory::CategoryFilter> previousFilter;
            if (!statLog().isDebugEnabled()) {
                previousFilter = QLoggingCategory::installFilter([](QLoggingCategory *log) {
                    if (previousFilter && previousFilter.has_value())
                        (*previousFilter)(log);
                    if (QString::fromUtf8(log->categoryName()).startsWith("qt.insight"))
                        log->setEnabled(QtInfoMsg, false);
                });
            }

            qCDebug(statLog) << "Creating tracker";
            m_tracker.reset(new QInsightTracker);
            QInsightConfiguration *config = m_tracker->configuration();
            config->setEvents({}); // the default is a big list including key events....
            config->setStoragePath(ICore::cacheResourcePath("insight").path());
            qCDebug(statLog) << "Cache path:" << config->storagePath();
            // TODO provide a button for removing the cache?
            // TODO config->setStorageSize(???); // unlimited by default
            config->setSyncInterval(submissionInterval());
            config->setBatchSize(100);
            config->setDeviceModel(QString("%1 (%2)").arg(QSysInfo::productType(),
                                                          QSysInfo::currentCpuArchitecture()));
            config->setDeviceVariant(QSysInfo::productVersion());
            config->setDeviceScreenType("NON_TOUCH");
            config->setPlatform("app"); // see "Snowplow Tracker Protocol"
            config->setAppBuild(appInfo().displayVersion);
            config->setServer(QTC_INSIGHT_URL);
            config->setToken(QTC_INSIGHT_TOKEN);
            m_tracker->setEnabled(true);
            createProviders();
            m_tracker->startNewSession();

            // reinstall previous logging filter if required
            if (previousFilter)
                QLoggingCategory::installFilter(*previousFilter);
        }
    } else {
        if (m_tracker)
            m_tracker->setEnabled(false);
    }

    Core::Command *cmd = Core::ActionManager::command("Help.GiveFeedback");

    if (cmd) {
        cmd->action()->setEnabled(m_tracker->isEnabled());
        cmd->action()->setVisible(m_tracker->isEnabled());
    }
}

void UsageStatisticPlugin::showInfoBar()
{
    static const char kInfoBarId[] = "UsageStatistic.AskAboutCollectingDataInfoBar";
    if (!ICore::infoBar()->canInfoBeAdded(kInfoBarId) || theSettings().trackingEnabled.value())
        return;
    static auto infoText = UsageStatisticPlugin::tr(
                               "We make %1 for you. Would you like to help us make it even better?")
                               .arg(QGuiApplication::applicationDisplayName());
    static auto configureButtonInfoText = UsageStatisticPlugin::tr("Configure usage statistics...");
    static auto cancelButtonInfoText = UsageStatisticPlugin::tr("Decide later");

    ::Utils::InfoBarEntry entry(kInfoBarId, infoText, InfoBarEntry::GlobalSuppression::Enabled);
    entry.addCustomButton(configureButtonInfoText, [] {
        ICore::infoBar()->removeInfo(kInfoBarId);
        ICore::showOptionsDialog(kSettingsPageId);
    });
    entry.setCancelButtonInfo(cancelButtonInfoText, {});
    ICore::infoBar()->addInfo(entry);
}

void UsageStatisticPlugin::createProviders()
{
    // startup configs first, otherwise they will be attributed to the UI state
    m_providers.push_back(std::make_unique<Theme>(m_tracker.get()));
    m_providers.push_back(std::make_unique<QtModules>(m_tracker.get()));

    // not needed for QDS
    if (!ICore::isQtDesignStudio()) {
        m_providers.push_back(std::make_unique<UILanguage>(m_tracker.get()));

        // UI state last
        m_providers.push_back(std::make_unique<ModeChanges>(m_tracker.get()));
    }

#ifdef BUILD_DESIGNSTUDIO
    // handle events emitted from QDS
    m_providers.push_back(std::make_unique<QDSEventsHandler>(m_tracker.get()));
#endif

    for (const auto &provider : m_providers) {
        qCDebug(statLog) << "Created usage statistics provider"
                         << provider.get()->metaObject()->className();
    }
}

} // namespace UsageStatistic::Internal

#include "usagestatisticplugin.moc"