aboutsummaryrefslogtreecommitdiffstats
path: root/src/libs/qmljs/qmljsmodelmanagerinterface.cpp
blob: a525c6c3054bb0981455e874a039438b124b1729 (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
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "qmljsmodelmanagerinterface.h"

#include "qmljsbind.h"
#include "qmljsconstants.h"
#include "qmljsdialect.h"
#include "qmljsfindexportedcpptypes.h"
#include "qmljsinterpreter.h"
#include "qmljsplugindumper.h"
#include "qmljstr.h"
#include "qmljsutils.h"
#include "qmljsviewercontext.h"

#include <cplusplus/cppmodelmanagerbase.h>
#include <utils/algorithm.h>
#include <utils/async.h>
#include <utils/hostosinfo.h>
#include <utils/stringutils.h>

#ifdef WITH_TESTS
#include <extensionsystem/pluginmanager.h>
#endif

#include <QDir>
#include <QDirIterator>
#include <QFile>
#include <QFileInfo>
#include <QLibraryInfo>
#include <QMetaObject>
#include <QTextDocument>
#include <QTextStream>
#include <QtAlgorithms>
#include <QTimer>

using namespace Utils;

namespace QmlJS {

QMLJS_EXPORT Q_LOGGING_CATEGORY(qmljsLog, "qtc.qmljs.common", QtWarningMsg)

/*!
    \class QmlJS::ModelManagerInterface
    \brief The ModelManagerInterface class acts as an interface to the
    global state of the QmlJS code model.
    \sa QmlJS::Document QmlJS::Snapshot QmlJSTools::Internal::ModelManager

    The ModelManagerInterface is an interface for global state and actions in
    the QmlJS code model. It is implemented by \l{QmlJSTools::Internal::ModelManager}
    and the instance can be accessed through ModelManagerInterface::instance().

    One of its primary concerns is to keep the Snapshots it
    maintains up to date by parsing documents and finding QML modules.

    It has a Snapshot that contains only valid Documents,
    accessible through ModelManagerInterface::snapshot() and a Snapshot with
    potentially more recent, but invalid documents that is exposed through
    ModelManagerInterface::newestSnapshot().
*/

static ModelManagerInterface *g_instance = nullptr;
static QMutex g_instanceMutex;
static const char *qtQuickUISuffix = "ui.qml";

static void maybeAddPath(ViewerContext &context, const Utils::FilePath &path)
{
    if (!path.isEmpty() && (context.paths.count(path) <= 0))
        context.paths.insert(path);
}

static QList<Utils::FilePath> environmentImportPaths()
{
    QList<Utils::FilePath> paths;

    const QStringList importPaths = QString::fromLocal8Bit(qgetenv("QML_IMPORT_PATH")).split(
        Utils::HostOsInfo::pathListSeparator(), Qt::SkipEmptyParts);

    for (const QString &path : importPaths) {
        const Utils::FilePath canonicalPath = Utils::FilePath::fromString(path).canonicalPath();
        if (!canonicalPath.isEmpty() && !paths.contains(canonicalPath))
            paths.append(canonicalPath);
    }

    return paths;
}

ModelManagerInterface::ModelManagerInterface(QObject *parent)
    : QObject(parent)
    , m_syncedData(environmentImportPaths())
    , m_pluginDumper(new PluginDumper(this))
{
    m_threadPool.setMaxThreadCount(4);
    m_futureSynchronizer.setCancelOnWait(false);
    m_indexerDisabled = qEnvironmentVariableIsSet("QTC_NO_CODE_INDEXER");

    m_updateCppQmlTypesTimer = new QTimer(this);
    const int second = 1000;
    m_updateCppQmlTypesTimer->setInterval(second);
    m_updateCppQmlTypesTimer->setSingleShot(true);
    connect(m_updateCppQmlTypesTimer, &QTimer::timeout,
            this, &ModelManagerInterface::startCppQmlTypeUpdate);

    m_asyncResetTimer = new QTimer(this);
    const int fifteenSeconds = 15000;
    m_asyncResetTimer->setInterval(fifteenSeconds);
    m_asyncResetTimer->setSingleShot(true);
    connect(m_asyncResetTimer, &QTimer::timeout, this, &ModelManagerInterface::resetCodeModel);

    qRegisterMetaType<QmlJS::Document::Ptr>("QmlJS::Document::Ptr");
    qRegisterMetaType<QmlJS::LibraryInfo>("QmlJS::LibraryInfo");
    qRegisterMetaType<QmlJS::Dialect>("QmlJS::Dialect");
    qRegisterMetaType<QmlJS::PathAndLanguage>("QmlJS::PathAndLanguage");
    qRegisterMetaType<QmlJS::PathsAndLanguages>("QmlJS::PathsAndLanguages");

    m_syncedData.write([](SyncedData &ld) {
        ld.m_defaultProjectInfo.qtQmlPath = FilePath::fromUserInput(
            QLibraryInfo::path(QLibraryInfo::Qml2ImportsPath));
        ld.m_defaultProjectInfo.qmllsPath
            = ModelManagerInterface::qmllsForBinPath(FilePath::fromUserInput(QLibraryInfo::path(
                                                         QLibraryInfo::BinariesPath)),
                                                     QLibraryInfo::version());
        ld.m_defaultProjectInfo.qtVersionString = QLibraryInfo::version().toString();
    });

    updateImportPaths();

    QMutexLocker locker(&g_instanceMutex);
    Q_ASSERT(! g_instance);
    g_instance = this;
}

ModelManagerInterface::~ModelManagerInterface()
{
    Q_ASSERT(g_instance == this);
    m_cppQmlTypesUpdater.cancel();
    m_cppQmlTypesUpdater.waitForFinished();

    while (true) {
        joinAllThreads(true);
        // Keep these 2 mutexes in the same order as inside instanceForFuture()
        QMutexLocker instanceLocker(&g_instanceMutex);
        QMutexLocker futureLocker(&m_futuresMutex);
        if (m_futureSynchronizer.isEmpty()) {
            g_instance = nullptr;
            return;
        }
    }
}

static QHash<QString, Dialect> defaultLanguageMapping()
{
    static QHash<QString, Dialect> res{
        {QLatin1String("mjs"), Dialect::JavaScript},
        {QLatin1String("js"), Dialect::JavaScript},
        {QLatin1String("qml"), Dialect::Qml},
        {QLatin1String("qmltypes"), Dialect::QmlTypeInfo},
        {QLatin1String("qmlproject"), Dialect::QmlProject},
        {QLatin1String("json"), Dialect::Json},
        {QLatin1String("qbs"), Dialect::QmlQbs},
        {QLatin1String(qtQuickUISuffix), Dialect::QmlQtQuick2Ui}
    };
    return res;
}

Dialect ModelManagerInterface::guessLanguageOfFile(const Utils::FilePath &fileName)
{
    QHash<QString, Dialect> lMapping;
    if (instance())
        lMapping = instance()->languageForSuffix();
    else
        lMapping = defaultLanguageMapping();
    QString fileSuffix = fileName.suffix();

    /*
     * I was reluctant to use complete suffix in all cases, because it is a huge
     * change in behaivour. But in case of .qml this should be safe.
     */

    if (fileSuffix == QLatin1String("qml"))
        fileSuffix = fileName.completeSuffix();

    return lMapping.value(fileSuffix, Dialect::NoLanguage);
}

QStringList ModelManagerInterface::globPatternsForLanguages(const QList<Dialect> &languages)
{
    QStringList patterns;
    const QHash<QString, Dialect> lMapping =
            instance() ? instance()->languageForSuffix() : defaultLanguageMapping();
    for (auto i = lMapping.cbegin(), end = lMapping.cend(); i != end; ++i) {
        if (languages.contains(i.value()))
            patterns << QLatin1String("*.") + i.key();
    }
    return patterns;
}

ModelManagerInterface *ModelManagerInterface::instance()
{
    return g_instance;
}

// If the returned instance is not null, it's guaranteed that it will be valid at least as long
// as the passed QFuture object isn't finished.
ModelManagerInterface *ModelManagerInterface::instanceForFuture(const QFuture<void> &future)
{
    QMutexLocker locker(&g_instanceMutex);
    if (g_instance)
        g_instance->addFuture(future);
    return g_instance;
}
void ModelManagerInterface::writeWarning(const QString &msg)
{
    if (ModelManagerInterface *i = instance())
        i->writeMessageInternal(msg);
    else
        qCWarning(qmljsLog) << msg;
}

ModelManagerInterface::WorkingCopy ModelManagerInterface::workingCopy()
{
    if (ModelManagerInterface *i = instance())
        return i->workingCopyInternal();
    return WorkingCopy();
}

FilePath ModelManagerInterface::qmllsForBinPath(const Utils::FilePath &binPath, const QVersionNumber &version)
{
    if (version < QVersionNumber(6,4,0))
        return {};
    QString qmllsExe = "qmlls";
    if (HostOsInfo::isWindowsHost())
        qmllsExe = "qmlls.exe";
    return binPath.resolvePath(qmllsExe);
}

void ModelManagerInterface::activateScan()
{
    const bool shouldScan = m_syncedData.update<bool>([](SyncedData &sd) {
        if (!sd.m_shouldScanImports) {
            sd.m_shouldScanImports = true;
            return true;
        }
        return false;
    });

    if (shouldScan)
        updateImportPaths();
}

QHash<QString, Dialect> ModelManagerInterface::languageForSuffix() const
{
    return defaultLanguageMapping();
}

void ModelManagerInterface::writeMessageInternal(const QString &msg) const
{
    qCDebug(qmljsLog) << msg;
}

ModelManagerInterface::WorkingCopy ModelManagerInterface::workingCopyInternal() const
{
    ModelManagerInterface::WorkingCopy res;
    return res;
}

void ModelManagerInterface::addTaskInternal(const QFuture<void> &result, const QString &msg,
                                            const char *taskId) const
{
    Q_UNUSED(result)
    qCDebug(qmljsLog) << "started " << taskId << " " << msg;
}

void ModelManagerInterface::loadQmlTypeDescriptionsInternal(const QString &resourcePath)
{
    const QDir typeFileDir(resourcePath + QLatin1String("/qml-type-descriptions"));
    const QStringList qmlTypesExtensions = QStringList("*.qmltypes");
    QFileInfoList qmlTypesFiles = typeFileDir.entryInfoList(
                qmlTypesExtensions,
                QDir::Files,
                QDir::Name);

    QStringList errors;
    QStringList warnings;

    // filter out the actual Qt builtins
    for (int i = 0; i < qmlTypesFiles.size(); ++i) {
        if (qmlTypesFiles.at(i).baseName() == QLatin1String("builtins")) {
            QFileInfoList list;
            list.append(qmlTypesFiles.at(i));
            CppQmlTypesLoader::defaultQtObjects() = CppQmlTypesLoader::loadQmlTypes(list,
                                                                                    &errors,
                                                                                    &warnings);
            qmlTypesFiles.removeAt(i);
            break;
        }
    }

    // load the fallbacks for libraries
    const CppQmlTypesLoader::BuiltinObjects objs =
            CppQmlTypesLoader::loadQmlTypes(qmlTypesFiles, &errors, &warnings);
    for (auto it = objs.cbegin(); it != objs.cend(); ++it)
        CppQmlTypesLoader::defaultLibraryObjects().insert(it.key(), it.value());

    for (const QString &error : std::as_const(errors))
        writeMessageInternal(error);
    for (const QString &warning : std::as_const(warnings))
        writeMessageInternal(warning);
}

void ModelManagerInterface::setDefaultProject(const ModelManagerInterface::ProjectInfo &pInfo,
                                              ProjectExplorer::Project *p)
{
    m_syncedData.write([p, pInfo](SyncedData &sd) {
        sd.m_defaultProject = p;
        sd.m_defaultProjectInfo = pInfo;
    });
}

void ModelManagerInterface::cancelAllThreads()
{
    m_cppQmlTypesUpdater.cancel();
    // Don't execute the scheduled updates for the old session anymore
    m_updateCppQmlTypesTimer->stop();
    m_asyncResetTimer->stop();
    QMutexLocker locker(&m_futuresMutex);
    m_futureSynchronizer.cancelAllFutures();
}

Snapshot ModelManagerInterface::snapshot() const
{
    return m_syncedData.readLocked()->m_validSnapshot;
}

Snapshot ModelManagerInterface::newestSnapshot() const
{
    return m_syncedData.readLocked()->m_newestSnapshot;
}

QThreadPool *ModelManagerInterface::threadPool()
{
    return &m_threadPool;
}

QSet<Utils::FilePath> ModelManagerInterface::scannedPaths() const
{
    return m_syncedData.readLocked()->m_scannedPaths;
}

void ModelManagerInterface::removeFromScannedPaths(const PathsAndLanguages &pathsAndLanguages)
{
    m_syncedData.write([&pathsAndLanguages](SyncedData &sd) {
        for (const PathAndLanguage &path : pathsAndLanguages)
            sd.m_scannedPaths.remove(path.path());
    });
}

void ModelManagerInterface::updateSourceFiles(const QList<Utils::FilePath> &files,
                                              bool emitDocumentOnDiskChanged)
{
    if (m_indexerDisabled)
        return;
    refreshSourceFiles(files, emitDocumentOnDiskChanged);
}

QFuture<void> ModelManagerInterface::refreshSourceFiles(const QList<Utils::FilePath> &sourceFiles,
                                                        bool emitDocumentOnDiskChanged)
{
    if (sourceFiles.isEmpty())
        return QFuture<void>();

    QFuture<void> result = Utils::asyncRun(&m_threadPool, &ModelManagerInterface::parse,
                                           workingCopyInternal(), sourceFiles, this,
                                           Dialect(Dialect::Qml), emitDocumentOnDiskChanged);
    addFuture(result);

    if (sourceFiles.count() > 1)
         addTaskInternal(result, Tr::tr("Parsing QML Files"), Constants::TASK_INDEX);

    bool scan = m_syncedData.update<bool>([&sourceFiles](SyncedData &sd) {
        if (sourceFiles.count() > 1 && !sd.m_shouldScanImports) {
            if (!sd.m_shouldScanImports) {
                sd.m_shouldScanImports = true;
                return true;
            }
        }
        return false;
    });

    if (scan)
         updateImportPaths();

    return result;
}

void ModelManagerInterface::fileChangedOnDisk(const Utils::FilePath &path)
{
    addFuture(Utils::asyncRun(&m_threadPool, &ModelManagerInterface::parse, workingCopyInternal(),
                              FilePaths({path}), this, Dialect(Dialect::AnyLanguage), true));
}

void ModelManagerInterface::removeFiles(const QList<Utils::FilePath> &files)
{
    emit aboutToRemoveFiles(files);

    m_syncedData.write([&files](SyncedData &sd) {
        for (const Utils::FilePath &file : files) {
            sd.m_validSnapshot.remove(file);
            sd.m_newestSnapshot.remove(file);
        }
    });
}

namespace {
bool pInfoLessThanActive(const ModelManagerInterface::ProjectInfo &p1,
                         const ModelManagerInterface::ProjectInfo &p2)
{
    QList<Utils::FilePath> s1 = p1.activeResourceFiles;
    QList<Utils::FilePath> s2 = p2.activeResourceFiles;
    if (s1.size() < s2.size())
        return true;
    if (s1.size() > s2.size())
        return false;
    for (int i = 0; i < s1.size(); ++i) {
        if (s1.at(i) < s2.at(i))
            return true;
        if (s1.at(i) > s2.at(i))
            return false;
    }
    return false;
}

bool pInfoLessThanAll(const ModelManagerInterface::ProjectInfo &p1,
                      const ModelManagerInterface::ProjectInfo &p2)
{
    QList<Utils::FilePath> s1 = p1.allResourceFiles;
    QList<Utils::FilePath> s2 = p2.allResourceFiles;
    if (s1.size() < s2.size())
        return true;
    if (s1.size() > s2.size())
        return false;
    for (int i = 0; i < s1.size(); ++i) {
        if (s1.at(i) < s2.at(i))
            return true;
        if (s1.at(i) > s2.at(i))
            return false;
    }
    return false;
}

bool pInfoLessThanImports(const ModelManagerInterface::ProjectInfo &p1,
                          const ModelManagerInterface::ProjectInfo &p2)
{
    if (p1.qtQmlPath < p2.qtQmlPath)
        return true;
    if (p1.qtQmlPath > p2.qtQmlPath)
        return false;
    if (p1.qmllsPath < p2.qmllsPath)
        return true;
    if (p1.qmllsPath > p2.qmllsPath)
        return false;
    const PathsAndLanguages &s1 = p1.importPaths;
    const PathsAndLanguages &s2 = p2.importPaths;
    if (s1.size() < s2.size())
        return true;
    if (s1.size() > s2.size())
        return false;
    for (int i = 0; i < s1.size(); ++i) {
        if (s1.at(i) < s2.at(i))
            return true;
        if (s2.at(i) < s1.at(i))
            return false;
    }
    return false;
}

}

inline void combine(QSet<FilePath> &set, const QList<FilePath> &list)
{
    for (const FilePath &path : list)
        set.insert(path);
}

static QSet<Utils::FilePath> generatedQrc(
    const QList<ModelManagerInterface::ProjectInfo> &projectInfos)
{
    QSet<Utils::FilePath> res;
    for (const ModelManagerInterface::ProjectInfo &pInfo : projectInfos) {
        combine(res, pInfo.generatedQrcFiles);
    }
    return res;
}

void ModelManagerInterface::iterateQrcFiles(
        ProjectExplorer::Project *project, QrcResourceSelector resources,
        const std::function<void(QrcParser::ConstPtr)> &callback)
{
    QList<ProjectInfo> pInfos;
    if (project) {
        pInfos.append(projectInfo(project));
    } else {
        pInfos = projectInfos();
        if (resources == ActiveQrcResources) // make the result predictable
            Utils::sort(pInfos, &pInfoLessThanActive);
        else
            Utils::sort(pInfos, &pInfoLessThanAll);
    }

    QSet<Utils::FilePath> allQrcs = generatedQrc(pInfos);

    for (const ModelManagerInterface::ProjectInfo &pInfo : std::as_const(pInfos)) {
        if (resources == ActiveQrcResources)
            combine(allQrcs, pInfo.activeResourceFiles);
        else
            combine(allQrcs, pInfo.allResourceFiles);
    }

    for (const Utils::FilePath &qrcFilePath : std::as_const(allQrcs)) {
        QrcParser::ConstPtr qrcFile = m_qrcCache.parsedPath(qrcFilePath.toFSPathString());
        if (!qrcFile)
            continue;
        callback(qrcFile);
    }
}

QStringList ModelManagerInterface::qrcPathsForFile(const Utils::FilePath &file,
                                                   const QLocale *locale,
                                                   ProjectExplorer::Project *project,
                                                   QrcResourceSelector resources)
{
    QStringList res;
    iterateQrcFiles(project, resources, [&](const QrcParser::ConstPtr &qrcFile) {
        qrcFile->collectResourceFilesForSourceFile(file.toString(), &res, locale);
    });
    return res;
}

QStringList ModelManagerInterface::filesAtQrcPath(const QString &path, const QLocale *locale,
                                         ProjectExplorer::Project *project,
                                         QrcResourceSelector resources)
{
    QString normPath = QrcParser::normalizedQrcFilePath(path);
    QStringList res;
    iterateQrcFiles(project, resources, [&](const QrcParser::ConstPtr &qrcFile) {
        qrcFile->collectFilesAtPath(normPath, &res, locale);
    });
    return res;
}

QMap<QString, QStringList> ModelManagerInterface::filesInQrcPath(const QString &path,
                                                        const QLocale *locale,
                                                        ProjectExplorer::Project *project,
                                                        bool addDirs,
                                                        QrcResourceSelector resources)
{
    QString normPath = QrcParser::normalizedQrcDirectoryPath(path);
    QMap<QString, QStringList> res;
    iterateQrcFiles(project, resources, [&](const QrcParser::ConstPtr &qrcFile) {
        qrcFile->collectFilesInPath(normPath, &res, addDirs, locale);
    });
    return res;
}

QList<ModelManagerInterface::ProjectInfo> ModelManagerInterface::projectInfos() const
{
    return m_syncedData.readLocked()->m_projects.values();
}

bool ModelManagerInterface::containsProject(ProjectExplorer::Project *project) const
{
    return m_syncedData.readLocked()->m_projects.contains(project);
}

ModelManagerInterface::ProjectInfo ModelManagerInterface::projectInfo(
        ProjectExplorer::Project *project) const
{
    return m_syncedData.readLocked()->m_projects.value(project);
}

void ModelManagerInterface::updateProjectInfo(const ProjectInfo &pinfo, ProjectExplorer::Project *p)
{
    if (pinfo.project.isNull() || !p || m_indexerDisabled)
        return;

    Snapshot snapshot;
    ProjectInfo oldInfo;

    m_syncedData.write([&oldInfo, &snapshot, p, &pinfo](SyncedData &sd) {
        ProjectInfo &storedInfo = sd.m_projects[p];
        oldInfo = storedInfo;
        storedInfo = pinfo;
        if (p == sd.m_defaultProject)
            sd.m_defaultProjectInfo = pinfo;
        snapshot = sd.m_validSnapshot;
    });

    if (oldInfo.qmlDumpPath != pinfo.qmlDumpPath
            || oldInfo.qmlDumpEnvironment != pinfo.qmlDumpEnvironment) {
        m_pluginDumper->scheduleRedumpPlugins();
    }


    updateImportPaths();

    // remove files that are no longer in the project and have been deleted
    QList<Utils::FilePath> deletedFiles;
    for (const Utils::FilePath &oldFile : std::as_const(oldInfo.sourceFiles)) {
        if (snapshot.document(oldFile) && !pinfo.sourceFiles.contains(oldFile)
            && !oldFile.exists()) {
            deletedFiles += oldFile;
        }
    }
    removeFiles(deletedFiles);

    QList<Utils::FilePath> newFiles;

    m_syncedData.write([p, &pinfo, &deletedFiles, &snapshot, &newFiles](SyncedData &sd) {
        for (const Utils::FilePath &oldFile : std::as_const(deletedFiles))
            sd.m_fileToProject.remove(oldFile, p);

        // parse any files not yet in the snapshot
        for (const Utils::FilePath &file : std::as_const(pinfo.sourceFiles)) {
            if (!sd.m_fileToProject.contains(file, p))
                sd.m_fileToProject.insert(file, p);
            if (!snapshot.document(file))
                newFiles += file;
        }
    });

    updateSourceFiles(newFiles, false);

    // update qrc cache
    m_qrcContents = pinfo.resourceFileContents;
    for (const Utils::FilePath &newQrc : std::as_const(pinfo.allResourceFiles))
        m_qrcCache.addPath(newQrc.toString(), m_qrcContents.value(newQrc));
    for (const Utils::FilePath &newQrc : pinfo.generatedQrcFiles)
        m_qrcCache.addPath(newQrc.toString(), m_qrcContents.value(newQrc));
    for (const Utils::FilePath &oldQrc : std::as_const(oldInfo.allResourceFiles))
        m_qrcCache.removePath(oldQrc.toString());

    m_pluginDumper->loadBuiltinTypes(pinfo);
    emit projectInfoUpdated(pinfo);
}


void ModelManagerInterface::removeProjectInfo(ProjectExplorer::Project *project)
{
    ProjectInfo info;
    info.sourceFiles.clear();
    // update with an empty project info to clear data
    updateProjectInfo(info, project);

    m_syncedData.write([project](SyncedData &ld) { ld.m_projects.remove(project); });
}

/*!
    Returns project info with summarized info for \a path

    \note Project pointer will be empty
 */
ModelManagerInterface::ProjectInfo ModelManagerInterface::projectInfoForPath(
    const Utils::FilePath &path) const
{
    ProjectInfo res;
    const auto allProjectInfos = allProjectInfosForPath(path);
    for (const ProjectInfo &pInfo : allProjectInfos) {
        if (res.qtQmlPath.isEmpty()) {
            res.qtQmlPath = pInfo.qtQmlPath;
            res.qtVersionString = pInfo.qtVersionString;
        }
        if (res.qmllsPath.isEmpty())
            res.qmllsPath = pInfo.qmllsPath;
        res.applicationDirectories.append(pInfo.applicationDirectories);
        for (const auto &importPath : pInfo.importPaths)
            res.importPaths.maybeInsert(importPath);
        auto end = pInfo.moduleMappings.cend();
        for (auto it = pInfo.moduleMappings.cbegin(); it != end; ++it)
            res.moduleMappings.insert(it.key(), it.value());
    }
    res.applicationDirectories = Utils::filteredUnique(res.applicationDirectories);
    return res;
}

/*!
    Returns list of project infos for \a path
 */
QList<ModelManagerInterface::ProjectInfo> ModelManagerInterface::allProjectInfosForPath(
    const Utils::FilePath &path) const
{
    QList<ProjectExplorer::Project *> projects
        = m_syncedData.get<QList<ProjectExplorer::Project *>>([&path](const SyncedData &sd) {
              auto projects = sd.m_fileToProject.values(path);
              if (projects.isEmpty())
                  projects = sd.m_fileToProject.values(path.canonicalPath());
              return projects;
          });

    QList<ProjectInfo> infos;
    for (ProjectExplorer::Project *project : std::as_const(projects)) {
        ProjectInfo info = projectInfo(project);
        if (!info.project.isNull())
            infos.append(info);
    }
    if (infos.isEmpty()) {
        return {m_syncedData.readLocked()->m_defaultProjectInfo};
    }
    std::sort(infos.begin(), infos.end(), &pInfoLessThanImports);
    return infos;
}

void ModelManagerInterface::emitDocumentChangedOnDisk(Document::Ptr doc)
{
    emit documentChangedOnDisk(std::move(doc));
}

void ModelManagerInterface::updateQrcFile(const Utils::FilePath &path)
{
    m_qrcCache.updatePath(path.toString(), m_qrcContents.value(path));
}

void ModelManagerInterface::updateDocument(const Document::Ptr &doc)
{
    m_syncedData.write([&doc](SyncedData &sd) {
        sd.m_validSnapshot.insert(doc);
        sd.m_newestSnapshot.insert(doc, true);
    });

    emit documentUpdated(doc);
}

void ModelManagerInterface::updateLibraryInfo(const FilePath &path,
                                              const LibraryInfo &info,
                                              SynchronizedValue<SyncedData>::unique_lock &lock)
{
    if (!info.pluginTypeInfoError().isEmpty())
        qCDebug(qmljsLog) << "Dumping errors for " << path << ":" << info.pluginTypeInfoError();

    lock->m_validSnapshot.insertLibraryInfo(path, info);
    lock->m_newestSnapshot.insertLibraryInfo(path, info);

    // only emit if we got new useful information
    if (info.isValid())
        emit libraryInfoUpdated(path, info);
}

void ModelManagerInterface::updateLibraryInfo(const FilePath &path, const LibraryInfo &info)
{
    SynchronizedValue<SyncedData>::unique_lock lock = m_syncedData.writeLocked();
    updateLibraryInfo(path, info, lock);
}

static QList<Utils::FilePath> filesInDirectoryForLanguages(const Utils::FilePath &path,
                                                           const QList<Dialect> &languages)
{
    const QStringList pattern = ModelManagerInterface::globPatternsForLanguages(languages);
    QList<Utils::FilePath> files;

    for (const Utils::FilePath &p : path.dirEntries(FileFilter(pattern, QDir::Files)))
        files.append(p.absoluteFilePath());

    return files;
}

static void findNewImplicitImports(const Document::Ptr &doc,
                                   const Snapshot &snapshot,
                                   QList<Utils::FilePath> *importedFiles,
                                   QSet<Utils::FilePath> *scannedPaths)
{
    // scan files that could be implicitly imported
    // it's important we also do this for JS files, otherwise the isEmpty check will fail
    if (snapshot.documentsInDirectory(doc->path()).isEmpty()) {
        if (Utils::insert(*scannedPaths, doc->path())) {
            *importedFiles += filesInDirectoryForLanguages(doc->path(),
                                                           doc->language().companionLanguages());
        }
    }
}

static void findNewFileImports(const Document::Ptr &doc,
                               const Snapshot &snapshot,
                               QList<Utils::FilePath> *importedFiles,
                               QSet<Utils::FilePath> *scannedPaths)
{
    // scan files and directories that are explicitly imported
    const auto imports = doc->bind()->imports();
    for (const ImportInfo &import : imports) {
        const QString &importName = import.path();
        Utils::FilePath importPath = Utils::FilePath::fromString(importName);
        if (import.type() == ImportType::File) {
            if (!snapshot.document(importPath))
                *importedFiles += importPath;
        } else if (import.type() == ImportType::Directory) {
            if (snapshot.documentsInDirectory(importPath).isEmpty()) {
                if (Utils::insert(*scannedPaths, importPath)) {
                    *importedFiles
                        += filesInDirectoryForLanguages(importPath,
                                                        doc->language().companionLanguages());
                }
            }
        } else if (import.type() == ImportType::QrcFile) {
            const QStringList importPaths
                    = ModelManagerInterface::instance()->filesAtQrcPath(importName);
            for (const QString &importStr : importPaths) {
                Utils::FilePath importPath = Utils::FilePath::fromString(importStr);
                if (!snapshot.document(importPath))
                    *importedFiles += importPath;
            }
        } else if (import.type() == ImportType::QrcDirectory) {
            const QMap<QString, QStringList> files
                    = ModelManagerInterface::instance()->filesInQrcPath(importName);
            for (auto qrc = files.cbegin(), end = files.cend(); qrc != end; ++qrc) {
                if (ModelManagerInterface::guessLanguageOfFile(
                        Utils::FilePath::fromString(qrc.key()))
                        .isQmlLikeOrJsLanguage()) {
                    for (const QString &sourceFile : qrc.value()) {
                        auto sourceFilePath = Utils::FilePath::fromString(sourceFile);
                        if (!snapshot.document(sourceFilePath))
                            *importedFiles += sourceFilePath;
                    }
                }
            }
        }
    }
}

enum class LibraryStatus {
    Accepted,
    Rejected,
    Unknown
};

static LibraryStatus libraryStatus(const FilePath &path,
                                   const Snapshot &snapshot,
                                   QSet<Utils::FilePath> *newLibraries)
{
    if (path.isEmpty())
        return LibraryStatus::Rejected;
    // if we know there is a library, done
    const LibraryInfo &existingInfo = snapshot.libraryInfo(path);
    if (existingInfo.isValid())
        return LibraryStatus::Accepted;
    if (newLibraries->contains(path))
        return LibraryStatus::Accepted;
    // if we looked at the path before, done
    return existingInfo.wasScanned()
            ? LibraryStatus::Rejected
            : LibraryStatus::Unknown;
}

bool ModelManagerInterface::findNewQmlApplicationInPath(
    const FilePath &path,
    const Snapshot &snapshot,
    ModelManagerInterface *modelManager,
    QSet<FilePath> *newLibraries,
    SynchronizedValue<SyncedData>::unique_lock &lock)
{
    switch (libraryStatus(path, snapshot, newLibraries)) {
    case LibraryStatus::Accepted: return true;
    case LibraryStatus::Rejected: return false;
    default: break;
    }

    FilePath qmltypesFile;

    QList<Utils::FilePath> qmlTypes = path.dirEntries(
        FileFilter(QStringList{"*.qmltypes"}, QDir::Files));

    if (qmlTypes.isEmpty())
        return false;

    qmltypesFile = qmlTypes.first();

    LibraryInfo libraryInfo = LibraryInfo(qmltypesFile.toString());
    const Utils::FilePath libraryPath = path.absolutePath();
    newLibraries->insert(libraryPath);
    modelManager->updateLibraryInfo(path, libraryInfo, lock);
    lock.unlock();
    modelManager->loadPluginTypes(libraryPath.canonicalPath(), libraryPath, QString(), QString());
    lock.lock();
    return true;
}

bool ModelManagerInterface::findNewQmlLibraryInPath(const Utils::FilePath &path,
                                                    const Snapshot &snapshot,
                                                    ModelManagerInterface *modelManager,
                                                    QList<Utils::FilePath> *importedFiles,
                                                    QSet<Utils::FilePath> *scannedPaths,
                                                    QSet<Utils::FilePath> *newLibraries,
                                                    bool ignoreMissing,
                                                    SynchronizedValue<SyncedData>::unique_lock *lock)
{
    switch (libraryStatus(path, snapshot, newLibraries)) {
    case LibraryStatus::Accepted: return true;
    case LibraryStatus::Rejected: return false;
    default: break;
    }

    Utils::FilePath qmldirFile = path.pathAppended(QLatin1String("qmldir"));
    if (!qmldirFile.exists()) {
        if (!ignoreMissing) {
            LibraryInfo libraryInfo(LibraryInfo::NotFound);
            if (lock)
                modelManager->updateLibraryInfo(path, libraryInfo, *lock);
            else
                modelManager->updateLibraryInfo(path, libraryInfo);
        }
        return false;
    }

    if (Utils::HostOsInfo::isWindowsHost()) {
        // QTCREATORBUG-3402 - be case sensitive even here?
    }

    // found a new library!
    const expected_str<QByteArray> contents = qmldirFile.fileContents();
    if (!contents)
        return false;
    QString qmldirData = QString::fromUtf8(*contents);

    QmlDirParser qmldirParser;
    qmldirParser.parse(qmldirData);

    const Utils::FilePath libraryPath = qmldirFile.absolutePath();
    newLibraries->insert(libraryPath);
    if (lock)
        modelManager->updateLibraryInfo(libraryPath, LibraryInfo(qmldirParser), *lock);
    else
        modelManager->updateLibraryInfo(libraryPath, LibraryInfo(qmldirParser));

    if (lock) {
        lock->unlock();
        // This will call our locking functions again, so we have to unlock first.
        modelManager->loadPluginTypes(libraryPath.canonicalPath(),
                                      libraryPath,
                                      QString(),
                                      QString());
        lock->lock();
    } else {
        modelManager->loadPluginTypes(libraryPath.canonicalPath(),
                                      libraryPath,
                                      QString(),
                                      QString());
    }

    // scan the qml files in the library
    const auto components = qmldirParser.components();
    for (const QmlDirParser::Component &component : components) {
        if (!component.fileName.isEmpty()) {
            const FilePath componentFile = path.pathAppended(component.fileName);
            const FilePath path = componentFile.absolutePath().cleanPath();
            if (Utils::insert(*scannedPaths, path)) {
                *importedFiles += filesInDirectoryForLanguages(path, Dialect(Dialect::AnyLanguage)
                                                               .companionLanguages());
            }
        }
    }

    return true;
}

static FilePath modulePath(const ImportInfo &import, const FilePaths &paths)
{
    if (!import.version().isValid())
        return {};

    const FilePaths modPaths = modulePaths(import.name(), import.version().toString(), paths);
    return modPaths.value(0); // first is best match
}

void ModelManagerInterface::findNewLibraryImports(const Document::Ptr &doc,
                                                  const Snapshot &snapshot,
                                                  ModelManagerInterface *modelManager,
                                                  FilePaths *importedFiles,
                                                  QSet<Utils::FilePath> *scannedPaths,
                                                  QSet<Utils::FilePath> *newLibraries,
                                                  SynchronizedValue<SyncedData>::unique_lock *lock)
{
    // scan current dir
    findNewQmlLibraryInPath(doc->path(),
                            snapshot,
                            modelManager,
                            importedFiles,
                            scannedPaths,
                            newLibraries,
                            false,
                            lock);

    // scan dir and lib imports
    const FilePaths importPaths = lock ? modelManager->importPathsNames(**lock)
                                       : modelManager->importPathsNames();
    const auto imports = doc->bind()->imports();
    for (const ImportInfo &import : imports) {
        switch (import.type()) {
        case ImportType::Directory:
            findNewQmlLibraryInPath(Utils::FilePath::fromString(import.path()),
                                    snapshot,
                                    modelManager,
                                    importedFiles,
                                    scannedPaths,
                                    newLibraries,
                                    false,
                                    lock);
            break;
        case ImportType::Library:
            findNewQmlLibraryInPath(modulePath(import, importPaths),
                                    snapshot,
                                    modelManager,
                                    importedFiles,
                                    scannedPaths,
                                    newLibraries,
                                    false,
                                    lock);
            break;
        default:
            break;
        }
    }
}

void ModelManagerInterface::parseLoop(QSet<Utils::FilePath> &scannedPaths,
                                      QSet<Utils::FilePath> &newLibraries,
                                      const WorkingCopy &workingCopy,
                                      QList<Utils::FilePath> files,
                                      ModelManagerInterface *modelManager,
                                      Dialect mainLanguage,
                                      bool emitDocChangedOnDisk,
                                      const std::function<bool(qreal)> &reportProgress)
{
    for (int i = 0; i < files.size(); ++i) {
        if (!reportProgress(qreal(i) / files.size()))
            return;

        const Utils::FilePath fileName = files.at(i);

        Dialect language = guessLanguageOfFile(fileName);
        if (language == Dialect::NoLanguage) {
            if (fileName.endsWith(QLatin1String(".qrc")))
                modelManager->updateQrcFile(fileName);
            continue;
        }
        if (language == Dialect::Qml
                && (mainLanguage == Dialect::QmlQtQuick2))
            language = mainLanguage;
        if (language == Dialect::Qml && mainLanguage == Dialect::QmlQtQuick2Ui)
            language = Dialect::QmlQtQuick2;
        if (language == Dialect::QmlTypeInfo || language == Dialect::QmlProject)
            continue;
        QString contents;
        int documentRevision = 0;

        if (workingCopy.contains(fileName)) {
            QPair<QString, int> entry = workingCopy.get(fileName);
            contents = entry.first;
            documentRevision = entry.second;
        } else {
            const expected_str<QByteArray> fileContents = fileName.fileContents();
            if (fileContents) {
                QTextStream ins(*fileContents);
                contents = ins.readAll();
            } else {
                continue;
            }
        }

        Document::MutablePtr doc = Document::create(fileName, language);
        doc->setEditorRevision(documentRevision);
        doc->setSource(contents);
        doc->parse();

#ifdef WITH_TESTS
        if (ExtensionSystem::PluginManager::instance() // we might run as an auto-test
            && ExtensionSystem::PluginManager::isScenarioRunning("TestModelManagerInterface")) {
            ExtensionSystem::PluginManager::waitForScenarioFullyInitialized();
            if (ExtensionSystem::PluginManager::finishScenario()) {
                qDebug() << "Point 1: Shutdown triggered";
                QThread::sleep(2);
                qDebug() << "Point 3: If Point 2 was already reached, expect a crash now";
            }
        }
#endif
        // get list of referenced files not yet in snapshot or in directories already scanned
        QList<Utils::FilePath> importedFiles;

        // update snapshot. requires synchronization, but significantly reduces amount of file
        // system queries for library imports because queries are cached in libraryInfo
        {
            // Make sure the snapshot is destroyed before updateDocument, so that we don't trigger
            // the copy-on-write mechanism on its internals.
            const Snapshot snapshot = modelManager->snapshot();

            findNewImplicitImports(doc, snapshot, &importedFiles, &scannedPaths);
            findNewFileImports(doc, snapshot, &importedFiles, &scannedPaths);

            findNewLibraryImports(doc,
                                  snapshot,
                                  modelManager,
                                  &importedFiles,
                                  &scannedPaths,
                                  &newLibraries,
                                  nullptr);
        }

        // add new files to parse list
        for (const Utils::FilePath &file : std::as_const(importedFiles)) {
            if (!files.contains(file))
                files.append(file);
        }

        modelManager->updateDocument(doc);
        if (emitDocChangedOnDisk)
            modelManager->emitDocumentChangedOnDisk(doc);
    }
}

class FutureReporter
{
public:
    FutureReporter(QPromise<void> &promise, int multiplier, int base)
        : m_promise(promise), m_multiplier(multiplier), m_base(base)
    {}

    bool operator()(qreal val)
    {
        if (m_promise.isCanceled())
            return false;
        m_promise.setProgressValue(int(m_base + m_multiplier * val));
        return true;
    }
private:
    QPromise<void> &m_promise;
    int m_multiplier;
    int m_base;
};

void ModelManagerInterface::parse(QPromise<void> &promise,
                                  const WorkingCopy &workingCopy,
                                  QList<Utils::FilePath> files,
                                  ModelManagerInterface *modelManager,
                                  Dialect mainLanguage,
                                  bool emitDocChangedOnDisk)
{
    const int progressMax = 100;
    FutureReporter reporter(promise, progressMax, 0);
    promise.setProgressRange(0, progressMax);

    // paths we have scanned for files and added to the files list
    QSet<Utils::FilePath> scannedPaths;
    // libraries we've found while scanning imports
    QSet<Utils::FilePath> newLibraries;
    parseLoop(scannedPaths, newLibraries, workingCopy, std::move(files), modelManager, mainLanguage,
              emitDocChangedOnDisk, reporter);
    promise.setProgressValue(progressMax);
}

struct ScanItem {
    Utils::FilePath path;
    int depth = 0;
    Dialect language = Dialect::AnyLanguage;
};

void ModelManagerInterface::importScan(const WorkingCopy &workingCopy,
                                       const PathsAndLanguages &paths,
                                       ModelManagerInterface *modelManager,
                                       bool emitDocChanged, bool libOnly, bool forceRescan)
{
    QPromise<void> promise;
    promise.start();
    importScanAsync(promise, workingCopy, paths, modelManager, emitDocChanged, libOnly, forceRescan);
}

void ModelManagerInterface::importScanAsync(QPromise<void> &promise, const WorkingCopy &workingCopy,
                                            const PathsAndLanguages &paths,
                                            ModelManagerInterface *modelManager,
                                            bool emitDocChanged, bool libOnly, bool forceRescan)
{
    // paths we have scanned for files and added to the files list
    QSet<Utils::FilePath> scannedPaths = modelManager->scannedPaths();

    // libraries we've found while scanning imports
    QSet<Utils::FilePath> newLibraries;

    QVector<ScanItem> pathsToScan;
    pathsToScan.reserve(paths.size());
    for (const auto &path : paths) {
        Utils::FilePath cPath = path.path().cleanPath();
        if (!forceRescan && !Utils::insert(scannedPaths, cPath))
            continue;
        pathsToScan.append({cPath, 0, path.language()});
    }

    const int maxScanDepth = 5;
    int progressRange = pathsToScan.size() * (1 << (2 + maxScanDepth));
    int totalWork = progressRange;
    int workDone = 0;
    promise.setProgressRange(0, progressRange); // update max length while iterating?
    const Snapshot snapshot = modelManager->snapshot();
    bool isCanceled = promise.isCanceled();
    while (!pathsToScan.isEmpty() && !isCanceled) {
        ScanItem toScan = pathsToScan.last();
        pathsToScan.pop_back();
        int pathBudget = (1 << (maxScanDepth + 2 - toScan.depth));
        if (forceRescan || !scannedPaths.contains(toScan.path)) {
            QList<Utils::FilePath> importedFiles;
            if (forceRescan
                || (!findNewQmlLibraryInPath(toScan.path,
                                             snapshot,
                                             modelManager,
                                             &importedFiles,
                                             &scannedPaths,
                                             &newLibraries,
                                             true,
                                             nullptr)
                    && !libOnly && snapshot.documentsInDirectory(toScan.path).isEmpty())) {
                importedFiles += filesInDirectoryForLanguages(toScan.path,
                                                              toScan.language.companionLanguages());
            }
            workDone += 1;
            promise.setProgressValue(progressRange * workDone / totalWork);
            if (!importedFiles.isEmpty()) {
                FutureReporter reporter(promise, progressRange * pathBudget / (4 * totalWork),
                                        progressRange * workDone / totalWork);
                parseLoop(scannedPaths, newLibraries, workingCopy, importedFiles, modelManager,
                          toScan.language, emitDocChanged, reporter); // run in parallel??
                importedFiles.clear();
            }
            workDone += pathBudget / 4 - 1;
            promise.setProgressValue(progressRange * workDone / totalWork);
        } else {
            workDone += pathBudget / 4;
        }
        // always descend tree, as we might have just scanned with a smaller depth
        if (toScan.depth < maxScanDepth) {
            Utils::FilePath dir = toScan.path;
            const QList<Utils::FilePath> subDirs = dir.dirEntries(QDir::Dirs | QDir::NoDotAndDotDot);
            workDone += 1;
            totalWork += pathBudget / 2 * subDirs.size() - pathBudget * 3 / 4 + 1;
            for (const Utils::FilePath &path : subDirs)
                pathsToScan.append({path.absoluteFilePath(), toScan.depth + 1, toScan.language});
        } else {
            workDone += pathBudget * 3 / 4;
        }
        promise.setProgressValue(progressRange * workDone / totalWork);
        isCanceled = promise.isCanceled();
    }
    promise.setProgressValue(progressRange);
    if (isCanceled) {
        // assume no work has been done
        modelManager->removeFromScannedPaths(paths);
    }
}

QList<Utils::FilePath> ModelManagerInterface::importPathsNames(const SyncedData &lockedData) const
{
    QList<Utils::FilePath> names;
    names.reserve(lockedData.m_allImportPaths.size());
    for (const PathAndLanguage &x : lockedData.m_allImportPaths)
        names << x.path();
    return names;
}

QList<Utils::FilePath> ModelManagerInterface::importPathsNames() const
{
    return m_syncedData.get<QList<Utils::FilePath>>(
        [this](const SyncedData &sd) { return importPathsNames(sd); });
}

QmlLanguageBundles ModelManagerInterface::activeBundles() const
{
    return m_syncedData.readLocked()->m_activeBundles;
}

QmlLanguageBundles ModelManagerInterface::extendedBundles() const
{
    return m_syncedData.readLocked()->m_extendedBundles;
}

void ModelManagerInterface::maybeScan(const PathsAndLanguages &importPaths)
{
    if (m_indexerDisabled)
        return;
    PathsAndLanguages pathToScan;
    m_syncedData.write([&pathToScan, &importPaths](SyncedData &sd) {
        for (const PathAndLanguage &importPath : importPaths)
            if (!sd.m_scannedPaths.contains(importPath.path()))
                pathToScan.maybeInsert(importPath);
    });

    if (pathToScan.length() >= 1) {
        QFuture<void> result = Utils::asyncRun(&m_threadPool,
                                               &ModelManagerInterface::importScanAsync,
                                               workingCopyInternal(), pathToScan,
                                               this, true, true, false);
        addFuture(result);
        addTaskInternal(result, Tr::tr("Scanning QML Imports"), Constants::TASK_IMPORT_SCAN);
    }
}

static QList<Utils::FilePath> minimalPrefixPaths(const QList<Utils::FilePath> &paths)
{
    QList<Utils::FilePath> sortedPaths;
    // find minimal prefix, ensure '/' at end
    for (Utils::FilePath path : std::as_const(paths)) {
        if (!path.endsWith("/"))
            path = path.withNewPath(path.path() + "/");
        if (path.path().length() > 1)
            sortedPaths.append(path);
    }
    std::sort(sortedPaths.begin(), sortedPaths.end());
    QList<Utils::FilePath> res;
    QString lastPrefix;
    for (auto it = sortedPaths.begin(); it != sortedPaths.end(); ++it) {
        if (lastPrefix.isEmpty() || !it->startsWith(lastPrefix)) {
            lastPrefix = it->path();
            res.append(*it);
        }
    }
    return res;
}

void ModelManagerInterface::updateImportPaths()
{
    if (m_indexerDisabled)
        return;

    PathsAndLanguages allImportPaths;
    QList<Utils::FilePath> importedFiles;

    SynchronizedValue<SyncedData>::unique_lock lock = m_syncedData.writeLocked();

    QList<Utils::FilePath> allApplicationDirectories;
    QmlLanguageBundles activeBundles;
    QmlLanguageBundles extendedBundles;

    for (const ProjectInfo &pInfo : std::as_const(lock->m_projects)) {
        for (const auto &importPath : pInfo.importPaths) {
            const FilePath canonicalPath = importPath.path().canonicalPath();
            if (!canonicalPath.isEmpty())
                allImportPaths.maybeInsert(canonicalPath, importPath.language());
        }
        allApplicationDirectories.append(pInfo.applicationDirectories);
    }

    for (const ViewerContext &vContext : std::as_const(lock->m_defaultVContexts)) {
        for (const Utils::FilePath &path : vContext.paths)
            allImportPaths.maybeInsert(path, vContext.language);
        allApplicationDirectories.append(vContext.applicationDirectories);
    }

    for (const ProjectInfo &pInfo : std::as_const(lock->m_projects)) {
        activeBundles.mergeLanguageBundles(pInfo.activeBundle);
        const auto languages = pInfo.activeBundle.languages();
        for (Dialect l : languages) {
            const auto paths = pInfo.activeBundle.bundleForLanguage(l).searchPaths().stringList();
            for (const QString &path : paths) {
                const QString canonicalPath = QFileInfo(path).canonicalFilePath();
                if (!canonicalPath.isEmpty())
                    allImportPaths.maybeInsert(Utils::FilePath::fromString(canonicalPath), l);
            }
        }
    }

    for (const ProjectInfo &pInfo : std::as_const(lock->m_projects)) {
        if (!pInfo.qtQmlPath.isEmpty())
            allImportPaths.maybeInsert(pInfo.qtQmlPath, Dialect::QmlQtQuick2);
    }
    const FilePath pathAtt = lock->m_defaultProjectInfo.qtQmlPath;
    if (!pathAtt.isEmpty())
        allImportPaths.maybeInsert(pathAtt, Dialect::QmlQtQuick2);
    for (const auto &importPath : lock->m_defaultProjectInfo.importPaths) {
        allImportPaths.maybeInsert(importPath);
    }
    for (const Utils::FilePath &path : std::as_const(lock->m_defaultImportPaths))
        allImportPaths.maybeInsert(path, Dialect::Qml);
    allImportPaths.compact();
    allApplicationDirectories = Utils::filteredUnique(allApplicationDirectories);

    lock->m_allImportPaths = allImportPaths;
    lock->m_activeBundles = activeBundles;
    lock->m_extendedBundles = extendedBundles;
    lock->m_applicationPaths = minimalPrefixPaths(allApplicationDirectories);
    // check if any file in the snapshot imports something new in the new paths
    Snapshot snapshot = lock->m_validSnapshot;
    QSet<Utils::FilePath> scannedPaths;
    QSet<Utils::FilePath> newLibraries;

    for (const Document::Ptr &doc : std::as_const(snapshot))
        findNewLibraryImports(doc,
                              snapshot,
                              this,
                              &importedFiles,
                              &scannedPaths,
                              &newLibraries,
                              &lock);

    for (const Utils::FilePath &path : std::as_const(allApplicationDirectories)) {
        allImportPaths.maybeInsert(path, Dialect::Qml);
        findNewQmlApplicationInPath(path, snapshot, this, &newLibraries, lock);
    }
    for (const Utils::FilePath &qrcPath : generatedQrc(lock->m_projects.values()))
        updateQrcFile(qrcPath);

    const bool shouldScan = lock->m_shouldScanImports;

    lock.unlock();

    updateSourceFiles(importedFiles, true);

    if (!shouldScan)
        return;
    maybeScan(allImportPaths);
}

void ModelManagerInterface::loadPluginTypes(const Utils::FilePath &libraryPath,
                                            const Utils::FilePath &importPath,
                                            const QString &importUri,
                                            const QString &importVersion)
{
    m_pluginDumper->loadPluginTypes(libraryPath, importPath, importUri, importVersion);
}

// is called *inside a c++ parsing thread*, to allow hanging on to source and ast
void ModelManagerInterface::maybeQueueCppQmlTypeUpdate(const CPlusPlus::Document::Ptr &doc)
{
    // avoid scanning documents without source code available
    doc->keepSourceAndAST();
    if (doc->utf8Source().isEmpty()) {
        doc->releaseSourceAndAST();
        return;
    }

    // keep source and AST alive if we want to scan for register calls
    const bool scan = FindExportedCppTypes::maybeExportsTypes(doc);
    if (!scan)
        doc->releaseSourceAndAST();

    QMutexLocker locker(&g_instanceMutex);
    if (g_instance) // delegate actual queuing to the gui thread
        QMetaObject::invokeMethod(g_instance, [this, doc, scan] { queueCppQmlTypeUpdate(doc, scan); });
}

void ModelManagerInterface::queueCppQmlTypeUpdate(const CPlusPlus::Document::Ptr &doc, bool scan)
{
    QPair<CPlusPlus::Document::Ptr, bool> prev = m_queuedCppDocuments.value(doc->filePath().path());
    if (prev.first && prev.second)
        prev.first->releaseSourceAndAST();
    m_queuedCppDocuments.insert(doc->filePath().path(), {doc, scan});
    m_updateCppQmlTypesTimer->start();
}

void ModelManagerInterface::startCppQmlTypeUpdate()
{
    // if a future is still running, delay
    if (m_cppQmlTypesUpdater.isRunning()) {
        m_updateCppQmlTypesTimer->start();
        return;
    }

    if (!CPlusPlus::CppModelManagerBase::hasSnapshots())
        return;

    m_cppQmlTypesUpdater = Utils::asyncRun(&ModelManagerInterface::updateCppQmlTypes, this,
                                           CPlusPlus::CppModelManagerBase::snapshot(),
                                           m_queuedCppDocuments);
    m_queuedCppDocuments.clear();
}

void ModelManagerInterface::asyncReset()
{
    m_asyncResetTimer->start();
}

bool rescanExports(const QString &fileName, FindExportedCppTypes &finder,
                   ModelManagerInterface::CppDataHash &newData)
{
    bool hasNewInfo = false;

    QList<LanguageUtils::FakeMetaObject::ConstPtr> exported = finder.exportedTypes();
    QHash<QString, QString> contextProperties = finder.contextProperties();
    if (exported.isEmpty() && contextProperties.isEmpty()) {
        hasNewInfo = hasNewInfo || newData.remove(fileName);
    } else {
        ModelManagerInterface::CppData &data = newData[fileName];
        if (!hasNewInfo && (data.exportedTypes.size() != exported.size()
                            || data.contextProperties != contextProperties)) {
            hasNewInfo = true;
        }
        if (!hasNewInfo) {
            QHash<QString, QByteArray> newFingerprints;
            for (const auto &newType : std::as_const(exported))
                newFingerprints[newType->className()]=newType->fingerprint();
            for (const auto &oldType : std::as_const(data.exportedTypes)) {
                if (newFingerprints.value(oldType->className()) != oldType->fingerprint()) {
                    hasNewInfo = true;
                    break;
                }
            }
        }
        data.exportedTypes = exported;
        data.contextProperties = contextProperties;
    }
    return hasNewInfo;
}

void ModelManagerInterface::updateCppQmlTypes(QPromise<void> &promise,
        ModelManagerInterface *qmlModelManager, const CPlusPlus::Snapshot &snapshot,
        const QHash<QString, QPair<CPlusPlus::Document::Ptr, bool>> &documents)
{
    promise.setProgressRange(0, documents.size());
    promise.setProgressValue(0);

    CppDataHash newData;
    QHash<QString, QList<CPlusPlus::Document::Ptr>> newDeclarations;
    qmlModelManager->m_syncedCppData.read([&newData, &newDeclarations](const SyncedCppData &sd) {
        newData = sd.m_cppDataHash;
        newDeclarations = sd.m_cppDeclarationFiles;
    });

    FindExportedCppTypes finder(snapshot);

    bool hasNewInfo = false;
    using DocScanPair = QPair<CPlusPlus::Document::Ptr, bool>;
    for (const DocScanPair &pair : documents) {
        if (promise.isCanceled())
            return;
        promise.setProgressValue(promise.future().progressValue() + 1);

        CPlusPlus::Document::Ptr doc = pair.first;
        const bool scan = pair.second;
        const FilePath filePath = doc->filePath();
        if (!scan) {
            hasNewInfo = newData.remove(filePath.path()) || hasNewInfo;
            const auto savedDocs = newDeclarations.value(filePath.path());
            for (const CPlusPlus::Document::Ptr &savedDoc : savedDocs) {
                finder(savedDoc);
                hasNewInfo = rescanExports(savedDoc->filePath().path(), finder, newData) || hasNewInfo;
            }
            continue;
        }

        for (auto it = newDeclarations.begin(), end = newDeclarations.end(); it != end;) {
            for (auto docIt = it->begin(), endDocIt = it->end(); docIt != endDocIt;) {
                const CPlusPlus::Document::Ptr &savedDoc = *docIt;
                if (savedDoc->filePath() == filePath) {
                    savedDoc->releaseSourceAndAST();
                    it->erase(docIt);
                    break;
                }
                ++docIt;
            }
            if (it->isEmpty())
                it = newDeclarations.erase(it);
            else
                ++it;
        }

        const auto found = finder(doc);
        for (const QString &declarationFile : found) {
            newDeclarations[declarationFile].append(doc);
            doc->keepSourceAndAST(); // keep for later reparsing when dependent doc changes
        }

        hasNewInfo = rescanExports(filePath.path(), finder, newData) || hasNewInfo;
        doc->releaseSourceAndAST();
    }

    qmlModelManager->m_syncedCppData.write(
        [qmlModelManager, hasNewInfo, &newData, &newDeclarations](SyncedCppData &sd) {
            sd.m_cppDataHash = newData;
            sd.m_cppDeclarationFiles = newDeclarations;
            if (hasNewInfo)
                // one could get away with re-linking the cpp types...
                QMetaObject::invokeMethod(qmlModelManager, &ModelManagerInterface::asyncReset);
        });
}

ModelManagerInterface::CppDataHash ModelManagerInterface::cppData() const
{
    return m_syncedCppData.readLocked()->m_cppDataHash;
}

LibraryInfo ModelManagerInterface::builtins(const Document::Ptr &doc) const
{
    const ProjectInfo info = projectInfoForPath(doc->fileName());
    if (!info.qtQmlPath.isEmpty())
        return m_syncedData.readLocked()->m_validSnapshot.libraryInfo(info.qtQmlPath);
    return LibraryInfo();
}

ViewerContext ModelManagerInterface::completeVContext(const ViewerContext &vCtx,
                                                      const Document::Ptr &doc) const
{
    return getVContext(vCtx, doc, false);
}

ViewerContext ModelManagerInterface::getVContext(const ViewerContext &vCtx,
                                                 const Document::Ptr &doc,
                                                 bool limitToProject) const
{
    ViewerContext res = vCtx;

    if (!doc.isNull()
            && ((vCtx.language == Dialect::AnyLanguage && doc->language() != Dialect::NoLanguage)
                || (vCtx.language == Dialect::Qml
                    && (doc->language() == Dialect::QmlQtQuick2
                        || doc->language() == Dialect::QmlQtQuick2Ui))))
        res.language = doc->language();
    ProjectInfo info;
    if (!doc.isNull())
        info = projectInfoForPath(doc->fileName());
    ViewerContext defaultVCtx = defaultVContext(res.language, Document::Ptr(nullptr), false);
    ProjectInfo defaultInfo = defaultProjectInfo();
    if (info.qtQmlPath.isEmpty()) {
        info.qtQmlPath = defaultInfo.qtQmlPath;
        info.qtVersionString = defaultInfo.qtVersionString;
    }
    if (info.qtQmlPath.isEmpty() && info.importPaths.size() == 0)
        info.importPaths = defaultInfo.importPaths;
    info.applicationDirectories = Utils::filteredUnique(info.applicationDirectories
                                                        + defaultInfo.applicationDirectories);
    switch (res.flags) {
    case ViewerContext::Complete:
        break;
    case ViewerContext::AddAllPathsAndDefaultSelectors:
        res.selectors.append(defaultVCtx.selectors);
        Q_FALLTHROUGH();
    case ViewerContext::AddAllPaths:
    {
        for (const Utils::FilePath &path : std::as_const(defaultVCtx.paths))
            maybeAddPath(res, path);
        switch (res.language.dialect()) {
        case Dialect::AnyLanguage:
        case Dialect::Qml:
            maybeAddPath(res, info.qtQmlPath);
            Q_FALLTHROUGH();
        case Dialect::QmlQtQuick2:
        case Dialect::QmlQtQuick2Ui:
        {
            if (res.language == Dialect::QmlQtQuick2 || res.language == Dialect::QmlQtQuick2Ui)
                maybeAddPath(res, info.qtQmlPath);

            QList<Dialect> languages = res.language.companionLanguages();
            auto addPathsOnLanguageMatch = [&](const PathsAndLanguages &importPaths) {
                for (const auto &importPath : importPaths) {
                    if (languages.contains(importPath.language())
                            || importPath.language().companionLanguages().contains(res.language)) {
                        maybeAddPath(res, importPath.path());
                    }
                }
            };
            if (limitToProject) {
                addPathsOnLanguageMatch(info.importPaths);
            } else {
                QList<ProjectInfo> allProjects = m_syncedData.readLocked()->m_projects.values();
                std::sort(allProjects.begin(), allProjects.end(), &pInfoLessThanImports);
                for (const ProjectInfo &pInfo : std::as_const(allProjects))
                    addPathsOnLanguageMatch(pInfo.importPaths);
            }
            const auto environmentPaths = environmentImportPaths();
            for (const Utils::FilePath &path : environmentPaths)
                maybeAddPath(res, path);
            break;
        }
        case Dialect::NoLanguage:
        case Dialect::JavaScript:
        case Dialect::QmlTypeInfo:
        case Dialect::Json:
        case Dialect::QmlQbs:
        case Dialect::QmlProject:
            break;
        }
        break;
    }
    case ViewerContext::AddDefaultPathsAndSelectors:
        res.selectors.append(defaultVCtx.selectors);
        Q_FALLTHROUGH();
    case ViewerContext::AddDefaultPaths:
        for (const Utils::FilePath &path : std::as_const(defaultVCtx.paths))
            maybeAddPath(res, path);
        if (res.language == Dialect::AnyLanguage || res.language == Dialect::Qml)
            maybeAddPath(res, info.qtQmlPath);
        if (res.language == Dialect::AnyLanguage || res.language == Dialect::Qml
                || res.language == Dialect::QmlQtQuick2 || res.language == Dialect::QmlQtQuick2Ui) {
            const auto environemntPaths = environmentImportPaths();
            for (const Utils::FilePath &path : environemntPaths)
                maybeAddPath(res, path);
        }
        break;
    }
    res.flags = ViewerContext::Complete;
    res.applicationDirectories = info.applicationDirectories;
    return res;
}

ViewerContext ModelManagerInterface::defaultVContext(Dialect language,
                                                     const Document::Ptr &doc,
                                                     bool autoComplete) const
{
    if (!doc.isNull()) {
        if (language == Dialect::AnyLanguage && doc->language() != Dialect::NoLanguage)
            language = doc->language();
        else if (language == Dialect::Qml &&
                 (doc->language() == Dialect::QmlQtQuick2
                  || doc->language() == Dialect::QmlQtQuick2Ui))
            language = doc->language();
    }
    ViewerContext defaultCtx = m_syncedData.readLocked()->m_defaultVContexts.value(language);
    defaultCtx.language = language;
    return autoComplete ? completeVContext(defaultCtx, doc) : defaultCtx;
}

ViewerContext ModelManagerInterface::projectVContext(Dialect language, const Document::Ptr &doc) const
{
    // Returns context limited to the project the file belongs to
    ViewerContext defaultCtx = defaultVContext(language, doc, false);
    return getVContext(defaultCtx, doc, true);
}

ModelManagerInterface::ProjectInfo ModelManagerInterface::defaultProjectInfo() const
{
    return m_syncedData.readLocked()->m_defaultProjectInfo;
}

ModelManagerInterface::ProjectInfo ModelManagerInterface::defaultProjectInfoForProject(
    ProjectExplorer::Project *project, const FilePaths &hiddenRccFolders) const
{
    Q_UNUSED(project);
    Q_UNUSED(hiddenRccFolders);
    return ModelManagerInterface::ProjectInfo();
}

void ModelManagerInterface::setDefaultVContext(const ViewerContext &vContext)
{
    m_syncedData.write(
        [&vContext](SyncedData &sd) { sd.m_defaultVContexts[vContext.language] = vContext; });
}

void ModelManagerInterface::joinAllThreads(bool cancelOnWait)
{
    while (true) {
        FutureSynchronizer futureSynchronizer;
        {
            QMutexLocker locker(&m_futuresMutex);
            futureSynchronizer = m_futureSynchronizer;
            m_futureSynchronizer.clearFutures();
        }
        futureSynchronizer.setCancelOnWait(cancelOnWait);
        if (futureSynchronizer.isEmpty())
            return;
    }
}

void ModelManagerInterface::test_joinAllThreads()
{
    while (true) {
        joinAllThreads();
        // In order to process all onFinished handlers of finished futures
        QCoreApplication::processEvents();
        QMutexLocker lock(&m_futuresMutex);
        // If handlers created new futures, repeat the loop
        if (m_futureSynchronizer.isEmpty())
            return;
    }
}

void ModelManagerInterface::addFuture(const QFuture<void> &future)
{
    QMutexLocker lock(&m_futuresMutex);
    m_futureSynchronizer.addFuture(future);
}

Document::Ptr ModelManagerInterface::ensuredGetDocumentForPath(const Utils::FilePath &filePath)
{
    QmlJS::Document::Ptr document = newestSnapshot().document(filePath);
    if (!document) {
        document = QmlJS::Document::create(filePath, QmlJS::Dialect::Qml);
        m_syncedData.write([&document](SyncedData &sd) { sd.m_newestSnapshot.insert(document); });
    }

    return document;
}

void ModelManagerInterface::resetCodeModel()
{
    QList<Utils::FilePath> documents;

    m_syncedData.write([&documents](SyncedData &sd) {
        // find all documents currently in the code model
        for (const Document::Ptr &doc : std::as_const(sd.m_validSnapshot))
            documents.append(doc->fileName());

        // reset the snapshot
        sd.m_validSnapshot = Snapshot();
        sd.m_newestSnapshot = Snapshot();
        sd.m_scannedPaths.clear();
        sd.m_shouldScanImports = true;
    });

    // start a reparse thread
    updateSourceFiles(documents, false);

    // rescan import directories
    updateImportPaths();
}

Utils::FilePath ModelManagerInterface::fileToSource(const Utils::FilePath &path)
{
    if (!path.scheme().isEmpty())
        return path;

    QList<Utils::FilePath> applicationPaths = m_syncedData.readLocked()->m_applicationPaths;

    for (const Utils::FilePath &p : applicationPaths) {
        if (!p.isEmpty() && path.startsWith(p.path())) {
            // if it is an applicationPath (i.e. in the build directory)
            // try to use the path from the build dir as resource path
            // and recover the path of the corresponding source file
            QString reducedPath = path.path().mid(p.path().size());
            QString reversePath(reducedPath);
            std::reverse(reversePath.begin(), reversePath.end());
            if (!reversePath.endsWith('/'))
                reversePath.append('/');
            QrcParser::MatchResult res;
            iterateQrcFiles(nullptr,
                            QrcResourceSelector::AllQrcResources,
                            [&](const QrcParser::ConstPtr &qrcFile) {
                                if (!qrcFile)
                                    return;
                                QrcParser::MatchResult matchNow = qrcFile->longestReverseMatches(
                                    reversePath);

                                if (matchNow.matchDepth < res.matchDepth)
                                    return;
                                if (matchNow.matchDepth == res.matchDepth) {
                                    res.reversedPaths += matchNow.reversedPaths;
                                    res.sourceFiles += matchNow.sourceFiles;
                                } else {
                                    res = matchNow;
                                }
                            });
            std::sort(res.sourceFiles.begin(), res.sourceFiles.end());
            if (!res.sourceFiles.isEmpty()) {
                return res.sourceFiles.first();
            }
            qCWarning(qmljsLog) << "Could not find source file for file" << path
                                << "in application path" << p;
        }
    }
    return path;
}

ModelManagerInterface::SyncedData::SyncedData(const QList<Utils::FilePath> &defaultImportPaths)
    : m_defaultImportPaths(defaultImportPaths)
{}

} // namespace QmlJS