qmljsmodelmanagerinterface.cpp 50.6 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8 9 10 11 12 13 14
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15 16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17 18 19 20 21 22 23 24 25
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26 27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
29

30 31 32 33
#include "qmljsbind.h"
#include "qmljsconstants.h"
#include "qmljsfindexportedcpptypes.h"
#include "qmljsinterpreter.h"
34
#include "qmljsmodelmanagerinterface.h"
35 36
#include "qmljsplugindumper.h"
#include "qmljstypedescriptionreader.h"
37

38 39
#include <cplusplus/cppmodelmanagerbase.h>
#include <utils/hostosinfo.h>
40
#include <utils/runextensions.h>
41 42 43

#include <QDir>
#include <QFile>
44
#include <QFileInfo>
45 46 47 48 49 50
#include <QMetaObject>
#include <QRegExp>
#include <QTextDocument>
#include <QTextStream>
#include <QTimer>
#include <QtAlgorithms>
51
#include <QLibraryInfo>
52 53

#include <stdio.h>
54

55
namespace QmlJS {
56

57 58
QMLJS_EXPORT Q_LOGGING_CATEGORY(qmljsLog, "qtc.qmljs.common")

59 60
/*!
    \class QmlJS::ModelManagerInterface
61 62
    \brief The ModelManagerInterface class acts as an interface to the
    global state of the QmlJS code model.
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    \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().
*/

78 79
static ModelManagerInterface *g_instance = 0;

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
static QStringList environmentImportPaths()
{
    QStringList paths;

    QByteArray envImportPath = qgetenv("QML_IMPORT_PATH");

    foreach (const QString &path, QString::fromLatin1(envImportPath)
             .split(Utils::HostOsInfo::pathListSeparator(), QString::SkipEmptyParts)) {
        QString canonicalPath = QDir(path).canonicalPath();
        if (!canonicalPath.isEmpty() && !paths.contains(canonicalPath))
            paths.append(canonicalPath);
    }

    return paths;
}

96
ModelManagerInterface::ModelManagerInterface(QObject *parent)
97 98
    : QObject(parent),
      m_shouldScanImports(false),
99
      m_defaultProject(0),
100
      m_pluginDumper(new PluginDumper(this))
101
{
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
    m_synchronizer.setCancelOnWait(true);

    m_updateCppQmlTypesTimer = new QTimer(this);
    m_updateCppQmlTypesTimer->setInterval(1000);
    m_updateCppQmlTypesTimer->setSingleShot(true);
    connect(m_updateCppQmlTypesTimer, SIGNAL(timeout()), SLOT(startCppQmlTypeUpdate()));

    m_asyncResetTimer = new QTimer(this);
    m_asyncResetTimer->setInterval(15000);
    m_asyncResetTimer->setSingleShot(true);
    connect(m_asyncResetTimer, SIGNAL(timeout()), SLOT(resetCodeModel()));

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

117 118 119 120 121
    m_defaultProjectInfo.qtImportsPath = QLibraryInfo::location(QLibraryInfo::ImportsPath);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
    m_defaultProjectInfo.qtQmlPath = QLibraryInfo::location(QLibraryInfo::Qml2ImportsPath);
#endif

122 123 124
    m_defaultImportPaths << environmentImportPaths();
    updateImportPaths();

125 126
    Q_ASSERT(! g_instance);
    g_instance = this;
127 128
}

129
ModelManagerInterface::~ModelManagerInterface()
130
{
131 132
    m_cppQmlTypesUpdater.cancel();
    m_cppQmlTypesUpdater.waitForFinished();
133 134
    Q_ASSERT(g_instance == this);
    g_instance = 0;
135
}
136

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
static QHash<QString, Language::Enum> defaultLanguageMapping()
{
    QHash<QString, Language::Enum> res;
    res[QLatin1String("js")] = Language::JavaScript;
    res[QLatin1String("qml")] = Language::Qml;
    res[QLatin1String("qmltypes")] = Language::QmlTypeInfo;
    res[QLatin1String("qmlproject")] = Language::QmlProject;
    res[QLatin1String("json")] = Language::Json;
    res[QLatin1String("qbs")] = Language::QmlQbs;
    return res;
}

Language::Enum ModelManagerInterface::guessLanguageOfFile(const QString &fileName)
{
    QHash<QString, Language::Enum> lMapping;
    if (instance())
        lMapping = instance()->languageForSuffix();
    else
        lMapping = defaultLanguageMapping();
    const QFileInfo info(fileName);
    const QString fileSuffix = info.suffix();
158
    return lMapping.value(fileSuffix, Language::NoLanguage);
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
}

QStringList ModelManagerInterface::globPatternsForLanguages(const QList<Language::Enum> languages)
{
    QHash<QString, Language::Enum> lMapping;
    if (instance())
        lMapping = instance()->languageForSuffix();
    else
        lMapping = defaultLanguageMapping();
    QStringList patterns;
    QHashIterator<QString,Language::Enum> i(lMapping);
    while (i.hasNext()) {
        i.next();
        if (languages.contains(i.value()))
            patterns << QLatin1String("*.") + i.key();
    }
    return patterns;
}

178 179 180 181
ModelManagerInterface *ModelManagerInterface::instance()
{
    return g_instance;
}
182

183 184 185 186 187
void ModelManagerInterface::writeWarning(const QString &msg)
{
    if (ModelManagerInterface *i = instance())
        i->writeMessageInternal(msg);
    else
188
        qCWarning(qmljsLog) << msg;
189 190 191 192 193 194 195 196 197
}

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

198 199 200 201 202 203 204 205
void ModelManagerInterface::activateScan()
{
    if (!m_shouldScanImports) {
        m_shouldScanImports = true;
        updateImportPaths();
    }
}

206 207 208 209 210
QHash<QString, Language::Enum> ModelManagerInterface::languageForSuffix() const
{
    return defaultLanguageMapping();
}

211 212
void ModelManagerInterface::writeMessageInternal(const QString &msg) const
{
213
    qCWarning(qmljsLog) << msg;
214 215 216 217 218 219 220 221 222 223 224 225
}

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

void ModelManagerInterface::addTaskInternal(QFuture<void> result, const QString &msg,
                                            const char *taskId) const
{
    Q_UNUSED(result);
226
    qCDebug(qmljsLog) << "started " << taskId << " " << msg;
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
}

void ModelManagerInterface::loadQmlTypeDescriptionsInternal(const QString &resourcePath)
{
    const QDir typeFileDir(resourcePath + QLatin1String("/qml-type-descriptions"));
    const QStringList qmlTypesExtensions = QStringList() << QLatin1String("*.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
    CppQmlTypesLoader::defaultLibraryObjects.unite(
                CppQmlTypesLoader::loadQmlTypes(qmlTypesFiles, &errors, &warnings));

    foreach (const QString &error, errors)
        writeMessageInternal(error);
    foreach (const QString &warning, warnings)
        writeMessageInternal(warning);
}

263 264 265 266 267 268 269
void ModelManagerInterface::setDefaultProject(const ModelManagerInterface::ProjectInfo &pInfo,
                                              ProjectExplorer::Project *p)
{
    QMutexLocker l(mutex());
    m_defaultProject = p;
    m_defaultProjectInfo = pInfo;
}
270 271 272 273

Snapshot ModelManagerInterface::snapshot() const
{
    QMutexLocker locker(&m_mutex);
274
    return m_validSnapshot;
275 276 277 278 279
}

Snapshot ModelManagerInterface::newestSnapshot() const
{
    QMutexLocker locker(&m_mutex);
280
    return m_newestSnapshot;
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
}

void ModelManagerInterface::updateSourceFiles(const QStringList &files,
                                     bool emitDocumentOnDiskChanged)
{
    refreshSourceFiles(files, emitDocumentOnDiskChanged);
}

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

    QFuture<void> result = QtConcurrent::run(&ModelManagerInterface::parse,
                                              workingCopyInternal(), sourceFiles,
                                              this, Language::Qml,
                                              emitDocumentOnDiskChanged);

    if (m_synchronizer.futures().size() > 10) {
        QList<QFuture<void> > futures = m_synchronizer.futures();

        m_synchronizer.clearFutures();

        foreach (const QFuture<void> &future, futures) {
            if (! (future.isFinished() || future.isCanceled()))
                m_synchronizer.addFuture(future);
        }
    }

    m_synchronizer.addFuture(result);

    if (sourceFiles.count() > 1)
314
         addTaskInternal(result, tr("Parsing QML Files"), Constants::TASK_INDEX);
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336

    if (sourceFiles.count() > 1 && !m_shouldScanImports) {
        bool scan = false;
        {
            QMutexLocker l(&m_mutex);
            if (!m_shouldScanImports) {
                m_shouldScanImports = true;
                scan = true;
            }
        }
        if (scan)
        updateImportPaths();
    }

    return result;
}


void ModelManagerInterface::fileChangedOnDisk(const QString &path)
{
    QtConcurrent::run(&ModelManagerInterface::parse,
                      workingCopyInternal(), QStringList() << path,
337
                      this, Language::AnyLanguage, true);
338 339 340 341 342 343 344 345 346
}

void ModelManagerInterface::removeFiles(const QStringList &files)
{
    emit aboutToRemoveFiles(files);

    QMutexLocker locker(&m_mutex);

    foreach (const QString &file, files) {
347 348
        m_validSnapshot.remove(file);
        m_newestSnapshot.remove(file);
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
    }
}

namespace {
bool pInfoLessThanActive(const ModelManagerInterface::ProjectInfo &p1, const ModelManagerInterface::ProjectInfo &p2)
{
    QStringList s1 = p1.activeResourceFiles;
    QStringList 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;
        else if (s1.at(i) > s2.at(i))
            return false;
    }
    return false;
}

bool pInfoLessThanAll(const ModelManagerInterface::ProjectInfo &p1, const ModelManagerInterface::ProjectInfo &p2)
{
    QStringList s1 = p1.allResourceFiles;
    QStringList 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;
        else if (s1.at(i) > s2.at(i))
            return false;
    }
    return false;
}
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

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.qtImportsPath < p2.qtImportsPath)
        return true;
    if (p1.qtImportsPath > p2.qtImportsPath)
        return false;
    QStringList s1 = p1.importPaths;
    QStringList 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;
        else if (s1.at(i) > s2.at(i))
            return false;
    }
    return false;
}

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
}

QStringList ModelManagerInterface::filesAtQrcPath(const QString &path, const QLocale *locale,
                                         ProjectExplorer::Project *project,
                                         QrcResourceSelector resources)
{
    QString normPath = QrcParser::normalizedQrcFilePath(path);
    QList<ProjectInfo> pInfos;
    if (project)
        pInfos.append(projectInfo(project));
    else
        pInfos = projectInfos();

    QStringList res;
    QSet<QString> pathsChecked;
    foreach (const ModelManagerInterface::ProjectInfo &pInfo, pInfos) {
        QStringList qrcFilePaths;
        if (resources == ActiveQrcResources)
            qrcFilePaths = pInfo.activeResourceFiles;
        else
            qrcFilePaths = pInfo.allResourceFiles;
        foreach (const QString &qrcFilePath, qrcFilePaths) {
            if (pathsChecked.contains(qrcFilePath))
                continue;
            pathsChecked.insert(qrcFilePath);
            QrcParser::ConstPtr qrcFile = m_qrcCache.parsedPath(qrcFilePath);
            if (qrcFile.isNull())
                continue;
            qrcFile->collectFilesAtPath(normPath, &res, locale);
        }
    }
    res.sort(); // make the result predictable
    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);
    QList<ProjectInfo> pInfos;
    if (project) {
        pInfos.append(projectInfo(project));
    } else {
        pInfos = projectInfos();
        if (resources == ActiveQrcResources) // make the result predictable
            qSort(pInfos.begin(), pInfos.end(), &pInfoLessThanActive);
        else
            qSort(pInfos.begin(), pInfos.end(), &pInfoLessThanAll);
    }
    QMap<QString, QStringList> res;
    QSet<QString> pathsChecked;
    foreach (const ModelManagerInterface::ProjectInfo &pInfo, pInfos) {
        QStringList qrcFilePaths;
        if (resources == ActiveQrcResources)
            qrcFilePaths = pInfo.activeResourceFiles;
        else
            qrcFilePaths = pInfo.allResourceFiles;
        foreach (const QString &qrcFilePath, qrcFilePaths) {
            if (pathsChecked.contains(qrcFilePath))
                continue;
            pathsChecked.insert(qrcFilePath);
            QrcParser::ConstPtr qrcFile = m_qrcCache.parsedPath(qrcFilePath);

            if (qrcFile.isNull())
                continue;
            qrcFile->collectFilesInPath(normPath, &res, addDirs, locale);
        }
    }
    return res;
}

QList<ModelManagerInterface::ProjectInfo> ModelManagerInterface::projectInfos() const
{
    QMutexLocker locker(&m_mutex);

    return m_projects.values();
}

493 494 495
ModelManagerInterface::ProjectInfo ModelManagerInterface::projectInfo(
        ProjectExplorer::Project *project,
        const ModelManagerInterface::ProjectInfo &defaultValue) const
496 497 498
{
    QMutexLocker locker(&m_mutex);

499
    return m_projects.value(project, defaultValue);
500 501 502 503 504 505 506 507 508 509 510 511 512
}

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

    Snapshot snapshot;
    ProjectInfo oldInfo;
    {
        QMutexLocker locker(&m_mutex);
        oldInfo = m_projects.value(p);
        m_projects.insert(p, pinfo);
513 514
        if (p == m_defaultProject)
            m_defaultProjectInfo = pinfo;
515
        snapshot = m_validSnapshot;
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
    }

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


    updateImportPaths();

    // remove files that are no longer in the project and have been deleted
    QStringList deletedFiles;
    foreach (const QString &oldFile, oldInfo.sourceFiles) {
        if (snapshot.document(oldFile)
                && !pinfo.sourceFiles.contains(oldFile)
                && !QFile::exists(oldFile)) {
            deletedFiles += oldFile;
        }
    }
    removeFiles(deletedFiles);
    foreach (const QString &oldFile, deletedFiles)
        m_fileToProject.remove(oldFile, p);

    // parse any files not yet in the snapshot
    QStringList newFiles;
    foreach (const QString &file, pinfo.sourceFiles) {
        if (!snapshot.document(file))
            newFiles += file;
    }
    updateSourceFiles(newFiles, false);
    foreach (const QString &newFile, deletedFiles)
        m_fileToProject.insert(newFile, p);

    // update qrc cache
    foreach (const QString &newQrc, pinfo.allResourceFiles)
        m_qrcCache.addPath(newQrc);
    foreach (const QString &oldQrc, oldInfo.allResourceFiles)
        m_qrcCache.removePath(oldQrc);

    int majorVersion, minorVersion, patchVersion;
    // dump builtin types if the shipped definitions are probably outdated and the
    // Qt version ships qmlplugindump
    if (::sscanf(pinfo.qtVersionString.toLatin1().constData(), "%d.%d.%d",
           &majorVersion, &minorVersion, &patchVersion) != 3)
        majorVersion = minorVersion = patchVersion = -1;

    if (majorVersion > 4 || (majorVersion == 4 && (minorVersion > 8 || (majorVersion == 8
                                                                       && patchVersion >= 5)))) {
        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);

    {
        QMutexLocker locker(&m_mutex);
        m_projects.remove(project);
    }
}

585
ModelManagerInterface::ProjectInfo ModelManagerInterface::projectInfoForPath(QString path) const
586
{
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
    QList<ProjectExplorer::Project *> projects;
    {
        QMutexLocker locker(&m_mutex);
        projects = m_fileToProject.values(path);
    }
    QList<ProjectInfo> infos;
    foreach (ProjectExplorer::Project *project, projects) {
        ProjectInfo info = projectInfo(project);
        if (info.isValid())
            infos.append(info);
    }
    std::sort(infos.begin(), infos.end(), &pInfoLessThanImports);

    ProjectInfo res;
    foreach (const ProjectInfo &pInfo, infos) {
        if (res.qtImportsPath.isEmpty())
            res.qtImportsPath = pInfo.qtImportsPath;
        if (res.qtQmlPath.isEmpty())
            res.qtQmlPath = pInfo.qtQmlPath;
        foreach (const QString &path, pInfo.importPaths)
607
            if (!res.importPaths.contains(path))
608 609 610
                res.importPaths.append(path);
    }
    return res;
611 612 613 614 615 616 617 618 619 620 621 622 623 624
}

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

void ModelManagerInterface::updateQrcFile(const QString &path)
{
    m_qrcCache.updatePath(path);
}

void ModelManagerInterface::updateDocument(Document::Ptr doc)
{
    {
        QMutexLocker locker(&m_mutex);
625 626
        m_validSnapshot.insert(doc);
        m_newestSnapshot.insert(doc, true);
627 628 629 630 631 632 633
    }
    emit documentUpdated(doc);
}

void ModelManagerInterface::updateLibraryInfo(const QString &path, const LibraryInfo &info)
{
    if (!info.pluginTypeInfoError().isEmpty())
634
        qCWarning(qmljsLog) << "Dumping errors for " << path << ":" << info.pluginTypeInfoError();
635 636 637

    {
        QMutexLocker locker(&m_mutex);
638 639
        m_validSnapshot.insertLibraryInfo(path, info);
        m_newestSnapshot.insertLibraryInfo(path, info);
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
    }
    // only emit if we got new useful information
    if (info.isValid())
        emit libraryInfoUpdated(path, info);
}

static QStringList filesInDirectoryForLanguages(const QString &path, QList<Language::Enum> languages)
{
    const QStringList pattern = ModelManagerInterface::globPatternsForLanguages(languages);
    QStringList files;

    const QDir dir(path);
    foreach (const QFileInfo &fi, dir.entryInfoList(pattern, QDir::Files))
        files += fi.absoluteFilePath();

    return files;
}

static void findNewImplicitImports(const Document::Ptr &doc, const Snapshot &snapshot,
                            QStringList *importedFiles, QSet<QString> *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 (! scannedPaths->contains(doc->path())) {
            *importedFiles += filesInDirectoryForLanguages(doc->path(),
                                                  Document::companionLanguages(doc->language()));
            scannedPaths->insert(doc->path());
        }
    }
}

static void findNewFileImports(const Document::Ptr &doc, const Snapshot &snapshot,
                        QStringList *importedFiles, QSet<QString> *scannedPaths)
{
    // scan files and directories that are explicitly imported
    foreach (const ImportInfo &import, doc->bind()->imports()) {
        const QString &importName = import.path();
        if (import.type() == ImportType::File) {
            if (! snapshot.document(importName))
                *importedFiles += importName;
        } else if (import.type() == ImportType::Directory) {
            if (snapshot.documentsInDirectory(importName).isEmpty()) {
                if (! scannedPaths->contains(importName)) {
                    *importedFiles += filesInDirectoryForLanguages(importName,
                                                          Document::companionLanguages(doc->language()));
                    scannedPaths->insert(importName);
                }
            }
        } else if (import.type() == ImportType::QrcFile) {
            QStringList importPaths = ModelManagerInterface::instance()->filesAtQrcPath(importName);
            foreach (const QString &importPath, importPaths) {
                if (! snapshot.document(importPath))
                    *importedFiles += importPath;
            }
        } else if (import.type() == ImportType::QrcDirectory) {
            QMapIterator<QString,QStringList> dirContents(ModelManagerInterface::instance()->filesInQrcPath(importName));
            while (dirContents.hasNext()) {
                dirContents.next();
                if (Document::isQmlLikeOrJsLanguage(ModelManagerInterface::guessLanguageOfFile(dirContents.key()))) {
                    foreach (const QString &filePath, dirContents.value()) {
                        if (! snapshot.document(filePath))
                            *importedFiles += filePath;
                    }
                }
            }
        }
    }
}

static bool findNewQmlLibraryInPath(const QString &path,
                                    const Snapshot &snapshot,
                                    ModelManagerInterface *modelManager,
                                    QStringList *importedFiles,
                                    QSet<QString> *scannedPaths,
                                    QSet<QString> *newLibraries,
                                    bool ignoreMissing)
{
    // if we know there is a library, done
    const LibraryInfo &existingInfo = snapshot.libraryInfo(path);
    if (existingInfo.isValid())
        return true;
    if (newLibraries->contains(path))
        return true;
    // if we looked at the path before, done
    if (existingInfo.wasScanned())
        return false;

    const QDir dir(path);
    QFile qmldirFile(dir.filePath(QLatin1String("qmldir")));
    if (!qmldirFile.exists()) {
        if (!ignoreMissing) {
            LibraryInfo libraryInfo(LibraryInfo::NotFound);
            modelManager->updateLibraryInfo(path, libraryInfo);
        }
        return false;
    }

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

    // found a new library!
    qmldirFile.open(QFile::ReadOnly);
    QString qmldirData = QString::fromUtf8(qmldirFile.readAll());

    QmlDirParser qmldirParser;
    qmldirParser.parse(qmldirData);

    const QString libraryPath = QFileInfo(qmldirFile).absolutePath();
    newLibraries->insert(libraryPath);
    modelManager->updateLibraryInfo(libraryPath, LibraryInfo(qmldirParser));
752 753
    modelManager->loadPluginTypes(QFileInfo(libraryPath).canonicalFilePath(), libraryPath,
                QString(), QString());
754 755 756 757 758 759 760 761

    // scan the qml files in the library
    foreach (const QmlDirParser::Component &component, qmldirParser.components()) {
        if (! component.fileName.isEmpty()) {
            const QFileInfo componentFileInfo(dir.filePath(component.fileName));
            const QString path = QDir::cleanPath(componentFileInfo.absolutePath());
            if (! scannedPaths->contains(path)) {
                *importedFiles += filesInDirectoryForLanguages(path,
762
                                                      Document::companionLanguages(Language::AnyLanguage));
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
                scannedPaths->insert(path);
            }
        }
    }

    return true;
}

static void findNewQmlLibrary(
    const QString &path,
    const LanguageUtils::ComponentVersion &version,
    const Snapshot &snapshot,
    ModelManagerInterface *modelManager,
    QStringList *importedFiles,
    QSet<QString> *scannedPaths,
    QSet<QString> *newLibraries)
{
    QString libraryPath = QString::fromLatin1("%1.%2.%3").arg(
                path,
                QString::number(version.majorVersion()),
                QString::number(version.minorVersion()));
    findNewQmlLibraryInPath(
                libraryPath, snapshot, modelManager,
                importedFiles, scannedPaths, newLibraries, false);

    libraryPath = QString::fromLatin1("%1.%2").arg(
                path,
                QString::number(version.majorVersion()));
    findNewQmlLibraryInPath(
                libraryPath, snapshot, modelManager,
                importedFiles, scannedPaths, newLibraries, false);

    findNewQmlLibraryInPath(
                path, snapshot, modelManager,
                importedFiles, scannedPaths, newLibraries, false);
}

static void findNewLibraryImports(const Document::Ptr &doc, const Snapshot &snapshot,
                           ModelManagerInterface *modelManager,
                           QStringList *importedFiles, QSet<QString> *scannedPaths, QSet<QString> *newLibraries)
{
    // scan current dir
    findNewQmlLibraryInPath(doc->path(), snapshot, modelManager,
                            importedFiles, scannedPaths, newLibraries, false);

    // scan dir and lib imports
    const QStringList importPaths = modelManager->importPaths();
    foreach (const ImportInfo &import, doc->bind()->imports()) {
        if (import.type() == ImportType::Directory) {
            const QString targetPath = import.path();
            findNewQmlLibraryInPath(targetPath, snapshot, modelManager,
                                    importedFiles, scannedPaths, newLibraries, false);
        }

        if (import.type() == ImportType::Library) {
            if (!import.version().isValid())
                continue;
            foreach (const QString &importPath, importPaths) {
                const QString targetPath = QDir(importPath).filePath(import.path());
                findNewQmlLibrary(targetPath, import.version(), snapshot, modelManager,
                                  importedFiles, scannedPaths, newLibraries);
            }
        }
    }
}

void ModelManagerInterface::parseLoop(QSet<QString> &scannedPaths,
                             QSet<QString> &newLibraries,
                             WorkingCopy workingCopy,
                             QStringList files,
                             ModelManagerInterface *modelManager,
                             Language::Enum mainLanguage,
                             bool emitDocChangedOnDisk,
hjk's avatar
hjk committed
836
                             std::function<bool(qreal)> reportProgress)
837 838 839 840 841 842 843 844
{
    for (int i = 0; i < files.size(); ++i) {
        if (!reportProgress(qreal(i) / files.size()))
            return;

        const QString fileName = files.at(i);

        Language::Enum language = guessLanguageOfFile(fileName);
845
        if (language == Language::NoLanguage) {
846 847 848 849 850
            if (fileName.endsWith(QLatin1String(".qrc")))
                modelManager->updateQrcFile(fileName);
            continue;
        }
        if (language == Language::Qml
851
                && (mainLanguage == Language::QmlQtQuick1 || mainLanguage == Language::QmlQtQuick2))
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
            language = mainLanguage;
        QString contents;
        int documentRevision = 0;

        if (workingCopy.contains(fileName)) {
            QPair<QString, int> entry = workingCopy.get(fileName);
            contents = entry.first;
            documentRevision = entry.second;
        } else {
            QFile inFile(fileName);

            if (inFile.open(QIODevice::ReadOnly)) {
                QTextStream ins(&inFile);
                contents = ins.readAll();
                inFile.close();
            }
        }

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

        // update snapshot. requires synchronization, but significantly reduces amount of file
        // system queries for library imports because queries are cached in libraryInfo
        const Snapshot snapshot = modelManager->snapshot();

        // get list of referenced files not yet in snapshot or in directories already scanned
        QStringList importedFiles;
        findNewImplicitImports(doc, snapshot, &importedFiles, &scannedPaths);
        findNewFileImports(doc, snapshot, &importedFiles, &scannedPaths);
        findNewLibraryImports(doc, snapshot, modelManager, &importedFiles, &scannedPaths, &newLibraries);

        // add new files to parse list
        foreach (const QString &file, importedFiles) {
            if (! files.contains(file))
                files.append(file);
        }

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

class FutureReporter
{
public:
    FutureReporter(QFutureInterface<void> &future, int multiplier = 100, int base = 0)
        :future(future), multiplier(multiplier), base(base)
    { }
    bool operator()(qreal val)
    {
        if (future.isCanceled())
            return false;
        future.setProgressValue(int(base + multiplier * val));
        return true;
    }
private:
    QFutureInterface<void> &future;
    int multiplier;
    int base;
};

void ModelManagerInterface::parse(QFutureInterface<void> &future,
                         WorkingCopy workingCopy,
                         QStringList files,
                         ModelManagerInterface *modelManager,
                         Language::Enum mainLanguage,
                         bool emitDocChangedOnDisk)
{
    FutureReporter reporter(future);
    future.setProgressRange(0, 100);

    // paths we have scanned for files and added to the files list
    QSet<QString> scannedPaths;
    // libraries we've found while scanning imports
    QSet<QString> newLibraries;
    parseLoop(scannedPaths, newLibraries, workingCopy, files, modelManager, mainLanguage,
              emitDocChangedOnDisk, reporter);
    future.setProgressValue(100);
}

struct ScanItem {
    QString path;
    int depth;
    ScanItem(QString path = QString(), int depth = 0)
        : path(path), depth(depth)
    { }
};

void ModelManagerInterface::importScan(QFutureInterface<void> &future,
                              ModelManagerInterface::WorkingCopy workingCopy,
                              QStringList paths, ModelManagerInterface *modelManager,
                              Language::Enum language,
                              bool emitDocChangedOnDisk)
{
    // paths we have scanned for files and added to the files list
    QSet<QString> scannedPaths = modelManager->m_scannedPaths;
    // libraries we've found while scanning imports
    QSet<QString> newLibraries;

    QVector<ScanItem> pathsToScan;
    pathsToScan.reserve(paths.size());
    {
        QMutexLocker l(&modelManager->m_mutex);
        foreach (const QString &path, paths) {
            QString cPath = QDir::cleanPath(path);
            if (modelManager->m_scannedPaths.contains(cPath))
                continue;
            pathsToScan.append(ScanItem(cPath));
            modelManager->m_scannedPaths.insert(cPath);
        }
    }
    const int maxScanDepth = 5;
    int progressRange = pathsToScan.size() * (1 << (2 + maxScanDepth));
    int totalWork(progressRange), workDone(0);
    future.setProgressRange(0, progressRange); // update max length while iterating?
    const bool libOnly = true; // FIXME remove when tested more
    const Snapshot snapshot = modelManager->snapshot();
    while (!pathsToScan.isEmpty() && !future.isCanceled()) {
        ScanItem toScan = pathsToScan.last();
        pathsToScan.pop_back();
975
        int pathBudget = (1 << (maxScanDepth + 2 - toScan.depth));
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
        if (!scannedPaths.contains(toScan.path)) {
            QStringList importedFiles;
            if (!findNewQmlLibraryInPath(toScan.path, snapshot, modelManager, &importedFiles,
                                         &scannedPaths, &newLibraries, true)
                    && !libOnly && snapshot.documentsInDirectory(toScan.path).isEmpty())
                importedFiles += filesInDirectoryForLanguages(toScan.path,
                                                     Document::companionLanguages(language));
            workDone += 1;
            future.setProgressValue(progressRange * workDone / totalWork);
            if (!importedFiles.isEmpty()) {
                FutureReporter reporter(future, progressRange * pathBudget / (4 * totalWork),
                                        progressRange * workDone / totalWork);
                parseLoop(scannedPaths, newLibraries, workingCopy, importedFiles, modelManager,
                          language, emitDocChangedOnDisk, reporter); // run in parallel??
                importedFiles.clear();
            }
            workDone += pathBudget / 4 - 1;
            future.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) {
            QDir dir(toScan.path);
1000
            QStringList subDirs(dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot));
1001 1002 1003 1004 1005
            workDone += 1;
            totalWork += pathBudget / 2 * subDirs.size() - pathBudget * 3 / 4 + 1;
            foreach (const QString path, subDirs)
                pathsToScan.append(ScanItem(dir.absoluteFilePath(path), toScan.depth + 1));
        } else {
1006
            workDone += pathBudget * 3 / 4;
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
        }
        future.setProgressValue(progressRange * workDone / totalWork);
    }
    future.setProgressValue(progressRange);
    if (future.isCanceled()) {
        // assume no work has been done
        QMutexLocker l(&modelManager->m_mutex);
        foreach (const QString &path, paths)
            modelManager->m_scannedPaths.remove(path);
    }
}

QStringList ModelManagerInterface::importPaths() const
{
    QMutexLocker l(&m_mutex);
    return m_allImportPaths;
}

QmlLanguageBundles ModelManagerInterface::activeBundles() const
{
    QMutexLocker l(&m_mutex);
    return m_activeBundles;
}

QmlLanguageBundles ModelManagerInterface::extendedBundles() const
{
    QMutexLocker l(&m_mutex);
    return m_extendedBundles;
}

Fawzi Mohamed's avatar
Fawzi Mohamed committed
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
void ModelManagerInterface::maybeScan(const QStringList &importPaths,
                                      Language::Enum defaultLanguage)
{
    QStringList pathToScan;
    {
        QMutexLocker l(&m_mutex);
        foreach (QString importPath, importPaths)
            if (!m_scannedPaths.contains(importPath)) {
                pathToScan.append(importPath);
            }
    }

    if (pathToScan.count() > 1) {
        QFuture<void> result = QtConcurrent::run(&ModelManagerInterface::importScan,
                                                  workingCopyInternal(), pathToScan,
                                                  this, defaultLanguage,
                                                  true);

        if (m_synchronizer.futures().size() > 10) {
            QList<QFuture<void> > futures = m_synchronizer.futures();

            m_synchronizer.clearFutures();

            foreach (const QFuture<void> &future, futures) {
                if (! (future.isFinished() || future.isCanceled()))
                    m_synchronizer.addFuture(future);
            }
        }

        m_synchronizer.addFuture(result);

1068
        addTaskInternal(result, tr("Scanning QML Imports"), Constants::TASK_IMPORT_SCAN);
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1069 1070 1071
    }
}

1072 1073 1074 1075 1076
void ModelManagerInterface::updateImportPaths()
{
    QStringList allImportPaths;
    QmlLanguageBundles activeBundles;
    QmlLanguageBundles extendedBundles;
1077 1078 1079 1080 1081
    QMapIterator<ProjectExplorer::Project *, ProjectInfo> pInfoIter(m_projects);
    QHashIterator<Language::Enum, QmlJS::ViewerContext> vCtxsIter = m_defaultVContexts;
    while (pInfoIter.hasNext()) {
        pInfoIter.next();
        foreach (const QString &path, pInfoIter.value().importPaths) {
1082 1083 1084 1085 1086
            const QString canonicalPath = QFileInfo(path).canonicalFilePath();
            if (!canonicalPath.isEmpty())
                allImportPaths += canonicalPath;
        }
    }
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
    while (vCtxsIter.hasNext()) {
        vCtxsIter.next();
        allImportPaths << vCtxsIter.value().paths;
    }
    pInfoIter.toFront();
    while (pInfoIter.hasNext()) {
        pInfoIter.next();
        activeBundles.mergeLanguageBundles(pInfoIter.value().activeBundle);
        foreach (Language::Enum l, pInfoIter.value().activeBundle.languages()) {
            foreach (const QString &path, pInfoIter.value().activeBundle.bundleForLanguage(l)
1097 1098 1099 1100 1101 1102 1103
                 .searchPaths().stringList()) {
                const QString canonicalPath = QFileInfo(path).canonicalFilePath();
                if (!canonicalPath.isEmpty())
                    allImportPaths += canonicalPath;
            }
        }
    }
1104 1105 1106 1107
    pInfoIter.toFront();
    while (pInfoIter.hasNext()) {
        pInfoIter.next();
        QString pathAtt = pInfoIter.value().qtQmlPath;
1108
        if (!pathAtt.isEmpty() && (allImportPaths.isEmpty() || allImportPaths.last() != pathAtt))
1109 1110 1111 1112
            allImportPaths.append(pathAtt);
    }
    {
        QString pathAtt = defaultProjectInfo().qtQmlPath;
1113
        if (!pathAtt.isEmpty() && (allImportPaths.isEmpty() || allImportPaths.last() != pathAtt))
1114 1115 1116 1117 1118 1119
            allImportPaths.append(pathAtt);
    }
    pInfoIter.toFront();
    while (pInfoIter.hasNext()) {
        pInfoIter.next();
        QString pathAtt = pInfoIter.value().qtImportsPath;
1120
        if (!pathAtt.isEmpty() && (allImportPaths.isEmpty() || allImportPaths.last() != pathAtt))
1121 1122 1123 1124
            allImportPaths.append(pathAtt);
    }
    {
        QString pathAtt = defaultProjectInfo().qtImportsPath;
1125
        if (!pathAtt.isEmpty() && (allImportPaths.isEmpty() || allImportPaths.last() != pathAtt))
1126
            allImportPaths.append(pathAtt);
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
    }
    allImportPaths += m_defaultImportPaths;
    allImportPaths.removeDuplicates();

    {
        QMutexLocker l(&m_mutex);
        m_allImportPaths = allImportPaths;
        m_activeBundles = activeBundles;
        m_extendedBundles = extendedBundles;
    }


    // check if any file in the snapshot imports something new in the new paths
1140
    Snapshot snapshot = m_validSnapshot;
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
    QStringList importedFiles;
    QSet<QString> scannedPaths;
    QSet<QString> newLibraries;
    foreach (const Document::Ptr &doc, snapshot)
        findNewLibraryImports(doc, snapshot, this, &importedFiles, &scannedPaths, &newLibraries);

    updateSourceFiles(importedFiles, true);

    if (!m_shouldScanImports)
        return;
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1151
    maybeScan(allImportPaths, Language::Qml);
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
}

void ModelManagerInterface::loadPluginTypes(const QString &libraryPath, const QString &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();

    // delegate actual queuing to the gui thread
    QMetaObject::invokeMethod(this, "queueCppQmlTypeUpdate",
                              Q_ARG(CPlusPlus::Document::Ptr, doc), Q_ARG(bool, scan));
}

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

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

    CPlusPlus::CppModelManagerBase *cppModelManager =
            CPlusPlus::CppModelManagerBase::instance();
    if (!cppModelManager)
        return;

    m_cppQmlTypesUpdater = QtConcurrent::run(
                &ModelManagerInterface::updateCppQmlTypes,
                this, cppModelManager->snapshot(), m_queuedCppDocuments);
    m_queuedCppDocuments.clear();
}

1208 1209 1210 1211 1212
QMutex *ModelManagerInterface::mutex() const
{
    return &m_mutex;
}

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
void ModelManagerInterface::asyncReset()
{
    m_asyncResetTimer->start();
}

void ModelManagerInterface::updateCppQmlTypes(QFutureInterface<void> &interface,
                                     ModelManagerInterface *qmlModelManager,
                                     CPlusPlus::Snapshot snapshot,
                                     QHash<QString, QPair<CPlusPlus::Document::Ptr, bool> > documents)
{
    CppDataHash newData = qmlModelManager->cppData();

    FindExportedCppTypes finder(snapshot);

    bool hasNewInfo = false;
    typedef QPair<CPlusPlus::Document::Ptr, bool> DocScanPair;
    foreach (const DocScanPair &pair, documents) {
        if (interface.isCanceled())
            return;

        CPlusPlus::Document::Ptr doc = pair.first;
        const bool scan = pair.second;
        const QString fileName = doc->fileName();
        if (!scan) {
            hasNewInfo = hasNewInfo || newData.remove(fileName) > 0;
            continue;
        }

        finder(doc);

        QList<LanguageUtils::FakeMetaObject::ConstPtr> exported = finder.exportedTypes();
        QHash<QString, QString> contextProperties = finder.contextProperties();
        if (exported.isEmpty() && contextProperties.isEmpty()) {
            hasNewInfo = hasNewInfo || newData.remove(fileName) > 0;
        } else {
            CppData &data = newData[fileName];
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
            if (!hasNewInfo && (data.exportedTypes.size() != exported.size()
                                || data.contextProperties != contextProperties))
                hasNewInfo = true;
            if (!hasNewInfo) {
                QHash<QString, QByteArray> newFingerprints;
                foreach (LanguageUtils::FakeMetaObject::ConstPtr newType, exported)
                    newFingerprints[newType->className()]=newType->fingerprint();
                foreach (LanguageUtils::FakeMetaObject::ConstPtr oldType, data.exportedTypes) {
                    if (newFingerprints.value(oldType->className()) != oldType->fingerprint()) {
                        hasNewInfo = true;
                        break;
                    }
                }
            }
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
            data.exportedTypes = exported;
            data.contextProperties = contextProperties;
        }

        doc->releaseSourceAndAST();
    }

    QMutexLocker locker(&qmlModelManager->m_cppDataMutex);
    qmlModelManager->m_cppDataHash = newData;
    if (hasNewInfo)
        // one could get away with re-linking the cpp types...
        QMetaObject::invokeMethod(qmlModelManager, "asyncReset");
}

ModelManagerInterface::CppDataHash ModelManagerInterface::cppData() const
{
    QMutexLocker locker(&m_cppDataMutex);
    return m_cppDataHash;
}

LibraryInfo ModelManagerInterface::builtins(const Document::Ptr &doc) const
{
1285
    ProjectInfo info = projectInfoForPath(doc->path());
1286 1287
    if (!info.isValid())
        return LibraryInfo();
1288
    return m_validSnapshot.libraryInfo(info.qtImportsPath);
1289 1290 1291
}

ViewerContext ModelManagerInterface::completeVContext(const ViewerContext &vCtx,
1292
                                                      const Document::Ptr &doc) const
1293 1294
{
    ViewerContext res = vCtx;
1295

1296 1297 1298 1299 1300
    if (!doc.isNull()
            && ((vCtx.language == Language::AnyLanguage && doc->language() != Language::NoLanguage)
                || (vCtx.language == Language::Qml
                    && (doc->language() == Language::QmlQtQuick1
                        || doc->language() == Language::QmlQtQuick2))))
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
        res.language = doc->language();
    ProjectInfo info;
    if (!doc.isNull())
        info = projectInfoForPath(doc->path());
    ViewerContext defaultVCtx = defaultVContext(res.language, Document::Ptr(0), false);
    ProjectInfo defaultInfo = defaultProjectInfo();
    if (info.qtImportsPath.isEmpty())
        info.qtImportsPath = defaultInfo.qtImportsPath;
    if (info.qtQmlPath.isEmpty())
        info.qtQmlPath = defaultInfo.qtQmlPath;
1311 1312 1313
    switch (res.flags) {
    case ViewerContext::Complete:
        break;
1314 1315 1316
    case ViewerContext::AddAllPathsAndDefaultSelectors:
        res.selectors.append(defaultVCtx.selectors);
        // fallthrough
1317
    case ViewerContext::AddAllPaths:
1318 1319 1320 1321
    {
        foreach (const QString &path, defaultVCtx.paths)
            res.maybeAddPath(path);
        switch (res.language) {
1322
        case Language::AnyLanguage:
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
        case Language::Qml:
            res.maybeAddPath(info.qtQmlPath);
            // fallthrough
        case Language::QmlQtQuick1:
            res.maybeAddPath(info.qtImportsPath);
            // fallthrough
        case Language::QmlQtQuick2:
        {
            if (res.language == Language::QmlQtQuick2)
                res.maybeAddPath(info.qtQmlPath);
            QList<ProjectInfo> allProjects;
            {
                QMutexLocker locker(&m_mutex);
                allProjects = m_projects.values();
            }
            std::sort(allProjects.begin(), allProjects.end(), &pInfoLessThanImports);
            foreach (const ProjectInfo &pInfo, allProjects) {
                foreach (const QString &path, pInfo.importPaths)
                    res.maybeAddPath(path);
            }
            break;
        }
1345
        case Language::NoLanguage:
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
        case Language::JavaScript:
        case Language::QmlTypeInfo:
        case Language::Json:
        case Language::QmlQbs:
        case Language::QmlProject:
            break;
        }
        break;
    }
    case ViewerContext::AddDefaultPathsAndSelectors:
        res.selectors.append(defaultVCtx.selectors);
        // fallthrough
    case ViewerContext::AddDefaultPaths:
        foreach (const QString &path, defaultVCtx.paths)
            res.maybeAddPath(path);
1361
        if (res.language == Language::AnyLanguage || res.language == Language::Qml
1362 1363
                || res.language == Language::QmlQtQuick2)
            res.maybeAddPath(info.qtImportsPath);
1364
        if (res.language == Language::AnyLanguage || res.language == Language::Qml
1365 1366 1367
                || res.language == Language::QmlQtQuick1)
            res.maybeAddPath(info.qtQmlPath);
        break;
1368 1369 1370 1371 1372
    }
    res.flags = ViewerContext::Complete;
    return res;
}

1373 1374 1375
ViewerContext ModelManagerInterface::defaultVContext(Language::Enum language,
                                                     const Document::Ptr &doc,
                                                     bool autoComplete) const
1376
{
1377
    if (!doc.isNull()) {
1378
        if (language == Language::AnyLanguage && doc->language() != Language::NoLanguage)
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
            language = doc->language();
        else if (language == Language::Qml &&
                 (doc->language() == Language::QmlQtQuick1 || doc->language() == Language::QmlQtQuick2))
            language = doc->language();
    }
    ViewerContext defaultCtx;
    {
        QMutexLocker locker(&m_mutex);
        defaultCtx = m_defaultVContexts.value(language);
    }
1389
    defaultCtx.language = language;
1390
    if (autoComplete)
1391
        return completeVContext(defaultCtx, doc);
1392
    else
1393 1394 1395 1396 1397
        return defaultCtx;
}

ModelManagerInterface::ProjectInfo ModelManagerInterface::defaultProjectInfo() const
{
1398 1399
    QMutexLocker l(mutex());
    return m_defaultProjectInfo;
1400 1401 1402 1403
}

void ModelManagerInterface::setDefaultVContext(const ViewerContext &vContext)
{
1404 1405
    QMutexLocker locker(&m_mutex);
    m_defaultVContexts[vContext.language] = vContext;
1406 1407 1408 1409 1410 1411 1412 1413
}

void ModelManagerInterface::joinAllThreads()
{
    foreach (QFuture<void> future, m_synchronizer.futures())
        future.waitForFinished();
}

1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
Document::Ptr ModelManagerInterface::ensuredGetDocumentForPath(const QString &filePath)
{
    QmlJS::Document::Ptr document = newestSnapshot().document(filePath);
    if (!document) {
        document = QmlJS::Document::create(filePath, QmlJS::Language::Qml);
        QMutexLocker lock(&m_mutex);

        m_newestSnapshot.insert(document);
    }

    return document;
}

1427 1428 1429 1430 1431 1432 1433 1434
void ModelManagerInterface::resetCodeModel()
{
    QStringList documents;

    {
        QMutexLocker locker(&m_mutex);

        // find all documents currently in the code model
1435
        foreach (Document::Ptr doc, m_validSnapshot)
1436 1437 1438
            documents.append(doc->fileName());

        // reset the snapshot
1439 1440
        m_validSnapshot = Snapshot();
        m_newestSnapshot = Snapshot();
1441 1442 1443 1444 1445 1446 1447
    }

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

} // namespace QmlJS