aboutsummaryrefslogtreecommitdiffstats
path: root/src/usagestatisticplugin.cpp
blob: e76536ae108bbe16b8d597bfcc21439cb603ee1a (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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
// 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"

#include <extensionsystem/pluginmanager.h>
#include <extensionsystem/pluginspec.h>
#include <utils/algorithm.h>
#include <utils/appinfo.h>
#include <utils/aspects.h>
#include <utils/async.h>
#include <utils/infobar.h>
#include <utils/layoutbuilder.h>
#include <utils/link.h>
#include <utils/mimeconstants.h>
#include <utils/mimeutils.h>
#include <utils/qtcprocess.h>
#include <utils/temporaryfile.h>
#include <utils/theme/theme.h>

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

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

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

#include <QtTaskTree/QSingleTaskTreeRunner>

#include <QCryptographicHash>
#include <QGuiApplication>
#include <QInsightConfiguration>
#include <QInsightTracker>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#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);
Q_LOGGING_CATEGORY(qtmodulesLog, "qtc.usagestatistic.qtmodules", QtWarningMsg);
Q_LOGGING_CATEGORY(qtexampleLog, "qtc.usagestatistic.qtexample", QtWarningMsg);
Q_LOGGING_CATEGORY(qmlmodulesLog, "qtc.usagestatistic.qmlmodules", QtWarningMsg);

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

namespace UsageStatistic::Internal {

static UsageStatisticPlugin *m_instance = nullptr;

#define QT_WITH_CONTEXTDATA QT_VERSION_CHECK(6, 9, 2)

static void addEvent(QInsightTracker *tracker, const QString &key, const QString &data)
{
#if QT_VERSION >= QT_WITH_CONTEXTDATA
    tracker->contextData(key, data);
#else
    tracker->interaction(key, data, 0);
#endif
}

static QString hashed(const QString &path)
{
    return QString::fromLatin1(
        QCryptographicHash::hash(path.toUtf8(), QCryptographicHash::Sha1).toHex());
}

static QString projectId(Project *project)
{
    return hashed(project->projectFilePath().toFSPathString());
}

class ModeChanges : public QObject
{
    Q_OBJECT
public:
    ModeChanges(QInsightTracker *tracker)
    {
        const auto id = [](const Id &modeId) -> QString {
            QString ret = ":MODE:" + QString::fromUtf8(modeId.name());
            if (modeId == Core::Constants::MODE_DESIGN)
                ret += ":" + QString::fromUtf8(DesignMode::currentDesignWidget().name());
            return ret;
        };
        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)
    {
        addEvent(tracker, ":CONFIG:UILanguage", ICore::userInterfaceLanguage());
        const QStringList languages = QLocale::system().uiLanguages();
        addEvent(tracker,
                 ":CONFIG:SystemLanguage",
                 languages.isEmpty() ? QString("Unknown") : languages.first());
    }
};

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

class AndroidManifestGuiEnabled : public QObject
{
    Q_OBJECT

public:
    AndroidManifestGuiEnabled(QInsightTracker *tracker)
    {
        connect(ExtensionSystem::PluginManager::instance(), &ExtensionSystem::PluginManager::objectAdded,
        this, [this, tracker](QObject *object) {
            if (object->objectName() == QString("AndroidManifestEditorEnabled"))
                addEvent(tracker, ":ANDROID:ManifestGuiEditorEnabled", object->objectName());
        });
    }
};

class QtModules : public QObject
{
    Q_OBJECT
public:
    static QStringList getQtPackages(Project *project, QtVersion *qtVersion)
    {
        if (!qtVersion)
            return {};
        const FilePath qtLibPath = qtVersion->libraryPath();
        using ModuleHash = QHash<QString, Utils::Link>;
        const ModuleHash all
            = project->activeBuildSystem()->additionalData("FoundPackages").value<ModuleHash>();
        QStringList packages;
        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))
                packages.append(name);
        }
        return packages;
    }

    static QString qtVersionString(QtVersion *qtVersion)
    {
        return qtVersion ? qtVersion->qtVersion().toString() : QString("None");
    }

    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 QStringList qtPackages = getQtPackages(project, qtVersion);
                        if (qtPackages.isEmpty())
                            return;
                        QJsonObject json;
                        json.insert("projectid", projectId(project));
                        json.insert("qtmodules", QJsonArray::fromStringList(qtPackages));
                        json.insert("qtversion", qtVersionString(qtVersion));
                        const QString jsonStr = QString::fromUtf8(
                            QJsonDocument(json).toJson(QJsonDocument::Compact));
                        qCDebug(qtmodulesLog) << qPrintable(jsonStr);
                        addEvent(tracker, "QtModules", jsonStr);
                    });
                });
    }
};

class QmlModules : public QObject
{
    Q_OBJECT

public:
    using ScanStorage = QtTaskTree::Storage<std::unique_ptr<TemporaryFilePath>>;

    QmlModules(QInsightTracker *tracker)
    {
        // Management code for being able to access the project's import paths
        // Would be nice if this was available more directly from the project->activeBuildSystem()
        connect(
            ProjectManager::instance(),
            &ProjectManager::extraProjectInfoChanged,
            this,
            [this](BuildConfiguration *bc, const ProjectExplorer::QmlCodeModelInfo &extra) {
                m_qmlCodeModelInfo.insert(bc, extra);
            });
        connect(
            ProjectManager::instance(),
            &ProjectManager::buildConfigurationRemoved,
            this,
            [this](BuildConfiguration *bc) { m_qmlCodeModelInfo.remove(bc); });
        // The actual retrieval of QML modules
        connect(
            BuildManager::instance(),
            &BuildManager::buildStateChanged,
            this,
            [this, tracker](Project *project) {
                if (!shouldStartCollectingFor(project))
                    return;

                if (!project->activeBuildSystem())
                    return;
                if (!project->activeBuildSystem()->kit())
                    return;
                QtVersion *qtVersion = QtKitAspect::qtVersion(project->activeBuildSystem()->kit());
                if (!qtVersion)
                    return;
                const FilePath qmlimportscanner = qtVersion->hostLibexecPath()
                                                      .pathAppended("qmlimportscanner")
                                                      .withExecutableSuffix();
                const FilePath qtImportPath = qtVersion->qmlPath();
                FilePaths importPaths
                    = m_qmlCodeModelInfo.value(project->activeBuildConfiguration()).qmlImportPaths;
                if (!qtImportPath.isEmpty())
                    importPaths << qtImportPath;
                const FilePaths qmlFiles = project->files([](const Node *n) -> bool {
                    const FilePath filePath = n->filePath();
                    if (!n->asFileNode() || n->isGenerated() || !n->isEnabled()
                        || filePath.isEmpty())
                        return false;
                    const MimeType mimeType
                        = mimeTypeForFile(filePath, MimeMatchMode::MatchExtension);
                    return mimeType.matchesName(Utils::Constants::QML_MIMETYPE)
                           || mimeType.matchesName(Utils::Constants::QMLUI_MIMETYPE);
                });
                qCDebug(qmlmodulesLog) << QString("Starting \"%1\" for project \"%2\" and files %3")
                                              .arg(
                                                  qmlimportscanner.toUserOutput(),
                                                  project->displayName(),
                                                  qmlFiles.toUserOutput(", "));
                const QString id = projectId(project);
                const QString qtVersionString = qtVersion->qtVersion().toString();

                const ScanStorage storage;

                m_runner.start(
                    project,
                    QtTaskTree::Group{
                        QtTaskTree::sequential,
                        storage,
                        createResponseFile(storage, qmlimportscanner, qmlFiles, importPaths),
                        runQmlImportScanner(storage, qmlimportscanner, id, qtVersionString, tracker)});
            });
    }

    QtTaskTree::ExecutableItem createResponseFile(
        const ScanStorage &storage,
        const FilePath &qmlimportscanner,
        const FilePaths &qmlFiles,
        const FilePaths &importPaths)
    {
        const auto setup = [qmlimportscanner, qmlFiles, importPaths](
                               Async<Result<TemporaryFilePath *>> &async) {
            async.setConcurrentCallData(
                [](const FilePath &qmlimportscanner,
                   const FilePaths &qmlFiles,
                   const FilePaths &importPaths) -> Result<TemporaryFilePath *> {
                    // Remove files that do not exist
                    const FilePaths actualQmlFiles = Utils::filtered(qmlFiles, &FilePath::exists);
                    const Result<FilePath> tmpDir = qmlimportscanner.tmpDir();
                    if (!tmpDir)
                        return ResultError("Failed to determine temporary directory");
                    auto tempPath = TemporaryFilePath::create(
                        tmpDir->pathAppended("qmlimportscanner.rsp"));
                    if (!tempPath) {
                        return ResultError(
                            QString("Failed to create response file: %1").arg(tempPath.error()));
                    }
                    QByteArrayList arguments = {"-qmlFiles"};
                    for (const FilePath &file : actualQmlFiles)
                        arguments << file.nativePath().toUtf8();
                    for (const FilePath &importPath : importPaths)
                        arguments << "-importPath" << importPath.nativePath().toUtf8();
                    if (Result<qint64> writeResult = (*tempPath)->filePath().writeFileContents(
                            arguments.join('\n'));
                        !writeResult) {
                        return ResultError(
                            QString("Failed to create response file: %1").arg(writeResult.error()));
                    }
                    return tempPath->release();
                },
                qmlimportscanner,
                qmlFiles,
                importPaths);
        };
        const auto done = [storage](const Async<Result<TemporaryFilePath *>> &async) {
            Result<TemporaryFilePath *> result = async.result();
            if (!result) {
                qCDebug(qmlmodulesLog) << "Failed to set up qmlimportscanner:" << result.error();
                return QtTaskTree::DoneResult::Error;
            }
            storage->reset(*result);
            return QtTaskTree::DoneResult::Success;
        };
        return AsyncTask<Result<TemporaryFilePath *>>(setup, done);
    }

    QtTaskTree::ExecutableItem runQmlImportScanner(
        const ScanStorage &storage,
        const FilePath &qmlimportscanner,
        const QString &projectId,
        const QString &qtVersionString,
        QInsightTracker *tracker)
    {
        const auto setup = [qmlimportscanner, storage](Process &process) {
            process.setCommand({qmlimportscanner, {"@" + (*storage)->filePath().nativePath()}});
        };
        const auto done = [projectId,
                           qtVersionString,
                           tracker = QPointer<QInsightTracker>(tracker)](const Process &process) {
            QJsonParseError error;
            const auto doc = QJsonDocument::fromJson(process.rawStdOut(), &error);
            if (error.error != QJsonParseError::NoError) {
                qCDebug(qmlmodulesLog) << "Parse error:" << error.errorString();
                qCDebug(qmlmodulesLog) << "At:" << error.offset;
                qCDebug(qmlmodulesLog) << "Stdout:";
                qCDebug(qmlmodulesLog) << qPrintable(process.stdOut());
                qCDebug(qmlmodulesLog) << "Stderr:";
                qCDebug(qmlmodulesLog) << qPrintable(process.stdErr());
                return;
            }
            qCDebug(qmlmodulesLog) << "Response:" << qPrintable(QString::fromUtf8(doc.toJson()));
            if (!doc.isArray()) {
                qCDebug(qmlmodulesLog) << "Unexpected response, not a JSON array";
                return;
            }
            QStringList qmlModules;
            const QJsonArray array = doc.array();
            for (const QJsonValue &v : array) {
                const QJsonObject obj = v.toObject();
                const QString name = obj.value("name").toString();
                if (name.isEmpty()) {
                    qCDebug(qmlmodulesLog) << "Skipping import without name";
                    continue;
                }
                const QString type = obj.value("type").toString();
                if (type != "module") {
                    qCDebug(qmlmodulesLog) << "Skipping import with type \"" + type + "\"";
                    continue;
                }
                qmlModules += name;
            }
            if (qmlModules.isEmpty())
                return;
            // - the list of modules can contain all kinds of user defined modules too, since
            //   we need to add the user import paths to catch the QDS modules
            // - a hardcoded whitelist here would be ugly because older Qt Creator versions would
            //   filter out new QML modules in newer Qt versions
            // - so send a hash of the module "name" to telemetry, and the script that processes
            //   that data has a mapping of hash -> known Qt module
            const QStringList moduleHashes = Utils::transform(qmlModules, hashed);
            QJsonObject json;
            json.insert("projectid", projectId);
            json.insert("qmlmodules", QJsonArray::fromStringList(moduleHashes));
            json.insert("qtversion", qtVersionString);
            const QString jsonStr = QString::fromUtf8(
                QJsonDocument(json).toJson(QJsonDocument::Compact));
            qCDebug(qmlmodulesLog) << qPrintable(jsonStr);
            addEvent(tracker, "QmlModules", jsonStr);
        };
        return ProcessTask(setup, done);
    }

    bool shouldStartCollectingFor(Project *project)
    {
        if (!BuildManager::isBuilding(project)) {
            m_buildingProjects.remove(project);
            return false;
        }
        if (!Utils::insert(m_buildingProjects, project)) // already seen before as "building"
            return false;

        // don't interrupt a running scan
        return !m_runner.isKeyRunning(project);
    }

    QHash<BuildConfiguration *, QmlCodeModelInfo> m_qmlCodeModelInfo;
    QSet<Project *> m_buildingProjects;
    QMappedTaskTreeRunner<Project *> m_runner;
};

class QtExample : public QObject
{
    Q_OBJECT
public:
    QtExample(QInsightTracker *tracker)
    {
        connect(ProjectManager::instance(),
                &ProjectManager::projectAdded,
                this,
                [this, tracker](Project *project) {
                    connect(project, &Project::anyParsingFinished, this, [project, tracker] {
                        const QtVersions versions = QtVersionManager::versions();
                        for (QtVersion *qtVersion : versions) {
                            const FilePath examplesPath = qtVersion->examplesPath();
                            if (examplesPath.isEmpty())
                                continue;
                            if (!project->projectFilePath().isChildOf(examplesPath))
                                continue;
                            const FilePath examplePath = project->projectFilePath()
                                                             .relativeChildPath(examplesPath)
                                                             .parentDir();
                            const QString exampleHash = hashed(examplePath.path());
                            QJsonObject json;
                            json.insert("projectid", projectId(project));
                            json.insert("qtexample", exampleHash);
                            json.insert("qtversion", qtVersion->qtVersion().toString());
                            const QString jsonStr = QString::fromUtf8(
                                QJsonDocument(json).toJson(QJsonDocument::Compact));
                            qCDebug(qtexampleLog) << qPrintable(jsonStr);
                            addEvent(tracker, "QtExample", jsonStr);
                            return;
                        }
                    });
                });
    }
};

static const char licenseKey[] = "QtLicenseSchema";
class QtLicense : public QObject
{
    Q_OBJECT
public:
    static QObject *getLicensechecker()
    {
        return PluginManager::getObjectByName("LicenseCheckerPlugin");
    }

    QtLicense(QInsightTracker *tracker)
        : m_tracker(tracker)
    {
        QObject *licensechecker = getLicensechecker();
        if (!licensechecker) {
            addEvent(tracker, licenseKey, "opensource");
            return;
        }
        connect(
            licensechecker, SIGNAL(licenseInfoAvailableChanged()), this, SLOT(reportLicenseInfo()));
        reportLicenseInfo();
    }

private slots:
    void reportLicenseInfo()
    {
        QObject *licensechecker = getLicensechecker();
        QTC_ASSERT(licensechecker, return);
        bool available = false;
        QTC_CHECK(
            QMetaObject::invokeMethod(
                licensechecker,
                "isLicenseInfoAvailable",
                Qt::DirectConnection,
                Q_RETURN_ARG(bool, available)));
        if (!available)
            return;
        QString schema;
        QTC_CHECK(
            QMetaObject::invokeMethod(
                licensechecker,
                "licenseSchema",
                Qt::DirectConnection,
                Q_RETURN_ARG(QString, schema)));
        addEvent(m_tracker, licenseKey, schema);
    }

private:
    QInsightTracker *m_tracker = nullptr;
};

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;
        auto moreInformationLabel = new QLabel(
            "<a "
            "href=\"qthelp://org.qt-project.qtcreator/doc/"
            "creator-how-to-collect-usage-statistics.html\">"
            + 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(); });
    }
};

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 defaultSubmissionInterval()
{
    using namespace std::literals;
    return std::chrono::hours(1) / 1s;
}

static constexpr int defaultBatchSize()
{
    return 100;
}

static int fromEnvironment(const QString &key, int defaultValue)
{
    bool ok = false;
    const int env = qtcEnvironmentVariableIntValue(key, &ok);
    if (ok)
        return env;
    return defaultValue;
}

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(
                fromEnvironment("QTC_INSIGHT_SUBMISSIONINTERVAL", defaultSubmissionInterval()));
            config->setBatchSize(fromEnvironment("QTC_INSIGHT_BATCHSIZE", defaultBatchSize()));
            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";
    InfoBar *infoBar = ICore::popupInfoBar();
    if (!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.setTitle("Usage Statistics");
    entry.addCustomButton(configureButtonInfoText, [infoBar] {
        infoBar->removeInfo(kInfoBarId);
        ICore::showOptionsDialog(kSettingsPageId);
    });
    entry.setCancelButtonInfo(cancelButtonInfoText, {});
    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()));
    // module and example telemetry require QInsightTracker::contextData to
    // work reliably, because the key of QInsightTracker::interaction is limited to 255 characters.
#if QT_VERSION >= QT_WITH_CONTEXTDATA
    m_providers.push_back(std::make_unique<QtModules>(m_tracker.get()));
    m_providers.push_back(std::make_unique<QtExample>(m_tracker.get()));
    m_providers.push_back(std::make_unique<QmlModules>(m_tracker.get()));
#endif

    m_providers.push_back(std::make_unique<UILanguage>(m_tracker.get()));
    m_providers.push_back(std::make_unique<QtLicense>(m_tracker.get()));

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

    //Android Manifest enabled
    m_providers.push_back(std::make_unique<AndroidManifestGuiEnabled>(m_tracker.get()));

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

} // namespace UsageStatistic::Internal

#include "usagestatisticplugin.moc"