summaryrefslogtreecommitdiff
path: root/src/main-lib/main.cpp
blob: a014029446c9835aeefdc806712bb230a2a008a7 (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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
/****************************************************************************
**
** Copyright (C) 2021 The Qt Company Ltd.
** Copyright (C) 2019 Luxoft Sweden AB
** Copyright (C) 2018 Pelagicore AG
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtApplicationManager module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 or (at your option) any later version
** approved by the KDE Free Qt Foundation. The licenses are as published by
** the Free Software Foundation and appearing in the file LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <memory>
#include <qglobal.h>

#if defined(QT_DBUS_LIB) && !defined(AM_DISABLE_EXTERNAL_DBUS_INTERFACES)
#  include <QDBusConnection>
#  include <QDBusAbstractAdaptor>
#  include "dbusdaemon.h"
#  include "dbuspolicy.h"
#  include "applicationmanagerdbuscontextadaptor.h"
#  include "packagemanagerdbuscontextadaptor.h"
#  include "notificationmanagerdbuscontextadaptor.h"
#endif

#include <QFile>
#include <QDir>
#include <QStringList>
#include <QVariant>
#include <QFileInfo>
#include <QQmlContext>
#include <QQmlComponent>
#include <QQmlApplicationEngine>
#include <QTimer>
#include <QUrl>
#include <QLibrary>
#include <QFunctionPointer>
#include <QProcess>
#include <QQmlDebuggingEnabler>
#include <QNetworkInterface>
#include <private/qabstractanimation_p.h>
#include <QGuiApplication>
#include <QQuickView>
#include <QQuickItem>
#include <QInputDevice>
#include <private/qopenglcontext_p.h>
#include <QLocalServer>

#include "global.h"
#include "logging.h"
#include "main.h"
#include "configuration.h"
#include "applicationmanager.h"
#include "package.h"
#include "packagemanager.h"
#include "packagedatabase.h"
#include "installationreport.h"
#include "yamlpackagescanner.h"
#if !defined(AM_DISABLE_INSTALLER)
#  include "applicationinstaller.h"
#  include "sudo.h"
#  include "packageutilities.h"
#endif
#include "runtimefactory.h"
#include "containerfactory.h"
#include "quicklauncher.h"
#if defined(AM_MULTI_PROCESS)
#  include "processcontainer.h"
#  include "nativeruntime.h"
#endif
#include "plugincontainer.h"
#include "notificationmanager.h"
#include "qmlinprocessruntime.h"
#include "qmlinprocessapplicationinterface.h"
#include "qml-utilities.h"
#include "dbus-utilities.h"
#include "intentserver.h"
#include "intentaminterface.h"

#include "windowmanager.h"
#include "qmlinprocessapplicationmanagerwindow.h"
#if defined(QT_DBUS_LIB) && !defined(AM_DISABLE_EXTERNAL_DBUS_INTERFACES)
#  include "windowmanagerdbuscontextadaptor.h"
#endif
#include "windowframetimer.h"
#include "gpustatus.h"

#include "configuration.h"
#include "utilities.h"
#include "exception.h"
#include "crashhandler.h"
#include "qmllogger.h"
#include "startuptimer.h"
#include "unixsignalhandler.h"

// monitor-lib
#include "cpustatus.h"
#include "iostatus.h"
#include "memorystatus.h"
#include "monitormodel.h"
#include "processstatus.h"

#include "../plugin-interfaces/startupinterface.h"


QT_BEGIN_NAMESPACE_AM

// We need to do some things BEFORE the Q*Application constructor runs, so we're using this
// old trick to do this hooking transparently for the user of the class.
int &Main::preConstructor(int &argc)
{
#if !defined(AM_DISABLE_INSTALLER)
    // try to set a reasonable locale - we later verify with checkCorrectLocale() if we succeeded
    PackageUtilities::ensureCorrectLocale();
#endif
    return argc;
}

Main::Main(int &argc, char **argv)
    : MainBase(SharedMain::preConstructor(Main::preConstructor(argc)), argv)
    , SharedMain()
{
    m_isRunningOnEmbedded =
#if defined(Q_OS_LINUX)
            !qEnvironmentVariableIsSet("XDG_CURRENT_DESKTOP");
#else
            false;
#endif

    // this might be needed later on by the native runtime to find a suitable qml runtime launcher
    setProperty("_am_build_dir", qSL(AM_BUILD_DIR));

    UnixSignalHandler::instance()->install(UnixSignalHandler::ForwardedToEventLoopHandler,
                                           { SIGINT, SIGTERM },
                                           [](int sig) {
        UnixSignalHandler::instance()->resetToDefault(sig);
        if (sig == SIGINT)
            fputs("\n*** received SIGINT / Ctrl+C ... exiting ***\n\n", stderr);
        static_cast<Main *>(QCoreApplication::instance())->shutDown();
    });
    StartupTimer::instance()->checkpoint("after application constructor");
}

Main::~Main()
{
    delete m_engine;

    delete m_intentServer;
    delete m_notificationManager;
    delete m_windowManager;
    delete m_view;
    delete m_applicationManager;
#if !defined(AM_DISABLE_INSTALLER)
    delete m_applicationInstaller;
#endif
    delete m_packageManager;
    delete m_quickLauncher;

    delete RuntimeFactory::instance();
    delete ContainerFactory::instance();
    delete StartupTimer::instance();
}

/*! \internal
    The caller has to make sure that cfg will be available even after this function returns:
    we will access the cfg object from delayed init functions via lambdas!
*/
void Main::setup(const Configuration *cfg, const QStringList &deploymentWarnings) Q_DECL_NOEXCEPT_EXPR(false)
{
    Q_UNUSED(deploymentWarnings)
    setup(cfg);
}

void Main::setup(const Configuration *cfg) Q_DECL_NOEXCEPT_EXPR(false)
{
    // basics that are needed in multiple setup functions below
    m_noSecurity = cfg->noSecurity();
    m_builtinAppsManifestDirs = cfg->builtinAppsManifestDirs();
    m_installationDir = cfg->installationDir();
    m_installationDirMountPoint = cfg->installationDirMountPoint();
    m_documentDir = cfg->documentDir();

    CrashHandler::setCrashActionConfiguration(cfg->managerCrashAction());
    setupQmlDebugging(cfg->qmlDebugging());
    if (!cfg->dltId().isEmpty() || !cfg->dltDescription().isEmpty())
        Logging::setSystemUiDltId(cfg->dltId().toLocal8Bit(), cfg->dltDescription().toLocal8Bit());
    Logging::setDltLongMessageBehavior(cfg->dltLongMessageBehavior());
    Logging::registerUnregisteredDltContexts();
    setupLogging(cfg->verbose(), cfg->loggingRules(), cfg->messagePattern(), cfg->useAMConsoleLogger());

    registerResources(cfg->resources());

    setupOpenGL(cfg->openGLConfiguration());
    setupIconTheme(cfg->iconThemeSearchPaths(), cfg->iconThemeName());

    loadStartupPlugins(cfg->pluginFilePaths("startup"));
    parseSystemProperties(cfg->rawSystemProperties());

    setMainQmlFile(cfg->mainQmlFile());
    setupSingleOrMultiProcess(cfg->forceSingleProcess(), cfg->forceMultiProcess());
    setupRuntimesAndContainers(cfg->runtimeConfigurations(), cfg->openGLConfiguration(),
                               cfg->containerConfigurations(), cfg->pluginFilePaths("container"),
                               cfg->iconThemeSearchPaths(), cfg->iconThemeName());

    loadPackageDatabase(cfg->clearCache() || cfg->noCache(), cfg->singleApp());

    setupSingletons(cfg->containerSelectionConfiguration(), cfg->quickLaunchRuntimesPerContainer(),
                    cfg->quickLaunchIdleLoad());

    if (!cfg->disableIntents()) {
        setupIntents(cfg->intentTimeoutForDisambiguation(), cfg->intentTimeoutForStartApplication(),
                     cfg->intentTimeoutForReplyFromApplication(), cfg->intentTimeoutForReplyFromSystem());
    }

    registerPackages();

    if (m_installationDir.isEmpty() || cfg->disableInstaller()) {
        StartupTimer::instance()->checkpoint("skipping installer");
    } else {
        setupInstaller(cfg->developmentMode(), cfg->allowUnsignedPackages(), cfg->caCertificates(),
                       std::bind(&Configuration::applicationUserIdSeparation, cfg,
                                 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }
    setLibraryPaths(libraryPaths() + cfg->pluginPaths());
    setupQmlEngine(cfg->importPaths(), cfg->style());
    setupWindowTitle(QString(), cfg->windowIcon());
    setupWindowManager(cfg->waylandSocketName(), cfg->waylandExtraSockets(),
                       cfg->slowAnimations(), cfg->noUiWatchdog());

    setupDBus(std::bind(&Configuration::dbusRegistration, cfg, std::placeholders::_1),
              std::bind(&Configuration::dbusPolicy, cfg, std::placeholders::_1));
}

bool Main::isSingleProcessMode() const
{
    return m_isSingleProcessMode;
}

bool Main::isRunningOnEmbedded() const
{
    return m_isRunningOnEmbedded;
}

void Main::shutDown(int exitCode)
{
    enum {
        ApplicationManagerDown = 0x01,
        QuickLauncherDown = 0x02,
        WindowManagerDown = 0x04
    };

    static int down = 0;

    static auto checkShutDownFinished = [exitCode](int nextDown) {
        down |= nextDown;
        if (down == (ApplicationManagerDown | QuickLauncherDown | WindowManagerDown)) {
            down = 0;
            QCoreApplication::exit(exitCode);
        }
    };

    if (m_applicationManager) {
        connect(m_applicationManager, &ApplicationManager::shutDownFinished,
                this, []() { checkShutDownFinished(ApplicationManagerDown); });
        m_applicationManager->shutDown();
    }
    if (m_quickLauncher) {
        connect(m_quickLauncher, &QuickLauncher::shutDownFinished,
                this, []() { checkShutDownFinished(QuickLauncherDown); });
        m_quickLauncher->shutDown();
    } else {
        down |= QuickLauncherDown;
    }
    if (m_windowManager) {
        connect(m_windowManager, &WindowManager::shutDownFinished,
                this, []() { checkShutDownFinished(WindowManagerDown); });
        m_windowManager->shutDown();
    }

    QTimer::singleShot(5000, this, [exitCode] {
        QStringList resources;
        if (!(down & ApplicationManagerDown))
            resources << qSL("runtimes");
        if (!(down & QuickLauncherDown))
            resources << qSL("quick-launchers");
        if (!(down & WindowManagerDown))
            resources << qSL("windows");
        qCCritical(LogSystem, "There are still resources in use (%s). Check your System UI implementation. "
                              "Exiting anyhow.", resources.join(qSL(", ")).toLocal8Bit().constData());
        QCoreApplication::exit(exitCode);
    });
}

QQmlApplicationEngine *Main::qmlEngine() const
{
    return m_engine;
}

void Main::registerResources(const QStringList &resources) const
{
    for (const QString &resource: resources) {
        if (!loadResource(resource))
            qCWarning(LogSystem) << "Cannot register resource:" << resource;
    }
}

void Main::loadStartupPlugins(const QStringList &startupPluginPaths) Q_DECL_NOEXCEPT_EXPR(false)
{
    m_startupPlugins = loadPlugins<StartupInterface>("startup", startupPluginPaths);
    StartupTimer::instance()->checkpoint("after startup-plugin load");
}

void Main::parseSystemProperties(const QVariantMap &rawSystemProperties)
{
    m_systemProperties.resize(SP_SystemUi + 1);
    QVariantMap rawMap = rawSystemProperties;

    m_systemProperties[SP_ThirdParty] = rawMap.value(qSL("public")).toMap();

    m_systemProperties[SP_BuiltIn] = m_systemProperties.at(SP_ThirdParty);
    const QVariantMap pro = rawMap.value(qSL("protected")).toMap();
    for (auto it = pro.cbegin(); it != pro.cend(); ++it)
        m_systemProperties[SP_BuiltIn].insert(it.key(), it.value());

    m_systemProperties[SP_SystemUi] = m_systemProperties.at(SP_BuiltIn);
    const QVariantMap pri = rawMap.value(qSL("private")).toMap();
    for (auto it = pri.cbegin(); it != pri.cend(); ++it)
        m_systemProperties[SP_SystemUi].insert(it.key(), it.value());

    for (auto iface : qAsConst(m_startupPlugins))
        iface->initialize(m_systemProperties.at(SP_SystemUi));
}

void Main::setMainQmlFile(const QString &mainQml) Q_DECL_NOEXCEPT_EXPR(false)
{
    // For some weird reason, QFile cannot cope with "qrc:/" and QUrl cannot cope with ":/",
    // so we have to translate ourselves between those two "worlds".

    m_mainQml = filePathToUrl(mainQml, QDir::currentPath());
    m_mainQmlLocalFile = urlToLocalFilePath(m_mainQml);

    if (!QFileInfo(m_mainQmlLocalFile).isFile()) {
        if (mainQml.isEmpty())
            throw Exception("No main QML file specified");

        // basically accept schemes other than file and qrc:
        if (!m_mainQmlLocalFile.isEmpty())
            throw Exception("Invalid main QML file specified: %1").arg(mainQml);
    }
}

void Main::setupSingleOrMultiProcess(bool forceSingleProcess, bool forceMultiProcess) Q_DECL_NOEXCEPT_EXPR(false)
{
    m_isSingleProcessMode = forceSingleProcess;
    if (forceMultiProcess && m_isSingleProcessMode)
        throw Exception("You cannot enforce multi- and single-process mode at the same time.");

#if !defined(AM_MULTI_PROCESS)
    if (forceMultiProcess)
        throw Exception("This application manager build is not multi-process capable.");
    m_isSingleProcessMode = true;
#endif
}

void Main::setupRuntimesAndContainers(const QVariantMap &runtimeConfigurations, const QVariantMap &openGLConfiguration,
                                      const QVariantMap &containerConfigurations, const QStringList &containerPluginPaths,
                                      const QStringList &iconThemeSearchPaths, const QString &iconThemeName)
{
    if (m_isSingleProcessMode) {
        RuntimeFactory::instance()->registerRuntime(new QmlInProcessRuntimeManager());
        RuntimeFactory::instance()->registerRuntime(new QmlInProcessRuntimeManager(qSL("qml")));
    } else {
        RuntimeFactory::instance()->registerRuntime(new QmlInProcessRuntimeManager());
#if defined(AM_MULTI_PROCESS)
        RuntimeFactory::instance()->registerRuntime(new NativeRuntimeManager());
        RuntimeFactory::instance()->registerRuntime(new NativeRuntimeManager(qSL("qml")));
        //RuntimeFactory::instance()->registerRuntime(new NativeRuntimeManager(qSL("html")));

        ContainerFactory::instance()->registerContainer(new ProcessContainerManager());
#endif
        auto containerPlugins = loadPlugins<ContainerManagerInterface>("container", containerPluginPaths);
        for (auto iface : qAsConst(containerPlugins))
            ContainerFactory::instance()->registerContainer(new PluginContainerManager(iface));
    }
    for (auto iface : qAsConst(m_startupPlugins))
        iface->afterRuntimeRegistration();

    ContainerFactory::instance()->setConfiguration(containerConfigurations);
    RuntimeFactory::instance()->setConfiguration(runtimeConfigurations);
    RuntimeFactory::instance()->setSystemOpenGLConfiguration(openGLConfiguration);
    RuntimeFactory::instance()->setIconTheme(iconThemeSearchPaths, iconThemeName);
    RuntimeFactory::instance()->setSystemProperties(m_systemProperties.at(SP_ThirdParty),
                                                    m_systemProperties.at(SP_BuiltIn));

    StartupTimer::instance()->checkpoint("after runtime registration");
}

void Main::loadPackageDatabase(bool recreateDatabase, const QString &singlePackage) Q_DECL_NOEXCEPT_EXPR(false)
{
    if (!singlePackage.isEmpty()) {
        m_packageDatabase = new PackageDatabase(singlePackage);
    } else {
        m_packageDatabase = new PackageDatabase(m_builtinAppsManifestDirs, m_installationDir,
                                                m_installationDirMountPoint);
        if (!recreateDatabase)
            m_packageDatabase->enableLoadFromCache();
        m_packageDatabase->enableSaveToCache();
    }
    m_packageDatabase->parse();

    const QVector<PackageInfo *> allPackages =
            m_packageDatabase->builtInPackages()
            + m_packageDatabase->installedPackages();

    for (auto package : allPackages) {
        // check that the runtimes are supported in this instance of the AM
        auto apps = package->applications();

        for (const auto app : apps) {
            if (!RuntimeFactory::instance()->manager(app->runtimeName()))
                qCWarning(LogSystem) << "Application" << app->id() << "uses an unknown runtime:" << app->runtimeName();
        }
    }

    StartupTimer::instance()->checkpoint("after package database loading");
}

void Main::setupIntents(int disambiguationTimeout, int startApplicationTimeout,
                        int replyFromApplicationTimeout, int replyFromSystemTimeout) Q_DECL_NOEXCEPT_EXPR(false)
{
    m_intentServer = IntentAMImplementation::createIntentServerAndClientInstance(m_packageManager,
                                                                                 disambiguationTimeout,
                                                                                 startApplicationTimeout,
                                                                                 replyFromApplicationTimeout,
                                                                                 replyFromSystemTimeout);
    StartupTimer::instance()->checkpoint("after IntentServer instantiation");
}

void Main::setupSingletons(const QList<QPair<QString, QString>> &containerSelectionConfiguration,
                           int quickLaunchRuntimesPerContainer,
                           qreal quickLaunchIdleLoad) Q_DECL_NOEXCEPT_EXPR(false)
{
    m_packageManager = PackageManager::createInstance(m_packageDatabase, m_documentDir);
    m_applicationManager = ApplicationManager::createInstance(m_isSingleProcessMode);

    if (m_noSecurity)
        m_applicationManager->setSecurityChecksEnabled(false);

    m_applicationManager->setSystemProperties(m_systemProperties.at(SP_SystemUi));
    m_applicationManager->setContainerSelectionConfiguration(containerSelectionConfiguration);

    StartupTimer::instance()->checkpoint("after ApplicationManager instantiation");

    m_notificationManager = NotificationManager::createInstance();
    StartupTimer::instance()->checkpoint("after NotificationManager instantiation");

    if (quickLaunchRuntimesPerContainer > 0) {
        m_quickLauncher = QuickLauncher::createInstance(quickLaunchRuntimesPerContainer, quickLaunchIdleLoad);
        StartupTimer::instance()->checkpoint("after quick-launcher setup");
    } else {
        qCDebug(LogSystem) << "Not setting up the quick-launch pool (runtimesPerContainer is 0)";
    }
}

void Main::setupInstaller(bool devMode, bool allowUnsigned, const QStringList &caCertificatePaths,
                          const std::function<bool(uint *, uint *, uint *)> &userIdSeparation) Q_DECL_NOEXCEPT_EXPR(false)
{
#if !defined(AM_DISABLE_INSTALLER)
    if (Q_UNLIKELY(!PackageUtilities::checkCorrectLocale())) {
        // we should really throw here, but so many embedded systems are badly set up
        qCWarning(LogDeployment) << "The appman installer needs a UTF-8 locale to work correctly: "
                                    "even automatically switching to C.UTF-8 or en_US.UTF-8 failed.";
    }

    // make sure the installation and document dirs are valid
    Q_ASSERT(!m_installationDir.isEmpty());
    const auto instPath = QDir(m_installationDir).canonicalPath();
    const auto docPath = m_documentDir.isEmpty() ? QString { }
                                                 : QDir(m_documentDir).canonicalPath();

    if (!docPath.isEmpty() && (instPath.startsWith(docPath) || docPath.startsWith(instPath)))
        throw Exception("either installationDir or documentDir cannot be a sub-directory of the other");

    // we only output these deployment warnings, if we are on embedded, applicationUserIdSeparation
    // is enabled and either...
    if (isRunningOnEmbedded() && userIdSeparation && userIdSeparation(nullptr, nullptr, nullptr)) {
        // ... the user forgot to call Sudo::forkServer() quite early in main()
        if (Q_UNLIKELY(!SudoClient::instance())) {
            qCWarning(LogDeployment) << "In order for the package-manager to support \"applicationUserIdSeparation\", "
                                        "please call Sudo::forkServer() as early as possible in main()";
        // ... or the user called Sudo::forkServer() explicitly AND that called failed.
        } else if (Q_UNLIKELY(SudoClient::instance()->isFallbackImplementation())) {
            qCWarning(LogDeployment) << "In order for the package-manager to support \"applicationUserIdSeparation\", "
                                        "please run as root either via sudo or SUID (preferred)";
        }
    }

    if (Q_UNLIKELY(hardwareId().isEmpty()))
        throw Exception("the installer is enabled, but the device-id is empty");

    if (!isRunningOnEmbedded()) { // this is just for convenience sake during development
        if (Q_UNLIKELY(!m_installationDir.isEmpty() && !QDir::root().mkpath(m_installationDir)))
            throw Exception("could not create package installation directory: \'%1\'").arg(m_installationDir);
        if (Q_UNLIKELY(!m_documentDir.isEmpty() && !QDir::root().mkpath(m_documentDir)))
            throw Exception("could not create document directory for packages: \'%1\'").arg(m_documentDir);
    }

    StartupTimer::instance()->checkpoint("after installer setup checks");

    m_applicationInstaller = ApplicationInstaller::createInstance(m_packageManager);

    if (devMode)
        m_packageManager->setDevelopmentMode(true);

    if (m_noSecurity || allowUnsigned)
        m_packageManager->setAllowInstallationOfUnsignedPackages(true);

    if (!m_noSecurity) {
        QList<QByteArray> caCertificateList;

        for (const auto &caFile : caCertificatePaths) {
            QFile f(caFile);
            if (Q_UNLIKELY(!f.open(QFile::ReadOnly)))
                throw Exception(f, "could not open CA-certificate file");
            QByteArray cert = f.readAll();
            if (Q_UNLIKELY(cert.isEmpty()))
                throw Exception(f, "CA-certificate file is empty");
            caCertificateList << cert;
        }
        m_packageManager->setCACertificates(caCertificateList);
    }

    uint minUserId, maxUserId, commonGroupId;
    if (userIdSeparation && userIdSeparation(&minUserId, &maxUserId, &commonGroupId)) {
#  if defined(Q_OS_LINUX)
        if (!m_packageManager->enableApplicationUserIdSeparation(minUserId, maxUserId, commonGroupId))
            throw Exception("could not enable application user-id separation in the installer.");
#  else
        qCCritical(LogSystem) << "WARNING: application user-id separation requested, but not possible on this platform.";
#  endif // Q_OS_LINUX
    }

    m_packageManager->enableInstaller();

    StartupTimer::instance()->checkpoint("after installer setup");
#else
    Q_UNUSED(devMode)
    Q_UNUSED(allowUnsigned)
    Q_UNUSED(caCertificatePaths)
    Q_UNUSED(userIdSeparation)
#endif // AM_DISABLE_INSTALLER
}

void Main::registerPackages()
{
    // the installation dir might not be mounted yet, so we have to watch for the package
    // DB's signal and then register these packages later in the already running system
    if (!(m_packageDatabase->parsedPackageLocations() & PackageDatabase::Installed)) {
        connect(m_packageDatabase, &PackageDatabase::installedPackagesParsed,
                m_packageManager, [this]() {
            // we are not in main() anymore: we can't just throw
            try {
                m_packageManager->registerPackages();
            } catch (const Exception &e) {
                qCCritical(LogInstaller) << "Failed to register packages:" << e.what();
                std::abort(); // there is no qCFatal()
            }
        });
        StartupTimer::instance()->checkpoint("after package registration (delayed)");
    } else {
        m_packageManager->registerPackages();
        StartupTimer::instance()->checkpoint("after package registration");
    }
}

void Main::setupQmlEngine(const QStringList &importPaths, const QString &quickControlsStyle)
{
    if (!quickControlsStyle.isEmpty())
        qputenv("QT_QUICK_CONTROLS_STYLE", quickControlsStyle.toLocal8Bit());

    qmlRegisterType<QmlInProcessNotification>("QtApplicationManager", 2, 0, "Notification");
    qmlRegisterType<QmlInProcessApplicationManagerWindow>("QtApplicationManager.Application", 2, 0, "ApplicationManagerWindow");

    // monitor-lib
    qmlRegisterType<CpuStatus>("QtApplicationManager", 2, 0, "CpuStatus");
    qmlRegisterType<WindowFrameTimer>("QtApplicationManager", 2, 0, "FrameTimer");
    qmlRegisterType<GpuStatus>("QtApplicationManager", 2, 0, "GpuStatus");
    qmlRegisterType<IoStatus>("QtApplicationManager", 2, 0, "IoStatus");
    qmlRegisterType<MemoryStatus>("QtApplicationManager", 2, 0, "MemoryStatus");
    qmlRegisterType<MonitorModel>("QtApplicationManager", 2, 0, "MonitorModel");
    qmlRegisterType<ProcessStatus>("QtApplicationManager.SystemUI", 2, 0, "ProcessStatus");

    StartupTimer::instance()->checkpoint("after QML registrations");

    m_engine = new QQmlApplicationEngine(this);
    disconnect(m_engine, &QQmlEngine::quit, qApp, nullptr);
    disconnect(m_engine, &QQmlEngine::exit, qApp, nullptr);
    connect(m_engine, &QQmlEngine::quit, this, [this]() { shutDown(); });
    connect(m_engine, &QQmlEngine::exit, this, [this](int retCode) { shutDown(retCode); });
    CrashHandler::setQmlEngine(m_engine);
    new QmlLogger(m_engine);
    m_engine->setOutputWarningsToStandardError(false);
    m_engine->setImportPathList(m_engine->importPathList() + importPaths);
    m_engine->rootContext()->setContextProperty(qSL("StartupTimer"), StartupTimer::instance());

    StartupTimer::instance()->checkpoint("after QML engine instantiation");
}

void Main::setupWindowTitle(const QString &title, const QString &iconPath)
{
    // For development only: set an icon, so you know which window is the AM
    if (Q_UNLIKELY(!isRunningOnEmbedded())) {
        if (!iconPath.isEmpty())
            QGuiApplication::setWindowIcon(QIcon(iconPath));
        if (!title.isEmpty())
            QGuiApplication::setApplicationDisplayName(title);
    }
}

void Main::setupWindowManager(const QString &waylandSocketName, const QVariantList &waylandExtraSockets,
                              bool slowAnimations, bool uiWatchdog)
{
    QUnifiedTimer::instance()->setSlowModeEnabled(slowAnimations);

    m_windowManager = WindowManager::createInstance(m_engine, waylandSocketName);
    m_windowManager->setSlowAnimations(slowAnimations);
    m_windowManager->enableWatchdog(!uiWatchdog);

#if defined(QT_WAYLANDCOMPOSITOR_LIB)
    connect(&m_windowManager->internalSignals, &WindowManagerInternalSignals::compositorAboutToBeCreated,
            this, [this, waylandExtraSockets] {
        // This needs to be delayed until directly before creating the Wayland compositor.
        // Otherwise we have a "dangling" socket you cannot connect to.

        for (const auto &v : waylandExtraSockets) {
            const QVariantMap &wes = v.toMap();

            const QString path = wes.value(qSL("path")).toString();

            if (path.isEmpty())
                continue;

            try {
                QFileInfo fi(path);
                if (!fi.dir().mkpath(qSL(".")))
                    throw Exception("could not create path to extra Wayland socket: %1").arg(path);

                auto sudo = SudoClient::instance();

                if (!sudo || sudo->isFallbackImplementation()) {
                    if (!QLocalServer::removeServer(path)) {
                        throw Exception("could not clean up leftover extra Wayland socket %1").arg(path);
                    }
                } else {
                    sudo->removeRecursive(path);
                }

                QScopedPointer<QLocalServer> extraSocket(new QLocalServer);
                extraSocket->setMaxPendingConnections(0); // disable Qt's new connection handling
                if (!extraSocket->listen(path)) {
                    throw Exception("could not listen on extra Wayland socket %1: %2")
                        .arg(path, extraSocket->errorString());
                }
                int mode = wes.value(qSL("permissions"), -1).toInt();
                int uid = wes.value(qSL("userId"), -1).toInt();
                int gid = wes.value(qSL("groupId"), -1).toInt();

                QByteArray encodedPath = QFile::encodeName(path);

                if ((mode > 0) || (uid != -1) || (gid != -1)) {
                    if (!sudo || sudo->isFallbackImplementation()) {
                        if (mode > 0) {
                            if (::chmod(encodedPath, static_cast<mode_t>(mode)) != 0)
                                throw Exception(errno, "could not chmod(mode: %1) the extra Wayland socket %2")
                                    .arg(QString::number(mode, 8), path);
                        }
                        if ((uid != -1) || (gid != -1)) {
                            if (::chown(encodedPath, static_cast<uid_t>(uid), static_cast<gid_t>(gid)) != 0)
                                throw Exception(errno, "could not chown(uid: %1, gid: %2) the extra Wayland socket %3")
                                    .arg(uid).arg(gid).arg(path);
                        }
                    } else {
                        if (!sudo->setOwnerAndPermissionsRecursive(path, static_cast<uid_t>(uid),
                                                                   static_cast<gid_t>(gid),
                                                                   static_cast<mode_t>(mode))) {
                            throw Exception(Error::IO, "could not change the owner to %1:%2 and the permission"
                                                       " bits to %3 for the extra Wayland socket %4: %5")
                                    .arg(uid).arg(gid).arg(mode, 0, 8).arg(path).arg(sudo->lastError());
                        }
                        // if we changed the owner, ~QLocalServer might not be able to clean up the
                        // socket inode, so we need to sudo this removal as well
                        QObject::connect(extraSocket.data(), &QObject::destroyed, [path, sudo]() {
                            sudo->removeRecursive(path);
                        });
                    }
                }

                m_windowManager->addWaylandSocket(extraSocket.take());
            } catch (const std::exception &e) {
                qCCritical(LogSystem) << "ERROR:" << e.what();
            }
        }
    });
#else
    Q_UNUSED(waylandExtraSockets)
#endif

    QObject::connect(&m_applicationManager->internalSignals, &ApplicationManagerInternalSignals::newRuntimeCreated,
                     m_windowManager, &WindowManager::setupInProcessRuntime);
    QObject::connect(m_applicationManager, &ApplicationManager::applicationWasActivated,
                     m_windowManager, &WindowManager::raiseApplicationWindow);
}

void Main::loadQml(bool loadDummyData) Q_DECL_NOEXCEPT_EXPR(false)
{
    for (auto iface : qAsConst(m_startupPlugins))
        iface->beforeQmlEngineLoad(m_engine);

    // protect our namespace from this point onward
    qmlProtectModule("QtApplicationManager", 1);
    qmlProtectModule("QtApplicationManager.SystemUI", 1);
    qmlProtectModule("QtApplicationManager", 2);
    qmlProtectModule("QtApplicationManager.SystemUI", 2);

    if (Q_UNLIKELY(loadDummyData)) {
        if (m_mainQmlLocalFile.isEmpty()) {
            qCDebug(LogQml) << "Not loading QML dummy data on non-local URL" << m_mainQml;
        } else {
            loadQmlDummyDataFiles(m_engine, QFileInfo(m_mainQmlLocalFile).path());
            StartupTimer::instance()->checkpoint("after loading dummy-data");
        }
    }

    m_engine->load(m_mainQml);
    if (Q_UNLIKELY(m_engine->rootObjects().isEmpty()))
        throw Exception("Qml scene does not have a root object");

    for (auto iface : qAsConst(m_startupPlugins))
        iface->afterQmlEngineLoad(m_engine);

    StartupTimer::instance()->checkpoint("after loading main QML file");
}

void Main::showWindow(bool showFullscreen)
{
    setQuitOnLastWindowClosed(false);
    connect(this, &QGuiApplication::lastWindowClosed, this, [this]() { shutDown(); });

    QQuickWindow *window = nullptr;
    QObject *rootObject = m_engine->rootObjects().constFirst();

    if (!rootObject->isWindowType()) {
        QQuickItem *contentItem = qobject_cast<QQuickItem *>(rootObject);
        if (contentItem) {
            m_view = new QQuickView(m_engine, nullptr);
            m_view->setContent(m_mainQml, nullptr, rootObject);
            m_view->setVisible(contentItem->isVisible());
            connect(contentItem, &QQuickItem::visibleChanged, this, [this, contentItem]() {
                m_view->setVisible(contentItem->isVisible());
            });
            window = m_view;
        }
    } else {
        window = qobject_cast<QQuickWindow *>(rootObject);
        if (!m_engine->incubationController())
            m_engine->setIncubationController(window->incubationController());
    }

    for (auto iface : qAsConst(m_startupPlugins))
        iface->beforeWindowShow(window);

    if (!window) {
        const QWindowList windowList = allWindows();
        for (QWindow *w : windowList) {
            if (w->isVisible()) {
                window = qobject_cast<QQuickWindow*>(w);
                break;
            }
        }
    }

    if (window) {
        StartupTimer::instance()->checkpoint("after Window instantiation/setup");

        static QMetaObject::Connection conn = QObject::connect(window, &QQuickWindow::frameSwapped, this, []() {
            // this is a queued signal, so there may be still one in the queue after calling disconnect()
            if (conn) {
#if defined(Q_CC_MSVC)
                qApp->disconnect(conn); // MSVC cannot distinguish between static and non-static overloads in lambdas
#else
                QObject::disconnect(conn);
#endif
                auto st = StartupTimer::instance();
                st->checkFirstFrame();
                st->createAutomaticReport(qSL("System UI"));
            }
        });

        // Main window will always be shown, neglecting visible property for backwards compatibility
        if (Q_LIKELY(showFullscreen))
            window->showFullScreen();
        else
            window->show();

        // now check the surface format, in case we had requested a specific GL version/profile
        checkOpenGLFormat("main window", window->format());

        for (auto iface : qAsConst(m_startupPlugins))
            iface->afterWindowShow(window);

        StartupTimer::instance()->checkpoint("after window show");
    } else {
        static QMetaObject::Connection conn =
            connect(this, &QGuiApplication::focusWindowChanged, this, [this] (QWindow *win) {
            if (conn) {
                QObject::disconnect(conn);
                checkOpenGLFormat("first window", win->format());
            }
        });
        StartupTimer::instance()->createAutomaticReport(qSL("System UI"));
    }
}

#if defined(QT_DBUS_LIB) && !defined(AM_DISABLE_EXTERNAL_DBUS_INTERFACES)

void Main::registerDBusObject(QDBusAbstractAdaptor *adaptor, QString dbusName, const char *serviceName, const char *interfaceName, const char *path) Q_DECL_NOEXCEPT_EXPR(false)
{
    QString dbusAddress;
    QDBusConnection conn((QString()));

    if (dbusName.isEmpty()) {
        return;
    } else if (dbusName == qL1S("system")) {
        dbusAddress = QString::fromLocal8Bit(qgetenv("DBUS_SYSTEM_BUS_ADDRESS"));
#  if defined(Q_OS_LINUX)
        if (dbusAddress.isEmpty())
            dbusAddress = qL1S("unix:path=/var/run/dbus/system_bus_socket");
#  endif
        conn = QDBusConnection::systemBus();
    } else if (dbusName == qL1S("session")) {
        dbusAddress = QString::fromLocal8Bit(qgetenv("DBUS_SESSION_BUS_ADDRESS"));
        conn = QDBusConnection::sessionBus();
    } else if (dbusName == qL1S("auto")) {
        dbusAddress = QString::fromLocal8Bit(qgetenv("DBUS_SESSION_BUS_ADDRESS"));
        conn = QDBusConnection::sessionBus();
        if (!conn.isConnected())
            return;
        dbusName = qL1S("session");
    } else {
        dbusAddress = dbusName;
        conn = QDBusConnection::connectToBus(dbusAddress, qSL("custom"));
    }

    if (!conn.isConnected()) {
        throw Exception("could not connect to D-Bus (%1): %2")
                .arg(dbusAddress.isEmpty() ? dbusName : dbusAddress).arg(conn.lastError().message());
    }

    if (adaptor->parent() && adaptor->parent()->parent()) {
        // we need this information later on to tell apps where services are listening
        adaptor->parent()->parent()->setProperty("_am_dbus_name", dbusName);
        adaptor->parent()->parent()->setProperty("_am_dbus_address", dbusAddress);
    }

    if (!conn.registerObject(qL1S(path), adaptor->parent(), QDBusConnection::ExportAdaptors)) {
        throw Exception("could not register object %1 on D-Bus (%2): %3")
                .arg(qL1S(path)).arg(dbusName).arg(conn.lastError().message());
    }

    if (!conn.registerService(qL1S(serviceName))) {
        throw Exception("could not register service %1 on D-Bus (%2): %3")
                .arg(qL1S(serviceName)).arg(dbusName).arg(conn.lastError().message());
    }

    qCDebug(LogSystem).nospace().noquote() << " * " << serviceName << path << " [on bus: " << dbusName << "]";

    if (QByteArray::fromRawData(interfaceName, int(qstrlen(interfaceName))).startsWith("io.qt.")) {
        // Write the bus address of the interface to a file in /tmp. This is needed for the
        // controller tool, which does not even have a session bus, when started via ssh.

        QFile f(QDir::temp().absoluteFilePath(qL1S(interfaceName) + qSL(".dbus")));
        QByteArray dbusUtf8 = dbusAddress.isEmpty() ? dbusName.toUtf8() : dbusAddress.toUtf8();
        if (!f.open(QFile::WriteOnly | QFile::Truncate) || (f.write(dbusUtf8) != dbusUtf8.size()))
            throw Exception(f, "Could not write D-Bus address of interface %1").arg(qL1S(interfaceName));

        static QStringList filesToDelete;
        if (filesToDelete.isEmpty())
            atexit([]() { for (const QString &ftd : qAsConst(filesToDelete)) QFile::remove(ftd); });
        filesToDelete << f.fileName();
    }
}

#endif // defined(QT_DBUS_LIB) && !defined(AM_DISABLE_EXTERNAL_DBUS_INTERFACES)


void Main::setupDBus(const std::function<QString(const char *)> &busForInterface,
                     const std::function<QVariantMap(const char *)> &policyForInterface)
{
#if defined(QT_DBUS_LIB) && !defined(AM_DISABLE_EXTERNAL_DBUS_INTERFACES)
    registerDBusTypes();

    // <0> AbstractDBusContextAdaptor instance
    // <1> D-Bus name (extracted from callback function busForInterface)
    // <2> D-Bus service
    // <3> D-Bus path
    // <4> Interface name (extracted from Q_CLASSINFO below)

    std::vector<std::tuple<AbstractDBusContextAdaptor *, QString, const char *, const char *, const char *>> ifaces;

    auto addInterface = [&ifaces, &busForInterface](AbstractDBusContextAdaptor *adaptor, const char *service, const char *path) {
        int idx = adaptor->parent()->metaObject()->indexOfClassInfo("D-Bus Interface");
        if (idx < 0) {
            throw Exception("Could not get class-info \"D-Bus Interface\" for D-Bus adapter %1")
                    .arg(qL1S(adaptor->parent()->metaObject()->className()));
        }
        const char *interfaceName = adaptor->parent()->metaObject()->classInfo(idx).value();
        ifaces.emplace_back(adaptor, busForInterface(interfaceName), service, path, interfaceName);
    };

#  if !defined(AM_DISABLE_INSTALLER)
    if (m_packageManager) {
        addInterface(new PackageManagerDBusContextAdaptor(m_packageManager),
                     "io.qt.ApplicationManager", "/PackageManager");
    }
#  endif
    addInterface(new WindowManagerDBusContextAdaptor(m_windowManager),
                 "io.qt.ApplicationManager", "/WindowManager");
    addInterface(new NotificationManagerDBusContextAdaptor(m_notificationManager),
                 "org.freedesktop.Notifications", "/org/freedesktop/Notifications");
    addInterface(new ApplicationManagerDBusContextAdaptor(m_applicationManager),
                 "io.qt.ApplicationManager", "/ApplicationManager");

    bool autoOnly = true;
    bool noneOnly = true;

    // check if all interfaces are on the "auto" bus and replace the "none" bus with nullptr
    for (auto &&iface : ifaces) {
        QString dbusName = std::get<1>(iface);
        if (dbusName != qSL("auto"))
            autoOnly = false;
        if (dbusName == qSL("none"))
            std::get<1>(iface).clear();
        else
            noneOnly = false;
    }

    // start a private dbus-daemon session instance if all interfaces are set to "auto"
    if (Q_UNLIKELY(autoOnly)) {
        try {
            DBusDaemonProcess::start();
            StartupTimer::instance()->checkpoint("after starting session D-Bus");
        } catch (const Exception &e) {
            qCWarning(LogSystem) << "Disabling external D-Bus interfaces:" << e.what();
            for (auto &&iface : ifaces)
                std::get<1>(iface).clear();
            noneOnly = true;
        }
    }

    if (!noneOnly) {
        try {
            qCDebug(LogSystem) << "Registering D-Bus services:";

            for (auto &&iface : ifaces) {
                AbstractDBusContextAdaptor *dbusAdaptor = std::get<0>(iface);
                QString &dbusName = std::get<1>(iface);
                const char *interfaceName = std::get<4>(iface);

                if (dbusName.isEmpty())
                    continue;

                registerDBusObject(dbusAdaptor->generatedAdaptor(), dbusName,
                                   std::get<2>(iface),interfaceName, std::get<3>(iface));
                if (!DBusPolicy::add(dbusAdaptor->generatedAdaptor(), policyForInterface(interfaceName)))
                    throw Exception(Error::DBus, "could not set DBus policy for %1").arg(qL1S(interfaceName));
            }
        } catch (const std::exception &e) {
            qCCritical(LogSystem) << "ERROR:" << e.what();
            qApp->exit(2);
        }
    }
#else
    Q_UNUSED(busForInterface)
    Q_UNUSED(policyForInterface)
#endif // defined(QT_DBUS_LIB) && !defined(AM_DISABLE_EXTERNAL_DBUS_INTERFACES)
}

QString Main::hardwareId() const
{
    static QString hardwareId;
    if (hardwareId.isEmpty()) {
#if defined(AM_HARDWARE_ID)
        hardwareId = QString::fromLocal8Bit(AM_HARDWARE_ID);
        if (hardwareId.startsWith(qL1C('@'))) {
            QFile f(hardwareId.mid(1));
            hardwareId.clear();
            if (f.open(QFile::ReadOnly))
                hardwareId = QString::fromLocal8Bit(f.readAll().trimmed());
        }
#else
        QVector<QNetworkInterface> candidateIfaces;
        for (const QNetworkInterface &iface : QNetworkInterface::allInterfaces()) {
            if (iface.isValid()
                    && !(iface.flags() & (QNetworkInterface::IsPointToPoint | QNetworkInterface::IsLoopBack))
                    && iface.type() > QNetworkInterface::Virtual
                    && !iface.hardwareAddress().isEmpty()) {
                candidateIfaces << iface;
            }
        }
        if (!candidateIfaces.isEmpty()) {
            std::sort(candidateIfaces.begin(), candidateIfaces.end(), [](const QNetworkInterface &first, const QNetworkInterface &second) {
                return first.name().compare(second.name()) < 0;
            });
            hardwareId = candidateIfaces.constFirst().hardwareAddress().replace(qL1C(':'), qL1S("-"));
        }
#endif
    }
    return hardwareId;
}

QT_END_NAMESPACE_AM

#include "moc_main.cpp"