summaryrefslogtreecommitdiff
path: root/src/manager-lib/applicationmanager.cpp
blob: 464b59ee1a4104edc5cb6a1f464a518775363133 (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
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
/****************************************************************************
**
** Copyright (C) 2019 Luxoft Sweden AB
** Copyright (C) 2018 Pelagicore AG
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Luxoft Application Manager.
**
** $QT_BEGIN_LICENSE:LGPL-QTAS$
** Commercial License Usage
** Licensees holding valid commercial Qt Automotive Suite 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 Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or 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.GPL2 and 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-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
** SPDX-License-Identifier: LGPL-3.0
**
****************************************************************************/

#include <QCoreApplication>
#include <QUrl>
#include <QFileInfo>
#include <QProcess>
#include <QDir>
#include <QMetaObject>
#include <QUuid>
#include <QThread>
#include <QMimeDatabase>
#if defined(QT_GUI_LIB)
#  include <QDesktopServices>
#endif
#if defined(Q_OS_UNIX)
#  include <signal.h>
#endif

#include "global.h"
#include "applicationinfo.h"
#include "logging.h"
#include "exception.h"
#include "applicationmanager.h"
#include "applicationmodel.h"
#include "applicationmanager_p.h"
#include "application.h"
#include "runtimefactory.h"
#include "containerfactory.h"
#include "quicklauncher.h"
#include "abstractruntime.h"
#include "abstractcontainer.h"
#include "qml-utilities.h"
#include "utilities.h"
#include "qtyaml.h"
#include "debugwrapper.h"
#include "amnamespace.h"

/*!
    \qmltype ApplicationManager
    \inqmlmodule QtApplicationManager.SystemUI
    \ingroup system-ui-singletons
    \brief The application model and controller.

    The ApplicationManager singleton type is the core of the application manager.
    It provides both a DBus and a QML API for all of its functionality.

    The type is derived from \c QAbstractListModel, so it can be used directly
    as a model in app-grid views.

    \target ApplicationManager Roles

    The following roles are available in this model:

    \table
    \header
        \li Role name
        \li Type
        \li Description
    \row
        \li \c applicationId
        \li string
        \li The unique Id of an application, represented as a string (e.g. \c Browser or
            \c com.pelagicore.music)
    \row
        \li \c name
        \li string
        \li The name of the application. If possible, already translated to the current locale.
    \row
        \li \c icon
        \li string
        \li The URL of the application's icon.

    \row
        \li \c isRunning
        \li bool
        \li A boolean value representing the run-state of the application.
    \row
        \li \c isStartingUp
        \li bool
        \li A boolean value indicating whether the application is starting up and not fully operational yet.
    \row
        \li \c isShuttingDown
        \li bool
        \li A boolean value indicating whether the application is currently shutting down.
    \row
        \li \c isBlocked
        \li bool
        \li A boolean value that gets set when the application manager needs to block the application
        from running: this is normally only the case while an update is applied.
    \row
        \li \c isUpdating
        \li bool
        \li A boolean value indicating whether the application is currently being installed or updated.
            If \c true, the \c updateProgress can be used to track the actual progress.
    \row
        \li \c isRemovable
        \li bool
        \li A boolean value indicating whether this application is user-removable; \c true for all
            dynamically installed third party applications and \c false for all system applications.

    \row
        \li \c updateProgress
        \li real
        \li While \c isUpdating is \c true, querying this role returns the actual progress as a floating-point
            value in the \c 0.0 to \c 1.0 range.

    \row
        \li \c codeFilePath
        \li string
        \li The filesystem path to the main "executable". The format of this file is dependent on the
        actual runtime though: for QML applications the "executable" is the \c main.qml file.

    \row
        \li \c categories
        \li list<string>
        \li The categories this application is registered for via its meta-data file (currently work in progress).

    \row
        \li \c version
        \li string
        \li The currently installed version of this application.

    \row
        \li \c application
        \li Application
        \li The underlying application object for quick access to the properties outside of a
            model delegate.
    \endtable

    \note The index-based API is currently not available via DBus. However, the same functionality
    is provided by the id-based API.

    After importing, you can just use the ApplicationManager singleton as follows:

    \qml
    import QtQuick 2.0
    import QtApplicationManager.SystemUI 2.0

    ListView {
        id: appList
        model: ApplicationManager

        delegate: Text {
            text: name + "(" + applicationId + ")"

            MouseArea {
                anchors.fill: parent
                onClick: ApplicationManager.startApplication(applicationId)
            }
        }
    }
    \endqml
*/

/*!
    \qmlproperty int ApplicationManager::count
    \readonly

    This property holds the number of applications available.
*/

/*!
    \qmlproperty bool ApplicationManager::singleProcess
    \readonly

    This property indicates whether the application-manager runs in single- or multi-process mode.
*/

/*!
    \qmlproperty bool ApplicationManager::shuttingDown
    \readonly

    This property is there to inform the System-UI, when the application-manager has entered its
    shutdown phase. New application starts are already prevented, but the System-UI might want
    to impose additional restrictions in this state.
*/

/*!
    \qmlproperty bool ApplicationManager::securityChecksEnabled
    \readonly

    This property holds whether security related checks are enabled.

    \sa no-security
*/

/*!
    \qmlproperty var ApplicationManager::systemProperties
    \readonly

    Returns the project specific \l{system properties} that were set via the config file.
*/

/*!
    \qmlproperty var ApplicationManager::containerSelectionFunction

    A JavaScript function callback that will be called whenever the application-manager needs to
    instantiate a container for running an application. See \l {Container Selection Configuration}
    for more information.
*/

/*!
    \qmlsignal ApplicationManager::applicationWasActivated(string id, string aliasId)

    This signal is emitted when an application identified by \a id is (re-)started via
    the ApplicationManager API, possibly through an alias, provided in \a aliasId.

    The window manager should take care of raising the application's window in this case.
*/

/*!
    \qmlsignal ApplicationManager::applicationRunStateChanged(string id, enumeration runState)

    This signal is emitted when the \a runState of the application identified by \a id changed.
    Possible values for the \l {ApplicationObject::runState} {runState} are defined by the
    ApplicationObject type.

    For example this signal can be used to restart an application in multi-process mode when
    it has crashed:

    \qml
    Connections {
        target: ApplicationManager
        onApplicationRunStateChanged: {
            if (runState === Am.NotRunning
                && ApplicationManager.application(id).lastExitStatus === Am.CrashExit) {
                ApplicationManager.startApplication(id);
            }
        }
    }
    \endqml

    See also Application::runState
*/

/*!
    \qmlsignal ApplicationManager::applicationAdded(string id)

    This signal is emitted after a new application, identified by \a id, has been installed via the
    ApplicationInstaller. The model has already been update before this signal is sent out.

    \note In addition to the normal "low-level" QAbstractListModel signals, the application-manager
          will also emit these "high-level" signals for System-UIs that cannot work directly on the
          ApplicationManager model: applicationAdded, applicationAboutToBeRemoved and applicationChanged.
*/

/*!
    \qmlsignal ApplicationManager::applicationAboutToBeRemoved(string id)

    This signal is emitted before an existing application, identified by \a id, is removed via the
    ApplicationInstaller.

    \note In addition to the normal "low-level" QAbstractListModel signals, the application-manager
          will also emit these "high-level" signals for System-UIs that cannot work directly on the
          ApplicationManager model: applicationAdded, applicationAboutToBeRemoved and applicationChanged.
*/

/*!
    \qmlsignal ApplicationManager::applicationChanged(string id, list<string> changedRoles)

    Emitted whenever one or more data roles, denoted by \a changedRoles, changed on the application
    identified by \a id. An empty list in the \a changedRoles argument means that all roles should
    be considered modified.

    \note In addition to the normal "low-level" QAbstractListModel signals, the application-manager
          will also emit these "high-level" signals for System-UIs that cannot work directly on the
          ApplicationManager model: applicationAdded, applicationAboutToBeRemoved and applicationChanged.
*/

/*!
    \qmlproperty bool ApplicationManager::windowManagerCompositorReady
    \readonly

    This property starts with the value \c false and will change to \c true once the Wayland
    compositor is ready to accept connections from other processes. In multi-process mode, this
    happens implicitly after the System-UI's main QML has been loaded.
*/

enum Roles
{
    Id = Qt::UserRole,
    Name,
    Icon,

    IsRunning,
    IsStartingUp,
    IsShuttingDown,
    IsBlocked,
    IsUpdating,
    IsRemovable,

    UpdateProgress,

    CodeFilePath,
    RuntimeName,
    RuntimeParameters,
    Capabilities,
    Categories,
    Version,
    ApplicationItem,
    LastExitCode,
    LastExitStatus
};

QT_BEGIN_NAMESPACE_AM

ApplicationManagerPrivate::ApplicationManagerPrivate()
{
    currentLocale = QLocale::system().name(); //TODO: language changes

    roleNames.insert(Id, "applicationId");
    roleNames.insert(Name, "name");
    roleNames.insert(Icon, "icon");
    roleNames.insert(IsRunning, "isRunning");
    roleNames.insert(IsStartingUp, "isStartingUp");
    roleNames.insert(IsShuttingDown, "isShuttingDown");
    roleNames.insert(IsBlocked, "isBlocked");
    roleNames.insert(IsUpdating, "isUpdating");
    roleNames.insert(IsRemovable, "isRemovable");
    roleNames.insert(UpdateProgress, "updateProgress");
    roleNames.insert(CodeFilePath, "codeFilePath");
    roleNames.insert(RuntimeName, "runtimeName");
    roleNames.insert(RuntimeParameters, "runtimeParameters");
    roleNames.insert(Capabilities, "capabilities");
    roleNames.insert(Categories, "categories");
    roleNames.insert(Version, "version");
    roleNames.insert(ApplicationItem, "application");
    roleNames.insert(LastExitCode, "lastExitCode");
    roleNames.insert(LastExitStatus, "lastExitStatus");
}

ApplicationManagerPrivate::~ApplicationManagerPrivate()
{
    qDeleteAll(apps);
}

ApplicationManager *ApplicationManager::s_instance = nullptr;

ApplicationManager *ApplicationManager::createInstance(bool singleProcess)
{
    if (Q_UNLIKELY(s_instance))
        qFatal("ApplicationManager::createInstance() was called a second time.");

    QScopedPointer<ApplicationManager> am(new ApplicationManager(singleProcess));

    qmlRegisterSingletonType<ApplicationManager>("QtApplicationManager.SystemUI", 2, 0, "ApplicationManager",
                                                 &ApplicationManager::instanceForQml);
    qmlRegisterType<ApplicationModel>("QtApplicationManager.SystemUI", 2, 0, "ApplicationModel");
    qmlRegisterUncreatableType<AbstractApplication>("QtApplicationManager.SystemUI", 2, 0, "ApplicationObject",
                                                  qSL("Cannot create objects of type ApplicationObject"));
    qRegisterMetaType<AbstractApplication*>("AbstractApplication*");
    qmlRegisterUncreatableType<AbstractRuntime>("QtApplicationManager.SystemUI", 2, 0, "Runtime",
                                                qSL("Cannot create objects of type Runtime"));
    qRegisterMetaType<AbstractRuntime*>("AbstractRuntime*");
    qmlRegisterUncreatableType<AbstractContainer>("QtApplicationManager.SystemUI", 2, 0, "Container",
                                                  qSL("Cannot create objects of type Container"));
    qRegisterMetaType<AbstractContainer*>("AbstractContainer*");

    qmlRegisterUncreatableType<Am>("QtApplicationManager.SystemUI", 2, 0, "Am",
                                   qSL("Cannot create objects of type Am"));

    qRegisterMetaType<Am::RunState>();
    qRegisterMetaType<Am::ExitStatus>();
    qRegisterMetaType<Am::ProcessError>();

    return s_instance = am.take();
}

ApplicationManager *ApplicationManager::instance()
{
    if (!s_instance)
        qFatal("ApplicationManager::instance() was called before createInstance().");
    return s_instance;
}

QObject *ApplicationManager::instanceForQml(QQmlEngine *, QJSEngine *)
{
    QQmlEngine::setObjectOwnership(instance(), QQmlEngine::CppOwnership);
    return instance();
}

ApplicationManager::ApplicationManager(bool singleProcess, QObject *parent)
    : QAbstractListModel(parent)
    , d(new ApplicationManagerPrivate())
{
    d->singleProcess = singleProcess;
    connect(this, &QAbstractItemModel::rowsInserted, this, &ApplicationManager::countChanged);
    connect(this, &QAbstractItemModel::rowsRemoved, this, &ApplicationManager::countChanged);
    connect(this, &QAbstractItemModel::layoutChanged, this, &ApplicationManager::countChanged);
    connect(this, &QAbstractItemModel::modelReset, this, &ApplicationManager::countChanged);
}

ApplicationManager::~ApplicationManager()
{
    delete d;
    s_instance = nullptr;
}

bool ApplicationManager::isSingleProcess() const
{
    return d->singleProcess;
}

bool ApplicationManager::isShuttingDown() const
{
    return d->shuttingDown;
}

bool ApplicationManager::securityChecksEnabled() const
{
    return d->securityChecksEnabled;
}

void ApplicationManager::setSecurityChecksEnabled(bool enabled)
{
    d->securityChecksEnabled = enabled;
}

QVariantMap ApplicationManager::systemProperties() const
{
    return d->systemProperties;
}

void ApplicationManager::setSystemProperties(const QVariantMap &map)
{
    d->systemProperties = map;
}

void ApplicationManager::setContainerSelectionConfiguration(const QList<QPair<QString, QString>> &containerSelectionConfig)
{
    d->containerSelectionConfig = containerSelectionConfig;
}

QJSValue ApplicationManager::containerSelectionFunction() const
{
    return d->containerSelectionFunction;
}

void ApplicationManager::setContainerSelectionFunction(const QJSValue &callback)
{
    if (callback.isCallable() && !callback.equals(d->containerSelectionFunction)) {
        d->containerSelectionFunction = callback;
        emit containerSelectionFunctionChanged();
    }
}

bool ApplicationManager::isWindowManagerCompositorReady() const
{
    return d->windowManagerCompositorReady;
}

void ApplicationManager::setWindowManagerCompositorReady(bool ready)
{
    if (d->windowManagerCompositorReady != ready) {
        d->windowManagerCompositorReady = ready;
        emit windowManagerCompositorReadyChanged(ready);
    }
}

QVector<AbstractApplication *> ApplicationManager::applications() const
{
    return d->apps;
}

AbstractApplication *ApplicationManager::fromId(const QString &id) const
{
    for (AbstractApplication *app : d->apps) {
        if (app->id() == id)
            return app;
    }
    return nullptr;
}

AbstractApplication *ApplicationManager::fromProcessId(qint64 pid) const
{
    // pid could be an indirect child (e.g. when started via gdbserver)
    qint64 appmanPid = QCoreApplication::applicationPid();

    while ((pid > 1) && (pid != appmanPid)) {
        for (AbstractApplication *app : d->apps) {
            if (app->currentRuntime() && (app->currentRuntime()->applicationProcessId() == pid))
                return app;
        }
        pid = getParentPid(pid);
    }
    return nullptr;
}

AbstractApplication *ApplicationManager::fromSecurityToken(const QByteArray &securityToken) const
{
    if (securityToken.size() != AbstractRuntime::SecurityTokenSize)
        return nullptr;

    for (AbstractApplication *app : d->apps) {
        if (app->currentRuntime() && app->currentRuntime()->securityToken() == securityToken)
            return app;
    }
    return nullptr;
}

QVector<AbstractApplication *> ApplicationManager::schemeHandlers(const QString &scheme) const
{
    QVector<AbstractApplication *> handlers;

    for (AbstractApplication *app : d->apps) {
        if (app->isAlias())
            continue;

        const auto mimeTypes = app->supportedMimeTypes();
        for (const QString &mime : mimeTypes) {
            int pos = mime.indexOf(QLatin1Char('/'));

            if ((pos > 0)
                    && (mime.left(pos) == qL1S("x-scheme-handler"))
                    && (mime.mid(pos + 1) == scheme)) {
                handlers << app;
            }
        }
    }
    return handlers;
}

QVector<AbstractApplication *> ApplicationManager::mimeTypeHandlers(const QString &mimeType) const
{
    QVector<AbstractApplication *> handlers;

    for (AbstractApplication *app : d->apps) {
        if (app->isAlias())
            continue;

        if (app->supportedMimeTypes().contains(mimeType))
            handlers << app;
    }
    return handlers;
}

void ApplicationManager::registerMimeTypes()
{
#if defined(QT_GUI_LIB)
    QSet<QString> schemes;
    schemes << qSL("file") << qSL("http") << qSL("https");

    for (AbstractApplication *app : qAsConst(d->apps)) {
        if (app->isAlias())
            continue;

        const auto mimeTypes = app->supportedMimeTypes();
        for (const QString &mime : mimeTypes) {
            int pos = mime.indexOf(QLatin1Char('/'));

            if ((pos > 0) && (mime.left(pos) == qL1S("x-scheme-handler")))
                schemes << mime.mid(pos + 1);
        }
    }
    QSet<QString> registerSchemes = schemes;
    registerSchemes.subtract(d->registeredMimeSchemes);
    QSet<QString> unregisterSchemes = d->registeredMimeSchemes;
    unregisterSchemes.subtract(schemes);

    for (const QString &scheme : qAsConst(unregisterSchemes))
        QDesktopServices::unsetUrlHandler(scheme);
    for (const QString &scheme : qAsConst(registerSchemes))
        QDesktopServices::setUrlHandler(scheme, this, "openUrlRelay");

    d->registeredMimeSchemes = schemes;
#endif
}

bool ApplicationManager::startApplicationInternal(const QString &appId, const QString &documentUrl,
                                                  const QString &documentMimeType,
                                                  const QString &debugWrapperSpecification,
                                                  const QVector<int> &stdioRedirections)  Q_DECL_NOEXCEPT_EXPR(false)
{
    if (d->shuttingDown)
        throw Exception("Cannot start applications during shutdown");
    AbstractApplication *app = fromId(appId);
    if (!app)
        throw Exception("Cannot start application: id '%1' is not known").arg(appId);
    if (app->isBlocked())
        throw Exception("Application %1 is blocked - cannot start").arg( app->id());

    Application* realApp = app->nonAliased();

    AbstractRuntime *runtime = app->currentRuntime();
    auto runtimeManager = runtime ? runtime->manager() : RuntimeFactory::instance()->manager(app->runtimeName());
    if (!runtimeManager)
        throw Exception("No RuntimeManager found for runtime: %1").arg(app->runtimeName());
    bool inProcess = runtimeManager->inProcess();

    // validate stdio redirections
    if (stdioRedirections.size() > 3) {
        throw Exception("Tried to start application %1 using an invalid standard IO redirection specification")
                .arg(app->id());
    }
    bool hasStdioRedirections = !stdioRedirections.isEmpty();
    if (hasStdioRedirections) {
        // we have an array - check if it just consists of -1 fds
        hasStdioRedirections = false;
        std::for_each(stdioRedirections.cbegin(), stdioRedirections.cend(), [&hasStdioRedirections](int fd) {
            if (fd >= 0)
                hasStdioRedirections = true;
        });
    }

    // validate the debug-wrapper
    QStringList debugWrapperCommand;
    QMap<QString, QString> debugEnvironmentVariables;
    if (!debugWrapperSpecification.isEmpty()) {
        if (isSingleProcess())
            throw Exception("Using debug-wrappers is not supported when the application-manager is running in single-process mode.");
        if (inProcess) {
            throw Exception("Using debug-wrappers is not supported when starting an app using an in-process runtime (%1).")
                .arg(runtimeManager->identifier());
        }

        if (!DebugWrapper::parseSpecification(debugWrapperSpecification, debugWrapperCommand,
                                              debugEnvironmentVariables)) {
            throw Exception("Tried to start application %1 using an invalid debug-wrapper specification: %2")
                    .arg(app->id(), debugWrapperSpecification);
        }
    }

    if (runtime) {
        switch (runtime->state()) {
        case Am::StartingUp:
        case Am::Running:
            if (!debugWrapperCommand.isEmpty()) {
                throw Exception("Application %1 is already running - cannot start with debug-wrapper: %2")
                        .arg(app->id(), debugWrapperSpecification);
            }

            if (!documentUrl.isNull())
                runtime->openDocument(documentUrl, documentMimeType);
            else if (!app->documentUrl().isNull())
                runtime->openDocument(app->documentUrl(), documentMimeType);

            emitActivated(app);
            return true;

        case Am::ShuttingDown:
            return false;

        case Am::NotRunning:
            break;
        }
    }

    AbstractContainer *container = nullptr;
    QString containerId;

    if (!inProcess) {
        if (d->containerSelectionConfig.isEmpty()) {
            containerId = qSL("process");
        } else {
            // check config file
            for (const auto &it : qAsConst(d->containerSelectionConfig)) {
                const QString &key = it.first;
                const QString &value = it.second;
                bool hasAsterisk = key.contains(qL1C('*'));

                if ((hasAsterisk && key.length() == 1)
                        || (!hasAsterisk && key == app->id())
                        || QRegExp(key, Qt::CaseSensitive, QRegExp::Wildcard).exactMatch(app->id())) {
                    containerId = value;
                    break;
                }
            }
        }

        if (d->containerSelectionFunction.isCallable()) {
            QJSValueList args = { QJSValue(app->id()), QJSValue(containerId) };
            containerId = d->containerSelectionFunction.call(args).toString();
        }

        if (!ContainerFactory::instance()->manager(containerId))
            throw Exception("No ContainerManager found for container: %1").arg(containerId);
    }
    bool attachRuntime = false;

    if (!runtime) {
        if (!inProcess) {
            // we cannot use the quicklaunch pool, if
            //  (a) a debug-wrapper is being used,
            //  (b) stdio is redirected or
            //  (c) the app requests special environment variables or
            //  (d) the app requests a different OpenGL config from the AM
            const char *cannotUseQuickLaunch = nullptr;

            if (!debugWrapperCommand.isEmpty())
                cannotUseQuickLaunch = "the app is started using a debug-wrapper";
            else if (hasStdioRedirections)
                cannotUseQuickLaunch = "standard I/O is redirected";
            else if (!app->runtimeParameters().value(qSL("environmentVariables")).toMap().isEmpty())
                cannotUseQuickLaunch = "the app requests customs environment variables";
            else if (app->nonAliasedInfo()->openGLConfiguration() != runtimeManager->systemOpenGLConfiguration())
                cannotUseQuickLaunch = "the app requests a custom OpenGL configuration";

            if (cannotUseQuickLaunch) {
                qCDebug(LogSystem) << "Cannot use quick-launch for application" << app->id()
                                   << "because" << cannotUseQuickLaunch;
            } else {
                // check quicklaunch pool
                QPair<AbstractContainer *, AbstractRuntime *> quickLaunch =
                        QuickLauncher::instance()->take(containerId, app->nonAliasedInfo()->runtimeName());
                container = quickLaunch.first;
                runtime = quickLaunch.second;

                qCDebug(LogSystem) << "Found a quick-launch entry for container" << containerId
                                   << "and runtime" << app->nonAliasedInfo()->runtimeName() << "->" << container << runtime;

                if (!container && runtime) {
                    runtime->deleteLater();
                    qCCritical(LogSystem) << "ERROR: QuickLauncher provided a runtime without a container.";
                    return false;
                }
            }

            if (!container) {
                container = ContainerFactory::instance()->create(containerId, app, stdioRedirections,
                                                                 debugEnvironmentVariables, debugWrapperCommand);
            } else {
                container->setApplication(app);
            }
            if (!container) {
                qCCritical(LogSystem) << "ERROR: Couldn't create Container for Application (" << app->id() <<")!";
                return false;
            }
            if (runtime)
                attachRuntime = true;
        }
        if (!runtime)
            runtime = RuntimeFactory::instance()->create(container, realApp);

        if (runtime)
            emit internalSignals.newRuntimeCreated(runtime);
    }

    if (!runtime) {
        qCCritical(LogSystem) << "ERROR: Couldn't create Runtime for Application (" << app->id() <<")!";
        return false;
    }

    connect(runtime, &AbstractRuntime::stateChanged, this, [this, app](Am::RunState newRuntimeState) {
        QVector<AbstractApplication *> apps;
        //Always emit the actual starting app/alias first
        apps.append(app);

        //Add the original app and all aliases
        AbstractApplication *nonAliasedApp = app->nonAliased();

        if (!apps.contains(nonAliasedApp))
            apps.append(nonAliasedApp);

        for (AbstractApplication *alias : qAsConst(d->apps)) {
            if (!apps.contains(alias) && alias->isAlias() && alias->nonAliased() == nonAliasedApp)
                apps.append(alias);
        }

        static_cast<Application*>(nonAliasedApp)->setRunState(newRuntimeState);

        for (AbstractApplication *app : qAsConst(apps)) {
            emit applicationRunStateChanged(app->id(), newRuntimeState);
            emitDataChanged(app, QVector<int> { IsRunning, IsStartingUp, IsShuttingDown });
        }
    });

    if (!documentUrl.isNull())
        runtime->openDocument(documentUrl, documentMimeType);
    else if (!app->documentUrl().isNull())
        runtime->openDocument(app->documentUrl(), documentMimeType);

    emitActivated(app);

    qCDebug(LogSystem) << "Starting application" << app->id() << "in container" << containerId
                       << "using runtime" << runtimeManager->identifier();
    if (!documentUrl.isEmpty())
        qCDebug(LogSystem) << "  documentUrl:" << documentUrl;

    if (inProcess) {
        bool ok = runtime->start();
        if (!ok)
            runtime->deleteLater();
        return ok;
    } else {
        // We can only start the app when both the container and the windowmanager are ready.
        // Using a state-machine would be one option, but then we would need that state-machine
        // object plus the per-app state. Relying on 2 lambdas is the easier choice for now.

        auto doStartInContainer = [realApp, attachRuntime, runtime]() -> bool {
            bool successfullyStarted = attachRuntime ? runtime->attachApplicationToQuickLauncher(realApp)
                                                     : runtime->start();
            if (!successfullyStarted)
                runtime->deleteLater(); // ~Runtime() will clean realApp->m_runtime

            return successfullyStarted;
        };

        auto tryStartInContainer = [container, doStartInContainer]() -> bool {
            if (container->isReady()) {
                // Since the container is already ready, start the app immediately
                return doStartInContainer();
            } else {
                // We postpone the starting of the application to a later point in time,
                // since the container is not ready yet
#  if defined(Q_CC_MSVC)
                qApp->connect(container, &AbstractContainer::ready, doStartInContainer); // MSVC cannot distinguish between static and non-static overloads in lambdas
# else
                connect(container, &AbstractContainer::ready, doStartInContainer);
#endif
                return true;
            }
        };

#if defined(AM_HEADLESS)
        bool tryStartNow = true;
#else
        bool tryStartNow = isWindowManagerCompositorReady();
#endif

        if (tryStartNow) {
            return tryStartInContainer();
        } else {
            connect(this, &ApplicationManager::windowManagerCompositorReadyChanged, tryStartInContainer);
            return true;
        }
    }
}

void ApplicationManager::stopApplicationInternal(AbstractApplication *app, bool forceKill)
{
    if (!app)
        return;
    AbstractRuntime *rt = app->currentRuntime();
    if (rt)
        rt->stop(forceKill);
}

/*!
    \qmlmethod bool ApplicationManager::startApplication(string id, string document)

    Instructs the application manager to start the application identified by its unique \a id. The
    optional argument \a document will be supplied to the application as is - most commonly this
    is used to refer to a document to display.
    Returns \c true if the application \a id is valid and the application manager was able to start
    the runtime plugin. Returns \c false otherwise. Note that even though this call may
    indicate success, the application may still later fail to start correctly as the actual
    startup process within the runtime plugin may be asynchronous.

    \sa ApplicationObject::start
*/
bool ApplicationManager::startApplication(const QString &id, const QString &documentUrl)
{
    try {
        return startApplicationInternal(id, documentUrl);
    } catch (const Exception &e) {
        qCWarning(LogSystem) << e.what();
        return false;
    }
}

/*!
    \qmlmethod bool ApplicationManager::debugApplication(string id, string debugWrapper, string document)

    Instructs the application manager to start the application just like startApplication. The
    application is started via the given \a debugWrapper though. Please see the \l{Debugging} page
    for more information on how to setup and use these debug-wrappers.

    \sa ApplicationObject::debug
*/

bool ApplicationManager::debugApplication(const QString &id, const QString &debugWrapper, const QString &documentUrl)
{
    try {
        return startApplicationInternal(id, documentUrl, QString(), debugWrapper);
    } catch (const Exception &e) {
        qCWarning(LogSystem) << e.what();
        return false;
    }
}

/*!
    \qmlmethod ApplicationManager::stopApplication(string id, bool forceKill)

    Tells the application manager to stop an application identified by its unique \a id. The
    meaning of the \a forceKill parameter is runtime dependent, but in general you should always try
    to stop an application with \a forceKill set to \c false first in order to allow a clean
    shutdown. Use \a forceKill set to \c true only as a last resort to kill hanging applications.

    \sa ApplicationObject::stop
*/
void ApplicationManager::stopApplication(const QString &id, bool forceKill)
{
    return stopApplicationInternal(fromId(id), forceKill);
}

/*!
    \qmlmethod ApplicationManager::stopAllApplications(bool forceKill)

    Tells the application manager to stop all running applications. The meaning of the \a forceKill
    parameter is runtime dependent, but in general you should always try to stop an application
    with \a forceKill set to \c false first in order to allow a clean shutdown.
    Use \a forceKill set to \c true only as a last resort to kill hanging applications.
*/
void ApplicationManager::stopAllApplications(bool forceKill)
{
    for (AbstractApplication *app : qAsConst(d->apps)) {
        if (!app->isAlias()) {
            AbstractRuntime *rt = app->currentRuntime();
            if (rt)
                rt->stop(forceKill);
        }
    }
}

/*!
    \qmlmethod bool ApplicationManager::openUrl(string url)

    Tries start an application that is capable of handling \a url. The application-manager will
    first look at the URL's scheme:
    \list
    \li If it is \c{file:}, the operating system's MIME database will be consulted, which will
        try to find a MIME type match, based on file endings or file content. In case this is
        successful, the application-manager will use this MIME type to find all of its applications
        that claim support for it (see the \l{mimeTypes field} in the application's manifest).
        A music player application that can handle \c mp3 and \c wav files, could add this to its
        manifest:
        \badcode
        mimeTypes: [ 'audio/mpeg', 'audio/wav' ]
        \endcode
    \li If it is something other than \c{file:}, the application-manager will consult its
        internal database of applications that claim support for a matching \c{x-scheme-handler/...}
        MIME type. In order to have your web-browser application handle \c{http:} and \c{https:}
        URLs, you would have to have this in your application's manifest:
        \badcode
        mimeTypes: [ 'x-scheme-handler/http', 'x-scheme-handler/https' ]
        \endcode
    \endlist

    If there is at least one possible match, it depends on the signal openUrlRequested() being
    connected within the System-UI:
    In case the signal is not connected, an arbitrary application from the matching set will be
    started. Otherwise the application-manager will emit the openUrlRequested signal and
    return \c true. It is up to the receiver of this signal to choose from one of possible
    applications via acknowledgeOpenUrlRequest or deny the request entirely via rejectOpenUrlRequest.
    Not calling one of these two functions will result in memory leaks.

    If an application is started by one of the two mechanisms, the \a url is supplied to
    the application as a document to open via its ApplicationInterface.

    Returns \c true, if a match was found in the database, or \c false otherwise.

    \sa openUrlRequested, acknowledgeOpenUrlRequest, rejectOpenUrlRequest
*/
bool ApplicationManager::openUrl(const QString &urlStr)
{
    // QDesktopServices::openUrl has a special behavior when called recursively, which makes sense
    // on the desktop, but is completely counter-productive for the AM.
    static bool recursionGuard = false;
    if (recursionGuard) {
        QMetaObject::invokeMethod(this, [urlStr, this]() { openUrl(urlStr); }, Qt::QueuedConnection);
        return true; // this is not correct, but the best we can do in this situation
    }
    recursionGuard = true;

    QUrl url(urlStr);
    QString mimeTypeName;
    QVector<AbstractApplication *> apps;

    if (url.isValid()) {
        QString scheme = url.scheme();
        if (scheme != qL1S("file")) {
            apps = schemeHandlers(scheme);

            for (auto it = apps.begin(); it != apps.end(); ++it) {
                AbstractApplication *&app = *it;

                // try to find a better matching alias, if available
                for (AbstractApplication *alias : d->apps) {
                    if (alias->isAlias() && alias->nonAliased() == app) {
                        if (url.toString(QUrl::PrettyDecoded) == alias->documentUrl()) {
                            app = alias;
                            break;
                        }
                    }
                }
            }
        }

        if (apps.isEmpty()) {
            QMimeDatabase mdb;
            QMimeType mt = mdb.mimeTypeForUrl(url);
            mimeTypeName = mt.name();

            apps = mimeTypeHandlers(mimeTypeName);
        }
    }

    if (!apps.isEmpty()) {
        if (!isSignalConnected(QMetaMethod::fromSignal(&ApplicationManager::openUrlRequested))) {
            // If the System-UI does not react to the signal, then just use the first match.
            startApplicationInternal(apps.constFirst()->id(), urlStr, mimeTypeName);
        } else {
            ApplicationManagerPrivate::OpenUrlRequest req {
                QUuid::createUuid().toString(),
                urlStr,
                mimeTypeName,
                QStringList()
            };
            for (const auto &app : qAsConst(apps))
                req.possibleAppIds << app->id();
            d->openUrlRequests << req;

            emit openUrlRequested(req.requestId, req.urlStr, req.mimeTypeName, req.possibleAppIds);
        }
    }

    recursionGuard = false;
    return !apps.isEmpty();
}

/*!
    \qmlsignal ApplicationManager::openUrlRequested(string requestId, string url, string mimeType, list<string> possibleAppIds)

    This signal is emitted when the application-manager is requested to open an URL. This can happen
    by calling
    \list
    \li Qt.openUrlExternally in an application,
    \li Qt.openUrlExternally in the System-UI,
    \li ApplicationManager::openUrl in the System-UI or
    \li \c io.qt.ApplicationManager.openUrl via D-Bus
    \endlist
    \note This signal is only emitted, if there is a receiver connected at all - see openUrl for the
          fallback behavior.

    The receiver of this signal can inspect the requested \a url an its \a mimeType. It can then
    either call acknowledgeOpenUrlRequest to choose from one of the supplied \a possibleAppIds or
    rejectOpenUrlRequest to ignore the request. In both cases the unique \a requestId needs to be
    sent to identify the request.
    Not calling one of these two functions will result in memory leaks.

    \sa openUrl, acknowledgeOpenUrlRequest, rejectOpenUrlRequest
*/

/*!
    \qmlmethod ApplicationManager::acknowledgeOpenUrlRequest(string requestId, string appId)

    Tells the application-manager to go ahead with the request to open an URL, identified by \a
    requestId. The chosen \a appId needs to be one of the \c possibleAppIds supplied to the
    receiver of the openUrlRequested signal.

    \sa openUrl, openUrlRequested
*/
void ApplicationManager::acknowledgeOpenUrlRequest(const QString &requestId, const QString &appId)
{
    for (auto it = d->openUrlRequests.begin(); it != d->openUrlRequests.end(); ++it) {
        if (it->requestId == requestId) {
            if (it->possibleAppIds.contains(appId)) {
                startApplicationInternal(appId, it->urlStr, it->mimeTypeName);
            } else {
                qCWarning(LogSystem) << "acknowledgeOpenUrlRequest for" << it->urlStr << "requested app"
                                     << appId << "which is not one of the registered possibilities:"
                                     << it->possibleAppIds;
            }
            d->openUrlRequests.erase(it);
            break;
        }
    }
}

/*!
    \qmlmethod ApplicationManager::rejectOpenUrlRequest(string requestId)

    Tells the application-manager to ignore the request to open an URL, identified by \a requestId.

    \sa openUrl, openUrlRequested
*/
void ApplicationManager::rejectOpenUrlRequest(const QString &requestId)
{
    for (auto it = d->openUrlRequests.begin(); it != d->openUrlRequests.end(); ++it) {
        if (it->requestId == requestId) {
            d->openUrlRequests.erase(it);
            break;
        }
    }
}

/*!
    \qmlmethod list<string> ApplicationManager::capabilities(string id)

    Returns a list of all capabilities granted by the user to the application identified by \a id.
    Returns an empty list if the application \a id is not valid.
*/
QStringList ApplicationManager::capabilities(const QString &id) const
{
    AbstractApplication *app = fromId(id);
    return app ? app->capabilities() : QStringList();
}

/*!
    \qmlmethod string ApplicationManager::identifyApplication(int pid)

    Validates the process running with process-identifier \a pid as a process started by the
    application manager.

    Returns the application's \c id on success, or an empty string on failure.
*/
QString ApplicationManager::identifyApplication(qint64 pid) const
{
    AbstractApplication *app = fromProcessId(pid);
    return app ? app->id() : QString();
}

bool ApplicationManager::blockApplication(const QString &id)
{
    AbstractApplication *app = fromId(id);
    if (!app)
        return false;
    if (!app->block())
        return false;
    emitDataChanged(app, QVector<int> { IsBlocked });
    stopApplicationInternal(app, true);
    emitDataChanged(app, QVector<int> { IsRunning });
    return true;
}

bool ApplicationManager::unblockApplication(const QString &id)
{
    AbstractApplication *app = fromId(id);
    if (!app)
        return false;
    if (!app->unblock())
        return false;
    emitDataChanged(app, QVector<int> { IsBlocked });
    return true;
}

bool ApplicationManager::startingApplicationInstallation(ApplicationInfo *info)
{
    // ownership of info is transferred to ApplicationManager
    QScopedPointer<ApplicationInfo> newInfo(info);

    if (!newInfo || newInfo->id().isEmpty())
        return false;
    AbstractApplication *absApp = fromId(newInfo->id());
    if (!RuntimeFactory::instance()->manager(newInfo->runtimeName()))
        return false;

    if (absApp) { // update
        Q_ASSERT(!absApp->isAlias());
        Application *app = static_cast<Application*>(absApp);

        if (!blockApplication(app->id()))
            return false;

        if (app->isBuiltIn()) {
            // overlay the existing base info
            // we will rollback to the base one if this update is removed.
            app->setUpdatedInfo(newInfo.take());
        } else {
            // overwrite the existing base info
            // we're not keeping track of the original. so removing the updated base version removes the
            // application entirely.
            app->setBaseInfo(newInfo.take());
        }
        app->setState(Application::BeingUpdated);
        app->setProgress(0);
        emitDataChanged(app);
    } else { // installation
        Application *app = new Application(newInfo.take(), Application::BeingInstalled);

        app->block();

        beginInsertRows(QModelIndex(), d->apps.count(), d->apps.count());
        addApplication(app);
        endInsertRows();

        emitDataChanged(app);

        emit applicationAdded(app->id());
    }
    return true;
}

bool ApplicationManager::startingApplicationRemoval(const QString &id)
{
    AbstractApplication *absApp = fromId(id);
    if (!absApp)
        return false;

    Q_ASSERT(!absApp->isAlias());

    Application *app = static_cast<Application*>(absApp);
    if (app->isBlocked() || (app->state() != Application::Installed))
        return false;

    if (app->isBuiltIn() && !app->updatedInfo())
        return false;

    if (!blockApplication(id))
        return false;

    if (app->updatedInfo())
        app->setState(Application::BeingDowngraded);
    else
        app->setState(Application::BeingRemoved);

    app->setProgress(0);
    emitDataChanged(app, QVector<int> { IsUpdating });
    return true;
}

void ApplicationManager::progressingApplicationInstall(const QString &id, qreal progress)
{
    AbstractApplication *absApp = fromId(id);
    if (!absApp)
        return;

    Q_ASSERT(!absApp->isAlias());
    Application *app = static_cast<Application*>(absApp);

    if (app->state() == Application::Installed)
        return;
    app->setProgress(progress);
    // Icon will be in a "+" suffixed directory during installation. So notify about a change on its
    // location as well.
    emitDataChanged(app, QVector<int> { Icon, UpdateProgress });
}

bool ApplicationManager::finishedApplicationInstall(const QString &id)
{
    AbstractApplication *absApp = fromId(id);
    if (!absApp)
        return false;

    Q_ASSERT(!absApp->isAlias());
    Application *app = static_cast<Application*>(absApp);

    switch (app->state()) {
    case Application::Installed:
        return false;

    case Application::BeingInstalled:
    case Application::BeingUpdated: {
        // The Application object has been updated right at the start of the installation/update.
        // Now's the time to update the InstallationReport that was written by the installer.
        QFile irfile(QDir(app->nonAliasedInfo()->manifestDir()).absoluteFilePath(qSL("installation-report.yaml")));
        QScopedPointer<InstallationReport> ir(new InstallationReport(app->id()));
        if (!irfile.open(QFile::ReadOnly) || !ir->deserialize(&irfile)) {
            qCCritical(LogInstaller) << "Could not read the new installation-report for application"
                                     << app->id() << "at" << irfile.fileName();
            return false;
        }
        app->nonAliasedInfo()->setInstallationReport(ir.take());
        registerMimeTypes();
        app->setState(Application::Installed);
        app->setProgress(0);

        emitDataChanged(app);

        unblockApplication(id);
        emit app->bulkChange(); // not ideal, but icon and codeDir have changed
        break;
    }
    case Application::BeingDowngraded:
        app->setUpdatedInfo(nullptr);
        app->setState(Application::Installed);
        registerMimeTypes();
        break;
    case Application::BeingRemoved: {
        int row = d->apps.indexOf(app);
        if (row >= 0) {
            emit applicationAboutToBeRemoved(app->id());
            beginRemoveRows(QModelIndex(), row, row);
            d->apps.removeAt(row);
            endRemoveRows();
        }
        delete app;
        registerMimeTypes();
        break;
    }
    }

    emit internalSignals.applicationsChanged();

    return true;
}

bool ApplicationManager::canceledApplicationInstall(const QString &id)
{
    AbstractApplication *absApp = fromId(id);
    if (!absApp)
        return false;

    Q_ASSERT(!absApp->isAlias());
    Application *app = static_cast<Application*>(absApp);

    switch (app->state()) {
    case Application::Installed:
        return false;

    case Application::BeingInstalled: {
        int row = d->apps.indexOf(app);
        if (row >= 0) {
            emit applicationAboutToBeRemoved(app->id());
            beginRemoveRows(QModelIndex(), row, row);
            d->apps.removeAt(row);
            endRemoveRows();
        }
        delete app;
        break;
    }
    case Application::BeingUpdated:
    case Application::BeingDowngraded:
    case Application::BeingRemoved:
        app->setState(Application::Installed);
        app->setProgress(0);
        emitDataChanged(app, QVector<int> { IsUpdating });

        unblockApplication(id);
        break;
    }
    return true;
}

void ApplicationManager::enableSingleAppMode()
{
    QMetaObject::invokeMethod(this, &ApplicationManager::startSingleAppAndQuitWhenStopped, Qt::QueuedConnection);
}

void ApplicationManager::startSingleAppAndQuitWhenStopped()
{
    Q_ASSERT(d->apps.count() == 1);

    AbstractApplication *app = d->apps[0];

    if (!startApplicationInternal(app->id())) {
        QMetaObject::invokeMethod(qApp, "shutDown", Qt::DirectConnection, Q_ARG(int, 1));
    } else {
        connect(this, &ApplicationManager::applicationRunStateChanged, [app](const QString &id, Am::RunState runState) {
            if ((id == app->id()) && (runState == Am::NotRunning)) {
                QMetaObject::invokeMethod(qApp, "shutDown", Qt::DirectConnection,
                                          Q_ARG(int, app->lastExitCode()));
            }
        });
    }
}

void ApplicationManager::shutDown()
{
    d->shuttingDown = true;
    emit shuttingDownChanged();

    auto shutdownHelper = [this]() {
        bool activeRuntime = false;
        for (AbstractApplication *app : qAsConst(d->apps)) {
            AbstractRuntime *rt = app->currentRuntime();
            if (rt) {
                activeRuntime = true;
                break;
            }
        }
        if (!activeRuntime)
            emit shutDownFinished();
    };

    for (AbstractApplication *app : qAsConst(d->apps)) {
        AbstractRuntime *rt = app->currentRuntime();
        if (rt) {
            connect(rt, &AbstractRuntime::destroyed,
                    this, shutdownHelper);
            rt->stop();
        }
    }
    shutdownHelper();
}

void ApplicationManager::openUrlRelay(const QUrl &url)
{
    if (QThread::currentThread() != thread()) {
        staticMetaObject.invokeMethod(this, "openUrlRelay", Qt::QueuedConnection, Q_ARG(QUrl, url));
        return;
    }
    openUrl(url.toString());
}

void ApplicationManager::emitDataChanged(AbstractApplication *app, const QVector<int> &roles)
{
    int row = d->apps.indexOf(app);
    if (row >= 0) {
        emit dataChanged(index(row), index(row), roles);

        static const auto appChanged = QMetaMethod::fromSignal(&ApplicationManager::applicationChanged);
        if (isSignalConnected(appChanged)) {
            QStringList stringRoles;
            for (auto role : roles)
                stringRoles << qL1S(d->roleNames[role]);
            emit applicationChanged(app->id(), stringRoles);
        }
    }
}

void ApplicationManager::emitActivated(AbstractApplication *app)
{
    emit applicationWasActivated(app->isAlias() ? app->nonAliased()->id() : app->id(), app->id());
    emit app->activated();
}

// item model part

int ApplicationManager::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;
    return d->apps.count();
}

QVariant ApplicationManager::data(const QModelIndex &index, int role) const
{
    if (index.parent().isValid() || !index.isValid())
        return QVariant();

    AbstractApplication *app = d->apps.at(index.row());

    switch (role) {
    case Id:
        return app->id();
    case Name: {
        QString name;
        if (!app->info()->names().isEmpty()) {
            name = app->info()->name(d->currentLocale);
            if (name.isEmpty())
                name = app->info()->name(qSL("en"));
            if (name.isEmpty())
                name = app->info()->name(qSL("en_US"));
            if (name.isEmpty())
                name = *app->info()->names().constBegin();
        } else {
            name = app->id();
        }
        return name;
    }
    case Icon:
        return app->icon();

    case IsRunning:
        return app->currentRuntime() ? (app->currentRuntime()->state() == Am::Running) : false;
    case IsStartingUp:
        return app->currentRuntime() ? (app->currentRuntime()->state() == Am::StartingUp) : false;
    case IsShuttingDown:
        return app->currentRuntime() ? (app->currentRuntime()->state() == Am::ShuttingDown) : false;
    case IsBlocked:
        return app->isBlocked();
    case IsUpdating:
        return app->state() != Application::Installed;
    case UpdateProgress:
        return app->progress();
    case IsRemovable:
        return !app->isBuiltIn();

    case CodeFilePath:
        return app->nonAliasedInfo()->absoluteCodeFilePath();
    case RuntimeName:
        return app->runtimeName();
    case RuntimeParameters:
        return app->runtimeParameters();
    case Capabilities:
        return app->capabilities();
    case Categories:
        return app->categories();
    case Version:
        return app->version();
    case ApplicationItem:
        return QVariant::fromValue(app);
    case LastExitCode:
        return app->lastExitCode();
    case LastExitStatus:
        return app->lastExitStatus();
    }
    return QVariant();
}

QHash<int, QByteArray> ApplicationManager::roleNames() const
{
    return d->roleNames;
}

int ApplicationManager::count() const
{
    return rowCount();
}

/*!
    \qmlmethod object ApplicationManager::get(int index)

    Retrieves the model data at \a index as a JavaScript object. See the
    \l {ApplicationManager Roles}{role names} for the expected object fields.

    Returns an empty object if the specified \a index is invalid.

    \note This is very inefficient if you only want to access a single property from QML; use
          application() instead to access the Application object's properties directly.
*/
QVariantMap ApplicationManager::get(int index) const
{
    if (index < 0 || index >= count()) {
        qCWarning(LogSystem) << "ApplicationManager::get(index): invalid index:" << index;
        return QVariantMap();
    }

    QVariantMap map;
    QHash<int, QByteArray> roles = roleNames();
    for (auto it = roles.begin(); it != roles.end(); ++it)
        map.insert(qL1S(it.value()), data(this->index(index), it.key()));
    return map;
}

/*!
    \qmlmethod ApplicationObject ApplicationManager::application(int index)

    Returns the \l{ApplicationObject}{application} corresponding to the given \a index in the
    model, or \c null if the index is invalid.

    \note The object ownership of the returned Application object stays with the application-manager.
          If you want to store this pointer, you can use the ApplicationManager's QAbstractListModel
          signals or the applicationAboutToBeRemoved signal to get notified if the object is about
          to be deleted on the C++ side.
*/
AbstractApplication *ApplicationManager::application(int index) const
{
    if (index < 0 || index >= count()) {
        qCWarning(LogSystem) << "ApplicationManager::application(index): invalid index:" << index;
        return nullptr;
    }
    return d->apps.at(index);
}

/*!
    \qmlmethod ApplicationObject ApplicationManager::application(string id)

    Returns the \l{ApplicationObject}{application} corresponding to the given application \a id,
    or \c null if the id does not exist.

    \note The object ownership of the returned Application object stays with the application-manager.
          If you want to store this pointer, you can use the ApplicationManager's QAbstractListModel
          signals or the applicationAboutToBeRemoved signal to get notified if the object is about
          to be deleted on the C++ side.
*/
AbstractApplication *ApplicationManager::application(const QString &id) const
{
    auto index = indexOfApplication(id);
    return (index < 0) ? nullptr : application(index);
}

/*!
    \qmlmethod int ApplicationManager::indexOfApplication(string id)

    Maps the application \a id to its position within the model.

    Returns \c -1 if the specified \a id is invalid.
*/
int ApplicationManager::indexOfApplication(const QString &id) const
{
    for (int i = 0; i < d->apps.size(); ++i) {
        if (d->apps.at(i)->id() == id)
            return i;
    }
    return -1;
}

/*!
    \qmlmethod list<string> ApplicationManager::applicationIds()

    Returns a list of all available application ids. This can be used to further query for specific
    information via get().
*/
QStringList ApplicationManager::applicationIds() const
{
    QStringList ids;
    ids.reserve(d->apps.size());
    for (int i = 0; i < d->apps.size(); ++i)
        ids << d->apps.at(i)->id();
    return ids;
}

/*!
    \qmlmethod object ApplicationManager::get(string id)

    Retrieves the model data for the application identified by \a id as a JavaScript object.
    See the \l {ApplicationManager Roles}{role names} for the expected object fields.

    Returns an empty object if the specified \a id is invalid.
*/
QVariantMap ApplicationManager::get(const QString &id) const
{
    int index = indexOfApplication(id);
    return (index < 0) ? QVariantMap{} : get(index);
}

Am::RunState ApplicationManager::applicationRunState(const QString &id) const
{
    int index = indexOfApplication(id);
    return (index < 0) ? Am::NotRunning : d->apps.at(index)->runState();
}

void ApplicationManager::setApplications(const QVector<AbstractApplication *> &apps)
{
    Q_ASSERT(d->apps.count() == 0);
    for (auto app : apps)
        addApplication(app);
    registerMimeTypes();
}

void ApplicationManager::addApplication(AbstractApplication *app)
{
    QQmlEngine::setObjectOwnership(app, QQmlEngine::CppOwnership);

    connect (&app->requests, &ApplicationRequests::startRequested,
            this, [this, app](const QString &documentUrl) {
        startApplicationInternal(app->id(), documentUrl);
    });

    connect (&app->requests, &ApplicationRequests::debugRequested,
            this, [this, app](const QString &debugWrapper, const QString &documentUrl) {
        debugApplication(app->id(), debugWrapper, documentUrl);
    });

    connect (&app->requests, &ApplicationRequests::stopRequested,
            this, [this, app](bool forceKill) {
        stopApplication(app->id(), forceKill);
    });

    d->apps << app;
}

QT_END_NAMESPACE_AM